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