blob: cf8c6272baccb501a624167bebaf52365a66fe59 [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//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +000024// DAGISelEmitter Helper methods
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025//
26
Chris Lattner4ca8ff02008-01-05 22:25:12 +000027/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
28/// ComplexPattern.
29static bool NodeIsComplexPattern(TreePatternNode *N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030 return (N->isLeaf() &&
31 dynamic_cast<DefInit*>(N->getLeafValue()) &&
32 static_cast<DefInit*>(N->getLeafValue())->getDef()->
33 isSubClassOf("ComplexPattern"));
34}
35
Chris Lattner4ca8ff02008-01-05 22:25:12 +000036/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
Chris Lattnerae506702008-01-06 01:10:31 +000039 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040 if (N->isLeaf() &&
41 dynamic_cast<DefInit*>(N->getLeafValue()) &&
42 static_cast<DefInit*>(N->getLeafValue())->getDef()->
43 isSubClassOf("ComplexPattern")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +000044 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
45 ->getDef());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046 }
47 return NULL;
48}
49
50/// getPatternSize - Return the 'size' of this pattern. We want to match large
51/// patterns before small ones. This is used to determine the size of a
52/// pattern.
Chris Lattnerae506702008-01-06 01:10:31 +000053static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +000054 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR) &&
59 "Not a valid pattern node to size!");
60 unsigned Size = 3; // The node itself.
61 // If the root node is a ConstantSDNode, increases its size.
62 // e.g. (set R32:$dst, 0).
63 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
64 Size += 2;
65
66 // FIXME: This is a hack to statically increase the priority of patterns
67 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68 // Later we can allow complexity / cost for each pattern to be (optionally)
69 // specified. To get best possible pattern match we'll need to dynamically
70 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner4ca8ff02008-01-05 22:25:12 +000071 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072 if (AM)
73 Size += AM->getNumOperands() * 3;
74
75 // If this node has some predicate function that must match, it adds to the
76 // complexity of this node.
77 if (!P->getPredicateFn().empty())
78 ++Size;
79
80 // Count children in the count if they are also nodes.
81 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82 TreePatternNode *Child = P->getChild(i);
83 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner4ca8ff02008-01-05 22:25:12 +000084 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085 else if (Child->isLeaf()) {
86 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
87 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
88 else if (NodeIsComplexPattern(Child))
Chris Lattner4ca8ff02008-01-05 22:25:12 +000089 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 else if (!Child->getPredicateFn().empty())
91 ++Size;
92 }
93 }
94
95 return Size;
96}
97
98/// getResultPatternCost - Compute the number of instructions for this pattern.
99/// This is a temporary hack. We should really include the instruction
100/// latencies in this calculation.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000101static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000102 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 if (P->isLeaf()) return 0;
104
105 unsigned Cost = 0;
106 Record *Op = P->getOperator();
107 if (Op->isSubClassOf("Instruction")) {
108 Cost++;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000109 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000110 if (II.usesCustomDAGSchedInserter)
111 Cost += 10;
112 }
113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000114 Cost += getResultPatternCost(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115 return Cost;
116}
117
118/// getResultPatternCodeSize - Compute the code size of instructions for this
119/// pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000120static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000121 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 if (P->isLeaf()) return 0;
123
124 unsigned Cost = 0;
125 Record *Op = P->getOperator();
126 if (Op->isSubClassOf("Instruction")) {
127 Cost += Op->getValueAsInt("CodeSize");
128 }
129 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000130 Cost += getResultPatternSize(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 return Cost;
132}
133
134// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135// In particular, we want to match maximal patterns first and lowest cost within
136// a particular complexity first.
137struct PatternSortingPredicate {
Chris Lattnerae506702008-01-06 01:10:31 +0000138 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140
Chris Lattner81915752008-01-05 22:30:17 +0000141 bool operator()(const PatternToMatch *LHS,
142 const PatternToMatch *RHS) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000143 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 LHSSize += LHS->getAddedComplexity();
146 RHSSize += RHS->getAddedComplexity();
147 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
148 if (LHSSize < RHSSize) return false;
149
150 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000151 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 if (LHSCost < RHSCost) return true;
154 if (LHSCost > RHSCost) return false;
155
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000156 return getResultPatternSize(LHS->getDstPattern(), CGP) <
157 getResultPatternSize(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 }
159};
160
161/// getRegisterValueType - Look up and return the first ValueType of specified
162/// RegisterClass record
163static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
164 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165 return RC->getValueTypeNum(0);
166 return MVT::Other;
167}
168
169
170/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171/// type information from it.
172static void RemoveAllTypes(TreePatternNode *N) {
173 N->removeTypes();
174 if (!N->isLeaf())
175 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176 RemoveAllTypes(N->getChild(i));
177}
178
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179/// NodeHasProperty - return true if TreePatternNode has the specified
180/// property.
181static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000182 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 if (N->isLeaf()) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000184 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 if (CP)
186 return CP->hasProperty(Property);
187 return false;
188 }
189 Record *Operator = N->getOperator();
190 if (!Operator->isSubClassOf("SDNode")) return false;
191
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000192 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193}
194
195static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000196 CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000197 if (NodeHasProperty(N, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 return true;
199
200 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201 TreePatternNode *Child = N->getChild(i);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000202 if (PatternHasProperty(Child, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 return true;
204 }
205
206 return false;
207}
208
Chris Lattner7fdd9342008-01-05 22:43:57 +0000209//===----------------------------------------------------------------------===//
Chris Lattner227da452008-01-05 22:54:53 +0000210// Node Transformation emitter implementation.
211//
212void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213 // Walk the pattern fragments, adding them to a map, which sorts them by
214 // name.
Chris Lattnerae506702008-01-06 01:10:31 +0000215 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner227da452008-01-05 22:54:53 +0000216 NXsByNameTy NXsByName;
217
Chris Lattnerae506702008-01-06 01:10:31 +0000218 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner227da452008-01-05 22:54:53 +0000219 I != E; ++I)
220 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
221
222 OS << "\n// Node transformations.\n";
223
224 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
225 I != E; ++I) {
226 Record *SDNode = I->second.first;
227 std::string Code = I->second.second;
228
229 if (Code.empty()) continue; // Empty code? Skip it.
230
Chris Lattner14948ea2008-01-05 22:58:54 +0000231 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner227da452008-01-05 22:54:53 +0000232 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
233
234 OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
235 << ") {\n";
236 if (ClassName != "SDNode")
237 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238 OS << Code << "\n}\n";
239 }
240}
241
242//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +0000243// Predicate emitter implementation.
244//
245
246void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247 OS << "\n// Predicate functions.\n";
248
249 // Walk the pattern fragments, adding them to a map, which sorts them by
250 // name.
251 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252 PFsByNameTy PFsByName;
253
Chris Lattnerae506702008-01-06 01:10:31 +0000254 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000255 I != E; ++I)
256 PFsByName.insert(std::make_pair(I->first->getName(), *I));
257
258
259 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
260 I != E; ++I) {
261 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262 TreePattern *P = I->second.second;
263
264 // If there is a code init for this fragment, emit the predicate code.
265 std::string Code = PatFragRecord->getValueAsCode("Predicate");
266 if (Code.empty()) continue;
267
268 if (P->getOnlyTree()->isLeaf())
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *N) {\n";
271 else {
272 std::string ClassName =
Chris Lattner14948ea2008-01-05 22:58:54 +0000273 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000274 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
275
276 OS << "inline bool Predicate_" << PatFragRecord->getName()
277 << "(SDNode *" << C2 << ") {\n";
278 if (ClassName != "SDNode")
279 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
280 }
281 OS << Code << "\n}\n";
282 }
283
284 OS << "\n\n";
285}
286
287
288//===----------------------------------------------------------------------===//
289// PatternCodeEmitter implementation.
290//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291class PatternCodeEmitter {
292private:
Chris Lattnerae506702008-01-06 01:10:31 +0000293 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
295 // Predicates.
296 ListInit *Predicates;
297 // Pattern cost.
298 unsigned Cost;
299 // Instruction selector pattern.
300 TreePatternNode *Pattern;
301 // Matched instruction.
302 TreePatternNode *Instruction;
303
304 // Node to name mapping
305 std::map<std::string, std::string> VariableMap;
306 // Node to operator mapping
307 std::map<std::string, Record*> OperatorMap;
Evan Cheng07f307d2008-02-05 22:50:29 +0000308 // Name of the folded node which produces a flag.
309 std::pair<std::string, unsigned> FoldedFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310 // Names of all the folded nodes which produce chains.
311 std::vector<std::pair<std::string, unsigned> > FoldedChains;
312 // Original input chain(s).
313 std::vector<std::pair<std::string, std::string> > OrigChains;
314 std::set<std::string> Duplicates;
315
Dan Gohman12a9c082008-02-06 22:27:42 +0000316 /// LSI - Load/Store information.
317 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
318 /// for each memory access. This facilitates the use of AliasAnalysis in
319 /// the backend.
320 std::vector<std::string> LSI;
321
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 /// GeneratedCode - This is the buffer that we emit code to. The first int
323 /// indicates whether this is an exit predicate (something that should be
324 /// tested, and if true, the match fails) [when 1], or normal code to emit
325 /// [when 0], or initialization code to emit [when 2].
326 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
327 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
328 /// the set of patterns for each top-level opcode.
329 std::set<std::string> &GeneratedDecl;
330 /// TargetOpcodes - The target specific opcodes used by the resulting
331 /// instructions.
332 std::vector<std::string> &TargetOpcodes;
333 std::vector<std::string> &TargetVTs;
334
335 std::string ChainName;
336 unsigned TmpNo;
337 unsigned OpcNo;
338 unsigned VTNo;
339
340 void emitCheck(const std::string &S) {
341 if (!S.empty())
342 GeneratedCode.push_back(std::make_pair(1, S));
343 }
344 void emitCode(const std::string &S) {
345 if (!S.empty())
346 GeneratedCode.push_back(std::make_pair(0, S));
347 }
348 void emitInit(const std::string &S) {
349 if (!S.empty())
350 GeneratedCode.push_back(std::make_pair(2, S));
351 }
352 void emitDecl(const std::string &S) {
353 assert(!S.empty() && "Invalid declaration");
354 GeneratedDecl.insert(S);
355 }
356 void emitOpcode(const std::string &Opc) {
357 TargetOpcodes.push_back(Opc);
358 OpcNo++;
359 }
360 void emitVT(const std::string &VT) {
361 TargetVTs.push_back(VT);
362 VTNo++;
363 }
364public:
Chris Lattnerae506702008-01-06 01:10:31 +0000365 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 TreePatternNode *pattern, TreePatternNode *instr,
367 std::vector<std::pair<unsigned, std::string> > &gc,
368 std::set<std::string> &gd,
369 std::vector<std::string> &to,
370 std::vector<std::string> &tv)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000371 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 GeneratedCode(gc), GeneratedDecl(gd),
373 TargetOpcodes(to), TargetVTs(tv),
374 TmpNo(0), OpcNo(0), VTNo(0) {}
375
376 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
377 /// if the match fails. At this point, we already know that the opcode for N
378 /// matches, and the SDNode for the result has the RootName specified name.
379 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
380 const std::string &RootName, const std::string &ChainSuffix,
381 bool &FoundChain) {
Dan Gohman12a9c082008-02-06 22:27:42 +0000382
383 // Save loads/stores matched by a pattern.
384 if (!N->isLeaf() && N->getName().empty()) {
385 std::string EnumName = N->getOperator()->getValueAsString("Opcode");
386 if (EnumName == "ISD::LOAD" ||
387 EnumName == "ISD::STORE") {
388 LSI.push_back(RootName);
389 }
390 }
391
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 bool isRoot = (P == NULL);
393 // Emit instruction predicates. Each predicate is just a string for now.
394 if (isRoot) {
395 std::string PredicateCheck;
396 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
397 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
398 Record *Def = Pred->getDef();
399 if (!Def->isSubClassOf("Predicate")) {
400#ifndef NDEBUG
401 Def->dump();
402#endif
403 assert(0 && "Unknown predicate type!");
404 }
405 if (!PredicateCheck.empty())
406 PredicateCheck += " && ";
407 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
408 }
409 }
410
411 emitCheck(PredicateCheck);
412 }
413
414 if (N->isLeaf()) {
415 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
416 emitCheck("cast<ConstantSDNode>(" + RootName +
417 ")->getSignExtended() == " + itostr(II->getValue()));
418 return;
419 } else if (!NodeIsComplexPattern(N)) {
420 assert(0 && "Cannot match this as a leaf value!");
421 abort();
422 }
423 }
424
425 // If this node has a name associated with it, capture it in VariableMap. If
426 // we already saw this in the pattern, emit code to verify dagness.
427 if (!N->getName().empty()) {
428 std::string &VarMapEntry = VariableMap[N->getName()];
429 if (VarMapEntry.empty()) {
430 VarMapEntry = RootName;
431 } else {
432 // If we get here, this is a second reference to a specific name. Since
433 // we already have checked that the first reference is valid, we don't
434 // have to recursively match it, just check that it's the same as the
435 // previously named thing.
436 emitCheck(VarMapEntry + " == " + RootName);
437 return;
438 }
439
440 if (!N->isLeaf())
441 OperatorMap[N->getName()] = N->getOperator();
442 }
443
444
445 // Emit code to load the child nodes and match their contents recursively.
446 unsigned OpNo = 0;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000447 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
448 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 bool EmittedUseCheck = false;
450 if (HasChain) {
451 if (NodeHasChain)
452 OpNo = 1;
453 if (!isRoot) {
454 // Multiple uses of actual result?
455 emitCheck(RootName + ".hasOneUse()");
456 EmittedUseCheck = true;
457 if (NodeHasChain) {
458 // If the immediate use can somehow reach this node through another
459 // path, then can't fold it either or it will create a cycle.
460 // e.g. In the following diagram, XX can reach ld through YY. If
461 // ld is folded into XX, then YY is both a predecessor and a successor
462 // of XX.
463 //
464 // [ld]
465 // ^ ^
466 // | |
467 // / \---
468 // / [YY]
469 // | ^
470 // [XX]-------|
471 bool NeedCheck = false;
472 if (P != Pattern)
473 NeedCheck = true;
474 else {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000475 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 NeedCheck =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000477 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
478 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
479 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 PInfo.getNumOperands() > 1 ||
481 PInfo.hasProperty(SDNPHasChain) ||
482 PInfo.hasProperty(SDNPInFlag) ||
483 PInfo.hasProperty(SDNPOptInFlag);
484 }
485
486 if (NeedCheck) {
487 std::string ParentName(RootName.begin(), RootName.end()-1);
488 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
489 ".Val, N.Val)");
490 }
491 }
492 }
493
494 if (NodeHasChain) {
495 if (FoundChain) {
496 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
497 "IsChainCompatible(" + ChainName + ".Val, " +
498 RootName + ".Val))");
499 OrigChains.push_back(std::make_pair(ChainName, RootName));
500 } else
501 FoundChain = true;
502 ChainName = "Chain" + ChainSuffix;
503 emitInit("SDOperand " + ChainName + " = " + RootName +
504 ".getOperand(0);");
505 }
506 }
507
508 // Don't fold any node which reads or writes a flag and has multiple uses.
509 // FIXME: We really need to separate the concepts of flag and "glue". Those
510 // real flag results, e.g. X86CMP output, can have multiple uses.
511 // FIXME: If the optional incoming flag does not exist. Then it is ok to
512 // fold it.
513 if (!isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000514 (PatternHasProperty(N, SDNPInFlag, CGP) ||
515 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
516 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 if (!EmittedUseCheck) {
518 // Multiple uses of actual result?
519 emitCheck(RootName + ".hasOneUse()");
520 }
521 }
522
523 // If there is a node predicate for this, emit the call.
524 if (!N->getPredicateFn().empty())
525 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
526
527
528 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
529 // a constant without a predicate fn that has more that one bit set, handle
530 // this as a special case. This is usually for targets that have special
531 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
532 // handling stuff). Using these instructions is often far more efficient
533 // than materializing the constant. Unfortunately, both the instcombiner
534 // and the dag combiner can often infer that bits are dead, and thus drop
535 // them from the mask in the dag. For example, it might turn 'AND X, 255'
536 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
537 // to handle this.
538 if (!N->isLeaf() &&
539 (N->getOperator()->getName() == "and" ||
540 N->getOperator()->getName() == "or") &&
541 N->getChild(1)->isLeaf() &&
542 N->getChild(1)->getPredicateFn().empty()) {
543 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
544 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
545 emitInit("SDOperand " + RootName + "0" + " = " +
546 RootName + ".getOperand(" + utostr(0) + ");");
547 emitInit("SDOperand " + RootName + "1" + " = " +
548 RootName + ".getOperand(" + utostr(1) + ");");
549
550 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
551 const char *MaskPredicate = N->getOperator()->getName() == "or"
552 ? "CheckOrMask(" : "CheckAndMask(";
553 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
554 RootName + "1), " + itostr(II->getValue()) + ")");
555
Christopher Lamb059c7c92008-01-31 07:27:46 +0000556 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000557 ChainSuffix + utostr(0), FoundChain);
558 return;
559 }
560 }
561 }
562
563 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
564 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
565 RootName + ".getOperand(" +utostr(OpNo) + ");");
566
Christopher Lamb059c7c92008-01-31 07:27:46 +0000567 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 ChainSuffix + utostr(OpNo), FoundChain);
569 }
570
571 // Handle cases when root is a complex pattern.
572 const ComplexPattern *CP;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000573 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000574 std::string Fn = CP->getSelectFunc();
575 unsigned NumOps = CP->getNumOperands();
576 for (unsigned i = 0; i < NumOps; ++i) {
577 emitDecl("CPTmp" + utostr(i));
578 emitCode("SDOperand CPTmp" + utostr(i) + ";");
579 }
580 if (CP->hasProperty(SDNPHasChain)) {
581 emitDecl("CPInChain");
582 emitDecl("Chain" + ChainSuffix);
583 emitCode("SDOperand CPInChain;");
584 emitCode("SDOperand Chain" + ChainSuffix + ";");
585 }
586
587 std::string Code = Fn + "(" + RootName + ", " + RootName;
588 for (unsigned i = 0; i < NumOps; i++)
589 Code += ", CPTmp" + utostr(i);
590 if (CP->hasProperty(SDNPHasChain)) {
591 ChainName = "Chain" + ChainSuffix;
592 Code += ", CPInChain, Chain" + ChainSuffix;
593 }
594 emitCheck(Code + ")");
595 }
596 }
597
598 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb059c7c92008-01-31 07:27:46 +0000599 const std::string &RootName,
600 const std::string &ParentRootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 const std::string &ChainSuffix, bool &FoundChain) {
602 if (!Child->isLeaf()) {
603 // If it's not a leaf, recursively match.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000604 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 emitCheck(RootName + ".getOpcode() == " +
606 CInfo.getEnumName());
607 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng07f307d2008-02-05 22:50:29 +0000608 bool HasChain = false;
609 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
610 HasChain = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
Evan Cheng07f307d2008-02-05 22:50:29 +0000612 }
613 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
614 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
615 "Pattern folded multiple nodes which produce flags?");
616 FoldedFlag = std::make_pair(RootName,
617 CInfo.getNumResults() + (unsigned)HasChain);
618 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 } else {
620 // If this child has a name associated with it, capture it in VarMap. If
621 // we already saw this in the pattern, emit code to verify dagness.
622 if (!Child->getName().empty()) {
623 std::string &VarMapEntry = VariableMap[Child->getName()];
624 if (VarMapEntry.empty()) {
625 VarMapEntry = RootName;
626 } else {
627 // If we get here, this is a second reference to a specific name.
628 // Since we already have checked that the first reference is valid,
629 // we don't have to recursively match it, just check that it's the
630 // same as the previously named thing.
631 emitCheck(VarMapEntry + " == " + RootName);
632 Duplicates.insert(RootName);
633 return;
634 }
635 }
636
637 // Handle leaves of various types.
638 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
639 Record *LeafRec = DI->getDef();
640 if (LeafRec->isSubClassOf("RegisterClass") ||
641 LeafRec->getName() == "ptr_rc") {
642 // Handle register references. Nothing to do here.
643 } else if (LeafRec->isSubClassOf("Register")) {
644 // Handle register references.
645 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
646 // Handle complex pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000647 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 std::string Fn = CP->getSelectFunc();
649 unsigned NumOps = CP->getNumOperands();
650 for (unsigned i = 0; i < NumOps; ++i) {
651 emitDecl("CPTmp" + utostr(i));
652 emitCode("SDOperand CPTmp" + utostr(i) + ";");
653 }
654 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000655 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 FoldedChains.push_back(std::make_pair("CPInChain",
657 PInfo.getNumResults()));
658 ChainName = "Chain" + ChainSuffix;
659 emitDecl("CPInChain");
660 emitDecl(ChainName);
661 emitCode("SDOperand CPInChain;");
662 emitCode("SDOperand " + ChainName + ";");
663 }
664
Christopher Lamb059c7c92008-01-31 07:27:46 +0000665 std::string Code = Fn + "(";
666 if (CP->hasAttribute(CPAttrParentAsRoot)) {
667 Code += ParentRootName + ", ";
668 } else {
669 Code += "N, ";
670 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 if (CP->hasProperty(SDNPHasChain)) {
672 std::string ParentName(RootName.begin(), RootName.end()-1);
673 Code += ParentName + ", ";
674 }
675 Code += RootName;
676 for (unsigned i = 0; i < NumOps; i++)
677 Code += ", CPTmp" + utostr(i);
678 if (CP->hasProperty(SDNPHasChain))
679 Code += ", CPInChain, Chain" + ChainSuffix;
680 emitCheck(Code + ")");
681 } else if (LeafRec->getName() == "srcvalue") {
682 // Place holder for SRCVALUE nodes. Nothing to do here.
683 } else if (LeafRec->isSubClassOf("ValueType")) {
684 // Make sure this is the specified value type.
685 emitCheck("cast<VTSDNode>(" + RootName +
686 ")->getVT() == MVT::" + LeafRec->getName());
687 } else if (LeafRec->isSubClassOf("CondCode")) {
688 // Make sure this is the specified cond code.
689 emitCheck("cast<CondCodeSDNode>(" + RootName +
690 ")->get() == ISD::" + LeafRec->getName());
691 } else {
692#ifndef NDEBUG
693 Child->dump();
694 cerr << " ";
695#endif
696 assert(0 && "Unknown leaf type!");
697 }
698
699 // If there is a node predicate for this, emit the call.
700 if (!Child->getPredicateFn().empty())
701 emitCheck(Child->getPredicateFn() + "(" + RootName +
702 ".Val)");
703 } else if (IntInit *II =
704 dynamic_cast<IntInit*>(Child->getLeafValue())) {
705 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
706 unsigned CTmp = TmpNo++;
707 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
708 RootName + ")->getSignExtended();");
709
710 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
711 } else {
712#ifndef NDEBUG
713 Child->dump();
714#endif
715 assert(0 && "Unknown leaf type!");
716 }
717 }
718 }
719
720 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
721 /// we actually have to build a DAG!
722 std::vector<std::string>
Evan Cheng775baac2007-09-12 23:30:14 +0000723 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 bool InFlagDecled, bool ResNodeDecled,
725 bool LikeLeaf = false, bool isRoot = false) {
726 // List of arguments of getTargetNode() or SelectNodeTo().
727 std::vector<std::string> NodeOps;
728 // This is something selected from the pattern we matched.
729 if (!N->getName().empty()) {
Scott Michel30124c22008-01-29 02:29:31 +0000730 const std::string &VarName = N->getName();
731 std::string Val = VariableMap[VarName];
732 bool ModifiedVal = false;
Scott Michelac7091c2008-02-15 23:05:48 +0000733 if (Val.empty()) {
Bill Wendling39d33752008-02-26 10:45:29 +0000734 cerr << "Variable '" << VarName << " referenced but not defined "
735 << "and not caught earlier!\n";
736 abort();
Scott Michelac7091c2008-02-15 23:05:48 +0000737 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
739 // Already selected this operand, just return the tmpval.
740 NodeOps.push_back(Val);
741 return NodeOps;
742 }
743
744 const ComplexPattern *CP;
745 unsigned ResNo = TmpNo++;
746 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
747 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
748 std::string CastType;
Scott Michel30124c22008-01-29 02:29:31 +0000749 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 switch (N->getTypeNum(0)) {
751 default:
752 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
753 << " type as an immediate constant. Aborting\n";
754 abort();
755 case MVT::i1: CastType = "bool"; break;
756 case MVT::i8: CastType = "unsigned char"; break;
757 case MVT::i16: CastType = "unsigned short"; break;
758 case MVT::i32: CastType = "unsigned"; break;
759 case MVT::i64: CastType = "uint64_t"; break;
760 }
Scott Michel30124c22008-01-29 02:29:31 +0000761 emitCode("SDOperand " + TmpVar +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 " = CurDAG->getTargetConstant(((" + CastType +
763 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
764 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
766 // value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000767 Val = TmpVar;
768 ModifiedVal = true;
769 NodeOps.push_back(Val);
Nate Begemane2ba64f2008-02-14 08:57:00 +0000770 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
771 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
772 std::string TmpVar = "Tmp" + utostr(ResNo);
773 emitCode("SDOperand " + TmpVar +
774 " = CurDAG->getTargetConstantFP(cast<ConstantFPSDNode>(" +
775 Val + ")->getValueAPF(), cast<ConstantFPSDNode>(" + Val +
776 ")->getValueType(0));");
777 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
778 // value if used multiple times by this pattern result.
779 Val = TmpVar;
780 ModifiedVal = true;
781 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
783 Record *Op = OperatorMap[N->getName()];
784 // Transform ExternalSymbol to TargetExternalSymbol
785 if (Op && Op->getName() == "externalsym") {
Scott Michel30124c22008-01-29 02:29:31 +0000786 std::string TmpVar = "Tmp"+utostr(ResNo);
787 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
789 Val + ")->getSymbol(), " +
790 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
792 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000793 Val = TmpVar;
794 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 }
Scott Michel30124c22008-01-29 02:29:31 +0000796 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
798 || N->getOperator()->getName() == "tglobaltlsaddr")) {
799 Record *Op = OperatorMap[N->getName()];
800 // Transform GlobalAddress to TargetGlobalAddress
801 if (Op && (Op->getName() == "globaladdr" ||
802 Op->getName() == "globaltlsaddr")) {
Scott Michel30124c22008-01-29 02:29:31 +0000803 std::string TmpVar = "Tmp" + utostr(ResNo);
804 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
806 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
807 ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
809 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000810 Val = TmpVar;
811 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 NodeOps.push_back(Val);
Scott Michel30124c22008-01-29 02:29:31 +0000814 } else if (!N->isLeaf()
815 && (N->getOperator()->getName() == "texternalsym"
816 || N->getOperator()->getName() == "tconstpool")) {
817 // Do not rewrite the variable name, since we don't generate a new
818 // temporary.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 NodeOps.push_back(Val);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000820 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
822 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
823 NodeOps.push_back("CPTmp" + utostr(i));
824 }
825 } else {
826 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
827 // node even if it isn't one. Don't select it.
828 if (!LikeLeaf) {
829 emitCode("AddToISelQueue(" + Val + ");");
830 if (isRoot && N->isLeaf()) {
831 emitCode("ReplaceUses(N, " + Val + ");");
832 emitCode("return NULL;");
833 }
834 }
835 NodeOps.push_back(Val);
836 }
Scott Michel30124c22008-01-29 02:29:31 +0000837
838 if (ModifiedVal) {
839 VariableMap[VarName] = Val;
840 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 return NodeOps;
842 }
843 if (N->isLeaf()) {
844 // If this is an explicit register reference, handle it.
845 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
846 unsigned ResNo = TmpNo++;
847 if (DI->getDef()->isSubClassOf("Register")) {
848 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000849 getQualifiedName(DI->getDef()) + ", " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 getEnumName(N->getTypeNum(0)) + ");");
851 NodeOps.push_back("Tmp" + utostr(ResNo));
852 return NodeOps;
853 } else if (DI->getDef()->getName() == "zero_reg") {
854 emitCode("SDOperand Tmp" + utostr(ResNo) +
855 " = CurDAG->getRegister(0, " +
856 getEnumName(N->getTypeNum(0)) + ");");
857 NodeOps.push_back("Tmp" + utostr(ResNo));
858 return NodeOps;
859 }
860 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
861 unsigned ResNo = TmpNo++;
862 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
863 emitCode("SDOperand Tmp" + utostr(ResNo) +
Scott Michelac7091c2008-02-15 23:05:48 +0000864 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
865 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 NodeOps.push_back("Tmp" + utostr(ResNo));
867 return NodeOps;
868 }
869
870#ifndef NDEBUG
871 N->dump();
872#endif
873 assert(0 && "Unknown leaf type!");
874 return NodeOps;
875 }
876
877 Record *Op = N->getOperator();
878 if (Op->isSubClassOf("Instruction")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000879 const CodeGenTarget &CGT = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000881 const DAGInstruction &Inst = CGP.getInstruction(Op);
Chris Lattner7c6e5852008-01-06 01:52:22 +0000882 const TreePattern *InstPat = Inst.getPattern();
Evan Chengf031fcb2007-09-25 01:48:59 +0000883 // FIXME: Assume actual pattern comes before "implicit".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 TreePatternNode *InstPatNode =
Evan Cheng775baac2007-09-12 23:30:14 +0000885 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
886 : (InstPat ? InstPat->getTree(0) : NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengf37df842007-09-11 19:52:18 +0000888 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 }
Chris Lattner2fb37c02008-01-07 05:19:29 +0000890 bool HasVarOps = isRoot && II.isVariadic;
Evan Cheng775baac2007-09-12 23:30:14 +0000891 // FIXME: fix how we deal with physical register operands.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng775baac2007-09-12 23:30:14 +0000893 bool HasImpResults = isRoot && DstRegs.size() > 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 bool NodeHasOptInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000895 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 bool NodeHasInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000897 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengdec1dd12007-09-07 23:59:02 +0000898 bool NodeHasOutFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000899 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 bool NodeHasChain = InstPatNode &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000901 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 bool InputHasChain = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000903 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904 unsigned NumResults = Inst.getNumResults();
Evan Cheng775baac2007-09-12 23:30:14 +0000905 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906
907 if (NodeHasOptInFlag) {
908 emitCode("bool HasInFlag = "
909 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
910 }
911 if (HasVarOps)
912 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
913
914 // How many results is this pattern expected to produce?
Evan Cheng775baac2007-09-12 23:30:14 +0000915 unsigned NumPatResults = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
917 MVT::ValueType VT = Pattern->getTypeNum(i);
918 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng775baac2007-09-12 23:30:14 +0000919 NumPatResults++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 }
921
922 if (OrigChains.size() > 0) {
923 // The original input chain is being ignored. If it is not just
924 // pointing to the op that's being folded, we should create a
925 // TokenFactor with it and the chain of the folded op as the new chain.
926 // We could potentially be doing multiple levels of folding, in that
927 // case, the TokenFactor can have more operands.
928 emitCode("SmallVector<SDOperand, 8> InChains;");
929 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
930 emitCode("if (" + OrigChains[i].first + ".Val != " +
931 OrigChains[i].second + ".Val) {");
932 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
933 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
934 emitCode("}");
935 }
936 emitCode("AddToISelQueue(" + ChainName + ");");
937 emitCode("InChains.push_back(" + ChainName + ");");
938 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
939 "&InChains[0], InChains.size());");
940 }
941
942 // Loop over all of the operands of the instruction pattern, emitting code
943 // to fill them all in. The node 'N' usually has number children equal to
944 // the number of input operands of the instruction. However, in cases
945 // where there are predicate operands for an instruction, we need to fill
946 // in the 'execute always' values. Match up the node operands to the
947 // instruction operands to do this.
948 std::vector<std::string> AllOps;
949 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
Dan Gohmanea4faba2008-05-29 21:50:34 +0000950 unsigned InputIndex = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 for (unsigned ChildNo = 0, InstOpNo = NumResults;
952 InstOpNo != II.OperandList.size(); ++InstOpNo) {
953 std::vector<std::string> Ops;
954
Dan Gohman3329ffe2008-05-29 19:57:41 +0000955 // Determine what to emit for this operand.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Dan Gohman3329ffe2008-05-29 19:57:41 +0000957 if (OperandNode->getName() == "discard") {
958 // This is a "discard" operand; emit nothing. Just note it.
Dan Gohmanea4faba2008-05-29 21:50:34 +0000959 ++InputIndex;
Dan Gohman3329ffe2008-05-29 19:57:41 +0000960 } else if ((OperandNode->isSubClassOf("PredicateOperand") ||
961 OperandNode->isSubClassOf("OptionalDefOperand")) &&
962 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
963 // This is a predicate or optional def operand; emit the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 // 'default ops' operands.
965 const DAGDefaultOperand &DefaultOp =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000966 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Chengdb1f2462007-09-17 22:26:41 +0000968 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 InFlagDecled, ResNodeDecled);
970 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
971 NumEAInputs += Ops.size();
972 }
Dan Gohmanea4faba2008-05-29 21:50:34 +0000973 ++InputIndex;
Dan Gohman3329ffe2008-05-29 19:57:41 +0000974 } else {
975 // Otherwise this is a normal operand or a predicate operand without
976 // 'execute always'; emit it.
977 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
978 InFlagDecled, ResNodeDecled);
979 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
980 ++ChildNo;
Dan Gohmanea4faba2008-05-29 21:50:34 +0000981 ++InputIndex;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 }
983 }
984
Christopher Lambb371e032008-03-13 05:47:01 +0000985 // Generate MemOperandSDNodes nodes for each memory accesses covered by
986 // this pattern.
987 if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
Dan Gohman12a9c082008-02-06 22:27:42 +0000988 std::vector<std::string>::const_iterator mi, mie;
989 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
990 emitCode("SDOperand LSI_" + *mi + " = "
991 "CurDAG->getMemOperand(cast<LSBaseSDNode>(" +
992 *mi + ")->getMemOperand());");
993 AllOps.push_back("LSI_" + *mi);
994 }
995 }
996
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 // Emit all the chain and CopyToReg stuff.
998 bool ChainEmitted = NodeHasChain;
999 if (NodeHasChain)
1000 emitCode("AddToISelQueue(" + ChainName + ");");
1001 if (NodeHasInFlag || HasImpInputs)
1002 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1003 InFlagDecled, ResNodeDecled, true);
1004 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1005 if (!InFlagDecled) {
1006 emitCode("SDOperand InFlag(0, 0);");
1007 InFlagDecled = true;
1008 }
1009 if (NodeHasOptInFlag) {
1010 emitCode("if (HasInFlag) {");
1011 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1012 emitCode(" AddToISelQueue(InFlag);");
1013 emitCode("}");
1014 }
1015 }
1016
1017 unsigned ResNo = TmpNo++;
1018 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
Evan Chengdec1dd12007-09-07 23:59:02 +00001019 NodeHasOptInFlag || HasImpResults) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 std::string Code;
1021 std::string Code2;
1022 std::string NodeName;
1023 if (!isRoot) {
1024 NodeName = "Tmp" + utostr(ResNo);
Dan Gohman875770e2007-07-24 22:58:00 +00001025 Code2 = "SDOperand " + NodeName + "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 } else {
1027 NodeName = "ResNode";
1028 if (!ResNodeDecled) {
1029 Code2 = "SDNode *" + NodeName + " = ";
1030 ResNodeDecled = true;
1031 } else
1032 Code2 = NodeName + " = ";
1033 }
1034
Evan Cheng775baac2007-09-12 23:30:14 +00001035 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 unsigned OpsNo = OpcNo;
1037 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1038
1039 // Output order: results, chain, flags
1040 // Result types.
1041 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1042 Code += ", VT" + utostr(VTNo);
1043 emitVT(getEnumName(N->getTypeNum(0)));
1044 }
Evan Chengdec1dd12007-09-07 23:59:02 +00001045 // Add types for implicit results in physical registers, scheduler will
1046 // care of adding copyfromreg nodes.
Evan Cheng775baac2007-09-12 23:30:14 +00001047 for (unsigned i = 0; i < NumDstRegs; i++) {
1048 Record *RR = DstRegs[i];
1049 if (RR->isSubClassOf("Register")) {
1050 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1051 Code += ", " + getEnumName(RVT);
Evan Chengdec1dd12007-09-07 23:59:02 +00001052 }
1053 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 if (NodeHasChain)
1055 Code += ", MVT::Other";
1056 if (NodeHasOutFlag)
1057 Code += ", MVT::Flag";
1058
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 // Inputs.
1060 if (HasVarOps) {
Dan Gohman3329ffe2008-05-29 19:57:41 +00001061 // Figure out how many fixed inputs the node has. This is important
1062 // to know which inputs are the variable ones if present. Include
1063 // the 'discard' and chain inputs in the count, and adjust for the
1064 // number of operands that are 'execute always'. This is the index
1065 // where we should start copying operands into the 'variable_ops'
1066 // portion of the output.
Dan Gohmanea4faba2008-05-29 21:50:34 +00001067 InputIndex += NodeHasChain - NumEAInputs;
Dan Gohman3329ffe2008-05-29 19:57:41 +00001068
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1070 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1071 AllOps.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 // Figure out whether any operands at the end of the op list are not
1074 // part of the variable section.
1075 std::string EndAdjust;
1076 if (NodeHasInFlag || HasImpInputs)
1077 EndAdjust = "-1"; // Always has one flag.
1078 else if (NodeHasOptInFlag)
1079 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1080
Dan Gohman3329ffe2008-05-29 19:57:41 +00001081 emitCode("for (unsigned i = " + utostr(InputIndex) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1083
1084 emitCode(" AddToISelQueue(N.getOperand(i));");
1085 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1086 emitCode("}");
1087 }
1088
1089 if (NodeHasChain) {
1090 if (HasVarOps)
1091 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1092 else
1093 AllOps.push_back(ChainName);
1094 }
1095
1096 if (HasVarOps) {
1097 if (NodeHasInFlag || HasImpInputs)
1098 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1099 else if (NodeHasOptInFlag) {
1100 emitCode("if (HasInFlag)");
1101 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1102 }
1103 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1104 ".size()";
1105 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng775baac2007-09-12 23:30:14 +00001106 AllOps.push_back("InFlag");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107
1108 unsigned NumOps = AllOps.size();
1109 if (NumOps) {
1110 if (!NodeHasOptInFlag && NumOps < 4) {
1111 for (unsigned i = 0; i != NumOps; ++i)
1112 Code += ", " + AllOps[i];
1113 } else {
1114 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1115 for (unsigned i = 0; i != NumOps; ++i) {
1116 OpsCode += AllOps[i];
1117 if (i != NumOps-1)
1118 OpsCode += ", ";
1119 }
1120 emitCode(OpsCode + " };");
1121 Code += ", Ops" + utostr(OpsNo) + ", ";
1122 if (NodeHasOptInFlag) {
1123 Code += "HasInFlag ? ";
1124 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1125 } else
1126 Code += utostr(NumOps);
1127 }
1128 }
1129
1130 if (!isRoot)
1131 Code += "), 0";
1132 emitCode(Code2 + Code + ");");
1133
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00001134 if (NodeHasChain) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 // Remember which op produces the chain.
1136 if (!isRoot)
1137 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng775baac2007-09-12 23:30:14 +00001138 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139 else
1140 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng775baac2007-09-12 23:30:14 +00001141 ", " + utostr(NumResults+NumDstRegs) + ");");
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00001142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143
1144 if (!isRoot) {
1145 NodeOps.push_back("Tmp" + utostr(ResNo));
1146 return NodeOps;
1147 }
1148
1149 bool NeedReplace = false;
1150 if (NodeHasOutFlag) {
1151 if (!InFlagDecled) {
Dan Gohman875770e2007-07-24 22:58:00 +00001152 emitCode("SDOperand InFlag(ResNode, " +
Evan Chengdb1f2462007-09-17 22:26:41 +00001153 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 InFlagDecled = true;
1155 } else
1156 emitCode("InFlag = SDOperand(ResNode, " +
Evan Chengdb1f2462007-09-17 22:26:41 +00001157 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 }
1159
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 if (FoldedChains.size() > 0) {
1161 std::string Code;
1162 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1163 emitCode("ReplaceUses(SDOperand(" +
1164 FoldedChains[j].first + ".Val, " +
1165 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
Evan Cheng775baac2007-09-12 23:30:14 +00001166 utostr(NumResults+NumDstRegs) + "));");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 NeedReplace = true;
1168 }
1169
1170 if (NodeHasOutFlag) {
Evan Cheng07f307d2008-02-05 22:50:29 +00001171 if (FoldedFlag.first != "") {
1172 emitCode("ReplaceUses(SDOperand(" + FoldedFlag.first + ".Val, " +
1173 utostr(FoldedFlag.second) + "), InFlag);");
1174 } else {
1175 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1176 emitCode("ReplaceUses(SDOperand(N.Val, " +
1177 utostr(NumPatResults + (unsigned)InputHasChain)
1178 +"), InFlag);");
1179 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 NeedReplace = true;
1181 }
1182
Evan Chengdb1f2462007-09-17 22:26:41 +00001183 if (NeedReplace && InputHasChain)
1184 emitCode("ReplaceUses(SDOperand(N.Val, " +
1185 utostr(NumPatResults) + "), SDOperand(" + ChainName
1186 + ".Val, " + ChainName + ".ResNo" + "));");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187
1188 // User does not expect the instruction would produce a chain!
1189 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1190 ;
1191 } else if (InputHasChain && !NodeHasChain) {
1192 // One of the inner node produces a chain.
1193 if (NodeHasOutFlag)
Bill Wendling39d33752008-02-26 10:45:29 +00001194 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1195 "), SDOperand(ResNode, N.ResNo-1));");
1196 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1197 "), " + ChainName + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 }
1199
Evan Chengdb1f2462007-09-17 22:26:41 +00001200 emitCode("return ResNode;");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 } else {
1202 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1203 utostr(OpcNo);
1204 if (N->getTypeNum(0) != MVT::isVoid)
1205 Code += ", VT" + utostr(VTNo);
1206 if (NodeHasOutFlag)
1207 Code += ", MVT::Flag";
1208
1209 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1210 AllOps.push_back("InFlag");
1211
1212 unsigned NumOps = AllOps.size();
1213 if (NumOps) {
1214 if (!NodeHasOptInFlag && NumOps < 4) {
1215 for (unsigned i = 0; i != NumOps; ++i)
1216 Code += ", " + AllOps[i];
1217 } else {
1218 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1219 for (unsigned i = 0; i != NumOps; ++i) {
1220 OpsCode += AllOps[i];
1221 if (i != NumOps-1)
1222 OpsCode += ", ";
1223 }
1224 emitCode(OpsCode + " };");
1225 Code += ", Ops" + utostr(OpcNo) + ", ";
1226 Code += utostr(NumOps);
1227 }
1228 }
1229 emitCode(Code + ");");
1230 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1231 if (N->getTypeNum(0) != MVT::isVoid)
1232 emitVT(getEnumName(N->getTypeNum(0)));
1233 }
1234
1235 return NodeOps;
1236 } else if (Op->isSubClassOf("SDNodeXForm")) {
1237 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1238 // PatLeaf node - the operand may or may not be a leaf node. But it should
1239 // behave like one.
1240 std::vector<std::string> Ops =
Evan Chengdb1f2462007-09-17 22:26:41 +00001241 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 ResNodeDecled, true);
1243 unsigned ResNo = TmpNo++;
1244 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1245 + "(" + Ops.back() + ".Val);");
1246 NodeOps.push_back("Tmp" + utostr(ResNo));
1247 if (isRoot)
1248 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1249 return NodeOps;
1250 } else {
1251 N->dump();
1252 cerr << "\n";
1253 throw std::string("Unknown node in result pattern!");
1254 }
1255 }
1256
1257 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1258 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1259 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1260 /// for, this returns true otherwise false if Pat has all types.
1261 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1262 const std::string &Prefix, bool isRoot = false) {
1263 // Did we find one?
1264 if (Pat->getExtTypes() != Other->getExtTypes()) {
1265 // Move a type over from 'other' to 'pat'.
1266 Pat->setTypes(Other->getExtTypes());
1267 // The top level node type is checked outside of the select function.
1268 if (!isRoot)
1269 emitCheck(Prefix + ".Val->getValueType(0) == " +
1270 getName(Pat->getTypeNum(0)));
1271 return true;
1272 }
1273
1274 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001275 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1277 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1278 Prefix + utostr(OpNo)))
1279 return true;
1280 return false;
1281 }
1282
1283private:
1284 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1285 /// being built.
1286 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1287 bool &ChainEmitted, bool &InFlagDecled,
1288 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001289 const CodeGenTarget &T = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001291 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1292 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1294 TreePatternNode *Child = N->getChild(i);
1295 if (!Child->isLeaf()) {
1296 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1297 InFlagDecled, ResNodeDecled);
1298 } else {
1299 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1300 if (!Child->getName().empty()) {
1301 std::string Name = RootName + utostr(OpNo);
1302 if (Duplicates.find(Name) != Duplicates.end())
1303 // A duplicate! Do not emit a copy for this node.
1304 continue;
1305 }
1306
1307 Record *RR = DI->getDef();
1308 if (RR->isSubClassOf("Register")) {
1309 MVT::ValueType RVT = getRegisterValueType(RR, T);
1310 if (RVT == MVT::Flag) {
1311 if (!InFlagDecled) {
1312 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1313 InFlagDecled = true;
1314 } else
1315 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1316 emitCode("AddToISelQueue(InFlag);");
1317 } else {
1318 if (!ChainEmitted) {
1319 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1320 ChainName = "Chain";
1321 ChainEmitted = true;
1322 }
1323 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1324 if (!InFlagDecled) {
1325 emitCode("SDOperand InFlag(0, 0);");
1326 InFlagDecled = true;
1327 }
1328 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1329 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001330 ", " + getQualifiedName(RR) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1332 ResNodeDecled = true;
1333 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1334 emitCode("InFlag = SDOperand(ResNode, 1);");
1335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 if (HasInFlag) {
1342 if (!InFlagDecled) {
1343 emitCode("SDOperand InFlag = " + RootName +
1344 ".getOperand(" + utostr(OpNo) + ");");
1345 InFlagDecled = true;
1346 } else
1347 emitCode("InFlag = " + RootName +
1348 ".getOperand(" + utostr(OpNo) + ");");
1349 emitCode("AddToISelQueue(InFlag);");
1350 }
1351 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352};
1353
1354/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1355/// stream to match the pattern, and generate the code for the match if it
1356/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner81915752008-01-05 22:30:17 +00001357void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1359 std::set<std::string> &GeneratedDecl,
1360 std::vector<std::string> &TargetOpcodes,
1361 std::vector<std::string> &TargetVTs) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001362 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1364 GeneratedCode, GeneratedDecl,
1365 TargetOpcodes, TargetVTs);
1366
1367 // Emit the matcher, capturing named arguments in VariableMap.
1368 bool FoundChain = false;
1369 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1370
1371 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner14948ea2008-01-05 22:58:54 +00001372 TreePattern &TP = *CGP.pf_begin()->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373
1374 // At this point, we know that we structurally match the pattern, but the
1375 // types of the nodes may not match. Figure out the fewest number of type
1376 // comparisons we need to emit. For example, if there is only one integer
1377 // type supported by a target, there should be no type comparisons at all for
1378 // integer patterns!
1379 //
1380 // To figure out the fewest number of type checks needed, clone the pattern,
1381 // remove the types, then perform type inference on the pattern as a whole.
1382 // If there are unresolved types, emit an explicit check for those types,
1383 // apply the type to the tree, then rerun type inference. Iterate until all
1384 // types are resolved.
1385 //
1386 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1387 RemoveAllTypes(Pat);
1388
1389 do {
1390 // Resolve/propagate as many types as possible.
1391 try {
1392 bool MadeChange = true;
1393 while (MadeChange)
1394 MadeChange = Pat->ApplyTypeConstraints(TP,
1395 true/*Ignore reg constraints*/);
1396 } catch (...) {
1397 assert(0 && "Error: could not find consistent types for something we"
1398 " already decided was ok!");
1399 abort();
1400 }
1401
1402 // Insert a check for an unresolved type and add it to the tree. If we find
1403 // an unresolved type to add a check for, this returns true and we iterate,
1404 // otherwise we are done.
1405 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1406
Evan Cheng775baac2007-09-12 23:30:14 +00001407 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Chengdb1f2462007-09-17 22:26:41 +00001408 false, false, false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001409 delete Pat;
1410}
1411
1412/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1413/// a line causes any of them to be empty, remove them and return true when
1414/// done.
Chris Lattner81915752008-01-05 22:30:17 +00001415static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 std::vector<std::pair<unsigned, std::string> > > >
1417 &Patterns) {
1418 bool ErasedPatterns = false;
1419 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1420 Patterns[i].second.pop_back();
1421 if (Patterns[i].second.empty()) {
1422 Patterns.erase(Patterns.begin()+i);
1423 --i; --e;
1424 ErasedPatterns = true;
1425 }
1426 }
1427 return ErasedPatterns;
1428}
1429
1430/// EmitPatterns - Emit code for at least one pattern, but try to group common
1431/// code together between the patterns.
Chris Lattner81915752008-01-05 22:30:17 +00001432void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 std::vector<std::pair<unsigned, std::string> > > >
1434 &Patterns, unsigned Indent,
1435 std::ostream &OS) {
1436 typedef std::pair<unsigned, std::string> CodeLine;
1437 typedef std::vector<CodeLine> CodeList;
Chris Lattner81915752008-01-05 22:30:17 +00001438 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439
1440 if (Patterns.empty()) return;
1441
1442 // Figure out how many patterns share the next code line. Explicitly copy
1443 // FirstCodeLine so that we don't invalidate a reference when changing
1444 // Patterns.
1445 const CodeLine FirstCodeLine = Patterns.back().second.back();
1446 unsigned LastMatch = Patterns.size()-1;
1447 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1448 --LastMatch;
1449
1450 // If not all patterns share this line, split the list into two pieces. The
1451 // first chunk will use this line, the second chunk won't.
1452 if (LastMatch != 0) {
1453 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1454 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1455
1456 // FIXME: Emit braces?
1457 if (Shared.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001458 const PatternToMatch &Pattern = *Shared.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1460 Pattern.getSrcPattern()->print(OS);
1461 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1462 Pattern.getDstPattern()->print(OS);
1463 OS << "\n";
1464 unsigned AddedComplexity = Pattern.getAddedComplexity();
1465 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001466 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001468 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001470 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 }
1472 if (FirstCodeLine.first != 1) {
1473 OS << std::string(Indent, ' ') << "{\n";
1474 Indent += 2;
1475 }
1476 EmitPatterns(Shared, Indent, OS);
1477 if (FirstCodeLine.first != 1) {
1478 Indent -= 2;
1479 OS << std::string(Indent, ' ') << "}\n";
1480 }
1481
1482 if (Other.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001483 const PatternToMatch &Pattern = *Other.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1485 Pattern.getSrcPattern()->print(OS);
1486 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1487 Pattern.getDstPattern()->print(OS);
1488 OS << "\n";
1489 unsigned AddedComplexity = Pattern.getAddedComplexity();
1490 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001491 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001493 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001495 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496 }
1497 EmitPatterns(Other, Indent, OS);
1498 return;
1499 }
1500
1501 // Remove this code from all of the patterns that share it.
1502 bool ErasedPatterns = EraseCodeLine(Patterns);
1503
1504 bool isPredicate = FirstCodeLine.first == 1;
1505
1506 // Otherwise, every pattern in the list has this line. Emit it.
1507 if (!isPredicate) {
1508 // Normal code.
1509 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1510 } else {
1511 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1512
1513 // If the next code line is another predicate, and if all of the pattern
1514 // in this group share the same next line, emit it inline now. Do this
1515 // until we run out of common predicates.
1516 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1517 // Check that all of fhe patterns in Patterns end with the same predicate.
1518 bool AllEndWithSamePredicate = true;
1519 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1520 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1521 AllEndWithSamePredicate = false;
1522 break;
1523 }
1524 // If all of the predicates aren't the same, we can't share them.
1525 if (!AllEndWithSamePredicate) break;
1526
1527 // Otherwise we can. Emit it shared now.
1528 OS << " &&\n" << std::string(Indent+4, ' ')
1529 << Patterns.back().second.back().second;
1530 ErasedPatterns = EraseCodeLine(Patterns);
1531 }
1532
1533 OS << ") {\n";
1534 Indent += 2;
1535 }
1536
1537 EmitPatterns(Patterns, Indent, OS);
1538
1539 if (isPredicate)
1540 OS << std::string(Indent-2, ' ') << "}\n";
1541}
1542
Chris Lattnerae506702008-01-06 01:10:31 +00001543static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001544 return CGP.getSDNodeInfo(Op).getEnumName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545}
1546
1547static std::string getLegalCName(std::string OpName) {
1548 std::string::size_type pos = OpName.find("::");
1549 if (pos != std::string::npos)
1550 OpName.replace(pos, 2, "_");
1551 return OpName;
1552}
1553
1554void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001555 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001556
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557 // Get the namespace to insert instructions into. Make sure not to pick up
1558 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1559 // instruction or something.
1560 std::string InstNS;
1561 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1562 e = Target.inst_end(); i != e; ++i) {
1563 InstNS = i->second.Namespace;
1564 if (InstNS != "TargetInstrInfo")
1565 break;
1566 }
1567
1568 if (!InstNS.empty()) InstNS += "::";
1569
1570 // Group the patterns by their top-level opcodes.
Chris Lattner81915752008-01-05 22:30:17 +00001571 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001572 // All unique target node emission functions.
1573 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerae506702008-01-06 01:10:31 +00001574 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001575 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner81915752008-01-05 22:30:17 +00001576 const PatternToMatch &Pattern = *I;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001577
1578 TreePatternNode *Node = Pattern.getSrcPattern();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001579 if (!Node->isLeaf()) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001580 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001581 push_back(&Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001582 } else {
1583 const ComplexPattern *CP;
1584 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001585 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001586 push_back(&Pattern);
Chris Lattner14948ea2008-01-05 22:58:54 +00001587 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588 std::vector<Record*> OpNodes = CP->getRootNodes();
1589 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001590 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1591 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001592 &Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593 }
1594 } else {
1595 cerr << "Unrecognized opcode '";
1596 Node->dump();
1597 cerr << "' on tree pattern '";
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001598 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599 exit(1);
1600 }
1601 }
1602 }
1603
1604 // For each opcode, there might be multiple select functions, one per
1605 // ValueType of the node (or its first operand if it doesn't produce a
1606 // non-chain result.
1607 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1608
1609 // Emit one Select_* method for each top-level opcode. We do this instead of
1610 // emitting one giant switch statement to support compilers where this will
1611 // result in the recursive functions taking less stack space.
Chris Lattner81915752008-01-05 22:30:17 +00001612 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001613 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1614 PBOI != E; ++PBOI) {
1615 const std::string &OpName = PBOI->first;
Chris Lattner81915752008-01-05 22:30:17 +00001616 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001617 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1618
1619 // We want to emit all of the matching code now. However, we want to emit
1620 // the matches in order of minimal cost. Sort the patterns so the least
1621 // cost one is at the start.
1622 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001623 PatternSortingPredicate(CGP));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624
1625 // Split them into groups by type.
Chris Lattner81915752008-01-05 22:30:17 +00001626 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner81915752008-01-05 22:30:17 +00001628 const PatternToMatch *Pat = PatternsOfOp[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 TreePatternNode *SrcPat = Pat->getSrcPattern();
1630 MVT::ValueType VT = SrcPat->getTypeNum(0);
Chris Lattner81915752008-01-05 22:30:17 +00001631 std::map<MVT::ValueType,
1632 std::vector<const PatternToMatch*> >::iterator TI =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633 PatternsByType.find(VT);
1634 if (TI != PatternsByType.end())
1635 TI->second.push_back(Pat);
1636 else {
Chris Lattner81915752008-01-05 22:30:17 +00001637 std::vector<const PatternToMatch*> PVec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001638 PVec.push_back(Pat);
1639 PatternsByType.insert(std::make_pair(VT, PVec));
1640 }
1641 }
1642
Chris Lattner81915752008-01-05 22:30:17 +00001643 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001644 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1645 ++II) {
1646 MVT::ValueType OpVT = II->first;
Chris Lattner81915752008-01-05 22:30:17 +00001647 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1649 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1650
Chris Lattner81915752008-01-05 22:30:17 +00001651 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652 std::vector<std::vector<std::string> > PatternOpcodes;
1653 std::vector<std::vector<std::string> > PatternVTs;
1654 std::vector<std::set<std::string> > PatternDecls;
1655 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1656 CodeList GeneratedCode;
1657 std::set<std::string> GeneratedDecl;
1658 std::vector<std::string> TargetOpcodes;
1659 std::vector<std::string> TargetVTs;
1660 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1661 TargetOpcodes, TargetVTs);
1662 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1663 PatternDecls.push_back(GeneratedDecl);
1664 PatternOpcodes.push_back(TargetOpcodes);
1665 PatternVTs.push_back(TargetVTs);
1666 }
1667
1668 // Scan the code to see if all of the patterns are reachable and if it is
1669 // possible that the last one might not match.
1670 bool mightNotMatch = true;
1671 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1672 CodeList &GeneratedCode = CodeForPatterns[i].second;
1673 mightNotMatch = false;
1674
1675 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1676 if (GeneratedCode[j].first == 1) { // predicate.
1677 mightNotMatch = true;
1678 break;
1679 }
1680 }
1681
1682 // If this pattern definitely matches, and if it isn't the last one, the
1683 // patterns after it CANNOT ever match. Error out.
1684 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1685 cerr << "Pattern '";
1686 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1687 cerr << "' is impossible to select!\n";
1688 exit(1);
1689 }
1690 }
1691
1692 // Factor target node emission code (emitted by EmitResultCode) into
1693 // separate functions. Uniquing and share them among all instruction
1694 // selection routines.
1695 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1696 CodeList &GeneratedCode = CodeForPatterns[i].second;
1697 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1698 std::vector<std::string> &TargetVTs = PatternVTs[i];
1699 std::set<std::string> Decls = PatternDecls[i];
1700 std::vector<std::string> AddedInits;
1701 int CodeSize = (int)GeneratedCode.size();
1702 int LastPred = -1;
1703 for (int j = CodeSize-1; j >= 0; --j) {
1704 if (LastPred == -1 && GeneratedCode[j].first == 1)
1705 LastPred = j;
1706 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1707 AddedInits.push_back(GeneratedCode[j].second);
1708 }
1709
1710 std::string CalleeCode = "(const SDOperand &N";
1711 std::string CallerCode = "(N";
1712 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1713 CalleeCode += ", unsigned Opc" + utostr(j);
1714 CallerCode += ", " + TargetOpcodes[j];
1715 }
1716 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1717 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1718 CallerCode += ", " + TargetVTs[j];
1719 }
1720 for (std::set<std::string>::iterator
1721 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1722 std::string Name = *I;
1723 CalleeCode += ", SDOperand &" + Name;
1724 CallerCode += ", " + Name;
1725 }
1726 CallerCode += ");";
1727 CalleeCode += ") ";
1728 // Prevent emission routines from being inlined to reduce selection
1729 // routines stack frame sizes.
1730 CalleeCode += "DISABLE_INLINE ";
1731 CalleeCode += "{\n";
1732
1733 for (std::vector<std::string>::const_reverse_iterator
1734 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1735 CalleeCode += " " + *I + "\n";
1736
1737 for (int j = LastPred+1; j < CodeSize; ++j)
1738 CalleeCode += " " + GeneratedCode[j].second + "\n";
1739 for (int j = LastPred+1; j < CodeSize; ++j)
1740 GeneratedCode.pop_back();
1741 CalleeCode += "}\n";
1742
1743 // Uniquing the emission routines.
1744 unsigned EmitFuncNum;
1745 std::map<std::string, unsigned>::iterator EFI =
1746 EmitFunctions.find(CalleeCode);
1747 if (EFI != EmitFunctions.end()) {
1748 EmitFuncNum = EFI->second;
1749 } else {
1750 EmitFuncNum = EmitFunctions.size();
1751 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1752 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1753 }
1754
1755 // Replace the emission code within selection routines with calls to the
1756 // emission functions.
1757 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1758 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1759 }
1760
1761 // Print function.
1762 std::string OpVTStr;
1763 if (OpVT == MVT::iPTR) {
1764 OpVTStr = "_iPTR";
1765 } else if (OpVT == MVT::isVoid) {
1766 // Nodes with a void result actually have a first result type of either
1767 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1768 // void to this case, we handle it specially here.
1769 } else {
1770 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1771 }
1772 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1773 OpcodeVTMap.find(OpName);
1774 if (OpVTI == OpcodeVTMap.end()) {
1775 std::vector<std::string> VTSet;
1776 VTSet.push_back(OpVTStr);
1777 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1778 } else
1779 OpVTI->second.push_back(OpVTStr);
1780
1781 OS << "SDNode *Select_" << getLegalCName(OpName)
1782 << OpVTStr << "(const SDOperand &N) {\n";
1783
1784 // Loop through and reverse all of the CodeList vectors, as we will be
1785 // accessing them from their logical front, but accessing the end of a
1786 // vector is more efficient.
1787 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1788 CodeList &GeneratedCode = CodeForPatterns[i].second;
1789 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1790 }
1791
1792 // Next, reverse the list of patterns itself for the same reason.
1793 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1794
1795 // Emit all of the patterns now, grouped together to share code.
1796 EmitPatterns(CodeForPatterns, 2, OS);
1797
1798 // If the last pattern has predicates (which could fail) emit code to
1799 // catch the case where nothing handles a pattern.
1800 if (mightNotMatch) {
1801 OS << " cerr << \"Cannot yet select: \";\n";
1802 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1803 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1804 OpName != "ISD::INTRINSIC_VOID") {
1805 OS << " N.Val->dump(CurDAG);\n";
1806 } else {
1807 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1808 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1809 << " cerr << \"intrinsic %\"<< "
1810 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1811 }
1812 OS << " cerr << '\\n';\n"
1813 << " abort();\n"
1814 << " return NULL;\n";
1815 }
1816 OS << "}\n\n";
1817 }
1818 }
1819
1820 // Emit boilerplate.
1821 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1822 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1823 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1824
1825 << " // Ensure that the asm operands are themselves selected.\n"
1826 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1827 << " AddToISelQueue(Ops[j]);\n\n"
1828
1829 << " std::vector<MVT::ValueType> VTs;\n"
1830 << " VTs.push_back(MVT::Other);\n"
1831 << " VTs.push_back(MVT::Flag);\n"
1832 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1833 "Ops.size());\n"
1834 << " return New.Val;\n"
1835 << "}\n\n";
Evan Cheng3c0eda52008-03-15 00:03:38 +00001836
1837 OS << "SDNode *Select_UNDEF(const SDOperand &N) {\n"
1838 << " return CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,\n"
1839 << " N.getValueType());\n"
1840 << "}\n\n";
1841
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1843 << " SDOperand Chain = N.getOperand(0);\n"
1844 << " SDOperand N1 = N.getOperand(1);\n"
Evan Cheng13d1c292008-01-31 09:59:15 +00001845 << " SDOperand N2 = N.getOperand(2);\n"
1846 << " unsigned C1 = cast<ConstantSDNode>(N1)->getValue();\n"
1847 << " unsigned C2 = cast<ConstantSDNode>(N2)->getValue();\n"
1848 << " SDOperand Tmp1 = CurDAG->getTargetConstant(C1, MVT::i32);\n"
1849 << " SDOperand Tmp2 = CurDAG->getTargetConstant(C2, MVT::i32);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001850 << " AddToISelQueue(Chain);\n"
Evan Cheng13d1c292008-01-31 09:59:15 +00001851 << " SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001852 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Evan Cheng13d1c292008-01-31 09:59:15 +00001853 << " MVT::Other, Ops, 3);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 << "}\n\n";
1855
Evan Cheng2e28d622008-02-02 04:07:54 +00001856 OS << "SDNode *Select_DECLARE(const SDOperand &N) {\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001857 << " SDOperand Chain = N.getOperand(0);\n"
1858 << " SDOperand N1 = N.getOperand(1);\n"
1859 << " SDOperand N2 = N.getOperand(2);\n"
1860 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1861 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1862 << " N.Val->dump(CurDAG);\n"
1863 << " abort();\n"
1864 << " }\n"
1865 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1866 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001867 << " SDOperand Tmp1 = "
1868 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1869 << " SDOperand Tmp2 = "
1870 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1871 << " AddToISelQueue(Chain);\n"
1872 << " SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1873 << " return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,\n"
1874 << " MVT::Other, Ops, 3);\n"
1875 << "}\n\n";
1876
Christopher Lamb071a2a72007-07-26 07:48:21 +00001877 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1878 << " SDOperand N0 = N.getOperand(0);\n"
1879 << " SDOperand N1 = N.getOperand(1);\n"
1880 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1881 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1882 << " AddToISelQueue(N0);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001883 << " SDOperand Ops[] = { N0, Tmp };\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001884 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001885 << " N.getValueType(), Ops, 2);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001886 << "}\n\n";
1887
1888 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1889 << " SDOperand N0 = N.getOperand(0);\n"
1890 << " SDOperand N1 = N.getOperand(1);\n"
1891 << " SDOperand N2 = N.getOperand(2);\n"
1892 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1893 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1894 << " AddToISelQueue(N1);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001895 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
Christopher Lambb371e032008-03-13 05:47:01 +00001896 << " AddToISelQueue(N0);\n"
1897 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1898 << " N.getValueType(), Ops, 3);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001899 << "}\n\n";
1900
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901 OS << "// The main instruction selector code.\n"
1902 << "SDNode *SelectCode(SDOperand N) {\n"
1903 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1904 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1905 << "INSTRUCTION_LIST_END)) {\n"
1906 << " return NULL; // Already selected.\n"
1907 << " }\n\n"
1908 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1909 << " switch (N.getOpcode()) {\n"
1910 << " default: break;\n"
1911 << " case ISD::EntryToken: // These leaves remain the same.\n"
1912 << " case ISD::BasicBlock:\n"
1913 << " case ISD::Register:\n"
1914 << " case ISD::HANDLENODE:\n"
1915 << " case ISD::TargetConstant:\n"
Nate Begemane2ba64f2008-02-14 08:57:00 +00001916 << " case ISD::TargetConstantFP:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001917 << " case ISD::TargetConstantPool:\n"
1918 << " case ISD::TargetFrameIndex:\n"
1919 << " case ISD::TargetExternalSymbol:\n"
1920 << " case ISD::TargetJumpTable:\n"
1921 << " case ISD::TargetGlobalTLSAddress:\n"
1922 << " case ISD::TargetGlobalAddress: {\n"
1923 << " return NULL;\n"
1924 << " }\n"
1925 << " case ISD::AssertSext:\n"
1926 << " case ISD::AssertZext: {\n"
1927 << " AddToISelQueue(N.getOperand(0));\n"
1928 << " ReplaceUses(N, N.getOperand(0));\n"
1929 << " return NULL;\n"
1930 << " }\n"
1931 << " case ISD::TokenFactor:\n"
1932 << " case ISD::CopyFromReg:\n"
1933 << " case ISD::CopyToReg: {\n"
1934 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1935 << " AddToISelQueue(N.getOperand(i));\n"
1936 << " return NULL;\n"
1937 << " }\n"
1938 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001939 << " case ISD::LABEL: return Select_LABEL(N);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001940 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001941 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00001942 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
1943 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001944
1945
1946 // Loop over all of the case statements, emiting a call to each method we
1947 // emitted above.
Chris Lattner81915752008-01-05 22:30:17 +00001948 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001949 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1950 PBOI != E; ++PBOI) {
1951 const std::string &OpName = PBOI->first;
1952 // Potentially multiple versions of select for this opcode. One for each
1953 // ValueType of the node (or its first true operand if it doesn't produce a
1954 // result.
1955 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1956 OpcodeVTMap.find(OpName);
1957 std::vector<std::string> &OpVTs = OpVTI->second;
1958 OS << " case " << OpName << ": {\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00001959 // Keep track of whether we see a pattern that has an iPtr result.
1960 bool HasPtrPattern = false;
1961 bool HasDefaultPattern = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001962
Evan Chengb8b6b182007-09-04 20:18:28 +00001963 OS << " switch (NVT) {\n";
1964 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1965 std::string &VTStr = OpVTs[i];
1966 if (VTStr.empty()) {
1967 HasDefaultPattern = true;
1968 continue;
1969 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970
Evan Chengb8b6b182007-09-04 20:18:28 +00001971 // If this is a match on iPTR: don't emit it directly, we need special
1972 // code.
1973 if (VTStr == "_iPTR") {
1974 HasPtrPattern = true;
1975 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001977 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1978 << " return Select_" << getLegalCName(OpName)
1979 << VTStr << "(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001981 OS << " default:\n";
1982
1983 // If there is an iPTR result version of this pattern, emit it here.
1984 if (HasPtrPattern) {
1985 OS << " if (NVT == TLI.getPointerTy())\n";
1986 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1987 }
1988 if (HasDefaultPattern) {
1989 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1990 }
1991 OS << " break;\n";
1992 OS << " }\n";
1993 OS << " break;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001994 OS << " }\n";
1995 }
1996
1997 OS << " } // end of big switch.\n\n"
1998 << " cerr << \"Cannot yet select: \";\n"
1999 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2000 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2001 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2002 << " N.Val->dump(CurDAG);\n"
2003 << " } else {\n"
2004 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2005 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
2006 << " cerr << \"intrinsic %\"<< "
2007 "Intrinsic::getName((Intrinsic::ID)iid);\n"
2008 << " }\n"
2009 << " cerr << '\\n';\n"
2010 << " abort();\n"
2011 << " return NULL;\n"
2012 << "}\n";
2013}
2014
2015void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00002016 EmitSourceFileHeader("DAG Instruction Selector for the " +
2017 CGP.getTargetInfo().getName() + " target", OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002018
2019 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2020 << "// *** instruction selector class. These functions are really "
2021 << "methods.\n\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00002022
Roman Levenstein393ad0f2008-05-14 10:17:11 +00002023 OS << "// Include standard, target-independent definitions and methods used\n"
2024 << "// by the instruction selector.\n";
2025 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026
Chris Lattner227da452008-01-05 22:54:53 +00002027 EmitNodeTransforms(OS);
Chris Lattner7fdd9342008-01-05 22:43:57 +00002028 EmitPredicateFunctions(OS);
2029
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattnerae506702008-01-06 01:10:31 +00002031 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00002032 I != E; ++I) {
2033 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2034 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002035 DOUT << "\n";
2036 }
2037
2038 // At this point, we have full information about the 'Patterns' we need to
2039 // parse, both implicitly from instructions as well as from explicit pattern
2040 // definitions. Emit the resultant instruction selector.
2041 EmitInstructionSelector(OS);
2042
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043}