Factor the code for determining the target-specific instruction
[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                   const CodeGenRegisterClass *DstRC) {
67     for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
68       TreePatternNode *Op = InstPatNode->getChild(i);
69       if (!Op->isLeaf())
70         return false;
71       // For now, filter out any operand with a predicate.
72       if (!Op->getPredicateFn().empty())
73         return false;
74       DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
75       if (!OpDI)
76         return false;
77       Record *OpLeafRec = OpDI->getDef();
78       // For now, only accept register operands.
79       if (!OpLeafRec->isSubClassOf("RegisterClass"))
80         return false;
81       // For now, require the register operands' register classes to all
82       // be the same.
83       const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
84       if (!RC)
85         return false;
86       // For now, all the operands must have the same register class.
87       if (DstRC != RC)
88         return false;
89       // For now, all the operands must have the same type.
90       if (Op->getTypeNum(0) != VT)
91         return false;
92       Operands.push_back("r");
93     }
94     return true;
95   }
96
97   void PrintParameters(std::ostream &OS) const {
98     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
99       if (Operands[i] == "r") {
100         OS << "unsigned Op" << i;
101       } else {
102         assert("Unknown operand kind!");
103         abort();
104       }
105       if (i + 1 != e)
106         OS << ", ";
107     }
108   }
109
110   void PrintArguments(std::ostream &OS) const {
111     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
112       if (Operands[i] == "r") {
113         OS << "Op" << i;
114       } else {
115         assert("Unknown operand kind!");
116         abort();
117       }
118       if (i + 1 != e)
119         OS << ", ";
120     }
121   }
122
123   void PrintManglingSuffix(std::ostream &OS) const {
124     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
125       OS << Operands[i];
126     }
127   }
128 };
129
130 /// InstructionMemo - This class holds additional information about an
131 /// instruction needed to emit code for it.
132 ///
133 struct InstructionMemo {
134   std::string Name;
135   const CodeGenRegisterClass *RC;
136 };
137
138 }
139
140 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
141   return CGP.getSDNodeInfo(Op).getEnumName();
142 }
143
144 static std::string getLegalCName(std::string OpName) {
145   std::string::size_type pos = OpName.find("::");
146   if (pos != std::string::npos)
147     OpName.replace(pos, 2, "_");
148   return OpName;
149 }
150
151 void FastISelEmitter::run(std::ostream &OS) {
152   EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
153                        CGP.getTargetInfo().getName() + " target", OS);
154   
155   const CodeGenTarget &Target = CGP.getTargetInfo();
156   
157   // Get the namespace to insert instructions into.  Make sure not to pick up
158   // "TargetInstrInfo" by accidentally getting the namespace off the PHI
159   // instruction or something.
160   std::string InstNS = Target.getInstNamespace();
161
162   OS << "namespace llvm {\n";
163   OS << "namespace " << InstNS << " {\n";
164   OS << "class FastISel;\n";
165   OS << "}\n";
166   OS << "}\n";
167   OS << "\n";
168   
169   if (!InstNS.empty()) InstNS += "::";
170
171   typedef std::map<MVT::SimpleValueType, InstructionMemo> TypeMap;
172   typedef std::map<std::string, TypeMap> OpcodeTypeMap;
173   typedef std::map<OperandsSignature, OpcodeTypeMap> OperandsOpcodeTypeMap;
174   OperandsOpcodeTypeMap SimplePatterns;
175
176   // Create the supported type signatures.
177   OperandsSignature KnownOperands;
178   SimplePatterns[KnownOperands] = OpcodeTypeMap();
179   KnownOperands.Operands.push_back("r");
180   SimplePatterns[KnownOperands] = OpcodeTypeMap();
181   KnownOperands.Operands.push_back("r");
182   SimplePatterns[KnownOperands] = OpcodeTypeMap();
183
184   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
185        E = CGP.ptm_end(); I != E; ++I) {
186     const PatternToMatch &Pattern = *I;
187
188     // For now, just look at Instructions, so that we don't have to worry
189     // about emitting multiple instructions for a pattern.
190     TreePatternNode *Dst = Pattern.getDstPattern();
191     if (Dst->isLeaf()) continue;
192     Record *Op = Dst->getOperator();
193     if (!Op->isSubClassOf("Instruction"))
194       continue;
195     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
196     if (II.OperandList.empty())
197       continue;
198
199     // For now, ignore instructions where the first operand is not an
200     // output register.
201     Record *Op0Rec = II.OperandList[0].Rec;
202     if (!Op0Rec->isSubClassOf("RegisterClass"))
203       continue;
204     const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
205     if (!DstRC)
206       continue;
207
208     // Inspect the pattern.
209     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
210     if (!InstPatNode) continue;
211     if (InstPatNode->isLeaf()) continue;
212
213     Record *InstPatOp = InstPatNode->getOperator();
214     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
215     MVT::SimpleValueType VT = InstPatNode->getTypeNum(0);
216
217     // For now, filter out instructions which just set a register to
218     // an Operand or an immediate, like MOV32ri.
219     if (InstPatOp->isSubClassOf("Operand"))
220       continue;
221     if (InstPatOp->getName() == "imm" ||
222         InstPatOp->getName() == "fpimm")
223       continue;
224
225     // For now, filter out any instructions with predicates.
226     if (!InstPatNode->getPredicateFn().empty())
227       continue;
228
229     // Check all the operands.
230     OperandsSignature Operands;
231     if (!Operands.initialize(InstPatNode, Target, VT, DstRC))
232       continue;
233
234     // If it's not a known signature, ignore it.
235     if (!SimplePatterns.count(Operands))
236       continue;
237
238     // Ok, we found a pattern that we can handle. Remember it.
239     {
240       InstructionMemo Memo = {
241         Pattern.getDstPattern()->getOperator()->getName(),
242         DstRC
243       };
244       SimplePatterns[Operands][OpcodeName][VT] = Memo;
245     }
246   }
247
248   OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
249   OS << "\n";
250   OS << "namespace llvm {\n";
251   OS << "\n";
252
253   // Declare the target FastISel class.
254   OS << "class " << InstNS << "FastISel : public llvm::FastISel {\n";
255   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
256        OE = SimplePatterns.end(); OI != OE; ++OI) {
257     const OperandsSignature &Operands = OI->first;
258     const OpcodeTypeMap &OTM = OI->second;
259
260     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
261          I != E; ++I) {
262       const std::string &Opcode = I->first;
263       const TypeMap &TM = I->second;
264
265       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
266            TI != TE; ++TI) {
267         MVT::SimpleValueType VT = TI->first;
268
269         OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
270            << "_" << getLegalCName(getName(VT)) << "(";
271         Operands.PrintParameters(OS);
272         OS << ");\n";
273       }
274
275       OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
276          << "(MVT::SimpleValueType VT";
277       if (!Operands.empty())
278         OS << ", ";
279       Operands.PrintParameters(OS);
280       OS << ");\n";
281     }
282
283     OS << "  unsigned FastEmit_";
284     Operands.PrintManglingSuffix(OS);
285     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
286     if (!Operands.empty())
287       OS << ", ";
288     Operands.PrintParameters(OS);
289     OS << ");\n";
290   }
291   OS << "public:\n";
292   OS << "  explicit FastISel(MachineFunction &mf) : llvm::FastISel(mf) {}\n";
293   OS << "};\n";
294   OS << "\n";
295
296   // Define the target FastISel creation function.
297   OS << "llvm::FastISel *" << InstNS
298      << "createFastISel(MachineFunction &mf) {\n";
299   OS << "  return new " << InstNS << "FastISel(mf);\n";
300   OS << "}\n";
301   OS << "\n";
302
303   // Now emit code for all the patterns that we collected.
304   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
305        OE = SimplePatterns.end(); OI != OE; ++OI) {
306     const OperandsSignature &Operands = OI->first;
307     const OpcodeTypeMap &OTM = OI->second;
308
309     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
310          I != E; ++I) {
311       const std::string &Opcode = I->first;
312       const TypeMap &TM = I->second;
313
314       OS << "// FastEmit functions for " << Opcode << ".\n";
315       OS << "\n";
316
317       // Emit one function for each opcode,type pair.
318       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
319            TI != TE; ++TI) {
320         MVT::SimpleValueType VT = TI->first;
321         const InstructionMemo &Memo = TI->second;
322   
323         OS << "unsigned " << InstNS << "FastISel::FastEmit_"
324            << getLegalCName(Opcode)
325            << "_" << getLegalCName(getName(VT)) << "(";
326         Operands.PrintParameters(OS);
327         OS << ") {\n";
328         OS << "  return FastEmitInst_";
329         Operands.PrintManglingSuffix(OS);
330         OS << "(" << InstNS << Memo.Name << ", ";
331         OS << InstNS << Memo.RC->getName() << "RegisterClass";
332         if (!Operands.empty())
333           OS << ", ";
334         Operands.PrintArguments(OS);
335         OS << ");\n";
336         OS << "}\n";
337         OS << "\n";
338       }
339
340       // Emit one function for the opcode that demultiplexes based on the type.
341       OS << "unsigned " << InstNS << "FastISel::FastEmit_"
342          << getLegalCName(Opcode) << "(MVT::SimpleValueType VT";
343       if (!Operands.empty())
344         OS << ", ";
345       Operands.PrintParameters(OS);
346       OS << ") {\n";
347       OS << "  switch (VT) {\n";
348       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
349            TI != TE; ++TI) {
350         MVT::SimpleValueType VT = TI->first;
351         std::string TypeName = getName(VT);
352         OS << "  case " << TypeName << ": return FastEmit_"
353            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "(";
354         Operands.PrintArguments(OS);
355         OS << ");\n";
356       }
357       OS << "  default: return 0;\n";
358       OS << "  }\n";
359       OS << "}\n";
360       OS << "\n";
361     }
362
363     // Emit one function for the operand signature that demultiplexes based
364     // on opcode and type.
365     OS << "unsigned " << InstNS << "FastISel::FastEmit_";
366     Operands.PrintManglingSuffix(OS);
367     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
368     if (!Operands.empty())
369       OS << ", ";
370     Operands.PrintParameters(OS);
371     OS << ") {\n";
372     OS << "  switch (Opcode) {\n";
373     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
374          I != E; ++I) {
375       const std::string &Opcode = I->first;
376
377       OS << "  case " << Opcode << ": return FastEmit_"
378          << getLegalCName(Opcode) << "(VT";
379       if (!Operands.empty())
380         OS << ", ";
381       Operands.PrintArguments(OS);
382       OS << ");\n";
383     }
384     OS << "  default: return 0;\n";
385     OS << "  }\n";
386     OS << "}\n";
387     OS << "\n";
388   }
389
390   OS << "}\n";
391 }
392
393 // todo: really filter out Constants