9650ea8855b83d265b24423dd6f5baeaf893a639
[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;
161   for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
162        e = Target.inst_end(); i != e; ++i) {
163     InstNS = i->second.Namespace;
164     if (InstNS != "TargetInstrInfo")
165       break;
166   }
167
168   OS << "namespace llvm {\n";
169   OS << "namespace " << InstNS << " {\n";
170   OS << "class FastISel;\n";
171   OS << "}\n";
172   OS << "}\n";
173   OS << "\n";
174   
175   if (!InstNS.empty()) InstNS += "::";
176
177   typedef std::map<MVT::SimpleValueType, InstructionMemo> TypeMap;
178   typedef std::map<std::string, TypeMap> OpcodeTypeMap;
179   typedef std::map<OperandsSignature, OpcodeTypeMap> OperandsOpcodeTypeMap;
180   OperandsOpcodeTypeMap SimplePatterns;
181
182   // Create the supported type signatures.
183   OperandsSignature KnownOperands;
184   SimplePatterns[KnownOperands] = OpcodeTypeMap();
185   KnownOperands.Operands.push_back("r");
186   SimplePatterns[KnownOperands] = OpcodeTypeMap();
187   KnownOperands.Operands.push_back("r");
188   SimplePatterns[KnownOperands] = OpcodeTypeMap();
189
190   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
191        E = CGP.ptm_end(); I != E; ++I) {
192     const PatternToMatch &Pattern = *I;
193
194     // For now, just look at Instructions, so that we don't have to worry
195     // about emitting multiple instructions for a pattern.
196     TreePatternNode *Dst = Pattern.getDstPattern();
197     if (Dst->isLeaf()) continue;
198     Record *Op = Dst->getOperator();
199     if (!Op->isSubClassOf("Instruction"))
200       continue;
201     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
202     if (II.OperandList.empty())
203       continue;
204
205     // For now, ignore instructions where the first operand is not an
206     // output register.
207     Record *Op0Rec = II.OperandList[0].Rec;
208     if (!Op0Rec->isSubClassOf("RegisterClass"))
209       continue;
210     const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
211     if (!DstRC)
212       continue;
213
214     // Inspect the pattern.
215     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
216     if (!InstPatNode) continue;
217     if (InstPatNode->isLeaf()) continue;
218
219     Record *InstPatOp = InstPatNode->getOperator();
220     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
221     MVT::SimpleValueType VT = InstPatNode->getTypeNum(0);
222
223     // For now, filter out instructions which just set a register to
224     // an Operand or an immediate, like MOV32ri.
225     if (InstPatOp->isSubClassOf("Operand"))
226       continue;
227     if (InstPatOp->getName() == "imm" ||
228         InstPatOp->getName() == "fpimm")
229       continue;
230
231     // For now, filter out any instructions with predicates.
232     if (!InstPatNode->getPredicateFn().empty())
233       continue;
234
235     // Check all the operands.
236     OperandsSignature Operands;
237     if (!Operands.initialize(InstPatNode, Target, VT, DstRC))
238       continue;
239
240     // If it's not a known signature, ignore it.
241     if (!SimplePatterns.count(Operands))
242       continue;
243
244     // Ok, we found a pattern that we can handle. Remember it.
245     {
246       InstructionMemo Memo = {
247         Pattern.getDstPattern()->getOperator()->getName(),
248         DstRC
249       };
250       SimplePatterns[Operands][OpcodeName][VT] = Memo;
251     }
252   }
253
254   OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
255   OS << "\n";
256   OS << "namespace llvm {\n";
257   OS << "\n";
258
259   // Declare the target FastISel class.
260   OS << "class " << InstNS << "FastISel : public llvm::FastISel {\n";
261   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
262        OE = SimplePatterns.end(); OI != OE; ++OI) {
263     const OperandsSignature &Operands = OI->first;
264     const OpcodeTypeMap &OTM = OI->second;
265
266     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
267          I != E; ++I) {
268       const std::string &Opcode = I->first;
269       const TypeMap &TM = I->second;
270
271       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
272            TI != TE; ++TI) {
273         MVT::SimpleValueType VT = TI->first;
274
275         OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
276            << "_" << getLegalCName(getName(VT)) << "(";
277         Operands.PrintParameters(OS);
278         OS << ");\n";
279       }
280
281       OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
282          << "(MVT::SimpleValueType VT";
283       if (!Operands.empty())
284         OS << ", ";
285       Operands.PrintParameters(OS);
286       OS << ");\n";
287     }
288
289     OS << "  unsigned FastEmit_";
290     Operands.PrintManglingSuffix(OS);
291     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
292     if (!Operands.empty())
293       OS << ", ";
294     Operands.PrintParameters(OS);
295     OS << ");\n";
296   }
297   OS << "public:\n";
298   OS << "  explicit FastISel(MachineFunction &mf) : llvm::FastISel(mf) {}\n";
299   OS << "};\n";
300   OS << "\n";
301
302   // Define the target FastISel creation function.
303   OS << "llvm::FastISel *" << InstNS
304      << "createFastISel(MachineFunction &mf) {\n";
305   OS << "  return new " << InstNS << "FastISel(mf);\n";
306   OS << "}\n";
307   OS << "\n";
308
309   // Now emit code for all the patterns that we collected.
310   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
311        OE = SimplePatterns.end(); OI != OE; ++OI) {
312     const OperandsSignature &Operands = OI->first;
313     const OpcodeTypeMap &OTM = OI->second;
314
315     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
316          I != E; ++I) {
317       const std::string &Opcode = I->first;
318       const TypeMap &TM = I->second;
319
320       OS << "// FastEmit functions for " << Opcode << ".\n";
321       OS << "\n";
322
323       // Emit one function for each opcode,type pair.
324       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
325            TI != TE; ++TI) {
326         MVT::SimpleValueType VT = TI->first;
327         const InstructionMemo &Memo = TI->second;
328   
329         OS << "unsigned " << InstNS << "FastISel::FastEmit_"
330            << getLegalCName(Opcode)
331            << "_" << getLegalCName(getName(VT)) << "(";
332         Operands.PrintParameters(OS);
333         OS << ") {\n";
334         OS << "  return FastEmitInst_";
335         Operands.PrintManglingSuffix(OS);
336         OS << "(" << InstNS << Memo.Name << ", ";
337         OS << InstNS << Memo.RC->getName() << "RegisterClass";
338         if (!Operands.empty())
339           OS << ", ";
340         Operands.PrintArguments(OS);
341         OS << ");\n";
342         OS << "}\n";
343         OS << "\n";
344       }
345
346       // Emit one function for the opcode that demultiplexes based on the type.
347       OS << "unsigned " << InstNS << "FastISel::FastEmit_"
348          << getLegalCName(Opcode) << "(MVT::SimpleValueType VT";
349       if (!Operands.empty())
350         OS << ", ";
351       Operands.PrintParameters(OS);
352       OS << ") {\n";
353       OS << "  switch (VT) {\n";
354       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
355            TI != TE; ++TI) {
356         MVT::SimpleValueType VT = TI->first;
357         std::string TypeName = getName(VT);
358         OS << "  case " << TypeName << ": return FastEmit_"
359            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "(";
360         Operands.PrintArguments(OS);
361         OS << ");\n";
362       }
363       OS << "  default: return 0;\n";
364       OS << "  }\n";
365       OS << "}\n";
366       OS << "\n";
367     }
368
369     // Emit one function for the operand signature that demultiplexes based
370     // on opcode and type.
371     OS << "unsigned " << InstNS << "FastISel::FastEmit_";
372     Operands.PrintManglingSuffix(OS);
373     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
374     if (!Operands.empty())
375       OS << ", ";
376     Operands.PrintParameters(OS);
377     OS << ") {\n";
378     OS << "  switch (Opcode) {\n";
379     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
380          I != E; ++I) {
381       const std::string &Opcode = I->first;
382
383       OS << "  case " << Opcode << ": return FastEmit_"
384          << getLegalCName(Opcode) << "(VT";
385       if (!Operands.empty())
386         OS << ", ";
387       Operands.PrintArguments(OS);
388       OS << ");\n";
389     }
390     OS << "  default: return 0;\n";
391     OS << "  }\n";
392     OS << "}\n";
393     OS << "\n";
394   }
395
396   OS << "}\n";
397 }
398
399 // todo: really filter out Constants