1 ///===- FastISelEmitter.cpp - Generate an instruction selector -------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This tablegen backend emits code for use by the "fast" instruction
10 // selection algorithm. See the comments at the top of
11 // lib/CodeGen/SelectionDAG/FastISel.cpp for background.
13 // This file scans through the target's tablegen instruction-info files
14 // and extracts instructions with obvious-looking patterns, and it emits
15 // code to look up these instructions by type and operator.
17 //===----------------------------------------------------------------------===//
19 #include "CodeGenDAGPatterns.h"
20 #include "CodeGenInstruction.h"
21 #include "CodeGenRegisters.h"
22 #include "CodeGenTarget.h"
23 #include "InfoByHwMode.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
28 #include "llvm/TableGen/TableGenBackend.h"
34 /// InstructionMemo - This class holds additional information about an
35 /// instruction needed to emit code for it.
38 struct InstructionMemo
{
40 const CodeGenRegisterClass
*RC
;
42 std::vector
<std::string
> PhysRegs
;
43 std::string PredicateCheck
;
45 InstructionMemo(StringRef Name
, const CodeGenRegisterClass
*RC
,
46 std::string SubRegNo
, std::vector
<std::string
> PhysRegs
,
47 std::string PredicateCheck
)
48 : Name(Name
), RC(RC
), SubRegNo(std::move(SubRegNo
)),
49 PhysRegs(std::move(PhysRegs
)),
50 PredicateCheck(std::move(PredicateCheck
)) {}
52 // Make sure we do not copy InstructionMemo.
53 InstructionMemo(const InstructionMemo
&Other
) = delete;
54 InstructionMemo(InstructionMemo
&&Other
) = default;
56 } // End anonymous namespace
58 /// ImmPredicateSet - This uniques predicates (represented as a string) and
59 /// gives them unique (small) integer ID's that start at 0.
61 class ImmPredicateSet
{
62 DenseMap
<TreePattern
*, unsigned> ImmIDs
;
63 std::vector
<TreePredicateFn
> PredsByName
;
66 unsigned getIDFor(TreePredicateFn Pred
) {
67 unsigned &Entry
= ImmIDs
[Pred
.getOrigPatFragRecord()];
69 PredsByName
.push_back(Pred
);
70 Entry
= PredsByName
.size();
75 const TreePredicateFn
&getPredicate(unsigned i
) {
76 assert(i
< PredsByName
.size());
77 return PredsByName
[i
];
80 typedef std::vector
<TreePredicateFn
>::const_iterator iterator
;
81 iterator
begin() const { return PredsByName
.begin(); }
82 iterator
end() const { return PredsByName
.end(); }
85 } // End anonymous namespace
87 /// OperandsSignature - This class holds a description of a list of operand
88 /// types. It has utility methods for emitting text based on the operands.
91 struct OperandsSignature
{
93 enum { OK_Reg
, OK_FP
, OK_Imm
, OK_Invalid
= -1 };
97 OpKind() : Repr(OK_Invalid
) {}
99 bool operator<(OpKind RHS
) const { return Repr
< RHS
.Repr
; }
100 bool operator==(OpKind RHS
) const { return Repr
== RHS
.Repr
; }
102 static OpKind
getReg() { OpKind K
; K
.Repr
= OK_Reg
; return K
; }
103 static OpKind
getFP() { OpKind K
; K
.Repr
= OK_FP
; return K
; }
104 static OpKind
getImm(unsigned V
) {
105 assert((unsigned)OK_Imm
+V
< 128 &&
106 "Too many integer predicates for the 'Repr' char");
107 OpKind K
; K
.Repr
= OK_Imm
+V
; return K
;
110 bool isReg() const { return Repr
== OK_Reg
; }
111 bool isFP() const { return Repr
== OK_FP
; }
112 bool isImm() const { return Repr
>= OK_Imm
; }
114 unsigned getImmCode() const { assert(isImm()); return Repr
-OK_Imm
; }
116 void printManglingSuffix(raw_ostream
&OS
, ImmPredicateSet
&ImmPredicates
,
117 bool StripImmCodes
) const {
125 if (unsigned Code
= getImmCode())
126 OS
<< "_" << ImmPredicates
.getPredicate(Code
-1).getFnName();
132 SmallVector
<OpKind
, 3> Operands
;
134 bool operator<(const OperandsSignature
&O
) const {
135 return Operands
< O
.Operands
;
137 bool operator==(const OperandsSignature
&O
) const {
138 return Operands
== O
.Operands
;
141 bool empty() const { return Operands
.empty(); }
143 bool hasAnyImmediateCodes() const {
144 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
)
145 if (Operands
[i
].isImm() && Operands
[i
].getImmCode() != 0)
150 /// getWithoutImmCodes - Return a copy of this with any immediate codes forced
152 OperandsSignature
getWithoutImmCodes() const {
153 OperandsSignature Result
;
154 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
)
155 if (!Operands
[i
].isImm())
156 Result
.Operands
.push_back(Operands
[i
]);
158 Result
.Operands
.push_back(OpKind::getImm(0));
162 void emitImmediatePredicate(raw_ostream
&OS
, ImmPredicateSet
&ImmPredicates
) {
163 bool EmittedAnything
= false;
164 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
165 if (!Operands
[i
].isImm()) continue;
167 unsigned Code
= Operands
[i
].getImmCode();
168 if (Code
== 0) continue;
173 TreePredicateFn PredFn
= ImmPredicates
.getPredicate(Code
-1);
175 // Emit the type check.
176 TreePattern
*TP
= PredFn
.getOrigPatFragRecord();
177 ValueTypeByHwMode VVT
= TP
->getTree(0)->getType(0);
178 assert(VVT
.isSimple() &&
179 "Cannot use variable value types with fast isel");
180 OS
<< "VT == " << getEnumName(VVT
.getSimple().SimpleTy
) << " && ";
182 OS
<< PredFn
.getFnName() << "(imm" << i
<<')';
183 EmittedAnything
= true;
187 /// initialize - Examine the given pattern and initialize the contents
188 /// of the Operands array accordingly. Return true if all the operands
189 /// are supported, false otherwise.
191 bool initialize(TreePatternNode
*InstPatNode
, const CodeGenTarget
&Target
,
192 MVT::SimpleValueType VT
,
193 ImmPredicateSet
&ImmediatePredicates
,
194 const CodeGenRegisterClass
*OrigDstRC
) {
195 if (InstPatNode
->isLeaf())
198 if (InstPatNode
->getOperator()->getName() == "imm") {
199 Operands
.push_back(OpKind::getImm(0));
203 if (InstPatNode
->getOperator()->getName() == "fpimm") {
204 Operands
.push_back(OpKind::getFP());
208 const CodeGenRegisterClass
*DstRC
= nullptr;
210 for (unsigned i
= 0, e
= InstPatNode
->getNumChildren(); i
!= e
; ++i
) {
211 TreePatternNode
*Op
= InstPatNode
->getChild(i
);
213 // Handle imm operands specially.
214 if (!Op
->isLeaf() && Op
->getOperator()->getName() == "imm") {
216 if (!Op
->getPredicateCalls().empty()) {
217 TreePredicateFn PredFn
= Op
->getPredicateCalls()[0].Fn
;
218 // If there is more than one predicate weighing in on this operand
219 // then we don't handle it. This doesn't typically happen for
220 // immediates anyway.
221 if (Op
->getPredicateCalls().size() > 1 ||
222 !PredFn
.isImmediatePattern() || PredFn
.usesOperands())
224 // Ignore any instruction with 'FastIselShouldIgnore', these are
225 // not needed and just bloat the fast instruction selector. For
226 // example, X86 doesn't need to generate code to match ADD16ri8 since
227 // ADD16ri will do just fine.
228 Record
*Rec
= PredFn
.getOrigPatFragRecord()->getRecord();
229 if (Rec
->getValueAsBit("FastIselShouldIgnore"))
232 PredNo
= ImmediatePredicates
.getIDFor(PredFn
)+1;
235 Operands
.push_back(OpKind::getImm(PredNo
));
240 // For now, filter out any operand with a predicate.
241 // For now, filter out any operand with multiple values.
242 if (!Op
->getPredicateCalls().empty() || Op
->getNumTypes() != 1)
246 if (Op
->getOperator()->getName() == "fpimm") {
247 Operands
.push_back(OpKind::getFP());
250 // For now, ignore other non-leaf nodes.
254 assert(Op
->hasConcreteType(0) && "Type infererence not done?");
256 // For now, all the operands must have the same type (if they aren't
257 // immediates). Note that this causes us to reject variable sized shifts
259 if (Op
->getSimpleType(0) != VT
)
262 DefInit
*OpDI
= dyn_cast
<DefInit
>(Op
->getLeafValue());
265 Record
*OpLeafRec
= OpDI
->getDef();
267 // For now, the only other thing we accept is register operands.
268 const CodeGenRegisterClass
*RC
= nullptr;
269 if (OpLeafRec
->isSubClassOf("RegisterOperand"))
270 OpLeafRec
= OpLeafRec
->getValueAsDef("RegClass");
271 if (OpLeafRec
->isSubClassOf("RegisterClass"))
272 RC
= &Target
.getRegisterClass(OpLeafRec
);
273 else if (OpLeafRec
->isSubClassOf("Register"))
274 RC
= Target
.getRegBank().getRegClassForRegister(OpLeafRec
);
275 else if (OpLeafRec
->isSubClassOf("ValueType")) {
280 // For now, this needs to be a register class of some sort.
284 // For now, all the operands must have the same register class or be
285 // a strict subclass of the destination.
287 if (DstRC
!= RC
&& !DstRC
->hasSubClass(RC
))
291 Operands
.push_back(OpKind::getReg());
296 void PrintParameters(raw_ostream
&OS
) const {
298 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
300 if (Operands
[i
].isReg()) {
301 OS
<< "unsigned Op" << i
;
302 } else if (Operands
[i
].isImm()) {
303 OS
<< "uint64_t imm" << i
;
304 } else if (Operands
[i
].isFP()) {
305 OS
<< "const ConstantFP *f" << i
;
307 llvm_unreachable("Unknown operand kind!");
312 void PrintArguments(raw_ostream
&OS
,
313 const std::vector
<std::string
> &PR
) const {
314 assert(PR
.size() == Operands
.size());
316 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
318 // Implicit physical register operand.
322 if (Operands
[i
].isReg()) {
324 } else if (Operands
[i
].isImm()) {
326 } else if (Operands
[i
].isFP()) {
329 llvm_unreachable("Unknown operand kind!");
334 void PrintArguments(raw_ostream
&OS
) const {
336 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
338 if (Operands
[i
].isReg()) {
340 } else if (Operands
[i
].isImm()) {
342 } else if (Operands
[i
].isFP()) {
345 llvm_unreachable("Unknown operand kind!");
351 void PrintManglingSuffix(raw_ostream
&OS
, const std::vector
<std::string
> &PR
,
352 ImmPredicateSet
&ImmPredicates
,
353 bool StripImmCodes
= false) const {
354 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
) {
356 // Implicit physical register operand. e.g. Instruction::Mul expect to
357 // select to a binary op. On x86, mul may take a single operand with
358 // the other operand being implicit. We must emit something that looks
359 // like a binary instruction except for the very inner fastEmitInst_*
362 Operands
[i
].printManglingSuffix(OS
, ImmPredicates
, StripImmCodes
);
366 void PrintManglingSuffix(raw_ostream
&OS
, ImmPredicateSet
&ImmPredicates
,
367 bool StripImmCodes
= false) const {
368 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
)
369 Operands
[i
].printManglingSuffix(OS
, ImmPredicates
, StripImmCodes
);
372 } // End anonymous namespace
376 // A multimap is needed instead of a "plain" map because the key is
377 // the instruction's complexity (an int) and they are not unique.
378 typedef std::multimap
<int, InstructionMemo
> PredMap
;
379 typedef std::map
<MVT::SimpleValueType
, PredMap
> RetPredMap
;
380 typedef std::map
<MVT::SimpleValueType
, RetPredMap
> TypeRetPredMap
;
381 typedef std::map
<std::string
, TypeRetPredMap
> OpcodeTypeRetPredMap
;
382 typedef std::map
<OperandsSignature
, OpcodeTypeRetPredMap
>
383 OperandsOpcodeTypeRetPredMap
;
385 OperandsOpcodeTypeRetPredMap SimplePatterns
;
387 // This is used to check that there are no duplicate predicates
388 std::set
<std::tuple
<OperandsSignature
, std::string
, MVT::SimpleValueType
,
389 MVT::SimpleValueType
, std::string
>>
392 std::map
<OperandsSignature
, std::vector
<OperandsSignature
> >
393 SignaturesWithConstantForms
;
396 ImmPredicateSet ImmediatePredicates
;
398 explicit FastISelMap(StringRef InstNS
);
400 void collectPatterns(CodeGenDAGPatterns
&CGP
);
401 void printImmediatePredicates(raw_ostream
&OS
);
402 void printFunctionDefinitions(raw_ostream
&OS
);
404 void emitInstructionCode(raw_ostream
&OS
,
405 const OperandsSignature
&Operands
,
407 const std::string
&RetVTName
);
409 } // End anonymous namespace
411 static std::string
getOpcodeName(Record
*Op
, CodeGenDAGPatterns
&CGP
) {
412 return std::string(CGP
.getSDNodeInfo(Op
).getEnumName());
415 static std::string
getLegalCName(std::string OpName
) {
416 std::string::size_type pos
= OpName
.find("::");
417 if (pos
!= std::string::npos
)
418 OpName
.replace(pos
, 2, "_");
422 FastISelMap::FastISelMap(StringRef instns
) : InstNS(instns
) {}
424 static std::string
PhyRegForNode(TreePatternNode
*Op
,
425 const CodeGenTarget
&Target
) {
431 Record
*OpLeafRec
= cast
<DefInit
>(Op
->getLeafValue())->getDef();
432 if (!OpLeafRec
->isSubClassOf("Register"))
435 PhysReg
+= cast
<StringInit
>(OpLeafRec
->getValue("Namespace")->getValue())
438 PhysReg
+= Target
.getRegBank().getReg(OpLeafRec
)->getName();
442 void FastISelMap::collectPatterns(CodeGenDAGPatterns
&CGP
) {
443 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
445 // Scan through all the patterns and record the simple ones.
446 for (CodeGenDAGPatterns::ptm_iterator I
= CGP
.ptm_begin(),
447 E
= CGP
.ptm_end(); I
!= E
; ++I
) {
448 const PatternToMatch
&Pattern
= *I
;
450 // For now, just look at Instructions, so that we don't have to worry
451 // about emitting multiple instructions for a pattern.
452 TreePatternNode
*Dst
= Pattern
.getDstPattern();
453 if (Dst
->isLeaf()) continue;
454 Record
*Op
= Dst
->getOperator();
455 if (!Op
->isSubClassOf("Instruction"))
457 CodeGenInstruction
&II
= CGP
.getTargetInfo().getInstruction(Op
);
458 if (II
.Operands
.empty())
461 // Allow instructions to be marked as unavailable for FastISel for
462 // certain cases, i.e. an ISA has two 'and' instruction which differ
463 // by what registers they can use but are otherwise identical for
465 if (II
.FastISelShouldIgnore
)
468 // For now, ignore multi-instruction patterns.
469 bool MultiInsts
= false;
470 for (unsigned i
= 0, e
= Dst
->getNumChildren(); i
!= e
; ++i
) {
471 TreePatternNode
*ChildOp
= Dst
->getChild(i
);
472 if (ChildOp
->isLeaf())
474 if (ChildOp
->getOperator()->isSubClassOf("Instruction")) {
482 // For now, ignore instructions where the first operand is not an
484 const CodeGenRegisterClass
*DstRC
= nullptr;
485 std::string SubRegNo
;
486 if (Op
->getName() != "EXTRACT_SUBREG") {
487 Record
*Op0Rec
= II
.Operands
[0].Rec
;
488 if (Op0Rec
->isSubClassOf("RegisterOperand"))
489 Op0Rec
= Op0Rec
->getValueAsDef("RegClass");
490 if (!Op0Rec
->isSubClassOf("RegisterClass"))
492 DstRC
= &Target
.getRegisterClass(Op0Rec
);
496 // If this isn't a leaf, then continue since the register classes are
497 // a bit too complicated for now.
498 if (!Dst
->getChild(1)->isLeaf()) continue;
500 DefInit
*SR
= dyn_cast
<DefInit
>(Dst
->getChild(1)->getLeafValue());
502 SubRegNo
= getQualifiedName(SR
->getDef());
504 SubRegNo
= Dst
->getChild(1)->getLeafValue()->getAsString();
507 // Inspect the pattern.
508 TreePatternNode
*InstPatNode
= Pattern
.getSrcPattern();
509 if (!InstPatNode
) continue;
510 if (InstPatNode
->isLeaf()) continue;
512 // Ignore multiple result nodes for now.
513 if (InstPatNode
->getNumTypes() > 1) continue;
515 Record
*InstPatOp
= InstPatNode
->getOperator();
516 std::string OpcodeName
= getOpcodeName(InstPatOp
, CGP
);
517 MVT::SimpleValueType RetVT
= MVT::isVoid
;
518 if (InstPatNode
->getNumTypes()) RetVT
= InstPatNode
->getSimpleType(0);
519 MVT::SimpleValueType VT
= RetVT
;
520 if (InstPatNode
->getNumChildren()) {
521 assert(InstPatNode
->getChild(0)->getNumTypes() == 1);
522 VT
= InstPatNode
->getChild(0)->getSimpleType(0);
525 // For now, filter out any instructions with predicates.
526 if (!InstPatNode
->getPredicateCalls().empty())
529 // Check all the operands.
530 OperandsSignature Operands
;
531 if (!Operands
.initialize(InstPatNode
, Target
, VT
, ImmediatePredicates
,
535 std::vector
<std::string
> PhysRegInputs
;
536 if (InstPatNode
->getOperator()->getName() == "imm" ||
537 InstPatNode
->getOperator()->getName() == "fpimm")
538 PhysRegInputs
.push_back("");
540 // Compute the PhysRegs used by the given pattern, and check that
541 // the mapping from the src to dst patterns is simple.
542 bool FoundNonSimplePattern
= false;
543 unsigned DstIndex
= 0;
544 for (unsigned i
= 0, e
= InstPatNode
->getNumChildren(); i
!= e
; ++i
) {
545 std::string PhysReg
= PhyRegForNode(InstPatNode
->getChild(i
), Target
);
546 if (PhysReg
.empty()) {
547 if (DstIndex
>= Dst
->getNumChildren() ||
548 Dst
->getChild(DstIndex
)->getName() !=
549 InstPatNode
->getChild(i
)->getName()) {
550 FoundNonSimplePattern
= true;
556 PhysRegInputs
.push_back(PhysReg
);
559 if (Op
->getName() != "EXTRACT_SUBREG" && DstIndex
< Dst
->getNumChildren())
560 FoundNonSimplePattern
= true;
562 if (FoundNonSimplePattern
)
566 // Check if the operands match one of the patterns handled by FastISel.
567 std::string ManglingSuffix
;
568 raw_string_ostream
SuffixOS(ManglingSuffix
);
569 Operands
.PrintManglingSuffix(SuffixOS
, ImmediatePredicates
, true);
570 if (!StringSwitch
<bool>(ManglingSuffix
)
571 .Cases("", "r", "rr", "ri", "i", "f", true)
575 // Get the predicate that guards this pattern.
576 std::string PredicateCheck
= Pattern
.getPredicateCheck();
578 // Ok, we found a pattern that we can handle. Remember it.
579 InstructionMemo
Memo(
580 Pattern
.getDstPattern()->getOperator()->getName(),
587 int complexity
= Pattern
.getPatternComplexity(CGP
);
589 auto inserted_simple_pattern
= SimplePatternsCheck
.insert(
590 std::make_tuple(Operands
, OpcodeName
, VT
, RetVT
, PredicateCheck
));
591 if (!inserted_simple_pattern
.second
) {
592 PrintFatalError(Pattern
.getSrcRecord()->getLoc(),
593 "Duplicate predicate in FastISel table!");
596 // Note: Instructions with the same complexity will appear in the order
597 // that they are encountered.
598 SimplePatterns
[Operands
][OpcodeName
][VT
][RetVT
].emplace(complexity
,
601 // If any of the operands were immediates with predicates on them, strip
602 // them down to a signature that doesn't have predicates so that we can
603 // associate them with the stripped predicate version.
604 if (Operands
.hasAnyImmediateCodes()) {
605 SignaturesWithConstantForms
[Operands
.getWithoutImmCodes()]
606 .push_back(Operands
);
611 void FastISelMap::printImmediatePredicates(raw_ostream
&OS
) {
612 if (ImmediatePredicates
.begin() == ImmediatePredicates
.end())
615 OS
<< "\n// FastEmit Immediate Predicate functions.\n";
616 for (auto ImmediatePredicate
: ImmediatePredicates
) {
617 OS
<< "static bool " << ImmediatePredicate
.getFnName()
618 << "(int64_t Imm) {\n";
619 OS
<< ImmediatePredicate
.getImmediatePredicateCode() << "\n}\n";
625 void FastISelMap::emitInstructionCode(raw_ostream
&OS
,
626 const OperandsSignature
&Operands
,
628 const std::string
&RetVTName
) {
629 // Emit code for each possible instruction. There may be
630 // multiple if there are subtarget concerns. A reverse iterator
631 // is used to produce the ones with highest complexity first.
633 bool OneHadNoPredicate
= false;
634 for (PredMap::const_reverse_iterator PI
= PM
.rbegin(), PE
= PM
.rend();
636 const InstructionMemo
&Memo
= PI
->second
;
637 std::string PredicateCheck
= Memo
.PredicateCheck
;
639 if (PredicateCheck
.empty()) {
640 assert(!OneHadNoPredicate
&&
641 "Multiple instructions match and more than one had "
643 OneHadNoPredicate
= true;
645 if (OneHadNoPredicate
) {
646 PrintFatalError("Multiple instructions match and one with no "
647 "predicate came before one with a predicate! "
648 "name:" + Memo
.Name
+ " predicate: " + PredicateCheck
);
650 OS
<< " if (" + PredicateCheck
+ ") {\n";
654 for (unsigned i
= 0; i
< Memo
.PhysRegs
.size(); ++i
) {
655 if (Memo
.PhysRegs
[i
] != "")
656 OS
<< " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, "
657 << "TII.get(TargetOpcode::COPY), " << Memo
.PhysRegs
[i
]
658 << ").addReg(Op" << i
<< ");\n";
661 OS
<< " return fastEmitInst_";
662 if (Memo
.SubRegNo
.empty()) {
663 Operands
.PrintManglingSuffix(OS
, Memo
.PhysRegs
, ImmediatePredicates
,
665 OS
<< "(" << InstNS
<< "::" << Memo
.Name
<< ", ";
666 OS
<< "&" << InstNS
<< "::" << Memo
.RC
->getName() << "RegClass";
667 if (!Operands
.empty())
669 Operands
.PrintArguments(OS
, Memo
.PhysRegs
);
672 OS
<< "extractsubreg(" << RetVTName
673 << ", Op0, " << Memo
.SubRegNo
<< ");\n";
676 if (!PredicateCheck
.empty()) {
680 // Return 0 if all of the possibilities had predicates but none
682 if (!OneHadNoPredicate
)
683 OS
<< " return 0;\n";
689 void FastISelMap::printFunctionDefinitions(raw_ostream
&OS
) {
690 // Now emit code for all the patterns that we collected.
691 for (const auto &SimplePattern
: SimplePatterns
) {
692 const OperandsSignature
&Operands
= SimplePattern
.first
;
693 const OpcodeTypeRetPredMap
&OTM
= SimplePattern
.second
;
695 for (const auto &I
: OTM
) {
696 const std::string
&Opcode
= I
.first
;
697 const TypeRetPredMap
&TM
= I
.second
;
699 OS
<< "// FastEmit functions for " << Opcode
<< ".\n";
702 // Emit one function for each opcode,type pair.
703 for (const auto &TI
: TM
) {
704 MVT::SimpleValueType VT
= TI
.first
;
705 const RetPredMap
&RM
= TI
.second
;
706 if (RM
.size() != 1) {
707 for (const auto &RI
: RM
) {
708 MVT::SimpleValueType RetVT
= RI
.first
;
709 const PredMap
&PM
= RI
.second
;
711 OS
<< "unsigned fastEmit_" << getLegalCName(Opcode
) << "_"
712 << getLegalCName(std::string(getName(VT
))) << "_"
713 << getLegalCName(std::string(getName(RetVT
))) << "_";
714 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
716 Operands
.PrintParameters(OS
);
719 emitInstructionCode(OS
, Operands
, PM
, std::string(getName(RetVT
)));
722 // Emit one function for the type that demultiplexes on return type.
723 OS
<< "unsigned fastEmit_" << getLegalCName(Opcode
) << "_"
724 << getLegalCName(std::string(getName(VT
))) << "_";
725 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
727 if (!Operands
.empty())
729 Operands
.PrintParameters(OS
);
730 OS
<< ") {\nswitch (RetVT.SimpleTy) {\n";
731 for (const auto &RI
: RM
) {
732 MVT::SimpleValueType RetVT
= RI
.first
;
733 OS
<< " case " << getName(RetVT
) << ": return fastEmit_"
734 << getLegalCName(Opcode
) << "_"
735 << getLegalCName(std::string(getName(VT
))) << "_"
736 << getLegalCName(std::string(getName(RetVT
))) << "_";
737 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
739 Operands
.PrintArguments(OS
);
742 OS
<< " default: return 0;\n}\n}\n\n";
745 // Non-variadic return type.
746 OS
<< "unsigned fastEmit_" << getLegalCName(Opcode
) << "_"
747 << getLegalCName(std::string(getName(VT
))) << "_";
748 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
750 if (!Operands
.empty())
752 Operands
.PrintParameters(OS
);
755 OS
<< " if (RetVT.SimpleTy != " << getName(RM
.begin()->first
)
756 << ")\n return 0;\n";
758 const PredMap
&PM
= RM
.begin()->second
;
760 emitInstructionCode(OS
, Operands
, PM
, "RetVT");
764 // Emit one function for the opcode that demultiplexes based on the type.
765 OS
<< "unsigned fastEmit_"
766 << getLegalCName(Opcode
) << "_";
767 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
768 OS
<< "(MVT VT, MVT RetVT";
769 if (!Operands
.empty())
771 Operands
.PrintParameters(OS
);
773 OS
<< " switch (VT.SimpleTy) {\n";
774 for (const auto &TI
: TM
) {
775 MVT::SimpleValueType VT
= TI
.first
;
776 std::string TypeName
= std::string(getName(VT
));
777 OS
<< " case " << TypeName
<< ": return fastEmit_"
778 << getLegalCName(Opcode
) << "_" << getLegalCName(TypeName
) << "_";
779 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
781 if (!Operands
.empty())
783 Operands
.PrintArguments(OS
);
786 OS
<< " default: return 0;\n";
792 OS
<< "// Top-level FastEmit function.\n";
795 // Emit one function for the operand signature that demultiplexes based
796 // on opcode and type.
797 OS
<< "unsigned fastEmit_";
798 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
799 OS
<< "(MVT VT, MVT RetVT, unsigned Opcode";
800 if (!Operands
.empty())
802 Operands
.PrintParameters(OS
);
804 if (!Operands
.hasAnyImmediateCodes())
808 // If there are any forms of this signature available that operate on
809 // constrained forms of the immediate (e.g., 32-bit sext immediate in a
810 // 64-bit operand), check them first.
812 std::map
<OperandsSignature
, std::vector
<OperandsSignature
> >::iterator MI
813 = SignaturesWithConstantForms
.find(Operands
);
814 if (MI
!= SignaturesWithConstantForms
.end()) {
815 // Unique any duplicates out of the list.
816 llvm::sort(MI
->second
);
817 MI
->second
.erase(std::unique(MI
->second
.begin(), MI
->second
.end()),
820 // Check each in order it was seen. It would be nice to have a good
821 // relative ordering between them, but we're not going for optimality
823 for (unsigned i
= 0, e
= MI
->second
.size(); i
!= e
; ++i
) {
825 MI
->second
[i
].emitImmediatePredicate(OS
, ImmediatePredicates
);
826 OS
<< ")\n if (unsigned Reg = fastEmit_";
827 MI
->second
[i
].PrintManglingSuffix(OS
, ImmediatePredicates
);
828 OS
<< "(VT, RetVT, Opcode";
829 if (!MI
->second
[i
].empty())
831 MI
->second
[i
].PrintArguments(OS
);
832 OS
<< "))\n return Reg;\n\n";
835 // Done with this, remove it.
836 SignaturesWithConstantForms
.erase(MI
);
839 OS
<< " switch (Opcode) {\n";
840 for (const auto &I
: OTM
) {
841 const std::string
&Opcode
= I
.first
;
843 OS
<< " case " << Opcode
<< ": return fastEmit_"
844 << getLegalCName(Opcode
) << "_";
845 Operands
.PrintManglingSuffix(OS
, ImmediatePredicates
);
847 if (!Operands
.empty())
849 Operands
.PrintArguments(OS
);
852 OS
<< " default: return 0;\n";
858 // TODO: SignaturesWithConstantForms should be empty here.
861 static void EmitFastISel(RecordKeeper
&RK
, raw_ostream
&OS
) {
862 CodeGenDAGPatterns
CGP(RK
);
863 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
864 emitSourceFileHeader("\"Fast\" Instruction Selector for the " +
865 Target
.getName().str() + " target", OS
);
867 // Determine the target's namespace name.
868 StringRef InstNS
= Target
.getInstNamespace();
869 assert(!InstNS
.empty() && "Can't determine target-specific namespace!");
871 FastISelMap
F(InstNS
);
872 F
.collectPatterns(CGP
);
873 F
.printImmediatePredicates(OS
);
874 F
.printFunctionDefinitions(OS
);
877 static TableGen::Emitter::Opt
X("gen-fast-isel", EmitFastISel
,
878 "Generate a \"fast\" instruction selector");