blob: b9ef3da5cac4030d06dab4c079af1e1127357d9c [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 Lattner05814af2005-09-28 17:57:56 +000050/// getPatternSize - Return the 'size' of this pattern. We want to match large
51/// patterns before small ones. This is used to determine the size of a
52/// pattern.
Chris Lattnerfe718932008-01-06 01:10:31 +000053static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Owen Andersone50ed302009-08-10 22:56:29 +000054 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +000056 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR ||
59 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +000060 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +000061 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +000062 // If the root node is a ConstantSDNode, increases its size.
63 // e.g. (set R32:$dst, 0).
64 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000065 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +000066
67 // FIXME: This is a hack to statically increase the priority of patterns
68 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
69 // Later we can allow complexity / cost for each pattern to be (optionally)
70 // specified. To get best possible pattern match we'll need to dynamically
71 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner47661322010-02-14 22:22:58 +000072 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000073 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +000074 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +000075
76 // If this node has some predicate function that must match, it adds to the
77 // complexity of this node.
Dan Gohman0540e172008-10-15 06:17:21 +000078 if (!P->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +000079 ++Size;
80
Chris Lattner05814af2005-09-28 17:57:56 +000081 // Count children in the count if they are also nodes.
82 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
83 TreePatternNode *Child = P->getChild(i);
Owen Anderson825b72b2009-08-11 20:47:22 +000084 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner6cefb772008-01-05 22:25:12 +000085 Size += getPatternSize(Child, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000086 else if (Child->isLeaf()) {
87 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000088 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Chris Lattner05446e72010-02-16 23:13:59 +000089 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner6cefb772008-01-05 22:25:12 +000090 Size += getPatternSize(Child, CGP);
Dan Gohman0540e172008-10-15 06:17:21 +000091 else if (!Child->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +000092 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +000093 }
Chris Lattner05814af2005-09-28 17:57:56 +000094 }
95
96 return Size;
97}
98
99/// getResultPatternCost - Compute the number of instructions for this pattern.
100/// This is a temporary hack. We should really include the instruction
101/// latencies in this calculation.
Chris Lattner6cefb772008-01-05 22:25:12 +0000102static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000103 CodeGenDAGPatterns &CGP) {
Chris Lattner05814af2005-09-28 17:57:56 +0000104 if (P->isLeaf()) return 0;
105
Evan Chengfbad7082006-02-18 02:33:09 +0000106 unsigned Cost = 0;
107 Record *Op = P->getOperator();
108 if (Op->isSubClassOf("Instruction")) {
109 Cost++;
Chris Lattner6cefb772008-01-05 22:25:12 +0000110 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohman533297b2009-10-29 18:10:34 +0000111 if (II.usesCustomInserter)
Evan Chengfbad7082006-02-18 02:33:09 +0000112 Cost += 10;
113 }
Chris Lattner05814af2005-09-28 17:57:56 +0000114 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000115 Cost += getResultPatternCost(P->getChild(i), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000116 return Cost;
117}
118
Evan Chenge6f32032006-07-19 00:24:41 +0000119/// getResultPatternCodeSize - Compute the code size of instructions for this
120/// pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000121static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000122 CodeGenDAGPatterns &CGP) {
Evan Chenge6f32032006-07-19 00:24:41 +0000123 if (P->isLeaf()) return 0;
124
125 unsigned Cost = 0;
126 Record *Op = P->getOperator();
127 if (Op->isSubClassOf("Instruction")) {
128 Cost += Op->getValueAsInt("CodeSize");
129 }
130 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000131 Cost += getResultPatternSize(P->getChild(i), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000132 return Cost;
133}
134
Chris Lattner05814af2005-09-28 17:57:56 +0000135// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
136// In particular, we want to match maximal patterns first and lowest cost within
137// a particular complexity first.
138struct PatternSortingPredicate {
Chris Lattnerfe718932008-01-06 01:10:31 +0000139 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
140 CodeGenDAGPatterns &CGP;
Evan Cheng0fc71982005-12-08 02:00:36 +0000141
Dan Gohman0540e172008-10-15 06:17:21 +0000142 typedef std::pair<unsigned, std::string> CodeLine;
143 typedef std::vector<CodeLine> CodeList;
Dan Gohman0540e172008-10-15 06:17:21 +0000144
145 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
146 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
147 const PatternToMatch *LHS = LHSPair.first;
148 const PatternToMatch *RHS = RHSPair.first;
149
Chris Lattner6cefb772008-01-05 22:25:12 +0000150 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
151 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Evan Chengc81d2a02006-04-19 20:36:09 +0000152 LHSSize += LHS->getAddedComplexity();
153 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +0000154 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
155 if (LHSSize < RHSSize) return false;
156
157 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner6cefb772008-01-05 22:25:12 +0000158 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
159 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000160 if (LHSCost < RHSCost) return true;
161 if (LHSCost > RHSCost) return false;
162
Chris Lattner6cefb772008-01-05 22:25:12 +0000163 return getResultPatternSize(LHS->getDstPattern(), CGP) <
164 getResultPatternSize(RHS->getDstPattern(), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000165 }
166};
167
Jim Grosbach54f30222009-03-25 23:28:33 +0000168/// getRegisterValueType - Look up and return the ValueType of the specified
169/// register. If the register is a member of multiple register classes which
Owen Anderson825b72b2009-08-11 20:47:22 +0000170/// have different associated types, return MVT::Other.
Chris Lattner8e946be2010-02-21 03:22:59 +0000171static MVT::SimpleValueType getRegisterValueType(Record *R,
172 const CodeGenTarget &T) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000173 bool FoundRC = false;
Owen Anderson825b72b2009-08-11 20:47:22 +0000174 MVT::SimpleValueType VT = MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000175 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
176 std::vector<CodeGenRegisterClass>::const_iterator RC;
177 std::vector<Record*>::const_iterator Element;
178
179 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
180 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
181 if (Element != (*RC).Elements.end()) {
182 if (!FoundRC) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000183 FoundRC = true;
Jim Grosbach54f30222009-03-25 23:28:33 +0000184 VT = (*RC).getValueTypeNum(0);
185 } else {
186 // In multiple RC's
187 if (VT != (*RC).getValueTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000188 // Types of the RC's do not agree. Return MVT::Other. The
Jim Grosbach54f30222009-03-25 23:28:33 +0000189 // target is responsible for handling this.
Owen Anderson825b72b2009-08-11 20:47:22 +0000190 return MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000191 }
192 }
193 }
194 }
195 return VT;
Evan Cheng66a48bb2005-12-01 00:18:45 +0000196}
197
Evan Chengf9d03182008-07-03 08:39:51 +0000198static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
199 return CGP.getSDNodeInfo(Op).getEnumName();
200}
201
Chris Lattnerdc32f982008-01-05 22:43:57 +0000202//===----------------------------------------------------------------------===//
Chris Lattner443e3f92008-01-05 22:54:53 +0000203// Node Transformation emitter implementation.
204//
Daniel Dunbar1a551802009-07-03 00:10:29 +0000205void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
Chris Lattner443e3f92008-01-05 22:54:53 +0000206 // Walk the pattern fragments, adding them to a map, which sorts them by
207 // name.
Chris Lattnerfe718932008-01-06 01:10:31 +0000208 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner443e3f92008-01-05 22:54:53 +0000209 NXsByNameTy NXsByName;
210
Chris Lattnerfe718932008-01-06 01:10:31 +0000211 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner443e3f92008-01-05 22:54:53 +0000212 I != E; ++I)
213 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
214
215 OS << "\n// Node transformations.\n";
216
217 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
218 I != E; ++I) {
219 Record *SDNode = I->second.first;
220 std::string Code = I->second.second;
221
222 if (Code.empty()) continue; // Empty code? Skip it.
223
Chris Lattner200c57e2008-01-05 22:58:54 +0000224 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner443e3f92008-01-05 22:54:53 +0000225 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
226
Dan Gohman475871a2008-07-27 21:46:04 +0000227 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner443e3f92008-01-05 22:54:53 +0000228 << ") {\n";
229 if (ClassName != "SDNode")
230 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
231 OS << Code << "\n}\n";
232 }
233}
234
235//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +0000236// Predicate emitter implementation.
237//
238
Daniel Dunbar1a551802009-07-03 00:10:29 +0000239void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
Chris Lattnerdc32f982008-01-05 22:43:57 +0000240 OS << "\n// Predicate functions.\n";
241
242 // Walk the pattern fragments, adding them to a map, which sorts them by
243 // name.
244 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
245 PFsByNameTy PFsByName;
246
Chris Lattnerfe718932008-01-06 01:10:31 +0000247 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000248 I != E; ++I)
249 PFsByName.insert(std::make_pair(I->first->getName(), *I));
250
251
252 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
253 I != E; ++I) {
254 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
255 TreePattern *P = I->second.second;
256
257 // If there is a code init for this fragment, emit the predicate code.
258 std::string Code = PatFragRecord->getValueAsCode("Predicate");
259 if (Code.empty()) continue;
260
261 if (P->getOnlyTree()->isLeaf())
262 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattnerccba15f2010-02-16 07:26:36 +0000263 << "(SDNode *N) const {\n";
Chris Lattnerdc32f982008-01-05 22:43:57 +0000264 else {
265 std::string ClassName =
Chris Lattner200c57e2008-01-05 22:58:54 +0000266 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000267 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
268
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattnerccba15f2010-02-16 07:26:36 +0000270 << "(SDNode *" << C2 << ") const {\n";
Chris Lattnerdc32f982008-01-05 22:43:57 +0000271 if (ClassName != "SDNode")
272 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
273 }
274 OS << Code << "\n}\n";
275 }
276
277 OS << "\n\n";
278}
279
280
281//===----------------------------------------------------------------------===//
282// PatternCodeEmitter implementation.
283//
Evan Chengb915f312005-12-09 22:45:35 +0000284class PatternCodeEmitter {
285private:
Chris Lattnerfe718932008-01-06 01:10:31 +0000286 CodeGenDAGPatterns &CGP;
Evan Chengb915f312005-12-09 22:45:35 +0000287
Evan Cheng58e84a62005-12-14 22:02:59 +0000288 // Predicates.
Dan Gohman22bb3112008-08-22 00:20:26 +0000289 std::string PredicateCheck;
Evan Cheng59413202006-04-19 18:07:24 +0000290 // Pattern cost.
291 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +0000292 // Instruction selector pattern.
293 TreePatternNode *Pattern;
294 // Matched instruction.
295 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000296
Evan Chengb915f312005-12-09 22:45:35 +0000297 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +0000298 std::map<std::string, std::string> VariableMap;
Evan Chenga58891f2008-02-05 22:50:29 +0000299 // Name of the folded node which produces a flag.
300 std::pair<std::string, unsigned> FoldedFlag;
Evan Chengb915f312005-12-09 22:45:35 +0000301 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +0000302 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +0000303 // Original input chain(s).
304 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +0000305 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +0000306
Dan Gohman69de1932008-02-06 22:27:42 +0000307 /// LSI - Load/Store information.
308 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
309 /// for each memory access. This facilitates the use of AliasAnalysis in
310 /// the backend.
311 std::vector<std::string> LSI;
312
Evan Cheng676d7312006-08-26 00:59:04 +0000313 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000314 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000315 /// tested, and if true, the match fails) [when 1], or normal code to emit
316 /// [when 0], or initialization code to emit [when 2].
317 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman475871a2008-07-27 21:46:04 +0000318 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Evan Cheng21ad3922006-02-07 00:37:41 +0000319 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000320 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000321 /// TargetOpcodes - The target specific opcodes used by the resulting
322 /// instructions.
323 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000324 std::vector<std::string> &TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000325 /// OutputIsVariadic - Records whether the instruction output pattern uses
326 /// variable_ops. This requires that the Emit function be passed an
327 /// additional argument to indicate where the input varargs operands
328 /// begin.
329 bool &OutputIsVariadic;
330 /// NumInputRootOps - Records the number of operands the root node of the
331 /// input pattern has. This information is used in the generated code to
332 /// pass to Emit functions when variable_ops processing is needed.
333 unsigned &NumInputRootOps;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000334
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000335 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000336 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000337 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000338 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000339
340 void emitCheck(const std::string &S) {
341 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000342 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000343 }
344 void emitCode(const std::string &S) {
345 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000346 GeneratedCode.push_back(std::make_pair(0, S));
347 }
348 void emitInit(const std::string &S) {
349 if (!S.empty())
350 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000351 }
Evan Chengf5493192006-08-26 01:02:19 +0000352 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000353 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000354 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000355 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000356 void emitOpcode(const std::string &Opc) {
357 TargetOpcodes.push_back(Opc);
358 OpcNo++;
359 }
Evan Chengf8729402006-07-16 06:12:52 +0000360 void emitVT(const std::string &VT) {
361 TargetVTs.push_back(VT);
362 VTNo++;
363 }
Evan Chengb915f312005-12-09 22:45:35 +0000364public:
Dan Gohman22bb3112008-08-22 00:20:26 +0000365 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Evan Cheng58e84a62005-12-14 22:02:59 +0000366 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000367 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000368 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000369 std::vector<std::string> &to,
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000370 std::vector<std::string> &tv,
371 bool &oiv,
372 unsigned &niro)
Dan Gohman22bb3112008-08-22 00:20:26 +0000373 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000374 GeneratedCode(gc), GeneratedDecl(gd),
375 TargetOpcodes(to), TargetVTs(tv),
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000376 OutputIsVariadic(oiv), NumInputRootOps(niro),
Chris Lattner706d2d32006-08-09 16:44:44 +0000377 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000378
379 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
380 /// if the match fails. At this point, we already know that the opcode for N
381 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000382 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
383 const std::string &RootName, const std::string &ChainSuffix,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000384 bool &FoundChain);
Chris Lattner39e73f72006-10-11 04:05:55 +0000385
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000386 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb85356242008-01-31 07:27:46 +0000387 const std::string &RootName,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000388 const std::string &ChainSuffix, bool &FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000389
390 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
391 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000392 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000393 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000394 bool InFlagDecled, bool ResNodeDecled,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000395 bool LikeLeaf = false, bool isRoot = false);
Evan Chengb915f312005-12-09 22:45:35 +0000396
Chris Lattner488580c2006-01-28 19:06:51 +0000397 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
398 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +0000399 /// 'Pat' may be missing types. If we find an unresolved type to add a check
400 /// for, this returns true otherwise false if Pat has all types.
401 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +0000402 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +0000403 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +0000404 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +0000405 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +0000406 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +0000407 // The top level node type is checked outside of the select function.
408 if (!isRoot)
Anton Korobeynikovc2fd9192009-11-08 12:14:54 +0000409 emitCheck(Prefix + ".getValueType() == " +
Chris Lattner706d2d32006-08-09 16:44:44 +0000410 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +0000411 return true;
Evan Chengb915f312005-12-09 22:45:35 +0000412 }
413
Chris Lattner47661322010-02-14 22:22:58 +0000414 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000415 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
416 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
417 Prefix + utostr(OpNo)))
418 return true;
419 return false;
420 }
421
422private:
Evan Cheng54597732006-01-26 00:22:25 +0000423 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +0000424 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +0000425 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +0000426 bool &ChainEmitted, bool &InFlagDecled,
427 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000428 const CodeGenTarget &T = CGP.getTargetInfo();
Chris Lattner47661322010-02-14 22:22:58 +0000429 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000430 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
431 TreePatternNode *Child = N->getChild(i);
432 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000433 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
434 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +0000435 } else {
436 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +0000437 if (!Child->getName().empty()) {
438 std::string Name = RootName + utostr(OpNo);
439 if (Duplicates.find(Name) != Duplicates.end())
440 // A duplicate! Do not emit a copy for this node.
441 continue;
442 }
443
Evan Chengb915f312005-12-09 22:45:35 +0000444 Record *RR = DI->getDef();
445 if (RR->isSubClassOf("Register")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000446 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
447 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000448 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000449 emitCode("SDValue InFlag = " +
450 getValueName(RootName + utostr(OpNo)) + ";");
Evan Cheng676d7312006-08-26 00:59:04 +0000451 InFlagDecled = true;
452 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000453 emitCode("InFlag = " +
454 getValueName(RootName + utostr(OpNo)) + ";");
Evan Chengb2c6d492006-01-11 22:16:13 +0000455 } else {
456 if (!ChainEmitted) {
Dan Gohman475871a2008-07-27 21:46:04 +0000457 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000458 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +0000459 ChainEmitted = true;
460 }
Evan Cheng676d7312006-08-26 00:59:04 +0000461 if (!InFlagDecled) {
Dan Gohman475871a2008-07-27 21:46:04 +0000462 emitCode("SDValue InFlag(0, 0);");
Evan Cheng676d7312006-08-26 00:59:04 +0000463 InFlagDecled = true;
464 }
Dale Johannesen874ae252009-06-02 03:12:52 +0000465 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
466 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000467 ", " + getNodeName(RootName) + "->getDebugLoc()" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000468 ", " + getQualifiedName(RR) +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000469 ", " + getValueName(RootName + utostr(OpNo)) +
470 ", InFlag).getNode();");
Dale Johannesen874ae252009-06-02 03:12:52 +0000471 ResNodeDecled = true;
Dan Gohman475871a2008-07-27 21:46:04 +0000472 emitCode(ChainName + " = SDValue(ResNode, 0);");
473 emitCode("InFlag = SDValue(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +0000474 }
475 }
476 }
477 }
478 }
Evan Cheng54597732006-01-26 00:22:25 +0000479
Chris Lattner8e946be2010-02-21 03:22:59 +0000480 if (N->NodeHasProperty(SDNPInFlag, CGP)) {
Evan Cheng676d7312006-08-26 00:59:04 +0000481 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000482 emitCode("SDValue InFlag = " + getNodeName(RootName) +
483 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000484 InFlagDecled = true;
485 } else
Chris Lattner8e946be2010-02-21 03:22:59 +0000486 abort();
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000487 emitCode("InFlag = " + getNodeName(RootName) +
488 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000489 }
Evan Chengb915f312005-12-09 22:45:35 +0000490 }
491};
492
Chris Lattnera0cdf172010-02-13 20:06:50 +0000493
494/// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
495/// if the match fails. At this point, we already know that the opcode for N
496/// matches, and the SDNode for the result has the RootName specified name.
497void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
498 const std::string &RootName,
499 const std::string &ChainSuffix,
500 bool &FoundChain) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000501 // Save loads/stores matched by a pattern.
502 if (!N->isLeaf() && N->getName().empty()) {
Chris Lattner47661322010-02-14 22:22:58 +0000503 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnera0cdf172010-02-13 20:06:50 +0000504 LSI.push_back(getNodeName(RootName));
505 }
506
507 bool isRoot = (P == NULL);
508 // Emit instruction predicates. Each predicate is just a string for now.
509 if (isRoot) {
510 // Record input varargs info.
511 NumInputRootOps = N->getNumChildren();
Chris Lattnera0cdf172010-02-13 20:06:50 +0000512 emitCheck(PredicateCheck);
513 }
514
515 if (N->isLeaf()) {
516 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
517 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
518 ")->getSExtValue() == INT64_C(" +
519 itostr(II->getValue()) + ")");
520 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000521 }
Chris Lattner05446e72010-02-16 23:13:59 +0000522 assert(N->getComplexPatternInfo(CGP) != 0 &&
523 "Cannot match this as a leaf value!");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000524 }
525
526 // If this node has a name associated with it, capture it in VariableMap. If
527 // we already saw this in the pattern, emit code to verify dagness.
528 if (!N->getName().empty()) {
529 std::string &VarMapEntry = VariableMap[N->getName()];
530 if (VarMapEntry.empty()) {
531 VarMapEntry = RootName;
532 } else {
533 // If we get here, this is a second reference to a specific name. Since
534 // we already have checked that the first reference is valid, we don't
535 // have to recursively match it, just check that it's the same as the
536 // previously named thing.
537 emitCheck(VarMapEntry + " == " + RootName);
538 return;
539 }
Chris Lattnera0cdf172010-02-13 20:06:50 +0000540 }
541
542
543 // Emit code to load the child nodes and match their contents recursively.
544 unsigned OpNo = 0;
Chris Lattner47661322010-02-14 22:22:58 +0000545 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
546 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000547 if (HasChain) {
548 if (NodeHasChain)
549 OpNo = 1;
550 if (!isRoot) {
Evan Cheng014bf212010-02-15 19:41:07 +0000551 // Check if it's profitable to fold the node. e.g. Check for multiple uses
552 // of actual result?
553 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner29c62702010-02-16 19:03:34 +0000554 if (!NodeHasChain) {
555 // If this is just an interior node, check to see if it has a single
556 // use. If the node has multiple uses and the pattern has a load as
557 // an operand, then we can't fold the load.
558 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattner92d3ada2010-02-16 22:35:06 +0000559 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000560 // If the immediate use can somehow reach this node through another
561 // path, then can't fold it either or it will create a cycle.
562 // e.g. In the following diagram, XX can reach ld through YY. If
563 // ld is folded into XX, then YY is both a predecessor and a successor
564 // of XX.
565 //
566 // [ld]
567 // ^ ^
568 // | |
569 // / \---
570 // / [YY]
571 // | ^
572 // [XX]-------|
Chris Lattnere39650a2010-02-16 06:10:58 +0000573
574 // We know we need the check if N's parent is not the root.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000575 bool NeedCheck = P != Pattern;
576 if (!NeedCheck) {
Chris Lattner29c62702010-02-16 19:03:34 +0000577 // If the parent is the root and the node has more than one operand,
578 // we need to check.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000579 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
580 NeedCheck =
581 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
582 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
583 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
584 PInfo.getNumOperands() > 1 ||
585 PInfo.hasProperty(SDNPHasChain) ||
586 PInfo.hasProperty(SDNPInFlag) ||
587 PInfo.hasProperty(SDNPOptInFlag);
588 }
589
590 if (NeedCheck) {
Chris Lattner29c62702010-02-16 19:03:34 +0000591 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
592 ", " + getNodeName(ParentName) + ", N)");
Evan Cheng014bf212010-02-15 19:41:07 +0000593 emitCheck("IsLegalToFold(" + getValueName(RootName) +
Chris Lattnera0cdf172010-02-13 20:06:50 +0000594 ", " + getNodeName(ParentName) + ", N)");
Chris Lattner29c62702010-02-16 19:03:34 +0000595 } else {
596 // Otherwise, just verify that the node only has a single use.
597 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000598 }
599 }
600 }
601
602 if (NodeHasChain) {
603 if (FoundChain) {
Chris Lattnerd9c1a342010-02-17 05:35:28 +0000604 emitCheck("IsChainCompatible(" + ChainName + ".getNode(), " +
605 getNodeName(RootName) + ")");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000606 OrigChains.push_back(std::make_pair(ChainName,
607 getValueName(RootName)));
608 } else
609 FoundChain = true;
610 ChainName = "Chain" + ChainSuffix;
Chris Lattner92d3ada2010-02-16 22:35:06 +0000611
612 if (!N->getComplexPatternInfo(CGP) ||
613 isRoot)
614 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
615 "->getOperand(0);");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000616 }
617 }
618
Chris Lattnera0cdf172010-02-13 20:06:50 +0000619 // If there are node predicates for this, emit the calls.
620 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
621 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
622
623 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
624 // a constant without a predicate fn that has more that one bit set, handle
625 // this as a special case. This is usually for targets that have special
626 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
627 // handling stuff). Using these instructions is often far more efficient
628 // than materializing the constant. Unfortunately, both the instcombiner
629 // and the dag combiner can often infer that bits are dead, and thus drop
630 // them from the mask in the dag. For example, it might turn 'AND X, 255'
631 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
632 // to handle this.
633 if (!N->isLeaf() &&
634 (N->getOperator()->getName() == "and" ||
635 N->getOperator()->getName() == "or") &&
636 N->getChild(1)->isLeaf() &&
637 N->getChild(1)->getPredicateFns().empty()) {
638 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
639 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
640 emitInit("SDValue " + RootName + "0" + " = " +
641 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
642 emitInit("SDValue " + RootName + "1" + " = " +
643 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
644
645 unsigned NTmp = TmpNo++;
646 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
647 " = dyn_cast<ConstantSDNode>(" +
648 getNodeName(RootName + "1") + ");");
649 emitCheck("Tmp" + utostr(NTmp));
650 const char *MaskPredicate = N->getOperator()->getName() == "or"
651 ? "CheckOrMask(" : "CheckAndMask(";
652 emitCheck(MaskPredicate + getValueName(RootName + "0") +
653 ", Tmp" + utostr(NTmp) +
654 ", INT64_C(" + itostr(II->getValue()) + "))");
655
656 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
657 ChainSuffix + utostr(0), FoundChain);
658 return;
659 }
660 }
661 }
662
663 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
664 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
665 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
666
667 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
668 ChainSuffix + utostr(OpNo), FoundChain);
669 }
670
Chris Lattner8e946be2010-02-21 03:22:59 +0000671 // Handle complex patterns.
672 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000673 std::string Fn = CP->getSelectFunc();
674 unsigned NumOps = CP->getNumOperands();
675 for (unsigned i = 0; i < NumOps; ++i) {
676 emitDecl("CPTmp" + RootName + "_" + utostr(i));
677 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
678 }
679 if (CP->hasProperty(SDNPHasChain)) {
680 emitDecl("CPInChain");
681 emitDecl("Chain" + ChainSuffix);
682 emitCode("SDValue CPInChain;");
683 emitCode("SDValue Chain" + ChainSuffix + ";");
684 }
685
Chris Lattner92d3ada2010-02-16 22:35:06 +0000686 std::string Code = Fn + "(N, "; // always pass in the root.
687 Code += getValueName(RootName);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000688 for (unsigned i = 0; i < NumOps; i++)
689 Code += ", CPTmp" + RootName + "_" + utostr(i);
690 if (CP->hasProperty(SDNPHasChain)) {
691 ChainName = "Chain" + ChainSuffix;
Chris Lattnere609a512010-02-17 00:31:50 +0000692 Code += ", CPInChain, " + ChainName;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000693 }
694 emitCheck(Code + ")");
695 }
696}
697
698void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
699 TreePatternNode *Parent,
700 const std::string &RootName,
701 const std::string &ChainSuffix,
702 bool &FoundChain) {
703 if (!Child->isLeaf()) {
704 // If it's not a leaf, recursively match.
705 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
706 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
707 CInfo.getEnumName());
708 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
709 bool HasChain = false;
Chris Lattner47661322010-02-14 22:22:58 +0000710 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000711 HasChain = true;
712 FoldedChains.push_back(std::make_pair(getValueName(RootName),
713 CInfo.getNumResults()));
714 }
Chris Lattner47661322010-02-14 22:22:58 +0000715 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000716 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
717 "Pattern folded multiple nodes which produce flags?");
718 FoldedFlag = std::make_pair(getValueName(RootName),
719 CInfo.getNumResults() + (unsigned)HasChain);
720 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000721 return;
722 }
723
724 if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
Chris Lattner92d3ada2010-02-16 22:35:06 +0000725 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
726 bool HasChain = false;
727
728 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
729 HasChain = true;
730 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
731 FoldedChains.push_back(std::make_pair("CPInChain",
732 PInfo.getNumResults()));
733 }
734 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
735 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
736 "Pattern folded multiple nodes which produce flags?");
737 FoldedFlag = std::make_pair(getValueName(RootName),
738 CP->getNumOperands() + (unsigned)HasChain);
739 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000740 return;
741 }
742
743 // If this child has a name associated with it, capture it in VarMap. If
744 // we already saw this in the pattern, emit code to verify dagness.
745 if (!Child->getName().empty()) {
746 std::string &VarMapEntry = VariableMap[Child->getName()];
747 if (VarMapEntry.empty()) {
748 VarMapEntry = getValueName(RootName);
749 } else {
750 // If we get here, this is a second reference to a specific name.
751 // Since we already have checked that the first reference is valid,
752 // we don't have to recursively match it, just check that it's the
753 // same as the previously named thing.
754 emitCheck(VarMapEntry + " == " + getValueName(RootName));
755 Duplicates.insert(getValueName(RootName));
756 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000757 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000758 }
759
760 // Handle leaves of various types.
761 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
762 Record *LeafRec = DI->getDef();
763 if (LeafRec->isSubClassOf("RegisterClass") ||
764 LeafRec->isSubClassOf("PointerLikeRegClass")) {
765 // Handle register references. Nothing to do here.
766 } else if (LeafRec->isSubClassOf("Register")) {
767 // Handle register references.
768 } else if (LeafRec->getName() == "srcvalue") {
769 // Place holder for SRCVALUE nodes. Nothing to do here.
770 } else if (LeafRec->isSubClassOf("ValueType")) {
771 // Make sure this is the specified value type.
772 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
773 ")->getVT() == MVT::" + LeafRec->getName());
774 } else if (LeafRec->isSubClassOf("CondCode")) {
775 // Make sure this is the specified cond code.
776 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
777 ")->get() == ISD::" + LeafRec->getName());
Chris Lattnera0cdf172010-02-13 20:06:50 +0000778 } else {
779#ifndef NDEBUG
780 Child->dump();
Chris Lattner5b08f772010-02-16 22:38:31 +0000781 errs() << " ";
Chris Lattnera0cdf172010-02-13 20:06:50 +0000782#endif
783 assert(0 && "Unknown leaf type!");
784 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000785
786 // If there are node predicates for this, emit the calls.
787 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
788 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
789 ")");
790 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000791 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000792
793 if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
794 unsigned NTmp = TmpNo++;
795 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
796 " = dyn_cast<ConstantSDNode>("+
797 getNodeName(RootName) + ");");
798 emitCheck("Tmp" + utostr(NTmp));
799 unsigned CTmp = TmpNo++;
800 emitCode("int64_t CN"+ utostr(CTmp) +
801 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
802 emitCheck("CN" + utostr(CTmp) + " == "
803 "INT64_C(" +itostr(II->getValue()) + ")");
804 return;
805 }
806#ifndef NDEBUG
807 Child->dump();
808#endif
809 assert(0 && "Unknown leaf type!");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000810}
811
812/// EmitResultCode - Emit the action for a pattern. Now that it has matched
813/// we actually have to build a DAG!
814std::vector<std::string>
815PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
816 std::vector<Record*> DstRegs,
817 bool InFlagDecled, bool ResNodeDecled,
818 bool LikeLeaf, bool isRoot) {
819 // List of arguments of getMachineNode() or SelectNodeTo().
820 std::vector<std::string> NodeOps;
821 // This is something selected from the pattern we matched.
822 if (!N->getName().empty()) {
823 const std::string &VarName = N->getName();
824 std::string Val = VariableMap[VarName];
Chris Lattnera0cdf172010-02-13 20:06:50 +0000825 if (Val.empty()) {
826 errs() << "Variable '" << VarName << " referenced but not defined "
827 << "and not caught earlier!\n";
828 abort();
829 }
Chris Lattnera0cdf172010-02-13 20:06:50 +0000830
Chris Lattnera0cdf172010-02-13 20:06:50 +0000831 unsigned ResNo = TmpNo++;
832 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
833 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
834 std::string CastType;
835 std::string TmpVar = "Tmp" + utostr(ResNo);
836 switch (N->getTypeNum(0)) {
837 default:
838 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
839 << " type as an immediate constant. Aborting\n";
840 abort();
841 case MVT::i1: CastType = "bool"; break;
842 case MVT::i8: CastType = "unsigned char"; break;
843 case MVT::i16: CastType = "unsigned short"; break;
844 case MVT::i32: CastType = "unsigned"; break;
845 case MVT::i64: CastType = "uint64_t"; break;
846 }
847 emitCode("SDValue " + TmpVar +
848 " = CurDAG->getTargetConstant(((" + CastType +
849 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
850 getEnumName(N->getTypeNum(0)) + ");");
Chris Lattner8e946be2010-02-21 03:22:59 +0000851 NodeOps.push_back(getValueName(TmpVar));
Chris Lattnera0cdf172010-02-13 20:06:50 +0000852 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
853 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
854 std::string TmpVar = "Tmp" + utostr(ResNo);
855 emitCode("SDValue " + TmpVar +
856 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
857 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
858 Val + ")->getValueType(0));");
Chris Lattner8e946be2010-02-21 03:22:59 +0000859 NodeOps.push_back(getValueName(TmpVar));
860 } else if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
861 for (unsigned i = 0; i < CP->getNumOperands(); ++i)
Chris Lattner47661322010-02-14 22:22:58 +0000862 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
Chris Lattner47661322010-02-14 22:22:58 +0000863 } else {
864 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
865 // node even if it isn't one. Don't select it.
866 if (!LikeLeaf) {
867 if (isRoot && N->isLeaf()) {
868 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
869 emitCode("return NULL;");
870 }
871 }
872 NodeOps.push_back(getValueName(Val));
Chris Lattnera0cdf172010-02-13 20:06:50 +0000873 }
874 return NodeOps;
875 }
876 if (N->isLeaf()) {
877 // If this is an explicit register reference, handle it.
878 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
879 unsigned ResNo = TmpNo++;
880 if (DI->getDef()->isSubClassOf("Register")) {
881 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
882 getQualifiedName(DI->getDef()) + ", " +
883 getEnumName(N->getTypeNum(0)) + ");");
884 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
885 return NodeOps;
886 } else if (DI->getDef()->getName() == "zero_reg") {
887 emitCode("SDValue Tmp" + utostr(ResNo) +
888 " = CurDAG->getRegister(0, " +
889 getEnumName(N->getTypeNum(0)) + ");");
890 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
891 return NodeOps;
892 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
893 // Handle a reference to a register class. This is used
894 // in COPY_TO_SUBREG instructions.
895 emitCode("SDValue Tmp" + utostr(ResNo) +
896 " = CurDAG->getTargetConstant(" +
897 getQualifiedName(DI->getDef()) + "RegClassID, " +
898 "MVT::i32);");
899 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
900 return NodeOps;
901 }
902 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
903 unsigned ResNo = TmpNo++;
904 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
905 emitCode("SDValue Tmp" + utostr(ResNo) +
906 " = CurDAG->getTargetConstant(0x" +
907 utohexstr((uint64_t) II->getValue()) +
908 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
909 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
910 return NodeOps;
911 }
912
913#ifndef NDEBUG
914 N->dump();
915#endif
916 assert(0 && "Unknown leaf type!");
917 return NodeOps;
918 }
919
920 Record *Op = N->getOperator();
921 if (Op->isSubClassOf("Instruction")) {
922 const CodeGenTarget &CGT = CGP.getTargetInfo();
923 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
924 const DAGInstruction &Inst = CGP.getInstruction(Op);
925 const TreePattern *InstPat = Inst.getPattern();
926 // FIXME: Assume actual pattern comes before "implicit".
927 TreePatternNode *InstPatNode =
928 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
929 : (InstPat ? InstPat->getTree(0) : NULL);
930 if (InstPatNode && !InstPatNode->isLeaf() &&
931 InstPatNode->getOperator()->getName() == "set") {
932 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
933 }
934 bool IsVariadic = isRoot && II.isVariadic;
935 // FIXME: fix how we deal with physical register operands.
936 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
937 bool HasImpResults = isRoot && DstRegs.size() > 0;
938 bool NodeHasOptInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +0000939 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000940 bool NodeHasInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +0000941 Pattern->TreeHasProperty(SDNPInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000942 bool NodeHasOutFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +0000943 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000944 bool NodeHasChain = InstPatNode &&
Chris Lattner47661322010-02-14 22:22:58 +0000945 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
946 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000947 unsigned NumResults = Inst.getNumResults();
948 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
949
950 // Record output varargs info.
951 OutputIsVariadic = IsVariadic;
952
953 if (NodeHasOptInFlag) {
954 emitCode("bool HasInFlag = "
955 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
956 "MVT::Flag);");
957 }
958 if (IsVariadic)
959 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
Chris Lattnerb49985a2010-02-18 06:47:49 +0000960
Chris Lattnera0cdf172010-02-13 20:06:50 +0000961 // How many results is this pattern expected to produce?
962 unsigned NumPatResults = 0;
963 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
964 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
965 if (VT != MVT::isVoid && VT != MVT::Flag)
966 NumPatResults++;
967 }
968
969 if (OrigChains.size() > 0) {
970 // The original input chain is being ignored. If it is not just
971 // pointing to the op that's being folded, we should create a
972 // TokenFactor with it and the chain of the folded op as the new chain.
973 // We could potentially be doing multiple levels of folding, in that
974 // case, the TokenFactor can have more operands.
975 emitCode("SmallVector<SDValue, 8> InChains;");
976 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
977 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
978 OrigChains[i].second + ".getNode()) {");
979 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
980 emitCode("}");
981 }
982 emitCode("InChains.push_back(" + ChainName + ");");
983 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
984 "N->getDebugLoc(), MVT::Other, "
985 "&InChains[0], InChains.size());");
986 if (GenDebug) {
Chris Lattnerdcdcef22010-02-18 00:23:27 +0000987 emitCode("CurDAG->setSubgraphColor(" + ChainName +
988 ".getNode(), \"yellow\");");
989 emitCode("CurDAG->setSubgraphColor(" + ChainName +
990 ".getNode(), \"black\");");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000991 }
992 }
993
994 // Loop over all of the operands of the instruction pattern, emitting code
995 // to fill them all in. The node 'N' usually has number children equal to
996 // the number of input operands of the instruction. However, in cases
997 // where there are predicate operands for an instruction, we need to fill
998 // in the 'execute always' values. Match up the node operands to the
999 // instruction operands to do this.
1000 std::vector<std::string> AllOps;
1001 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1002 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1003 std::vector<std::string> Ops;
1004
1005 // Determine what to emit for this operand.
1006 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1007 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1008 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1009 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1010 // This is a predicate or optional def operand; emit the
1011 // 'default ops' operands.
1012 const DAGDefaultOperand &DefaultOp =
1013 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1014 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1015 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1016 InFlagDecled, ResNodeDecled);
1017 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1018 }
1019 } else {
1020 // Otherwise this is a normal operand or a predicate operand without
1021 // 'execute always'; emit it.
1022 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1023 InFlagDecled, ResNodeDecled);
1024 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1025 ++ChildNo;
1026 }
1027 }
1028
1029 // Emit all the chain and CopyToReg stuff.
1030 bool ChainEmitted = NodeHasChain;
1031 if (NodeHasInFlag || HasImpInputs)
1032 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1033 InFlagDecled, ResNodeDecled, true);
1034 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1035 if (!InFlagDecled) {
1036 emitCode("SDValue InFlag(0, 0);");
1037 InFlagDecled = true;
1038 }
1039 if (NodeHasOptInFlag) {
1040 emitCode("if (HasInFlag) {");
1041 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1042 emitCode("}");
1043 }
1044 }
1045
1046 unsigned ResNo = TmpNo++;
1047
1048 unsigned OpsNo = OpcNo;
1049 std::string CodePrefix;
1050 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1051 std::deque<std::string> After;
1052 std::string NodeName;
1053 if (!isRoot) {
1054 NodeName = "Tmp" + utostr(ResNo);
1055 CodePrefix = "SDValue " + NodeName + "(";
1056 } else {
1057 NodeName = "ResNode";
1058 if (!ResNodeDecled) {
1059 CodePrefix = "SDNode *" + NodeName + " = ";
1060 ResNodeDecled = true;
1061 } else
1062 CodePrefix = NodeName + " = ";
1063 }
1064
1065 std::string Code = "Opc" + utostr(OpcNo);
1066
1067 if (!isRoot || (InputHasChain && !NodeHasChain))
1068 // For call to "getMachineNode()".
1069 Code += ", N->getDebugLoc()";
1070
1071 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1072
1073 // Output order: results, chain, flags
1074 // Result types.
1075 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1076 Code += ", VT" + utostr(VTNo);
1077 emitVT(getEnumName(N->getTypeNum(0)));
1078 }
1079 // Add types for implicit results in physical registers, scheduler will
1080 // care of adding copyfromreg nodes.
1081 for (unsigned i = 0; i < NumDstRegs; i++) {
1082 Record *RR = DstRegs[i];
1083 if (RR->isSubClassOf("Register")) {
1084 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1085 Code += ", " + getEnumName(RVT);
1086 }
1087 }
1088 if (NodeHasChain)
1089 Code += ", MVT::Other";
1090 if (NodeHasOutFlag)
1091 Code += ", MVT::Flag";
1092
1093 // Inputs.
1094 if (IsVariadic) {
1095 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1096 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1097 AllOps.clear();
1098
1099 // Figure out whether any operands at the end of the op list are not
1100 // part of the variable section.
1101 std::string EndAdjust;
1102 if (NodeHasInFlag || HasImpInputs)
1103 EndAdjust = "-1"; // Always has one flag.
1104 else if (NodeHasOptInFlag)
1105 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1106
1107 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1108 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1109
1110 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1111 emitCode("}");
1112 }
1113
1114 // Populate MemRefs with entries for each memory accesses covered by
1115 // this pattern.
1116 if (isRoot && !LSI.empty()) {
1117 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1118 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1119 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1120 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1121 emitCode(MemRefs + "[" + utostr(i) + "] = "
1122 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1123 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1124 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1125 ");");
1126 }
1127
1128 if (NodeHasChain) {
1129 if (IsVariadic)
1130 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1131 else
1132 AllOps.push_back(ChainName);
1133 }
1134
1135 if (IsVariadic) {
1136 if (NodeHasInFlag || HasImpInputs)
1137 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1138 else if (NodeHasOptInFlag) {
1139 emitCode("if (HasInFlag)");
1140 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1141 }
1142 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1143 ".size()";
1144 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1145 AllOps.push_back("InFlag");
1146
1147 unsigned NumOps = AllOps.size();
1148 if (NumOps) {
1149 if (!NodeHasOptInFlag && NumOps < 4) {
1150 for (unsigned i = 0; i != NumOps; ++i)
1151 Code += ", " + AllOps[i];
1152 } else {
1153 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1154 for (unsigned i = 0; i != NumOps; ++i) {
1155 OpsCode += AllOps[i];
1156 if (i != NumOps-1)
1157 OpsCode += ", ";
1158 }
1159 emitCode(OpsCode + " };");
1160 Code += ", Ops" + utostr(OpsNo) + ", ";
1161 if (NodeHasOptInFlag) {
1162 Code += "HasInFlag ? ";
1163 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1164 } else
1165 Code += utostr(NumOps);
1166 }
1167 }
1168
1169 if (!isRoot)
1170 Code += "), 0";
1171
1172 std::vector<std::string> ReplaceFroms;
1173 std::vector<std::string> ReplaceTos;
1174 if (!isRoot) {
1175 NodeOps.push_back("Tmp" + utostr(ResNo));
1176 } else {
1177
1178 if (NodeHasOutFlag) {
1179 if (!InFlagDecled) {
1180 After.push_back("SDValue InFlag(ResNode, " +
1181 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1182 ");");
1183 InFlagDecled = true;
1184 } else
1185 After.push_back("InFlag = SDValue(ResNode, " +
1186 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1187 ");");
1188 }
1189
1190 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1191 ReplaceFroms.push_back("SDValue(" +
1192 FoldedChains[j].first + ".getNode(), " +
1193 utostr(FoldedChains[j].second) +
1194 ")");
1195 ReplaceTos.push_back("SDValue(ResNode, " +
1196 utostr(NumResults+NumDstRegs) + ")");
1197 }
1198
1199 if (NodeHasOutFlag) {
1200 if (FoldedFlag.first != "") {
1201 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1202 utostr(FoldedFlag.second) + ")");
1203 ReplaceTos.push_back("InFlag");
1204 } else {
Chris Lattner47661322010-02-14 22:22:58 +00001205 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
Chris Lattnera0cdf172010-02-13 20:06:50 +00001206 ReplaceFroms.push_back("SDValue(N, " +
1207 utostr(NumPatResults + (unsigned)InputHasChain)
1208 + ")");
1209 ReplaceTos.push_back("InFlag");
1210 }
1211 }
1212
1213 if (!ReplaceFroms.empty() && InputHasChain) {
1214 ReplaceFroms.push_back("SDValue(N, " +
1215 utostr(NumPatResults) + ")");
1216 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1217 ChainName + ".getResNo()" + ")");
1218 ChainAssignmentNeeded |= NodeHasChain;
1219 }
1220
1221 // User does not expect the instruction would produce a chain!
1222 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1223 ;
1224 } else if (InputHasChain && !NodeHasChain) {
1225 // One of the inner node produces a chain.
1226 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1227 ReplaceFroms.push_back("SDValue(N, " +
1228 utostr(NumPatResults) + ")");
1229 ReplaceTos.push_back(ChainName);
1230 }
1231 }
1232
1233 if (ChainAssignmentNeeded) {
1234 // Remember which op produces the chain.
1235 std::string ChainAssign;
1236 if (!isRoot)
1237 ChainAssign = ChainName + " = SDValue(" + NodeName +
1238 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1239 else
1240 ChainAssign = ChainName + " = SDValue(" + NodeName +
1241 ", " + utostr(NumResults+NumDstRegs) + ");";
1242
1243 After.push_front(ChainAssign);
1244 }
1245
1246 if (ReplaceFroms.size() == 1) {
1247 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1248 ReplaceTos[0] + ");");
1249 } else if (!ReplaceFroms.empty()) {
1250 After.push_back("const SDValue Froms[] = {");
1251 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1252 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1253 After.push_back("};");
1254 After.push_back("const SDValue Tos[] = {");
1255 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1256 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1257 After.push_back("};");
1258 After.push_back("ReplaceUses(Froms, Tos, " +
1259 itostr(ReplaceFroms.size()) + ");");
1260 }
1261
1262 // We prefer to use SelectNodeTo since it avoids allocation when
1263 // possible and it avoids CSE map recalculation for the node's
1264 // users, however it's tricky to use in a non-root context.
1265 //
1266 // We also don't use SelectNodeTo if the pattern replacement is being
1267 // used to jettison a chain result, since morphing the node in place
1268 // would leave users of the chain dangling.
1269 //
1270 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1271 Code = "CurDAG->getMachineNode(" + Code;
1272 } else {
1273 Code = "CurDAG->SelectNodeTo(N, " + Code;
1274 }
1275 if (isRoot) {
1276 if (After.empty())
1277 CodePrefix = "return ";
1278 else
1279 After.push_back("return ResNode;");
1280 }
1281
1282 emitCode(CodePrefix + Code + ");");
1283
1284 if (GenDebug) {
1285 if (!isRoot) {
1286 emitCode("CurDAG->setSubgraphColor(" +
1287 NodeName +".getNode(), \"yellow\");");
1288 emitCode("CurDAG->setSubgraphColor(" +
1289 NodeName +".getNode(), \"black\");");
1290 } else {
1291 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1292 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1293 }
1294 }
1295
1296 for (unsigned i = 0, e = After.size(); i != e; ++i)
1297 emitCode(After[i]);
1298
1299 return NodeOps;
1300 }
1301 if (Op->isSubClassOf("SDNodeXForm")) {
1302 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1303 // PatLeaf node - the operand may or may not be a leaf node. But it should
1304 // behave like one.
1305 std::vector<std::string> Ops =
1306 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1307 ResNodeDecled, true);
1308 unsigned ResNo = TmpNo++;
1309 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1310 + "(" + Ops.back() + ".getNode());");
1311 NodeOps.push_back("Tmp" + utostr(ResNo));
1312 if (isRoot)
1313 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1314 return NodeOps;
1315 }
1316
1317 N->dump();
1318 errs() << "\n";
1319 throw std::string("Unknown node in result pattern!");
1320}
1321
1322
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001323/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1324/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001325/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001326void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001327 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001328 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001329 std::vector<std::string> &TargetOpcodes,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001330 std::vector<std::string> &TargetVTs,
1331 bool &OutputIsVariadic,
1332 unsigned &NumInputRootOps) {
1333 OutputIsVariadic = false;
1334 NumInputRootOps = 0;
1335
Dan Gohman22bb3112008-08-22 00:20:26 +00001336 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001337 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001338 GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001339 TargetOpcodes, TargetVTs,
1340 OutputIsVariadic, NumInputRootOps);
Evan Chengb915f312005-12-09 22:45:35 +00001341
Chris Lattner8fc35682005-09-23 23:16:51 +00001342 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001343 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001344 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001345
Chris Lattnerc87bf382010-02-14 21:11:53 +00001346 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1347 // diagnostics, which we know are impossible at this point.
Chris Lattner200c57e2008-01-05 22:58:54 +00001348 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001349
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001350 // At this point, we know that we structurally match the pattern, but the
1351 // types of the nodes may not match. Figure out the fewest number of type
1352 // comparisons we need to emit. For example, if there is only one integer
1353 // type supported by a target, there should be no type comparisons at all for
1354 // integer patterns!
1355 //
1356 // To figure out the fewest number of type checks needed, clone the pattern,
1357 // remove the types, then perform type inference on the pattern as a whole.
1358 // If there are unresolved types, emit an explicit check for those types,
1359 // apply the type to the tree, then rerun type inference. Iterate until all
1360 // types are resolved.
1361 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001362 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner47661322010-02-14 22:22:58 +00001363 Pat->RemoveAllTypes();
Chris Lattner7e82f132005-10-15 21:34:21 +00001364
1365 do {
1366 // Resolve/propagate as many types as possible.
1367 try {
1368 bool MadeChange = true;
1369 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001370 MadeChange = Pat->ApplyTypeConstraints(TP,
1371 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001372 } catch (...) {
1373 assert(0 && "Error: could not find consistent types for something we"
1374 " already decided was ok!");
1375 abort();
1376 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001377
Chris Lattner7e82f132005-10-15 21:34:21 +00001378 // Insert a check for an unresolved type and add it to the tree. If we find
1379 // an unresolved type to add a check for, this returns true and we iterate,
1380 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001381 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001382
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001383 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001384 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001385 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001386}
1387
Chris Lattner24e00a42006-01-29 04:41:05 +00001388/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1389/// a line causes any of them to be empty, remove them and return true when
1390/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001391static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001392 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001393 &Patterns) {
1394 bool ErasedPatterns = false;
1395 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1396 Patterns[i].second.pop_back();
1397 if (Patterns[i].second.empty()) {
1398 Patterns.erase(Patterns.begin()+i);
1399 --i; --e;
1400 ErasedPatterns = true;
1401 }
1402 }
1403 return ErasedPatterns;
1404}
1405
Chris Lattner8bc74722006-01-29 04:25:26 +00001406/// EmitPatterns - Emit code for at least one pattern, but try to group common
1407/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001408void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001409 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001410 &Patterns, unsigned Indent,
Daniel Dunbar1a551802009-07-03 00:10:29 +00001411 raw_ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001412 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001413 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001414 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001415
1416 if (Patterns.empty()) return;
1417
Chris Lattner24e00a42006-01-29 04:41:05 +00001418 // Figure out how many patterns share the next code line. Explicitly copy
1419 // FirstCodeLine so that we don't invalidate a reference when changing
1420 // Patterns.
1421 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001422 unsigned LastMatch = Patterns.size()-1;
1423 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1424 --LastMatch;
1425
1426 // If not all patterns share this line, split the list into two pieces. The
1427 // first chunk will use this line, the second chunk won't.
1428 if (LastMatch != 0) {
1429 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1430 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1431
1432 // FIXME: Emit braces?
1433 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001434 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001435 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1436 Pattern.getSrcPattern()->print(OS);
1437 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1438 Pattern.getDstPattern()->print(OS);
1439 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001440 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001441 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001442 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001443 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001444 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001445 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001446 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001447 }
Evan Cheng676d7312006-08-26 00:59:04 +00001448 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001449 OS << std::string(Indent, ' ') << "{\n";
1450 Indent += 2;
1451 }
1452 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001453 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001454 Indent -= 2;
1455 OS << std::string(Indent, ' ') << "}\n";
1456 }
1457
1458 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001459 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001460 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1461 Pattern.getSrcPattern()->print(OS);
1462 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1463 Pattern.getDstPattern()->print(OS);
1464 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001465 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001466 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001467 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001468 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001469 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001470 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001471 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001472 }
1473 EmitPatterns(Other, Indent, OS);
1474 return;
1475 }
1476
Chris Lattner24e00a42006-01-29 04:41:05 +00001477 // Remove this code from all of the patterns that share it.
1478 bool ErasedPatterns = EraseCodeLine(Patterns);
1479
Evan Cheng676d7312006-08-26 00:59:04 +00001480 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001481
1482 // Otherwise, every pattern in the list has this line. Emit it.
1483 if (!isPredicate) {
1484 // Normal code.
1485 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1486 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001487 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1488
1489 // If the next code line is another predicate, and if all of the pattern
1490 // in this group share the same next line, emit it inline now. Do this
1491 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001492 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00001493 // Check that all of the patterns in Patterns end with the same predicate.
Chris Lattner24e00a42006-01-29 04:41:05 +00001494 bool AllEndWithSamePredicate = true;
1495 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1496 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1497 AllEndWithSamePredicate = false;
1498 break;
1499 }
1500 // If all of the predicates aren't the same, we can't share them.
1501 if (!AllEndWithSamePredicate) break;
1502
1503 // Otherwise we can. Emit it shared now.
1504 OS << " &&\n" << std::string(Indent+4, ' ')
1505 << Patterns.back().second.back().second;
1506 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001507 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001508
1509 OS << ") {\n";
1510 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001511 }
1512
1513 EmitPatterns(Patterns, Indent, OS);
1514
1515 if (isPredicate)
1516 OS << std::string(Indent-2, ' ') << "}\n";
1517}
1518
Evan Cheng892aaf82006-11-08 23:01:03 +00001519static std::string getLegalCName(std::string OpName) {
1520 std::string::size_type pos = OpName.find("::");
1521 if (pos != std::string::npos)
1522 OpName.replace(pos, 2, "_");
1523 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001524}
1525
Daniel Dunbar1a551802009-07-03 00:10:29 +00001526void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001527 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattnerda272d12010-02-15 08:04:42 +00001528
Dan Gohman1e0ee4b2008-08-20 21:45:57 +00001529 // Get the namespace to insert instructions into.
1530 std::string InstNS = Target.getInstNamespace();
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001531 if (!InstNS.empty()) InstNS += "::";
1532
Chris Lattner602f6922006-01-04 00:25:00 +00001533 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001534 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001535 // All unique target node emission functions.
1536 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001537 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001538 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001539 const PatternToMatch &Pattern = *I;
Chris Lattner6cefb772008-01-05 22:25:12 +00001540 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001541 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001542 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001543 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001544 } else {
1545 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001546 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001547 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001548 push_back(&Pattern);
Chris Lattner47661322010-02-14 22:22:58 +00001549 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001550 std::vector<Record*> OpNodes = CP->getRootNodes();
1551 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001552 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1553 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001554 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001555 }
1556 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001557 errs() << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001558 Node->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001559 errs() << "' on tree pattern '";
1560 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001561 exit(1);
1562 }
1563 }
1564 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001565
1566 // For each opcode, there might be multiple select functions, one per
1567 // ValueType of the node (or its first operand if it doesn't produce a
1568 // non-chain result.
1569 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1570
Chris Lattner602f6922006-01-04 00:25:00 +00001571 // Emit one Select_* method for each top-level opcode. We do this instead of
1572 // emitting one giant switch statement to support compilers where this will
1573 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001574 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001575 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1576 PBOI != E; ++PBOI) {
1577 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001578 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001579 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1580
Chris Lattner706d2d32006-08-09 16:44:44 +00001581 // Split them into groups by type.
Owen Anderson825b72b2009-08-11 20:47:22 +00001582 std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001583 std::vector<const PatternToMatch*> > PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001584 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001585 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001586 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner9783d622008-08-26 07:01:28 +00001587 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Chris Lattner706d2d32006-08-09 16:44:44 +00001588 }
1589
Owen Anderson825b72b2009-08-11 20:47:22 +00001590 for (std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001591 std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001592 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1593 ++II) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001594 MVT::SimpleValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001595 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman0540e172008-10-15 06:17:21 +00001596 typedef std::pair<unsigned, std::string> CodeLine;
1597 typedef std::vector<CodeLine> CodeList;
1598 typedef CodeList::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001599
Chris Lattner60d81392008-01-05 22:30:17 +00001600 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001601 std::vector<std::vector<std::string> > PatternOpcodes;
1602 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001603 std::vector<std::set<std::string> > PatternDecls;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001604 std::vector<bool> OutputIsVariadicFlags;
1605 std::vector<unsigned> NumInputRootOpsCounts;
Chris Lattner706d2d32006-08-09 16:44:44 +00001606 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1607 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001608 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001609 std::vector<std::string> TargetOpcodes;
1610 std::vector<std::string> TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001611 bool OutputIsVariadic;
1612 unsigned NumInputRootOps;
Chris Lattner706d2d32006-08-09 16:44:44 +00001613 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001614 TargetOpcodes, TargetVTs,
1615 OutputIsVariadic, NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001616 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1617 PatternDecls.push_back(GeneratedDecl);
1618 PatternOpcodes.push_back(TargetOpcodes);
1619 PatternVTs.push_back(TargetVTs);
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001620 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1621 NumInputRootOpsCounts.push_back(NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001622 }
1623
Chris Lattner706d2d32006-08-09 16:44:44 +00001624 // Factor target node emission code (emitted by EmitResultCode) into
1625 // separate functions. Uniquing and share them among all instruction
1626 // selection routines.
1627 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1628 CodeList &GeneratedCode = CodeForPatterns[i].second;
1629 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1630 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001631 std::set<std::string> Decls = PatternDecls[i];
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001632 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1633 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001634 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001635 int CodeSize = (int)GeneratedCode.size();
1636 int LastPred = -1;
1637 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001638 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001639 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001640 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1641 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001642 }
1643
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001644 std::string CalleeCode = "(SDNode *N";
Evan Cheng9ade2182006-08-26 05:34:46 +00001645 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001646 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1647 CalleeCode += ", unsigned Opc" + utostr(j);
1648 CallerCode += ", " + TargetOpcodes[j];
1649 }
1650 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Owen Anderson69110c92009-09-11 09:01:57 +00001651 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
Chris Lattner706d2d32006-08-09 16:44:44 +00001652 CallerCode += ", " + TargetVTs[j];
1653 }
Evan Chengf5493192006-08-26 01:02:19 +00001654 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001655 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001656 std::string Name = *I;
Dan Gohman475871a2008-07-27 21:46:04 +00001657 CalleeCode += ", SDValue &" + Name;
Evan Cheng676d7312006-08-26 00:59:04 +00001658 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001659 }
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001660
1661 if (OutputIsVariadic) {
1662 CalleeCode += ", unsigned NumInputRootOps";
1663 CallerCode += ", " + utostr(NumInputRootOps);
1664 }
1665
Chris Lattner706d2d32006-08-09 16:44:44 +00001666 CallerCode += ");";
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001667 CalleeCode += ") {\n";
Evan Cheng676d7312006-08-26 00:59:04 +00001668
1669 for (std::vector<std::string>::const_reverse_iterator
1670 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1671 CalleeCode += " " + *I + "\n";
1672
Evan Chengf5493192006-08-26 01:02:19 +00001673 for (int j = LastPred+1; j < CodeSize; ++j)
1674 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001675 for (int j = LastPred+1; j < CodeSize; ++j)
1676 GeneratedCode.pop_back();
1677 CalleeCode += "}\n";
1678
1679 // Uniquing the emission routines.
1680 unsigned EmitFuncNum;
1681 std::map<std::string, unsigned>::iterator EFI =
1682 EmitFunctions.find(CalleeCode);
1683 if (EFI != EmitFunctions.end()) {
1684 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001685 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001686 EmitFuncNum = EmitFunctions.size();
1687 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001688 // Prevent emission routines from being inlined to reduce selection
1689 // routines stack frame sizes.
1690 OS << "DISABLE_INLINE ";
Evan Cheng06d64702006-08-11 08:59:35 +00001691 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001692 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001693
Chris Lattner706d2d32006-08-09 16:44:44 +00001694 // Replace the emission code within selection routines with calls to the
1695 // emission functions.
Chris Lattnera0cdf172010-02-13 20:06:50 +00001696 if (GenDebug)
Chris Lattnerdcdcef22010-02-18 00:23:27 +00001697 GeneratedCode.push_back(std::make_pair(0,
1698 "CurDAG->setSubgraphColor(N, \"red\");"));
1699 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) +CallerCode;
David Greene8ad4c002008-10-27 21:56:29 +00001700 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1701 if (GenDebug) {
1702 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
Chris Lattnerdcdcef22010-02-18 00:23:27 +00001703 GeneratedCode.push_back(std::make_pair(0,
1704 " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1705 GeneratedCode.push_back(std::make_pair(0,
1706 " CurDAG->setSubgraphColor(Result, \"black\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001707 GeneratedCode.push_back(std::make_pair(0, "}"));
David Greene8ad4c002008-10-27 21:56:29 +00001708 }
1709 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001710 }
1711
Chris Lattner706d2d32006-08-09 16:44:44 +00001712 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001713 std::string OpVTStr;
Owen Anderson825b72b2009-08-11 20:47:22 +00001714 if (OpVT == MVT::iPTR) {
Chris Lattner33a40042006-11-14 22:17:10 +00001715 OpVTStr = "_iPTR";
Owen Anderson825b72b2009-08-11 20:47:22 +00001716 } else if (OpVT == MVT::iPTRAny) {
Mon P Wange3b3a722008-07-30 04:36:53 +00001717 OpVTStr = "_iPTRAny";
Owen Anderson825b72b2009-08-11 20:47:22 +00001718 } else if (OpVT == MVT::isVoid) {
Chris Lattner33a40042006-11-14 22:17:10 +00001719 // Nodes with a void result actually have a first result type of either
1720 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1721 // void to this case, we handle it specially here.
1722 } else {
Owen Anderson825b72b2009-08-11 20:47:22 +00001723 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
Chris Lattner33a40042006-11-14 22:17:10 +00001724 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001725 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1726 OpcodeVTMap.find(OpName);
1727 if (OpVTI == OpcodeVTMap.end()) {
1728 std::vector<std::string> VTSet;
1729 VTSet.push_back(OpVTStr);
1730 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1731 } else
1732 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001733
Dan Gohman0540e172008-10-15 06:17:21 +00001734 // We want to emit all of the matching code now. However, we want to emit
1735 // the matches in order of minimal cost. Sort the patterns so the least
1736 // cost one is at the start.
1737 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1738 PatternSortingPredicate(CGP));
1739
1740 // Scan the code to see if all of the patterns are reachable and if it is
1741 // possible that the last one might not match.
1742 bool mightNotMatch = true;
1743 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1744 CodeList &GeneratedCode = CodeForPatterns[i].second;
1745 mightNotMatch = false;
1746
1747 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1748 if (GeneratedCode[j].first == 1) { // predicate.
1749 mightNotMatch = true;
1750 break;
1751 }
1752 }
1753
1754 // If this pattern definitely matches, and if it isn't the last one, the
1755 // patterns after it CANNOT ever match. Error out.
1756 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001757 errs() << "Pattern '";
1758 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1759 errs() << "' is impossible to select!\n";
Dan Gohman0540e172008-10-15 06:17:21 +00001760 exit(1);
1761 }
1762 }
1763
Chris Lattner706d2d32006-08-09 16:44:44 +00001764 // Loop through and reverse all of the CodeList vectors, as we will be
1765 // accessing them from their logical front, but accessing the end of a
1766 // vector is more efficient.
1767 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1768 CodeList &GeneratedCode = CodeForPatterns[i].second;
1769 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001770 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001771
1772 // Next, reverse the list of patterns itself for the same reason.
1773 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1774
Dan Gohman63e3e632009-01-29 01:37:18 +00001775 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001776 << OpVTStr << "(SDNode *N) {\n";
Dan Gohman63e3e632009-01-29 01:37:18 +00001777
Chris Lattner706d2d32006-08-09 16:44:44 +00001778 // Emit all of the patterns now, grouped together to share code.
1779 EmitPatterns(CodeForPatterns, 2, OS);
1780
Chris Lattner64906972006-09-21 18:28:27 +00001781 // If the last pattern has predicates (which could fail) emit code to
1782 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001783 if (mightNotMatch) {
Dan Gohman31bd42b2008-09-27 23:53:14 +00001784 OS << "\n";
Chris Lattner409ac582010-02-17 06:28:22 +00001785 OS << " CannotYetSelect(N);\n";
Dan Gohman31bd42b2008-09-27 23:53:14 +00001786 OS << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001787 }
1788 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001789 }
Chris Lattner602f6922006-01-04 00:25:00 +00001790 }
1791
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001792 OS << "// The main instruction selector code.\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001793 << "SDNode *SelectCode(SDNode *N) {\n"
1794 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1795 << " switch (N->getOpcode()) {\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001796 << " default:\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001797 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001798 << " break;\n"
1799 << " case ISD::EntryToken: // These nodes remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001800 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001801 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001802 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001803 << " case ISD::TargetConstant:\n"
Nate Begemane1795842008-02-14 08:57:00 +00001804 << " case ISD::TargetConstantFP:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001805 << " case ISD::TargetConstantPool:\n"
1806 << " case ISD::TargetFrameIndex:\n"
Bill Wendling056292f2008-09-16 21:48:12 +00001807 << " case ISD::TargetExternalSymbol:\n"
Dan Gohman8c2b5252009-10-30 01:27:03 +00001808 << " case ISD::TargetBlockAddress:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001809 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001810 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohman8be6bbe2008-11-05 04:14:16 +00001811 << " case ISD::TargetGlobalAddress:\n"
1812 << " case ISD::TokenFactor:\n"
1813 << " case ISD::CopyFromReg:\n"
1814 << " case ISD::CopyToReg: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001815 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001816 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001817 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001818 << " case ISD::AssertZext: {\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001819 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001820 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001821 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001822 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohmancd920d92008-07-02 23:23:19 +00001823 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Chengda47e6e2008-03-15 00:03:38 +00001824 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001825
Chris Lattner602f6922006-01-04 00:25:00 +00001826 // Loop over all of the case statements, emiting a call to each method we
1827 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001828 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001829 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1830 PBOI != E; ++PBOI) {
1831 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001832 // Potentially multiple versions of select for this opcode. One for each
1833 // ValueType of the node (or its first true operand if it doesn't produce a
1834 // result.
1835 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1836 OpcodeVTMap.find(OpName);
1837 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00001838 OS << " case " << OpName << ": {\n";
Dale Johannesen3b895cf2009-05-12 22:32:29 +00001839 // If we have only one variant and it's the default, elide the
1840 // switch. Marginally faster, and makes MSVC happier.
1841 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1842 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1843 OS << " break;\n";
1844 OS << " }\n";
1845 continue;
1846 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001847 // Keep track of whether we see a pattern that has an iPtr result.
1848 bool HasPtrPattern = false;
1849 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00001850
Evan Cheng425e8c72007-09-04 20:18:28 +00001851 OS << " switch (NVT) {\n";
1852 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1853 std::string &VTStr = OpVTs[i];
1854 if (VTStr.empty()) {
1855 HasDefaultPattern = true;
1856 continue;
1857 }
Chris Lattner717a6112006-11-14 21:50:27 +00001858
Evan Cheng425e8c72007-09-04 20:18:28 +00001859 // If this is a match on iPTR: don't emit it directly, we need special
1860 // code.
1861 if (VTStr == "_iPTR") {
1862 HasPtrPattern = true;
1863 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00001864 }
Owen Anderson825b72b2009-08-11 20:47:22 +00001865 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng425e8c72007-09-04 20:18:28 +00001866 << " return Select_" << getLegalCName(OpName)
1867 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001868 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001869 OS << " default:\n";
1870
1871 // If there is an iPTR result version of this pattern, emit it here.
1872 if (HasPtrPattern) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001873 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00001874 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1875 }
1876 if (HasDefaultPattern) {
1877 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1878 }
1879 OS << " break;\n";
1880 OS << " }\n";
1881 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001882 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00001883 }
Chris Lattner81303322005-09-23 19:36:15 +00001884
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001885 OS << " } // end of big switch.\n\n"
Chris Lattner409ac582010-02-17 06:28:22 +00001886 << " CannotYetSelect(N);\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00001887 << " return NULL;\n"
1888 << "}\n\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001889}
1890
Chris Lattner99ce6e82010-02-21 19:22:06 +00001891namespace {
1892// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1893// In particular, we want to match maximal patterns first and lowest cost within
1894// a particular complexity first.
1895struct PatternSortingPredicate2 {
1896 PatternSortingPredicate2(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
1897 CodeGenDAGPatterns &CGP;
1898
1899 bool operator()(const PatternToMatch *LHS,
1900 const PatternToMatch *RHS) {
1901 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
1902 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
1903 LHSSize += LHS->getAddedComplexity();
1904 RHSSize += RHS->getAddedComplexity();
1905 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1906 if (LHSSize < RHSSize) return false;
1907
1908 // If the patterns have equal complexity, compare generated instruction cost
1909 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
1910 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
1911 if (LHSCost < RHSCost) return true;
1912 if (LHSCost > RHSCost) return false;
1913
1914 return getResultPatternSize(LHS->getDstPattern(), CGP) <
1915 getResultPatternSize(RHS->getDstPattern(), CGP);
1916 }
1917};
1918}
1919
1920
Daniel Dunbar1a551802009-07-03 00:10:29 +00001921void DAGISelEmitter::run(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001922 EmitSourceFileHeader("DAG Instruction Selector for the " +
1923 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001924
Chris Lattner1f39e292005-09-14 00:09:24 +00001925 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1926 << "// *** instruction selector class. These functions are really "
1927 << "methods.\n\n";
Chris Lattnerf8dc0612008-02-03 06:49:24 +00001928
Roman Levenstein6422e8a2008-05-14 10:17:11 +00001929 OS << "// Include standard, target-independent definitions and methods used\n"
1930 << "// by the instruction selector.\n";
Mike Stumpfe095f32009-05-04 18:40:41 +00001931 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00001932
Chris Lattner443e3f92008-01-05 22:54:53 +00001933 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00001934 EmitPredicateFunctions(OS);
1935
Chris Lattner569f1212009-08-23 04:44:11 +00001936 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
Chris Lattnerfe718932008-01-06 01:10:31 +00001937 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00001938 I != E; ++I) {
Chris Lattner569f1212009-08-23 04:44:11 +00001939 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1940 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1941 DEBUG(errs() << "\n");
Bill Wendlingf5da1332006-12-07 22:21:48 +00001942 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001943
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001944 // At this point, we have full information about the 'Patterns' we need to
1945 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001946 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001947 EmitInstructionSelector(OS);
1948
Chris Lattner0ab1c5f2010-02-21 06:03:56 +00001949#if 0
Chris Lattnerda272d12010-02-15 08:04:42 +00001950 MatcherNode *Matcher = 0;
Chris Lattner99ce6e82010-02-21 19:22:06 +00001951
1952 // Add all the patterns to a temporary list so we can sort them.
1953 std::vector<const PatternToMatch*> Patterns;
1954 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1955 I != E; ++I)
1956 Patterns.push_back(&*I);
1957
1958 // We want to process the matches in order of minimal cost. Sort the patterns
1959 // so the least cost one is at the start.
1960 // FIXME: Eliminate "PatternSortingPredicate" and rename.
1961 std::stable_sort(Patterns.begin(), Patterns.end(),
1962 PatternSortingPredicate2(CGP));
1963
1964
1965 // Walk the patterns backwards (since we append to the front of the generated
1966 // code), building a matcher for each and adding it to the matcher for the
1967 // whole target.
1968 while (!Patterns.empty()) {
1969 const PatternToMatch &Pattern = *Patterns.back();
1970 Patterns.pop_back();
1971
Chris Lattnerda272d12010-02-15 08:04:42 +00001972 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
1973
1974 if (Matcher == 0)
1975 Matcher = N;
1976 else
1977 Matcher = new PushMatcherNode(N, Matcher);
1978 }
Chris Lattner05446e72010-02-16 23:13:59 +00001979
1980 // OptimizeMatcher(Matcher);
Chris Lattnerda272d12010-02-15 08:04:42 +00001981 //Matcher->dump();
Chris Lattner99ce6e82010-02-21 19:22:06 +00001982 EmitMatcherTable(Matcher, OS);
Chris Lattnerda272d12010-02-15 08:04:42 +00001983 delete Matcher;
1984#endif
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001985}