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 /// GeneratedCode - This is the buffer that we emit code to. The first int
317 /// indicates whether this is an exit predicate (something that should be
318 /// tested, and if true, the match fails) [when 1], or normal code to emit
319 /// [when 0], or initialization code to emit [when 2].
320 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
321 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
322 /// the set of patterns for each top-level opcode.
323 std::set<std::string> &GeneratedDecl;
324 /// TargetOpcodes - The target specific opcodes used by the resulting
326 std::vector<std::string> &TargetOpcodes;
327 std::vector<std::string> &TargetVTs;
329 std::string ChainName;
334 void emitCheck(const std::string &S) {
336 GeneratedCode.push_back(std::make_pair(1, S));
338 void emitCode(const std::string &S) {
340 GeneratedCode.push_back(std::make_pair(0, S));
342 void emitInit(const std::string &S) {
344 GeneratedCode.push_back(std::make_pair(2, S));
346 void emitDecl(const std::string &S) {
347 assert(!S.empty() && "Invalid declaration");
348 GeneratedDecl.insert(S);
350 void emitOpcode(const std::string &Opc) {
351 TargetOpcodes.push_back(Opc);
354 void emitVT(const std::string &VT) {
355 TargetVTs.push_back(VT);
359 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
360 TreePatternNode *pattern, TreePatternNode *instr,
361 std::vector<std::pair<unsigned, std::string> > &gc,
362 std::set<std::string> &gd,
363 std::vector<std::string> &to,
364 std::vector<std::string> &tv)
365 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
366 GeneratedCode(gc), GeneratedDecl(gd),
367 TargetOpcodes(to), TargetVTs(tv),
368 TmpNo(0), OpcNo(0), VTNo(0) {}
370 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
371 /// if the match fails. At this point, we already know that the opcode for N
372 /// matches, and the SDNode for the result has the RootName specified name.
373 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
374 const std::string &RootName, const std::string &ChainSuffix,
376 bool isRoot = (P == NULL);
377 // Emit instruction predicates. Each predicate is just a string for now.
379 std::string PredicateCheck;
380 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
381 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
382 Record *Def = Pred->getDef();
383 if (!Def->isSubClassOf("Predicate")) {
387 assert(0 && "Unknown predicate type!");
389 if (!PredicateCheck.empty())
390 PredicateCheck += " && ";
391 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
395 emitCheck(PredicateCheck);
399 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
400 emitCheck("cast<ConstantSDNode>(" + RootName +
401 ")->getSignExtended() == " + itostr(II->getValue()));
403 } else if (!NodeIsComplexPattern(N)) {
404 assert(0 && "Cannot match this as a leaf value!");
409 // If this node has a name associated with it, capture it in VariableMap. If
410 // we already saw this in the pattern, emit code to verify dagness.
411 if (!N->getName().empty()) {
412 std::string &VarMapEntry = VariableMap[N->getName()];
413 if (VarMapEntry.empty()) {
414 VarMapEntry = RootName;
416 // If we get here, this is a second reference to a specific name. Since
417 // we already have checked that the first reference is valid, we don't
418 // have to recursively match it, just check that it's the same as the
419 // previously named thing.
420 emitCheck(VarMapEntry + " == " + RootName);
425 OperatorMap[N->getName()] = N->getOperator();
429 // Emit code to load the child nodes and match their contents recursively.
431 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
432 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
433 bool EmittedUseCheck = false;
438 // Multiple uses of actual result?
439 emitCheck(RootName + ".hasOneUse()");
440 EmittedUseCheck = true;
442 // If the immediate use can somehow reach this node through another
443 // path, then can't fold it either or it will create a cycle.
444 // e.g. In the following diagram, XX can reach ld through YY. If
445 // ld is folded into XX, then YY is both a predecessor and a successor
455 bool NeedCheck = false;
459 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
461 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
462 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
463 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
464 PInfo.getNumOperands() > 1 ||
465 PInfo.hasProperty(SDNPHasChain) ||
466 PInfo.hasProperty(SDNPInFlag) ||
467 PInfo.hasProperty(SDNPOptInFlag);
471 std::string ParentName(RootName.begin(), RootName.end()-1);
472 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
480 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
481 "IsChainCompatible(" + ChainName + ".Val, " +
482 RootName + ".Val))");
483 OrigChains.push_back(std::make_pair(ChainName, RootName));
486 ChainName = "Chain" + ChainSuffix;
487 emitInit("SDOperand " + ChainName + " = " + RootName +
492 // Don't fold any node which reads or writes a flag and has multiple uses.
493 // FIXME: We really need to separate the concepts of flag and "glue". Those
494 // real flag results, e.g. X86CMP output, can have multiple uses.
495 // FIXME: If the optional incoming flag does not exist. Then it is ok to
498 (PatternHasProperty(N, SDNPInFlag, CGP) ||
499 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
500 PatternHasProperty(N, SDNPOutFlag, CGP))) {
501 if (!EmittedUseCheck) {
502 // Multiple uses of actual result?
503 emitCheck(RootName + ".hasOneUse()");
507 // If there is a node predicate for this, emit the call.
508 if (!N->getPredicateFn().empty())
509 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
512 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
513 // a constant without a predicate fn that has more that one bit set, handle
514 // this as a special case. This is usually for targets that have special
515 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
516 // handling stuff). Using these instructions is often far more efficient
517 // than materializing the constant. Unfortunately, both the instcombiner
518 // and the dag combiner can often infer that bits are dead, and thus drop
519 // them from the mask in the dag. For example, it might turn 'AND X, 255'
520 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
523 (N->getOperator()->getName() == "and" ||
524 N->getOperator()->getName() == "or") &&
525 N->getChild(1)->isLeaf() &&
526 N->getChild(1)->getPredicateFn().empty()) {
527 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
528 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
529 emitInit("SDOperand " + RootName + "0" + " = " +
530 RootName + ".getOperand(" + utostr(0) + ");");
531 emitInit("SDOperand " + RootName + "1" + " = " +
532 RootName + ".getOperand(" + utostr(1) + ");");
534 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
535 const char *MaskPredicate = N->getOperator()->getName() == "or"
536 ? "CheckOrMask(" : "CheckAndMask(";
537 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
538 RootName + "1), " + itostr(II->getValue()) + ")");
540 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
541 ChainSuffix + utostr(0), FoundChain);
547 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
548 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
549 RootName + ".getOperand(" +utostr(OpNo) + ");");
551 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
552 ChainSuffix + utostr(OpNo), FoundChain);
555 // Handle cases when root is a complex pattern.
556 const ComplexPattern *CP;
557 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
558 std::string Fn = CP->getSelectFunc();
559 unsigned NumOps = CP->getNumOperands();
560 for (unsigned i = 0; i < NumOps; ++i) {
561 emitDecl("CPTmp" + utostr(i));
562 emitCode("SDOperand CPTmp" + utostr(i) + ";");
564 if (CP->hasProperty(SDNPHasChain)) {
565 emitDecl("CPInChain");
566 emitDecl("Chain" + ChainSuffix);
567 emitCode("SDOperand CPInChain;");
568 emitCode("SDOperand Chain" + ChainSuffix + ";");
571 std::string Code = Fn + "(" + RootName + ", " + RootName;
572 for (unsigned i = 0; i < NumOps; i++)
573 Code += ", CPTmp" + utostr(i);
574 if (CP->hasProperty(SDNPHasChain)) {
575 ChainName = "Chain" + ChainSuffix;
576 Code += ", CPInChain, Chain" + ChainSuffix;
578 emitCheck(Code + ")");
582 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
583 const std::string &RootName,
584 const std::string &ParentRootName,
585 const std::string &ChainSuffix, bool &FoundChain) {
586 if (!Child->isLeaf()) {
587 // If it's not a leaf, recursively match.
588 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
589 emitCheck(RootName + ".getOpcode() == " +
590 CInfo.getEnumName());
591 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
592 bool HasChain = false;
593 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
595 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
597 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
598 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
599 "Pattern folded multiple nodes which produce flags?");
600 FoldedFlag = std::make_pair(RootName,
601 CInfo.getNumResults() + (unsigned)HasChain);
604 // If this child has a name associated with it, capture it in VarMap. If
605 // we already saw this in the pattern, emit code to verify dagness.
606 if (!Child->getName().empty()) {
607 std::string &VarMapEntry = VariableMap[Child->getName()];
608 if (VarMapEntry.empty()) {
609 VarMapEntry = RootName;
611 // If we get here, this is a second reference to a specific name.
612 // Since we already have checked that the first reference is valid,
613 // we don't have to recursively match it, just check that it's the
614 // same as the previously named thing.
615 emitCheck(VarMapEntry + " == " + RootName);
616 Duplicates.insert(RootName);
621 // Handle leaves of various types.
622 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
623 Record *LeafRec = DI->getDef();
624 if (LeafRec->isSubClassOf("RegisterClass") ||
625 LeafRec->getName() == "ptr_rc") {
626 // Handle register references. Nothing to do here.
627 } else if (LeafRec->isSubClassOf("Register")) {
628 // Handle register references.
629 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
630 // Handle complex pattern.
631 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
632 std::string Fn = CP->getSelectFunc();
633 unsigned NumOps = CP->getNumOperands();
634 for (unsigned i = 0; i < NumOps; ++i) {
635 emitDecl("CPTmp" + utostr(i));
636 emitCode("SDOperand CPTmp" + utostr(i) + ";");
638 if (CP->hasProperty(SDNPHasChain)) {
639 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
640 FoldedChains.push_back(std::make_pair("CPInChain",
641 PInfo.getNumResults()));
642 ChainName = "Chain" + ChainSuffix;
643 emitDecl("CPInChain");
645 emitCode("SDOperand CPInChain;");
646 emitCode("SDOperand " + ChainName + ";");
649 std::string Code = Fn + "(";
650 if (CP->hasAttribute(CPAttrParentAsRoot)) {
651 Code += ParentRootName + ", ";
655 if (CP->hasProperty(SDNPHasChain)) {
656 std::string ParentName(RootName.begin(), RootName.end()-1);
657 Code += ParentName + ", ";
660 for (unsigned i = 0; i < NumOps; i++)
661 Code += ", CPTmp" + utostr(i);
662 if (CP->hasProperty(SDNPHasChain))
663 Code += ", CPInChain, Chain" + ChainSuffix;
664 emitCheck(Code + ")");
665 } else if (LeafRec->getName() == "srcvalue") {
666 // Place holder for SRCVALUE nodes. Nothing to do here.
667 } else if (LeafRec->isSubClassOf("ValueType")) {
668 // Make sure this is the specified value type.
669 emitCheck("cast<VTSDNode>(" + RootName +
670 ")->getVT() == MVT::" + LeafRec->getName());
671 } else if (LeafRec->isSubClassOf("CondCode")) {
672 // Make sure this is the specified cond code.
673 emitCheck("cast<CondCodeSDNode>(" + RootName +
674 ")->get() == ISD::" + LeafRec->getName());
680 assert(0 && "Unknown leaf type!");
683 // If there is a node predicate for this, emit the call.
684 if (!Child->getPredicateFn().empty())
685 emitCheck(Child->getPredicateFn() + "(" + RootName +
687 } else if (IntInit *II =
688 dynamic_cast<IntInit*>(Child->getLeafValue())) {
689 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
690 unsigned CTmp = TmpNo++;
691 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
692 RootName + ")->getSignExtended();");
694 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
699 assert(0 && "Unknown leaf type!");
704 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
705 /// we actually have to build a DAG!
706 std::vector<std::string>
707 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
708 bool InFlagDecled, bool ResNodeDecled,
709 bool LikeLeaf = false, bool isRoot = false) {
710 // List of arguments of getTargetNode() or SelectNodeTo().
711 std::vector<std::string> NodeOps;
712 // This is something selected from the pattern we matched.
713 if (!N->getName().empty()) {
714 const std::string &VarName = N->getName();
715 std::string Val = VariableMap[VarName];
716 bool ModifiedVal = false;
717 assert(!Val.empty() &&
718 "Variable referenced but not defined and not caught earlier!");
719 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
720 // Already selected this operand, just return the tmpval.
721 NodeOps.push_back(Val);
725 const ComplexPattern *CP;
726 unsigned ResNo = TmpNo++;
727 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
728 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
729 std::string CastType;
730 std::string TmpVar = "Tmp" + utostr(ResNo);
731 switch (N->getTypeNum(0)) {
733 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
734 << " type as an immediate constant. Aborting\n";
736 case MVT::i1: CastType = "bool"; break;
737 case MVT::i8: CastType = "unsigned char"; break;
738 case MVT::i16: CastType = "unsigned short"; break;
739 case MVT::i32: CastType = "unsigned"; break;
740 case MVT::i64: CastType = "uint64_t"; break;
742 emitCode("SDOperand " + TmpVar +
743 " = CurDAG->getTargetConstant(((" + CastType +
744 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
745 getEnumName(N->getTypeNum(0)) + ");");
746 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
747 // value if used multiple times by this pattern result.
750 NodeOps.push_back(Val);
751 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
752 Record *Op = OperatorMap[N->getName()];
753 // Transform ExternalSymbol to TargetExternalSymbol
754 if (Op && Op->getName() == "externalsym") {
755 std::string TmpVar = "Tmp"+utostr(ResNo);
756 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
757 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
758 Val + ")->getSymbol(), " +
759 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() && (N->getOperator()->getName() == "tglobaladdr"
767 || N->getOperator()->getName() == "tglobaltlsaddr")) {
768 Record *Op = OperatorMap[N->getName()];
769 // Transform GlobalAddress to TargetGlobalAddress
770 if (Op && (Op->getName() == "globaladdr" ||
771 Op->getName() == "globaltlsaddr")) {
772 std::string TmpVar = "Tmp" + utostr(ResNo);
773 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
774 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
775 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
777 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
778 // this value if used multiple times by this pattern result.
782 NodeOps.push_back(Val);
783 } else if (!N->isLeaf()
784 && (N->getOperator()->getName() == "texternalsym"
785 || N->getOperator()->getName() == "tconstpool")) {
786 // Do not rewrite the variable name, since we don't generate a new
788 NodeOps.push_back(Val);
789 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
790 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
791 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
792 NodeOps.push_back("CPTmp" + utostr(i));
795 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
796 // node even if it isn't one. Don't select it.
798 emitCode("AddToISelQueue(" + Val + ");");
799 if (isRoot && N->isLeaf()) {
800 emitCode("ReplaceUses(N, " + Val + ");");
801 emitCode("return NULL;");
804 NodeOps.push_back(Val);
808 VariableMap[VarName] = Val;
813 // If this is an explicit register reference, handle it.
814 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
815 unsigned ResNo = TmpNo++;
816 if (DI->getDef()->isSubClassOf("Register")) {
817 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
818 getQualifiedName(DI->getDef()) + ", " +
819 getEnumName(N->getTypeNum(0)) + ");");
820 NodeOps.push_back("Tmp" + utostr(ResNo));
822 } else if (DI->getDef()->getName() == "zero_reg") {
823 emitCode("SDOperand Tmp" + utostr(ResNo) +
824 " = CurDAG->getRegister(0, " +
825 getEnumName(N->getTypeNum(0)) + ");");
826 NodeOps.push_back("Tmp" + utostr(ResNo));
829 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
830 unsigned ResNo = TmpNo++;
831 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
832 emitCode("SDOperand Tmp" + utostr(ResNo) +
833 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
834 ", " + getEnumName(N->getTypeNum(0)) + ");");
835 NodeOps.push_back("Tmp" + utostr(ResNo));
842 assert(0 && "Unknown leaf type!");
846 Record *Op = N->getOperator();
847 if (Op->isSubClassOf("Instruction")) {
848 const CodeGenTarget &CGT = CGP.getTargetInfo();
849 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
850 const DAGInstruction &Inst = CGP.getInstruction(Op);
851 const TreePattern *InstPat = Inst.getPattern();
852 // FIXME: Assume actual pattern comes before "implicit".
853 TreePatternNode *InstPatNode =
854 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
855 : (InstPat ? InstPat->getTree(0) : NULL);
856 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
857 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
859 bool HasVarOps = isRoot && II.isVariadic;
860 // FIXME: fix how we deal with physical register operands.
861 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
862 bool HasImpResults = isRoot && DstRegs.size() > 0;
863 bool NodeHasOptInFlag = isRoot &&
864 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
865 bool NodeHasInFlag = isRoot &&
866 PatternHasProperty(Pattern, SDNPInFlag, CGP);
867 bool NodeHasOutFlag = isRoot &&
868 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
869 bool NodeHasChain = InstPatNode &&
870 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
871 bool InputHasChain = isRoot &&
872 NodeHasProperty(Pattern, SDNPHasChain, CGP);
873 unsigned NumResults = Inst.getNumResults();
874 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
876 if (NodeHasOptInFlag) {
877 emitCode("bool HasInFlag = "
878 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
881 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
883 // How many results is this pattern expected to produce?
884 unsigned NumPatResults = 0;
885 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
886 MVT::ValueType VT = Pattern->getTypeNum(i);
887 if (VT != MVT::isVoid && VT != MVT::Flag)
891 if (OrigChains.size() > 0) {
892 // The original input chain is being ignored. If it is not just
893 // pointing to the op that's being folded, we should create a
894 // TokenFactor with it and the chain of the folded op as the new chain.
895 // We could potentially be doing multiple levels of folding, in that
896 // case, the TokenFactor can have more operands.
897 emitCode("SmallVector<SDOperand, 8> InChains;");
898 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
899 emitCode("if (" + OrigChains[i].first + ".Val != " +
900 OrigChains[i].second + ".Val) {");
901 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
902 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
905 emitCode("AddToISelQueue(" + ChainName + ");");
906 emitCode("InChains.push_back(" + ChainName + ");");
907 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
908 "&InChains[0], InChains.size());");
911 // Loop over all of the operands of the instruction pattern, emitting code
912 // to fill them all in. The node 'N' usually has number children equal to
913 // the number of input operands of the instruction. However, in cases
914 // where there are predicate operands for an instruction, we need to fill
915 // in the 'execute always' values. Match up the node operands to the
916 // instruction operands to do this.
917 std::vector<std::string> AllOps;
918 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
919 for (unsigned ChildNo = 0, InstOpNo = NumResults;
920 InstOpNo != II.OperandList.size(); ++InstOpNo) {
921 std::vector<std::string> Ops;
923 // If this is a normal operand or a predicate operand without
924 // 'execute always', emit it.
925 Record *OperandNode = II.OperandList[InstOpNo].Rec;
926 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
927 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
928 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
929 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
930 InFlagDecled, ResNodeDecled);
931 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
934 // Otherwise, this is a predicate or optional def operand, emit the
935 // 'default ops' operands.
936 const DAGDefaultOperand &DefaultOp =
937 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
938 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
939 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
940 InFlagDecled, ResNodeDecled);
941 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
942 NumEAInputs += Ops.size();
947 // Emit all the chain and CopyToReg stuff.
948 bool ChainEmitted = NodeHasChain;
950 emitCode("AddToISelQueue(" + ChainName + ");");
951 if (NodeHasInFlag || HasImpInputs)
952 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
953 InFlagDecled, ResNodeDecled, true);
954 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
956 emitCode("SDOperand InFlag(0, 0);");
959 if (NodeHasOptInFlag) {
960 emitCode("if (HasInFlag) {");
961 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
962 emitCode(" AddToISelQueue(InFlag);");
967 unsigned ResNo = TmpNo++;
968 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
969 NodeHasOptInFlag || HasImpResults) {
972 std::string NodeName;
974 NodeName = "Tmp" + utostr(ResNo);
975 Code2 = "SDOperand " + NodeName + "(";
977 NodeName = "ResNode";
978 if (!ResNodeDecled) {
979 Code2 = "SDNode *" + NodeName + " = ";
980 ResNodeDecled = true;
982 Code2 = NodeName + " = ";
985 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
986 unsigned OpsNo = OpcNo;
987 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
989 // Output order: results, chain, flags
991 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
992 Code += ", VT" + utostr(VTNo);
993 emitVT(getEnumName(N->getTypeNum(0)));
995 // Add types for implicit results in physical registers, scheduler will
996 // care of adding copyfromreg nodes.
997 for (unsigned i = 0; i < NumDstRegs; i++) {
998 Record *RR = DstRegs[i];
999 if (RR->isSubClassOf("Register")) {
1000 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1001 Code += ", " + getEnumName(RVT);
1005 Code += ", MVT::Other";
1007 Code += ", MVT::Flag";
1009 // Figure out how many fixed inputs the node has. This is important to
1010 // know which inputs are the variable ones if present.
1011 unsigned NumInputs = AllOps.size();
1012 NumInputs += NodeHasChain;
1016 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1017 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1022 // Figure out whether any operands at the end of the op list are not
1023 // part of the variable section.
1024 std::string EndAdjust;
1025 if (NodeHasInFlag || HasImpInputs)
1026 EndAdjust = "-1"; // Always has one flag.
1027 else if (NodeHasOptInFlag)
1028 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1030 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1031 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1033 emitCode(" AddToISelQueue(N.getOperand(i));");
1034 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1040 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1042 AllOps.push_back(ChainName);
1046 if (NodeHasInFlag || HasImpInputs)
1047 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1048 else if (NodeHasOptInFlag) {
1049 emitCode("if (HasInFlag)");
1050 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1052 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1054 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1055 AllOps.push_back("InFlag");
1057 unsigned NumOps = AllOps.size();
1059 if (!NodeHasOptInFlag && NumOps < 4) {
1060 for (unsigned i = 0; i != NumOps; ++i)
1061 Code += ", " + AllOps[i];
1063 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1064 for (unsigned i = 0; i != NumOps; ++i) {
1065 OpsCode += AllOps[i];
1069 emitCode(OpsCode + " };");
1070 Code += ", Ops" + utostr(OpsNo) + ", ";
1071 if (NodeHasOptInFlag) {
1072 Code += "HasInFlag ? ";
1073 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1075 Code += utostr(NumOps);
1081 emitCode(Code2 + Code + ");");
1084 // Remember which op produces the chain.
1086 emitCode(ChainName + " = SDOperand(" + NodeName +
1087 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
1089 emitCode(ChainName + " = SDOperand(" + NodeName +
1090 ", " + utostr(NumResults+NumDstRegs) + ");");
1093 NodeOps.push_back("Tmp" + utostr(ResNo));
1097 bool NeedReplace = false;
1098 if (NodeHasOutFlag) {
1099 if (!InFlagDecled) {
1100 emitCode("SDOperand InFlag(ResNode, " +
1101 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1102 InFlagDecled = true;
1104 emitCode("InFlag = SDOperand(ResNode, " +
1105 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1108 if (FoldedChains.size() > 0) {
1110 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1111 emitCode("ReplaceUses(SDOperand(" +
1112 FoldedChains[j].first + ".Val, " +
1113 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1114 utostr(NumResults+NumDstRegs) + "));");
1118 if (NodeHasOutFlag) {
1119 if (FoldedFlag.first != "") {
1120 emitCode("ReplaceUses(SDOperand(" + FoldedFlag.first + ".Val, " +
1121 utostr(FoldedFlag.second) + "), InFlag);");
1123 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1124 emitCode("ReplaceUses(SDOperand(N.Val, " +
1125 utostr(NumPatResults + (unsigned)InputHasChain)
1131 if (NeedReplace && InputHasChain)
1132 emitCode("ReplaceUses(SDOperand(N.Val, " +
1133 utostr(NumPatResults) + "), SDOperand(" + ChainName
1134 + ".Val, " + ChainName + ".ResNo" + "));");
1136 // User does not expect the instruction would produce a chain!
1137 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1139 } else if (InputHasChain && !NodeHasChain) {
1140 // One of the inner node produces a chain.
1142 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1143 "), SDOperand(ResNode, N.ResNo-1));");
1144 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1145 "), " + ChainName + ");");
1148 emitCode("return ResNode;");
1150 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1152 if (N->getTypeNum(0) != MVT::isVoid)
1153 Code += ", VT" + utostr(VTNo);
1155 Code += ", MVT::Flag";
1157 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1158 AllOps.push_back("InFlag");
1160 unsigned NumOps = AllOps.size();
1162 if (!NodeHasOptInFlag && NumOps < 4) {
1163 for (unsigned i = 0; i != NumOps; ++i)
1164 Code += ", " + AllOps[i];
1166 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1167 for (unsigned i = 0; i != NumOps; ++i) {
1168 OpsCode += AllOps[i];
1172 emitCode(OpsCode + " };");
1173 Code += ", Ops" + utostr(OpcNo) + ", ";
1174 Code += utostr(NumOps);
1177 emitCode(Code + ");");
1178 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1179 if (N->getTypeNum(0) != MVT::isVoid)
1180 emitVT(getEnumName(N->getTypeNum(0)));
1184 } else if (Op->isSubClassOf("SDNodeXForm")) {
1185 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1186 // PatLeaf node - the operand may or may not be a leaf node. But it should
1188 std::vector<std::string> Ops =
1189 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1190 ResNodeDecled, true);
1191 unsigned ResNo = TmpNo++;
1192 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1193 + "(" + Ops.back() + ".Val);");
1194 NodeOps.push_back("Tmp" + utostr(ResNo));
1196 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1201 throw std::string("Unknown node in result pattern!");
1205 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1206 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1207 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1208 /// for, this returns true otherwise false if Pat has all types.
1209 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1210 const std::string &Prefix, bool isRoot = false) {
1212 if (Pat->getExtTypes() != Other->getExtTypes()) {
1213 // Move a type over from 'other' to 'pat'.
1214 Pat->setTypes(Other->getExtTypes());
1215 // The top level node type is checked outside of the select function.
1217 emitCheck(Prefix + ".Val->getValueType(0) == " +
1218 getName(Pat->getTypeNum(0)));
1223 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1224 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1225 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1226 Prefix + utostr(OpNo)))
1232 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1234 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1235 bool &ChainEmitted, bool &InFlagDecled,
1236 bool &ResNodeDecled, bool isRoot = false) {
1237 const CodeGenTarget &T = CGP.getTargetInfo();
1239 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1240 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1241 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1242 TreePatternNode *Child = N->getChild(i);
1243 if (!Child->isLeaf()) {
1244 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1245 InFlagDecled, ResNodeDecled);
1247 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1248 if (!Child->getName().empty()) {
1249 std::string Name = RootName + utostr(OpNo);
1250 if (Duplicates.find(Name) != Duplicates.end())
1251 // A duplicate! Do not emit a copy for this node.
1255 Record *RR = DI->getDef();
1256 if (RR->isSubClassOf("Register")) {
1257 MVT::ValueType RVT = getRegisterValueType(RR, T);
1258 if (RVT == MVT::Flag) {
1259 if (!InFlagDecled) {
1260 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1261 InFlagDecled = true;
1263 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1264 emitCode("AddToISelQueue(InFlag);");
1266 if (!ChainEmitted) {
1267 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1268 ChainName = "Chain";
1269 ChainEmitted = true;
1271 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1272 if (!InFlagDecled) {
1273 emitCode("SDOperand InFlag(0, 0);");
1274 InFlagDecled = true;
1276 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1277 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1278 ", " + getQualifiedName(RR) +
1279 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1280 ResNodeDecled = true;
1281 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1282 emitCode("InFlag = SDOperand(ResNode, 1);");
1290 if (!InFlagDecled) {
1291 emitCode("SDOperand InFlag = " + RootName +
1292 ".getOperand(" + utostr(OpNo) + ");");
1293 InFlagDecled = true;
1295 emitCode("InFlag = " + RootName +
1296 ".getOperand(" + utostr(OpNo) + ");");
1297 emitCode("AddToISelQueue(InFlag);");
1302 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1303 /// stream to match the pattern, and generate the code for the match if it
1304 /// succeeds. Returns true if the pattern is not guaranteed to match.
1305 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1306 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1307 std::set<std::string> &GeneratedDecl,
1308 std::vector<std::string> &TargetOpcodes,
1309 std::vector<std::string> &TargetVTs) {
1310 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1311 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1312 GeneratedCode, GeneratedDecl,
1313 TargetOpcodes, TargetVTs);
1315 // Emit the matcher, capturing named arguments in VariableMap.
1316 bool FoundChain = false;
1317 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1319 // TP - Get *SOME* tree pattern, we don't care which.
1320 TreePattern &TP = *CGP.pf_begin()->second;
1322 // At this point, we know that we structurally match the pattern, but the
1323 // types of the nodes may not match. Figure out the fewest number of type
1324 // comparisons we need to emit. For example, if there is only one integer
1325 // type supported by a target, there should be no type comparisons at all for
1326 // integer patterns!
1328 // To figure out the fewest number of type checks needed, clone the pattern,
1329 // remove the types, then perform type inference on the pattern as a whole.
1330 // If there are unresolved types, emit an explicit check for those types,
1331 // apply the type to the tree, then rerun type inference. Iterate until all
1332 // types are resolved.
1334 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1335 RemoveAllTypes(Pat);
1338 // Resolve/propagate as many types as possible.
1340 bool MadeChange = true;
1342 MadeChange = Pat->ApplyTypeConstraints(TP,
1343 true/*Ignore reg constraints*/);
1345 assert(0 && "Error: could not find consistent types for something we"
1346 " already decided was ok!");
1350 // Insert a check for an unresolved type and add it to the tree. If we find
1351 // an unresolved type to add a check for, this returns true and we iterate,
1352 // otherwise we are done.
1353 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1355 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1356 false, false, false, true);
1360 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1361 /// a line causes any of them to be empty, remove them and return true when
1363 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1364 std::vector<std::pair<unsigned, std::string> > > >
1366 bool ErasedPatterns = false;
1367 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1368 Patterns[i].second.pop_back();
1369 if (Patterns[i].second.empty()) {
1370 Patterns.erase(Patterns.begin()+i);
1372 ErasedPatterns = true;
1375 return ErasedPatterns;
1378 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1379 /// code together between the patterns.
1380 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1381 std::vector<std::pair<unsigned, std::string> > > >
1382 &Patterns, unsigned Indent,
1384 typedef std::pair<unsigned, std::string> CodeLine;
1385 typedef std::vector<CodeLine> CodeList;
1386 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1388 if (Patterns.empty()) return;
1390 // Figure out how many patterns share the next code line. Explicitly copy
1391 // FirstCodeLine so that we don't invalidate a reference when changing
1393 const CodeLine FirstCodeLine = Patterns.back().second.back();
1394 unsigned LastMatch = Patterns.size()-1;
1395 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1398 // If not all patterns share this line, split the list into two pieces. The
1399 // first chunk will use this line, the second chunk won't.
1400 if (LastMatch != 0) {
1401 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1402 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1404 // FIXME: Emit braces?
1405 if (Shared.size() == 1) {
1406 const PatternToMatch &Pattern = *Shared.back().first;
1407 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1408 Pattern.getSrcPattern()->print(OS);
1409 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1410 Pattern.getDstPattern()->print(OS);
1412 unsigned AddedComplexity = Pattern.getAddedComplexity();
1413 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1414 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1416 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1418 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1420 if (FirstCodeLine.first != 1) {
1421 OS << std::string(Indent, ' ') << "{\n";
1424 EmitPatterns(Shared, Indent, OS);
1425 if (FirstCodeLine.first != 1) {
1427 OS << std::string(Indent, ' ') << "}\n";
1430 if (Other.size() == 1) {
1431 const PatternToMatch &Pattern = *Other.back().first;
1432 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1433 Pattern.getSrcPattern()->print(OS);
1434 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1435 Pattern.getDstPattern()->print(OS);
1437 unsigned AddedComplexity = Pattern.getAddedComplexity();
1438 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1439 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1441 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1443 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1445 EmitPatterns(Other, Indent, OS);
1449 // Remove this code from all of the patterns that share it.
1450 bool ErasedPatterns = EraseCodeLine(Patterns);
1452 bool isPredicate = FirstCodeLine.first == 1;
1454 // Otherwise, every pattern in the list has this line. Emit it.
1457 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1459 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1461 // If the next code line is another predicate, and if all of the pattern
1462 // in this group share the same next line, emit it inline now. Do this
1463 // until we run out of common predicates.
1464 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1465 // Check that all of fhe patterns in Patterns end with the same predicate.
1466 bool AllEndWithSamePredicate = true;
1467 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1468 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1469 AllEndWithSamePredicate = false;
1472 // If all of the predicates aren't the same, we can't share them.
1473 if (!AllEndWithSamePredicate) break;
1475 // Otherwise we can. Emit it shared now.
1476 OS << " &&\n" << std::string(Indent+4, ' ')
1477 << Patterns.back().second.back().second;
1478 ErasedPatterns = EraseCodeLine(Patterns);
1485 EmitPatterns(Patterns, Indent, OS);
1488 OS << std::string(Indent-2, ' ') << "}\n";
1491 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
1492 return CGP.getSDNodeInfo(Op).getEnumName();
1495 static std::string getLegalCName(std::string OpName) {
1496 std::string::size_type pos = OpName.find("::");
1497 if (pos != std::string::npos)
1498 OpName.replace(pos, 2, "_");
1502 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1503 const CodeGenTarget &Target = CGP.getTargetInfo();
1505 // Get the namespace to insert instructions into. Make sure not to pick up
1506 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1507 // instruction or something.
1509 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1510 e = Target.inst_end(); i != e; ++i) {
1511 InstNS = i->second.Namespace;
1512 if (InstNS != "TargetInstrInfo")
1516 if (!InstNS.empty()) InstNS += "::";
1518 // Group the patterns by their top-level opcodes.
1519 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1520 // All unique target node emission functions.
1521 std::map<std::string, unsigned> EmitFunctions;
1522 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1523 E = CGP.ptm_end(); I != E; ++I) {
1524 const PatternToMatch &Pattern = *I;
1526 TreePatternNode *Node = Pattern.getSrcPattern();
1527 if (!Node->isLeaf()) {
1528 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1529 push_back(&Pattern);
1531 const ComplexPattern *CP;
1532 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1533 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1534 push_back(&Pattern);
1535 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1536 std::vector<Record*> OpNodes = CP->getRootNodes();
1537 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1538 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1539 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1543 cerr << "Unrecognized opcode '";
1545 cerr << "' on tree pattern '";
1546 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1552 // For each opcode, there might be multiple select functions, one per
1553 // ValueType of the node (or its first operand if it doesn't produce a
1554 // non-chain result.
1555 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1557 // Emit one Select_* method for each top-level opcode. We do this instead of
1558 // emitting one giant switch statement to support compilers where this will
1559 // result in the recursive functions taking less stack space.
1560 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1561 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1562 PBOI != E; ++PBOI) {
1563 const std::string &OpName = PBOI->first;
1564 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1565 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1567 // We want to emit all of the matching code now. However, we want to emit
1568 // the matches in order of minimal cost. Sort the patterns so the least
1569 // cost one is at the start.
1570 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1571 PatternSortingPredicate(CGP));
1573 // Split them into groups by type.
1574 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1575 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1576 const PatternToMatch *Pat = PatternsOfOp[i];
1577 TreePatternNode *SrcPat = Pat->getSrcPattern();
1578 MVT::ValueType VT = SrcPat->getTypeNum(0);
1579 std::map<MVT::ValueType,
1580 std::vector<const PatternToMatch*> >::iterator TI =
1581 PatternsByType.find(VT);
1582 if (TI != PatternsByType.end())
1583 TI->second.push_back(Pat);
1585 std::vector<const PatternToMatch*> PVec;
1586 PVec.push_back(Pat);
1587 PatternsByType.insert(std::make_pair(VT, PVec));
1591 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1592 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1594 MVT::ValueType OpVT = II->first;
1595 std::vector<const PatternToMatch*> &Patterns = II->second;
1596 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1597 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1599 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1600 std::vector<std::vector<std::string> > PatternOpcodes;
1601 std::vector<std::vector<std::string> > PatternVTs;
1602 std::vector<std::set<std::string> > PatternDecls;
1603 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1604 CodeList GeneratedCode;
1605 std::set<std::string> GeneratedDecl;
1606 std::vector<std::string> TargetOpcodes;
1607 std::vector<std::string> TargetVTs;
1608 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1609 TargetOpcodes, TargetVTs);
1610 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1611 PatternDecls.push_back(GeneratedDecl);
1612 PatternOpcodes.push_back(TargetOpcodes);
1613 PatternVTs.push_back(TargetVTs);
1616 // Scan the code to see if all of the patterns are reachable and if it is
1617 // possible that the last one might not match.
1618 bool mightNotMatch = true;
1619 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1620 CodeList &GeneratedCode = CodeForPatterns[i].second;
1621 mightNotMatch = false;
1623 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1624 if (GeneratedCode[j].first == 1) { // predicate.
1625 mightNotMatch = true;
1630 // If this pattern definitely matches, and if it isn't the last one, the
1631 // patterns after it CANNOT ever match. Error out.
1632 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1633 cerr << "Pattern '";
1634 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1635 cerr << "' is impossible to select!\n";
1640 // Factor target node emission code (emitted by EmitResultCode) into
1641 // separate functions. Uniquing and share them among all instruction
1642 // selection routines.
1643 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1644 CodeList &GeneratedCode = CodeForPatterns[i].second;
1645 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1646 std::vector<std::string> &TargetVTs = PatternVTs[i];
1647 std::set<std::string> Decls = PatternDecls[i];
1648 std::vector<std::string> AddedInits;
1649 int CodeSize = (int)GeneratedCode.size();
1651 for (int j = CodeSize-1; j >= 0; --j) {
1652 if (LastPred == -1 && GeneratedCode[j].first == 1)
1654 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1655 AddedInits.push_back(GeneratedCode[j].second);
1658 std::string CalleeCode = "(const SDOperand &N";
1659 std::string CallerCode = "(N";
1660 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1661 CalleeCode += ", unsigned Opc" + utostr(j);
1662 CallerCode += ", " + TargetOpcodes[j];
1664 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1665 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1666 CallerCode += ", " + TargetVTs[j];
1668 for (std::set<std::string>::iterator
1669 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1670 std::string Name = *I;
1671 CalleeCode += ", SDOperand &" + Name;
1672 CallerCode += ", " + Name;
1676 // Prevent emission routines from being inlined to reduce selection
1677 // routines stack frame sizes.
1678 CalleeCode += "DISABLE_INLINE ";
1679 CalleeCode += "{\n";
1681 for (std::vector<std::string>::const_reverse_iterator
1682 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1683 CalleeCode += " " + *I + "\n";
1685 for (int j = LastPred+1; j < CodeSize; ++j)
1686 CalleeCode += " " + GeneratedCode[j].second + "\n";
1687 for (int j = LastPred+1; j < CodeSize; ++j)
1688 GeneratedCode.pop_back();
1689 CalleeCode += "}\n";
1691 // Uniquing the emission routines.
1692 unsigned EmitFuncNum;
1693 std::map<std::string, unsigned>::iterator EFI =
1694 EmitFunctions.find(CalleeCode);
1695 if (EFI != EmitFunctions.end()) {
1696 EmitFuncNum = EFI->second;
1698 EmitFuncNum = EmitFunctions.size();
1699 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1700 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1703 // Replace the emission code within selection routines with calls to the
1704 // emission functions.
1705 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1706 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1710 std::string OpVTStr;
1711 if (OpVT == MVT::iPTR) {
1713 } else if (OpVT == MVT::isVoid) {
1714 // Nodes with a void result actually have a first result type of either
1715 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1716 // void to this case, we handle it specially here.
1718 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1720 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1721 OpcodeVTMap.find(OpName);
1722 if (OpVTI == OpcodeVTMap.end()) {
1723 std::vector<std::string> VTSet;
1724 VTSet.push_back(OpVTStr);
1725 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1727 OpVTI->second.push_back(OpVTStr);
1729 OS << "SDNode *Select_" << getLegalCName(OpName)
1730 << OpVTStr << "(const SDOperand &N) {\n";
1732 // Loop through and reverse all of the CodeList vectors, as we will be
1733 // accessing them from their logical front, but accessing the end of a
1734 // vector is more efficient.
1735 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1736 CodeList &GeneratedCode = CodeForPatterns[i].second;
1737 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1740 // Next, reverse the list of patterns itself for the same reason.
1741 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1743 // Emit all of the patterns now, grouped together to share code.
1744 EmitPatterns(CodeForPatterns, 2, OS);
1746 // If the last pattern has predicates (which could fail) emit code to
1747 // catch the case where nothing handles a pattern.
1748 if (mightNotMatch) {
1749 OS << " cerr << \"Cannot yet select: \";\n";
1750 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1751 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1752 OpName != "ISD::INTRINSIC_VOID") {
1753 OS << " N.Val->dump(CurDAG);\n";
1755 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1756 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1757 << " cerr << \"intrinsic %\"<< "
1758 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1760 OS << " cerr << '\\n';\n"
1762 << " return NULL;\n";
1768 // Emit boilerplate.
1769 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1770 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1771 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1773 << " // Ensure that the asm operands are themselves selected.\n"
1774 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1775 << " AddToISelQueue(Ops[j]);\n\n"
1777 << " std::vector<MVT::ValueType> VTs;\n"
1778 << " VTs.push_back(MVT::Other);\n"
1779 << " VTs.push_back(MVT::Flag);\n"
1780 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1782 << " return New.Val;\n"
1785 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1786 << " SDOperand Chain = N.getOperand(0);\n"
1787 << " SDOperand N1 = N.getOperand(1);\n"
1788 << " SDOperand N2 = N.getOperand(2);\n"
1789 << " unsigned C1 = cast<ConstantSDNode>(N1)->getValue();\n"
1790 << " unsigned C2 = cast<ConstantSDNode>(N2)->getValue();\n"
1791 << " SDOperand Tmp1 = CurDAG->getTargetConstant(C1, MVT::i32);\n"
1792 << " SDOperand Tmp2 = CurDAG->getTargetConstant(C2, MVT::i32);\n"
1793 << " AddToISelQueue(Chain);\n"
1794 << " SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1795 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1796 << " MVT::Other, Ops, 3);\n"
1799 OS << "SDNode *Select_DECLARE(const SDOperand &N) {\n"
1800 << " SDOperand Chain = N.getOperand(0);\n"
1801 << " SDOperand N1 = N.getOperand(1);\n"
1802 << " SDOperand N2 = N.getOperand(2);\n"
1803 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1804 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1805 << " N.Val->dump(CurDAG);\n"
1808 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1809 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1810 << " SDOperand Tmp1 = "
1811 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1812 << " SDOperand Tmp2 = "
1813 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1814 << " AddToISelQueue(Chain);\n"
1815 << " SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1816 << " return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,\n"
1817 << " MVT::Other, Ops, 3);\n"
1820 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1821 << " SDOperand N0 = N.getOperand(0);\n"
1822 << " SDOperand N1 = N.getOperand(1);\n"
1823 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1824 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1825 << " AddToISelQueue(N0);\n"
1826 << " SDOperand Ops[] = { N0, Tmp };\n"
1827 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1828 << " N.getValueType(), Ops, 2);\n"
1831 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1832 << " SDOperand N0 = N.getOperand(0);\n"
1833 << " SDOperand N1 = N.getOperand(1);\n"
1834 << " SDOperand N2 = N.getOperand(2);\n"
1835 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1836 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1837 << " AddToISelQueue(N1);\n"
1838 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
1839 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
1840 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1841 << " N.getValueType(), Ops+1, 2);\n"
1843 << " AddToISelQueue(N0);\n"
1844 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1845 << " N.getValueType(), Ops, 3);\n"
1849 OS << "// The main instruction selector code.\n"
1850 << "SDNode *SelectCode(SDOperand N) {\n"
1851 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1852 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1853 << "INSTRUCTION_LIST_END)) {\n"
1854 << " return NULL; // Already selected.\n"
1856 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1857 << " switch (N.getOpcode()) {\n"
1858 << " default: break;\n"
1859 << " case ISD::EntryToken: // These leaves remain the same.\n"
1860 << " case ISD::BasicBlock:\n"
1861 << " case ISD::Register:\n"
1862 << " case ISD::HANDLENODE:\n"
1863 << " case ISD::TargetConstant:\n"
1864 << " case ISD::TargetConstantPool:\n"
1865 << " case ISD::TargetFrameIndex:\n"
1866 << " case ISD::TargetExternalSymbol:\n"
1867 << " case ISD::TargetJumpTable:\n"
1868 << " case ISD::TargetGlobalTLSAddress:\n"
1869 << " case ISD::TargetGlobalAddress: {\n"
1870 << " return NULL;\n"
1872 << " case ISD::AssertSext:\n"
1873 << " case ISD::AssertZext: {\n"
1874 << " AddToISelQueue(N.getOperand(0));\n"
1875 << " ReplaceUses(N, N.getOperand(0));\n"
1876 << " return NULL;\n"
1878 << " case ISD::TokenFactor:\n"
1879 << " case ISD::CopyFromReg:\n"
1880 << " case ISD::CopyToReg: {\n"
1881 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1882 << " AddToISelQueue(N.getOperand(i));\n"
1883 << " return NULL;\n"
1885 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1886 << " case ISD::LABEL: return Select_LABEL(N);\n"
1887 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
1888 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1889 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
1892 // Loop over all of the case statements, emiting a call to each method we
1894 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1895 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1896 PBOI != E; ++PBOI) {
1897 const std::string &OpName = PBOI->first;
1898 // Potentially multiple versions of select for this opcode. One for each
1899 // ValueType of the node (or its first true operand if it doesn't produce a
1901 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1902 OpcodeVTMap.find(OpName);
1903 std::vector<std::string> &OpVTs = OpVTI->second;
1904 OS << " case " << OpName << ": {\n";
1905 // Keep track of whether we see a pattern that has an iPtr result.
1906 bool HasPtrPattern = false;
1907 bool HasDefaultPattern = false;
1909 OS << " switch (NVT) {\n";
1910 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1911 std::string &VTStr = OpVTs[i];
1912 if (VTStr.empty()) {
1913 HasDefaultPattern = true;
1917 // If this is a match on iPTR: don't emit it directly, we need special
1919 if (VTStr == "_iPTR") {
1920 HasPtrPattern = true;
1923 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1924 << " return Select_" << getLegalCName(OpName)
1925 << VTStr << "(N);\n";
1927 OS << " default:\n";
1929 // If there is an iPTR result version of this pattern, emit it here.
1930 if (HasPtrPattern) {
1931 OS << " if (NVT == TLI.getPointerTy())\n";
1932 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1934 if (HasDefaultPattern) {
1935 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1943 OS << " } // end of big switch.\n\n"
1944 << " cerr << \"Cannot yet select: \";\n"
1945 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1946 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1947 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1948 << " N.Val->dump(CurDAG);\n"
1950 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1951 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1952 << " cerr << \"intrinsic %\"<< "
1953 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1955 << " cerr << '\\n';\n"
1957 << " return NULL;\n"
1961 void DAGISelEmitter::run(std::ostream &OS) {
1962 EmitSourceFileHeader("DAG Instruction Selector for the " +
1963 CGP.getTargetInfo().getName() + " target", OS);
1965 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1966 << "// *** instruction selector class. These functions are really "
1969 OS << "// Instruction selector priority queue:\n"
1970 << "std::vector<SDNode*> ISelQueue;\n";
1971 OS << "/// Keep track of nodes which have already been added to queue.\n"
1972 << "unsigned char *ISelQueued;\n";
1973 OS << "/// Keep track of nodes which have already been selected.\n"
1974 << "unsigned char *ISelSelected;\n";
1977 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1978 OS << "/// not reach Op.\n";
1979 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1980 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1981 OS << " return true;\n";
1982 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1983 OS << " return false;\n";
1984 OS << " else if (Chain->getNumOperands() > 0) {\n";
1985 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1986 OS << " if (C0.getValueType() == MVT::Other)\n";
1987 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1989 OS << " return true;\n";
1992 OS << "/// Sorting functions for the selection queue.\n"
1993 << "struct isel_sort : public std::binary_function"
1994 << "<SDNode*, SDNode*, bool> {\n"
1995 << " bool operator()(const SDNode* left, const SDNode* right) "
1997 << " return (left->getNodeId() > right->getNodeId());\n"
2001 OS << "inline void setQueued(int Id) {\n";
2002 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
2004 OS << "inline bool isQueued(int Id) {\n";
2005 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
2007 OS << "inline void setSelected(int Id) {\n";
2008 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
2010 OS << "inline bool isSelected(int Id) {\n";
2011 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
2014 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
2015 OS << " int Id = N.Val->getNodeId();\n";
2016 OS << " if (Id != -1 && !isQueued(Id)) {\n";
2017 OS << " ISelQueue.push_back(N.Val);\n";
2018 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2019 OS << " setQueued(Id);\n";
2024 OS << "class VISIBILITY_HIDDEN ISelQueueUpdater :\n";
2025 OS << " public SelectionDAG::DAGUpdateListener {\n";
2026 OS << " std::vector<SDNode*> &ISelQueue;\n";
2027 OS << " bool HadDelete;\n";
2029 OS << " ISelQueueUpdater(std::vector<SDNode*> &isq)\n";
2030 OS << " : ISelQueue(isq), HadDelete(false) {}\n";
2032 OS << " bool hadDelete() const { return HadDelete; }\n";
2034 OS << " virtual void NodeDeleted(SDNode *N) {\n";
2035 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(),";
2036 OS << " N),\n ISelQueue.end());\n";
2037 OS << " HadDelete = true;\n";
2040 OS << " // Ignore updates.\n";
2041 OS << " virtual void NodeUpdated(SDNode *N) {}\n";
2044 OS << "inline void UpdateQueue(const ISelQueueUpdater &ISQU) {\n";
2045 OS << " if (ISQU.hadDelete())\n";
2046 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(),isel_sort());\n";
2049 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
2050 OS << " ISelQueueUpdater ISQU(ISelQueue);\n";
2051 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISQU);\n";
2052 OS << " setSelected(F.Val->getNodeId());\n";
2053 OS << " UpdateQueue(ISQU);\n";
2055 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
2056 OS << " unsigned FNumVals = F->getNumValues();\n";
2057 OS << " unsigned TNumVals = T->getNumValues();\n";
2058 OS << " ISelQueueUpdater ISQU(ISelQueue);\n";
2059 OS << " if (FNumVals != TNumVals) {\n";
2060 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2062 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
2063 << "SDOperand(T, i), &ISQU);\n";
2064 OS << " } else {\n";
2065 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISQU);\n";
2067 OS << " setSelected(F->getNodeId());\n";
2068 OS << " UpdateQueue(ISQU);\n";
2071 OS << "// SelectRoot - Top level entry to DAG isel.\n";
2072 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2073 OS << " SelectRootInit();\n";
2074 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2075 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2076 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2077 OS << " memset(ISelQueued, 0, NumBytes);\n";
2078 OS << " memset(ISelSelected, 0, NumBytes);\n";
2080 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2081 << " // a reference to the root node, preventing it from being deleted,\n"
2082 << " // and tracking any changes of the root.\n"
2083 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2084 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2085 OS << " while (!ISelQueue.empty()) {\n";
2086 OS << " SDNode *Node = ISelQueue.front();\n";
2087 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2088 OS << " ISelQueue.pop_back();\n";
2089 OS << " if (!isSelected(Node->getNodeId())) {\n";
2090 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2091 OS << " if (ResNode != Node) {\n";
2092 OS << " if (ResNode)\n";
2093 OS << " ReplaceUses(Node, ResNode);\n";
2094 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2095 OS << " ISelQueueUpdater ISQU(ISelQueue);\n";
2096 OS << " CurDAG->RemoveDeadNode(Node, &ISQU);\n";
2097 OS << " UpdateQueue(ISQU);\n";
2103 OS << " delete[] ISelQueued;\n";
2104 OS << " ISelQueued = NULL;\n";
2105 OS << " delete[] ISelSelected;\n";
2106 OS << " ISelSelected = NULL;\n";
2107 OS << " return Dummy.getValue();\n";
2110 EmitNodeTransforms(OS);
2111 EmitPredicateFunctions(OS);
2113 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2114 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2116 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2117 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2121 // At this point, we have full information about the 'Patterns' we need to
2122 // parse, both implicitly from instructions as well as from explicit pattern
2123 // definitions. Emit the resultant instruction selector.
2124 EmitInstructionSelector(OS);