31e0d1953cf908e1e105d6c55b4ce05fee8bd3f6
[oota-llvm.git] / utils / TableGen / FastISelEmitter.cpp
1 //===- FastISelEmitter.cpp - Generate an instruction selector -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a "fast" instruction selector.
11 //
12 // This instruction selection method is designed to emit very poor code
13 // quickly. Also, it is not designed to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations (e.g. calls) are not
15 // supported and cannot easily be added. Blocks containing operations
16 // that are not supported need to be handled by a more capable selector,
17 // such as the SelectionDAG selector.
18 //
19 // The intended use for "fast" instruction selection is "-O0" mode
20 // compilation, where the quality of the generated code is irrelevant when
21 // weighed against the speed at which the code can be generated.
22 //
23 // If compile time is so important, you might wonder why we don't just
24 // skip codegen all-together, emit LLVM bytecode files, and execute them
25 // with an interpreter. The answer is that it would complicate linking and
26 // debugging, and also because that isn't how a compiler is expected to
27 // work in some circles.
28 //
29 // If you need better generated code or more lowering than what this
30 // instruction selector provides, use the SelectionDAG (DAGISel) instruction
31 // selector instead. If you're looking here because SelectionDAG isn't fast
32 // enough, consider looking into improving the SelectionDAG infastructure
33 // instead. At the time of this writing there remain several major
34 // opportunities for improvement.
35 // 
36 //===----------------------------------------------------------------------===//
37
38 #include "FastISelEmitter.h"
39 #include "Record.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Streams.h"
42 #include "llvm/ADT/VectorExtras.h"
43 using namespace llvm;
44
45 namespace {
46
47 /// OperandsSignature - This class holds a description of a list of operand
48 /// types. It has utility methods for emitting text based on the operands.
49 ///
50 struct OperandsSignature {
51   std::vector<std::string> Operands;
52
53   bool operator<(const OperandsSignature &O) const {
54     return Operands < O.Operands;
55   }
56
57   bool empty() const { return Operands.empty(); }
58
59   /// initialize - Examine the given pattern and initialize the contents
60   /// of the Operands array accordingly. Return true if all the operands
61   /// are supported, false otherwise.
62   ///
63   bool initialize(TreePatternNode *InstPatNode,
64                   const CodeGenTarget &Target,
65                   MVT::SimpleValueType VT) {
66     for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
67       TreePatternNode *Op = InstPatNode->getChild(i);
68       if (!Op->isLeaf())
69         return false;
70       // For now, filter out any operand with a predicate.
71       if (!Op->getPredicateFn().empty())
72         return false;
73       DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
74       if (!OpDI)
75         return false;
76       Record *OpLeafRec = OpDI->getDef();
77       // For now, only accept register operands.
78       if (!OpLeafRec->isSubClassOf("RegisterClass"))
79         return false;
80       // For now, require the register operands' register classes to all
81       // be the same.
82       const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
83       if (!RC)
84         return false;
85       // For now, all the operands must have the same type.
86       if (Op->getTypeNum(0) != VT)
87         return false;
88       Operands.push_back("r");
89     }
90     return true;
91   }
92
93   void PrintParameters(std::ostream &OS) const {
94     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
95       if (Operands[i] == "r") {
96         OS << "unsigned Op" << i;
97       } else {
98         assert("Unknown operand kind!");
99         abort();
100       }
101       if (i + 1 != e)
102         OS << ", ";
103     }
104   }
105
106   void PrintArguments(std::ostream &OS) const {
107     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
108       if (Operands[i] == "r") {
109         OS << "Op" << i;
110       } else {
111         assert("Unknown operand kind!");
112         abort();
113       }
114       if (i + 1 != e)
115         OS << ", ";
116     }
117   }
118
119   void PrintManglingSuffix(std::ostream &OS) const {
120     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
121       OS << Operands[i];
122     }
123   }
124 };
125
126 /// InstructionMemo - This class holds additional information about an
127 /// instruction needed to emit code for it.
128 ///
129 struct InstructionMemo {
130   std::string Name;
131   const CodeGenRegisterClass *RC;
132 };
133
134 }
135
136 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
137   return CGP.getSDNodeInfo(Op).getEnumName();
138 }
139
140 static std::string getLegalCName(std::string OpName) {
141   std::string::size_type pos = OpName.find("::");
142   if (pos != std::string::npos)
143     OpName.replace(pos, 2, "_");
144   return OpName;
145 }
146
147 void FastISelEmitter::run(std::ostream &OS) {
148   EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
149                        CGP.getTargetInfo().getName() + " target", OS);
150   
151   const CodeGenTarget &Target = CGP.getTargetInfo();
152   
153   // Get the namespace to insert instructions into.  Make sure not to pick up
154   // "TargetInstrInfo" by accidentally getting the namespace off the PHI
155   // instruction or something.
156   std::string InstNS;
157   for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
158        e = Target.inst_end(); i != e; ++i) {
159     InstNS = i->second.Namespace;
160     if (InstNS != "TargetInstrInfo")
161       break;
162   }
163
164   OS << "namespace llvm {\n";
165   OS << "namespace " << InstNS << " {\n";
166   OS << "class FastISel;\n";
167   OS << "}\n";
168   OS << "}\n";
169   OS << "\n";
170   
171   if (!InstNS.empty()) InstNS += "::";
172
173   typedef std::map<MVT::SimpleValueType, InstructionMemo> TypeMap;
174   typedef std::map<std::string, TypeMap> OpcodeTypeMap;
175   typedef std::map<OperandsSignature, OpcodeTypeMap> OperandsOpcodeTypeMap;
176   OperandsOpcodeTypeMap SimplePatterns;
177
178   // Create the supported type signatures.
179   OperandsSignature KnownOperands;
180   SimplePatterns[KnownOperands] = OpcodeTypeMap();
181   KnownOperands.Operands.push_back("r");
182   SimplePatterns[KnownOperands] = OpcodeTypeMap();
183   KnownOperands.Operands.push_back("r");
184   SimplePatterns[KnownOperands] = OpcodeTypeMap();
185
186   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
187        E = CGP.ptm_end(); I != E; ++I) {
188     const PatternToMatch &Pattern = *I;
189
190     // For now, just look at Instructions, so that we don't have to worry
191     // about emitting multiple instructions for a pattern.
192     TreePatternNode *Dst = Pattern.getDstPattern();
193     if (Dst->isLeaf()) continue;
194     Record *Op = Dst->getOperator();
195     if (!Op->isSubClassOf("Instruction"))
196       continue;
197     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
198     if (II.OperandList.empty())
199       continue;
200
201     // For now, ignore instructions where the first operand is not an
202     // output register.
203     Record *Op0Rec = II.OperandList[0].Rec;
204     if (!Op0Rec->isSubClassOf("RegisterClass"))
205       continue;
206     const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
207     if (!DstRC)
208       continue;
209
210     // Inspect the pattern.
211     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
212     if (!InstPatNode) continue;
213     if (InstPatNode->isLeaf()) continue;
214
215     Record *InstPatOp = InstPatNode->getOperator();
216     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
217     MVT::SimpleValueType VT = InstPatNode->getTypeNum(0);
218
219     // For now, filter out instructions which just set a register to
220     // an Operand or an immediate, like MOV32ri.
221     if (InstPatOp->isSubClassOf("Operand"))
222       continue;
223     if (InstPatOp->getName() == "imm" ||
224         InstPatOp->getName() == "fpimm")
225       continue;
226
227     // For now, filter out any instructions with predicates.
228     if (!InstPatNode->getPredicateFn().empty())
229       continue;
230
231     // Check all the operands.
232     OperandsSignature Operands;
233     if (!Operands.initialize(InstPatNode, Target, VT))
234       continue;
235
236     // If it's not a known signature, ignore it.
237     if (!SimplePatterns.count(Operands))
238       continue;
239
240     // Ok, we found a pattern that we can handle. Remember it.
241     {
242       InstructionMemo Memo = {
243         Pattern.getDstPattern()->getOperator()->getName(),
244         DstRC
245       };
246       SimplePatterns[Operands][OpcodeName][VT] = Memo;
247     }
248   }
249
250   OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
251   OS << "\n";
252   OS << "namespace llvm {\n";
253   OS << "\n";
254
255   // Declare the target FastISel class.
256   OS << "class " << InstNS << "FastISel : public llvm::FastISel {\n";
257   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
258        OE = SimplePatterns.end(); OI != OE; ++OI) {
259     const OperandsSignature &Operands = OI->first;
260     const OpcodeTypeMap &OTM = OI->second;
261
262     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
263          I != E; ++I) {
264       const std::string &Opcode = I->first;
265       const TypeMap &TM = I->second;
266
267       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
268            TI != TE; ++TI) {
269         MVT::SimpleValueType VT = TI->first;
270
271         OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
272            << "_" << getLegalCName(getName(VT)) << "(";
273         Operands.PrintParameters(OS);
274         OS << ");\n";
275       }
276
277       OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
278          << "(MVT::SimpleValueType VT";
279       if (!Operands.empty())
280         OS << ", ";
281       Operands.PrintParameters(OS);
282       OS << ");\n";
283     }
284
285     OS << "  unsigned FastEmit_";
286     Operands.PrintManglingSuffix(OS);
287     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
288     if (!Operands.empty())
289       OS << ", ";
290     Operands.PrintParameters(OS);
291     OS << ");\n";
292   }
293   OS << "public:\n";
294   OS << "  FastISel(MachineBasicBlock *mbb, MachineFunction *mf, ";
295   OS << "const TargetInstrInfo *tii) : llvm::FastISel(mbb, mf, tii) {}\n";
296   OS << "};\n";
297   OS << "\n";
298
299   // Define the target FastISel creation function.
300   OS << "llvm::FastISel *" << InstNS
301      << "createFastISel(MachineBasicBlock *mbb, MachineFunction *mf, ";
302   OS << "const TargetInstrInfo *tii) {\n";
303   OS << "  return new " << InstNS << "FastISel(mbb, mf, tii);\n";
304   OS << "}\n";
305   OS << "\n";
306
307   // Now emit code for all the patterns that we collected.
308   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
309        OE = SimplePatterns.end(); OI != OE; ++OI) {
310     const OperandsSignature &Operands = OI->first;
311     const OpcodeTypeMap &OTM = OI->second;
312
313     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
314          I != E; ++I) {
315       const std::string &Opcode = I->first;
316       const TypeMap &TM = I->second;
317
318       OS << "// FastEmit functions for " << Opcode << ".\n";
319       OS << "\n";
320
321       // Emit one function for each opcode,type pair.
322       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
323            TI != TE; ++TI) {
324         MVT::SimpleValueType VT = TI->first;
325         const InstructionMemo &Memo = TI->second;
326   
327         OS << "unsigned " << InstNS << "FastISel::FastEmit_"
328            << getLegalCName(Opcode)
329            << "_" << getLegalCName(getName(VT)) << "(";
330         Operands.PrintParameters(OS);
331         OS << ") {\n";
332         OS << "  return FastEmitInst_";
333         Operands.PrintManglingSuffix(OS);
334         OS << "(" << InstNS << Memo.Name << ", ";
335         OS << InstNS << Memo.RC->getName() << "RegisterClass";
336         if (!Operands.empty())
337           OS << ", ";
338         Operands.PrintArguments(OS);
339         OS << ");\n";
340         OS << "}\n";
341         OS << "\n";
342       }
343
344       // Emit one function for the opcode that demultiplexes based on the type.
345       OS << "unsigned " << InstNS << "FastISel::FastEmit_"
346          << getLegalCName(Opcode) << "(MVT::SimpleValueType VT";
347       if (!Operands.empty())
348         OS << ", ";
349       Operands.PrintParameters(OS);
350       OS << ") {\n";
351       OS << "  switch (VT) {\n";
352       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
353            TI != TE; ++TI) {
354         MVT::SimpleValueType VT = TI->first;
355         std::string TypeName = getName(VT);
356         OS << "  case " << TypeName << ": return FastEmit_"
357            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "(";
358         Operands.PrintArguments(OS);
359         OS << ");\n";
360       }
361       OS << "  default: return 0;\n";
362       OS << "  }\n";
363       OS << "}\n";
364       OS << "\n";
365     }
366
367     // Emit one function for the operand signature that demultiplexes based
368     // on opcode and type.
369     OS << "unsigned " << InstNS << "FastISel::FastEmit_";
370     Operands.PrintManglingSuffix(OS);
371     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
372     if (!Operands.empty())
373       OS << ", ";
374     Operands.PrintParameters(OS);
375     OS << ") {\n";
376     OS << "  switch (Opcode) {\n";
377     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
378          I != E; ++I) {
379       const std::string &Opcode = I->first;
380
381       OS << "  case " << Opcode << ": return FastEmit_"
382          << getLegalCName(Opcode) << "(VT";
383       if (!Operands.empty())
384         OS << ", ";
385       Operands.PrintArguments(OS);
386       OS << ");\n";
387     }
388     OS << "  default: return 0;\n";
389     OS << "  }\n";
390     OS << "}\n";
391     OS << "\n";
392   }
393
394   OS << "}\n";
395 }
396
397 // todo: really filter out Constants