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 "CodeGenDAGPatterns.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 #include "llvm/TableGen/TableGenBackend.h"
27 #include <utility>
28 using namespace llvm;
29 
30 
31 /// InstructionMemo - This class holds additional information about an
32 /// instruction needed to emit code for it.
33 ///
34 namespace {
35 struct InstructionMemo {
36   std::string Name;
37   const CodeGenRegisterClass *RC;
38   std::string SubRegNo;
39   std::vector<std::string>* PhysRegs;
40   std::string PredicateCheck;
41 };
42 } // End anonymous namespace
43 
44 /// ImmPredicateSet - This uniques predicates (represented as a string) and
45 /// gives them unique (small) integer ID's that start at 0.
46 namespace {
47 class ImmPredicateSet {
48   DenseMap<TreePattern *, unsigned> ImmIDs;
49   std::vector<TreePredicateFn> PredsByName;
50 public:
51 
52   unsigned getIDFor(TreePredicateFn Pred) {
53     unsigned &Entry = ImmIDs[Pred.getOrigPatFragRecord()];
54     if (Entry == 0) {
55       PredsByName.push_back(Pred);
56       Entry = PredsByName.size();
57     }
58     return Entry-1;
59   }
60 
61   const TreePredicateFn &getPredicate(unsigned i) {
62     assert(i < PredsByName.size());
63     return PredsByName[i];
64   }
65 
66   typedef std::vector<TreePredicateFn>::const_iterator iterator;
67   iterator begin() const { return PredsByName.begin(); }
68   iterator end() const { return PredsByName.end(); }
69 
70 };
71 } // End anonymous namespace
72 
73 /// OperandsSignature - This class holds a description of a list of operand
74 /// types. It has utility methods for emitting text based on the operands.
75 ///
76 namespace {
77 struct OperandsSignature {
78   class OpKind {
79     enum { OK_Reg, OK_FP, OK_Imm, OK_Invalid = -1 };
80     char Repr;
81   public:
82 
83     OpKind() : Repr(OK_Invalid) {}
84 
85     bool operator<(OpKind RHS) const { return Repr < RHS.Repr; }
86     bool operator==(OpKind RHS) const { return Repr == RHS.Repr; }
87 
88     static OpKind getReg() { OpKind K; K.Repr = OK_Reg; return K; }
89     static OpKind getFP()  { OpKind K; K.Repr = OK_FP; return K; }
90     static OpKind getImm(unsigned V) {
91       assert((unsigned)OK_Imm+V < 128 &&
92              "Too many integer predicates for the 'Repr' char");
93       OpKind K; K.Repr = OK_Imm+V; return K;
94     }
95 
96     bool isReg() const { return Repr == OK_Reg; }
97     bool isFP() const  { return Repr == OK_FP; }
98     bool isImm() const { return Repr >= OK_Imm; }
99 
100     unsigned getImmCode() const { assert(isImm()); return Repr-OK_Imm; }
101 
102     void printManglingSuffix(raw_ostream &OS, ImmPredicateSet &ImmPredicates,
103                              bool StripImmCodes) const {
104       if (isReg())
105         OS << 'r';
106       else if (isFP())
107         OS << 'f';
108       else {
109         OS << 'i';
110         if (!StripImmCodes)
111           if (unsigned Code = getImmCode())
112             OS << "_" << ImmPredicates.getPredicate(Code-1).getFnName();
113       }
114     }
115   };
116 
117 
118   SmallVector<OpKind, 3> Operands;
119 
120   bool operator<(const OperandsSignature &O) const {
121     return Operands < O.Operands;
122   }
123   bool operator==(const OperandsSignature &O) const {
124     return Operands == O.Operands;
125   }
126 
127   bool empty() const { return Operands.empty(); }
128 
129   bool hasAnyImmediateCodes() const {
130     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
131       if (Operands[i].isImm() && Operands[i].getImmCode() != 0)
132         return true;
133     return false;
134   }
135 
136   /// getWithoutImmCodes - Return a copy of this with any immediate codes forced
137   /// to zero.
138   OperandsSignature getWithoutImmCodes() const {
139     OperandsSignature Result;
140     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
141       if (!Operands[i].isImm())
142         Result.Operands.push_back(Operands[i]);
143       else
144         Result.Operands.push_back(OpKind::getImm(0));
145     return Result;
146   }
147 
148   void emitImmediatePredicate(raw_ostream &OS, ImmPredicateSet &ImmPredicates) {
149     bool EmittedAnything = false;
150     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
151       if (!Operands[i].isImm()) continue;
152 
153       unsigned Code = Operands[i].getImmCode();
154       if (Code == 0) continue;
155 
156       if (EmittedAnything)
157         OS << " &&\n        ";
158 
159       TreePredicateFn PredFn = ImmPredicates.getPredicate(Code-1);
160 
161       // Emit the type check.
162       OS << "VT == "
163          << getEnumName(PredFn.getOrigPatFragRecord()->getTree(0)->getType(0))
164          << " && ";
165 
166 
167       OS << PredFn.getFnName() << "(imm" << i <<')';
168       EmittedAnything = true;
169     }
170   }
171 
172   /// initialize - Examine the given pattern and initialize the contents
173   /// of the Operands array accordingly. Return true if all the operands
174   /// are supported, false otherwise.
175   ///
176   bool initialize(TreePatternNode *InstPatNode, const CodeGenTarget &Target,
177                   MVT::SimpleValueType VT,
178                   ImmPredicateSet &ImmediatePredicates,
179                   const CodeGenRegisterClass *OrigDstRC) {
180     if (InstPatNode->isLeaf())
181       return false;
182 
183     if (InstPatNode->getOperator()->getName() == "imm") {
184       Operands.push_back(OpKind::getImm(0));
185       return true;
186     }
187 
188     if (InstPatNode->getOperator()->getName() == "fpimm") {
189       Operands.push_back(OpKind::getFP());
190       return true;
191     }
192 
193     const CodeGenRegisterClass *DstRC = nullptr;
194 
195     for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
196       TreePatternNode *Op = InstPatNode->getChild(i);
197 
198       // Handle imm operands specially.
199       if (!Op->isLeaf() && Op->getOperator()->getName() == "imm") {
200         unsigned PredNo = 0;
201         if (!Op->getPredicateFns().empty()) {
202           TreePredicateFn PredFn = Op->getPredicateFns()[0];
203           // If there is more than one predicate weighing in on this operand
204           // then we don't handle it.  This doesn't typically happen for
205           // immediates anyway.
206           if (Op->getPredicateFns().size() > 1 ||
207               !PredFn.isImmediatePattern())
208             return false;
209           // Ignore any instruction with 'FastIselShouldIgnore', these are
210           // not needed and just bloat the fast instruction selector.  For
211           // example, X86 doesn't need to generate code to match ADD16ri8 since
212           // ADD16ri will do just fine.
213           Record *Rec = PredFn.getOrigPatFragRecord()->getRecord();
214           if (Rec->getValueAsBit("FastIselShouldIgnore"))
215             return false;
216 
217           PredNo = ImmediatePredicates.getIDFor(PredFn)+1;
218         }
219 
220         // Handle unmatched immediate sizes here.
221         //if (Op->getType(0) != VT)
222         //  return false;
223 
224         Operands.push_back(OpKind::getImm(PredNo));
225         continue;
226       }
227 
228 
229       // For now, filter out any operand with a predicate.
230       // For now, filter out any operand with multiple values.
231       if (!Op->getPredicateFns().empty() || Op->getNumTypes() != 1)
232         return false;
233 
234       if (!Op->isLeaf()) {
235          if (Op->getOperator()->getName() == "fpimm") {
236           Operands.push_back(OpKind::getFP());
237           continue;
238         }
239         // For now, ignore other non-leaf nodes.
240         return false;
241       }
242 
243       assert(Op->hasTypeSet(0) && "Type infererence not done?");
244 
245       // For now, all the operands must have the same type (if they aren't
246       // immediates).  Note that this causes us to reject variable sized shifts
247       // on X86.
248       if (Op->getType(0) != VT)
249         return false;
250 
251       DefInit *OpDI = dyn_cast<DefInit>(Op->getLeafValue());
252       if (!OpDI)
253         return false;
254       Record *OpLeafRec = OpDI->getDef();
255 
256       // For now, the only other thing we accept is register operands.
257       const CodeGenRegisterClass *RC = nullptr;
258       if (OpLeafRec->isSubClassOf("RegisterOperand"))
259         OpLeafRec = OpLeafRec->getValueAsDef("RegClass");
260       if (OpLeafRec->isSubClassOf("RegisterClass"))
261         RC = &Target.getRegisterClass(OpLeafRec);
262       else if (OpLeafRec->isSubClassOf("Register"))
263         RC = Target.getRegBank().getRegClassForRegister(OpLeafRec);
264       else if (OpLeafRec->isSubClassOf("ValueType")) {
265         RC = OrigDstRC;
266       } else
267         return false;
268 
269       // For now, this needs to be a register class of some sort.
270       if (!RC)
271         return false;
272 
273       // For now, all the operands must have the same register class or be
274       // a strict subclass of the destination.
275       if (DstRC) {
276         if (DstRC != RC && !DstRC->hasSubClass(RC))
277           return false;
278       } else
279         DstRC = RC;
280       Operands.push_back(OpKind::getReg());
281     }
282     return true;
283   }
284 
285   void PrintParameters(raw_ostream &OS) const {
286     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
287       if (Operands[i].isReg()) {
288         OS << "unsigned Op" << i << ", bool Op" << i << "IsKill";
289       } else if (Operands[i].isImm()) {
290         OS << "uint64_t imm" << i;
291       } else if (Operands[i].isFP()) {
292         OS << "const ConstantFP *f" << i;
293       } else {
294         llvm_unreachable("Unknown operand kind!");
295       }
296       if (i + 1 != e)
297         OS << ", ";
298     }
299   }
300 
301   void PrintArguments(raw_ostream &OS,
302                       const std::vector<std::string> &PR) const {
303     assert(PR.size() == Operands.size());
304     bool PrintedArg = false;
305     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
306       if (PR[i] != "")
307         // Implicit physical register operand.
308         continue;
309 
310       if (PrintedArg)
311         OS << ", ";
312       if (Operands[i].isReg()) {
313         OS << "Op" << i << ", Op" << i << "IsKill";
314         PrintedArg = true;
315       } else if (Operands[i].isImm()) {
316         OS << "imm" << i;
317         PrintedArg = true;
318       } else if (Operands[i].isFP()) {
319         OS << "f" << i;
320         PrintedArg = true;
321       } else {
322         llvm_unreachable("Unknown operand kind!");
323       }
324     }
325   }
326 
327   void PrintArguments(raw_ostream &OS) const {
328     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
329       if (Operands[i].isReg()) {
330         OS << "Op" << i << ", Op" << i << "IsKill";
331       } else if (Operands[i].isImm()) {
332         OS << "imm" << i;
333       } else if (Operands[i].isFP()) {
334         OS << "f" << i;
335       } else {
336         llvm_unreachable("Unknown operand kind!");
337       }
338       if (i + 1 != e)
339         OS << ", ";
340     }
341   }
342 
343 
344   void PrintManglingSuffix(raw_ostream &OS, const std::vector<std::string> &PR,
345                            ImmPredicateSet &ImmPredicates,
346                            bool StripImmCodes = false) const {
347     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
348       if (PR[i] != "")
349         // Implicit physical register operand. e.g. Instruction::Mul expect to
350         // select to a binary op. On x86, mul may take a single operand with
351         // the other operand being implicit. We must emit something that looks
352         // like a binary instruction except for the very inner fastEmitInst_*
353         // call.
354         continue;
355       Operands[i].printManglingSuffix(OS, ImmPredicates, StripImmCodes);
356     }
357   }
358 
359   void PrintManglingSuffix(raw_ostream &OS, ImmPredicateSet &ImmPredicates,
360                            bool StripImmCodes = false) const {
361     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
362       Operands[i].printManglingSuffix(OS, ImmPredicates, StripImmCodes);
363   }
364 };
365 } // End anonymous namespace
366 
367 namespace {
368 class FastISelMap {
369   // A multimap is needed instead of a "plain" map because the key is
370   // the instruction's complexity (an int) and they are not unique.
371   typedef std::multimap<int, InstructionMemo> PredMap;
372   typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
373   typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
374   typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
375   typedef std::map<OperandsSignature, OpcodeTypeRetPredMap>
376             OperandsOpcodeTypeRetPredMap;
377 
378   OperandsOpcodeTypeRetPredMap SimplePatterns;
379 
380   // This is used to check that there are no duplicate predicates
381   typedef std::multimap<std::string, bool> PredCheckMap;
382   typedef std::map<MVT::SimpleValueType, PredCheckMap> RetPredCheckMap;
383   typedef std::map<MVT::SimpleValueType, RetPredCheckMap> TypeRetPredCheckMap;
384   typedef std::map<std::string, TypeRetPredCheckMap> OpcodeTypeRetPredCheckMap;
385   typedef std::map<OperandsSignature, OpcodeTypeRetPredCheckMap>
386             OperandsOpcodeTypeRetPredCheckMap;
387 
388   OperandsOpcodeTypeRetPredCheckMap SimplePatternsCheck;
389 
390   std::map<OperandsSignature, std::vector<OperandsSignature> >
391     SignaturesWithConstantForms;
392 
393   StringRef InstNS;
394   ImmPredicateSet ImmediatePredicates;
395 public:
396   explicit FastISelMap(StringRef InstNS);
397 
398   void collectPatterns(CodeGenDAGPatterns &CGP);
399   void printImmediatePredicates(raw_ostream &OS);
400   void printFunctionDefinitions(raw_ostream &OS);
401 private:
402   void emitInstructionCode(raw_ostream &OS,
403                            const OperandsSignature &Operands,
404                            const PredMap &PM,
405                            const std::string &RetVTName);
406 };
407 } // End anonymous namespace
408 
409 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
410   return CGP.getSDNodeInfo(Op).getEnumName();
411 }
412 
413 static std::string getLegalCName(std::string OpName) {
414   std::string::size_type pos = OpName.find("::");
415   if (pos != std::string::npos)
416     OpName.replace(pos, 2, "_");
417   return OpName;
418 }
419 
420 FastISelMap::FastISelMap(StringRef instns) : InstNS(instns) {}
421 
422 static std::string PhyRegForNode(TreePatternNode *Op,
423                                  const CodeGenTarget &Target) {
424   std::string PhysReg;
425 
426   if (!Op->isLeaf())
427     return PhysReg;
428 
429   Record *OpLeafRec = cast<DefInit>(Op->getLeafValue())->getDef();
430   if (!OpLeafRec->isSubClassOf("Register"))
431     return PhysReg;
432 
433   PhysReg += cast<StringInit>(OpLeafRec->getValue("Namespace")->getValue())
434                ->getValue();
435   PhysReg += "::";
436   PhysReg += Target.getRegBank().getReg(OpLeafRec)->getName();
437   return PhysReg;
438 }
439 
440 void FastISelMap::collectPatterns(CodeGenDAGPatterns &CGP) {
441   const CodeGenTarget &Target = CGP.getTargetInfo();
442 
443   // Scan through all the patterns and record the simple ones.
444   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
445        E = CGP.ptm_end(); I != E; ++I) {
446     const PatternToMatch &Pattern = *I;
447 
448     // For now, just look at Instructions, so that we don't have to worry
449     // about emitting multiple instructions for a pattern.
450     TreePatternNode *Dst = Pattern.getDstPattern();
451     if (Dst->isLeaf()) continue;
452     Record *Op = Dst->getOperator();
453     if (!Op->isSubClassOf("Instruction"))
454       continue;
455     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
456     if (II.Operands.empty())
457       continue;
458 
459     // For now, ignore multi-instruction patterns.
460     bool MultiInsts = false;
461     for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
462       TreePatternNode *ChildOp = Dst->getChild(i);
463       if (ChildOp->isLeaf())
464         continue;
465       if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
466         MultiInsts = true;
467         break;
468       }
469     }
470     if (MultiInsts)
471       continue;
472 
473     // For now, ignore instructions where the first operand is not an
474     // output register.
475     const CodeGenRegisterClass *DstRC = nullptr;
476     std::string SubRegNo;
477     if (Op->getName() != "EXTRACT_SUBREG") {
478       Record *Op0Rec = II.Operands[0].Rec;
479       if (Op0Rec->isSubClassOf("RegisterOperand"))
480         Op0Rec = Op0Rec->getValueAsDef("RegClass");
481       if (!Op0Rec->isSubClassOf("RegisterClass"))
482         continue;
483       DstRC = &Target.getRegisterClass(Op0Rec);
484       if (!DstRC)
485         continue;
486     } else {
487       // If this isn't a leaf, then continue since the register classes are
488       // a bit too complicated for now.
489       if (!Dst->getChild(1)->isLeaf()) continue;
490 
491       DefInit *SR = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
492       if (SR)
493         SubRegNo = getQualifiedName(SR->getDef());
494       else
495         SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
496     }
497 
498     // Inspect the pattern.
499     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
500     if (!InstPatNode) continue;
501     if (InstPatNode->isLeaf()) continue;
502 
503     // Ignore multiple result nodes for now.
504     if (InstPatNode->getNumTypes() > 1) continue;
505 
506     Record *InstPatOp = InstPatNode->getOperator();
507     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
508     MVT::SimpleValueType RetVT = MVT::isVoid;
509     if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0);
510     MVT::SimpleValueType VT = RetVT;
511     if (InstPatNode->getNumChildren()) {
512       assert(InstPatNode->getChild(0)->getNumTypes() == 1);
513       VT = InstPatNode->getChild(0)->getType(0);
514     }
515 
516     // For now, filter out any instructions with predicates.
517     if (!InstPatNode->getPredicateFns().empty())
518       continue;
519 
520     // Check all the operands.
521     OperandsSignature Operands;
522     if (!Operands.initialize(InstPatNode, Target, VT, ImmediatePredicates,
523                              DstRC))
524       continue;
525 
526     std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
527     if (InstPatNode->getOperator()->getName() == "imm" ||
528         InstPatNode->getOperator()->getName() == "fpimm")
529       PhysRegInputs->push_back("");
530     else {
531       // Compute the PhysRegs used by the given pattern, and check that
532       // the mapping from the src to dst patterns is simple.
533       bool FoundNonSimplePattern = false;
534       unsigned DstIndex = 0;
535       for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
536         std::string PhysReg = PhyRegForNode(InstPatNode->getChild(i), Target);
537         if (PhysReg.empty()) {
538           if (DstIndex >= Dst->getNumChildren() ||
539               Dst->getChild(DstIndex)->getName() !=
540               InstPatNode->getChild(i)->getName()) {
541             FoundNonSimplePattern = true;
542             break;
543           }
544           ++DstIndex;
545         }
546 
547         PhysRegInputs->push_back(PhysReg);
548       }
549 
550       if (Op->getName() != "EXTRACT_SUBREG" && DstIndex < Dst->getNumChildren())
551         FoundNonSimplePattern = true;
552 
553       if (FoundNonSimplePattern)
554         continue;
555     }
556 
557     // Check if the operands match one of the patterns handled by FastISel.
558     std::string ManglingSuffix;
559     raw_string_ostream SuffixOS(ManglingSuffix);
560     Operands.PrintManglingSuffix(SuffixOS, ImmediatePredicates, true);
561     SuffixOS.flush();
562     if (!StringSwitch<bool>(ManglingSuffix)
563         .Cases("", "r", "rr", "ri", "i", "f", true)
564         .Default(false))
565       continue;
566 
567     // Get the predicate that guards this pattern.
568     std::string PredicateCheck = Pattern.getPredicateCheck();
569 
570     // Ok, we found a pattern that we can handle. Remember it.
571     InstructionMemo Memo = {
572       Pattern.getDstPattern()->getOperator()->getName(),
573       DstRC,
574       SubRegNo,
575       PhysRegInputs,
576       PredicateCheck
577     };
578 
579     int complexity = Pattern.getPatternComplexity(CGP);
580 
581     if (SimplePatternsCheck[Operands][OpcodeName][VT]
582          [RetVT].count(PredicateCheck)) {
583       PrintFatalError(Pattern.getSrcRecord()->getLoc(),
584                     "Duplicate predicate in FastISel table!");
585     }
586     SimplePatternsCheck[Operands][OpcodeName][VT][RetVT].insert(
587             std::make_pair(PredicateCheck, true));
588 
589        // Note: Instructions with the same complexity will appear in the order
590           // that they are encountered.
591     SimplePatterns[Operands][OpcodeName][VT][RetVT].insert(
592       std::make_pair(complexity, Memo));
593 
594     // If any of the operands were immediates with predicates on them, strip
595     // them down to a signature that doesn't have predicates so that we can
596     // associate them with the stripped predicate version.
597     if (Operands.hasAnyImmediateCodes()) {
598       SignaturesWithConstantForms[Operands.getWithoutImmCodes()]
599         .push_back(Operands);
600     }
601   }
602 }
603 
604 void FastISelMap::printImmediatePredicates(raw_ostream &OS) {
605   if (ImmediatePredicates.begin() == ImmediatePredicates.end())
606     return;
607 
608   OS << "\n// FastEmit Immediate Predicate functions.\n";
609   for (ImmPredicateSet::iterator I = ImmediatePredicates.begin(),
610        E = ImmediatePredicates.end(); I != E; ++I) {
611     OS << "static bool " << I->getFnName() << "(int64_t Imm) {\n";
612     OS << I->getImmediatePredicateCode() << "\n}\n";
613   }
614 
615   OS << "\n\n";
616 }
617 
618 void FastISelMap::emitInstructionCode(raw_ostream &OS,
619                                       const OperandsSignature &Operands,
620                                       const PredMap &PM,
621                                       const std::string &RetVTName) {
622   // Emit code for each possible instruction. There may be
623   // multiple if there are subtarget concerns.  A reverse iterator
624   // is used to produce the ones with highest complexity first.
625 
626   bool OneHadNoPredicate = false;
627   for (PredMap::const_reverse_iterator PI = PM.rbegin(), PE = PM.rend();
628        PI != PE; ++PI) {
629     const InstructionMemo &Memo = PI->second;
630     std::string PredicateCheck = Memo.PredicateCheck;
631 
632     if (PredicateCheck.empty()) {
633       assert(!OneHadNoPredicate &&
634              "Multiple instructions match and more than one had "
635              "no predicate!");
636       OneHadNoPredicate = true;
637     } else {
638       if (OneHadNoPredicate) {
639         PrintFatalError("Multiple instructions match and one with no "
640                         "predicate came before one with a predicate!  "
641                         "name:" + Memo.Name + "  predicate: " + PredicateCheck);
642       }
643       OS << "  if (" + PredicateCheck + ") {\n";
644       OS << "  ";
645     }
646 
647     for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
648       if ((*Memo.PhysRegs)[i] != "")
649         OS << "  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, "
650            << "TII.get(TargetOpcode::COPY), "
651            << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
652     }
653 
654     OS << "  return fastEmitInst_";
655     if (Memo.SubRegNo.empty()) {
656       Operands.PrintManglingSuffix(OS, *Memo.PhysRegs,
657      ImmediatePredicates, true);
658       OS << "(" << InstNS << "::" << Memo.Name << ", ";
659       OS << "&" << InstNS << "::" << Memo.RC->getName() << "RegClass";
660       if (!Operands.empty())
661         OS << ", ";
662       Operands.PrintArguments(OS, *Memo.PhysRegs);
663       OS << ");\n";
664     } else {
665       OS << "extractsubreg(" << RetVTName
666          << ", Op0, Op0IsKill, " << Memo.SubRegNo << ");\n";
667     }
668 
669     if (!PredicateCheck.empty()) {
670       OS << "  }\n";
671     }
672   }
673   // Return 0 if all of the possibilities had predicates but none
674   // were satisfied.
675   if (!OneHadNoPredicate)
676     OS << "  return 0;\n";
677   OS << "}\n";
678   OS << "\n";
679 }
680 
681 
682 void FastISelMap::printFunctionDefinitions(raw_ostream &OS) {
683   // Now emit code for all the patterns that we collected.
684   for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
685        OE = SimplePatterns.end(); OI != OE; ++OI) {
686     const OperandsSignature &Operands = OI->first;
687     const OpcodeTypeRetPredMap &OTM = OI->second;
688 
689     for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
690          I != E; ++I) {
691       const std::string &Opcode = I->first;
692       const TypeRetPredMap &TM = I->second;
693 
694       OS << "// FastEmit functions for " << Opcode << ".\n";
695       OS << "\n";
696 
697       // Emit one function for each opcode,type pair.
698       for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
699            TI != TE; ++TI) {
700         MVT::SimpleValueType VT = TI->first;
701         const RetPredMap &RM = TI->second;
702         if (RM.size() != 1) {
703           for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
704                RI != RE; ++RI) {
705             MVT::SimpleValueType RetVT = RI->first;
706             const PredMap &PM = RI->second;
707 
708             OS << "unsigned fastEmit_"
709                << getLegalCName(Opcode)
710                << "_" << getLegalCName(getName(VT))
711                << "_" << getLegalCName(getName(RetVT)) << "_";
712             Operands.PrintManglingSuffix(OS, ImmediatePredicates);
713             OS << "(";
714             Operands.PrintParameters(OS);
715             OS << ") {\n";
716 
717             emitInstructionCode(OS, Operands, PM, getName(RetVT));
718           }
719 
720           // Emit one function for the type that demultiplexes on return type.
721           OS << "unsigned fastEmit_"
722              << getLegalCName(Opcode) << "_"
723              << getLegalCName(getName(VT)) << "_";
724           Operands.PrintManglingSuffix(OS, ImmediatePredicates);
725           OS << "(MVT RetVT";
726           if (!Operands.empty())
727             OS << ", ";
728           Operands.PrintParameters(OS);
729           OS << ") {\nswitch (RetVT.SimpleTy) {\n";
730           for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
731                RI != RE; ++RI) {
732             MVT::SimpleValueType RetVT = RI->first;
733             OS << "  case " << getName(RetVT) << ": return fastEmit_"
734                << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
735                << "_" << getLegalCName(getName(RetVT)) << "_";
736             Operands.PrintManglingSuffix(OS, ImmediatePredicates);
737             OS << "(";
738             Operands.PrintArguments(OS);
739             OS << ");\n";
740           }
741           OS << "  default: return 0;\n}\n}\n\n";
742 
743         } else {
744           // Non-variadic return type.
745           OS << "unsigned fastEmit_"
746              << getLegalCName(Opcode) << "_"
747              << getLegalCName(getName(VT)) << "_";
748           Operands.PrintManglingSuffix(OS, ImmediatePredicates);
749           OS << "(MVT RetVT";
750           if (!Operands.empty())
751             OS << ", ";
752           Operands.PrintParameters(OS);
753           OS << ") {\n";
754 
755           OS << "  if (RetVT.SimpleTy != " << getName(RM.begin()->first)
756              << ")\n    return 0;\n";
757 
758           const PredMap &PM = RM.begin()->second;
759 
760           emitInstructionCode(OS, Operands, PM, "RetVT");
761         }
762       }
763 
764       // Emit one function for the opcode that demultiplexes based on the type.
765       OS << "unsigned fastEmit_"
766          << getLegalCName(Opcode) << "_";
767       Operands.PrintManglingSuffix(OS, ImmediatePredicates);
768       OS << "(MVT VT, MVT RetVT";
769       if (!Operands.empty())
770         OS << ", ";
771       Operands.PrintParameters(OS);
772       OS << ") {\n";
773       OS << "  switch (VT.SimpleTy) {\n";
774       for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
775            TI != TE; ++TI) {
776         MVT::SimpleValueType VT = TI->first;
777         std::string TypeName = getName(VT);
778         OS << "  case " << TypeName << ": return fastEmit_"
779            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
780         Operands.PrintManglingSuffix(OS, ImmediatePredicates);
781         OS << "(RetVT";
782         if (!Operands.empty())
783           OS << ", ";
784         Operands.PrintArguments(OS);
785         OS << ");\n";
786       }
787       OS << "  default: return 0;\n";
788       OS << "  }\n";
789       OS << "}\n";
790       OS << "\n";
791     }
792 
793     OS << "// Top-level FastEmit function.\n";
794     OS << "\n";
795 
796     // Emit one function for the operand signature that demultiplexes based
797     // on opcode and type.
798     OS << "unsigned fastEmit_";
799     Operands.PrintManglingSuffix(OS, ImmediatePredicates);
800     OS << "(MVT VT, MVT RetVT, unsigned Opcode";
801     if (!Operands.empty())
802       OS << ", ";
803     Operands.PrintParameters(OS);
804     OS << ") ";
805     if (!Operands.hasAnyImmediateCodes())
806       OS << "override ";
807     OS << "{\n";
808 
809     // If there are any forms of this signature available that operate on
810     // constrained forms of the immediate (e.g., 32-bit sext immediate in a
811     // 64-bit operand), check them first.
812 
813     std::map<OperandsSignature, std::vector<OperandsSignature> >::iterator MI
814       = SignaturesWithConstantForms.find(Operands);
815     if (MI != SignaturesWithConstantForms.end()) {
816       // Unique any duplicates out of the list.
817       std::sort(MI->second.begin(), MI->second.end());
818       MI->second.erase(std::unique(MI->second.begin(), MI->second.end()),
819                        MI->second.end());
820 
821       // Check each in order it was seen.  It would be nice to have a good
822       // relative ordering between them, but we're not going for optimality
823       // here.
824       for (unsigned i = 0, e = MI->second.size(); i != e; ++i) {
825         OS << "  if (";
826         MI->second[i].emitImmediatePredicate(OS, ImmediatePredicates);
827         OS << ")\n    if (unsigned Reg = fastEmit_";
828         MI->second[i].PrintManglingSuffix(OS, ImmediatePredicates);
829         OS << "(VT, RetVT, Opcode";
830         if (!MI->second[i].empty())
831           OS << ", ";
832         MI->second[i].PrintArguments(OS);
833         OS << "))\n      return Reg;\n\n";
834       }
835 
836       // Done with this, remove it.
837       SignaturesWithConstantForms.erase(MI);
838     }
839 
840     OS << "  switch (Opcode) {\n";
841     for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
842          I != E; ++I) {
843       const std::string &Opcode = I->first;
844 
845       OS << "  case " << Opcode << ": return fastEmit_"
846          << getLegalCName(Opcode) << "_";
847       Operands.PrintManglingSuffix(OS, ImmediatePredicates);
848       OS << "(VT, RetVT";
849       if (!Operands.empty())
850         OS << ", ";
851       Operands.PrintArguments(OS);
852       OS << ");\n";
853     }
854     OS << "  default: return 0;\n";
855     OS << "  }\n";
856     OS << "}\n";
857     OS << "\n";
858   }
859 
860   // TODO: SignaturesWithConstantForms should be empty here.
861 }
862 
863 namespace llvm {
864 
865 void EmitFastISel(RecordKeeper &RK, raw_ostream &OS) {
866   CodeGenDAGPatterns CGP(RK);
867   const CodeGenTarget &Target = CGP.getTargetInfo();
868   emitSourceFileHeader("\"Fast\" Instruction Selector for the " +
869                        Target.getName().str() + " target", OS);
870 
871   // Determine the target's namespace name.
872   StringRef InstNS = Target.getInstNamespace();
873   assert(!InstNS.empty() && "Can't determine target-specific namespace!");
874 
875   FastISelMap F(InstNS);
876   F.collectPatterns(CGP);
877   F.printImmediatePredicates(OS);
878   F.printFunctionDefinitions(OS);
879 }
880 
881 } // End llvm namespace
882