1 //===- FastISelEmitter.cpp - Generate an instruction selector -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a "fast" instruction selector.
12 // This instruction selection method is designed to emit very poor code
13 // quickly. Also, it is not designed to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations (e.g. calls) are not
15 // supported and cannot easily be added. Blocks containing operations
16 // that are not supported need to be handled by a more capable selector,
17 // such as the SelectionDAG selector.
19 // The intended use for "fast" instruction selection is "-O0" mode
20 // compilation, where the quality of the generated code is irrelevant when
21 // weighed against the speed at which the code can be generated.
23 // If compile time is so important, you might wonder why we don't just
24 // skip codegen all-together, emit LLVM bytecode files, and execute them
25 // with an interpreter. The answer is that it would complicate linking and
26 // debugging, and also because that isn't how a compiler is expected to
27 // work in some circles.
29 // If you need better generated code or more lowering than what this
30 // instruction selector provides, use the SelectionDAG (DAGISel) instruction
31 // selector instead. If you're looking here because SelectionDAG isn't fast
32 // enough, consider looking into improving the SelectionDAG infastructure
33 // instead. At the time of this writing there remain several major
34 // opportunities for improvement.
36 //===----------------------------------------------------------------------===//
38 #include "FastISelEmitter.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Streams.h"
42 #include "llvm/ADT/VectorExtras.h"
47 /// OperandsSignature - This class holds a description of a list of operand
48 /// types. It has utility methods for emitting text based on the operands.
50 struct OperandsSignature {
51 std::vector<std::string> Operands;
53 bool operator<(const OperandsSignature &O) const {
54 return Operands < O.Operands;
57 bool empty() const { return Operands.empty(); }
59 /// initialize - Examine the given pattern and initialize the contents
60 /// of the Operands array accordingly. Return true if all the operands
61 /// are supported, false otherwise.
63 bool initialize(TreePatternNode *InstPatNode,
64 const CodeGenTarget &Target,
65 MVT::SimpleValueType VT) {
66 if (!InstPatNode->isLeaf() &&
67 InstPatNode->getOperator()->getName() == "imm") {
68 Operands.push_back("i");
71 if (!InstPatNode->isLeaf() &&
72 InstPatNode->getOperator()->getName() == "fpimm") {
73 Operands.push_back("f");
77 const CodeGenRegisterClass *DstRC = 0;
79 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
80 TreePatternNode *Op = InstPatNode->getChild(i);
81 // For now, filter out any operand with a predicate.
82 if (!Op->getPredicateFn().empty())
84 // For now, filter out any operand with multiple values.
85 if (Op->getExtTypes().size() != 1)
87 // For now, all the operands must have the same type.
88 if (Op->getTypeNum(0) != VT)
91 if (Op->getOperator()->getName() == "imm") {
92 Operands.push_back("i");
95 if (Op->getOperator()->getName() == "fpimm") {
96 Operands.push_back("f");
99 // For now, ignore other non-leaf nodes.
102 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
105 Record *OpLeafRec = OpDI->getDef();
106 // TODO: handle instructions which have physreg operands.
107 if (OpLeafRec->isSubClassOf("Register"))
109 // For now, the only other thing we accept is register operands.
110 if (!OpLeafRec->isSubClassOf("RegisterClass"))
112 // For now, require the register operands' register classes to all
114 const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
117 // For now, all the operands must have the same register class.
123 Operands.push_back("r");
128 void PrintParameters(std::ostream &OS) const {
129 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
130 if (Operands[i] == "r") {
131 OS << "unsigned Op" << i;
132 } else if (Operands[i] == "i") {
133 OS << "uint64_t imm" << i;
134 } else if (Operands[i] == "f") {
135 OS << "ConstantFP *f" << i;
137 assert("Unknown operand kind!");
145 void PrintArguments(std::ostream &OS) const {
146 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
147 if (Operands[i] == "r") {
149 } else if (Operands[i] == "i") {
151 } else if (Operands[i] == "f") {
154 assert("Unknown operand kind!");
162 void PrintManglingSuffix(std::ostream &OS) const {
163 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
169 /// InstructionMemo - This class holds additional information about an
170 /// instruction needed to emit code for it.
172 struct InstructionMemo {
174 const CodeGenRegisterClass *RC;
175 unsigned char SubRegNo;
179 typedef std::map<std::string, InstructionMemo> PredMap;
180 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
181 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
182 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
183 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
185 OperandsOpcodeTypeRetPredMap SimplePatterns;
190 explicit FastISelMap(std::string InstNS);
192 void CollectPatterns(CodeGenDAGPatterns &CGP);
193 void PrintClass(std::ostream &OS);
194 void PrintFunctionDefinitions(std::ostream &OS);
199 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
200 return CGP.getSDNodeInfo(Op).getEnumName();
203 static std::string getLegalCName(std::string OpName) {
204 std::string::size_type pos = OpName.find("::");
205 if (pos != std::string::npos)
206 OpName.replace(pos, 2, "_");
210 FastISelMap::FastISelMap(std::string instns)
214 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
215 const CodeGenTarget &Target = CGP.getTargetInfo();
217 // Determine the target's namespace name.
218 InstNS = Target.getInstNamespace() + "::";
219 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
221 // Scan through all the patterns and record the simple ones.
222 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
223 E = CGP.ptm_end(); I != E; ++I) {
224 const PatternToMatch &Pattern = *I;
226 // For now, just look at Instructions, so that we don't have to worry
227 // about emitting multiple instructions for a pattern.
228 TreePatternNode *Dst = Pattern.getDstPattern();
229 if (Dst->isLeaf()) continue;
230 Record *Op = Dst->getOperator();
231 if (!Op->isSubClassOf("Instruction"))
233 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
234 if (II.OperandList.empty())
237 // For now, ignore instructions where the first operand is not an
239 const CodeGenRegisterClass *DstRC = 0;
240 unsigned SubRegNo = ~0;
241 if (Op->getName() != "EXTRACT_SUBREG") {
242 Record *Op0Rec = II.OperandList[0].Rec;
243 if (!Op0Rec->isSubClassOf("RegisterClass"))
245 DstRC = &Target.getRegisterClass(Op0Rec);
249 SubRegNo = static_cast<IntInit*>(
250 Dst->getChild(1)->getLeafValue())->getValue();
253 // Inspect the pattern.
254 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
255 if (!InstPatNode) continue;
256 if (InstPatNode->isLeaf()) continue;
258 Record *InstPatOp = InstPatNode->getOperator();
259 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
260 MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
261 MVT::SimpleValueType VT = RetVT;
262 if (InstPatNode->getNumChildren())
263 VT = InstPatNode->getChild(0)->getTypeNum(0);
265 // For now, filter out instructions which just set a register to
266 // an Operand or an immediate, like MOV32ri.
267 if (InstPatOp->isSubClassOf("Operand"))
270 // For now, filter out any instructions with predicates.
271 if (!InstPatNode->getPredicateFn().empty())
274 // Check all the operands.
275 OperandsSignature Operands;
276 if (!Operands.initialize(InstPatNode, Target, VT))
279 // Get the predicate that guards this pattern.
280 std::string PredicateCheck = Pattern.getPredicateCheck();
282 // Ok, we found a pattern that we can handle. Remember it.
283 InstructionMemo Memo = {
284 Pattern.getDstPattern()->getOperator()->getName(),
288 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
289 "Duplicate pattern!");
290 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
294 void FastISelMap::PrintClass(std::ostream &OS) {
295 // Declare the target FastISel class.
296 OS << "class FastISel : public llvm::FastISel {\n";
297 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
298 OE = SimplePatterns.end(); OI != OE; ++OI) {
299 const OperandsSignature &Operands = OI->first;
300 const OpcodeTypeRetPredMap &OTM = OI->second;
302 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
304 const std::string &Opcode = I->first;
305 const TypeRetPredMap &TM = I->second;
307 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
309 MVT::SimpleValueType VT = TI->first;
310 const RetPredMap &RM = TI->second;
313 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
315 MVT::SimpleValueType RetVT = RI->first;
316 OS << " unsigned FastEmit_" << getLegalCName(Opcode)
317 << "_" << getLegalCName(getName(VT)) << "_"
318 << getLegalCName(getName(RetVT)) << "_";
319 Operands.PrintManglingSuffix(OS);
321 Operands.PrintParameters(OS);
325 OS << " unsigned FastEmit_" << getLegalCName(Opcode)
326 << "_" << getLegalCName(getName(VT)) << "_";
327 Operands.PrintManglingSuffix(OS);
328 OS << "(MVT::SimpleValueType RetVT";
329 if (!Operands.empty())
331 Operands.PrintParameters(OS);
335 OS << " unsigned FastEmit_" << getLegalCName(Opcode) << "_";
336 Operands.PrintManglingSuffix(OS);
337 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
338 if (!Operands.empty())
340 Operands.PrintParameters(OS);
344 OS << " unsigned FastEmit_";
345 Operands.PrintManglingSuffix(OS);
346 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
347 if (!Operands.empty())
349 Operands.PrintParameters(OS);
354 OS << "bool TargetSelectInstruction(Instruction *I,\n";
356 "DenseMap<const Value *, unsigned> &ValueMap,\n";
358 "DenseMap<const BasicBlock *, MachineBasicBlock *> &MBBMap,\n";
360 "MachineBasicBlock *MBB);\n";
362 // Declare the Subtarget member, which is used for predicate checks.
363 OS << " const " << InstNS.substr(0, InstNS.size() - 2)
364 << "Subtarget *Subtarget;\n";
367 // Declare the constructor.
369 OS << " explicit FastISel(MachineFunction &mf)\n";
370 OS << " : llvm::FastISel(mf),\n";
371 OS << " Subtarget(&TM.getSubtarget<" << InstNS.substr(0, InstNS.size() - 2)
372 << "Subtarget>()) {}\n";
377 void FastISelMap::PrintFunctionDefinitions(std::ostream &OS) {
378 // Now emit code for all the patterns that we collected.
379 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
380 OE = SimplePatterns.end(); OI != OE; ++OI) {
381 const OperandsSignature &Operands = OI->first;
382 const OpcodeTypeRetPredMap &OTM = OI->second;
384 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
386 const std::string &Opcode = I->first;
387 const TypeRetPredMap &TM = I->second;
389 OS << "// FastEmit functions for " << Opcode << ".\n";
392 // Emit one function for each opcode,type pair.
393 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
395 MVT::SimpleValueType VT = TI->first;
396 const RetPredMap &RM = TI->second;
397 if (RM.size() != 1) {
398 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
400 MVT::SimpleValueType RetVT = RI->first;
401 const PredMap &PM = RI->second;
402 bool HasPred = false;
404 OS << "unsigned FastISel::FastEmit_"
405 << getLegalCName(Opcode)
406 << "_" << getLegalCName(getName(VT))
407 << "_" << getLegalCName(getName(RetVT)) << "_";
408 Operands.PrintManglingSuffix(OS);
410 Operands.PrintParameters(OS);
413 // Emit code for each possible instruction. There may be
414 // multiple if there are subtarget concerns.
415 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
417 std::string PredicateCheck = PI->first;
418 const InstructionMemo &Memo = PI->second;
420 if (PredicateCheck.empty()) {
422 "Multiple instructions match, at least one has "
423 "a predicate and at least one doesn't!");
425 OS << " if (" + PredicateCheck + ")\n";
429 OS << " return FastEmitInst_";
430 if (Memo.SubRegNo == (unsigned char)~0) {
431 Operands.PrintManglingSuffix(OS);
432 OS << "(" << InstNS << Memo.Name << ", ";
433 OS << InstNS << Memo.RC->getName() << "RegisterClass";
434 if (!Operands.empty())
436 Operands.PrintArguments(OS);
439 OS << "extractsubreg(Op0, ";
440 OS << (unsigned)Memo.SubRegNo;
444 // Return 0 if none of the predicates were satisfied.
446 OS << " return 0;\n";
451 // Emit one function for the type that demultiplexes on return type.
452 OS << "unsigned FastISel::FastEmit_"
453 << getLegalCName(Opcode) << "_"
454 << getLegalCName(getName(VT)) << "_";
455 Operands.PrintManglingSuffix(OS);
456 OS << "(MVT::SimpleValueType RetVT";
457 if (!Operands.empty())
459 Operands.PrintParameters(OS);
460 OS << ") {\nswitch (RetVT) {\n";
461 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
463 MVT::SimpleValueType RetVT = RI->first;
464 OS << " case " << getName(RetVT) << ": return FastEmit_"
465 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
466 << "_" << getLegalCName(getName(RetVT)) << "_";
467 Operands.PrintManglingSuffix(OS);
469 Operands.PrintArguments(OS);
472 OS << " default: return 0;\n}\n}\n\n";
475 // Non-variadic return type.
476 OS << "unsigned FastISel::FastEmit_"
477 << getLegalCName(Opcode) << "_"
478 << getLegalCName(getName(VT)) << "_";
479 Operands.PrintManglingSuffix(OS);
480 OS << "(MVT::SimpleValueType RetVT";
481 if (!Operands.empty())
483 Operands.PrintParameters(OS);
486 OS << " if (RetVT != " << getName(RM.begin()->first)
487 << ")\n return 0;\n";
489 const PredMap &PM = RM.begin()->second;
490 bool HasPred = false;
492 // Emit code for each possible instruction. There may be
493 // multiple if there are subtarget concerns.
494 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE; ++PI) {
495 std::string PredicateCheck = PI->first;
496 const InstructionMemo &Memo = PI->second;
498 if (PredicateCheck.empty()) {
500 "Multiple instructions match, at least one has "
501 "a predicate and at least one doesn't!");
503 OS << " if (" + PredicateCheck + ")\n";
507 OS << " return FastEmitInst_";
509 if (Memo.SubRegNo == (unsigned char)~0) {
510 Operands.PrintManglingSuffix(OS);
511 OS << "(" << InstNS << Memo.Name << ", ";
512 OS << InstNS << Memo.RC->getName() << "RegisterClass";
513 if (!Operands.empty())
515 Operands.PrintArguments(OS);
518 OS << "extractsubreg(Op0, ";
519 OS << (unsigned)Memo.SubRegNo;
524 // Return 0 if none of the predicates were satisfied.
526 OS << " return 0;\n";
532 // Emit one function for the opcode that demultiplexes based on the type.
533 OS << "unsigned FastISel::FastEmit_"
534 << getLegalCName(Opcode) << "_";
535 Operands.PrintManglingSuffix(OS);
536 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
537 if (!Operands.empty())
539 Operands.PrintParameters(OS);
541 OS << " switch (VT) {\n";
542 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
544 MVT::SimpleValueType VT = TI->first;
545 std::string TypeName = getName(VT);
546 OS << " case " << TypeName << ": return FastEmit_"
547 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
548 Operands.PrintManglingSuffix(OS);
550 if (!Operands.empty())
552 Operands.PrintArguments(OS);
555 OS << " default: return 0;\n";
561 OS << "// Top-level FastEmit function.\n";
564 // Emit one function for the operand signature that demultiplexes based
565 // on opcode and type.
566 OS << "unsigned FastISel::FastEmit_";
567 Operands.PrintManglingSuffix(OS);
568 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
569 if (!Operands.empty())
571 Operands.PrintParameters(OS);
573 OS << " switch (Opcode) {\n";
574 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
576 const std::string &Opcode = I->first;
578 OS << " case " << Opcode << ": return FastEmit_"
579 << getLegalCName(Opcode) << "_";
580 Operands.PrintManglingSuffix(OS);
582 if (!Operands.empty())
584 Operands.PrintArguments(OS);
587 OS << " default: return 0;\n";
594 void FastISelEmitter::run(std::ostream &OS) {
595 const CodeGenTarget &Target = CGP.getTargetInfo();
597 // Determine the target's namespace name.
598 std::string InstNS = Target.getInstNamespace() + "::";
599 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
601 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
602 Target.getName() + " target", OS);
604 OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
606 OS << "namespace llvm {\n";
608 OS << "namespace " << InstNS.substr(0, InstNS.size() - 2) << " {\n";
611 FastISelMap F(InstNS);
612 F.CollectPatterns(CGP);
614 F.PrintFunctionDefinitions(OS);
616 // Define the target FastISel creation function.
617 OS << "llvm::FastISel *createFastISel(MachineFunction &mf) {\n";
618 OS << " return new FastISel(mf);\n";
622 OS << "} // namespace X86\n";
624 OS << "} // namespace llvm\n";
627 FastISelEmitter::FastISelEmitter(RecordKeeper &R)