blob: c9ca971c18b1cabff2b462f819eed1a1ad5f2d5b [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.
320 ListInit *Predicates;
321 // 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:
Chris Lattnerae506702008-01-06 01:10:31 +0000398 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
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)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000406 : CGP(cgp), Predicates(preds), 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))
432 emitCheck("!FastISel");
433
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 std::string PredicateCheck;
435 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
436 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
437 Record *Def = Pred->getDef();
438 if (!Def->isSubClassOf("Predicate")) {
439#ifndef NDEBUG
440 Def->dump();
441#endif
442 assert(0 && "Unknown predicate type!");
443 }
444 if (!PredicateCheck.empty())
445 PredicateCheck += " && ";
446 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
447 }
448 }
449
450 emitCheck(PredicateCheck);
451 }
452
453 if (N->isLeaf()) {
454 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
455 emitCheck("cast<ConstantSDNode>(" + RootName +
456 ")->getSignExtended() == " + itostr(II->getValue()));
457 return;
458 } else if (!NodeIsComplexPattern(N)) {
459 assert(0 && "Cannot match this as a leaf value!");
460 abort();
461 }
462 }
463
464 // If this node has a name associated with it, capture it in VariableMap. If
465 // we already saw this in the pattern, emit code to verify dagness.
466 if (!N->getName().empty()) {
467 std::string &VarMapEntry = VariableMap[N->getName()];
468 if (VarMapEntry.empty()) {
469 VarMapEntry = RootName;
470 } else {
471 // If we get here, this is a second reference to a specific name. Since
472 // we already have checked that the first reference is valid, we don't
473 // have to recursively match it, just check that it's the same as the
474 // previously named thing.
475 emitCheck(VarMapEntry + " == " + RootName);
476 return;
477 }
478
479 if (!N->isLeaf())
480 OperatorMap[N->getName()] = N->getOperator();
481 }
482
483
484 // Emit code to load the child nodes and match their contents recursively.
485 unsigned OpNo = 0;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000486 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
487 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 bool EmittedUseCheck = false;
489 if (HasChain) {
490 if (NodeHasChain)
491 OpNo = 1;
492 if (!isRoot) {
493 // Multiple uses of actual result?
494 emitCheck(RootName + ".hasOneUse()");
495 EmittedUseCheck = true;
496 if (NodeHasChain) {
497 // If the immediate use can somehow reach this node through another
498 // path, then can't fold it either or it will create a cycle.
499 // e.g. In the following diagram, XX can reach ld through YY. If
500 // ld is folded into XX, then YY is both a predecessor and a successor
501 // of XX.
502 //
503 // [ld]
504 // ^ ^
505 // | |
506 // / \---
507 // / [YY]
508 // | ^
509 // [XX]-------|
Evan Cheng43f0c652008-07-03 08:39:51 +0000510 bool NeedCheck = P != Pattern;
511 if (!NeedCheck) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000512 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 NeedCheck =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000514 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
515 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
516 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 PInfo.getNumOperands() > 1 ||
518 PInfo.hasProperty(SDNPHasChain) ||
519 PInfo.hasProperty(SDNPInFlag) ||
520 PInfo.hasProperty(SDNPOptInFlag);
521 }
522
523 if (NeedCheck) {
524 std::string ParentName(RootName.begin(), RootName.end()-1);
525 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
526 ".Val, N.Val)");
527 }
528 }
529 }
530
531 if (NodeHasChain) {
532 if (FoundChain) {
533 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
534 "IsChainCompatible(" + ChainName + ".Val, " +
535 RootName + ".Val))");
536 OrigChains.push_back(std::make_pair(ChainName, RootName));
537 } else
538 FoundChain = true;
539 ChainName = "Chain" + ChainSuffix;
Dan Gohman8181bd12008-07-27 21:46:04 +0000540 emitInit("SDValue " + ChainName + " = " + RootName +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 ".getOperand(0);");
542 }
543 }
544
545 // Don't fold any node which reads or writes a flag and has multiple uses.
546 // FIXME: We really need to separate the concepts of flag and "glue". Those
547 // real flag results, e.g. X86CMP output, can have multiple uses.
548 // FIXME: If the optional incoming flag does not exist. Then it is ok to
549 // fold it.
550 if (!isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000551 (PatternHasProperty(N, SDNPInFlag, CGP) ||
552 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
553 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 if (!EmittedUseCheck) {
555 // Multiple uses of actual result?
556 emitCheck(RootName + ".hasOneUse()");
557 }
558 }
559
560 // If there is a node predicate for this, emit the call.
561 if (!N->getPredicateFn().empty())
562 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
563
564
565 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
566 // a constant without a predicate fn that has more that one bit set, handle
567 // this as a special case. This is usually for targets that have special
568 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
569 // handling stuff). Using these instructions is often far more efficient
570 // than materializing the constant. Unfortunately, both the instcombiner
571 // and the dag combiner can often infer that bits are dead, and thus drop
572 // them from the mask in the dag. For example, it might turn 'AND X, 255'
573 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
574 // to handle this.
575 if (!N->isLeaf() &&
576 (N->getOperator()->getName() == "and" ||
577 N->getOperator()->getName() == "or") &&
578 N->getChild(1)->isLeaf() &&
579 N->getChild(1)->getPredicateFn().empty()) {
580 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
581 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Dan Gohman8181bd12008-07-27 21:46:04 +0000582 emitInit("SDValue " + RootName + "0" + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 RootName + ".getOperand(" + utostr(0) + ");");
Dan Gohman8181bd12008-07-27 21:46:04 +0000584 emitInit("SDValue " + RootName + "1" + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 RootName + ".getOperand(" + utostr(1) + ");");
586
587 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
588 const char *MaskPredicate = N->getOperator()->getName() == "or"
589 ? "CheckOrMask(" : "CheckAndMask(";
590 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
591 RootName + "1), " + itostr(II->getValue()) + ")");
592
Christopher Lamb059c7c92008-01-31 07:27:46 +0000593 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594 ChainSuffix + utostr(0), FoundChain);
595 return;
596 }
597 }
598 }
599
600 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000601 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 RootName + ".getOperand(" +utostr(OpNo) + ");");
603
Christopher Lamb059c7c92008-01-31 07:27:46 +0000604 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 ChainSuffix + utostr(OpNo), FoundChain);
606 }
607
608 // Handle cases when root is a complex pattern.
609 const ComplexPattern *CP;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000610 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 std::string Fn = CP->getSelectFunc();
612 unsigned NumOps = CP->getNumOperands();
613 for (unsigned i = 0; i < NumOps; ++i) {
614 emitDecl("CPTmp" + utostr(i));
Dan Gohman8181bd12008-07-27 21:46:04 +0000615 emitCode("SDValue CPTmp" + utostr(i) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 }
617 if (CP->hasProperty(SDNPHasChain)) {
618 emitDecl("CPInChain");
619 emitDecl("Chain" + ChainSuffix);
Dan Gohman8181bd12008-07-27 21:46:04 +0000620 emitCode("SDValue CPInChain;");
621 emitCode("SDValue Chain" + ChainSuffix + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 }
623
624 std::string Code = Fn + "(" + RootName + ", " + RootName;
625 for (unsigned i = 0; i < NumOps; i++)
626 Code += ", CPTmp" + utostr(i);
627 if (CP->hasProperty(SDNPHasChain)) {
628 ChainName = "Chain" + ChainSuffix;
629 Code += ", CPInChain, Chain" + ChainSuffix;
630 }
631 emitCheck(Code + ")");
632 }
633 }
634
635 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb059c7c92008-01-31 07:27:46 +0000636 const std::string &RootName,
637 const std::string &ParentRootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 const std::string &ChainSuffix, bool &FoundChain) {
639 if (!Child->isLeaf()) {
640 // If it's not a leaf, recursively match.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000641 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 emitCheck(RootName + ".getOpcode() == " +
643 CInfo.getEnumName());
644 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng07f307d2008-02-05 22:50:29 +0000645 bool HasChain = false;
646 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
647 HasChain = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
Evan Cheng07f307d2008-02-05 22:50:29 +0000649 }
650 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
651 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
652 "Pattern folded multiple nodes which produce flags?");
653 FoldedFlag = std::make_pair(RootName,
654 CInfo.getNumResults() + (unsigned)HasChain);
655 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 } else {
657 // If this child has a name associated with it, capture it in VarMap. If
658 // we already saw this in the pattern, emit code to verify dagness.
659 if (!Child->getName().empty()) {
660 std::string &VarMapEntry = VariableMap[Child->getName()];
661 if (VarMapEntry.empty()) {
662 VarMapEntry = RootName;
663 } else {
664 // If we get here, this is a second reference to a specific name.
665 // Since we already have checked that the first reference is valid,
666 // we don't have to recursively match it, just check that it's the
667 // same as the previously named thing.
668 emitCheck(VarMapEntry + " == " + RootName);
669 Duplicates.insert(RootName);
670 return;
671 }
672 }
673
674 // Handle leaves of various types.
675 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
676 Record *LeafRec = DI->getDef();
677 if (LeafRec->isSubClassOf("RegisterClass") ||
678 LeafRec->getName() == "ptr_rc") {
679 // Handle register references. Nothing to do here.
680 } else if (LeafRec->isSubClassOf("Register")) {
681 // Handle register references.
682 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
683 // Handle complex pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000684 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 std::string Fn = CP->getSelectFunc();
686 unsigned NumOps = CP->getNumOperands();
687 for (unsigned i = 0; i < NumOps; ++i) {
688 emitDecl("CPTmp" + utostr(i));
Dan Gohman8181bd12008-07-27 21:46:04 +0000689 emitCode("SDValue CPTmp" + utostr(i) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 }
691 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000692 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693 FoldedChains.push_back(std::make_pair("CPInChain",
694 PInfo.getNumResults()));
695 ChainName = "Chain" + ChainSuffix;
696 emitDecl("CPInChain");
697 emitDecl(ChainName);
Dan Gohman8181bd12008-07-27 21:46:04 +0000698 emitCode("SDValue CPInChain;");
699 emitCode("SDValue " + ChainName + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 }
701
Christopher Lamb059c7c92008-01-31 07:27:46 +0000702 std::string Code = Fn + "(";
703 if (CP->hasAttribute(CPAttrParentAsRoot)) {
704 Code += ParentRootName + ", ";
705 } else {
706 Code += "N, ";
707 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708 if (CP->hasProperty(SDNPHasChain)) {
709 std::string ParentName(RootName.begin(), RootName.end()-1);
710 Code += ParentName + ", ";
711 }
712 Code += RootName;
713 for (unsigned i = 0; i < NumOps; i++)
714 Code += ", CPTmp" + utostr(i);
715 if (CP->hasProperty(SDNPHasChain))
716 Code += ", CPInChain, Chain" + ChainSuffix;
717 emitCheck(Code + ")");
718 } else if (LeafRec->getName() == "srcvalue") {
719 // Place holder for SRCVALUE nodes. Nothing to do here.
720 } else if (LeafRec->isSubClassOf("ValueType")) {
721 // Make sure this is the specified value type.
722 emitCheck("cast<VTSDNode>(" + RootName +
723 ")->getVT() == MVT::" + LeafRec->getName());
724 } else if (LeafRec->isSubClassOf("CondCode")) {
725 // Make sure this is the specified cond code.
726 emitCheck("cast<CondCodeSDNode>(" + RootName +
727 ")->get() == ISD::" + LeafRec->getName());
728 } else {
729#ifndef NDEBUG
730 Child->dump();
731 cerr << " ";
732#endif
733 assert(0 && "Unknown leaf type!");
734 }
735
736 // If there is a node predicate for this, emit the call.
737 if (!Child->getPredicateFn().empty())
738 emitCheck(Child->getPredicateFn() + "(" + RootName +
739 ".Val)");
740 } else if (IntInit *II =
741 dynamic_cast<IntInit*>(Child->getLeafValue())) {
742 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
743 unsigned CTmp = TmpNo++;
744 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
745 RootName + ")->getSignExtended();");
746
747 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
748 } else {
749#ifndef NDEBUG
750 Child->dump();
751#endif
752 assert(0 && "Unknown leaf type!");
753 }
754 }
755 }
756
757 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
758 /// we actually have to build a DAG!
759 std::vector<std::string>
Evan Cheng775baac2007-09-12 23:30:14 +0000760 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 bool InFlagDecled, bool ResNodeDecled,
762 bool LikeLeaf = false, bool isRoot = false) {
763 // List of arguments of getTargetNode() or SelectNodeTo().
764 std::vector<std::string> NodeOps;
765 // This is something selected from the pattern we matched.
766 if (!N->getName().empty()) {
Scott Michel30124c22008-01-29 02:29:31 +0000767 const std::string &VarName = N->getName();
768 std::string Val = VariableMap[VarName];
769 bool ModifiedVal = false;
Scott Michelac7091c2008-02-15 23:05:48 +0000770 if (Val.empty()) {
Bill Wendling39d33752008-02-26 10:45:29 +0000771 cerr << "Variable '" << VarName << " referenced but not defined "
772 << "and not caught earlier!\n";
773 abort();
Scott Michelac7091c2008-02-15 23:05:48 +0000774 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
776 // Already selected this operand, just return the tmpval.
777 NodeOps.push_back(Val);
778 return NodeOps;
779 }
780
781 const ComplexPattern *CP;
782 unsigned ResNo = TmpNo++;
783 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
784 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
785 std::string CastType;
Scott Michel30124c22008-01-29 02:29:31 +0000786 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 switch (N->getTypeNum(0)) {
788 default:
789 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
790 << " type as an immediate constant. Aborting\n";
791 abort();
792 case MVT::i1: CastType = "bool"; break;
793 case MVT::i8: CastType = "unsigned char"; break;
794 case MVT::i16: CastType = "unsigned short"; break;
795 case MVT::i32: CastType = "unsigned"; break;
796 case MVT::i64: CastType = "uint64_t"; break;
797 }
Dan Gohman8181bd12008-07-27 21:46:04 +0000798 emitCode("SDValue " + TmpVar +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 " = CurDAG->getTargetConstant(((" + CastType +
800 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
801 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
803 // value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000804 Val = TmpVar;
805 ModifiedVal = true;
806 NodeOps.push_back(Val);
Nate Begemane2ba64f2008-02-14 08:57:00 +0000807 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
808 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
809 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000810 emitCode("SDValue " + TmpVar +
Nate Begemane2ba64f2008-02-14 08:57:00 +0000811 " = CurDAG->getTargetConstantFP(cast<ConstantFPSDNode>(" +
812 Val + ")->getValueAPF(), cast<ConstantFPSDNode>(" + Val +
813 ")->getValueType(0));");
814 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
815 // value if used multiple times by this pattern result.
816 Val = TmpVar;
817 ModifiedVal = true;
818 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
820 Record *Op = OperatorMap[N->getName()];
821 // Transform ExternalSymbol to TargetExternalSymbol
822 if (Op && Op->getName() == "externalsym") {
Scott Michel30124c22008-01-29 02:29:31 +0000823 std::string TmpVar = "Tmp"+utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000824 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
826 Val + ")->getSymbol(), " +
827 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
829 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000830 Val = TmpVar;
831 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 }
Scott Michel30124c22008-01-29 02:29:31 +0000833 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
835 || N->getOperator()->getName() == "tglobaltlsaddr")) {
836 Record *Op = OperatorMap[N->getName()];
837 // Transform GlobalAddress to TargetGlobalAddress
838 if (Op && (Op->getName() == "globaladdr" ||
839 Op->getName() == "globaltlsaddr")) {
Scott Michel30124c22008-01-29 02:29:31 +0000840 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000841 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
843 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
844 ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
846 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000847 Val = TmpVar;
848 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 NodeOps.push_back(Val);
Scott Michel30124c22008-01-29 02:29:31 +0000851 } else if (!N->isLeaf()
852 && (N->getOperator()->getName() == "texternalsym"
853 || N->getOperator()->getName() == "tconstpool")) {
854 // Do not rewrite the variable name, since we don't generate a new
855 // temporary.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 NodeOps.push_back(Val);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000857 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
859 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
860 NodeOps.push_back("CPTmp" + utostr(i));
861 }
862 } else {
863 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
864 // node even if it isn't one. Don't select it.
865 if (!LikeLeaf) {
866 emitCode("AddToISelQueue(" + Val + ");");
867 if (isRoot && N->isLeaf()) {
868 emitCode("ReplaceUses(N, " + Val + ");");
869 emitCode("return NULL;");
870 }
871 }
872 NodeOps.push_back(Val);
873 }
Scott Michel30124c22008-01-29 02:29:31 +0000874
875 if (ModifiedVal) {
876 VariableMap[VarName] = Val;
877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878 return NodeOps;
879 }
880 if (N->isLeaf()) {
881 // If this is an explicit register reference, handle it.
882 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
883 unsigned ResNo = TmpNo++;
884 if (DI->getDef()->isSubClassOf("Register")) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000885 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000886 getQualifiedName(DI->getDef()) + ", " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 getEnumName(N->getTypeNum(0)) + ");");
888 NodeOps.push_back("Tmp" + utostr(ResNo));
889 return NodeOps;
890 } else if (DI->getDef()->getName() == "zero_reg") {
Dan Gohman8181bd12008-07-27 21:46:04 +0000891 emitCode("SDValue Tmp" + utostr(ResNo) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 " = CurDAG->getRegister(0, " +
893 getEnumName(N->getTypeNum(0)) + ");");
894 NodeOps.push_back("Tmp" + utostr(ResNo));
895 return NodeOps;
896 }
897 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
898 unsigned ResNo = TmpNo++;
899 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Dan Gohman8181bd12008-07-27 21:46:04 +0000900 emitCode("SDValue Tmp" + utostr(ResNo) +
Scott Michelac7091c2008-02-15 23:05:48 +0000901 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
902 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 NodeOps.push_back("Tmp" + utostr(ResNo));
904 return NodeOps;
905 }
906
907#ifndef NDEBUG
908 N->dump();
909#endif
910 assert(0 && "Unknown leaf type!");
911 return NodeOps;
912 }
913
914 Record *Op = N->getOperator();
915 if (Op->isSubClassOf("Instruction")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000916 const CodeGenTarget &CGT = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000918 const DAGInstruction &Inst = CGP.getInstruction(Op);
Chris Lattner7c6e5852008-01-06 01:52:22 +0000919 const TreePattern *InstPat = Inst.getPattern();
Evan Chengf031fcb2007-09-25 01:48:59 +0000920 // FIXME: Assume actual pattern comes before "implicit".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 TreePatternNode *InstPatNode =
Evan Cheng775baac2007-09-12 23:30:14 +0000922 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
923 : (InstPat ? InstPat->getTree(0) : NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengf37df842007-09-11 19:52:18 +0000925 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000927 bool IsVariadic = isRoot && II.isVariadic;
Evan Cheng775baac2007-09-12 23:30:14 +0000928 // FIXME: fix how we deal with physical register operands.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng775baac2007-09-12 23:30:14 +0000930 bool HasImpResults = isRoot && DstRegs.size() > 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 bool NodeHasOptInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000932 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933 bool NodeHasInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000934 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengdec1dd12007-09-07 23:59:02 +0000935 bool NodeHasOutFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000936 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 bool NodeHasChain = InstPatNode &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000938 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 bool InputHasChain = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000940 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 unsigned NumResults = Inst.getNumResults();
Evan Cheng775baac2007-09-12 23:30:14 +0000942 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000944 // Record output varargs info.
945 OutputIsVariadic = IsVariadic;
946
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 if (NodeHasOptInFlag) {
948 emitCode("bool HasInFlag = "
949 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
950 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000951 if (IsVariadic)
Dan Gohman8181bd12008-07-27 21:46:04 +0000952 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953
954 // How many results is this pattern expected to produce?
Evan Cheng775baac2007-09-12 23:30:14 +0000955 unsigned NumPatResults = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
Duncan Sands92c43912008-06-06 12:08:01 +0000957 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng775baac2007-09-12 23:30:14 +0000959 NumPatResults++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 }
961
962 if (OrigChains.size() > 0) {
963 // The original input chain is being ignored. If it is not just
964 // pointing to the op that's being folded, we should create a
965 // TokenFactor with it and the chain of the folded op as the new chain.
966 // We could potentially be doing multiple levels of folding, in that
967 // case, the TokenFactor can have more operands.
Dan Gohman8181bd12008-07-27 21:46:04 +0000968 emitCode("SmallVector<SDValue, 8> InChains;");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
970 emitCode("if (" + OrigChains[i].first + ".Val != " +
971 OrigChains[i].second + ".Val) {");
972 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
973 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
974 emitCode("}");
975 }
976 emitCode("AddToISelQueue(" + ChainName + ");");
977 emitCode("InChains.push_back(" + ChainName + ");");
978 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
979 "&InChains[0], InChains.size());");
980 }
981
982 // Loop over all of the operands of the instruction pattern, emitting code
983 // to fill them all in. The node 'N' usually has number children equal to
984 // the number of input operands of the instruction. However, in cases
985 // where there are predicate operands for an instruction, we need to fill
986 // in the 'execute always' values. Match up the node operands to the
987 // instruction operands to do this.
988 std::vector<std::string> AllOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 for (unsigned ChildNo = 0, InstOpNo = NumResults;
990 InstOpNo != II.OperandList.size(); ++InstOpNo) {
991 std::vector<std::string> Ops;
992
Dan Gohman3329ffe2008-05-29 19:57:41 +0000993 // Determine what to emit for this operand.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000995 if ((OperandNode->isSubClassOf("PredicateOperand") ||
996 OperandNode->isSubClassOf("OptionalDefOperand")) &&
997 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Dan Gohman3329ffe2008-05-29 19:57:41 +0000998 // This is a predicate or optional def operand; emit the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 // 'default ops' operands.
1000 const DAGDefaultOperand &DefaultOp =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001001 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Chengdb1f2462007-09-17 22:26:41 +00001003 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004 InFlagDecled, ResNodeDecled);
1005 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 }
Dan Gohman3329ffe2008-05-29 19:57:41 +00001007 } else {
1008 // Otherwise this is a normal operand or a predicate operand without
1009 // 'execute always'; emit it.
1010 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1011 InFlagDecled, ResNodeDecled);
1012 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1013 ++ChildNo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 }
1015 }
1016
1017 // Emit all the chain and CopyToReg stuff.
1018 bool ChainEmitted = NodeHasChain;
1019 if (NodeHasChain)
1020 emitCode("AddToISelQueue(" + ChainName + ");");
1021 if (NodeHasInFlag || HasImpInputs)
1022 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1023 InFlagDecled, ResNodeDecled, true);
1024 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1025 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001026 emitCode("SDValue InFlag(0, 0);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027 InFlagDecled = true;
1028 }
1029 if (NodeHasOptInFlag) {
1030 emitCode("if (HasInFlag) {");
1031 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1032 emitCode(" AddToISelQueue(InFlag);");
1033 emitCode("}");
1034 }
1035 }
1036
1037 unsigned ResNo = TmpNo++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038
Dan Gohman6761ff52008-07-07 21:00:17 +00001039 unsigned OpsNo = OpcNo;
1040 std::string CodePrefix;
1041 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1042 std::deque<std::string> After;
1043 std::string NodeName;
1044 if (!isRoot) {
1045 NodeName = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +00001046 CodePrefix = "SDValue " + NodeName + "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 } else {
Dan Gohman6761ff52008-07-07 21:00:17 +00001048 NodeName = "ResNode";
1049 if (!ResNodeDecled) {
1050 CodePrefix = "SDNode *" + NodeName + " = ";
1051 ResNodeDecled = true;
1052 } else
1053 CodePrefix = NodeName + " = ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 }
1055
Dan Gohman6761ff52008-07-07 21:00:17 +00001056 std::string Code = "Opc" + utostr(OpcNo);
1057
1058 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1059
1060 // Output order: results, chain, flags
1061 // Result types.
1062 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1063 Code += ", VT" + utostr(VTNo);
1064 emitVT(getEnumName(N->getTypeNum(0)));
1065 }
1066 // Add types for implicit results in physical registers, scheduler will
1067 // care of adding copyfromreg nodes.
1068 for (unsigned i = 0; i < NumDstRegs; i++) {
1069 Record *RR = DstRegs[i];
1070 if (RR->isSubClassOf("Register")) {
1071 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1072 Code += ", " + getEnumName(RVT);
1073 }
1074 }
1075 if (NodeHasChain)
1076 Code += ", MVT::Other";
1077 if (NodeHasOutFlag)
1078 Code += ", MVT::Flag";
1079
1080 // Inputs.
1081 if (IsVariadic) {
1082 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1083 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1084 AllOps.clear();
1085
1086 // Figure out whether any operands at the end of the op list are not
1087 // part of the variable section.
1088 std::string EndAdjust;
1089 if (NodeHasInFlag || HasImpInputs)
1090 EndAdjust = "-1"; // Always has one flag.
1091 else if (NodeHasOptInFlag)
1092 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1093
1094 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1095 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1096
1097 emitCode(" AddToISelQueue(N.getOperand(i));");
1098 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1099 emitCode("}");
1100 }
1101
1102 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1103 // this pattern.
1104 if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
1105 std::vector<std::string>::const_iterator mi, mie;
1106 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001107 emitCode("SDValue LSI_" + *mi + " = "
Dan Gohman6761ff52008-07-07 21:00:17 +00001108 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1109 *mi + ")->getMemOperand());");
1110 if (IsVariadic)
1111 emitCode("Ops" + utostr(OpsNo) + ".push_back(LSI_" + *mi + ");");
1112 else
1113 AllOps.push_back("LSI_" + *mi);
1114 }
1115 }
1116
1117 if (NodeHasChain) {
1118 if (IsVariadic)
1119 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1120 else
1121 AllOps.push_back(ChainName);
1122 }
1123
1124 if (IsVariadic) {
1125 if (NodeHasInFlag || HasImpInputs)
1126 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1127 else if (NodeHasOptInFlag) {
1128 emitCode("if (HasInFlag)");
1129 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1130 }
1131 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1132 ".size()";
1133 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1134 AllOps.push_back("InFlag");
1135
1136 unsigned NumOps = AllOps.size();
1137 if (NumOps) {
1138 if (!NodeHasOptInFlag && NumOps < 4) {
1139 for (unsigned i = 0; i != NumOps; ++i)
1140 Code += ", " + AllOps[i];
1141 } else {
Dan Gohman8181bd12008-07-27 21:46:04 +00001142 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
Dan Gohman6761ff52008-07-07 21:00:17 +00001143 for (unsigned i = 0; i != NumOps; ++i) {
1144 OpsCode += AllOps[i];
1145 if (i != NumOps-1)
1146 OpsCode += ", ";
1147 }
1148 emitCode(OpsCode + " };");
1149 Code += ", Ops" + utostr(OpsNo) + ", ";
1150 if (NodeHasOptInFlag) {
1151 Code += "HasInFlag ? ";
1152 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1153 } else
1154 Code += utostr(NumOps);
1155 }
1156 }
1157
1158 if (!isRoot)
1159 Code += "), 0";
1160
Dan Gohmanbd68c792008-07-17 19:10:17 +00001161 std::vector<std::string> ReplaceFroms;
1162 std::vector<std::string> ReplaceTos;
Dan Gohman6761ff52008-07-07 21:00:17 +00001163 if (!isRoot) {
1164 NodeOps.push_back("Tmp" + utostr(ResNo));
1165 } else {
1166
1167 if (NodeHasOutFlag) {
1168 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001169 After.push_back("SDValue InFlag(ResNode, " +
Dan Gohman6761ff52008-07-07 21:00:17 +00001170 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1171 ");");
1172 InFlagDecled = true;
1173 } else
Dan Gohman8181bd12008-07-27 21:46:04 +00001174 After.push_back("InFlag = SDValue(ResNode, " +
Dan Gohman6761ff52008-07-07 21:00:17 +00001175 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1176 ");");
1177 }
1178
1179 if (FoldedChains.size() > 0) {
1180 std::string Code;
Dan Gohmanbd68c792008-07-17 19:10:17 +00001181 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001182 ReplaceFroms.push_back("SDValue(" +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001183 FoldedChains[j].first + ".Val, " +
1184 utostr(FoldedChains[j].second) +
1185 ")");
Dan Gohman8181bd12008-07-27 21:46:04 +00001186 ReplaceTos.push_back("SDValue(ResNode, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001187 utostr(NumResults+NumDstRegs) + ")");
1188 }
Dan Gohman6761ff52008-07-07 21:00:17 +00001189 }
1190
1191 if (NodeHasOutFlag) {
1192 if (FoldedFlag.first != "") {
Dan Gohman8181bd12008-07-27 21:46:04 +00001193 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001194 utostr(FoldedFlag.second) + ")");
1195 ReplaceTos.push_back("InFlag");
Dan Gohman6761ff52008-07-07 21:00:17 +00001196 } else {
1197 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
Dan Gohman8181bd12008-07-27 21:46:04 +00001198 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001199 utostr(NumPatResults + (unsigned)InputHasChain)
1200 + ")");
1201 ReplaceTos.push_back("InFlag");
Dan Gohman6761ff52008-07-07 21:00:17 +00001202 }
Dan Gohman6761ff52008-07-07 21:00:17 +00001203 }
1204
Dan Gohmanbd68c792008-07-17 19:10:17 +00001205 if (!ReplaceFroms.empty() && InputHasChain) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001206 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001207 utostr(NumPatResults) + ")");
Dan Gohman8181bd12008-07-27 21:46:04 +00001208 ReplaceTos.push_back("SDValue(" + ChainName + ".Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001209 ChainName + ".ResNo" + ")");
Dan Gohman6761ff52008-07-07 21:00:17 +00001210 ChainAssignmentNeeded |= NodeHasChain;
1211 }
1212
1213 // User does not expect the instruction would produce a chain!
1214 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1215 ;
1216 } else if (InputHasChain && !NodeHasChain) {
1217 // One of the inner node produces a chain.
Dan Gohmanbd68c792008-07-17 19:10:17 +00001218 if (NodeHasOutFlag) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001219 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001220 utostr(NumPatResults+1) +
1221 ")");
Dan Gohman8181bd12008-07-27 21:46:04 +00001222 ReplaceTos.push_back("SDValue(ResNode, N.ResNo-1)");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001223 }
Dan Gohman8181bd12008-07-27 21:46:04 +00001224 ReplaceFroms.push_back("SDValue(N.Val, " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001225 utostr(NumPatResults) + ")");
1226 ReplaceTos.push_back(ChainName);
Dan Gohman6761ff52008-07-07 21:00:17 +00001227 }
1228 }
1229
1230 if (ChainAssignmentNeeded) {
1231 // Remember which op produces the chain.
1232 std::string ChainAssign;
1233 if (!isRoot)
Dan Gohman8181bd12008-07-27 21:46:04 +00001234 ChainAssign = ChainName + " = SDValue(" + NodeName +
Dan Gohman6761ff52008-07-07 21:00:17 +00001235 ".Val, " + utostr(NumResults+NumDstRegs) + ");";
1236 else
Dan Gohman8181bd12008-07-27 21:46:04 +00001237 ChainAssign = ChainName + " = SDValue(" + NodeName +
Dan Gohman6761ff52008-07-07 21:00:17 +00001238 ", " + utostr(NumResults+NumDstRegs) + ");";
1239
1240 After.push_front(ChainAssign);
1241 }
1242
Dan Gohmanbd68c792008-07-17 19:10:17 +00001243 if (ReplaceFroms.size() == 1) {
1244 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1245 ReplaceTos[0] + ");");
1246 } else if (!ReplaceFroms.empty()) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001247 After.push_back("const SDValue Froms[] = {");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001248 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1249 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1250 After.push_back("};");
Dan Gohman8181bd12008-07-27 21:46:04 +00001251 After.push_back("const SDValue Tos[] = {");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001252 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1253 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1254 After.push_back("};");
1255 After.push_back("ReplaceUses(Froms, Tos, " +
1256 itostr(ReplaceFroms.size()) + ");");
1257 }
1258
1259 // We prefer to use SelectNodeTo since it avoids allocation when
1260 // possible and it avoids CSE map recalculation for the node's
1261 // users, however it's tricky to use in a non-root context.
Dan Gohman6761ff52008-07-07 21:00:17 +00001262 //
Dan Gohmanbd68c792008-07-17 19:10:17 +00001263 // We also don't use if the pattern replacement is being used to
1264 // jettison a chain result, since morphing the node in place
1265 // would leave users of the chain dangling.
Dan Gohman6761ff52008-07-07 21:00:17 +00001266 //
Dan Gohmanbd68c792008-07-17 19:10:17 +00001267 if (!isRoot || (InputHasChain && !NodeHasChain)) {
Dan Gohman6761ff52008-07-07 21:00:17 +00001268 Code = "CurDAG->getTargetNode(" + Code;
1269 } else {
1270 Code = "CurDAG->SelectNodeTo(N.Val, " + Code;
1271 }
1272 if (isRoot) {
1273 if (After.empty())
1274 CodePrefix = "return ";
1275 else
1276 After.push_back("return ResNode;");
1277 }
1278
1279 emitCode(CodePrefix + Code + ");");
1280 for (unsigned i = 0, e = After.size(); i != e; ++i)
1281 emitCode(After[i]);
1282
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 return NodeOps;
1284 } else if (Op->isSubClassOf("SDNodeXForm")) {
1285 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1286 // PatLeaf node - the operand may or may not be a leaf node. But it should
1287 // behave like one.
1288 std::vector<std::string> Ops =
Evan Chengdb1f2462007-09-17 22:26:41 +00001289 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 ResNodeDecled, true);
1291 unsigned ResNo = TmpNo++;
Dan Gohman8181bd12008-07-27 21:46:04 +00001292 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 + "(" + Ops.back() + ".Val);");
1294 NodeOps.push_back("Tmp" + utostr(ResNo));
1295 if (isRoot)
1296 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1297 return NodeOps;
1298 } else {
1299 N->dump();
1300 cerr << "\n";
1301 throw std::string("Unknown node in result pattern!");
1302 }
1303 }
1304
1305 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1306 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1307 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1308 /// for, this returns true otherwise false if Pat has all types.
1309 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1310 const std::string &Prefix, bool isRoot = false) {
1311 // Did we find one?
1312 if (Pat->getExtTypes() != Other->getExtTypes()) {
1313 // Move a type over from 'other' to 'pat'.
1314 Pat->setTypes(Other->getExtTypes());
1315 // The top level node type is checked outside of the select function.
1316 if (!isRoot)
1317 emitCheck(Prefix + ".Val->getValueType(0) == " +
1318 getName(Pat->getTypeNum(0)));
1319 return true;
1320 }
1321
1322 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001323 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1325 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1326 Prefix + utostr(OpNo)))
1327 return true;
1328 return false;
1329 }
1330
1331private:
1332 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1333 /// being built.
1334 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1335 bool &ChainEmitted, bool &InFlagDecled,
1336 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001337 const CodeGenTarget &T = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001339 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1340 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1342 TreePatternNode *Child = N->getChild(i);
1343 if (!Child->isLeaf()) {
1344 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1345 InFlagDecled, ResNodeDecled);
1346 } else {
1347 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1348 if (!Child->getName().empty()) {
1349 std::string Name = RootName + utostr(OpNo);
1350 if (Duplicates.find(Name) != Duplicates.end())
1351 // A duplicate! Do not emit a copy for this node.
1352 continue;
1353 }
1354
1355 Record *RR = DI->getDef();
1356 if (RR->isSubClassOf("Register")) {
Duncan Sands92c43912008-06-06 12:08:01 +00001357 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 if (RVT == MVT::Flag) {
1359 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001360 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 InFlagDecled = true;
1362 } else
1363 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1364 emitCode("AddToISelQueue(InFlag);");
1365 } else {
1366 if (!ChainEmitted) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001367 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 ChainName = "Chain";
1369 ChainEmitted = true;
1370 }
1371 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1372 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001373 emitCode("SDValue InFlag(0, 0);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001374 InFlagDecled = true;
1375 }
1376 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1377 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001378 ", " + getQualifiedName(RR) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1380 ResNodeDecled = true;
Dan Gohman8181bd12008-07-27 21:46:04 +00001381 emitCode(ChainName + " = SDValue(ResNode, 0);");
1382 emitCode("InFlag = SDValue(ResNode, 1);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 }
1384 }
1385 }
1386 }
1387 }
1388
1389 if (HasInFlag) {
1390 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001391 emitCode("SDValue InFlag = " + RootName +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 ".getOperand(" + utostr(OpNo) + ");");
1393 InFlagDecled = true;
1394 } else
1395 emitCode("InFlag = " + RootName +
1396 ".getOperand(" + utostr(OpNo) + ");");
1397 emitCode("AddToISelQueue(InFlag);");
1398 }
1399 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001400};
1401
1402/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1403/// stream to match the pattern, and generate the code for the match if it
1404/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner81915752008-01-05 22:30:17 +00001405void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1407 std::set<std::string> &GeneratedDecl,
1408 std::vector<std::string> &TargetOpcodes,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001409 std::vector<std::string> &TargetVTs,
1410 bool &OutputIsVariadic,
1411 unsigned &NumInputRootOps) {
1412 OutputIsVariadic = false;
1413 NumInputRootOps = 0;
1414
Chris Lattner14948ea2008-01-05 22:58:54 +00001415 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1417 GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001418 TargetOpcodes, TargetVTs,
1419 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420
1421 // Emit the matcher, capturing named arguments in VariableMap.
1422 bool FoundChain = false;
1423 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1424
1425 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner14948ea2008-01-05 22:58:54 +00001426 TreePattern &TP = *CGP.pf_begin()->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427
1428 // At this point, we know that we structurally match the pattern, but the
1429 // types of the nodes may not match. Figure out the fewest number of type
1430 // comparisons we need to emit. For example, if there is only one integer
1431 // type supported by a target, there should be no type comparisons at all for
1432 // integer patterns!
1433 //
1434 // To figure out the fewest number of type checks needed, clone the pattern,
1435 // remove the types, then perform type inference on the pattern as a whole.
1436 // If there are unresolved types, emit an explicit check for those types,
1437 // apply the type to the tree, then rerun type inference. Iterate until all
1438 // types are resolved.
1439 //
1440 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1441 RemoveAllTypes(Pat);
1442
1443 do {
1444 // Resolve/propagate as many types as possible.
1445 try {
1446 bool MadeChange = true;
1447 while (MadeChange)
1448 MadeChange = Pat->ApplyTypeConstraints(TP,
1449 true/*Ignore reg constraints*/);
1450 } catch (...) {
1451 assert(0 && "Error: could not find consistent types for something we"
1452 " already decided was ok!");
1453 abort();
1454 }
1455
1456 // Insert a check for an unresolved type and add it to the tree. If we find
1457 // an unresolved type to add a check for, this returns true and we iterate,
1458 // otherwise we are done.
1459 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1460
Evan Cheng775baac2007-09-12 23:30:14 +00001461 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Chengdb1f2462007-09-17 22:26:41 +00001462 false, false, false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 delete Pat;
1464}
1465
1466/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1467/// a line causes any of them to be empty, remove them and return true when
1468/// done.
Chris Lattner81915752008-01-05 22:30:17 +00001469static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 std::vector<std::pair<unsigned, std::string> > > >
1471 &Patterns) {
1472 bool ErasedPatterns = false;
1473 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1474 Patterns[i].second.pop_back();
1475 if (Patterns[i].second.empty()) {
1476 Patterns.erase(Patterns.begin()+i);
1477 --i; --e;
1478 ErasedPatterns = true;
1479 }
1480 }
1481 return ErasedPatterns;
1482}
1483
1484/// EmitPatterns - Emit code for at least one pattern, but try to group common
1485/// code together between the patterns.
Chris Lattner81915752008-01-05 22:30:17 +00001486void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 std::vector<std::pair<unsigned, std::string> > > >
1488 &Patterns, unsigned Indent,
1489 std::ostream &OS) {
1490 typedef std::pair<unsigned, std::string> CodeLine;
1491 typedef std::vector<CodeLine> CodeList;
Chris Lattner81915752008-01-05 22:30:17 +00001492 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493
1494 if (Patterns.empty()) return;
1495
1496 // Figure out how many patterns share the next code line. Explicitly copy
1497 // FirstCodeLine so that we don't invalidate a reference when changing
1498 // Patterns.
1499 const CodeLine FirstCodeLine = Patterns.back().second.back();
1500 unsigned LastMatch = Patterns.size()-1;
1501 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1502 --LastMatch;
1503
1504 // If not all patterns share this line, split the list into two pieces. The
1505 // first chunk will use this line, the second chunk won't.
1506 if (LastMatch != 0) {
1507 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1508 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1509
1510 // FIXME: Emit braces?
1511 if (Shared.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001512 const PatternToMatch &Pattern = *Shared.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1514 Pattern.getSrcPattern()->print(OS);
1515 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1516 Pattern.getDstPattern()->print(OS);
1517 OS << "\n";
1518 unsigned AddedComplexity = Pattern.getAddedComplexity();
1519 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001520 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001522 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001524 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525 }
1526 if (FirstCodeLine.first != 1) {
1527 OS << std::string(Indent, ' ') << "{\n";
1528 Indent += 2;
1529 }
1530 EmitPatterns(Shared, Indent, OS);
1531 if (FirstCodeLine.first != 1) {
1532 Indent -= 2;
1533 OS << std::string(Indent, ' ') << "}\n";
1534 }
1535
1536 if (Other.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001537 const PatternToMatch &Pattern = *Other.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1539 Pattern.getSrcPattern()->print(OS);
1540 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1541 Pattern.getDstPattern()->print(OS);
1542 OS << "\n";
1543 unsigned AddedComplexity = Pattern.getAddedComplexity();
1544 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001545 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001547 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001549 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550 }
1551 EmitPatterns(Other, Indent, OS);
1552 return;
1553 }
1554
1555 // Remove this code from all of the patterns that share it.
1556 bool ErasedPatterns = EraseCodeLine(Patterns);
1557
1558 bool isPredicate = FirstCodeLine.first == 1;
1559
1560 // Otherwise, every pattern in the list has this line. Emit it.
1561 if (!isPredicate) {
1562 // Normal code.
1563 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1564 } else {
1565 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1566
1567 // If the next code line is another predicate, and if all of the pattern
1568 // in this group share the same next line, emit it inline now. Do this
1569 // until we run out of common predicates.
1570 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1571 // Check that all of fhe patterns in Patterns end with the same predicate.
1572 bool AllEndWithSamePredicate = true;
1573 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1574 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1575 AllEndWithSamePredicate = false;
1576 break;
1577 }
1578 // If all of the predicates aren't the same, we can't share them.
1579 if (!AllEndWithSamePredicate) break;
1580
1581 // Otherwise we can. Emit it shared now.
1582 OS << " &&\n" << std::string(Indent+4, ' ')
1583 << Patterns.back().second.back().second;
1584 ErasedPatterns = EraseCodeLine(Patterns);
1585 }
1586
1587 OS << ") {\n";
1588 Indent += 2;
1589 }
1590
1591 EmitPatterns(Patterns, Indent, OS);
1592
1593 if (isPredicate)
1594 OS << std::string(Indent-2, ' ') << "}\n";
1595}
1596
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001597static std::string getLegalCName(std::string OpName) {
1598 std::string::size_type pos = OpName.find("::");
1599 if (pos != std::string::npos)
1600 OpName.replace(pos, 2, "_");
1601 return OpName;
1602}
1603
1604void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001605 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001606
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 // Get the namespace to insert instructions into. Make sure not to pick up
1608 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1609 // instruction or something.
1610 std::string InstNS;
1611 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1612 e = Target.inst_end(); i != e; ++i) {
1613 InstNS = i->second.Namespace;
1614 if (InstNS != "TargetInstrInfo")
1615 break;
1616 }
1617
1618 if (!InstNS.empty()) InstNS += "::";
1619
1620 // Group the patterns by their top-level opcodes.
Chris Lattner81915752008-01-05 22:30:17 +00001621 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622 // All unique target node emission functions.
1623 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerae506702008-01-06 01:10:31 +00001624 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001625 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner81915752008-01-05 22:30:17 +00001626 const PatternToMatch &Pattern = *I;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001627
1628 TreePatternNode *Node = Pattern.getSrcPattern();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 if (!Node->isLeaf()) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001630 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001631 push_back(&Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001632 } else {
1633 const ComplexPattern *CP;
1634 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001635 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001636 push_back(&Pattern);
Chris Lattner14948ea2008-01-05 22:58:54 +00001637 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001638 std::vector<Record*> OpNodes = CP->getRootNodes();
1639 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001640 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1641 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001642 &Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643 }
1644 } else {
1645 cerr << "Unrecognized opcode '";
1646 Node->dump();
1647 cerr << "' on tree pattern '";
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001648 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 exit(1);
1650 }
1651 }
1652 }
1653
1654 // For each opcode, there might be multiple select functions, one per
1655 // ValueType of the node (or its first operand if it doesn't produce a
1656 // non-chain result.
1657 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1658
1659 // Emit one Select_* method for each top-level opcode. We do this instead of
1660 // emitting one giant switch statement to support compilers where this will
1661 // result in the recursive functions taking less stack space.
Chris Lattner81915752008-01-05 22:30:17 +00001662 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1664 PBOI != E; ++PBOI) {
1665 const std::string &OpName = PBOI->first;
Chris Lattner81915752008-01-05 22:30:17 +00001666 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001667 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1668
1669 // We want to emit all of the matching code now. However, we want to emit
1670 // the matches in order of minimal cost. Sort the patterns so the least
1671 // cost one is at the start.
1672 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001673 PatternSortingPredicate(CGP));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674
1675 // Split them into groups by type.
Duncan Sands92c43912008-06-06 12:08:01 +00001676 std::map<MVT::SimpleValueType,
1677 std::vector<const PatternToMatch*> > PatternsByType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner81915752008-01-05 22:30:17 +00001679 const PatternToMatch *Pat = PatternsOfOp[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 TreePatternNode *SrcPat = Pat->getSrcPattern();
Duncan Sands92c43912008-06-06 12:08:01 +00001681 MVT::SimpleValueType VT = SrcPat->getTypeNum(0);
1682 std::map<MVT::SimpleValueType,
Chris Lattner81915752008-01-05 22:30:17 +00001683 std::vector<const PatternToMatch*> >::iterator TI =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001684 PatternsByType.find(VT);
1685 if (TI != PatternsByType.end())
1686 TI->second.push_back(Pat);
1687 else {
Chris Lattner81915752008-01-05 22:30:17 +00001688 std::vector<const PatternToMatch*> PVec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689 PVec.push_back(Pat);
1690 PatternsByType.insert(std::make_pair(VT, PVec));
1691 }
1692 }
1693
Duncan Sands92c43912008-06-06 12:08:01 +00001694 for (std::map<MVT::SimpleValueType,
1695 std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1697 ++II) {
Duncan Sands92c43912008-06-06 12:08:01 +00001698 MVT::SimpleValueType OpVT = II->first;
Chris Lattner81915752008-01-05 22:30:17 +00001699 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001700 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1701 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1702
Chris Lattner81915752008-01-05 22:30:17 +00001703 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704 std::vector<std::vector<std::string> > PatternOpcodes;
1705 std::vector<std::vector<std::string> > PatternVTs;
1706 std::vector<std::set<std::string> > PatternDecls;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001707 std::vector<bool> OutputIsVariadicFlags;
1708 std::vector<unsigned> NumInputRootOpsCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1710 CodeList GeneratedCode;
1711 std::set<std::string> GeneratedDecl;
1712 std::vector<std::string> TargetOpcodes;
1713 std::vector<std::string> TargetVTs;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001714 bool OutputIsVariadic;
1715 unsigned NumInputRootOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001716 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001717 TargetOpcodes, TargetVTs,
1718 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1720 PatternDecls.push_back(GeneratedDecl);
1721 PatternOpcodes.push_back(TargetOpcodes);
1722 PatternVTs.push_back(TargetVTs);
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001723 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1724 NumInputRootOpsCounts.push_back(NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725 }
1726
1727 // Scan the code to see if all of the patterns are reachable and if it is
1728 // possible that the last one might not match.
1729 bool mightNotMatch = true;
1730 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1731 CodeList &GeneratedCode = CodeForPatterns[i].second;
1732 mightNotMatch = false;
1733
1734 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1735 if (GeneratedCode[j].first == 1) { // predicate.
1736 mightNotMatch = true;
1737 break;
1738 }
1739 }
1740
1741 // If this pattern definitely matches, and if it isn't the last one, the
1742 // patterns after it CANNOT ever match. Error out.
1743 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1744 cerr << "Pattern '";
1745 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1746 cerr << "' is impossible to select!\n";
1747 exit(1);
1748 }
1749 }
1750
1751 // Factor target node emission code (emitted by EmitResultCode) into
1752 // separate functions. Uniquing and share them among all instruction
1753 // selection routines.
1754 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1755 CodeList &GeneratedCode = CodeForPatterns[i].second;
1756 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1757 std::vector<std::string> &TargetVTs = PatternVTs[i];
1758 std::set<std::string> Decls = PatternDecls[i];
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001759 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1760 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761 std::vector<std::string> AddedInits;
1762 int CodeSize = (int)GeneratedCode.size();
1763 int LastPred = -1;
1764 for (int j = CodeSize-1; j >= 0; --j) {
1765 if (LastPred == -1 && GeneratedCode[j].first == 1)
1766 LastPred = j;
1767 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1768 AddedInits.push_back(GeneratedCode[j].second);
1769 }
1770
Dan Gohman8181bd12008-07-27 21:46:04 +00001771 std::string CalleeCode = "(const SDValue &N";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772 std::string CallerCode = "(N";
1773 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1774 CalleeCode += ", unsigned Opc" + utostr(j);
1775 CallerCode += ", " + TargetOpcodes[j];
1776 }
1777 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Duncan Sands92c43912008-06-06 12:08:01 +00001778 CalleeCode += ", MVT VT" + utostr(j);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779 CallerCode += ", " + TargetVTs[j];
1780 }
1781 for (std::set<std::string>::iterator
1782 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1783 std::string Name = *I;
Dan Gohman8181bd12008-07-27 21:46:04 +00001784 CalleeCode += ", SDValue &" + Name;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 CallerCode += ", " + Name;
1786 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001787
1788 if (OutputIsVariadic) {
1789 CalleeCode += ", unsigned NumInputRootOps";
1790 CallerCode += ", " + utostr(NumInputRootOps);
1791 }
1792
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793 CallerCode += ");";
1794 CalleeCode += ") ";
1795 // Prevent emission routines from being inlined to reduce selection
1796 // routines stack frame sizes.
1797 CalleeCode += "DISABLE_INLINE ";
1798 CalleeCode += "{\n";
1799
1800 for (std::vector<std::string>::const_reverse_iterator
1801 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1802 CalleeCode += " " + *I + "\n";
1803
1804 for (int j = LastPred+1; j < CodeSize; ++j)
1805 CalleeCode += " " + GeneratedCode[j].second + "\n";
1806 for (int j = LastPred+1; j < CodeSize; ++j)
1807 GeneratedCode.pop_back();
1808 CalleeCode += "}\n";
1809
1810 // Uniquing the emission routines.
1811 unsigned EmitFuncNum;
1812 std::map<std::string, unsigned>::iterator EFI =
1813 EmitFunctions.find(CalleeCode);
1814 if (EFI != EmitFunctions.end()) {
1815 EmitFuncNum = EFI->second;
1816 } else {
1817 EmitFuncNum = EmitFunctions.size();
1818 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1819 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1820 }
1821
1822 // Replace the emission code within selection routines with calls to the
1823 // emission functions.
1824 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1825 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1826 }
1827
1828 // Print function.
1829 std::string OpVTStr;
1830 if (OpVT == MVT::iPTR) {
1831 OpVTStr = "_iPTR";
Mon P Wangce3ac892008-07-30 04:36:53 +00001832 } else if (OpVT == MVT::iPTRAny) {
1833 OpVTStr = "_iPTRAny";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 } else if (OpVT == MVT::isVoid) {
1835 // Nodes with a void result actually have a first result type of either
1836 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1837 // void to this case, we handle it specially here.
1838 } else {
1839 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1840 }
1841 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1842 OpcodeVTMap.find(OpName);
1843 if (OpVTI == OpcodeVTMap.end()) {
1844 std::vector<std::string> VTSet;
1845 VTSet.push_back(OpVTStr);
1846 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1847 } else
1848 OpVTI->second.push_back(OpVTStr);
1849
1850 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohman8181bd12008-07-27 21:46:04 +00001851 << OpVTStr << "(const SDValue &N) {\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001852
1853 // Loop through and reverse all of the CodeList vectors, as we will be
1854 // accessing them from their logical front, but accessing the end of a
1855 // vector is more efficient.
1856 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1857 CodeList &GeneratedCode = CodeForPatterns[i].second;
1858 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1859 }
1860
1861 // Next, reverse the list of patterns itself for the same reason.
1862 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1863
1864 // Emit all of the patterns now, grouped together to share code.
1865 EmitPatterns(CodeForPatterns, 2, OS);
1866
1867 // If the last pattern has predicates (which could fail) emit code to
1868 // catch the case where nothing handles a pattern.
1869 if (mightNotMatch) {
1870 OS << " cerr << \"Cannot yet select: \";\n";
1871 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1872 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1873 OpName != "ISD::INTRINSIC_VOID") {
1874 OS << " N.Val->dump(CurDAG);\n";
1875 } else {
1876 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1877 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1878 << " cerr << \"intrinsic %\"<< "
1879 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1880 }
1881 OS << " cerr << '\\n';\n"
1882 << " abort();\n"
1883 << " return NULL;\n";
1884 }
1885 OS << "}\n\n";
1886 }
1887 }
1888
1889 // Emit boilerplate.
Dan Gohman8181bd12008-07-27 21:46:04 +00001890 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1891 << " std::vector<SDValue> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1893
1894 << " // Ensure that the asm operands are themselves selected.\n"
1895 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1896 << " AddToISelQueue(Ops[j]);\n\n"
1897
Duncan Sands92c43912008-06-06 12:08:01 +00001898 << " std::vector<MVT> VTs;\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001899 << " VTs.push_back(MVT::Other);\n"
1900 << " VTs.push_back(MVT::Flag);\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001901 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 "Ops.size());\n"
1903 << " return New.Val;\n"
1904 << "}\n\n";
Evan Cheng3c0eda52008-03-15 00:03:38 +00001905
Dan Gohman8181bd12008-07-27 21:46:04 +00001906 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001907 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::IMPLICIT_DEF,\n"
1908 << " N.getValueType());\n"
1909 << "}\n\n";
1910
Dan Gohman8181bd12008-07-27 21:46:04 +00001911 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1912 << " SDValue Chain = N.getOperand(0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001913 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001914 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001915 << " AddToISelQueue(Chain);\n"
1916 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DBG_LABEL,\n"
1917 << " MVT::Other, Tmp, Chain);\n"
1918 << "}\n\n";
1919
Dan Gohman8181bd12008-07-27 21:46:04 +00001920 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1921 << " SDValue Chain = N.getOperand(0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001922 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001923 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001924 << " AddToISelQueue(Chain);\n"
1925 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EH_LABEL,\n"
1926 << " MVT::Other, Tmp, Chain);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00001927 << "}\n\n";
1928
Dan Gohman8181bd12008-07-27 21:46:04 +00001929 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1930 << " SDValue Chain = N.getOperand(0);\n"
1931 << " SDValue N1 = N.getOperand(1);\n"
1932 << " SDValue N2 = N.getOperand(2);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001933 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1934 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1935 << " N.Val->dump(CurDAG);\n"
1936 << " abort();\n"
1937 << " }\n"
1938 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1939 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001940 << " SDValue Tmp1 = "
Evan Cheng2e28d622008-02-02 04:07:54 +00001941 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001942 << " SDValue Tmp2 = "
Evan Cheng2e28d622008-02-02 04:07:54 +00001943 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1944 << " AddToISelQueue(Chain);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001945 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DECLARE,\n"
1946 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001947 << "}\n\n";
1948
Dan Gohman8181bd12008-07-27 21:46:04 +00001949 OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1950 << " SDValue N0 = N.getOperand(0);\n"
1951 << " SDValue N1 = N.getOperand(1);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001952 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001953 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001954 << " AddToISelQueue(N0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001955 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EXTRACT_SUBREG,\n"
1956 << " N.getValueType(), N0, Tmp);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001957 << "}\n\n";
1958
Dan Gohman8181bd12008-07-27 21:46:04 +00001959 OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1960 << " SDValue N0 = N.getOperand(0);\n"
1961 << " SDValue N1 = N.getOperand(1);\n"
1962 << " SDValue N2 = N.getOperand(2);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001963 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001964 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001965 << " AddToISelQueue(N1);\n"
Christopher Lambb371e032008-03-13 05:47:01 +00001966 << " AddToISelQueue(N0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001967 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::INSERT_SUBREG,\n"
1968 << " N.getValueType(), N0, N1, Tmp);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001969 << "}\n\n";
1970
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001971 OS << "// The main instruction selector code.\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001972 << "SDNode *SelectCode(SDValue N) {\n"
Dan Gohmanbd68c792008-07-17 19:10:17 +00001973 << " if (N.isMachineOpcode()) {\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974 << " return NULL; // Already selected.\n"
1975 << " }\n\n"
Duncan Sands92c43912008-06-06 12:08:01 +00001976 << " MVT::SimpleValueType NVT = N.Val->getValueType(0).getSimpleVT();\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977 << " switch (N.getOpcode()) {\n"
1978 << " default: break;\n"
1979 << " case ISD::EntryToken: // These leaves remain the same.\n"
1980 << " case ISD::BasicBlock:\n"
1981 << " case ISD::Register:\n"
1982 << " case ISD::HANDLENODE:\n"
1983 << " case ISD::TargetConstant:\n"
Nate Begemane2ba64f2008-02-14 08:57:00 +00001984 << " case ISD::TargetConstantFP:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001985 << " case ISD::TargetConstantPool:\n"
1986 << " case ISD::TargetFrameIndex:\n"
1987 << " case ISD::TargetExternalSymbol:\n"
1988 << " case ISD::TargetJumpTable:\n"
1989 << " case ISD::TargetGlobalTLSAddress:\n"
1990 << " case ISD::TargetGlobalAddress: {\n"
1991 << " return NULL;\n"
1992 << " }\n"
1993 << " case ISD::AssertSext:\n"
1994 << " case ISD::AssertZext: {\n"
1995 << " AddToISelQueue(N.getOperand(0));\n"
1996 << " ReplaceUses(N, N.getOperand(0));\n"
1997 << " return NULL;\n"
1998 << " }\n"
1999 << " case ISD::TokenFactor:\n"
2000 << " case ISD::CopyFromReg:\n"
2001 << " case ISD::CopyToReg: {\n"
2002 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2003 << " AddToISelQueue(N.getOperand(i));\n"
2004 << " return NULL;\n"
2005 << " }\n"
2006 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00002007 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
2008 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00002009 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00002010 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00002011 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
2012 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013
2014
2015 // Loop over all of the case statements, emiting a call to each method we
2016 // emitted above.
Chris Lattner81915752008-01-05 22:30:17 +00002017 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002018 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
2019 PBOI != E; ++PBOI) {
2020 const std::string &OpName = PBOI->first;
2021 // Potentially multiple versions of select for this opcode. One for each
2022 // ValueType of the node (or its first true operand if it doesn't produce a
2023 // result.
2024 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2025 OpcodeVTMap.find(OpName);
2026 std::vector<std::string> &OpVTs = OpVTI->second;
2027 OS << " case " << OpName << ": {\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00002028 // Keep track of whether we see a pattern that has an iPtr result.
2029 bool HasPtrPattern = false;
2030 bool HasDefaultPattern = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002031
Evan Chengb8b6b182007-09-04 20:18:28 +00002032 OS << " switch (NVT) {\n";
2033 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2034 std::string &VTStr = OpVTs[i];
2035 if (VTStr.empty()) {
2036 HasDefaultPattern = true;
2037 continue;
2038 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002039
Evan Chengb8b6b182007-09-04 20:18:28 +00002040 // If this is a match on iPTR: don't emit it directly, we need special
2041 // code.
2042 if (VTStr == "_iPTR") {
2043 HasPtrPattern = true;
2044 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045 }
Evan Chengb8b6b182007-09-04 20:18:28 +00002046 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2047 << " return Select_" << getLegalCName(OpName)
2048 << VTStr << "(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002049 }
Evan Chengb8b6b182007-09-04 20:18:28 +00002050 OS << " default:\n";
2051
2052 // If there is an iPTR result version of this pattern, emit it here.
2053 if (HasPtrPattern) {
Duncan Sands92c43912008-06-06 12:08:01 +00002054 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00002055 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2056 }
2057 if (HasDefaultPattern) {
2058 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2059 }
2060 OS << " break;\n";
2061 OS << " }\n";
2062 OS << " break;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 OS << " }\n";
2064 }
2065
2066 OS << " } // end of big switch.\n\n"
2067 << " cerr << \"Cannot yet select: \";\n"
2068 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2069 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2070 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2071 << " N.Val->dump(CurDAG);\n"
2072 << " } else {\n"
2073 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2074 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
2075 << " cerr << \"intrinsic %\"<< "
2076 "Intrinsic::getName((Intrinsic::ID)iid);\n"
2077 << " }\n"
2078 << " cerr << '\\n';\n"
2079 << " abort();\n"
2080 << " return NULL;\n"
2081 << "}\n";
2082}
2083
2084void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00002085 EmitSourceFileHeader("DAG Instruction Selector for the " +
2086 CGP.getTargetInfo().getName() + " target", OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002087
2088 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2089 << "// *** instruction selector class. These functions are really "
2090 << "methods.\n\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00002091
Roman Levenstein393ad0f2008-05-14 10:17:11 +00002092 OS << "// Include standard, target-independent definitions and methods used\n"
2093 << "// by the instruction selector.\n";
2094 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095
Chris Lattner227da452008-01-05 22:54:53 +00002096 EmitNodeTransforms(OS);
Chris Lattner7fdd9342008-01-05 22:43:57 +00002097 EmitPredicateFunctions(OS);
2098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattnerae506702008-01-06 01:10:31 +00002100 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00002101 I != E; ++I) {
2102 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2103 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 DOUT << "\n";
2105 }
2106
2107 // At this point, we have full information about the 'Patterns' we need to
2108 // parse, both implicitly from instructions as well as from explicit pattern
2109 // definitions. Emit the resultant instruction selector.
2110 EmitInstructionSelector(OS);
2111
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112}