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