We need to check that the return type is correct, even in cases where we don't
[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     if (!InstPatNode->isLeaf() &&
67         InstPatNode->getOperator()->getName() == "imm") {
68       Operands.push_back("i");
69       return true;
70     }
71     
72     const CodeGenRegisterClass *DstRC = 0;
73     
74     for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
75       TreePatternNode *Op = InstPatNode->getChild(i);
76       // For now, filter out any operand with a predicate.
77       if (!Op->getPredicateFn().empty())
78         return false;
79       // For now, filter out any operand with multiple values.
80       if (Op->getExtTypes().size() != 1)
81         return false;
82       // For now, all the operands must have the same type.
83       if (Op->getTypeNum(0) != VT)
84         return false;
85       if (!Op->isLeaf()) {
86         if (Op->getOperator()->getName() == "imm") {
87           Operands.push_back("i");
88           return true;
89         }
90         // For now, ignore fpimm and other non-leaf nodes.
91         return false;
92       }
93       DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
94       if (!OpDI)
95         return false;
96       Record *OpLeafRec = OpDI->getDef();
97       // TODO: handle instructions which have physreg operands.
98       if (OpLeafRec->isSubClassOf("Register"))
99         return false;
100       // For now, the only other thing we accept is register operands.
101       if (!OpLeafRec->isSubClassOf("RegisterClass"))
102         return false;
103       // For now, require the register operands' register classes to all
104       // be the same.
105       const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
106       if (!RC)
107         return false;
108       // For now, all the operands must have the same register class.
109       if (DstRC) {
110         if (DstRC != RC)
111           return false;
112       } else
113         DstRC = RC;
114       Operands.push_back("r");
115     }
116     return true;
117   }
118
119   void PrintParameters(std::ostream &OS) const {
120     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
121       if (Operands[i] == "r") {
122         OS << "unsigned Op" << i;
123       } else if (Operands[i] == "i") {
124         OS << "uint64_t imm" << i;
125       } else {
126         assert("Unknown operand kind!");
127         abort();
128       }
129       if (i + 1 != e)
130         OS << ", ";
131     }
132   }
133
134   void PrintArguments(std::ostream &OS) const {
135     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
136       if (Operands[i] == "r") {
137         OS << "Op" << i;
138       } else if (Operands[i] == "i") {
139         OS << "imm" << i;
140       } else {
141         assert("Unknown operand kind!");
142         abort();
143       }
144       if (i + 1 != e)
145         OS << ", ";
146     }
147   }
148
149   void PrintManglingSuffix(std::ostream &OS) const {
150     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
151       OS << Operands[i];
152     }
153   }
154 };
155
156 /// InstructionMemo - This class holds additional information about an
157 /// instruction needed to emit code for it.
158 ///
159 struct InstructionMemo {
160   std::string Name;
161   const CodeGenRegisterClass *RC;
162 };
163
164 }
165
166 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
167   return CGP.getSDNodeInfo(Op).getEnumName();
168 }
169
170 static std::string getLegalCName(std::string OpName) {
171   std::string::size_type pos = OpName.find("::");
172   if (pos != std::string::npos)
173     OpName.replace(pos, 2, "_");
174   return OpName;
175 }
176
177 void FastISelEmitter::run(std::ostream &OS) {
178   EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
179                        Target.getName() + " target", OS);
180
181   OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
182   OS << "\n";
183   OS << "namespace llvm {\n";
184   OS << "\n";
185   OS << "namespace " << InstNS.substr(0, InstNS.size() - 2) << " {\n";
186   OS << "\n";
187   
188   typedef std::map<std::string, InstructionMemo> PredMap;
189   typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
190   typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
191   typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
192   typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
193   OperandsOpcodeTypeRetPredMap SimplePatterns;
194
195   // Scan through all the patterns and record the simple ones.
196   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
197        E = CGP.ptm_end(); I != E; ++I) {
198     const PatternToMatch &Pattern = *I;
199
200     // For now, just look at Instructions, so that we don't have to worry
201     // about emitting multiple instructions for a pattern.
202     TreePatternNode *Dst = Pattern.getDstPattern();
203     if (Dst->isLeaf()) continue;
204     Record *Op = Dst->getOperator();
205     if (!Op->isSubClassOf("Instruction"))
206       continue;
207     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
208     if (II.OperandList.empty())
209       continue;
210
211     // For now, ignore instructions where the first operand is not an
212     // output register.
213     Record *Op0Rec = II.OperandList[0].Rec;
214     if (!Op0Rec->isSubClassOf("RegisterClass"))
215       continue;
216     const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
217     if (!DstRC)
218       continue;
219
220     // Inspect the pattern.
221     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
222     if (!InstPatNode) continue;
223     if (InstPatNode->isLeaf()) continue;
224
225     Record *InstPatOp = InstPatNode->getOperator();
226     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
227     MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
228     MVT::SimpleValueType VT = RetVT;
229     if (InstPatNode->getNumChildren())
230       VT = InstPatNode->getChild(0)->getTypeNum(0);
231
232     // For now, filter out instructions which just set a register to
233     // an Operand or an immediate, like MOV32ri.
234     if (InstPatOp->isSubClassOf("Operand"))
235       continue;
236
237     // For now, filter out any instructions with predicates.
238     if (!InstPatNode->getPredicateFn().empty())
239       continue;
240
241     // Check all the operands.
242     OperandsSignature Operands;
243     if (!Operands.initialize(InstPatNode, Target, VT))
244       continue;
245
246     // Get the predicate that guards this pattern.
247     std::string PredicateCheck = Pattern.getPredicateCheck();
248
249     // Ok, we found a pattern that we can handle. Remember it.
250     InstructionMemo Memo = {
251       Pattern.getDstPattern()->getOperator()->getName(),
252       DstRC
253     };
254     assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
255            "Duplicate pattern!");
256     SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
257   }
258
259   // Declare the target FastISel class.
260   OS << "class FastISel : public llvm::FastISel {\n";
261   for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
262        OE = SimplePatterns.end(); OI != OE; ++OI) {
263     const OperandsSignature &Operands = OI->first;
264     const OpcodeTypeRetPredMap &OTM = OI->second;
265
266     for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
267          I != E; ++I) {
268       const std::string &Opcode = I->first;
269       const TypeRetPredMap &TM = I->second;
270
271       for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
272            TI != TE; ++TI) {
273         MVT::SimpleValueType VT = TI->first;
274         const RetPredMap &RM = TI->second;
275         
276         if (RM.size() != 1)
277           for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
278                RI != RE; ++RI) {
279             MVT::SimpleValueType RetVT = RI->first;
280             OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
281                << "_" << getLegalCName(getName(VT)) << "_"
282                << getLegalCName(getName(RetVT)) << "_";
283             Operands.PrintManglingSuffix(OS);
284             OS << "(";
285             Operands.PrintParameters(OS);
286             OS << ");\n";
287           }
288         
289         OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
290            << "_" << getLegalCName(getName(VT)) << "_";
291         Operands.PrintManglingSuffix(OS);
292         OS << "(MVT::SimpleValueType RetVT";
293         if (!Operands.empty())
294           OS << ", ";
295         Operands.PrintParameters(OS);
296         OS << ");\n";
297       }
298
299       OS << "  unsigned FastEmit_" << getLegalCName(Opcode) << "_";
300       Operands.PrintManglingSuffix(OS);
301       OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
302       if (!Operands.empty())
303         OS << ", ";
304       Operands.PrintParameters(OS);
305       OS << ");\n";
306     }
307
308     OS << "  unsigned FastEmit_";
309     Operands.PrintManglingSuffix(OS);
310     OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
311     if (!Operands.empty())
312       OS << ", ";
313     Operands.PrintParameters(OS);
314     OS << ");\n";
315   }
316   OS << "\n";
317
318   // Declare the Subtarget member, which is used for predicate checks.
319   OS << "  const " << InstNS.substr(0, InstNS.size() - 2)
320      << "Subtarget *Subtarget;\n";
321   OS << "\n";
322
323   // Declare the constructor.
324   OS << "public:\n";
325   OS << "  explicit FastISel(MachineFunction &mf)\n";
326   OS << "     : llvm::FastISel(mf),\n";
327   OS << "       Subtarget(&TM.getSubtarget<" << InstNS.substr(0, InstNS.size() - 2)
328      << "Subtarget>()) {}\n";
329   OS << "};\n";
330   OS << "\n";
331
332   // Define the target FastISel creation function.
333   OS << "llvm::FastISel *createFastISel(MachineFunction &mf) {\n";
334   OS << "  return new FastISel(mf);\n";
335   OS << "}\n";
336   OS << "\n";
337
338   // Now emit code for all the patterns that we collected.
339   for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
340        OE = SimplePatterns.end(); OI != OE; ++OI) {
341     const OperandsSignature &Operands = OI->first;
342     const OpcodeTypeRetPredMap &OTM = OI->second;
343
344     for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
345          I != E; ++I) {
346       const std::string &Opcode = I->first;
347       const TypeRetPredMap &TM = I->second;
348
349       OS << "// FastEmit functions for " << Opcode << ".\n";
350       OS << "\n";
351
352       // Emit one function for each opcode,type pair.
353       for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
354            TI != TE; ++TI) {
355         MVT::SimpleValueType VT = TI->first;
356         const RetPredMap &RM = TI->second;
357         if (RM.size() != 1) {
358           for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
359                RI != RE; ++RI) {
360             MVT::SimpleValueType RetVT = RI->first;
361             const PredMap &PM = RI->second;
362             bool HasPred = false;
363
364             OS << "unsigned FastISel::FastEmit_"
365                << getLegalCName(Opcode)
366                << "_" << getLegalCName(getName(VT))
367                << "_" << getLegalCName(getName(RetVT)) << "_";
368             Operands.PrintManglingSuffix(OS);
369             OS << "(";
370             Operands.PrintParameters(OS);
371             OS << ") {\n";
372
373             // Emit code for each possible instruction. There may be
374             // multiple if there are subtarget concerns.
375             for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
376                  PI != PE; ++PI) {
377               std::string PredicateCheck = PI->first;
378               const InstructionMemo &Memo = PI->second;
379   
380               if (PredicateCheck.empty()) {
381                 assert(!HasPred &&
382                        "Multiple instructions match, at least one has "
383                        "a predicate and at least one doesn't!");
384               } else {
385                 OS << "  if (" + PredicateCheck + ")\n";
386                 OS << "  ";
387                 HasPred = true;
388               }
389               OS << "  return FastEmitInst_";
390               Operands.PrintManglingSuffix(OS);
391               OS << "(" << InstNS << Memo.Name << ", ";
392               OS << InstNS << Memo.RC->getName() << "RegisterClass";
393               if (!Operands.empty())
394                 OS << ", ";
395               Operands.PrintArguments(OS);
396               OS << ");\n";
397             }
398             // Return 0 if none of the predicates were satisfied.
399             if (HasPred)
400               OS << "  return 0;\n";
401             OS << "}\n";
402             OS << "\n";
403           }
404           
405           // Emit one function for the type that demultiplexes on return type.
406           OS << "unsigned FastISel::FastEmit_"
407              << getLegalCName(Opcode) << "_"
408              << getLegalCName(getName(VT)) << "_";
409           Operands.PrintManglingSuffix(OS);
410           OS << "(MVT::SimpleValueType RetVT";
411           if (!Operands.empty())
412             OS << ", ";
413           Operands.PrintParameters(OS);
414           OS << ") {\nswitch (RetVT) {\n";
415           for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
416                RI != RE; ++RI) {
417             MVT::SimpleValueType RetVT = RI->first;
418             OS << "  case " << getName(RetVT) << ": return FastEmit_"
419                << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
420                << "_" << getLegalCName(getName(RetVT)) << "_";
421             Operands.PrintManglingSuffix(OS);
422             OS << "(";
423             Operands.PrintArguments(OS);
424             OS << ");\n";
425           }
426           OS << "  default: return 0;\n}\n}\n\n";
427           
428         } else {
429           // Non-variadic return type.
430           OS << "unsigned FastISel::FastEmit_"
431              << getLegalCName(Opcode) << "_"
432              << getLegalCName(getName(VT)) << "_";
433           Operands.PrintManglingSuffix(OS);
434           OS << "(MVT::SimpleValueType RetVT";
435           if (!Operands.empty())
436             OS << ", ";
437           Operands.PrintParameters(OS);
438           OS << ") {\n";
439           
440           OS << "  if (RetVT != " << getName(RM.begin()->first)
441              << ")\n    return 0;\n";
442           
443           const PredMap &PM = RM.begin()->second;
444           bool HasPred = false;
445           
446           // Emit code for each possible instruction. There may be
447           // multiple if there are subtarget concerns.
448           for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE; ++PI) {
449             std::string PredicateCheck = PI->first;
450             const InstructionMemo &Memo = PI->second;
451
452             if (PredicateCheck.empty()) {
453               assert(!HasPred &&
454                      "Multiple instructions match, at least one has "
455                      "a predicate and at least one doesn't!");
456             } else {
457               OS << "  if (" + PredicateCheck + ")\n";
458               OS << "  ";
459               HasPred = true;
460             }
461             OS << "  return FastEmitInst_";
462             Operands.PrintManglingSuffix(OS);
463             OS << "(" << InstNS << Memo.Name << ", ";
464             OS << InstNS << Memo.RC->getName() << "RegisterClass";
465             if (!Operands.empty())
466               OS << ", ";
467             Operands.PrintArguments(OS);
468             OS << ");\n";
469           }
470           
471           // Return 0 if none of the predicates were satisfied.
472           if (HasPred)
473             OS << "  return 0;\n";
474           OS << "}\n";
475           OS << "\n";
476         }
477       }
478
479       // Emit one function for the opcode that demultiplexes based on the type.
480       OS << "unsigned FastISel::FastEmit_"
481          << getLegalCName(Opcode) << "_";
482       Operands.PrintManglingSuffix(OS);
483       OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
484       if (!Operands.empty())
485         OS << ", ";
486       Operands.PrintParameters(OS);
487       OS << ") {\n";
488       OS << "  switch (VT) {\n";
489       for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
490            TI != TE; ++TI) {
491         MVT::SimpleValueType VT = TI->first;
492         std::string TypeName = getName(VT);
493         OS << "  case " << TypeName << ": return FastEmit_"
494            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
495         Operands.PrintManglingSuffix(OS);
496         OS << "(RetVT";
497         if (!Operands.empty())
498           OS << ", ";
499         Operands.PrintArguments(OS);
500         OS << ");\n";
501       }
502       OS << "  default: return 0;\n";
503       OS << "  }\n";
504       OS << "}\n";
505       OS << "\n";
506     }
507
508     OS << "// Top-level FastEmit function.\n";
509     OS << "\n";
510
511     // Emit one function for the operand signature that demultiplexes based
512     // on opcode and type.
513     OS << "unsigned FastISel::FastEmit_";
514     Operands.PrintManglingSuffix(OS);
515     OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
516     if (!Operands.empty())
517       OS << ", ";
518     Operands.PrintParameters(OS);
519     OS << ") {\n";
520     OS << "  switch (Opcode) {\n";
521     for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
522          I != E; ++I) {
523       const std::string &Opcode = I->first;
524
525       OS << "  case " << Opcode << ": return FastEmit_"
526          << getLegalCName(Opcode) << "_";
527       Operands.PrintManglingSuffix(OS);
528       OS << "(VT, RetVT";
529       if (!Operands.empty())
530         OS << ", ";
531       Operands.PrintArguments(OS);
532       OS << ");\n";
533     }
534     OS << "  default: return 0;\n";
535     OS << "  }\n";
536     OS << "}\n";
537     OS << "\n";
538   }
539
540   OS << "} // namespace X86\n";
541   OS << "\n";
542   OS << "} // namespace llvm\n";
543 }
544
545 FastISelEmitter::FastISelEmitter(RecordKeeper &R)
546   : Records(R),
547     CGP(R),
548     Target(CGP.getTargetInfo()),
549     InstNS(Target.getInstNamespace() + "::") {
550
551   assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
552 }