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 const CodeGenRegisterClass *DstRC) {
67 if (!InstPatNode->isLeaf() &&
68 InstPatNode->getOperator()->getName() == "imm") {
69 Operands.push_back("i");
73 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
74 TreePatternNode *Op = InstPatNode->getChild(i);
75 // For now, filter out any operand with a predicate.
76 if (!Op->getPredicateFn().empty())
78 // For now, filter out any operand with multiple values.
79 if (Op->getExtTypes().size() != 1)
81 // For now, all the operands must have the same type.
82 if (Op->getTypeNum(0) != VT)
85 if (Op->getOperator()->getName() == "imm") {
86 Operands.push_back("i");
89 // For now, ignore fpimm and other non-leaf nodes.
92 DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
95 Record *OpLeafRec = OpDI->getDef();
96 // TODO: handle instructions which have physreg operands.
97 if (OpLeafRec->isSubClassOf("Register"))
99 // For now, the only other thing we accept is register operands.
100 if (!OpLeafRec->isSubClassOf("RegisterClass"))
102 // For now, require the register operands' register classes to all
104 const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
107 // For now, all the operands must have the same register class.
110 Operands.push_back("r");
115 void PrintParameters(std::ostream &OS) const {
116 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
117 if (Operands[i] == "r") {
118 OS << "unsigned Op" << i;
119 } else if (Operands[i] == "i") {
120 OS << "uint64_t imm" << i;
122 assert("Unknown operand kind!");
130 void PrintArguments(std::ostream &OS) const {
131 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
132 if (Operands[i] == "r") {
134 } else if (Operands[i] == "i") {
137 assert("Unknown operand kind!");
145 void PrintManglingSuffix(std::ostream &OS) const {
146 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
152 /// InstructionMemo - This class holds additional information about an
153 /// instruction needed to emit code for it.
155 struct InstructionMemo {
157 const CodeGenRegisterClass *RC;
162 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
163 return CGP.getSDNodeInfo(Op).getEnumName();
166 static std::string getLegalCName(std::string OpName) {
167 std::string::size_type pos = OpName.find("::");
168 if (pos != std::string::npos)
169 OpName.replace(pos, 2, "_");
173 void FastISelEmitter::run(std::ostream &OS) {
174 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
175 Target.getName() + " target", OS);
177 OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
179 OS << "namespace llvm {\n";
181 OS << "namespace " << InstNS.substr(0, InstNS.size() - 2) << " {\n";
184 typedef std::map<std::string, InstructionMemo> PredMap;
185 typedef std::map<MVT::SimpleValueType, PredMap> TypePredMap;
186 typedef std::map<std::string, TypePredMap> OpcodeTypePredMap;
187 typedef std::map<OperandsSignature, OpcodeTypePredMap> OperandsOpcodeTypePredMap;
188 OperandsOpcodeTypePredMap SimplePatterns;
190 // Scan through all the patterns and record the simple ones.
191 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
192 E = CGP.ptm_end(); I != E; ++I) {
193 const PatternToMatch &Pattern = *I;
195 // For now, just look at Instructions, so that we don't have to worry
196 // about emitting multiple instructions for a pattern.
197 TreePatternNode *Dst = Pattern.getDstPattern();
198 if (Dst->isLeaf()) continue;
199 Record *Op = Dst->getOperator();
200 if (!Op->isSubClassOf("Instruction"))
202 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
203 if (II.OperandList.empty())
206 // For now, ignore instructions where the first operand is not an
208 Record *Op0Rec = II.OperandList[0].Rec;
209 if (!Op0Rec->isSubClassOf("RegisterClass"))
211 const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
215 // Inspect the pattern.
216 TreePatternNode *InstPatNode = Pattern.getSrcPattern();
217 if (!InstPatNode) continue;
218 if (InstPatNode->isLeaf()) continue;
220 Record *InstPatOp = InstPatNode->getOperator();
221 std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
222 MVT::SimpleValueType VT = InstPatNode->getTypeNum(0);
224 // For now, filter out instructions which just set a register to
225 // an Operand or an immediate, like MOV32ri.
226 if (InstPatOp->isSubClassOf("Operand"))
229 // For now, filter out any instructions with predicates.
230 if (!InstPatNode->getPredicateFn().empty())
233 // Check all the operands.
234 OperandsSignature Operands;
235 if (!Operands.initialize(InstPatNode, Target, VT, DstRC))
238 // Get the predicate that guards this pattern.
239 std::string PredicateCheck = Pattern.getPredicateCheck();
241 // Ok, we found a pattern that we can handle. Remember it.
242 InstructionMemo Memo = {
243 Pattern.getDstPattern()->getOperator()->getName(),
246 assert(!SimplePatterns[Operands][OpcodeName][VT].count(PredicateCheck) &&
247 "Duplicate pattern!");
248 SimplePatterns[Operands][OpcodeName][VT][PredicateCheck] = Memo;
251 // Declare the target FastISel class.
252 OS << "class FastISel : public llvm::FastISel {\n";
253 for (OperandsOpcodeTypePredMap::const_iterator OI = SimplePatterns.begin(),
254 OE = SimplePatterns.end(); OI != OE; ++OI) {
255 const OperandsSignature &Operands = OI->first;
256 const OpcodeTypePredMap &OTM = OI->second;
258 for (OpcodeTypePredMap::const_iterator I = OTM.begin(), E = OTM.end();
260 const std::string &Opcode = I->first;
261 const TypePredMap &TM = I->second;
263 for (TypePredMap::const_iterator TI = TM.begin(), TE = TM.end();
265 MVT::SimpleValueType VT = TI->first;
267 OS << " unsigned FastEmit_" << getLegalCName(Opcode)
268 << "_" << getLegalCName(getName(VT)) << "_";
269 Operands.PrintManglingSuffix(OS);
271 Operands.PrintParameters(OS);
275 OS << " unsigned FastEmit_" << getLegalCName(Opcode) << "_";
276 Operands.PrintManglingSuffix(OS);
277 OS << "(MVT::SimpleValueType VT";
278 if (!Operands.empty())
280 Operands.PrintParameters(OS);
284 OS << " unsigned FastEmit_";
285 Operands.PrintManglingSuffix(OS);
286 OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
287 if (!Operands.empty())
289 Operands.PrintParameters(OS);
294 // Declare the Subtarget member, which is used for predicate checks.
295 OS << " const " << InstNS.substr(0, InstNS.size() - 2)
296 << "Subtarget *Subtarget;\n";
299 // Declare the constructor.
301 OS << " explicit FastISel(MachineFunction &mf)\n";
302 OS << " : llvm::FastISel(mf),\n";
303 OS << " Subtarget(&TM.getSubtarget<" << InstNS.substr(0, InstNS.size() - 2)
304 << "Subtarget>()) {}\n";
308 // Define the target FastISel creation function.
309 OS << "llvm::FastISel *createFastISel(MachineFunction &mf) {\n";
310 OS << " return new FastISel(mf);\n";
314 // Now emit code for all the patterns that we collected.
315 for (OperandsOpcodeTypePredMap::const_iterator OI = SimplePatterns.begin(),
316 OE = SimplePatterns.end(); OI != OE; ++OI) {
317 const OperandsSignature &Operands = OI->first;
318 const OpcodeTypePredMap &OTM = OI->second;
320 for (OpcodeTypePredMap::const_iterator I = OTM.begin(), E = OTM.end();
322 const std::string &Opcode = I->first;
323 const TypePredMap &TM = I->second;
325 OS << "// FastEmit functions for " << Opcode << ".\n";
328 // Emit one function for each opcode,type pair.
329 for (TypePredMap::const_iterator TI = TM.begin(), TE = TM.end();
331 MVT::SimpleValueType VT = TI->first;
332 const PredMap &PM = TI->second;
333 bool HasPred = false;
335 OS << "unsigned FastISel::FastEmit_"
336 << getLegalCName(Opcode)
337 << "_" << getLegalCName(getName(VT)) << "_";
338 Operands.PrintManglingSuffix(OS);
340 Operands.PrintParameters(OS);
343 // Emit code for each possible instruction. There may be
344 // multiple if there are subtarget concerns.
345 for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
347 std::string PredicateCheck = PI->first;
348 const InstructionMemo &Memo = PI->second;
350 if (PredicateCheck.empty()) {
351 assert(!HasPred && "Multiple instructions match, at least one has "
352 "a predicate and at least one doesn't!");
354 OS << " if (" + PredicateCheck + ")\n";
358 OS << " return FastEmitInst_";
359 Operands.PrintManglingSuffix(OS);
360 OS << "(" << InstNS << Memo.Name << ", ";
361 OS << InstNS << Memo.RC->getName() << "RegisterClass";
362 if (!Operands.empty())
364 Operands.PrintArguments(OS);
367 // Return 0 if none of the predicates were satisfied.
369 OS << " return 0;\n";
374 // Emit one function for the opcode that demultiplexes based on the type.
375 OS << "unsigned FastISel::FastEmit_"
376 << getLegalCName(Opcode) << "_";
377 Operands.PrintManglingSuffix(OS);
378 OS << "(MVT::SimpleValueType VT";
379 if (!Operands.empty())
381 Operands.PrintParameters(OS);
383 OS << " switch (VT) {\n";
384 for (TypePredMap::const_iterator TI = TM.begin(), TE = TM.end();
386 MVT::SimpleValueType VT = TI->first;
387 std::string TypeName = getName(VT);
388 OS << " case " << TypeName << ": return FastEmit_"
389 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
390 Operands.PrintManglingSuffix(OS);
392 Operands.PrintArguments(OS);
395 OS << " default: return 0;\n";
401 OS << "// Top-level FastEmit function.\n";
404 // Emit one function for the operand signature that demultiplexes based
405 // on opcode and type.
406 OS << "unsigned FastISel::FastEmit_";
407 Operands.PrintManglingSuffix(OS);
408 OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
409 if (!Operands.empty())
411 Operands.PrintParameters(OS);
413 OS << " switch (Opcode) {\n";
414 for (OpcodeTypePredMap::const_iterator I = OTM.begin(), E = OTM.end();
416 const std::string &Opcode = I->first;
418 OS << " case " << Opcode << ": return FastEmit_"
419 << getLegalCName(Opcode) << "_";
420 Operands.PrintManglingSuffix(OS);
422 if (!Operands.empty())
424 Operands.PrintArguments(OS);
427 OS << " default: return 0;\n";
433 OS << "} // namespace X86\n";
435 OS << "} // namespace llvm\n";
438 FastISelEmitter::FastISelEmitter(RecordKeeper &R)
441 Target(CGP.getTargetInfo()),
442 InstNS(Target.getInstNamespace() + "::") {
444 assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");