blob: 8632bc5ce8db7adf7debe9a64921d3040784968f [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 Gohmanf17a25c2007-07-18 16:29:46 +000021using namespace llvm;
22
23//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024// DAGISelEmitter implementation
25//
26
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027
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 Lattner4ca8ff02008-01-05 22:25:12 +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 Lattner4ca8ff02008-01-05 22:25:12 +000054static unsigned getPatternSize(TreePatternNode *P, CodegenDAGPatterns &CGP) {
55 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
56 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057 P->getExtTypeNum(0) == MVT::isVoid ||
58 P->getExtTypeNum(0) == MVT::Flag ||
59 P->getExtTypeNum(0) == MVT::iPTR) &&
60 "Not a valid pattern node to size!");
61 unsigned Size = 3; // The node itself.
62 // If the root node is a ConstantSDNode, increases its size.
63 // e.g. (set R32:$dst, 0).
64 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
65 Size += 2;
66
67 // FIXME: This is a hack to statically increase the priority of patterns
68 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
69 // Later we can allow complexity / cost for each pattern to be (optionally)
70 // specified. To get best possible pattern match we'll need to dynamically
71 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner4ca8ff02008-01-05 22:25:12 +000072 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073 if (AM)
74 Size += AM->getNumOperands() * 3;
75
76 // If this node has some predicate function that must match, it adds to the
77 // complexity of this node.
78 if (!P->getPredicateFn().empty())
79 ++Size;
80
81 // Count children in the count if they are also nodes.
82 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
83 TreePatternNode *Child = P->getChild(i);
84 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner4ca8ff02008-01-05 22:25:12 +000085 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 else if (Child->isLeaf()) {
87 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
88 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
89 else if (NodeIsComplexPattern(Child))
Chris Lattner4ca8ff02008-01-05 22:25:12 +000090 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091 else if (!Child->getPredicateFn().empty())
92 ++Size;
93 }
94 }
95
96 return Size;
97}
98
99/// getResultPatternCost - Compute the number of instructions for this pattern.
100/// This is a temporary hack. We should really include the instruction
101/// latencies in this calculation.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000102static unsigned getResultPatternCost(TreePatternNode *P,
103 CodegenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 if (P->isLeaf()) return 0;
105
106 unsigned Cost = 0;
107 Record *Op = P->getOperator();
108 if (Op->isSubClassOf("Instruction")) {
109 Cost++;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000110 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 if (II.usesCustomDAGSchedInserter)
112 Cost += 10;
113 }
114 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000115 Cost += getResultPatternCost(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 return Cost;
117}
118
119/// getResultPatternCodeSize - Compute the code size of instructions for this
120/// pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000121static unsigned getResultPatternSize(TreePatternNode *P,
122 CodegenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 if (P->isLeaf()) return 0;
124
125 unsigned Cost = 0;
126 Record *Op = P->getOperator();
127 if (Op->isSubClassOf("Instruction")) {
128 Cost += Op->getValueAsInt("CodeSize");
129 }
130 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000131 Cost += getResultPatternSize(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 return Cost;
133}
134
135// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
136// In particular, we want to match maximal patterns first and lowest cost within
137// a particular complexity first.
138struct PatternSortingPredicate {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000139 PatternSortingPredicate(CodegenDAGPatterns &cgp) : CGP(cgp) {}
140 CodegenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141
Chris Lattner81915752008-01-05 22:30:17 +0000142 bool operator()(const PatternToMatch *LHS,
143 const PatternToMatch *RHS) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000144 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
145 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 LHSSize += LHS->getAddedComplexity();
147 RHSSize += RHS->getAddedComplexity();
148 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
149 if (LHSSize < RHSSize) return false;
150
151 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000152 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
153 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 if (LHSCost < RHSCost) return true;
155 if (LHSCost > RHSCost) return false;
156
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000157 return getResultPatternSize(LHS->getDstPattern(), CGP) <
158 getResultPatternSize(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 }
160};
161
162/// getRegisterValueType - Look up and return the first ValueType of specified
163/// RegisterClass record
164static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
165 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
166 return RC->getValueTypeNum(0);
167 return MVT::Other;
168}
169
170
171/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
172/// type information from it.
173static void RemoveAllTypes(TreePatternNode *N) {
174 N->removeTypes();
175 if (!N->isLeaf())
176 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
177 RemoveAllTypes(N->getChild(i));
178}
179
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180/// NodeHasProperty - return true if TreePatternNode has the specified
181/// property.
182static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000183 CodegenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 if (N->isLeaf()) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000185 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186 if (CP)
187 return CP->hasProperty(Property);
188 return false;
189 }
190 Record *Operator = N->getOperator();
191 if (!Operator->isSubClassOf("SDNode")) return false;
192
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000193 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194}
195
196static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000197 CodegenDAGPatterns &CGP) {
198 if (NodeHasProperty(N, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 return true;
200
201 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
202 TreePatternNode *Child = N->getChild(i);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000203 if (PatternHasProperty(Child, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 return true;
205 }
206
207 return false;
208}
209
210class PatternCodeEmitter {
211private:
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000212 CodegenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213
214 // Predicates.
215 ListInit *Predicates;
216 // Pattern cost.
217 unsigned Cost;
218 // Instruction selector pattern.
219 TreePatternNode *Pattern;
220 // Matched instruction.
221 TreePatternNode *Instruction;
222
223 // Node to name mapping
224 std::map<std::string, std::string> VariableMap;
225 // Node to operator mapping
226 std::map<std::string, Record*> OperatorMap;
227 // Names of all the folded nodes which produce chains.
228 std::vector<std::pair<std::string, unsigned> > FoldedChains;
229 // Original input chain(s).
230 std::vector<std::pair<std::string, std::string> > OrigChains;
231 std::set<std::string> Duplicates;
232
233 /// GeneratedCode - This is the buffer that we emit code to. The first int
234 /// indicates whether this is an exit predicate (something that should be
235 /// tested, and if true, the match fails) [when 1], or normal code to emit
236 /// [when 0], or initialization code to emit [when 2].
237 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
238 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
239 /// the set of patterns for each top-level opcode.
240 std::set<std::string> &GeneratedDecl;
241 /// TargetOpcodes - The target specific opcodes used by the resulting
242 /// instructions.
243 std::vector<std::string> &TargetOpcodes;
244 std::vector<std::string> &TargetVTs;
245
246 std::string ChainName;
247 unsigned TmpNo;
248 unsigned OpcNo;
249 unsigned VTNo;
250
251 void emitCheck(const std::string &S) {
252 if (!S.empty())
253 GeneratedCode.push_back(std::make_pair(1, S));
254 }
255 void emitCode(const std::string &S) {
256 if (!S.empty())
257 GeneratedCode.push_back(std::make_pair(0, S));
258 }
259 void emitInit(const std::string &S) {
260 if (!S.empty())
261 GeneratedCode.push_back(std::make_pair(2, S));
262 }
263 void emitDecl(const std::string &S) {
264 assert(!S.empty() && "Invalid declaration");
265 GeneratedDecl.insert(S);
266 }
267 void emitOpcode(const std::string &Opc) {
268 TargetOpcodes.push_back(Opc);
269 OpcNo++;
270 }
271 void emitVT(const std::string &VT) {
272 TargetVTs.push_back(VT);
273 VTNo++;
274 }
275public:
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000276 PatternCodeEmitter(CodegenDAGPatterns &cgp, ListInit *preds,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277 TreePatternNode *pattern, TreePatternNode *instr,
278 std::vector<std::pair<unsigned, std::string> > &gc,
279 std::set<std::string> &gd,
280 std::vector<std::string> &to,
281 std::vector<std::string> &tv)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000282 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 GeneratedCode(gc), GeneratedDecl(gd),
284 TargetOpcodes(to), TargetVTs(tv),
285 TmpNo(0), OpcNo(0), VTNo(0) {}
286
287 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
288 /// if the match fails. At this point, we already know that the opcode for N
289 /// matches, and the SDNode for the result has the RootName specified name.
290 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
291 const std::string &RootName, const std::string &ChainSuffix,
292 bool &FoundChain) {
293 bool isRoot = (P == NULL);
294 // Emit instruction predicates. Each predicate is just a string for now.
295 if (isRoot) {
296 std::string PredicateCheck;
297 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
298 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
299 Record *Def = Pred->getDef();
300 if (!Def->isSubClassOf("Predicate")) {
301#ifndef NDEBUG
302 Def->dump();
303#endif
304 assert(0 && "Unknown predicate type!");
305 }
306 if (!PredicateCheck.empty())
307 PredicateCheck += " && ";
308 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
309 }
310 }
311
312 emitCheck(PredicateCheck);
313 }
314
315 if (N->isLeaf()) {
316 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
317 emitCheck("cast<ConstantSDNode>(" + RootName +
318 ")->getSignExtended() == " + itostr(II->getValue()));
319 return;
320 } else if (!NodeIsComplexPattern(N)) {
321 assert(0 && "Cannot match this as a leaf value!");
322 abort();
323 }
324 }
325
326 // If this node has a name associated with it, capture it in VariableMap. If
327 // we already saw this in the pattern, emit code to verify dagness.
328 if (!N->getName().empty()) {
329 std::string &VarMapEntry = VariableMap[N->getName()];
330 if (VarMapEntry.empty()) {
331 VarMapEntry = RootName;
332 } else {
333 // If we get here, this is a second reference to a specific name. Since
334 // we already have checked that the first reference is valid, we don't
335 // have to recursively match it, just check that it's the same as the
336 // previously named thing.
337 emitCheck(VarMapEntry + " == " + RootName);
338 return;
339 }
340
341 if (!N->isLeaf())
342 OperatorMap[N->getName()] = N->getOperator();
343 }
344
345
346 // Emit code to load the child nodes and match their contents recursively.
347 unsigned OpNo = 0;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000348 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
349 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 bool EmittedUseCheck = false;
351 if (HasChain) {
352 if (NodeHasChain)
353 OpNo = 1;
354 if (!isRoot) {
355 // Multiple uses of actual result?
356 emitCheck(RootName + ".hasOneUse()");
357 EmittedUseCheck = true;
358 if (NodeHasChain) {
359 // If the immediate use can somehow reach this node through another
360 // path, then can't fold it either or it will create a cycle.
361 // e.g. In the following diagram, XX can reach ld through YY. If
362 // ld is folded into XX, then YY is both a predecessor and a successor
363 // of XX.
364 //
365 // [ld]
366 // ^ ^
367 // | |
368 // / \---
369 // / [YY]
370 // | ^
371 // [XX]-------|
372 bool NeedCheck = false;
373 if (P != Pattern)
374 NeedCheck = true;
375 else {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000376 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 NeedCheck =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000378 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
379 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
380 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 PInfo.getNumOperands() > 1 ||
382 PInfo.hasProperty(SDNPHasChain) ||
383 PInfo.hasProperty(SDNPInFlag) ||
384 PInfo.hasProperty(SDNPOptInFlag);
385 }
386
387 if (NeedCheck) {
388 std::string ParentName(RootName.begin(), RootName.end()-1);
389 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
390 ".Val, N.Val)");
391 }
392 }
393 }
394
395 if (NodeHasChain) {
396 if (FoundChain) {
397 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
398 "IsChainCompatible(" + ChainName + ".Val, " +
399 RootName + ".Val))");
400 OrigChains.push_back(std::make_pair(ChainName, RootName));
401 } else
402 FoundChain = true;
403 ChainName = "Chain" + ChainSuffix;
404 emitInit("SDOperand " + ChainName + " = " + RootName +
405 ".getOperand(0);");
406 }
407 }
408
409 // Don't fold any node which reads or writes a flag and has multiple uses.
410 // FIXME: We really need to separate the concepts of flag and "glue". Those
411 // real flag results, e.g. X86CMP output, can have multiple uses.
412 // FIXME: If the optional incoming flag does not exist. Then it is ok to
413 // fold it.
414 if (!isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000415 (PatternHasProperty(N, SDNPInFlag, CGP) ||
416 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
417 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 if (!EmittedUseCheck) {
419 // Multiple uses of actual result?
420 emitCheck(RootName + ".hasOneUse()");
421 }
422 }
423
424 // If there is a node predicate for this, emit the call.
425 if (!N->getPredicateFn().empty())
426 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
427
428
429 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
430 // a constant without a predicate fn that has more that one bit set, handle
431 // this as a special case. This is usually for targets that have special
432 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
433 // handling stuff). Using these instructions is often far more efficient
434 // than materializing the constant. Unfortunately, both the instcombiner
435 // and the dag combiner can often infer that bits are dead, and thus drop
436 // them from the mask in the dag. For example, it might turn 'AND X, 255'
437 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
438 // to handle this.
439 if (!N->isLeaf() &&
440 (N->getOperator()->getName() == "and" ||
441 N->getOperator()->getName() == "or") &&
442 N->getChild(1)->isLeaf() &&
443 N->getChild(1)->getPredicateFn().empty()) {
444 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
445 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
446 emitInit("SDOperand " + RootName + "0" + " = " +
447 RootName + ".getOperand(" + utostr(0) + ");");
448 emitInit("SDOperand " + RootName + "1" + " = " +
449 RootName + ".getOperand(" + utostr(1) + ");");
450
451 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
452 const char *MaskPredicate = N->getOperator()->getName() == "or"
453 ? "CheckOrMask(" : "CheckAndMask(";
454 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
455 RootName + "1), " + itostr(II->getValue()) + ")");
456
457 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
458 ChainSuffix + utostr(0), FoundChain);
459 return;
460 }
461 }
462 }
463
464 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
465 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
466 RootName + ".getOperand(" +utostr(OpNo) + ");");
467
468 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
469 ChainSuffix + utostr(OpNo), FoundChain);
470 }
471
472 // Handle cases when root is a complex pattern.
473 const ComplexPattern *CP;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000474 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 std::string Fn = CP->getSelectFunc();
476 unsigned NumOps = CP->getNumOperands();
477 for (unsigned i = 0; i < NumOps; ++i) {
478 emitDecl("CPTmp" + utostr(i));
479 emitCode("SDOperand CPTmp" + utostr(i) + ";");
480 }
481 if (CP->hasProperty(SDNPHasChain)) {
482 emitDecl("CPInChain");
483 emitDecl("Chain" + ChainSuffix);
484 emitCode("SDOperand CPInChain;");
485 emitCode("SDOperand Chain" + ChainSuffix + ";");
486 }
487
488 std::string Code = Fn + "(" + RootName + ", " + RootName;
489 for (unsigned i = 0; i < NumOps; i++)
490 Code += ", CPTmp" + utostr(i);
491 if (CP->hasProperty(SDNPHasChain)) {
492 ChainName = "Chain" + ChainSuffix;
493 Code += ", CPInChain, Chain" + ChainSuffix;
494 }
495 emitCheck(Code + ")");
496 }
497 }
498
499 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
500 const std::string &RootName,
501 const std::string &ChainSuffix, bool &FoundChain) {
502 if (!Child->isLeaf()) {
503 // If it's not a leaf, recursively match.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000504 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 emitCheck(RootName + ".getOpcode() == " +
506 CInfo.getEnumName());
507 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000508 if (NodeHasProperty(Child, SDNPHasChain, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
510 } else {
511 // If this child has a name associated with it, capture it in VarMap. If
512 // we already saw this in the pattern, emit code to verify dagness.
513 if (!Child->getName().empty()) {
514 std::string &VarMapEntry = VariableMap[Child->getName()];
515 if (VarMapEntry.empty()) {
516 VarMapEntry = RootName;
517 } else {
518 // If we get here, this is a second reference to a specific name.
519 // Since we already have checked that the first reference is valid,
520 // we don't have to recursively match it, just check that it's the
521 // same as the previously named thing.
522 emitCheck(VarMapEntry + " == " + RootName);
523 Duplicates.insert(RootName);
524 return;
525 }
526 }
527
528 // Handle leaves of various types.
529 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
530 Record *LeafRec = DI->getDef();
531 if (LeafRec->isSubClassOf("RegisterClass") ||
532 LeafRec->getName() == "ptr_rc") {
533 // Handle register references. Nothing to do here.
534 } else if (LeafRec->isSubClassOf("Register")) {
535 // Handle register references.
536 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
537 // Handle complex pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000538 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 std::string Fn = CP->getSelectFunc();
540 unsigned NumOps = CP->getNumOperands();
541 for (unsigned i = 0; i < NumOps; ++i) {
542 emitDecl("CPTmp" + utostr(i));
543 emitCode("SDOperand CPTmp" + utostr(i) + ";");
544 }
545 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000546 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 FoldedChains.push_back(std::make_pair("CPInChain",
548 PInfo.getNumResults()));
549 ChainName = "Chain" + ChainSuffix;
550 emitDecl("CPInChain");
551 emitDecl(ChainName);
552 emitCode("SDOperand CPInChain;");
553 emitCode("SDOperand " + ChainName + ";");
554 }
555
556 std::string Code = Fn + "(N, ";
557 if (CP->hasProperty(SDNPHasChain)) {
558 std::string ParentName(RootName.begin(), RootName.end()-1);
559 Code += ParentName + ", ";
560 }
561 Code += RootName;
562 for (unsigned i = 0; i < NumOps; i++)
563 Code += ", CPTmp" + utostr(i);
564 if (CP->hasProperty(SDNPHasChain))
565 Code += ", CPInChain, Chain" + ChainSuffix;
566 emitCheck(Code + ")");
567 } else if (LeafRec->getName() == "srcvalue") {
568 // Place holder for SRCVALUE nodes. Nothing to do here.
569 } else if (LeafRec->isSubClassOf("ValueType")) {
570 // Make sure this is the specified value type.
571 emitCheck("cast<VTSDNode>(" + RootName +
572 ")->getVT() == MVT::" + LeafRec->getName());
573 } else if (LeafRec->isSubClassOf("CondCode")) {
574 // Make sure this is the specified cond code.
575 emitCheck("cast<CondCodeSDNode>(" + RootName +
576 ")->get() == ISD::" + LeafRec->getName());
577 } else {
578#ifndef NDEBUG
579 Child->dump();
580 cerr << " ";
581#endif
582 assert(0 && "Unknown leaf type!");
583 }
584
585 // If there is a node predicate for this, emit the call.
586 if (!Child->getPredicateFn().empty())
587 emitCheck(Child->getPredicateFn() + "(" + RootName +
588 ".Val)");
589 } else if (IntInit *II =
590 dynamic_cast<IntInit*>(Child->getLeafValue())) {
591 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
592 unsigned CTmp = TmpNo++;
593 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
594 RootName + ")->getSignExtended();");
595
596 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
597 } else {
598#ifndef NDEBUG
599 Child->dump();
600#endif
601 assert(0 && "Unknown leaf type!");
602 }
603 }
604 }
605
606 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
607 /// we actually have to build a DAG!
608 std::vector<std::string>
Evan Cheng775baac2007-09-12 23:30:14 +0000609 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610 bool InFlagDecled, bool ResNodeDecled,
611 bool LikeLeaf = false, bool isRoot = false) {
612 // List of arguments of getTargetNode() or SelectNodeTo().
613 std::vector<std::string> NodeOps;
614 // This is something selected from the pattern we matched.
615 if (!N->getName().empty()) {
616 std::string &Val = VariableMap[N->getName()];
617 assert(!Val.empty() &&
618 "Variable referenced but not defined and not caught earlier!");
619 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
620 // Already selected this operand, just return the tmpval.
621 NodeOps.push_back(Val);
622 return NodeOps;
623 }
624
625 const ComplexPattern *CP;
626 unsigned ResNo = TmpNo++;
627 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
628 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
629 std::string CastType;
630 switch (N->getTypeNum(0)) {
631 default:
632 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
633 << " type as an immediate constant. Aborting\n";
634 abort();
635 case MVT::i1: CastType = "bool"; break;
636 case MVT::i8: CastType = "unsigned char"; break;
637 case MVT::i16: CastType = "unsigned short"; break;
638 case MVT::i32: CastType = "unsigned"; break;
639 case MVT::i64: CastType = "uint64_t"; break;
640 }
641 emitCode("SDOperand Tmp" + utostr(ResNo) +
642 " = CurDAG->getTargetConstant(((" + CastType +
643 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
644 getEnumName(N->getTypeNum(0)) + ");");
645 NodeOps.push_back("Tmp" + utostr(ResNo));
646 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
647 // value if used multiple times by this pattern result.
648 Val = "Tmp"+utostr(ResNo);
649 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
650 Record *Op = OperatorMap[N->getName()];
651 // Transform ExternalSymbol to TargetExternalSymbol
652 if (Op && Op->getName() == "externalsym") {
653 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
654 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
655 Val + ")->getSymbol(), " +
656 getEnumName(N->getTypeNum(0)) + ");");
657 NodeOps.push_back("Tmp" + utostr(ResNo));
658 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
659 // this value if used multiple times by this pattern result.
660 Val = "Tmp"+utostr(ResNo);
661 } else {
662 NodeOps.push_back(Val);
663 }
664 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
665 || N->getOperator()->getName() == "tglobaltlsaddr")) {
666 Record *Op = OperatorMap[N->getName()];
667 // Transform GlobalAddress to TargetGlobalAddress
668 if (Op && (Op->getName() == "globaladdr" ||
669 Op->getName() == "globaltlsaddr")) {
670 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
671 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
672 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
673 ");");
674 NodeOps.push_back("Tmp" + utostr(ResNo));
675 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
676 // this value if used multiple times by this pattern result.
677 Val = "Tmp"+utostr(ResNo);
678 } else {
679 NodeOps.push_back(Val);
680 }
681 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
682 NodeOps.push_back(Val);
683 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
684 // value if used multiple times by this pattern result.
685 Val = "Tmp"+utostr(ResNo);
686 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
687 NodeOps.push_back(Val);
688 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
689 // value if used multiple times by this pattern result.
690 Val = "Tmp"+utostr(ResNo);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000691 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
693 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
694 NodeOps.push_back("CPTmp" + utostr(i));
695 }
696 } else {
697 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
698 // node even if it isn't one. Don't select it.
699 if (!LikeLeaf) {
700 emitCode("AddToISelQueue(" + Val + ");");
701 if (isRoot && N->isLeaf()) {
702 emitCode("ReplaceUses(N, " + Val + ");");
703 emitCode("return NULL;");
704 }
705 }
706 NodeOps.push_back(Val);
707 }
708 return NodeOps;
709 }
710 if (N->isLeaf()) {
711 // If this is an explicit register reference, handle it.
712 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
713 unsigned ResNo = TmpNo++;
714 if (DI->getDef()->isSubClassOf("Register")) {
715 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000716 getQualifiedName(DI->getDef()) + ", " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 getEnumName(N->getTypeNum(0)) + ");");
718 NodeOps.push_back("Tmp" + utostr(ResNo));
719 return NodeOps;
720 } else if (DI->getDef()->getName() == "zero_reg") {
721 emitCode("SDOperand Tmp" + utostr(ResNo) +
722 " = CurDAG->getRegister(0, " +
723 getEnumName(N->getTypeNum(0)) + ");");
724 NodeOps.push_back("Tmp" + utostr(ResNo));
725 return NodeOps;
726 }
727 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
728 unsigned ResNo = TmpNo++;
729 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
730 emitCode("SDOperand Tmp" + utostr(ResNo) +
731 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
732 ", " + getEnumName(N->getTypeNum(0)) + ");");
733 NodeOps.push_back("Tmp" + utostr(ResNo));
734 return NodeOps;
735 }
736
737#ifndef NDEBUG
738 N->dump();
739#endif
740 assert(0 && "Unknown leaf type!");
741 return NodeOps;
742 }
743
744 Record *Op = N->getOperator();
745 if (Op->isSubClassOf("Instruction")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000746 const CodeGenTarget &CGT = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000748 const DAGInstruction &Inst = CGP.getInstruction(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 TreePattern *InstPat = Inst.getPattern();
Evan Chengf031fcb2007-09-25 01:48:59 +0000750 // FIXME: Assume actual pattern comes before "implicit".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 TreePatternNode *InstPatNode =
Evan Cheng775baac2007-09-12 23:30:14 +0000752 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
753 : (InstPat ? InstPat->getTree(0) : NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengf37df842007-09-11 19:52:18 +0000755 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 }
757 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng775baac2007-09-12 23:30:14 +0000758 // FIXME: fix how we deal with physical register operands.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng775baac2007-09-12 23:30:14 +0000760 bool HasImpResults = isRoot && DstRegs.size() > 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 bool NodeHasOptInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000762 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 bool NodeHasInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000764 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengdec1dd12007-09-07 23:59:02 +0000765 bool NodeHasOutFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000766 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 bool NodeHasChain = InstPatNode &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000768 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 bool InputHasChain = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000770 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 unsigned NumResults = Inst.getNumResults();
Evan Cheng775baac2007-09-12 23:30:14 +0000772 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773
774 if (NodeHasOptInFlag) {
775 emitCode("bool HasInFlag = "
776 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
777 }
778 if (HasVarOps)
779 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
780
781 // How many results is this pattern expected to produce?
Evan Cheng775baac2007-09-12 23:30:14 +0000782 unsigned NumPatResults = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
784 MVT::ValueType VT = Pattern->getTypeNum(i);
785 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng775baac2007-09-12 23:30:14 +0000786 NumPatResults++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 }
788
789 if (OrigChains.size() > 0) {
790 // The original input chain is being ignored. If it is not just
791 // pointing to the op that's being folded, we should create a
792 // TokenFactor with it and the chain of the folded op as the new chain.
793 // We could potentially be doing multiple levels of folding, in that
794 // case, the TokenFactor can have more operands.
795 emitCode("SmallVector<SDOperand, 8> InChains;");
796 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
797 emitCode("if (" + OrigChains[i].first + ".Val != " +
798 OrigChains[i].second + ".Val) {");
799 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
800 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
801 emitCode("}");
802 }
803 emitCode("AddToISelQueue(" + ChainName + ");");
804 emitCode("InChains.push_back(" + ChainName + ");");
805 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
806 "&InChains[0], InChains.size());");
807 }
808
809 // Loop over all of the operands of the instruction pattern, emitting code
810 // to fill them all in. The node 'N' usually has number children equal to
811 // the number of input operands of the instruction. However, in cases
812 // where there are predicate operands for an instruction, we need to fill
813 // in the 'execute always' values. Match up the node operands to the
814 // instruction operands to do this.
815 std::vector<std::string> AllOps;
816 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
817 for (unsigned ChildNo = 0, InstOpNo = NumResults;
818 InstOpNo != II.OperandList.size(); ++InstOpNo) {
819 std::vector<std::string> Ops;
820
821 // If this is a normal operand or a predicate operand without
822 // 'execute always', emit it.
823 Record *OperandNode = II.OperandList[InstOpNo].Rec;
824 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
825 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000826 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Evan Chengdb1f2462007-09-17 22:26:41 +0000827 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 InFlagDecled, ResNodeDecled);
829 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
830 ++ChildNo;
831 } else {
832 // Otherwise, this is a predicate or optional def operand, emit the
833 // 'default ops' operands.
834 const DAGDefaultOperand &DefaultOp =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000835 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Chengdb1f2462007-09-17 22:26:41 +0000837 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 InFlagDecled, ResNodeDecled);
839 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
840 NumEAInputs += Ops.size();
841 }
842 }
843 }
844
845 // Emit all the chain and CopyToReg stuff.
846 bool ChainEmitted = NodeHasChain;
847 if (NodeHasChain)
848 emitCode("AddToISelQueue(" + ChainName + ");");
849 if (NodeHasInFlag || HasImpInputs)
850 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
851 InFlagDecled, ResNodeDecled, true);
852 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
853 if (!InFlagDecled) {
854 emitCode("SDOperand InFlag(0, 0);");
855 InFlagDecled = true;
856 }
857 if (NodeHasOptInFlag) {
858 emitCode("if (HasInFlag) {");
859 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
860 emitCode(" AddToISelQueue(InFlag);");
861 emitCode("}");
862 }
863 }
864
865 unsigned ResNo = TmpNo++;
866 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
Evan Chengdec1dd12007-09-07 23:59:02 +0000867 NodeHasOptInFlag || HasImpResults) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 std::string Code;
869 std::string Code2;
870 std::string NodeName;
871 if (!isRoot) {
872 NodeName = "Tmp" + utostr(ResNo);
Dan Gohman875770e2007-07-24 22:58:00 +0000873 Code2 = "SDOperand " + NodeName + "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874 } else {
875 NodeName = "ResNode";
876 if (!ResNodeDecled) {
877 Code2 = "SDNode *" + NodeName + " = ";
878 ResNodeDecled = true;
879 } else
880 Code2 = NodeName + " = ";
881 }
882
Evan Cheng775baac2007-09-12 23:30:14 +0000883 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 unsigned OpsNo = OpcNo;
885 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
886
887 // Output order: results, chain, flags
888 // Result types.
889 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
890 Code += ", VT" + utostr(VTNo);
891 emitVT(getEnumName(N->getTypeNum(0)));
892 }
Evan Chengdec1dd12007-09-07 23:59:02 +0000893 // Add types for implicit results in physical registers, scheduler will
894 // care of adding copyfromreg nodes.
Evan Cheng775baac2007-09-12 23:30:14 +0000895 for (unsigned i = 0; i < NumDstRegs; i++) {
896 Record *RR = DstRegs[i];
897 if (RR->isSubClassOf("Register")) {
898 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
899 Code += ", " + getEnumName(RVT);
Evan Chengdec1dd12007-09-07 23:59:02 +0000900 }
901 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 if (NodeHasChain)
903 Code += ", MVT::Other";
904 if (NodeHasOutFlag)
905 Code += ", MVT::Flag";
906
907 // Figure out how many fixed inputs the node has. This is important to
908 // know which inputs are the variable ones if present.
909 unsigned NumInputs = AllOps.size();
910 NumInputs += NodeHasChain;
911
912 // Inputs.
913 if (HasVarOps) {
914 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
915 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
916 AllOps.clear();
917 }
918
919 if (HasVarOps) {
920 // Figure out whether any operands at the end of the op list are not
921 // part of the variable section.
922 std::string EndAdjust;
923 if (NodeHasInFlag || HasImpInputs)
924 EndAdjust = "-1"; // Always has one flag.
925 else if (NodeHasOptInFlag)
926 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
927
928 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
929 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
930
931 emitCode(" AddToISelQueue(N.getOperand(i));");
932 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
933 emitCode("}");
934 }
935
936 if (NodeHasChain) {
937 if (HasVarOps)
938 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
939 else
940 AllOps.push_back(ChainName);
941 }
942
943 if (HasVarOps) {
944 if (NodeHasInFlag || HasImpInputs)
945 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
946 else if (NodeHasOptInFlag) {
947 emitCode("if (HasInFlag)");
948 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
949 }
950 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
951 ".size()";
952 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng775baac2007-09-12 23:30:14 +0000953 AllOps.push_back("InFlag");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954
955 unsigned NumOps = AllOps.size();
956 if (NumOps) {
957 if (!NodeHasOptInFlag && NumOps < 4) {
958 for (unsigned i = 0; i != NumOps; ++i)
959 Code += ", " + AllOps[i];
960 } else {
961 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
962 for (unsigned i = 0; i != NumOps; ++i) {
963 OpsCode += AllOps[i];
964 if (i != NumOps-1)
965 OpsCode += ", ";
966 }
967 emitCode(OpsCode + " };");
968 Code += ", Ops" + utostr(OpsNo) + ", ";
969 if (NodeHasOptInFlag) {
970 Code += "HasInFlag ? ";
971 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
972 } else
973 Code += utostr(NumOps);
974 }
975 }
976
977 if (!isRoot)
978 Code += "), 0";
979 emitCode(Code2 + Code + ");");
980
981 if (NodeHasChain)
982 // Remember which op produces the chain.
983 if (!isRoot)
984 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng775baac2007-09-12 23:30:14 +0000985 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 else
987 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng775baac2007-09-12 23:30:14 +0000988 ", " + utostr(NumResults+NumDstRegs) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989
990 if (!isRoot) {
991 NodeOps.push_back("Tmp" + utostr(ResNo));
992 return NodeOps;
993 }
994
995 bool NeedReplace = false;
996 if (NodeHasOutFlag) {
997 if (!InFlagDecled) {
Dan Gohman875770e2007-07-24 22:58:00 +0000998 emitCode("SDOperand InFlag(ResNode, " +
Evan Chengdb1f2462007-09-17 22:26:41 +0000999 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 InFlagDecled = true;
1001 } else
1002 emitCode("InFlag = SDOperand(ResNode, " +
Evan Chengdb1f2462007-09-17 22:26:41 +00001003 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004 }
1005
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 if (FoldedChains.size() > 0) {
1007 std::string Code;
1008 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1009 emitCode("ReplaceUses(SDOperand(" +
1010 FoldedChains[j].first + ".Val, " +
1011 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
Evan Cheng775baac2007-09-12 23:30:14 +00001012 utostr(NumResults+NumDstRegs) + "));");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 NeedReplace = true;
1014 }
1015
1016 if (NodeHasOutFlag) {
1017 emitCode("ReplaceUses(SDOperand(N.Val, " +
Evan Chengdb1f2462007-09-17 22:26:41 +00001018 utostr(NumPatResults + (unsigned)InputHasChain)
1019 +"), InFlag);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 NeedReplace = true;
1021 }
1022
Evan Chengdb1f2462007-09-17 22:26:41 +00001023 if (NeedReplace && InputHasChain)
1024 emitCode("ReplaceUses(SDOperand(N.Val, " +
1025 utostr(NumPatResults) + "), SDOperand(" + ChainName
1026 + ".Val, " + ChainName + ".ResNo" + "));");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027
1028 // User does not expect the instruction would produce a chain!
1029 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1030 ;
1031 } else if (InputHasChain && !NodeHasChain) {
1032 // One of the inner node produces a chain.
1033 if (NodeHasOutFlag)
Evan Cheng775baac2007-09-12 23:30:14 +00001034 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng775baac2007-09-12 23:30:14 +00001036 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 "), " + ChainName + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 }
1039
Evan Chengdb1f2462007-09-17 22:26:41 +00001040 emitCode("return ResNode;");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 } else {
1042 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1043 utostr(OpcNo);
1044 if (N->getTypeNum(0) != MVT::isVoid)
1045 Code += ", VT" + utostr(VTNo);
1046 if (NodeHasOutFlag)
1047 Code += ", MVT::Flag";
1048
1049 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1050 AllOps.push_back("InFlag");
1051
1052 unsigned NumOps = AllOps.size();
1053 if (NumOps) {
1054 if (!NodeHasOptInFlag && NumOps < 4) {
1055 for (unsigned i = 0; i != NumOps; ++i)
1056 Code += ", " + AllOps[i];
1057 } else {
1058 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1059 for (unsigned i = 0; i != NumOps; ++i) {
1060 OpsCode += AllOps[i];
1061 if (i != NumOps-1)
1062 OpsCode += ", ";
1063 }
1064 emitCode(OpsCode + " };");
1065 Code += ", Ops" + utostr(OpcNo) + ", ";
1066 Code += utostr(NumOps);
1067 }
1068 }
1069 emitCode(Code + ");");
1070 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1071 if (N->getTypeNum(0) != MVT::isVoid)
1072 emitVT(getEnumName(N->getTypeNum(0)));
1073 }
1074
1075 return NodeOps;
1076 } else if (Op->isSubClassOf("SDNodeXForm")) {
1077 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1078 // PatLeaf node - the operand may or may not be a leaf node. But it should
1079 // behave like one.
1080 std::vector<std::string> Ops =
Evan Chengdb1f2462007-09-17 22:26:41 +00001081 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 ResNodeDecled, true);
1083 unsigned ResNo = TmpNo++;
1084 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1085 + "(" + Ops.back() + ".Val);");
1086 NodeOps.push_back("Tmp" + utostr(ResNo));
1087 if (isRoot)
1088 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1089 return NodeOps;
1090 } else {
1091 N->dump();
1092 cerr << "\n";
1093 throw std::string("Unknown node in result pattern!");
1094 }
1095 }
1096
1097 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1098 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1099 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1100 /// for, this returns true otherwise false if Pat has all types.
1101 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1102 const std::string &Prefix, bool isRoot = false) {
1103 // Did we find one?
1104 if (Pat->getExtTypes() != Other->getExtTypes()) {
1105 // Move a type over from 'other' to 'pat'.
1106 Pat->setTypes(Other->getExtTypes());
1107 // The top level node type is checked outside of the select function.
1108 if (!isRoot)
1109 emitCheck(Prefix + ".Val->getValueType(0) == " +
1110 getName(Pat->getTypeNum(0)));
1111 return true;
1112 }
1113
1114 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001115 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1117 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1118 Prefix + utostr(OpNo)))
1119 return true;
1120 return false;
1121 }
1122
1123private:
1124 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1125 /// being built.
1126 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1127 bool &ChainEmitted, bool &InFlagDecled,
1128 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001129 const CodeGenTarget &T = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001131 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1132 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1134 TreePatternNode *Child = N->getChild(i);
1135 if (!Child->isLeaf()) {
1136 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1137 InFlagDecled, ResNodeDecled);
1138 } else {
1139 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1140 if (!Child->getName().empty()) {
1141 std::string Name = RootName + utostr(OpNo);
1142 if (Duplicates.find(Name) != Duplicates.end())
1143 // A duplicate! Do not emit a copy for this node.
1144 continue;
1145 }
1146
1147 Record *RR = DI->getDef();
1148 if (RR->isSubClassOf("Register")) {
1149 MVT::ValueType RVT = getRegisterValueType(RR, T);
1150 if (RVT == MVT::Flag) {
1151 if (!InFlagDecled) {
1152 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1153 InFlagDecled = true;
1154 } else
1155 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1156 emitCode("AddToISelQueue(InFlag);");
1157 } else {
1158 if (!ChainEmitted) {
1159 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1160 ChainName = "Chain";
1161 ChainEmitted = true;
1162 }
1163 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1164 if (!InFlagDecled) {
1165 emitCode("SDOperand InFlag(0, 0);");
1166 InFlagDecled = true;
1167 }
1168 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1169 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001170 ", " + getQualifiedName(RR) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1172 ResNodeDecled = true;
1173 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1174 emitCode("InFlag = SDOperand(ResNode, 1);");
1175 }
1176 }
1177 }
1178 }
1179 }
1180
1181 if (HasInFlag) {
1182 if (!InFlagDecled) {
1183 emitCode("SDOperand InFlag = " + RootName +
1184 ".getOperand(" + utostr(OpNo) + ");");
1185 InFlagDecled = true;
1186 } else
1187 emitCode("InFlag = " + RootName +
1188 ".getOperand(" + utostr(OpNo) + ");");
1189 emitCode("AddToISelQueue(InFlag);");
1190 }
1191 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192};
1193
1194/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1195/// stream to match the pattern, and generate the code for the match if it
1196/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner81915752008-01-05 22:30:17 +00001197void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1199 std::set<std::string> &GeneratedDecl,
1200 std::vector<std::string> &TargetOpcodes,
1201 std::vector<std::string> &TargetVTs) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001202 PatternCodeEmitter Emitter(*CGP, Pattern.getPredicates(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1204 GeneratedCode, GeneratedDecl,
1205 TargetOpcodes, TargetVTs);
1206
1207 // Emit the matcher, capturing named arguments in VariableMap.
1208 bool FoundChain = false;
1209 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1210
1211 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001212 TreePattern &TP = *CGP->pf_begin()->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213
1214 // At this point, we know that we structurally match the pattern, but the
1215 // types of the nodes may not match. Figure out the fewest number of type
1216 // comparisons we need to emit. For example, if there is only one integer
1217 // type supported by a target, there should be no type comparisons at all for
1218 // integer patterns!
1219 //
1220 // To figure out the fewest number of type checks needed, clone the pattern,
1221 // remove the types, then perform type inference on the pattern as a whole.
1222 // If there are unresolved types, emit an explicit check for those types,
1223 // apply the type to the tree, then rerun type inference. Iterate until all
1224 // types are resolved.
1225 //
1226 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1227 RemoveAllTypes(Pat);
1228
1229 do {
1230 // Resolve/propagate as many types as possible.
1231 try {
1232 bool MadeChange = true;
1233 while (MadeChange)
1234 MadeChange = Pat->ApplyTypeConstraints(TP,
1235 true/*Ignore reg constraints*/);
1236 } catch (...) {
1237 assert(0 && "Error: could not find consistent types for something we"
1238 " already decided was ok!");
1239 abort();
1240 }
1241
1242 // Insert a check for an unresolved type and add it to the tree. If we find
1243 // an unresolved type to add a check for, this returns true and we iterate,
1244 // otherwise we are done.
1245 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1246
Evan Cheng775baac2007-09-12 23:30:14 +00001247 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Chengdb1f2462007-09-17 22:26:41 +00001248 false, false, false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 delete Pat;
1250}
1251
1252/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1253/// a line causes any of them to be empty, remove them and return true when
1254/// done.
Chris Lattner81915752008-01-05 22:30:17 +00001255static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 std::vector<std::pair<unsigned, std::string> > > >
1257 &Patterns) {
1258 bool ErasedPatterns = false;
1259 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1260 Patterns[i].second.pop_back();
1261 if (Patterns[i].second.empty()) {
1262 Patterns.erase(Patterns.begin()+i);
1263 --i; --e;
1264 ErasedPatterns = true;
1265 }
1266 }
1267 return ErasedPatterns;
1268}
1269
1270/// EmitPatterns - Emit code for at least one pattern, but try to group common
1271/// code together between the patterns.
Chris Lattner81915752008-01-05 22:30:17 +00001272void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 std::vector<std::pair<unsigned, std::string> > > >
1274 &Patterns, unsigned Indent,
1275 std::ostream &OS) {
1276 typedef std::pair<unsigned, std::string> CodeLine;
1277 typedef std::vector<CodeLine> CodeList;
Chris Lattner81915752008-01-05 22:30:17 +00001278 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279
1280 if (Patterns.empty()) return;
1281
1282 // Figure out how many patterns share the next code line. Explicitly copy
1283 // FirstCodeLine so that we don't invalidate a reference when changing
1284 // Patterns.
1285 const CodeLine FirstCodeLine = Patterns.back().second.back();
1286 unsigned LastMatch = Patterns.size()-1;
1287 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1288 --LastMatch;
1289
1290 // If not all patterns share this line, split the list into two pieces. The
1291 // first chunk will use this line, the second chunk won't.
1292 if (LastMatch != 0) {
1293 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1294 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1295
1296 // FIXME: Emit braces?
1297 if (Shared.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001298 const PatternToMatch &Pattern = *Shared.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1300 Pattern.getSrcPattern()->print(OS);
1301 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1302 Pattern.getDstPattern()->print(OS);
1303 OS << "\n";
1304 unsigned AddedComplexity = Pattern.getAddedComplexity();
1305 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001306 << getPatternSize(Pattern.getSrcPattern(), *CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 << " cost = "
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001308 << getResultPatternCost(Pattern.getDstPattern(), *CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309 << " size = "
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001310 << getResultPatternSize(Pattern.getDstPattern(), *CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 }
1312 if (FirstCodeLine.first != 1) {
1313 OS << std::string(Indent, ' ') << "{\n";
1314 Indent += 2;
1315 }
1316 EmitPatterns(Shared, Indent, OS);
1317 if (FirstCodeLine.first != 1) {
1318 Indent -= 2;
1319 OS << std::string(Indent, ' ') << "}\n";
1320 }
1321
1322 if (Other.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001323 const PatternToMatch &Pattern = *Other.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1325 Pattern.getSrcPattern()->print(OS);
1326 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1327 Pattern.getDstPattern()->print(OS);
1328 OS << "\n";
1329 unsigned AddedComplexity = Pattern.getAddedComplexity();
1330 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001331 << getPatternSize(Pattern.getSrcPattern(), *CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 << " cost = "
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001333 << getResultPatternCost(Pattern.getDstPattern(), *CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 << " size = "
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001335 << getResultPatternSize(Pattern.getDstPattern(), *CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 }
1337 EmitPatterns(Other, Indent, OS);
1338 return;
1339 }
1340
1341 // Remove this code from all of the patterns that share it.
1342 bool ErasedPatterns = EraseCodeLine(Patterns);
1343
1344 bool isPredicate = FirstCodeLine.first == 1;
1345
1346 // Otherwise, every pattern in the list has this line. Emit it.
1347 if (!isPredicate) {
1348 // Normal code.
1349 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1350 } else {
1351 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1352
1353 // If the next code line is another predicate, and if all of the pattern
1354 // in this group share the same next line, emit it inline now. Do this
1355 // until we run out of common predicates.
1356 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1357 // Check that all of fhe patterns in Patterns end with the same predicate.
1358 bool AllEndWithSamePredicate = true;
1359 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1360 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1361 AllEndWithSamePredicate = false;
1362 break;
1363 }
1364 // If all of the predicates aren't the same, we can't share them.
1365 if (!AllEndWithSamePredicate) break;
1366
1367 // Otherwise we can. Emit it shared now.
1368 OS << " &&\n" << std::string(Indent+4, ' ')
1369 << Patterns.back().second.back().second;
1370 ErasedPatterns = EraseCodeLine(Patterns);
1371 }
1372
1373 OS << ") {\n";
1374 Indent += 2;
1375 }
1376
1377 EmitPatterns(Patterns, Indent, OS);
1378
1379 if (isPredicate)
1380 OS << std::string(Indent-2, ' ') << "}\n";
1381}
1382
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001383static std::string getOpcodeName(Record *Op, CodegenDAGPatterns &CGP) {
1384 return CGP.getSDNodeInfo(Op).getEnumName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385}
1386
1387static std::string getLegalCName(std::string OpName) {
1388 std::string::size_type pos = OpName.find("::");
1389 if (pos != std::string::npos)
1390 OpName.replace(pos, 2, "_");
1391 return OpName;
1392}
1393
1394void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001395 const CodeGenTarget &Target = CGP->getTargetInfo();
1396
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 // Get the namespace to insert instructions into. Make sure not to pick up
1398 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1399 // instruction or something.
1400 std::string InstNS;
1401 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1402 e = Target.inst_end(); i != e; ++i) {
1403 InstNS = i->second.Namespace;
1404 if (InstNS != "TargetInstrInfo")
1405 break;
1406 }
1407
1408 if (!InstNS.empty()) InstNS += "::";
1409
1410 // Group the patterns by their top-level opcodes.
Chris Lattner81915752008-01-05 22:30:17 +00001411 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 // All unique target node emission functions.
1413 std::map<std::string, unsigned> EmitFunctions;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001414 for (CodegenDAGPatterns::ptm_iterator I = CGP->ptm_begin(),
1415 E = CGP->ptm_end(); I != E; ++I) {
Chris Lattner81915752008-01-05 22:30:17 +00001416 const PatternToMatch &Pattern = *I;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001417
1418 TreePatternNode *Node = Pattern.getSrcPattern();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 if (!Node->isLeaf()) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001420 PatternsByOpcode[getOpcodeName(Node->getOperator(), *CGP)].
1421 push_back(&Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 } else {
1423 const ComplexPattern *CP;
1424 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001425 PatternsByOpcode[getOpcodeName(CGP->getSDNodeNamed("imm"), *CGP)].
1426 push_back(&Pattern);
1427 } else if ((CP = NodeGetComplexPattern(Node, *CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428 std::vector<Record*> OpNodes = CP->getRootNodes();
1429 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001430 PatternsByOpcode[getOpcodeName(OpNodes[j], *CGP)]
1431 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *CGP)].begin(),
1432 &Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 }
1434 } else {
1435 cerr << "Unrecognized opcode '";
1436 Node->dump();
1437 cerr << "' on tree pattern '";
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001438 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 exit(1);
1440 }
1441 }
1442 }
1443
1444 // For each opcode, there might be multiple select functions, one per
1445 // ValueType of the node (or its first operand if it doesn't produce a
1446 // non-chain result.
1447 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1448
1449 // Emit one Select_* method for each top-level opcode. We do this instead of
1450 // emitting one giant switch statement to support compilers where this will
1451 // result in the recursive functions taking less stack space.
Chris Lattner81915752008-01-05 22:30:17 +00001452 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1454 PBOI != E; ++PBOI) {
1455 const std::string &OpName = PBOI->first;
Chris Lattner81915752008-01-05 22:30:17 +00001456 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1458
1459 // We want to emit all of the matching code now. However, we want to emit
1460 // the matches in order of minimal cost. Sort the patterns so the least
1461 // cost one is at the start.
1462 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001463 PatternSortingPredicate(*CGP));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464
1465 // Split them into groups by type.
Chris Lattner81915752008-01-05 22:30:17 +00001466 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner81915752008-01-05 22:30:17 +00001468 const PatternToMatch *Pat = PatternsOfOp[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 TreePatternNode *SrcPat = Pat->getSrcPattern();
1470 MVT::ValueType VT = SrcPat->getTypeNum(0);
Chris Lattner81915752008-01-05 22:30:17 +00001471 std::map<MVT::ValueType,
1472 std::vector<const PatternToMatch*> >::iterator TI =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473 PatternsByType.find(VT);
1474 if (TI != PatternsByType.end())
1475 TI->second.push_back(Pat);
1476 else {
Chris Lattner81915752008-01-05 22:30:17 +00001477 std::vector<const PatternToMatch*> PVec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001478 PVec.push_back(Pat);
1479 PatternsByType.insert(std::make_pair(VT, PVec));
1480 }
1481 }
1482
Chris Lattner81915752008-01-05 22:30:17 +00001483 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1485 ++II) {
1486 MVT::ValueType OpVT = II->first;
Chris Lattner81915752008-01-05 22:30:17 +00001487 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1489 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1490
Chris Lattner81915752008-01-05 22:30:17 +00001491 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 std::vector<std::vector<std::string> > PatternOpcodes;
1493 std::vector<std::vector<std::string> > PatternVTs;
1494 std::vector<std::set<std::string> > PatternDecls;
1495 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1496 CodeList GeneratedCode;
1497 std::set<std::string> GeneratedDecl;
1498 std::vector<std::string> TargetOpcodes;
1499 std::vector<std::string> TargetVTs;
1500 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1501 TargetOpcodes, TargetVTs);
1502 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1503 PatternDecls.push_back(GeneratedDecl);
1504 PatternOpcodes.push_back(TargetOpcodes);
1505 PatternVTs.push_back(TargetVTs);
1506 }
1507
1508 // Scan the code to see if all of the patterns are reachable and if it is
1509 // possible that the last one might not match.
1510 bool mightNotMatch = true;
1511 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1512 CodeList &GeneratedCode = CodeForPatterns[i].second;
1513 mightNotMatch = false;
1514
1515 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1516 if (GeneratedCode[j].first == 1) { // predicate.
1517 mightNotMatch = true;
1518 break;
1519 }
1520 }
1521
1522 // If this pattern definitely matches, and if it isn't the last one, the
1523 // patterns after it CANNOT ever match. Error out.
1524 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1525 cerr << "Pattern '";
1526 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1527 cerr << "' is impossible to select!\n";
1528 exit(1);
1529 }
1530 }
1531
1532 // Factor target node emission code (emitted by EmitResultCode) into
1533 // separate functions. Uniquing and share them among all instruction
1534 // selection routines.
1535 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1536 CodeList &GeneratedCode = CodeForPatterns[i].second;
1537 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1538 std::vector<std::string> &TargetVTs = PatternVTs[i];
1539 std::set<std::string> Decls = PatternDecls[i];
1540 std::vector<std::string> AddedInits;
1541 int CodeSize = (int)GeneratedCode.size();
1542 int LastPred = -1;
1543 for (int j = CodeSize-1; j >= 0; --j) {
1544 if (LastPred == -1 && GeneratedCode[j].first == 1)
1545 LastPred = j;
1546 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1547 AddedInits.push_back(GeneratedCode[j].second);
1548 }
1549
1550 std::string CalleeCode = "(const SDOperand &N";
1551 std::string CallerCode = "(N";
1552 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1553 CalleeCode += ", unsigned Opc" + utostr(j);
1554 CallerCode += ", " + TargetOpcodes[j];
1555 }
1556 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1557 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1558 CallerCode += ", " + TargetVTs[j];
1559 }
1560 for (std::set<std::string>::iterator
1561 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1562 std::string Name = *I;
1563 CalleeCode += ", SDOperand &" + Name;
1564 CallerCode += ", " + Name;
1565 }
1566 CallerCode += ");";
1567 CalleeCode += ") ";
1568 // Prevent emission routines from being inlined to reduce selection
1569 // routines stack frame sizes.
1570 CalleeCode += "DISABLE_INLINE ";
1571 CalleeCode += "{\n";
1572
1573 for (std::vector<std::string>::const_reverse_iterator
1574 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1575 CalleeCode += " " + *I + "\n";
1576
1577 for (int j = LastPred+1; j < CodeSize; ++j)
1578 CalleeCode += " " + GeneratedCode[j].second + "\n";
1579 for (int j = LastPred+1; j < CodeSize; ++j)
1580 GeneratedCode.pop_back();
1581 CalleeCode += "}\n";
1582
1583 // Uniquing the emission routines.
1584 unsigned EmitFuncNum;
1585 std::map<std::string, unsigned>::iterator EFI =
1586 EmitFunctions.find(CalleeCode);
1587 if (EFI != EmitFunctions.end()) {
1588 EmitFuncNum = EFI->second;
1589 } else {
1590 EmitFuncNum = EmitFunctions.size();
1591 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1592 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1593 }
1594
1595 // Replace the emission code within selection routines with calls to the
1596 // emission functions.
1597 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1598 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1599 }
1600
1601 // Print function.
1602 std::string OpVTStr;
1603 if (OpVT == MVT::iPTR) {
1604 OpVTStr = "_iPTR";
1605 } else if (OpVT == MVT::isVoid) {
1606 // Nodes with a void result actually have a first result type of either
1607 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1608 // void to this case, we handle it specially here.
1609 } else {
1610 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1611 }
1612 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1613 OpcodeVTMap.find(OpName);
1614 if (OpVTI == OpcodeVTMap.end()) {
1615 std::vector<std::string> VTSet;
1616 VTSet.push_back(OpVTStr);
1617 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1618 } else
1619 OpVTI->second.push_back(OpVTStr);
1620
1621 OS << "SDNode *Select_" << getLegalCName(OpName)
1622 << OpVTStr << "(const SDOperand &N) {\n";
1623
1624 // Loop through and reverse all of the CodeList vectors, as we will be
1625 // accessing them from their logical front, but accessing the end of a
1626 // vector is more efficient.
1627 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1628 CodeList &GeneratedCode = CodeForPatterns[i].second;
1629 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1630 }
1631
1632 // Next, reverse the list of patterns itself for the same reason.
1633 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1634
1635 // Emit all of the patterns now, grouped together to share code.
1636 EmitPatterns(CodeForPatterns, 2, OS);
1637
1638 // If the last pattern has predicates (which could fail) emit code to
1639 // catch the case where nothing handles a pattern.
1640 if (mightNotMatch) {
1641 OS << " cerr << \"Cannot yet select: \";\n";
1642 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1643 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1644 OpName != "ISD::INTRINSIC_VOID") {
1645 OS << " N.Val->dump(CurDAG);\n";
1646 } else {
1647 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1648 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1649 << " cerr << \"intrinsic %\"<< "
1650 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1651 }
1652 OS << " cerr << '\\n';\n"
1653 << " abort();\n"
1654 << " return NULL;\n";
1655 }
1656 OS << "}\n\n";
1657 }
1658 }
1659
1660 // Emit boilerplate.
1661 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1662 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1663 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1664
1665 << " // Ensure that the asm operands are themselves selected.\n"
1666 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1667 << " AddToISelQueue(Ops[j]);\n\n"
1668
1669 << " std::vector<MVT::ValueType> VTs;\n"
1670 << " VTs.push_back(MVT::Other);\n"
1671 << " VTs.push_back(MVT::Flag);\n"
1672 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1673 "Ops.size());\n"
1674 << " return New.Val;\n"
1675 << "}\n\n";
1676
1677 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1678 << " SDOperand Chain = N.getOperand(0);\n"
1679 << " SDOperand N1 = N.getOperand(1);\n"
1680 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1681 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1682 << " AddToISelQueue(Chain);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001683 << " SDOperand Ops[] = { Tmp, Chain };\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001684 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001685 << " MVT::Other, Ops, 2);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 << "}\n\n";
1687
Christopher Lamb071a2a72007-07-26 07:48:21 +00001688 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1689 << " SDOperand N0 = N.getOperand(0);\n"
1690 << " SDOperand N1 = N.getOperand(1);\n"
1691 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1692 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1693 << " AddToISelQueue(N0);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001694 << " SDOperand Ops[] = { N0, Tmp };\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001695 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001696 << " N.getValueType(), Ops, 2);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001697 << "}\n\n";
1698
1699 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1700 << " SDOperand N0 = N.getOperand(0);\n"
1701 << " SDOperand N1 = N.getOperand(1);\n"
1702 << " SDOperand N2 = N.getOperand(2);\n"
1703 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1704 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1705 << " AddToISelQueue(N1);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001706 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001707 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
Evan Cheng2929a8e2007-10-12 08:39:02 +00001708 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001709 << " N.getValueType(), Ops+1, 2);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001710 << " } else {\n"
1711 << " AddToISelQueue(N0);\n"
Evan Cheng2929a8e2007-10-12 08:39:02 +00001712 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001713 << " N.getValueType(), Ops, 3);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001714 << " }\n"
1715 << "}\n\n";
1716
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001717 OS << "// The main instruction selector code.\n"
1718 << "SDNode *SelectCode(SDOperand N) {\n"
1719 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1720 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1721 << "INSTRUCTION_LIST_END)) {\n"
1722 << " return NULL; // Already selected.\n"
1723 << " }\n\n"
1724 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1725 << " switch (N.getOpcode()) {\n"
1726 << " default: break;\n"
1727 << " case ISD::EntryToken: // These leaves remain the same.\n"
1728 << " case ISD::BasicBlock:\n"
1729 << " case ISD::Register:\n"
1730 << " case ISD::HANDLENODE:\n"
1731 << " case ISD::TargetConstant:\n"
1732 << " case ISD::TargetConstantPool:\n"
1733 << " case ISD::TargetFrameIndex:\n"
1734 << " case ISD::TargetExternalSymbol:\n"
1735 << " case ISD::TargetJumpTable:\n"
1736 << " case ISD::TargetGlobalTLSAddress:\n"
1737 << " case ISD::TargetGlobalAddress: {\n"
1738 << " return NULL;\n"
1739 << " }\n"
1740 << " case ISD::AssertSext:\n"
1741 << " case ISD::AssertZext: {\n"
1742 << " AddToISelQueue(N.getOperand(0));\n"
1743 << " ReplaceUses(N, N.getOperand(0));\n"
1744 << " return NULL;\n"
1745 << " }\n"
1746 << " case ISD::TokenFactor:\n"
1747 << " case ISD::CopyFromReg:\n"
1748 << " case ISD::CopyToReg: {\n"
1749 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1750 << " AddToISelQueue(N.getOperand(i));\n"
1751 << " return NULL;\n"
1752 << " }\n"
1753 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001754 << " case ISD::LABEL: return Select_LABEL(N);\n"
1755 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1756 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757
1758
1759 // Loop over all of the case statements, emiting a call to each method we
1760 // emitted above.
Chris Lattner81915752008-01-05 22:30:17 +00001761 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001762 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1763 PBOI != E; ++PBOI) {
1764 const std::string &OpName = PBOI->first;
1765 // Potentially multiple versions of select for this opcode. One for each
1766 // ValueType of the node (or its first true operand if it doesn't produce a
1767 // result.
1768 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1769 OpcodeVTMap.find(OpName);
1770 std::vector<std::string> &OpVTs = OpVTI->second;
1771 OS << " case " << OpName << ": {\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00001772 // Keep track of whether we see a pattern that has an iPtr result.
1773 bool HasPtrPattern = false;
1774 bool HasDefaultPattern = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001775
Evan Chengb8b6b182007-09-04 20:18:28 +00001776 OS << " switch (NVT) {\n";
1777 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1778 std::string &VTStr = OpVTs[i];
1779 if (VTStr.empty()) {
1780 HasDefaultPattern = true;
1781 continue;
1782 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001783
Evan Chengb8b6b182007-09-04 20:18:28 +00001784 // If this is a match on iPTR: don't emit it directly, we need special
1785 // code.
1786 if (VTStr == "_iPTR") {
1787 HasPtrPattern = true;
1788 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001789 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001790 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1791 << " return Select_" << getLegalCName(OpName)
1792 << VTStr << "(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001794 OS << " default:\n";
1795
1796 // If there is an iPTR result version of this pattern, emit it here.
1797 if (HasPtrPattern) {
1798 OS << " if (NVT == TLI.getPointerTy())\n";
1799 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1800 }
1801 if (HasDefaultPattern) {
1802 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1803 }
1804 OS << " break;\n";
1805 OS << " }\n";
1806 OS << " break;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807 OS << " }\n";
1808 }
1809
1810 OS << " } // end of big switch.\n\n"
1811 << " cerr << \"Cannot yet select: \";\n"
1812 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1813 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1814 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1815 << " N.Val->dump(CurDAG);\n"
1816 << " } else {\n"
1817 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1818 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1819 << " cerr << \"intrinsic %\"<< "
1820 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1821 << " }\n"
1822 << " cerr << '\\n';\n"
1823 << " abort();\n"
1824 << " return NULL;\n"
1825 << "}\n";
1826}
1827
1828void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001829 CodeGenTarget Target;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001830 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1831 " target", OS);
1832
1833 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1834 << "// *** instruction selector class. These functions are really "
1835 << "methods.\n\n";
1836
1837 OS << "#include \"llvm/Support/Compiler.h\"\n";
1838
1839 OS << "// Instruction selector priority queue:\n"
1840 << "std::vector<SDNode*> ISelQueue;\n";
1841 OS << "/// Keep track of nodes which have already been added to queue.\n"
1842 << "unsigned char *ISelQueued;\n";
1843 OS << "/// Keep track of nodes which have already been selected.\n"
1844 << "unsigned char *ISelSelected;\n";
1845 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1846 << "std::vector<SDNode*> ISelKilled;\n\n";
1847
1848 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1849 OS << "/// not reach Op.\n";
1850 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1851 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1852 OS << " return true;\n";
1853 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1854 OS << " return false;\n";
1855 OS << " else if (Chain->getNumOperands() > 0) {\n";
1856 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1857 OS << " if (C0.getValueType() == MVT::Other)\n";
1858 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1859 OS << " }\n";
1860 OS << " return true;\n";
1861 OS << "}\n";
1862
1863 OS << "/// Sorting functions for the selection queue.\n"
1864 << "struct isel_sort : public std::binary_function"
1865 << "<SDNode*, SDNode*, bool> {\n"
1866 << " bool operator()(const SDNode* left, const SDNode* right) "
1867 << "const {\n"
1868 << " return (left->getNodeId() > right->getNodeId());\n"
1869 << " }\n"
1870 << "};\n\n";
1871
1872 OS << "inline void setQueued(int Id) {\n";
1873 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1874 OS << "}\n";
1875 OS << "inline bool isQueued(int Id) {\n";
1876 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1877 OS << "}\n";
1878 OS << "inline void setSelected(int Id) {\n";
1879 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1880 OS << "}\n";
1881 OS << "inline bool isSelected(int Id) {\n";
1882 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1883 OS << "}\n\n";
1884
1885 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
1886 OS << " int Id = N.Val->getNodeId();\n";
1887 OS << " if (Id != -1 && !isQueued(Id)) {\n";
1888 OS << " ISelQueue.push_back(N.Val);\n";
1889 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1890 OS << " setQueued(Id);\n";
1891 OS << " }\n";
1892 OS << "}\n\n";
1893
1894 OS << "inline void RemoveKilled() {\n";
1895OS << " unsigned NumKilled = ISelKilled.size();\n";
1896 OS << " if (NumKilled) {\n";
1897 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
1898 OS << " SDNode *Temp = ISelKilled[i];\n";
1899 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
1900 << "Temp), ISelQueue.end());\n";
1901 OS << " };\n";
1902 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1903 OS << " ISelKilled.clear();\n";
1904 OS << " }\n";
1905 OS << "}\n\n";
1906
1907 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner8a258202007-10-15 06:10:22 +00001908 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001909 OS << " setSelected(F.Val->getNodeId());\n";
1910 OS << " RemoveKilled();\n";
1911 OS << "}\n";
Evan Cheng775baac2007-09-12 23:30:14 +00001912 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
Evan Chengdb1f2462007-09-17 22:26:41 +00001913 OS << " unsigned FNumVals = F->getNumValues();\n";
1914 OS << " unsigned TNumVals = T->getNumValues();\n";
1915 OS << " if (FNumVals != TNumVals) {\n";
1916 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
1917 << "i < e; ++i)\n";
Evan Cheng775baac2007-09-12 23:30:14 +00001918 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
Chris Lattner8a258202007-10-15 06:10:22 +00001919 << "SDOperand(T, i), &ISelKilled);\n";
Evan Cheng775baac2007-09-12 23:30:14 +00001920 OS << " } else {\n";
1921 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
1922 OS << " }\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001923 OS << " setSelected(F->getNodeId());\n";
1924 OS << " RemoveKilled();\n";
1925 OS << "}\n\n";
1926
1927 OS << "// SelectRoot - Top level entry to DAG isel.\n";
1928 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
1929 OS << " SelectRootInit();\n";
1930 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
1931 OS << " ISelQueued = new unsigned char[NumBytes];\n";
1932 OS << " ISelSelected = new unsigned char[NumBytes];\n";
1933 OS << " memset(ISelQueued, 0, NumBytes);\n";
1934 OS << " memset(ISelSelected, 0, NumBytes);\n";
1935 OS << "\n";
1936 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
1937 << " // a reference to the root node, preventing it from being deleted,\n"
1938 << " // and tracking any changes of the root.\n"
1939 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
1940 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
1941 OS << " while (!ISelQueue.empty()) {\n";
1942 OS << " SDNode *Node = ISelQueue.front();\n";
1943 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1944 OS << " ISelQueue.pop_back();\n";
1945 OS << " if (!isSelected(Node->getNodeId())) {\n";
1946 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
1947 OS << " if (ResNode != Node) {\n";
1948 OS << " if (ResNode)\n";
1949 OS << " ReplaceUses(Node, ResNode);\n";
1950 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
1951 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
1952 OS << " RemoveKilled();\n";
1953 OS << " }\n";
1954 OS << " }\n";
1955 OS << " }\n";
1956 OS << " }\n";
1957 OS << "\n";
1958 OS << " delete[] ISelQueued;\n";
1959 OS << " ISelQueued = NULL;\n";
1960 OS << " delete[] ISelSelected;\n";
1961 OS << " ISelSelected = NULL;\n";
1962 OS << " return Dummy.getValue();\n";
1963 OS << "}\n";
1964
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001965 CodegenDAGPatterns CGP(Records, OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001967 this->CGP = &CGP;
1968
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001970 for (CodegenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1971 I != E; ++I) {
1972 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
1973 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974 DOUT << "\n";
1975 }
1976
1977 // At this point, we have full information about the 'Patterns' we need to
1978 // parse, both implicitly from instructions as well as from explicit pattern
1979 // definitions. Emit the resultant instruction selector.
1980 EmitInstructionSelector(OS);
1981
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001982}