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/VectorExtras.h"
28 /// InstructionMemo - This class holds additional information about an
29 /// instruction needed to emit code for it.
31 struct InstructionMemo
{
33 const CodeGenRegisterClass
*RC
;
34 unsigned char SubRegNo
;
35 std::vector
<std::string
>* PhysRegs
;
38 /// OperandsSignature - This class holds a description of a list of operand
39 /// types. It has utility methods for emitting text based on the operands.
41 struct OperandsSignature
{
42 std::vector
<std::string
> Operands
;
44 bool operator<(const OperandsSignature
&O
) const {
45 return Operands
< O
.Operands
;
48 bool empty() const { return Operands
.empty(); }
50 /// initialize - Examine the given pattern and initialize the contents
51 /// of the Operands array accordingly. Return true if all the operands
52 /// are supported, false otherwise.
54 bool initialize(TreePatternNode
*InstPatNode
,
55 const CodeGenTarget
&Target
,
56 MVT::SimpleValueType VT
) {
57 if (!InstPatNode
->isLeaf() &&
58 InstPatNode
->getOperator()->getName() == "imm") {
59 Operands
.push_back("i");
62 if (!InstPatNode
->isLeaf() &&
63 InstPatNode
->getOperator()->getName() == "fpimm") {
64 Operands
.push_back("f");
68 const CodeGenRegisterClass
*DstRC
= 0;
70 for (unsigned i
= 0, e
= InstPatNode
->getNumChildren(); i
!= e
; ++i
) {
71 TreePatternNode
*Op
= InstPatNode
->getChild(i
);
72 // For now, filter out any operand with a predicate.
73 if (!Op
->getPredicateFns().empty())
75 // For now, filter out any operand with multiple values.
76 if (Op
->getExtTypes().size() != 1)
78 // For now, all the operands must have the same type.
79 if (Op
->getTypeNum(0) != VT
)
82 if (Op
->getOperator()->getName() == "imm") {
83 Operands
.push_back("i");
86 if (Op
->getOperator()->getName() == "fpimm") {
87 Operands
.push_back("f");
90 // For now, ignore other non-leaf nodes.
93 DefInit
*OpDI
= dynamic_cast<DefInit
*>(Op
->getLeafValue());
96 Record
*OpLeafRec
= OpDI
->getDef();
97 // For now, the only other thing we accept is register operands.
99 const CodeGenRegisterClass
*RC
= 0;
100 if (OpLeafRec
->isSubClassOf("RegisterClass"))
101 RC
= &Target
.getRegisterClass(OpLeafRec
);
102 else if (OpLeafRec
->isSubClassOf("Register"))
103 RC
= Target
.getRegisterClassForRegister(OpLeafRec
);
106 // For now, require the register operands' register classes to all
110 // For now, all the operands must have the same register class.
116 Operands
.push_back("r");
121 void PrintParameters(raw_ostream
&OS
) const {
122 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
123 if (Operands
[i
] == "r") {
124 OS
<< "unsigned Op" << i
;
125 } else if (Operands
[i
] == "i") {
126 OS
<< "uint64_t imm" << i
;
127 } else if (Operands
[i
] == "f") {
128 OS
<< "ConstantFP *f" << i
;
130 assert("Unknown operand kind!");
138 void PrintArguments(raw_ostream
&OS
,
139 const std::vector
<std::string
>& PR
) const {
140 assert(PR
.size() == Operands
.size());
141 bool PrintedArg
= false;
142 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
144 // Implicit physical register operand.
149 if (Operands
[i
] == "r") {
152 } else if (Operands
[i
] == "i") {
155 } else if (Operands
[i
] == "f") {
159 assert("Unknown operand kind!");
165 void PrintArguments(raw_ostream
&OS
) const {
166 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
167 if (Operands
[i
] == "r") {
169 } else if (Operands
[i
] == "i") {
171 } else if (Operands
[i
] == "f") {
174 assert("Unknown operand kind!");
183 void PrintManglingSuffix(raw_ostream
&OS
,
184 const std::vector
<std::string
>& PR
) const {
185 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
187 // Implicit physical register operand. e.g. Instruction::Mul expect to
188 // select to a binary op. On x86, mul may take a single operand with
189 // the other operand being implicit. We must emit something that looks
190 // like a binary instruction except for the very inner FastEmitInst_*
197 void PrintManglingSuffix(raw_ostream
&OS
) const {
198 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
205 typedef std::map
<std::string
, InstructionMemo
> PredMap
;
206 typedef std::map
<MVT::SimpleValueType
, PredMap
> RetPredMap
;
207 typedef std::map
<MVT::SimpleValueType
, RetPredMap
> TypeRetPredMap
;
208 typedef std::map
<std::string
, TypeRetPredMap
> OpcodeTypeRetPredMap
;
209 typedef std::map
<OperandsSignature
, OpcodeTypeRetPredMap
> OperandsOpcodeTypeRetPredMap
;
211 OperandsOpcodeTypeRetPredMap SimplePatterns
;
216 explicit FastISelMap(std::string InstNS
);
218 void CollectPatterns(CodeGenDAGPatterns
&CGP
);
219 void PrintFunctionDefinitions(raw_ostream
&OS
);
224 static std::string
getOpcodeName(Record
*Op
, CodeGenDAGPatterns
&CGP
) {
225 return CGP
.getSDNodeInfo(Op
).getEnumName();
228 static std::string
getLegalCName(std::string OpName
) {
229 std::string::size_type pos
= OpName
.find("::");
230 if (pos
!= std::string::npos
)
231 OpName
.replace(pos
, 2, "_");
235 FastISelMap::FastISelMap(std::string instns
)
239 void FastISelMap::CollectPatterns(CodeGenDAGPatterns
&CGP
) {
240 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
242 // Determine the target's namespace name.
243 InstNS
= Target
.getInstNamespace() + "::";
244 assert(InstNS
.size() > 2 && "Can't determine target-specific namespace!");
246 // Scan through all the patterns and record the simple ones.
247 for (CodeGenDAGPatterns::ptm_iterator I
= CGP
.ptm_begin(),
248 E
= CGP
.ptm_end(); I
!= E
; ++I
) {
249 const PatternToMatch
&Pattern
= *I
;
251 // For now, just look at Instructions, so that we don't have to worry
252 // about emitting multiple instructions for a pattern.
253 TreePatternNode
*Dst
= Pattern
.getDstPattern();
254 if (Dst
->isLeaf()) continue;
255 Record
*Op
= Dst
->getOperator();
256 if (!Op
->isSubClassOf("Instruction"))
258 CodeGenInstruction
&II
= CGP
.getTargetInfo().getInstruction(Op
->getName());
259 if (II
.OperandList
.empty())
262 // For now, ignore multi-instruction patterns.
263 bool MultiInsts
= false;
264 for (unsigned i
= 0, e
= Dst
->getNumChildren(); i
!= e
; ++i
) {
265 TreePatternNode
*ChildOp
= Dst
->getChild(i
);
266 if (ChildOp
->isLeaf())
268 if (ChildOp
->getOperator()->isSubClassOf("Instruction")) {
276 // For now, ignore instructions where the first operand is not an
278 const CodeGenRegisterClass
*DstRC
= 0;
279 unsigned SubRegNo
= ~0;
280 if (Op
->getName() != "EXTRACT_SUBREG") {
281 Record
*Op0Rec
= II
.OperandList
[0].Rec
;
282 if (!Op0Rec
->isSubClassOf("RegisterClass"))
284 DstRC
= &Target
.getRegisterClass(Op0Rec
);
288 SubRegNo
= static_cast<IntInit
*>(
289 Dst
->getChild(1)->getLeafValue())->getValue();
292 // Inspect the pattern.
293 TreePatternNode
*InstPatNode
= Pattern
.getSrcPattern();
294 if (!InstPatNode
) continue;
295 if (InstPatNode
->isLeaf()) continue;
297 Record
*InstPatOp
= InstPatNode
->getOperator();
298 std::string OpcodeName
= getOpcodeName(InstPatOp
, CGP
);
299 MVT::SimpleValueType RetVT
= InstPatNode
->getTypeNum(0);
300 MVT::SimpleValueType VT
= RetVT
;
301 if (InstPatNode
->getNumChildren())
302 VT
= InstPatNode
->getChild(0)->getTypeNum(0);
304 // For now, filter out instructions which just set a register to
305 // an Operand or an immediate, like MOV32ri.
306 if (InstPatOp
->isSubClassOf("Operand"))
309 // For now, filter out any instructions with predicates.
310 if (!InstPatNode
->getPredicateFns().empty())
313 // Check all the operands.
314 OperandsSignature Operands
;
315 if (!Operands
.initialize(InstPatNode
, Target
, VT
))
318 std::vector
<std::string
>* PhysRegInputs
= new std::vector
<std::string
>();
319 if (!InstPatNode
->isLeaf() &&
320 (InstPatNode
->getOperator()->getName() == "imm" ||
321 InstPatNode
->getOperator()->getName() == "fpimmm"))
322 PhysRegInputs
->push_back("");
323 else if (!InstPatNode
->isLeaf()) {
324 for (unsigned i
= 0, e
= InstPatNode
->getNumChildren(); i
!= e
; ++i
) {
325 TreePatternNode
*Op
= InstPatNode
->getChild(i
);
327 PhysRegInputs
->push_back("");
331 DefInit
*OpDI
= dynamic_cast<DefInit
*>(Op
->getLeafValue());
332 Record
*OpLeafRec
= OpDI
->getDef();
334 if (OpLeafRec
->isSubClassOf("Register")) {
335 PhysReg
+= static_cast<StringInit
*>(OpLeafRec
->getValue( \
336 "Namespace")->getValue())->getValue();
339 std::vector
<CodeGenRegister
> Regs
= Target
.getRegisters();
340 for (unsigned i
= 0; i
< Regs
.size(); ++i
) {
341 if (Regs
[i
].TheDef
== OpLeafRec
) {
342 PhysReg
+= Regs
[i
].getName();
348 PhysRegInputs
->push_back(PhysReg
);
351 PhysRegInputs
->push_back("");
353 // Get the predicate that guards this pattern.
354 std::string PredicateCheck
= Pattern
.getPredicateCheck();
356 // Ok, we found a pattern that we can handle. Remember it.
357 InstructionMemo Memo
= {
358 Pattern
.getDstPattern()->getOperator()->getName(),
363 assert(!SimplePatterns
[Operands
][OpcodeName
][VT
][RetVT
].count(PredicateCheck
) &&
364 "Duplicate pattern!");
365 SimplePatterns
[Operands
][OpcodeName
][VT
][RetVT
][PredicateCheck
] = Memo
;
369 void FastISelMap::PrintFunctionDefinitions(raw_ostream
&OS
) {
370 // Now emit code for all the patterns that we collected.
371 for (OperandsOpcodeTypeRetPredMap::const_iterator OI
= SimplePatterns
.begin(),
372 OE
= SimplePatterns
.end(); OI
!= OE
; ++OI
) {
373 const OperandsSignature
&Operands
= OI
->first
;
374 const OpcodeTypeRetPredMap
&OTM
= OI
->second
;
376 for (OpcodeTypeRetPredMap::const_iterator I
= OTM
.begin(), E
= OTM
.end();
378 const std::string
&Opcode
= I
->first
;
379 const TypeRetPredMap
&TM
= I
->second
;
381 OS
<< "// FastEmit functions for " << Opcode
<< ".\n";
384 // Emit one function for each opcode,type pair.
385 for (TypeRetPredMap::const_iterator TI
= TM
.begin(), TE
= TM
.end();
387 MVT::SimpleValueType VT
= TI
->first
;
388 const RetPredMap
&RM
= TI
->second
;
389 if (RM
.size() != 1) {
390 for (RetPredMap::const_iterator RI
= RM
.begin(), RE
= RM
.end();
392 MVT::SimpleValueType RetVT
= RI
->first
;
393 const PredMap
&PM
= RI
->second
;
394 bool HasPred
= false;
396 OS
<< "unsigned FastEmit_"
397 << getLegalCName(Opcode
)
398 << "_" << getLegalCName(getName(VT
))
399 << "_" << getLegalCName(getName(RetVT
)) << "_";
400 Operands
.PrintManglingSuffix(OS
);
402 Operands
.PrintParameters(OS
);
405 // Emit code for each possible instruction. There may be
406 // multiple if there are subtarget concerns.
407 for (PredMap::const_iterator PI
= PM
.begin(), PE
= PM
.end();
409 std::string PredicateCheck
= PI
->first
;
410 const InstructionMemo
&Memo
= PI
->second
;
412 if (PredicateCheck
.empty()) {
414 "Multiple instructions match, at least one has "
415 "a predicate and at least one doesn't!");
417 OS
<< " if (" + PredicateCheck
+ ") {\n";
422 for (unsigned i
= 0; i
< Memo
.PhysRegs
->size(); ++i
) {
423 if ((*Memo
.PhysRegs
)[i
] != "")
424 OS
<< " TII.copyRegToReg(*MBB, MBB->end(), "
425 << (*Memo
.PhysRegs
)[i
] << ", Op" << i
<< ", "
426 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
427 << (*Memo
.PhysRegs
)[i
] << "), "
428 << "MRI.getRegClass(Op" << i
<< "));\n";
431 OS
<< " return FastEmitInst_";
432 if (Memo
.SubRegNo
== (unsigned char)~0) {
433 Operands
.PrintManglingSuffix(OS
, *Memo
.PhysRegs
);
434 OS
<< "(" << InstNS
<< Memo
.Name
<< ", ";
435 OS
<< InstNS
<< Memo
.RC
->getName() << "RegisterClass";
436 if (!Operands
.empty())
438 Operands
.PrintArguments(OS
, *Memo
.PhysRegs
);
441 OS
<< "extractsubreg(" << getName(RetVT
);
443 OS
<< (unsigned)Memo
.SubRegNo
;
451 // Return 0 if none of the predicates were satisfied.
453 OS
<< " return 0;\n";
458 // Emit one function for the type that demultiplexes on return type.
459 OS
<< "unsigned FastEmit_"
460 << getLegalCName(Opcode
) << "_"
461 << getLegalCName(getName(VT
)) << "_";
462 Operands
.PrintManglingSuffix(OS
);
464 if (!Operands
.empty())
466 Operands
.PrintParameters(OS
);
467 OS
<< ") {\nswitch (RetVT.SimpleTy) {\n";
468 for (RetPredMap::const_iterator RI
= RM
.begin(), RE
= RM
.end();
470 MVT::SimpleValueType RetVT
= RI
->first
;
471 OS
<< " case " << getName(RetVT
) << ": return FastEmit_"
472 << getLegalCName(Opcode
) << "_" << getLegalCName(getName(VT
))
473 << "_" << getLegalCName(getName(RetVT
)) << "_";
474 Operands
.PrintManglingSuffix(OS
);
476 Operands
.PrintArguments(OS
);
479 OS
<< " default: return 0;\n}\n}\n\n";
482 // Non-variadic return type.
483 OS
<< "unsigned FastEmit_"
484 << getLegalCName(Opcode
) << "_"
485 << getLegalCName(getName(VT
)) << "_";
486 Operands
.PrintManglingSuffix(OS
);
488 if (!Operands
.empty())
490 Operands
.PrintParameters(OS
);
493 OS
<< " if (RetVT.SimpleTy != " << getName(RM
.begin()->first
)
494 << ")\n return 0;\n";
496 const PredMap
&PM
= RM
.begin()->second
;
497 bool HasPred
= false;
499 // Emit code for each possible instruction. There may be
500 // multiple if there are subtarget concerns.
501 for (PredMap::const_iterator PI
= PM
.begin(), PE
= PM
.end(); PI
!= PE
;
503 std::string PredicateCheck
= PI
->first
;
504 const InstructionMemo
&Memo
= PI
->second
;
506 if (PredicateCheck
.empty()) {
508 "Multiple instructions match, at least one has "
509 "a predicate and at least one doesn't!");
511 OS
<< " if (" + PredicateCheck
+ ") {\n";
516 for (unsigned i
= 0; i
< Memo
.PhysRegs
->size(); ++i
) {
517 if ((*Memo
.PhysRegs
)[i
] != "")
518 OS
<< " TII.copyRegToReg(*MBB, MBB->end(), "
519 << (*Memo
.PhysRegs
)[i
] << ", Op" << i
<< ", "
520 << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
521 << (*Memo
.PhysRegs
)[i
] << "), "
522 << "MRI.getRegClass(Op" << i
<< "));\n";
525 OS
<< " return FastEmitInst_";
527 if (Memo
.SubRegNo
== (unsigned char)~0) {
528 Operands
.PrintManglingSuffix(OS
, *Memo
.PhysRegs
);
529 OS
<< "(" << InstNS
<< Memo
.Name
<< ", ";
530 OS
<< InstNS
<< Memo
.RC
->getName() << "RegisterClass";
531 if (!Operands
.empty())
533 Operands
.PrintArguments(OS
, *Memo
.PhysRegs
);
536 OS
<< "extractsubreg(RetVT, Op0, ";
537 OS
<< (unsigned)Memo
.SubRegNo
;
545 // Return 0 if none of the predicates were satisfied.
547 OS
<< " return 0;\n";
553 // Emit one function for the opcode that demultiplexes based on the type.
554 OS
<< "unsigned FastEmit_"
555 << getLegalCName(Opcode
) << "_";
556 Operands
.PrintManglingSuffix(OS
);
557 OS
<< "(MVT VT, MVT RetVT";
558 if (!Operands
.empty())
560 Operands
.PrintParameters(OS
);
562 OS
<< " switch (VT.SimpleTy) {\n";
563 for (TypeRetPredMap::const_iterator TI
= TM
.begin(), TE
= TM
.end();
565 MVT::SimpleValueType VT
= TI
->first
;
566 std::string TypeName
= getName(VT
);
567 OS
<< " case " << TypeName
<< ": return FastEmit_"
568 << getLegalCName(Opcode
) << "_" << getLegalCName(TypeName
) << "_";
569 Operands
.PrintManglingSuffix(OS
);
571 if (!Operands
.empty())
573 Operands
.PrintArguments(OS
);
576 OS
<< " default: return 0;\n";
582 OS
<< "// Top-level FastEmit function.\n";
585 // Emit one function for the operand signature that demultiplexes based
586 // on opcode and type.
587 OS
<< "unsigned FastEmit_";
588 Operands
.PrintManglingSuffix(OS
);
589 OS
<< "(MVT VT, MVT RetVT, ISD::NodeType Opcode";
590 if (!Operands
.empty())
592 Operands
.PrintParameters(OS
);
594 OS
<< " switch (Opcode) {\n";
595 for (OpcodeTypeRetPredMap::const_iterator I
= OTM
.begin(), E
= OTM
.end();
597 const std::string
&Opcode
= I
->first
;
599 OS
<< " case " << Opcode
<< ": return FastEmit_"
600 << getLegalCName(Opcode
) << "_";
601 Operands
.PrintManglingSuffix(OS
);
603 if (!Operands
.empty())
605 Operands
.PrintArguments(OS
);
608 OS
<< " default: return 0;\n";
615 void FastISelEmitter::run(raw_ostream
&OS
) {
616 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
618 // Determine the target's namespace name.
619 std::string InstNS
= Target
.getInstNamespace() + "::";
620 assert(InstNS
.size() > 2 && "Can't determine target-specific namespace!");
622 EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
623 Target
.getName() + " target", OS
);
625 FastISelMap
F(InstNS
);
626 F
.CollectPatterns(CGP
);
627 F
.PrintFunctionDefinitions(OS
);
630 FastISelEmitter::FastISelEmitter(RecordKeeper
&R
)