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