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/ADT/SmallString.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;
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) {
59 if (!InstPatNode->isLeaf()) {
60 if (InstPatNode->getOperator()->getName() == "imm") {
61 Operands.push_back("i");
64 if (InstPatNode->getOperator()->getName() == "fpimm") {
65 Operands.push_back("f");
70 const CodeGenRegisterClass *DstRC = 0;
72 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
73 TreePatternNode *Op = InstPatNode->getChild(i);
75 // For now, filter out any operand with a predicate.
76 // For now, filter out any operand with multiple values.
77 if (!Op->getPredicateFns().empty() ||
78 Op->getNumTypes() != 1)
81 assert(Op->hasTypeSet(0) && "Type infererence not done?");
82 // For now, all the operands must have the same type.
83 if (Op->getType(0) != VT)
87 if (Op->getOperator()->getName() == "imm") {
88 Operands.push_back("i");
91 if (Op->getOperator()->getName() == "fpimm") {
92 Operands.push_back("f");
95 // For now, ignore other non-leaf nodes.
98 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
101 Record *OpLeafRec = OpDI->getDef();
102 // For now, the only other thing we accept is register operands.
104 const CodeGenRegisterClass *RC = 0;
105 if (OpLeafRec->isSubClassOf("RegisterClass"))
106 RC = &Target.getRegisterClass(OpLeafRec);
107 else if (OpLeafRec->isSubClassOf("Register"))
108 RC = Target.getRegisterClassForRegister(OpLeafRec);
112 // For now, this needs to be a register class of some sort.
116 // For now, all the operands must have the same register class or be
117 // a strict subclass of the destination.
119 if (DstRC != RC && !DstRC->hasSubClass(RC))
123 Operands.push_back("r");
128 void PrintParameters(raw_ostream &OS) const {
129 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
130 if (Operands[i] == "r") {
131 OS << "unsigned Op" << i << ", bool Op" << i << "IsKill";
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(raw_ostream &OS,
146 const std::vector<std::string>& PR) const {
147 assert(PR.size() == Operands.size());
148 bool PrintedArg = false;
149 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
151 // Implicit physical register operand.
156 if (Operands[i] == "r") {
157 OS << "Op" << i << ", Op" << i << "IsKill";
159 } else if (Operands[i] == "i") {
162 } else if (Operands[i] == "f") {
166 assert("Unknown operand kind!");
172 void PrintArguments(raw_ostream &OS) const {
173 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
174 if (Operands[i] == "r") {
175 OS << "Op" << i << ", Op" << i << "IsKill";
176 } else if (Operands[i] == "i") {
178 } else if (Operands[i] == "f") {
181 assert("Unknown operand kind!");
190 void PrintManglingSuffix(raw_ostream &OS,
191 const std::vector<std::string>& PR) const {
192 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
194 // Implicit physical register operand. e.g. Instruction::Mul expect to
195 // select to a binary op. On x86, mul may take a single operand with
196 // the other operand being implicit. We must emit something that looks
197 // like a binary instruction except for the very inner FastEmitInst_*
204 void PrintManglingSuffix(raw_ostream &OS) const {
205 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
212 typedef std::map<std::string, InstructionMemo> PredMap;
213 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
214 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
215 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
216 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap>
217 OperandsOpcodeTypeRetPredMap;
219 OperandsOpcodeTypeRetPredMap SimplePatterns;
224 explicit FastISelMap(std::string InstNS);
226 void CollectPatterns(CodeGenDAGPatterns &CGP);
227 void PrintFunctionDefinitions(raw_ostream &OS);
232 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
233 return CGP.getSDNodeInfo(Op).getEnumName();
236 static std::string getLegalCName(std::string OpName) {
237 std::string::size_type pos = OpName.find("::");
238 if (pos != std::string::npos)
239 OpName.replace(pos, 2, "_");
243 FastISelMap::FastISelMap(std::string instns)
247 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
248 const CodeGenTarget &Target = CGP.getTargetInfo();
250 // Determine the target's namespace name.
251 InstNS = Target.getInstNamespace() + "::";
252 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
254 // Scan through all the patterns and record the simple ones.
255 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
256 E = CGP.ptm_end(); I != E; ++I) {
257 const PatternToMatch &Pattern = *I;
259 // For now, just look at Instructions, so that we don't have to worry
260 // about emitting multiple instructions for a pattern.
261 TreePatternNode *Dst = Pattern.getDstPattern();
262 if (Dst->isLeaf()) continue;
263 Record *Op = Dst->getOperator();
264 if (!Op->isSubClassOf("Instruction"))
266 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
267 if (II.Operands.size() == 0)
270 // For now, ignore multi-instruction patterns.
271 bool MultiInsts = false;
272 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
273 TreePatternNode *ChildOp = Dst->getChild(i);
274 if (ChildOp->isLeaf())
276 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
284 // For now, ignore instructions where the first operand is not an
286 const CodeGenRegisterClass *DstRC = 0;
287 std::string SubRegNo;
288 if (Op->getName() != "EXTRACT_SUBREG") {
289 Record *Op0Rec = II.Operands[0].Rec;
290 if (!Op0Rec->isSubClassOf("RegisterClass"))
292 DstRC = &Target.getRegisterClass(Op0Rec);
296 // If this isn't a leaf, then continue since the register classes are
297 // a bit too complicated for now.
298 if (!Dst->getChild(1)->isLeaf()) continue;
300 DefInit *SR = dynamic_cast<DefInit*>(Dst->getChild(1)->getLeafValue());
302 SubRegNo = getQualifiedName(SR->getDef());
304 SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
307 // Inspect the pattern.
308 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
309 if (!InstPatNode) continue;
310 if (InstPatNode->isLeaf()) continue;
312 // Ignore multiple result nodes for now.
313 if (InstPatNode->getNumTypes() > 1) continue;
315 Record *InstPatOp = InstPatNode->getOperator();
316 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
317 MVT::SimpleValueType RetVT = MVT::isVoid;
318 if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0);
319 MVT::SimpleValueType VT = RetVT;
320 if (InstPatNode->getNumChildren()) {
321 assert(InstPatNode->getChild(0)->getNumTypes() == 1);
322 VT = InstPatNode->getChild(0)->getType(0);
325 // For now, filter out instructions which just set a register to
326 // an Operand or an immediate, like MOV32ri.
327 if (InstPatOp->isSubClassOf("Operand"))
330 // For now, filter out any instructions with predicates.
331 if (!InstPatNode->getPredicateFns().empty())
334 // Check all the operands.
335 OperandsSignature Operands;
336 if (!Operands.initialize(InstPatNode, Target, VT))
339 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
340 if (!InstPatNode->isLeaf() &&
341 (InstPatNode->getOperator()->getName() == "imm" ||
342 InstPatNode->getOperator()->getName() == "fpimmm"))
343 PhysRegInputs->push_back("");
344 else if (!InstPatNode->isLeaf()) {
345 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
346 TreePatternNode *Op = InstPatNode->getChild(i);
348 PhysRegInputs->push_back("");
352 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
353 Record *OpLeafRec = OpDI->getDef();
355 if (OpLeafRec->isSubClassOf("Register")) {
356 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
357 "Namespace")->getValue())->getValue();
360 std::vector<CodeGenRegister> Regs = Target.getRegisters();
361 for (unsigned i = 0; i < Regs.size(); ++i) {
362 if (Regs[i].TheDef == OpLeafRec) {
363 PhysReg += Regs[i].getName();
369 PhysRegInputs->push_back(PhysReg);
372 PhysRegInputs->push_back("");
374 // Get the predicate that guards this pattern.
375 std::string PredicateCheck = Pattern.getPredicateCheck();
377 // Ok, we found a pattern that we can handle. Remember it.
378 InstructionMemo Memo = {
379 Pattern.getDstPattern()->getOperator()->getName(),
384 // FIXME: Source location information for the diagnostic.
385 if (SimplePatterns[Operands][OpcodeName][VT][RetVT]
386 .count(PredicateCheck)) {
387 SmallString<128> PatText;
388 raw_svector_ostream OS(PatText);
389 Pattern.SrcPattern->print(OS);
390 throw "Duplicate record: " + OS.str().str();
392 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
396 void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
397 // Now emit code for all the patterns that we collected.
398 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
399 OE = SimplePatterns.end(); OI != OE; ++OI) {
400 const OperandsSignature &Operands = OI->first;
401 const OpcodeTypeRetPredMap &OTM = OI->second;
403 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
405 const std::string &Opcode = I->first;
406 const TypeRetPredMap &TM = I->second;
408 OS << "// FastEmit functions for " << Opcode << ".\n";
411 // Emit one function for each opcode,type pair.
412 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
414 MVT::SimpleValueType VT = TI->first;
415 const RetPredMap &RM = TI->second;
416 if (RM.size() != 1) {
417 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
419 MVT::SimpleValueType RetVT = RI->first;
420 const PredMap &PM = RI->second;
421 bool HasPred = false;
423 OS << "unsigned FastEmit_"
424 << getLegalCName(Opcode)
425 << "_" << getLegalCName(getName(VT))
426 << "_" << getLegalCName(getName(RetVT)) << "_";
427 Operands.PrintManglingSuffix(OS);
429 Operands.PrintParameters(OS);
432 // Emit code for each possible instruction. There may be
433 // multiple if there are subtarget concerns.
434 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
436 std::string PredicateCheck = PI->first;
437 const InstructionMemo &Memo = PI->second;
439 if (PredicateCheck.empty()) {
441 "Multiple instructions match, at least one has "
442 "a predicate and at least one doesn't!");
444 OS << " if (" + PredicateCheck + ") {\n";
449 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
450 if ((*Memo.PhysRegs)[i] != "")
451 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
452 << "TII.get(TargetOpcode::COPY), "
453 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
456 OS << " return FastEmitInst_";
457 if (Memo.SubRegNo.empty()) {
458 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
459 OS << "(" << InstNS << Memo.Name << ", ";
460 OS << InstNS << Memo.RC->getName() << "RegisterClass";
461 if (!Operands.empty())
463 Operands.PrintArguments(OS, *Memo.PhysRegs);
466 OS << "extractsubreg(" << getName(RetVT);
467 OS << ", Op0, Op0IsKill, ";
476 // Return 0 if none of the predicates were satisfied.
478 OS << " return 0;\n";
483 // Emit one function for the type that demultiplexes on return type.
484 OS << "unsigned FastEmit_"
485 << getLegalCName(Opcode) << "_"
486 << getLegalCName(getName(VT)) << "_";
487 Operands.PrintManglingSuffix(OS);
489 if (!Operands.empty())
491 Operands.PrintParameters(OS);
492 OS << ") {\nswitch (RetVT.SimpleTy) {\n";
493 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
495 MVT::SimpleValueType RetVT = RI->first;
496 OS << " case " << getName(RetVT) << ": return FastEmit_"
497 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
498 << "_" << getLegalCName(getName(RetVT)) << "_";
499 Operands.PrintManglingSuffix(OS);
501 Operands.PrintArguments(OS);
504 OS << " default: return 0;\n}\n}\n\n";
507 // Non-variadic return type.
508 OS << "unsigned FastEmit_"
509 << getLegalCName(Opcode) << "_"
510 << getLegalCName(getName(VT)) << "_";
511 Operands.PrintManglingSuffix(OS);
513 if (!Operands.empty())
515 Operands.PrintParameters(OS);
518 OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
519 << ")\n return 0;\n";
521 const PredMap &PM = RM.begin()->second;
522 bool HasPred = false;
524 // Emit code for each possible instruction. There may be
525 // multiple if there are subtarget concerns.
526 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
528 std::string PredicateCheck = PI->first;
529 const InstructionMemo &Memo = PI->second;
531 if (PredicateCheck.empty()) {
533 "Multiple instructions match, at least one has "
534 "a predicate and at least one doesn't!");
536 OS << " if (" + PredicateCheck + ") {\n";
541 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
542 if ((*Memo.PhysRegs)[i] != "")
543 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
544 << "TII.get(TargetOpcode::COPY), "
545 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
548 OS << " return FastEmitInst_";
550 if (Memo.SubRegNo.empty()) {
551 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
552 OS << "(" << InstNS << Memo.Name << ", ";
553 OS << InstNS << Memo.RC->getName() << "RegisterClass";
554 if (!Operands.empty())
556 Operands.PrintArguments(OS, *Memo.PhysRegs);
559 OS << "extractsubreg(RetVT, Op0, Op0IsKill, ";
568 // Return 0 if none of the predicates were satisfied.
570 OS << " return 0;\n";
576 // Emit one function for the opcode that demultiplexes based on the type.
577 OS << "unsigned FastEmit_"
578 << getLegalCName(Opcode) << "_";
579 Operands.PrintManglingSuffix(OS);
580 OS << "(MVT VT, MVT RetVT";
581 if (!Operands.empty())
583 Operands.PrintParameters(OS);
585 OS << " switch (VT.SimpleTy) {\n";
586 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
588 MVT::SimpleValueType VT = TI->first;
589 std::string TypeName = getName(VT);
590 OS << " case " << TypeName << ": return FastEmit_"
591 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
592 Operands.PrintManglingSuffix(OS);
594 if (!Operands.empty())
596 Operands.PrintArguments(OS);
599 OS << " default: return 0;\n";
605 OS << "// Top-level FastEmit function.\n";
608 // Emit one function for the operand signature that demultiplexes based
609 // on opcode and type.
610 OS << "unsigned FastEmit_";
611 Operands.PrintManglingSuffix(OS);
612 OS << "(MVT VT, MVT RetVT, unsigned Opcode";
613 if (!Operands.empty())
615 Operands.PrintParameters(OS);
617 OS << " switch (Opcode) {\n";
618 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
620 const std::string &Opcode = I->first;
622 OS << " case " << Opcode << ": return FastEmit_"
623 << getLegalCName(Opcode) << "_";
624 Operands.PrintManglingSuffix(OS);
626 if (!Operands.empty())
628 Operands.PrintArguments(OS);
631 OS << " default: return 0;\n";
638 void FastISelEmitter::run(raw_ostream &OS) {
639 const CodeGenTarget &Target = CGP.getTargetInfo();
641 // Determine the target's namespace name.
642 std::string InstNS = Target.getInstNamespace() + "::";
643 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
645 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
646 Target.getName() + " target", OS);
648 FastISelMap F(InstNS);
649 F.CollectPatterns(CGP);
650 F.PrintFunctionDefinitions(OS);
653 FastISelEmitter::FastISelEmitter(RecordKeeper &R)