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