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 /// InstructionMemo - This class holds additional information about an
48 /// instruction needed to emit code for it.
50 struct InstructionMemo {
52 const CodeGenRegisterClass *RC;
53 unsigned char SubRegNo;
54 std::vector<std::string>* PhysRegs;
57 /// OperandsSignature - This class holds a description of a list of operand
58 /// types. It has utility methods for emitting text based on the operands.
60 struct OperandsSignature {
61 std::vector<std::string> Operands;
63 bool operator<(const OperandsSignature &O) const {
64 return Operands < O.Operands;
67 bool empty() const { return Operands.empty(); }
69 /// initialize - Examine the given pattern and initialize the contents
70 /// of the Operands array accordingly. Return true if all the operands
71 /// are supported, false otherwise.
73 bool initialize(TreePatternNode *InstPatNode,
74 const CodeGenTarget &Target,
75 MVT::SimpleValueType VT) {
76 if (!InstPatNode->isLeaf() &&
77 InstPatNode->getOperator()->getName() == "imm") {
78 Operands.push_back("i");
81 if (!InstPatNode->isLeaf() &&
82 InstPatNode->getOperator()->getName() == "fpimm") {
83 Operands.push_back("f");
87 const CodeGenRegisterClass *DstRC = 0;
89 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
90 TreePatternNode *Op = InstPatNode->getChild(i);
91 // For now, filter out any operand with a predicate.
92 if (!Op->getPredicateFn().empty())
94 // For now, filter out any operand with multiple values.
95 if (Op->getExtTypes().size() != 1)
97 // For now, all the operands must have the same type.
98 if (Op->getTypeNum(0) != VT)
101 if (Op->getOperator()->getName() == "imm") {
102 Operands.push_back("i");
105 if (Op->getOperator()->getName() == "fpimm") {
106 Operands.push_back("f");
109 // For now, ignore other non-leaf nodes.
112 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
115 Record *OpLeafRec = OpDI->getDef();
116 // For now, the only other thing we accept is register operands.
118 const CodeGenRegisterClass *RC = 0;
119 if (OpLeafRec->isSubClassOf("RegisterClass"))
120 RC = &Target.getRegisterClass(OpLeafRec);
121 else if (OpLeafRec->isSubClassOf("Register"))
122 RC = Target.getRegisterClassForRegister(OpLeafRec);
125 // For now, require the register operands' register classes to all
129 // For now, all the operands must have the same register class.
135 Operands.push_back("r");
140 void PrintParameters(std::ostream &OS) const {
141 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
142 if (Operands[i] == "r") {
143 OS << "unsigned Op" << i;
144 } else if (Operands[i] == "i") {
145 OS << "uint64_t imm" << i;
146 } else if (Operands[i] == "f") {
147 OS << "ConstantFP *f" << i;
149 assert("Unknown operand kind!");
157 void PrintArguments(std::ostream &OS,
158 const std::vector<std::string>& PR) const {
159 assert(PR.size() == Operands.size());
160 bool PrintedArg = false;
161 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
163 // Implicit physical register operand.
168 if (Operands[i] == "r") {
171 } else if (Operands[i] == "i") {
174 } else if (Operands[i] == "f") {
178 assert("Unknown operand kind!");
184 void PrintArguments(std::ostream &OS) const {
185 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
186 if (Operands[i] == "r") {
188 } else if (Operands[i] == "i") {
190 } else if (Operands[i] == "f") {
193 assert("Unknown operand kind!");
202 void PrintManglingSuffix(std::ostream &OS,
203 const std::vector<std::string>& PR) const {
204 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
206 // Implicit physical register operand. e.g. Instruction::Mul expect to
207 // select to a binary op. On x86, mul may take a single operand with
208 // the other operand being implicit. We must emit something that looks
209 // like a binary instruction except for the very inner FastEmitInst_*
216 void PrintManglingSuffix(std::ostream &OS) const {
217 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
224 typedef std::map<std::string, InstructionMemo> PredMap;
225 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
226 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
227 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
228 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
230 OperandsOpcodeTypeRetPredMap SimplePatterns;
235 explicit FastISelMap(std::string InstNS);
237 void CollectPatterns(CodeGenDAGPatterns &CGP);
238 void PrintClass(std::ostream &OS);
239 void PrintFunctionDefinitions(std::ostream &OS);
244 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
245 return CGP.getSDNodeInfo(Op).getEnumName();
248 static std::string getLegalCName(std::string OpName) {
249 std::string::size_type pos = OpName.find("::");
250 if (pos != std::string::npos)
251 OpName.replace(pos, 2, "_");
255 FastISelMap::FastISelMap(std::string instns)
259 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
260 const CodeGenTarget &Target = CGP.getTargetInfo();
262 // Determine the target's namespace name.
263 InstNS = Target.getInstNamespace() + "::";
264 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
266 // Scan through all the patterns and record the simple ones.
267 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
268 E = CGP.ptm_end(); I != E; ++I) {
269 const PatternToMatch &Pattern = *I;
271 // For now, just look at Instructions, so that we don't have to worry
272 // about emitting multiple instructions for a pattern.
273 TreePatternNode *Dst = Pattern.getDstPattern();
274 if (Dst->isLeaf()) continue;
275 Record *Op = Dst->getOperator();
276 if (!Op->isSubClassOf("Instruction"))
278 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
279 if (II.OperandList.empty())
282 // For now, ignore multi-instruction patterns.
283 bool MultiInsts = false;
284 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
285 TreePatternNode *ChildOp = Dst->getChild(i);
286 if (ChildOp->isLeaf())
288 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
296 // For now, ignore instructions where the first operand is not an
298 const CodeGenRegisterClass *DstRC = 0;
299 unsigned SubRegNo = ~0;
300 if (Op->getName() != "EXTRACT_SUBREG") {
301 Record *Op0Rec = II.OperandList[0].Rec;
302 if (!Op0Rec->isSubClassOf("RegisterClass"))
304 DstRC = &Target.getRegisterClass(Op0Rec);
308 SubRegNo = static_cast<IntInit*>(
309 Dst->getChild(1)->getLeafValue())->getValue();
312 // Inspect the pattern.
313 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
314 if (!InstPatNode) continue;
315 if (InstPatNode->isLeaf()) continue;
317 Record *InstPatOp = InstPatNode->getOperator();
318 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
319 MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
320 MVT::SimpleValueType VT = RetVT;
321 if (InstPatNode->getNumChildren())
322 VT = InstPatNode->getChild(0)->getTypeNum(0);
324 // For now, filter out instructions which just set a register to
325 // an Operand or an immediate, like MOV32ri.
326 if (InstPatOp->isSubClassOf("Operand"))
329 // For now, filter out any instructions with predicates.
330 if (!InstPatNode->getPredicateFn().empty())
333 // Check all the operands.
334 OperandsSignature Operands;
335 if (!Operands.initialize(InstPatNode, Target, VT))
338 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
339 if (!InstPatNode->isLeaf() &&
340 (InstPatNode->getOperator()->getName() == "imm" ||
341 InstPatNode->getOperator()->getName() == "fpimmm"))
342 PhysRegInputs->push_back("");
343 else if (!InstPatNode->isLeaf()) {
344 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
345 TreePatternNode *Op = InstPatNode->getChild(i);
347 PhysRegInputs->push_back("");
351 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
352 Record *OpLeafRec = OpDI->getDef();
354 if (OpLeafRec->isSubClassOf("Register")) {
355 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
356 "Namespace")->getValue())->getValue();
359 std::vector<CodeGenRegister> Regs = Target.getRegisters();
360 for (unsigned i = 0; i < Regs.size(); ++i) {
361 if (Regs[i].TheDef == OpLeafRec) {
362 PhysReg += Regs[i].getName();
368 PhysRegInputs->push_back(PhysReg);
371 PhysRegInputs->push_back("");
373 // Get the predicate that guards this pattern.
374 std::string PredicateCheck = Pattern.getPredicateCheck();
376 // Ok, we found a pattern that we can handle. Remember it.
377 InstructionMemo Memo = {
378 Pattern.getDstPattern()->getOperator()->getName(),
383 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
384 "Duplicate pattern!");
385 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
389 void FastISelMap::PrintFunctionDefinitions(std::ostream &OS) {
390 // Now emit code for all the patterns that we collected.
391 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
392 OE = SimplePatterns.end(); OI != OE; ++OI) {
393 const OperandsSignature &Operands = OI->first;
394 const OpcodeTypeRetPredMap &OTM = OI->second;
396 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
398 const std::string &Opcode = I->first;
399 const TypeRetPredMap &TM = I->second;
401 OS << "// FastEmit functions for " << Opcode << ".\n";
404 // Emit one function for each opcode,type pair.
405 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
407 MVT::SimpleValueType VT = TI->first;
408 const RetPredMap &RM = TI->second;
409 if (RM.size() != 1) {
410 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
412 MVT::SimpleValueType RetVT = RI->first;
413 const PredMap &PM = RI->second;
414 bool HasPred = false;
416 OS << "unsigned FastEmit_"
417 << getLegalCName(Opcode)
418 << "_" << getLegalCName(getName(VT))
419 << "_" << getLegalCName(getName(RetVT)) << "_";
420 Operands.PrintManglingSuffix(OS);
422 Operands.PrintParameters(OS);
425 // Emit code for each possible instruction. There may be
426 // multiple if there are subtarget concerns.
427 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
429 std::string PredicateCheck = PI->first;
430 const InstructionMemo &Memo = PI->second;
432 if (PredicateCheck.empty()) {
434 "Multiple instructions match, at least one has "
435 "a predicate and at least one doesn't!");
437 OS << " if (" + PredicateCheck + ") {\n";
442 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
443 if ((*Memo.PhysRegs)[i] != "")
444 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
445 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
446 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
447 << (*Memo.PhysRegs)[i] << "), "
448 << "MRI.getRegClass(Op" << i << "));\n";
451 OS << " return FastEmitInst_";
452 if (Memo.SubRegNo == (unsigned char)~0) {
453 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
454 OS << "(" << InstNS << Memo.Name << ", ";
455 OS << InstNS << Memo.RC->getName() << "RegisterClass";
456 if (!Operands.empty())
458 Operands.PrintArguments(OS, *Memo.PhysRegs);
461 OS << "extractsubreg(Op0, ";
462 OS << (unsigned)Memo.SubRegNo;
470 // Return 0 if none of the predicates were satisfied.
472 OS << " return 0;\n";
477 // Emit one function for the type that demultiplexes on return type.
478 OS << "unsigned FastEmit_"
479 << getLegalCName(Opcode) << "_"
480 << getLegalCName(getName(VT)) << "_";
481 Operands.PrintManglingSuffix(OS);
482 OS << "(MVT::SimpleValueType RetVT";
483 if (!Operands.empty())
485 Operands.PrintParameters(OS);
486 OS << ") {\nswitch (RetVT) {\n";
487 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
489 MVT::SimpleValueType RetVT = RI->first;
490 OS << " case " << getName(RetVT) << ": return FastEmit_"
491 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
492 << "_" << getLegalCName(getName(RetVT)) << "_";
493 Operands.PrintManglingSuffix(OS);
495 Operands.PrintArguments(OS);
498 OS << " default: return 0;\n}\n}\n\n";
501 // Non-variadic return type.
502 OS << "unsigned FastEmit_"
503 << getLegalCName(Opcode) << "_"
504 << getLegalCName(getName(VT)) << "_";
505 Operands.PrintManglingSuffix(OS);
506 OS << "(MVT::SimpleValueType RetVT";
507 if (!Operands.empty())
509 Operands.PrintParameters(OS);
512 OS << " if (RetVT != " << getName(RM.begin()->first)
513 << ")\n return 0;\n";
515 const PredMap &PM = RM.begin()->second;
516 bool HasPred = false;
518 // Emit code for each possible instruction. There may be
519 // multiple if there are subtarget concerns.
520 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
522 std::string PredicateCheck = PI->first;
523 const InstructionMemo &Memo = PI->second;
525 if (PredicateCheck.empty()) {
527 "Multiple instructions match, at least one has "
528 "a predicate and at least one doesn't!");
530 OS << " if (" + PredicateCheck + ") {\n";
535 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
536 if ((*Memo.PhysRegs)[i] != "")
537 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
538 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
539 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
540 << (*Memo.PhysRegs)[i] << "), "
541 << "MRI.getRegClass(Op" << i << "));\n";
544 OS << " return FastEmitInst_";
546 if (Memo.SubRegNo == (unsigned char)~0) {
547 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
548 OS << "(" << InstNS << Memo.Name << ", ";
549 OS << InstNS << Memo.RC->getName() << "RegisterClass";
550 if (!Operands.empty())
552 Operands.PrintArguments(OS, *Memo.PhysRegs);
555 OS << "extractsubreg(Op0, ";
556 OS << (unsigned)Memo.SubRegNo;
564 // Return 0 if none of the predicates were satisfied.
566 OS << " return 0;\n";
572 // Emit one function for the opcode that demultiplexes based on the type.
573 OS << "unsigned FastEmit_"
574 << getLegalCName(Opcode) << "_";
575 Operands.PrintManglingSuffix(OS);
576 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
577 if (!Operands.empty())
579 Operands.PrintParameters(OS);
581 OS << " switch (VT) {\n";
582 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
584 MVT::SimpleValueType VT = TI->first;
585 std::string TypeName = getName(VT);
586 OS << " case " << TypeName << ": return FastEmit_"
587 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
588 Operands.PrintManglingSuffix(OS);
590 if (!Operands.empty())
592 Operands.PrintArguments(OS);
595 OS << " default: return 0;\n";
601 OS << "// Top-level FastEmit function.\n";
604 // Emit one function for the operand signature that demultiplexes based
605 // on opcode and type.
606 OS << "unsigned FastEmit_";
607 Operands.PrintManglingSuffix(OS);
608 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
609 if (!Operands.empty())
611 Operands.PrintParameters(OS);
613 OS << " switch (Opcode) {\n";
614 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
616 const std::string &Opcode = I->first;
618 OS << " case " << Opcode << ": return FastEmit_"
619 << getLegalCName(Opcode) << "_";
620 Operands.PrintManglingSuffix(OS);
622 if (!Operands.empty())
624 Operands.PrintArguments(OS);
627 OS << " default: return 0;\n";
634 void FastISelEmitter::run(std::ostream &OS) {
635 const CodeGenTarget &Target = CGP.getTargetInfo();
637 // Determine the target's namespace name.
638 std::string InstNS = Target.getInstNamespace() + "::";
639 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
641 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
642 Target.getName() + " target", OS);
644 FastISelMap F(InstNS);
645 F.CollectPatterns(CGP);
646 F.PrintFunctionDefinitions(OS);
649 FastISelEmitter::FastISelEmitter(RecordKeeper &R)