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"
15 #include "DAGISelMatcher.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Debug.h"
28 GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
30 //===----------------------------------------------------------------------===//
31 // DAGISelEmitter Helper methods
34 /// getNodeName - The top level Select_* functions have an "SDNode* N"
35 /// argument. When expanding the pattern-matching code, the intermediate
36 /// variables have type SDValue. This function provides a uniform way to
37 /// reference the underlying "SDNode *" for both cases.
38 static std::string getNodeName(const std::string &S) {
39 if (S == "N") return S;
40 return S + ".getNode()";
43 /// getNodeValue - Similar to getNodeName, except it provides a uniform
44 /// way to access the SDValue for both cases.
45 static std::string getValueName(const std::string &S) {
46 if (S == "N") return "SDValue(N, 0)";
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((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
56 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR ||
59 P->getExtTypeNum(0) == MVT::iPTRAny) &&
60 "Not a valid pattern node to size!");
61 unsigned Size = 3; // The node itself.
62 // If the root node is a ConstantSDNode, increases its size.
63 // e.g. (set R32:$dst, 0).
64 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
67 // FIXME: This is a hack to statically increase the priority of patterns
68 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
69 // Later we can allow complexity / cost for each pattern to be (optionally)
70 // specified. To get best possible pattern match we'll need to dynamically
71 // calculate the complexity of all patterns a dag can potentially map to.
72 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
74 Size += AM->getNumOperands() * 3;
76 // If this node has some predicate function that must match, it adds to the
77 // complexity of this node.
78 if (!P->getPredicateFns().empty())
81 // Count children in the count if they are also nodes.
82 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
83 TreePatternNode *Child = P->getChild(i);
84 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
85 Size += getPatternSize(Child, CGP);
86 else if (Child->isLeaf()) {
87 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
88 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
89 else if (Child->getComplexPatternInfo(CGP))
90 Size += getPatternSize(Child, CGP);
91 else if (!Child->getPredicateFns().empty())
99 /// getResultPatternCost - Compute the number of instructions for this pattern.
100 /// This is a temporary hack. We should really include the instruction
101 /// latencies in this calculation.
102 static unsigned getResultPatternCost(TreePatternNode *P,
103 CodeGenDAGPatterns &CGP) {
104 if (P->isLeaf()) return 0;
107 Record *Op = P->getOperator();
108 if (Op->isSubClassOf("Instruction")) {
110 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
111 if (II.usesCustomInserter)
114 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
115 Cost += getResultPatternCost(P->getChild(i), CGP);
119 /// getResultPatternCodeSize - Compute the code size of instructions for this
121 static unsigned getResultPatternSize(TreePatternNode *P,
122 CodeGenDAGPatterns &CGP) {
123 if (P->isLeaf()) return 0;
126 Record *Op = P->getOperator();
127 if (Op->isSubClassOf("Instruction")) {
128 Cost += Op->getValueAsInt("CodeSize");
130 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
131 Cost += getResultPatternSize(P->getChild(i), CGP);
135 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
136 // In particular, we want to match maximal patterns first and lowest cost within
137 // a particular complexity first.
138 struct PatternSortingPredicate {
139 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
140 CodeGenDAGPatterns &CGP;
142 typedef std::pair<unsigned, std::string> CodeLine;
143 typedef std::vector<CodeLine> CodeList;
144 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
146 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
147 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
148 const PatternToMatch *LHS = LHSPair.first;
149 const PatternToMatch *RHS = RHSPair.first;
151 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
152 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
153 LHSSize += LHS->getAddedComplexity();
154 RHSSize += RHS->getAddedComplexity();
155 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
156 if (LHSSize < RHSSize) return false;
158 // If the patterns have equal complexity, compare generated instruction cost
159 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
160 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
161 if (LHSCost < RHSCost) return true;
162 if (LHSCost > RHSCost) return false;
164 return getResultPatternSize(LHS->getDstPattern(), CGP) <
165 getResultPatternSize(RHS->getDstPattern(), CGP);
169 /// getRegisterValueType - Look up and return the ValueType of the specified
170 /// register. If the register is a member of multiple register classes which
171 /// have different associated types, return MVT::Other.
172 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
173 bool FoundRC = false;
174 MVT::SimpleValueType VT = MVT::Other;
175 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
176 std::vector<CodeGenRegisterClass>::const_iterator RC;
177 std::vector<Record*>::const_iterator Element;
179 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
180 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
181 if (Element != (*RC).Elements.end()) {
184 VT = (*RC).getValueTypeNum(0);
187 if (VT != (*RC).getValueTypeNum(0)) {
188 // Types of the RC's do not agree. Return MVT::Other. The
189 // target is responsible for handling this.
198 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
199 return CGP.getSDNodeInfo(Op).getEnumName();
202 //===----------------------------------------------------------------------===//
203 // Node Transformation emitter implementation.
205 void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
206 // Walk the pattern fragments, adding them to a map, which sorts them by
208 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
209 NXsByNameTy NXsByName;
211 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
213 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
215 OS << "\n// Node transformations.\n";
217 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
219 Record *SDNode = I->second.first;
220 std::string Code = I->second.second;
222 if (Code.empty()) continue; // Empty code? Skip it.
224 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
225 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
227 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
229 if (ClassName != "SDNode")
230 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
231 OS << Code << "\n}\n";
235 //===----------------------------------------------------------------------===//
236 // Predicate emitter implementation.
239 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
240 OS << "\n// Predicate functions.\n";
242 // Walk the pattern fragments, adding them to a map, which sorts them by
244 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
245 PFsByNameTy PFsByName;
247 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
249 PFsByName.insert(std::make_pair(I->first->getName(), *I));
252 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
254 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
255 TreePattern *P = I->second.second;
257 // If there is a code init for this fragment, emit the predicate code.
258 std::string Code = PatFragRecord->getValueAsCode("Predicate");
259 if (Code.empty()) continue;
261 if (P->getOnlyTree()->isLeaf())
262 OS << "inline bool Predicate_" << PatFragRecord->getName()
263 << "(SDNode *N) const {\n";
265 std::string ClassName =
266 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
267 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *" << C2 << ") const {\n";
271 if (ClassName != "SDNode")
272 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
274 OS << Code << "\n}\n";
281 //===----------------------------------------------------------------------===//
282 // PatternCodeEmitter implementation.
284 class PatternCodeEmitter {
286 CodeGenDAGPatterns &CGP;
289 std::string PredicateCheck;
292 // Instruction selector pattern.
293 TreePatternNode *Pattern;
294 // Matched instruction.
295 TreePatternNode *Instruction;
297 // Node to name mapping
298 std::map<std::string, std::string> VariableMap;
299 // Node to operator mapping
300 std::map<std::string, Record*> OperatorMap;
301 // Name of the folded node which produces a flag.
302 std::pair<std::string, unsigned> FoldedFlag;
303 // Names of all the folded nodes which produce chains.
304 std::vector<std::pair<std::string, unsigned> > FoldedChains;
305 // Original input chain(s).
306 std::vector<std::pair<std::string, std::string> > OrigChains;
307 std::set<std::string> Duplicates;
309 /// LSI - Load/Store information.
310 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
311 /// for each memory access. This facilitates the use of AliasAnalysis in
313 std::vector<std::string> LSI;
315 /// GeneratedCode - This is the buffer that we emit code to. The first int
316 /// indicates whether this is an exit predicate (something that should be
317 /// tested, and if true, the match fails) [when 1], or normal code to emit
318 /// [when 0], or initialization code to emit [when 2].
319 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
320 /// GeneratedDecl - This is the set of all SDValue declarations needed for
321 /// the set of patterns for each top-level opcode.
322 std::set<std::string> &GeneratedDecl;
323 /// TargetOpcodes - The target specific opcodes used by the resulting
325 std::vector<std::string> &TargetOpcodes;
326 std::vector<std::string> &TargetVTs;
327 /// OutputIsVariadic - Records whether the instruction output pattern uses
328 /// variable_ops. This requires that the Emit function be passed an
329 /// additional argument to indicate where the input varargs operands
331 bool &OutputIsVariadic;
332 /// NumInputRootOps - Records the number of operands the root node of the
333 /// input pattern has. This information is used in the generated code to
334 /// pass to Emit functions when variable_ops processing is needed.
335 unsigned &NumInputRootOps;
337 std::string ChainName;
342 void emitCheck(const std::string &S) {
344 GeneratedCode.push_back(std::make_pair(1, S));
346 void emitCode(const std::string &S) {
348 GeneratedCode.push_back(std::make_pair(0, S));
350 void emitInit(const std::string &S) {
352 GeneratedCode.push_back(std::make_pair(2, S));
354 void emitDecl(const std::string &S) {
355 assert(!S.empty() && "Invalid declaration");
356 GeneratedDecl.insert(S);
358 void emitOpcode(const std::string &Opc) {
359 TargetOpcodes.push_back(Opc);
362 void emitVT(const std::string &VT) {
363 TargetVTs.push_back(VT);
367 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
368 TreePatternNode *pattern, TreePatternNode *instr,
369 std::vector<std::pair<unsigned, std::string> > &gc,
370 std::set<std::string> &gd,
371 std::vector<std::string> &to,
372 std::vector<std::string> &tv,
375 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
376 GeneratedCode(gc), GeneratedDecl(gd),
377 TargetOpcodes(to), TargetVTs(tv),
378 OutputIsVariadic(oiv), NumInputRootOps(niro),
379 TmpNo(0), OpcNo(0), VTNo(0) {}
381 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
382 /// if the match fails. At this point, we already know that the opcode for N
383 /// matches, and the SDNode for the result has the RootName specified name.
384 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
385 const std::string &RootName, const std::string &ChainSuffix,
388 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
389 const std::string &RootName,
390 const std::string &ChainSuffix, bool &FoundChain);
392 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
393 /// we actually have to build a DAG!
394 std::vector<std::string>
395 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
396 bool InFlagDecled, bool ResNodeDecled,
397 bool LikeLeaf = false, bool isRoot = false);
399 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
400 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
401 /// 'Pat' may be missing types. If we find an unresolved type to add a check
402 /// for, this returns true otherwise false if Pat has all types.
403 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
404 const std::string &Prefix, bool isRoot = false) {
406 if (Pat->getExtTypes() != Other->getExtTypes()) {
407 // Move a type over from 'other' to 'pat'.
408 Pat->setTypes(Other->getExtTypes());
409 // The top level node type is checked outside of the select function.
411 emitCheck(Prefix + ".getValueType() == " +
412 getName(Pat->getTypeNum(0)));
416 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
417 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
418 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
419 Prefix + utostr(OpNo)))
425 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
427 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
428 bool &ChainEmitted, bool &InFlagDecled,
429 bool &ResNodeDecled, bool isRoot = false) {
430 const CodeGenTarget &T = CGP.getTargetInfo();
431 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
432 bool HasInFlag = N->NodeHasProperty(SDNPInFlag, CGP);
433 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
434 TreePatternNode *Child = N->getChild(i);
435 if (!Child->isLeaf()) {
436 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
437 InFlagDecled, ResNodeDecled);
439 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
440 if (!Child->getName().empty()) {
441 std::string Name = RootName + utostr(OpNo);
442 if (Duplicates.find(Name) != Duplicates.end())
443 // A duplicate! Do not emit a copy for this node.
447 Record *RR = DI->getDef();
448 if (RR->isSubClassOf("Register")) {
449 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
450 if (RVT == MVT::Flag) {
452 emitCode("SDValue InFlag = " +
453 getValueName(RootName + utostr(OpNo)) + ";");
456 emitCode("InFlag = " +
457 getValueName(RootName + utostr(OpNo)) + ";");
460 emitCode("SDValue Chain = CurDAG->getEntryNode();");
465 emitCode("SDValue InFlag(0, 0);");
468 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
469 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
470 ", " + getNodeName(RootName) + "->getDebugLoc()" +
471 ", " + getQualifiedName(RR) +
472 ", " + getValueName(RootName + utostr(OpNo)) +
473 ", InFlag).getNode();");
474 ResNodeDecled = true;
475 emitCode(ChainName + " = SDValue(ResNode, 0);");
476 emitCode("InFlag = SDValue(ResNode, 1);");
485 emitCode("SDValue InFlag = " + getNodeName(RootName) +
486 "->getOperand(" + utostr(OpNo) + ");");
489 emitCode("InFlag = " + getNodeName(RootName) +
490 "->getOperand(" + utostr(OpNo) + ");");
496 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
497 /// if the match fails. At this point, we already know that the opcode for N
498 /// matches, and the SDNode for the result has the RootName specified name.
499 void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
500 const std::string &RootName,
501 const std::string &ChainSuffix,
503 // Save loads/stores matched by a pattern.
504 if (!N->isLeaf() && N->getName().empty()) {
505 if (N->NodeHasProperty(SDNPMemOperand, CGP))
506 LSI.push_back(getNodeName(RootName));
509 bool isRoot = (P == NULL);
510 // Emit instruction predicates. Each predicate is just a string for now.
512 // Record input varargs info.
513 NumInputRootOps = N->getNumChildren();
514 emitCheck(PredicateCheck);
518 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
519 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
520 ")->getSExtValue() == INT64_C(" +
521 itostr(II->getValue()) + ")");
524 assert(N->getComplexPatternInfo(CGP) != 0 &&
525 "Cannot match this as a leaf value!");
528 // If this node has a name associated with it, capture it in VariableMap. If
529 // we already saw this in the pattern, emit code to verify dagness.
530 if (!N->getName().empty()) {
531 std::string &VarMapEntry = VariableMap[N->getName()];
532 if (VarMapEntry.empty()) {
533 VarMapEntry = RootName;
535 // If we get here, this is a second reference to a specific name. Since
536 // we already have checked that the first reference is valid, we don't
537 // have to recursively match it, just check that it's the same as the
538 // previously named thing.
539 emitCheck(VarMapEntry + " == " + RootName);
544 OperatorMap[N->getName()] = N->getOperator();
548 // Emit code to load the child nodes and match their contents recursively.
550 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
551 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
556 // Check if it's profitable to fold the node. e.g. Check for multiple uses
558 std::string ParentName(RootName.begin(), RootName.end()-1);
560 // If this is just an interior node, check to see if it has a single
561 // use. If the node has multiple uses and the pattern has a load as
562 // an operand, then we can't fold the load.
563 emitCheck(getValueName(RootName) + ".hasOneUse()");
564 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
565 // If the immediate use can somehow reach this node through another
566 // path, then can't fold it either or it will create a cycle.
567 // e.g. In the following diagram, XX can reach ld through YY. If
568 // ld is folded into XX, then YY is both a predecessor and a successor
579 // We know we need the check if N's parent is not the root.
580 bool NeedCheck = P != Pattern;
582 // If the parent is the root and the node has more than one operand,
584 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
586 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
587 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
588 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
589 PInfo.getNumOperands() > 1 ||
590 PInfo.hasProperty(SDNPHasChain) ||
591 PInfo.hasProperty(SDNPInFlag) ||
592 PInfo.hasProperty(SDNPOptInFlag);
596 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
597 ", " + getNodeName(ParentName) + ", N)");
598 emitCheck("IsLegalToFold(" + getValueName(RootName) +
599 ", " + getNodeName(ParentName) + ", N)");
601 // Otherwise, just verify that the node only has a single use.
602 emitCheck(getValueName(RootName) + ".hasOneUse()");
609 emitCheck("IsChainCompatible(" + ChainName + ".getNode(), " +
610 getNodeName(RootName) + ")");
611 OrigChains.push_back(std::make_pair(ChainName,
612 getValueName(RootName)));
615 ChainName = "Chain" + ChainSuffix;
617 if (!N->getComplexPatternInfo(CGP) ||
619 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
624 // If there are node predicates for this, emit the calls.
625 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
626 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
628 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
629 // a constant without a predicate fn that has more that one bit set, handle
630 // this as a special case. This is usually for targets that have special
631 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
632 // handling stuff). Using these instructions is often far more efficient
633 // than materializing the constant. Unfortunately, both the instcombiner
634 // and the dag combiner can often infer that bits are dead, and thus drop
635 // them from the mask in the dag. For example, it might turn 'AND X, 255'
636 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
639 (N->getOperator()->getName() == "and" ||
640 N->getOperator()->getName() == "or") &&
641 N->getChild(1)->isLeaf() &&
642 N->getChild(1)->getPredicateFns().empty()) {
643 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
644 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
645 emitInit("SDValue " + RootName + "0" + " = " +
646 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
647 emitInit("SDValue " + RootName + "1" + " = " +
648 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
650 unsigned NTmp = TmpNo++;
651 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
652 " = dyn_cast<ConstantSDNode>(" +
653 getNodeName(RootName + "1") + ");");
654 emitCheck("Tmp" + utostr(NTmp));
655 const char *MaskPredicate = N->getOperator()->getName() == "or"
656 ? "CheckOrMask(" : "CheckAndMask(";
657 emitCheck(MaskPredicate + getValueName(RootName + "0") +
658 ", Tmp" + utostr(NTmp) +
659 ", INT64_C(" + itostr(II->getValue()) + "))");
661 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
662 ChainSuffix + utostr(0), FoundChain);
668 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
669 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
670 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
672 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
673 ChainSuffix + utostr(OpNo), FoundChain);
676 // Handle cases when root is a complex pattern.
677 const ComplexPattern *CP;
678 if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
679 std::string Fn = CP->getSelectFunc();
680 unsigned NumOps = CP->getNumOperands();
681 for (unsigned i = 0; i < NumOps; ++i) {
682 emitDecl("CPTmp" + RootName + "_" + utostr(i));
683 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
685 if (CP->hasProperty(SDNPHasChain)) {
686 emitDecl("CPInChain");
687 emitDecl("Chain" + ChainSuffix);
688 emitCode("SDValue CPInChain;");
689 emitCode("SDValue Chain" + ChainSuffix + ";");
692 std::string Code = Fn + "(N, "; // always pass in the root.
693 Code += getValueName(RootName);
694 for (unsigned i = 0; i < NumOps; i++)
695 Code += ", CPTmp" + RootName + "_" + utostr(i);
696 if (CP->hasProperty(SDNPHasChain)) {
697 ChainName = "Chain" + ChainSuffix;
698 Code += ", CPInChain, " + ChainName;
700 emitCheck(Code + ")");
704 void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
705 TreePatternNode *Parent,
706 const std::string &RootName,
707 const std::string &ChainSuffix,
709 if (!Child->isLeaf()) {
710 // If it's not a leaf, recursively match.
711 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
712 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
713 CInfo.getEnumName());
714 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
715 bool HasChain = false;
716 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
718 FoldedChains.push_back(std::make_pair(getValueName(RootName),
719 CInfo.getNumResults()));
721 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
722 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
723 "Pattern folded multiple nodes which produce flags?");
724 FoldedFlag = std::make_pair(getValueName(RootName),
725 CInfo.getNumResults() + (unsigned)HasChain);
730 if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
731 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
732 bool HasChain = false;
734 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
736 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
737 FoldedChains.push_back(std::make_pair("CPInChain",
738 PInfo.getNumResults()));
740 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
741 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
742 "Pattern folded multiple nodes which produce flags?");
743 FoldedFlag = std::make_pair(getValueName(RootName),
744 CP->getNumOperands() + (unsigned)HasChain);
749 // If this child has a name associated with it, capture it in VarMap. If
750 // we already saw this in the pattern, emit code to verify dagness.
751 if (!Child->getName().empty()) {
752 std::string &VarMapEntry = VariableMap[Child->getName()];
753 if (VarMapEntry.empty()) {
754 VarMapEntry = getValueName(RootName);
756 // If we get here, this is a second reference to a specific name.
757 // Since we already have checked that the first reference is valid,
758 // we don't have to recursively match it, just check that it's the
759 // same as the previously named thing.
760 emitCheck(VarMapEntry + " == " + getValueName(RootName));
761 Duplicates.insert(getValueName(RootName));
766 // Handle leaves of various types.
767 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
768 Record *LeafRec = DI->getDef();
769 if (LeafRec->isSubClassOf("RegisterClass") ||
770 LeafRec->isSubClassOf("PointerLikeRegClass")) {
771 // Handle register references. Nothing to do here.
772 } else if (LeafRec->isSubClassOf("Register")) {
773 // Handle register references.
774 } else if (LeafRec->getName() == "srcvalue") {
775 // Place holder for SRCVALUE nodes. Nothing to do here.
776 } else if (LeafRec->isSubClassOf("ValueType")) {
777 // Make sure this is the specified value type.
778 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
779 ")->getVT() == MVT::" + LeafRec->getName());
780 } else if (LeafRec->isSubClassOf("CondCode")) {
781 // Make sure this is the specified cond code.
782 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
783 ")->get() == ISD::" + LeafRec->getName());
789 assert(0 && "Unknown leaf type!");
792 // If there are node predicates for this, emit the calls.
793 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
794 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
799 if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
800 unsigned NTmp = TmpNo++;
801 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
802 " = dyn_cast<ConstantSDNode>("+
803 getNodeName(RootName) + ");");
804 emitCheck("Tmp" + utostr(NTmp));
805 unsigned CTmp = TmpNo++;
806 emitCode("int64_t CN"+ utostr(CTmp) +
807 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
808 emitCheck("CN" + utostr(CTmp) + " == "
809 "INT64_C(" +itostr(II->getValue()) + ")");
815 assert(0 && "Unknown leaf type!");
818 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
819 /// we actually have to build a DAG!
820 std::vector<std::string>
821 PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
822 std::vector<Record*> DstRegs,
823 bool InFlagDecled, bool ResNodeDecled,
824 bool LikeLeaf, bool isRoot) {
825 // List of arguments of getMachineNode() or SelectNodeTo().
826 std::vector<std::string> NodeOps;
827 // This is something selected from the pattern we matched.
828 if (!N->getName().empty()) {
829 const std::string &VarName = N->getName();
830 std::string Val = VariableMap[VarName];
831 bool ModifiedVal = false;
833 errs() << "Variable '" << VarName << " referenced but not defined "
834 << "and not caught earlier!\n";
837 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
838 // Already selected this operand, just return the tmpval.
839 NodeOps.push_back(getValueName(Val));
843 const ComplexPattern *CP;
844 unsigned ResNo = TmpNo++;
845 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
846 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
847 std::string CastType;
848 std::string TmpVar = "Tmp" + utostr(ResNo);
849 switch (N->getTypeNum(0)) {
851 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
852 << " type as an immediate constant. Aborting\n";
854 case MVT::i1: CastType = "bool"; break;
855 case MVT::i8: CastType = "unsigned char"; break;
856 case MVT::i16: CastType = "unsigned short"; break;
857 case MVT::i32: CastType = "unsigned"; break;
858 case MVT::i64: CastType = "uint64_t"; break;
860 emitCode("SDValue " + TmpVar +
861 " = CurDAG->getTargetConstant(((" + CastType +
862 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
863 getEnumName(N->getTypeNum(0)) + ");");
864 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
865 // value if used multiple times by this pattern result.
868 NodeOps.push_back(getValueName(Val));
869 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
870 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
871 std::string TmpVar = "Tmp" + utostr(ResNo);
872 emitCode("SDValue " + TmpVar +
873 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
874 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
875 Val + ")->getValueType(0));");
876 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
877 // value if used multiple times by this pattern result.
880 NodeOps.push_back(getValueName(Val));
881 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
882 Record *Op = OperatorMap[N->getName()];
883 // Transform ExternalSymbol to TargetExternalSymbol
884 if (Op && Op->getName() == "externalsym") {
885 std::string TmpVar = "Tmp"+utostr(ResNo);
886 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
887 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
888 Val + ")->getSymbol(), " +
889 getEnumName(N->getTypeNum(0)) + ");");
890 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
891 // this value if used multiple times by this pattern result.
895 NodeOps.push_back(getValueName(Val));
896 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
897 || N->getOperator()->getName() == "tglobaltlsaddr")) {
898 Record *Op = OperatorMap[N->getName()];
899 // Transform GlobalAddress to TargetGlobalAddress
900 if (Op && (Op->getName() == "globaladdr" ||
901 Op->getName() == "globaltlsaddr")) {
902 std::string TmpVar = "Tmp" + utostr(ResNo);
903 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
904 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
905 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
907 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
908 // this value if used multiple times by this pattern result.
912 NodeOps.push_back(getValueName(Val));
913 } else if (!N->isLeaf()
914 && (N->getOperator()->getName() == "texternalsym" ||
915 N->getOperator()->getName() == "tconstpool")) {
916 // Do not rewrite the variable name, since we don't generate a new
918 NodeOps.push_back(getValueName(Val));
919 } else if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
920 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
921 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
924 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
925 // node even if it isn't one. Don't select it.
927 if (isRoot && N->isLeaf()) {
928 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
929 emitCode("return NULL;");
932 NodeOps.push_back(getValueName(Val));
936 VariableMap[VarName] = Val;
940 // If this is an explicit register reference, handle it.
941 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
942 unsigned ResNo = TmpNo++;
943 if (DI->getDef()->isSubClassOf("Register")) {
944 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
945 getQualifiedName(DI->getDef()) + ", " +
946 getEnumName(N->getTypeNum(0)) + ");");
947 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
949 } else if (DI->getDef()->getName() == "zero_reg") {
950 emitCode("SDValue Tmp" + utostr(ResNo) +
951 " = CurDAG->getRegister(0, " +
952 getEnumName(N->getTypeNum(0)) + ");");
953 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
955 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
956 // Handle a reference to a register class. This is used
957 // in COPY_TO_SUBREG instructions.
958 emitCode("SDValue Tmp" + utostr(ResNo) +
959 " = CurDAG->getTargetConstant(" +
960 getQualifiedName(DI->getDef()) + "RegClassID, " +
962 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
965 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
966 unsigned ResNo = TmpNo++;
967 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
968 emitCode("SDValue Tmp" + utostr(ResNo) +
969 " = CurDAG->getTargetConstant(0x" +
970 utohexstr((uint64_t) II->getValue()) +
971 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
972 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
979 assert(0 && "Unknown leaf type!");
983 Record *Op = N->getOperator();
984 if (Op->isSubClassOf("Instruction")) {
985 const CodeGenTarget &CGT = CGP.getTargetInfo();
986 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
987 const DAGInstruction &Inst = CGP.getInstruction(Op);
988 const TreePattern *InstPat = Inst.getPattern();
989 // FIXME: Assume actual pattern comes before "implicit".
990 TreePatternNode *InstPatNode =
991 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
992 : (InstPat ? InstPat->getTree(0) : NULL);
993 if (InstPatNode && !InstPatNode->isLeaf() &&
994 InstPatNode->getOperator()->getName() == "set") {
995 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
997 bool IsVariadic = isRoot && II.isVariadic;
998 // FIXME: fix how we deal with physical register operands.
999 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1000 bool HasImpResults = isRoot && DstRegs.size() > 0;
1001 bool NodeHasOptInFlag = isRoot &&
1002 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
1003 bool NodeHasInFlag = isRoot &&
1004 Pattern->TreeHasProperty(SDNPInFlag, CGP);
1005 bool NodeHasOutFlag = isRoot &&
1006 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
1007 bool NodeHasChain = InstPatNode &&
1008 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
1009 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
1010 unsigned NumResults = Inst.getNumResults();
1011 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1013 // Record output varargs info.
1014 OutputIsVariadic = IsVariadic;
1016 if (NodeHasOptInFlag) {
1017 emitCode("bool HasInFlag = "
1018 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1022 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1024 // How many results is this pattern expected to produce?
1025 unsigned NumPatResults = 0;
1026 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1027 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1028 if (VT != MVT::isVoid && VT != MVT::Flag)
1032 if (OrigChains.size() > 0) {
1033 // The original input chain is being ignored. If it is not just
1034 // pointing to the op that's being folded, we should create a
1035 // TokenFactor with it and the chain of the folded op as the new chain.
1036 // We could potentially be doing multiple levels of folding, in that
1037 // case, the TokenFactor can have more operands.
1038 emitCode("SmallVector<SDValue, 8> InChains;");
1039 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1040 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1041 OrigChains[i].second + ".getNode()) {");
1042 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1045 emitCode("InChains.push_back(" + ChainName + ");");
1046 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1047 "N->getDebugLoc(), MVT::Other, "
1048 "&InChains[0], InChains.size());");
1050 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1051 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1055 // Loop over all of the operands of the instruction pattern, emitting code
1056 // to fill them all in. The node 'N' usually has number children equal to
1057 // the number of input operands of the instruction. However, in cases
1058 // where there are predicate operands for an instruction, we need to fill
1059 // in the 'execute always' values. Match up the node operands to the
1060 // instruction operands to do this.
1061 std::vector<std::string> AllOps;
1062 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1063 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1064 std::vector<std::string> Ops;
1066 // Determine what to emit for this operand.
1067 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1068 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1069 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1070 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1071 // This is a predicate or optional def operand; emit the
1072 // 'default ops' operands.
1073 const DAGDefaultOperand &DefaultOp =
1074 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1075 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1076 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1077 InFlagDecled, ResNodeDecled);
1078 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1081 // Otherwise this is a normal operand or a predicate operand without
1082 // 'execute always'; emit it.
1083 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1084 InFlagDecled, ResNodeDecled);
1085 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1090 // Emit all the chain and CopyToReg stuff.
1091 bool ChainEmitted = NodeHasChain;
1092 if (NodeHasInFlag || HasImpInputs)
1093 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1094 InFlagDecled, ResNodeDecled, true);
1095 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1096 if (!InFlagDecled) {
1097 emitCode("SDValue InFlag(0, 0);");
1098 InFlagDecled = true;
1100 if (NodeHasOptInFlag) {
1101 emitCode("if (HasInFlag) {");
1102 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1107 unsigned ResNo = TmpNo++;
1109 unsigned OpsNo = OpcNo;
1110 std::string CodePrefix;
1111 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1112 std::deque<std::string> After;
1113 std::string NodeName;
1115 NodeName = "Tmp" + utostr(ResNo);
1116 CodePrefix = "SDValue " + NodeName + "(";
1118 NodeName = "ResNode";
1119 if (!ResNodeDecled) {
1120 CodePrefix = "SDNode *" + NodeName + " = ";
1121 ResNodeDecled = true;
1123 CodePrefix = NodeName + " = ";
1126 std::string Code = "Opc" + utostr(OpcNo);
1128 if (!isRoot || (InputHasChain && !NodeHasChain))
1129 // For call to "getMachineNode()".
1130 Code += ", N->getDebugLoc()";
1132 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1134 // Output order: results, chain, flags
1136 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1137 Code += ", VT" + utostr(VTNo);
1138 emitVT(getEnumName(N->getTypeNum(0)));
1140 // Add types for implicit results in physical registers, scheduler will
1141 // care of adding copyfromreg nodes.
1142 for (unsigned i = 0; i < NumDstRegs; i++) {
1143 Record *RR = DstRegs[i];
1144 if (RR->isSubClassOf("Register")) {
1145 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1146 Code += ", " + getEnumName(RVT);
1150 Code += ", MVT::Other";
1152 Code += ", MVT::Flag";
1156 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1157 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1160 // Figure out whether any operands at the end of the op list are not
1161 // part of the variable section.
1162 std::string EndAdjust;
1163 if (NodeHasInFlag || HasImpInputs)
1164 EndAdjust = "-1"; // Always has one flag.
1165 else if (NodeHasOptInFlag)
1166 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1168 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1169 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1171 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1175 // Populate MemRefs with entries for each memory accesses covered by
1177 if (isRoot && !LSI.empty()) {
1178 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1179 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1180 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1181 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1182 emitCode(MemRefs + "[" + utostr(i) + "] = "
1183 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1184 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1185 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1191 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1193 AllOps.push_back(ChainName);
1197 if (NodeHasInFlag || HasImpInputs)
1198 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1199 else if (NodeHasOptInFlag) {
1200 emitCode("if (HasInFlag)");
1201 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1203 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1205 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1206 AllOps.push_back("InFlag");
1208 unsigned NumOps = AllOps.size();
1210 if (!NodeHasOptInFlag && NumOps < 4) {
1211 for (unsigned i = 0; i != NumOps; ++i)
1212 Code += ", " + AllOps[i];
1214 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1215 for (unsigned i = 0; i != NumOps; ++i) {
1216 OpsCode += AllOps[i];
1220 emitCode(OpsCode + " };");
1221 Code += ", Ops" + utostr(OpsNo) + ", ";
1222 if (NodeHasOptInFlag) {
1223 Code += "HasInFlag ? ";
1224 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1226 Code += utostr(NumOps);
1233 std::vector<std::string> ReplaceFroms;
1234 std::vector<std::string> ReplaceTos;
1236 NodeOps.push_back("Tmp" + utostr(ResNo));
1239 if (NodeHasOutFlag) {
1240 if (!InFlagDecled) {
1241 After.push_back("SDValue InFlag(ResNode, " +
1242 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1244 InFlagDecled = true;
1246 After.push_back("InFlag = SDValue(ResNode, " +
1247 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1251 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1252 ReplaceFroms.push_back("SDValue(" +
1253 FoldedChains[j].first + ".getNode(), " +
1254 utostr(FoldedChains[j].second) +
1256 ReplaceTos.push_back("SDValue(ResNode, " +
1257 utostr(NumResults+NumDstRegs) + ")");
1260 if (NodeHasOutFlag) {
1261 if (FoldedFlag.first != "") {
1262 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1263 utostr(FoldedFlag.second) + ")");
1264 ReplaceTos.push_back("InFlag");
1266 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
1267 ReplaceFroms.push_back("SDValue(N, " +
1268 utostr(NumPatResults + (unsigned)InputHasChain)
1270 ReplaceTos.push_back("InFlag");
1274 if (!ReplaceFroms.empty() && InputHasChain) {
1275 ReplaceFroms.push_back("SDValue(N, " +
1276 utostr(NumPatResults) + ")");
1277 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1278 ChainName + ".getResNo()" + ")");
1279 ChainAssignmentNeeded |= NodeHasChain;
1282 // User does not expect the instruction would produce a chain!
1283 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1285 } else if (InputHasChain && !NodeHasChain) {
1286 // One of the inner node produces a chain.
1287 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1288 ReplaceFroms.push_back("SDValue(N, " +
1289 utostr(NumPatResults) + ")");
1290 ReplaceTos.push_back(ChainName);
1294 if (ChainAssignmentNeeded) {
1295 // Remember which op produces the chain.
1296 std::string ChainAssign;
1298 ChainAssign = ChainName + " = SDValue(" + NodeName +
1299 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1301 ChainAssign = ChainName + " = SDValue(" + NodeName +
1302 ", " + utostr(NumResults+NumDstRegs) + ");";
1304 After.push_front(ChainAssign);
1307 if (ReplaceFroms.size() == 1) {
1308 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1309 ReplaceTos[0] + ");");
1310 } else if (!ReplaceFroms.empty()) {
1311 After.push_back("const SDValue Froms[] = {");
1312 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1313 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1314 After.push_back("};");
1315 After.push_back("const SDValue Tos[] = {");
1316 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1317 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1318 After.push_back("};");
1319 After.push_back("ReplaceUses(Froms, Tos, " +
1320 itostr(ReplaceFroms.size()) + ");");
1323 // We prefer to use SelectNodeTo since it avoids allocation when
1324 // possible and it avoids CSE map recalculation for the node's
1325 // users, however it's tricky to use in a non-root context.
1327 // We also don't use SelectNodeTo if the pattern replacement is being
1328 // used to jettison a chain result, since morphing the node in place
1329 // would leave users of the chain dangling.
1331 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1332 Code = "CurDAG->getMachineNode(" + Code;
1334 Code = "CurDAG->SelectNodeTo(N, " + Code;
1338 CodePrefix = "return ";
1340 After.push_back("return ResNode;");
1343 emitCode(CodePrefix + Code + ");");
1347 emitCode("CurDAG->setSubgraphColor(" +
1348 NodeName +".getNode(), \"yellow\");");
1349 emitCode("CurDAG->setSubgraphColor(" +
1350 NodeName +".getNode(), \"black\");");
1352 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1353 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1357 for (unsigned i = 0, e = After.size(); i != e; ++i)
1362 if (Op->isSubClassOf("SDNodeXForm")) {
1363 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1364 // PatLeaf node - the operand may or may not be a leaf node. But it should
1366 std::vector<std::string> Ops =
1367 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1368 ResNodeDecled, true);
1369 unsigned ResNo = TmpNo++;
1370 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1371 + "(" + Ops.back() + ".getNode());");
1372 NodeOps.push_back("Tmp" + utostr(ResNo));
1374 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1380 throw std::string("Unknown node in result pattern!");
1384 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1385 /// stream to match the pattern, and generate the code for the match if it
1386 /// succeeds. Returns true if the pattern is not guaranteed to match.
1387 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1388 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1389 std::set<std::string> &GeneratedDecl,
1390 std::vector<std::string> &TargetOpcodes,
1391 std::vector<std::string> &TargetVTs,
1392 bool &OutputIsVariadic,
1393 unsigned &NumInputRootOps) {
1394 OutputIsVariadic = false;
1395 NumInputRootOps = 0;
1397 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1398 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1399 GeneratedCode, GeneratedDecl,
1400 TargetOpcodes, TargetVTs,
1401 OutputIsVariadic, NumInputRootOps);
1403 // Emit the matcher, capturing named arguments in VariableMap.
1404 bool FoundChain = false;
1405 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1407 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1408 // diagnostics, which we know are impossible at this point.
1409 TreePattern &TP = *CGP.pf_begin()->second;
1411 // At this point, we know that we structurally match the pattern, but the
1412 // types of the nodes may not match. Figure out the fewest number of type
1413 // comparisons we need to emit. For example, if there is only one integer
1414 // type supported by a target, there should be no type comparisons at all for
1415 // integer patterns!
1417 // To figure out the fewest number of type checks needed, clone the pattern,
1418 // remove the types, then perform type inference on the pattern as a whole.
1419 // If there are unresolved types, emit an explicit check for those types,
1420 // apply the type to the tree, then rerun type inference. Iterate until all
1421 // types are resolved.
1423 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1424 Pat->RemoveAllTypes();
1427 // Resolve/propagate as many types as possible.
1429 bool MadeChange = true;
1431 MadeChange = Pat->ApplyTypeConstraints(TP,
1432 true/*Ignore reg constraints*/);
1434 assert(0 && "Error: could not find consistent types for something we"
1435 " already decided was ok!");
1439 // Insert a check for an unresolved type and add it to the tree. If we find
1440 // an unresolved type to add a check for, this returns true and we iterate,
1441 // otherwise we are done.
1442 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1444 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1445 false, false, false, true);
1449 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1450 /// a line causes any of them to be empty, remove them and return true when
1452 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1453 std::vector<std::pair<unsigned, std::string> > > >
1455 bool ErasedPatterns = false;
1456 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1457 Patterns[i].second.pop_back();
1458 if (Patterns[i].second.empty()) {
1459 Patterns.erase(Patterns.begin()+i);
1461 ErasedPatterns = true;
1464 return ErasedPatterns;
1467 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1468 /// code together between the patterns.
1469 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1470 std::vector<std::pair<unsigned, std::string> > > >
1471 &Patterns, unsigned Indent,
1473 typedef std::pair<unsigned, std::string> CodeLine;
1474 typedef std::vector<CodeLine> CodeList;
1475 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1477 if (Patterns.empty()) return;
1479 // Figure out how many patterns share the next code line. Explicitly copy
1480 // FirstCodeLine so that we don't invalidate a reference when changing
1482 const CodeLine FirstCodeLine = Patterns.back().second.back();
1483 unsigned LastMatch = Patterns.size()-1;
1484 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1487 // If not all patterns share this line, split the list into two pieces. The
1488 // first chunk will use this line, the second chunk won't.
1489 if (LastMatch != 0) {
1490 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1491 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1493 // FIXME: Emit braces?
1494 if (Shared.size() == 1) {
1495 const PatternToMatch &Pattern = *Shared.back().first;
1496 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1497 Pattern.getSrcPattern()->print(OS);
1498 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1499 Pattern.getDstPattern()->print(OS);
1501 unsigned AddedComplexity = Pattern.getAddedComplexity();
1502 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1503 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1505 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1507 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1509 if (FirstCodeLine.first != 1) {
1510 OS << std::string(Indent, ' ') << "{\n";
1513 EmitPatterns(Shared, Indent, OS);
1514 if (FirstCodeLine.first != 1) {
1516 OS << std::string(Indent, ' ') << "}\n";
1519 if (Other.size() == 1) {
1520 const PatternToMatch &Pattern = *Other.back().first;
1521 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1522 Pattern.getSrcPattern()->print(OS);
1523 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1524 Pattern.getDstPattern()->print(OS);
1526 unsigned AddedComplexity = Pattern.getAddedComplexity();
1527 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1528 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1530 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1532 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1534 EmitPatterns(Other, Indent, OS);
1538 // Remove this code from all of the patterns that share it.
1539 bool ErasedPatterns = EraseCodeLine(Patterns);
1541 bool isPredicate = FirstCodeLine.first == 1;
1543 // Otherwise, every pattern in the list has this line. Emit it.
1546 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1548 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1550 // If the next code line is another predicate, and if all of the pattern
1551 // in this group share the same next line, emit it inline now. Do this
1552 // until we run out of common predicates.
1553 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1554 // Check that all of the patterns in Patterns end with the same predicate.
1555 bool AllEndWithSamePredicate = true;
1556 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1557 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1558 AllEndWithSamePredicate = false;
1561 // If all of the predicates aren't the same, we can't share them.
1562 if (!AllEndWithSamePredicate) break;
1564 // Otherwise we can. Emit it shared now.
1565 OS << " &&\n" << std::string(Indent+4, ' ')
1566 << Patterns.back().second.back().second;
1567 ErasedPatterns = EraseCodeLine(Patterns);
1574 EmitPatterns(Patterns, Indent, OS);
1577 OS << std::string(Indent-2, ' ') << "}\n";
1580 static std::string getLegalCName(std::string OpName) {
1581 std::string::size_type pos = OpName.find("::");
1582 if (pos != std::string::npos)
1583 OpName.replace(pos, 2, "_");
1587 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1588 const CodeGenTarget &Target = CGP.getTargetInfo();
1590 // Get the namespace to insert instructions into.
1591 std::string InstNS = Target.getInstNamespace();
1592 if (!InstNS.empty()) InstNS += "::";
1594 // Group the patterns by their top-level opcodes.
1595 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1596 // All unique target node emission functions.
1597 std::map<std::string, unsigned> EmitFunctions;
1598 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1599 E = CGP.ptm_end(); I != E; ++I) {
1600 const PatternToMatch &Pattern = *I;
1601 TreePatternNode *Node = Pattern.getSrcPattern();
1602 if (!Node->isLeaf()) {
1603 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1604 push_back(&Pattern);
1606 const ComplexPattern *CP;
1607 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1608 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1609 push_back(&Pattern);
1610 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
1611 std::vector<Record*> OpNodes = CP->getRootNodes();
1612 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1613 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1614 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1618 errs() << "Unrecognized opcode '";
1620 errs() << "' on tree pattern '";
1621 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1627 // For each opcode, there might be multiple select functions, one per
1628 // ValueType of the node (or its first operand if it doesn't produce a
1629 // non-chain result.
1630 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1632 // Emit one Select_* method for each top-level opcode. We do this instead of
1633 // emitting one giant switch statement to support compilers where this will
1634 // result in the recursive functions taking less stack space.
1635 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1636 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1637 PBOI != E; ++PBOI) {
1638 const std::string &OpName = PBOI->first;
1639 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1640 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1642 // Split them into groups by type.
1643 std::map<MVT::SimpleValueType,
1644 std::vector<const PatternToMatch*> > PatternsByType;
1645 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1646 const PatternToMatch *Pat = PatternsOfOp[i];
1647 TreePatternNode *SrcPat = Pat->getSrcPattern();
1648 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1651 for (std::map<MVT::SimpleValueType,
1652 std::vector<const PatternToMatch*> >::iterator
1653 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1655 MVT::SimpleValueType OpVT = II->first;
1656 std::vector<const PatternToMatch*> &Patterns = II->second;
1657 typedef std::pair<unsigned, std::string> CodeLine;
1658 typedef std::vector<CodeLine> CodeList;
1659 typedef CodeList::iterator CodeListI;
1661 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1662 std::vector<std::vector<std::string> > PatternOpcodes;
1663 std::vector<std::vector<std::string> > PatternVTs;
1664 std::vector<std::set<std::string> > PatternDecls;
1665 std::vector<bool> OutputIsVariadicFlags;
1666 std::vector<unsigned> NumInputRootOpsCounts;
1667 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1668 CodeList GeneratedCode;
1669 std::set<std::string> GeneratedDecl;
1670 std::vector<std::string> TargetOpcodes;
1671 std::vector<std::string> TargetVTs;
1672 bool OutputIsVariadic;
1673 unsigned NumInputRootOps;
1674 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1675 TargetOpcodes, TargetVTs,
1676 OutputIsVariadic, NumInputRootOps);
1677 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1678 PatternDecls.push_back(GeneratedDecl);
1679 PatternOpcodes.push_back(TargetOpcodes);
1680 PatternVTs.push_back(TargetVTs);
1681 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1682 NumInputRootOpsCounts.push_back(NumInputRootOps);
1685 // Factor target node emission code (emitted by EmitResultCode) into
1686 // separate functions. Uniquing and share them among all instruction
1687 // selection routines.
1688 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1689 CodeList &GeneratedCode = CodeForPatterns[i].second;
1690 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1691 std::vector<std::string> &TargetVTs = PatternVTs[i];
1692 std::set<std::string> Decls = PatternDecls[i];
1693 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1694 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1695 std::vector<std::string> AddedInits;
1696 int CodeSize = (int)GeneratedCode.size();
1698 for (int j = CodeSize-1; j >= 0; --j) {
1699 if (LastPred == -1 && GeneratedCode[j].first == 1)
1701 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1702 AddedInits.push_back(GeneratedCode[j].second);
1705 std::string CalleeCode = "(SDNode *N";
1706 std::string CallerCode = "(N";
1707 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1708 CalleeCode += ", unsigned Opc" + utostr(j);
1709 CallerCode += ", " + TargetOpcodes[j];
1711 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1712 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1713 CallerCode += ", " + TargetVTs[j];
1715 for (std::set<std::string>::iterator
1716 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1717 std::string Name = *I;
1718 CalleeCode += ", SDValue &" + Name;
1719 CallerCode += ", " + Name;
1722 if (OutputIsVariadic) {
1723 CalleeCode += ", unsigned NumInputRootOps";
1724 CallerCode += ", " + utostr(NumInputRootOps);
1728 CalleeCode += ") {\n";
1730 for (std::vector<std::string>::const_reverse_iterator
1731 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1732 CalleeCode += " " + *I + "\n";
1734 for (int j = LastPred+1; j < CodeSize; ++j)
1735 CalleeCode += " " + GeneratedCode[j].second + "\n";
1736 for (int j = LastPred+1; j < CodeSize; ++j)
1737 GeneratedCode.pop_back();
1738 CalleeCode += "}\n";
1740 // Uniquing the emission routines.
1741 unsigned EmitFuncNum;
1742 std::map<std::string, unsigned>::iterator EFI =
1743 EmitFunctions.find(CalleeCode);
1744 if (EFI != EmitFunctions.end()) {
1745 EmitFuncNum = EFI->second;
1747 EmitFuncNum = EmitFunctions.size();
1748 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1749 // Prevent emission routines from being inlined to reduce selection
1750 // routines stack frame sizes.
1751 OS << "DISABLE_INLINE ";
1752 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1755 // Replace the emission code within selection routines with calls to the
1756 // emission functions.
1758 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
1759 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1760 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1762 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1763 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1764 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1765 GeneratedCode.push_back(std::make_pair(0, "}"));
1766 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
1768 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1772 std::string OpVTStr;
1773 if (OpVT == MVT::iPTR) {
1775 } else if (OpVT == MVT::iPTRAny) {
1776 OpVTStr = "_iPTRAny";
1777 } else if (OpVT == MVT::isVoid) {
1778 // Nodes with a void result actually have a first result type of either
1779 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1780 // void to this case, we handle it specially here.
1782 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1784 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1785 OpcodeVTMap.find(OpName);
1786 if (OpVTI == OpcodeVTMap.end()) {
1787 std::vector<std::string> VTSet;
1788 VTSet.push_back(OpVTStr);
1789 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1791 OpVTI->second.push_back(OpVTStr);
1793 // We want to emit all of the matching code now. However, we want to emit
1794 // the matches in order of minimal cost. Sort the patterns so the least
1795 // cost one is at the start.
1796 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1797 PatternSortingPredicate(CGP));
1799 // Scan the code to see if all of the patterns are reachable and if it is
1800 // possible that the last one might not match.
1801 bool mightNotMatch = true;
1802 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1803 CodeList &GeneratedCode = CodeForPatterns[i].second;
1804 mightNotMatch = false;
1806 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1807 if (GeneratedCode[j].first == 1) { // predicate.
1808 mightNotMatch = true;
1813 // If this pattern definitely matches, and if it isn't the last one, the
1814 // patterns after it CANNOT ever match. Error out.
1815 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1816 errs() << "Pattern '";
1817 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1818 errs() << "' is impossible to select!\n";
1823 // Loop through and reverse all of the CodeList vectors, as we will be
1824 // accessing them from their logical front, but accessing the end of a
1825 // vector is more efficient.
1826 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1827 CodeList &GeneratedCode = CodeForPatterns[i].second;
1828 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1831 // Next, reverse the list of patterns itself for the same reason.
1832 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1834 OS << "SDNode *Select_" << getLegalCName(OpName)
1835 << OpVTStr << "(SDNode *N) {\n";
1837 // Emit all of the patterns now, grouped together to share code.
1838 EmitPatterns(CodeForPatterns, 2, OS);
1840 // If the last pattern has predicates (which could fail) emit code to
1841 // catch the case where nothing handles a pattern.
1842 if (mightNotMatch) {
1844 OS << " CannotYetSelect(N);\n";
1845 OS << " return NULL;\n";
1851 OS << "// The main instruction selector code.\n"
1852 << "SDNode *SelectCode(SDNode *N) {\n"
1853 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1854 << " switch (N->getOpcode()) {\n"
1856 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
1858 << " case ISD::EntryToken: // These nodes remain the same.\n"
1859 << " case ISD::BasicBlock:\n"
1860 << " case ISD::Register:\n"
1861 << " case ISD::HANDLENODE:\n"
1862 << " case ISD::TargetConstant:\n"
1863 << " case ISD::TargetConstantFP:\n"
1864 << " case ISD::TargetConstantPool:\n"
1865 << " case ISD::TargetFrameIndex:\n"
1866 << " case ISD::TargetExternalSymbol:\n"
1867 << " case ISD::TargetBlockAddress:\n"
1868 << " case ISD::TargetJumpTable:\n"
1869 << " case ISD::TargetGlobalTLSAddress:\n"
1870 << " case ISD::TargetGlobalAddress:\n"
1871 << " case ISD::TokenFactor:\n"
1872 << " case ISD::CopyFromReg:\n"
1873 << " case ISD::CopyToReg: {\n"
1874 << " return NULL;\n"
1876 << " case ISD::AssertSext:\n"
1877 << " case ISD::AssertZext: {\n"
1878 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
1879 << " return NULL;\n"
1881 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1882 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1883 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1885 // Loop over all of the case statements, emiting a call to each method we
1887 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1888 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1889 PBOI != E; ++PBOI) {
1890 const std::string &OpName = PBOI->first;
1891 // Potentially multiple versions of select for this opcode. One for each
1892 // ValueType of the node (or its first true operand if it doesn't produce a
1894 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1895 OpcodeVTMap.find(OpName);
1896 std::vector<std::string> &OpVTs = OpVTI->second;
1897 OS << " case " << OpName << ": {\n";
1898 // If we have only one variant and it's the default, elide the
1899 // switch. Marginally faster, and makes MSVC happier.
1900 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1901 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1906 // Keep track of whether we see a pattern that has an iPtr result.
1907 bool HasPtrPattern = false;
1908 bool HasDefaultPattern = false;
1910 OS << " switch (NVT) {\n";
1911 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1912 std::string &VTStr = OpVTs[i];
1913 if (VTStr.empty()) {
1914 HasDefaultPattern = true;
1918 // If this is a match on iPTR: don't emit it directly, we need special
1920 if (VTStr == "_iPTR") {
1921 HasPtrPattern = true;
1924 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1925 << " return Select_" << getLegalCName(OpName)
1926 << VTStr << "(N);\n";
1928 OS << " default:\n";
1930 // If there is an iPTR result version of this pattern, emit it here.
1931 if (HasPtrPattern) {
1932 OS << " if (TLI.getPointerTy() == NVT)\n";
1933 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1935 if (HasDefaultPattern) {
1936 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1944 OS << " } // end of big switch.\n\n"
1945 << " CannotYetSelect(N);\n"
1946 << " return NULL;\n"
1950 void DAGISelEmitter::run(raw_ostream &OS) {
1951 EmitSourceFileHeader("DAG Instruction Selector for the " +
1952 CGP.getTargetInfo().getName() + " target", OS);
1954 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1955 << "// *** instruction selector class. These functions are really "
1958 OS << "// Include standard, target-independent definitions and methods used\n"
1959 << "// by the instruction selector.\n";
1960 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
1962 EmitNodeTransforms(OS);
1963 EmitPredicateFunctions(OS);
1965 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
1966 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1968 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1969 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1970 DEBUG(errs() << "\n");
1973 // At this point, we have full information about the 'Patterns' we need to
1974 // parse, both implicitly from instructions as well as from explicit pattern
1975 // definitions. Emit the resultant instruction selector.
1976 EmitInstructionSelector(OS);
1979 MatcherNode *Matcher = 0;
1980 // Walk the patterns backwards, building a matcher for each and adding it to
1981 // the matcher for the whole target.
1982 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1983 E = CGP.ptm_end(); I != E;) {
1984 const PatternToMatch &Pattern = *--E;
1985 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
1990 Matcher = new PushMatcherNode(N, Matcher);
1993 // OptimizeMatcher(Matcher);
1994 EmitMatcherTable(Matcher, OS);