blob: 243700fdb71fc647f14e1616522e93339fb90a24 [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"
Chris Lattnerda272d12010-02-15 08:04:42 +000015#include "DAGISelMatcher.h"
Chris Lattner54cb8fd2005-09-07 23:44:43 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
David Greene8ad4c002008-10-27 21:56:29 +000018#include "llvm/Support/CommandLine.h"
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include "llvm/Support/Debug.h"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000020#include "llvm/Support/MathExtras.h"
David Greene8ad4c002008-10-27 21:56:29 +000021#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000022#include <algorithm>
Dan Gohman95d11092008-07-07 21:00:17 +000023#include <deque>
Daniel Dunbar1a551802009-07-03 00:10:29 +000024#include <iostream>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000025using namespace llvm;
26
Chris Lattner3d4ad292009-08-07 22:27:19 +000027static cl::opt<bool>
28GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
David Greene8ad4c002008-10-27 21:56:29 +000029
Chris Lattnerca559d02005-09-08 21:03:01 +000030//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +000031// DAGISelEmitter Helper methods
Chris Lattner54cb8fd2005-09-07 23:44:43 +000032//
33
Dan Gohmaneeb3a002010-01-05 01:24:18 +000034/// getNodeName - The top level Select_* functions have an "SDNode* N"
35/// argument. When expanding the pattern-matching code, the intermediate
36/// variables have type SDValue. This function provides a uniform way to
37/// reference the underlying "SDNode *" for both cases.
38static std::string getNodeName(const std::string &S) {
39 if (S == "N") return S;
40 return S + ".getNode()";
41}
42
43/// getNodeValue - Similar to getNodeName, except it provides a uniform
44/// way to access the SDValue for both cases.
45static std::string getValueName(const std::string &S) {
46 if (S == "N") return "SDValue(N, 0)";
47 return S;
48}
49
Chris Lattner6cefb772008-01-05 22:25:12 +000050/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
51/// ComplexPattern.
52static bool NodeIsComplexPattern(TreePatternNode *N) {
Evan Cheng0fc71982005-12-08 02:00:36 +000053 return (N->isLeaf() &&
54 dynamic_cast<DefInit*>(N->getLeafValue()) &&
55 static_cast<DefInit*>(N->getLeafValue())->getDef()->
56 isSubClassOf("ComplexPattern"));
57}
58
Evan Cheng0fc71982005-12-08 02:00:36 +000059
Chris Lattner05814af2005-09-28 17:57:56 +000060/// getPatternSize - Return the 'size' of this pattern. We want to match large
61/// patterns before small ones. This is used to determine the size of a
62/// pattern.
Chris Lattnerfe718932008-01-06 01:10:31 +000063static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Owen Andersone50ed302009-08-10 22:56:29 +000064 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
65 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +000066 P->getExtTypeNum(0) == MVT::isVoid ||
67 P->getExtTypeNum(0) == MVT::Flag ||
68 P->getExtTypeNum(0) == MVT::iPTR ||
69 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +000070 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +000071 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +000072 // If the root node is a ConstantSDNode, increases its size.
73 // e.g. (set R32:$dst, 0).
74 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000075 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +000076
77 // FIXME: This is a hack to statically increase the priority of patterns
78 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
79 // Later we can allow complexity / cost for each pattern to be (optionally)
80 // specified. To get best possible pattern match we'll need to dynamically
81 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner47661322010-02-14 22:22:58 +000082 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000083 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +000084 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +000085
86 // If this node has some predicate function that must match, it adds to the
87 // complexity of this node.
Dan Gohman0540e172008-10-15 06:17:21 +000088 if (!P->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +000089 ++Size;
90
Chris Lattner05814af2005-09-28 17:57:56 +000091 // Count children in the count if they are also nodes.
92 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
93 TreePatternNode *Child = P->getChild(i);
Owen Anderson825b72b2009-08-11 20:47:22 +000094 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner6cefb772008-01-05 22:25:12 +000095 Size += getPatternSize(Child, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000096 else if (Child->isLeaf()) {
97 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000098 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +000099 else if (NodeIsComplexPattern(Child))
Chris Lattner6cefb772008-01-05 22:25:12 +0000100 Size += getPatternSize(Child, CGP);
Dan Gohman0540e172008-10-15 06:17:21 +0000101 else if (!Child->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +0000102 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +0000103 }
Chris Lattner05814af2005-09-28 17:57:56 +0000104 }
105
106 return Size;
107}
108
109/// getResultPatternCost - Compute the number of instructions for this pattern.
110/// This is a temporary hack. We should really include the instruction
111/// latencies in this calculation.
Chris Lattner6cefb772008-01-05 22:25:12 +0000112static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000113 CodeGenDAGPatterns &CGP) {
Chris Lattner05814af2005-09-28 17:57:56 +0000114 if (P->isLeaf()) return 0;
115
Evan Chengfbad7082006-02-18 02:33:09 +0000116 unsigned Cost = 0;
117 Record *Op = P->getOperator();
118 if (Op->isSubClassOf("Instruction")) {
119 Cost++;
Chris Lattner6cefb772008-01-05 22:25:12 +0000120 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohman533297b2009-10-29 18:10:34 +0000121 if (II.usesCustomInserter)
Evan Chengfbad7082006-02-18 02:33:09 +0000122 Cost += 10;
123 }
Chris Lattner05814af2005-09-28 17:57:56 +0000124 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000125 Cost += getResultPatternCost(P->getChild(i), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000126 return Cost;
127}
128
Evan Chenge6f32032006-07-19 00:24:41 +0000129/// getResultPatternCodeSize - Compute the code size of instructions for this
130/// pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000131static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000132 CodeGenDAGPatterns &CGP) {
Evan Chenge6f32032006-07-19 00:24:41 +0000133 if (P->isLeaf()) return 0;
134
135 unsigned Cost = 0;
136 Record *Op = P->getOperator();
137 if (Op->isSubClassOf("Instruction")) {
138 Cost += Op->getValueAsInt("CodeSize");
139 }
140 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000141 Cost += getResultPatternSize(P->getChild(i), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000142 return Cost;
143}
144
Chris Lattner05814af2005-09-28 17:57:56 +0000145// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
146// In particular, we want to match maximal patterns first and lowest cost within
147// a particular complexity first.
148struct PatternSortingPredicate {
Chris Lattnerfe718932008-01-06 01:10:31 +0000149 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
150 CodeGenDAGPatterns &CGP;
Evan Cheng0fc71982005-12-08 02:00:36 +0000151
Dan Gohman0540e172008-10-15 06:17:21 +0000152 typedef std::pair<unsigned, std::string> CodeLine;
153 typedef std::vector<CodeLine> CodeList;
154 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
155
156 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
157 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
158 const PatternToMatch *LHS = LHSPair.first;
159 const PatternToMatch *RHS = RHSPair.first;
160
Chris Lattner6cefb772008-01-05 22:25:12 +0000161 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
162 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Evan Chengc81d2a02006-04-19 20:36:09 +0000163 LHSSize += LHS->getAddedComplexity();
164 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +0000165 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
166 if (LHSSize < RHSSize) return false;
167
168 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner6cefb772008-01-05 22:25:12 +0000169 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
170 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000171 if (LHSCost < RHSCost) return true;
172 if (LHSCost > RHSCost) return false;
173
Chris Lattner6cefb772008-01-05 22:25:12 +0000174 return getResultPatternSize(LHS->getDstPattern(), CGP) <
175 getResultPatternSize(RHS->getDstPattern(), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000176 }
177};
178
Jim Grosbach54f30222009-03-25 23:28:33 +0000179/// getRegisterValueType - Look up and return the ValueType of the specified
180/// register. If the register is a member of multiple register classes which
Owen Anderson825b72b2009-08-11 20:47:22 +0000181/// have different associated types, return MVT::Other.
182static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000183 bool FoundRC = false;
Owen Anderson825b72b2009-08-11 20:47:22 +0000184 MVT::SimpleValueType VT = MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000185 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
186 std::vector<CodeGenRegisterClass>::const_iterator RC;
187 std::vector<Record*>::const_iterator Element;
188
189 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
190 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
191 if (Element != (*RC).Elements.end()) {
192 if (!FoundRC) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000193 FoundRC = true;
Jim Grosbach54f30222009-03-25 23:28:33 +0000194 VT = (*RC).getValueTypeNum(0);
195 } else {
196 // In multiple RC's
197 if (VT != (*RC).getValueTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000198 // Types of the RC's do not agree. Return MVT::Other. The
Jim Grosbach54f30222009-03-25 23:28:33 +0000199 // target is responsible for handling this.
Owen Anderson825b72b2009-08-11 20:47:22 +0000200 return MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000201 }
202 }
203 }
204 }
205 return VT;
Evan Cheng66a48bb2005-12-01 00:18:45 +0000206}
207
Evan Chengf9d03182008-07-03 08:39:51 +0000208static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
209 return CGP.getSDNodeInfo(Op).getEnumName();
210}
211
Chris Lattnerdc32f982008-01-05 22:43:57 +0000212//===----------------------------------------------------------------------===//
Chris Lattner443e3f92008-01-05 22:54:53 +0000213// Node Transformation emitter implementation.
214//
Daniel Dunbar1a551802009-07-03 00:10:29 +0000215void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
Chris Lattner443e3f92008-01-05 22:54:53 +0000216 // Walk the pattern fragments, adding them to a map, which sorts them by
217 // name.
Chris Lattnerfe718932008-01-06 01:10:31 +0000218 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner443e3f92008-01-05 22:54:53 +0000219 NXsByNameTy NXsByName;
220
Chris Lattnerfe718932008-01-06 01:10:31 +0000221 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner443e3f92008-01-05 22:54:53 +0000222 I != E; ++I)
223 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
224
225 OS << "\n// Node transformations.\n";
226
227 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
228 I != E; ++I) {
229 Record *SDNode = I->second.first;
230 std::string Code = I->second.second;
231
232 if (Code.empty()) continue; // Empty code? Skip it.
233
Chris Lattner200c57e2008-01-05 22:58:54 +0000234 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner443e3f92008-01-05 22:54:53 +0000235 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
236
Dan Gohman475871a2008-07-27 21:46:04 +0000237 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner443e3f92008-01-05 22:54:53 +0000238 << ") {\n";
239 if (ClassName != "SDNode")
240 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
241 OS << Code << "\n}\n";
242 }
243}
244
245//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +0000246// Predicate emitter implementation.
247//
248
Daniel Dunbar1a551802009-07-03 00:10:29 +0000249void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
Chris Lattnerdc32f982008-01-05 22:43:57 +0000250 OS << "\n// Predicate functions.\n";
251
252 // Walk the pattern fragments, adding them to a map, which sorts them by
253 // name.
254 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
255 PFsByNameTy PFsByName;
256
Chris Lattnerfe718932008-01-06 01:10:31 +0000257 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000258 I != E; ++I)
259 PFsByName.insert(std::make_pair(I->first->getName(), *I));
260
261
262 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
263 I != E; ++I) {
264 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
265 TreePattern *P = I->second.second;
266
267 // If there is a code init for this fragment, emit the predicate code.
268 std::string Code = PatFragRecord->getValueAsCode("Predicate");
269 if (Code.empty()) continue;
270
271 if (P->getOnlyTree()->isLeaf())
272 OS << "inline bool Predicate_" << PatFragRecord->getName()
273 << "(SDNode *N) {\n";
274 else {
275 std::string ClassName =
Chris Lattner200c57e2008-01-05 22:58:54 +0000276 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000277 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
278
279 OS << "inline bool Predicate_" << PatFragRecord->getName()
280 << "(SDNode *" << C2 << ") {\n";
281 if (ClassName != "SDNode")
282 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
283 }
284 OS << Code << "\n}\n";
285 }
286
287 OS << "\n\n";
288}
289
290
291//===----------------------------------------------------------------------===//
292// PatternCodeEmitter implementation.
293//
Evan Chengb915f312005-12-09 22:45:35 +0000294class PatternCodeEmitter {
295private:
Chris Lattnerfe718932008-01-06 01:10:31 +0000296 CodeGenDAGPatterns &CGP;
Evan Chengb915f312005-12-09 22:45:35 +0000297
Evan Cheng58e84a62005-12-14 22:02:59 +0000298 // Predicates.
Dan Gohman22bb3112008-08-22 00:20:26 +0000299 std::string PredicateCheck;
Evan Cheng59413202006-04-19 18:07:24 +0000300 // Pattern cost.
301 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +0000302 // Instruction selector pattern.
303 TreePatternNode *Pattern;
304 // Matched instruction.
305 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000306
Evan Chengb915f312005-12-09 22:45:35 +0000307 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +0000308 std::map<std::string, std::string> VariableMap;
309 // Node to operator mapping
310 std::map<std::string, Record*> OperatorMap;
Evan Chenga58891f2008-02-05 22:50:29 +0000311 // Name of the folded node which produces a flag.
312 std::pair<std::string, unsigned> FoldedFlag;
Evan Chengb915f312005-12-09 22:45:35 +0000313 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +0000314 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +0000315 // Original input chain(s).
316 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +0000317 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +0000318
Dan Gohman69de1932008-02-06 22:27:42 +0000319 /// LSI - Load/Store information.
320 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
321 /// for each memory access. This facilitates the use of AliasAnalysis in
322 /// the backend.
323 std::vector<std::string> LSI;
324
Evan Cheng676d7312006-08-26 00:59:04 +0000325 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000326 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000327 /// tested, and if true, the match fails) [when 1], or normal code to emit
328 /// [when 0], or initialization code to emit [when 2].
329 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman475871a2008-07-27 21:46:04 +0000330 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Evan Cheng21ad3922006-02-07 00:37:41 +0000331 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000332 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000333 /// TargetOpcodes - The target specific opcodes used by the resulting
334 /// instructions.
335 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000336 std::vector<std::string> &TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000337 /// OutputIsVariadic - Records whether the instruction output pattern uses
338 /// variable_ops. This requires that the Emit function be passed an
339 /// additional argument to indicate where the input varargs operands
340 /// begin.
341 bool &OutputIsVariadic;
342 /// NumInputRootOps - Records the number of operands the root node of the
343 /// input pattern has. This information is used in the generated code to
344 /// pass to Emit functions when variable_ops processing is needed.
345 unsigned &NumInputRootOps;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000346
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000347 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000348 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000349 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000350 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000351
352 void emitCheck(const std::string &S) {
353 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000354 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000355 }
356 void emitCode(const std::string &S) {
357 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000358 GeneratedCode.push_back(std::make_pair(0, S));
359 }
360 void emitInit(const std::string &S) {
361 if (!S.empty())
362 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000363 }
Evan Chengf5493192006-08-26 01:02:19 +0000364 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000365 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000366 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000367 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000368 void emitOpcode(const std::string &Opc) {
369 TargetOpcodes.push_back(Opc);
370 OpcNo++;
371 }
Evan Chengf8729402006-07-16 06:12:52 +0000372 void emitVT(const std::string &VT) {
373 TargetVTs.push_back(VT);
374 VTNo++;
375 }
Evan Chengb915f312005-12-09 22:45:35 +0000376public:
Dan Gohman22bb3112008-08-22 00:20:26 +0000377 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Evan Cheng58e84a62005-12-14 22:02:59 +0000378 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000379 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000380 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000381 std::vector<std::string> &to,
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000382 std::vector<std::string> &tv,
383 bool &oiv,
384 unsigned &niro)
Dan Gohman22bb3112008-08-22 00:20:26 +0000385 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000386 GeneratedCode(gc), GeneratedDecl(gd),
387 TargetOpcodes(to), TargetVTs(tv),
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000388 OutputIsVariadic(oiv), NumInputRootOps(niro),
Chris Lattner706d2d32006-08-09 16:44:44 +0000389 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000390
391 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
392 /// if the match fails. At this point, we already know that the opcode for N
393 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000394 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
395 const std::string &RootName, const std::string &ChainSuffix,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000396 bool &FoundChain);
Chris Lattner39e73f72006-10-11 04:05:55 +0000397
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000398 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb85356242008-01-31 07:27:46 +0000399 const std::string &RootName,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000400 const std::string &ChainSuffix, bool &FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000401
402 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
403 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000404 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000405 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000406 bool InFlagDecled, bool ResNodeDecled,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000407 bool LikeLeaf = false, bool isRoot = false);
Evan Chengb915f312005-12-09 22:45:35 +0000408
Chris Lattner488580c2006-01-28 19:06:51 +0000409 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
410 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +0000411 /// 'Pat' may be missing types. If we find an unresolved type to add a check
412 /// for, this returns true otherwise false if Pat has all types.
413 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +0000414 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +0000415 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +0000416 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +0000417 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +0000418 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +0000419 // The top level node type is checked outside of the select function.
420 if (!isRoot)
Anton Korobeynikovc2fd9192009-11-08 12:14:54 +0000421 emitCheck(Prefix + ".getValueType() == " +
Chris Lattner706d2d32006-08-09 16:44:44 +0000422 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +0000423 return true;
Evan Chengb915f312005-12-09 22:45:35 +0000424 }
425
Chris Lattner47661322010-02-14 22:22:58 +0000426 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000427 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
428 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
429 Prefix + utostr(OpNo)))
430 return true;
431 return false;
432 }
433
434private:
Evan Cheng54597732006-01-26 00:22:25 +0000435 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +0000436 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +0000437 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +0000438 bool &ChainEmitted, bool &InFlagDecled,
439 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000440 const CodeGenTarget &T = CGP.getTargetInfo();
Chris Lattner47661322010-02-14 22:22:58 +0000441 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
442 bool HasInFlag = N->NodeHasProperty(SDNPInFlag, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000443 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
444 TreePatternNode *Child = N->getChild(i);
445 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000446 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
447 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +0000448 } else {
449 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +0000450 if (!Child->getName().empty()) {
451 std::string Name = RootName + utostr(OpNo);
452 if (Duplicates.find(Name) != Duplicates.end())
453 // A duplicate! Do not emit a copy for this node.
454 continue;
455 }
456
Evan Chengb915f312005-12-09 22:45:35 +0000457 Record *RR = DI->getDef();
458 if (RR->isSubClassOf("Register")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000459 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
460 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000461 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000462 emitCode("SDValue InFlag = " +
463 getValueName(RootName + utostr(OpNo)) + ";");
Evan Cheng676d7312006-08-26 00:59:04 +0000464 InFlagDecled = true;
465 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000466 emitCode("InFlag = " +
467 getValueName(RootName + utostr(OpNo)) + ";");
Evan Chengb2c6d492006-01-11 22:16:13 +0000468 } else {
469 if (!ChainEmitted) {
Dan Gohman475871a2008-07-27 21:46:04 +0000470 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000471 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +0000472 ChainEmitted = true;
473 }
Evan Cheng676d7312006-08-26 00:59:04 +0000474 if (!InFlagDecled) {
Dan Gohman475871a2008-07-27 21:46:04 +0000475 emitCode("SDValue InFlag(0, 0);");
Evan Cheng676d7312006-08-26 00:59:04 +0000476 InFlagDecled = true;
477 }
Dale Johannesen874ae252009-06-02 03:12:52 +0000478 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
479 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000480 ", " + getNodeName(RootName) + "->getDebugLoc()" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000481 ", " + getQualifiedName(RR) +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000482 ", " + getValueName(RootName + utostr(OpNo)) +
483 ", InFlag).getNode();");
Dale Johannesen874ae252009-06-02 03:12:52 +0000484 ResNodeDecled = true;
Dan Gohman475871a2008-07-27 21:46:04 +0000485 emitCode(ChainName + " = SDValue(ResNode, 0);");
486 emitCode("InFlag = SDValue(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +0000487 }
488 }
489 }
490 }
491 }
Evan Cheng54597732006-01-26 00:22:25 +0000492
Dale Johannesen874ae252009-06-02 03:12:52 +0000493 if (HasInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000494 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000495 emitCode("SDValue InFlag = " + getNodeName(RootName) +
496 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000497 InFlagDecled = true;
498 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000499 emitCode("InFlag = " + getNodeName(RootName) +
500 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000501 }
Evan Chengb915f312005-12-09 22:45:35 +0000502 }
503};
504
Chris Lattnera0cdf172010-02-13 20:06:50 +0000505
506/// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
507/// if the match fails. At this point, we already know that the opcode for N
508/// matches, and the SDNode for the result has the RootName specified name.
509void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
510 const std::string &RootName,
511 const std::string &ChainSuffix,
512 bool &FoundChain) {
513
514 // Save loads/stores matched by a pattern.
515 if (!N->isLeaf() && N->getName().empty()) {
Chris Lattner47661322010-02-14 22:22:58 +0000516 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnera0cdf172010-02-13 20:06:50 +0000517 LSI.push_back(getNodeName(RootName));
518 }
519
520 bool isRoot = (P == NULL);
521 // Emit instruction predicates. Each predicate is just a string for now.
522 if (isRoot) {
523 // Record input varargs info.
524 NumInputRootOps = N->getNumChildren();
Chris Lattnera0cdf172010-02-13 20:06:50 +0000525 emitCheck(PredicateCheck);
526 }
527
528 if (N->isLeaf()) {
529 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
530 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
531 ")->getSExtValue() == INT64_C(" +
532 itostr(II->getValue()) + ")");
533 return;
534 } else if (!NodeIsComplexPattern(N)) {
535 assert(0 && "Cannot match this as a leaf value!");
536 abort();
537 }
538 }
539
540 // If this node has a name associated with it, capture it in VariableMap. If
541 // we already saw this in the pattern, emit code to verify dagness.
542 if (!N->getName().empty()) {
543 std::string &VarMapEntry = VariableMap[N->getName()];
544 if (VarMapEntry.empty()) {
545 VarMapEntry = RootName;
546 } else {
547 // If we get here, this is a second reference to a specific name. Since
548 // we already have checked that the first reference is valid, we don't
549 // have to recursively match it, just check that it's the same as the
550 // previously named thing.
551 emitCheck(VarMapEntry + " == " + RootName);
552 return;
553 }
554
555 if (!N->isLeaf())
556 OperatorMap[N->getName()] = N->getOperator();
557 }
558
559
560 // Emit code to load the child nodes and match their contents recursively.
561 unsigned OpNo = 0;
Chris Lattner47661322010-02-14 22:22:58 +0000562 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
563 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000564 bool EmittedUseCheck = false;
565 if (HasChain) {
566 if (NodeHasChain)
567 OpNo = 1;
568 if (!isRoot) {
Evan Cheng014bf212010-02-15 19:41:07 +0000569 // Check if it's profitable to fold the node. e.g. Check for multiple uses
570 // of actual result?
571 std::string ParentName(RootName.begin(), RootName.end()-1);
572 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
573 ", " + getNodeName(ParentName) + ", N)");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000574 EmittedUseCheck = true;
575 if (NodeHasChain) {
576 // If the immediate use can somehow reach this node through another
577 // path, then can't fold it either or it will create a cycle.
578 // e.g. In the following diagram, XX can reach ld through YY. If
579 // ld is folded into XX, then YY is both a predecessor and a successor
580 // of XX.
581 //
582 // [ld]
583 // ^ ^
584 // | |
585 // / \---
586 // / [YY]
587 // | ^
588 // [XX]-------|
Chris Lattnere39650a2010-02-16 06:10:58 +0000589
590 // We know we need the check if N's parent is not the root.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000591 bool NeedCheck = P != Pattern;
592 if (!NeedCheck) {
593 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
594 NeedCheck =
595 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
596 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
597 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
598 PInfo.getNumOperands() > 1 ||
599 PInfo.hasProperty(SDNPHasChain) ||
600 PInfo.hasProperty(SDNPInFlag) ||
601 PInfo.hasProperty(SDNPOptInFlag);
602 }
603
604 if (NeedCheck) {
Evan Cheng014bf212010-02-15 19:41:07 +0000605 emitCheck("IsLegalToFold(" + getValueName(RootName) +
Chris Lattnera0cdf172010-02-13 20:06:50 +0000606 ", " + getNodeName(ParentName) + ", N)");
607 }
608 }
609 }
610
611 if (NodeHasChain) {
612 if (FoundChain) {
613 emitCheck("(" + ChainName + ".getNode() == " +
614 getNodeName(RootName) + " || "
615 "IsChainCompatible(" + ChainName + ".getNode(), " +
616 getNodeName(RootName) + "))");
617 OrigChains.push_back(std::make_pair(ChainName,
618 getValueName(RootName)));
619 } else
620 FoundChain = true;
621 ChainName = "Chain" + ChainSuffix;
622 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
623 "->getOperand(0);");
624 }
625 }
626
627 // Don't fold any node which reads or writes a flag and has multiple uses.
628 // FIXME: We really need to separate the concepts of flag and "glue". Those
629 // real flag results, e.g. X86CMP output, can have multiple uses.
630 // FIXME: If the optional incoming flag does not exist. Then it is ok to
631 // fold it.
632 if (!isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +0000633 (N->TreeHasProperty(SDNPInFlag, CGP) ||
634 N->TreeHasProperty(SDNPOptInFlag, CGP) ||
635 N->TreeHasProperty(SDNPOutFlag, CGP))) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000636 if (!EmittedUseCheck) {
637 // Multiple uses of actual result?
638 emitCheck(getValueName(RootName) + ".hasOneUse()");
639 }
640 }
641
642 // If there are node predicates for this, emit the calls.
643 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
644 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
645
646 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
647 // a constant without a predicate fn that has more that one bit set, handle
648 // this as a special case. This is usually for targets that have special
649 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
650 // handling stuff). Using these instructions is often far more efficient
651 // than materializing the constant. Unfortunately, both the instcombiner
652 // and the dag combiner can often infer that bits are dead, and thus drop
653 // them from the mask in the dag. For example, it might turn 'AND X, 255'
654 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
655 // to handle this.
656 if (!N->isLeaf() &&
657 (N->getOperator()->getName() == "and" ||
658 N->getOperator()->getName() == "or") &&
659 N->getChild(1)->isLeaf() &&
660 N->getChild(1)->getPredicateFns().empty()) {
661 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
662 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
663 emitInit("SDValue " + RootName + "0" + " = " +
664 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
665 emitInit("SDValue " + RootName + "1" + " = " +
666 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
667
668 unsigned NTmp = TmpNo++;
669 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
670 " = dyn_cast<ConstantSDNode>(" +
671 getNodeName(RootName + "1") + ");");
672 emitCheck("Tmp" + utostr(NTmp));
673 const char *MaskPredicate = N->getOperator()->getName() == "or"
674 ? "CheckOrMask(" : "CheckAndMask(";
675 emitCheck(MaskPredicate + getValueName(RootName + "0") +
676 ", Tmp" + utostr(NTmp) +
677 ", INT64_C(" + itostr(II->getValue()) + "))");
678
679 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
680 ChainSuffix + utostr(0), FoundChain);
681 return;
682 }
683 }
684 }
685
686 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
687 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
688 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
689
690 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
691 ChainSuffix + utostr(OpNo), FoundChain);
692 }
693
694 // Handle cases when root is a complex pattern.
695 const ComplexPattern *CP;
Chris Lattner47661322010-02-14 22:22:58 +0000696 if (isRoot && N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000697 std::string Fn = CP->getSelectFunc();
698 unsigned NumOps = CP->getNumOperands();
699 for (unsigned i = 0; i < NumOps; ++i) {
700 emitDecl("CPTmp" + RootName + "_" + utostr(i));
701 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
702 }
703 if (CP->hasProperty(SDNPHasChain)) {
704 emitDecl("CPInChain");
705 emitDecl("Chain" + ChainSuffix);
706 emitCode("SDValue CPInChain;");
707 emitCode("SDValue Chain" + ChainSuffix + ";");
708 }
709
710 std::string Code = Fn + "(" +
711 getNodeName(RootName) + ", " +
712 getValueName(RootName);
713 for (unsigned i = 0; i < NumOps; i++)
714 Code += ", CPTmp" + RootName + "_" + utostr(i);
715 if (CP->hasProperty(SDNPHasChain)) {
716 ChainName = "Chain" + ChainSuffix;
717 Code += ", CPInChain, Chain" + ChainSuffix;
718 }
719 emitCheck(Code + ")");
720 }
721}
722
723void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
724 TreePatternNode *Parent,
725 const std::string &RootName,
726 const std::string &ChainSuffix,
727 bool &FoundChain) {
728 if (!Child->isLeaf()) {
729 // If it's not a leaf, recursively match.
730 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
731 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
732 CInfo.getEnumName());
733 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
734 bool HasChain = false;
Chris Lattner47661322010-02-14 22:22:58 +0000735 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000736 HasChain = true;
737 FoldedChains.push_back(std::make_pair(getValueName(RootName),
738 CInfo.getNumResults()));
739 }
Chris Lattner47661322010-02-14 22:22:58 +0000740 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000741 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
742 "Pattern folded multiple nodes which produce flags?");
743 FoldedFlag = std::make_pair(getValueName(RootName),
744 CInfo.getNumResults() + (unsigned)HasChain);
745 }
746 } else {
747 // If this child has a name associated with it, capture it in VarMap. If
748 // we already saw this in the pattern, emit code to verify dagness.
749 if (!Child->getName().empty()) {
750 std::string &VarMapEntry = VariableMap[Child->getName()];
751 if (VarMapEntry.empty()) {
752 VarMapEntry = getValueName(RootName);
753 } else {
754 // If we get here, this is a second reference to a specific name.
755 // Since we already have checked that the first reference is valid,
756 // we don't have to recursively match it, just check that it's the
757 // same as the previously named thing.
758 emitCheck(VarMapEntry + " == " + getValueName(RootName));
759 Duplicates.insert(getValueName(RootName));
760 return;
761 }
762 }
763
764 // Handle leaves of various types.
765 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
766 Record *LeafRec = DI->getDef();
767 if (LeafRec->isSubClassOf("RegisterClass") ||
768 LeafRec->isSubClassOf("PointerLikeRegClass")) {
769 // Handle register references. Nothing to do here.
770 } else if (LeafRec->isSubClassOf("Register")) {
771 // Handle register references.
772 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
773 // Handle complex pattern.
Chris Lattner47661322010-02-14 22:22:58 +0000774 const ComplexPattern *CP = Child->getComplexPatternInfo(CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000775 std::string Fn = CP->getSelectFunc();
776 unsigned NumOps = CP->getNumOperands();
777 for (unsigned i = 0; i < NumOps; ++i) {
778 emitDecl("CPTmp" + RootName + "_" + utostr(i));
779 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
780 }
781 if (CP->hasProperty(SDNPHasChain)) {
782 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
783 FoldedChains.push_back(std::make_pair("CPInChain",
784 PInfo.getNumResults()));
785 ChainName = "Chain" + ChainSuffix;
786 emitDecl("CPInChain");
787 emitDecl(ChainName);
788 emitCode("SDValue CPInChain;");
789 emitCode("SDValue " + ChainName + ";");
790 }
791
792 std::string Code = Fn + "(N, ";
793 if (CP->hasProperty(SDNPHasChain)) {
794 std::string ParentName(RootName.begin(), RootName.end()-1);
795 Code += getValueName(ParentName) + ", ";
796 }
797 Code += getValueName(RootName);
798 for (unsigned i = 0; i < NumOps; i++)
799 Code += ", CPTmp" + RootName + "_" + utostr(i);
800 if (CP->hasProperty(SDNPHasChain))
801 Code += ", CPInChain, Chain" + ChainSuffix;
802 emitCheck(Code + ")");
803 } else if (LeafRec->getName() == "srcvalue") {
804 // Place holder for SRCVALUE nodes. Nothing to do here.
805 } else if (LeafRec->isSubClassOf("ValueType")) {
806 // Make sure this is the specified value type.
807 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
808 ")->getVT() == MVT::" + LeafRec->getName());
809 } else if (LeafRec->isSubClassOf("CondCode")) {
810 // Make sure this is the specified cond code.
811 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
812 ")->get() == ISD::" + LeafRec->getName());
813 } else {
814#ifndef NDEBUG
815 Child->dump();
816 errs() << " ";
817#endif
818 assert(0 && "Unknown leaf type!");
819 }
820
821 // If there are node predicates for this, emit the calls.
822 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
823 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
824 ")");
825 } else if (IntInit *II =
826 dynamic_cast<IntInit*>(Child->getLeafValue())) {
827 unsigned NTmp = TmpNo++;
828 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
829 " = dyn_cast<ConstantSDNode>("+
830 getNodeName(RootName) + ");");
831 emitCheck("Tmp" + utostr(NTmp));
832 unsigned CTmp = TmpNo++;
833 emitCode("int64_t CN"+ utostr(CTmp) +
834 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
835 emitCheck("CN" + utostr(CTmp) + " == "
836 "INT64_C(" +itostr(II->getValue()) + ")");
837 } else {
838#ifndef NDEBUG
839 Child->dump();
840#endif
841 assert(0 && "Unknown leaf type!");
842 }
843 }
844}
845
846/// EmitResultCode - Emit the action for a pattern. Now that it has matched
847/// we actually have to build a DAG!
848std::vector<std::string>
849PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
850 std::vector<Record*> DstRegs,
851 bool InFlagDecled, bool ResNodeDecled,
852 bool LikeLeaf, bool isRoot) {
853 // List of arguments of getMachineNode() or SelectNodeTo().
854 std::vector<std::string> NodeOps;
855 // This is something selected from the pattern we matched.
856 if (!N->getName().empty()) {
857 const std::string &VarName = N->getName();
858 std::string Val = VariableMap[VarName];
859 bool ModifiedVal = false;
860 if (Val.empty()) {
861 errs() << "Variable '" << VarName << " referenced but not defined "
862 << "and not caught earlier!\n";
863 abort();
864 }
865 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
866 // Already selected this operand, just return the tmpval.
867 NodeOps.push_back(getValueName(Val));
868 return NodeOps;
869 }
870
871 const ComplexPattern *CP;
872 unsigned ResNo = TmpNo++;
873 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
874 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
875 std::string CastType;
876 std::string TmpVar = "Tmp" + utostr(ResNo);
877 switch (N->getTypeNum(0)) {
878 default:
879 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
880 << " type as an immediate constant. Aborting\n";
881 abort();
882 case MVT::i1: CastType = "bool"; break;
883 case MVT::i8: CastType = "unsigned char"; break;
884 case MVT::i16: CastType = "unsigned short"; break;
885 case MVT::i32: CastType = "unsigned"; break;
886 case MVT::i64: CastType = "uint64_t"; break;
887 }
888 emitCode("SDValue " + TmpVar +
889 " = CurDAG->getTargetConstant(((" + CastType +
890 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
891 getEnumName(N->getTypeNum(0)) + ");");
892 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
893 // value if used multiple times by this pattern result.
894 Val = TmpVar;
895 ModifiedVal = true;
896 NodeOps.push_back(getValueName(Val));
897 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
898 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
899 std::string TmpVar = "Tmp" + utostr(ResNo);
900 emitCode("SDValue " + TmpVar +
901 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
902 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
903 Val + ")->getValueType(0));");
904 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
905 // value if used multiple times by this pattern result.
906 Val = TmpVar;
907 ModifiedVal = true;
908 NodeOps.push_back(getValueName(Val));
909 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
910 Record *Op = OperatorMap[N->getName()];
911 // Transform ExternalSymbol to TargetExternalSymbol
912 if (Op && Op->getName() == "externalsym") {
913 std::string TmpVar = "Tmp"+utostr(ResNo);
914 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
915 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
916 Val + ")->getSymbol(), " +
917 getEnumName(N->getTypeNum(0)) + ");");
918 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
919 // this value if used multiple times by this pattern result.
920 Val = TmpVar;
921 ModifiedVal = true;
922 }
923 NodeOps.push_back(getValueName(Val));
924 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
925 || N->getOperator()->getName() == "tglobaltlsaddr")) {
926 Record *Op = OperatorMap[N->getName()];
927 // Transform GlobalAddress to TargetGlobalAddress
928 if (Op && (Op->getName() == "globaladdr" ||
929 Op->getName() == "globaltlsaddr")) {
930 std::string TmpVar = "Tmp" + utostr(ResNo);
931 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
932 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
933 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
934 ");");
935 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
936 // this value if used multiple times by this pattern result.
937 Val = TmpVar;
938 ModifiedVal = true;
939 }
940 NodeOps.push_back(getValueName(Val));
941 } else if (!N->isLeaf()
Chris Lattner47661322010-02-14 22:22:58 +0000942 && (N->getOperator()->getName() == "texternalsym" ||
943 N->getOperator()->getName() == "tconstpool")) {
944 // Do not rewrite the variable name, since we don't generate a new
945 // temporary.
946 NodeOps.push_back(getValueName(Val));
947 } else if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
948 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
949 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
950 }
951 } else {
952 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
953 // node even if it isn't one. Don't select it.
954 if (!LikeLeaf) {
955 if (isRoot && N->isLeaf()) {
956 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
957 emitCode("return NULL;");
958 }
959 }
960 NodeOps.push_back(getValueName(Val));
Chris Lattnera0cdf172010-02-13 20:06:50 +0000961 }
Chris Lattner47661322010-02-14 22:22:58 +0000962
963 if (ModifiedVal)
964 VariableMap[VarName] = Val;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000965 return NodeOps;
966 }
967 if (N->isLeaf()) {
968 // If this is an explicit register reference, handle it.
969 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
970 unsigned ResNo = TmpNo++;
971 if (DI->getDef()->isSubClassOf("Register")) {
972 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
973 getQualifiedName(DI->getDef()) + ", " +
974 getEnumName(N->getTypeNum(0)) + ");");
975 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
976 return NodeOps;
977 } else if (DI->getDef()->getName() == "zero_reg") {
978 emitCode("SDValue Tmp" + utostr(ResNo) +
979 " = CurDAG->getRegister(0, " +
980 getEnumName(N->getTypeNum(0)) + ");");
981 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
982 return NodeOps;
983 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
984 // Handle a reference to a register class. This is used
985 // in COPY_TO_SUBREG instructions.
986 emitCode("SDValue Tmp" + utostr(ResNo) +
987 " = CurDAG->getTargetConstant(" +
988 getQualifiedName(DI->getDef()) + "RegClassID, " +
989 "MVT::i32);");
990 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
991 return NodeOps;
992 }
993 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
994 unsigned ResNo = TmpNo++;
995 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
996 emitCode("SDValue Tmp" + utostr(ResNo) +
997 " = CurDAG->getTargetConstant(0x" +
998 utohexstr((uint64_t) II->getValue()) +
999 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
1000 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1001 return NodeOps;
1002 }
1003
1004#ifndef NDEBUG
1005 N->dump();
1006#endif
1007 assert(0 && "Unknown leaf type!");
1008 return NodeOps;
1009 }
1010
1011 Record *Op = N->getOperator();
1012 if (Op->isSubClassOf("Instruction")) {
1013 const CodeGenTarget &CGT = CGP.getTargetInfo();
1014 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
1015 const DAGInstruction &Inst = CGP.getInstruction(Op);
1016 const TreePattern *InstPat = Inst.getPattern();
1017 // FIXME: Assume actual pattern comes before "implicit".
1018 TreePatternNode *InstPatNode =
1019 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
1020 : (InstPat ? InstPat->getTree(0) : NULL);
1021 if (InstPatNode && !InstPatNode->isLeaf() &&
1022 InstPatNode->getOperator()->getName() == "set") {
1023 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
1024 }
1025 bool IsVariadic = isRoot && II.isVariadic;
1026 // FIXME: fix how we deal with physical register operands.
1027 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1028 bool HasImpResults = isRoot && DstRegs.size() > 0;
1029 bool NodeHasOptInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +00001030 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001031 bool NodeHasInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +00001032 Pattern->TreeHasProperty(SDNPInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001033 bool NodeHasOutFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +00001034 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001035 bool NodeHasChain = InstPatNode &&
Chris Lattner47661322010-02-14 22:22:58 +00001036 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
1037 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001038 unsigned NumResults = Inst.getNumResults();
1039 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1040
1041 // Record output varargs info.
1042 OutputIsVariadic = IsVariadic;
1043
1044 if (NodeHasOptInFlag) {
1045 emitCode("bool HasInFlag = "
1046 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1047 "MVT::Flag);");
1048 }
1049 if (IsVariadic)
1050 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1051
1052 // How many results is this pattern expected to produce?
1053 unsigned NumPatResults = 0;
1054 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1055 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1056 if (VT != MVT::isVoid && VT != MVT::Flag)
1057 NumPatResults++;
1058 }
1059
1060 if (OrigChains.size() > 0) {
1061 // The original input chain is being ignored. If it is not just
1062 // pointing to the op that's being folded, we should create a
1063 // TokenFactor with it and the chain of the folded op as the new chain.
1064 // We could potentially be doing multiple levels of folding, in that
1065 // case, the TokenFactor can have more operands.
1066 emitCode("SmallVector<SDValue, 8> InChains;");
1067 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1068 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1069 OrigChains[i].second + ".getNode()) {");
1070 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1071 emitCode("}");
1072 }
1073 emitCode("InChains.push_back(" + ChainName + ");");
1074 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1075 "N->getDebugLoc(), MVT::Other, "
1076 "&InChains[0], InChains.size());");
1077 if (GenDebug) {
1078 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1079 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1080 }
1081 }
1082
1083 // Loop over all of the operands of the instruction pattern, emitting code
1084 // to fill them all in. The node 'N' usually has number children equal to
1085 // the number of input operands of the instruction. However, in cases
1086 // where there are predicate operands for an instruction, we need to fill
1087 // in the 'execute always' values. Match up the node operands to the
1088 // instruction operands to do this.
1089 std::vector<std::string> AllOps;
1090 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1091 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1092 std::vector<std::string> Ops;
1093
1094 // Determine what to emit for this operand.
1095 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1096 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1097 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1098 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1099 // This is a predicate or optional def operand; emit the
1100 // 'default ops' operands.
1101 const DAGDefaultOperand &DefaultOp =
1102 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1103 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1104 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1105 InFlagDecled, ResNodeDecled);
1106 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1107 }
1108 } else {
1109 // Otherwise this is a normal operand or a predicate operand without
1110 // 'execute always'; emit it.
1111 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1112 InFlagDecled, ResNodeDecled);
1113 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1114 ++ChildNo;
1115 }
1116 }
1117
1118 // Emit all the chain and CopyToReg stuff.
1119 bool ChainEmitted = NodeHasChain;
1120 if (NodeHasInFlag || HasImpInputs)
1121 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1122 InFlagDecled, ResNodeDecled, true);
1123 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1124 if (!InFlagDecled) {
1125 emitCode("SDValue InFlag(0, 0);");
1126 InFlagDecled = true;
1127 }
1128 if (NodeHasOptInFlag) {
1129 emitCode("if (HasInFlag) {");
1130 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1131 emitCode("}");
1132 }
1133 }
1134
1135 unsigned ResNo = TmpNo++;
1136
1137 unsigned OpsNo = OpcNo;
1138 std::string CodePrefix;
1139 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1140 std::deque<std::string> After;
1141 std::string NodeName;
1142 if (!isRoot) {
1143 NodeName = "Tmp" + utostr(ResNo);
1144 CodePrefix = "SDValue " + NodeName + "(";
1145 } else {
1146 NodeName = "ResNode";
1147 if (!ResNodeDecled) {
1148 CodePrefix = "SDNode *" + NodeName + " = ";
1149 ResNodeDecled = true;
1150 } else
1151 CodePrefix = NodeName + " = ";
1152 }
1153
1154 std::string Code = "Opc" + utostr(OpcNo);
1155
1156 if (!isRoot || (InputHasChain && !NodeHasChain))
1157 // For call to "getMachineNode()".
1158 Code += ", N->getDebugLoc()";
1159
1160 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1161
1162 // Output order: results, chain, flags
1163 // Result types.
1164 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1165 Code += ", VT" + utostr(VTNo);
1166 emitVT(getEnumName(N->getTypeNum(0)));
1167 }
1168 // Add types for implicit results in physical registers, scheduler will
1169 // care of adding copyfromreg nodes.
1170 for (unsigned i = 0; i < NumDstRegs; i++) {
1171 Record *RR = DstRegs[i];
1172 if (RR->isSubClassOf("Register")) {
1173 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1174 Code += ", " + getEnumName(RVT);
1175 }
1176 }
1177 if (NodeHasChain)
1178 Code += ", MVT::Other";
1179 if (NodeHasOutFlag)
1180 Code += ", MVT::Flag";
1181
1182 // Inputs.
1183 if (IsVariadic) {
1184 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1185 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1186 AllOps.clear();
1187
1188 // Figure out whether any operands at the end of the op list are not
1189 // part of the variable section.
1190 std::string EndAdjust;
1191 if (NodeHasInFlag || HasImpInputs)
1192 EndAdjust = "-1"; // Always has one flag.
1193 else if (NodeHasOptInFlag)
1194 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1195
1196 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1197 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1198
1199 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1200 emitCode("}");
1201 }
1202
1203 // Populate MemRefs with entries for each memory accesses covered by
1204 // this pattern.
1205 if (isRoot && !LSI.empty()) {
1206 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1207 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1208 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1209 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1210 emitCode(MemRefs + "[" + utostr(i) + "] = "
1211 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1212 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1213 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1214 ");");
1215 }
1216
1217 if (NodeHasChain) {
1218 if (IsVariadic)
1219 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1220 else
1221 AllOps.push_back(ChainName);
1222 }
1223
1224 if (IsVariadic) {
1225 if (NodeHasInFlag || HasImpInputs)
1226 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1227 else if (NodeHasOptInFlag) {
1228 emitCode("if (HasInFlag)");
1229 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1230 }
1231 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1232 ".size()";
1233 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1234 AllOps.push_back("InFlag");
1235
1236 unsigned NumOps = AllOps.size();
1237 if (NumOps) {
1238 if (!NodeHasOptInFlag && NumOps < 4) {
1239 for (unsigned i = 0; i != NumOps; ++i)
1240 Code += ", " + AllOps[i];
1241 } else {
1242 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1243 for (unsigned i = 0; i != NumOps; ++i) {
1244 OpsCode += AllOps[i];
1245 if (i != NumOps-1)
1246 OpsCode += ", ";
1247 }
1248 emitCode(OpsCode + " };");
1249 Code += ", Ops" + utostr(OpsNo) + ", ";
1250 if (NodeHasOptInFlag) {
1251 Code += "HasInFlag ? ";
1252 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1253 } else
1254 Code += utostr(NumOps);
1255 }
1256 }
1257
1258 if (!isRoot)
1259 Code += "), 0";
1260
1261 std::vector<std::string> ReplaceFroms;
1262 std::vector<std::string> ReplaceTos;
1263 if (!isRoot) {
1264 NodeOps.push_back("Tmp" + utostr(ResNo));
1265 } else {
1266
1267 if (NodeHasOutFlag) {
1268 if (!InFlagDecled) {
1269 After.push_back("SDValue InFlag(ResNode, " +
1270 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1271 ");");
1272 InFlagDecled = true;
1273 } else
1274 After.push_back("InFlag = SDValue(ResNode, " +
1275 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1276 ");");
1277 }
1278
1279 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1280 ReplaceFroms.push_back("SDValue(" +
1281 FoldedChains[j].first + ".getNode(), " +
1282 utostr(FoldedChains[j].second) +
1283 ")");
1284 ReplaceTos.push_back("SDValue(ResNode, " +
1285 utostr(NumResults+NumDstRegs) + ")");
1286 }
1287
1288 if (NodeHasOutFlag) {
1289 if (FoldedFlag.first != "") {
1290 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1291 utostr(FoldedFlag.second) + ")");
1292 ReplaceTos.push_back("InFlag");
1293 } else {
Chris Lattner47661322010-02-14 22:22:58 +00001294 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
Chris Lattnera0cdf172010-02-13 20:06:50 +00001295 ReplaceFroms.push_back("SDValue(N, " +
1296 utostr(NumPatResults + (unsigned)InputHasChain)
1297 + ")");
1298 ReplaceTos.push_back("InFlag");
1299 }
1300 }
1301
1302 if (!ReplaceFroms.empty() && InputHasChain) {
1303 ReplaceFroms.push_back("SDValue(N, " +
1304 utostr(NumPatResults) + ")");
1305 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1306 ChainName + ".getResNo()" + ")");
1307 ChainAssignmentNeeded |= NodeHasChain;
1308 }
1309
1310 // User does not expect the instruction would produce a chain!
1311 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1312 ;
1313 } else if (InputHasChain && !NodeHasChain) {
1314 // One of the inner node produces a chain.
1315 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1316 ReplaceFroms.push_back("SDValue(N, " +
1317 utostr(NumPatResults) + ")");
1318 ReplaceTos.push_back(ChainName);
1319 }
1320 }
1321
1322 if (ChainAssignmentNeeded) {
1323 // Remember which op produces the chain.
1324 std::string ChainAssign;
1325 if (!isRoot)
1326 ChainAssign = ChainName + " = SDValue(" + NodeName +
1327 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1328 else
1329 ChainAssign = ChainName + " = SDValue(" + NodeName +
1330 ", " + utostr(NumResults+NumDstRegs) + ");";
1331
1332 After.push_front(ChainAssign);
1333 }
1334
1335 if (ReplaceFroms.size() == 1) {
1336 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1337 ReplaceTos[0] + ");");
1338 } else if (!ReplaceFroms.empty()) {
1339 After.push_back("const SDValue Froms[] = {");
1340 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1341 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1342 After.push_back("};");
1343 After.push_back("const SDValue Tos[] = {");
1344 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1345 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1346 After.push_back("};");
1347 After.push_back("ReplaceUses(Froms, Tos, " +
1348 itostr(ReplaceFroms.size()) + ");");
1349 }
1350
1351 // We prefer to use SelectNodeTo since it avoids allocation when
1352 // possible and it avoids CSE map recalculation for the node's
1353 // users, however it's tricky to use in a non-root context.
1354 //
1355 // We also don't use SelectNodeTo if the pattern replacement is being
1356 // used to jettison a chain result, since morphing the node in place
1357 // would leave users of the chain dangling.
1358 //
1359 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1360 Code = "CurDAG->getMachineNode(" + Code;
1361 } else {
1362 Code = "CurDAG->SelectNodeTo(N, " + Code;
1363 }
1364 if (isRoot) {
1365 if (After.empty())
1366 CodePrefix = "return ";
1367 else
1368 After.push_back("return ResNode;");
1369 }
1370
1371 emitCode(CodePrefix + Code + ");");
1372
1373 if (GenDebug) {
1374 if (!isRoot) {
1375 emitCode("CurDAG->setSubgraphColor(" +
1376 NodeName +".getNode(), \"yellow\");");
1377 emitCode("CurDAG->setSubgraphColor(" +
1378 NodeName +".getNode(), \"black\");");
1379 } else {
1380 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1381 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1382 }
1383 }
1384
1385 for (unsigned i = 0, e = After.size(); i != e; ++i)
1386 emitCode(After[i]);
1387
1388 return NodeOps;
1389 }
1390 if (Op->isSubClassOf("SDNodeXForm")) {
1391 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1392 // PatLeaf node - the operand may or may not be a leaf node. But it should
1393 // behave like one.
1394 std::vector<std::string> Ops =
1395 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1396 ResNodeDecled, true);
1397 unsigned ResNo = TmpNo++;
1398 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1399 + "(" + Ops.back() + ".getNode());");
1400 NodeOps.push_back("Tmp" + utostr(ResNo));
1401 if (isRoot)
1402 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1403 return NodeOps;
1404 }
1405
1406 N->dump();
1407 errs() << "\n";
1408 throw std::string("Unknown node in result pattern!");
1409}
1410
1411
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001412/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1413/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001414/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001415void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001416 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001417 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001418 std::vector<std::string> &TargetOpcodes,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001419 std::vector<std::string> &TargetVTs,
1420 bool &OutputIsVariadic,
1421 unsigned &NumInputRootOps) {
1422 OutputIsVariadic = false;
1423 NumInputRootOps = 0;
1424
Dan Gohman22bb3112008-08-22 00:20:26 +00001425 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001426 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001427 GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001428 TargetOpcodes, TargetVTs,
1429 OutputIsVariadic, NumInputRootOps);
Evan Chengb915f312005-12-09 22:45:35 +00001430
Chris Lattner8fc35682005-09-23 23:16:51 +00001431 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001432 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001433 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001434
Chris Lattnerc87bf382010-02-14 21:11:53 +00001435 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1436 // diagnostics, which we know are impossible at this point.
Chris Lattner200c57e2008-01-05 22:58:54 +00001437 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001438
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001439 // At this point, we know that we structurally match the pattern, but the
1440 // types of the nodes may not match. Figure out the fewest number of type
1441 // comparisons we need to emit. For example, if there is only one integer
1442 // type supported by a target, there should be no type comparisons at all for
1443 // integer patterns!
1444 //
1445 // To figure out the fewest number of type checks needed, clone the pattern,
1446 // remove the types, then perform type inference on the pattern as a whole.
1447 // If there are unresolved types, emit an explicit check for those types,
1448 // apply the type to the tree, then rerun type inference. Iterate until all
1449 // types are resolved.
1450 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001451 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner47661322010-02-14 22:22:58 +00001452 Pat->RemoveAllTypes();
Chris Lattner7e82f132005-10-15 21:34:21 +00001453
1454 do {
1455 // Resolve/propagate as many types as possible.
1456 try {
1457 bool MadeChange = true;
1458 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001459 MadeChange = Pat->ApplyTypeConstraints(TP,
1460 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001461 } catch (...) {
1462 assert(0 && "Error: could not find consistent types for something we"
1463 " already decided was ok!");
1464 abort();
1465 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001466
Chris Lattner7e82f132005-10-15 21:34:21 +00001467 // Insert a check for an unresolved type and add it to the tree. If we find
1468 // an unresolved type to add a check for, this returns true and we iterate,
1469 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001470 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001471
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001472 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001473 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001474 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001475}
1476
Chris Lattner24e00a42006-01-29 04:41:05 +00001477/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1478/// a line causes any of them to be empty, remove them and return true when
1479/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001480static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001481 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001482 &Patterns) {
1483 bool ErasedPatterns = false;
1484 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1485 Patterns[i].second.pop_back();
1486 if (Patterns[i].second.empty()) {
1487 Patterns.erase(Patterns.begin()+i);
1488 --i; --e;
1489 ErasedPatterns = true;
1490 }
1491 }
1492 return ErasedPatterns;
1493}
1494
Chris Lattner8bc74722006-01-29 04:25:26 +00001495/// EmitPatterns - Emit code for at least one pattern, but try to group common
1496/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001497void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001498 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001499 &Patterns, unsigned Indent,
Daniel Dunbar1a551802009-07-03 00:10:29 +00001500 raw_ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001501 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001502 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001503 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001504
1505 if (Patterns.empty()) return;
1506
Chris Lattner24e00a42006-01-29 04:41:05 +00001507 // Figure out how many patterns share the next code line. Explicitly copy
1508 // FirstCodeLine so that we don't invalidate a reference when changing
1509 // Patterns.
1510 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001511 unsigned LastMatch = Patterns.size()-1;
1512 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1513 --LastMatch;
1514
1515 // If not all patterns share this line, split the list into two pieces. The
1516 // first chunk will use this line, the second chunk won't.
1517 if (LastMatch != 0) {
1518 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1519 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1520
1521 // FIXME: Emit braces?
1522 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001523 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001524 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1525 Pattern.getSrcPattern()->print(OS);
1526 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1527 Pattern.getDstPattern()->print(OS);
1528 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001529 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001530 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001531 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001532 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001533 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001534 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001535 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001536 }
Evan Cheng676d7312006-08-26 00:59:04 +00001537 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001538 OS << std::string(Indent, ' ') << "{\n";
1539 Indent += 2;
1540 }
1541 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001542 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001543 Indent -= 2;
1544 OS << std::string(Indent, ' ') << "}\n";
1545 }
1546
1547 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001548 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001549 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1550 Pattern.getSrcPattern()->print(OS);
1551 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1552 Pattern.getDstPattern()->print(OS);
1553 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001554 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001555 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001556 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001557 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001558 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001559 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001560 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001561 }
1562 EmitPatterns(Other, Indent, OS);
1563 return;
1564 }
1565
Chris Lattner24e00a42006-01-29 04:41:05 +00001566 // Remove this code from all of the patterns that share it.
1567 bool ErasedPatterns = EraseCodeLine(Patterns);
1568
Evan Cheng676d7312006-08-26 00:59:04 +00001569 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001570
1571 // Otherwise, every pattern in the list has this line. Emit it.
1572 if (!isPredicate) {
1573 // Normal code.
1574 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1575 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001576 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1577
1578 // If the next code line is another predicate, and if all of the pattern
1579 // in this group share the same next line, emit it inline now. Do this
1580 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001581 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00001582 // Check that all of the patterns in Patterns end with the same predicate.
Chris Lattner24e00a42006-01-29 04:41:05 +00001583 bool AllEndWithSamePredicate = true;
1584 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1585 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1586 AllEndWithSamePredicate = false;
1587 break;
1588 }
1589 // If all of the predicates aren't the same, we can't share them.
1590 if (!AllEndWithSamePredicate) break;
1591
1592 // Otherwise we can. Emit it shared now.
1593 OS << " &&\n" << std::string(Indent+4, ' ')
1594 << Patterns.back().second.back().second;
1595 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001596 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001597
1598 OS << ") {\n";
1599 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001600 }
1601
1602 EmitPatterns(Patterns, Indent, OS);
1603
1604 if (isPredicate)
1605 OS << std::string(Indent-2, ' ') << "}\n";
1606}
1607
Evan Cheng892aaf82006-11-08 23:01:03 +00001608static std::string getLegalCName(std::string OpName) {
1609 std::string::size_type pos = OpName.find("::");
1610 if (pos != std::string::npos)
1611 OpName.replace(pos, 2, "_");
1612 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001613}
1614
Daniel Dunbar1a551802009-07-03 00:10:29 +00001615void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001616 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattnerda272d12010-02-15 08:04:42 +00001617
Dan Gohman1e0ee4b2008-08-20 21:45:57 +00001618 // Get the namespace to insert instructions into.
1619 std::string InstNS = Target.getInstNamespace();
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001620 if (!InstNS.empty()) InstNS += "::";
1621
Chris Lattner602f6922006-01-04 00:25:00 +00001622 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001623 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001624 // All unique target node emission functions.
1625 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001626 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001627 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001628 const PatternToMatch &Pattern = *I;
Chris Lattner6cefb772008-01-05 22:25:12 +00001629 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001630 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001631 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001632 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001633 } else {
1634 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001635 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001636 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001637 push_back(&Pattern);
Chris Lattner47661322010-02-14 22:22:58 +00001638 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001639 std::vector<Record*> OpNodes = CP->getRootNodes();
1640 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001641 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1642 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001643 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001644 }
1645 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001646 errs() << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001647 Node->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001648 errs() << "' on tree pattern '";
1649 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001650 exit(1);
1651 }
1652 }
1653 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001654
1655 // For each opcode, there might be multiple select functions, one per
1656 // ValueType of the node (or its first operand if it doesn't produce a
1657 // non-chain result.
1658 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1659
Chris Lattner602f6922006-01-04 00:25:00 +00001660 // Emit one Select_* method for each top-level opcode. We do this instead of
1661 // emitting one giant switch statement to support compilers where this will
1662 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001663 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001664 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1665 PBOI != E; ++PBOI) {
1666 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001667 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001668 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1669
Chris Lattner706d2d32006-08-09 16:44:44 +00001670 // Split them into groups by type.
Owen Anderson825b72b2009-08-11 20:47:22 +00001671 std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001672 std::vector<const PatternToMatch*> > PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001673 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001674 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001675 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner9783d622008-08-26 07:01:28 +00001676 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Chris Lattner706d2d32006-08-09 16:44:44 +00001677 }
1678
Owen Anderson825b72b2009-08-11 20:47:22 +00001679 for (std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001680 std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001681 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1682 ++II) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001683 MVT::SimpleValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001684 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman0540e172008-10-15 06:17:21 +00001685 typedef std::pair<unsigned, std::string> CodeLine;
1686 typedef std::vector<CodeLine> CodeList;
1687 typedef CodeList::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001688
Chris Lattner60d81392008-01-05 22:30:17 +00001689 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001690 std::vector<std::vector<std::string> > PatternOpcodes;
1691 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001692 std::vector<std::set<std::string> > PatternDecls;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001693 std::vector<bool> OutputIsVariadicFlags;
1694 std::vector<unsigned> NumInputRootOpsCounts;
Chris Lattner706d2d32006-08-09 16:44:44 +00001695 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1696 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001697 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001698 std::vector<std::string> TargetOpcodes;
1699 std::vector<std::string> TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001700 bool OutputIsVariadic;
1701 unsigned NumInputRootOps;
Chris Lattner706d2d32006-08-09 16:44:44 +00001702 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001703 TargetOpcodes, TargetVTs,
1704 OutputIsVariadic, NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001705 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1706 PatternDecls.push_back(GeneratedDecl);
1707 PatternOpcodes.push_back(TargetOpcodes);
1708 PatternVTs.push_back(TargetVTs);
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001709 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1710 NumInputRootOpsCounts.push_back(NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001711 }
1712
Chris Lattner706d2d32006-08-09 16:44:44 +00001713 // Factor target node emission code (emitted by EmitResultCode) into
1714 // separate functions. Uniquing and share them among all instruction
1715 // selection routines.
1716 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1717 CodeList &GeneratedCode = CodeForPatterns[i].second;
1718 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1719 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001720 std::set<std::string> Decls = PatternDecls[i];
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001721 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1722 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001723 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001724 int CodeSize = (int)GeneratedCode.size();
1725 int LastPred = -1;
1726 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001727 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001728 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001729 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1730 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001731 }
1732
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001733 std::string CalleeCode = "(SDNode *N";
Evan Cheng9ade2182006-08-26 05:34:46 +00001734 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001735 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1736 CalleeCode += ", unsigned Opc" + utostr(j);
1737 CallerCode += ", " + TargetOpcodes[j];
1738 }
1739 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Owen Anderson69110c92009-09-11 09:01:57 +00001740 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
Chris Lattner706d2d32006-08-09 16:44:44 +00001741 CallerCode += ", " + TargetVTs[j];
1742 }
Evan Chengf5493192006-08-26 01:02:19 +00001743 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001744 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001745 std::string Name = *I;
Dan Gohman475871a2008-07-27 21:46:04 +00001746 CalleeCode += ", SDValue &" + Name;
Evan Cheng676d7312006-08-26 00:59:04 +00001747 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001748 }
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001749
1750 if (OutputIsVariadic) {
1751 CalleeCode += ", unsigned NumInputRootOps";
1752 CallerCode += ", " + utostr(NumInputRootOps);
1753 }
1754
Chris Lattner706d2d32006-08-09 16:44:44 +00001755 CallerCode += ");";
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001756 CalleeCode += ") {\n";
Evan Cheng676d7312006-08-26 00:59:04 +00001757
1758 for (std::vector<std::string>::const_reverse_iterator
1759 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1760 CalleeCode += " " + *I + "\n";
1761
Evan Chengf5493192006-08-26 01:02:19 +00001762 for (int j = LastPred+1; j < CodeSize; ++j)
1763 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001764 for (int j = LastPred+1; j < CodeSize; ++j)
1765 GeneratedCode.pop_back();
1766 CalleeCode += "}\n";
1767
1768 // Uniquing the emission routines.
1769 unsigned EmitFuncNum;
1770 std::map<std::string, unsigned>::iterator EFI =
1771 EmitFunctions.find(CalleeCode);
1772 if (EFI != EmitFunctions.end()) {
1773 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001774 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001775 EmitFuncNum = EmitFunctions.size();
1776 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001777 // Prevent emission routines from being inlined to reduce selection
1778 // routines stack frame sizes.
1779 OS << "DISABLE_INLINE ";
Evan Cheng06d64702006-08-11 08:59:35 +00001780 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001781 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001782
Chris Lattner706d2d32006-08-09 16:44:44 +00001783 // Replace the emission code within selection routines with calls to the
1784 // emission functions.
Chris Lattnera0cdf172010-02-13 20:06:50 +00001785 if (GenDebug)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001786 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001787 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1788 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1789 if (GenDebug) {
1790 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1791 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1792 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1793 GeneratedCode.push_back(std::make_pair(0, "}"));
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001794 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001795 }
1796 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001797 }
1798
Chris Lattner706d2d32006-08-09 16:44:44 +00001799 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001800 std::string OpVTStr;
Owen Anderson825b72b2009-08-11 20:47:22 +00001801 if (OpVT == MVT::iPTR) {
Chris Lattner33a40042006-11-14 22:17:10 +00001802 OpVTStr = "_iPTR";
Owen Anderson825b72b2009-08-11 20:47:22 +00001803 } else if (OpVT == MVT::iPTRAny) {
Mon P Wange3b3a722008-07-30 04:36:53 +00001804 OpVTStr = "_iPTRAny";
Owen Anderson825b72b2009-08-11 20:47:22 +00001805 } else if (OpVT == MVT::isVoid) {
Chris Lattner33a40042006-11-14 22:17:10 +00001806 // Nodes with a void result actually have a first result type of either
1807 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1808 // void to this case, we handle it specially here.
1809 } else {
Owen Anderson825b72b2009-08-11 20:47:22 +00001810 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
Chris Lattner33a40042006-11-14 22:17:10 +00001811 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001812 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1813 OpcodeVTMap.find(OpName);
1814 if (OpVTI == OpcodeVTMap.end()) {
1815 std::vector<std::string> VTSet;
1816 VTSet.push_back(OpVTStr);
1817 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1818 } else
1819 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001820
Dan Gohman0540e172008-10-15 06:17:21 +00001821 // We want to emit all of the matching code now. However, we want to emit
1822 // the matches in order of minimal cost. Sort the patterns so the least
1823 // cost one is at the start.
1824 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1825 PatternSortingPredicate(CGP));
1826
1827 // Scan the code to see if all of the patterns are reachable and if it is
1828 // possible that the last one might not match.
1829 bool mightNotMatch = true;
1830 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1831 CodeList &GeneratedCode = CodeForPatterns[i].second;
1832 mightNotMatch = false;
1833
1834 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1835 if (GeneratedCode[j].first == 1) { // predicate.
1836 mightNotMatch = true;
1837 break;
1838 }
1839 }
1840
1841 // If this pattern definitely matches, and if it isn't the last one, the
1842 // patterns after it CANNOT ever match. Error out.
1843 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001844 errs() << "Pattern '";
1845 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1846 errs() << "' is impossible to select!\n";
Dan Gohman0540e172008-10-15 06:17:21 +00001847 exit(1);
1848 }
1849 }
1850
Chris Lattner706d2d32006-08-09 16:44:44 +00001851 // Loop through and reverse all of the CodeList vectors, as we will be
1852 // accessing them from their logical front, but accessing the end of a
1853 // vector is more efficient.
1854 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1855 CodeList &GeneratedCode = CodeForPatterns[i].second;
1856 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001857 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001858
1859 // Next, reverse the list of patterns itself for the same reason.
1860 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1861
Dan Gohman63e3e632009-01-29 01:37:18 +00001862 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001863 << OpVTStr << "(SDNode *N) {\n";
Dan Gohman63e3e632009-01-29 01:37:18 +00001864
Chris Lattner706d2d32006-08-09 16:44:44 +00001865 // Emit all of the patterns now, grouped together to share code.
1866 EmitPatterns(CodeForPatterns, 2, OS);
1867
Chris Lattner64906972006-09-21 18:28:27 +00001868 // If the last pattern has predicates (which could fail) emit code to
1869 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001870 if (mightNotMatch) {
Dan Gohman31bd42b2008-09-27 23:53:14 +00001871 OS << "\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00001872 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1873 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
Dan Gohman31bd42b2008-09-27 23:53:14 +00001874 OpName != "ISD::INTRINSIC_VOID")
1875 OS << " CannotYetSelect(N);\n";
1876 else
1877 OS << " CannotYetSelectIntrinsic(N);\n";
1878
1879 OS << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001880 }
1881 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001882 }
Chris Lattner602f6922006-01-04 00:25:00 +00001883 }
1884
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001885 OS << "// The main instruction selector code.\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001886 << "SDNode *SelectCode(SDNode *N) {\n"
1887 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1888 << " switch (N->getOpcode()) {\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001889 << " default:\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001890 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001891 << " break;\n"
1892 << " case ISD::EntryToken: // These nodes remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001893 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001894 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001895 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001896 << " case ISD::TargetConstant:\n"
Nate Begemane1795842008-02-14 08:57:00 +00001897 << " case ISD::TargetConstantFP:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001898 << " case ISD::TargetConstantPool:\n"
1899 << " case ISD::TargetFrameIndex:\n"
Bill Wendling056292f2008-09-16 21:48:12 +00001900 << " case ISD::TargetExternalSymbol:\n"
Dan Gohman8c2b5252009-10-30 01:27:03 +00001901 << " case ISD::TargetBlockAddress:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001902 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001903 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohman8be6bbe2008-11-05 04:14:16 +00001904 << " case ISD::TargetGlobalAddress:\n"
1905 << " case ISD::TokenFactor:\n"
1906 << " case ISD::CopyFromReg:\n"
1907 << " case ISD::CopyToReg: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001908 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001909 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001910 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001911 << " case ISD::AssertZext: {\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001912 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001913 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001914 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001915 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohmancd920d92008-07-02 23:23:19 +00001916 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Chengda47e6e2008-03-15 00:03:38 +00001917 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001918
Chris Lattner602f6922006-01-04 00:25:00 +00001919 // Loop over all of the case statements, emiting a call to each method we
1920 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001921 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001922 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1923 PBOI != E; ++PBOI) {
1924 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001925 // Potentially multiple versions of select for this opcode. One for each
1926 // ValueType of the node (or its first true operand if it doesn't produce a
1927 // result.
1928 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1929 OpcodeVTMap.find(OpName);
1930 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00001931 OS << " case " << OpName << ": {\n";
Dale Johannesen3b895cf2009-05-12 22:32:29 +00001932 // If we have only one variant and it's the default, elide the
1933 // switch. Marginally faster, and makes MSVC happier.
1934 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1935 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1936 OS << " break;\n";
1937 OS << " }\n";
1938 continue;
1939 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001940 // Keep track of whether we see a pattern that has an iPtr result.
1941 bool HasPtrPattern = false;
1942 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00001943
Evan Cheng425e8c72007-09-04 20:18:28 +00001944 OS << " switch (NVT) {\n";
1945 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1946 std::string &VTStr = OpVTs[i];
1947 if (VTStr.empty()) {
1948 HasDefaultPattern = true;
1949 continue;
1950 }
Chris Lattner717a6112006-11-14 21:50:27 +00001951
Evan Cheng425e8c72007-09-04 20:18:28 +00001952 // If this is a match on iPTR: don't emit it directly, we need special
1953 // code.
1954 if (VTStr == "_iPTR") {
1955 HasPtrPattern = true;
1956 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00001957 }
Owen Anderson825b72b2009-08-11 20:47:22 +00001958 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng425e8c72007-09-04 20:18:28 +00001959 << " return Select_" << getLegalCName(OpName)
1960 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001961 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001962 OS << " default:\n";
1963
1964 // If there is an iPTR result version of this pattern, emit it here.
1965 if (HasPtrPattern) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001966 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00001967 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1968 }
1969 if (HasDefaultPattern) {
1970 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1971 }
1972 OS << " break;\n";
1973 OS << " }\n";
1974 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001975 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00001976 }
Chris Lattner81303322005-09-23 19:36:15 +00001977
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001978 OS << " } // end of big switch.\n\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001979 << " if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1980 << " N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1981 << " N->getOpcode() != ISD::INTRINSIC_VOID) {\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00001982 << " CannotYetSelect(N);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00001983 << " } else {\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00001984 << " CannotYetSelectIntrinsic(N);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00001985 << " }\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00001986 << " return NULL;\n"
1987 << "}\n\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001988}
1989
Daniel Dunbar1a551802009-07-03 00:10:29 +00001990void DAGISelEmitter::run(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001991 EmitSourceFileHeader("DAG Instruction Selector for the " +
1992 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001993
Chris Lattner1f39e292005-09-14 00:09:24 +00001994 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1995 << "// *** instruction selector class. These functions are really "
1996 << "methods.\n\n";
Chris Lattnerf8dc0612008-02-03 06:49:24 +00001997
Roman Levenstein6422e8a2008-05-14 10:17:11 +00001998 OS << "// Include standard, target-independent definitions and methods used\n"
1999 << "// by the instruction selector.\n";
Mike Stumpfe095f32009-05-04 18:40:41 +00002000 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00002001
Chris Lattner443e3f92008-01-05 22:54:53 +00002002 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00002003 EmitPredicateFunctions(OS);
2004
Chris Lattner569f1212009-08-23 04:44:11 +00002005 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
Chris Lattnerfe718932008-01-06 01:10:31 +00002006 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00002007 I != E; ++I) {
Chris Lattner569f1212009-08-23 04:44:11 +00002008 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
2009 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
2010 DEBUG(errs() << "\n");
Bill Wendlingf5da1332006-12-07 22:21:48 +00002011 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00002012
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002013 // At this point, we have full information about the 'Patterns' we need to
2014 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002015 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002016 EmitInstructionSelector(OS);
2017
Chris Lattnerda272d12010-02-15 08:04:42 +00002018#if 0
2019 MatcherNode *Matcher = 0;
2020 // Walk the patterns backwards, building a matcher for each and adding it to
2021 // the matcher for the whole target.
2022 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
2023 E = CGP.ptm_end(); I != E;) {
2024 const PatternToMatch &Pattern = *--E;
2025 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
2026
2027 if (Matcher == 0)
2028 Matcher = N;
2029 else
2030 Matcher = new PushMatcherNode(N, Matcher);
2031 }
2032
2033
2034 EmitMatcherTable(Matcher, OS);
2035
2036
2037 //Matcher->dump();
2038 delete Matcher;
2039#endif
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002040}