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 // Name of the folded node which produces a flag.
309 std::pair<std::string, unsigned> FoldedFlag;
310 // Names of all the folded nodes which produce chains.
311 std::vector<std::pair<std::string, unsigned> > FoldedChains;
312 // Original input chain(s).
313 std::vector<std::pair<std::string, std::string> > OrigChains;
314 std::set<std::string> Duplicates;
316 /// LSI - Load/Store information.
317 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
318 /// for each memory access. This facilitates the use of AliasAnalysis in
320 std::vector<std::string> LSI;
322 /// GeneratedCode - This is the buffer that we emit code to. The first int
323 /// indicates whether this is an exit predicate (something that should be
324 /// tested, and if true, the match fails) [when 1], or normal code to emit
325 /// [when 0], or initialization code to emit [when 2].
326 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
327 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
328 /// the set of patterns for each top-level opcode.
329 std::set<std::string> &GeneratedDecl;
330 /// TargetOpcodes - The target specific opcodes used by the resulting
332 std::vector<std::string> &TargetOpcodes;
333 std::vector<std::string> &TargetVTs;
335 std::string ChainName;
340 void emitCheck(const std::string &S) {
342 GeneratedCode.push_back(std::make_pair(1, S));
344 void emitCode(const std::string &S) {
346 GeneratedCode.push_back(std::make_pair(0, S));
348 void emitInit(const std::string &S) {
350 GeneratedCode.push_back(std::make_pair(2, S));
352 void emitDecl(const std::string &S) {
353 assert(!S.empty() && "Invalid declaration");
354 GeneratedDecl.insert(S);
356 void emitOpcode(const std::string &Opc) {
357 TargetOpcodes.push_back(Opc);
360 void emitVT(const std::string &VT) {
361 TargetVTs.push_back(VT);
365 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
366 TreePatternNode *pattern, TreePatternNode *instr,
367 std::vector<std::pair<unsigned, std::string> > &gc,
368 std::set<std::string> &gd,
369 std::vector<std::string> &to,
370 std::vector<std::string> &tv)
371 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
372 GeneratedCode(gc), GeneratedDecl(gd),
373 TargetOpcodes(to), TargetVTs(tv),
374 TmpNo(0), OpcNo(0), VTNo(0) {}
376 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
377 /// if the match fails. At this point, we already know that the opcode for N
378 /// matches, and the SDNode for the result has the RootName specified name.
379 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
380 const std::string &RootName, const std::string &ChainSuffix,
383 // Save loads/stores matched by a pattern.
384 if (!N->isLeaf() && N->getName().empty()) {
385 std::string EnumName = N->getOperator()->getValueAsString("Opcode");
386 if (EnumName == "ISD::LOAD" ||
387 EnumName == "ISD::STORE") {
388 LSI.push_back(RootName);
392 bool isRoot = (P == NULL);
393 // Emit instruction predicates. Each predicate is just a string for now.
395 std::string PredicateCheck;
396 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
397 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
398 Record *Def = Pred->getDef();
399 if (!Def->isSubClassOf("Predicate")) {
403 assert(0 && "Unknown predicate type!");
405 if (!PredicateCheck.empty())
406 PredicateCheck += " && ";
407 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
411 emitCheck(PredicateCheck);
415 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
416 emitCheck("cast<ConstantSDNode>(" + RootName +
417 ")->getSignExtended() == " + itostr(II->getValue()));
419 } else if (!NodeIsComplexPattern(N)) {
420 assert(0 && "Cannot match this as a leaf value!");
425 // If this node has a name associated with it, capture it in VariableMap. If
426 // we already saw this in the pattern, emit code to verify dagness.
427 if (!N->getName().empty()) {
428 std::string &VarMapEntry = VariableMap[N->getName()];
429 if (VarMapEntry.empty()) {
430 VarMapEntry = RootName;
432 // If we get here, this is a second reference to a specific name. Since
433 // we already have checked that the first reference is valid, we don't
434 // have to recursively match it, just check that it's the same as the
435 // previously named thing.
436 emitCheck(VarMapEntry + " == " + RootName);
441 OperatorMap[N->getName()] = N->getOperator();
445 // Emit code to load the child nodes and match their contents recursively.
447 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
448 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
449 bool EmittedUseCheck = false;
454 // Multiple uses of actual result?
455 emitCheck(RootName + ".hasOneUse()");
456 EmittedUseCheck = true;
458 // If the immediate use can somehow reach this node through another
459 // path, then can't fold it either or it will create a cycle.
460 // e.g. In the following diagram, XX can reach ld through YY. If
461 // ld is folded into XX, then YY is both a predecessor and a successor
471 bool NeedCheck = false;
475 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
477 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
478 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
479 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
480 PInfo.getNumOperands() > 1 ||
481 PInfo.hasProperty(SDNPHasChain) ||
482 PInfo.hasProperty(SDNPInFlag) ||
483 PInfo.hasProperty(SDNPOptInFlag);
487 std::string ParentName(RootName.begin(), RootName.end()-1);
488 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
496 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
497 "IsChainCompatible(" + ChainName + ".Val, " +
498 RootName + ".Val))");
499 OrigChains.push_back(std::make_pair(ChainName, RootName));
502 ChainName = "Chain" + ChainSuffix;
503 emitInit("SDOperand " + ChainName + " = " + RootName +
508 // Don't fold any node which reads or writes a flag and has multiple uses.
509 // FIXME: We really need to separate the concepts of flag and "glue". Those
510 // real flag results, e.g. X86CMP output, can have multiple uses.
511 // FIXME: If the optional incoming flag does not exist. Then it is ok to
514 (PatternHasProperty(N, SDNPInFlag, CGP) ||
515 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
516 PatternHasProperty(N, SDNPOutFlag, CGP))) {
517 if (!EmittedUseCheck) {
518 // Multiple uses of actual result?
519 emitCheck(RootName + ".hasOneUse()");
523 // If there is a node predicate for this, emit the call.
524 if (!N->getPredicateFn().empty())
525 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
528 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
529 // a constant without a predicate fn that has more that one bit set, handle
530 // this as a special case. This is usually for targets that have special
531 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
532 // handling stuff). Using these instructions is often far more efficient
533 // than materializing the constant. Unfortunately, both the instcombiner
534 // and the dag combiner can often infer that bits are dead, and thus drop
535 // them from the mask in the dag. For example, it might turn 'AND X, 255'
536 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
539 (N->getOperator()->getName() == "and" ||
540 N->getOperator()->getName() == "or") &&
541 N->getChild(1)->isLeaf() &&
542 N->getChild(1)->getPredicateFn().empty()) {
543 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
544 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
545 emitInit("SDOperand " + RootName + "0" + " = " +
546 RootName + ".getOperand(" + utostr(0) + ");");
547 emitInit("SDOperand " + RootName + "1" + " = " +
548 RootName + ".getOperand(" + utostr(1) + ");");
550 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
551 const char *MaskPredicate = N->getOperator()->getName() == "or"
552 ? "CheckOrMask(" : "CheckAndMask(";
553 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
554 RootName + "1), " + itostr(II->getValue()) + ")");
556 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
557 ChainSuffix + utostr(0), FoundChain);
563 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
564 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
565 RootName + ".getOperand(" +utostr(OpNo) + ");");
567 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
568 ChainSuffix + utostr(OpNo), FoundChain);
571 // Handle cases when root is a complex pattern.
572 const ComplexPattern *CP;
573 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
574 std::string Fn = CP->getSelectFunc();
575 unsigned NumOps = CP->getNumOperands();
576 for (unsigned i = 0; i < NumOps; ++i) {
577 emitDecl("CPTmp" + utostr(i));
578 emitCode("SDOperand CPTmp" + utostr(i) + ";");
580 if (CP->hasProperty(SDNPHasChain)) {
581 emitDecl("CPInChain");
582 emitDecl("Chain" + ChainSuffix);
583 emitCode("SDOperand CPInChain;");
584 emitCode("SDOperand Chain" + ChainSuffix + ";");
587 std::string Code = Fn + "(" + RootName + ", " + RootName;
588 for (unsigned i = 0; i < NumOps; i++)
589 Code += ", CPTmp" + utostr(i);
590 if (CP->hasProperty(SDNPHasChain)) {
591 ChainName = "Chain" + ChainSuffix;
592 Code += ", CPInChain, Chain" + ChainSuffix;
594 emitCheck(Code + ")");
598 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
599 const std::string &RootName,
600 const std::string &ParentRootName,
601 const std::string &ChainSuffix, bool &FoundChain) {
602 if (!Child->isLeaf()) {
603 // If it's not a leaf, recursively match.
604 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
605 emitCheck(RootName + ".getOpcode() == " +
606 CInfo.getEnumName());
607 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
608 bool HasChain = false;
609 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
611 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
613 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
614 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
615 "Pattern folded multiple nodes which produce flags?");
616 FoldedFlag = std::make_pair(RootName,
617 CInfo.getNumResults() + (unsigned)HasChain);
620 // If this child has a name associated with it, capture it in VarMap. If
621 // we already saw this in the pattern, emit code to verify dagness.
622 if (!Child->getName().empty()) {
623 std::string &VarMapEntry = VariableMap[Child->getName()];
624 if (VarMapEntry.empty()) {
625 VarMapEntry = RootName;
627 // If we get here, this is a second reference to a specific name.
628 // Since we already have checked that the first reference is valid,
629 // we don't have to recursively match it, just check that it's the
630 // same as the previously named thing.
631 emitCheck(VarMapEntry + " == " + RootName);
632 Duplicates.insert(RootName);
637 // Handle leaves of various types.
638 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
639 Record *LeafRec = DI->getDef();
640 if (LeafRec->isSubClassOf("RegisterClass") ||
641 LeafRec->getName() == "ptr_rc") {
642 // Handle register references. Nothing to do here.
643 } else if (LeafRec->isSubClassOf("Register")) {
644 // Handle register references.
645 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
646 // Handle complex pattern.
647 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
648 std::string Fn = CP->getSelectFunc();
649 unsigned NumOps = CP->getNumOperands();
650 for (unsigned i = 0; i < NumOps; ++i) {
651 emitDecl("CPTmp" + utostr(i));
652 emitCode("SDOperand CPTmp" + utostr(i) + ";");
654 if (CP->hasProperty(SDNPHasChain)) {
655 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
656 FoldedChains.push_back(std::make_pair("CPInChain",
657 PInfo.getNumResults()));
658 ChainName = "Chain" + ChainSuffix;
659 emitDecl("CPInChain");
661 emitCode("SDOperand CPInChain;");
662 emitCode("SDOperand " + ChainName + ";");
665 std::string Code = Fn + "(";
666 if (CP->hasAttribute(CPAttrParentAsRoot)) {
667 Code += ParentRootName + ", ";
671 if (CP->hasProperty(SDNPHasChain)) {
672 std::string ParentName(RootName.begin(), RootName.end()-1);
673 Code += ParentName + ", ";
676 for (unsigned i = 0; i < NumOps; i++)
677 Code += ", CPTmp" + utostr(i);
678 if (CP->hasProperty(SDNPHasChain))
679 Code += ", CPInChain, Chain" + ChainSuffix;
680 emitCheck(Code + ")");
681 } else if (LeafRec->getName() == "srcvalue") {
682 // Place holder for SRCVALUE nodes. Nothing to do here.
683 } else if (LeafRec->isSubClassOf("ValueType")) {
684 // Make sure this is the specified value type.
685 emitCheck("cast<VTSDNode>(" + RootName +
686 ")->getVT() == MVT::" + LeafRec->getName());
687 } else if (LeafRec->isSubClassOf("CondCode")) {
688 // Make sure this is the specified cond code.
689 emitCheck("cast<CondCodeSDNode>(" + RootName +
690 ")->get() == ISD::" + LeafRec->getName());
696 assert(0 && "Unknown leaf type!");
699 // If there is a node predicate for this, emit the call.
700 if (!Child->getPredicateFn().empty())
701 emitCheck(Child->getPredicateFn() + "(" + RootName +
703 } else if (IntInit *II =
704 dynamic_cast<IntInit*>(Child->getLeafValue())) {
705 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
706 unsigned CTmp = TmpNo++;
707 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
708 RootName + ")->getSignExtended();");
710 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
715 assert(0 && "Unknown leaf type!");
720 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
721 /// we actually have to build a DAG!
722 std::vector<std::string>
723 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
724 bool InFlagDecled, bool ResNodeDecled,
725 bool LikeLeaf = false, bool isRoot = false) {
726 // List of arguments of getTargetNode() or SelectNodeTo().
727 std::vector<std::string> NodeOps;
728 // This is something selected from the pattern we matched.
729 if (!N->getName().empty()) {
730 const std::string &VarName = N->getName();
731 std::string Val = VariableMap[VarName];
732 bool ModifiedVal = false;
734 cerr << "Variable '" << VarName << " referenced but not defined "
735 << "and not caught earlier!\n";
738 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
739 // Already selected this operand, just return the tmpval.
740 NodeOps.push_back(Val);
744 const ComplexPattern *CP;
745 unsigned ResNo = TmpNo++;
746 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
747 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
748 std::string CastType;
749 std::string TmpVar = "Tmp" + utostr(ResNo);
750 switch (N->getTypeNum(0)) {
752 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
753 << " type as an immediate constant. Aborting\n";
755 case MVT::i1: CastType = "bool"; break;
756 case MVT::i8: CastType = "unsigned char"; break;
757 case MVT::i16: CastType = "unsigned short"; break;
758 case MVT::i32: CastType = "unsigned"; break;
759 case MVT::i64: CastType = "uint64_t"; break;
761 emitCode("SDOperand " + TmpVar +
762 " = CurDAG->getTargetConstant(((" + CastType +
763 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
764 getEnumName(N->getTypeNum(0)) + ");");
765 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
766 // value if used multiple times by this pattern result.
769 NodeOps.push_back(Val);
770 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
771 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
772 std::string TmpVar = "Tmp" + utostr(ResNo);
773 emitCode("SDOperand " + TmpVar +
774 " = CurDAG->getTargetConstantFP(cast<ConstantFPSDNode>(" +
775 Val + ")->getValueAPF(), cast<ConstantFPSDNode>(" + Val +
776 ")->getValueType(0));");
777 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
778 // value if used multiple times by this pattern result.
781 NodeOps.push_back(Val);
782 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
783 Record *Op = OperatorMap[N->getName()];
784 // Transform ExternalSymbol to TargetExternalSymbol
785 if (Op && Op->getName() == "externalsym") {
786 std::string TmpVar = "Tmp"+utostr(ResNo);
787 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
788 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
789 Val + ")->getSymbol(), " +
790 getEnumName(N->getTypeNum(0)) + ");");
791 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
792 // this value if used multiple times by this pattern result.
796 NodeOps.push_back(Val);
797 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
798 || N->getOperator()->getName() == "tglobaltlsaddr")) {
799 Record *Op = OperatorMap[N->getName()];
800 // Transform GlobalAddress to TargetGlobalAddress
801 if (Op && (Op->getName() == "globaladdr" ||
802 Op->getName() == "globaltlsaddr")) {
803 std::string TmpVar = "Tmp" + utostr(ResNo);
804 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
805 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
806 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
808 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
809 // this value if used multiple times by this pattern result.
813 NodeOps.push_back(Val);
814 } else if (!N->isLeaf()
815 && (N->getOperator()->getName() == "texternalsym"
816 || N->getOperator()->getName() == "tconstpool")) {
817 // Do not rewrite the variable name, since we don't generate a new
819 NodeOps.push_back(Val);
820 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
821 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
822 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
823 NodeOps.push_back("CPTmp" + utostr(i));
826 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
827 // node even if it isn't one. Don't select it.
829 emitCode("AddToISelQueue(" + Val + ");");
830 if (isRoot && N->isLeaf()) {
831 emitCode("ReplaceUses(N, " + Val + ");");
832 emitCode("return NULL;");
835 NodeOps.push_back(Val);
839 VariableMap[VarName] = Val;
844 // If this is an explicit register reference, handle it.
845 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
846 unsigned ResNo = TmpNo++;
847 if (DI->getDef()->isSubClassOf("Register")) {
848 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
849 getQualifiedName(DI->getDef()) + ", " +
850 getEnumName(N->getTypeNum(0)) + ");");
851 NodeOps.push_back("Tmp" + utostr(ResNo));
853 } else if (DI->getDef()->getName() == "zero_reg") {
854 emitCode("SDOperand Tmp" + utostr(ResNo) +
855 " = CurDAG->getRegister(0, " +
856 getEnumName(N->getTypeNum(0)) + ");");
857 NodeOps.push_back("Tmp" + utostr(ResNo));
860 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
861 unsigned ResNo = TmpNo++;
862 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
863 emitCode("SDOperand Tmp" + utostr(ResNo) +
864 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
865 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
866 NodeOps.push_back("Tmp" + utostr(ResNo));
873 assert(0 && "Unknown leaf type!");
877 Record *Op = N->getOperator();
878 if (Op->isSubClassOf("Instruction")) {
879 const CodeGenTarget &CGT = CGP.getTargetInfo();
880 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
881 const DAGInstruction &Inst = CGP.getInstruction(Op);
882 const TreePattern *InstPat = Inst.getPattern();
883 // FIXME: Assume actual pattern comes before "implicit".
884 TreePatternNode *InstPatNode =
885 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
886 : (InstPat ? InstPat->getTree(0) : NULL);
887 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
888 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
890 bool HasVarOps = isRoot && II.isVariadic;
891 // FIXME: fix how we deal with physical register operands.
892 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
893 bool HasImpResults = isRoot && DstRegs.size() > 0;
894 bool NodeHasOptInFlag = isRoot &&
895 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
896 bool NodeHasInFlag = isRoot &&
897 PatternHasProperty(Pattern, SDNPInFlag, CGP);
898 bool NodeHasOutFlag = isRoot &&
899 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
900 bool NodeHasChain = InstPatNode &&
901 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
902 bool InputHasChain = isRoot &&
903 NodeHasProperty(Pattern, SDNPHasChain, CGP);
904 unsigned NumResults = Inst.getNumResults();
905 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
907 if (NodeHasOptInFlag) {
908 emitCode("bool HasInFlag = "
909 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
912 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
914 // How many results is this pattern expected to produce?
915 unsigned NumPatResults = 0;
916 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
917 MVT::ValueType VT = Pattern->getTypeNum(i);
918 if (VT != MVT::isVoid && VT != MVT::Flag)
922 if (OrigChains.size() > 0) {
923 // The original input chain is being ignored. If it is not just
924 // pointing to the op that's being folded, we should create a
925 // TokenFactor with it and the chain of the folded op as the new chain.
926 // We could potentially be doing multiple levels of folding, in that
927 // case, the TokenFactor can have more operands.
928 emitCode("SmallVector<SDOperand, 8> InChains;");
929 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
930 emitCode("if (" + OrigChains[i].first + ".Val != " +
931 OrigChains[i].second + ".Val) {");
932 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
933 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
936 emitCode("AddToISelQueue(" + ChainName + ");");
937 emitCode("InChains.push_back(" + ChainName + ");");
938 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
939 "&InChains[0], InChains.size());");
942 // Loop over all of the operands of the instruction pattern, emitting code
943 // to fill them all in. The node 'N' usually has number children equal to
944 // the number of input operands of the instruction. However, in cases
945 // where there are predicate operands for an instruction, we need to fill
946 // in the 'execute always' values. Match up the node operands to the
947 // instruction operands to do this.
948 std::vector<std::string> AllOps;
949 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
950 for (unsigned ChildNo = 0, InstOpNo = NumResults;
951 InstOpNo != II.OperandList.size(); ++InstOpNo) {
952 std::vector<std::string> Ops;
954 // If this is a normal operand or a predicate operand without
955 // 'execute always', emit it.
956 Record *OperandNode = II.OperandList[InstOpNo].Rec;
957 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
958 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
959 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
960 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
961 InFlagDecled, ResNodeDecled);
962 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
965 // Otherwise, this is a predicate or optional def operand, emit the
966 // 'default ops' operands.
967 const DAGDefaultOperand &DefaultOp =
968 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
969 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
970 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
971 InFlagDecled, ResNodeDecled);
972 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
973 NumEAInputs += Ops.size();
978 // Generate MemOperandSDNodes nodes for each memory accesses covered by this
981 std::vector<std::string>::const_iterator mi, mie;
982 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
983 emitCode("SDOperand LSI_" + *mi + " = "
984 "CurDAG->getMemOperand(cast<LSBaseSDNode>(" +
985 *mi + ")->getMemOperand());");
986 AllOps.push_back("LSI_" + *mi);
990 // Emit all the chain and CopyToReg stuff.
991 bool ChainEmitted = NodeHasChain;
993 emitCode("AddToISelQueue(" + ChainName + ");");
994 if (NodeHasInFlag || HasImpInputs)
995 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
996 InFlagDecled, ResNodeDecled, true);
997 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
999 emitCode("SDOperand InFlag(0, 0);");
1000 InFlagDecled = true;
1002 if (NodeHasOptInFlag) {
1003 emitCode("if (HasInFlag) {");
1004 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1005 emitCode(" AddToISelQueue(InFlag);");
1010 unsigned ResNo = TmpNo++;
1011 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
1012 NodeHasOptInFlag || HasImpResults) {
1015 std::string NodeName;
1017 NodeName = "Tmp" + utostr(ResNo);
1018 Code2 = "SDOperand " + NodeName + "(";
1020 NodeName = "ResNode";
1021 if (!ResNodeDecled) {
1022 Code2 = "SDNode *" + NodeName + " = ";
1023 ResNodeDecled = true;
1025 Code2 = NodeName + " = ";
1028 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
1029 unsigned OpsNo = OpcNo;
1030 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1032 // Output order: results, chain, flags
1034 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1035 Code += ", VT" + utostr(VTNo);
1036 emitVT(getEnumName(N->getTypeNum(0)));
1038 // Add types for implicit results in physical registers, scheduler will
1039 // care of adding copyfromreg nodes.
1040 for (unsigned i = 0; i < NumDstRegs; i++) {
1041 Record *RR = DstRegs[i];
1042 if (RR->isSubClassOf("Register")) {
1043 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1044 Code += ", " + getEnumName(RVT);
1048 Code += ", MVT::Other";
1050 Code += ", MVT::Flag";
1052 // Figure out how many fixed inputs the node has. This is important to
1053 // know which inputs are the variable ones if present.
1054 unsigned NumInputs = AllOps.size();
1055 NumInputs += NodeHasChain;
1059 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1060 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1065 // Figure out whether any operands at the end of the op list are not
1066 // part of the variable section.
1067 std::string EndAdjust;
1068 if (NodeHasInFlag || HasImpInputs)
1069 EndAdjust = "-1"; // Always has one flag.
1070 else if (NodeHasOptInFlag)
1071 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1073 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1074 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1076 emitCode(" AddToISelQueue(N.getOperand(i));");
1077 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1083 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1085 AllOps.push_back(ChainName);
1089 if (NodeHasInFlag || HasImpInputs)
1090 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1091 else if (NodeHasOptInFlag) {
1092 emitCode("if (HasInFlag)");
1093 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1095 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1097 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1098 AllOps.push_back("InFlag");
1100 unsigned NumOps = AllOps.size();
1102 if (!NodeHasOptInFlag && NumOps < 4) {
1103 for (unsigned i = 0; i != NumOps; ++i)
1104 Code += ", " + AllOps[i];
1106 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1107 for (unsigned i = 0; i != NumOps; ++i) {
1108 OpsCode += AllOps[i];
1112 emitCode(OpsCode + " };");
1113 Code += ", Ops" + utostr(OpsNo) + ", ";
1114 if (NodeHasOptInFlag) {
1115 Code += "HasInFlag ? ";
1116 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1118 Code += utostr(NumOps);
1124 emitCode(Code2 + Code + ");");
1127 // Remember which op produces the chain.
1129 emitCode(ChainName + " = SDOperand(" + NodeName +
1130 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
1132 emitCode(ChainName + " = SDOperand(" + NodeName +
1133 ", " + utostr(NumResults+NumDstRegs) + ");");
1136 NodeOps.push_back("Tmp" + utostr(ResNo));
1140 bool NeedReplace = false;
1141 if (NodeHasOutFlag) {
1142 if (!InFlagDecled) {
1143 emitCode("SDOperand InFlag(ResNode, " +
1144 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1145 InFlagDecled = true;
1147 emitCode("InFlag = SDOperand(ResNode, " +
1148 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1151 if (FoldedChains.size() > 0) {
1153 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1154 emitCode("ReplaceUses(SDOperand(" +
1155 FoldedChains[j].first + ".Val, " +
1156 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1157 utostr(NumResults+NumDstRegs) + "));");
1161 if (NodeHasOutFlag) {
1162 if (FoldedFlag.first != "") {
1163 emitCode("ReplaceUses(SDOperand(" + FoldedFlag.first + ".Val, " +
1164 utostr(FoldedFlag.second) + "), InFlag);");
1166 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1167 emitCode("ReplaceUses(SDOperand(N.Val, " +
1168 utostr(NumPatResults + (unsigned)InputHasChain)
1174 if (NeedReplace && InputHasChain)
1175 emitCode("ReplaceUses(SDOperand(N.Val, " +
1176 utostr(NumPatResults) + "), SDOperand(" + ChainName
1177 + ".Val, " + ChainName + ".ResNo" + "));");
1179 // User does not expect the instruction would produce a chain!
1180 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1182 } else if (InputHasChain && !NodeHasChain) {
1183 // One of the inner node produces a chain.
1185 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1186 "), SDOperand(ResNode, N.ResNo-1));");
1187 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1188 "), " + ChainName + ");");
1191 emitCode("return ResNode;");
1193 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1195 if (N->getTypeNum(0) != MVT::isVoid)
1196 Code += ", VT" + utostr(VTNo);
1198 Code += ", MVT::Flag";
1200 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1201 AllOps.push_back("InFlag");
1203 unsigned NumOps = AllOps.size();
1205 if (!NodeHasOptInFlag && NumOps < 4) {
1206 for (unsigned i = 0; i != NumOps; ++i)
1207 Code += ", " + AllOps[i];
1209 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1210 for (unsigned i = 0; i != NumOps; ++i) {
1211 OpsCode += AllOps[i];
1215 emitCode(OpsCode + " };");
1216 Code += ", Ops" + utostr(OpcNo) + ", ";
1217 Code += utostr(NumOps);
1220 emitCode(Code + ");");
1221 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1222 if (N->getTypeNum(0) != MVT::isVoid)
1223 emitVT(getEnumName(N->getTypeNum(0)));
1227 } else if (Op->isSubClassOf("SDNodeXForm")) {
1228 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1229 // PatLeaf node - the operand may or may not be a leaf node. But it should
1231 std::vector<std::string> Ops =
1232 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1233 ResNodeDecled, true);
1234 unsigned ResNo = TmpNo++;
1235 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1236 + "(" + Ops.back() + ".Val);");
1237 NodeOps.push_back("Tmp" + utostr(ResNo));
1239 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1244 throw std::string("Unknown node in result pattern!");
1248 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1249 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1250 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1251 /// for, this returns true otherwise false if Pat has all types.
1252 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1253 const std::string &Prefix, bool isRoot = false) {
1255 if (Pat->getExtTypes() != Other->getExtTypes()) {
1256 // Move a type over from 'other' to 'pat'.
1257 Pat->setTypes(Other->getExtTypes());
1258 // The top level node type is checked outside of the select function.
1260 emitCheck(Prefix + ".Val->getValueType(0) == " +
1261 getName(Pat->getTypeNum(0)));
1266 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1267 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1268 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1269 Prefix + utostr(OpNo)))
1275 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1277 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1278 bool &ChainEmitted, bool &InFlagDecled,
1279 bool &ResNodeDecled, bool isRoot = false) {
1280 const CodeGenTarget &T = CGP.getTargetInfo();
1282 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1283 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1284 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1285 TreePatternNode *Child = N->getChild(i);
1286 if (!Child->isLeaf()) {
1287 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1288 InFlagDecled, ResNodeDecled);
1290 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1291 if (!Child->getName().empty()) {
1292 std::string Name = RootName + utostr(OpNo);
1293 if (Duplicates.find(Name) != Duplicates.end())
1294 // A duplicate! Do not emit a copy for this node.
1298 Record *RR = DI->getDef();
1299 if (RR->isSubClassOf("Register")) {
1300 MVT::ValueType RVT = getRegisterValueType(RR, T);
1301 if (RVT == MVT::Flag) {
1302 if (!InFlagDecled) {
1303 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1304 InFlagDecled = true;
1306 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1307 emitCode("AddToISelQueue(InFlag);");
1309 if (!ChainEmitted) {
1310 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1311 ChainName = "Chain";
1312 ChainEmitted = true;
1314 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1315 if (!InFlagDecled) {
1316 emitCode("SDOperand InFlag(0, 0);");
1317 InFlagDecled = true;
1319 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1320 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1321 ", " + getQualifiedName(RR) +
1322 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1323 ResNodeDecled = true;
1324 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1325 emitCode("InFlag = SDOperand(ResNode, 1);");
1333 if (!InFlagDecled) {
1334 emitCode("SDOperand InFlag = " + RootName +
1335 ".getOperand(" + utostr(OpNo) + ");");
1336 InFlagDecled = true;
1338 emitCode("InFlag = " + RootName +
1339 ".getOperand(" + utostr(OpNo) + ");");
1340 emitCode("AddToISelQueue(InFlag);");
1345 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1346 /// stream to match the pattern, and generate the code for the match if it
1347 /// succeeds. Returns true if the pattern is not guaranteed to match.
1348 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1349 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1350 std::set<std::string> &GeneratedDecl,
1351 std::vector<std::string> &TargetOpcodes,
1352 std::vector<std::string> &TargetVTs) {
1353 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1354 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1355 GeneratedCode, GeneratedDecl,
1356 TargetOpcodes, TargetVTs);
1358 // Emit the matcher, capturing named arguments in VariableMap.
1359 bool FoundChain = false;
1360 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1362 // TP - Get *SOME* tree pattern, we don't care which.
1363 TreePattern &TP = *CGP.pf_begin()->second;
1365 // At this point, we know that we structurally match the pattern, but the
1366 // types of the nodes may not match. Figure out the fewest number of type
1367 // comparisons we need to emit. For example, if there is only one integer
1368 // type supported by a target, there should be no type comparisons at all for
1369 // integer patterns!
1371 // To figure out the fewest number of type checks needed, clone the pattern,
1372 // remove the types, then perform type inference on the pattern as a whole.
1373 // If there are unresolved types, emit an explicit check for those types,
1374 // apply the type to the tree, then rerun type inference. Iterate until all
1375 // types are resolved.
1377 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1378 RemoveAllTypes(Pat);
1381 // Resolve/propagate as many types as possible.
1383 bool MadeChange = true;
1385 MadeChange = Pat->ApplyTypeConstraints(TP,
1386 true/*Ignore reg constraints*/);
1388 assert(0 && "Error: could not find consistent types for something we"
1389 " already decided was ok!");
1393 // Insert a check for an unresolved type and add it to the tree. If we find
1394 // an unresolved type to add a check for, this returns true and we iterate,
1395 // otherwise we are done.
1396 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1398 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1399 false, false, false, true);
1403 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1404 /// a line causes any of them to be empty, remove them and return true when
1406 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1407 std::vector<std::pair<unsigned, std::string> > > >
1409 bool ErasedPatterns = false;
1410 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1411 Patterns[i].second.pop_back();
1412 if (Patterns[i].second.empty()) {
1413 Patterns.erase(Patterns.begin()+i);
1415 ErasedPatterns = true;
1418 return ErasedPatterns;
1421 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1422 /// code together between the patterns.
1423 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1424 std::vector<std::pair<unsigned, std::string> > > >
1425 &Patterns, unsigned Indent,
1427 typedef std::pair<unsigned, std::string> CodeLine;
1428 typedef std::vector<CodeLine> CodeList;
1429 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1431 if (Patterns.empty()) return;
1433 // Figure out how many patterns share the next code line. Explicitly copy
1434 // FirstCodeLine so that we don't invalidate a reference when changing
1436 const CodeLine FirstCodeLine = Patterns.back().second.back();
1437 unsigned LastMatch = Patterns.size()-1;
1438 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1441 // If not all patterns share this line, split the list into two pieces. The
1442 // first chunk will use this line, the second chunk won't.
1443 if (LastMatch != 0) {
1444 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1445 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1447 // FIXME: Emit braces?
1448 if (Shared.size() == 1) {
1449 const PatternToMatch &Pattern = *Shared.back().first;
1450 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1451 Pattern.getSrcPattern()->print(OS);
1452 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1453 Pattern.getDstPattern()->print(OS);
1455 unsigned AddedComplexity = Pattern.getAddedComplexity();
1456 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1457 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1459 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1461 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1463 if (FirstCodeLine.first != 1) {
1464 OS << std::string(Indent, ' ') << "{\n";
1467 EmitPatterns(Shared, Indent, OS);
1468 if (FirstCodeLine.first != 1) {
1470 OS << std::string(Indent, ' ') << "}\n";
1473 if (Other.size() == 1) {
1474 const PatternToMatch &Pattern = *Other.back().first;
1475 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1476 Pattern.getSrcPattern()->print(OS);
1477 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1478 Pattern.getDstPattern()->print(OS);
1480 unsigned AddedComplexity = Pattern.getAddedComplexity();
1481 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1482 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1484 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1486 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1488 EmitPatterns(Other, Indent, OS);
1492 // Remove this code from all of the patterns that share it.
1493 bool ErasedPatterns = EraseCodeLine(Patterns);
1495 bool isPredicate = FirstCodeLine.first == 1;
1497 // Otherwise, every pattern in the list has this line. Emit it.
1500 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1502 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1504 // If the next code line is another predicate, and if all of the pattern
1505 // in this group share the same next line, emit it inline now. Do this
1506 // until we run out of common predicates.
1507 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1508 // Check that all of fhe patterns in Patterns end with the same predicate.
1509 bool AllEndWithSamePredicate = true;
1510 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1511 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1512 AllEndWithSamePredicate = false;
1515 // If all of the predicates aren't the same, we can't share them.
1516 if (!AllEndWithSamePredicate) break;
1518 // Otherwise we can. Emit it shared now.
1519 OS << " &&\n" << std::string(Indent+4, ' ')
1520 << Patterns.back().second.back().second;
1521 ErasedPatterns = EraseCodeLine(Patterns);
1528 EmitPatterns(Patterns, Indent, OS);
1531 OS << std::string(Indent-2, ' ') << "}\n";
1534 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
1535 return CGP.getSDNodeInfo(Op).getEnumName();
1538 static std::string getLegalCName(std::string OpName) {
1539 std::string::size_type pos = OpName.find("::");
1540 if (pos != std::string::npos)
1541 OpName.replace(pos, 2, "_");
1545 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1546 const CodeGenTarget &Target = CGP.getTargetInfo();
1548 // Get the namespace to insert instructions into. Make sure not to pick up
1549 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1550 // instruction or something.
1552 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1553 e = Target.inst_end(); i != e; ++i) {
1554 InstNS = i->second.Namespace;
1555 if (InstNS != "TargetInstrInfo")
1559 if (!InstNS.empty()) InstNS += "::";
1561 // Group the patterns by their top-level opcodes.
1562 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1563 // All unique target node emission functions.
1564 std::map<std::string, unsigned> EmitFunctions;
1565 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1566 E = CGP.ptm_end(); I != E; ++I) {
1567 const PatternToMatch &Pattern = *I;
1569 TreePatternNode *Node = Pattern.getSrcPattern();
1570 if (!Node->isLeaf()) {
1571 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1572 push_back(&Pattern);
1574 const ComplexPattern *CP;
1575 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1576 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1577 push_back(&Pattern);
1578 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1579 std::vector<Record*> OpNodes = CP->getRootNodes();
1580 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1581 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1582 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1586 cerr << "Unrecognized opcode '";
1588 cerr << "' on tree pattern '";
1589 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1595 // For each opcode, there might be multiple select functions, one per
1596 // ValueType of the node (or its first operand if it doesn't produce a
1597 // non-chain result.
1598 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1600 // Emit one Select_* method for each top-level opcode. We do this instead of
1601 // emitting one giant switch statement to support compilers where this will
1602 // result in the recursive functions taking less stack space.
1603 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1604 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1605 PBOI != E; ++PBOI) {
1606 const std::string &OpName = PBOI->first;
1607 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1608 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1610 // We want to emit all of the matching code now. However, we want to emit
1611 // the matches in order of minimal cost. Sort the patterns so the least
1612 // cost one is at the start.
1613 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1614 PatternSortingPredicate(CGP));
1616 // Split them into groups by type.
1617 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1618 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1619 const PatternToMatch *Pat = PatternsOfOp[i];
1620 TreePatternNode *SrcPat = Pat->getSrcPattern();
1621 MVT::ValueType VT = SrcPat->getTypeNum(0);
1622 std::map<MVT::ValueType,
1623 std::vector<const PatternToMatch*> >::iterator TI =
1624 PatternsByType.find(VT);
1625 if (TI != PatternsByType.end())
1626 TI->second.push_back(Pat);
1628 std::vector<const PatternToMatch*> PVec;
1629 PVec.push_back(Pat);
1630 PatternsByType.insert(std::make_pair(VT, PVec));
1634 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1635 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1637 MVT::ValueType OpVT = II->first;
1638 std::vector<const PatternToMatch*> &Patterns = II->second;
1639 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1640 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1642 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1643 std::vector<std::vector<std::string> > PatternOpcodes;
1644 std::vector<std::vector<std::string> > PatternVTs;
1645 std::vector<std::set<std::string> > PatternDecls;
1646 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1647 CodeList GeneratedCode;
1648 std::set<std::string> GeneratedDecl;
1649 std::vector<std::string> TargetOpcodes;
1650 std::vector<std::string> TargetVTs;
1651 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1652 TargetOpcodes, TargetVTs);
1653 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1654 PatternDecls.push_back(GeneratedDecl);
1655 PatternOpcodes.push_back(TargetOpcodes);
1656 PatternVTs.push_back(TargetVTs);
1659 // Scan the code to see if all of the patterns are reachable and if it is
1660 // possible that the last one might not match.
1661 bool mightNotMatch = true;
1662 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1663 CodeList &GeneratedCode = CodeForPatterns[i].second;
1664 mightNotMatch = false;
1666 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1667 if (GeneratedCode[j].first == 1) { // predicate.
1668 mightNotMatch = true;
1673 // If this pattern definitely matches, and if it isn't the last one, the
1674 // patterns after it CANNOT ever match. Error out.
1675 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1676 cerr << "Pattern '";
1677 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1678 cerr << "' is impossible to select!\n";
1683 // Factor target node emission code (emitted by EmitResultCode) into
1684 // separate functions. Uniquing and share them among all instruction
1685 // selection routines.
1686 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1687 CodeList &GeneratedCode = CodeForPatterns[i].second;
1688 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1689 std::vector<std::string> &TargetVTs = PatternVTs[i];
1690 std::set<std::string> Decls = PatternDecls[i];
1691 std::vector<std::string> AddedInits;
1692 int CodeSize = (int)GeneratedCode.size();
1694 for (int j = CodeSize-1; j >= 0; --j) {
1695 if (LastPred == -1 && GeneratedCode[j].first == 1)
1697 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1698 AddedInits.push_back(GeneratedCode[j].second);
1701 std::string CalleeCode = "(const SDOperand &N";
1702 std::string CallerCode = "(N";
1703 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1704 CalleeCode += ", unsigned Opc" + utostr(j);
1705 CallerCode += ", " + TargetOpcodes[j];
1707 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1708 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1709 CallerCode += ", " + TargetVTs[j];
1711 for (std::set<std::string>::iterator
1712 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1713 std::string Name = *I;
1714 CalleeCode += ", SDOperand &" + Name;
1715 CallerCode += ", " + Name;
1719 // Prevent emission routines from being inlined to reduce selection
1720 // routines stack frame sizes.
1721 CalleeCode += "DISABLE_INLINE ";
1722 CalleeCode += "{\n";
1724 for (std::vector<std::string>::const_reverse_iterator
1725 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1726 CalleeCode += " " + *I + "\n";
1728 for (int j = LastPred+1; j < CodeSize; ++j)
1729 CalleeCode += " " + GeneratedCode[j].second + "\n";
1730 for (int j = LastPred+1; j < CodeSize; ++j)
1731 GeneratedCode.pop_back();
1732 CalleeCode += "}\n";
1734 // Uniquing the emission routines.
1735 unsigned EmitFuncNum;
1736 std::map<std::string, unsigned>::iterator EFI =
1737 EmitFunctions.find(CalleeCode);
1738 if (EFI != EmitFunctions.end()) {
1739 EmitFuncNum = EFI->second;
1741 EmitFuncNum = EmitFunctions.size();
1742 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1743 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1746 // Replace the emission code within selection routines with calls to the
1747 // emission functions.
1748 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1749 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1753 std::string OpVTStr;
1754 if (OpVT == MVT::iPTR) {
1756 } else if (OpVT == MVT::isVoid) {
1757 // Nodes with a void result actually have a first result type of either
1758 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1759 // void to this case, we handle it specially here.
1761 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1763 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1764 OpcodeVTMap.find(OpName);
1765 if (OpVTI == OpcodeVTMap.end()) {
1766 std::vector<std::string> VTSet;
1767 VTSet.push_back(OpVTStr);
1768 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1770 OpVTI->second.push_back(OpVTStr);
1772 OS << "SDNode *Select_" << getLegalCName(OpName)
1773 << OpVTStr << "(const SDOperand &N) {\n";
1775 // Loop through and reverse all of the CodeList vectors, as we will be
1776 // accessing them from their logical front, but accessing the end of a
1777 // vector is more efficient.
1778 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1779 CodeList &GeneratedCode = CodeForPatterns[i].second;
1780 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1783 // Next, reverse the list of patterns itself for the same reason.
1784 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1786 // Emit all of the patterns now, grouped together to share code.
1787 EmitPatterns(CodeForPatterns, 2, OS);
1789 // If the last pattern has predicates (which could fail) emit code to
1790 // catch the case where nothing handles a pattern.
1791 if (mightNotMatch) {
1792 OS << " cerr << \"Cannot yet select: \";\n";
1793 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1794 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1795 OpName != "ISD::INTRINSIC_VOID") {
1796 OS << " N.Val->dump(CurDAG);\n";
1798 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1799 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1800 << " cerr << \"intrinsic %\"<< "
1801 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1803 OS << " cerr << '\\n';\n"
1805 << " return NULL;\n";
1811 // Emit boilerplate.
1812 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1813 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1814 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1816 << " // Ensure that the asm operands are themselves selected.\n"
1817 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1818 << " AddToISelQueue(Ops[j]);\n\n"
1820 << " std::vector<MVT::ValueType> VTs;\n"
1821 << " VTs.push_back(MVT::Other);\n"
1822 << " VTs.push_back(MVT::Flag);\n"
1823 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1825 << " return New.Val;\n"
1828 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1829 << " SDOperand Chain = N.getOperand(0);\n"
1830 << " SDOperand N1 = N.getOperand(1);\n"
1831 << " SDOperand N2 = N.getOperand(2);\n"
1832 << " unsigned C1 = cast<ConstantSDNode>(N1)->getValue();\n"
1833 << " unsigned C2 = cast<ConstantSDNode>(N2)->getValue();\n"
1834 << " SDOperand Tmp1 = CurDAG->getTargetConstant(C1, MVT::i32);\n"
1835 << " SDOperand Tmp2 = CurDAG->getTargetConstant(C2, MVT::i32);\n"
1836 << " AddToISelQueue(Chain);\n"
1837 << " SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1838 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1839 << " MVT::Other, Ops, 3);\n"
1842 OS << "SDNode *Select_DECLARE(const SDOperand &N) {\n"
1843 << " SDOperand Chain = N.getOperand(0);\n"
1844 << " SDOperand N1 = N.getOperand(1);\n"
1845 << " SDOperand N2 = N.getOperand(2);\n"
1846 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1847 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1848 << " N.Val->dump(CurDAG);\n"
1851 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1852 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1853 << " SDOperand Tmp1 = "
1854 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1855 << " SDOperand Tmp2 = "
1856 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1857 << " AddToISelQueue(Chain);\n"
1858 << " SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1859 << " return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,\n"
1860 << " MVT::Other, Ops, 3);\n"
1863 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1864 << " SDOperand N0 = N.getOperand(0);\n"
1865 << " SDOperand N1 = N.getOperand(1);\n"
1866 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1867 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1868 << " AddToISelQueue(N0);\n"
1869 << " SDOperand Ops[] = { N0, Tmp };\n"
1870 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1871 << " N.getValueType(), Ops, 2);\n"
1874 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1875 << " SDOperand N0 = N.getOperand(0);\n"
1876 << " SDOperand N1 = N.getOperand(1);\n"
1877 << " SDOperand N2 = N.getOperand(2);\n"
1878 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1879 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1880 << " AddToISelQueue(N1);\n"
1881 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
1882 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
1883 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1884 << " N.getValueType(), Ops+1, 2);\n"
1886 << " AddToISelQueue(N0);\n"
1887 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1888 << " N.getValueType(), Ops, 3);\n"
1892 OS << "// The main instruction selector code.\n"
1893 << "SDNode *SelectCode(SDOperand N) {\n"
1894 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1895 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1896 << "INSTRUCTION_LIST_END)) {\n"
1897 << " return NULL; // Already selected.\n"
1899 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1900 << " switch (N.getOpcode()) {\n"
1901 << " default: break;\n"
1902 << " case ISD::EntryToken: // These leaves remain the same.\n"
1903 << " case ISD::BasicBlock:\n"
1904 << " case ISD::Register:\n"
1905 << " case ISD::HANDLENODE:\n"
1906 << " case ISD::TargetConstant:\n"
1907 << " case ISD::TargetConstantFP:\n"
1908 << " case ISD::TargetConstantPool:\n"
1909 << " case ISD::TargetFrameIndex:\n"
1910 << " case ISD::TargetExternalSymbol:\n"
1911 << " case ISD::TargetJumpTable:\n"
1912 << " case ISD::TargetGlobalTLSAddress:\n"
1913 << " case ISD::TargetGlobalAddress: {\n"
1914 << " return NULL;\n"
1916 << " case ISD::AssertSext:\n"
1917 << " case ISD::AssertZext: {\n"
1918 << " AddToISelQueue(N.getOperand(0));\n"
1919 << " ReplaceUses(N, N.getOperand(0));\n"
1920 << " return NULL;\n"
1922 << " case ISD::TokenFactor:\n"
1923 << " case ISD::CopyFromReg:\n"
1924 << " case ISD::CopyToReg: {\n"
1925 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1926 << " AddToISelQueue(N.getOperand(i));\n"
1927 << " return NULL;\n"
1929 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1930 << " case ISD::LABEL: return Select_LABEL(N);\n"
1931 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
1932 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1933 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
1936 // Loop over all of the case statements, emiting a call to each method we
1938 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1939 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1940 PBOI != E; ++PBOI) {
1941 const std::string &OpName = PBOI->first;
1942 // Potentially multiple versions of select for this opcode. One for each
1943 // ValueType of the node (or its first true operand if it doesn't produce a
1945 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1946 OpcodeVTMap.find(OpName);
1947 std::vector<std::string> &OpVTs = OpVTI->second;
1948 OS << " case " << OpName << ": {\n";
1949 // Keep track of whether we see a pattern that has an iPtr result.
1950 bool HasPtrPattern = false;
1951 bool HasDefaultPattern = false;
1953 OS << " switch (NVT) {\n";
1954 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1955 std::string &VTStr = OpVTs[i];
1956 if (VTStr.empty()) {
1957 HasDefaultPattern = true;
1961 // If this is a match on iPTR: don't emit it directly, we need special
1963 if (VTStr == "_iPTR") {
1964 HasPtrPattern = true;
1967 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1968 << " return Select_" << getLegalCName(OpName)
1969 << VTStr << "(N);\n";
1971 OS << " default:\n";
1973 // If there is an iPTR result version of this pattern, emit it here.
1974 if (HasPtrPattern) {
1975 OS << " if (NVT == TLI.getPointerTy())\n";
1976 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1978 if (HasDefaultPattern) {
1979 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1987 OS << " } // end of big switch.\n\n"
1988 << " cerr << \"Cannot yet select: \";\n"
1989 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1990 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1991 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1992 << " N.Val->dump(CurDAG);\n"
1994 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1995 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1996 << " cerr << \"intrinsic %\"<< "
1997 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1999 << " cerr << '\\n';\n"
2001 << " return NULL;\n"
2005 void DAGISelEmitter::run(std::ostream &OS) {
2006 EmitSourceFileHeader("DAG Instruction Selector for the " +
2007 CGP.getTargetInfo().getName() + " target", OS);
2009 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2010 << "// *** instruction selector class. These functions are really "
2013 OS << "// Instruction selector priority queue:\n"
2014 << "std::vector<SDNode*> ISelQueue;\n";
2015 OS << "/// Keep track of nodes which have already been added to queue.\n"
2016 << "unsigned char *ISelQueued;\n";
2017 OS << "/// Keep track of nodes which have already been selected.\n"
2018 << "unsigned char *ISelSelected;\n";
2021 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
2022 OS << "/// not reach Op.\n";
2023 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
2024 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
2025 OS << " return true;\n";
2026 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
2027 OS << " return false;\n";
2028 OS << " else if (Chain->getNumOperands() > 0) {\n";
2029 OS << " SDOperand C0 = Chain->getOperand(0);\n";
2030 OS << " if (C0.getValueType() == MVT::Other)\n";
2031 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
2033 OS << " return true;\n";
2036 OS << "/// Sorting functions for the selection queue.\n"
2037 << "struct isel_sort : public std::binary_function"
2038 << "<SDNode*, SDNode*, bool> {\n"
2039 << " bool operator()(const SDNode* left, const SDNode* right) "
2041 << " return (left->getNodeId() > right->getNodeId());\n"
2045 OS << "inline void setQueued(int Id) {\n";
2046 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
2048 OS << "inline bool isQueued(int Id) {\n";
2049 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
2051 OS << "inline void setSelected(int Id) {\n";
2052 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
2054 OS << "inline bool isSelected(int Id) {\n";
2055 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
2058 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
2059 OS << " int Id = N.Val->getNodeId();\n";
2060 OS << " if (Id != -1 && !isQueued(Id)) {\n";
2061 OS << " ISelQueue.push_back(N.Val);\n";
2062 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2063 OS << " setQueued(Id);\n";
2068 OS << "class VISIBILITY_HIDDEN ISelQueueUpdater :\n";
2069 OS << " public SelectionDAG::DAGUpdateListener {\n";
2070 OS << " std::vector<SDNode*> &ISelQueue;\n";
2071 OS << " bool HadDelete;\n";
2073 OS << " ISelQueueUpdater(std::vector<SDNode*> &isq)\n";
2074 OS << " : ISelQueue(isq), HadDelete(false) {}\n";
2076 OS << " bool hadDelete() const { return HadDelete; }\n";
2078 OS << " virtual void NodeDeleted(SDNode *N) {\n";
2079 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(),";
2080 OS << " N),\n ISelQueue.end());\n";
2081 OS << " HadDelete = true;\n";
2084 OS << " // Ignore updates.\n";
2085 OS << " virtual void NodeUpdated(SDNode *N) {}\n";
2088 OS << "inline void UpdateQueue(const ISelQueueUpdater &ISQU) {\n";
2089 OS << " if (ISQU.hadDelete())\n";
2090 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(),isel_sort());\n";
2093 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
2094 OS << " ISelQueueUpdater ISQU(ISelQueue);\n";
2095 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISQU);\n";
2096 OS << " setSelected(F.Val->getNodeId());\n";
2097 OS << " UpdateQueue(ISQU);\n";
2099 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
2100 OS << " unsigned FNumVals = F->getNumValues();\n";
2101 OS << " unsigned TNumVals = T->getNumValues();\n";
2102 OS << " ISelQueueUpdater ISQU(ISelQueue);\n";
2103 OS << " if (FNumVals != TNumVals) {\n";
2104 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2106 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
2107 << "SDOperand(T, i), &ISQU);\n";
2108 OS << " } else {\n";
2109 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISQU);\n";
2111 OS << " setSelected(F->getNodeId());\n";
2112 OS << " UpdateQueue(ISQU);\n";
2115 OS << "// SelectRoot - Top level entry to DAG isel.\n";
2116 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2117 OS << " SelectRootInit();\n";
2118 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2119 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2120 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2121 OS << " memset(ISelQueued, 0, NumBytes);\n";
2122 OS << " memset(ISelSelected, 0, NumBytes);\n";
2124 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2125 << " // a reference to the root node, preventing it from being deleted,\n"
2126 << " // and tracking any changes of the root.\n"
2127 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2128 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2129 OS << " while (!ISelQueue.empty()) {\n";
2130 OS << " SDNode *Node = ISelQueue.front();\n";
2131 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2132 OS << " ISelQueue.pop_back();\n";
2133 OS << " if (!isSelected(Node->getNodeId())) {\n";
2134 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2135 OS << " if (ResNode != Node) {\n";
2136 OS << " if (ResNode)\n";
2137 OS << " ReplaceUses(Node, ResNode);\n";
2138 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2139 OS << " ISelQueueUpdater ISQU(ISelQueue);\n";
2140 OS << " CurDAG->RemoveDeadNode(Node, &ISQU);\n";
2141 OS << " UpdateQueue(ISQU);\n";
2147 OS << " delete[] ISelQueued;\n";
2148 OS << " ISelQueued = NULL;\n";
2149 OS << " delete[] ISelSelected;\n";
2150 OS << " ISelSelected = NULL;\n";
2151 OS << " return Dummy.getValue();\n";
2154 EmitNodeTransforms(OS);
2155 EmitPredicateFunctions(OS);
2157 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2158 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2160 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2161 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2165 // At this point, we have full information about the 'Patterns' we need to
2166 // parse, both implicitly from instructions as well as from explicit pattern
2167 // definitions. Emit the resultant instruction selector.
2168 EmitInstructionSelector(OS);