Support using DebugLoc's in a DenseMap.
[llvm/stm8.git] / utils / TableGen / FastISelEmitter.cpp
blobf01de1dcfce600a9f86730ab06d4260443d6c480
1 //===- FastISelEmitter.cpp - Generate an instruction selector -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
21 #include "Record.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/VectorExtras.h"
25 using namespace llvm;
27 namespace {
29 /// InstructionMemo - This class holds additional information about an
30 /// instruction needed to emit code for it.
31 ///
32 struct InstructionMemo {
33 std::string Name;
34 const CodeGenRegisterClass *RC;
35 std::string 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.
41 ///
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.
54 ///
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");
62 return true;
64 if (InstPatNode->getOperator()->getName() == "fpimm") {
65 Operands.push_back("f");
66 return true;
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)
79 return false;
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)
84 return false;
86 if (!Op->isLeaf()) {
87 if (Op->getOperator()->getName() == "imm") {
88 Operands.push_back("i");
89 continue;
91 if (Op->getOperator()->getName() == "fpimm") {
92 Operands.push_back("f");
93 continue;
95 // For now, ignore other non-leaf nodes.
96 return false;
98 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
99 if (!OpDI)
100 return false;
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);
109 else
110 return false;
112 // For now, this needs to be a register class of some sort.
113 if (!RC)
114 return false;
116 // For now, all the operands must have the same register class or be
117 // a strict subclass of the destination.
118 if (DstRC) {
119 if (DstRC != RC && !DstRC->hasSubClass(RC))
120 return false;
121 } else
122 DstRC = RC;
123 Operands.push_back("r");
125 return true;
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;
136 } else {
137 assert("Unknown operand kind!");
138 abort();
140 if (i + 1 != e)
141 OS << ", ";
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) {
150 if (PR[i] != "")
151 // Implicit physical register operand.
152 continue;
154 if (PrintedArg)
155 OS << ", ";
156 if (Operands[i] == "r") {
157 OS << "Op" << i << ", Op" << i << "IsKill";
158 PrintedArg = true;
159 } else if (Operands[i] == "i") {
160 OS << "imm" << i;
161 PrintedArg = true;
162 } else if (Operands[i] == "f") {
163 OS << "f" << i;
164 PrintedArg = true;
165 } else {
166 assert("Unknown operand kind!");
167 abort();
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") {
177 OS << "imm" << i;
178 } else if (Operands[i] == "f") {
179 OS << "f" << i;
180 } else {
181 assert("Unknown operand kind!");
182 abort();
184 if (i + 1 != e)
185 OS << ", ";
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) {
193 if (PR[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_*
198 // call.
199 continue;
200 OS << Operands[i];
204 void PrintManglingSuffix(raw_ostream &OS) const {
205 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
206 OS << Operands[i];
211 class FastISelMap {
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;
221 std::string InstNS;
223 public:
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, "_");
240 return OpName;
243 FastISelMap::FastISelMap(std::string instns)
244 : InstNS(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"))
265 continue;
266 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
267 if (II.Operands.size() == 0)
268 continue;
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())
275 continue;
276 if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
277 MultiInsts = true;
278 break;
281 if (MultiInsts)
282 continue;
284 // For now, ignore instructions where the first operand is not an
285 // output register.
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"))
291 continue;
292 DstRC = &Target.getRegisterClass(Op0Rec);
293 if (!DstRC)
294 continue;
295 } else {
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());
301 if (SR)
302 SubRegNo = getQualifiedName(SR->getDef());
303 else
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"))
328 continue;
330 // For now, filter out any instructions with predicates.
331 if (!InstPatNode->getPredicateFns().empty())
332 continue;
334 // Check all the operands.
335 OperandsSignature Operands;
336 if (!Operands.initialize(InstPatNode, Target, VT))
337 continue;
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);
347 if (!Op->isLeaf()) {
348 PhysRegInputs->push_back("");
349 continue;
352 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
353 Record *OpLeafRec = OpDI->getDef();
354 std::string PhysReg;
355 if (OpLeafRec->isSubClassOf("Register")) {
356 PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
357 "Namespace")->getValue())->getValue();
358 PhysReg += "::";
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();
364 break;
369 PhysRegInputs->push_back(PhysReg);
371 } else
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(),
380 DstRC,
381 SubRegNo,
382 PhysRegInputs
384 if (SimplePatterns[Operands][OpcodeName][VT][RetVT]
385 .count(PredicateCheck))
386 throw TGError(Pattern.getSrcRecord()->getLoc(), "Duplicate record!");
388 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
392 void FastISelMap::PrintFunctionDefinitions(raw_ostream &OS) {
393 // Now emit code for all the patterns that we collected.
394 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
395 OE = SimplePatterns.end(); OI != OE; ++OI) {
396 const OperandsSignature &Operands = OI->first;
397 const OpcodeTypeRetPredMap &OTM = OI->second;
399 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
400 I != E; ++I) {
401 const std::string &Opcode = I->first;
402 const TypeRetPredMap &TM = I->second;
404 OS << "// FastEmit functions for " << Opcode << ".\n";
405 OS << "\n";
407 // Emit one function for each opcode,type pair.
408 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
409 TI != TE; ++TI) {
410 MVT::SimpleValueType VT = TI->first;
411 const RetPredMap &RM = TI->second;
412 if (RM.size() != 1) {
413 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
414 RI != RE; ++RI) {
415 MVT::SimpleValueType RetVT = RI->first;
416 const PredMap &PM = RI->second;
417 bool HasPred = false;
419 OS << "unsigned FastEmit_"
420 << getLegalCName(Opcode)
421 << "_" << getLegalCName(getName(VT))
422 << "_" << getLegalCName(getName(RetVT)) << "_";
423 Operands.PrintManglingSuffix(OS);
424 OS << "(";
425 Operands.PrintParameters(OS);
426 OS << ") {\n";
428 // Emit code for each possible instruction. There may be
429 // multiple if there are subtarget concerns.
430 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
431 PI != PE; ++PI) {
432 std::string PredicateCheck = PI->first;
433 const InstructionMemo &Memo = PI->second;
435 if (PredicateCheck.empty()) {
436 assert(!HasPred &&
437 "Multiple instructions match, at least one has "
438 "a predicate and at least one doesn't!");
439 } else {
440 OS << " if (" + PredicateCheck + ") {\n";
441 OS << " ";
442 HasPred = true;
445 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
446 if ((*Memo.PhysRegs)[i] != "")
447 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
448 << "TII.get(TargetOpcode::COPY), "
449 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
452 OS << " return FastEmitInst_";
453 if (Memo.SubRegNo.empty()) {
454 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
455 OS << "(" << InstNS << Memo.Name << ", ";
456 OS << InstNS << Memo.RC->getName() << "RegisterClass";
457 if (!Operands.empty())
458 OS << ", ";
459 Operands.PrintArguments(OS, *Memo.PhysRegs);
460 OS << ");\n";
461 } else {
462 OS << "extractsubreg(" << getName(RetVT);
463 OS << ", Op0, Op0IsKill, ";
464 OS << Memo.SubRegNo;
465 OS << ");\n";
468 if (HasPred)
469 OS << " }\n";
472 // Return 0 if none of the predicates were satisfied.
473 if (HasPred)
474 OS << " return 0;\n";
475 OS << "}\n";
476 OS << "\n";
479 // Emit one function for the type that demultiplexes on return type.
480 OS << "unsigned FastEmit_"
481 << getLegalCName(Opcode) << "_"
482 << getLegalCName(getName(VT)) << "_";
483 Operands.PrintManglingSuffix(OS);
484 OS << "(MVT RetVT";
485 if (!Operands.empty())
486 OS << ", ";
487 Operands.PrintParameters(OS);
488 OS << ") {\nswitch (RetVT.SimpleTy) {\n";
489 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
490 RI != RE; ++RI) {
491 MVT::SimpleValueType RetVT = RI->first;
492 OS << " case " << getName(RetVT) << ": return FastEmit_"
493 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
494 << "_" << getLegalCName(getName(RetVT)) << "_";
495 Operands.PrintManglingSuffix(OS);
496 OS << "(";
497 Operands.PrintArguments(OS);
498 OS << ");\n";
500 OS << " default: return 0;\n}\n}\n\n";
502 } else {
503 // Non-variadic return type.
504 OS << "unsigned FastEmit_"
505 << getLegalCName(Opcode) << "_"
506 << getLegalCName(getName(VT)) << "_";
507 Operands.PrintManglingSuffix(OS);
508 OS << "(MVT RetVT";
509 if (!Operands.empty())
510 OS << ", ";
511 Operands.PrintParameters(OS);
512 OS << ") {\n";
514 OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
515 << ")\n return 0;\n";
517 const PredMap &PM = RM.begin()->second;
518 bool HasPred = false;
520 // Emit code for each possible instruction. There may be
521 // multiple if there are subtarget concerns.
522 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE;
523 ++PI) {
524 std::string PredicateCheck = PI->first;
525 const InstructionMemo &Memo = PI->second;
527 if (PredicateCheck.empty()) {
528 assert(!HasPred &&
529 "Multiple instructions match, at least one has "
530 "a predicate and at least one doesn't!");
531 } else {
532 OS << " if (" + PredicateCheck + ") {\n";
533 OS << " ";
534 HasPred = true;
537 for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
538 if ((*Memo.PhysRegs)[i] != "")
539 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, "
540 << "TII.get(TargetOpcode::COPY), "
541 << (*Memo.PhysRegs)[i] << ").addReg(Op" << i << ");\n";
544 OS << " return FastEmitInst_";
546 if (Memo.SubRegNo.empty()) {
547 Operands.PrintManglingSuffix(OS, *Memo.PhysRegs);
548 OS << "(" << InstNS << Memo.Name << ", ";
549 OS << InstNS << Memo.RC->getName() << "RegisterClass";
550 if (!Operands.empty())
551 OS << ", ";
552 Operands.PrintArguments(OS, *Memo.PhysRegs);
553 OS << ");\n";
554 } else {
555 OS << "extractsubreg(RetVT, Op0, Op0IsKill, ";
556 OS << Memo.SubRegNo;
557 OS << ");\n";
560 if (HasPred)
561 OS << " }\n";
564 // Return 0 if none of the predicates were satisfied.
565 if (HasPred)
566 OS << " return 0;\n";
567 OS << "}\n";
568 OS << "\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 VT, MVT RetVT";
577 if (!Operands.empty())
578 OS << ", ";
579 Operands.PrintParameters(OS);
580 OS << ") {\n";
581 OS << " switch (VT.SimpleTy) {\n";
582 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
583 TI != TE; ++TI) {
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);
589 OS << "(RetVT";
590 if (!Operands.empty())
591 OS << ", ";
592 Operands.PrintArguments(OS);
593 OS << ");\n";
595 OS << " default: return 0;\n";
596 OS << " }\n";
597 OS << "}\n";
598 OS << "\n";
601 OS << "// Top-level FastEmit function.\n";
602 OS << "\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 VT, MVT RetVT, unsigned Opcode";
609 if (!Operands.empty())
610 OS << ", ";
611 Operands.PrintParameters(OS);
612 OS << ") {\n";
613 OS << " switch (Opcode) {\n";
614 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
615 I != E; ++I) {
616 const std::string &Opcode = I->first;
618 OS << " case " << Opcode << ": return FastEmit_"
619 << getLegalCName(Opcode) << "_";
620 Operands.PrintManglingSuffix(OS);
621 OS << "(VT, RetVT";
622 if (!Operands.empty())
623 OS << ", ";
624 Operands.PrintArguments(OS);
625 OS << ");\n";
627 OS << " default: return 0;\n";
628 OS << " }\n";
629 OS << "}\n";
630 OS << "\n";
634 void FastISelEmitter::run(raw_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)
650 : Records(R),
651 CGP(R) {