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;
145 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
146 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
147 const PatternToMatch *LHS = LHSPair.first;
148 const PatternToMatch *RHS = RHSPair.first;
150 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
151 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
152 LHSSize += LHS->getAddedComplexity();
153 RHSSize += RHS->getAddedComplexity();
154 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
155 if (LHSSize < RHSSize) return false;
157 // If the patterns have equal complexity, compare generated instruction cost
158 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
159 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
160 if (LHSCost < RHSCost) return true;
161 if (LHSCost > RHSCost) return false;
163 return getResultPatternSize(LHS->getDstPattern(), CGP) <
164 getResultPatternSize(RHS->getDstPattern(), CGP);
168 /// getRegisterValueType - Look up and return the ValueType of the specified
169 /// register. If the register is a member of multiple register classes which
170 /// have different associated types, return MVT::Other.
171 static MVT::SimpleValueType getRegisterValueType(Record *R,
172 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 // Name of the folded node which produces a flag.
300 std::pair<std::string, unsigned> FoldedFlag;
301 // Names of all the folded nodes which produce chains.
302 std::vector<std::pair<std::string, unsigned> > FoldedChains;
303 // Original input chain(s).
304 std::vector<std::pair<std::string, std::string> > OrigChains;
305 std::set<std::string> Duplicates;
307 /// LSI - Load/Store information.
308 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
309 /// for each memory access. This facilitates the use of AliasAnalysis in
311 std::vector<std::string> LSI;
313 /// GeneratedCode - This is the buffer that we emit code to. The first int
314 /// indicates whether this is an exit predicate (something that should be
315 /// tested, and if true, the match fails) [when 1], or normal code to emit
316 /// [when 0], or initialization code to emit [when 2].
317 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
318 /// GeneratedDecl - This is the set of all SDValue declarations needed for
319 /// the set of patterns for each top-level opcode.
320 std::set<std::string> &GeneratedDecl;
321 /// TargetOpcodes - The target specific opcodes used by the resulting
323 std::vector<std::string> &TargetOpcodes;
324 std::vector<std::string> &TargetVTs;
325 /// OutputIsVariadic - Records whether the instruction output pattern uses
326 /// variable_ops. This requires that the Emit function be passed an
327 /// additional argument to indicate where the input varargs operands
329 bool &OutputIsVariadic;
330 /// NumInputRootOps - Records the number of operands the root node of the
331 /// input pattern has. This information is used in the generated code to
332 /// pass to Emit functions when variable_ops processing is needed.
333 unsigned &NumInputRootOps;
335 std::string ChainName;
340 void emitCheck(const std::string &S) {
342 GeneratedCode.push_back(std::make_pair(1, S));
344 void emitCode(const std::string &S) {
346 GeneratedCode.push_back(std::make_pair(0, S));
348 void emitInit(const std::string &S) {
350 GeneratedCode.push_back(std::make_pair(2, S));
352 void emitDecl(const std::string &S) {
353 assert(!S.empty() && "Invalid declaration");
354 GeneratedDecl.insert(S);
356 void emitOpcode(const std::string &Opc) {
357 TargetOpcodes.push_back(Opc);
360 void emitVT(const std::string &VT) {
361 TargetVTs.push_back(VT);
365 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
366 TreePatternNode *pattern, TreePatternNode *instr,
367 std::vector<std::pair<unsigned, std::string> > &gc,
368 std::set<std::string> &gd,
369 std::vector<std::string> &to,
370 std::vector<std::string> &tv,
373 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
374 GeneratedCode(gc), GeneratedDecl(gd),
375 TargetOpcodes(to), TargetVTs(tv),
376 OutputIsVariadic(oiv), NumInputRootOps(niro),
377 TmpNo(0), OpcNo(0), VTNo(0) {}
379 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
380 /// if the match fails. At this point, we already know that the opcode for N
381 /// matches, and the SDNode for the result has the RootName specified name.
382 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
383 const std::string &RootName, const std::string &ChainSuffix,
386 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
387 const std::string &RootName,
388 const std::string &ChainSuffix, bool &FoundChain);
390 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
391 /// we actually have to build a DAG!
392 std::vector<std::string>
393 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
394 bool InFlagDecled, bool ResNodeDecled,
395 bool LikeLeaf = false, bool isRoot = false);
397 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
398 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
399 /// 'Pat' may be missing types. If we find an unresolved type to add a check
400 /// for, this returns true otherwise false if Pat has all types.
401 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
402 const std::string &Prefix, bool isRoot = false) {
404 if (Pat->getExtTypes() != Other->getExtTypes()) {
405 // Move a type over from 'other' to 'pat'.
406 Pat->setTypes(Other->getExtTypes());
407 // The top level node type is checked outside of the select function.
409 emitCheck(Prefix + ".getValueType() == " +
410 getName(Pat->getTypeNum(0)));
414 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
415 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
416 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
417 Prefix + utostr(OpNo)))
423 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
425 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
426 bool &ChainEmitted, bool &InFlagDecled,
427 bool &ResNodeDecled, bool isRoot = false) {
428 const CodeGenTarget &T = CGP.getTargetInfo();
429 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
430 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
431 TreePatternNode *Child = N->getChild(i);
432 if (!Child->isLeaf()) {
433 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
434 InFlagDecled, ResNodeDecled);
436 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
437 if (!Child->getName().empty()) {
438 std::string Name = RootName + utostr(OpNo);
439 if (Duplicates.find(Name) != Duplicates.end())
440 // A duplicate! Do not emit a copy for this node.
444 Record *RR = DI->getDef();
445 if (RR->isSubClassOf("Register")) {
446 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
447 if (RVT == MVT::Flag) {
449 emitCode("SDValue InFlag = " +
450 getValueName(RootName + utostr(OpNo)) + ";");
453 emitCode("InFlag = " +
454 getValueName(RootName + utostr(OpNo)) + ";");
457 emitCode("SDValue Chain = CurDAG->getEntryNode();");
462 emitCode("SDValue InFlag(0, 0);");
465 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
466 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
467 ", " + getNodeName(RootName) + "->getDebugLoc()" +
468 ", " + getQualifiedName(RR) +
469 ", " + getValueName(RootName + utostr(OpNo)) +
470 ", InFlag).getNode();");
471 ResNodeDecled = true;
472 emitCode(ChainName + " = SDValue(ResNode, 0);");
473 emitCode("InFlag = SDValue(ResNode, 1);");
480 if (N->NodeHasProperty(SDNPInFlag, CGP)) {
482 emitCode("SDValue InFlag = " + getNodeName(RootName) +
483 "->getOperand(" + utostr(OpNo) + ");");
487 emitCode("InFlag = " + getNodeName(RootName) +
488 "->getOperand(" + utostr(OpNo) + ");");
494 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
495 /// if the match fails. At this point, we already know that the opcode for N
496 /// matches, and the SDNode for the result has the RootName specified name.
497 void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
498 const std::string &RootName,
499 const std::string &ChainSuffix,
501 // Save loads/stores matched by a pattern.
502 if (!N->isLeaf() && N->getName().empty()) {
503 if (N->NodeHasProperty(SDNPMemOperand, CGP))
504 LSI.push_back(getNodeName(RootName));
507 bool isRoot = (P == NULL);
508 // Emit instruction predicates. Each predicate is just a string for now.
510 // Record input varargs info.
511 NumInputRootOps = N->getNumChildren();
512 emitCheck(PredicateCheck);
516 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
517 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
518 ")->getSExtValue() == INT64_C(" +
519 itostr(II->getValue()) + ")");
522 assert(N->getComplexPatternInfo(CGP) != 0 &&
523 "Cannot match this as a leaf value!");
526 // If this node has a name associated with it, capture it in VariableMap. If
527 // we already saw this in the pattern, emit code to verify dagness.
528 if (!N->getName().empty()) {
529 std::string &VarMapEntry = VariableMap[N->getName()];
530 if (VarMapEntry.empty()) {
531 VarMapEntry = RootName;
533 // If we get here, this is a second reference to a specific name. Since
534 // we already have checked that the first reference is valid, we don't
535 // have to recursively match it, just check that it's the same as the
536 // previously named thing.
537 emitCheck(VarMapEntry + " == " + RootName);
543 // Emit code to load the child nodes and match their contents recursively.
545 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
546 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
551 // Check if it's profitable to fold the node. e.g. Check for multiple uses
553 std::string ParentName(RootName.begin(), RootName.end()-1);
555 // If this is just an interior node, check to see if it has a single
556 // use. If the node has multiple uses and the pattern has a load as
557 // an operand, then we can't fold the load.
558 emitCheck(getValueName(RootName) + ".hasOneUse()");
559 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
560 // If the immediate use can somehow reach this node through another
561 // path, then can't fold it either or it will create a cycle.
562 // e.g. In the following diagram, XX can reach ld through YY. If
563 // ld is folded into XX, then YY is both a predecessor and a successor
574 // We know we need the check if N's parent is not the root.
575 bool NeedCheck = P != Pattern;
577 // If the parent is the root and the node has more than one operand,
579 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
581 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
582 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
583 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
584 PInfo.getNumOperands() > 1 ||
585 PInfo.hasProperty(SDNPHasChain) ||
586 PInfo.hasProperty(SDNPInFlag) ||
587 PInfo.hasProperty(SDNPOptInFlag);
591 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
592 ", " + getNodeName(ParentName) + ", N)");
593 emitCheck("IsLegalToFold(" + getValueName(RootName) +
594 ", " + getNodeName(ParentName) + ", N)");
596 // Otherwise, just verify that the node only has a single use.
597 emitCheck(getValueName(RootName) + ".hasOneUse()");
604 emitCheck("IsChainCompatible(" + ChainName + ".getNode(), " +
605 getNodeName(RootName) + ")");
606 OrigChains.push_back(std::make_pair(ChainName,
607 getValueName(RootName)));
610 ChainName = "Chain" + ChainSuffix;
612 if (!N->getComplexPatternInfo(CGP) ||
614 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
619 // If there are node predicates for this, emit the calls.
620 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
621 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
623 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
624 // a constant without a predicate fn that has more that one bit set, handle
625 // this as a special case. This is usually for targets that have special
626 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
627 // handling stuff). Using these instructions is often far more efficient
628 // than materializing the constant. Unfortunately, both the instcombiner
629 // and the dag combiner can often infer that bits are dead, and thus drop
630 // them from the mask in the dag. For example, it might turn 'AND X, 255'
631 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
634 (N->getOperator()->getName() == "and" ||
635 N->getOperator()->getName() == "or") &&
636 N->getChild(1)->isLeaf() &&
637 N->getChild(1)->getPredicateFns().empty()) {
638 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
639 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
640 emitInit("SDValue " + RootName + "0" + " = " +
641 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
642 emitInit("SDValue " + RootName + "1" + " = " +
643 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
645 unsigned NTmp = TmpNo++;
646 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
647 " = dyn_cast<ConstantSDNode>(" +
648 getNodeName(RootName + "1") + ");");
649 emitCheck("Tmp" + utostr(NTmp));
650 const char *MaskPredicate = N->getOperator()->getName() == "or"
651 ? "CheckOrMask(" : "CheckAndMask(";
652 emitCheck(MaskPredicate + getValueName(RootName + "0") +
653 ", Tmp" + utostr(NTmp) +
654 ", INT64_C(" + itostr(II->getValue()) + "))");
656 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
657 ChainSuffix + utostr(0), FoundChain);
663 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
664 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
665 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
667 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
668 ChainSuffix + utostr(OpNo), FoundChain);
671 // Handle complex patterns.
672 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
673 std::string Fn = CP->getSelectFunc();
674 unsigned NumOps = CP->getNumOperands();
675 for (unsigned i = 0; i < NumOps; ++i) {
676 emitDecl("CPTmp" + RootName + "_" + utostr(i));
677 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
679 if (CP->hasProperty(SDNPHasChain)) {
680 emitDecl("CPInChain");
681 emitDecl("Chain" + ChainSuffix);
682 emitCode("SDValue CPInChain;");
683 emitCode("SDValue Chain" + ChainSuffix + ";");
686 std::string Code = Fn + "(N, "; // always pass in the root.
687 Code += getValueName(RootName);
688 for (unsigned i = 0; i < NumOps; i++)
689 Code += ", CPTmp" + RootName + "_" + utostr(i);
690 if (CP->hasProperty(SDNPHasChain)) {
691 ChainName = "Chain" + ChainSuffix;
692 Code += ", CPInChain, " + ChainName;
694 emitCheck(Code + ")");
698 void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
699 TreePatternNode *Parent,
700 const std::string &RootName,
701 const std::string &ChainSuffix,
703 if (!Child->isLeaf()) {
704 // If it's not a leaf, recursively match.
705 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
706 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
707 CInfo.getEnumName());
708 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
709 bool HasChain = false;
710 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
712 FoldedChains.push_back(std::make_pair(getValueName(RootName),
713 CInfo.getNumResults()));
715 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
716 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
717 "Pattern folded multiple nodes which produce flags?");
718 FoldedFlag = std::make_pair(getValueName(RootName),
719 CInfo.getNumResults() + (unsigned)HasChain);
724 if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
725 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
726 bool HasChain = false;
728 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
730 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
731 FoldedChains.push_back(std::make_pair("CPInChain",
732 PInfo.getNumResults()));
734 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
735 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
736 "Pattern folded multiple nodes which produce flags?");
737 FoldedFlag = std::make_pair(getValueName(RootName),
738 CP->getNumOperands() + (unsigned)HasChain);
743 // If this child has a name associated with it, capture it in VarMap. If
744 // we already saw this in the pattern, emit code to verify dagness.
745 if (!Child->getName().empty()) {
746 std::string &VarMapEntry = VariableMap[Child->getName()];
747 if (VarMapEntry.empty()) {
748 VarMapEntry = getValueName(RootName);
750 // If we get here, this is a second reference to a specific name.
751 // Since we already have checked that the first reference is valid,
752 // we don't have to recursively match it, just check that it's the
753 // same as the previously named thing.
754 emitCheck(VarMapEntry + " == " + getValueName(RootName));
755 Duplicates.insert(getValueName(RootName));
760 // Handle leaves of various types.
761 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
762 Record *LeafRec = DI->getDef();
763 if (LeafRec->isSubClassOf("RegisterClass") ||
764 LeafRec->isSubClassOf("PointerLikeRegClass")) {
765 // Handle register references. Nothing to do here.
766 } else if (LeafRec->isSubClassOf("Register")) {
767 // Handle register references.
768 } else if (LeafRec->getName() == "srcvalue") {
769 // Place holder for SRCVALUE nodes. Nothing to do here.
770 } else if (LeafRec->isSubClassOf("ValueType")) {
771 // Make sure this is the specified value type.
772 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
773 ")->getVT() == MVT::" + LeafRec->getName());
774 } else if (LeafRec->isSubClassOf("CondCode")) {
775 // Make sure this is the specified cond code.
776 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
777 ")->get() == ISD::" + LeafRec->getName());
783 assert(0 && "Unknown leaf type!");
786 // If there are node predicates for this, emit the calls.
787 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
788 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
793 if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
794 unsigned NTmp = TmpNo++;
795 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
796 " = dyn_cast<ConstantSDNode>("+
797 getNodeName(RootName) + ");");
798 emitCheck("Tmp" + utostr(NTmp));
799 unsigned CTmp = TmpNo++;
800 emitCode("int64_t CN"+ utostr(CTmp) +
801 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
802 emitCheck("CN" + utostr(CTmp) + " == "
803 "INT64_C(" +itostr(II->getValue()) + ")");
809 assert(0 && "Unknown leaf type!");
812 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
813 /// we actually have to build a DAG!
814 std::vector<std::string>
815 PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
816 std::vector<Record*> DstRegs,
817 bool InFlagDecled, bool ResNodeDecled,
818 bool LikeLeaf, bool isRoot) {
819 // List of arguments of getMachineNode() or SelectNodeTo().
820 std::vector<std::string> NodeOps;
821 // This is something selected from the pattern we matched.
822 if (!N->getName().empty()) {
823 const std::string &VarName = N->getName();
824 std::string Val = VariableMap[VarName];
826 errs() << "Variable '" << VarName << " referenced but not defined "
827 << "and not caught earlier!\n";
831 unsigned ResNo = TmpNo++;
832 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
833 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
834 std::string CastType;
835 std::string TmpVar = "Tmp" + utostr(ResNo);
836 switch (N->getTypeNum(0)) {
838 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
839 << " type as an immediate constant. Aborting\n";
841 case MVT::i1: CastType = "bool"; break;
842 case MVT::i8: CastType = "unsigned char"; break;
843 case MVT::i16: CastType = "unsigned short"; break;
844 case MVT::i32: CastType = "unsigned"; break;
845 case MVT::i64: CastType = "uint64_t"; break;
847 emitCode("SDValue " + TmpVar +
848 " = CurDAG->getTargetConstant(((" + CastType +
849 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
850 getEnumName(N->getTypeNum(0)) + ");");
851 NodeOps.push_back(getValueName(TmpVar));
852 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
853 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
854 std::string TmpVar = "Tmp" + utostr(ResNo);
855 emitCode("SDValue " + TmpVar +
856 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
857 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
858 Val + ")->getValueType(0));");
859 NodeOps.push_back(getValueName(TmpVar));
860 } else if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
861 for (unsigned i = 0; i < CP->getNumOperands(); ++i)
862 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
864 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
865 // node even if it isn't one. Don't select it.
867 if (isRoot && N->isLeaf()) {
868 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
869 emitCode("return NULL;");
872 NodeOps.push_back(getValueName(Val));
877 // If this is an explicit register reference, handle it.
878 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
879 unsigned ResNo = TmpNo++;
880 if (DI->getDef()->isSubClassOf("Register")) {
881 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
882 getQualifiedName(DI->getDef()) + ", " +
883 getEnumName(N->getTypeNum(0)) + ");");
884 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
886 } else if (DI->getDef()->getName() == "zero_reg") {
887 emitCode("SDValue Tmp" + utostr(ResNo) +
888 " = CurDAG->getRegister(0, " +
889 getEnumName(N->getTypeNum(0)) + ");");
890 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
892 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
893 // Handle a reference to a register class. This is used
894 // in COPY_TO_SUBREG instructions.
895 emitCode("SDValue Tmp" + utostr(ResNo) +
896 " = CurDAG->getTargetConstant(" +
897 getQualifiedName(DI->getDef()) + "RegClassID, " +
899 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
902 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
903 unsigned ResNo = TmpNo++;
904 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
905 emitCode("SDValue Tmp" + utostr(ResNo) +
906 " = CurDAG->getTargetConstant(0x" +
907 utohexstr((uint64_t) II->getValue()) +
908 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
909 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
916 assert(0 && "Unknown leaf type!");
920 Record *Op = N->getOperator();
921 if (Op->isSubClassOf("Instruction")) {
922 const CodeGenTarget &CGT = CGP.getTargetInfo();
923 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
924 const DAGInstruction &Inst = CGP.getInstruction(Op);
925 const TreePattern *InstPat = Inst.getPattern();
926 // FIXME: Assume actual pattern comes before "implicit".
927 TreePatternNode *InstPatNode =
928 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
929 : (InstPat ? InstPat->getTree(0) : NULL);
930 if (InstPatNode && !InstPatNode->isLeaf() &&
931 InstPatNode->getOperator()->getName() == "set") {
932 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
934 bool IsVariadic = isRoot && II.isVariadic;
935 // FIXME: fix how we deal with physical register operands.
936 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
937 bool HasImpResults = isRoot && DstRegs.size() > 0;
938 bool NodeHasOptInFlag = isRoot &&
939 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
940 bool NodeHasInFlag = isRoot &&
941 Pattern->TreeHasProperty(SDNPInFlag, CGP);
942 bool NodeHasOutFlag = isRoot &&
943 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
944 bool NodeHasChain = InstPatNode &&
945 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
946 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
947 unsigned NumResults = Inst.getNumResults();
948 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
950 // Record output varargs info.
951 OutputIsVariadic = IsVariadic;
953 if (NodeHasOptInFlag) {
954 emitCode("bool HasInFlag = "
955 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
959 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
961 // How many results is this pattern expected to produce?
962 unsigned NumPatResults = 0;
963 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
964 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
965 if (VT != MVT::isVoid && VT != MVT::Flag)
969 if (OrigChains.size() > 0) {
970 // The original input chain is being ignored. If it is not just
971 // pointing to the op that's being folded, we should create a
972 // TokenFactor with it and the chain of the folded op as the new chain.
973 // We could potentially be doing multiple levels of folding, in that
974 // case, the TokenFactor can have more operands.
975 emitCode("SmallVector<SDValue, 8> InChains;");
976 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
977 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
978 OrigChains[i].second + ".getNode()) {");
979 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
982 emitCode("InChains.push_back(" + ChainName + ");");
983 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
984 "N->getDebugLoc(), MVT::Other, "
985 "&InChains[0], InChains.size());");
987 emitCode("CurDAG->setSubgraphColor(" + ChainName +
988 ".getNode(), \"yellow\");");
989 emitCode("CurDAG->setSubgraphColor(" + ChainName +
990 ".getNode(), \"black\");");
994 // Loop over all of the operands of the instruction pattern, emitting code
995 // to fill them all in. The node 'N' usually has number children equal to
996 // the number of input operands of the instruction. However, in cases
997 // where there are predicate operands for an instruction, we need to fill
998 // in the 'execute always' values. Match up the node operands to the
999 // instruction operands to do this.
1000 std::vector<std::string> AllOps;
1001 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1002 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1003 std::vector<std::string> Ops;
1005 // Determine what to emit for this operand.
1006 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1007 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1008 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1009 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1010 // This is a predicate or optional def operand; emit the
1011 // 'default ops' operands.
1012 const DAGDefaultOperand &DefaultOp =
1013 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1014 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1015 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1016 InFlagDecled, ResNodeDecled);
1017 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1020 // Otherwise this is a normal operand or a predicate operand without
1021 // 'execute always'; emit it.
1022 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1023 InFlagDecled, ResNodeDecled);
1024 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1029 // Emit all the chain and CopyToReg stuff.
1030 bool ChainEmitted = NodeHasChain;
1031 if (NodeHasInFlag || HasImpInputs)
1032 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1033 InFlagDecled, ResNodeDecled, true);
1034 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1035 if (!InFlagDecled) {
1036 emitCode("SDValue InFlag(0, 0);");
1037 InFlagDecled = true;
1039 if (NodeHasOptInFlag) {
1040 emitCode("if (HasInFlag) {");
1041 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1046 unsigned ResNo = TmpNo++;
1048 unsigned OpsNo = OpcNo;
1049 std::string CodePrefix;
1050 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1051 std::deque<std::string> After;
1052 std::string NodeName;
1054 NodeName = "Tmp" + utostr(ResNo);
1055 CodePrefix = "SDValue " + NodeName + "(";
1057 NodeName = "ResNode";
1058 if (!ResNodeDecled) {
1059 CodePrefix = "SDNode *" + NodeName + " = ";
1060 ResNodeDecled = true;
1062 CodePrefix = NodeName + " = ";
1065 std::string Code = "Opc" + utostr(OpcNo);
1067 if (!isRoot || (InputHasChain && !NodeHasChain))
1068 // For call to "getMachineNode()".
1069 Code += ", N->getDebugLoc()";
1071 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1073 // Output order: results, chain, flags
1075 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1076 Code += ", VT" + utostr(VTNo);
1077 emitVT(getEnumName(N->getTypeNum(0)));
1079 // Add types for implicit results in physical registers, scheduler will
1080 // care of adding copyfromreg nodes.
1081 for (unsigned i = 0; i < NumDstRegs; i++) {
1082 Record *RR = DstRegs[i];
1083 if (RR->isSubClassOf("Register")) {
1084 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1085 Code += ", " + getEnumName(RVT);
1089 Code += ", MVT::Other";
1091 Code += ", MVT::Flag";
1095 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1096 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1099 // Figure out whether any operands at the end of the op list are not
1100 // part of the variable section.
1101 std::string EndAdjust;
1102 if (NodeHasInFlag || HasImpInputs)
1103 EndAdjust = "-1"; // Always has one flag.
1104 else if (NodeHasOptInFlag)
1105 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1107 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1108 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1110 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1114 // Populate MemRefs with entries for each memory accesses covered by
1116 if (isRoot && !LSI.empty()) {
1117 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1118 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1119 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1120 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1121 emitCode(MemRefs + "[" + utostr(i) + "] = "
1122 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1123 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1124 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1130 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1132 AllOps.push_back(ChainName);
1136 if (NodeHasInFlag || HasImpInputs)
1137 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1138 else if (NodeHasOptInFlag) {
1139 emitCode("if (HasInFlag)");
1140 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1142 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1144 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1145 AllOps.push_back("InFlag");
1147 unsigned NumOps = AllOps.size();
1149 if (!NodeHasOptInFlag && NumOps < 4) {
1150 for (unsigned i = 0; i != NumOps; ++i)
1151 Code += ", " + AllOps[i];
1153 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1154 for (unsigned i = 0; i != NumOps; ++i) {
1155 OpsCode += AllOps[i];
1159 emitCode(OpsCode + " };");
1160 Code += ", Ops" + utostr(OpsNo) + ", ";
1161 if (NodeHasOptInFlag) {
1162 Code += "HasInFlag ? ";
1163 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1165 Code += utostr(NumOps);
1172 std::vector<std::string> ReplaceFroms;
1173 std::vector<std::string> ReplaceTos;
1175 NodeOps.push_back("Tmp" + utostr(ResNo));
1178 if (NodeHasOutFlag) {
1179 if (!InFlagDecled) {
1180 After.push_back("SDValue InFlag(ResNode, " +
1181 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1183 InFlagDecled = true;
1185 After.push_back("InFlag = SDValue(ResNode, " +
1186 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1190 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1191 ReplaceFroms.push_back("SDValue(" +
1192 FoldedChains[j].first + ".getNode(), " +
1193 utostr(FoldedChains[j].second) +
1195 ReplaceTos.push_back("SDValue(ResNode, " +
1196 utostr(NumResults+NumDstRegs) + ")");
1199 if (NodeHasOutFlag) {
1200 if (FoldedFlag.first != "") {
1201 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1202 utostr(FoldedFlag.second) + ")");
1203 ReplaceTos.push_back("InFlag");
1205 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
1206 ReplaceFroms.push_back("SDValue(N, " +
1207 utostr(NumPatResults + (unsigned)InputHasChain)
1209 ReplaceTos.push_back("InFlag");
1213 if (!ReplaceFroms.empty() && InputHasChain) {
1214 ReplaceFroms.push_back("SDValue(N, " +
1215 utostr(NumPatResults) + ")");
1216 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1217 ChainName + ".getResNo()" + ")");
1218 ChainAssignmentNeeded |= NodeHasChain;
1221 // User does not expect the instruction would produce a chain!
1222 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1224 } else if (InputHasChain && !NodeHasChain) {
1225 // One of the inner node produces a chain.
1226 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1227 ReplaceFroms.push_back("SDValue(N, " +
1228 utostr(NumPatResults) + ")");
1229 ReplaceTos.push_back(ChainName);
1233 if (ChainAssignmentNeeded) {
1234 // Remember which op produces the chain.
1235 std::string ChainAssign;
1237 ChainAssign = ChainName + " = SDValue(" + NodeName +
1238 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1240 ChainAssign = ChainName + " = SDValue(" + NodeName +
1241 ", " + utostr(NumResults+NumDstRegs) + ");";
1243 After.push_front(ChainAssign);
1246 if (ReplaceFroms.size() == 1) {
1247 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1248 ReplaceTos[0] + ");");
1249 } else if (!ReplaceFroms.empty()) {
1250 After.push_back("const SDValue Froms[] = {");
1251 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1252 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1253 After.push_back("};");
1254 After.push_back("const SDValue Tos[] = {");
1255 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1256 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1257 After.push_back("};");
1258 After.push_back("ReplaceUses(Froms, Tos, " +
1259 itostr(ReplaceFroms.size()) + ");");
1262 // We prefer to use SelectNodeTo since it avoids allocation when
1263 // possible and it avoids CSE map recalculation for the node's
1264 // users, however it's tricky to use in a non-root context.
1266 // We also don't use SelectNodeTo if the pattern replacement is being
1267 // used to jettison a chain result, since morphing the node in place
1268 // would leave users of the chain dangling.
1270 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1271 Code = "CurDAG->getMachineNode(" + Code;
1273 Code = "CurDAG->SelectNodeTo(N, " + Code;
1277 CodePrefix = "return ";
1279 After.push_back("return ResNode;");
1282 emitCode(CodePrefix + Code + ");");
1286 emitCode("CurDAG->setSubgraphColor(" +
1287 NodeName +".getNode(), \"yellow\");");
1288 emitCode("CurDAG->setSubgraphColor(" +
1289 NodeName +".getNode(), \"black\");");
1291 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1292 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1296 for (unsigned i = 0, e = After.size(); i != e; ++i)
1301 if (Op->isSubClassOf("SDNodeXForm")) {
1302 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1303 // PatLeaf node - the operand may or may not be a leaf node. But it should
1305 std::vector<std::string> Ops =
1306 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1307 ResNodeDecled, true);
1308 unsigned ResNo = TmpNo++;
1309 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1310 + "(" + Ops.back() + ".getNode());");
1311 NodeOps.push_back("Tmp" + utostr(ResNo));
1313 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1319 throw std::string("Unknown node in result pattern!");
1323 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1324 /// stream to match the pattern, and generate the code for the match if it
1325 /// succeeds. Returns true if the pattern is not guaranteed to match.
1326 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1327 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1328 std::set<std::string> &GeneratedDecl,
1329 std::vector<std::string> &TargetOpcodes,
1330 std::vector<std::string> &TargetVTs,
1331 bool &OutputIsVariadic,
1332 unsigned &NumInputRootOps) {
1333 OutputIsVariadic = false;
1334 NumInputRootOps = 0;
1336 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1337 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1338 GeneratedCode, GeneratedDecl,
1339 TargetOpcodes, TargetVTs,
1340 OutputIsVariadic, NumInputRootOps);
1342 // Emit the matcher, capturing named arguments in VariableMap.
1343 bool FoundChain = false;
1344 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1346 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1347 // diagnostics, which we know are impossible at this point.
1348 TreePattern &TP = *CGP.pf_begin()->second;
1350 // At this point, we know that we structurally match the pattern, but the
1351 // types of the nodes may not match. Figure out the fewest number of type
1352 // comparisons we need to emit. For example, if there is only one integer
1353 // type supported by a target, there should be no type comparisons at all for
1354 // integer patterns!
1356 // To figure out the fewest number of type checks needed, clone the pattern,
1357 // remove the types, then perform type inference on the pattern as a whole.
1358 // If there are unresolved types, emit an explicit check for those types,
1359 // apply the type to the tree, then rerun type inference. Iterate until all
1360 // types are resolved.
1362 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1363 Pat->RemoveAllTypes();
1366 // Resolve/propagate as many types as possible.
1368 bool MadeChange = true;
1370 MadeChange = Pat->ApplyTypeConstraints(TP,
1371 true/*Ignore reg constraints*/);
1373 assert(0 && "Error: could not find consistent types for something we"
1374 " already decided was ok!");
1378 // Insert a check for an unresolved type and add it to the tree. If we find
1379 // an unresolved type to add a check for, this returns true and we iterate,
1380 // otherwise we are done.
1381 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1383 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1384 false, false, false, true);
1388 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1389 /// a line causes any of them to be empty, remove them and return true when
1391 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1392 std::vector<std::pair<unsigned, std::string> > > >
1394 bool ErasedPatterns = false;
1395 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1396 Patterns[i].second.pop_back();
1397 if (Patterns[i].second.empty()) {
1398 Patterns.erase(Patterns.begin()+i);
1400 ErasedPatterns = true;
1403 return ErasedPatterns;
1406 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1407 /// code together between the patterns.
1408 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1409 std::vector<std::pair<unsigned, std::string> > > >
1410 &Patterns, unsigned Indent,
1412 typedef std::pair<unsigned, std::string> CodeLine;
1413 typedef std::vector<CodeLine> CodeList;
1414 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1416 if (Patterns.empty()) return;
1418 // Figure out how many patterns share the next code line. Explicitly copy
1419 // FirstCodeLine so that we don't invalidate a reference when changing
1421 const CodeLine FirstCodeLine = Patterns.back().second.back();
1422 unsigned LastMatch = Patterns.size()-1;
1423 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1426 // If not all patterns share this line, split the list into two pieces. The
1427 // first chunk will use this line, the second chunk won't.
1428 if (LastMatch != 0) {
1429 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1430 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1432 // FIXME: Emit braces?
1433 if (Shared.size() == 1) {
1434 const PatternToMatch &Pattern = *Shared.back().first;
1435 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1436 Pattern.getSrcPattern()->print(OS);
1437 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1438 Pattern.getDstPattern()->print(OS);
1440 unsigned AddedComplexity = Pattern.getAddedComplexity();
1441 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1442 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1444 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1446 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1448 if (FirstCodeLine.first != 1) {
1449 OS << std::string(Indent, ' ') << "{\n";
1452 EmitPatterns(Shared, Indent, OS);
1453 if (FirstCodeLine.first != 1) {
1455 OS << std::string(Indent, ' ') << "}\n";
1458 if (Other.size() == 1) {
1459 const PatternToMatch &Pattern = *Other.back().first;
1460 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1461 Pattern.getSrcPattern()->print(OS);
1462 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1463 Pattern.getDstPattern()->print(OS);
1465 unsigned AddedComplexity = Pattern.getAddedComplexity();
1466 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1467 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1469 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1471 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1473 EmitPatterns(Other, Indent, OS);
1477 // Remove this code from all of the patterns that share it.
1478 bool ErasedPatterns = EraseCodeLine(Patterns);
1480 bool isPredicate = FirstCodeLine.first == 1;
1482 // Otherwise, every pattern in the list has this line. Emit it.
1485 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1487 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1489 // If the next code line is another predicate, and if all of the pattern
1490 // in this group share the same next line, emit it inline now. Do this
1491 // until we run out of common predicates.
1492 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1493 // Check that all of the patterns in Patterns end with the same predicate.
1494 bool AllEndWithSamePredicate = true;
1495 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1496 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1497 AllEndWithSamePredicate = false;
1500 // If all of the predicates aren't the same, we can't share them.
1501 if (!AllEndWithSamePredicate) break;
1503 // Otherwise we can. Emit it shared now.
1504 OS << " &&\n" << std::string(Indent+4, ' ')
1505 << Patterns.back().second.back().second;
1506 ErasedPatterns = EraseCodeLine(Patterns);
1513 EmitPatterns(Patterns, Indent, OS);
1516 OS << std::string(Indent-2, ' ') << "}\n";
1519 static std::string getLegalCName(std::string OpName) {
1520 std::string::size_type pos = OpName.find("::");
1521 if (pos != std::string::npos)
1522 OpName.replace(pos, 2, "_");
1526 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1527 const CodeGenTarget &Target = CGP.getTargetInfo();
1529 // Get the namespace to insert instructions into.
1530 std::string InstNS = Target.getInstNamespace();
1531 if (!InstNS.empty()) InstNS += "::";
1533 // Group the patterns by their top-level opcodes.
1534 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1535 // All unique target node emission functions.
1536 std::map<std::string, unsigned> EmitFunctions;
1537 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1538 E = CGP.ptm_end(); I != E; ++I) {
1539 const PatternToMatch &Pattern = *I;
1540 TreePatternNode *Node = Pattern.getSrcPattern();
1541 if (!Node->isLeaf()) {
1542 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1543 push_back(&Pattern);
1545 const ComplexPattern *CP;
1546 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1547 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1548 push_back(&Pattern);
1549 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
1550 std::vector<Record*> OpNodes = CP->getRootNodes();
1551 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1552 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1553 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1557 errs() << "Unrecognized opcode '";
1559 errs() << "' on tree pattern '";
1560 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1566 // For each opcode, there might be multiple select functions, one per
1567 // ValueType of the node (or its first operand if it doesn't produce a
1568 // non-chain result.
1569 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1571 // Emit one Select_* method for each top-level opcode. We do this instead of
1572 // emitting one giant switch statement to support compilers where this will
1573 // result in the recursive functions taking less stack space.
1574 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1575 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1576 PBOI != E; ++PBOI) {
1577 const std::string &OpName = PBOI->first;
1578 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1579 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1581 // Split them into groups by type.
1582 std::map<MVT::SimpleValueType,
1583 std::vector<const PatternToMatch*> > PatternsByType;
1584 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1585 const PatternToMatch *Pat = PatternsOfOp[i];
1586 TreePatternNode *SrcPat = Pat->getSrcPattern();
1587 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1590 for (std::map<MVT::SimpleValueType,
1591 std::vector<const PatternToMatch*> >::iterator
1592 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1594 MVT::SimpleValueType OpVT = II->first;
1595 std::vector<const PatternToMatch*> &Patterns = II->second;
1596 typedef std::pair<unsigned, std::string> CodeLine;
1597 typedef std::vector<CodeLine> CodeList;
1598 typedef CodeList::iterator CodeListI;
1600 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1601 std::vector<std::vector<std::string> > PatternOpcodes;
1602 std::vector<std::vector<std::string> > PatternVTs;
1603 std::vector<std::set<std::string> > PatternDecls;
1604 std::vector<bool> OutputIsVariadicFlags;
1605 std::vector<unsigned> NumInputRootOpsCounts;
1606 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1607 CodeList GeneratedCode;
1608 std::set<std::string> GeneratedDecl;
1609 std::vector<std::string> TargetOpcodes;
1610 std::vector<std::string> TargetVTs;
1611 bool OutputIsVariadic;
1612 unsigned NumInputRootOps;
1613 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1614 TargetOpcodes, TargetVTs,
1615 OutputIsVariadic, NumInputRootOps);
1616 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1617 PatternDecls.push_back(GeneratedDecl);
1618 PatternOpcodes.push_back(TargetOpcodes);
1619 PatternVTs.push_back(TargetVTs);
1620 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1621 NumInputRootOpsCounts.push_back(NumInputRootOps);
1624 // Factor target node emission code (emitted by EmitResultCode) into
1625 // separate functions. Uniquing and share them among all instruction
1626 // selection routines.
1627 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1628 CodeList &GeneratedCode = CodeForPatterns[i].second;
1629 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1630 std::vector<std::string> &TargetVTs = PatternVTs[i];
1631 std::set<std::string> Decls = PatternDecls[i];
1632 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1633 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1634 std::vector<std::string> AddedInits;
1635 int CodeSize = (int)GeneratedCode.size();
1637 for (int j = CodeSize-1; j >= 0; --j) {
1638 if (LastPred == -1 && GeneratedCode[j].first == 1)
1640 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1641 AddedInits.push_back(GeneratedCode[j].second);
1644 std::string CalleeCode = "(SDNode *N";
1645 std::string CallerCode = "(N";
1646 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1647 CalleeCode += ", unsigned Opc" + utostr(j);
1648 CallerCode += ", " + TargetOpcodes[j];
1650 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1651 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1652 CallerCode += ", " + TargetVTs[j];
1654 for (std::set<std::string>::iterator
1655 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1656 std::string Name = *I;
1657 CalleeCode += ", SDValue &" + Name;
1658 CallerCode += ", " + Name;
1661 if (OutputIsVariadic) {
1662 CalleeCode += ", unsigned NumInputRootOps";
1663 CallerCode += ", " + utostr(NumInputRootOps);
1667 CalleeCode += ") {\n";
1669 for (std::vector<std::string>::const_reverse_iterator
1670 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1671 CalleeCode += " " + *I + "\n";
1673 for (int j = LastPred+1; j < CodeSize; ++j)
1674 CalleeCode += " " + GeneratedCode[j].second + "\n";
1675 for (int j = LastPred+1; j < CodeSize; ++j)
1676 GeneratedCode.pop_back();
1677 CalleeCode += "}\n";
1679 // Uniquing the emission routines.
1680 unsigned EmitFuncNum;
1681 std::map<std::string, unsigned>::iterator EFI =
1682 EmitFunctions.find(CalleeCode);
1683 if (EFI != EmitFunctions.end()) {
1684 EmitFuncNum = EFI->second;
1686 EmitFuncNum = EmitFunctions.size();
1687 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1688 // Prevent emission routines from being inlined to reduce selection
1689 // routines stack frame sizes.
1690 OS << "DISABLE_INLINE ";
1691 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1694 // Replace the emission code within selection routines with calls to the
1695 // emission functions.
1697 GeneratedCode.push_back(std::make_pair(0,
1698 "CurDAG->setSubgraphColor(N, \"red\");"));
1699 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) +CallerCode;
1700 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1702 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1703 GeneratedCode.push_back(std::make_pair(0,
1704 " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1705 GeneratedCode.push_back(std::make_pair(0,
1706 " CurDAG->setSubgraphColor(Result, \"black\");"));
1707 GeneratedCode.push_back(std::make_pair(0, "}"));
1709 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1713 std::string OpVTStr;
1714 if (OpVT == MVT::iPTR) {
1716 } else if (OpVT == MVT::iPTRAny) {
1717 OpVTStr = "_iPTRAny";
1718 } else if (OpVT == MVT::isVoid) {
1719 // Nodes with a void result actually have a first result type of either
1720 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1721 // void to this case, we handle it specially here.
1723 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1725 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1726 OpcodeVTMap.find(OpName);
1727 if (OpVTI == OpcodeVTMap.end()) {
1728 std::vector<std::string> VTSet;
1729 VTSet.push_back(OpVTStr);
1730 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1732 OpVTI->second.push_back(OpVTStr);
1734 // We want to emit all of the matching code now. However, we want to emit
1735 // the matches in order of minimal cost. Sort the patterns so the least
1736 // cost one is at the start.
1737 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1738 PatternSortingPredicate(CGP));
1740 // Scan the code to see if all of the patterns are reachable and if it is
1741 // possible that the last one might not match.
1742 bool mightNotMatch = true;
1743 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1744 CodeList &GeneratedCode = CodeForPatterns[i].second;
1745 mightNotMatch = false;
1747 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1748 if (GeneratedCode[j].first == 1) { // predicate.
1749 mightNotMatch = true;
1754 // If this pattern definitely matches, and if it isn't the last one, the
1755 // patterns after it CANNOT ever match. Error out.
1756 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1757 errs() << "Pattern '";
1758 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1759 errs() << "' is impossible to select!\n";
1764 // Loop through and reverse all of the CodeList vectors, as we will be
1765 // accessing them from their logical front, but accessing the end of a
1766 // vector is more efficient.
1767 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1768 CodeList &GeneratedCode = CodeForPatterns[i].second;
1769 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1772 // Next, reverse the list of patterns itself for the same reason.
1773 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1775 OS << "SDNode *Select_" << getLegalCName(OpName)
1776 << OpVTStr << "(SDNode *N) {\n";
1778 // Emit all of the patterns now, grouped together to share code.
1779 EmitPatterns(CodeForPatterns, 2, OS);
1781 // If the last pattern has predicates (which could fail) emit code to
1782 // catch the case where nothing handles a pattern.
1783 if (mightNotMatch) {
1785 OS << " CannotYetSelect(N);\n";
1786 OS << " return NULL;\n";
1792 OS << "// The main instruction selector code.\n"
1793 << "SDNode *SelectCode(SDNode *N) {\n"
1794 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1795 << " switch (N->getOpcode()) {\n"
1797 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
1799 << " case ISD::EntryToken: // These nodes remain the same.\n"
1800 << " case ISD::BasicBlock:\n"
1801 << " case ISD::Register:\n"
1802 << " case ISD::HANDLENODE:\n"
1803 << " case ISD::TargetConstant:\n"
1804 << " case ISD::TargetConstantFP:\n"
1805 << " case ISD::TargetConstantPool:\n"
1806 << " case ISD::TargetFrameIndex:\n"
1807 << " case ISD::TargetExternalSymbol:\n"
1808 << " case ISD::TargetBlockAddress:\n"
1809 << " case ISD::TargetJumpTable:\n"
1810 << " case ISD::TargetGlobalTLSAddress:\n"
1811 << " case ISD::TargetGlobalAddress:\n"
1812 << " case ISD::TokenFactor:\n"
1813 << " case ISD::CopyFromReg:\n"
1814 << " case ISD::CopyToReg: {\n"
1815 << " return NULL;\n"
1817 << " case ISD::AssertSext:\n"
1818 << " case ISD::AssertZext: {\n"
1819 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
1820 << " return NULL;\n"
1822 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1823 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1824 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1826 // Loop over all of the case statements, emiting a call to each method we
1828 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1829 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1830 PBOI != E; ++PBOI) {
1831 const std::string &OpName = PBOI->first;
1832 // Potentially multiple versions of select for this opcode. One for each
1833 // ValueType of the node (or its first true operand if it doesn't produce a
1835 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1836 OpcodeVTMap.find(OpName);
1837 std::vector<std::string> &OpVTs = OpVTI->second;
1838 OS << " case " << OpName << ": {\n";
1839 // If we have only one variant and it's the default, elide the
1840 // switch. Marginally faster, and makes MSVC happier.
1841 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1842 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1847 // Keep track of whether we see a pattern that has an iPtr result.
1848 bool HasPtrPattern = false;
1849 bool HasDefaultPattern = false;
1851 OS << " switch (NVT) {\n";
1852 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1853 std::string &VTStr = OpVTs[i];
1854 if (VTStr.empty()) {
1855 HasDefaultPattern = true;
1859 // If this is a match on iPTR: don't emit it directly, we need special
1861 if (VTStr == "_iPTR") {
1862 HasPtrPattern = true;
1865 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1866 << " return Select_" << getLegalCName(OpName)
1867 << VTStr << "(N);\n";
1869 OS << " default:\n";
1871 // If there is an iPTR result version of this pattern, emit it here.
1872 if (HasPtrPattern) {
1873 OS << " if (TLI.getPointerTy() == NVT)\n";
1874 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1876 if (HasDefaultPattern) {
1877 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1885 OS << " } // end of big switch.\n\n"
1886 << " CannotYetSelect(N);\n"
1887 << " return NULL;\n"
1892 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1893 // In particular, we want to match maximal patterns first and lowest cost within
1894 // a particular complexity first.
1895 struct PatternSortingPredicate2 {
1896 PatternSortingPredicate2(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
1897 CodeGenDAGPatterns &CGP;
1899 bool operator()(const PatternToMatch *LHS,
1900 const PatternToMatch *RHS) {
1901 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
1902 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
1903 LHSSize += LHS->getAddedComplexity();
1904 RHSSize += RHS->getAddedComplexity();
1905 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1906 if (LHSSize < RHSSize) return false;
1908 // If the patterns have equal complexity, compare generated instruction cost
1909 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
1910 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
1911 if (LHSCost < RHSCost) return true;
1912 if (LHSCost > RHSCost) return false;
1914 return getResultPatternSize(LHS->getDstPattern(), CGP) <
1915 getResultPatternSize(RHS->getDstPattern(), CGP);
1921 void DAGISelEmitter::run(raw_ostream &OS) {
1922 EmitSourceFileHeader("DAG Instruction Selector for the " +
1923 CGP.getTargetInfo().getName() + " target", OS);
1925 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1926 << "// *** instruction selector class. These functions are really "
1929 OS << "// Include standard, target-independent definitions and methods used\n"
1930 << "// by the instruction selector.\n";
1931 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
1933 EmitNodeTransforms(OS);
1934 EmitPredicateFunctions(OS);
1936 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
1937 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1939 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1940 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1941 DEBUG(errs() << "\n");
1944 // At this point, we have full information about the 'Patterns' we need to
1945 // parse, both implicitly from instructions as well as from explicit pattern
1946 // definitions. Emit the resultant instruction selector.
1947 EmitInstructionSelector(OS);
1950 MatcherNode *Matcher = 0;
1952 // Add all the patterns to a temporary list so we can sort them.
1953 std::vector<const PatternToMatch*> Patterns;
1954 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1956 Patterns.push_back(&*I);
1958 // We want to process the matches in order of minimal cost. Sort the patterns
1959 // so the least cost one is at the start.
1960 // FIXME: Eliminate "PatternSortingPredicate" and rename.
1961 std::stable_sort(Patterns.begin(), Patterns.end(),
1962 PatternSortingPredicate2(CGP));
1965 // Walk the patterns backwards (since we append to the front of the generated
1966 // code), building a matcher for each and adding it to the matcher for the
1968 while (!Patterns.empty()) {
1969 const PatternToMatch &Pattern = *Patterns.back();
1970 Patterns.pop_back();
1972 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
1977 Matcher = new PushMatcherNode(N, Matcher);
1980 // OptimizeMatcher(Matcher);
1982 EmitMatcherTable(Matcher, OS);