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 /// OperandsSignature - This class holds a description of a list of operand
48 /// types. It has utility methods for emitting text based on the operands.
50 struct OperandsSignature {
51 std::vector<std::string> Operands;
53 bool operator<(const OperandsSignature &O) const {
54 return Operands < O.Operands;
57 bool empty() const { return Operands.empty(); }
59 /// initialize - Examine the given pattern and initialize the contents
60 /// of the Operands array accordingly. Return true if all the operands
61 /// are supported, false otherwise.
63 bool initialize(TreePatternNode *InstPatNode,
64 const CodeGenTarget &Target,
65 MVT::SimpleValueType VT) {
66 if (!InstPatNode->isLeaf() &&
67 InstPatNode->getOperator()->getName() == "imm") {
68 Operands.push_back("i");
72 const CodeGenRegisterClass *DstRC = 0;
74 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
75 TreePatternNode *Op = InstPatNode->getChild(i);
76 // For now, filter out any operand with a predicate.
77 if (!Op->getPredicateFn().empty())
79 // For now, filter out any operand with multiple values.
80 if (Op->getExtTypes().size() != 1)
82 // For now, all the operands must have the same type.
83 if (Op->getTypeNum(0) != VT)
86 if (Op->getOperator()->getName() == "imm") {
87 Operands.push_back("i");
90 // For now, ignore fpimm and other non-leaf nodes.
93 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
96 Record *OpLeafRec = OpDI->getDef();
97 // TODO: handle instructions which have physreg operands.
98 if (OpLeafRec->isSubClassOf("Register"))
100 // For now, the only other thing we accept is register operands.
101 if (!OpLeafRec->isSubClassOf("RegisterClass"))
103 // For now, require the register operands' register classes to all
105 const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
108 // For now, all the operands must have the same register class.
114 Operands.push_back("r");
119 void PrintParameters(std::ostream &OS) const {
120 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
121 if (Operands[i] == "r") {
122 OS << "unsigned Op" << i;
123 } else if (Operands[i] == "i") {
124 OS << "uint64_t imm" << i;
126 assert("Unknown operand kind!");
134 void PrintArguments(std::ostream &OS) const {
135 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
136 if (Operands[i] == "r") {
138 } else if (Operands[i] == "i") {
141 assert("Unknown operand kind!");
149 void PrintManglingSuffix(std::ostream &OS) const {
150 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
156 /// InstructionMemo - This class holds additional information about an
157 /// instruction needed to emit code for it.
159 struct InstructionMemo {
161 const CodeGenRegisterClass *RC;
166 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
167 return CGP.getSDNodeInfo(Op).getEnumName();
170 static std::string getLegalCName(std::string OpName) {
171 std::string::size_type pos = OpName.find("::");
172 if (pos != std::string::npos)
173 OpName.replace(pos, 2, "_");
177 void FastISelEmitter::run(std::ostream &OS) {
178 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
179 Target.getName() + " target", OS);
181 OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
183 OS << "namespace llvm {\n";
185 OS << "namespace " << InstNS.substr(0, InstNS.size() - 2) << " {\n";
188 typedef std::map<std::string, InstructionMemo> PredMap;
189 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
190 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
191 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
192 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
193 OperandsOpcodeTypeRetPredMap SimplePatterns;
195 // Scan through all the patterns and record the simple ones.
196 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
197 E = CGP.ptm_end(); I != E; ++I) {
198 const PatternToMatch &Pattern = *I;
200 // For now, just look at Instructions, so that we don't have to worry
201 // about emitting multiple instructions for a pattern.
202 TreePatternNode *Dst = Pattern.getDstPattern();
203 if (Dst->isLeaf()) continue;
204 Record *Op = Dst->getOperator();
205 if (!Op->isSubClassOf("Instruction"))
207 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
208 if (II.OperandList.empty())
211 // For now, ignore instructions where the first operand is not an
213 Record *Op0Rec = II.OperandList[0].Rec;
214 if (!Op0Rec->isSubClassOf("RegisterClass"))
216 const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
220 // Inspect the pattern.
221 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
222 if (!InstPatNode) continue;
223 if (InstPatNode->isLeaf()) continue;
225 Record *InstPatOp = InstPatNode->getOperator();
226 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
227 MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
228 MVT::SimpleValueType VT = RetVT;
229 if (InstPatNode->getNumChildren())
230 VT = InstPatNode->getChild(0)->getTypeNum(0);
232 // For now, filter out instructions which just set a register to
233 // an Operand or an immediate, like MOV32ri.
234 if (InstPatOp->isSubClassOf("Operand"))
237 // For now, filter out any instructions with predicates.
238 if (!InstPatNode->getPredicateFn().empty())
241 // Check all the operands.
242 OperandsSignature Operands;
243 if (!Operands.initialize(InstPatNode, Target, VT))
246 // Get the predicate that guards this pattern.
247 std::string PredicateCheck = Pattern.getPredicateCheck();
249 // Ok, we found a pattern that we can handle. Remember it.
250 InstructionMemo Memo = {
251 Pattern.getDstPattern()->getOperator()->getName(),
254 assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
255 "Duplicate pattern!");
256 SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
259 // Declare the target FastISel class.
260 OS << "class FastISel : public llvm::FastISel {\n";
261 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
262 OE = SimplePatterns.end(); OI != OE; ++OI) {
263 const OperandsSignature &Operands = OI->first;
264 const OpcodeTypeRetPredMap &OTM = OI->second;
266 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
268 const std::string &Opcode = I->first;
269 const TypeRetPredMap &TM = I->second;
271 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
273 MVT::SimpleValueType VT = TI->first;
274 const RetPredMap &RM = TI->second;
277 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
279 MVT::SimpleValueType RetVT = RI->first;
280 OS << " unsigned FastEmit_" << getLegalCName(Opcode)
281 << "_" << getLegalCName(getName(VT)) << "_"
282 << getLegalCName(getName(RetVT)) << "_";
283 Operands.PrintManglingSuffix(OS);
285 Operands.PrintParameters(OS);
289 OS << " unsigned FastEmit_" << getLegalCName(Opcode)
290 << "_" << getLegalCName(getName(VT)) << "_";
291 Operands.PrintManglingSuffix(OS);
292 OS << "(MVT::SimpleValueType RetVT";
293 if (!Operands.empty())
295 Operands.PrintParameters(OS);
299 OS << " unsigned FastEmit_" << getLegalCName(Opcode) << "_";
300 Operands.PrintManglingSuffix(OS);
301 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
302 if (!Operands.empty())
304 Operands.PrintParameters(OS);
308 OS << " unsigned FastEmit_";
309 Operands.PrintManglingSuffix(OS);
310 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
311 if (!Operands.empty())
313 Operands.PrintParameters(OS);
318 // Declare the Subtarget member, which is used for predicate checks.
319 OS << " const " << InstNS.substr(0, InstNS.size() - 2)
320 << "Subtarget *Subtarget;\n";
323 // Declare the constructor.
325 OS << " explicit FastISel(MachineFunction &mf)\n";
326 OS << " : llvm::FastISel(mf),\n";
327 OS << " Subtarget(&TM.getSubtarget<" << InstNS.substr(0, InstNS.size() - 2)
328 << "Subtarget>()) {}\n";
332 // Define the target FastISel creation function.
333 OS << "llvm::FastISel *createFastISel(MachineFunction &mf) {\n";
334 OS << " return new FastISel(mf);\n";
338 // Now emit code for all the patterns that we collected.
339 for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
340 OE = SimplePatterns.end(); OI != OE; ++OI) {
341 const OperandsSignature &Operands = OI->first;
342 const OpcodeTypeRetPredMap &OTM = OI->second;
344 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
346 const std::string &Opcode = I->first;
347 const TypeRetPredMap &TM = I->second;
349 OS << "// FastEmit functions for " << Opcode << ".\n";
352 // Emit one function for each opcode,type pair.
353 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
355 MVT::SimpleValueType VT = TI->first;
356 const RetPredMap &RM = TI->second;
357 if (RM.size() != 1) {
358 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
360 MVT::SimpleValueType RetVT = RI->first;
361 const PredMap &PM = RI->second;
362 bool HasPred = false;
364 OS << "unsigned FastISel::FastEmit_"
365 << getLegalCName(Opcode)
366 << "_" << getLegalCName(getName(VT))
367 << "_" << getLegalCName(getName(RetVT)) << "_";
368 Operands.PrintManglingSuffix(OS);
370 Operands.PrintParameters(OS);
373 // Emit code for each possible instruction. There may be
374 // multiple if there are subtarget concerns.
375 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
377 std::string PredicateCheck = PI->first;
378 const InstructionMemo &Memo = PI->second;
380 if (PredicateCheck.empty()) {
382 "Multiple instructions match, at least one has "
383 "a predicate and at least one doesn't!");
385 OS << " if (" + PredicateCheck + ")\n";
389 OS << " return FastEmitInst_";
390 Operands.PrintManglingSuffix(OS);
391 OS << "(" << InstNS << Memo.Name << ", ";
392 OS << InstNS << Memo.RC->getName() << "RegisterClass";
393 if (!Operands.empty())
395 Operands.PrintArguments(OS);
398 // Return 0 if none of the predicates were satisfied.
400 OS << " return 0;\n";
405 // Emit one function for the type that demultiplexes on return type.
406 OS << "unsigned FastISel::FastEmit_"
407 << getLegalCName(Opcode) << "_"
408 << getLegalCName(getName(VT)) << "_";
409 Operands.PrintManglingSuffix(OS);
410 OS << "(MVT::SimpleValueType RetVT";
411 if (!Operands.empty())
413 Operands.PrintParameters(OS);
414 OS << ") {\nswitch (RetVT) {\n";
415 for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
417 MVT::SimpleValueType RetVT = RI->first;
418 OS << " case " << getName(RetVT) << ": return FastEmit_"
419 << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
420 << "_" << getLegalCName(getName(RetVT)) << "_";
421 Operands.PrintManglingSuffix(OS);
423 Operands.PrintArguments(OS);
426 OS << " default: return 0;\n}\n}\n\n";
429 // Non-variadic return type.
430 OS << "unsigned FastISel::FastEmit_"
431 << getLegalCName(Opcode) << "_"
432 << getLegalCName(getName(VT)) << "_";
433 Operands.PrintManglingSuffix(OS);
434 OS << "(MVT::SimpleValueType RetVT";
435 if (!Operands.empty())
437 Operands.PrintParameters(OS);
440 const PredMap &PM = RM.begin()->second;
441 bool HasPred = false;
443 // Emit code for each possible instruction. There may be
444 // multiple if there are subtarget concerns.
445 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE; ++PI) {
446 std::string PredicateCheck = PI->first;
447 const InstructionMemo &Memo = PI->second;
449 if (PredicateCheck.empty()) {
451 "Multiple instructions match, at least one has "
452 "a predicate and at least one doesn't!");
454 OS << " if (" + PredicateCheck + ")\n";
458 OS << " return FastEmitInst_";
459 Operands.PrintManglingSuffix(OS);
460 OS << "(" << InstNS << Memo.Name << ", ";
461 OS << InstNS << Memo.RC->getName() << "RegisterClass";
462 if (!Operands.empty())
464 Operands.PrintArguments(OS);
468 // Return 0 if none of the predicates were satisfied.
470 OS << " return 0;\n";
476 // Emit one function for the opcode that demultiplexes based on the type.
477 OS << "unsigned FastISel::FastEmit_"
478 << getLegalCName(Opcode) << "_";
479 Operands.PrintManglingSuffix(OS);
480 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
481 if (!Operands.empty())
483 Operands.PrintParameters(OS);
485 OS << " switch (VT) {\n";
486 for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
488 MVT::SimpleValueType VT = TI->first;
489 std::string TypeName = getName(VT);
490 OS << " case " << TypeName << ": return FastEmit_"
491 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
492 Operands.PrintManglingSuffix(OS);
494 if (!Operands.empty())
496 Operands.PrintArguments(OS);
499 OS << " default: return 0;\n";
505 OS << "// Top-level FastEmit function.\n";
508 // Emit one function for the operand signature that demultiplexes based
509 // on opcode and type.
510 OS << "unsigned FastISel::FastEmit_";
511 Operands.PrintManglingSuffix(OS);
512 OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
513 if (!Operands.empty())
515 Operands.PrintParameters(OS);
517 OS << " switch (Opcode) {\n";
518 for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
520 const std::string &Opcode = I->first;
522 OS << " case " << Opcode << ": return FastEmit_"
523 << getLegalCName(Opcode) << "_";
524 Operands.PrintManglingSuffix(OS);
526 if (!Operands.empty())
528 Operands.PrintArguments(OS);
531 OS << " default: return 0;\n";
537 OS << "} // namespace X86\n";
539 OS << "} // namespace llvm\n";
542 FastISelEmitter::FastISelEmitter(RecordKeeper &R)
545 Target(CGP.getTargetInfo()),
546 InstNS(Target.getInstNamespace() + "::") {
548 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");