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 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.
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.
18 //===----------------------------------------------------------------------===//
20 #include "FastISelEmitter.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/Streams.h"
24 #include "llvm/ADT/VectorExtras.h"
29 /// InstructionMemo - This class holds additional information about an
30 /// instruction needed to emit code for it.
32 struct InstructionMemo {
34 const CodeGenRegisterClass *RC;
35 unsigned char SubRegNo;
36 std::vector<std::string>* PhysRegs;
39 /// OperandsSignature - This class holds a description of a list of operand
40 /// types. It has utility methods for emitting text based on the operands.
42 struct OperandsSignature {
43 std::vector<std::string> Operands;
45 bool operator<(const OperandsSignature &O) const {
46 return Operands < O.Operands;
49 bool empty() const { return Operands.empty(); }
51 /// initialize - Examine the given pattern and initialize the contents
52 /// of the Operands array accordingly. Return true if all the operands
53 /// are supported, false otherwise.
55 bool initialize(TreePatternNode *InstPatNode,
56 const CodeGenTarget &Target,
57 MVT::SimpleValueType VT) {
58 if (!InstPatNode->isLeaf() &&
59 InstPatNode->getOperator()->getName() == "imm") {
60 Operands.push_back("i");
63 if (!InstPatNode->isLeaf() &&
64 InstPatNode->getOperator()->getName() == "fpimm") {
65 Operands.push_back("f");
69 const CodeGenRegisterClass *DstRC = 0;
71 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
72 TreePatternNode *Op = InstPatNode->getChild(i);
73 // For now, filter out any operand with a predicate.
74 if (!Op->getPredicateFns().empty())
76 // For now, filter out any operand with multiple values.
77 if (Op->getExtTypes().size() != 1)
79 // For now, all the operands must have the same type.
80 if (Op->getTypeNum(0) != VT)
83 if (Op->getOperator()->getName() == "imm") {
84 Operands.push_back("i");
87 if (Op->getOperator()->getName() == "fpimm") {
88 Operands.push_back("f");
91 // For now, ignore other non-leaf nodes.
94 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
97 Record *OpLeafRec = OpDI->getDef();
98 // For now, the only other thing we accept is register operands.
100 const CodeGenRegisterClass *RC = 0;
101 if (OpLeafRec->isSubClassOf("RegisterClass"))
102 RC = &Target.getRegisterClass(OpLeafRec);
103 else if (OpLeafRec->isSubClassOf("Register"))
104 RC = Target.getRegisterClassForRegister(OpLeafRec);
107 // For now, require the register operands' register classes to all
111 // For now, all the operands must have the same register class.
117 Operands.push_back("r");
122 void PrintParameters(std::ostream &OS) const {
123 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
124 if (Operands[i] == "r") {
125 OS << "unsigned Op" << i;
126 } else if (Operands[i] == "i") {
127 OS << "uint64_t imm" << i;
128 } else if (Operands[i] == "f") {
129 OS << "ConstantFP *f" << i;
131 assert("Unknown operand kind!");
139 void PrintArguments(std::ostream &OS,
140 const std::vector<std::string>& PR) const {
141 assert(PR.size() == Operands.size());
142 bool PrintedArg = false;
143 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
145 // Implicit physical register operand.
150 if (Operands[i] == "r") {
153 } else if (Operands[i] == "i") {
156 } else if (Operands[i] == "f") {
160 assert("Unknown operand kind!");
166 void PrintArguments(std::ostream &OS) const {
167 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
168 if (Operands[i] == "r") {
170 } else if (Operands[i] == "i") {
172 } else if (Operands[i] == "f") {
175 assert("Unknown operand kind!");
184 void PrintManglingSuffix(std::ostream &OS,
185 const std::vector<std::string>& PR) const {
186 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
188 // Implicit physical register operand. e.g. Instruction::Mul expect to
189 // select to a binary op. On x86, mul may take a single operand with
190 // the other operand being implicit. We must emit something that looks
191 // like a binary instruction except for the very inner FastEmitInst_*
198 void PrintManglingSuffix(std::ostream &OS) const {
199 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
206 typedef std::map<std::string, InstructionMemo> PredMap;
207 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
208 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
209 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
210 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
212 OperandsOpcodeTypeRetPredMap SimplePatterns;
217 explicit FastISelMap(std::string InstNS);
219 void CollectPatterns(CodeGenDAGPatterns &CGP);
220 void PrintClass(std::ostream &OS);
221 void PrintFunctionDefinitions(std::ostream &OS);
226 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
227 return CGP.getSDNodeInfo(Op).getEnumName();
230 static std::string getLegalCName(std::string OpName) {
231 std::string::size_type pos = OpName.find("::");
232 if (pos != std::string::npos)
233 OpName.replace(pos, 2, "_");
237 FastISelMap::FastISelMap(std::string instns)
241 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
242 const CodeGenTarget &Target = CGP.getTargetInfo();
244 // Determine the target's namespace name.
245 InstNS = Target.getInstNamespace() + "::";
246 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
248 // Scan through all the patterns and record the simple ones.
249 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
250 E = CGP.ptm_end(); I != E; ++I) {
251 const PatternToMatch &Pattern = *I;
253 // For now, just look at Instructions, so that we don't have to worry
254 // about emitting multiple instructions for a pattern.
255 TreePatternNode *Dst = Pattern.getDstPattern();
256 if (Dst->isLeaf()) continue;
257 Record *Op = Dst->getOperator();
258 if (!Op->isSubClassOf("Instruction"))
260 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
261 if (II.OperandList.empty())
264 // For now, ignore multi-instruction patterns.
265 bool MultiInsts = false;
266 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
267 TreePatternNode *ChildOp = Dst->getChild(i);
268 if (ChildOp->isLeaf())
270 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
278 // For now, ignore instructions where the first operand is not an
280 const CodeGenRegisterClass *DstRC = 0;
281 unsigned SubRegNo = ~0;
282 if (Op->getName() != "EXTRACT_SUBREG") {
283 Record *Op0Rec = II.OperandList[0].Rec;
284 if (!Op0Rec->isSubClassOf("RegisterClass"))
286 DstRC = &Target.getRegisterClass(Op0Rec);
290 SubRegNo = static_cast<IntInit*>(
291 Dst->getChild(1)->getLeafValue())->getValue();
294 // Inspect the pattern.
295 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
296 if (!InstPatNode) continue;
297 if (InstPatNode->isLeaf()) continue;
299 Record *InstPatOp = InstPatNode->getOperator();
300 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
301 MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
302 MVT::SimpleValueType VT = RetVT;
303 if (InstPatNode->getNumChildren())
304 VT = InstPatNode->getChild(0)->getTypeNum(0);
306 // For now, filter out instructions which just set a register to
307 // an Operand or an immediate, like MOV32ri.
308 if (InstPatOp->isSubClassOf("Operand"))
311 // For now, filter out any instructions with predicates.
312 if (!InstPatNode->getPredicateFns().empty())
315 // Check all the operands.
316 OperandsSignature Operands;
317 if (!Operands.initialize(InstPatNode, Target, VT))
320 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
321 if (!InstPatNode->isLeaf() &&
322 (InstPatNode->getOperator()->getName() == "imm" ||
323 InstPatNode->getOperator()->getName() == "fpimmm"))
324 PhysRegInputs->push_back("");
325 else if (!InstPatNode->isLeaf()) {
326 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
327 TreePatternNode *Op = InstPatNode->getChild(i);
329 PhysRegInputs->push_back("");
333 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
334 Record *OpLeafRec = OpDI->getDef();
336 if (OpLeafRec->isSubClassOf("Register")) {
337 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
338 "Namespace")->getValue())->getValue();
341 std::vector<CodeGenRegister> Regs = Target.getRegisters();
342 for (unsigned i = 0; i < Regs.size(); ++i) {
343 if (Regs[i].TheDef == OpLeafRec) {
344 PhysReg += Regs[i].getName();
350 PhysRegInputs->push_back(PhysReg);
353 PhysRegInputs->push_back("");
355 // Get the predicate that guards this pattern.
356 std::string PredicateCheck = Pattern.getPredicateCheck();
358 // Ok, we found a pattern that we can handle. Remember it.
359 InstructionMemo Memo = {
360 Pattern.getDstPattern()->getOperator()->getName(),
365 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
366 "Duplicate pattern!");
367 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
371 void FastISelMap::PrintFunctionDefinitions(std::ostream &OS) {
372 // Now emit code for all the patterns that we collected.
373 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
374 OE = SimplePatterns.end(); OI != OE; ++OI) {
375 const OperandsSignature &Operands = OI->first;
376 const OpcodeTypeRetPredMap &OTM = OI->second;
378 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
380 const std::string &Opcode = I->first;
381 const TypeRetPredMap &TM = I->second;
383 OS << "// FastEmit functions for " << Opcode << ".\n";
386 // Emit one function for each opcode,type pair.
387 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
389 MVT::SimpleValueType VT = TI->first;
390 const RetPredMap &RM = TI->second;
391 if (RM.size() != 1) {
392 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
394 MVT::SimpleValueType RetVT = RI->first;
395 const PredMap &PM = RI->second;
396 bool HasPred = false;
398 OS << "unsigned FastEmit_"
399 << getLegalCName(Opcode)
400 << "_" << getLegalCName(getName(VT))
401 << "_" << getLegalCName(getName(RetVT)) << "_";
402 Operands.PrintManglingSuffix(OS);
404 Operands.PrintParameters(OS);
407 // Emit code for each possible instruction. There may be
408 // multiple if there are subtarget concerns.
409 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
411 std::string PredicateCheck = PI->first;
412 const InstructionMemo &Memo = PI->second;
414 if (PredicateCheck.empty()) {
416 "Multiple instructions match, at least one has "
417 "a predicate and at least one doesn't!");
419 OS << " if (" + PredicateCheck + ") {\n";
424 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
425 if ((*Memo.PhysRegs)[i] != "")
426 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
427 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
428 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
429 << (*Memo.PhysRegs)[i] << "), "
430 << "MRI.getRegClass(Op" << i << "));\n";
433 OS << " return FastEmitInst_";
434 if (Memo.SubRegNo == (unsigned char)~0) {
435 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
436 OS << "(" << InstNS << Memo.Name << ", ";
437 OS << InstNS << Memo.RC->getName() << "RegisterClass";
438 if (!Operands.empty())
440 Operands.PrintArguments(OS, *Memo.PhysRegs);
443 OS << "extractsubreg(" << getName(RetVT);
445 OS << (unsigned)Memo.SubRegNo;
453 // Return 0 if none of the predicates were satisfied.
455 OS << " return 0;\n";
460 // Emit one function for the type that demultiplexes on return type.
461 OS << "unsigned FastEmit_"
462 << getLegalCName(Opcode) << "_"
463 << getLegalCName(getName(VT)) << "_";
464 Operands.PrintManglingSuffix(OS);
465 OS << "(MVT::SimpleValueType RetVT";
466 if (!Operands.empty())
468 Operands.PrintParameters(OS);
469 OS << ") {\nswitch (RetVT) {\n";
470 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
472 MVT::SimpleValueType RetVT = RI->first;
473 OS << " case " << getName(RetVT) << ": return FastEmit_"
474 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
475 << "_" << getLegalCName(getName(RetVT)) << "_";
476 Operands.PrintManglingSuffix(OS);
478 Operands.PrintArguments(OS);
481 OS << " default: return 0;\n}\n}\n\n";
484 // Non-variadic return type.
485 OS << "unsigned FastEmit_"
486 << getLegalCName(Opcode) << "_"
487 << getLegalCName(getName(VT)) << "_";
488 Operands.PrintManglingSuffix(OS);
489 OS << "(MVT::SimpleValueType RetVT";
490 if (!Operands.empty())
492 Operands.PrintParameters(OS);
495 OS << " if (RetVT != " << getName(RM.begin()->first)
496 << ")\n return 0;\n";
498 const PredMap &PM = RM.begin()->second;
499 bool HasPred = false;
501 // Emit code for each possible instruction. There may be
502 // multiple if there are subtarget concerns.
503 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
505 std::string PredicateCheck = PI->first;
506 const InstructionMemo &Memo = PI->second;
508 if (PredicateCheck.empty()) {
510 "Multiple instructions match, at least one has "
511 "a predicate and at least one doesn't!");
513 OS << " if (" + PredicateCheck + ") {\n";
518 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
519 if ((*Memo.PhysRegs)[i] != "")
520 OS << " TII.copyRegToReg(*MBB, MBB->end(), "
521 << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
522 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
523 << (*Memo.PhysRegs)[i] << "), "
524 << "MRI.getRegClass(Op" << i << "));\n";
527 OS << " return FastEmitInst_";
529 if (Memo.SubRegNo == (unsigned char)~0) {
530 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
531 OS << "(" << InstNS << Memo.Name << ", ";
532 OS << InstNS << Memo.RC->getName() << "RegisterClass";
533 if (!Operands.empty())
535 Operands.PrintArguments(OS, *Memo.PhysRegs);
538 OS << "extractsubreg(RetVT, Op0, ";
539 OS << (unsigned)Memo.SubRegNo;
547 // Return 0 if none of the predicates were satisfied.
549 OS << " return 0;\n";
555 // Emit one function for the opcode that demultiplexes based on the type.
556 OS << "unsigned FastEmit_"
557 << getLegalCName(Opcode) << "_";
558 Operands.PrintManglingSuffix(OS);
559 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
560 if (!Operands.empty())
562 Operands.PrintParameters(OS);
564 OS << " switch (VT) {\n";
565 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
567 MVT::SimpleValueType VT = TI->first;
568 std::string TypeName = getName(VT);
569 OS << " case " << TypeName << ": return FastEmit_"
570 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
571 Operands.PrintManglingSuffix(OS);
573 if (!Operands.empty())
575 Operands.PrintArguments(OS);
578 OS << " default: return 0;\n";
584 OS << "// Top-level FastEmit function.\n";
587 // Emit one function for the operand signature that demultiplexes based
588 // on opcode and type.
589 OS << "unsigned FastEmit_";
590 Operands.PrintManglingSuffix(OS);
591 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
592 if (!Operands.empty())
594 Operands.PrintParameters(OS);
596 OS << " switch (Opcode) {\n";
597 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
599 const std::string &Opcode = I->first;
601 OS << " case " << Opcode << ": return FastEmit_"
602 << getLegalCName(Opcode) << "_";
603 Operands.PrintManglingSuffix(OS);
605 if (!Operands.empty())
607 Operands.PrintArguments(OS);
610 OS << " default: return 0;\n";
617 void FastISelEmitter::run(std::ostream &OS) {
618 const CodeGenTarget &Target = CGP.getTargetInfo();
620 // Determine the target's namespace name.
621 std::string InstNS = Target.getInstNamespace() + "::";
622 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
624 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
625 Target.getName() + " target", OS);
627 FastISelMap F(InstNS);
628 F.CollectPatterns(CGP);
629 F.PrintFunctionDefinitions(OS);
632 FastISelEmitter::FastISelEmitter(RecordKeeper &R)