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, const CodeGenTarget &Target,
56 MVT::SimpleValueType VT) {
58 if (!InstPatNode->isLeaf()) {
59 if (InstPatNode->getOperator()->getName() == "imm") {
60 Operands.push_back("i");
63 if (InstPatNode->getOperator()->getName() == "fpimm") {
64 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);
74 // For now, filter out any operand with a predicate.
75 // For now, filter out any operand with multiple values.
76 if (!Op->getPredicateFns().empty() || Op->getNumTypes() != 1)
80 if (Op->getOperator()->getName() == "imm") {
81 Operands.push_back("i");
84 if (Op->getOperator()->getName() == "fpimm") {
85 Operands.push_back("f");
88 // For now, ignore other non-leaf nodes.
92 assert(Op->hasTypeSet(0) && "Type infererence not done?");
94 // For now, all the operands must have the same type (if they aren't
95 // immediates). Note that this causes us to reject variable sized shifts
97 if (Op->getType(0) != VT)
100 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
103 Record *OpLeafRec = OpDI->getDef();
104 // For now, the only other thing we accept is register operands.
106 const CodeGenRegisterClass *RC = 0;
107 if (OpLeafRec->isSubClassOf("RegisterClass"))
108 RC = &Target.getRegisterClass(OpLeafRec);
109 else if (OpLeafRec->isSubClassOf("Register"))
110 RC = Target.getRegisterClassForRegister(OpLeafRec);
114 // For now, this needs to be a register class of some sort.
118 // For now, all the operands must have the same register class or be
119 // a strict subclass of the destination.
121 if (DstRC != RC && !DstRC->hasSubClass(RC))
125 Operands.push_back("r");
130 void PrintParameters(raw_ostream &OS) const {
131 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
132 if (Operands[i] == "r") {
133 OS << "unsigned Op" << i << ", bool Op" << i << "IsKill";
134 } else if (Operands[i] == "i") {
135 OS << "uint64_t imm" << i;
136 } else if (Operands[i] == "f") {
137 OS << "ConstantFP *f" << i;
139 assert("Unknown operand kind!");
147 void PrintArguments(raw_ostream &OS,
148 const std::vector<std::string>& PR) const {
149 assert(PR.size() == Operands.size());
150 bool PrintedArg = false;
151 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
153 // Implicit physical register operand.
158 if (Operands[i] == "r") {
159 OS << "Op" << i << ", Op" << i << "IsKill";
161 } else if (Operands[i] == "i") {
164 } else if (Operands[i] == "f") {
168 assert("Unknown operand kind!");
174 void PrintArguments(raw_ostream &OS) const {
175 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
176 if (Operands[i] == "r") {
177 OS << "Op" << i << ", Op" << i << "IsKill";
178 } else if (Operands[i] == "i") {
180 } else if (Operands[i] == "f") {
183 assert("Unknown operand kind!");
192 void PrintManglingSuffix(raw_ostream &OS,
193 const std::vector<std::string>& PR) const {
194 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
196 // Implicit physical register operand. e.g. Instruction::Mul expect to
197 // select to a binary op. On x86, mul may take a single operand with
198 // the other operand being implicit. We must emit something that looks
199 // like a binary instruction except for the very inner FastEmitInst_*
206 void PrintManglingSuffix(raw_ostream &OS) const {
207 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
214 typedef std::map<std::string, InstructionMemo> PredMap;
215 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
216 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
217 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
218 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap>
219 OperandsOpcodeTypeRetPredMap;
221 OperandsOpcodeTypeRetPredMap SimplePatterns;
226 explicit FastISelMap(std::string InstNS);
228 void CollectPatterns(CodeGenDAGPatterns &CGP);
229 void PrintFunctionDefinitions(raw_ostream &OS);
234 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
235 return CGP.getSDNodeInfo(Op).getEnumName();
238 static std::string getLegalCName(std::string OpName) {
239 std::string::size_type pos = OpName.find("::");
240 if (pos != std::string::npos)
241 OpName.replace(pos, 2, "_");
245 FastISelMap::FastISelMap(std::string instns)
249 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
250 const CodeGenTarget &Target = CGP.getTargetInfo();
252 // Determine the target's namespace name.
253 InstNS = Target.getInstNamespace() + "::";
254 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
256 // Scan through all the patterns and record the simple ones.
257 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
258 E = CGP.ptm_end(); I != E; ++I) {
259 const PatternToMatch &Pattern = *I;
261 // For now, just look at Instructions, so that we don't have to worry
262 // about emitting multiple instructions for a pattern.
263 TreePatternNode *Dst = Pattern.getDstPattern();
264 if (Dst->isLeaf()) continue;
265 Record *Op = Dst->getOperator();
266 if (!Op->isSubClassOf("Instruction"))
268 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
269 if (II.Operands.size() == 0)
272 // For now, ignore multi-instruction patterns.
273 bool MultiInsts = false;
274 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
275 TreePatternNode *ChildOp = Dst->getChild(i);
276 if (ChildOp->isLeaf())
278 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
286 // For now, ignore instructions where the first operand is not an
288 const CodeGenRegisterClass *DstRC = 0;
289 std::string SubRegNo;
290 if (Op->getName() != "EXTRACT_SUBREG") {
291 Record *Op0Rec = II.Operands[0].Rec;
292 if (!Op0Rec->isSubClassOf("RegisterClass"))
294 DstRC = &Target.getRegisterClass(Op0Rec);
298 // If this isn't a leaf, then continue since the register classes are
299 // a bit too complicated for now.
300 if (!Dst->getChild(1)->isLeaf()) continue;
302 DefInit *SR = dynamic_cast<DefInit*>(Dst->getChild(1)->getLeafValue());
304 SubRegNo = getQualifiedName(SR->getDef());
306 SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
309 // Inspect the pattern.
310 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
311 if (!InstPatNode) continue;
312 if (InstPatNode->isLeaf()) continue;
314 // Ignore multiple result nodes for now.
315 if (InstPatNode->getNumTypes() > 1) continue;
317 Record *InstPatOp = InstPatNode->getOperator();
318 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
319 MVT::SimpleValueType RetVT = MVT::isVoid;
320 if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0);
321 MVT::SimpleValueType VT = RetVT;
322 if (InstPatNode->getNumChildren()) {
323 assert(InstPatNode->getChild(0)->getNumTypes() == 1);
324 VT = InstPatNode->getChild(0)->getType(0);
327 // For now, filter out instructions which just set a register to
328 // an Operand or an immediate, like MOV32ri.
329 if (InstPatOp->isSubClassOf("Operand"))
332 // For now, filter out any instructions with predicates.
333 if (!InstPatNode->getPredicateFns().empty())
336 // Check all the operands.
337 OperandsSignature Operands;
338 if (!Operands.initialize(InstPatNode, Target, VT))
341 std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
342 if (!InstPatNode->isLeaf() &&
343 (InstPatNode->getOperator()->getName() == "imm" ||
344 InstPatNode->getOperator()->getName() == "fpimmm"))
345 PhysRegInputs->push_back("");
346 else if (!InstPatNode->isLeaf()) {
347 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
348 TreePatternNode *Op = InstPatNode->getChild(i);
350 PhysRegInputs->push_back("");
354 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
355 Record *OpLeafRec = OpDI->getDef();
357 if (OpLeafRec->isSubClassOf("Register")) {
358 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
359 "Namespace")->getValue())->getValue();
362 std::vector<CodeGenRegister> Regs = Target.getRegisters();
363 for (unsigned i = 0; i < Regs.size(); ++i) {
364 if (Regs[i].TheDef == OpLeafRec) {
365 PhysReg += Regs[i].getName();
371 PhysRegInputs->push_back(PhysReg);
374 PhysRegInputs->push_back("");
376 // Get the predicate that guards this pattern.
377 std::string PredicateCheck = Pattern.getPredicateCheck();
379 // Ok, we found a pattern that we can handle. Remember it.
380 InstructionMemo Memo = {
381 Pattern.getDstPattern()->getOperator()->getName(),
386 if (SimplePatterns[Operands][OpcodeName][VT][RetVT]
387 .count(PredicateCheck))
388 throw TGError(Pattern.getSrcRecord()->getLoc(), "Duplicate record!");
390 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
394 void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
395 // Now emit code for all the patterns that we collected.
396 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
397 OE = SimplePatterns.end(); OI != OE; ++OI) {
398 const OperandsSignature &Operands = OI->first;
399 const OpcodeTypeRetPredMap &OTM = OI->second;
401 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
403 const std::string &Opcode = I->first;
404 const TypeRetPredMap &TM = I->second;
406 OS << "// FastEmit functions for " << Opcode << ".\n";
409 // Emit one function for each opcode,type pair.
410 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
412 MVT::SimpleValueType VT = TI->first;
413 const RetPredMap &RM = TI->second;
414 if (RM.size() != 1) {
415 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
417 MVT::SimpleValueType RetVT = RI->first;
418 const PredMap &PM = RI->second;
419 bool HasPred = false;
421 OS << "unsigned FastEmit_"
422 << getLegalCName(Opcode)
423 << "_" << getLegalCName(getName(VT))
424 << "_" << getLegalCName(getName(RetVT)) << "_";
425 Operands.PrintManglingSuffix(OS);
427 Operands.PrintParameters(OS);
430 // Emit code for each possible instruction. There may be
431 // multiple if there are subtarget concerns.
432 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
434 std::string PredicateCheck = PI->first;
435 const InstructionMemo &Memo = PI->second;
437 if (PredicateCheck.empty()) {
439 "Multiple instructions match, at least one has "
440 "a predicate and at least one doesn't!");
442 OS << " if (" + PredicateCheck + ") {\n";
447 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
448 if ((*Memo.PhysRegs)[i] != "")
449 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
450 << "TII.get(TargetOpcode::COPY), "
451 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
454 OS << " return FastEmitInst_";
455 if (Memo.SubRegNo.empty()) {
456 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
457 OS << "(" << InstNS << Memo.Name << ", ";
458 OS << InstNS << Memo.RC->getName() << "RegisterClass";
459 if (!Operands.empty())
461 Operands.PrintArguments(OS, *Memo.PhysRegs);
464 OS << "extractsubreg(" << getName(RetVT);
465 OS << ", Op0, Op0IsKill, ";
474 // Return 0 if none of the predicates were satisfied.
476 OS << " return 0;\n";
481 // Emit one function for the type that demultiplexes on return type.
482 OS << "unsigned FastEmit_"
483 << getLegalCName(Opcode) << "_"
484 << getLegalCName(getName(VT)) << "_";
485 Operands.PrintManglingSuffix(OS);
487 if (!Operands.empty())
489 Operands.PrintParameters(OS);
490 OS << ") {\nswitch (RetVT.SimpleTy) {\n";
491 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
493 MVT::SimpleValueType RetVT = RI->first;
494 OS << " case " << getName(RetVT) << ": return FastEmit_"
495 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
496 << "_" << getLegalCName(getName(RetVT)) << "_";
497 Operands.PrintManglingSuffix(OS);
499 Operands.PrintArguments(OS);
502 OS << " default: return 0;\n}\n}\n\n";
505 // Non-variadic return type.
506 OS << "unsigned FastEmit_"
507 << getLegalCName(Opcode) << "_"
508 << getLegalCName(getName(VT)) << "_";
509 Operands.PrintManglingSuffix(OS);
511 if (!Operands.empty())
513 Operands.PrintParameters(OS);
516 OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
517 << ")\n return 0;\n";
519 const PredMap &PM = RM.begin()->second;
520 bool HasPred = false;
522 // Emit code for each possible instruction. There may be
523 // multiple if there are subtarget concerns.
524 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
526 std::string PredicateCheck = PI->first;
527 const InstructionMemo &Memo = PI->second;
529 if (PredicateCheck.empty()) {
531 "Multiple instructions match, at least one has "
532 "a predicate and at least one doesn't!");
534 OS << " if (" + PredicateCheck + ") {\n";
539 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
540 if ((*Memo.PhysRegs)[i] != "")
541 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
542 << "TII.get(TargetOpcode::COPY), "
543 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
546 OS << " return FastEmitInst_";
548 if (Memo.SubRegNo.empty()) {
549 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
550 OS << "(" << InstNS << Memo.Name << ", ";
551 OS << InstNS << Memo.RC->getName() << "RegisterClass";
552 if (!Operands.empty())
554 Operands.PrintArguments(OS, *Memo.PhysRegs);
557 OS << "extractsubreg(RetVT, Op0, Op0IsKill, ";
566 // Return 0 if none of the predicates were satisfied.
568 OS << " return 0;\n";
574 // Emit one function for the opcode that demultiplexes based on the type.
575 OS << "unsigned FastEmit_"
576 << getLegalCName(Opcode) << "_";
577 Operands.PrintManglingSuffix(OS);
578 OS << "(MVT VT, MVT RetVT";
579 if (!Operands.empty())
581 Operands.PrintParameters(OS);
583 OS << " switch (VT.SimpleTy) {\n";
584 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
586 MVT::SimpleValueType VT = TI->first;
587 std::string TypeName = getName(VT);
588 OS << " case " << TypeName << ": return FastEmit_"
589 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
590 Operands.PrintManglingSuffix(OS);
592 if (!Operands.empty())
594 Operands.PrintArguments(OS);
597 OS << " default: return 0;\n";
603 OS << "// Top-level FastEmit function.\n";
606 // Emit one function for the operand signature that demultiplexes based
607 // on opcode and type.
608 OS << "unsigned FastEmit_";
609 Operands.PrintManglingSuffix(OS);
610 OS << "(MVT VT, MVT RetVT, unsigned Opcode";
611 if (!Operands.empty())
613 Operands.PrintParameters(OS);
615 OS << " switch (Opcode) {\n";
616 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
618 const std::string &Opcode = I->first;
620 OS << " case " << Opcode << ": return FastEmit_"
621 << getLegalCName(Opcode) << "_";
622 Operands.PrintManglingSuffix(OS);
624 if (!Operands.empty())
626 Operands.PrintArguments(OS);
629 OS << " default: return 0;\n";
636 void FastISelEmitter::run(raw_ostream &OS) {
637 const CodeGenTarget &Target = CGP.getTargetInfo();
639 // Determine the target's namespace name.
640 std::string InstNS = Target.getInstNamespace() + "::";
641 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
643 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
644 Target.getName() + " target", OS);
646 FastISelMap F(InstNS);
647 F.CollectPatterns(CGP);
648 F.PrintFunctionDefinitions(OS);
651 FastISelEmitter::FastISelEmitter(RecordKeeper &R)