blob: 355a438d84fd4d6e049121533a83d33b8a40644b [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner30609102007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner54cb8fd2005-09-07 23:44:43 +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"
David Greene8ad4c002008-10-27 21:56:29 +000017#include "llvm/Support/CommandLine.h"
Chris Lattner54cb8fd2005-09-07 23:44:43 +000018#include "llvm/Support/Debug.h"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000019#include "llvm/Support/MathExtras.h"
David Greene8ad4c002008-10-27 21:56:29 +000020#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000021#include <algorithm>
Dan Gohman95d11092008-07-07 21:00:17 +000022#include <deque>
Daniel Dunbar1a551802009-07-03 00:10:29 +000023#include <iostream>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000024using namespace llvm;
25
Chris Lattner3d4ad292009-08-07 22:27:19 +000026static cl::opt<bool>
27GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
David Greene8ad4c002008-10-27 21:56:29 +000028
Chris Lattnerca559d02005-09-08 21:03:01 +000029//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +000030// DAGISelEmitter Helper methods
Chris Lattner54cb8fd2005-09-07 23:44:43 +000031//
32
Dan Gohmaneeb3a002010-01-05 01:24:18 +000033/// getNodeName - The top level Select_* functions have an "SDNode* N"
34/// argument. When expanding the pattern-matching code, the intermediate
35/// variables have type SDValue. This function provides a uniform way to
36/// reference the underlying "SDNode *" for both cases.
37static std::string getNodeName(const std::string &S) {
38 if (S == "N") return S;
39 return S + ".getNode()";
40}
41
42/// getNodeValue - Similar to getNodeName, except it provides a uniform
43/// way to access the SDValue for both cases.
44static std::string getValueName(const std::string &S) {
45 if (S == "N") return "SDValue(N, 0)";
46 return S;
47}
48
Chris Lattner6cefb772008-01-05 22:25:12 +000049/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
50/// ComplexPattern.
51static bool NodeIsComplexPattern(TreePatternNode *N) {
Evan Cheng0fc71982005-12-08 02:00:36 +000052 return (N->isLeaf() &&
53 dynamic_cast<DefInit*>(N->getLeafValue()) &&
54 static_cast<DefInit*>(N->getLeafValue())->getDef()->
55 isSubClassOf("ComplexPattern"));
56}
57
Chris Lattner6cefb772008-01-05 22:25:12 +000058/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
59/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
Evan Cheng0fc71982005-12-08 02:00:36 +000060static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
Chris Lattnerfe718932008-01-06 01:10:31 +000061 CodeGenDAGPatterns &CGP) {
Evan Cheng0fc71982005-12-08 02:00:36 +000062 if (N->isLeaf() &&
63 dynamic_cast<DefInit*>(N->getLeafValue()) &&
64 static_cast<DefInit*>(N->getLeafValue())->getDef()->
65 isSubClassOf("ComplexPattern")) {
Chris Lattner6cefb772008-01-05 22:25:12 +000066 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
67 ->getDef());
Evan Cheng0fc71982005-12-08 02:00:36 +000068 }
69 return NULL;
70}
71
Chris Lattner05814af2005-09-28 17:57:56 +000072/// getPatternSize - Return the 'size' of this pattern. We want to match large
73/// patterns before small ones. This is used to determine the size of a
74/// pattern.
Chris Lattnerfe718932008-01-06 01:10:31 +000075static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Owen Andersone50ed302009-08-10 22:56:29 +000076 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
77 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +000078 P->getExtTypeNum(0) == MVT::isVoid ||
79 P->getExtTypeNum(0) == MVT::Flag ||
80 P->getExtTypeNum(0) == MVT::iPTR ||
81 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +000082 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +000083 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +000084 // If the root node is a ConstantSDNode, increases its size.
85 // e.g. (set R32:$dst, 0).
86 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000087 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +000088
89 // FIXME: This is a hack to statically increase the priority of patterns
90 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
91 // Later we can allow complexity / cost for each pattern to be (optionally)
92 // specified. To get best possible pattern match we'll need to dynamically
93 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner6cefb772008-01-05 22:25:12 +000094 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000095 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +000096 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +000097
98 // If this node has some predicate function that must match, it adds to the
99 // complexity of this node.
Dan Gohman0540e172008-10-15 06:17:21 +0000100 if (!P->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +0000101 ++Size;
102
Chris Lattner05814af2005-09-28 17:57:56 +0000103 // Count children in the count if they are also nodes.
104 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
105 TreePatternNode *Child = P->getChild(i);
Owen Anderson825b72b2009-08-11 20:47:22 +0000106 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner6cefb772008-01-05 22:25:12 +0000107 Size += getPatternSize(Child, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +0000108 else if (Child->isLeaf()) {
109 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +0000110 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +0000111 else if (NodeIsComplexPattern(Child))
Chris Lattner6cefb772008-01-05 22:25:12 +0000112 Size += getPatternSize(Child, CGP);
Dan Gohman0540e172008-10-15 06:17:21 +0000113 else if (!Child->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +0000114 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +0000115 }
Chris Lattner05814af2005-09-28 17:57:56 +0000116 }
117
118 return Size;
119}
120
121/// getResultPatternCost - Compute the number of instructions for this pattern.
122/// This is a temporary hack. We should really include the instruction
123/// latencies in this calculation.
Chris Lattner6cefb772008-01-05 22:25:12 +0000124static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000125 CodeGenDAGPatterns &CGP) {
Chris Lattner05814af2005-09-28 17:57:56 +0000126 if (P->isLeaf()) return 0;
127
Evan Chengfbad7082006-02-18 02:33:09 +0000128 unsigned Cost = 0;
129 Record *Op = P->getOperator();
130 if (Op->isSubClassOf("Instruction")) {
131 Cost++;
Chris Lattner6cefb772008-01-05 22:25:12 +0000132 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohman533297b2009-10-29 18:10:34 +0000133 if (II.usesCustomInserter)
Evan Chengfbad7082006-02-18 02:33:09 +0000134 Cost += 10;
135 }
Chris Lattner05814af2005-09-28 17:57:56 +0000136 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000137 Cost += getResultPatternCost(P->getChild(i), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000138 return Cost;
139}
140
Evan Chenge6f32032006-07-19 00:24:41 +0000141/// getResultPatternCodeSize - Compute the code size of instructions for this
142/// pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000143static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000144 CodeGenDAGPatterns &CGP) {
Evan Chenge6f32032006-07-19 00:24:41 +0000145 if (P->isLeaf()) return 0;
146
147 unsigned Cost = 0;
148 Record *Op = P->getOperator();
149 if (Op->isSubClassOf("Instruction")) {
150 Cost += Op->getValueAsInt("CodeSize");
151 }
152 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000153 Cost += getResultPatternSize(P->getChild(i), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000154 return Cost;
155}
156
Chris Lattner05814af2005-09-28 17:57:56 +0000157// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
158// In particular, we want to match maximal patterns first and lowest cost within
159// a particular complexity first.
160struct PatternSortingPredicate {
Chris Lattnerfe718932008-01-06 01:10:31 +0000161 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
162 CodeGenDAGPatterns &CGP;
Evan Cheng0fc71982005-12-08 02:00:36 +0000163
Dan Gohman0540e172008-10-15 06:17:21 +0000164 typedef std::pair<unsigned, std::string> CodeLine;
165 typedef std::vector<CodeLine> CodeList;
166 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
167
168 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
169 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
170 const PatternToMatch *LHS = LHSPair.first;
171 const PatternToMatch *RHS = RHSPair.first;
172
Chris Lattner6cefb772008-01-05 22:25:12 +0000173 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
174 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Evan Chengc81d2a02006-04-19 20:36:09 +0000175 LHSSize += LHS->getAddedComplexity();
176 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +0000177 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
178 if (LHSSize < RHSSize) return false;
179
180 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner6cefb772008-01-05 22:25:12 +0000181 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
182 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000183 if (LHSCost < RHSCost) return true;
184 if (LHSCost > RHSCost) return false;
185
Chris Lattner6cefb772008-01-05 22:25:12 +0000186 return getResultPatternSize(LHS->getDstPattern(), CGP) <
187 getResultPatternSize(RHS->getDstPattern(), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000188 }
189};
190
Jim Grosbach54f30222009-03-25 23:28:33 +0000191/// getRegisterValueType - Look up and return the ValueType of the specified
192/// register. If the register is a member of multiple register classes which
Owen Anderson825b72b2009-08-11 20:47:22 +0000193/// have different associated types, return MVT::Other.
194static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000195 bool FoundRC = false;
Owen Anderson825b72b2009-08-11 20:47:22 +0000196 MVT::SimpleValueType VT = MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000197 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
198 std::vector<CodeGenRegisterClass>::const_iterator RC;
199 std::vector<Record*>::const_iterator Element;
200
201 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
202 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
203 if (Element != (*RC).Elements.end()) {
204 if (!FoundRC) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000205 FoundRC = true;
Jim Grosbach54f30222009-03-25 23:28:33 +0000206 VT = (*RC).getValueTypeNum(0);
207 } else {
208 // In multiple RC's
209 if (VT != (*RC).getValueTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000210 // Types of the RC's do not agree. Return MVT::Other. The
Jim Grosbach54f30222009-03-25 23:28:33 +0000211 // target is responsible for handling this.
Owen Anderson825b72b2009-08-11 20:47:22 +0000212 return MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000213 }
214 }
215 }
216 }
217 return VT;
Evan Cheng66a48bb2005-12-01 00:18:45 +0000218}
219
Chris Lattner72fe91c2005-09-24 00:40:24 +0000220
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000221/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
222/// type information from it.
223static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000224 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000225 if (!N->isLeaf())
226 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
227 RemoveAllTypes(N->getChild(i));
228}
Chris Lattner72fe91c2005-09-24 00:40:24 +0000229
Evan Cheng51fecc82006-01-09 18:27:06 +0000230/// NodeHasProperty - return true if TreePatternNode has the specified
231/// property.
Evan Cheng94b30402006-10-11 21:02:01 +0000232static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerfe718932008-01-06 01:10:31 +0000233 CodeGenDAGPatterns &CGP) {
Evan Cheng94b30402006-10-11 21:02:01 +0000234 if (N->isLeaf()) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000235 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Evan Cheng94b30402006-10-11 21:02:01 +0000236 if (CP)
237 return CP->hasProperty(Property);
238 return false;
239 }
Evan Cheng7b05bd52005-12-23 22:11:47 +0000240 Record *Operator = N->getOperator();
241 if (!Operator->isSubClassOf("SDNode")) return false;
242
Chris Lattner6cefb772008-01-05 22:25:12 +0000243 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +0000244}
245
Evan Cheng94b30402006-10-11 21:02:01 +0000246static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerfe718932008-01-06 01:10:31 +0000247 CodeGenDAGPatterns &CGP) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000248 if (NodeHasProperty(N, Property, CGP))
Evan Cheng7b05bd52005-12-23 22:11:47 +0000249 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +0000250
251 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
252 TreePatternNode *Child = N->getChild(i);
Chris Lattner6cefb772008-01-05 22:25:12 +0000253 if (PatternHasProperty(Child, Property, CGP))
Evan Cheng51fecc82006-01-09 18:27:06 +0000254 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +0000255 }
256
257 return false;
258}
259
Evan Chengf9d03182008-07-03 08:39:51 +0000260static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
261 return CGP.getSDNodeInfo(Op).getEnumName();
262}
263
Chris Lattnerdc32f982008-01-05 22:43:57 +0000264//===----------------------------------------------------------------------===//
Chris Lattner443e3f92008-01-05 22:54:53 +0000265// Node Transformation emitter implementation.
266//
Daniel Dunbar1a551802009-07-03 00:10:29 +0000267void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
Chris Lattner443e3f92008-01-05 22:54:53 +0000268 // Walk the pattern fragments, adding them to a map, which sorts them by
269 // name.
Chris Lattnerfe718932008-01-06 01:10:31 +0000270 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner443e3f92008-01-05 22:54:53 +0000271 NXsByNameTy NXsByName;
272
Chris Lattnerfe718932008-01-06 01:10:31 +0000273 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner443e3f92008-01-05 22:54:53 +0000274 I != E; ++I)
275 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
276
277 OS << "\n// Node transformations.\n";
278
279 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
280 I != E; ++I) {
281 Record *SDNode = I->second.first;
282 std::string Code = I->second.second;
283
284 if (Code.empty()) continue; // Empty code? Skip it.
285
Chris Lattner200c57e2008-01-05 22:58:54 +0000286 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner443e3f92008-01-05 22:54:53 +0000287 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
288
Dan Gohman475871a2008-07-27 21:46:04 +0000289 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner443e3f92008-01-05 22:54:53 +0000290 << ") {\n";
291 if (ClassName != "SDNode")
292 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
293 OS << Code << "\n}\n";
294 }
295}
296
297//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +0000298// Predicate emitter implementation.
299//
300
Daniel Dunbar1a551802009-07-03 00:10:29 +0000301void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
Chris Lattnerdc32f982008-01-05 22:43:57 +0000302 OS << "\n// Predicate functions.\n";
303
304 // Walk the pattern fragments, adding them to a map, which sorts them by
305 // name.
306 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
307 PFsByNameTy PFsByName;
308
Chris Lattnerfe718932008-01-06 01:10:31 +0000309 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000310 I != E; ++I)
311 PFsByName.insert(std::make_pair(I->first->getName(), *I));
312
313
314 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
315 I != E; ++I) {
316 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
317 TreePattern *P = I->second.second;
318
319 // If there is a code init for this fragment, emit the predicate code.
320 std::string Code = PatFragRecord->getValueAsCode("Predicate");
321 if (Code.empty()) continue;
322
323 if (P->getOnlyTree()->isLeaf())
324 OS << "inline bool Predicate_" << PatFragRecord->getName()
325 << "(SDNode *N) {\n";
326 else {
327 std::string ClassName =
Chris Lattner200c57e2008-01-05 22:58:54 +0000328 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000329 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
330
331 OS << "inline bool Predicate_" << PatFragRecord->getName()
332 << "(SDNode *" << C2 << ") {\n";
333 if (ClassName != "SDNode")
334 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
335 }
336 OS << Code << "\n}\n";
337 }
338
339 OS << "\n\n";
340}
341
342
343//===----------------------------------------------------------------------===//
344// PatternCodeEmitter implementation.
345//
Evan Chengb915f312005-12-09 22:45:35 +0000346class PatternCodeEmitter {
347private:
Chris Lattnerfe718932008-01-06 01:10:31 +0000348 CodeGenDAGPatterns &CGP;
Evan Chengb915f312005-12-09 22:45:35 +0000349
Evan Cheng58e84a62005-12-14 22:02:59 +0000350 // Predicates.
Dan Gohman22bb3112008-08-22 00:20:26 +0000351 std::string PredicateCheck;
Evan Cheng59413202006-04-19 18:07:24 +0000352 // Pattern cost.
353 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +0000354 // Instruction selector pattern.
355 TreePatternNode *Pattern;
356 // Matched instruction.
357 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000358
Evan Chengb915f312005-12-09 22:45:35 +0000359 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +0000360 std::map<std::string, std::string> VariableMap;
361 // Node to operator mapping
362 std::map<std::string, Record*> OperatorMap;
Evan Chenga58891f2008-02-05 22:50:29 +0000363 // Name of the folded node which produces a flag.
364 std::pair<std::string, unsigned> FoldedFlag;
Evan Chengb915f312005-12-09 22:45:35 +0000365 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +0000366 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +0000367 // Original input chain(s).
368 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +0000369 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +0000370
Dan Gohman69de1932008-02-06 22:27:42 +0000371 /// LSI - Load/Store information.
372 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
373 /// for each memory access. This facilitates the use of AliasAnalysis in
374 /// the backend.
375 std::vector<std::string> LSI;
376
Evan Cheng676d7312006-08-26 00:59:04 +0000377 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000378 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000379 /// tested, and if true, the match fails) [when 1], or normal code to emit
380 /// [when 0], or initialization code to emit [when 2].
381 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman475871a2008-07-27 21:46:04 +0000382 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Evan Cheng21ad3922006-02-07 00:37:41 +0000383 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000384 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000385 /// TargetOpcodes - The target specific opcodes used by the resulting
386 /// instructions.
387 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000388 std::vector<std::string> &TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000389 /// OutputIsVariadic - Records whether the instruction output pattern uses
390 /// variable_ops. This requires that the Emit function be passed an
391 /// additional argument to indicate where the input varargs operands
392 /// begin.
393 bool &OutputIsVariadic;
394 /// NumInputRootOps - Records the number of operands the root node of the
395 /// input pattern has. This information is used in the generated code to
396 /// pass to Emit functions when variable_ops processing is needed.
397 unsigned &NumInputRootOps;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000398
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000399 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000400 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000401 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000402 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000403
404 void emitCheck(const std::string &S) {
405 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000406 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000407 }
408 void emitCode(const std::string &S) {
409 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000410 GeneratedCode.push_back(std::make_pair(0, S));
411 }
412 void emitInit(const std::string &S) {
413 if (!S.empty())
414 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000415 }
Evan Chengf5493192006-08-26 01:02:19 +0000416 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000417 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000418 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000419 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000420 void emitOpcode(const std::string &Opc) {
421 TargetOpcodes.push_back(Opc);
422 OpcNo++;
423 }
Evan Chengf8729402006-07-16 06:12:52 +0000424 void emitVT(const std::string &VT) {
425 TargetVTs.push_back(VT);
426 VTNo++;
427 }
Evan Chengb915f312005-12-09 22:45:35 +0000428public:
Dan Gohman22bb3112008-08-22 00:20:26 +0000429 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Evan Cheng58e84a62005-12-14 22:02:59 +0000430 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000431 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000432 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000433 std::vector<std::string> &to,
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000434 std::vector<std::string> &tv,
435 bool &oiv,
436 unsigned &niro)
Dan Gohman22bb3112008-08-22 00:20:26 +0000437 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000438 GeneratedCode(gc), GeneratedDecl(gd),
439 TargetOpcodes(to), TargetVTs(tv),
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000440 OutputIsVariadic(oiv), NumInputRootOps(niro),
Chris Lattner706d2d32006-08-09 16:44:44 +0000441 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000442
443 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
444 /// if the match fails. At this point, we already know that the opcode for N
445 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000446 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
447 const std::string &RootName, const std::string &ChainSuffix,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000448 bool &FoundChain);
Chris Lattner39e73f72006-10-11 04:05:55 +0000449
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000450 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb85356242008-01-31 07:27:46 +0000451 const std::string &RootName,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000452 const std::string &ChainSuffix, bool &FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000453
454 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
455 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000456 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000457 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000458 bool InFlagDecled, bool ResNodeDecled,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000459 bool LikeLeaf = false, bool isRoot = false);
Evan Chengb915f312005-12-09 22:45:35 +0000460
Chris Lattner488580c2006-01-28 19:06:51 +0000461 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
462 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +0000463 /// 'Pat' may be missing types. If we find an unresolved type to add a check
464 /// for, this returns true otherwise false if Pat has all types.
465 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +0000466 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +0000467 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +0000468 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +0000469 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +0000470 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +0000471 // The top level node type is checked outside of the select function.
472 if (!isRoot)
Anton Korobeynikovc2fd9192009-11-08 12:14:54 +0000473 emitCheck(Prefix + ".getValueType() == " +
Chris Lattner706d2d32006-08-09 16:44:44 +0000474 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +0000475 return true;
Evan Chengb915f312005-12-09 22:45:35 +0000476 }
477
Evan Cheng51fecc82006-01-09 18:27:06 +0000478 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +0000479 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000480 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
481 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
482 Prefix + utostr(OpNo)))
483 return true;
484 return false;
485 }
486
487private:
Evan Cheng54597732006-01-26 00:22:25 +0000488 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +0000489 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +0000490 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +0000491 bool &ChainEmitted, bool &InFlagDecled,
492 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000493 const CodeGenTarget &T = CGP.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +0000494 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +0000495 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
496 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000497 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
498 TreePatternNode *Child = N->getChild(i);
499 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000500 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
501 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +0000502 } else {
503 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +0000504 if (!Child->getName().empty()) {
505 std::string Name = RootName + utostr(OpNo);
506 if (Duplicates.find(Name) != Duplicates.end())
507 // A duplicate! Do not emit a copy for this node.
508 continue;
509 }
510
Evan Chengb915f312005-12-09 22:45:35 +0000511 Record *RR = DI->getDef();
512 if (RR->isSubClassOf("Register")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000513 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
514 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000515 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000516 emitCode("SDValue InFlag = " +
517 getValueName(RootName + utostr(OpNo)) + ";");
Evan Cheng676d7312006-08-26 00:59:04 +0000518 InFlagDecled = true;
519 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000520 emitCode("InFlag = " +
521 getValueName(RootName + utostr(OpNo)) + ";");
Evan Chengb2c6d492006-01-11 22:16:13 +0000522 } else {
523 if (!ChainEmitted) {
Dan Gohman475871a2008-07-27 21:46:04 +0000524 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000525 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +0000526 ChainEmitted = true;
527 }
Evan Cheng676d7312006-08-26 00:59:04 +0000528 if (!InFlagDecled) {
Dan Gohman475871a2008-07-27 21:46:04 +0000529 emitCode("SDValue InFlag(0, 0);");
Evan Cheng676d7312006-08-26 00:59:04 +0000530 InFlagDecled = true;
531 }
Dale Johannesen874ae252009-06-02 03:12:52 +0000532 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
533 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000534 ", " + getNodeName(RootName) + "->getDebugLoc()" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000535 ", " + getQualifiedName(RR) +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000536 ", " + getValueName(RootName + utostr(OpNo)) +
537 ", InFlag).getNode();");
Dale Johannesen874ae252009-06-02 03:12:52 +0000538 ResNodeDecled = true;
Dan Gohman475871a2008-07-27 21:46:04 +0000539 emitCode(ChainName + " = SDValue(ResNode, 0);");
540 emitCode("InFlag = SDValue(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +0000541 }
542 }
543 }
544 }
545 }
Evan Cheng54597732006-01-26 00:22:25 +0000546
Dale Johannesen874ae252009-06-02 03:12:52 +0000547 if (HasInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000548 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000549 emitCode("SDValue InFlag = " + getNodeName(RootName) +
550 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000551 InFlagDecled = true;
552 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000553 emitCode("InFlag = " + getNodeName(RootName) +
554 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000555 }
Evan Chengb915f312005-12-09 22:45:35 +0000556 }
557};
558
Chris Lattnera0cdf172010-02-13 20:06:50 +0000559
560/// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
561/// if the match fails. At this point, we already know that the opcode for N
562/// matches, and the SDNode for the result has the RootName specified name.
563void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
564 const std::string &RootName,
565 const std::string &ChainSuffix,
566 bool &FoundChain) {
567
568 // Save loads/stores matched by a pattern.
569 if (!N->isLeaf() && N->getName().empty()) {
570 if (NodeHasProperty(N, SDNPMemOperand, CGP))
571 LSI.push_back(getNodeName(RootName));
572 }
573
574 bool isRoot = (P == NULL);
575 // Emit instruction predicates. Each predicate is just a string for now.
576 if (isRoot) {
577 // Record input varargs info.
578 NumInputRootOps = N->getNumChildren();
Chris Lattnera0cdf172010-02-13 20:06:50 +0000579 emitCheck(PredicateCheck);
580 }
581
582 if (N->isLeaf()) {
583 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
584 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
585 ")->getSExtValue() == INT64_C(" +
586 itostr(II->getValue()) + ")");
587 return;
588 } else if (!NodeIsComplexPattern(N)) {
589 assert(0 && "Cannot match this as a leaf value!");
590 abort();
591 }
592 }
593
594 // If this node has a name associated with it, capture it in VariableMap. If
595 // we already saw this in the pattern, emit code to verify dagness.
596 if (!N->getName().empty()) {
597 std::string &VarMapEntry = VariableMap[N->getName()];
598 if (VarMapEntry.empty()) {
599 VarMapEntry = RootName;
600 } else {
601 // If we get here, this is a second reference to a specific name. Since
602 // we already have checked that the first reference is valid, we don't
603 // have to recursively match it, just check that it's the same as the
604 // previously named thing.
605 emitCheck(VarMapEntry + " == " + RootName);
606 return;
607 }
608
609 if (!N->isLeaf())
610 OperatorMap[N->getName()] = N->getOperator();
611 }
612
613
614 // Emit code to load the child nodes and match their contents recursively.
615 unsigned OpNo = 0;
616 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
617 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
618 bool EmittedUseCheck = false;
619 if (HasChain) {
620 if (NodeHasChain)
621 OpNo = 1;
622 if (!isRoot) {
623 // Multiple uses of actual result?
624 emitCheck(getValueName(RootName) + ".hasOneUse()");
625 EmittedUseCheck = true;
626 if (NodeHasChain) {
627 // If the immediate use can somehow reach this node through another
628 // path, then can't fold it either or it will create a cycle.
629 // e.g. In the following diagram, XX can reach ld through YY. If
630 // ld is folded into XX, then YY is both a predecessor and a successor
631 // of XX.
632 //
633 // [ld]
634 // ^ ^
635 // | |
636 // / \---
637 // / [YY]
638 // | ^
639 // [XX]-------|
640 bool NeedCheck = P != Pattern;
641 if (!NeedCheck) {
642 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
643 NeedCheck =
644 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
645 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
646 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
647 PInfo.getNumOperands() > 1 ||
648 PInfo.hasProperty(SDNPHasChain) ||
649 PInfo.hasProperty(SDNPInFlag) ||
650 PInfo.hasProperty(SDNPOptInFlag);
651 }
652
653 if (NeedCheck) {
654 std::string ParentName(RootName.begin(), RootName.end()-1);
655 emitCheck("IsLegalAndProfitableToFold(" + getNodeName(RootName) +
656 ", " + getNodeName(ParentName) + ", N)");
657 }
658 }
659 }
660
661 if (NodeHasChain) {
662 if (FoundChain) {
663 emitCheck("(" + ChainName + ".getNode() == " +
664 getNodeName(RootName) + " || "
665 "IsChainCompatible(" + ChainName + ".getNode(), " +
666 getNodeName(RootName) + "))");
667 OrigChains.push_back(std::make_pair(ChainName,
668 getValueName(RootName)));
669 } else
670 FoundChain = true;
671 ChainName = "Chain" + ChainSuffix;
672 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
673 "->getOperand(0);");
674 }
675 }
676
677 // Don't fold any node which reads or writes a flag and has multiple uses.
678 // FIXME: We really need to separate the concepts of flag and "glue". Those
679 // real flag results, e.g. X86CMP output, can have multiple uses.
680 // FIXME: If the optional incoming flag does not exist. Then it is ok to
681 // fold it.
682 if (!isRoot &&
683 (PatternHasProperty(N, SDNPInFlag, CGP) ||
684 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
685 PatternHasProperty(N, SDNPOutFlag, CGP))) {
686 if (!EmittedUseCheck) {
687 // Multiple uses of actual result?
688 emitCheck(getValueName(RootName) + ".hasOneUse()");
689 }
690 }
691
692 // If there are node predicates for this, emit the calls.
693 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
694 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
695
696 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
697 // a constant without a predicate fn that has more that one bit set, handle
698 // this as a special case. This is usually for targets that have special
699 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
700 // handling stuff). Using these instructions is often far more efficient
701 // than materializing the constant. Unfortunately, both the instcombiner
702 // and the dag combiner can often infer that bits are dead, and thus drop
703 // them from the mask in the dag. For example, it might turn 'AND X, 255'
704 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
705 // to handle this.
706 if (!N->isLeaf() &&
707 (N->getOperator()->getName() == "and" ||
708 N->getOperator()->getName() == "or") &&
709 N->getChild(1)->isLeaf() &&
710 N->getChild(1)->getPredicateFns().empty()) {
711 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
712 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
713 emitInit("SDValue " + RootName + "0" + " = " +
714 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
715 emitInit("SDValue " + RootName + "1" + " = " +
716 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
717
718 unsigned NTmp = TmpNo++;
719 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
720 " = dyn_cast<ConstantSDNode>(" +
721 getNodeName(RootName + "1") + ");");
722 emitCheck("Tmp" + utostr(NTmp));
723 const char *MaskPredicate = N->getOperator()->getName() == "or"
724 ? "CheckOrMask(" : "CheckAndMask(";
725 emitCheck(MaskPredicate + getValueName(RootName + "0") +
726 ", Tmp" + utostr(NTmp) +
727 ", INT64_C(" + itostr(II->getValue()) + "))");
728
729 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
730 ChainSuffix + utostr(0), FoundChain);
731 return;
732 }
733 }
734 }
735
736 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
737 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
738 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
739
740 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
741 ChainSuffix + utostr(OpNo), FoundChain);
742 }
743
744 // Handle cases when root is a complex pattern.
745 const ComplexPattern *CP;
746 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
747 std::string Fn = CP->getSelectFunc();
748 unsigned NumOps = CP->getNumOperands();
749 for (unsigned i = 0; i < NumOps; ++i) {
750 emitDecl("CPTmp" + RootName + "_" + utostr(i));
751 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
752 }
753 if (CP->hasProperty(SDNPHasChain)) {
754 emitDecl("CPInChain");
755 emitDecl("Chain" + ChainSuffix);
756 emitCode("SDValue CPInChain;");
757 emitCode("SDValue Chain" + ChainSuffix + ";");
758 }
759
760 std::string Code = Fn + "(" +
761 getNodeName(RootName) + ", " +
762 getValueName(RootName);
763 for (unsigned i = 0; i < NumOps; i++)
764 Code += ", CPTmp" + RootName + "_" + utostr(i);
765 if (CP->hasProperty(SDNPHasChain)) {
766 ChainName = "Chain" + ChainSuffix;
767 Code += ", CPInChain, Chain" + ChainSuffix;
768 }
769 emitCheck(Code + ")");
770 }
771}
772
773void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
774 TreePatternNode *Parent,
775 const std::string &RootName,
776 const std::string &ChainSuffix,
777 bool &FoundChain) {
778 if (!Child->isLeaf()) {
779 // If it's not a leaf, recursively match.
780 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
781 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
782 CInfo.getEnumName());
783 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
784 bool HasChain = false;
785 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
786 HasChain = true;
787 FoldedChains.push_back(std::make_pair(getValueName(RootName),
788 CInfo.getNumResults()));
789 }
790 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
791 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
792 "Pattern folded multiple nodes which produce flags?");
793 FoldedFlag = std::make_pair(getValueName(RootName),
794 CInfo.getNumResults() + (unsigned)HasChain);
795 }
796 } else {
797 // If this child has a name associated with it, capture it in VarMap. If
798 // we already saw this in the pattern, emit code to verify dagness.
799 if (!Child->getName().empty()) {
800 std::string &VarMapEntry = VariableMap[Child->getName()];
801 if (VarMapEntry.empty()) {
802 VarMapEntry = getValueName(RootName);
803 } else {
804 // If we get here, this is a second reference to a specific name.
805 // Since we already have checked that the first reference is valid,
806 // we don't have to recursively match it, just check that it's the
807 // same as the previously named thing.
808 emitCheck(VarMapEntry + " == " + getValueName(RootName));
809 Duplicates.insert(getValueName(RootName));
810 return;
811 }
812 }
813
814 // Handle leaves of various types.
815 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
816 Record *LeafRec = DI->getDef();
817 if (LeafRec->isSubClassOf("RegisterClass") ||
818 LeafRec->isSubClassOf("PointerLikeRegClass")) {
819 // Handle register references. Nothing to do here.
820 } else if (LeafRec->isSubClassOf("Register")) {
821 // Handle register references.
822 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
823 // Handle complex pattern.
824 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
825 std::string Fn = CP->getSelectFunc();
826 unsigned NumOps = CP->getNumOperands();
827 for (unsigned i = 0; i < NumOps; ++i) {
828 emitDecl("CPTmp" + RootName + "_" + utostr(i));
829 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
830 }
831 if (CP->hasProperty(SDNPHasChain)) {
832 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
833 FoldedChains.push_back(std::make_pair("CPInChain",
834 PInfo.getNumResults()));
835 ChainName = "Chain" + ChainSuffix;
836 emitDecl("CPInChain");
837 emitDecl(ChainName);
838 emitCode("SDValue CPInChain;");
839 emitCode("SDValue " + ChainName + ";");
840 }
841
842 std::string Code = Fn + "(N, ";
843 if (CP->hasProperty(SDNPHasChain)) {
844 std::string ParentName(RootName.begin(), RootName.end()-1);
845 Code += getValueName(ParentName) + ", ";
846 }
847 Code += getValueName(RootName);
848 for (unsigned i = 0; i < NumOps; i++)
849 Code += ", CPTmp" + RootName + "_" + utostr(i);
850 if (CP->hasProperty(SDNPHasChain))
851 Code += ", CPInChain, Chain" + ChainSuffix;
852 emitCheck(Code + ")");
853 } else if (LeafRec->getName() == "srcvalue") {
854 // Place holder for SRCVALUE nodes. Nothing to do here.
855 } else if (LeafRec->isSubClassOf("ValueType")) {
856 // Make sure this is the specified value type.
857 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
858 ")->getVT() == MVT::" + LeafRec->getName());
859 } else if (LeafRec->isSubClassOf("CondCode")) {
860 // Make sure this is the specified cond code.
861 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
862 ")->get() == ISD::" + LeafRec->getName());
863 } else {
864#ifndef NDEBUG
865 Child->dump();
866 errs() << " ";
867#endif
868 assert(0 && "Unknown leaf type!");
869 }
870
871 // If there are node predicates for this, emit the calls.
872 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
873 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
874 ")");
875 } else if (IntInit *II =
876 dynamic_cast<IntInit*>(Child->getLeafValue())) {
877 unsigned NTmp = TmpNo++;
878 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
879 " = dyn_cast<ConstantSDNode>("+
880 getNodeName(RootName) + ");");
881 emitCheck("Tmp" + utostr(NTmp));
882 unsigned CTmp = TmpNo++;
883 emitCode("int64_t CN"+ utostr(CTmp) +
884 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
885 emitCheck("CN" + utostr(CTmp) + " == "
886 "INT64_C(" +itostr(II->getValue()) + ")");
887 } else {
888#ifndef NDEBUG
889 Child->dump();
890#endif
891 assert(0 && "Unknown leaf type!");
892 }
893 }
894}
895
896/// EmitResultCode - Emit the action for a pattern. Now that it has matched
897/// we actually have to build a DAG!
898std::vector<std::string>
899PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
900 std::vector<Record*> DstRegs,
901 bool InFlagDecled, bool ResNodeDecled,
902 bool LikeLeaf, bool isRoot) {
903 // List of arguments of getMachineNode() or SelectNodeTo().
904 std::vector<std::string> NodeOps;
905 // This is something selected from the pattern we matched.
906 if (!N->getName().empty()) {
907 const std::string &VarName = N->getName();
908 std::string Val = VariableMap[VarName];
909 bool ModifiedVal = false;
910 if (Val.empty()) {
911 errs() << "Variable '" << VarName << " referenced but not defined "
912 << "and not caught earlier!\n";
913 abort();
914 }
915 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
916 // Already selected this operand, just return the tmpval.
917 NodeOps.push_back(getValueName(Val));
918 return NodeOps;
919 }
920
921 const ComplexPattern *CP;
922 unsigned ResNo = TmpNo++;
923 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
924 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
925 std::string CastType;
926 std::string TmpVar = "Tmp" + utostr(ResNo);
927 switch (N->getTypeNum(0)) {
928 default:
929 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
930 << " type as an immediate constant. Aborting\n";
931 abort();
932 case MVT::i1: CastType = "bool"; break;
933 case MVT::i8: CastType = "unsigned char"; break;
934 case MVT::i16: CastType = "unsigned short"; break;
935 case MVT::i32: CastType = "unsigned"; break;
936 case MVT::i64: CastType = "uint64_t"; break;
937 }
938 emitCode("SDValue " + TmpVar +
939 " = CurDAG->getTargetConstant(((" + CastType +
940 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
941 getEnumName(N->getTypeNum(0)) + ");");
942 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
943 // value if used multiple times by this pattern result.
944 Val = TmpVar;
945 ModifiedVal = true;
946 NodeOps.push_back(getValueName(Val));
947 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
948 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
949 std::string TmpVar = "Tmp" + utostr(ResNo);
950 emitCode("SDValue " + TmpVar +
951 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
952 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
953 Val + ")->getValueType(0));");
954 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
955 // value if used multiple times by this pattern result.
956 Val = TmpVar;
957 ModifiedVal = true;
958 NodeOps.push_back(getValueName(Val));
959 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
960 Record *Op = OperatorMap[N->getName()];
961 // Transform ExternalSymbol to TargetExternalSymbol
962 if (Op && Op->getName() == "externalsym") {
963 std::string TmpVar = "Tmp"+utostr(ResNo);
964 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
965 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
966 Val + ")->getSymbol(), " +
967 getEnumName(N->getTypeNum(0)) + ");");
968 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
969 // this value if used multiple times by this pattern result.
970 Val = TmpVar;
971 ModifiedVal = true;
972 }
973 NodeOps.push_back(getValueName(Val));
974 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
975 || N->getOperator()->getName() == "tglobaltlsaddr")) {
976 Record *Op = OperatorMap[N->getName()];
977 // Transform GlobalAddress to TargetGlobalAddress
978 if (Op && (Op->getName() == "globaladdr" ||
979 Op->getName() == "globaltlsaddr")) {
980 std::string TmpVar = "Tmp" + utostr(ResNo);
981 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
982 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
983 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
984 ");");
985 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
986 // this value if used multiple times by this pattern result.
987 Val = TmpVar;
988 ModifiedVal = true;
989 }
990 NodeOps.push_back(getValueName(Val));
991 } else if (!N->isLeaf()
992 && (N->getOperator()->getName() == "texternalsym"
993 || N->getOperator()->getName() == "tconstpool")) {
994 // Do not rewrite the variable name, since we don't generate a new
995 // temporary.
996 NodeOps.push_back(getValueName(Val));
997 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
998 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
999 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
1000 }
1001 } else {
1002 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
1003 // node even if it isn't one. Don't select it.
1004 if (!LikeLeaf) {
1005 if (isRoot && N->isLeaf()) {
1006 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
1007 emitCode("return NULL;");
1008 }
1009 }
1010 NodeOps.push_back(getValueName(Val));
1011 }
1012
1013 if (ModifiedVal) {
1014 VariableMap[VarName] = Val;
1015 }
1016 return NodeOps;
1017 }
1018 if (N->isLeaf()) {
1019 // If this is an explicit register reference, handle it.
1020 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1021 unsigned ResNo = TmpNo++;
1022 if (DI->getDef()->isSubClassOf("Register")) {
1023 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
1024 getQualifiedName(DI->getDef()) + ", " +
1025 getEnumName(N->getTypeNum(0)) + ");");
1026 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1027 return NodeOps;
1028 } else if (DI->getDef()->getName() == "zero_reg") {
1029 emitCode("SDValue Tmp" + utostr(ResNo) +
1030 " = CurDAG->getRegister(0, " +
1031 getEnumName(N->getTypeNum(0)) + ");");
1032 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1033 return NodeOps;
1034 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
1035 // Handle a reference to a register class. This is used
1036 // in COPY_TO_SUBREG instructions.
1037 emitCode("SDValue Tmp" + utostr(ResNo) +
1038 " = CurDAG->getTargetConstant(" +
1039 getQualifiedName(DI->getDef()) + "RegClassID, " +
1040 "MVT::i32);");
1041 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1042 return NodeOps;
1043 }
1044 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1045 unsigned ResNo = TmpNo++;
1046 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
1047 emitCode("SDValue Tmp" + utostr(ResNo) +
1048 " = CurDAG->getTargetConstant(0x" +
1049 utohexstr((uint64_t) II->getValue()) +
1050 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
1051 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1052 return NodeOps;
1053 }
1054
1055#ifndef NDEBUG
1056 N->dump();
1057#endif
1058 assert(0 && "Unknown leaf type!");
1059 return NodeOps;
1060 }
1061
1062 Record *Op = N->getOperator();
1063 if (Op->isSubClassOf("Instruction")) {
1064 const CodeGenTarget &CGT = CGP.getTargetInfo();
1065 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
1066 const DAGInstruction &Inst = CGP.getInstruction(Op);
1067 const TreePattern *InstPat = Inst.getPattern();
1068 // FIXME: Assume actual pattern comes before "implicit".
1069 TreePatternNode *InstPatNode =
1070 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
1071 : (InstPat ? InstPat->getTree(0) : NULL);
1072 if (InstPatNode && !InstPatNode->isLeaf() &&
1073 InstPatNode->getOperator()->getName() == "set") {
1074 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
1075 }
1076 bool IsVariadic = isRoot && II.isVariadic;
1077 // FIXME: fix how we deal with physical register operands.
1078 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1079 bool HasImpResults = isRoot && DstRegs.size() > 0;
1080 bool NodeHasOptInFlag = isRoot &&
1081 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
1082 bool NodeHasInFlag = isRoot &&
1083 PatternHasProperty(Pattern, SDNPInFlag, CGP);
1084 bool NodeHasOutFlag = isRoot &&
1085 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
1086 bool NodeHasChain = InstPatNode &&
1087 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
1088 bool InputHasChain = isRoot &&
1089 NodeHasProperty(Pattern, SDNPHasChain, CGP);
1090 unsigned NumResults = Inst.getNumResults();
1091 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1092
1093 // Record output varargs info.
1094 OutputIsVariadic = IsVariadic;
1095
1096 if (NodeHasOptInFlag) {
1097 emitCode("bool HasInFlag = "
1098 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1099 "MVT::Flag);");
1100 }
1101 if (IsVariadic)
1102 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1103
1104 // How many results is this pattern expected to produce?
1105 unsigned NumPatResults = 0;
1106 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1107 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1108 if (VT != MVT::isVoid && VT != MVT::Flag)
1109 NumPatResults++;
1110 }
1111
1112 if (OrigChains.size() > 0) {
1113 // The original input chain is being ignored. If it is not just
1114 // pointing to the op that's being folded, we should create a
1115 // TokenFactor with it and the chain of the folded op as the new chain.
1116 // We could potentially be doing multiple levels of folding, in that
1117 // case, the TokenFactor can have more operands.
1118 emitCode("SmallVector<SDValue, 8> InChains;");
1119 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1120 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1121 OrigChains[i].second + ".getNode()) {");
1122 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1123 emitCode("}");
1124 }
1125 emitCode("InChains.push_back(" + ChainName + ");");
1126 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1127 "N->getDebugLoc(), MVT::Other, "
1128 "&InChains[0], InChains.size());");
1129 if (GenDebug) {
1130 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1131 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1132 }
1133 }
1134
1135 // Loop over all of the operands of the instruction pattern, emitting code
1136 // to fill them all in. The node 'N' usually has number children equal to
1137 // the number of input operands of the instruction. However, in cases
1138 // where there are predicate operands for an instruction, we need to fill
1139 // in the 'execute always' values. Match up the node operands to the
1140 // instruction operands to do this.
1141 std::vector<std::string> AllOps;
1142 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1143 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1144 std::vector<std::string> Ops;
1145
1146 // Determine what to emit for this operand.
1147 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1148 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1149 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1150 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1151 // This is a predicate or optional def operand; emit the
1152 // 'default ops' operands.
1153 const DAGDefaultOperand &DefaultOp =
1154 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1155 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1156 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1157 InFlagDecled, ResNodeDecled);
1158 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1159 }
1160 } else {
1161 // Otherwise this is a normal operand or a predicate operand without
1162 // 'execute always'; emit it.
1163 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1164 InFlagDecled, ResNodeDecled);
1165 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1166 ++ChildNo;
1167 }
1168 }
1169
1170 // Emit all the chain and CopyToReg stuff.
1171 bool ChainEmitted = NodeHasChain;
1172 if (NodeHasInFlag || HasImpInputs)
1173 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1174 InFlagDecled, ResNodeDecled, true);
1175 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1176 if (!InFlagDecled) {
1177 emitCode("SDValue InFlag(0, 0);");
1178 InFlagDecled = true;
1179 }
1180 if (NodeHasOptInFlag) {
1181 emitCode("if (HasInFlag) {");
1182 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1183 emitCode("}");
1184 }
1185 }
1186
1187 unsigned ResNo = TmpNo++;
1188
1189 unsigned OpsNo = OpcNo;
1190 std::string CodePrefix;
1191 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1192 std::deque<std::string> After;
1193 std::string NodeName;
1194 if (!isRoot) {
1195 NodeName = "Tmp" + utostr(ResNo);
1196 CodePrefix = "SDValue " + NodeName + "(";
1197 } else {
1198 NodeName = "ResNode";
1199 if (!ResNodeDecled) {
1200 CodePrefix = "SDNode *" + NodeName + " = ";
1201 ResNodeDecled = true;
1202 } else
1203 CodePrefix = NodeName + " = ";
1204 }
1205
1206 std::string Code = "Opc" + utostr(OpcNo);
1207
1208 if (!isRoot || (InputHasChain && !NodeHasChain))
1209 // For call to "getMachineNode()".
1210 Code += ", N->getDebugLoc()";
1211
1212 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1213
1214 // Output order: results, chain, flags
1215 // Result types.
1216 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1217 Code += ", VT" + utostr(VTNo);
1218 emitVT(getEnumName(N->getTypeNum(0)));
1219 }
1220 // Add types for implicit results in physical registers, scheduler will
1221 // care of adding copyfromreg nodes.
1222 for (unsigned i = 0; i < NumDstRegs; i++) {
1223 Record *RR = DstRegs[i];
1224 if (RR->isSubClassOf("Register")) {
1225 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1226 Code += ", " + getEnumName(RVT);
1227 }
1228 }
1229 if (NodeHasChain)
1230 Code += ", MVT::Other";
1231 if (NodeHasOutFlag)
1232 Code += ", MVT::Flag";
1233
1234 // Inputs.
1235 if (IsVariadic) {
1236 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1237 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1238 AllOps.clear();
1239
1240 // Figure out whether any operands at the end of the op list are not
1241 // part of the variable section.
1242 std::string EndAdjust;
1243 if (NodeHasInFlag || HasImpInputs)
1244 EndAdjust = "-1"; // Always has one flag.
1245 else if (NodeHasOptInFlag)
1246 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1247
1248 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1249 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1250
1251 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1252 emitCode("}");
1253 }
1254
1255 // Populate MemRefs with entries for each memory accesses covered by
1256 // this pattern.
1257 if (isRoot && !LSI.empty()) {
1258 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1259 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1260 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1261 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1262 emitCode(MemRefs + "[" + utostr(i) + "] = "
1263 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1264 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1265 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1266 ");");
1267 }
1268
1269 if (NodeHasChain) {
1270 if (IsVariadic)
1271 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1272 else
1273 AllOps.push_back(ChainName);
1274 }
1275
1276 if (IsVariadic) {
1277 if (NodeHasInFlag || HasImpInputs)
1278 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1279 else if (NodeHasOptInFlag) {
1280 emitCode("if (HasInFlag)");
1281 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1282 }
1283 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1284 ".size()";
1285 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1286 AllOps.push_back("InFlag");
1287
1288 unsigned NumOps = AllOps.size();
1289 if (NumOps) {
1290 if (!NodeHasOptInFlag && NumOps < 4) {
1291 for (unsigned i = 0; i != NumOps; ++i)
1292 Code += ", " + AllOps[i];
1293 } else {
1294 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1295 for (unsigned i = 0; i != NumOps; ++i) {
1296 OpsCode += AllOps[i];
1297 if (i != NumOps-1)
1298 OpsCode += ", ";
1299 }
1300 emitCode(OpsCode + " };");
1301 Code += ", Ops" + utostr(OpsNo) + ", ";
1302 if (NodeHasOptInFlag) {
1303 Code += "HasInFlag ? ";
1304 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1305 } else
1306 Code += utostr(NumOps);
1307 }
1308 }
1309
1310 if (!isRoot)
1311 Code += "), 0";
1312
1313 std::vector<std::string> ReplaceFroms;
1314 std::vector<std::string> ReplaceTos;
1315 if (!isRoot) {
1316 NodeOps.push_back("Tmp" + utostr(ResNo));
1317 } else {
1318
1319 if (NodeHasOutFlag) {
1320 if (!InFlagDecled) {
1321 After.push_back("SDValue InFlag(ResNode, " +
1322 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1323 ");");
1324 InFlagDecled = true;
1325 } else
1326 After.push_back("InFlag = SDValue(ResNode, " +
1327 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1328 ");");
1329 }
1330
1331 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1332 ReplaceFroms.push_back("SDValue(" +
1333 FoldedChains[j].first + ".getNode(), " +
1334 utostr(FoldedChains[j].second) +
1335 ")");
1336 ReplaceTos.push_back("SDValue(ResNode, " +
1337 utostr(NumResults+NumDstRegs) + ")");
1338 }
1339
1340 if (NodeHasOutFlag) {
1341 if (FoldedFlag.first != "") {
1342 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1343 utostr(FoldedFlag.second) + ")");
1344 ReplaceTos.push_back("InFlag");
1345 } else {
1346 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1347 ReplaceFroms.push_back("SDValue(N, " +
1348 utostr(NumPatResults + (unsigned)InputHasChain)
1349 + ")");
1350 ReplaceTos.push_back("InFlag");
1351 }
1352 }
1353
1354 if (!ReplaceFroms.empty() && InputHasChain) {
1355 ReplaceFroms.push_back("SDValue(N, " +
1356 utostr(NumPatResults) + ")");
1357 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1358 ChainName + ".getResNo()" + ")");
1359 ChainAssignmentNeeded |= NodeHasChain;
1360 }
1361
1362 // User does not expect the instruction would produce a chain!
1363 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1364 ;
1365 } else if (InputHasChain && !NodeHasChain) {
1366 // One of the inner node produces a chain.
1367 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1368 ReplaceFroms.push_back("SDValue(N, " +
1369 utostr(NumPatResults) + ")");
1370 ReplaceTos.push_back(ChainName);
1371 }
1372 }
1373
1374 if (ChainAssignmentNeeded) {
1375 // Remember which op produces the chain.
1376 std::string ChainAssign;
1377 if (!isRoot)
1378 ChainAssign = ChainName + " = SDValue(" + NodeName +
1379 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1380 else
1381 ChainAssign = ChainName + " = SDValue(" + NodeName +
1382 ", " + utostr(NumResults+NumDstRegs) + ");";
1383
1384 After.push_front(ChainAssign);
1385 }
1386
1387 if (ReplaceFroms.size() == 1) {
1388 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1389 ReplaceTos[0] + ");");
1390 } else if (!ReplaceFroms.empty()) {
1391 After.push_back("const SDValue Froms[] = {");
1392 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1393 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1394 After.push_back("};");
1395 After.push_back("const SDValue Tos[] = {");
1396 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1397 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1398 After.push_back("};");
1399 After.push_back("ReplaceUses(Froms, Tos, " +
1400 itostr(ReplaceFroms.size()) + ");");
1401 }
1402
1403 // We prefer to use SelectNodeTo since it avoids allocation when
1404 // possible and it avoids CSE map recalculation for the node's
1405 // users, however it's tricky to use in a non-root context.
1406 //
1407 // We also don't use SelectNodeTo if the pattern replacement is being
1408 // used to jettison a chain result, since morphing the node in place
1409 // would leave users of the chain dangling.
1410 //
1411 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1412 Code = "CurDAG->getMachineNode(" + Code;
1413 } else {
1414 Code = "CurDAG->SelectNodeTo(N, " + Code;
1415 }
1416 if (isRoot) {
1417 if (After.empty())
1418 CodePrefix = "return ";
1419 else
1420 After.push_back("return ResNode;");
1421 }
1422
1423 emitCode(CodePrefix + Code + ");");
1424
1425 if (GenDebug) {
1426 if (!isRoot) {
1427 emitCode("CurDAG->setSubgraphColor(" +
1428 NodeName +".getNode(), \"yellow\");");
1429 emitCode("CurDAG->setSubgraphColor(" +
1430 NodeName +".getNode(), \"black\");");
1431 } else {
1432 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1433 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1434 }
1435 }
1436
1437 for (unsigned i = 0, e = After.size(); i != e; ++i)
1438 emitCode(After[i]);
1439
1440 return NodeOps;
1441 }
1442 if (Op->isSubClassOf("SDNodeXForm")) {
1443 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1444 // PatLeaf node - the operand may or may not be a leaf node. But it should
1445 // behave like one.
1446 std::vector<std::string> Ops =
1447 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1448 ResNodeDecled, true);
1449 unsigned ResNo = TmpNo++;
1450 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1451 + "(" + Ops.back() + ".getNode());");
1452 NodeOps.push_back("Tmp" + utostr(ResNo));
1453 if (isRoot)
1454 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1455 return NodeOps;
1456 }
1457
1458 N->dump();
1459 errs() << "\n";
1460 throw std::string("Unknown node in result pattern!");
1461}
1462
1463
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001464/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1465/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001466/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001467void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001468 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001469 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001470 std::vector<std::string> &TargetOpcodes,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001471 std::vector<std::string> &TargetVTs,
1472 bool &OutputIsVariadic,
1473 unsigned &NumInputRootOps) {
1474 OutputIsVariadic = false;
1475 NumInputRootOps = 0;
1476
Dan Gohman22bb3112008-08-22 00:20:26 +00001477 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001478 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001479 GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001480 TargetOpcodes, TargetVTs,
1481 OutputIsVariadic, NumInputRootOps);
Evan Chengb915f312005-12-09 22:45:35 +00001482
Chris Lattner8fc35682005-09-23 23:16:51 +00001483 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001484 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001485 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001486
Chris Lattnerc87bf382010-02-14 21:11:53 +00001487 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1488 // diagnostics, which we know are impossible at this point.
Chris Lattner200c57e2008-01-05 22:58:54 +00001489 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001490
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001491 // At this point, we know that we structurally match the pattern, but the
1492 // types of the nodes may not match. Figure out the fewest number of type
1493 // comparisons we need to emit. For example, if there is only one integer
1494 // type supported by a target, there should be no type comparisons at all for
1495 // integer patterns!
1496 //
1497 // To figure out the fewest number of type checks needed, clone the pattern,
1498 // remove the types, then perform type inference on the pattern as a whole.
1499 // If there are unresolved types, emit an explicit check for those types,
1500 // apply the type to the tree, then rerun type inference. Iterate until all
1501 // types are resolved.
1502 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001503 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001504 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001505
1506 do {
1507 // Resolve/propagate as many types as possible.
1508 try {
1509 bool MadeChange = true;
1510 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001511 MadeChange = Pat->ApplyTypeConstraints(TP,
1512 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001513 } catch (...) {
1514 assert(0 && "Error: could not find consistent types for something we"
1515 " already decided was ok!");
1516 abort();
1517 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001518
Chris Lattner7e82f132005-10-15 21:34:21 +00001519 // Insert a check for an unresolved type and add it to the tree. If we find
1520 // an unresolved type to add a check for, this returns true and we iterate,
1521 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001522 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001523
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001524 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001525 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001526 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001527}
1528
Chris Lattner24e00a42006-01-29 04:41:05 +00001529/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1530/// a line causes any of them to be empty, remove them and return true when
1531/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001532static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001533 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001534 &Patterns) {
1535 bool ErasedPatterns = false;
1536 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1537 Patterns[i].second.pop_back();
1538 if (Patterns[i].second.empty()) {
1539 Patterns.erase(Patterns.begin()+i);
1540 --i; --e;
1541 ErasedPatterns = true;
1542 }
1543 }
1544 return ErasedPatterns;
1545}
1546
Chris Lattner8bc74722006-01-29 04:25:26 +00001547/// EmitPatterns - Emit code for at least one pattern, but try to group common
1548/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001549void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001550 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001551 &Patterns, unsigned Indent,
Daniel Dunbar1a551802009-07-03 00:10:29 +00001552 raw_ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001553 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001554 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001555 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001556
1557 if (Patterns.empty()) return;
1558
Chris Lattner24e00a42006-01-29 04:41:05 +00001559 // Figure out how many patterns share the next code line. Explicitly copy
1560 // FirstCodeLine so that we don't invalidate a reference when changing
1561 // Patterns.
1562 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001563 unsigned LastMatch = Patterns.size()-1;
1564 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1565 --LastMatch;
1566
1567 // If not all patterns share this line, split the list into two pieces. The
1568 // first chunk will use this line, the second chunk won't.
1569 if (LastMatch != 0) {
1570 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1571 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1572
1573 // FIXME: Emit braces?
1574 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001575 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001576 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1577 Pattern.getSrcPattern()->print(OS);
1578 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1579 Pattern.getDstPattern()->print(OS);
1580 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001581 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001582 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001583 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001584 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001585 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001586 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001587 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001588 }
Evan Cheng676d7312006-08-26 00:59:04 +00001589 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001590 OS << std::string(Indent, ' ') << "{\n";
1591 Indent += 2;
1592 }
1593 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001594 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001595 Indent -= 2;
1596 OS << std::string(Indent, ' ') << "}\n";
1597 }
1598
1599 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001600 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001601 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1602 Pattern.getSrcPattern()->print(OS);
1603 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1604 Pattern.getDstPattern()->print(OS);
1605 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001606 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001607 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001608 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001609 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001610 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001611 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001612 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001613 }
1614 EmitPatterns(Other, Indent, OS);
1615 return;
1616 }
1617
Chris Lattner24e00a42006-01-29 04:41:05 +00001618 // Remove this code from all of the patterns that share it.
1619 bool ErasedPatterns = EraseCodeLine(Patterns);
1620
Evan Cheng676d7312006-08-26 00:59:04 +00001621 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001622
1623 // Otherwise, every pattern in the list has this line. Emit it.
1624 if (!isPredicate) {
1625 // Normal code.
1626 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1627 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001628 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1629
1630 // If the next code line is another predicate, and if all of the pattern
1631 // in this group share the same next line, emit it inline now. Do this
1632 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001633 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00001634 // Check that all of the patterns in Patterns end with the same predicate.
Chris Lattner24e00a42006-01-29 04:41:05 +00001635 bool AllEndWithSamePredicate = true;
1636 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1637 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1638 AllEndWithSamePredicate = false;
1639 break;
1640 }
1641 // If all of the predicates aren't the same, we can't share them.
1642 if (!AllEndWithSamePredicate) break;
1643
1644 // Otherwise we can. Emit it shared now.
1645 OS << " &&\n" << std::string(Indent+4, ' ')
1646 << Patterns.back().second.back().second;
1647 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001648 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001649
1650 OS << ") {\n";
1651 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001652 }
1653
1654 EmitPatterns(Patterns, Indent, OS);
1655
1656 if (isPredicate)
1657 OS << std::string(Indent-2, ' ') << "}\n";
1658}
1659
Evan Cheng892aaf82006-11-08 23:01:03 +00001660static std::string getLegalCName(std::string OpName) {
1661 std::string::size_type pos = OpName.find("::");
1662 if (pos != std::string::npos)
1663 OpName.replace(pos, 2, "_");
1664 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001665}
1666
Daniel Dunbar1a551802009-07-03 00:10:29 +00001667void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001668 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner6cefb772008-01-05 22:25:12 +00001669
Dan Gohman1e0ee4b2008-08-20 21:45:57 +00001670 // Get the namespace to insert instructions into.
1671 std::string InstNS = Target.getInstNamespace();
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001672 if (!InstNS.empty()) InstNS += "::";
1673
Chris Lattner602f6922006-01-04 00:25:00 +00001674 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001675 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001676 // All unique target node emission functions.
1677 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001678 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001679 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001680 const PatternToMatch &Pattern = *I;
Chris Lattnerc87bf382010-02-14 21:11:53 +00001681
Chris Lattner6cefb772008-01-05 22:25:12 +00001682 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001683 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001684 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001685 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001686 } else {
1687 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001688 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001689 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001690 push_back(&Pattern);
Chris Lattner200c57e2008-01-05 22:58:54 +00001691 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001692 std::vector<Record*> OpNodes = CP->getRootNodes();
1693 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001694 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1695 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001696 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001697 }
1698 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001699 errs() << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001700 Node->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001701 errs() << "' on tree pattern '";
1702 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001703 exit(1);
1704 }
1705 }
1706 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001707
1708 // For each opcode, there might be multiple select functions, one per
1709 // ValueType of the node (or its first operand if it doesn't produce a
1710 // non-chain result.
1711 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1712
Chris Lattner602f6922006-01-04 00:25:00 +00001713 // Emit one Select_* method for each top-level opcode. We do this instead of
1714 // emitting one giant switch statement to support compilers where this will
1715 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001716 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001717 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1718 PBOI != E; ++PBOI) {
1719 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001720 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001721 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1722
Chris Lattner706d2d32006-08-09 16:44:44 +00001723 // Split them into groups by type.
Owen Anderson825b72b2009-08-11 20:47:22 +00001724 std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001725 std::vector<const PatternToMatch*> > PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001726 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001727 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001728 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner9783d622008-08-26 07:01:28 +00001729 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Chris Lattner706d2d32006-08-09 16:44:44 +00001730 }
1731
Owen Anderson825b72b2009-08-11 20:47:22 +00001732 for (std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001733 std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001734 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1735 ++II) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001736 MVT::SimpleValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001737 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman0540e172008-10-15 06:17:21 +00001738 typedef std::pair<unsigned, std::string> CodeLine;
1739 typedef std::vector<CodeLine> CodeList;
1740 typedef CodeList::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001741
Chris Lattner60d81392008-01-05 22:30:17 +00001742 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001743 std::vector<std::vector<std::string> > PatternOpcodes;
1744 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001745 std::vector<std::set<std::string> > PatternDecls;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001746 std::vector<bool> OutputIsVariadicFlags;
1747 std::vector<unsigned> NumInputRootOpsCounts;
Chris Lattner706d2d32006-08-09 16:44:44 +00001748 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1749 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001750 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001751 std::vector<std::string> TargetOpcodes;
1752 std::vector<std::string> TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001753 bool OutputIsVariadic;
1754 unsigned NumInputRootOps;
Chris Lattner706d2d32006-08-09 16:44:44 +00001755 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001756 TargetOpcodes, TargetVTs,
1757 OutputIsVariadic, NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001758 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1759 PatternDecls.push_back(GeneratedDecl);
1760 PatternOpcodes.push_back(TargetOpcodes);
1761 PatternVTs.push_back(TargetVTs);
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001762 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1763 NumInputRootOpsCounts.push_back(NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001764 }
1765
Chris Lattner706d2d32006-08-09 16:44:44 +00001766 // Factor target node emission code (emitted by EmitResultCode) into
1767 // separate functions. Uniquing and share them among all instruction
1768 // selection routines.
1769 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1770 CodeList &GeneratedCode = CodeForPatterns[i].second;
1771 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1772 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001773 std::set<std::string> Decls = PatternDecls[i];
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001774 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1775 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001776 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001777 int CodeSize = (int)GeneratedCode.size();
1778 int LastPred = -1;
1779 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001780 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001781 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001782 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1783 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001784 }
1785
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001786 std::string CalleeCode = "(SDNode *N";
Evan Cheng9ade2182006-08-26 05:34:46 +00001787 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001788 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1789 CalleeCode += ", unsigned Opc" + utostr(j);
1790 CallerCode += ", " + TargetOpcodes[j];
1791 }
1792 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Owen Anderson69110c92009-09-11 09:01:57 +00001793 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
Chris Lattner706d2d32006-08-09 16:44:44 +00001794 CallerCode += ", " + TargetVTs[j];
1795 }
Evan Chengf5493192006-08-26 01:02:19 +00001796 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001797 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001798 std::string Name = *I;
Dan Gohman475871a2008-07-27 21:46:04 +00001799 CalleeCode += ", SDValue &" + Name;
Evan Cheng676d7312006-08-26 00:59:04 +00001800 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001801 }
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001802
1803 if (OutputIsVariadic) {
1804 CalleeCode += ", unsigned NumInputRootOps";
1805 CallerCode += ", " + utostr(NumInputRootOps);
1806 }
1807
Chris Lattner706d2d32006-08-09 16:44:44 +00001808 CallerCode += ");";
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001809 CalleeCode += ") {\n";
Evan Cheng676d7312006-08-26 00:59:04 +00001810
1811 for (std::vector<std::string>::const_reverse_iterator
1812 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1813 CalleeCode += " " + *I + "\n";
1814
Evan Chengf5493192006-08-26 01:02:19 +00001815 for (int j = LastPred+1; j < CodeSize; ++j)
1816 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001817 for (int j = LastPred+1; j < CodeSize; ++j)
1818 GeneratedCode.pop_back();
1819 CalleeCode += "}\n";
1820
1821 // Uniquing the emission routines.
1822 unsigned EmitFuncNum;
1823 std::map<std::string, unsigned>::iterator EFI =
1824 EmitFunctions.find(CalleeCode);
1825 if (EFI != EmitFunctions.end()) {
1826 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001827 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001828 EmitFuncNum = EmitFunctions.size();
1829 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001830 // Prevent emission routines from being inlined to reduce selection
1831 // routines stack frame sizes.
1832 OS << "DISABLE_INLINE ";
Evan Cheng06d64702006-08-11 08:59:35 +00001833 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001834 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001835
Chris Lattner706d2d32006-08-09 16:44:44 +00001836 // Replace the emission code within selection routines with calls to the
1837 // emission functions.
Chris Lattnera0cdf172010-02-13 20:06:50 +00001838 if (GenDebug)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001839 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001840 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1841 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1842 if (GenDebug) {
1843 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1844 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1845 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1846 GeneratedCode.push_back(std::make_pair(0, "}"));
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001847 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001848 }
1849 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001850 }
1851
Chris Lattner706d2d32006-08-09 16:44:44 +00001852 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001853 std::string OpVTStr;
Owen Anderson825b72b2009-08-11 20:47:22 +00001854 if (OpVT == MVT::iPTR) {
Chris Lattner33a40042006-11-14 22:17:10 +00001855 OpVTStr = "_iPTR";
Owen Anderson825b72b2009-08-11 20:47:22 +00001856 } else if (OpVT == MVT::iPTRAny) {
Mon P Wange3b3a722008-07-30 04:36:53 +00001857 OpVTStr = "_iPTRAny";
Owen Anderson825b72b2009-08-11 20:47:22 +00001858 } else if (OpVT == MVT::isVoid) {
Chris Lattner33a40042006-11-14 22:17:10 +00001859 // Nodes with a void result actually have a first result type of either
1860 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1861 // void to this case, we handle it specially here.
1862 } else {
Owen Anderson825b72b2009-08-11 20:47:22 +00001863 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
Chris Lattner33a40042006-11-14 22:17:10 +00001864 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001865 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1866 OpcodeVTMap.find(OpName);
1867 if (OpVTI == OpcodeVTMap.end()) {
1868 std::vector<std::string> VTSet;
1869 VTSet.push_back(OpVTStr);
1870 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1871 } else
1872 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001873
Dan Gohman0540e172008-10-15 06:17:21 +00001874 // We want to emit all of the matching code now. However, we want to emit
1875 // the matches in order of minimal cost. Sort the patterns so the least
1876 // cost one is at the start.
1877 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1878 PatternSortingPredicate(CGP));
1879
1880 // Scan the code to see if all of the patterns are reachable and if it is
1881 // possible that the last one might not match.
1882 bool mightNotMatch = true;
1883 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1884 CodeList &GeneratedCode = CodeForPatterns[i].second;
1885 mightNotMatch = false;
1886
1887 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1888 if (GeneratedCode[j].first == 1) { // predicate.
1889 mightNotMatch = true;
1890 break;
1891 }
1892 }
1893
1894 // If this pattern definitely matches, and if it isn't the last one, the
1895 // patterns after it CANNOT ever match. Error out.
1896 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001897 errs() << "Pattern '";
1898 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1899 errs() << "' is impossible to select!\n";
Dan Gohman0540e172008-10-15 06:17:21 +00001900 exit(1);
1901 }
1902 }
1903
Chris Lattner706d2d32006-08-09 16:44:44 +00001904 // Loop through and reverse all of the CodeList vectors, as we will be
1905 // accessing them from their logical front, but accessing the end of a
1906 // vector is more efficient.
1907 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1908 CodeList &GeneratedCode = CodeForPatterns[i].second;
1909 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001910 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001911
1912 // Next, reverse the list of patterns itself for the same reason.
1913 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1914
Dan Gohman63e3e632009-01-29 01:37:18 +00001915 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001916 << OpVTStr << "(SDNode *N) {\n";
Dan Gohman63e3e632009-01-29 01:37:18 +00001917
Chris Lattner706d2d32006-08-09 16:44:44 +00001918 // Emit all of the patterns now, grouped together to share code.
1919 EmitPatterns(CodeForPatterns, 2, OS);
1920
Chris Lattner64906972006-09-21 18:28:27 +00001921 // If the last pattern has predicates (which could fail) emit code to
1922 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001923 if (mightNotMatch) {
Dan Gohman31bd42b2008-09-27 23:53:14 +00001924 OS << "\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00001925 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1926 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
Dan Gohman31bd42b2008-09-27 23:53:14 +00001927 OpName != "ISD::INTRINSIC_VOID")
1928 OS << " CannotYetSelect(N);\n";
1929 else
1930 OS << " CannotYetSelectIntrinsic(N);\n";
1931
1932 OS << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001933 }
1934 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001935 }
Chris Lattner602f6922006-01-04 00:25:00 +00001936 }
1937
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001938 OS << "// The main instruction selector code.\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001939 << "SDNode *SelectCode(SDNode *N) {\n"
1940 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1941 << " switch (N->getOpcode()) {\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001942 << " default:\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001943 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001944 << " break;\n"
1945 << " case ISD::EntryToken: // These nodes remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001946 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001947 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001948 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001949 << " case ISD::TargetConstant:\n"
Nate Begemane1795842008-02-14 08:57:00 +00001950 << " case ISD::TargetConstantFP:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001951 << " case ISD::TargetConstantPool:\n"
1952 << " case ISD::TargetFrameIndex:\n"
Bill Wendling056292f2008-09-16 21:48:12 +00001953 << " case ISD::TargetExternalSymbol:\n"
Dan Gohman8c2b5252009-10-30 01:27:03 +00001954 << " case ISD::TargetBlockAddress:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001955 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001956 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohman8be6bbe2008-11-05 04:14:16 +00001957 << " case ISD::TargetGlobalAddress:\n"
1958 << " case ISD::TokenFactor:\n"
1959 << " case ISD::CopyFromReg:\n"
1960 << " case ISD::CopyToReg: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001961 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001962 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001963 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001964 << " case ISD::AssertZext: {\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001965 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001966 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001967 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001968 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohmancd920d92008-07-02 23:23:19 +00001969 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Chengda47e6e2008-03-15 00:03:38 +00001970 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001971
Chris Lattner602f6922006-01-04 00:25:00 +00001972 // Loop over all of the case statements, emiting a call to each method we
1973 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001974 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001975 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1976 PBOI != E; ++PBOI) {
1977 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001978 // Potentially multiple versions of select for this opcode. One for each
1979 // ValueType of the node (or its first true operand if it doesn't produce a
1980 // result.
1981 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1982 OpcodeVTMap.find(OpName);
1983 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00001984 OS << " case " << OpName << ": {\n";
Dale Johannesen3b895cf2009-05-12 22:32:29 +00001985 // If we have only one variant and it's the default, elide the
1986 // switch. Marginally faster, and makes MSVC happier.
1987 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1988 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1989 OS << " break;\n";
1990 OS << " }\n";
1991 continue;
1992 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001993 // Keep track of whether we see a pattern that has an iPtr result.
1994 bool HasPtrPattern = false;
1995 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00001996
Evan Cheng425e8c72007-09-04 20:18:28 +00001997 OS << " switch (NVT) {\n";
1998 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1999 std::string &VTStr = OpVTs[i];
2000 if (VTStr.empty()) {
2001 HasDefaultPattern = true;
2002 continue;
2003 }
Chris Lattner717a6112006-11-14 21:50:27 +00002004
Evan Cheng425e8c72007-09-04 20:18:28 +00002005 // If this is a match on iPTR: don't emit it directly, we need special
2006 // code.
2007 if (VTStr == "_iPTR") {
2008 HasPtrPattern = true;
2009 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00002010 }
Owen Anderson825b72b2009-08-11 20:47:22 +00002011 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng425e8c72007-09-04 20:18:28 +00002012 << " return Select_" << getLegalCName(OpName)
2013 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002014 }
Evan Cheng425e8c72007-09-04 20:18:28 +00002015 OS << " default:\n";
2016
2017 // If there is an iPTR result version of this pattern, emit it here.
2018 if (HasPtrPattern) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002019 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00002020 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2021 }
2022 if (HasDefaultPattern) {
2023 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2024 }
2025 OS << " break;\n";
2026 OS << " }\n";
2027 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002028 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00002029 }
Chris Lattner81303322005-09-23 19:36:15 +00002030
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002031 OS << " } // end of big switch.\n\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00002032 << " if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2033 << " N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2034 << " N->getOpcode() != ISD::INTRINSIC_VOID) {\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00002035 << " CannotYetSelect(N);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00002036 << " } else {\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00002037 << " CannotYetSelectIntrinsic(N);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00002038 << " }\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00002039 << " return NULL;\n"
2040 << "}\n\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002041}
2042
Daniel Dunbar1a551802009-07-03 00:10:29 +00002043void DAGISelEmitter::run(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00002044 EmitSourceFileHeader("DAG Instruction Selector for the " +
2045 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002046
Chris Lattner1f39e292005-09-14 00:09:24 +00002047 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2048 << "// *** instruction selector class. These functions are really "
2049 << "methods.\n\n";
Chris Lattnerf8dc0612008-02-03 06:49:24 +00002050
Roman Levenstein6422e8a2008-05-14 10:17:11 +00002051 OS << "// Include standard, target-independent definitions and methods used\n"
2052 << "// by the instruction selector.\n";
Mike Stumpfe095f32009-05-04 18:40:41 +00002053 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00002054
Chris Lattner443e3f92008-01-05 22:54:53 +00002055 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00002056 EmitPredicateFunctions(OS);
2057
Chris Lattner569f1212009-08-23 04:44:11 +00002058 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
Chris Lattnerfe718932008-01-06 01:10:31 +00002059 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00002060 I != E; ++I) {
Chris Lattner569f1212009-08-23 04:44:11 +00002061 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
2062 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
2063 DEBUG(errs() << "\n");
Bill Wendlingf5da1332006-12-07 22:21:48 +00002064 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00002065
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002066 // At this point, we have full information about the 'Patterns' we need to
2067 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002068 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002069 EmitInstructionSelector(OS);
2070
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002071}