Deleted Added
sdiff udiff text old ( 199989 ) new ( 201360 )
full compact
1//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/Debug.h"
21#include <algorithm>
22#include <deque>
23#include <iostream>
24using namespace llvm;
25
26static cl::opt<bool>
27GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
28
29//===----------------------------------------------------------------------===//
30// DAGISelEmitter Helper methods
31//
32
33/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
34/// ComplexPattern.
35static bool NodeIsComplexPattern(TreePatternNode *N) {
36 return (N->isLeaf() &&
37 dynamic_cast<DefInit*>(N->getLeafValue()) &&
38 static_cast<DefInit*>(N->getLeafValue())->getDef()->
39 isSubClassOf("ComplexPattern"));
40}
41
42/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
43/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
44static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
45 CodeGenDAGPatterns &CGP) {
46 if (N->isLeaf() &&
47 dynamic_cast<DefInit*>(N->getLeafValue()) &&
48 static_cast<DefInit*>(N->getLeafValue())->getDef()->
49 isSubClassOf("ComplexPattern")) {
50 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
51 ->getDef());
52 }
53 return NULL;
54}
55
56/// getPatternSize - Return the 'size' of this pattern. We want to match large
57/// patterns before small ones. This is used to determine the size of a
58/// pattern.
59static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
60 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
61 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
62 P->getExtTypeNum(0) == MVT::isVoid ||
63 P->getExtTypeNum(0) == MVT::Flag ||
64 P->getExtTypeNum(0) == MVT::iPTR ||
65 P->getExtTypeNum(0) == MVT::iPTRAny) &&
66 "Not a valid pattern node to size!");
67 unsigned Size = 3; // The node itself.
68 // If the root node is a ConstantSDNode, increases its size.
69 // e.g. (set R32:$dst, 0).
70 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
71 Size += 2;
72
73 // FIXME: This is a hack to statically increase the priority of patterns
74 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
75 // Later we can allow complexity / cost for each pattern to be (optionally)
76 // specified. To get best possible pattern match we'll need to dynamically
77 // calculate the complexity of all patterns a dag can potentially map to.
78 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
79 if (AM)
80 Size += AM->getNumOperands() * 3;
81
82 // If this node has some predicate function that must match, it adds to the
83 // complexity of this node.
84 if (!P->getPredicateFns().empty())
85 ++Size;
86
87 // Count children in the count if they are also nodes.
88 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
89 TreePatternNode *Child = P->getChild(i);
90 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
91 Size += getPatternSize(Child, CGP);
92 else if (Child->isLeaf()) {
93 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
94 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
95 else if (NodeIsComplexPattern(Child))
96 Size += getPatternSize(Child, CGP);
97 else if (!Child->getPredicateFns().empty())
98 ++Size;
99 }
100 }
101
102 return Size;
103}
104
105/// getResultPatternCost - Compute the number of instructions for this pattern.
106/// This is a temporary hack. We should really include the instruction
107/// latencies in this calculation.
108static unsigned getResultPatternCost(TreePatternNode *P,
109 CodeGenDAGPatterns &CGP) {
110 if (P->isLeaf()) return 0;
111
112 unsigned Cost = 0;
113 Record *Op = P->getOperator();
114 if (Op->isSubClassOf("Instruction")) {
115 Cost++;
116 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
117 if (II.usesCustomInserter)
118 Cost += 10;
119 }
120 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
121 Cost += getResultPatternCost(P->getChild(i), CGP);
122 return Cost;
123}
124
125/// getResultPatternCodeSize - Compute the code size of instructions for this
126/// pattern.
127static unsigned getResultPatternSize(TreePatternNode *P,
128 CodeGenDAGPatterns &CGP) {
129 if (P->isLeaf()) return 0;
130
131 unsigned Cost = 0;
132 Record *Op = P->getOperator();
133 if (Op->isSubClassOf("Instruction")) {
134 Cost += Op->getValueAsInt("CodeSize");
135 }
136 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
137 Cost += getResultPatternSize(P->getChild(i), CGP);
138 return Cost;
139}
140
141// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
142// In particular, we want to match maximal patterns first and lowest cost within
143// a particular complexity first.
144struct PatternSortingPredicate {
145 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
146 CodeGenDAGPatterns &CGP;
147
148 typedef std::pair<unsigned, std::string> CodeLine;
149 typedef std::vector<CodeLine> CodeList;
150 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
151
152 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
153 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
154 const PatternToMatch *LHS = LHSPair.first;
155 const PatternToMatch *RHS = RHSPair.first;
156
157 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
158 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
159 LHSSize += LHS->getAddedComplexity();
160 RHSSize += RHS->getAddedComplexity();
161 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
162 if (LHSSize < RHSSize) return false;
163
164 // If the patterns have equal complexity, compare generated instruction cost
165 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
166 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
167 if (LHSCost < RHSCost) return true;
168 if (LHSCost > RHSCost) return false;
169
170 return getResultPatternSize(LHS->getDstPattern(), CGP) <
171 getResultPatternSize(RHS->getDstPattern(), CGP);
172 }
173};
174
175/// getRegisterValueType - Look up and return the ValueType of the specified
176/// register. If the register is a member of multiple register classes which
177/// have different associated types, return MVT::Other.
178static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
179 bool FoundRC = false;
180 MVT::SimpleValueType VT = MVT::Other;
181 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
182 std::vector<CodeGenRegisterClass>::const_iterator RC;
183 std::vector<Record*>::const_iterator Element;
184
185 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
186 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
187 if (Element != (*RC).Elements.end()) {
188 if (!FoundRC) {
189 FoundRC = true;
190 VT = (*RC).getValueTypeNum(0);
191 } else {
192 // In multiple RC's
193 if (VT != (*RC).getValueTypeNum(0)) {
194 // Types of the RC's do not agree. Return MVT::Other. The
195 // target is responsible for handling this.
196 return MVT::Other;
197 }
198 }
199 }
200 }
201 return VT;
202}
203
204
205/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
206/// type information from it.
207static void RemoveAllTypes(TreePatternNode *N) {
208 N->removeTypes();
209 if (!N->isLeaf())
210 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
211 RemoveAllTypes(N->getChild(i));
212}
213
214/// NodeHasProperty - return true if TreePatternNode has the specified
215/// property.
216static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
217 CodeGenDAGPatterns &CGP) {
218 if (N->isLeaf()) {
219 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
220 if (CP)
221 return CP->hasProperty(Property);
222 return false;
223 }
224 Record *Operator = N->getOperator();
225 if (!Operator->isSubClassOf("SDNode")) return false;
226
227 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
228}
229
230static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
231 CodeGenDAGPatterns &CGP) {
232 if (NodeHasProperty(N, Property, CGP))
233 return true;
234
235 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
236 TreePatternNode *Child = N->getChild(i);
237 if (PatternHasProperty(Child, Property, CGP))
238 return true;
239 }
240
241 return false;
242}
243
244static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
245 return CGP.getSDNodeInfo(Op).getEnumName();
246}
247
248static
249bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
250 bool isStore = !N->isLeaf() &&
251 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
252 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
253 return false;
254
255 bool HasChain = false;
256 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
257 TreePatternNode *Child = N->getChild(i);
258 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
259 HasChain = true;
260 break;
261 }
262 }
263 return HasChain;
264}
265
266//===----------------------------------------------------------------------===//
267// Node Transformation emitter implementation.
268//
269void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
270 // Walk the pattern fragments, adding them to a map, which sorts them by
271 // name.
272 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
273 NXsByNameTy NXsByName;
274
275 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
276 I != E; ++I)
277 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
278
279 OS << "\n// Node transformations.\n";
280
281 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
282 I != E; ++I) {
283 Record *SDNode = I->second.first;
284 std::string Code = I->second.second;
285
286 if (Code.empty()) continue; // Empty code? Skip it.
287
288 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
289 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
290
291 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
292 << ") {\n";
293 if (ClassName != "SDNode")
294 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
295 OS << Code << "\n}\n";
296 }
297}
298
299//===----------------------------------------------------------------------===//
300// Predicate emitter implementation.
301//
302
303void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
304 OS << "\n// Predicate functions.\n";
305
306 // Walk the pattern fragments, adding them to a map, which sorts them by
307 // name.
308 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
309 PFsByNameTy PFsByName;
310
311 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
312 I != E; ++I)
313 PFsByName.insert(std::make_pair(I->first->getName(), *I));
314
315
316 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
317 I != E; ++I) {
318 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
319 TreePattern *P = I->second.second;
320
321 // If there is a code init for this fragment, emit the predicate code.
322 std::string Code = PatFragRecord->getValueAsCode("Predicate");
323 if (Code.empty()) continue;
324
325 if (P->getOnlyTree()->isLeaf())
326 OS << "inline bool Predicate_" << PatFragRecord->getName()
327 << "(SDNode *N) {\n";
328 else {
329 std::string ClassName =
330 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
331 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
332
333 OS << "inline bool Predicate_" << PatFragRecord->getName()
334 << "(SDNode *" << C2 << ") {\n";
335 if (ClassName != "SDNode")
336 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
337 }
338 OS << Code << "\n}\n";
339 }
340
341 OS << "\n\n";
342}
343
344
345//===----------------------------------------------------------------------===//
346// PatternCodeEmitter implementation.
347//
348class PatternCodeEmitter {
349private:
350 CodeGenDAGPatterns &CGP;
351
352 // Predicates.
353 std::string PredicateCheck;
354 // Pattern cost.
355 unsigned Cost;
356 // Instruction selector pattern.
357 TreePatternNode *Pattern;
358 // Matched instruction.
359 TreePatternNode *Instruction;
360
361 // Node to name mapping
362 std::map<std::string, std::string> VariableMap;
363 // Node to operator mapping
364 std::map<std::string, Record*> OperatorMap;
365 // Name of the folded node which produces a flag.
366 std::pair<std::string, unsigned> FoldedFlag;
367 // Names of all the folded nodes which produce chains.
368 std::vector<std::pair<std::string, unsigned> > FoldedChains;
369 // Original input chain(s).
370 std::vector<std::pair<std::string, std::string> > OrigChains;
371 std::set<std::string> Duplicates;
372
373 /// LSI - Load/Store information.
374 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
375 /// for each memory access. This facilitates the use of AliasAnalysis in
376 /// the backend.
377 std::vector<std::string> LSI;
378
379 /// GeneratedCode - This is the buffer that we emit code to. The first int
380 /// indicates whether this is an exit predicate (something that should be
381 /// tested, and if true, the match fails) [when 1], or normal code to emit
382 /// [when 0], or initialization code to emit [when 2].
383 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
384 /// GeneratedDecl - This is the set of all SDValue declarations needed for
385 /// the set of patterns for each top-level opcode.
386 std::set<std::string> &GeneratedDecl;
387 /// TargetOpcodes - The target specific opcodes used by the resulting
388 /// instructions.
389 std::vector<std::string> &TargetOpcodes;
390 std::vector<std::string> &TargetVTs;
391 /// OutputIsVariadic - Records whether the instruction output pattern uses
392 /// variable_ops. This requires that the Emit function be passed an
393 /// additional argument to indicate where the input varargs operands
394 /// begin.
395 bool &OutputIsVariadic;
396 /// NumInputRootOps - Records the number of operands the root node of the
397 /// input pattern has. This information is used in the generated code to
398 /// pass to Emit functions when variable_ops processing is needed.
399 unsigned &NumInputRootOps;
400
401 std::string ChainName;
402 unsigned TmpNo;
403 unsigned OpcNo;
404 unsigned VTNo;
405
406 void emitCheck(const std::string &S) {
407 if (!S.empty())
408 GeneratedCode.push_back(std::make_pair(1, S));
409 }
410 void emitCode(const std::string &S) {
411 if (!S.empty())
412 GeneratedCode.push_back(std::make_pair(0, S));
413 }
414 void emitInit(const std::string &S) {
415 if (!S.empty())
416 GeneratedCode.push_back(std::make_pair(2, S));
417 }
418 void emitDecl(const std::string &S) {
419 assert(!S.empty() && "Invalid declaration");
420 GeneratedDecl.insert(S);
421 }
422 void emitOpcode(const std::string &Opc) {
423 TargetOpcodes.push_back(Opc);
424 OpcNo++;
425 }
426 void emitVT(const std::string &VT) {
427 TargetVTs.push_back(VT);
428 VTNo++;
429 }
430public:
431 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
432 TreePatternNode *pattern, TreePatternNode *instr,
433 std::vector<std::pair<unsigned, std::string> > &gc,
434 std::set<std::string> &gd,
435 std::vector<std::string> &to,
436 std::vector<std::string> &tv,
437 bool &oiv,
438 unsigned &niro)
439 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
440 GeneratedCode(gc), GeneratedDecl(gd),
441 TargetOpcodes(to), TargetVTs(tv),
442 OutputIsVariadic(oiv), NumInputRootOps(niro),
443 TmpNo(0), OpcNo(0), VTNo(0) {}
444
445 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
446 /// if the match fails. At this point, we already know that the opcode for N
447 /// matches, and the SDNode for the result has the RootName specified name.
448 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
449 const std::string &RootName, const std::string &ChainSuffix,
450 bool &FoundChain) {
451
452 // Save loads/stores matched by a pattern.
453 if (!N->isLeaf() && N->getName().empty()) {
454 if (NodeHasProperty(N, SDNPMemOperand, CGP))
455 LSI.push_back(RootName);
456 }
457
458 bool isRoot = (P == NULL);
459 // Emit instruction predicates. Each predicate is just a string for now.
460 if (isRoot) {
461 // Record input varargs info.
462 NumInputRootOps = N->getNumChildren();
463
464 if (DisablePatternForFastISel(N, CGP))
465 emitCheck("OptLevel != CodeGenOpt::None");
466
467 emitCheck(PredicateCheck);
468 }
469
470 if (N->isLeaf()) {
471 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
472 emitCheck("cast<ConstantSDNode>(" + RootName +
473 ")->getSExtValue() == INT64_C(" +
474 itostr(II->getValue()) + ")");
475 return;
476 } else if (!NodeIsComplexPattern(N)) {
477 assert(0 && "Cannot match this as a leaf value!");
478 abort();
479 }
480 }
481
482 // If this node has a name associated with it, capture it in VariableMap. If
483 // we already saw this in the pattern, emit code to verify dagness.
484 if (!N->getName().empty()) {
485 std::string &VarMapEntry = VariableMap[N->getName()];
486 if (VarMapEntry.empty()) {
487 VarMapEntry = RootName;
488 } else {
489 // If we get here, this is a second reference to a specific name. Since
490 // we already have checked that the first reference is valid, we don't
491 // have to recursively match it, just check that it's the same as the
492 // previously named thing.
493 emitCheck(VarMapEntry + " == " + RootName);
494 return;
495 }
496
497 if (!N->isLeaf())
498 OperatorMap[N->getName()] = N->getOperator();
499 }
500
501
502 // Emit code to load the child nodes and match their contents recursively.
503 unsigned OpNo = 0;
504 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
505 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
506 bool EmittedUseCheck = false;
507 if (HasChain) {
508 if (NodeHasChain)
509 OpNo = 1;
510 if (!isRoot) {
511 // Multiple uses of actual result?
512 emitCheck(RootName + ".hasOneUse()");
513 EmittedUseCheck = true;
514 if (NodeHasChain) {
515 // If the immediate use can somehow reach this node through another
516 // path, then can't fold it either or it will create a cycle.
517 // e.g. In the following diagram, XX can reach ld through YY. If
518 // ld is folded into XX, then YY is both a predecessor and a successor
519 // of XX.
520 //
521 // [ld]
522 // ^ ^
523 // | |
524 // / \---
525 // / [YY]
526 // | ^
527 // [XX]-------|
528 bool NeedCheck = P != Pattern;
529 if (!NeedCheck) {
530 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
531 NeedCheck =
532 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
533 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
534 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
535 PInfo.getNumOperands() > 1 ||
536 PInfo.hasProperty(SDNPHasChain) ||
537 PInfo.hasProperty(SDNPInFlag) ||
538 PInfo.hasProperty(SDNPOptInFlag);
539 }
540
541 if (NeedCheck) {
542 std::string ParentName(RootName.begin(), RootName.end()-1);
543 emitCheck("IsLegalAndProfitableToFold(" + RootName +
544 ".getNode(), " + ParentName + ".getNode(), N.getNode())");
545 }
546 }
547 }
548
549 if (NodeHasChain) {
550 if (FoundChain) {
551 emitCheck("(" + ChainName + ".getNode() == " + RootName + ".getNode() || "
552 "IsChainCompatible(" + ChainName + ".getNode(), " +
553 RootName + ".getNode()))");
554 OrigChains.push_back(std::make_pair(ChainName, RootName));
555 } else
556 FoundChain = true;
557 ChainName = "Chain" + ChainSuffix;
558 emitInit("SDValue " + ChainName + " = " + RootName +
559 ".getOperand(0);");
560 }
561 }
562
563 // Don't fold any node which reads or writes a flag and has multiple uses.
564 // FIXME: We really need to separate the concepts of flag and "glue". Those
565 // real flag results, e.g. X86CMP output, can have multiple uses.
566 // FIXME: If the optional incoming flag does not exist. Then it is ok to
567 // fold it.
568 if (!isRoot &&
569 (PatternHasProperty(N, SDNPInFlag, CGP) ||
570 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
571 PatternHasProperty(N, SDNPOutFlag, CGP))) {
572 if (!EmittedUseCheck) {
573 // Multiple uses of actual result?
574 emitCheck(RootName + ".hasOneUse()");
575 }
576 }
577
578 // If there are node predicates for this, emit the calls.
579 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
580 emitCheck(N->getPredicateFns()[i] + "(" + RootName + ".getNode())");
581
582 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
583 // a constant without a predicate fn that has more that one bit set, handle
584 // this as a special case. This is usually for targets that have special
585 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
586 // handling stuff). Using these instructions is often far more efficient
587 // than materializing the constant. Unfortunately, both the instcombiner
588 // and the dag combiner can often infer that bits are dead, and thus drop
589 // them from the mask in the dag. For example, it might turn 'AND X, 255'
590 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
591 // to handle this.
592 if (!N->isLeaf() &&
593 (N->getOperator()->getName() == "and" ||
594 N->getOperator()->getName() == "or") &&
595 N->getChild(1)->isLeaf() &&
596 N->getChild(1)->getPredicateFns().empty()) {
597 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
598 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
599 emitInit("SDValue " + RootName + "0" + " = " +
600 RootName + ".getOperand(" + utostr(0) + ");");
601 emitInit("SDValue " + RootName + "1" + " = " +
602 RootName + ".getOperand(" + utostr(1) + ");");
603
604 unsigned NTmp = TmpNo++;
605 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
606 " = dyn_cast<ConstantSDNode>(" + RootName + "1);");
607 emitCheck("Tmp" + utostr(NTmp));
608 const char *MaskPredicate = N->getOperator()->getName() == "or"
609 ? "CheckOrMask(" : "CheckAndMask(";
610 emitCheck(MaskPredicate + RootName + "0, Tmp" + utostr(NTmp) +
611 ", INT64_C(" + itostr(II->getValue()) + "))");
612
613 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
614 ChainSuffix + utostr(0), FoundChain);
615 return;
616 }
617 }
618 }
619
620 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
621 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
622 RootName + ".getOperand(" +utostr(OpNo) + ");");
623
624 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
625 ChainSuffix + utostr(OpNo), FoundChain);
626 }
627
628 // Handle cases when root is a complex pattern.
629 const ComplexPattern *CP;
630 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
631 std::string Fn = CP->getSelectFunc();
632 unsigned NumOps = CP->getNumOperands();
633 for (unsigned i = 0; i < NumOps; ++i) {
634 emitDecl("CPTmp" + RootName + "_" + utostr(i));
635 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
636 }
637 if (CP->hasProperty(SDNPHasChain)) {
638 emitDecl("CPInChain");
639 emitDecl("Chain" + ChainSuffix);
640 emitCode("SDValue CPInChain;");
641 emitCode("SDValue Chain" + ChainSuffix + ";");
642 }
643
644 std::string Code = Fn + "(" + RootName + ", " + RootName;
645 for (unsigned i = 0; i < NumOps; i++)
646 Code += ", CPTmp" + RootName + "_" + utostr(i);
647 if (CP->hasProperty(SDNPHasChain)) {
648 ChainName = "Chain" + ChainSuffix;
649 Code += ", CPInChain, Chain" + ChainSuffix;
650 }
651 emitCheck(Code + ")");
652 }
653 }
654
655 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
656 const std::string &RootName,
657 const std::string &ParentRootName,
658 const std::string &ChainSuffix, bool &FoundChain) {
659 if (!Child->isLeaf()) {
660 // If it's not a leaf, recursively match.
661 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
662 emitCheck(RootName + ".getOpcode() == " +
663 CInfo.getEnumName());
664 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
665 bool HasChain = false;
666 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
667 HasChain = true;
668 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
669 }
670 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
671 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
672 "Pattern folded multiple nodes which produce flags?");
673 FoldedFlag = std::make_pair(RootName,
674 CInfo.getNumResults() + (unsigned)HasChain);
675 }
676 } else {
677 // If this child has a name associated with it, capture it in VarMap. If
678 // we already saw this in the pattern, emit code to verify dagness.
679 if (!Child->getName().empty()) {
680 std::string &VarMapEntry = VariableMap[Child->getName()];
681 if (VarMapEntry.empty()) {
682 VarMapEntry = RootName;
683 } else {
684 // If we get here, this is a second reference to a specific name.
685 // Since we already have checked that the first reference is valid,
686 // we don't have to recursively match it, just check that it's the
687 // same as the previously named thing.
688 emitCheck(VarMapEntry + " == " + RootName);
689 Duplicates.insert(RootName);
690 return;
691 }
692 }
693
694 // Handle leaves of various types.
695 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
696 Record *LeafRec = DI->getDef();
697 if (LeafRec->isSubClassOf("RegisterClass") ||
698 LeafRec->isSubClassOf("PointerLikeRegClass")) {
699 // Handle register references. Nothing to do here.
700 } else if (LeafRec->isSubClassOf("Register")) {
701 // Handle register references.
702 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
703 // Handle complex pattern.
704 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
705 std::string Fn = CP->getSelectFunc();
706 unsigned NumOps = CP->getNumOperands();
707 for (unsigned i = 0; i < NumOps; ++i) {
708 emitDecl("CPTmp" + RootName + "_" + utostr(i));
709 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
710 }
711 if (CP->hasProperty(SDNPHasChain)) {
712 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
713 FoldedChains.push_back(std::make_pair("CPInChain",
714 PInfo.getNumResults()));
715 ChainName = "Chain" + ChainSuffix;
716 emitDecl("CPInChain");
717 emitDecl(ChainName);
718 emitCode("SDValue CPInChain;");
719 emitCode("SDValue " + ChainName + ";");
720 }
721
722 std::string Code = Fn + "(";
723 if (CP->hasAttribute(CPAttrParentAsRoot)) {
724 Code += ParentRootName + ", ";
725 } else {
726 Code += "N, ";
727 }
728 if (CP->hasProperty(SDNPHasChain)) {
729 std::string ParentName(RootName.begin(), RootName.end()-1);
730 Code += ParentName + ", ";
731 }
732 Code += RootName;
733 for (unsigned i = 0; i < NumOps; i++)
734 Code += ", CPTmp" + RootName + "_" + utostr(i);
735 if (CP->hasProperty(SDNPHasChain))
736 Code += ", CPInChain, Chain" + ChainSuffix;
737 emitCheck(Code + ")");
738 } else if (LeafRec->getName() == "srcvalue") {
739 // Place holder for SRCVALUE nodes. Nothing to do here.
740 } else if (LeafRec->isSubClassOf("ValueType")) {
741 // Make sure this is the specified value type.
742 emitCheck("cast<VTSDNode>(" + RootName +
743 ")->getVT() == MVT::" + LeafRec->getName());
744 } else if (LeafRec->isSubClassOf("CondCode")) {
745 // Make sure this is the specified cond code.
746 emitCheck("cast<CondCodeSDNode>(" + RootName +
747 ")->get() == ISD::" + LeafRec->getName());
748 } else {
749#ifndef NDEBUG
750 Child->dump();
751 errs() << " ";
752#endif
753 assert(0 && "Unknown leaf type!");
754 }
755
756 // If there are node predicates for this, emit the calls.
757 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
758 emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
759 ".getNode())");
760 } else if (IntInit *II =
761 dynamic_cast<IntInit*>(Child->getLeafValue())) {
762 unsigned NTmp = TmpNo++;
763 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
764 " = dyn_cast<ConstantSDNode>("+
765 RootName + ");");
766 emitCheck("Tmp" + utostr(NTmp));
767 unsigned CTmp = TmpNo++;
768 emitCode("int64_t CN"+ utostr(CTmp) +
769 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
770 emitCheck("CN" + utostr(CTmp) + " == "
771 "INT64_C(" +itostr(II->getValue()) + ")");
772 } else {
773#ifndef NDEBUG
774 Child->dump();
775#endif
776 assert(0 && "Unknown leaf type!");
777 }
778 }
779 }
780
781 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
782 /// we actually have to build a DAG!
783 std::vector<std::string>
784 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
785 bool InFlagDecled, bool ResNodeDecled,
786 bool LikeLeaf = false, bool isRoot = false) {
787 // List of arguments of getMachineNode() or SelectNodeTo().
788 std::vector<std::string> NodeOps;
789 // This is something selected from the pattern we matched.
790 if (!N->getName().empty()) {
791 const std::string &VarName = N->getName();
792 std::string Val = VariableMap[VarName];
793 bool ModifiedVal = false;
794 if (Val.empty()) {
795 errs() << "Variable '" << VarName << " referenced but not defined "
796 << "and not caught earlier!\n";
797 abort();
798 }
799 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
800 // Already selected this operand, just return the tmpval.
801 NodeOps.push_back(Val);
802 return NodeOps;
803 }
804
805 const ComplexPattern *CP;
806 unsigned ResNo = TmpNo++;
807 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
808 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
809 std::string CastType;
810 std::string TmpVar = "Tmp" + utostr(ResNo);
811 switch (N->getTypeNum(0)) {
812 default:
813 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
814 << " type as an immediate constant. Aborting\n";
815 abort();
816 case MVT::i1: CastType = "bool"; break;
817 case MVT::i8: CastType = "unsigned char"; break;
818 case MVT::i16: CastType = "unsigned short"; break;
819 case MVT::i32: CastType = "unsigned"; break;
820 case MVT::i64: CastType = "uint64_t"; break;
821 }
822 emitCode("SDValue " + TmpVar +
823 " = CurDAG->getTargetConstant(((" + CastType +
824 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
825 getEnumName(N->getTypeNum(0)) + ");");
826 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
827 // value if used multiple times by this pattern result.
828 Val = TmpVar;
829 ModifiedVal = true;
830 NodeOps.push_back(Val);
831 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
832 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
833 std::string TmpVar = "Tmp" + utostr(ResNo);
834 emitCode("SDValue " + TmpVar +
835 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
836 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
837 Val + ")->getValueType(0));");
838 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
839 // value if used multiple times by this pattern result.
840 Val = TmpVar;
841 ModifiedVal = true;
842 NodeOps.push_back(Val);
843 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
844 Record *Op = OperatorMap[N->getName()];
845 // Transform ExternalSymbol to TargetExternalSymbol
846 if (Op && Op->getName() == "externalsym") {
847 std::string TmpVar = "Tmp"+utostr(ResNo);
848 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
849 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
850 Val + ")->getSymbol(), " +
851 getEnumName(N->getTypeNum(0)) + ");");
852 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
853 // this value if used multiple times by this pattern result.
854 Val = TmpVar;
855 ModifiedVal = true;
856 }
857 NodeOps.push_back(Val);
858 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
859 || N->getOperator()->getName() == "tglobaltlsaddr")) {
860 Record *Op = OperatorMap[N->getName()];
861 // Transform GlobalAddress to TargetGlobalAddress
862 if (Op && (Op->getName() == "globaladdr" ||
863 Op->getName() == "globaltlsaddr")) {
864 std::string TmpVar = "Tmp" + utostr(ResNo);
865 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
866 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
867 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
868 ");");
869 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
870 // this value if used multiple times by this pattern result.
871 Val = TmpVar;
872 ModifiedVal = true;
873 }
874 NodeOps.push_back(Val);
875 } else if (!N->isLeaf()
876 && (N->getOperator()->getName() == "texternalsym"
877 || N->getOperator()->getName() == "tconstpool")) {
878 // Do not rewrite the variable name, since we don't generate a new
879 // temporary.
880 NodeOps.push_back(Val);
881 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
882 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
883 NodeOps.push_back("CPTmp" + Val + "_" + utostr(i));
884 }
885 } else {
886 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
887 // node even if it isn't one. Don't select it.
888 if (!LikeLeaf) {
889 if (isRoot && N->isLeaf()) {
890 emitCode("ReplaceUses(N, " + Val + ");");
891 emitCode("return NULL;");
892 }
893 }
894 NodeOps.push_back(Val);
895 }
896
897 if (ModifiedVal) {
898 VariableMap[VarName] = Val;
899 }
900 return NodeOps;
901 }
902 if (N->isLeaf()) {
903 // If this is an explicit register reference, handle it.
904 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
905 unsigned ResNo = TmpNo++;
906 if (DI->getDef()->isSubClassOf("Register")) {
907 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
908 getQualifiedName(DI->getDef()) + ", " +
909 getEnumName(N->getTypeNum(0)) + ");");
910 NodeOps.push_back("Tmp" + utostr(ResNo));
911 return NodeOps;
912 } else if (DI->getDef()->getName() == "zero_reg") {
913 emitCode("SDValue Tmp" + utostr(ResNo) +
914 " = CurDAG->getRegister(0, " +
915 getEnumName(N->getTypeNum(0)) + ");");
916 NodeOps.push_back("Tmp" + utostr(ResNo));
917 return NodeOps;
918 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
919 // Handle a reference to a register class. This is used
920 // in COPY_TO_SUBREG instructions.
921 emitCode("SDValue Tmp" + utostr(ResNo) +
922 " = CurDAG->getTargetConstant(" +
923 getQualifiedName(DI->getDef()) + "RegClassID, " +
924 "MVT::i32);");
925 NodeOps.push_back("Tmp" + utostr(ResNo));
926 return NodeOps;
927 }
928 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
929 unsigned ResNo = TmpNo++;
930 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
931 emitCode("SDValue Tmp" + utostr(ResNo) +
932 " = CurDAG->getTargetConstant(0x" +
933 utohexstr((uint64_t) II->getValue()) +
934 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
935 NodeOps.push_back("Tmp" + utostr(ResNo));
936 return NodeOps;
937 }
938
939#ifndef NDEBUG
940 N->dump();
941#endif
942 assert(0 && "Unknown leaf type!");
943 return NodeOps;
944 }
945
946 Record *Op = N->getOperator();
947 if (Op->isSubClassOf("Instruction")) {
948 const CodeGenTarget &CGT = CGP.getTargetInfo();
949 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
950 const DAGInstruction &Inst = CGP.getInstruction(Op);
951 const TreePattern *InstPat = Inst.getPattern();
952 // FIXME: Assume actual pattern comes before "implicit".
953 TreePatternNode *InstPatNode =
954 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
955 : (InstPat ? InstPat->getTree(0) : NULL);
956 if (InstPatNode && !InstPatNode->isLeaf() &&
957 InstPatNode->getOperator()->getName() == "set") {
958 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
959 }
960 bool IsVariadic = isRoot && II.isVariadic;
961 // FIXME: fix how we deal with physical register operands.
962 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
963 bool HasImpResults = isRoot && DstRegs.size() > 0;
964 bool NodeHasOptInFlag = isRoot &&
965 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
966 bool NodeHasInFlag = isRoot &&
967 PatternHasProperty(Pattern, SDNPInFlag, CGP);
968 bool NodeHasOutFlag = isRoot &&
969 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
970 bool NodeHasChain = InstPatNode &&
971 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
972 bool InputHasChain = isRoot &&
973 NodeHasProperty(Pattern, SDNPHasChain, CGP);
974 unsigned NumResults = Inst.getNumResults();
975 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
976
977 // Record output varargs info.
978 OutputIsVariadic = IsVariadic;
979
980 if (NodeHasOptInFlag) {
981 emitCode("bool HasInFlag = "
982 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
983 }
984 if (IsVariadic)
985 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
986
987 // How many results is this pattern expected to produce?
988 unsigned NumPatResults = 0;
989 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
990 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
991 if (VT != MVT::isVoid && VT != MVT::Flag)
992 NumPatResults++;
993 }
994
995 if (OrigChains.size() > 0) {
996 // The original input chain is being ignored. If it is not just
997 // pointing to the op that's being folded, we should create a
998 // TokenFactor with it and the chain of the folded op as the new chain.
999 // We could potentially be doing multiple levels of folding, in that
1000 // case, the TokenFactor can have more operands.
1001 emitCode("SmallVector<SDValue, 8> InChains;");
1002 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1003 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1004 OrigChains[i].second + ".getNode()) {");
1005 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1006 emitCode("}");
1007 }
1008 emitCode("InChains.push_back(" + ChainName + ");");
1009 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1010 "N.getDebugLoc(), MVT::Other, "
1011 "&InChains[0], InChains.size());");
1012 if (GenDebug) {
1013 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1014 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1015 }
1016 }
1017
1018 // Loop over all of the operands of the instruction pattern, emitting code
1019 // to fill them all in. The node 'N' usually has number children equal to
1020 // the number of input operands of the instruction. However, in cases
1021 // where there are predicate operands for an instruction, we need to fill
1022 // in the 'execute always' values. Match up the node operands to the
1023 // instruction operands to do this.
1024 std::vector<std::string> AllOps;
1025 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1026 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1027 std::vector<std::string> Ops;
1028
1029 // Determine what to emit for this operand.
1030 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1031 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1032 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1033 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1034 // This is a predicate or optional def operand; emit the
1035 // 'default ops' operands.
1036 const DAGDefaultOperand &DefaultOp =
1037 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1038 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1039 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1040 InFlagDecled, ResNodeDecled);
1041 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1042 }
1043 } else {
1044 // Otherwise this is a normal operand or a predicate operand without
1045 // 'execute always'; emit it.
1046 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1047 InFlagDecled, ResNodeDecled);
1048 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1049 ++ChildNo;
1050 }
1051 }
1052
1053 // Emit all the chain and CopyToReg stuff.
1054 bool ChainEmitted = NodeHasChain;
1055 if (NodeHasInFlag || HasImpInputs)
1056 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1057 InFlagDecled, ResNodeDecled, true);
1058 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1059 if (!InFlagDecled) {
1060 emitCode("SDValue InFlag(0, 0);");
1061 InFlagDecled = true;
1062 }
1063 if (NodeHasOptInFlag) {
1064 emitCode("if (HasInFlag) {");
1065 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1066 emitCode("}");
1067 }
1068 }
1069
1070 unsigned ResNo = TmpNo++;
1071
1072 unsigned OpsNo = OpcNo;
1073 std::string CodePrefix;
1074 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1075 std::deque<std::string> After;
1076 std::string NodeName;
1077 if (!isRoot) {
1078 NodeName = "Tmp" + utostr(ResNo);
1079 CodePrefix = "SDValue " + NodeName + "(";
1080 } else {
1081 NodeName = "ResNode";
1082 if (!ResNodeDecled) {
1083 CodePrefix = "SDNode *" + NodeName + " = ";
1084 ResNodeDecled = true;
1085 } else
1086 CodePrefix = NodeName + " = ";
1087 }
1088
1089 std::string Code = "Opc" + utostr(OpcNo);
1090
1091 if (!isRoot || (InputHasChain && !NodeHasChain))
1092 // For call to "getMachineNode()".
1093 Code += ", N.getDebugLoc()";
1094
1095 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1096
1097 // Output order: results, chain, flags
1098 // Result types.
1099 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1100 Code += ", VT" + utostr(VTNo);
1101 emitVT(getEnumName(N->getTypeNum(0)));
1102 }
1103 // Add types for implicit results in physical registers, scheduler will
1104 // care of adding copyfromreg nodes.
1105 for (unsigned i = 0; i < NumDstRegs; i++) {
1106 Record *RR = DstRegs[i];
1107 if (RR->isSubClassOf("Register")) {
1108 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1109 Code += ", " + getEnumName(RVT);
1110 }
1111 }
1112 if (NodeHasChain)
1113 Code += ", MVT::Other";
1114 if (NodeHasOutFlag)
1115 Code += ", MVT::Flag";
1116
1117 // Inputs.
1118 if (IsVariadic) {
1119 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1120 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1121 AllOps.clear();
1122
1123 // Figure out whether any operands at the end of the op list are not
1124 // part of the variable section.
1125 std::string EndAdjust;
1126 if (NodeHasInFlag || HasImpInputs)
1127 EndAdjust = "-1"; // Always has one flag.
1128 else if (NodeHasOptInFlag)
1129 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1130
1131 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1132 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1133
1134 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1135 emitCode("}");
1136 }
1137
1138 // Populate MemRefs with entries for each memory accesses covered by
1139 // this pattern.
1140 if (isRoot && !LSI.empty()) {
1141 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1142 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1143 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1144 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1145 emitCode(MemRefs + "[" + utostr(i) + "] = "
1146 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1147 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1148 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1149 ");");
1150 }
1151
1152 if (NodeHasChain) {
1153 if (IsVariadic)
1154 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1155 else
1156 AllOps.push_back(ChainName);
1157 }
1158
1159 if (IsVariadic) {
1160 if (NodeHasInFlag || HasImpInputs)
1161 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1162 else if (NodeHasOptInFlag) {
1163 emitCode("if (HasInFlag)");
1164 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1165 }
1166 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1167 ".size()";
1168 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1169 AllOps.push_back("InFlag");
1170
1171 unsigned NumOps = AllOps.size();
1172 if (NumOps) {
1173 if (!NodeHasOptInFlag && NumOps < 4) {
1174 for (unsigned i = 0; i != NumOps; ++i)
1175 Code += ", " + AllOps[i];
1176 } else {
1177 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1178 for (unsigned i = 0; i != NumOps; ++i) {
1179 OpsCode += AllOps[i];
1180 if (i != NumOps-1)
1181 OpsCode += ", ";
1182 }
1183 emitCode(OpsCode + " };");
1184 Code += ", Ops" + utostr(OpsNo) + ", ";
1185 if (NodeHasOptInFlag) {
1186 Code += "HasInFlag ? ";
1187 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1188 } else
1189 Code += utostr(NumOps);
1190 }
1191 }
1192
1193 if (!isRoot)
1194 Code += "), 0";
1195
1196 std::vector<std::string> ReplaceFroms;
1197 std::vector<std::string> ReplaceTos;
1198 if (!isRoot) {
1199 NodeOps.push_back("Tmp" + utostr(ResNo));
1200 } else {
1201
1202 if (NodeHasOutFlag) {
1203 if (!InFlagDecled) {
1204 After.push_back("SDValue InFlag(ResNode, " +
1205 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1206 ");");
1207 InFlagDecled = true;
1208 } else
1209 After.push_back("InFlag = SDValue(ResNode, " +
1210 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1211 ");");
1212 }
1213
1214 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1215 ReplaceFroms.push_back("SDValue(" +
1216 FoldedChains[j].first + ".getNode(), " +
1217 utostr(FoldedChains[j].second) +
1218 ")");
1219 ReplaceTos.push_back("SDValue(ResNode, " +
1220 utostr(NumResults+NumDstRegs) + ")");
1221 }
1222
1223 if (NodeHasOutFlag) {
1224 if (FoldedFlag.first != "") {
1225 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1226 utostr(FoldedFlag.second) + ")");
1227 ReplaceTos.push_back("InFlag");
1228 } else {
1229 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1230 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1231 utostr(NumPatResults + (unsigned)InputHasChain)
1232 + ")");
1233 ReplaceTos.push_back("InFlag");
1234 }
1235 }
1236
1237 if (!ReplaceFroms.empty() && InputHasChain) {
1238 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1239 utostr(NumPatResults) + ")");
1240 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1241 ChainName + ".getResNo()" + ")");
1242 ChainAssignmentNeeded |= NodeHasChain;
1243 }
1244
1245 // User does not expect the instruction would produce a chain!
1246 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1247 ;
1248 } else if (InputHasChain && !NodeHasChain) {
1249 // One of the inner node produces a chain.
1250 if (NodeHasOutFlag) {
1251 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1252 utostr(NumPatResults+1) +
1253 ")");
1254 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
1255 }
1256 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1257 utostr(NumPatResults) + ")");
1258 ReplaceTos.push_back(ChainName);
1259 }
1260 }
1261
1262 if (ChainAssignmentNeeded) {
1263 // Remember which op produces the chain.
1264 std::string ChainAssign;
1265 if (!isRoot)
1266 ChainAssign = ChainName + " = SDValue(" + NodeName +
1267 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1268 else
1269 ChainAssign = ChainName + " = SDValue(" + NodeName +
1270 ", " + utostr(NumResults+NumDstRegs) + ");";
1271
1272 After.push_front(ChainAssign);
1273 }
1274
1275 if (ReplaceFroms.size() == 1) {
1276 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1277 ReplaceTos[0] + ");");
1278 } else if (!ReplaceFroms.empty()) {
1279 After.push_back("const SDValue Froms[] = {");
1280 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1281 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1282 After.push_back("};");
1283 After.push_back("const SDValue Tos[] = {");
1284 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1285 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1286 After.push_back("};");
1287 After.push_back("ReplaceUses(Froms, Tos, " +
1288 itostr(ReplaceFroms.size()) + ");");
1289 }
1290
1291 // We prefer to use SelectNodeTo since it avoids allocation when
1292 // possible and it avoids CSE map recalculation for the node's
1293 // users, however it's tricky to use in a non-root context.
1294 //
1295 // We also don't use if the pattern replacement is being used to
1296 // jettison a chain result, since morphing the node in place
1297 // would leave users of the chain dangling.
1298 //
1299 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1300 Code = "CurDAG->getMachineNode(" + Code;
1301 } else {
1302 Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1303 }
1304 if (isRoot) {
1305 if (After.empty())
1306 CodePrefix = "return ";
1307 else
1308 After.push_back("return ResNode;");
1309 }
1310
1311 emitCode(CodePrefix + Code + ");");
1312
1313 if (GenDebug) {
1314 if (!isRoot) {
1315 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1316 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1317 }
1318 else {
1319 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1320 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1321 }
1322 }
1323
1324 for (unsigned i = 0, e = After.size(); i != e; ++i)
1325 emitCode(After[i]);
1326
1327 return NodeOps;
1328 }
1329 if (Op->isSubClassOf("SDNodeXForm")) {
1330 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1331 // PatLeaf node - the operand may or may not be a leaf node. But it should
1332 // behave like one.
1333 std::vector<std::string> Ops =
1334 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1335 ResNodeDecled, true);
1336 unsigned ResNo = TmpNo++;
1337 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1338 + "(" + Ops.back() + ".getNode());");
1339 NodeOps.push_back("Tmp" + utostr(ResNo));
1340 if (isRoot)
1341 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1342 return NodeOps;
1343 }
1344
1345 N->dump();
1346 errs() << "\n";
1347 throw std::string("Unknown node in result pattern!");
1348 }
1349
1350 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1351 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1352 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1353 /// for, this returns true otherwise false if Pat has all types.
1354 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1355 const std::string &Prefix, bool isRoot = false) {
1356 // Did we find one?
1357 if (Pat->getExtTypes() != Other->getExtTypes()) {
1358 // Move a type over from 'other' to 'pat'.
1359 Pat->setTypes(Other->getExtTypes());
1360 // The top level node type is checked outside of the select function.
1361 if (!isRoot)
1362 emitCheck(Prefix + ".getValueType() == " +
1363 getName(Pat->getTypeNum(0)));
1364 return true;
1365 }
1366
1367 unsigned OpNo =
1368 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1369 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1370 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1371 Prefix + utostr(OpNo)))
1372 return true;
1373 return false;
1374 }
1375
1376private:
1377 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1378 /// being built.
1379 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1380 bool &ChainEmitted, bool &InFlagDecled,
1381 bool &ResNodeDecled, bool isRoot = false) {
1382 const CodeGenTarget &T = CGP.getTargetInfo();
1383 unsigned OpNo =
1384 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1385 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1386 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1387 TreePatternNode *Child = N->getChild(i);
1388 if (!Child->isLeaf()) {
1389 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1390 InFlagDecled, ResNodeDecled);
1391 } else {
1392 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1393 if (!Child->getName().empty()) {
1394 std::string Name = RootName + utostr(OpNo);
1395 if (Duplicates.find(Name) != Duplicates.end())
1396 // A duplicate! Do not emit a copy for this node.
1397 continue;
1398 }
1399
1400 Record *RR = DI->getDef();
1401 if (RR->isSubClassOf("Register")) {
1402 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1403 if (RVT == MVT::Flag) {
1404 if (!InFlagDecled) {
1405 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1406 InFlagDecled = true;
1407 } else
1408 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1409 } else {
1410 if (!ChainEmitted) {
1411 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1412 ChainName = "Chain";
1413 ChainEmitted = true;
1414 }
1415 if (!InFlagDecled) {
1416 emitCode("SDValue InFlag(0, 0);");
1417 InFlagDecled = true;
1418 }
1419 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1420 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1421 ", " + RootName + ".getDebugLoc()" +
1422 ", " + getQualifiedName(RR) +
1423 ", " + RootName + utostr(OpNo) + ", InFlag).getNode();");
1424 ResNodeDecled = true;
1425 emitCode(ChainName + " = SDValue(ResNode, 0);");
1426 emitCode("InFlag = SDValue(ResNode, 1);");
1427 }
1428 }
1429 }
1430 }
1431 }
1432
1433 if (HasInFlag) {
1434 if (!InFlagDecled) {
1435 emitCode("SDValue InFlag = " + RootName +
1436 ".getOperand(" + utostr(OpNo) + ");");
1437 InFlagDecled = true;
1438 } else
1439 emitCode("InFlag = " + RootName +
1440 ".getOperand(" + utostr(OpNo) + ");");
1441 }
1442 }
1443};
1444
1445/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1446/// stream to match the pattern, and generate the code for the match if it
1447/// succeeds. Returns true if the pattern is not guaranteed to match.
1448void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1449 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1450 std::set<std::string> &GeneratedDecl,
1451 std::vector<std::string> &TargetOpcodes,
1452 std::vector<std::string> &TargetVTs,
1453 bool &OutputIsVariadic,
1454 unsigned &NumInputRootOps) {
1455 OutputIsVariadic = false;
1456 NumInputRootOps = 0;
1457
1458 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1459 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1460 GeneratedCode, GeneratedDecl,
1461 TargetOpcodes, TargetVTs,
1462 OutputIsVariadic, NumInputRootOps);
1463
1464 // Emit the matcher, capturing named arguments in VariableMap.
1465 bool FoundChain = false;
1466 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1467
1468 // TP - Get *SOME* tree pattern, we don't care which.
1469 TreePattern &TP = *CGP.pf_begin()->second;
1470
1471 // At this point, we know that we structurally match the pattern, but the
1472 // types of the nodes may not match. Figure out the fewest number of type
1473 // comparisons we need to emit. For example, if there is only one integer
1474 // type supported by a target, there should be no type comparisons at all for
1475 // integer patterns!
1476 //
1477 // To figure out the fewest number of type checks needed, clone the pattern,
1478 // remove the types, then perform type inference on the pattern as a whole.
1479 // If there are unresolved types, emit an explicit check for those types,
1480 // apply the type to the tree, then rerun type inference. Iterate until all
1481 // types are resolved.
1482 //
1483 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1484 RemoveAllTypes(Pat);
1485
1486 do {
1487 // Resolve/propagate as many types as possible.
1488 try {
1489 bool MadeChange = true;
1490 while (MadeChange)
1491 MadeChange = Pat->ApplyTypeConstraints(TP,
1492 true/*Ignore reg constraints*/);
1493 } catch (...) {
1494 assert(0 && "Error: could not find consistent types for something we"
1495 " already decided was ok!");
1496 abort();
1497 }
1498
1499 // Insert a check for an unresolved type and add it to the tree. If we find
1500 // an unresolved type to add a check for, this returns true and we iterate,
1501 // otherwise we are done.
1502 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1503
1504 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1505 false, false, false, true);
1506 delete Pat;
1507}
1508
1509/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1510/// a line causes any of them to be empty, remove them and return true when
1511/// done.
1512static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1513 std::vector<std::pair<unsigned, std::string> > > >
1514 &Patterns) {
1515 bool ErasedPatterns = false;
1516 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1517 Patterns[i].second.pop_back();
1518 if (Patterns[i].second.empty()) {
1519 Patterns.erase(Patterns.begin()+i);
1520 --i; --e;
1521 ErasedPatterns = true;
1522 }
1523 }
1524 return ErasedPatterns;
1525}
1526
1527/// EmitPatterns - Emit code for at least one pattern, but try to group common
1528/// code together between the patterns.
1529void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1530 std::vector<std::pair<unsigned, std::string> > > >
1531 &Patterns, unsigned Indent,
1532 raw_ostream &OS) {
1533 typedef std::pair<unsigned, std::string> CodeLine;
1534 typedef std::vector<CodeLine> CodeList;
1535 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1536
1537 if (Patterns.empty()) return;
1538
1539 // Figure out how many patterns share the next code line. Explicitly copy
1540 // FirstCodeLine so that we don't invalidate a reference when changing
1541 // Patterns.
1542 const CodeLine FirstCodeLine = Patterns.back().second.back();
1543 unsigned LastMatch = Patterns.size()-1;
1544 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1545 --LastMatch;
1546
1547 // If not all patterns share this line, split the list into two pieces. The
1548 // first chunk will use this line, the second chunk won't.
1549 if (LastMatch != 0) {
1550 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1551 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1552
1553 // FIXME: Emit braces?
1554 if (Shared.size() == 1) {
1555 const PatternToMatch &Pattern = *Shared.back().first;
1556 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1557 Pattern.getSrcPattern()->print(OS);
1558 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1559 Pattern.getDstPattern()->print(OS);
1560 OS << "\n";
1561 unsigned AddedComplexity = Pattern.getAddedComplexity();
1562 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1563 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1564 << " cost = "
1565 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1566 << " size = "
1567 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1568 }
1569 if (FirstCodeLine.first != 1) {
1570 OS << std::string(Indent, ' ') << "{\n";
1571 Indent += 2;
1572 }
1573 EmitPatterns(Shared, Indent, OS);
1574 if (FirstCodeLine.first != 1) {
1575 Indent -= 2;
1576 OS << std::string(Indent, ' ') << "}\n";
1577 }
1578
1579 if (Other.size() == 1) {
1580 const PatternToMatch &Pattern = *Other.back().first;
1581 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1582 Pattern.getSrcPattern()->print(OS);
1583 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1584 Pattern.getDstPattern()->print(OS);
1585 OS << "\n";
1586 unsigned AddedComplexity = Pattern.getAddedComplexity();
1587 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1588 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1589 << " cost = "
1590 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1591 << " size = "
1592 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1593 }
1594 EmitPatterns(Other, Indent, OS);
1595 return;
1596 }
1597
1598 // Remove this code from all of the patterns that share it.
1599 bool ErasedPatterns = EraseCodeLine(Patterns);
1600
1601 bool isPredicate = FirstCodeLine.first == 1;
1602
1603 // Otherwise, every pattern in the list has this line. Emit it.
1604 if (!isPredicate) {
1605 // Normal code.
1606 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1607 } else {
1608 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1609
1610 // If the next code line is another predicate, and if all of the pattern
1611 // in this group share the same next line, emit it inline now. Do this
1612 // until we run out of common predicates.
1613 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1614 // Check that all of the patterns in Patterns end with the same predicate.
1615 bool AllEndWithSamePredicate = true;
1616 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1617 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1618 AllEndWithSamePredicate = false;
1619 break;
1620 }
1621 // If all of the predicates aren't the same, we can't share them.
1622 if (!AllEndWithSamePredicate) break;
1623
1624 // Otherwise we can. Emit it shared now.
1625 OS << " &&\n" << std::string(Indent+4, ' ')
1626 << Patterns.back().second.back().second;
1627 ErasedPatterns = EraseCodeLine(Patterns);
1628 }
1629
1630 OS << ") {\n";
1631 Indent += 2;
1632 }
1633
1634 EmitPatterns(Patterns, Indent, OS);
1635
1636 if (isPredicate)
1637 OS << std::string(Indent-2, ' ') << "}\n";
1638}
1639
1640static std::string getLegalCName(std::string OpName) {
1641 std::string::size_type pos = OpName.find("::");
1642 if (pos != std::string::npos)
1643 OpName.replace(pos, 2, "_");
1644 return OpName;
1645}
1646
1647void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1648 const CodeGenTarget &Target = CGP.getTargetInfo();
1649
1650 // Get the namespace to insert instructions into.
1651 std::string InstNS = Target.getInstNamespace();
1652 if (!InstNS.empty()) InstNS += "::";
1653
1654 // Group the patterns by their top-level opcodes.
1655 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1656 // All unique target node emission functions.
1657 std::map<std::string, unsigned> EmitFunctions;
1658 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1659 E = CGP.ptm_end(); I != E; ++I) {
1660 const PatternToMatch &Pattern = *I;
1661
1662 TreePatternNode *Node = Pattern.getSrcPattern();
1663 if (!Node->isLeaf()) {
1664 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1665 push_back(&Pattern);
1666 } else {
1667 const ComplexPattern *CP;
1668 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1669 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1670 push_back(&Pattern);
1671 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1672 std::vector<Record*> OpNodes = CP->getRootNodes();
1673 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1674 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1675 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1676 &Pattern);
1677 }
1678 } else {
1679 errs() << "Unrecognized opcode '";
1680 Node->dump();
1681 errs() << "' on tree pattern '";
1682 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1683 exit(1);
1684 }
1685 }
1686 }
1687
1688 // For each opcode, there might be multiple select functions, one per
1689 // ValueType of the node (or its first operand if it doesn't produce a
1690 // non-chain result.
1691 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1692
1693 // Emit one Select_* method for each top-level opcode. We do this instead of
1694 // emitting one giant switch statement to support compilers where this will
1695 // result in the recursive functions taking less stack space.
1696 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1697 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1698 PBOI != E; ++PBOI) {
1699 const std::string &OpName = PBOI->first;
1700 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1701 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1702
1703 // Split them into groups by type.
1704 std::map<MVT::SimpleValueType,
1705 std::vector<const PatternToMatch*> > PatternsByType;
1706 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1707 const PatternToMatch *Pat = PatternsOfOp[i];
1708 TreePatternNode *SrcPat = Pat->getSrcPattern();
1709 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1710 }
1711
1712 for (std::map<MVT::SimpleValueType,
1713 std::vector<const PatternToMatch*> >::iterator
1714 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1715 ++II) {
1716 MVT::SimpleValueType OpVT = II->first;
1717 std::vector<const PatternToMatch*> &Patterns = II->second;
1718 typedef std::pair<unsigned, std::string> CodeLine;
1719 typedef std::vector<CodeLine> CodeList;
1720 typedef CodeList::iterator CodeListI;
1721
1722 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1723 std::vector<std::vector<std::string> > PatternOpcodes;
1724 std::vector<std::vector<std::string> > PatternVTs;
1725 std::vector<std::set<std::string> > PatternDecls;
1726 std::vector<bool> OutputIsVariadicFlags;
1727 std::vector<unsigned> NumInputRootOpsCounts;
1728 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1729 CodeList GeneratedCode;
1730 std::set<std::string> GeneratedDecl;
1731 std::vector<std::string> TargetOpcodes;
1732 std::vector<std::string> TargetVTs;
1733 bool OutputIsVariadic;
1734 unsigned NumInputRootOps;
1735 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1736 TargetOpcodes, TargetVTs,
1737 OutputIsVariadic, NumInputRootOps);
1738 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1739 PatternDecls.push_back(GeneratedDecl);
1740 PatternOpcodes.push_back(TargetOpcodes);
1741 PatternVTs.push_back(TargetVTs);
1742 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1743 NumInputRootOpsCounts.push_back(NumInputRootOps);
1744 }
1745
1746 // Factor target node emission code (emitted by EmitResultCode) into
1747 // separate functions. Uniquing and share them among all instruction
1748 // selection routines.
1749 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1750 CodeList &GeneratedCode = CodeForPatterns[i].second;
1751 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1752 std::vector<std::string> &TargetVTs = PatternVTs[i];
1753 std::set<std::string> Decls = PatternDecls[i];
1754 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1755 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1756 std::vector<std::string> AddedInits;
1757 int CodeSize = (int)GeneratedCode.size();
1758 int LastPred = -1;
1759 for (int j = CodeSize-1; j >= 0; --j) {
1760 if (LastPred == -1 && GeneratedCode[j].first == 1)
1761 LastPred = j;
1762 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1763 AddedInits.push_back(GeneratedCode[j].second);
1764 }
1765
1766 std::string CalleeCode = "(const SDValue &N";
1767 std::string CallerCode = "(N";
1768 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1769 CalleeCode += ", unsigned Opc" + utostr(j);
1770 CallerCode += ", " + TargetOpcodes[j];
1771 }
1772 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1773 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1774 CallerCode += ", " + TargetVTs[j];
1775 }
1776 for (std::set<std::string>::iterator
1777 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1778 std::string Name = *I;
1779 CalleeCode += ", SDValue &" + Name;
1780 CallerCode += ", " + Name;
1781 }
1782
1783 if (OutputIsVariadic) {
1784 CalleeCode += ", unsigned NumInputRootOps";
1785 CallerCode += ", " + utostr(NumInputRootOps);
1786 }
1787
1788 CallerCode += ");";
1789 CalleeCode += ") {\n";
1790
1791 for (std::vector<std::string>::const_reverse_iterator
1792 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1793 CalleeCode += " " + *I + "\n";
1794
1795 for (int j = LastPred+1; j < CodeSize; ++j)
1796 CalleeCode += " " + GeneratedCode[j].second + "\n";
1797 for (int j = LastPred+1; j < CodeSize; ++j)
1798 GeneratedCode.pop_back();
1799 CalleeCode += "}\n";
1800
1801 // Uniquing the emission routines.
1802 unsigned EmitFuncNum;
1803 std::map<std::string, unsigned>::iterator EFI =
1804 EmitFunctions.find(CalleeCode);
1805 if (EFI != EmitFunctions.end()) {
1806 EmitFuncNum = EFI->second;
1807 } else {
1808 EmitFuncNum = EmitFunctions.size();
1809 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1810 // Prevent emission routines from being inlined to reduce selection
1811 // routines stack frame sizes.
1812 OS << "DISABLE_INLINE ";
1813 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1814 }
1815
1816 // Replace the emission code within selection routines with calls to the
1817 // emission functions.
1818 if (GenDebug) {
1819 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"red\");"));
1820 }
1821 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1822 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1823 if (GenDebug) {
1824 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1825 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1826 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1827 GeneratedCode.push_back(std::make_pair(0, "}"));
1828 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"black\");"));
1829 }
1830 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1831 }
1832
1833 // Print function.
1834 std::string OpVTStr;
1835 if (OpVT == MVT::iPTR) {
1836 OpVTStr = "_iPTR";
1837 } else if (OpVT == MVT::iPTRAny) {
1838 OpVTStr = "_iPTRAny";
1839 } else if (OpVT == MVT::isVoid) {
1840 // Nodes with a void result actually have a first result type of either
1841 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1842 // void to this case, we handle it specially here.
1843 } else {
1844 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1845 }
1846 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1847 OpcodeVTMap.find(OpName);
1848 if (OpVTI == OpcodeVTMap.end()) {
1849 std::vector<std::string> VTSet;
1850 VTSet.push_back(OpVTStr);
1851 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1852 } else
1853 OpVTI->second.push_back(OpVTStr);
1854
1855 // We want to emit all of the matching code now. However, we want to emit
1856 // the matches in order of minimal cost. Sort the patterns so the least
1857 // cost one is at the start.
1858 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1859 PatternSortingPredicate(CGP));
1860
1861 // Scan the code to see if all of the patterns are reachable and if it is
1862 // possible that the last one might not match.
1863 bool mightNotMatch = true;
1864 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1865 CodeList &GeneratedCode = CodeForPatterns[i].second;
1866 mightNotMatch = false;
1867
1868 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1869 if (GeneratedCode[j].first == 1) { // predicate.
1870 mightNotMatch = true;
1871 break;
1872 }
1873 }
1874
1875 // If this pattern definitely matches, and if it isn't the last one, the
1876 // patterns after it CANNOT ever match. Error out.
1877 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1878 errs() << "Pattern '";
1879 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1880 errs() << "' is impossible to select!\n";
1881 exit(1);
1882 }
1883 }
1884
1885 // Loop through and reverse all of the CodeList vectors, as we will be
1886 // accessing them from their logical front, but accessing the end of a
1887 // vector is more efficient.
1888 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1889 CodeList &GeneratedCode = CodeForPatterns[i].second;
1890 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1891 }
1892
1893 // Next, reverse the list of patterns itself for the same reason.
1894 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1895
1896 OS << "SDNode *Select_" << getLegalCName(OpName)
1897 << OpVTStr << "(const SDValue &N) {\n";
1898
1899 // Emit all of the patterns now, grouped together to share code.
1900 EmitPatterns(CodeForPatterns, 2, OS);
1901
1902 // If the last pattern has predicates (which could fail) emit code to
1903 // catch the case where nothing handles a pattern.
1904 if (mightNotMatch) {
1905 OS << "\n";
1906 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1907 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1908 OpName != "ISD::INTRINSIC_VOID")
1909 OS << " CannotYetSelect(N);\n";
1910 else
1911 OS << " CannotYetSelectIntrinsic(N);\n";
1912
1913 OS << " return NULL;\n";
1914 }
1915 OS << "}\n\n";
1916 }
1917 }
1918
1919 OS << "// The main instruction selector code.\n"
1920 << "SDNode *SelectCode(SDValue N) {\n"
1921 << " MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT().SimpleTy;\n"
1922 << " switch (N.getOpcode()) {\n"
1923 << " default:\n"
1924 << " assert(!N.isMachineOpcode() && \"Node already selected!\");\n"
1925 << " break;\n"
1926 << " case ISD::EntryToken: // These nodes remain the same.\n"
1927 << " case ISD::BasicBlock:\n"
1928 << " case ISD::Register:\n"
1929 << " case ISD::HANDLENODE:\n"
1930 << " case ISD::TargetConstant:\n"
1931 << " case ISD::TargetConstantFP:\n"
1932 << " case ISD::TargetConstantPool:\n"
1933 << " case ISD::TargetFrameIndex:\n"
1934 << " case ISD::TargetExternalSymbol:\n"
1935 << " case ISD::TargetBlockAddress:\n"
1936 << " case ISD::TargetJumpTable:\n"
1937 << " case ISD::TargetGlobalTLSAddress:\n"
1938 << " case ISD::TargetGlobalAddress:\n"
1939 << " case ISD::TokenFactor:\n"
1940 << " case ISD::CopyFromReg:\n"
1941 << " case ISD::CopyToReg: {\n"
1942 << " return NULL;\n"
1943 << " }\n"
1944 << " case ISD::AssertSext:\n"
1945 << " case ISD::AssertZext: {\n"
1946 << " ReplaceUses(N, N.getOperand(0));\n"
1947 << " return NULL;\n"
1948 << " }\n"
1949 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1950 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1951 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1952
1953 // Loop over all of the case statements, emiting a call to each method we
1954 // emitted above.
1955 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1956 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1957 PBOI != E; ++PBOI) {
1958 const std::string &OpName = PBOI->first;
1959 // Potentially multiple versions of select for this opcode. One for each
1960 // ValueType of the node (or its first true operand if it doesn't produce a
1961 // result.
1962 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1963 OpcodeVTMap.find(OpName);
1964 std::vector<std::string> &OpVTs = OpVTI->second;
1965 OS << " case " << OpName << ": {\n";
1966 // If we have only one variant and it's the default, elide the
1967 // switch. Marginally faster, and makes MSVC happier.
1968 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1969 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1970 OS << " break;\n";
1971 OS << " }\n";
1972 continue;
1973 }
1974 // Keep track of whether we see a pattern that has an iPtr result.
1975 bool HasPtrPattern = false;
1976 bool HasDefaultPattern = false;
1977
1978 OS << " switch (NVT) {\n";
1979 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1980 std::string &VTStr = OpVTs[i];
1981 if (VTStr.empty()) {
1982 HasDefaultPattern = true;
1983 continue;
1984 }
1985
1986 // If this is a match on iPTR: don't emit it directly, we need special
1987 // code.
1988 if (VTStr == "_iPTR") {
1989 HasPtrPattern = true;
1990 continue;
1991 }
1992 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1993 << " return Select_" << getLegalCName(OpName)
1994 << VTStr << "(N);\n";
1995 }
1996 OS << " default:\n";
1997
1998 // If there is an iPTR result version of this pattern, emit it here.
1999 if (HasPtrPattern) {
2000 OS << " if (TLI.getPointerTy() == NVT)\n";
2001 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2002 }
2003 if (HasDefaultPattern) {
2004 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2005 }
2006 OS << " break;\n";
2007 OS << " }\n";
2008 OS << " break;\n";
2009 OS << " }\n";
2010 }
2011
2012 OS << " } // end of big switch.\n\n"
2013 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2014 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2015 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2016 << " CannotYetSelect(N);\n"
2017 << " } else {\n"
2018 << " CannotYetSelectIntrinsic(N);\n"
2019 << " }\n"
2020 << " return NULL;\n"
2021 << "}\n\n";
2022}
2023
2024void DAGISelEmitter::run(raw_ostream &OS) {
2025 EmitSourceFileHeader("DAG Instruction Selector for the " +
2026 CGP.getTargetInfo().getName() + " target", OS);
2027
2028 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2029 << "// *** instruction selector class. These functions are really "
2030 << "methods.\n\n";
2031
2032 OS << "// Include standard, target-independent definitions and methods used\n"
2033 << "// by the instruction selector.\n";
2034 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
2035
2036 EmitNodeTransforms(OS);
2037 EmitPredicateFunctions(OS);
2038
2039 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
2040 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2041 I != E; ++I) {
2042 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
2043 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
2044 DEBUG(errs() << "\n");
2045 }
2046
2047 // At this point, we have full information about the 'Patterns' we need to
2048 // parse, both implicitly from instructions as well as from explicit pattern
2049 // definitions. Emit the resultant instruction selector.
2050 EmitInstructionSelector(OS);
2051
2052}