1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
23 //===----------------------------------------------------------------------===//
24 // DAGISelEmitter Helper methods
27 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
29 static bool NodeIsComplexPattern(TreePatternNode *N) {
30 return (N->isLeaf() &&
31 dynamic_cast<DefInit*>(N->getLeafValue()) &&
32 static_cast<DefInit*>(N->getLeafValue())->getDef()->
33 isSubClassOf("ComplexPattern"));
36 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
38 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
39 CodeGenDAGPatterns &CGP) {
41 dynamic_cast<DefInit*>(N->getLeafValue()) &&
42 static_cast<DefInit*>(N->getLeafValue())->getDef()->
43 isSubClassOf("ComplexPattern")) {
44 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
50 /// getPatternSize - Return the 'size' of this pattern. We want to match large
51 /// patterns before small ones. This is used to determine the size of a
53 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
54 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
56 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR) &&
59 "Not a valid pattern node to size!");
60 unsigned Size = 3; // The node itself.
61 // If the root node is a ConstantSDNode, increases its size.
62 // e.g. (set R32:$dst, 0).
63 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
66 // FIXME: This is a hack to statically increase the priority of patterns
67 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68 // Later we can allow complexity / cost for each pattern to be (optionally)
69 // specified. To get best possible pattern match we'll need to dynamically
70 // calculate the complexity of all patterns a dag can potentially map to.
71 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
73 Size += AM->getNumOperands() * 3;
75 // If this node has some predicate function that must match, it adds to the
76 // complexity of this node.
77 if (!P->getPredicateFn().empty())
80 // Count children in the count if they are also nodes.
81 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82 TreePatternNode *Child = P->getChild(i);
83 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
84 Size += getPatternSize(Child, CGP);
85 else if (Child->isLeaf()) {
86 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
87 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
88 else if (NodeIsComplexPattern(Child))
89 Size += getPatternSize(Child, CGP);
90 else if (!Child->getPredicateFn().empty())
98 /// getResultPatternCost - Compute the number of instructions for this pattern.
99 /// This is a temporary hack. We should really include the instruction
100 /// latencies in this calculation.
101 static unsigned getResultPatternCost(TreePatternNode *P,
102 CodeGenDAGPatterns &CGP) {
103 if (P->isLeaf()) return 0;
106 Record *Op = P->getOperator();
107 if (Op->isSubClassOf("Instruction")) {
109 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
110 if (II.usesCustomDAGSchedInserter)
113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
114 Cost += getResultPatternCost(P->getChild(i), CGP);
118 /// getResultPatternCodeSize - Compute the code size of instructions for this
120 static unsigned getResultPatternSize(TreePatternNode *P,
121 CodeGenDAGPatterns &CGP) {
122 if (P->isLeaf()) return 0;
125 Record *Op = P->getOperator();
126 if (Op->isSubClassOf("Instruction")) {
127 Cost += Op->getValueAsInt("CodeSize");
129 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
130 Cost += getResultPatternSize(P->getChild(i), CGP);
134 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135 // In particular, we want to match maximal patterns first and lowest cost within
136 // a particular complexity first.
137 struct PatternSortingPredicate {
138 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139 CodeGenDAGPatterns &CGP;
141 bool operator()(const PatternToMatch *LHS,
142 const PatternToMatch *RHS) {
143 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
145 LHSSize += LHS->getAddedComplexity();
146 RHSSize += RHS->getAddedComplexity();
147 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
148 if (LHSSize < RHSSize) return false;
150 // If the patterns have equal complexity, compare generated instruction cost
151 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
153 if (LHSCost < RHSCost) return true;
154 if (LHSCost > RHSCost) return false;
156 return getResultPatternSize(LHS->getDstPattern(), CGP) <
157 getResultPatternSize(RHS->getDstPattern(), CGP);
161 /// getRegisterValueType - Look up and return the first ValueType of specified
162 /// RegisterClass record
163 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
164 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165 return RC->getValueTypeNum(0);
170 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171 /// type information from it.
172 static void RemoveAllTypes(TreePatternNode *N) {
175 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176 RemoveAllTypes(N->getChild(i));
179 /// NodeHasProperty - return true if TreePatternNode has the specified
181 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
182 CodeGenDAGPatterns &CGP) {
184 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
186 return CP->hasProperty(Property);
189 Record *Operator = N->getOperator();
190 if (!Operator->isSubClassOf("SDNode")) return false;
192 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
195 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
196 CodeGenDAGPatterns &CGP) {
197 if (NodeHasProperty(N, Property, CGP))
200 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201 TreePatternNode *Child = N->getChild(i);
202 if (PatternHasProperty(Child, Property, CGP))
209 //===----------------------------------------------------------------------===//
210 // Node Transformation emitter implementation.
212 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213 // Walk the pattern fragments, adding them to a map, which sorts them by
215 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
216 NXsByNameTy NXsByName;
218 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
220 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
222 OS << "\n// Node transformations.\n";
224 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
226 Record *SDNode = I->second.first;
227 std::string Code = I->second.second;
229 if (Code.empty()) continue; // Empty code? Skip it.
231 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
232 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
234 OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
236 if (ClassName != "SDNode")
237 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238 OS << Code << "\n}\n";
242 //===----------------------------------------------------------------------===//
243 // Predicate emitter implementation.
246 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247 OS << "\n// Predicate functions.\n";
249 // Walk the pattern fragments, adding them to a map, which sorts them by
251 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252 PFsByNameTy PFsByName;
254 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
256 PFsByName.insert(std::make_pair(I->first->getName(), *I));
259 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
261 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262 TreePattern *P = I->second.second;
264 // If there is a code init for this fragment, emit the predicate code.
265 std::string Code = PatFragRecord->getValueAsCode("Predicate");
266 if (Code.empty()) continue;
268 if (P->getOnlyTree()->isLeaf())
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *N) {\n";
272 std::string ClassName =
273 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
274 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
276 OS << "inline bool Predicate_" << PatFragRecord->getName()
277 << "(SDNode *" << C2 << ") {\n";
278 if (ClassName != "SDNode")
279 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
281 OS << Code << "\n}\n";
288 //===----------------------------------------------------------------------===//
289 // PatternCodeEmitter implementation.
291 class PatternCodeEmitter {
293 CodeGenDAGPatterns &CGP;
296 ListInit *Predicates;
299 // Instruction selector pattern.
300 TreePatternNode *Pattern;
301 // Matched instruction.
302 TreePatternNode *Instruction;
304 // Node to name mapping
305 std::map<std::string, std::string> VariableMap;
306 // Node to operator mapping
307 std::map<std::string, Record*> OperatorMap;
308 // Names of all the folded nodes which produce chains.
309 std::vector<std::pair<std::string, unsigned> > FoldedChains;
310 // Original input chain(s).
311 std::vector<std::pair<std::string, std::string> > OrigChains;
312 std::set<std::string> Duplicates;
314 /// LSI - Load/Store information.
315 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
316 /// for each memory access. This facilitates the use of AliasAnalysis in
318 std::vector<std::string> LSI;
320 /// GeneratedCode - This is the buffer that we emit code to. The first int
321 /// indicates whether this is an exit predicate (something that should be
322 /// tested, and if true, the match fails) [when 1], or normal code to emit
323 /// [when 0], or initialization code to emit [when 2].
324 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
325 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
326 /// the set of patterns for each top-level opcode.
327 std::set<std::string> &GeneratedDecl;
328 /// TargetOpcodes - The target specific opcodes used by the resulting
330 std::vector<std::string> &TargetOpcodes;
331 std::vector<std::string> &TargetVTs;
333 std::string ChainName;
338 void emitCheck(const std::string &S) {
340 GeneratedCode.push_back(std::make_pair(1, S));
342 void emitCode(const std::string &S) {
344 GeneratedCode.push_back(std::make_pair(0, S));
346 void emitInit(const std::string &S) {
348 GeneratedCode.push_back(std::make_pair(2, S));
350 void emitDecl(const std::string &S) {
351 assert(!S.empty() && "Invalid declaration");
352 GeneratedDecl.insert(S);
354 void emitOpcode(const std::string &Opc) {
355 TargetOpcodes.push_back(Opc);
358 void emitVT(const std::string &VT) {
359 TargetVTs.push_back(VT);
363 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
364 TreePatternNode *pattern, TreePatternNode *instr,
365 std::vector<std::pair<unsigned, std::string> > &gc,
366 std::set<std::string> &gd,
367 std::vector<std::string> &to,
368 std::vector<std::string> &tv)
369 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
370 GeneratedCode(gc), GeneratedDecl(gd),
371 TargetOpcodes(to), TargetVTs(tv),
372 TmpNo(0), OpcNo(0), VTNo(0) {}
374 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
375 /// if the match fails. At this point, we already know that the opcode for N
376 /// matches, and the SDNode for the result has the RootName specified name.
377 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
378 const std::string &RootName, const std::string &ChainSuffix,
381 // Save loads/stores matched by a pattern.
382 if (!N->isLeaf() && N->getName().empty() &&
383 ((N->getOperator()->getName() == "ld") ||
384 (N->getOperator()->getName() == "st") ||
385 (N->getOperator()->getName() == "ist"))) {
386 LSI.push_back(RootName);
389 bool isRoot = (P == NULL);
390 // Emit instruction predicates. Each predicate is just a string for now.
392 std::string PredicateCheck;
393 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
394 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
395 Record *Def = Pred->getDef();
396 if (!Def->isSubClassOf("Predicate")) {
400 assert(0 && "Unknown predicate type!");
402 if (!PredicateCheck.empty())
403 PredicateCheck += " && ";
404 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
408 emitCheck(PredicateCheck);
412 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
413 emitCheck("cast<ConstantSDNode>(" + RootName +
414 ")->getSignExtended() == " + itostr(II->getValue()));
416 } else if (!NodeIsComplexPattern(N)) {
417 assert(0 && "Cannot match this as a leaf value!");
422 // If this node has a name associated with it, capture it in VariableMap. If
423 // we already saw this in the pattern, emit code to verify dagness.
424 if (!N->getName().empty()) {
425 std::string &VarMapEntry = VariableMap[N->getName()];
426 if (VarMapEntry.empty()) {
427 VarMapEntry = RootName;
429 // If we get here, this is a second reference to a specific name. Since
430 // we already have checked that the first reference is valid, we don't
431 // have to recursively match it, just check that it's the same as the
432 // previously named thing.
433 emitCheck(VarMapEntry + " == " + RootName);
438 OperatorMap[N->getName()] = N->getOperator();
442 // Emit code to load the child nodes and match their contents recursively.
444 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
445 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
446 bool EmittedUseCheck = false;
451 // Multiple uses of actual result?
452 emitCheck(RootName + ".hasOneUse()");
453 EmittedUseCheck = true;
455 // If the immediate use can somehow reach this node through another
456 // path, then can't fold it either or it will create a cycle.
457 // e.g. In the following diagram, XX can reach ld through YY. If
458 // ld is folded into XX, then YY is both a predecessor and a successor
468 bool NeedCheck = false;
472 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
474 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
475 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
476 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
477 PInfo.getNumOperands() > 1 ||
478 PInfo.hasProperty(SDNPHasChain) ||
479 PInfo.hasProperty(SDNPInFlag) ||
480 PInfo.hasProperty(SDNPOptInFlag);
484 std::string ParentName(RootName.begin(), RootName.end()-1);
485 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
493 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
494 "IsChainCompatible(" + ChainName + ".Val, " +
495 RootName + ".Val))");
496 OrigChains.push_back(std::make_pair(ChainName, RootName));
499 ChainName = "Chain" + ChainSuffix;
500 emitInit("SDOperand " + ChainName + " = " + RootName +
505 // Don't fold any node which reads or writes a flag and has multiple uses.
506 // FIXME: We really need to separate the concepts of flag and "glue". Those
507 // real flag results, e.g. X86CMP output, can have multiple uses.
508 // FIXME: If the optional incoming flag does not exist. Then it is ok to
511 (PatternHasProperty(N, SDNPInFlag, CGP) ||
512 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
513 PatternHasProperty(N, SDNPOutFlag, CGP))) {
514 if (!EmittedUseCheck) {
515 // Multiple uses of actual result?
516 emitCheck(RootName + ".hasOneUse()");
520 // If there is a node predicate for this, emit the call.
521 if (!N->getPredicateFn().empty())
522 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
525 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
526 // a constant without a predicate fn that has more that one bit set, handle
527 // this as a special case. This is usually for targets that have special
528 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
529 // handling stuff). Using these instructions is often far more efficient
530 // than materializing the constant. Unfortunately, both the instcombiner
531 // and the dag combiner can often infer that bits are dead, and thus drop
532 // them from the mask in the dag. For example, it might turn 'AND X, 255'
533 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
536 (N->getOperator()->getName() == "and" ||
537 N->getOperator()->getName() == "or") &&
538 N->getChild(1)->isLeaf() &&
539 N->getChild(1)->getPredicateFn().empty()) {
540 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
541 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
542 emitInit("SDOperand " + RootName + "0" + " = " +
543 RootName + ".getOperand(" + utostr(0) + ");");
544 emitInit("SDOperand " + RootName + "1" + " = " +
545 RootName + ".getOperand(" + utostr(1) + ");");
547 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
548 const char *MaskPredicate = N->getOperator()->getName() == "or"
549 ? "CheckOrMask(" : "CheckAndMask(";
550 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
551 RootName + "1), " + itostr(II->getValue()) + ")");
553 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
554 ChainSuffix + utostr(0), FoundChain);
560 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
561 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
562 RootName + ".getOperand(" +utostr(OpNo) + ");");
564 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
565 ChainSuffix + utostr(OpNo), FoundChain);
568 // Handle cases when root is a complex pattern.
569 const ComplexPattern *CP;
570 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
571 std::string Fn = CP->getSelectFunc();
572 unsigned NumOps = CP->getNumOperands();
573 for (unsigned i = 0; i < NumOps; ++i) {
574 emitDecl("CPTmp" + utostr(i));
575 emitCode("SDOperand CPTmp" + utostr(i) + ";");
577 if (CP->hasProperty(SDNPHasChain)) {
578 emitDecl("CPInChain");
579 emitDecl("Chain" + ChainSuffix);
580 emitCode("SDOperand CPInChain;");
581 emitCode("SDOperand Chain" + ChainSuffix + ";");
584 std::string Code = Fn + "(" + RootName + ", " + RootName;
585 for (unsigned i = 0; i < NumOps; i++)
586 Code += ", CPTmp" + utostr(i);
587 if (CP->hasProperty(SDNPHasChain)) {
588 ChainName = "Chain" + ChainSuffix;
589 Code += ", CPInChain, Chain" + ChainSuffix;
591 emitCheck(Code + ")");
595 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
596 const std::string &RootName,
597 const std::string &ChainSuffix, bool &FoundChain) {
598 if (!Child->isLeaf()) {
599 // If it's not a leaf, recursively match.
600 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
601 emitCheck(RootName + ".getOpcode() == " +
602 CInfo.getEnumName());
603 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
604 if (NodeHasProperty(Child, SDNPHasChain, CGP))
605 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
607 // If this child has a name associated with it, capture it in VarMap. If
608 // we already saw this in the pattern, emit code to verify dagness.
609 if (!Child->getName().empty()) {
610 std::string &VarMapEntry = VariableMap[Child->getName()];
611 if (VarMapEntry.empty()) {
612 VarMapEntry = RootName;
614 // If we get here, this is a second reference to a specific name.
615 // Since we already have checked that the first reference is valid,
616 // we don't have to recursively match it, just check that it's the
617 // same as the previously named thing.
618 emitCheck(VarMapEntry + " == " + RootName);
619 Duplicates.insert(RootName);
624 // Handle leaves of various types.
625 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
626 Record *LeafRec = DI->getDef();
627 if (LeafRec->isSubClassOf("RegisterClass") ||
628 LeafRec->getName() == "ptr_rc") {
629 // Handle register references. Nothing to do here.
630 } else if (LeafRec->isSubClassOf("Register")) {
631 // Handle register references.
632 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
633 // Handle complex pattern.
634 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
635 std::string Fn = CP->getSelectFunc();
636 unsigned NumOps = CP->getNumOperands();
637 for (unsigned i = 0; i < NumOps; ++i) {
638 emitDecl("CPTmp" + utostr(i));
639 emitCode("SDOperand CPTmp" + utostr(i) + ";");
641 if (CP->hasProperty(SDNPHasChain)) {
642 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
643 FoldedChains.push_back(std::make_pair("CPInChain",
644 PInfo.getNumResults()));
645 ChainName = "Chain" + ChainSuffix;
646 emitDecl("CPInChain");
648 emitCode("SDOperand CPInChain;");
649 emitCode("SDOperand " + ChainName + ";");
652 std::string Code = Fn + "(N, ";
653 if (CP->hasProperty(SDNPHasChain)) {
654 std::string ParentName(RootName.begin(), RootName.end()-1);
655 Code += ParentName + ", ";
658 for (unsigned i = 0; i < NumOps; i++)
659 Code += ", CPTmp" + utostr(i);
660 if (CP->hasProperty(SDNPHasChain))
661 Code += ", CPInChain, Chain" + ChainSuffix;
662 emitCheck(Code + ")");
663 } else if (LeafRec->getName() == "srcvalue") {
664 // Place holder for SRCVALUE nodes. Nothing to do here.
665 } else if (LeafRec->isSubClassOf("ValueType")) {
666 // Make sure this is the specified value type.
667 emitCheck("cast<VTSDNode>(" + RootName +
668 ")->getVT() == MVT::" + LeafRec->getName());
669 } else if (LeafRec->isSubClassOf("CondCode")) {
670 // Make sure this is the specified cond code.
671 emitCheck("cast<CondCodeSDNode>(" + RootName +
672 ")->get() == ISD::" + LeafRec->getName());
678 assert(0 && "Unknown leaf type!");
681 // If there is a node predicate for this, emit the call.
682 if (!Child->getPredicateFn().empty())
683 emitCheck(Child->getPredicateFn() + "(" + RootName +
685 } else if (IntInit *II =
686 dynamic_cast<IntInit*>(Child->getLeafValue())) {
687 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
688 unsigned CTmp = TmpNo++;
689 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
690 RootName + ")->getSignExtended();");
692 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
697 assert(0 && "Unknown leaf type!");
702 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
703 /// we actually have to build a DAG!
704 std::vector<std::string>
705 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
706 bool InFlagDecled, bool ResNodeDecled,
707 bool LikeLeaf = false, bool isRoot = false) {
708 // List of arguments of getTargetNode() or SelectNodeTo().
709 std::vector<std::string> NodeOps;
710 // This is something selected from the pattern we matched.
711 if (!N->getName().empty()) {
712 const std::string &VarName = N->getName();
713 std::string Val = VariableMap[VarName];
714 bool ModifiedVal = false;
715 assert(!Val.empty() &&
716 "Variable referenced but not defined and not caught earlier!");
717 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
718 // Already selected this operand, just return the tmpval.
719 NodeOps.push_back(Val);
723 const ComplexPattern *CP;
724 unsigned ResNo = TmpNo++;
725 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
726 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
727 std::string CastType;
728 std::string TmpVar = "Tmp" + utostr(ResNo);
729 switch (N->getTypeNum(0)) {
731 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
732 << " type as an immediate constant. Aborting\n";
734 case MVT::i1: CastType = "bool"; break;
735 case MVT::i8: CastType = "unsigned char"; break;
736 case MVT::i16: CastType = "unsigned short"; break;
737 case MVT::i32: CastType = "unsigned"; break;
738 case MVT::i64: CastType = "uint64_t"; break;
740 emitCode("SDOperand " + TmpVar +
741 " = CurDAG->getTargetConstant(((" + CastType +
742 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
743 getEnumName(N->getTypeNum(0)) + ");");
744 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
745 // value if used multiple times by this pattern result.
748 NodeOps.push_back(Val);
749 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
750 Record *Op = OperatorMap[N->getName()];
751 // Transform ExternalSymbol to TargetExternalSymbol
752 if (Op && Op->getName() == "externalsym") {
753 std::string TmpVar = "Tmp"+utostr(ResNo);
754 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
755 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
756 Val + ")->getSymbol(), " +
757 getEnumName(N->getTypeNum(0)) + ");");
758 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
759 // this value if used multiple times by this pattern result.
763 NodeOps.push_back(Val);
764 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
765 || N->getOperator()->getName() == "tglobaltlsaddr")) {
766 Record *Op = OperatorMap[N->getName()];
767 // Transform GlobalAddress to TargetGlobalAddress
768 if (Op && (Op->getName() == "globaladdr" ||
769 Op->getName() == "globaltlsaddr")) {
770 std::string TmpVar = "Tmp" + utostr(ResNo);
771 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
772 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
773 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
775 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
776 // this value if used multiple times by this pattern result.
780 NodeOps.push_back(Val);
781 } else if (!N->isLeaf()
782 && (N->getOperator()->getName() == "texternalsym"
783 || N->getOperator()->getName() == "tconstpool")) {
784 // Do not rewrite the variable name, since we don't generate a new
786 NodeOps.push_back(Val);
787 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
788 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
789 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
790 NodeOps.push_back("CPTmp" + utostr(i));
793 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
794 // node even if it isn't one. Don't select it.
796 emitCode("AddToISelQueue(" + Val + ");");
797 if (isRoot && N->isLeaf()) {
798 emitCode("ReplaceUses(N, " + Val + ");");
799 emitCode("return NULL;");
802 NodeOps.push_back(Val);
806 VariableMap[VarName] = Val;
811 // If this is an explicit register reference, handle it.
812 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
813 unsigned ResNo = TmpNo++;
814 if (DI->getDef()->isSubClassOf("Register")) {
815 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
816 getQualifiedName(DI->getDef()) + ", " +
817 getEnumName(N->getTypeNum(0)) + ");");
818 NodeOps.push_back("Tmp" + utostr(ResNo));
820 } else if (DI->getDef()->getName() == "zero_reg") {
821 emitCode("SDOperand Tmp" + utostr(ResNo) +
822 " = CurDAG->getRegister(0, " +
823 getEnumName(N->getTypeNum(0)) + ");");
824 NodeOps.push_back("Tmp" + utostr(ResNo));
827 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
828 unsigned ResNo = TmpNo++;
829 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
830 emitCode("SDOperand Tmp" + utostr(ResNo) +
831 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
832 ", " + getEnumName(N->getTypeNum(0)) + ");");
833 NodeOps.push_back("Tmp" + utostr(ResNo));
840 assert(0 && "Unknown leaf type!");
844 Record *Op = N->getOperator();
845 if (Op->isSubClassOf("Instruction")) {
846 const CodeGenTarget &CGT = CGP.getTargetInfo();
847 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
848 const DAGInstruction &Inst = CGP.getInstruction(Op);
849 const TreePattern *InstPat = Inst.getPattern();
850 // FIXME: Assume actual pattern comes before "implicit".
851 TreePatternNode *InstPatNode =
852 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
853 : (InstPat ? InstPat->getTree(0) : NULL);
854 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
855 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
857 bool HasVarOps = isRoot && II.isVariadic;
858 // FIXME: fix how we deal with physical register operands.
859 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
860 bool HasImpResults = isRoot && DstRegs.size() > 0;
861 bool NodeHasOptInFlag = isRoot &&
862 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
863 bool NodeHasInFlag = isRoot &&
864 PatternHasProperty(Pattern, SDNPInFlag, CGP);
865 bool NodeHasOutFlag = isRoot &&
866 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
867 bool NodeHasChain = InstPatNode &&
868 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
869 bool InputHasChain = isRoot &&
870 NodeHasProperty(Pattern, SDNPHasChain, CGP);
871 unsigned NumResults = Inst.getNumResults();
872 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
874 if (NodeHasOptInFlag) {
875 emitCode("bool HasInFlag = "
876 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
879 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
881 // How many results is this pattern expected to produce?
882 unsigned NumPatResults = 0;
883 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
884 MVT::ValueType VT = Pattern->getTypeNum(i);
885 if (VT != MVT::isVoid && VT != MVT::Flag)
889 if (OrigChains.size() > 0) {
890 // The original input chain is being ignored. If it is not just
891 // pointing to the op that's being folded, we should create a
892 // TokenFactor with it and the chain of the folded op as the new chain.
893 // We could potentially be doing multiple levels of folding, in that
894 // case, the TokenFactor can have more operands.
895 emitCode("SmallVector<SDOperand, 8> InChains;");
896 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
897 emitCode("if (" + OrigChains[i].first + ".Val != " +
898 OrigChains[i].second + ".Val) {");
899 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
900 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
903 emitCode("AddToISelQueue(" + ChainName + ");");
904 emitCode("InChains.push_back(" + ChainName + ");");
905 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
906 "&InChains[0], InChains.size());");
909 // Loop over all of the operands of the instruction pattern, emitting code
910 // to fill them all in. The node 'N' usually has number children equal to
911 // the number of input operands of the instruction. However, in cases
912 // where there are predicate operands for an instruction, we need to fill
913 // in the 'execute always' values. Match up the node operands to the
914 // instruction operands to do this.
915 std::vector<std::string> AllOps;
916 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
917 for (unsigned ChildNo = 0, InstOpNo = NumResults;
918 InstOpNo != II.OperandList.size(); ++InstOpNo) {
919 std::vector<std::string> Ops;
921 // If this is a normal operand or a predicate operand without
922 // 'execute always', emit it.
923 Record *OperandNode = II.OperandList[InstOpNo].Rec;
924 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
925 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
926 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
927 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
928 InFlagDecled, ResNodeDecled);
929 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
932 // Otherwise, this is a predicate or optional def operand, emit the
933 // 'default ops' operands.
934 const DAGDefaultOperand &DefaultOp =
935 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
936 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
937 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
938 InFlagDecled, ResNodeDecled);
939 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
940 NumEAInputs += Ops.size();
945 // Generate MemOperandSDNodes nodes for each memory accesses covered by this
948 std::vector<std::string>::const_iterator mi, mie;
949 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
950 emitCode("SDOperand LSI_" + *mi + " = "
951 "CurDAG->getMemOperand(cast<LSBaseSDNode>(" +
952 *mi + ")->getMemOperand());");
953 AllOps.push_back("LSI_" + *mi);
957 // Emit all the chain and CopyToReg stuff.
958 bool ChainEmitted = NodeHasChain;
960 emitCode("AddToISelQueue(" + ChainName + ");");
961 if (NodeHasInFlag || HasImpInputs)
962 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
963 InFlagDecled, ResNodeDecled, true);
964 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
966 emitCode("SDOperand InFlag(0, 0);");
969 if (NodeHasOptInFlag) {
970 emitCode("if (HasInFlag) {");
971 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
972 emitCode(" AddToISelQueue(InFlag);");
977 unsigned ResNo = TmpNo++;
978 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
979 NodeHasOptInFlag || HasImpResults) {
982 std::string NodeName;
984 NodeName = "Tmp" + utostr(ResNo);
985 Code2 = "SDOperand " + NodeName + "(";
987 NodeName = "ResNode";
988 if (!ResNodeDecled) {
989 Code2 = "SDNode *" + NodeName + " = ";
990 ResNodeDecled = true;
992 Code2 = NodeName + " = ";
995 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
996 unsigned OpsNo = OpcNo;
997 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
999 // Output order: results, chain, flags
1001 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1002 Code += ", VT" + utostr(VTNo);
1003 emitVT(getEnumName(N->getTypeNum(0)));
1005 // Add types for implicit results in physical registers, scheduler will
1006 // care of adding copyfromreg nodes.
1007 for (unsigned i = 0; i < NumDstRegs; i++) {
1008 Record *RR = DstRegs[i];
1009 if (RR->isSubClassOf("Register")) {
1010 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1011 Code += ", " + getEnumName(RVT);
1015 Code += ", MVT::Other";
1017 Code += ", MVT::Flag";
1019 // Figure out how many fixed inputs the node has. This is important to
1020 // know which inputs are the variable ones if present.
1021 unsigned NumInputs = AllOps.size();
1022 NumInputs += NodeHasChain;
1026 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1027 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1032 // Figure out whether any operands at the end of the op list are not
1033 // part of the variable section.
1034 std::string EndAdjust;
1035 if (NodeHasInFlag || HasImpInputs)
1036 EndAdjust = "-1"; // Always has one flag.
1037 else if (NodeHasOptInFlag)
1038 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1040 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1041 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1043 emitCode(" AddToISelQueue(N.getOperand(i));");
1044 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1050 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1052 AllOps.push_back(ChainName);
1056 if (NodeHasInFlag || HasImpInputs)
1057 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1058 else if (NodeHasOptInFlag) {
1059 emitCode("if (HasInFlag)");
1060 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1062 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1064 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1065 AllOps.push_back("InFlag");
1067 unsigned NumOps = AllOps.size();
1069 if (!NodeHasOptInFlag && NumOps < 4) {
1070 for (unsigned i = 0; i != NumOps; ++i)
1071 Code += ", " + AllOps[i];
1073 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1074 for (unsigned i = 0; i != NumOps; ++i) {
1075 OpsCode += AllOps[i];
1079 emitCode(OpsCode + " };");
1080 Code += ", Ops" + utostr(OpsNo) + ", ";
1081 if (NodeHasOptInFlag) {
1082 Code += "HasInFlag ? ";
1083 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1085 Code += utostr(NumOps);
1091 emitCode(Code2 + Code + ");");
1094 // Remember which op produces the chain.
1096 emitCode(ChainName + " = SDOperand(" + NodeName +
1097 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
1099 emitCode(ChainName + " = SDOperand(" + NodeName +
1100 ", " + utostr(NumResults+NumDstRegs) + ");");
1103 NodeOps.push_back("Tmp" + utostr(ResNo));
1107 bool NeedReplace = false;
1108 if (NodeHasOutFlag) {
1109 if (!InFlagDecled) {
1110 emitCode("SDOperand InFlag(ResNode, " +
1111 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1112 InFlagDecled = true;
1114 emitCode("InFlag = SDOperand(ResNode, " +
1115 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1118 if (FoldedChains.size() > 0) {
1120 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1121 emitCode("ReplaceUses(SDOperand(" +
1122 FoldedChains[j].first + ".Val, " +
1123 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1124 utostr(NumResults+NumDstRegs) + "));");
1128 if (NodeHasOutFlag) {
1129 emitCode("ReplaceUses(SDOperand(N.Val, " +
1130 utostr(NumPatResults + (unsigned)InputHasChain)
1135 if (NeedReplace && InputHasChain)
1136 emitCode("ReplaceUses(SDOperand(N.Val, " +
1137 utostr(NumPatResults) + "), SDOperand(" + ChainName
1138 + ".Val, " + ChainName + ".ResNo" + "));");
1140 // User does not expect the instruction would produce a chain!
1141 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1143 } else if (InputHasChain && !NodeHasChain) {
1144 // One of the inner node produces a chain.
1146 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1147 "), SDOperand(ResNode, N.ResNo-1));");
1148 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1149 "), " + ChainName + ");");
1152 emitCode("return ResNode;");
1154 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1156 if (N->getTypeNum(0) != MVT::isVoid)
1157 Code += ", VT" + utostr(VTNo);
1159 Code += ", MVT::Flag";
1161 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1162 AllOps.push_back("InFlag");
1164 unsigned NumOps = AllOps.size();
1166 if (!NodeHasOptInFlag && NumOps < 4) {
1167 for (unsigned i = 0; i != NumOps; ++i)
1168 Code += ", " + AllOps[i];
1170 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1171 for (unsigned i = 0; i != NumOps; ++i) {
1172 OpsCode += AllOps[i];
1176 emitCode(OpsCode + " };");
1177 Code += ", Ops" + utostr(OpcNo) + ", ";
1178 Code += utostr(NumOps);
1181 emitCode(Code + ");");
1182 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1183 if (N->getTypeNum(0) != MVT::isVoid)
1184 emitVT(getEnumName(N->getTypeNum(0)));
1188 } else if (Op->isSubClassOf("SDNodeXForm")) {
1189 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1190 // PatLeaf node - the operand may or may not be a leaf node. But it should
1192 std::vector<std::string> Ops =
1193 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1194 ResNodeDecled, true);
1195 unsigned ResNo = TmpNo++;
1196 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1197 + "(" + Ops.back() + ".Val);");
1198 NodeOps.push_back("Tmp" + utostr(ResNo));
1200 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1205 throw std::string("Unknown node in result pattern!");
1209 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1210 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1211 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1212 /// for, this returns true otherwise false if Pat has all types.
1213 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1214 const std::string &Prefix, bool isRoot = false) {
1216 if (Pat->getExtTypes() != Other->getExtTypes()) {
1217 // Move a type over from 'other' to 'pat'.
1218 Pat->setTypes(Other->getExtTypes());
1219 // The top level node type is checked outside of the select function.
1221 emitCheck(Prefix + ".Val->getValueType(0) == " +
1222 getName(Pat->getTypeNum(0)));
1227 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1228 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1229 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1230 Prefix + utostr(OpNo)))
1236 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1238 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1239 bool &ChainEmitted, bool &InFlagDecled,
1240 bool &ResNodeDecled, bool isRoot = false) {
1241 const CodeGenTarget &T = CGP.getTargetInfo();
1243 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1244 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1245 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1246 TreePatternNode *Child = N->getChild(i);
1247 if (!Child->isLeaf()) {
1248 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1249 InFlagDecled, ResNodeDecled);
1251 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1252 if (!Child->getName().empty()) {
1253 std::string Name = RootName + utostr(OpNo);
1254 if (Duplicates.find(Name) != Duplicates.end())
1255 // A duplicate! Do not emit a copy for this node.
1259 Record *RR = DI->getDef();
1260 if (RR->isSubClassOf("Register")) {
1261 MVT::ValueType RVT = getRegisterValueType(RR, T);
1262 if (RVT == MVT::Flag) {
1263 if (!InFlagDecled) {
1264 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1265 InFlagDecled = true;
1267 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1268 emitCode("AddToISelQueue(InFlag);");
1270 if (!ChainEmitted) {
1271 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1272 ChainName = "Chain";
1273 ChainEmitted = true;
1275 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1276 if (!InFlagDecled) {
1277 emitCode("SDOperand InFlag(0, 0);");
1278 InFlagDecled = true;
1280 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1281 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1282 ", " + getQualifiedName(RR) +
1283 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1284 ResNodeDecled = true;
1285 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1286 emitCode("InFlag = SDOperand(ResNode, 1);");
1294 if (!InFlagDecled) {
1295 emitCode("SDOperand InFlag = " + RootName +
1296 ".getOperand(" + utostr(OpNo) + ");");
1297 InFlagDecled = true;
1299 emitCode("InFlag = " + RootName +
1300 ".getOperand(" + utostr(OpNo) + ");");
1301 emitCode("AddToISelQueue(InFlag);");
1306 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1307 /// stream to match the pattern, and generate the code for the match if it
1308 /// succeeds. Returns true if the pattern is not guaranteed to match.
1309 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1310 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1311 std::set<std::string> &GeneratedDecl,
1312 std::vector<std::string> &TargetOpcodes,
1313 std::vector<std::string> &TargetVTs) {
1314 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1315 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1316 GeneratedCode, GeneratedDecl,
1317 TargetOpcodes, TargetVTs);
1319 // Emit the matcher, capturing named arguments in VariableMap.
1320 bool FoundChain = false;
1321 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1323 // TP - Get *SOME* tree pattern, we don't care which.
1324 TreePattern &TP = *CGP.pf_begin()->second;
1326 // At this point, we know that we structurally match the pattern, but the
1327 // types of the nodes may not match. Figure out the fewest number of type
1328 // comparisons we need to emit. For example, if there is only one integer
1329 // type supported by a target, there should be no type comparisons at all for
1330 // integer patterns!
1332 // To figure out the fewest number of type checks needed, clone the pattern,
1333 // remove the types, then perform type inference on the pattern as a whole.
1334 // If there are unresolved types, emit an explicit check for those types,
1335 // apply the type to the tree, then rerun type inference. Iterate until all
1336 // types are resolved.
1338 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1339 RemoveAllTypes(Pat);
1342 // Resolve/propagate as many types as possible.
1344 bool MadeChange = true;
1346 MadeChange = Pat->ApplyTypeConstraints(TP,
1347 true/*Ignore reg constraints*/);
1349 assert(0 && "Error: could not find consistent types for something we"
1350 " already decided was ok!");
1354 // Insert a check for an unresolved type and add it to the tree. If we find
1355 // an unresolved type to add a check for, this returns true and we iterate,
1356 // otherwise we are done.
1357 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1359 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1360 false, false, false, true);
1364 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1365 /// a line causes any of them to be empty, remove them and return true when
1367 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1368 std::vector<std::pair<unsigned, std::string> > > >
1370 bool ErasedPatterns = false;
1371 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1372 Patterns[i].second.pop_back();
1373 if (Patterns[i].second.empty()) {
1374 Patterns.erase(Patterns.begin()+i);
1376 ErasedPatterns = true;
1379 return ErasedPatterns;
1382 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1383 /// code together between the patterns.
1384 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1385 std::vector<std::pair<unsigned, std::string> > > >
1386 &Patterns, unsigned Indent,
1388 typedef std::pair<unsigned, std::string> CodeLine;
1389 typedef std::vector<CodeLine> CodeList;
1390 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1392 if (Patterns.empty()) return;
1394 // Figure out how many patterns share the next code line. Explicitly copy
1395 // FirstCodeLine so that we don't invalidate a reference when changing
1397 const CodeLine FirstCodeLine = Patterns.back().second.back();
1398 unsigned LastMatch = Patterns.size()-1;
1399 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1402 // If not all patterns share this line, split the list into two pieces. The
1403 // first chunk will use this line, the second chunk won't.
1404 if (LastMatch != 0) {
1405 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1406 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1408 // FIXME: Emit braces?
1409 if (Shared.size() == 1) {
1410 const PatternToMatch &Pattern = *Shared.back().first;
1411 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1412 Pattern.getSrcPattern()->print(OS);
1413 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1414 Pattern.getDstPattern()->print(OS);
1416 unsigned AddedComplexity = Pattern.getAddedComplexity();
1417 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1418 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1420 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1422 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1424 if (FirstCodeLine.first != 1) {
1425 OS << std::string(Indent, ' ') << "{\n";
1428 EmitPatterns(Shared, Indent, OS);
1429 if (FirstCodeLine.first != 1) {
1431 OS << std::string(Indent, ' ') << "}\n";
1434 if (Other.size() == 1) {
1435 const PatternToMatch &Pattern = *Other.back().first;
1436 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1437 Pattern.getSrcPattern()->print(OS);
1438 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1439 Pattern.getDstPattern()->print(OS);
1441 unsigned AddedComplexity = Pattern.getAddedComplexity();
1442 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1443 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1445 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1447 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1449 EmitPatterns(Other, Indent, OS);
1453 // Remove this code from all of the patterns that share it.
1454 bool ErasedPatterns = EraseCodeLine(Patterns);
1456 bool isPredicate = FirstCodeLine.first == 1;
1458 // Otherwise, every pattern in the list has this line. Emit it.
1461 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1463 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1465 // If the next code line is another predicate, and if all of the pattern
1466 // in this group share the same next line, emit it inline now. Do this
1467 // until we run out of common predicates.
1468 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1469 // Check that all of fhe patterns in Patterns end with the same predicate.
1470 bool AllEndWithSamePredicate = true;
1471 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1472 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1473 AllEndWithSamePredicate = false;
1476 // If all of the predicates aren't the same, we can't share them.
1477 if (!AllEndWithSamePredicate) break;
1479 // Otherwise we can. Emit it shared now.
1480 OS << " &&\n" << std::string(Indent+4, ' ')
1481 << Patterns.back().second.back().second;
1482 ErasedPatterns = EraseCodeLine(Patterns);
1489 EmitPatterns(Patterns, Indent, OS);
1492 OS << std::string(Indent-2, ' ') << "}\n";
1495 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
1496 return CGP.getSDNodeInfo(Op).getEnumName();
1499 static std::string getLegalCName(std::string OpName) {
1500 std::string::size_type pos = OpName.find("::");
1501 if (pos != std::string::npos)
1502 OpName.replace(pos, 2, "_");
1506 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1507 const CodeGenTarget &Target = CGP.getTargetInfo();
1509 // Get the namespace to insert instructions into. Make sure not to pick up
1510 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1511 // instruction or something.
1513 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1514 e = Target.inst_end(); i != e; ++i) {
1515 InstNS = i->second.Namespace;
1516 if (InstNS != "TargetInstrInfo")
1520 if (!InstNS.empty()) InstNS += "::";
1522 // Group the patterns by their top-level opcodes.
1523 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1524 // All unique target node emission functions.
1525 std::map<std::string, unsigned> EmitFunctions;
1526 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1527 E = CGP.ptm_end(); I != E; ++I) {
1528 const PatternToMatch &Pattern = *I;
1530 TreePatternNode *Node = Pattern.getSrcPattern();
1531 if (!Node->isLeaf()) {
1532 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1533 push_back(&Pattern);
1535 const ComplexPattern *CP;
1536 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1537 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1538 push_back(&Pattern);
1539 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1540 std::vector<Record*> OpNodes = CP->getRootNodes();
1541 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1542 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1543 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1547 cerr << "Unrecognized opcode '";
1549 cerr << "' on tree pattern '";
1550 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1556 // For each opcode, there might be multiple select functions, one per
1557 // ValueType of the node (or its first operand if it doesn't produce a
1558 // non-chain result.
1559 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1561 // Emit one Select_* method for each top-level opcode. We do this instead of
1562 // emitting one giant switch statement to support compilers where this will
1563 // result in the recursive functions taking less stack space.
1564 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1565 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1566 PBOI != E; ++PBOI) {
1567 const std::string &OpName = PBOI->first;
1568 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1569 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1571 // We want to emit all of the matching code now. However, we want to emit
1572 // the matches in order of minimal cost. Sort the patterns so the least
1573 // cost one is at the start.
1574 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1575 PatternSortingPredicate(CGP));
1577 // Split them into groups by type.
1578 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1579 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1580 const PatternToMatch *Pat = PatternsOfOp[i];
1581 TreePatternNode *SrcPat = Pat->getSrcPattern();
1582 MVT::ValueType VT = SrcPat->getTypeNum(0);
1583 std::map<MVT::ValueType,
1584 std::vector<const PatternToMatch*> >::iterator TI =
1585 PatternsByType.find(VT);
1586 if (TI != PatternsByType.end())
1587 TI->second.push_back(Pat);
1589 std::vector<const PatternToMatch*> PVec;
1590 PVec.push_back(Pat);
1591 PatternsByType.insert(std::make_pair(VT, PVec));
1595 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1596 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1598 MVT::ValueType OpVT = II->first;
1599 std::vector<const PatternToMatch*> &Patterns = II->second;
1600 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1601 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1603 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1604 std::vector<std::vector<std::string> > PatternOpcodes;
1605 std::vector<std::vector<std::string> > PatternVTs;
1606 std::vector<std::set<std::string> > PatternDecls;
1607 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1608 CodeList GeneratedCode;
1609 std::set<std::string> GeneratedDecl;
1610 std::vector<std::string> TargetOpcodes;
1611 std::vector<std::string> TargetVTs;
1612 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1613 TargetOpcodes, TargetVTs);
1614 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1615 PatternDecls.push_back(GeneratedDecl);
1616 PatternOpcodes.push_back(TargetOpcodes);
1617 PatternVTs.push_back(TargetVTs);
1620 // Scan the code to see if all of the patterns are reachable and if it is
1621 // possible that the last one might not match.
1622 bool mightNotMatch = true;
1623 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1624 CodeList &GeneratedCode = CodeForPatterns[i].second;
1625 mightNotMatch = false;
1627 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1628 if (GeneratedCode[j].first == 1) { // predicate.
1629 mightNotMatch = true;
1634 // If this pattern definitely matches, and if it isn't the last one, the
1635 // patterns after it CANNOT ever match. Error out.
1636 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1637 cerr << "Pattern '";
1638 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1639 cerr << "' is impossible to select!\n";
1644 // Factor target node emission code (emitted by EmitResultCode) into
1645 // separate functions. Uniquing and share them among all instruction
1646 // selection routines.
1647 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1648 CodeList &GeneratedCode = CodeForPatterns[i].second;
1649 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1650 std::vector<std::string> &TargetVTs = PatternVTs[i];
1651 std::set<std::string> Decls = PatternDecls[i];
1652 std::vector<std::string> AddedInits;
1653 int CodeSize = (int)GeneratedCode.size();
1655 for (int j = CodeSize-1; j >= 0; --j) {
1656 if (LastPred == -1 && GeneratedCode[j].first == 1)
1658 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1659 AddedInits.push_back(GeneratedCode[j].second);
1662 std::string CalleeCode = "(const SDOperand &N";
1663 std::string CallerCode = "(N";
1664 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1665 CalleeCode += ", unsigned Opc" + utostr(j);
1666 CallerCode += ", " + TargetOpcodes[j];
1668 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1669 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1670 CallerCode += ", " + TargetVTs[j];
1672 for (std::set<std::string>::iterator
1673 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1674 std::string Name = *I;
1675 CalleeCode += ", SDOperand &" + Name;
1676 CallerCode += ", " + Name;
1680 // Prevent emission routines from being inlined to reduce selection
1681 // routines stack frame sizes.
1682 CalleeCode += "DISABLE_INLINE ";
1683 CalleeCode += "{\n";
1685 for (std::vector<std::string>::const_reverse_iterator
1686 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1687 CalleeCode += " " + *I + "\n";
1689 for (int j = LastPred+1; j < CodeSize; ++j)
1690 CalleeCode += " " + GeneratedCode[j].second + "\n";
1691 for (int j = LastPred+1; j < CodeSize; ++j)
1692 GeneratedCode.pop_back();
1693 CalleeCode += "}\n";
1695 // Uniquing the emission routines.
1696 unsigned EmitFuncNum;
1697 std::map<std::string, unsigned>::iterator EFI =
1698 EmitFunctions.find(CalleeCode);
1699 if (EFI != EmitFunctions.end()) {
1700 EmitFuncNum = EFI->second;
1702 EmitFuncNum = EmitFunctions.size();
1703 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1704 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1707 // Replace the emission code within selection routines with calls to the
1708 // emission functions.
1709 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1710 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1714 std::string OpVTStr;
1715 if (OpVT == MVT::iPTR) {
1717 } else if (OpVT == MVT::isVoid) {
1718 // Nodes with a void result actually have a first result type of either
1719 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1720 // void to this case, we handle it specially here.
1722 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1724 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1725 OpcodeVTMap.find(OpName);
1726 if (OpVTI == OpcodeVTMap.end()) {
1727 std::vector<std::string> VTSet;
1728 VTSet.push_back(OpVTStr);
1729 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1731 OpVTI->second.push_back(OpVTStr);
1733 OS << "SDNode *Select_" << getLegalCName(OpName)
1734 << OpVTStr << "(const SDOperand &N) {\n";
1736 // Loop through and reverse all of the CodeList vectors, as we will be
1737 // accessing them from their logical front, but accessing the end of a
1738 // vector is more efficient.
1739 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1740 CodeList &GeneratedCode = CodeForPatterns[i].second;
1741 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1744 // Next, reverse the list of patterns itself for the same reason.
1745 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1747 // Emit all of the patterns now, grouped together to share code.
1748 EmitPatterns(CodeForPatterns, 2, OS);
1750 // If the last pattern has predicates (which could fail) emit code to
1751 // catch the case where nothing handles a pattern.
1752 if (mightNotMatch) {
1753 OS << " cerr << \"Cannot yet select: \";\n";
1754 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1755 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1756 OpName != "ISD::INTRINSIC_VOID") {
1757 OS << " N.Val->dump(CurDAG);\n";
1759 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1760 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1761 << " cerr << \"intrinsic %\"<< "
1762 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1764 OS << " cerr << '\\n';\n"
1766 << " return NULL;\n";
1772 // Emit boilerplate.
1773 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1774 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1775 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1777 << " // Ensure that the asm operands are themselves selected.\n"
1778 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1779 << " AddToISelQueue(Ops[j]);\n\n"
1781 << " std::vector<MVT::ValueType> VTs;\n"
1782 << " VTs.push_back(MVT::Other);\n"
1783 << " VTs.push_back(MVT::Flag);\n"
1784 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1786 << " return New.Val;\n"
1789 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1790 << " SDOperand Chain = N.getOperand(0);\n"
1791 << " SDOperand N1 = N.getOperand(1);\n"
1792 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1793 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1794 << " AddToISelQueue(Chain);\n"
1795 << " SDOperand Ops[] = { Tmp, Chain };\n"
1796 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1797 << " MVT::Other, Ops, 2);\n"
1800 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1801 << " SDOperand N0 = N.getOperand(0);\n"
1802 << " SDOperand N1 = N.getOperand(1);\n"
1803 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1804 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1805 << " AddToISelQueue(N0);\n"
1806 << " SDOperand Ops[] = { N0, Tmp };\n"
1807 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1808 << " N.getValueType(), Ops, 2);\n"
1811 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1812 << " SDOperand N0 = N.getOperand(0);\n"
1813 << " SDOperand N1 = N.getOperand(1);\n"
1814 << " SDOperand N2 = N.getOperand(2);\n"
1815 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1816 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1817 << " AddToISelQueue(N1);\n"
1818 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
1819 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
1820 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1821 << " N.getValueType(), Ops+1, 2);\n"
1823 << " AddToISelQueue(N0);\n"
1824 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1825 << " N.getValueType(), Ops, 3);\n"
1829 OS << "// The main instruction selector code.\n"
1830 << "SDNode *SelectCode(SDOperand N) {\n"
1831 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1832 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1833 << "INSTRUCTION_LIST_END)) {\n"
1834 << " return NULL; // Already selected.\n"
1836 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1837 << " switch (N.getOpcode()) {\n"
1838 << " default: break;\n"
1839 << " case ISD::EntryToken: // These leaves remain the same.\n"
1840 << " case ISD::BasicBlock:\n"
1841 << " case ISD::Register:\n"
1842 << " case ISD::HANDLENODE:\n"
1843 << " case ISD::TargetConstant:\n"
1844 << " case ISD::TargetConstantPool:\n"
1845 << " case ISD::TargetFrameIndex:\n"
1846 << " case ISD::TargetExternalSymbol:\n"
1847 << " case ISD::TargetJumpTable:\n"
1848 << " case ISD::TargetGlobalTLSAddress:\n"
1849 << " case ISD::TargetGlobalAddress: {\n"
1850 << " return NULL;\n"
1852 << " case ISD::AssertSext:\n"
1853 << " case ISD::AssertZext: {\n"
1854 << " AddToISelQueue(N.getOperand(0));\n"
1855 << " ReplaceUses(N, N.getOperand(0));\n"
1856 << " return NULL;\n"
1858 << " case ISD::TokenFactor:\n"
1859 << " case ISD::CopyFromReg:\n"
1860 << " case ISD::CopyToReg: {\n"
1861 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1862 << " AddToISelQueue(N.getOperand(i));\n"
1863 << " return NULL;\n"
1865 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1866 << " case ISD::LABEL: return Select_LABEL(N);\n"
1867 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1868 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
1871 // Loop over all of the case statements, emiting a call to each method we
1873 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1874 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1875 PBOI != E; ++PBOI) {
1876 const std::string &OpName = PBOI->first;
1877 // Potentially multiple versions of select for this opcode. One for each
1878 // ValueType of the node (or its first true operand if it doesn't produce a
1880 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1881 OpcodeVTMap.find(OpName);
1882 std::vector<std::string> &OpVTs = OpVTI->second;
1883 OS << " case " << OpName << ": {\n";
1884 // Keep track of whether we see a pattern that has an iPtr result.
1885 bool HasPtrPattern = false;
1886 bool HasDefaultPattern = false;
1888 OS << " switch (NVT) {\n";
1889 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1890 std::string &VTStr = OpVTs[i];
1891 if (VTStr.empty()) {
1892 HasDefaultPattern = true;
1896 // If this is a match on iPTR: don't emit it directly, we need special
1898 if (VTStr == "_iPTR") {
1899 HasPtrPattern = true;
1902 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1903 << " return Select_" << getLegalCName(OpName)
1904 << VTStr << "(N);\n";
1906 OS << " default:\n";
1908 // If there is an iPTR result version of this pattern, emit it here.
1909 if (HasPtrPattern) {
1910 OS << " if (NVT == TLI.getPointerTy())\n";
1911 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1913 if (HasDefaultPattern) {
1914 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1922 OS << " } // end of big switch.\n\n"
1923 << " cerr << \"Cannot yet select: \";\n"
1924 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1925 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1926 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1927 << " N.Val->dump(CurDAG);\n"
1929 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1930 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1931 << " cerr << \"intrinsic %\"<< "
1932 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1934 << " cerr << '\\n';\n"
1936 << " return NULL;\n"
1940 void DAGISelEmitter::run(std::ostream &OS) {
1941 EmitSourceFileHeader("DAG Instruction Selector for the " +
1942 CGP.getTargetInfo().getName() + " target", OS);
1944 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1945 << "// *** instruction selector class. These functions are really "
1948 OS << "#include \"llvm/Support/Compiler.h\"\n";
1950 OS << "// Instruction selector priority queue:\n"
1951 << "std::vector<SDNode*> ISelQueue;\n";
1952 OS << "/// Keep track of nodes which have already been added to queue.\n"
1953 << "unsigned char *ISelQueued;\n";
1954 OS << "/// Keep track of nodes which have already been selected.\n"
1955 << "unsigned char *ISelSelected;\n";
1956 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1957 << "std::vector<SDNode*> ISelKilled;\n\n";
1959 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1960 OS << "/// not reach Op.\n";
1961 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1962 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1963 OS << " return true;\n";
1964 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1965 OS << " return false;\n";
1966 OS << " else if (Chain->getNumOperands() > 0) {\n";
1967 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1968 OS << " if (C0.getValueType() == MVT::Other)\n";
1969 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1971 OS << " return true;\n";
1974 OS << "/// Sorting functions for the selection queue.\n"
1975 << "struct isel_sort : public std::binary_function"
1976 << "<SDNode*, SDNode*, bool> {\n"
1977 << " bool operator()(const SDNode* left, const SDNode* right) "
1979 << " return (left->getNodeId() > right->getNodeId());\n"
1983 OS << "inline void setQueued(int Id) {\n";
1984 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1986 OS << "inline bool isQueued(int Id) {\n";
1987 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1989 OS << "inline void setSelected(int Id) {\n";
1990 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1992 OS << "inline bool isSelected(int Id) {\n";
1993 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1996 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
1997 OS << " int Id = N.Val->getNodeId();\n";
1998 OS << " if (Id != -1 && !isQueued(Id)) {\n";
1999 OS << " ISelQueue.push_back(N.Val);\n";
2000 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2001 OS << " setQueued(Id);\n";
2005 OS << "inline void RemoveKilled() {\n";
2006 OS << " unsigned NumKilled = ISelKilled.size();\n";
2007 OS << " if (NumKilled) {\n";
2008 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
2009 OS << " SDNode *Temp = ISelKilled[i];\n";
2010 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
2011 << "Temp), ISelQueue.end());\n";
2013 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2014 OS << " ISelKilled.clear();\n";
2018 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
2019 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
2020 OS << " setSelected(F.Val->getNodeId());\n";
2021 OS << " RemoveKilled();\n";
2023 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
2024 OS << " unsigned FNumVals = F->getNumValues();\n";
2025 OS << " unsigned TNumVals = T->getNumValues();\n";
2026 OS << " if (FNumVals != TNumVals) {\n";
2027 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2029 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
2030 << "SDOperand(T, i), &ISelKilled);\n";
2031 OS << " } else {\n";
2032 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2034 OS << " setSelected(F->getNodeId());\n";
2035 OS << " RemoveKilled();\n";
2038 OS << "// SelectRoot - Top level entry to DAG isel.\n";
2039 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2040 OS << " SelectRootInit();\n";
2041 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2042 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2043 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2044 OS << " memset(ISelQueued, 0, NumBytes);\n";
2045 OS << " memset(ISelSelected, 0, NumBytes);\n";
2047 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2048 << " // a reference to the root node, preventing it from being deleted,\n"
2049 << " // and tracking any changes of the root.\n"
2050 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2051 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2052 OS << " while (!ISelQueue.empty()) {\n";
2053 OS << " SDNode *Node = ISelQueue.front();\n";
2054 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2055 OS << " ISelQueue.pop_back();\n";
2056 OS << " if (!isSelected(Node->getNodeId())) {\n";
2057 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2058 OS << " if (ResNode != Node) {\n";
2059 OS << " if (ResNode)\n";
2060 OS << " ReplaceUses(Node, ResNode);\n";
2061 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2062 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2063 OS << " RemoveKilled();\n";
2069 OS << " delete[] ISelQueued;\n";
2070 OS << " ISelQueued = NULL;\n";
2071 OS << " delete[] ISelSelected;\n";
2072 OS << " ISelSelected = NULL;\n";
2073 OS << " return Dummy.getValue();\n";
2076 EmitNodeTransforms(OS);
2077 EmitPredicateFunctions(OS);
2079 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2080 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2082 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2083 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2087 // At this point, we have full information about the 'Patterns' we need to
2088 // parse, both implicitly from instructions as well as from explicit pattern
2089 // definitions. Emit the resultant instruction selector.
2090 EmitInstructionSelector(OS);