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