blob: 9d8e0a69eed27d50166959be865f4daa6cbe35de [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerfd6c2f02007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/MathExtras.h"
19#include "llvm/Support/Streams.h"
20#include <algorithm>
Dan Gohman6761ff52008-07-07 21:00:17 +000021#include <deque>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +000025// DAGISelEmitter Helper methods
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026//
27
Chris Lattner4ca8ff02008-01-05 22:25:12 +000028/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
29/// ComplexPattern.
30static bool NodeIsComplexPattern(TreePatternNode *N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031 return (N->isLeaf() &&
32 dynamic_cast<DefInit*>(N->getLeafValue()) &&
33 static_cast<DefInit*>(N->getLeafValue())->getDef()->
34 isSubClassOf("ComplexPattern"));
35}
36
Chris Lattner4ca8ff02008-01-05 22:25:12 +000037/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
38/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
Chris Lattnerae506702008-01-06 01:10:31 +000040 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041 if (N->isLeaf() &&
42 dynamic_cast<DefInit*>(N->getLeafValue()) &&
43 static_cast<DefInit*>(N->getLeafValue())->getDef()->
44 isSubClassOf("ComplexPattern")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +000045 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
46 ->getDef());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 }
48 return NULL;
49}
50
51/// getPatternSize - Return the 'size' of this pattern. We want to match large
52/// patterns before small ones. This is used to determine the size of a
53/// pattern.
Chris Lattnerae506702008-01-06 01:10:31 +000054static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Duncan Sands92c43912008-06-06 12:08:01 +000055 assert((EMVT::isExtIntegerInVTs(P->getExtTypes()) ||
56 EMVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057 P->getExtTypeNum(0) == MVT::isVoid ||
58 P->getExtTypeNum(0) == MVT::Flag ||
Mon P Wangce3ac892008-07-30 04:36:53 +000059 P->getExtTypeNum(0) == MVT::iPTR ||
60 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061 "Not a valid pattern node to size!");
62 unsigned Size = 3; // The node itself.
63 // If the root node is a ConstantSDNode, increases its size.
64 // e.g. (set R32:$dst, 0).
65 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
66 Size += 2;
67
68 // FIXME: This is a hack to statically increase the priority of patterns
69 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
70 // Later we can allow complexity / cost for each pattern to be (optionally)
71 // specified. To get best possible pattern match we'll need to dynamically
72 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner4ca8ff02008-01-05 22:25:12 +000073 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 if (AM)
75 Size += AM->getNumOperands() * 3;
76
77 // If this node has some predicate function that must match, it adds to the
78 // complexity of this node.
79 if (!P->getPredicateFn().empty())
80 ++Size;
81
82 // Count children in the count if they are also nodes.
83 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
84 TreePatternNode *Child = P->getChild(i);
85 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner4ca8ff02008-01-05 22:25:12 +000086 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087 else if (Child->isLeaf()) {
88 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
89 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
90 else if (NodeIsComplexPattern(Child))
Chris Lattner4ca8ff02008-01-05 22:25:12 +000091 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 else if (!Child->getPredicateFn().empty())
93 ++Size;
94 }
95 }
96
97 return Size;
98}
99
100/// getResultPatternCost - Compute the number of instructions for this pattern.
101/// This is a temporary hack. We should really include the instruction
102/// latencies in this calculation.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000103static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000104 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105 if (P->isLeaf()) return 0;
106
107 unsigned Cost = 0;
108 Record *Op = P->getOperator();
109 if (Op->isSubClassOf("Instruction")) {
110 Cost++;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000111 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000112 if (II.usesCustomDAGSchedInserter)
113 Cost += 10;
114 }
115 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000116 Cost += getResultPatternCost(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 return Cost;
118}
119
120/// getResultPatternCodeSize - Compute the code size of instructions for this
121/// pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000122static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000123 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124 if (P->isLeaf()) return 0;
125
126 unsigned Cost = 0;
127 Record *Op = P->getOperator();
128 if (Op->isSubClassOf("Instruction")) {
129 Cost += Op->getValueAsInt("CodeSize");
130 }
131 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000132 Cost += getResultPatternSize(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 return Cost;
134}
135
136// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
137// In particular, we want to match maximal patterns first and lowest cost within
138// a particular complexity first.
139struct PatternSortingPredicate {
Chris Lattnerae506702008-01-06 01:10:31 +0000140 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
141 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142
Chris Lattner81915752008-01-05 22:30:17 +0000143 bool operator()(const PatternToMatch *LHS,
144 const PatternToMatch *RHS) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000145 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
146 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 LHSSize += LHS->getAddedComplexity();
148 RHSSize += RHS->getAddedComplexity();
149 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
150 if (LHSSize < RHSSize) return false;
151
152 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000153 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
154 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 if (LHSCost < RHSCost) return true;
156 if (LHSCost > RHSCost) return false;
157
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000158 return getResultPatternSize(LHS->getDstPattern(), CGP) <
159 getResultPatternSize(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 }
161};
162
163/// getRegisterValueType - Look up and return the first ValueType of specified
164/// RegisterClass record
Duncan Sands92c43912008-06-06 12:08:01 +0000165static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
167 return RC->getValueTypeNum(0);
168 return MVT::Other;
169}
170
171
172/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
173/// type information from it.
174static void RemoveAllTypes(TreePatternNode *N) {
175 N->removeTypes();
176 if (!N->isLeaf())
177 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
178 RemoveAllTypes(N->getChild(i));
179}
180
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181/// NodeHasProperty - return true if TreePatternNode has the specified
182/// property.
183static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000184 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 if (N->isLeaf()) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000186 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 if (CP)
188 return CP->hasProperty(Property);
189 return false;
190 }
191 Record *Operator = N->getOperator();
192 if (!Operator->isSubClassOf("SDNode")) return false;
193
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000194 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195}
196
197static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000198 CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000199 if (NodeHasProperty(N, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 return true;
201
202 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
203 TreePatternNode *Child = N->getChild(i);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000204 if (PatternHasProperty(Child, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 return true;
206 }
207
208 return false;
209}
210
Evan Cheng43f0c652008-07-03 08:39:51 +0000211static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
212 return CGP.getSDNodeInfo(Op).getEnumName();
213}
214
215static
216bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
217 bool isStore = !N->isLeaf() &&
218 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
219 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
220 return false;
221
222 bool HasChain = false;
223 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
224 TreePatternNode *Child = N->getChild(i);
225 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
226 HasChain = true;
227 break;
228 }
229 }
230 return HasChain;
231}
232
Chris Lattner7fdd9342008-01-05 22:43:57 +0000233//===----------------------------------------------------------------------===//
Chris Lattner227da452008-01-05 22:54:53 +0000234// Node Transformation emitter implementation.
235//
236void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
237 // Walk the pattern fragments, adding them to a map, which sorts them by
238 // name.
Chris Lattnerae506702008-01-06 01:10:31 +0000239 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner227da452008-01-05 22:54:53 +0000240 NXsByNameTy NXsByName;
241
Chris Lattnerae506702008-01-06 01:10:31 +0000242 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner227da452008-01-05 22:54:53 +0000243 I != E; ++I)
244 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
245
246 OS << "\n// Node transformations.\n";
247
248 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
249 I != E; ++I) {
250 Record *SDNode = I->second.first;
251 std::string Code = I->second.second;
252
253 if (Code.empty()) continue; // Empty code? Skip it.
254
Chris Lattner14948ea2008-01-05 22:58:54 +0000255 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner227da452008-01-05 22:54:53 +0000256 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
257
Dan Gohman8181bd12008-07-27 21:46:04 +0000258 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner227da452008-01-05 22:54:53 +0000259 << ") {\n";
260 if (ClassName != "SDNode")
261 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
262 OS << Code << "\n}\n";
263 }
264}
265
266//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +0000267// Predicate emitter implementation.
268//
269
270void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
271 OS << "\n// Predicate functions.\n";
272
273 // Walk the pattern fragments, adding them to a map, which sorts them by
274 // name.
275 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
276 PFsByNameTy PFsByName;
277
Chris Lattnerae506702008-01-06 01:10:31 +0000278 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000279 I != E; ++I)
280 PFsByName.insert(std::make_pair(I->first->getName(), *I));
281
282
283 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
284 I != E; ++I) {
285 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
286 TreePattern *P = I->second.second;
287
288 // If there is a code init for this fragment, emit the predicate code.
289 std::string Code = PatFragRecord->getValueAsCode("Predicate");
290 if (Code.empty()) continue;
291
292 if (P->getOnlyTree()->isLeaf())
293 OS << "inline bool Predicate_" << PatFragRecord->getName()
294 << "(SDNode *N) {\n";
295 else {
296 std::string ClassName =
Chris Lattner14948ea2008-01-05 22:58:54 +0000297 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000298 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
299
300 OS << "inline bool Predicate_" << PatFragRecord->getName()
301 << "(SDNode *" << C2 << ") {\n";
302 if (ClassName != "SDNode")
303 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
304 }
305 OS << Code << "\n}\n";
306 }
307
308 OS << "\n\n";
309}
310
311
312//===----------------------------------------------------------------------===//
313// PatternCodeEmitter implementation.
314//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315class PatternCodeEmitter {
316private:
Chris Lattnerae506702008-01-06 01:10:31 +0000317 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318
319 // Predicates.
Dan Gohmane97f1a32008-08-22 00:20:26 +0000320 std::string PredicateCheck;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 // Pattern cost.
322 unsigned Cost;
323 // Instruction selector pattern.
324 TreePatternNode *Pattern;
325 // Matched instruction.
326 TreePatternNode *Instruction;
327
328 // Node to name mapping
329 std::map<std::string, std::string> VariableMap;
330 // Node to operator mapping
331 std::map<std::string, Record*> OperatorMap;
Evan Cheng07f307d2008-02-05 22:50:29 +0000332 // Name of the folded node which produces a flag.
333 std::pair<std::string, unsigned> FoldedFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 // Names of all the folded nodes which produce chains.
335 std::vector<std::pair<std::string, unsigned> > FoldedChains;
336 // Original input chain(s).
337 std::vector<std::pair<std::string, std::string> > OrigChains;
338 std::set<std::string> Duplicates;
339
Dan Gohman12a9c082008-02-06 22:27:42 +0000340 /// LSI - Load/Store information.
341 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
342 /// for each memory access. This facilitates the use of AliasAnalysis in
343 /// the backend.
344 std::vector<std::string> LSI;
345
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 /// GeneratedCode - This is the buffer that we emit code to. The first int
347 /// indicates whether this is an exit predicate (something that should be
348 /// tested, and if true, the match fails) [when 1], or normal code to emit
349 /// [when 0], or initialization code to emit [when 2].
350 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman8181bd12008-07-27 21:46:04 +0000351 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 /// the set of patterns for each top-level opcode.
353 std::set<std::string> &GeneratedDecl;
354 /// TargetOpcodes - The target specific opcodes used by the resulting
355 /// instructions.
356 std::vector<std::string> &TargetOpcodes;
357 std::vector<std::string> &TargetVTs;
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000358 /// OutputIsVariadic - Records whether the instruction output pattern uses
359 /// variable_ops. This requires that the Emit function be passed an
360 /// additional argument to indicate where the input varargs operands
361 /// begin.
362 bool &OutputIsVariadic;
363 /// NumInputRootOps - Records the number of operands the root node of the
364 /// input pattern has. This information is used in the generated code to
365 /// pass to Emit functions when variable_ops processing is needed.
366 unsigned &NumInputRootOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367
368 std::string ChainName;
369 unsigned TmpNo;
370 unsigned OpcNo;
371 unsigned VTNo;
372
373 void emitCheck(const std::string &S) {
374 if (!S.empty())
375 GeneratedCode.push_back(std::make_pair(1, S));
376 }
377 void emitCode(const std::string &S) {
378 if (!S.empty())
379 GeneratedCode.push_back(std::make_pair(0, S));
380 }
381 void emitInit(const std::string &S) {
382 if (!S.empty())
383 GeneratedCode.push_back(std::make_pair(2, S));
384 }
385 void emitDecl(const std::string &S) {
386 assert(!S.empty() && "Invalid declaration");
387 GeneratedDecl.insert(S);
388 }
389 void emitOpcode(const std::string &Opc) {
390 TargetOpcodes.push_back(Opc);
391 OpcNo++;
392 }
393 void emitVT(const std::string &VT) {
394 TargetVTs.push_back(VT);
395 VTNo++;
396 }
397public:
Dan Gohmane97f1a32008-08-22 00:20:26 +0000398 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 TreePatternNode *pattern, TreePatternNode *instr,
400 std::vector<std::pair<unsigned, std::string> > &gc,
401 std::set<std::string> &gd,
402 std::vector<std::string> &to,
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000403 std::vector<std::string> &tv,
404 bool &oiv,
405 unsigned &niro)
Dan Gohmane97f1a32008-08-22 00:20:26 +0000406 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407 GeneratedCode(gc), GeneratedDecl(gd),
408 TargetOpcodes(to), TargetVTs(tv),
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000409 OutputIsVariadic(oiv), NumInputRootOps(niro),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 TmpNo(0), OpcNo(0), VTNo(0) {}
411
412 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
413 /// if the match fails. At this point, we already know that the opcode for N
414 /// matches, and the SDNode for the result has the RootName specified name.
415 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
416 const std::string &RootName, const std::string &ChainSuffix,
417 bool &FoundChain) {
Dan Gohman12a9c082008-02-06 22:27:42 +0000418
419 // Save loads/stores matched by a pattern.
420 if (!N->isLeaf() && N->getName().empty()) {
Mon P Wang6bde9ec2008-06-25 08:15:39 +0000421 if (NodeHasProperty(N, SDNPMemOperand, CGP))
Dan Gohman12a9c082008-02-06 22:27:42 +0000422 LSI.push_back(RootName);
Dan Gohman12a9c082008-02-06 22:27:42 +0000423 }
424
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 bool isRoot = (P == NULL);
426 // Emit instruction predicates. Each predicate is just a string for now.
427 if (isRoot) {
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000428 // Record input varargs info.
429 NumInputRootOps = N->getNumChildren();
430
Evan Cheng43f0c652008-07-03 08:39:51 +0000431 if (DisablePatternForFastISel(N, CGP))
Dan Gohmana29efcf2008-08-13 19:55:00 +0000432 emitCheck("!Fast");
Evan Cheng43f0c652008-07-03 08:39:51 +0000433
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 emitCheck(PredicateCheck);
435 }
436
437 if (N->isLeaf()) {
438 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
439 emitCheck("cast<ConstantSDNode>(" + RootName +
440 ")->getSignExtended() == " + itostr(II->getValue()));
441 return;
442 } else if (!NodeIsComplexPattern(N)) {
443 assert(0 && "Cannot match this as a leaf value!");
444 abort();
445 }
446 }
447
448 // If this node has a name associated with it, capture it in VariableMap. If
449 // we already saw this in the pattern, emit code to verify dagness.
450 if (!N->getName().empty()) {
451 std::string &VarMapEntry = VariableMap[N->getName()];
452 if (VarMapEntry.empty()) {
453 VarMapEntry = RootName;
454 } else {
455 // If we get here, this is a second reference to a specific name. Since
456 // we already have checked that the first reference is valid, we don't
457 // have to recursively match it, just check that it's the same as the
458 // previously named thing.
459 emitCheck(VarMapEntry + " == " + RootName);
460 return;
461 }
462
463 if (!N->isLeaf())
464 OperatorMap[N->getName()] = N->getOperator();
465 }
466
467
468 // Emit code to load the child nodes and match their contents recursively.
469 unsigned OpNo = 0;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000470 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
471 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 bool EmittedUseCheck = false;
473 if (HasChain) {
474 if (NodeHasChain)
475 OpNo = 1;
476 if (!isRoot) {
477 // Multiple uses of actual result?
478 emitCheck(RootName + ".hasOneUse()");
479 EmittedUseCheck = true;
480 if (NodeHasChain) {
481 // If the immediate use can somehow reach this node through another
482 // path, then can't fold it either or it will create a cycle.
483 // e.g. In the following diagram, XX can reach ld through YY. If
484 // ld is folded into XX, then YY is both a predecessor and a successor
485 // of XX.
486 //
487 // [ld]
488 // ^ ^
489 // | |
490 // / \---
491 // / [YY]
492 // | ^
493 // [XX]-------|
Evan Cheng43f0c652008-07-03 08:39:51 +0000494 bool NeedCheck = P != Pattern;
495 if (!NeedCheck) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000496 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 NeedCheck =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000498 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
499 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
500 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 PInfo.getNumOperands() > 1 ||
502 PInfo.hasProperty(SDNPHasChain) ||
503 PInfo.hasProperty(SDNPInFlag) ||
504 PInfo.hasProperty(SDNPOptInFlag);
505 }
506
507 if (NeedCheck) {
508 std::string ParentName(RootName.begin(), RootName.end()-1);
509 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
510 ".Val, N.Val)");
511 }
512 }
513 }
514
515 if (NodeHasChain) {
516 if (FoundChain) {
517 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
518 "IsChainCompatible(" + ChainName + ".Val, " +
519 RootName + ".Val))");
520 OrigChains.push_back(std::make_pair(ChainName, RootName));
521 } else
522 FoundChain = true;
523 ChainName = "Chain" + ChainSuffix;
Dan Gohman8181bd12008-07-27 21:46:04 +0000524 emitInit("SDValue " + ChainName + " = " + RootName +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 ".getOperand(0);");
526 }
527 }
528
529 // Don't fold any node which reads or writes a flag and has multiple uses.
530 // FIXME: We really need to separate the concepts of flag and "glue". Those
531 // real flag results, e.g. X86CMP output, can have multiple uses.
532 // FIXME: If the optional incoming flag does not exist. Then it is ok to
533 // fold it.
534 if (!isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000535 (PatternHasProperty(N, SDNPInFlag, CGP) ||
536 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
537 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 if (!EmittedUseCheck) {
539 // Multiple uses of actual result?
540 emitCheck(RootName + ".hasOneUse()");
541 }
542 }
543
544 // If there is a node predicate for this, emit the call.
545 if (!N->getPredicateFn().empty())
546 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
547
548
549 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
550 // a constant without a predicate fn that has more that one bit set, handle
551 // this as a special case. This is usually for targets that have special
552 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
553 // handling stuff). Using these instructions is often far more efficient
554 // than materializing the constant. Unfortunately, both the instcombiner
555 // and the dag combiner can often infer that bits are dead, and thus drop
556 // them from the mask in the dag. For example, it might turn 'AND X, 255'
557 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
558 // to handle this.
559 if (!N->isLeaf() &&
560 (N->getOperator()->getName() == "and" ||
561 N->getOperator()->getName() == "or") &&
562 N->getChild(1)->isLeaf() &&
563 N->getChild(1)->getPredicateFn().empty()) {
564 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
565 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Dan Gohman8181bd12008-07-27 21:46:04 +0000566 emitInit("SDValue " + RootName + "0" + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 RootName + ".getOperand(" + utostr(0) + ");");
Dan Gohman8181bd12008-07-27 21:46:04 +0000568 emitInit("SDValue " + RootName + "1" + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 RootName + ".getOperand(" + utostr(1) + ");");
570
571 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
572 const char *MaskPredicate = N->getOperator()->getName() == "or"
573 ? "CheckOrMask(" : "CheckAndMask(";
574 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
575 RootName + "1), " + itostr(II->getValue()) + ")");
576
Christopher Lamb059c7c92008-01-31 07:27:46 +0000577 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 ChainSuffix + utostr(0), FoundChain);
579 return;
580 }
581 }
582 }
583
584 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000585 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 RootName + ".getOperand(" +utostr(OpNo) + ");");
587
Christopher Lamb059c7c92008-01-31 07:27:46 +0000588 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 ChainSuffix + utostr(OpNo), FoundChain);
590 }
591
592 // Handle cases when root is a complex pattern.
593 const ComplexPattern *CP;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000594 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595 std::string Fn = CP->getSelectFunc();
596 unsigned NumOps = CP->getNumOperands();
597 for (unsigned i = 0; i < NumOps; ++i) {
598 emitDecl("CPTmp" + utostr(i));
Dan Gohman8181bd12008-07-27 21:46:04 +0000599 emitCode("SDValue CPTmp" + utostr(i) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 }
601 if (CP->hasProperty(SDNPHasChain)) {
602 emitDecl("CPInChain");
603 emitDecl("Chain" + ChainSuffix);
Dan Gohman8181bd12008-07-27 21:46:04 +0000604 emitCode("SDValue CPInChain;");
605 emitCode("SDValue Chain" + ChainSuffix + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 }
607
608 std::string Code = Fn + "(" + RootName + ", " + RootName;
609 for (unsigned i = 0; i < NumOps; i++)
610 Code += ", CPTmp" + utostr(i);
611 if (CP->hasProperty(SDNPHasChain)) {
612 ChainName = "Chain" + ChainSuffix;
613 Code += ", CPInChain, Chain" + ChainSuffix;
614 }
615 emitCheck(Code + ")");
616 }
617 }
618
619 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb059c7c92008-01-31 07:27:46 +0000620 const std::string &RootName,
621 const std::string &ParentRootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 const std::string &ChainSuffix, bool &FoundChain) {
623 if (!Child->isLeaf()) {
624 // If it's not a leaf, recursively match.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000625 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 emitCheck(RootName + ".getOpcode() == " +
627 CInfo.getEnumName());
628 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng07f307d2008-02-05 22:50:29 +0000629 bool HasChain = false;
630 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
631 HasChain = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
Evan Cheng07f307d2008-02-05 22:50:29 +0000633 }
634 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
635 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
636 "Pattern folded multiple nodes which produce flags?");
637 FoldedFlag = std::make_pair(RootName,
638 CInfo.getNumResults() + (unsigned)HasChain);
639 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 } else {
641 // If this child has a name associated with it, capture it in VarMap. If
642 // we already saw this in the pattern, emit code to verify dagness.
643 if (!Child->getName().empty()) {
644 std::string &VarMapEntry = VariableMap[Child->getName()];
645 if (VarMapEntry.empty()) {
646 VarMapEntry = RootName;
647 } else {
648 // If we get here, this is a second reference to a specific name.
649 // Since we already have checked that the first reference is valid,
650 // we don't have to recursively match it, just check that it's the
651 // same as the previously named thing.
652 emitCheck(VarMapEntry + " == " + RootName);
653 Duplicates.insert(RootName);
654 return;
655 }
656 }
657
658 // Handle leaves of various types.
659 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
660 Record *LeafRec = DI->getDef();
661 if (LeafRec->isSubClassOf("RegisterClass") ||
662 LeafRec->getName() == "ptr_rc") {
663 // Handle register references. Nothing to do here.
664 } else if (LeafRec->isSubClassOf("Register")) {
665 // Handle register references.
666 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
667 // Handle complex pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000668 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 std::string Fn = CP->getSelectFunc();
670 unsigned NumOps = CP->getNumOperands();
671 for (unsigned i = 0; i < NumOps; ++i) {
672 emitDecl("CPTmp" + utostr(i));
Dan Gohman8181bd12008-07-27 21:46:04 +0000673 emitCode("SDValue CPTmp" + utostr(i) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 }
675 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000676 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 FoldedChains.push_back(std::make_pair("CPInChain",
678 PInfo.getNumResults()));
679 ChainName = "Chain" + ChainSuffix;
680 emitDecl("CPInChain");
681 emitDecl(ChainName);
Dan Gohman8181bd12008-07-27 21:46:04 +0000682 emitCode("SDValue CPInChain;");
683 emitCode("SDValue " + ChainName + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 }
685
Christopher Lamb059c7c92008-01-31 07:27:46 +0000686 std::string Code = Fn + "(";
687 if (CP->hasAttribute(CPAttrParentAsRoot)) {
688 Code += ParentRootName + ", ";
689 } else {
690 Code += "N, ";
691 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 if (CP->hasProperty(SDNPHasChain)) {
693 std::string ParentName(RootName.begin(), RootName.end()-1);
694 Code += ParentName + ", ";
695 }
696 Code += RootName;
697 for (unsigned i = 0; i < NumOps; i++)
698 Code += ", CPTmp" + utostr(i);
699 if (CP->hasProperty(SDNPHasChain))
700 Code += ", CPInChain, Chain" + ChainSuffix;
701 emitCheck(Code + ")");
702 } else if (LeafRec->getName() == "srcvalue") {
703 // Place holder for SRCVALUE nodes. Nothing to do here.
704 } else if (LeafRec->isSubClassOf("ValueType")) {
705 // Make sure this is the specified value type.
706 emitCheck("cast<VTSDNode>(" + RootName +
707 ")->getVT() == MVT::" + LeafRec->getName());
708 } else if (LeafRec->isSubClassOf("CondCode")) {
709 // Make sure this is the specified cond code.
710 emitCheck("cast<CondCodeSDNode>(" + RootName +
711 ")->get() == ISD::" + LeafRec->getName());
712 } else {
713#ifndef NDEBUG
714 Child->dump();
715 cerr << " ";
716#endif
717 assert(0 && "Unknown leaf type!");
718 }
719
720 // If there is a node predicate for this, emit the call.
721 if (!Child->getPredicateFn().empty())
722 emitCheck(Child->getPredicateFn() + "(" + RootName +
723 ".Val)");
724 } else if (IntInit *II =
725 dynamic_cast<IntInit*>(Child->getLeafValue())) {
726 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
727 unsigned CTmp = TmpNo++;
728 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
729 RootName + ")->getSignExtended();");
730
731 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
732 } else {
733#ifndef NDEBUG
734 Child->dump();
735#endif
736 assert(0 && "Unknown leaf type!");
737 }
738 }
739 }
740
741 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
742 /// we actually have to build a DAG!
743 std::vector<std::string>
Evan Cheng775baac2007-09-12 23:30:14 +0000744 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 bool InFlagDecled, bool ResNodeDecled,
746 bool LikeLeaf = false, bool isRoot = false) {
747 // List of arguments of getTargetNode() or SelectNodeTo().
748 std::vector<std::string> NodeOps;
749 // This is something selected from the pattern we matched.
750 if (!N->getName().empty()) {
Scott Michel30124c22008-01-29 02:29:31 +0000751 const std::string &VarName = N->getName();
752 std::string Val = VariableMap[VarName];
753 bool ModifiedVal = false;
Scott Michelac7091c2008-02-15 23:05:48 +0000754 if (Val.empty()) {
Bill Wendling39d33752008-02-26 10:45:29 +0000755 cerr << "Variable '" << VarName << " referenced but not defined "
756 << "and not caught earlier!\n";
757 abort();
Scott Michelac7091c2008-02-15 23:05:48 +0000758 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
760 // Already selected this operand, just return the tmpval.
761 NodeOps.push_back(Val);
762 return NodeOps;
763 }
764
765 const ComplexPattern *CP;
766 unsigned ResNo = TmpNo++;
767 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
768 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
769 std::string CastType;
Scott Michel30124c22008-01-29 02:29:31 +0000770 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 switch (N->getTypeNum(0)) {
772 default:
773 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
774 << " type as an immediate constant. Aborting\n";
775 abort();
776 case MVT::i1: CastType = "bool"; break;
777 case MVT::i8: CastType = "unsigned char"; break;
778 case MVT::i16: CastType = "unsigned short"; break;
779 case MVT::i32: CastType = "unsigned"; break;
780 case MVT::i64: CastType = "uint64_t"; break;
781 }
Dan Gohman8181bd12008-07-27 21:46:04 +0000782 emitCode("SDValue " + TmpVar +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 " = CurDAG->getTargetConstant(((" + CastType +
784 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
785 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
787 // value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000788 Val = TmpVar;
789 ModifiedVal = true;
790 NodeOps.push_back(Val);
Nate Begemane2ba64f2008-02-14 08:57:00 +0000791 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
792 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
793 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000794 emitCode("SDValue " + TmpVar +
Nate Begemane2ba64f2008-02-14 08:57:00 +0000795 " = CurDAG->getTargetConstantFP(cast<ConstantFPSDNode>(" +
796 Val + ")->getValueAPF(), cast<ConstantFPSDNode>(" + Val +
797 ")->getValueType(0));");
798 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
799 // value if used multiple times by this pattern result.
800 Val = TmpVar;
801 ModifiedVal = true;
802 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
804 Record *Op = OperatorMap[N->getName()];
805 // Transform ExternalSymbol to TargetExternalSymbol
806 if (Op && Op->getName() == "externalsym") {
Scott Michel30124c22008-01-29 02:29:31 +0000807 std::string TmpVar = "Tmp"+utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000808 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
810 Val + ")->getSymbol(), " +
811 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
813 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000814 Val = TmpVar;
815 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 }
Scott Michel30124c22008-01-29 02:29:31 +0000817 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
819 || N->getOperator()->getName() == "tglobaltlsaddr")) {
820 Record *Op = OperatorMap[N->getName()];
821 // Transform GlobalAddress to TargetGlobalAddress
822 if (Op && (Op->getName() == "globaladdr" ||
823 Op->getName() == "globaltlsaddr")) {
Scott Michel30124c22008-01-29 02:29:31 +0000824 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000825 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
827 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
828 ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
830 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000831 Val = TmpVar;
832 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 NodeOps.push_back(Val);
Scott Michel30124c22008-01-29 02:29:31 +0000835 } else if (!N->isLeaf()
836 && (N->getOperator()->getName() == "texternalsym"
837 || N->getOperator()->getName() == "tconstpool")) {
838 // Do not rewrite the variable name, since we don't generate a new
839 // temporary.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000840 NodeOps.push_back(Val);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000841 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
843 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
844 NodeOps.push_back("CPTmp" + utostr(i));
845 }
846 } else {
847 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
848 // node even if it isn't one. Don't select it.
849 if (!LikeLeaf) {
850 emitCode("AddToISelQueue(" + Val + ");");
851 if (isRoot && N->isLeaf()) {
852 emitCode("ReplaceUses(N, " + Val + ");");
853 emitCode("return NULL;");
854 }
855 }
856 NodeOps.push_back(Val);
857 }
Scott Michel30124c22008-01-29 02:29:31 +0000858
859 if (ModifiedVal) {
860 VariableMap[VarName] = Val;
861 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 return NodeOps;
863 }
864 if (N->isLeaf()) {
865 // If this is an explicit register reference, handle it.
866 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
867 unsigned ResNo = TmpNo++;
868 if (DI->getDef()->isSubClassOf("Register")) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000869 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000870 getQualifiedName(DI->getDef()) + ", " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 getEnumName(N->getTypeNum(0)) + ");");
872 NodeOps.push_back("Tmp" + utostr(ResNo));
873 return NodeOps;
874 } else if (DI->getDef()->getName() == "zero_reg") {
Dan Gohman8181bd12008-07-27 21:46:04 +0000875 emitCode("SDValue Tmp" + utostr(ResNo) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876 " = CurDAG->getRegister(0, " +
877 getEnumName(N->getTypeNum(0)) + ");");
878 NodeOps.push_back("Tmp" + utostr(ResNo));
879 return NodeOps;
880 }
881 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
882 unsigned ResNo = TmpNo++;
883 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Dan Gohman8181bd12008-07-27 21:46:04 +0000884 emitCode("SDValue Tmp" + utostr(ResNo) +
Scott Michelac7091c2008-02-15 23:05:48 +0000885 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
886 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 NodeOps.push_back("Tmp" + utostr(ResNo));
888 return NodeOps;
889 }
890
891#ifndef NDEBUG
892 N->dump();
893#endif
894 assert(0 && "Unknown leaf type!");
895 return NodeOps;
896 }
897
898 Record *Op = N->getOperator();
899 if (Op->isSubClassOf("Instruction")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000900 const CodeGenTarget &CGT = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000902 const DAGInstruction &Inst = CGP.getInstruction(Op);
Chris Lattner7c6e5852008-01-06 01:52:22 +0000903 const TreePattern *InstPat = Inst.getPattern();
Evan Chengf031fcb2007-09-25 01:48:59 +0000904 // FIXME: Assume actual pattern comes before "implicit".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 TreePatternNode *InstPatNode =
Evan Cheng775baac2007-09-12 23:30:14 +0000906 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
907 : (InstPat ? InstPat->getTree(0) : NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengf37df842007-09-11 19:52:18 +0000909 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000911 bool IsVariadic = isRoot && II.isVariadic;
Evan Cheng775baac2007-09-12 23:30:14 +0000912 // FIXME: fix how we deal with physical register operands.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng775baac2007-09-12 23:30:14 +0000914 bool HasImpResults = isRoot && DstRegs.size() > 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 bool NodeHasOptInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000916 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 bool NodeHasInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000918 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengdec1dd12007-09-07 23:59:02 +0000919 bool NodeHasOutFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000920 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 bool NodeHasChain = InstPatNode &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000922 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 bool InputHasChain = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000924 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 unsigned NumResults = Inst.getNumResults();
Evan Cheng775baac2007-09-12 23:30:14 +0000926 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000928 // Record output varargs info.
929 OutputIsVariadic = IsVariadic;
930
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 if (NodeHasOptInFlag) {
932 emitCode("bool HasInFlag = "
933 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
934 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000935 if (IsVariadic)
Dan Gohman8181bd12008-07-27 21:46:04 +0000936 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937
938 // How many results is this pattern expected to produce?
Evan Cheng775baac2007-09-12 23:30:14 +0000939 unsigned NumPatResults = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
Duncan Sands92c43912008-06-06 12:08:01 +0000941 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng775baac2007-09-12 23:30:14 +0000943 NumPatResults++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 }
945
946 if (OrigChains.size() > 0) {
947 // The original input chain is being ignored. If it is not just
948 // pointing to the op that's being folded, we should create a
949 // TokenFactor with it and the chain of the folded op as the new chain.
950 // We could potentially be doing multiple levels of folding, in that
951 // case, the TokenFactor can have more operands.
Dan Gohman8181bd12008-07-27 21:46:04 +0000952 emitCode("SmallVector<SDValue, 8> InChains;");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
954 emitCode("if (" + OrigChains[i].first + ".Val != " +
955 OrigChains[i].second + ".Val) {");
956 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
957 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
958 emitCode("}");
959 }
960 emitCode("AddToISelQueue(" + ChainName + ");");
961 emitCode("InChains.push_back(" + ChainName + ");");
962 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
963 "&InChains[0], InChains.size());");
964 }
965
966 // Loop over all of the operands of the instruction pattern, emitting code
967 // to fill them all in. The node 'N' usually has number children equal to
968 // the number of input operands of the instruction. However, in cases
969 // where there are predicate operands for an instruction, we need to fill
970 // in the 'execute always' values. Match up the node operands to the
971 // instruction operands to do this.
972 std::vector<std::string> AllOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 for (unsigned ChildNo = 0, InstOpNo = NumResults;
974 InstOpNo != II.OperandList.size(); ++InstOpNo) {
975 std::vector<std::string> Ops;
976
Dan Gohman3329ffe2008-05-29 19:57:41 +0000977 // Determine what to emit for this operand.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000979 if ((OperandNode->isSubClassOf("PredicateOperand") ||
980 OperandNode->isSubClassOf("OptionalDefOperand")) &&
981 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Dan Gohman3329ffe2008-05-29 19:57:41 +0000982 // This is a predicate or optional def operand; emit the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 // 'default ops' operands.
984 const DAGDefaultOperand &DefaultOp =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000985 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Chengdb1f2462007-09-17 22:26:41 +0000987 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 InFlagDecled, ResNodeDecled);
989 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 }
Dan Gohman3329ffe2008-05-29 19:57:41 +0000991 } else {
992 // Otherwise this is a normal operand or a predicate operand without
993 // 'execute always'; emit it.
994 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
995 InFlagDecled, ResNodeDecled);
996 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
997 ++ChildNo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 }
999 }
1000
1001 // Emit all the chain and CopyToReg stuff.
1002 bool ChainEmitted = NodeHasChain;
1003 if (NodeHasChain)
1004 emitCode("AddToISelQueue(" + ChainName + ");");
1005 if (NodeHasInFlag || HasImpInputs)
1006 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1007 InFlagDecled, ResNodeDecled, true);
1008 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1009 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001010 emitCode("SDValue InFlag(0, 0);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011 InFlagDecled = true;
1012 }
1013 if (NodeHasOptInFlag) {
1014 emitCode("if (HasInFlag) {");
1015 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1016 emitCode(" AddToISelQueue(InFlag);");
1017 emitCode("}");
1018 }
1019 }
1020
1021 unsigned ResNo = TmpNo++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022
Dan Gohman6761ff52008-07-07 21:00:17 +00001023 unsigned OpsNo = OpcNo;
1024 std::string CodePrefix;
1025 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1026 std::deque<std::string> After;
1027 std::string NodeName;
1028 if (!isRoot) {
1029 NodeName = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +00001030 CodePrefix = "SDValue " + NodeName + "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 } else {
Dan Gohman6761ff52008-07-07 21:00:17 +00001032 NodeName = "ResNode";
1033 if (!ResNodeDecled) {
1034 CodePrefix = "SDNode *" + NodeName + " = ";
1035 ResNodeDecled = true;
1036 } else
1037 CodePrefix = NodeName + " = ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 }
1039
Dan Gohman6761ff52008-07-07 21:00:17 +00001040 std::string Code = "Opc" + utostr(OpcNo);
1041
1042 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1043
1044 // Output order: results, chain, flags
1045 // Result types.
1046 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1047 Code += ", VT" + utostr(VTNo);
1048 emitVT(getEnumName(N->getTypeNum(0)));
1049 }
1050 // Add types for implicit results in physical registers, scheduler will
1051 // care of adding copyfromreg nodes.
1052 for (unsigned i = 0; i < NumDstRegs; i++) {
1053 Record *RR = DstRegs[i];
1054 if (RR->isSubClassOf("Register")) {
1055 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1056 Code += ", " + getEnumName(RVT);
1057 }
1058 }
1059 if (NodeHasChain)
1060 Code += ", MVT::Other";
1061 if (NodeHasOutFlag)
1062 Code += ", MVT::Flag";
1063
1064 // Inputs.
1065 if (IsVariadic) {
1066 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1067 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1068 AllOps.clear();
1069
1070 // Figure out whether any operands at the end of the op list are not
1071 // part of the variable section.
1072 std::string EndAdjust;
1073 if (NodeHasInFlag || HasImpInputs)
1074 EndAdjust = "-1"; // Always has one flag.
1075 else if (NodeHasOptInFlag)
1076 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1077
1078 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1079 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1080
1081 emitCode(" AddToISelQueue(N.getOperand(i));");
1082 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1083 emitCode("}");
1084 }
1085
1086 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1087 // this pattern.
1088 if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
1089 std::vector<std::string>::const_iterator mi, mie;
1090 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001091 emitCode("SDValue LSI_" + *mi + " = "
Dan Gohman6761ff52008-07-07 21:00:17 +00001092 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1093 *mi + ")->getMemOperand());");
1094 if (IsVariadic)
1095 emitCode("Ops" + utostr(OpsNo) + ".push_back(LSI_" + *mi + ");");
1096 else
1097 AllOps.push_back("LSI_" + *mi);
1098 }
1099 }
1100
1101 if (NodeHasChain) {
1102 if (IsVariadic)
1103 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1104 else
1105 AllOps.push_back(ChainName);
1106 }
1107
1108 if (IsVariadic) {
1109 if (NodeHasInFlag || HasImpInputs)
1110 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1111 else if (NodeHasOptInFlag) {
1112 emitCode("if (HasInFlag)");
1113 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1114 }
1115 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1116 ".size()";
1117 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1118 AllOps.push_back("InFlag");
1119
1120 unsigned NumOps = AllOps.size();
1121 if (NumOps) {
1122 if (!NodeHasOptInFlag && NumOps < 4) {
1123 for (unsigned i = 0; i != NumOps; ++i)
1124 Code += ", " + AllOps[i];
1125 } else {
Dan Gohman8181bd12008-07-27 21:46:04 +00001126 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
Dan Gohman6761ff52008-07-07 21:00:17 +00001127 for (unsigned i = 0; i != NumOps; ++i) {
1128 OpsCode += AllOps[i];
1129 if (i != NumOps-1)
1130 OpsCode += ", ";
1131 }
1132 emitCode(OpsCode + " };");
1133 Code += ", Ops" + utostr(OpsNo) + ", ";
1134 if (NodeHasOptInFlag) {
1135 Code += "HasInFlag ? ";
1136 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1137 } else
1138 Code += utostr(NumOps);
1139 }
1140 }
1141
1142 if (!isRoot)
1143 Code += "), 0";
1144
Dan Gohmanbd68c792008-07-17 19:10:17 +00001145 std::vector<std::string> ReplaceFroms;
1146 std::vector<std::string> ReplaceTos;
Dan Gohman6761ff52008-07-07 21:00:17 +00001147 if (!isRoot) {
1148 NodeOps.push_back("Tmp" + utostr(ResNo));
1149 } else {
1150
1151 if (NodeHasOutFlag) {
1152 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001153 After.push_back("SDValue InFlag(ResNode, " +
Dan Gohman6761ff52008-07-07 21:00:17 +00001154 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1155 ");");
1156 InFlagDecled = true;
1157 } else
Dan Gohman8181bd12008-07-27 21:46:04 +00001158 After.push_back("InFlag = SDValue(ResNode, " +
Dan Gohman6761ff52008-07-07 21:00:17 +00001159 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1160 ");");
1161 }
1162
1163 if (FoldedChains.size() > 0) {
1164 std::string Code;
Dan Gohmanbd68c792008-07-17 19:10:17 +00001165 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001166 ReplaceFroms.push_back("SDValue(" +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001167 FoldedChains[j].first + ".Val, " +
1168 utostr(FoldedChains[j].second) +
1169 ")");
Dan Gohman8181bd12008-07-27 21:46:04 +00001170 ReplaceTos.push_back("SDValue(ResNode, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001171 utostr(NumResults+NumDstRegs) + ")");
1172 }
Dan Gohman6761ff52008-07-07 21:00:17 +00001173 }
1174
1175 if (NodeHasOutFlag) {
1176 if (FoldedFlag.first != "") {
Dan Gohman8181bd12008-07-27 21:46:04 +00001177 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001178 utostr(FoldedFlag.second) + ")");
1179 ReplaceTos.push_back("InFlag");
Dan Gohman6761ff52008-07-07 21:00:17 +00001180 } else {
1181 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
Dan Gohman8181bd12008-07-27 21:46:04 +00001182 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001183 utostr(NumPatResults + (unsigned)InputHasChain)
1184 + ")");
1185 ReplaceTos.push_back("InFlag");
Dan Gohman6761ff52008-07-07 21:00:17 +00001186 }
Dan Gohman6761ff52008-07-07 21:00:17 +00001187 }
1188
Dan Gohmanbd68c792008-07-17 19:10:17 +00001189 if (!ReplaceFroms.empty() && InputHasChain) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001190 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001191 utostr(NumPatResults) + ")");
Dan Gohman8181bd12008-07-27 21:46:04 +00001192 ReplaceTos.push_back("SDValue(" + ChainName + ".Val, " +
Gabor Greif46bf5472008-08-26 22:36:50 +00001193 ChainName + ".getResNo()" + ")");
Dan Gohman6761ff52008-07-07 21:00:17 +00001194 ChainAssignmentNeeded |= NodeHasChain;
1195 }
1196
1197 // User does not expect the instruction would produce a chain!
1198 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1199 ;
1200 } else if (InputHasChain && !NodeHasChain) {
1201 // One of the inner node produces a chain.
Dan Gohmanbd68c792008-07-17 19:10:17 +00001202 if (NodeHasOutFlag) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001203 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001204 utostr(NumPatResults+1) +
1205 ")");
Gabor Greif46bf5472008-08-26 22:36:50 +00001206 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001207 }
Dan Gohman8181bd12008-07-27 21:46:04 +00001208 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001209 utostr(NumPatResults) + ")");
1210 ReplaceTos.push_back(ChainName);
Dan Gohman6761ff52008-07-07 21:00:17 +00001211 }
1212 }
1213
1214 if (ChainAssignmentNeeded) {
1215 // Remember which op produces the chain.
1216 std::string ChainAssign;
1217 if (!isRoot)
Dan Gohman8181bd12008-07-27 21:46:04 +00001218 ChainAssign = ChainName + " = SDValue(" + NodeName +
Dan Gohman6761ff52008-07-07 21:00:17 +00001219 ".Val, " + utostr(NumResults+NumDstRegs) + ");";
1220 else
Dan Gohman8181bd12008-07-27 21:46:04 +00001221 ChainAssign = ChainName + " = SDValue(" + NodeName +
Dan Gohman6761ff52008-07-07 21:00:17 +00001222 ", " + utostr(NumResults+NumDstRegs) + ");";
1223
1224 After.push_front(ChainAssign);
1225 }
1226
Dan Gohmanbd68c792008-07-17 19:10:17 +00001227 if (ReplaceFroms.size() == 1) {
1228 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1229 ReplaceTos[0] + ");");
1230 } else if (!ReplaceFroms.empty()) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001231 After.push_back("const SDValue Froms[] = {");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001232 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1233 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1234 After.push_back("};");
Dan Gohman8181bd12008-07-27 21:46:04 +00001235 After.push_back("const SDValue Tos[] = {");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001236 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1237 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1238 After.push_back("};");
1239 After.push_back("ReplaceUses(Froms, Tos, " +
1240 itostr(ReplaceFroms.size()) + ");");
1241 }
1242
1243 // We prefer to use SelectNodeTo since it avoids allocation when
1244 // possible and it avoids CSE map recalculation for the node's
1245 // users, however it's tricky to use in a non-root context.
Dan Gohman6761ff52008-07-07 21:00:17 +00001246 //
Dan Gohmanbd68c792008-07-17 19:10:17 +00001247 // We also don't use if the pattern replacement is being used to
1248 // jettison a chain result, since morphing the node in place
1249 // would leave users of the chain dangling.
Dan Gohman6761ff52008-07-07 21:00:17 +00001250 //
Dan Gohmanbd68c792008-07-17 19:10:17 +00001251 if (!isRoot || (InputHasChain && !NodeHasChain)) {
Dan Gohman6761ff52008-07-07 21:00:17 +00001252 Code = "CurDAG->getTargetNode(" + Code;
1253 } else {
1254 Code = "CurDAG->SelectNodeTo(N.Val, " + Code;
1255 }
1256 if (isRoot) {
1257 if (After.empty())
1258 CodePrefix = "return ";
1259 else
1260 After.push_back("return ResNode;");
1261 }
1262
1263 emitCode(CodePrefix + Code + ");");
1264 for (unsigned i = 0, e = After.size(); i != e; ++i)
1265 emitCode(After[i]);
1266
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 return NodeOps;
1268 } else if (Op->isSubClassOf("SDNodeXForm")) {
1269 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1270 // PatLeaf node - the operand may or may not be a leaf node. But it should
1271 // behave like one.
1272 std::vector<std::string> Ops =
Evan Chengdb1f2462007-09-17 22:26:41 +00001273 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 ResNodeDecled, true);
1275 unsigned ResNo = TmpNo++;
Dan Gohman8181bd12008-07-27 21:46:04 +00001276 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 + "(" + Ops.back() + ".Val);");
1278 NodeOps.push_back("Tmp" + utostr(ResNo));
1279 if (isRoot)
1280 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1281 return NodeOps;
1282 } else {
1283 N->dump();
1284 cerr << "\n";
1285 throw std::string("Unknown node in result pattern!");
1286 }
1287 }
1288
1289 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1290 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1291 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1292 /// for, this returns true otherwise false if Pat has all types.
1293 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1294 const std::string &Prefix, bool isRoot = false) {
1295 // Did we find one?
1296 if (Pat->getExtTypes() != Other->getExtTypes()) {
1297 // Move a type over from 'other' to 'pat'.
1298 Pat->setTypes(Other->getExtTypes());
1299 // The top level node type is checked outside of the select function.
1300 if (!isRoot)
1301 emitCheck(Prefix + ".Val->getValueType(0) == " +
1302 getName(Pat->getTypeNum(0)));
1303 return true;
1304 }
1305
1306 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001307 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1309 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1310 Prefix + utostr(OpNo)))
1311 return true;
1312 return false;
1313 }
1314
1315private:
1316 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1317 /// being built.
1318 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1319 bool &ChainEmitted, bool &InFlagDecled,
1320 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001321 const CodeGenTarget &T = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001323 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1324 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1326 TreePatternNode *Child = N->getChild(i);
1327 if (!Child->isLeaf()) {
1328 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1329 InFlagDecled, ResNodeDecled);
1330 } else {
1331 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1332 if (!Child->getName().empty()) {
1333 std::string Name = RootName + utostr(OpNo);
1334 if (Duplicates.find(Name) != Duplicates.end())
1335 // A duplicate! Do not emit a copy for this node.
1336 continue;
1337 }
1338
1339 Record *RR = DI->getDef();
1340 if (RR->isSubClassOf("Register")) {
Duncan Sands92c43912008-06-06 12:08:01 +00001341 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 if (RVT == MVT::Flag) {
1343 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001344 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 InFlagDecled = true;
1346 } else
1347 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1348 emitCode("AddToISelQueue(InFlag);");
1349 } else {
1350 if (!ChainEmitted) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001351 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 ChainName = "Chain";
1353 ChainEmitted = true;
1354 }
1355 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1356 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001357 emitCode("SDValue InFlag(0, 0);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 InFlagDecled = true;
1359 }
1360 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1361 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001362 ", " + getQualifiedName(RR) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1364 ResNodeDecled = true;
Dan Gohman8181bd12008-07-27 21:46:04 +00001365 emitCode(ChainName + " = SDValue(ResNode, 0);");
1366 emitCode("InFlag = SDValue(ResNode, 1);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 }
1368 }
1369 }
1370 }
1371 }
1372
1373 if (HasInFlag) {
1374 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001375 emitCode("SDValue InFlag = " + RootName +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 ".getOperand(" + utostr(OpNo) + ");");
1377 InFlagDecled = true;
1378 } else
1379 emitCode("InFlag = " + RootName +
1380 ".getOperand(" + utostr(OpNo) + ");");
1381 emitCode("AddToISelQueue(InFlag);");
1382 }
1383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384};
1385
1386/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1387/// stream to match the pattern, and generate the code for the match if it
1388/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner81915752008-01-05 22:30:17 +00001389void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1391 std::set<std::string> &GeneratedDecl,
1392 std::vector<std::string> &TargetOpcodes,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001393 std::vector<std::string> &TargetVTs,
1394 bool &OutputIsVariadic,
1395 unsigned &NumInputRootOps) {
1396 OutputIsVariadic = false;
1397 NumInputRootOps = 0;
1398
Dan Gohmane97f1a32008-08-22 00:20:26 +00001399 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001400 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1401 GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001402 TargetOpcodes, TargetVTs,
1403 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404
1405 // Emit the matcher, capturing named arguments in VariableMap.
1406 bool FoundChain = false;
1407 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1408
1409 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner14948ea2008-01-05 22:58:54 +00001410 TreePattern &TP = *CGP.pf_begin()->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411
1412 // At this point, we know that we structurally match the pattern, but the
1413 // types of the nodes may not match. Figure out the fewest number of type
1414 // comparisons we need to emit. For example, if there is only one integer
1415 // type supported by a target, there should be no type comparisons at all for
1416 // integer patterns!
1417 //
1418 // To figure out the fewest number of type checks needed, clone the pattern,
1419 // remove the types, then perform type inference on the pattern as a whole.
1420 // If there are unresolved types, emit an explicit check for those types,
1421 // apply the type to the tree, then rerun type inference. Iterate until all
1422 // types are resolved.
1423 //
1424 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1425 RemoveAllTypes(Pat);
1426
1427 do {
1428 // Resolve/propagate as many types as possible.
1429 try {
1430 bool MadeChange = true;
1431 while (MadeChange)
1432 MadeChange = Pat->ApplyTypeConstraints(TP,
1433 true/*Ignore reg constraints*/);
1434 } catch (...) {
1435 assert(0 && "Error: could not find consistent types for something we"
1436 " already decided was ok!");
1437 abort();
1438 }
1439
1440 // Insert a check for an unresolved type and add it to the tree. If we find
1441 // an unresolved type to add a check for, this returns true and we iterate,
1442 // otherwise we are done.
1443 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1444
Evan Cheng775baac2007-09-12 23:30:14 +00001445 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Chengdb1f2462007-09-17 22:26:41 +00001446 false, false, false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 delete Pat;
1448}
1449
1450/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1451/// a line causes any of them to be empty, remove them and return true when
1452/// done.
Chris Lattner81915752008-01-05 22:30:17 +00001453static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 std::vector<std::pair<unsigned, std::string> > > >
1455 &Patterns) {
1456 bool ErasedPatterns = false;
1457 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1458 Patterns[i].second.pop_back();
1459 if (Patterns[i].second.empty()) {
1460 Patterns.erase(Patterns.begin()+i);
1461 --i; --e;
1462 ErasedPatterns = true;
1463 }
1464 }
1465 return ErasedPatterns;
1466}
1467
1468/// EmitPatterns - Emit code for at least one pattern, but try to group common
1469/// code together between the patterns.
Chris Lattner81915752008-01-05 22:30:17 +00001470void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 std::vector<std::pair<unsigned, std::string> > > >
1472 &Patterns, unsigned Indent,
1473 std::ostream &OS) {
1474 typedef std::pair<unsigned, std::string> CodeLine;
1475 typedef std::vector<CodeLine> CodeList;
Chris Lattner81915752008-01-05 22:30:17 +00001476 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477
1478 if (Patterns.empty()) return;
1479
1480 // Figure out how many patterns share the next code line. Explicitly copy
1481 // FirstCodeLine so that we don't invalidate a reference when changing
1482 // Patterns.
1483 const CodeLine FirstCodeLine = Patterns.back().second.back();
1484 unsigned LastMatch = Patterns.size()-1;
1485 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1486 --LastMatch;
1487
1488 // If not all patterns share this line, split the list into two pieces. The
1489 // first chunk will use this line, the second chunk won't.
1490 if (LastMatch != 0) {
1491 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1492 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1493
1494 // FIXME: Emit braces?
1495 if (Shared.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001496 const PatternToMatch &Pattern = *Shared.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001497 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1498 Pattern.getSrcPattern()->print(OS);
1499 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1500 Pattern.getDstPattern()->print(OS);
1501 OS << "\n";
1502 unsigned AddedComplexity = Pattern.getAddedComplexity();
1503 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001504 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001506 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001507 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001508 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509 }
1510 if (FirstCodeLine.first != 1) {
1511 OS << std::string(Indent, ' ') << "{\n";
1512 Indent += 2;
1513 }
1514 EmitPatterns(Shared, Indent, OS);
1515 if (FirstCodeLine.first != 1) {
1516 Indent -= 2;
1517 OS << std::string(Indent, ' ') << "}\n";
1518 }
1519
1520 if (Other.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001521 const PatternToMatch &Pattern = *Other.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1523 Pattern.getSrcPattern()->print(OS);
1524 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1525 Pattern.getDstPattern()->print(OS);
1526 OS << "\n";
1527 unsigned AddedComplexity = Pattern.getAddedComplexity();
1528 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001529 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001531 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001533 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534 }
1535 EmitPatterns(Other, Indent, OS);
1536 return;
1537 }
1538
1539 // Remove this code from all of the patterns that share it.
1540 bool ErasedPatterns = EraseCodeLine(Patterns);
1541
1542 bool isPredicate = FirstCodeLine.first == 1;
1543
1544 // Otherwise, every pattern in the list has this line. Emit it.
1545 if (!isPredicate) {
1546 // Normal code.
1547 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1548 } else {
1549 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1550
1551 // If the next code line is another predicate, and if all of the pattern
1552 // in this group share the same next line, emit it inline now. Do this
1553 // until we run out of common predicates.
1554 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1555 // Check that all of fhe patterns in Patterns end with the same predicate.
1556 bool AllEndWithSamePredicate = true;
1557 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1558 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1559 AllEndWithSamePredicate = false;
1560 break;
1561 }
1562 // If all of the predicates aren't the same, we can't share them.
1563 if (!AllEndWithSamePredicate) break;
1564
1565 // Otherwise we can. Emit it shared now.
1566 OS << " &&\n" << std::string(Indent+4, ' ')
1567 << Patterns.back().second.back().second;
1568 ErasedPatterns = EraseCodeLine(Patterns);
1569 }
1570
1571 OS << ") {\n";
1572 Indent += 2;
1573 }
1574
1575 EmitPatterns(Patterns, Indent, OS);
1576
1577 if (isPredicate)
1578 OS << std::string(Indent-2, ' ') << "}\n";
1579}
1580
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001581static std::string getLegalCName(std::string OpName) {
1582 std::string::size_type pos = OpName.find("::");
1583 if (pos != std::string::npos)
1584 OpName.replace(pos, 2, "_");
1585 return OpName;
1586}
1587
1588void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001589 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001590
Dan Gohman6a36cc92008-08-20 21:45:57 +00001591 // Get the namespace to insert instructions into.
1592 std::string InstNS = Target.getInstNamespace();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593 if (!InstNS.empty()) InstNS += "::";
1594
1595 // Group the patterns by their top-level opcodes.
Chris Lattner81915752008-01-05 22:30:17 +00001596 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001597 // All unique target node emission functions.
1598 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerae506702008-01-06 01:10:31 +00001599 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001600 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner81915752008-01-05 22:30:17 +00001601 const PatternToMatch &Pattern = *I;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001602
1603 TreePatternNode *Node = Pattern.getSrcPattern();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001604 if (!Node->isLeaf()) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001605 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001606 push_back(&Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 } else {
1608 const ComplexPattern *CP;
1609 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001610 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001611 push_back(&Pattern);
Chris Lattner14948ea2008-01-05 22:58:54 +00001612 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001613 std::vector<Record*> OpNodes = CP->getRootNodes();
1614 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001615 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1616 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001617 &Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 }
1619 } else {
1620 cerr << "Unrecognized opcode '";
1621 Node->dump();
1622 cerr << "' on tree pattern '";
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001623 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624 exit(1);
1625 }
1626 }
1627 }
1628
1629 // For each opcode, there might be multiple select functions, one per
1630 // ValueType of the node (or its first operand if it doesn't produce a
1631 // non-chain result.
1632 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1633
1634 // Emit one Select_* method for each top-level opcode. We do this instead of
1635 // emitting one giant switch statement to support compilers where this will
1636 // result in the recursive functions taking less stack space.
Chris Lattner81915752008-01-05 22:30:17 +00001637 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001638 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1639 PBOI != E; ++PBOI) {
1640 const std::string &OpName = PBOI->first;
Chris Lattner81915752008-01-05 22:30:17 +00001641 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1643
1644 // We want to emit all of the matching code now. However, we want to emit
1645 // the matches in order of minimal cost. Sort the patterns so the least
1646 // cost one is at the start.
1647 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001648 PatternSortingPredicate(CGP));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649
1650 // Split them into groups by type.
Duncan Sands92c43912008-06-06 12:08:01 +00001651 std::map<MVT::SimpleValueType,
1652 std::vector<const PatternToMatch*> > PatternsByType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner81915752008-01-05 22:30:17 +00001654 const PatternToMatch *Pat = PatternsOfOp[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001655 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner4a5394e2008-08-26 07:01:28 +00001656 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 }
1658
Duncan Sands92c43912008-06-06 12:08:01 +00001659 for (std::map<MVT::SimpleValueType,
1660 std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001661 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1662 ++II) {
Duncan Sands92c43912008-06-06 12:08:01 +00001663 MVT::SimpleValueType OpVT = II->first;
Chris Lattner81915752008-01-05 22:30:17 +00001664 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1666 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1667
Chris Lattner81915752008-01-05 22:30:17 +00001668 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669 std::vector<std::vector<std::string> > PatternOpcodes;
1670 std::vector<std::vector<std::string> > PatternVTs;
1671 std::vector<std::set<std::string> > PatternDecls;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001672 std::vector<bool> OutputIsVariadicFlags;
1673 std::vector<unsigned> NumInputRootOpsCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1675 CodeList GeneratedCode;
1676 std::set<std::string> GeneratedDecl;
1677 std::vector<std::string> TargetOpcodes;
1678 std::vector<std::string> TargetVTs;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001679 bool OutputIsVariadic;
1680 unsigned NumInputRootOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001682 TargetOpcodes, TargetVTs,
1683 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001684 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1685 PatternDecls.push_back(GeneratedDecl);
1686 PatternOpcodes.push_back(TargetOpcodes);
1687 PatternVTs.push_back(TargetVTs);
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001688 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1689 NumInputRootOpsCounts.push_back(NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690 }
1691
1692 // Scan the code to see if all of the patterns are reachable and if it is
1693 // possible that the last one might not match.
1694 bool mightNotMatch = true;
1695 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1696 CodeList &GeneratedCode = CodeForPatterns[i].second;
1697 mightNotMatch = false;
1698
1699 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1700 if (GeneratedCode[j].first == 1) { // predicate.
1701 mightNotMatch = true;
1702 break;
1703 }
1704 }
1705
1706 // If this pattern definitely matches, and if it isn't the last one, the
1707 // patterns after it CANNOT ever match. Error out.
1708 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1709 cerr << "Pattern '";
1710 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1711 cerr << "' is impossible to select!\n";
1712 exit(1);
1713 }
1714 }
1715
1716 // Factor target node emission code (emitted by EmitResultCode) into
1717 // separate functions. Uniquing and share them among all instruction
1718 // selection routines.
1719 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1720 CodeList &GeneratedCode = CodeForPatterns[i].second;
1721 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1722 std::vector<std::string> &TargetVTs = PatternVTs[i];
1723 std::set<std::string> Decls = PatternDecls[i];
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001724 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1725 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726 std::vector<std::string> AddedInits;
1727 int CodeSize = (int)GeneratedCode.size();
1728 int LastPred = -1;
1729 for (int j = CodeSize-1; j >= 0; --j) {
1730 if (LastPred == -1 && GeneratedCode[j].first == 1)
1731 LastPred = j;
1732 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1733 AddedInits.push_back(GeneratedCode[j].second);
1734 }
1735
Dan Gohman8181bd12008-07-27 21:46:04 +00001736 std::string CalleeCode = "(const SDValue &N";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737 std::string CallerCode = "(N";
1738 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1739 CalleeCode += ", unsigned Opc" + utostr(j);
1740 CallerCode += ", " + TargetOpcodes[j];
1741 }
1742 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Duncan Sands92c43912008-06-06 12:08:01 +00001743 CalleeCode += ", MVT VT" + utostr(j);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 CallerCode += ", " + TargetVTs[j];
1745 }
1746 for (std::set<std::string>::iterator
1747 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1748 std::string Name = *I;
Dan Gohman8181bd12008-07-27 21:46:04 +00001749 CalleeCode += ", SDValue &" + Name;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001750 CallerCode += ", " + Name;
1751 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001752
1753 if (OutputIsVariadic) {
1754 CalleeCode += ", unsigned NumInputRootOps";
1755 CallerCode += ", " + utostr(NumInputRootOps);
1756 }
1757
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758 CallerCode += ");";
1759 CalleeCode += ") ";
1760 // Prevent emission routines from being inlined to reduce selection
1761 // routines stack frame sizes.
1762 CalleeCode += "DISABLE_INLINE ";
1763 CalleeCode += "{\n";
1764
1765 for (std::vector<std::string>::const_reverse_iterator
1766 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1767 CalleeCode += " " + *I + "\n";
1768
1769 for (int j = LastPred+1; j < CodeSize; ++j)
1770 CalleeCode += " " + GeneratedCode[j].second + "\n";
1771 for (int j = LastPred+1; j < CodeSize; ++j)
1772 GeneratedCode.pop_back();
1773 CalleeCode += "}\n";
1774
1775 // Uniquing the emission routines.
1776 unsigned EmitFuncNum;
1777 std::map<std::string, unsigned>::iterator EFI =
1778 EmitFunctions.find(CalleeCode);
1779 if (EFI != EmitFunctions.end()) {
1780 EmitFuncNum = EFI->second;
1781 } else {
1782 EmitFuncNum = EmitFunctions.size();
1783 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1784 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1785 }
1786
1787 // Replace the emission code within selection routines with calls to the
1788 // emission functions.
1789 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1790 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1791 }
1792
1793 // Print function.
1794 std::string OpVTStr;
1795 if (OpVT == MVT::iPTR) {
1796 OpVTStr = "_iPTR";
Mon P Wangce3ac892008-07-30 04:36:53 +00001797 } else if (OpVT == MVT::iPTRAny) {
1798 OpVTStr = "_iPTRAny";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799 } else if (OpVT == MVT::isVoid) {
1800 // Nodes with a void result actually have a first result type of either
1801 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1802 // void to this case, we handle it specially here.
1803 } else {
1804 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1805 }
1806 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1807 OpcodeVTMap.find(OpName);
1808 if (OpVTI == OpcodeVTMap.end()) {
1809 std::vector<std::string> VTSet;
1810 VTSet.push_back(OpVTStr);
1811 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1812 } else
1813 OpVTI->second.push_back(OpVTStr);
1814
1815 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohman8181bd12008-07-27 21:46:04 +00001816 << OpVTStr << "(const SDValue &N) {\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001817
1818 // Loop through and reverse all of the CodeList vectors, as we will be
1819 // accessing them from their logical front, but accessing the end of a
1820 // vector is more efficient.
1821 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1822 CodeList &GeneratedCode = CodeForPatterns[i].second;
1823 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1824 }
1825
1826 // Next, reverse the list of patterns itself for the same reason.
1827 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1828
1829 // Emit all of the patterns now, grouped together to share code.
1830 EmitPatterns(CodeForPatterns, 2, OS);
1831
1832 // If the last pattern has predicates (which could fail) emit code to
1833 // catch the case where nothing handles a pattern.
1834 if (mightNotMatch) {
1835 OS << " cerr << \"Cannot yet select: \";\n";
1836 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1837 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1838 OpName != "ISD::INTRINSIC_VOID") {
1839 OS << " N.Val->dump(CurDAG);\n";
1840 } else {
1841 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1842 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1843 << " cerr << \"intrinsic %\"<< "
1844 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1845 }
1846 OS << " cerr << '\\n';\n"
1847 << " abort();\n"
1848 << " return NULL;\n";
1849 }
1850 OS << "}\n\n";
1851 }
1852 }
1853
1854 // Emit boilerplate.
Dan Gohman8181bd12008-07-27 21:46:04 +00001855 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1856 << " std::vector<SDValue> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Dan Gohman14a66442008-08-23 02:25:05 +00001857 << " SelectInlineAsmMemoryOperands(Ops);\n\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001858
1859 << " // Ensure that the asm operands are themselves selected.\n"
1860 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1861 << " AddToISelQueue(Ops[j]);\n\n"
1862
Duncan Sands92c43912008-06-06 12:08:01 +00001863 << " std::vector<MVT> VTs;\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001864 << " VTs.push_back(MVT::Other);\n"
1865 << " VTs.push_back(MVT::Flag);\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001866 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 "Ops.size());\n"
1868 << " return New.Val;\n"
1869 << "}\n\n";
Evan Cheng3c0eda52008-03-15 00:03:38 +00001870
Dan Gohman8181bd12008-07-27 21:46:04 +00001871 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001872 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::IMPLICIT_DEF,\n"
1873 << " N.getValueType());\n"
1874 << "}\n\n";
1875
Dan Gohman8181bd12008-07-27 21:46:04 +00001876 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1877 << " SDValue Chain = N.getOperand(0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001878 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001879 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001880 << " AddToISelQueue(Chain);\n"
1881 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DBG_LABEL,\n"
1882 << " MVT::Other, Tmp, Chain);\n"
1883 << "}\n\n";
1884
Dan Gohman8181bd12008-07-27 21:46:04 +00001885 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1886 << " SDValue Chain = N.getOperand(0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001887 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001888 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001889 << " AddToISelQueue(Chain);\n"
1890 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EH_LABEL,\n"
1891 << " MVT::Other, Tmp, Chain);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00001892 << "}\n\n";
1893
Dan Gohman8181bd12008-07-27 21:46:04 +00001894 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1895 << " SDValue Chain = N.getOperand(0);\n"
1896 << " SDValue N1 = N.getOperand(1);\n"
1897 << " SDValue N2 = N.getOperand(2);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001898 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1899 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1900 << " N.Val->dump(CurDAG);\n"
1901 << " abort();\n"
1902 << " }\n"
1903 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1904 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001905 << " SDValue Tmp1 = "
Evan Cheng2e28d622008-02-02 04:07:54 +00001906 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001907 << " SDValue Tmp2 = "
Evan Cheng2e28d622008-02-02 04:07:54 +00001908 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1909 << " AddToISelQueue(Chain);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001910 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DECLARE,\n"
1911 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001912 << "}\n\n";
1913
Dan Gohman8181bd12008-07-27 21:46:04 +00001914 OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1915 << " SDValue N0 = N.getOperand(0);\n"
1916 << " SDValue N1 = N.getOperand(1);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001917 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001918 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001919 << " AddToISelQueue(N0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001920 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EXTRACT_SUBREG,\n"
1921 << " N.getValueType(), N0, Tmp);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001922 << "}\n\n";
1923
Dan Gohman8181bd12008-07-27 21:46:04 +00001924 OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1925 << " SDValue N0 = N.getOperand(0);\n"
1926 << " SDValue N1 = N.getOperand(1);\n"
1927 << " SDValue N2 = N.getOperand(2);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001928 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001929 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001930 << " AddToISelQueue(N1);\n"
Christopher Lambb371e032008-03-13 05:47:01 +00001931 << " AddToISelQueue(N0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001932 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::INSERT_SUBREG,\n"
1933 << " N.getValueType(), N0, N1, Tmp);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001934 << "}\n\n";
1935
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001936 OS << "// The main instruction selector code.\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001937 << "SDNode *SelectCode(SDValue N) {\n"
Dan Gohmanbd68c792008-07-17 19:10:17 +00001938 << " if (N.isMachineOpcode()) {\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939 << " return NULL; // Already selected.\n"
1940 << " }\n\n"
Duncan Sands92c43912008-06-06 12:08:01 +00001941 << " MVT::SimpleValueType NVT = N.Val->getValueType(0).getSimpleVT();\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001942 << " switch (N.getOpcode()) {\n"
1943 << " default: break;\n"
1944 << " case ISD::EntryToken: // These leaves remain the same.\n"
1945 << " case ISD::BasicBlock:\n"
1946 << " case ISD::Register:\n"
1947 << " case ISD::HANDLENODE:\n"
1948 << " case ISD::TargetConstant:\n"
Nate Begemane2ba64f2008-02-14 08:57:00 +00001949 << " case ISD::TargetConstantFP:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001950 << " case ISD::TargetConstantPool:\n"
1951 << " case ISD::TargetFrameIndex:\n"
1952 << " case ISD::TargetExternalSymbol:\n"
1953 << " case ISD::TargetJumpTable:\n"
1954 << " case ISD::TargetGlobalTLSAddress:\n"
1955 << " case ISD::TargetGlobalAddress: {\n"
1956 << " return NULL;\n"
1957 << " }\n"
1958 << " case ISD::AssertSext:\n"
1959 << " case ISD::AssertZext: {\n"
1960 << " AddToISelQueue(N.getOperand(0));\n"
1961 << " ReplaceUses(N, N.getOperand(0));\n"
1962 << " return NULL;\n"
1963 << " }\n"
1964 << " case ISD::TokenFactor:\n"
1965 << " case ISD::CopyFromReg:\n"
1966 << " case ISD::CopyToReg: {\n"
1967 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1968 << " AddToISelQueue(N.getOperand(i));\n"
1969 << " return NULL;\n"
1970 << " }\n"
1971 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001972 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1973 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001974 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001975 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00001976 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
1977 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001978
1979
1980 // Loop over all of the case statements, emiting a call to each method we
1981 // emitted above.
Chris Lattner81915752008-01-05 22:30:17 +00001982 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001983 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1984 PBOI != E; ++PBOI) {
1985 const std::string &OpName = PBOI->first;
1986 // Potentially multiple versions of select for this opcode. One for each
1987 // ValueType of the node (or its first true operand if it doesn't produce a
1988 // result.
1989 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1990 OpcodeVTMap.find(OpName);
1991 std::vector<std::string> &OpVTs = OpVTI->second;
1992 OS << " case " << OpName << ": {\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00001993 // Keep track of whether we see a pattern that has an iPtr result.
1994 bool HasPtrPattern = false;
1995 bool HasDefaultPattern = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996
Evan Chengb8b6b182007-09-04 20:18:28 +00001997 OS << " switch (NVT) {\n";
1998 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1999 std::string &VTStr = OpVTs[i];
2000 if (VTStr.empty()) {
2001 HasDefaultPattern = true;
2002 continue;
2003 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004
Evan Chengb8b6b182007-09-04 20:18:28 +00002005 // If this is a match on iPTR: don't emit it directly, we need special
2006 // code.
2007 if (VTStr == "_iPTR") {
2008 HasPtrPattern = true;
2009 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002010 }
Evan Chengb8b6b182007-09-04 20:18:28 +00002011 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2012 << " return Select_" << getLegalCName(OpName)
2013 << VTStr << "(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002014 }
Evan Chengb8b6b182007-09-04 20:18:28 +00002015 OS << " default:\n";
2016
2017 // If there is an iPTR result version of this pattern, emit it here.
2018 if (HasPtrPattern) {
Duncan Sands92c43912008-06-06 12:08:01 +00002019 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00002020 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2021 }
2022 if (HasDefaultPattern) {
2023 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2024 }
2025 OS << " break;\n";
2026 OS << " }\n";
2027 OS << " break;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002028 OS << " }\n";
2029 }
2030
2031 OS << " } // end of big switch.\n\n"
2032 << " cerr << \"Cannot yet select: \";\n"
2033 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2034 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2035 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2036 << " N.Val->dump(CurDAG);\n"
2037 << " } else {\n"
2038 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2039 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
2040 << " cerr << \"intrinsic %\"<< "
2041 "Intrinsic::getName((Intrinsic::ID)iid);\n"
2042 << " }\n"
2043 << " cerr << '\\n';\n"
2044 << " abort();\n"
2045 << " return NULL;\n"
2046 << "}\n";
2047}
2048
2049void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00002050 EmitSourceFileHeader("DAG Instruction Selector for the " +
2051 CGP.getTargetInfo().getName() + " target", OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002052
2053 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2054 << "// *** instruction selector class. These functions are really "
2055 << "methods.\n\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00002056
Roman Levenstein393ad0f2008-05-14 10:17:11 +00002057 OS << "// Include standard, target-independent definitions and methods used\n"
2058 << "// by the instruction selector.\n";
2059 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060
Chris Lattner227da452008-01-05 22:54:53 +00002061 EmitNodeTransforms(OS);
Chris Lattner7fdd9342008-01-05 22:43:57 +00002062 EmitPredicateFunctions(OS);
2063
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002064 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattnerae506702008-01-06 01:10:31 +00002065 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00002066 I != E; ++I) {
2067 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2068 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069 DOUT << "\n";
2070 }
2071
2072 // At this point, we have full information about the 'Patterns' we need to
2073 // parse, both implicitly from instructions as well as from explicit pattern
2074 // definitions. Emit the resultant instruction selector.
2075 EmitInstructionSelector(OS);
2076
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002077}