1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
23 //===----------------------------------------------------------------------===//
24 // DAGISelEmitter Helper methods
27 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
29 static bool NodeIsComplexPattern(TreePatternNode *N) {
30 return (N->isLeaf() &&
31 dynamic_cast<DefInit*>(N->getLeafValue()) &&
32 static_cast<DefInit*>(N->getLeafValue())->getDef()->
33 isSubClassOf("ComplexPattern"));
36 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
38 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
39 CodeGenDAGPatterns &CGP) {
41 dynamic_cast<DefInit*>(N->getLeafValue()) &&
42 static_cast<DefInit*>(N->getLeafValue())->getDef()->
43 isSubClassOf("ComplexPattern")) {
44 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
50 /// getPatternSize - Return the 'size' of this pattern. We want to match large
51 /// patterns before small ones. This is used to determine the size of a
53 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
54 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
56 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR) &&
59 "Not a valid pattern node to size!");
60 unsigned Size = 3; // The node itself.
61 // If the root node is a ConstantSDNode, increases its size.
62 // e.g. (set R32:$dst, 0).
63 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
66 // FIXME: This is a hack to statically increase the priority of patterns
67 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68 // Later we can allow complexity / cost for each pattern to be (optionally)
69 // specified. To get best possible pattern match we'll need to dynamically
70 // calculate the complexity of all patterns a dag can potentially map to.
71 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
73 Size += AM->getNumOperands() * 3;
75 // If this node has some predicate function that must match, it adds to the
76 // complexity of this node.
77 if (!P->getPredicateFn().empty())
80 // Count children in the count if they are also nodes.
81 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82 TreePatternNode *Child = P->getChild(i);
83 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
84 Size += getPatternSize(Child, CGP);
85 else if (Child->isLeaf()) {
86 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
87 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
88 else if (NodeIsComplexPattern(Child))
89 Size += getPatternSize(Child, CGP);
90 else if (!Child->getPredicateFn().empty())
98 /// getResultPatternCost - Compute the number of instructions for this pattern.
99 /// This is a temporary hack. We should really include the instruction
100 /// latencies in this calculation.
101 static unsigned getResultPatternCost(TreePatternNode *P,
102 CodeGenDAGPatterns &CGP) {
103 if (P->isLeaf()) return 0;
106 Record *Op = P->getOperator();
107 if (Op->isSubClassOf("Instruction")) {
109 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
110 if (II.usesCustomDAGSchedInserter)
113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
114 Cost += getResultPatternCost(P->getChild(i), CGP);
118 /// getResultPatternCodeSize - Compute the code size of instructions for this
120 static unsigned getResultPatternSize(TreePatternNode *P,
121 CodeGenDAGPatterns &CGP) {
122 if (P->isLeaf()) return 0;
125 Record *Op = P->getOperator();
126 if (Op->isSubClassOf("Instruction")) {
127 Cost += Op->getValueAsInt("CodeSize");
129 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
130 Cost += getResultPatternSize(P->getChild(i), CGP);
134 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135 // In particular, we want to match maximal patterns first and lowest cost within
136 // a particular complexity first.
137 struct PatternSortingPredicate {
138 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139 CodeGenDAGPatterns &CGP;
141 bool operator()(const PatternToMatch *LHS,
142 const PatternToMatch *RHS) {
143 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
145 LHSSize += LHS->getAddedComplexity();
146 RHSSize += RHS->getAddedComplexity();
147 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
148 if (LHSSize < RHSSize) return false;
150 // If the patterns have equal complexity, compare generated instruction cost
151 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
153 if (LHSCost < RHSCost) return true;
154 if (LHSCost > RHSCost) return false;
156 return getResultPatternSize(LHS->getDstPattern(), CGP) <
157 getResultPatternSize(RHS->getDstPattern(), CGP);
161 /// getRegisterValueType - Look up and return the first ValueType of specified
162 /// RegisterClass record
163 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
164 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165 return RC->getValueTypeNum(0);
170 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171 /// type information from it.
172 static void RemoveAllTypes(TreePatternNode *N) {
175 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176 RemoveAllTypes(N->getChild(i));
179 /// NodeHasProperty - return true if TreePatternNode has the specified
181 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
182 CodeGenDAGPatterns &CGP) {
184 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
186 return CP->hasProperty(Property);
189 Record *Operator = N->getOperator();
190 if (!Operator->isSubClassOf("SDNode")) return false;
192 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
195 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
196 CodeGenDAGPatterns &CGP) {
197 if (NodeHasProperty(N, Property, CGP))
200 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201 TreePatternNode *Child = N->getChild(i);
202 if (PatternHasProperty(Child, Property, CGP))
209 //===----------------------------------------------------------------------===//
210 // Node Transformation emitter implementation.
212 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213 // Walk the pattern fragments, adding them to a map, which sorts them by
215 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
216 NXsByNameTy NXsByName;
218 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
220 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
222 OS << "\n// Node transformations.\n";
224 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
226 Record *SDNode = I->second.first;
227 std::string Code = I->second.second;
229 if (Code.empty()) continue; // Empty code? Skip it.
231 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
232 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
234 OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
236 if (ClassName != "SDNode")
237 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238 OS << Code << "\n}\n";
242 //===----------------------------------------------------------------------===//
243 // Predicate emitter implementation.
246 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247 OS << "\n// Predicate functions.\n";
249 // Walk the pattern fragments, adding them to a map, which sorts them by
251 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252 PFsByNameTy PFsByName;
254 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
256 PFsByName.insert(std::make_pair(I->first->getName(), *I));
259 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
261 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262 TreePattern *P = I->second.second;
264 // If there is a code init for this fragment, emit the predicate code.
265 std::string Code = PatFragRecord->getValueAsCode("Predicate");
266 if (Code.empty()) continue;
268 if (P->getOnlyTree()->isLeaf())
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *N) {\n";
272 std::string ClassName =
273 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
274 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
276 OS << "inline bool Predicate_" << PatFragRecord->getName()
277 << "(SDNode *" << C2 << ") {\n";
278 if (ClassName != "SDNode")
279 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
281 OS << Code << "\n}\n";
288 //===----------------------------------------------------------------------===//
289 // PatternCodeEmitter implementation.
291 class PatternCodeEmitter {
293 CodeGenDAGPatterns &CGP;
296 ListInit *Predicates;
299 // Instruction selector pattern.
300 TreePatternNode *Pattern;
301 // Matched instruction.
302 TreePatternNode *Instruction;
304 // Node to name mapping
305 std::map<std::string, std::string> VariableMap;
306 // Node to operator mapping
307 std::map<std::string, Record*> OperatorMap;
308 // Names of all the folded nodes which produce chains.
309 std::vector<std::pair<std::string, unsigned> > FoldedChains;
310 // Original input chain(s).
311 std::vector<std::pair<std::string, std::string> > OrigChains;
312 std::set<std::string> Duplicates;
314 /// GeneratedCode - This is the buffer that we emit code to. The first int
315 /// indicates whether this is an exit predicate (something that should be
316 /// tested, and if true, the match fails) [when 1], or normal code to emit
317 /// [when 0], or initialization code to emit [when 2].
318 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
319 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
320 /// the set of patterns for each top-level opcode.
321 std::set<std::string> &GeneratedDecl;
322 /// TargetOpcodes - The target specific opcodes used by the resulting
324 std::vector<std::string> &TargetOpcodes;
325 std::vector<std::string> &TargetVTs;
327 std::string ChainName;
332 void emitCheck(const std::string &S) {
334 GeneratedCode.push_back(std::make_pair(1, S));
336 void emitCode(const std::string &S) {
338 GeneratedCode.push_back(std::make_pair(0, S));
340 void emitInit(const std::string &S) {
342 GeneratedCode.push_back(std::make_pair(2, S));
344 void emitDecl(const std::string &S) {
345 assert(!S.empty() && "Invalid declaration");
346 GeneratedDecl.insert(S);
348 void emitOpcode(const std::string &Opc) {
349 TargetOpcodes.push_back(Opc);
352 void emitVT(const std::string &VT) {
353 TargetVTs.push_back(VT);
357 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
358 TreePatternNode *pattern, TreePatternNode *instr,
359 std::vector<std::pair<unsigned, std::string> > &gc,
360 std::set<std::string> &gd,
361 std::vector<std::string> &to,
362 std::vector<std::string> &tv)
363 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
364 GeneratedCode(gc), GeneratedDecl(gd),
365 TargetOpcodes(to), TargetVTs(tv),
366 TmpNo(0), OpcNo(0), VTNo(0) {}
368 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
369 /// if the match fails. At this point, we already know that the opcode for N
370 /// matches, and the SDNode for the result has the RootName specified name.
371 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
372 const std::string &RootName, const std::string &ChainSuffix,
374 bool isRoot = (P == NULL);
375 // Emit instruction predicates. Each predicate is just a string for now.
377 std::string PredicateCheck;
378 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
379 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
380 Record *Def = Pred->getDef();
381 if (!Def->isSubClassOf("Predicate")) {
385 assert(0 && "Unknown predicate type!");
387 if (!PredicateCheck.empty())
388 PredicateCheck += " && ";
389 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
393 emitCheck(PredicateCheck);
397 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
398 emitCheck("cast<ConstantSDNode>(" + RootName +
399 ")->getSignExtended() == " + itostr(II->getValue()));
401 } else if (!NodeIsComplexPattern(N)) {
402 assert(0 && "Cannot match this as a leaf value!");
407 // If this node has a name associated with it, capture it in VariableMap. If
408 // we already saw this in the pattern, emit code to verify dagness.
409 if (!N->getName().empty()) {
410 std::string &VarMapEntry = VariableMap[N->getName()];
411 if (VarMapEntry.empty()) {
412 VarMapEntry = RootName;
414 // If we get here, this is a second reference to a specific name. Since
415 // we already have checked that the first reference is valid, we don't
416 // have to recursively match it, just check that it's the same as the
417 // previously named thing.
418 emitCheck(VarMapEntry + " == " + RootName);
423 OperatorMap[N->getName()] = N->getOperator();
427 // Emit code to load the child nodes and match their contents recursively.
429 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
430 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
431 bool EmittedUseCheck = false;
436 // Multiple uses of actual result?
437 emitCheck(RootName + ".hasOneUse()");
438 EmittedUseCheck = true;
440 // If the immediate use can somehow reach this node through another
441 // path, then can't fold it either or it will create a cycle.
442 // e.g. In the following diagram, XX can reach ld through YY. If
443 // ld is folded into XX, then YY is both a predecessor and a successor
453 bool NeedCheck = false;
457 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
459 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
460 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
461 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
462 PInfo.getNumOperands() > 1 ||
463 PInfo.hasProperty(SDNPHasChain) ||
464 PInfo.hasProperty(SDNPInFlag) ||
465 PInfo.hasProperty(SDNPOptInFlag);
469 std::string ParentName(RootName.begin(), RootName.end()-1);
470 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
478 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
479 "IsChainCompatible(" + ChainName + ".Val, " +
480 RootName + ".Val))");
481 OrigChains.push_back(std::make_pair(ChainName, RootName));
484 ChainName = "Chain" + ChainSuffix;
485 emitInit("SDOperand " + ChainName + " = " + RootName +
490 // Don't fold any node which reads or writes a flag and has multiple uses.
491 // FIXME: We really need to separate the concepts of flag and "glue". Those
492 // real flag results, e.g. X86CMP output, can have multiple uses.
493 // FIXME: If the optional incoming flag does not exist. Then it is ok to
496 (PatternHasProperty(N, SDNPInFlag, CGP) ||
497 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
498 PatternHasProperty(N, SDNPOutFlag, CGP))) {
499 if (!EmittedUseCheck) {
500 // Multiple uses of actual result?
501 emitCheck(RootName + ".hasOneUse()");
505 // If there is a node predicate for this, emit the call.
506 if (!N->getPredicateFn().empty())
507 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
510 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
511 // a constant without a predicate fn that has more that one bit set, handle
512 // this as a special case. This is usually for targets that have special
513 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
514 // handling stuff). Using these instructions is often far more efficient
515 // than materializing the constant. Unfortunately, both the instcombiner
516 // and the dag combiner can often infer that bits are dead, and thus drop
517 // them from the mask in the dag. For example, it might turn 'AND X, 255'
518 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
521 (N->getOperator()->getName() == "and" ||
522 N->getOperator()->getName() == "or") &&
523 N->getChild(1)->isLeaf() &&
524 N->getChild(1)->getPredicateFn().empty()) {
525 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
526 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
527 emitInit("SDOperand " + RootName + "0" + " = " +
528 RootName + ".getOperand(" + utostr(0) + ");");
529 emitInit("SDOperand " + RootName + "1" + " = " +
530 RootName + ".getOperand(" + utostr(1) + ");");
532 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
533 const char *MaskPredicate = N->getOperator()->getName() == "or"
534 ? "CheckOrMask(" : "CheckAndMask(";
535 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
536 RootName + "1), " + itostr(II->getValue()) + ")");
538 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
539 ChainSuffix + utostr(0), FoundChain);
545 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
546 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
547 RootName + ".getOperand(" +utostr(OpNo) + ");");
549 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
550 ChainSuffix + utostr(OpNo), FoundChain);
553 // Handle cases when root is a complex pattern.
554 const ComplexPattern *CP;
555 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
556 std::string Fn = CP->getSelectFunc();
557 unsigned NumOps = CP->getNumOperands();
558 for (unsigned i = 0; i < NumOps; ++i) {
559 emitDecl("CPTmp" + utostr(i));
560 emitCode("SDOperand CPTmp" + utostr(i) + ";");
562 if (CP->hasProperty(SDNPHasChain)) {
563 emitDecl("CPInChain");
564 emitDecl("Chain" + ChainSuffix);
565 emitCode("SDOperand CPInChain;");
566 emitCode("SDOperand Chain" + ChainSuffix + ";");
569 std::string Code = Fn + "(" + RootName + ", " + RootName;
570 for (unsigned i = 0; i < NumOps; i++)
571 Code += ", CPTmp" + utostr(i);
572 if (CP->hasProperty(SDNPHasChain)) {
573 ChainName = "Chain" + ChainSuffix;
574 Code += ", CPInChain, Chain" + ChainSuffix;
576 emitCheck(Code + ")");
580 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
581 const std::string &RootName,
582 const std::string &ChainSuffix, bool &FoundChain) {
583 if (!Child->isLeaf()) {
584 // If it's not a leaf, recursively match.
585 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
586 emitCheck(RootName + ".getOpcode() == " +
587 CInfo.getEnumName());
588 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
589 if (NodeHasProperty(Child, SDNPHasChain, CGP))
590 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
592 // If this child has a name associated with it, capture it in VarMap. If
593 // we already saw this in the pattern, emit code to verify dagness.
594 if (!Child->getName().empty()) {
595 std::string &VarMapEntry = VariableMap[Child->getName()];
596 if (VarMapEntry.empty()) {
597 VarMapEntry = RootName;
599 // If we get here, this is a second reference to a specific name.
600 // Since we already have checked that the first reference is valid,
601 // we don't have to recursively match it, just check that it's the
602 // same as the previously named thing.
603 emitCheck(VarMapEntry + " == " + RootName);
604 Duplicates.insert(RootName);
609 // Handle leaves of various types.
610 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
611 Record *LeafRec = DI->getDef();
612 if (LeafRec->isSubClassOf("RegisterClass") ||
613 LeafRec->getName() == "ptr_rc") {
614 // Handle register references. Nothing to do here.
615 } else if (LeafRec->isSubClassOf("Register")) {
616 // Handle register references.
617 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
618 // Handle complex pattern.
619 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
620 std::string Fn = CP->getSelectFunc();
621 unsigned NumOps = CP->getNumOperands();
622 for (unsigned i = 0; i < NumOps; ++i) {
623 emitDecl("CPTmp" + utostr(i));
624 emitCode("SDOperand CPTmp" + utostr(i) + ";");
626 if (CP->hasProperty(SDNPHasChain)) {
627 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
628 FoldedChains.push_back(std::make_pair("CPInChain",
629 PInfo.getNumResults()));
630 ChainName = "Chain" + ChainSuffix;
631 emitDecl("CPInChain");
633 emitCode("SDOperand CPInChain;");
634 emitCode("SDOperand " + ChainName + ";");
637 std::string Code = Fn + "(N, ";
638 if (CP->hasProperty(SDNPHasChain)) {
639 std::string ParentName(RootName.begin(), RootName.end()-1);
640 Code += ParentName + ", ";
643 for (unsigned i = 0; i < NumOps; i++)
644 Code += ", CPTmp" + utostr(i);
645 if (CP->hasProperty(SDNPHasChain))
646 Code += ", CPInChain, Chain" + ChainSuffix;
647 emitCheck(Code + ")");
648 } else if (LeafRec->getName() == "srcvalue") {
649 // Place holder for SRCVALUE nodes. Nothing to do here.
650 } else if (LeafRec->isSubClassOf("ValueType")) {
651 // Make sure this is the specified value type.
652 emitCheck("cast<VTSDNode>(" + RootName +
653 ")->getVT() == MVT::" + LeafRec->getName());
654 } else if (LeafRec->isSubClassOf("CondCode")) {
655 // Make sure this is the specified cond code.
656 emitCheck("cast<CondCodeSDNode>(" + RootName +
657 ")->get() == ISD::" + LeafRec->getName());
663 assert(0 && "Unknown leaf type!");
666 // If there is a node predicate for this, emit the call.
667 if (!Child->getPredicateFn().empty())
668 emitCheck(Child->getPredicateFn() + "(" + RootName +
670 } else if (IntInit *II =
671 dynamic_cast<IntInit*>(Child->getLeafValue())) {
672 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
673 unsigned CTmp = TmpNo++;
674 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
675 RootName + ")->getSignExtended();");
677 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
682 assert(0 && "Unknown leaf type!");
687 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
688 /// we actually have to build a DAG!
689 std::vector<std::string>
690 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
691 bool InFlagDecled, bool ResNodeDecled,
692 bool LikeLeaf = false, bool isRoot = false) {
693 // List of arguments of getTargetNode() or SelectNodeTo().
694 std::vector<std::string> NodeOps;
695 // This is something selected from the pattern we matched.
696 if (!N->getName().empty()) {
697 const std::string &VarName = N->getName();
698 std::string Val = VariableMap[VarName];
699 bool ModifiedVal = false;
700 assert(!Val.empty() &&
701 "Variable referenced but not defined and not caught earlier!");
702 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
703 // Already selected this operand, just return the tmpval.
704 NodeOps.push_back(Val);
708 const ComplexPattern *CP;
709 unsigned ResNo = TmpNo++;
710 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
711 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
712 std::string CastType;
713 std::string TmpVar = "Tmp" + utostr(ResNo);
714 switch (N->getTypeNum(0)) {
716 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
717 << " type as an immediate constant. Aborting\n";
719 case MVT::i1: CastType = "bool"; break;
720 case MVT::i8: CastType = "unsigned char"; break;
721 case MVT::i16: CastType = "unsigned short"; break;
722 case MVT::i32: CastType = "unsigned"; break;
723 case MVT::i64: CastType = "uint64_t"; break;
725 emitCode("SDOperand " + TmpVar +
726 " = CurDAG->getTargetConstant(((" + CastType +
727 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
728 getEnumName(N->getTypeNum(0)) + ");");
729 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
730 // value if used multiple times by this pattern result.
733 NodeOps.push_back(Val);
734 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
735 Record *Op = OperatorMap[N->getName()];
736 // Transform ExternalSymbol to TargetExternalSymbol
737 if (Op && Op->getName() == "externalsym") {
738 std::string TmpVar = "Tmp"+utostr(ResNo);
739 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
740 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
741 Val + ")->getSymbol(), " +
742 getEnumName(N->getTypeNum(0)) + ");");
743 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
744 // this value if used multiple times by this pattern result.
748 NodeOps.push_back(Val);
749 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
750 || N->getOperator()->getName() == "tglobaltlsaddr")) {
751 Record *Op = OperatorMap[N->getName()];
752 // Transform GlobalAddress to TargetGlobalAddress
753 if (Op && (Op->getName() == "globaladdr" ||
754 Op->getName() == "globaltlsaddr")) {
755 std::string TmpVar = "Tmp" + utostr(ResNo);
756 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
757 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
758 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
760 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
761 // this value if used multiple times by this pattern result.
765 NodeOps.push_back(Val);
766 } else if (!N->isLeaf()
767 && (N->getOperator()->getName() == "texternalsym"
768 || N->getOperator()->getName() == "tconstpool")) {
769 // Do not rewrite the variable name, since we don't generate a new
771 NodeOps.push_back(Val);
772 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
773 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
774 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
775 NodeOps.push_back("CPTmp" + utostr(i));
778 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
779 // node even if it isn't one. Don't select it.
781 emitCode("AddToISelQueue(" + Val + ");");
782 if (isRoot && N->isLeaf()) {
783 emitCode("ReplaceUses(N, " + Val + ");");
784 emitCode("return NULL;");
787 NodeOps.push_back(Val);
791 VariableMap[VarName] = Val;
796 // If this is an explicit register reference, handle it.
797 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
798 unsigned ResNo = TmpNo++;
799 if (DI->getDef()->isSubClassOf("Register")) {
800 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
801 getQualifiedName(DI->getDef()) + ", " +
802 getEnumName(N->getTypeNum(0)) + ");");
803 NodeOps.push_back("Tmp" + utostr(ResNo));
805 } else if (DI->getDef()->getName() == "zero_reg") {
806 emitCode("SDOperand Tmp" + utostr(ResNo) +
807 " = CurDAG->getRegister(0, " +
808 getEnumName(N->getTypeNum(0)) + ");");
809 NodeOps.push_back("Tmp" + utostr(ResNo));
812 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
813 unsigned ResNo = TmpNo++;
814 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
815 emitCode("SDOperand Tmp" + utostr(ResNo) +
816 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
817 ", " + getEnumName(N->getTypeNum(0)) + ");");
818 NodeOps.push_back("Tmp" + utostr(ResNo));
825 assert(0 && "Unknown leaf type!");
829 Record *Op = N->getOperator();
830 if (Op->isSubClassOf("Instruction")) {
831 const CodeGenTarget &CGT = CGP.getTargetInfo();
832 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
833 const DAGInstruction &Inst = CGP.getInstruction(Op);
834 const TreePattern *InstPat = Inst.getPattern();
835 // FIXME: Assume actual pattern comes before "implicit".
836 TreePatternNode *InstPatNode =
837 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
838 : (InstPat ? InstPat->getTree(0) : NULL);
839 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
840 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
842 bool HasVarOps = isRoot && II.isVariadic;
843 // FIXME: fix how we deal with physical register operands.
844 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
845 bool HasImpResults = isRoot && DstRegs.size() > 0;
846 bool NodeHasOptInFlag = isRoot &&
847 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
848 bool NodeHasInFlag = isRoot &&
849 PatternHasProperty(Pattern, SDNPInFlag, CGP);
850 bool NodeHasOutFlag = isRoot &&
851 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
852 bool NodeHasChain = InstPatNode &&
853 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
854 bool InputHasChain = isRoot &&
855 NodeHasProperty(Pattern, SDNPHasChain, CGP);
856 unsigned NumResults = Inst.getNumResults();
857 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
859 if (NodeHasOptInFlag) {
860 emitCode("bool HasInFlag = "
861 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
864 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
866 // How many results is this pattern expected to produce?
867 unsigned NumPatResults = 0;
868 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
869 MVT::ValueType VT = Pattern->getTypeNum(i);
870 if (VT != MVT::isVoid && VT != MVT::Flag)
874 if (OrigChains.size() > 0) {
875 // The original input chain is being ignored. If it is not just
876 // pointing to the op that's being folded, we should create a
877 // TokenFactor with it and the chain of the folded op as the new chain.
878 // We could potentially be doing multiple levels of folding, in that
879 // case, the TokenFactor can have more operands.
880 emitCode("SmallVector<SDOperand, 8> InChains;");
881 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
882 emitCode("if (" + OrigChains[i].first + ".Val != " +
883 OrigChains[i].second + ".Val) {");
884 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
885 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
888 emitCode("AddToISelQueue(" + ChainName + ");");
889 emitCode("InChains.push_back(" + ChainName + ");");
890 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
891 "&InChains[0], InChains.size());");
894 // Loop over all of the operands of the instruction pattern, emitting code
895 // to fill them all in. The node 'N' usually has number children equal to
896 // the number of input operands of the instruction. However, in cases
897 // where there are predicate operands for an instruction, we need to fill
898 // in the 'execute always' values. Match up the node operands to the
899 // instruction operands to do this.
900 std::vector<std::string> AllOps;
901 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
902 for (unsigned ChildNo = 0, InstOpNo = NumResults;
903 InstOpNo != II.OperandList.size(); ++InstOpNo) {
904 std::vector<std::string> Ops;
906 // If this is a normal operand or a predicate operand without
907 // 'execute always', emit it.
908 Record *OperandNode = II.OperandList[InstOpNo].Rec;
909 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
910 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
911 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
912 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
913 InFlagDecled, ResNodeDecled);
914 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
917 // Otherwise, this is a predicate or optional def operand, emit the
918 // 'default ops' operands.
919 const DAGDefaultOperand &DefaultOp =
920 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
921 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
922 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
923 InFlagDecled, ResNodeDecled);
924 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
925 NumEAInputs += Ops.size();
930 // Emit all the chain and CopyToReg stuff.
931 bool ChainEmitted = NodeHasChain;
933 emitCode("AddToISelQueue(" + ChainName + ");");
934 if (NodeHasInFlag || HasImpInputs)
935 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
936 InFlagDecled, ResNodeDecled, true);
937 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
939 emitCode("SDOperand InFlag(0, 0);");
942 if (NodeHasOptInFlag) {
943 emitCode("if (HasInFlag) {");
944 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
945 emitCode(" AddToISelQueue(InFlag);");
950 unsigned ResNo = TmpNo++;
951 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
952 NodeHasOptInFlag || HasImpResults) {
955 std::string NodeName;
957 NodeName = "Tmp" + utostr(ResNo);
958 Code2 = "SDOperand " + NodeName + "(";
960 NodeName = "ResNode";
961 if (!ResNodeDecled) {
962 Code2 = "SDNode *" + NodeName + " = ";
963 ResNodeDecled = true;
965 Code2 = NodeName + " = ";
968 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
969 unsigned OpsNo = OpcNo;
970 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
972 // Output order: results, chain, flags
974 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
975 Code += ", VT" + utostr(VTNo);
976 emitVT(getEnumName(N->getTypeNum(0)));
978 // Add types for implicit results in physical registers, scheduler will
979 // care of adding copyfromreg nodes.
980 for (unsigned i = 0; i < NumDstRegs; i++) {
981 Record *RR = DstRegs[i];
982 if (RR->isSubClassOf("Register")) {
983 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
984 Code += ", " + getEnumName(RVT);
988 Code += ", MVT::Other";
990 Code += ", MVT::Flag";
992 // Figure out how many fixed inputs the node has. This is important to
993 // know which inputs are the variable ones if present.
994 unsigned NumInputs = AllOps.size();
995 NumInputs += NodeHasChain;
999 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1000 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1005 // Figure out whether any operands at the end of the op list are not
1006 // part of the variable section.
1007 std::string EndAdjust;
1008 if (NodeHasInFlag || HasImpInputs)
1009 EndAdjust = "-1"; // Always has one flag.
1010 else if (NodeHasOptInFlag)
1011 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1013 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1014 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1016 emitCode(" AddToISelQueue(N.getOperand(i));");
1017 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1023 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1025 AllOps.push_back(ChainName);
1029 if (NodeHasInFlag || HasImpInputs)
1030 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1031 else if (NodeHasOptInFlag) {
1032 emitCode("if (HasInFlag)");
1033 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1035 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1037 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1038 AllOps.push_back("InFlag");
1040 unsigned NumOps = AllOps.size();
1042 if (!NodeHasOptInFlag && NumOps < 4) {
1043 for (unsigned i = 0; i != NumOps; ++i)
1044 Code += ", " + AllOps[i];
1046 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1047 for (unsigned i = 0; i != NumOps; ++i) {
1048 OpsCode += AllOps[i];
1052 emitCode(OpsCode + " };");
1053 Code += ", Ops" + utostr(OpsNo) + ", ";
1054 if (NodeHasOptInFlag) {
1055 Code += "HasInFlag ? ";
1056 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1058 Code += utostr(NumOps);
1064 emitCode(Code2 + Code + ");");
1067 // Remember which op produces the chain.
1069 emitCode(ChainName + " = SDOperand(" + NodeName +
1070 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
1072 emitCode(ChainName + " = SDOperand(" + NodeName +
1073 ", " + utostr(NumResults+NumDstRegs) + ");");
1076 NodeOps.push_back("Tmp" + utostr(ResNo));
1080 bool NeedReplace = false;
1081 if (NodeHasOutFlag) {
1082 if (!InFlagDecled) {
1083 emitCode("SDOperand InFlag(ResNode, " +
1084 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1085 InFlagDecled = true;
1087 emitCode("InFlag = SDOperand(ResNode, " +
1088 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1091 if (FoldedChains.size() > 0) {
1093 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1094 emitCode("ReplaceUses(SDOperand(" +
1095 FoldedChains[j].first + ".Val, " +
1096 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1097 utostr(NumResults+NumDstRegs) + "));");
1101 if (NodeHasOutFlag) {
1102 emitCode("ReplaceUses(SDOperand(N.Val, " +
1103 utostr(NumPatResults + (unsigned)InputHasChain)
1108 if (NeedReplace && InputHasChain)
1109 emitCode("ReplaceUses(SDOperand(N.Val, " +
1110 utostr(NumPatResults) + "), SDOperand(" + ChainName
1111 + ".Val, " + ChainName + ".ResNo" + "));");
1113 // User does not expect the instruction would produce a chain!
1114 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1116 } else if (InputHasChain && !NodeHasChain) {
1117 // One of the inner node produces a chain.
1119 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1120 "), SDOperand(ResNode, N.ResNo-1));");
1121 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1122 "), " + ChainName + ");");
1125 emitCode("return ResNode;");
1127 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1129 if (N->getTypeNum(0) != MVT::isVoid)
1130 Code += ", VT" + utostr(VTNo);
1132 Code += ", MVT::Flag";
1134 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1135 AllOps.push_back("InFlag");
1137 unsigned NumOps = AllOps.size();
1139 if (!NodeHasOptInFlag && NumOps < 4) {
1140 for (unsigned i = 0; i != NumOps; ++i)
1141 Code += ", " + AllOps[i];
1143 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1144 for (unsigned i = 0; i != NumOps; ++i) {
1145 OpsCode += AllOps[i];
1149 emitCode(OpsCode + " };");
1150 Code += ", Ops" + utostr(OpcNo) + ", ";
1151 Code += utostr(NumOps);
1154 emitCode(Code + ");");
1155 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1156 if (N->getTypeNum(0) != MVT::isVoid)
1157 emitVT(getEnumName(N->getTypeNum(0)));
1161 } else if (Op->isSubClassOf("SDNodeXForm")) {
1162 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1163 // PatLeaf node - the operand may or may not be a leaf node. But it should
1165 std::vector<std::string> Ops =
1166 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1167 ResNodeDecled, true);
1168 unsigned ResNo = TmpNo++;
1169 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1170 + "(" + Ops.back() + ".Val);");
1171 NodeOps.push_back("Tmp" + utostr(ResNo));
1173 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1178 throw std::string("Unknown node in result pattern!");
1182 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1183 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1184 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1185 /// for, this returns true otherwise false if Pat has all types.
1186 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1187 const std::string &Prefix, bool isRoot = false) {
1189 if (Pat->getExtTypes() != Other->getExtTypes()) {
1190 // Move a type over from 'other' to 'pat'.
1191 Pat->setTypes(Other->getExtTypes());
1192 // The top level node type is checked outside of the select function.
1194 emitCheck(Prefix + ".Val->getValueType(0) == " +
1195 getName(Pat->getTypeNum(0)));
1200 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1201 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1202 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1203 Prefix + utostr(OpNo)))
1209 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1211 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1212 bool &ChainEmitted, bool &InFlagDecled,
1213 bool &ResNodeDecled, bool isRoot = false) {
1214 const CodeGenTarget &T = CGP.getTargetInfo();
1216 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1217 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1218 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1219 TreePatternNode *Child = N->getChild(i);
1220 if (!Child->isLeaf()) {
1221 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1222 InFlagDecled, ResNodeDecled);
1224 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1225 if (!Child->getName().empty()) {
1226 std::string Name = RootName + utostr(OpNo);
1227 if (Duplicates.find(Name) != Duplicates.end())
1228 // A duplicate! Do not emit a copy for this node.
1232 Record *RR = DI->getDef();
1233 if (RR->isSubClassOf("Register")) {
1234 MVT::ValueType RVT = getRegisterValueType(RR, T);
1235 if (RVT == MVT::Flag) {
1236 if (!InFlagDecled) {
1237 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1238 InFlagDecled = true;
1240 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1241 emitCode("AddToISelQueue(InFlag);");
1243 if (!ChainEmitted) {
1244 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1245 ChainName = "Chain";
1246 ChainEmitted = true;
1248 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1249 if (!InFlagDecled) {
1250 emitCode("SDOperand InFlag(0, 0);");
1251 InFlagDecled = true;
1253 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1254 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1255 ", " + getQualifiedName(RR) +
1256 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1257 ResNodeDecled = true;
1258 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1259 emitCode("InFlag = SDOperand(ResNode, 1);");
1267 if (!InFlagDecled) {
1268 emitCode("SDOperand InFlag = " + RootName +
1269 ".getOperand(" + utostr(OpNo) + ");");
1270 InFlagDecled = true;
1272 emitCode("InFlag = " + RootName +
1273 ".getOperand(" + utostr(OpNo) + ");");
1274 emitCode("AddToISelQueue(InFlag);");
1279 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1280 /// stream to match the pattern, and generate the code for the match if it
1281 /// succeeds. Returns true if the pattern is not guaranteed to match.
1282 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1283 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1284 std::set<std::string> &GeneratedDecl,
1285 std::vector<std::string> &TargetOpcodes,
1286 std::vector<std::string> &TargetVTs) {
1287 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1288 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1289 GeneratedCode, GeneratedDecl,
1290 TargetOpcodes, TargetVTs);
1292 // Emit the matcher, capturing named arguments in VariableMap.
1293 bool FoundChain = false;
1294 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1296 // TP - Get *SOME* tree pattern, we don't care which.
1297 TreePattern &TP = *CGP.pf_begin()->second;
1299 // At this point, we know that we structurally match the pattern, but the
1300 // types of the nodes may not match. Figure out the fewest number of type
1301 // comparisons we need to emit. For example, if there is only one integer
1302 // type supported by a target, there should be no type comparisons at all for
1303 // integer patterns!
1305 // To figure out the fewest number of type checks needed, clone the pattern,
1306 // remove the types, then perform type inference on the pattern as a whole.
1307 // If there are unresolved types, emit an explicit check for those types,
1308 // apply the type to the tree, then rerun type inference. Iterate until all
1309 // types are resolved.
1311 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1312 RemoveAllTypes(Pat);
1315 // Resolve/propagate as many types as possible.
1317 bool MadeChange = true;
1319 MadeChange = Pat->ApplyTypeConstraints(TP,
1320 true/*Ignore reg constraints*/);
1322 assert(0 && "Error: could not find consistent types for something we"
1323 " already decided was ok!");
1327 // Insert a check for an unresolved type and add it to the tree. If we find
1328 // an unresolved type to add a check for, this returns true and we iterate,
1329 // otherwise we are done.
1330 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1332 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1333 false, false, false, true);
1337 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1338 /// a line causes any of them to be empty, remove them and return true when
1340 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1341 std::vector<std::pair<unsigned, std::string> > > >
1343 bool ErasedPatterns = false;
1344 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1345 Patterns[i].second.pop_back();
1346 if (Patterns[i].second.empty()) {
1347 Patterns.erase(Patterns.begin()+i);
1349 ErasedPatterns = true;
1352 return ErasedPatterns;
1355 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1356 /// code together between the patterns.
1357 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1358 std::vector<std::pair<unsigned, std::string> > > >
1359 &Patterns, unsigned Indent,
1361 typedef std::pair<unsigned, std::string> CodeLine;
1362 typedef std::vector<CodeLine> CodeList;
1363 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1365 if (Patterns.empty()) return;
1367 // Figure out how many patterns share the next code line. Explicitly copy
1368 // FirstCodeLine so that we don't invalidate a reference when changing
1370 const CodeLine FirstCodeLine = Patterns.back().second.back();
1371 unsigned LastMatch = Patterns.size()-1;
1372 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1375 // If not all patterns share this line, split the list into two pieces. The
1376 // first chunk will use this line, the second chunk won't.
1377 if (LastMatch != 0) {
1378 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1379 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1381 // FIXME: Emit braces?
1382 if (Shared.size() == 1) {
1383 const PatternToMatch &Pattern = *Shared.back().first;
1384 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1385 Pattern.getSrcPattern()->print(OS);
1386 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1387 Pattern.getDstPattern()->print(OS);
1389 unsigned AddedComplexity = Pattern.getAddedComplexity();
1390 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1391 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1393 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1395 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1397 if (FirstCodeLine.first != 1) {
1398 OS << std::string(Indent, ' ') << "{\n";
1401 EmitPatterns(Shared, Indent, OS);
1402 if (FirstCodeLine.first != 1) {
1404 OS << std::string(Indent, ' ') << "}\n";
1407 if (Other.size() == 1) {
1408 const PatternToMatch &Pattern = *Other.back().first;
1409 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1410 Pattern.getSrcPattern()->print(OS);
1411 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1412 Pattern.getDstPattern()->print(OS);
1414 unsigned AddedComplexity = Pattern.getAddedComplexity();
1415 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1416 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1418 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1420 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1422 EmitPatterns(Other, Indent, OS);
1426 // Remove this code from all of the patterns that share it.
1427 bool ErasedPatterns = EraseCodeLine(Patterns);
1429 bool isPredicate = FirstCodeLine.first == 1;
1431 // Otherwise, every pattern in the list has this line. Emit it.
1434 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1436 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1438 // If the next code line is another predicate, and if all of the pattern
1439 // in this group share the same next line, emit it inline now. Do this
1440 // until we run out of common predicates.
1441 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1442 // Check that all of fhe patterns in Patterns end with the same predicate.
1443 bool AllEndWithSamePredicate = true;
1444 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1445 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1446 AllEndWithSamePredicate = false;
1449 // If all of the predicates aren't the same, we can't share them.
1450 if (!AllEndWithSamePredicate) break;
1452 // Otherwise we can. Emit it shared now.
1453 OS << " &&\n" << std::string(Indent+4, ' ')
1454 << Patterns.back().second.back().second;
1455 ErasedPatterns = EraseCodeLine(Patterns);
1462 EmitPatterns(Patterns, Indent, OS);
1465 OS << std::string(Indent-2, ' ') << "}\n";
1468 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
1469 return CGP.getSDNodeInfo(Op).getEnumName();
1472 static std::string getLegalCName(std::string OpName) {
1473 std::string::size_type pos = OpName.find("::");
1474 if (pos != std::string::npos)
1475 OpName.replace(pos, 2, "_");
1479 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1480 const CodeGenTarget &Target = CGP.getTargetInfo();
1482 // Get the namespace to insert instructions into. Make sure not to pick up
1483 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1484 // instruction or something.
1486 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1487 e = Target.inst_end(); i != e; ++i) {
1488 InstNS = i->second.Namespace;
1489 if (InstNS != "TargetInstrInfo")
1493 if (!InstNS.empty()) InstNS += "::";
1495 // Group the patterns by their top-level opcodes.
1496 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1497 // All unique target node emission functions.
1498 std::map<std::string, unsigned> EmitFunctions;
1499 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1500 E = CGP.ptm_end(); I != E; ++I) {
1501 const PatternToMatch &Pattern = *I;
1503 TreePatternNode *Node = Pattern.getSrcPattern();
1504 if (!Node->isLeaf()) {
1505 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1506 push_back(&Pattern);
1508 const ComplexPattern *CP;
1509 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1510 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1511 push_back(&Pattern);
1512 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1513 std::vector<Record*> OpNodes = CP->getRootNodes();
1514 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1515 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1516 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1520 cerr << "Unrecognized opcode '";
1522 cerr << "' on tree pattern '";
1523 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1529 // For each opcode, there might be multiple select functions, one per
1530 // ValueType of the node (or its first operand if it doesn't produce a
1531 // non-chain result.
1532 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1534 // Emit one Select_* method for each top-level opcode. We do this instead of
1535 // emitting one giant switch statement to support compilers where this will
1536 // result in the recursive functions taking less stack space.
1537 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1538 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1539 PBOI != E; ++PBOI) {
1540 const std::string &OpName = PBOI->first;
1541 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1542 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1544 // We want to emit all of the matching code now. However, we want to emit
1545 // the matches in order of minimal cost. Sort the patterns so the least
1546 // cost one is at the start.
1547 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1548 PatternSortingPredicate(CGP));
1550 // Split them into groups by type.
1551 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1552 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1553 const PatternToMatch *Pat = PatternsOfOp[i];
1554 TreePatternNode *SrcPat = Pat->getSrcPattern();
1555 MVT::ValueType VT = SrcPat->getTypeNum(0);
1556 std::map<MVT::ValueType,
1557 std::vector<const PatternToMatch*> >::iterator TI =
1558 PatternsByType.find(VT);
1559 if (TI != PatternsByType.end())
1560 TI->second.push_back(Pat);
1562 std::vector<const PatternToMatch*> PVec;
1563 PVec.push_back(Pat);
1564 PatternsByType.insert(std::make_pair(VT, PVec));
1568 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1569 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1571 MVT::ValueType OpVT = II->first;
1572 std::vector<const PatternToMatch*> &Patterns = II->second;
1573 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1574 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1576 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1577 std::vector<std::vector<std::string> > PatternOpcodes;
1578 std::vector<std::vector<std::string> > PatternVTs;
1579 std::vector<std::set<std::string> > PatternDecls;
1580 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1581 CodeList GeneratedCode;
1582 std::set<std::string> GeneratedDecl;
1583 std::vector<std::string> TargetOpcodes;
1584 std::vector<std::string> TargetVTs;
1585 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1586 TargetOpcodes, TargetVTs);
1587 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1588 PatternDecls.push_back(GeneratedDecl);
1589 PatternOpcodes.push_back(TargetOpcodes);
1590 PatternVTs.push_back(TargetVTs);
1593 // Scan the code to see if all of the patterns are reachable and if it is
1594 // possible that the last one might not match.
1595 bool mightNotMatch = true;
1596 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1597 CodeList &GeneratedCode = CodeForPatterns[i].second;
1598 mightNotMatch = false;
1600 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1601 if (GeneratedCode[j].first == 1) { // predicate.
1602 mightNotMatch = true;
1607 // If this pattern definitely matches, and if it isn't the last one, the
1608 // patterns after it CANNOT ever match. Error out.
1609 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1610 cerr << "Pattern '";
1611 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1612 cerr << "' is impossible to select!\n";
1617 // Factor target node emission code (emitted by EmitResultCode) into
1618 // separate functions. Uniquing and share them among all instruction
1619 // selection routines.
1620 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1621 CodeList &GeneratedCode = CodeForPatterns[i].second;
1622 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1623 std::vector<std::string> &TargetVTs = PatternVTs[i];
1624 std::set<std::string> Decls = PatternDecls[i];
1625 std::vector<std::string> AddedInits;
1626 int CodeSize = (int)GeneratedCode.size();
1628 for (int j = CodeSize-1; j >= 0; --j) {
1629 if (LastPred == -1 && GeneratedCode[j].first == 1)
1631 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1632 AddedInits.push_back(GeneratedCode[j].second);
1635 std::string CalleeCode = "(const SDOperand &N";
1636 std::string CallerCode = "(N";
1637 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1638 CalleeCode += ", unsigned Opc" + utostr(j);
1639 CallerCode += ", " + TargetOpcodes[j];
1641 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1642 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1643 CallerCode += ", " + TargetVTs[j];
1645 for (std::set<std::string>::iterator
1646 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1647 std::string Name = *I;
1648 CalleeCode += ", SDOperand &" + Name;
1649 CallerCode += ", " + Name;
1653 // Prevent emission routines from being inlined to reduce selection
1654 // routines stack frame sizes.
1655 CalleeCode += "DISABLE_INLINE ";
1656 CalleeCode += "{\n";
1658 for (std::vector<std::string>::const_reverse_iterator
1659 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1660 CalleeCode += " " + *I + "\n";
1662 for (int j = LastPred+1; j < CodeSize; ++j)
1663 CalleeCode += " " + GeneratedCode[j].second + "\n";
1664 for (int j = LastPred+1; j < CodeSize; ++j)
1665 GeneratedCode.pop_back();
1666 CalleeCode += "}\n";
1668 // Uniquing the emission routines.
1669 unsigned EmitFuncNum;
1670 std::map<std::string, unsigned>::iterator EFI =
1671 EmitFunctions.find(CalleeCode);
1672 if (EFI != EmitFunctions.end()) {
1673 EmitFuncNum = EFI->second;
1675 EmitFuncNum = EmitFunctions.size();
1676 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1677 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1680 // Replace the emission code within selection routines with calls to the
1681 // emission functions.
1682 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1683 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1687 std::string OpVTStr;
1688 if (OpVT == MVT::iPTR) {
1690 } else if (OpVT == MVT::isVoid) {
1691 // Nodes with a void result actually have a first result type of either
1692 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1693 // void to this case, we handle it specially here.
1695 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1697 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1698 OpcodeVTMap.find(OpName);
1699 if (OpVTI == OpcodeVTMap.end()) {
1700 std::vector<std::string> VTSet;
1701 VTSet.push_back(OpVTStr);
1702 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1704 OpVTI->second.push_back(OpVTStr);
1706 OS << "SDNode *Select_" << getLegalCName(OpName)
1707 << OpVTStr << "(const SDOperand &N) {\n";
1709 // Loop through and reverse all of the CodeList vectors, as we will be
1710 // accessing them from their logical front, but accessing the end of a
1711 // vector is more efficient.
1712 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1713 CodeList &GeneratedCode = CodeForPatterns[i].second;
1714 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1717 // Next, reverse the list of patterns itself for the same reason.
1718 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1720 // Emit all of the patterns now, grouped together to share code.
1721 EmitPatterns(CodeForPatterns, 2, OS);
1723 // If the last pattern has predicates (which could fail) emit code to
1724 // catch the case where nothing handles a pattern.
1725 if (mightNotMatch) {
1726 OS << " cerr << \"Cannot yet select: \";\n";
1727 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1728 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1729 OpName != "ISD::INTRINSIC_VOID") {
1730 OS << " N.Val->dump(CurDAG);\n";
1732 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1733 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1734 << " cerr << \"intrinsic %\"<< "
1735 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1737 OS << " cerr << '\\n';\n"
1739 << " return NULL;\n";
1745 // Emit boilerplate.
1746 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1747 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1748 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1750 << " // Ensure that the asm operands are themselves selected.\n"
1751 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1752 << " AddToISelQueue(Ops[j]);\n\n"
1754 << " std::vector<MVT::ValueType> VTs;\n"
1755 << " VTs.push_back(MVT::Other);\n"
1756 << " VTs.push_back(MVT::Flag);\n"
1757 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1759 << " return New.Val;\n"
1762 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1763 << " SDOperand Chain = N.getOperand(0);\n"
1764 << " SDOperand N1 = N.getOperand(1);\n"
1765 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1766 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1767 << " AddToISelQueue(Chain);\n"
1768 << " SDOperand Ops[] = { Tmp, Chain };\n"
1769 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1770 << " MVT::Other, Ops, 2);\n"
1773 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1774 << " SDOperand N0 = N.getOperand(0);\n"
1775 << " SDOperand N1 = N.getOperand(1);\n"
1776 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1777 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1778 << " AddToISelQueue(N0);\n"
1779 << " SDOperand Ops[] = { N0, Tmp };\n"
1780 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1781 << " N.getValueType(), Ops, 2);\n"
1784 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1785 << " SDOperand N0 = N.getOperand(0);\n"
1786 << " SDOperand N1 = N.getOperand(1);\n"
1787 << " SDOperand N2 = N.getOperand(2);\n"
1788 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1789 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1790 << " AddToISelQueue(N1);\n"
1791 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
1792 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
1793 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1794 << " N.getValueType(), Ops+1, 2);\n"
1796 << " AddToISelQueue(N0);\n"
1797 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1798 << " N.getValueType(), Ops, 3);\n"
1802 OS << "// The main instruction selector code.\n"
1803 << "SDNode *SelectCode(SDOperand N) {\n"
1804 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1805 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1806 << "INSTRUCTION_LIST_END)) {\n"
1807 << " return NULL; // Already selected.\n"
1809 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1810 << " switch (N.getOpcode()) {\n"
1811 << " default: break;\n"
1812 << " case ISD::EntryToken: // These leaves remain the same.\n"
1813 << " case ISD::BasicBlock:\n"
1814 << " case ISD::Register:\n"
1815 << " case ISD::HANDLENODE:\n"
1816 << " case ISD::TargetConstant:\n"
1817 << " case ISD::TargetConstantPool:\n"
1818 << " case ISD::TargetFrameIndex:\n"
1819 << " case ISD::TargetExternalSymbol:\n"
1820 << " case ISD::TargetJumpTable:\n"
1821 << " case ISD::TargetGlobalTLSAddress:\n"
1822 << " case ISD::TargetGlobalAddress: {\n"
1823 << " return NULL;\n"
1825 << " case ISD::AssertSext:\n"
1826 << " case ISD::AssertZext: {\n"
1827 << " AddToISelQueue(N.getOperand(0));\n"
1828 << " ReplaceUses(N, N.getOperand(0));\n"
1829 << " return NULL;\n"
1831 << " case ISD::TokenFactor:\n"
1832 << " case ISD::CopyFromReg:\n"
1833 << " case ISD::CopyToReg: {\n"
1834 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1835 << " AddToISelQueue(N.getOperand(i));\n"
1836 << " return NULL;\n"
1838 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1839 << " case ISD::LABEL: return Select_LABEL(N);\n"
1840 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1841 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
1844 // Loop over all of the case statements, emiting a call to each method we
1846 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1847 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1848 PBOI != E; ++PBOI) {
1849 const std::string &OpName = PBOI->first;
1850 // Potentially multiple versions of select for this opcode. One for each
1851 // ValueType of the node (or its first true operand if it doesn't produce a
1853 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1854 OpcodeVTMap.find(OpName);
1855 std::vector<std::string> &OpVTs = OpVTI->second;
1856 OS << " case " << OpName << ": {\n";
1857 // Keep track of whether we see a pattern that has an iPtr result.
1858 bool HasPtrPattern = false;
1859 bool HasDefaultPattern = false;
1861 OS << " switch (NVT) {\n";
1862 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1863 std::string &VTStr = OpVTs[i];
1864 if (VTStr.empty()) {
1865 HasDefaultPattern = true;
1869 // If this is a match on iPTR: don't emit it directly, we need special
1871 if (VTStr == "_iPTR") {
1872 HasPtrPattern = true;
1875 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1876 << " return Select_" << getLegalCName(OpName)
1877 << VTStr << "(N);\n";
1879 OS << " default:\n";
1881 // If there is an iPTR result version of this pattern, emit it here.
1882 if (HasPtrPattern) {
1883 OS << " if (NVT == TLI.getPointerTy())\n";
1884 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1886 if (HasDefaultPattern) {
1887 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1895 OS << " } // end of big switch.\n\n"
1896 << " cerr << \"Cannot yet select: \";\n"
1897 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1898 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1899 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1900 << " N.Val->dump(CurDAG);\n"
1902 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1903 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1904 << " cerr << \"intrinsic %\"<< "
1905 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1907 << " cerr << '\\n';\n"
1909 << " return NULL;\n"
1913 void DAGISelEmitter::run(std::ostream &OS) {
1914 EmitSourceFileHeader("DAG Instruction Selector for the " +
1915 CGP.getTargetInfo().getName() + " target", OS);
1917 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1918 << "// *** instruction selector class. These functions are really "
1921 OS << "#include \"llvm/Support/Compiler.h\"\n";
1923 OS << "// Instruction selector priority queue:\n"
1924 << "std::vector<SDNode*> ISelQueue;\n";
1925 OS << "/// Keep track of nodes which have already been added to queue.\n"
1926 << "unsigned char *ISelQueued;\n";
1927 OS << "/// Keep track of nodes which have already been selected.\n"
1928 << "unsigned char *ISelSelected;\n";
1929 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1930 << "std::vector<SDNode*> ISelKilled;\n\n";
1932 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1933 OS << "/// not reach Op.\n";
1934 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1935 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1936 OS << " return true;\n";
1937 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1938 OS << " return false;\n";
1939 OS << " else if (Chain->getNumOperands() > 0) {\n";
1940 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1941 OS << " if (C0.getValueType() == MVT::Other)\n";
1942 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1944 OS << " return true;\n";
1947 OS << "/// Sorting functions for the selection queue.\n"
1948 << "struct isel_sort : public std::binary_function"
1949 << "<SDNode*, SDNode*, bool> {\n"
1950 << " bool operator()(const SDNode* left, const SDNode* right) "
1952 << " return (left->getNodeId() > right->getNodeId());\n"
1956 OS << "inline void setQueued(int Id) {\n";
1957 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1959 OS << "inline bool isQueued(int Id) {\n";
1960 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1962 OS << "inline void setSelected(int Id) {\n";
1963 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1965 OS << "inline bool isSelected(int Id) {\n";
1966 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1969 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
1970 OS << " int Id = N.Val->getNodeId();\n";
1971 OS << " if (Id != -1 && !isQueued(Id)) {\n";
1972 OS << " ISelQueue.push_back(N.Val);\n";
1973 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1974 OS << " setQueued(Id);\n";
1978 OS << "inline void RemoveKilled() {\n";
1979 OS << " unsigned NumKilled = ISelKilled.size();\n";
1980 OS << " if (NumKilled) {\n";
1981 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
1982 OS << " SDNode *Temp = ISelKilled[i];\n";
1983 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
1984 << "Temp), ISelQueue.end());\n";
1986 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1987 OS << " ISelKilled.clear();\n";
1991 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
1992 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
1993 OS << " setSelected(F.Val->getNodeId());\n";
1994 OS << " RemoveKilled();\n";
1996 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
1997 OS << " unsigned FNumVals = F->getNumValues();\n";
1998 OS << " unsigned TNumVals = T->getNumValues();\n";
1999 OS << " if (FNumVals != TNumVals) {\n";
2000 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2002 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
2003 << "SDOperand(T, i), &ISelKilled);\n";
2004 OS << " } else {\n";
2005 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2007 OS << " setSelected(F->getNodeId());\n";
2008 OS << " RemoveKilled();\n";
2011 OS << "// SelectRoot - Top level entry to DAG isel.\n";
2012 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2013 OS << " SelectRootInit();\n";
2014 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2015 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2016 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2017 OS << " memset(ISelQueued, 0, NumBytes);\n";
2018 OS << " memset(ISelSelected, 0, NumBytes);\n";
2020 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2021 << " // a reference to the root node, preventing it from being deleted,\n"
2022 << " // and tracking any changes of the root.\n"
2023 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2024 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2025 OS << " while (!ISelQueue.empty()) {\n";
2026 OS << " SDNode *Node = ISelQueue.front();\n";
2027 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2028 OS << " ISelQueue.pop_back();\n";
2029 OS << " if (!isSelected(Node->getNodeId())) {\n";
2030 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2031 OS << " if (ResNode != Node) {\n";
2032 OS << " if (ResNode)\n";
2033 OS << " ReplaceUses(Node, ResNode);\n";
2034 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2035 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2036 OS << " RemoveKilled();\n";
2042 OS << " delete[] ISelQueued;\n";
2043 OS << " ISelQueued = NULL;\n";
2044 OS << " delete[] ISelSelected;\n";
2045 OS << " ISelSelected = NULL;\n";
2046 OS << " return Dummy.getValue();\n";
2049 EmitNodeTransforms(OS);
2050 EmitPredicateFunctions(OS);
2052 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2053 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2055 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2056 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2060 // At this point, we have full information about the 'Patterns' we need to
2061 // parse, both implicitly from instructions as well as from explicit pattern
2062 // definitions. Emit the resultant instruction selector.
2063 EmitInstructionSelector(OS);