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