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 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
163 } else if (Operands[i] == "r") {
165 } else if (Operands[i] == "i") {
167 } else if (Operands[i] == "f") {
170 assert("Unknown operand kind!");
178 void PrintArguments(std::ostream &OS) const {
179 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
180 if (Operands[i] == "r") {
182 } else if (Operands[i] == "i") {
184 } else if (Operands[i] == "f") {
187 assert("Unknown operand kind!");
196 void PrintManglingSuffix(std::ostream &OS) const {
197 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
204 typedef std::map<std::string, InstructionMemo> PredMap;
205 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
206 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
207 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
208 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
210 OperandsOpcodeTypeRetPredMap SimplePatterns;
215 explicit FastISelMap(std::string InstNS);
217 void CollectPatterns(CodeGenDAGPatterns &CGP);
218 void PrintClass(std::ostream &OS);
219 void PrintFunctionDefinitions(std::ostream &OS);
224 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
225 return CGP.getSDNodeInfo(Op).getEnumName();
228 static 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, "_");
235 FastISelMap::FastISelMap(std::string instns)
239 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
240 const CodeGenTarget &Target = CGP.getTargetInfo();
242 // Determine the target's namespace name.
243 InstNS = Target.getInstNamespace() + "::";
244 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
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;
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"))
258 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
259 if (II.OperandList.empty())
262 // For now, ignore instructions where the first operand is not an
264 const CodeGenRegisterClass *DstRC = 0;
265 unsigned SubRegNo = ~0;
266 if (Op->getName() != "EXTRACT_SUBREG") {
267 Record *Op0Rec = II.OperandList[0].Rec;
268 if (!Op0Rec->isSubClassOf("RegisterClass"))
270 DstRC = &Target.getRegisterClass(Op0Rec);
274 SubRegNo = static_cast<IntInit*>(
275 Dst->getChild(1)->getLeafValue())->getValue();
278 // Inspect the pattern.
279 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
280 if (!InstPatNode) continue;
281 if (InstPatNode->isLeaf()) continue;
283 Record *InstPatOp = InstPatNode->getOperator();
284 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
285 MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
286 MVT::SimpleValueType VT = RetVT;
287 if (InstPatNode->getNumChildren())
288 VT = InstPatNode->getChild(0)->getTypeNum(0);
290 // For now, filter out instructions which just set a register to
291 // an Operand or an immediate, like MOV32ri.
292 if (InstPatOp->isSubClassOf("Operand"))
295 // For now, filter out any instructions with predicates.
296 if (!InstPatNode->getPredicateFn().empty())
299 // Check all the operands.
300 OperandsSignature Operands;
301 if (!Operands.initialize(InstPatNode, Target, VT))
304 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
305 if (!InstPatNode->isLeaf() &&
306 (InstPatNode->getOperator()->getName() == "imm" ||
307 InstPatNode->getOperator()->getName() == "fpimmm"))
308 PhysRegInputs->push_back("");
309 else if (!InstPatNode->isLeaf()) {
310 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
311 TreePatternNode *Op = InstPatNode->getChild(i);
313 PhysRegInputs->push_back("");
317 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
318 Record *OpLeafRec = OpDI->getDef();
320 if (OpLeafRec->isSubClassOf("Register")) {
321 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
322 "Namespace")->getValue())->getValue();
325 std::vector<CodeGenRegister> Regs = Target.getRegisters();
326 for (unsigned i = 0; i < Regs.size(); ++i) {
327 if (Regs[i].TheDef == OpLeafRec) {
328 PhysReg += Regs[i].getName();
334 PhysRegInputs->push_back(PhysReg);
337 PhysRegInputs->push_back("");
339 // Get the predicate that guards this pattern.
340 std::string PredicateCheck = Pattern.getPredicateCheck();
342 // Ok, we found a pattern that we can handle. Remember it.
343 InstructionMemo Memo = {
344 Pattern.getDstPattern()->getOperator()->getName(),
349 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
350 "Duplicate pattern!");
351 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
355 void FastISelMap::PrintFunctionDefinitions(std::ostream &OS) {
356 // Now emit code for all the patterns that we collected.
357 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
358 OE = SimplePatterns.end(); OI != OE; ++OI) {
359 const OperandsSignature &Operands = OI->first;
360 const OpcodeTypeRetPredMap &OTM = OI->second;
362 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
364 const std::string &Opcode = I->first;
365 const TypeRetPredMap &TM = I->second;
367 OS << "// FastEmit functions for " << Opcode << ".\n";
370 // Emit one function for each opcode,type pair.
371 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
373 MVT::SimpleValueType VT = TI->first;
374 const RetPredMap &RM = TI->second;
375 if (RM.size() != 1) {
376 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
378 MVT::SimpleValueType RetVT = RI->first;
379 const PredMap &PM = RI->second;
380 bool HasPred = false;
382 OS << "unsigned FastEmit_"
383 << getLegalCName(Opcode)
384 << "_" << getLegalCName(getName(VT))
385 << "_" << getLegalCName(getName(RetVT)) << "_";
386 Operands.PrintManglingSuffix(OS);
388 Operands.PrintParameters(OS);
391 // Emit code for each possible instruction. There may be
392 // multiple if there are subtarget concerns.
393 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
395 std::string PredicateCheck = PI->first;
396 const InstructionMemo &Memo = PI->second;
398 if (PredicateCheck.empty()) {
400 "Multiple instructions match, at least one has "
401 "a predicate and at least one doesn't!");
403 OS << " if (" + PredicateCheck + ") {\n";
408 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
409 if ((*Memo.PhysRegs)[i] != "")
410 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
411 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
412 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
413 << (*Memo.PhysRegs)[i] << "), "
414 << "MRI.getRegClass(Op" << i << "));\n";
417 OS << " return FastEmitInst_";
418 if (Memo.SubRegNo == (unsigned char)~0) {
419 Operands.PrintManglingSuffix(OS);
420 OS << "(" << InstNS << Memo.Name << ", ";
421 OS << InstNS << Memo.RC->getName() << "RegisterClass";
422 if (!Operands.empty())
424 Operands.PrintArguments(OS, *Memo.PhysRegs);
427 OS << "extractsubreg(Op0, ";
428 OS << (unsigned)Memo.SubRegNo;
436 // Return 0 if none of the predicates were satisfied.
438 OS << " return 0;\n";
443 // Emit one function for the type that demultiplexes on return type.
444 OS << "unsigned FastEmit_"
445 << getLegalCName(Opcode) << "_"
446 << getLegalCName(getName(VT)) << "_";
447 Operands.PrintManglingSuffix(OS);
448 OS << "(MVT::SimpleValueType RetVT";
449 if (!Operands.empty())
451 Operands.PrintParameters(OS);
452 OS << ") {\nswitch (RetVT) {\n";
453 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
455 MVT::SimpleValueType RetVT = RI->first;
456 OS << " case " << getName(RetVT) << ": return FastEmit_"
457 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
458 << "_" << getLegalCName(getName(RetVT)) << "_";
459 Operands.PrintManglingSuffix(OS);
461 Operands.PrintArguments(OS);
464 OS << " default: return 0;\n}\n}\n\n";
467 // Non-variadic return type.
468 OS << "unsigned FastEmit_"
469 << getLegalCName(Opcode) << "_"
470 << getLegalCName(getName(VT)) << "_";
471 Operands.PrintManglingSuffix(OS);
472 OS << "(MVT::SimpleValueType RetVT";
473 if (!Operands.empty())
475 Operands.PrintParameters(OS);
478 OS << " if (RetVT != " << getName(RM.begin()->first)
479 << ")\n return 0;\n";
481 const PredMap &PM = RM.begin()->second;
482 bool HasPred = false;
484 // Emit code for each possible instruction. There may be
485 // multiple if there are subtarget concerns.
486 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE; ++PI) {
487 std::string PredicateCheck = PI->first;
488 const InstructionMemo &Memo = PI->second;
490 if (PredicateCheck.empty()) {
492 "Multiple instructions match, at least one has "
493 "a predicate and at least one doesn't!");
495 OS << " if (" + PredicateCheck + ") {\n";
500 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
501 if ((*Memo.PhysRegs)[i] != "")
502 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
503 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
504 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
505 << (*Memo.PhysRegs)[i] << "), "
506 << "MRI.getRegClass(Op" << i << "));\n";
509 OS << " return FastEmitInst_";
511 if (Memo.SubRegNo == (unsigned char)~0) {
512 Operands.PrintManglingSuffix(OS);
513 OS << "(" << InstNS << Memo.Name << ", ";
514 OS << InstNS << Memo.RC->getName() << "RegisterClass";
515 if (!Operands.empty())
517 Operands.PrintArguments(OS, *Memo.PhysRegs);
520 OS << "extractsubreg(Op0, ";
521 OS << (unsigned)Memo.SubRegNo;
529 // Return 0 if none of the predicates were satisfied.
531 OS << " return 0;\n";
537 // Emit one function for the opcode that demultiplexes based on the type.
538 OS << "unsigned FastEmit_"
539 << getLegalCName(Opcode) << "_";
540 Operands.PrintManglingSuffix(OS);
541 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
542 if (!Operands.empty())
544 Operands.PrintParameters(OS);
546 OS << " switch (VT) {\n";
547 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
549 MVT::SimpleValueType VT = TI->first;
550 std::string TypeName = getName(VT);
551 OS << " case " << TypeName << ": return FastEmit_"
552 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
553 Operands.PrintManglingSuffix(OS);
555 if (!Operands.empty())
557 Operands.PrintArguments(OS);
560 OS << " default: return 0;\n";
566 OS << "// Top-level FastEmit function.\n";
569 // Emit one function for the operand signature that demultiplexes based
570 // on opcode and type.
571 OS << "unsigned FastEmit_";
572 Operands.PrintManglingSuffix(OS);
573 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
574 if (!Operands.empty())
576 Operands.PrintParameters(OS);
578 OS << " switch (Opcode) {\n";
579 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
581 const std::string &Opcode = I->first;
583 OS << " case " << Opcode << ": return FastEmit_"
584 << getLegalCName(Opcode) << "_";
585 Operands.PrintManglingSuffix(OS);
587 if (!Operands.empty())
589 Operands.PrintArguments(OS);
592 OS << " default: return 0;\n";
599 void FastISelEmitter::run(std::ostream &OS) {
600 const CodeGenTarget &Target = CGP.getTargetInfo();
602 // Determine the target's namespace name.
603 std::string InstNS = Target.getInstNamespace() + "::";
604 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
606 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
607 Target.getName() + " target", OS);
609 FastISelMap F(InstNS);
610 F.CollectPatterns(CGP);
611 F.PrintFunctionDefinitions(OS);
614 FastISelEmitter::FastISelEmitter(RecordKeeper &R)