1 //===- GlobalISelEmitter.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 //===----------------------------------------------------------------------===//
10 /// This tablegen backend emits code for use by the GlobalISel instruction
11 /// selector. See include/llvm/Target/GlobalISel/Target.td.
13 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14 /// backend, filters out the ones that are unsupported, maps
15 /// SelectionDAG-specific constructs to their GlobalISel counterpart
16 /// (when applicable: MVT to LLT; SDNode to generic Instruction).
18 /// Not all patterns are supported: pass the tablegen invocation
19 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
22 /// The generated file defines a single method:
23 /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24 /// intended to be used in InstructionSelector::select as the first-step
25 /// selector for the patterns that don't require complex C++.
27 /// FIXME: We'll probably want to eventually define a base
28 /// "TargetGenInstructionSelector" class.
30 //===----------------------------------------------------------------------===//
32 #include "CodeGenDAGPatterns.h"
33 #include "CodeGenInstruction.h"
34 #include "CodeGenIntrinsics.h"
35 #include "CodeGenRegisters.h"
36 #include "CodeGenTarget.h"
37 #include "GlobalISelMatchTable.h"
38 #include "GlobalISelMatchTableExecutorEmitter.h"
39 #include "InfoByHwMode.h"
40 #include "SubtargetFeatureInfo.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/CodeGen/LowLevelType.h"
43 #include "llvm/CodeGen/MachineValueType.h"
44 #include "llvm/Support/CodeGenCoverage.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Error.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/ScopedPrinter.h"
49 #include "llvm/TableGen/Error.h"
50 #include "llvm/TableGen/Record.h"
51 #include "llvm/TableGen/TableGenBackend.h"
56 using namespace llvm::gi
;
58 using action_iterator
= RuleMatcher::action_iterator
;
60 #define DEBUG_TYPE "gisel-emitter"
62 STATISTIC(NumPatternTotal
, "Total number of patterns");
63 STATISTIC(NumPatternImported
, "Number of patterns imported from SelectionDAG");
64 STATISTIC(NumPatternImportsSkipped
, "Number of SelectionDAG imports skipped");
65 STATISTIC(NumPatternsTested
,
66 "Number of patterns executed according to coverage information");
68 cl::OptionCategory
GlobalISelEmitterCat("Options for -gen-global-isel");
70 static cl::opt
<bool> WarnOnSkippedPatterns(
71 "warn-on-skipped-patterns",
72 cl::desc("Explain why a pattern was skipped for inclusion "
73 "in the GlobalISel selector"),
74 cl::init(false), cl::cat(GlobalISelEmitterCat
));
76 static cl::opt
<bool> GenerateCoverage(
77 "instrument-gisel-coverage",
78 cl::desc("Generate coverage instrumentation for GlobalISel"),
79 cl::init(false), cl::cat(GlobalISelEmitterCat
));
81 static cl::opt
<std::string
> UseCoverageFile(
82 "gisel-coverage-file", cl::init(""),
83 cl::desc("Specify file to retrieve coverage information from"),
84 cl::cat(GlobalISelEmitterCat
));
86 static cl::opt
<bool> OptimizeMatchTable(
87 "optimize-match-table",
88 cl::desc("Generate an optimized version of the match table"),
89 cl::init(true), cl::cat(GlobalISelEmitterCat
));
93 static std::string
explainPredicates(const TreePatternNode
*N
) {
94 std::string Explanation
;
95 StringRef Separator
= "";
96 for (const TreePredicateCall
&Call
: N
->getPredicateCalls()) {
97 const TreePredicateFn
&P
= Call
.Fn
;
99 (Separator
+ P
.getOrigPatFragRecord()->getRecord()->getName()).str();
102 if (P
.isAlwaysTrue())
103 Explanation
+= " always-true";
104 if (P
.isImmediatePattern())
105 Explanation
+= " immediate";
108 Explanation
+= " unindexed";
110 if (P
.isNonExtLoad())
111 Explanation
+= " non-extload";
112 if (P
.isAnyExtLoad())
113 Explanation
+= " extload";
114 if (P
.isSignExtLoad())
115 Explanation
+= " sextload";
116 if (P
.isZeroExtLoad())
117 Explanation
+= " zextload";
119 if (P
.isNonTruncStore())
120 Explanation
+= " non-truncstore";
121 if (P
.isTruncStore())
122 Explanation
+= " truncstore";
124 if (Record
*VT
= P
.getMemoryVT())
125 Explanation
+= (" MemVT=" + VT
->getName()).str();
126 if (Record
*VT
= P
.getScalarMemoryVT())
127 Explanation
+= (" ScalarVT(MemVT)=" + VT
->getName()).str();
129 if (ListInit
*AddrSpaces
= P
.getAddressSpaces()) {
130 raw_string_ostream
OS(Explanation
);
131 OS
<< " AddressSpaces=[";
133 StringRef AddrSpaceSeparator
;
134 for (Init
*Val
: AddrSpaces
->getValues()) {
135 IntInit
*IntVal
= dyn_cast
<IntInit
>(Val
);
139 OS
<< AddrSpaceSeparator
<< IntVal
->getValue();
140 AddrSpaceSeparator
= ", ";
146 int64_t MinAlign
= P
.getMinAlignment();
148 Explanation
+= " MinAlign=" + utostr(MinAlign
);
150 if (P
.isAtomicOrderingMonotonic())
151 Explanation
+= " monotonic";
152 if (P
.isAtomicOrderingAcquire())
153 Explanation
+= " acquire";
154 if (P
.isAtomicOrderingRelease())
155 Explanation
+= " release";
156 if (P
.isAtomicOrderingAcquireRelease())
157 Explanation
+= " acq_rel";
158 if (P
.isAtomicOrderingSequentiallyConsistent())
159 Explanation
+= " seq_cst";
160 if (P
.isAtomicOrderingAcquireOrStronger())
161 Explanation
+= " >=acquire";
162 if (P
.isAtomicOrderingWeakerThanAcquire())
163 Explanation
+= " <acquire";
164 if (P
.isAtomicOrderingReleaseOrStronger())
165 Explanation
+= " >=release";
166 if (P
.isAtomicOrderingWeakerThanRelease())
167 Explanation
+= " <release";
172 std::string
explainOperator(Record
*Operator
) {
173 if (Operator
->isSubClassOf("SDNode"))
174 return (" (" + Operator
->getValueAsString("Opcode") + ")").str();
176 if (Operator
->isSubClassOf("Intrinsic"))
177 return (" (Operator is an Intrinsic, " + Operator
->getName() + ")").str();
179 if (Operator
->isSubClassOf("ComplexPattern"))
180 return (" (Operator is an unmapped ComplexPattern, " + Operator
->getName() +
184 if (Operator
->isSubClassOf("SDNodeXForm"))
185 return (" (Operator is an unmapped SDNodeXForm, " + Operator
->getName() +
189 return (" (Operator " + Operator
->getName() + " not understood)").str();
192 /// Helper function to let the emitter report skip reason error messages.
193 static Error
failedImport(const Twine
&Reason
) {
194 return make_error
<StringError
>(Reason
, inconvertibleErrorCode());
197 static Error
isTrivialOperatorNode(const TreePatternNode
*N
) {
198 std::string Explanation
;
199 std::string Separator
;
201 bool HasUnsupportedPredicate
= false;
202 for (const TreePredicateCall
&Call
: N
->getPredicateCalls()) {
203 const TreePredicateFn
&Predicate
= Call
.Fn
;
205 if (Predicate
.isAlwaysTrue())
208 if (Predicate
.isImmediatePattern())
211 if (Predicate
.hasNoUse())
214 if (Predicate
.isNonExtLoad() || Predicate
.isAnyExtLoad() ||
215 Predicate
.isSignExtLoad() || Predicate
.isZeroExtLoad())
218 if (Predicate
.isNonTruncStore() || Predicate
.isTruncStore())
221 if (Predicate
.isLoad() && Predicate
.getMemoryVT())
224 if (Predicate
.isLoad() || Predicate
.isStore()) {
225 if (Predicate
.isUnindexed())
229 if (Predicate
.isLoad() || Predicate
.isStore() || Predicate
.isAtomic()) {
230 const ListInit
*AddrSpaces
= Predicate
.getAddressSpaces();
231 if (AddrSpaces
&& !AddrSpaces
->empty())
234 if (Predicate
.getMinAlignment() > 0)
238 if (Predicate
.isAtomic() && Predicate
.getMemoryVT())
241 if (Predicate
.isAtomic() &&
242 (Predicate
.isAtomicOrderingMonotonic() ||
243 Predicate
.isAtomicOrderingAcquire() ||
244 Predicate
.isAtomicOrderingRelease() ||
245 Predicate
.isAtomicOrderingAcquireRelease() ||
246 Predicate
.isAtomicOrderingSequentiallyConsistent() ||
247 Predicate
.isAtomicOrderingAcquireOrStronger() ||
248 Predicate
.isAtomicOrderingWeakerThanAcquire() ||
249 Predicate
.isAtomicOrderingReleaseOrStronger() ||
250 Predicate
.isAtomicOrderingWeakerThanRelease()))
253 if (Predicate
.hasGISelPredicateCode())
256 HasUnsupportedPredicate
= true;
257 Explanation
= Separator
+ "Has a predicate (" + explainPredicates(N
) + ")";
259 Explanation
+= (Separator
+ "first-failing:" +
260 Predicate
.getOrigPatFragRecord()->getRecord()->getName())
265 if (!HasUnsupportedPredicate
)
266 return Error::success();
268 return failedImport(Explanation
);
271 static Record
*getInitValueAsRegClass(Init
*V
) {
272 if (DefInit
*VDefInit
= dyn_cast
<DefInit
>(V
)) {
273 if (VDefInit
->getDef()->isSubClassOf("RegisterOperand"))
274 return VDefInit
->getDef()->getValueAsDef("RegClass");
275 if (VDefInit
->getDef()->isSubClassOf("RegisterClass"))
276 return VDefInit
->getDef();
281 static std::string
getScopedName(unsigned Scope
, const std::string
&Name
) {
282 return ("pred:" + Twine(Scope
) + ":" + Name
).str();
285 //===- GlobalISelEmitter class --------------------------------------------===//
287 static Expected
<LLTCodeGen
> getInstResultType(const TreePatternNode
*Dst
) {
288 ArrayRef
<TypeSetByHwMode
> ChildTypes
= Dst
->getExtTypes();
289 if (ChildTypes
.size() != 1)
290 return failedImport("Dst pattern child has multiple results");
292 std::optional
<LLTCodeGen
> MaybeOpTy
;
293 if (ChildTypes
.front().isMachineValueType()) {
294 MaybeOpTy
= MVTToLLT(ChildTypes
.front().getMachineValueType().SimpleTy
);
298 return failedImport("Dst operand has an unsupported type");
302 class GlobalISelEmitter final
: public GlobalISelMatchTableExecutorEmitter
{
304 explicit GlobalISelEmitter(RecordKeeper
&RK
);
306 void emitAdditionalImpl(raw_ostream
&OS
) override
;
308 void emitMIPredicateFns(raw_ostream
&OS
) override
;
309 void emitI64ImmPredicateFns(raw_ostream
&OS
) override
;
310 void emitAPFloatImmPredicateFns(raw_ostream
&OS
) override
;
311 void emitAPIntImmPredicateFns(raw_ostream
&OS
) override
;
312 void emitTestSimplePredicate(raw_ostream
&OS
) override
;
313 void emitRunCustomAction(raw_ostream
&OS
) override
;
315 void postProcessRule(RuleMatcher
&M
);
317 const CodeGenTarget
&getTarget() const override
{ return Target
; }
318 StringRef
getClassName() const override
{ return ClassName
; }
320 void run(raw_ostream
&OS
);
323 std::string ClassName
;
325 const RecordKeeper
&RK
;
326 const CodeGenDAGPatterns CGP
;
327 const CodeGenTarget
&Target
;
328 CodeGenRegBank
&CGRegs
;
330 std::vector
<Record
*> AllPatFrags
;
332 /// Keep track of the equivalence between SDNodes and Instruction by mapping
333 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
334 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
335 /// This is defined using 'GINodeEquiv' in the target description.
336 DenseMap
<Record
*, Record
*> NodeEquivs
;
338 /// Keep track of the equivalence between ComplexPattern's and
339 /// GIComplexOperandMatcher. Map entries are specified by subclassing
340 /// GIComplexPatternEquiv.
341 DenseMap
<const Record
*, const Record
*> ComplexPatternEquivs
;
343 /// Keep track of the equivalence between SDNodeXForm's and
344 /// GICustomOperandRenderer. Map entries are specified by subclassing
345 /// GISDNodeXFormEquiv.
346 DenseMap
<const Record
*, const Record
*> SDNodeXFormEquivs
;
348 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
349 /// This adds compatibility for RuleMatchers to use this for ordering rules.
350 DenseMap
<uint64_t, int> RuleMatcherScores
;
352 // Rule coverage information.
353 std::optional
<CodeGenCoverage
> RuleCoverage
;
355 /// Variables used to help with collecting of named operands for predicates
356 /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
357 /// to the number of named operands that predicate expects. Store locations in
358 /// StoreIdxForName correspond to the order in which operand names appear in
359 /// predicate's argument list.
360 /// When we visit named operand and WaitingForNamedOperands is not zero, add
361 /// matcher that will record operand and decrease counter.
362 unsigned WaitingForNamedOperands
= 0;
363 StringMap
<unsigned> StoreIdxForName
;
365 void gatherOpcodeValues();
366 void gatherTypeIDValues();
367 void gatherNodeEquivs();
369 Record
*findNodeEquiv(Record
*N
) const;
370 const CodeGenInstruction
*getEquivNode(Record
&Equiv
,
371 const TreePatternNode
*N
) const;
373 Error
importRulePredicates(RuleMatcher
&M
, ArrayRef
<Record
*> Predicates
);
374 Expected
<InstructionMatcher
&>
375 createAndImportSelDAGMatcher(RuleMatcher
&Rule
,
376 InstructionMatcher
&InsnMatcher
,
377 const TreePatternNode
*Src
, unsigned &TempOpIdx
);
378 Error
importComplexPatternOperandMatcher(OperandMatcher
&OM
, Record
*R
,
379 unsigned &TempOpIdx
) const;
380 Error
importChildMatcher(RuleMatcher
&Rule
, InstructionMatcher
&InsnMatcher
,
381 const TreePatternNode
*SrcChild
,
382 bool OperandIsAPointer
, bool OperandIsImmArg
,
383 unsigned OpIdx
, unsigned &TempOpIdx
);
385 Expected
<BuildMIAction
&> createAndImportInstructionRenderer(
386 RuleMatcher
&M
, InstructionMatcher
&InsnMatcher
,
387 const TreePatternNode
*Src
, const TreePatternNode
*Dst
);
388 Expected
<action_iterator
> createAndImportSubInstructionRenderer(
389 action_iterator InsertPt
, RuleMatcher
&M
, const TreePatternNode
*Dst
,
390 const TreePatternNode
*Src
, unsigned TempReg
);
391 Expected
<action_iterator
>
392 createInstructionRenderer(action_iterator InsertPt
, RuleMatcher
&M
,
393 const TreePatternNode
*Dst
);
395 Expected
<action_iterator
> importExplicitDefRenderers(
396 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
397 const TreePatternNode
*Src
, const TreePatternNode
*Dst
);
399 Expected
<action_iterator
> importExplicitUseRenderers(
400 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
401 const llvm::TreePatternNode
*Dst
, const TreePatternNode
*Src
);
402 Expected
<action_iterator
> importExplicitUseRenderer(
403 action_iterator InsertPt
, RuleMatcher
&Rule
, BuildMIAction
&DstMIBuilder
,
404 const TreePatternNode
*DstChild
, const TreePatternNode
*Src
);
405 Error
importDefaultOperandRenderers(action_iterator InsertPt
, RuleMatcher
&M
,
406 BuildMIAction
&DstMIBuilder
,
407 DagInit
*DefaultOps
) const;
409 importImplicitDefRenderers(BuildMIAction
&DstMIBuilder
,
410 const std::vector
<Record
*> &ImplicitDefs
) const;
412 /// Analyze pattern \p P, returning a matcher for it if possible.
413 /// Otherwise, return an Error explaining why we don't support it.
414 Expected
<RuleMatcher
> runOnPattern(const PatternToMatch
&P
);
416 void declareSubtargetFeature(Record
*Predicate
);
418 unsigned declareHwModeCheck(StringRef HwModeFeatures
);
420 MatchTable
buildMatchTable(MutableArrayRef
<RuleMatcher
> Rules
, bool Optimize
,
423 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
424 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
425 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
426 /// If no register class is found, return std::nullopt.
427 std::optional
<const CodeGenRegisterClass
*>
428 inferSuperRegisterClassForNode(const TypeSetByHwMode
&Ty
,
429 const TreePatternNode
*SuperRegNode
,
430 const TreePatternNode
*SubRegIdxNode
);
431 std::optional
<CodeGenSubRegIndex
*>
432 inferSubRegIndexForNode(const TreePatternNode
*SubRegIdxNode
);
434 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
435 /// Return std::nullopt if no such class exists.
436 std::optional
<const CodeGenRegisterClass
*>
437 inferSuperRegisterClass(const TypeSetByHwMode
&Ty
,
438 const TreePatternNode
*SubRegIdxNode
);
440 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
441 std::optional
<const CodeGenRegisterClass
*>
442 getRegClassFromLeaf(const TreePatternNode
*Leaf
);
444 /// Return a CodeGenRegisterClass for \p N if one can be found. Return
445 /// std::nullopt otherwise.
446 std::optional
<const CodeGenRegisterClass
*>
447 inferRegClassFromPattern(const TreePatternNode
*N
);
449 /// Return the size of the MemoryVT in this predicate, if possible.
450 std::optional
<unsigned>
451 getMemSizeBitsFromPredicate(const TreePredicateFn
&Predicate
);
453 // Add builtin predicates.
454 Expected
<InstructionMatcher
&>
455 addBuiltinPredicates(const Record
*SrcGIEquivOrNull
,
456 const TreePredicateFn
&Predicate
,
457 InstructionMatcher
&InsnMatcher
, bool &HasAddedMatcher
);
460 StringRef
getPatFragPredicateEnumName(Record
*R
) { return R
->getName(); }
462 void GlobalISelEmitter::gatherOpcodeValues() {
463 InstructionOpcodeMatcher::initOpcodeValuesMap(Target
);
466 void GlobalISelEmitter::gatherTypeIDValues() {
467 LLTOperandMatcher::initTypeIDValuesMap();
470 void GlobalISelEmitter::gatherNodeEquivs() {
471 assert(NodeEquivs
.empty());
472 for (Record
*Equiv
: RK
.getAllDerivedDefinitions("GINodeEquiv"))
473 NodeEquivs
[Equiv
->getValueAsDef("Node")] = Equiv
;
475 assert(ComplexPatternEquivs
.empty());
476 for (Record
*Equiv
: RK
.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
477 Record
*SelDAGEquiv
= Equiv
->getValueAsDef("SelDAGEquivalent");
480 ComplexPatternEquivs
[SelDAGEquiv
] = Equiv
;
483 assert(SDNodeXFormEquivs
.empty());
484 for (Record
*Equiv
: RK
.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
485 Record
*SelDAGEquiv
= Equiv
->getValueAsDef("SelDAGEquivalent");
488 SDNodeXFormEquivs
[SelDAGEquiv
] = Equiv
;
492 Record
*GlobalISelEmitter::findNodeEquiv(Record
*N
) const {
493 return NodeEquivs
.lookup(N
);
496 const CodeGenInstruction
*
497 GlobalISelEmitter::getEquivNode(Record
&Equiv
, const TreePatternNode
*N
) const {
498 if (N
->getNumChildren() >= 1) {
499 // setcc operation maps to two different G_* instructions based on the type.
500 if (!Equiv
.isValueUnset("IfFloatingPoint") &&
501 MVT(N
->getChild(0)->getSimpleType(0)).isFloatingPoint())
502 return &Target
.getInstruction(Equiv
.getValueAsDef("IfFloatingPoint"));
505 if (!Equiv
.isValueUnset("IfConvergent") &&
506 N
->getIntrinsicInfo(CGP
)->isConvergent
)
507 return &Target
.getInstruction(Equiv
.getValueAsDef("IfConvergent"));
509 for (const TreePredicateCall
&Call
: N
->getPredicateCalls()) {
510 const TreePredicateFn
&Predicate
= Call
.Fn
;
511 if (!Equiv
.isValueUnset("IfSignExtend") &&
512 (Predicate
.isLoad() || Predicate
.isAtomic()) &&
513 Predicate
.isSignExtLoad())
514 return &Target
.getInstruction(Equiv
.getValueAsDef("IfSignExtend"));
515 if (!Equiv
.isValueUnset("IfZeroExtend") &&
516 (Predicate
.isLoad() || Predicate
.isAtomic()) &&
517 Predicate
.isZeroExtLoad())
518 return &Target
.getInstruction(Equiv
.getValueAsDef("IfZeroExtend"));
521 return &Target
.getInstruction(Equiv
.getValueAsDef("I"));
524 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper
&RK
)
525 : GlobalISelMatchTableExecutorEmitter(), RK(RK
), CGP(RK
),
526 Target(CGP
.getTargetInfo()), CGRegs(Target
.getRegBank()) {
527 ClassName
= Target
.getName().str() + "InstructionSelector";
530 //===- Emitter ------------------------------------------------------------===//
532 Error
GlobalISelEmitter::importRulePredicates(RuleMatcher
&M
,
533 ArrayRef
<Record
*> Predicates
) {
534 for (Record
*Pred
: Predicates
) {
535 if (Pred
->getValueAsString("CondString").empty())
537 declareSubtargetFeature(Pred
);
538 M
.addRequiredFeature(Pred
);
541 return Error::success();
544 std::optional
<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(
545 const TreePredicateFn
&Predicate
) {
546 std::optional
<LLTCodeGen
> MemTyOrNone
=
547 MVTToLLT(getValueType(Predicate
.getMemoryVT()));
552 // Align so unusual types like i1 don't get rounded down.
553 return llvm::alignTo(
554 static_cast<unsigned>(MemTyOrNone
->get().getSizeInBits()), 8);
557 Expected
<InstructionMatcher
&> GlobalISelEmitter::addBuiltinPredicates(
558 const Record
*SrcGIEquivOrNull
, const TreePredicateFn
&Predicate
,
559 InstructionMatcher
&InsnMatcher
, bool &HasAddedMatcher
) {
560 if (Predicate
.isLoad() || Predicate
.isStore() || Predicate
.isAtomic()) {
561 if (const ListInit
*AddrSpaces
= Predicate
.getAddressSpaces()) {
562 SmallVector
<unsigned, 4> ParsedAddrSpaces
;
564 for (Init
*Val
: AddrSpaces
->getValues()) {
565 IntInit
*IntVal
= dyn_cast
<IntInit
>(Val
);
567 return failedImport("Address space is not an integer");
568 ParsedAddrSpaces
.push_back(IntVal
->getValue());
571 if (!ParsedAddrSpaces
.empty()) {
572 InsnMatcher
.addPredicate
<MemoryAddressSpacePredicateMatcher
>(
573 0, ParsedAddrSpaces
);
578 int64_t MinAlign
= Predicate
.getMinAlignment();
580 InsnMatcher
.addPredicate
<MemoryAlignmentPredicateMatcher
>(0, MinAlign
);
585 // G_LOAD is used for both non-extending and any-extending loads.
586 if (Predicate
.isLoad() && Predicate
.isNonExtLoad()) {
587 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
588 0, MemoryVsLLTSizePredicateMatcher::EqualTo
, 0);
591 if (Predicate
.isLoad() && Predicate
.isAnyExtLoad()) {
592 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
593 0, MemoryVsLLTSizePredicateMatcher::LessThan
, 0);
597 if (Predicate
.isStore()) {
598 if (Predicate
.isTruncStore()) {
599 if (Predicate
.getMemoryVT() != nullptr) {
600 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
601 auto MemSizeInBits
= getMemSizeBitsFromPredicate(Predicate
);
603 return failedImport("MemVT could not be converted to LLT");
605 InsnMatcher
.addPredicate
<MemorySizePredicateMatcher
>(0, *MemSizeInBits
/
608 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
609 0, MemoryVsLLTSizePredicateMatcher::LessThan
, 0);
613 if (Predicate
.isNonTruncStore()) {
614 // We need to check the sizes match here otherwise we could incorrectly
615 // match truncating stores with non-truncating ones.
616 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
617 0, MemoryVsLLTSizePredicateMatcher::EqualTo
, 0);
621 assert(SrcGIEquivOrNull
!= nullptr && "Invalid SrcGIEquivOrNull value");
622 // No check required. We already did it by swapping the opcode.
623 if (!SrcGIEquivOrNull
->isValueUnset("IfSignExtend") &&
624 Predicate
.isSignExtLoad())
627 // No check required. We already did it by swapping the opcode.
628 if (!SrcGIEquivOrNull
->isValueUnset("IfZeroExtend") &&
629 Predicate
.isZeroExtLoad())
632 // No check required. G_STORE by itself is a non-extending store.
633 if (Predicate
.isNonTruncStore())
636 if (Predicate
.isLoad() || Predicate
.isStore() || Predicate
.isAtomic()) {
637 if (Predicate
.getMemoryVT() != nullptr) {
638 auto MemSizeInBits
= getMemSizeBitsFromPredicate(Predicate
);
640 return failedImport("MemVT could not be converted to LLT");
642 InsnMatcher
.addPredicate
<MemorySizePredicateMatcher
>(0,
648 if (Predicate
.isLoad() || Predicate
.isStore()) {
649 // No check required. A G_LOAD/G_STORE is an unindexed load.
650 if (Predicate
.isUnindexed())
654 if (Predicate
.isAtomic()) {
655 if (Predicate
.isAtomicOrderingMonotonic()) {
656 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("Monotonic");
659 if (Predicate
.isAtomicOrderingAcquire()) {
660 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("Acquire");
663 if (Predicate
.isAtomicOrderingRelease()) {
664 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("Release");
667 if (Predicate
.isAtomicOrderingAcquireRelease()) {
668 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
672 if (Predicate
.isAtomicOrderingSequentiallyConsistent()) {
673 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
674 "SequentiallyConsistent");
679 if (Predicate
.isAtomicOrderingAcquireOrStronger()) {
680 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
681 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger
);
684 if (Predicate
.isAtomicOrderingWeakerThanAcquire()) {
685 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
686 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan
);
690 if (Predicate
.isAtomicOrderingReleaseOrStronger()) {
691 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
692 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger
);
695 if (Predicate
.isAtomicOrderingWeakerThanRelease()) {
696 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
697 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan
);
700 HasAddedMatcher
= false;
704 Expected
<InstructionMatcher
&> GlobalISelEmitter::createAndImportSelDAGMatcher(
705 RuleMatcher
&Rule
, InstructionMatcher
&InsnMatcher
,
706 const TreePatternNode
*Src
, unsigned &TempOpIdx
) {
707 const auto SavedFlags
= Rule
.setGISelFlags(Src
->getGISelFlagsRecord());
709 Record
*SrcGIEquivOrNull
= nullptr;
710 const CodeGenInstruction
*SrcGIOrNull
= nullptr;
712 // Start with the defined operands (i.e., the results of the root operator).
714 Init
*SrcInit
= Src
->getLeafValue();
715 if (isa
<IntInit
>(SrcInit
)) {
716 InsnMatcher
.addPredicate
<InstructionOpcodeMatcher
>(
717 &Target
.getInstruction(RK
.getDef("G_CONSTANT")));
720 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
722 SrcGIEquivOrNull
= findNodeEquiv(Src
->getOperator());
723 if (!SrcGIEquivOrNull
)
724 return failedImport("Pattern operator lacks an equivalent Instruction" +
725 explainOperator(Src
->getOperator()));
726 SrcGIOrNull
= getEquivNode(*SrcGIEquivOrNull
, Src
);
728 // The operators look good: match the opcode
729 InsnMatcher
.addPredicate
<InstructionOpcodeMatcher
>(SrcGIOrNull
);
733 for (const TypeSetByHwMode
&VTy
: Src
->getExtTypes()) {
734 // Results don't have a name unless they are the root node. The caller will
735 // set the name if appropriate.
736 const bool OperandIsAPointer
=
737 SrcGIOrNull
&& SrcGIOrNull
->isOutOperandAPointer(OpIdx
);
738 OperandMatcher
&OM
= InsnMatcher
.addOperand(OpIdx
++, "", TempOpIdx
);
739 if (auto Error
= OM
.addTypeCheckPredicate(VTy
, OperandIsAPointer
))
740 return failedImport(toString(std::move(Error
)) +
741 " for result of Src pattern operator");
744 for (const TreePredicateCall
&Call
: Src
->getPredicateCalls()) {
745 const TreePredicateFn
&Predicate
= Call
.Fn
;
746 bool HasAddedBuiltinMatcher
= true;
747 if (Predicate
.isAlwaysTrue())
750 if (Predicate
.isImmediatePattern()) {
751 InsnMatcher
.addPredicate
<InstructionImmPredicateMatcher
>(Predicate
);
755 auto InsnMatcherOrError
= addBuiltinPredicates(
756 SrcGIEquivOrNull
, Predicate
, InsnMatcher
, HasAddedBuiltinMatcher
);
757 if (auto Error
= InsnMatcherOrError
.takeError())
758 return std::move(Error
);
760 // FIXME: This should be part of addBuiltinPredicates(). If we add this at
761 // the start of addBuiltinPredicates() without returning, then there might
762 // be cases where we hit the last return before which the
763 // HasAddedBuiltinMatcher will be set to false. The predicate could be
764 // missed if we add it in the middle or at the end due to return statements
765 // after the addPredicate<>() calls.
766 if (Predicate
.hasNoUse()) {
767 InsnMatcher
.addPredicate
<NoUsePredicateMatcher
>();
768 HasAddedBuiltinMatcher
= true;
771 if (Predicate
.hasGISelPredicateCode()) {
772 if (Predicate
.usesOperands()) {
773 assert(WaitingForNamedOperands
== 0 &&
774 "previous predicate didn't find all operands or "
775 "nested predicate that uses operands");
776 TreePattern
*TP
= Predicate
.getOrigPatFragRecord();
777 WaitingForNamedOperands
= TP
->getNumArgs();
778 for (unsigned i
= 0; i
< WaitingForNamedOperands
; ++i
)
779 StoreIdxForName
[getScopedName(Call
.Scope
, TP
->getArgName(i
))] = i
;
781 InsnMatcher
.addPredicate
<GenericInstructionPredicateMatcher
>(Predicate
);
784 if (!HasAddedBuiltinMatcher
) {
785 return failedImport("Src pattern child has predicate (" +
786 explainPredicates(Src
) + ")");
790 if (SrcGIEquivOrNull
&&
791 SrcGIEquivOrNull
->getValueAsBit("CheckMMOIsNonAtomic"))
792 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("NotAtomic");
793 else if (SrcGIEquivOrNull
&&
794 SrcGIEquivOrNull
->getValueAsBit("CheckMMOIsAtomic")) {
795 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
796 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger
);
800 Init
*SrcInit
= Src
->getLeafValue();
801 if (IntInit
*SrcIntInit
= dyn_cast
<IntInit
>(SrcInit
)) {
803 InsnMatcher
.addOperand(OpIdx
++, Src
->getName(), TempOpIdx
);
804 OM
.addPredicate
<LiteralIntOperandMatcher
>(SrcIntInit
->getValue());
807 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
809 assert(SrcGIOrNull
&&
810 "Expected to have already found an equivalent Instruction");
811 if (SrcGIOrNull
->TheDef
->getName() == "G_CONSTANT" ||
812 SrcGIOrNull
->TheDef
->getName() == "G_FCONSTANT") {
813 // imm/fpimm still have operands but we don't need to do anything with it
814 // here since we don't support ImmLeaf predicates yet. However, we still
815 // need to note the hidden operand to get GIM_CheckNumOperands correct.
816 InsnMatcher
.addOperand(OpIdx
++, "", TempOpIdx
);
820 // Special case because the operand order is changed from setcc. The
821 // predicate operand needs to be swapped from the last operand to the first
824 unsigned NumChildren
= Src
->getNumChildren();
825 bool IsFCmp
= SrcGIOrNull
->TheDef
->getName() == "G_FCMP";
827 if (IsFCmp
|| SrcGIOrNull
->TheDef
->getName() == "G_ICMP") {
828 const TreePatternNode
*SrcChild
= Src
->getChild(NumChildren
- 1);
829 if (SrcChild
->isLeaf()) {
830 DefInit
*DI
= dyn_cast
<DefInit
>(SrcChild
->getLeafValue());
831 Record
*CCDef
= DI
? DI
->getDef() : nullptr;
832 if (!CCDef
|| !CCDef
->isSubClassOf("CondCode"))
833 return failedImport("Unable to handle CondCode");
836 InsnMatcher
.addOperand(OpIdx
++, SrcChild
->getName(), TempOpIdx
);
837 StringRef PredType
= IsFCmp
? CCDef
->getValueAsString("FCmpPredicate")
838 : CCDef
->getValueAsString("ICmpPredicate");
840 if (!PredType
.empty()) {
841 OM
.addPredicate
<CmpPredicateOperandMatcher
>(std::string(PredType
));
842 // Process the other 2 operands normally.
848 // Match the used operands (i.e. the children of the operator).
850 SrcGIOrNull
->TheDef
->getName() == "G_INTRINSIC" ||
851 SrcGIOrNull
->TheDef
->getName() == "G_INTRINSIC_W_SIDE_EFFECTS" ||
852 SrcGIOrNull
->TheDef
->getName() == "G_INTRINSIC_CONVERGENT" ||
853 SrcGIOrNull
->TheDef
->getName() ==
854 "G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS";
855 const CodeGenIntrinsic
*II
= Src
->getIntrinsicInfo(CGP
);
856 if (IsIntrinsic
&& !II
)
857 return failedImport("Expected IntInit containing intrinsic ID)");
859 for (unsigned i
= 0; i
!= NumChildren
; ++i
) {
860 const TreePatternNode
*SrcChild
= Src
->getChild(i
);
862 // We need to determine the meaning of a literal integer based on the
863 // context. If this is a field required to be an immediate (such as an
864 // immarg intrinsic argument), the required predicates are different than
865 // a constant which may be materialized in a register. If we have an
866 // argument that is required to be an immediate, we should not emit an LLT
867 // type check, and should not be looking for a G_CONSTANT defined
869 bool OperandIsImmArg
= SrcGIOrNull
->isInOperandImmArg(i
);
871 // SelectionDAG allows pointers to be represented with iN since it doesn't
872 // distinguish between pointers and integers but they are different types
873 // in GlobalISel. Coerce integers to pointers to address space 0 if the
874 // context indicates a pointer.
876 bool OperandIsAPointer
= SrcGIOrNull
->isInOperandAPointer(i
);
879 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
880 // following the defs is an intrinsic ID.
883 InsnMatcher
.addOperand(OpIdx
++, SrcChild
->getName(), TempOpIdx
);
884 OM
.addPredicate
<IntrinsicIDOperandMatcher
>(II
);
888 // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
890 // Note that we have to look at the i-1th parameter, because we don't
891 // have the intrinsic ID in the intrinsic's parameter list.
892 OperandIsAPointer
|= II
->isParamAPointer(i
- 1);
893 OperandIsImmArg
|= II
->isParamImmArg(i
- 1);
897 importChildMatcher(Rule
, InsnMatcher
, SrcChild
, OperandIsAPointer
,
898 OperandIsImmArg
, OpIdx
++, TempOpIdx
))
899 return std::move(Error
);
906 Error
GlobalISelEmitter::importComplexPatternOperandMatcher(
907 OperandMatcher
&OM
, Record
*R
, unsigned &TempOpIdx
) const {
908 const auto &ComplexPattern
= ComplexPatternEquivs
.find(R
);
909 if (ComplexPattern
== ComplexPatternEquivs
.end())
910 return failedImport("SelectionDAG ComplexPattern (" + R
->getName() +
911 ") not mapped to GlobalISel");
913 OM
.addPredicate
<ComplexPatternOperandMatcher
>(OM
, *ComplexPattern
->second
);
915 return Error::success();
918 // Get the name to use for a pattern operand. For an anonymous physical register
919 // input, this should use the register name.
920 static StringRef
getSrcChildName(const TreePatternNode
*SrcChild
,
922 StringRef SrcChildName
= SrcChild
->getName();
923 if (SrcChildName
.empty() && SrcChild
->isLeaf()) {
924 if (auto *ChildDefInit
= dyn_cast
<DefInit
>(SrcChild
->getLeafValue())) {
925 auto *ChildRec
= ChildDefInit
->getDef();
926 if (ChildRec
->isSubClassOf("Register")) {
927 SrcChildName
= ChildRec
->getName();
936 Error
GlobalISelEmitter::importChildMatcher(
937 RuleMatcher
&Rule
, InstructionMatcher
&InsnMatcher
,
938 const TreePatternNode
*SrcChild
, bool OperandIsAPointer
,
939 bool OperandIsImmArg
, unsigned OpIdx
, unsigned &TempOpIdx
) {
941 Record
*PhysReg
= nullptr;
942 std::string SrcChildName
= std::string(getSrcChildName(SrcChild
, PhysReg
));
943 if (!SrcChild
->isLeaf() &&
944 SrcChild
->getOperator()->isSubClassOf("ComplexPattern")) {
945 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
946 // "MY_PAT:op1:op2" and the ones with same "name" represent same operand.
947 std::string PatternName
= std::string(SrcChild
->getOperator()->getName());
948 for (unsigned i
= 0; i
< SrcChild
->getNumChildren(); ++i
) {
950 PatternName
+= SrcChild
->getChild(i
)->getName();
952 SrcChildName
= PatternName
;
956 PhysReg
? InsnMatcher
.addPhysRegInput(PhysReg
, OpIdx
, TempOpIdx
)
957 : InsnMatcher
.addOperand(OpIdx
, SrcChildName
, TempOpIdx
);
958 if (OM
.isSameAsAnotherOperand())
959 return Error::success();
961 ArrayRef
<TypeSetByHwMode
> ChildTypes
= SrcChild
->getExtTypes();
962 if (ChildTypes
.size() != 1)
963 return failedImport("Src pattern child has multiple results");
965 // Check MBB's before the type check since they are not a known type.
966 if (!SrcChild
->isLeaf()) {
967 if (SrcChild
->getOperator()->isSubClassOf("SDNode")) {
968 auto &ChildSDNI
= CGP
.getSDNodeInfo(SrcChild
->getOperator());
969 if (ChildSDNI
.getSDClassName() == "BasicBlockSDNode") {
970 OM
.addPredicate
<MBBOperandMatcher
>();
971 return Error::success();
973 if (SrcChild
->getOperator()->getName() == "timm") {
974 OM
.addPredicate
<ImmOperandMatcher
>();
976 // Add predicates, if any
977 for (const TreePredicateCall
&Call
: SrcChild
->getPredicateCalls()) {
978 const TreePredicateFn
&Predicate
= Call
.Fn
;
980 // Only handle immediate patterns for now
981 if (Predicate
.isImmediatePattern()) {
982 OM
.addPredicate
<OperandImmPredicateMatcher
>(Predicate
);
986 return Error::success();
991 // Immediate arguments have no meaningful type to check as they don't have
993 if (!OperandIsImmArg
) {
995 OM
.addTypeCheckPredicate(ChildTypes
.front(), OperandIsAPointer
))
996 return failedImport(toString(std::move(Error
)) + " for Src operand (" +
997 to_string(*SrcChild
) + ")");
1000 // Try look up SrcChild for a (named) predicate operand if there is any.
1001 if (WaitingForNamedOperands
) {
1002 auto &ScopedNames
= SrcChild
->getNamesAsPredicateArg();
1003 if (!ScopedNames
.empty()) {
1004 auto PA
= ScopedNames
.begin();
1005 std::string Name
= getScopedName(PA
->getScope(), PA
->getIdentifier());
1006 OM
.addPredicate
<RecordNamedOperandMatcher
>(StoreIdxForName
[Name
], Name
);
1007 --WaitingForNamedOperands
;
1011 // Check for nested instructions.
1012 if (!SrcChild
->isLeaf()) {
1013 if (SrcChild
->getOperator()->isSubClassOf("ComplexPattern")) {
1014 // When a ComplexPattern is used as an operator, it should do the same
1015 // thing as when used as a leaf. However, the children of the operator
1016 // name the sub-operands that make up the complex operand and we must
1017 // prepare to reference them in the renderer too.
1018 unsigned RendererID
= TempOpIdx
;
1019 if (auto Error
= importComplexPatternOperandMatcher(
1020 OM
, SrcChild
->getOperator(), TempOpIdx
))
1023 for (unsigned i
= 0, e
= SrcChild
->getNumChildren(); i
!= e
; ++i
) {
1024 auto *SubOperand
= SrcChild
->getChild(i
);
1025 if (!SubOperand
->getName().empty()) {
1026 if (auto Error
= Rule
.defineComplexSubOperand(
1027 SubOperand
->getName(), SrcChild
->getOperator(), RendererID
, i
,
1033 return Error::success();
1036 auto MaybeInsnOperand
= OM
.addPredicate
<InstructionOperandMatcher
>(
1037 InsnMatcher
.getRuleMatcher(), SrcChild
->getName());
1038 if (!MaybeInsnOperand
) {
1039 // This isn't strictly true. If the user were to provide exactly the same
1040 // matchers as the original operand then we could allow it. However, it's
1041 // simpler to not permit the redundant specification.
1042 return failedImport(
1043 "Nested instruction cannot be the same as another operand");
1046 // Map the node to a gMIR instruction.
1047 InstructionOperandMatcher
&InsnOperand
= **MaybeInsnOperand
;
1048 auto InsnMatcherOrError
= createAndImportSelDAGMatcher(
1049 Rule
, InsnOperand
.getInsnMatcher(), SrcChild
, TempOpIdx
);
1050 if (auto Error
= InsnMatcherOrError
.takeError())
1053 return Error::success();
1056 if (SrcChild
->hasAnyPredicate())
1057 return failedImport("Src pattern child has unsupported predicate");
1059 // Check for constant immediates.
1060 if (auto *ChildInt
= dyn_cast
<IntInit
>(SrcChild
->getLeafValue())) {
1061 if (OperandIsImmArg
) {
1062 // Checks for argument directly in operand list
1063 OM
.addPredicate
<LiteralIntOperandMatcher
>(ChildInt
->getValue());
1065 // Checks for materialized constant
1066 OM
.addPredicate
<ConstantIntOperandMatcher
>(ChildInt
->getValue());
1068 return Error::success();
1071 // Check for def's like register classes or ComplexPattern's.
1072 if (auto *ChildDefInit
= dyn_cast
<DefInit
>(SrcChild
->getLeafValue())) {
1073 auto *ChildRec
= ChildDefInit
->getDef();
1075 // Check for register classes.
1076 if (ChildRec
->isSubClassOf("RegisterClass") ||
1077 ChildRec
->isSubClassOf("RegisterOperand")) {
1078 OM
.addPredicate
<RegisterBankOperandMatcher
>(
1079 Target
.getRegisterClass(getInitValueAsRegClass(ChildDefInit
)));
1080 return Error::success();
1083 if (ChildRec
->isSubClassOf("Register")) {
1084 // This just be emitted as a copy to the specific register.
1085 ValueTypeByHwMode VT
= ChildTypes
.front().getValueTypeByHwMode();
1086 const CodeGenRegisterClass
*RC
=
1087 CGRegs
.getMinimalPhysRegClass(ChildRec
, &VT
);
1089 return failedImport(
1090 "Could not determine physical register class of pattern source");
1093 OM
.addPredicate
<RegisterBankOperandMatcher
>(*RC
);
1094 return Error::success();
1097 // Check for ValueType.
1098 if (ChildRec
->isSubClassOf("ValueType")) {
1099 // We already added a type check as standard practice so this doesn't need
1101 return Error::success();
1104 // Check for ComplexPattern's.
1105 if (ChildRec
->isSubClassOf("ComplexPattern"))
1106 return importComplexPatternOperandMatcher(OM
, ChildRec
, TempOpIdx
);
1108 if (ChildRec
->isSubClassOf("ImmLeaf")) {
1109 return failedImport(
1110 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1113 // Place holder for SRCVALUE nodes. Nothing to do here.
1114 if (ChildRec
->getName() == "srcvalue")
1115 return Error::success();
1117 const bool ImmAllOnesV
= ChildRec
->getName() == "immAllOnesV";
1118 if (ImmAllOnesV
|| ChildRec
->getName() == "immAllZerosV") {
1119 auto MaybeInsnOperand
= OM
.addPredicate
<InstructionOperandMatcher
>(
1120 InsnMatcher
.getRuleMatcher(), SrcChild
->getName(), false);
1121 InstructionOperandMatcher
&InsnOperand
= **MaybeInsnOperand
;
1123 ValueTypeByHwMode VTy
= ChildTypes
.front().getValueTypeByHwMode();
1125 const CodeGenInstruction
&BuildVector
=
1126 Target
.getInstruction(RK
.getDef("G_BUILD_VECTOR"));
1127 const CodeGenInstruction
&BuildVectorTrunc
=
1128 Target
.getInstruction(RK
.getDef("G_BUILD_VECTOR_TRUNC"));
1130 // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
1131 // as an alternative.
1132 InsnOperand
.getInsnMatcher().addPredicate
<InstructionOpcodeMatcher
>(
1133 ArrayRef({&BuildVector
, &BuildVectorTrunc
}));
1135 // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
1136 // theoretically not emit any opcode check, but getOpcodeMatcher currently
1138 OperandMatcher
&OM
=
1139 InsnOperand
.getInsnMatcher().addOperand(0, "", TempOpIdx
);
1141 OM
.addTypeCheckPredicate(VTy
, false /* OperandIsAPointer */))
1142 return failedImport(toString(std::move(Error
)) +
1143 " for result of Src pattern operator");
1145 InsnOperand
.getInsnMatcher().addPredicate
<VectorSplatImmPredicateMatcher
>(
1146 ImmAllOnesV
? VectorSplatImmPredicateMatcher::AllOnes
1147 : VectorSplatImmPredicateMatcher::AllZeros
);
1148 return Error::success();
1151 return failedImport(
1152 "Src pattern child def is an unsupported tablegen class");
1155 return failedImport("Src pattern child is an unsupported kind");
1158 Expected
<action_iterator
> GlobalISelEmitter::importExplicitUseRenderer(
1159 action_iterator InsertPt
, RuleMatcher
&Rule
, BuildMIAction
&DstMIBuilder
,
1160 const TreePatternNode
*DstChild
, const TreePatternNode
*Src
) {
1162 const auto &SubOperand
= Rule
.getComplexSubOperand(DstChild
->getName());
1164 DstMIBuilder
.addRenderer
<RenderComplexPatternOperand
>(
1165 *std::get
<0>(*SubOperand
), DstChild
->getName(),
1166 std::get
<1>(*SubOperand
), std::get
<2>(*SubOperand
));
1170 if (!DstChild
->isLeaf()) {
1171 if (DstChild
->getOperator()->isSubClassOf("SDNodeXForm")) {
1172 auto Child
= DstChild
->getChild(0);
1173 auto I
= SDNodeXFormEquivs
.find(DstChild
->getOperator());
1174 if (I
!= SDNodeXFormEquivs
.end()) {
1175 Record
*XFormOpc
= DstChild
->getOperator()->getValueAsDef("Opcode");
1176 if (XFormOpc
->getName() == "timm") {
1177 // If this is a TargetConstant, there won't be a corresponding
1178 // instruction to transform. Instead, this will refer directly to an
1179 // operand in an instruction's operand list.
1180 DstMIBuilder
.addRenderer
<CustomOperandRenderer
>(*I
->second
,
1183 DstMIBuilder
.addRenderer
<CustomRenderer
>(*I
->second
,
1189 return failedImport("SDNodeXForm " + Child
->getName() +
1190 " has no custom renderer");
1193 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
1194 // inline, but in MI it's just another operand.
1195 if (DstChild
->getOperator()->isSubClassOf("SDNode")) {
1196 auto &ChildSDNI
= CGP
.getSDNodeInfo(DstChild
->getOperator());
1197 if (ChildSDNI
.getSDClassName() == "BasicBlockSDNode") {
1198 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstChild
->getName());
1203 // Similarly, imm is an operator in TreePatternNode's view but must be
1204 // rendered as operands.
1205 // FIXME: The target should be able to choose sign-extended when appropriate
1207 if (DstChild
->getOperator()->getName() == "timm") {
1208 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstChild
->getName());
1210 } else if (DstChild
->getOperator()->getName() == "imm") {
1211 DstMIBuilder
.addRenderer
<CopyConstantAsImmRenderer
>(DstChild
->getName());
1213 } else if (DstChild
->getOperator()->getName() == "fpimm") {
1214 DstMIBuilder
.addRenderer
<CopyFConstantAsFPImmRenderer
>(
1215 DstChild
->getName());
1219 if (DstChild
->getOperator()->isSubClassOf("Instruction")) {
1220 auto OpTy
= getInstResultType(DstChild
);
1222 return OpTy
.takeError();
1224 unsigned TempRegID
= Rule
.allocateTempRegID();
1226 Rule
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *OpTy
, TempRegID
);
1227 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
);
1229 auto InsertPtOrError
= createAndImportSubInstructionRenderer(
1230 ++InsertPt
, Rule
, DstChild
, Src
, TempRegID
);
1231 if (auto Error
= InsertPtOrError
.takeError())
1232 return std::move(Error
);
1233 return InsertPtOrError
.get();
1236 return failedImport("Dst pattern child isn't a leaf node or an MBB" +
1237 llvm::to_string(*DstChild
));
1240 // It could be a specific immediate in which case we should just check for
1242 if (const IntInit
*ChildIntInit
=
1243 dyn_cast
<IntInit
>(DstChild
->getLeafValue())) {
1244 DstMIBuilder
.addRenderer
<ImmRenderer
>(ChildIntInit
->getValue());
1248 // Otherwise, we're looking for a bog-standard RegisterClass operand.
1249 if (auto *ChildDefInit
= dyn_cast
<DefInit
>(DstChild
->getLeafValue())) {
1250 auto *ChildRec
= ChildDefInit
->getDef();
1252 ArrayRef
<TypeSetByHwMode
> ChildTypes
= DstChild
->getExtTypes();
1253 if (ChildTypes
.size() != 1)
1254 return failedImport("Dst pattern child has multiple results");
1256 std::optional
<LLTCodeGen
> OpTyOrNone
;
1257 if (ChildTypes
.front().isMachineValueType())
1258 OpTyOrNone
= MVTToLLT(ChildTypes
.front().getMachineValueType().SimpleTy
);
1260 return failedImport("Dst operand has an unsupported type");
1262 if (ChildRec
->isSubClassOf("Register")) {
1263 DstMIBuilder
.addRenderer
<AddRegisterRenderer
>(Target
, ChildRec
);
1267 if (ChildRec
->isSubClassOf("RegisterClass") ||
1268 ChildRec
->isSubClassOf("RegisterOperand") ||
1269 ChildRec
->isSubClassOf("ValueType")) {
1270 if (ChildRec
->isSubClassOf("RegisterOperand") &&
1271 !ChildRec
->isValueUnset("GIZeroRegister")) {
1272 DstMIBuilder
.addRenderer
<CopyOrAddZeroRegRenderer
>(
1273 DstChild
->getName(), ChildRec
->getValueAsDef("GIZeroRegister"));
1277 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstChild
->getName());
1281 if (ChildRec
->isSubClassOf("SubRegIndex")) {
1282 CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(ChildRec
);
1283 DstMIBuilder
.addRenderer
<ImmRenderer
>(SubIdx
->EnumValue
);
1287 if (ChildRec
->isSubClassOf("ComplexPattern")) {
1288 const auto &ComplexPattern
= ComplexPatternEquivs
.find(ChildRec
);
1289 if (ComplexPattern
== ComplexPatternEquivs
.end())
1290 return failedImport(
1291 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1293 const OperandMatcher
&OM
= Rule
.getOperandMatcher(DstChild
->getName());
1294 DstMIBuilder
.addRenderer
<RenderComplexPatternOperand
>(
1295 *ComplexPattern
->second
, DstChild
->getName(),
1296 OM
.getAllocatedTemporariesBaseID());
1300 return failedImport(
1301 "Dst pattern child def is an unsupported tablegen class");
1304 // Handle the case where the MVT/register class is omitted in the dest pattern
1305 // but MVT exists in the source pattern.
1306 if (isa
<UnsetInit
>(DstChild
->getLeafValue())) {
1307 for (unsigned NumOp
= 0; NumOp
< Src
->getNumChildren(); NumOp
++)
1308 if (Src
->getChild(NumOp
)->getName() == DstChild
->getName()) {
1309 DstMIBuilder
.addRenderer
<CopyRenderer
>(Src
->getChild(NumOp
)->getName());
1313 return failedImport("Dst pattern child is an unsupported kind");
1316 Expected
<BuildMIAction
&> GlobalISelEmitter::createAndImportInstructionRenderer(
1317 RuleMatcher
&M
, InstructionMatcher
&InsnMatcher
, const TreePatternNode
*Src
,
1318 const TreePatternNode
*Dst
) {
1319 auto InsertPtOrError
= createInstructionRenderer(M
.actions_end(), M
, Dst
);
1320 if (auto Error
= InsertPtOrError
.takeError())
1321 return std::move(Error
);
1323 action_iterator InsertPt
= InsertPtOrError
.get();
1324 BuildMIAction
&DstMIBuilder
= *static_cast<BuildMIAction
*>(InsertPt
->get());
1326 for (auto PhysInput
: InsnMatcher
.getPhysRegInputs()) {
1327 InsertPt
= M
.insertAction
<BuildMIAction
>(
1328 InsertPt
, M
.allocateOutputInsnID(),
1329 &Target
.getInstruction(RK
.getDef("COPY")));
1330 BuildMIAction
&CopyToPhysRegMIBuilder
=
1331 *static_cast<BuildMIAction
*>(InsertPt
->get());
1332 CopyToPhysRegMIBuilder
.addRenderer
<AddRegisterRenderer
>(
1333 Target
, PhysInput
.first
, true);
1334 CopyToPhysRegMIBuilder
.addRenderer
<CopyPhysRegRenderer
>(PhysInput
.first
);
1338 importExplicitDefRenderers(InsertPt
, M
, DstMIBuilder
, Src
, Dst
)
1340 return std::move(Error
);
1343 importExplicitUseRenderers(InsertPt
, M
, DstMIBuilder
, Dst
, Src
)
1345 return std::move(Error
);
1347 return DstMIBuilder
;
1350 Expected
<action_iterator
>
1351 GlobalISelEmitter::createAndImportSubInstructionRenderer(
1352 const action_iterator InsertPt
, RuleMatcher
&M
, const TreePatternNode
*Dst
,
1353 const TreePatternNode
*Src
, unsigned TempRegID
) {
1354 auto InsertPtOrError
= createInstructionRenderer(InsertPt
, M
, Dst
);
1356 // TODO: Assert there's exactly one result.
1358 if (auto Error
= InsertPtOrError
.takeError())
1359 return std::move(Error
);
1361 BuildMIAction
&DstMIBuilder
=
1362 *static_cast<BuildMIAction
*>(InsertPtOrError
.get()->get());
1364 // Assign the result to TempReg.
1365 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
, true);
1367 InsertPtOrError
= importExplicitUseRenderers(InsertPtOrError
.get(), M
,
1368 DstMIBuilder
, Dst
, Src
);
1369 if (auto Error
= InsertPtOrError
.takeError())
1370 return std::move(Error
);
1372 // We need to make sure that when we import an INSERT_SUBREG as a
1373 // subinstruction that it ends up being constrained to the correct super
1374 // register and subregister classes.
1375 auto OpName
= Target
.getInstruction(Dst
->getOperator()).TheDef
->getName();
1376 if (OpName
== "INSERT_SUBREG") {
1377 auto SubClass
= inferRegClassFromPattern(Dst
->getChild(1));
1379 return failedImport(
1380 "Cannot infer register class from INSERT_SUBREG operand #1");
1381 std::optional
<const CodeGenRegisterClass
*> SuperClass
=
1382 inferSuperRegisterClassForNode(Dst
->getExtType(0), Dst
->getChild(0),
1385 return failedImport(
1386 "Cannot infer register class for INSERT_SUBREG operand #0");
1387 // The destination and the super register source of an INSERT_SUBREG must
1388 // be the same register class.
1389 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1390 InsertPt
, DstMIBuilder
.getInsnID(), 0, **SuperClass
);
1391 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1392 InsertPt
, DstMIBuilder
.getInsnID(), 1, **SuperClass
);
1393 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1394 InsertPt
, DstMIBuilder
.getInsnID(), 2, **SubClass
);
1395 return InsertPtOrError
.get();
1398 if (OpName
== "EXTRACT_SUBREG") {
1399 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
1400 // instructions, the result register class is controlled by the
1401 // subregisters of the operand. As a result, we must constrain the result
1402 // class rather than check that it's already the right one.
1403 auto SuperClass
= inferRegClassFromPattern(Dst
->getChild(0));
1405 return failedImport(
1406 "Cannot infer register class from EXTRACT_SUBREG operand #0");
1408 auto SubIdx
= inferSubRegIndexForNode(Dst
->getChild(1));
1410 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1412 const auto SrcRCDstRCPair
=
1413 (*SuperClass
)->getMatchingSubClassWithSubRegs(CGRegs
, *SubIdx
);
1414 assert(SrcRCDstRCPair
->second
&& "Couldn't find a matching subclass");
1415 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1416 InsertPt
, DstMIBuilder
.getInsnID(), 0, *SrcRCDstRCPair
->second
);
1417 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1418 InsertPt
, DstMIBuilder
.getInsnID(), 1, *SrcRCDstRCPair
->first
);
1420 // We're done with this pattern! It's eligible for GISel emission; return
1422 return InsertPtOrError
.get();
1425 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
1427 if (OpName
== "SUBREG_TO_REG") {
1428 auto SubClass
= inferRegClassFromPattern(Dst
->getChild(1));
1430 return failedImport(
1431 "Cannot infer register class from SUBREG_TO_REG child #1");
1433 inferSuperRegisterClass(Dst
->getExtType(0), Dst
->getChild(2));
1435 return failedImport(
1436 "Cannot infer register class for SUBREG_TO_REG operand #0");
1437 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1438 InsertPt
, DstMIBuilder
.getInsnID(), 0, **SuperClass
);
1439 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1440 InsertPt
, DstMIBuilder
.getInsnID(), 2, **SubClass
);
1441 return InsertPtOrError
.get();
1444 if (OpName
== "REG_SEQUENCE") {
1445 auto SuperClass
= inferRegClassFromPattern(Dst
->getChild(0));
1446 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1447 InsertPt
, DstMIBuilder
.getInsnID(), 0, **SuperClass
);
1449 unsigned Num
= Dst
->getNumChildren();
1450 for (unsigned I
= 1; I
!= Num
; I
+= 2) {
1451 const TreePatternNode
*SubRegChild
= Dst
->getChild(I
+ 1);
1453 auto SubIdx
= inferSubRegIndexForNode(SubRegChild
);
1455 return failedImport("REG_SEQUENCE child is not a subreg index");
1457 const auto SrcRCDstRCPair
=
1458 (*SuperClass
)->getMatchingSubClassWithSubRegs(CGRegs
, *SubIdx
);
1459 assert(SrcRCDstRCPair
->second
&& "Couldn't find a matching subclass");
1460 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1461 InsertPt
, DstMIBuilder
.getInsnID(), I
, *SrcRCDstRCPair
->second
);
1464 return InsertPtOrError
.get();
1467 M
.insertAction
<ConstrainOperandsToDefinitionAction
>(InsertPt
,
1468 DstMIBuilder
.getInsnID());
1469 return InsertPtOrError
.get();
1472 Expected
<action_iterator
> GlobalISelEmitter::createInstructionRenderer(
1473 action_iterator InsertPt
, RuleMatcher
&M
, const TreePatternNode
*Dst
) {
1474 Record
*DstOp
= Dst
->getOperator();
1475 if (!DstOp
->isSubClassOf("Instruction")) {
1476 if (DstOp
->isSubClassOf("ValueType"))
1477 return failedImport(
1478 "Pattern operator isn't an instruction (it's a ValueType)");
1479 return failedImport("Pattern operator isn't an instruction");
1481 CodeGenInstruction
*DstI
= &Target
.getInstruction(DstOp
);
1483 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
1484 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
1485 StringRef Name
= DstI
->TheDef
->getName();
1486 if (Name
== "COPY_TO_REGCLASS" || Name
== "EXTRACT_SUBREG")
1487 DstI
= &Target
.getInstruction(RK
.getDef("COPY"));
1489 return M
.insertAction
<BuildMIAction
>(InsertPt
, M
.allocateOutputInsnID(),
1493 Expected
<action_iterator
> GlobalISelEmitter::importExplicitDefRenderers(
1494 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
1495 const TreePatternNode
*Src
, const TreePatternNode
*Dst
) {
1496 const CodeGenInstruction
*DstI
= DstMIBuilder
.getCGI();
1497 const unsigned SrcNumDefs
= Src
->getExtTypes().size();
1498 const unsigned DstNumDefs
= DstI
->Operands
.NumDefs
;
1499 if (DstNumDefs
== 0)
1502 for (unsigned I
= 0; I
< SrcNumDefs
; ++I
)
1503 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstI
->Operands
[I
].Name
);
1505 // Some instructions have multiple defs, but are missing a type entry
1506 // (e.g. s_cc_out operands).
1507 if (Dst
->getExtTypes().size() < DstNumDefs
)
1508 return failedImport("unhandled discarded def");
1510 for (unsigned I
= SrcNumDefs
; I
< DstNumDefs
; ++I
) {
1511 const TypeSetByHwMode
&ExtTy
= Dst
->getExtType(I
);
1512 if (!ExtTy
.isMachineValueType())
1513 return failedImport("unsupported typeset");
1515 auto OpTy
= MVTToLLT(ExtTy
.getMachineValueType().SimpleTy
);
1517 return failedImport("unsupported type");
1519 unsigned TempRegID
= M
.allocateTempRegID();
1521 M
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *OpTy
, TempRegID
);
1522 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
, true, nullptr, true);
1528 Expected
<action_iterator
> GlobalISelEmitter::importExplicitUseRenderers(
1529 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
1530 const llvm::TreePatternNode
*Dst
, const llvm::TreePatternNode
*Src
) {
1531 const CodeGenInstruction
*DstI
= DstMIBuilder
.getCGI();
1532 CodeGenInstruction
*OrigDstI
= &Target
.getInstruction(Dst
->getOperator());
1534 StringRef Name
= OrigDstI
->TheDef
->getName();
1535 unsigned ExpectedDstINumUses
= Dst
->getNumChildren();
1537 // EXTRACT_SUBREG needs to use a subregister COPY.
1538 if (Name
== "EXTRACT_SUBREG") {
1539 if (!Dst
->getChild(1)->isLeaf())
1540 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
1541 DefInit
*SubRegInit
= dyn_cast
<DefInit
>(Dst
->getChild(1)->getLeafValue());
1543 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1545 CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1546 const TreePatternNode
*ValChild
= Dst
->getChild(0);
1547 if (!ValChild
->isLeaf()) {
1548 // We really have to handle the source instruction, and then insert a
1549 // copy from the subregister.
1550 auto ExtractSrcTy
= getInstResultType(ValChild
);
1552 return ExtractSrcTy
.takeError();
1554 unsigned TempRegID
= M
.allocateTempRegID();
1555 InsertPt
= M
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *ExtractSrcTy
,
1558 auto InsertPtOrError
= createAndImportSubInstructionRenderer(
1559 ++InsertPt
, M
, ValChild
, Src
, TempRegID
);
1560 if (auto Error
= InsertPtOrError
.takeError())
1561 return std::move(Error
);
1563 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
, false, SubIdx
);
1567 // If this is a source operand, this is just a subregister copy.
1568 Record
*RCDef
= getInitValueAsRegClass(ValChild
->getLeafValue());
1570 return failedImport("EXTRACT_SUBREG child #0 could not "
1571 "be coerced to a register class");
1573 CodeGenRegisterClass
*RC
= CGRegs
.getRegClass(RCDef
);
1575 const auto SrcRCDstRCPair
=
1576 RC
->getMatchingSubClassWithSubRegs(CGRegs
, SubIdx
);
1577 if (SrcRCDstRCPair
) {
1578 assert(SrcRCDstRCPair
->second
&& "Couldn't find a matching subclass");
1579 if (SrcRCDstRCPair
->first
!= RC
)
1580 return failedImport("EXTRACT_SUBREG requires an additional COPY");
1583 StringRef RegOperandName
= Dst
->getChild(0)->getName();
1584 if (const auto &SubOperand
= M
.getComplexSubOperand(RegOperandName
)) {
1585 DstMIBuilder
.addRenderer
<RenderComplexPatternOperand
>(
1586 *std::get
<0>(*SubOperand
), RegOperandName
, std::get
<1>(*SubOperand
),
1587 std::get
<2>(*SubOperand
), SubIdx
);
1591 DstMIBuilder
.addRenderer
<CopySubRegRenderer
>(RegOperandName
, SubIdx
);
1595 if (Name
== "REG_SEQUENCE") {
1596 if (!Dst
->getChild(0)->isLeaf())
1597 return failedImport("REG_SEQUENCE child #0 is not a leaf");
1599 Record
*RCDef
= getInitValueAsRegClass(Dst
->getChild(0)->getLeafValue());
1601 return failedImport("REG_SEQUENCE child #0 could not "
1602 "be coerced to a register class");
1604 if ((ExpectedDstINumUses
- 1) % 2 != 0)
1605 return failedImport("Malformed REG_SEQUENCE");
1607 for (unsigned I
= 1; I
!= ExpectedDstINumUses
; I
+= 2) {
1608 const TreePatternNode
*ValChild
= Dst
->getChild(I
);
1609 const TreePatternNode
*SubRegChild
= Dst
->getChild(I
+ 1);
1611 if (DefInit
*SubRegInit
=
1612 dyn_cast
<DefInit
>(SubRegChild
->getLeafValue())) {
1613 CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1615 auto InsertPtOrError
=
1616 importExplicitUseRenderer(InsertPt
, M
, DstMIBuilder
, ValChild
, Src
);
1617 if (auto Error
= InsertPtOrError
.takeError())
1618 return std::move(Error
);
1619 InsertPt
= InsertPtOrError
.get();
1620 DstMIBuilder
.addRenderer
<SubRegIndexRenderer
>(SubIdx
);
1627 // Render the explicit uses.
1628 unsigned DstINumUses
= OrigDstI
->Operands
.size() - OrigDstI
->Operands
.NumDefs
;
1629 if (Name
== "COPY_TO_REGCLASS") {
1630 DstINumUses
--; // Ignore the class constraint.
1631 ExpectedDstINumUses
--;
1634 // NumResults - This is the number of results produced by the instruction in
1636 unsigned NumResults
= OrigDstI
->Operands
.NumDefs
;
1638 // Number of operands we know the output instruction must have. If it is
1639 // variadic, we could have more operands.
1640 unsigned NumFixedOperands
= DstI
->Operands
.size();
1642 // Loop over all of the fixed operands of the instruction pattern, emitting
1643 // code to fill them all in. The node 'N' usually has number children equal to
1644 // the number of input operands of the instruction. However, in cases where
1645 // there are predicate operands for an instruction, we need to fill in the
1646 // 'execute always' values. Match up the node operands to the instruction
1647 // operands to do this.
1650 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
1651 // number of operands at the end of the list which have default values.
1652 // Those can come from the pattern if it provides enough arguments, or be
1653 // filled in with the default if the pattern hasn't provided them. But any
1654 // operand with a default value _before_ the last mandatory one will be
1655 // filled in with their defaults unconditionally.
1656 unsigned NonOverridableOperands
= NumFixedOperands
;
1657 while (NonOverridableOperands
> NumResults
&&
1658 CGP
.operandHasDefault(DstI
->Operands
[NonOverridableOperands
- 1].Rec
))
1659 --NonOverridableOperands
;
1661 unsigned NumDefaultOps
= 0;
1662 for (unsigned I
= 0; I
!= DstINumUses
; ++I
) {
1663 unsigned InstOpNo
= DstI
->Operands
.NumDefs
+ I
;
1665 // Determine what to emit for this operand.
1666 Record
*OperandNode
= DstI
->Operands
[InstOpNo
].Rec
;
1668 // If the operand has default values, introduce them now.
1669 if (CGP
.operandHasDefault(OperandNode
) &&
1670 (InstOpNo
< NonOverridableOperands
|| Child
>= Dst
->getNumChildren())) {
1671 // This is a predicate or optional def operand which the pattern has not
1672 // overridden, or which we aren't letting it override; emit the 'default
1675 const CGIOperandList::OperandInfo
&DstIOperand
= DstI
->Operands
[InstOpNo
];
1676 DagInit
*DefaultOps
= DstIOperand
.Rec
->getValueAsDag("DefaultOps");
1677 if (auto Error
= importDefaultOperandRenderers(InsertPt
, M
, DstMIBuilder
,
1679 return std::move(Error
);
1684 auto InsertPtOrError
= importExplicitUseRenderer(InsertPt
, M
, DstMIBuilder
,
1685 Dst
->getChild(Child
), Src
);
1686 if (auto Error
= InsertPtOrError
.takeError())
1687 return std::move(Error
);
1688 InsertPt
= InsertPtOrError
.get();
1692 if (NumDefaultOps
+ ExpectedDstINumUses
!= DstINumUses
)
1693 return failedImport("Expected " + llvm::to_string(DstINumUses
) +
1694 " used operands but found " +
1695 llvm::to_string(ExpectedDstINumUses
) +
1696 " explicit ones and " + llvm::to_string(NumDefaultOps
) +
1702 Error
GlobalISelEmitter::importDefaultOperandRenderers(
1703 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
1704 DagInit
*DefaultOps
) const {
1705 for (const auto *DefaultOp
: DefaultOps
->getArgs()) {
1706 std::optional
<LLTCodeGen
> OpTyOrNone
;
1708 // Look through ValueType operators.
1709 if (const DagInit
*DefaultDagOp
= dyn_cast
<DagInit
>(DefaultOp
)) {
1710 if (const DefInit
*DefaultDagOperator
=
1711 dyn_cast
<DefInit
>(DefaultDagOp
->getOperator())) {
1712 if (DefaultDagOperator
->getDef()->isSubClassOf("ValueType")) {
1713 OpTyOrNone
= MVTToLLT(getValueType(DefaultDagOperator
->getDef()));
1714 DefaultOp
= DefaultDagOp
->getArg(0);
1719 if (const DefInit
*DefaultDefOp
= dyn_cast
<DefInit
>(DefaultOp
)) {
1720 auto Def
= DefaultDefOp
->getDef();
1721 if (Def
->getName() == "undef_tied_input") {
1722 unsigned TempRegID
= M
.allocateTempRegID();
1723 M
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *OpTyOrNone
,
1725 InsertPt
= M
.insertAction
<BuildMIAction
>(
1726 InsertPt
, M
.allocateOutputInsnID(),
1727 &Target
.getInstruction(RK
.getDef("IMPLICIT_DEF")));
1728 BuildMIAction
&IDMIBuilder
=
1729 *static_cast<BuildMIAction
*>(InsertPt
->get());
1730 IDMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
);
1731 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
);
1733 DstMIBuilder
.addRenderer
<AddRegisterRenderer
>(Target
, Def
);
1738 if (const IntInit
*DefaultIntOp
= dyn_cast
<IntInit
>(DefaultOp
)) {
1739 DstMIBuilder
.addRenderer
<ImmRenderer
>(DefaultIntOp
->getValue());
1743 return failedImport("Could not add default op");
1746 return Error::success();
1749 Error
GlobalISelEmitter::importImplicitDefRenderers(
1750 BuildMIAction
&DstMIBuilder
,
1751 const std::vector
<Record
*> &ImplicitDefs
) const {
1752 if (!ImplicitDefs
.empty())
1753 return failedImport("Pattern defines a physical register");
1754 return Error::success();
1757 std::optional
<const CodeGenRegisterClass
*>
1758 GlobalISelEmitter::getRegClassFromLeaf(const TreePatternNode
*Leaf
) {
1759 assert(Leaf
&& "Expected node?");
1760 assert(Leaf
->isLeaf() && "Expected leaf?");
1761 Record
*RCRec
= getInitValueAsRegClass(Leaf
->getLeafValue());
1763 return std::nullopt
;
1764 CodeGenRegisterClass
*RC
= CGRegs
.getRegClass(RCRec
);
1766 return std::nullopt
;
1770 std::optional
<const CodeGenRegisterClass
*>
1771 GlobalISelEmitter::inferRegClassFromPattern(const TreePatternNode
*N
) {
1773 return std::nullopt
;
1776 return getRegClassFromLeaf(N
);
1778 // We don't have a leaf node, so we have to try and infer something. Check
1779 // that we have an instruction that we an infer something from.
1781 // Only handle things that produce a single type.
1782 if (N
->getNumTypes() != 1)
1783 return std::nullopt
;
1784 Record
*OpRec
= N
->getOperator();
1786 // We only want instructions.
1787 if (!OpRec
->isSubClassOf("Instruction"))
1788 return std::nullopt
;
1790 // Don't want to try and infer things when there could potentially be more
1791 // than one candidate register class.
1792 auto &Inst
= Target
.getInstruction(OpRec
);
1793 if (Inst
.Operands
.NumDefs
> 1)
1794 return std::nullopt
;
1796 // Handle any special-case instructions which we can safely infer register
1798 StringRef InstName
= Inst
.TheDef
->getName();
1799 bool IsRegSequence
= InstName
== "REG_SEQUENCE";
1800 if (IsRegSequence
|| InstName
== "COPY_TO_REGCLASS") {
1801 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
1802 // has the desired register class as the first child.
1803 const TreePatternNode
*RCChild
= N
->getChild(IsRegSequence
? 0 : 1);
1804 if (!RCChild
->isLeaf())
1805 return std::nullopt
;
1806 return getRegClassFromLeaf(RCChild
);
1808 if (InstName
== "INSERT_SUBREG") {
1809 const TreePatternNode
*Child0
= N
->getChild(0);
1810 assert(Child0
->getNumTypes() == 1 && "Unexpected number of types!");
1811 const TypeSetByHwMode
&VTy
= Child0
->getExtType(0);
1812 return inferSuperRegisterClassForNode(VTy
, Child0
, N
->getChild(2));
1814 if (InstName
== "EXTRACT_SUBREG") {
1815 assert(N
->getNumTypes() == 1 && "Unexpected number of types!");
1816 const TypeSetByHwMode
&VTy
= N
->getExtType(0);
1817 return inferSuperRegisterClass(VTy
, N
->getChild(1));
1820 // Handle destination record types that we can safely infer a register class
1822 const auto &DstIOperand
= Inst
.Operands
[0];
1823 Record
*DstIOpRec
= DstIOperand
.Rec
;
1824 if (DstIOpRec
->isSubClassOf("RegisterOperand")) {
1825 DstIOpRec
= DstIOpRec
->getValueAsDef("RegClass");
1826 const CodeGenRegisterClass
&RC
= Target
.getRegisterClass(DstIOpRec
);
1830 if (DstIOpRec
->isSubClassOf("RegisterClass")) {
1831 const CodeGenRegisterClass
&RC
= Target
.getRegisterClass(DstIOpRec
);
1835 return std::nullopt
;
1838 std::optional
<const CodeGenRegisterClass
*>
1839 GlobalISelEmitter::inferSuperRegisterClass(
1840 const TypeSetByHwMode
&Ty
, const TreePatternNode
*SubRegIdxNode
) {
1841 assert(SubRegIdxNode
&& "Expected subregister index node!");
1842 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
1843 if (!Ty
.isValueTypeByHwMode(false))
1844 return std::nullopt
;
1845 if (!SubRegIdxNode
->isLeaf())
1846 return std::nullopt
;
1847 DefInit
*SubRegInit
= dyn_cast
<DefInit
>(SubRegIdxNode
->getLeafValue());
1849 return std::nullopt
;
1850 CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1852 // Use the information we found above to find a minimal register class which
1853 // supports the subregister and type we want.
1855 Target
.getSuperRegForSubReg(Ty
.getValueTypeByHwMode(), CGRegs
, SubIdx
,
1856 /* MustBeAllocatable */ true);
1858 return std::nullopt
;
1862 std::optional
<const CodeGenRegisterClass
*>
1863 GlobalISelEmitter::inferSuperRegisterClassForNode(
1864 const TypeSetByHwMode
&Ty
, const TreePatternNode
*SuperRegNode
,
1865 const TreePatternNode
*SubRegIdxNode
) {
1866 assert(SuperRegNode
&& "Expected super register node!");
1867 // Check if we already have a defined register class for the super register
1868 // node. If we do, then we should preserve that rather than inferring anything
1869 // from the subregister index node. We can assume that whoever wrote the
1870 // pattern in the first place made sure that the super register and
1871 // subregister are compatible.
1872 if (std::optional
<const CodeGenRegisterClass
*> SuperRegisterClass
=
1873 inferRegClassFromPattern(SuperRegNode
))
1874 return *SuperRegisterClass
;
1875 return inferSuperRegisterClass(Ty
, SubRegIdxNode
);
1878 std::optional
<CodeGenSubRegIndex
*> GlobalISelEmitter::inferSubRegIndexForNode(
1879 const TreePatternNode
*SubRegIdxNode
) {
1880 if (!SubRegIdxNode
->isLeaf())
1881 return std::nullopt
;
1883 DefInit
*SubRegInit
= dyn_cast
<DefInit
>(SubRegIdxNode
->getLeafValue());
1885 return std::nullopt
;
1886 return CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1889 Expected
<RuleMatcher
> GlobalISelEmitter::runOnPattern(const PatternToMatch
&P
) {
1890 // Keep track of the matchers and actions to emit.
1891 int Score
= P
.getPatternComplexity(CGP
);
1892 RuleMatcher
M(P
.getSrcRecord()->getLoc());
1893 RuleMatcherScores
[M
.getRuleID()] = Score
;
1894 M
.addAction
<DebugCommentAction
>(llvm::to_string(*P
.getSrcPattern()) +
1896 llvm::to_string(*P
.getDstPattern()));
1898 SmallVector
<Record
*, 4> Predicates
;
1899 P
.getPredicateRecords(Predicates
);
1900 if (auto Error
= importRulePredicates(M
, Predicates
))
1901 return std::move(Error
);
1903 if (!P
.getHwModeFeatures().empty())
1904 M
.addHwModeIdx(declareHwModeCheck(P
.getHwModeFeatures()));
1906 // Next, analyze the pattern operators.
1907 TreePatternNode
*Src
= P
.getSrcPattern();
1908 TreePatternNode
*Dst
= P
.getDstPattern();
1910 // If the root of either pattern isn't a simple operator, ignore it.
1911 if (auto Err
= isTrivialOperatorNode(Dst
))
1912 return failedImport("Dst pattern root isn't a trivial operator (" +
1913 toString(std::move(Err
)) + ")");
1914 if (auto Err
= isTrivialOperatorNode(Src
))
1915 return failedImport("Src pattern root isn't a trivial operator (" +
1916 toString(std::move(Err
)) + ")");
1918 // The different predicates and matchers created during
1919 // addInstructionMatcher use the RuleMatcher M to set up their
1920 // instruction ID (InsnVarID) that are going to be used when
1921 // M is going to be emitted.
1922 // However, the code doing the emission still relies on the IDs
1923 // returned during that process by the RuleMatcher when issuing
1924 // the recordInsn opcodes.
1926 // 1. The order in which we created the predicates
1927 // and such must be the same as the order in which we emit them,
1929 // 2. We need to reset the generation of the IDs in M somewhere between
1930 // addInstructionMatcher and emit
1932 // FIXME: Long term, we don't want to have to rely on this implicit
1933 // naming being the same. One possible solution would be to have
1934 // explicit operator for operation capture and reference those.
1935 // The plus side is that it would expose opportunities to share
1936 // the capture accross rules. The downside is that it would
1937 // introduce a dependency between predicates (captures must happen
1938 // before their first use.)
1939 InstructionMatcher
&InsnMatcherTemp
= M
.addInstructionMatcher(Src
->getName());
1940 unsigned TempOpIdx
= 0;
1942 const auto SavedFlags
= M
.setGISelFlags(P
.getSrcRecord());
1944 auto InsnMatcherOrError
=
1945 createAndImportSelDAGMatcher(M
, InsnMatcherTemp
, Src
, TempOpIdx
);
1946 if (auto Error
= InsnMatcherOrError
.takeError())
1947 return std::move(Error
);
1948 InstructionMatcher
&InsnMatcher
= InsnMatcherOrError
.get();
1950 if (Dst
->isLeaf()) {
1951 Record
*RCDef
= getInitValueAsRegClass(Dst
->getLeafValue());
1953 const CodeGenRegisterClass
&RC
= Target
.getRegisterClass(RCDef
);
1955 // We need to replace the def and all its uses with the specified
1956 // operand. However, we must also insert COPY's wherever needed.
1957 // For now, emit a copy and let the register allocator clean up.
1958 auto &DstI
= Target
.getInstruction(RK
.getDef("COPY"));
1959 const auto &DstIOperand
= DstI
.Operands
[0];
1961 OperandMatcher
&OM0
= InsnMatcher
.getOperand(0);
1962 OM0
.setSymbolicName(DstIOperand
.Name
);
1963 M
.defineOperand(OM0
.getSymbolicName(), OM0
);
1964 OM0
.addPredicate
<RegisterBankOperandMatcher
>(RC
);
1966 auto &DstMIBuilder
=
1967 M
.addAction
<BuildMIAction
>(M
.allocateOutputInsnID(), &DstI
);
1968 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstIOperand
.Name
);
1969 DstMIBuilder
.addRenderer
<CopyRenderer
>(Dst
->getName());
1970 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 0, RC
);
1972 // We're done with this pattern! It's eligible for GISel emission; return
1974 ++NumPatternImported
;
1975 return std::move(M
);
1978 return failedImport("Dst pattern root isn't a known leaf");
1981 // Start with the defined operands (i.e., the results of the root operator).
1982 Record
*DstOp
= Dst
->getOperator();
1983 if (!DstOp
->isSubClassOf("Instruction"))
1984 return failedImport("Pattern operator isn't an instruction");
1986 auto &DstI
= Target
.getInstruction(DstOp
);
1987 StringRef DstIName
= DstI
.TheDef
->getName();
1989 unsigned DstNumDefs
= DstI
.Operands
.NumDefs
,
1990 SrcNumDefs
= Src
->getExtTypes().size();
1991 if (DstNumDefs
< SrcNumDefs
) {
1992 if (DstNumDefs
!= 0)
1993 return failedImport("Src pattern result has more defs than dst MI (" +
1994 to_string(SrcNumDefs
) + " def(s) vs " +
1995 to_string(DstNumDefs
) + " def(s))");
1997 bool FoundNoUsePred
= false;
1998 for (const auto &Pred
: InsnMatcher
.predicates()) {
1999 if ((FoundNoUsePred
= isa
<NoUsePredicateMatcher
>(Pred
.get())))
2002 if (!FoundNoUsePred
)
2003 return failedImport("Src pattern result has " + to_string(SrcNumDefs
) +
2004 " def(s) without the HasNoUse predicate set to true "
2005 "but Dst MI has no def");
2008 // The root of the match also has constraints on the register bank so that it
2009 // matches the result instruction.
2011 unsigned N
= std::min(DstNumDefs
, SrcNumDefs
);
2012 for (unsigned I
= 0; I
< N
; ++I
) {
2013 const TypeSetByHwMode
&VTy
= Src
->getExtType(I
);
2015 const auto &DstIOperand
= DstI
.Operands
[OpIdx
];
2016 Record
*DstIOpRec
= DstIOperand
.Rec
;
2017 if (DstIName
== "COPY_TO_REGCLASS") {
2018 DstIOpRec
= getInitValueAsRegClass(Dst
->getChild(1)->getLeafValue());
2020 if (DstIOpRec
== nullptr)
2021 return failedImport(
2022 "COPY_TO_REGCLASS operand #1 isn't a register class");
2023 } else if (DstIName
== "REG_SEQUENCE") {
2024 DstIOpRec
= getInitValueAsRegClass(Dst
->getChild(0)->getLeafValue());
2025 if (DstIOpRec
== nullptr)
2026 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
2027 } else if (DstIName
== "EXTRACT_SUBREG") {
2028 auto InferredClass
= inferRegClassFromPattern(Dst
->getChild(0));
2030 return failedImport(
2031 "Could not infer class for EXTRACT_SUBREG operand #0");
2033 // We can assume that a subregister is in the same bank as it's super
2035 DstIOpRec
= (*InferredClass
)->getDef();
2036 } else if (DstIName
== "INSERT_SUBREG") {
2037 auto MaybeSuperClass
= inferSuperRegisterClassForNode(
2038 VTy
, Dst
->getChild(0), Dst
->getChild(2));
2039 if (!MaybeSuperClass
)
2040 return failedImport(
2041 "Cannot infer register class for INSERT_SUBREG operand #0");
2042 // Move to the next pattern here, because the register class we found
2043 // doesn't necessarily have a record associated with it. So, we can't
2044 // set DstIOpRec using this.
2045 OperandMatcher
&OM
= InsnMatcher
.getOperand(OpIdx
);
2046 OM
.setSymbolicName(DstIOperand
.Name
);
2047 M
.defineOperand(OM
.getSymbolicName(), OM
);
2048 OM
.addPredicate
<RegisterBankOperandMatcher
>(**MaybeSuperClass
);
2051 } else if (DstIName
== "SUBREG_TO_REG") {
2052 auto MaybeRegClass
= inferSuperRegisterClass(VTy
, Dst
->getChild(2));
2054 return failedImport(
2055 "Cannot infer register class for SUBREG_TO_REG operand #0");
2056 OperandMatcher
&OM
= InsnMatcher
.getOperand(OpIdx
);
2057 OM
.setSymbolicName(DstIOperand
.Name
);
2058 M
.defineOperand(OM
.getSymbolicName(), OM
);
2059 OM
.addPredicate
<RegisterBankOperandMatcher
>(**MaybeRegClass
);
2062 } else if (DstIOpRec
->isSubClassOf("RegisterOperand"))
2063 DstIOpRec
= DstIOpRec
->getValueAsDef("RegClass");
2064 else if (!DstIOpRec
->isSubClassOf("RegisterClass"))
2065 return failedImport("Dst MI def isn't a register class" +
2068 OperandMatcher
&OM
= InsnMatcher
.getOperand(OpIdx
);
2069 OM
.setSymbolicName(DstIOperand
.Name
);
2070 M
.defineOperand(OM
.getSymbolicName(), OM
);
2071 OM
.addPredicate
<RegisterBankOperandMatcher
>(
2072 Target
.getRegisterClass(DstIOpRec
));
2076 auto DstMIBuilderOrError
=
2077 createAndImportInstructionRenderer(M
, InsnMatcher
, Src
, Dst
);
2078 if (auto Error
= DstMIBuilderOrError
.takeError())
2079 return std::move(Error
);
2080 BuildMIAction
&DstMIBuilder
= DstMIBuilderOrError
.get();
2082 // Render the implicit defs.
2083 // These are only added to the root of the result.
2084 if (auto Error
= importImplicitDefRenderers(DstMIBuilder
, P
.getDstRegs()))
2085 return std::move(Error
);
2087 DstMIBuilder
.chooseInsnToMutate(M
);
2089 // Constrain the registers to classes. This is normally derived from the
2090 // emitted instruction but a few instructions require special handling.
2091 if (DstIName
== "COPY_TO_REGCLASS") {
2092 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2093 // result is constrained to the class given by the second child.
2095 getInitValueAsRegClass(Dst
->getChild(1)->getLeafValue());
2097 if (DstIOpRec
== nullptr)
2098 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2100 M
.addAction
<ConstrainOperandToRegClassAction
>(
2101 0, 0, Target
.getRegisterClass(DstIOpRec
));
2103 // We're done with this pattern! It's eligible for GISel emission; return
2105 ++NumPatternImported
;
2106 return std::move(M
);
2109 if (DstIName
== "EXTRACT_SUBREG") {
2110 auto SuperClass
= inferRegClassFromPattern(Dst
->getChild(0));
2112 return failedImport(
2113 "Cannot infer register class from EXTRACT_SUBREG operand #0");
2115 auto SubIdx
= inferSubRegIndexForNode(Dst
->getChild(1));
2117 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2119 // It would be nice to leave this constraint implicit but we're required
2120 // to pick a register class so constrain the result to a register class
2121 // that can hold the correct MVT.
2123 // FIXME: This may introduce an extra copy if the chosen class doesn't
2124 // actually contain the subregisters.
2125 assert(Src
->getExtTypes().size() == 1 &&
2126 "Expected Src of EXTRACT_SUBREG to have one result type");
2128 const auto SrcRCDstRCPair
=
2129 (*SuperClass
)->getMatchingSubClassWithSubRegs(CGRegs
, *SubIdx
);
2130 if (!SrcRCDstRCPair
) {
2131 return failedImport("subreg index is incompatible "
2132 "with inferred reg class");
2135 assert(SrcRCDstRCPair
->second
&& "Couldn't find a matching subclass");
2136 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 0,
2137 *SrcRCDstRCPair
->second
);
2138 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 1, *SrcRCDstRCPair
->first
);
2140 // We're done with this pattern! It's eligible for GISel emission; return
2142 ++NumPatternImported
;
2143 return std::move(M
);
2146 if (DstIName
== "INSERT_SUBREG") {
2147 assert(Src
->getExtTypes().size() == 1 &&
2148 "Expected Src of INSERT_SUBREG to have one result type");
2149 // We need to constrain the destination, a super regsister source, and a
2150 // subregister source.
2151 auto SubClass
= inferRegClassFromPattern(Dst
->getChild(1));
2153 return failedImport(
2154 "Cannot infer register class from INSERT_SUBREG operand #1");
2155 auto SuperClass
= inferSuperRegisterClassForNode(
2156 Src
->getExtType(0), Dst
->getChild(0), Dst
->getChild(2));
2158 return failedImport(
2159 "Cannot infer register class for INSERT_SUBREG operand #0");
2160 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 0, **SuperClass
);
2161 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 1, **SuperClass
);
2162 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 2, **SubClass
);
2163 ++NumPatternImported
;
2164 return std::move(M
);
2167 if (DstIName
== "SUBREG_TO_REG") {
2168 // We need to constrain the destination and subregister source.
2169 assert(Src
->getExtTypes().size() == 1 &&
2170 "Expected Src of SUBREG_TO_REG to have one result type");
2172 // Attempt to infer the subregister source from the first child. If it has
2173 // an explicitly given register class, we'll use that. Otherwise, we will
2175 auto SubClass
= inferRegClassFromPattern(Dst
->getChild(1));
2177 return failedImport(
2178 "Cannot infer register class from SUBREG_TO_REG child #1");
2179 // We don't have a child to look at that might have a super register node.
2181 inferSuperRegisterClass(Src
->getExtType(0), Dst
->getChild(2));
2183 return failedImport(
2184 "Cannot infer register class for SUBREG_TO_REG operand #0");
2185 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 0, **SuperClass
);
2186 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 2, **SubClass
);
2187 ++NumPatternImported
;
2188 return std::move(M
);
2191 if (DstIName
== "REG_SEQUENCE") {
2192 auto SuperClass
= inferRegClassFromPattern(Dst
->getChild(0));
2194 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 0, **SuperClass
);
2196 unsigned Num
= Dst
->getNumChildren();
2197 for (unsigned I
= 1; I
!= Num
; I
+= 2) {
2198 TreePatternNode
*SubRegChild
= Dst
->getChild(I
+ 1);
2200 auto SubIdx
= inferSubRegIndexForNode(SubRegChild
);
2202 return failedImport("REG_SEQUENCE child is not a subreg index");
2204 const auto SrcRCDstRCPair
=
2205 (*SuperClass
)->getMatchingSubClassWithSubRegs(CGRegs
, *SubIdx
);
2207 M
.addAction
<ConstrainOperandToRegClassAction
>(0, I
,
2208 *SrcRCDstRCPair
->second
);
2211 ++NumPatternImported
;
2212 return std::move(M
);
2215 M
.addAction
<ConstrainOperandsToDefinitionAction
>(0);
2217 // We're done with this pattern! It's eligible for GISel emission; return it.
2218 ++NumPatternImported
;
2219 return std::move(M
);
2223 GlobalISelEmitter::buildMatchTable(MutableArrayRef
<RuleMatcher
> Rules
,
2224 bool Optimize
, bool WithCoverage
) {
2225 std::vector
<Matcher
*> InputRules
;
2226 for (Matcher
&Rule
: Rules
)
2227 InputRules
.push_back(&Rule
);
2230 return MatchTable::buildTable(InputRules
, WithCoverage
);
2232 unsigned CurrentOrdering
= 0;
2233 StringMap
<unsigned> OpcodeOrder
;
2234 for (RuleMatcher
&Rule
: Rules
) {
2235 const StringRef Opcode
= Rule
.getOpcode();
2236 assert(!Opcode
.empty() && "Didn't expect an undefined opcode");
2237 if (OpcodeOrder
.count(Opcode
) == 0)
2238 OpcodeOrder
[Opcode
] = CurrentOrdering
++;
2241 llvm::stable_sort(InputRules
, [&OpcodeOrder
](const Matcher
*A
,
2243 auto *L
= static_cast<const RuleMatcher
*>(A
);
2244 auto *R
= static_cast<const RuleMatcher
*>(B
);
2245 return std::make_tuple(OpcodeOrder
[L
->getOpcode()], L
->getNumOperands()) <
2246 std::make_tuple(OpcodeOrder
[R
->getOpcode()], R
->getNumOperands());
2249 for (Matcher
*Rule
: InputRules
)
2252 std::vector
<std::unique_ptr
<Matcher
>> MatcherStorage
;
2253 std::vector
<Matcher
*> OptRules
=
2254 optimizeRules
<GroupMatcher
>(InputRules
, MatcherStorage
);
2256 for (Matcher
*Rule
: OptRules
)
2259 OptRules
= optimizeRules
<SwitchMatcher
>(OptRules
, MatcherStorage
);
2261 return MatchTable::buildTable(OptRules
, WithCoverage
);
2264 void GlobalISelEmitter::emitAdditionalImpl(raw_ostream
&OS
) {
2265 OS
<< "bool " << getClassName()
2266 << "::selectImpl(MachineInstr &I, CodeGenCoverage "
2267 "&CoverageInfo) const {\n"
2268 << " const PredicateBitset AvailableFeatures = "
2269 "getAvailableFeatures();\n"
2270 << " MachineIRBuilder B(I);\n"
2271 << " State.MIs.clear();\n"
2272 << " State.MIs.push_back(&I);\n\n"
2273 << " if (executeMatchTable(*this, State, ExecInfo, B"
2274 << ", getMatchTable(), TII, MF->getRegInfo(), TRI, RBI, AvailableFeatures"
2275 << ", &CoverageInfo)) {\n"
2276 << " return true;\n"
2278 << " return false;\n"
2282 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream
&OS
) {
2283 std::vector
<Record
*> MatchedRecords
;
2284 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2285 std::back_inserter(MatchedRecords
), [&](Record
*R
) {
2286 return !R
->getValueAsString("GISelPredicateCode").empty();
2288 emitMIPredicateFnsImpl
<Record
*>(
2290 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
2291 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
2292 " const auto &Operands = State.RecordedOperands;\n"
2293 " (void)Operands;\n"
2295 ArrayRef
<Record
*>(MatchedRecords
), &getPatFragPredicateEnumName
,
2296 [&](Record
*R
) { return R
->getValueAsString("GISelPredicateCode"); },
2297 "PatFrag predicates.");
2300 void GlobalISelEmitter::emitI64ImmPredicateFns(raw_ostream
&OS
) {
2301 std::vector
<Record
*> MatchedRecords
;
2302 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2303 std::back_inserter(MatchedRecords
), [&](Record
*R
) {
2305 return !R
->getValueAsString("ImmediateCode").empty() &&
2306 !R
->getValueAsBitOrUnset("IsAPFloat", Unset
) &&
2307 !R
->getValueAsBit("IsAPInt");
2309 emitImmPredicateFnsImpl
<Record
*>(
2310 OS
, "I64", "int64_t", ArrayRef
<Record
*>(MatchedRecords
),
2311 &getPatFragPredicateEnumName
,
2312 [&](Record
*R
) { return R
->getValueAsString("ImmediateCode"); },
2313 "PatFrag predicates.");
2316 void GlobalISelEmitter::emitAPFloatImmPredicateFns(raw_ostream
&OS
) {
2317 std::vector
<Record
*> MatchedRecords
;
2318 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2319 std::back_inserter(MatchedRecords
), [&](Record
*R
) {
2321 return !R
->getValueAsString("ImmediateCode").empty() &&
2322 R
->getValueAsBitOrUnset("IsAPFloat", Unset
);
2324 emitImmPredicateFnsImpl
<Record
*>(
2325 OS
, "APFloat", "const APFloat &", ArrayRef
<Record
*>(MatchedRecords
),
2326 &getPatFragPredicateEnumName
,
2327 [&](Record
*R
) { return R
->getValueAsString("ImmediateCode"); },
2328 "PatFrag predicates.");
2331 void GlobalISelEmitter::emitAPIntImmPredicateFns(raw_ostream
&OS
) {
2332 std::vector
<Record
*> MatchedRecords
;
2333 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2334 std::back_inserter(MatchedRecords
), [&](Record
*R
) {
2335 return !R
->getValueAsString("ImmediateCode").empty() &&
2336 R
->getValueAsBit("IsAPInt");
2338 emitImmPredicateFnsImpl
<Record
*>(
2339 OS
, "APInt", "const APInt &", ArrayRef
<Record
*>(MatchedRecords
),
2340 &getPatFragPredicateEnumName
,
2341 [&](Record
*R
) { return R
->getValueAsString("ImmediateCode"); },
2342 "PatFrag predicates.");
2345 void GlobalISelEmitter::emitTestSimplePredicate(raw_ostream
&OS
) {
2346 OS
<< "bool " << getClassName() << "::testSimplePredicate(unsigned) const {\n"
2347 << " llvm_unreachable(\"" + getClassName() +
2348 " does not support simple predicates!\");\n"
2349 << " return false;\n"
2353 void GlobalISelEmitter::emitRunCustomAction(raw_ostream
&OS
) {
2354 OS
<< "void " << getClassName()
2355 << "::runCustomAction(unsigned, const MatcherState&, NewMIVector &) const "
2357 << " llvm_unreachable(\"" + getClassName() +
2358 " does not support custom C++ actions!\");\n"
2362 void GlobalISelEmitter::postProcessRule(RuleMatcher
&M
) {
2363 SmallPtrSet
<Record
*, 16> UsedRegs
;
2365 // TODO: deal with subregs?
2366 for (auto &A
: M
.actions()) {
2367 auto *MI
= dyn_cast
<BuildMIAction
>(A
.get());
2371 for (auto *Use
: MI
->getCGI()->ImplicitUses
)
2372 UsedRegs
.insert(Use
);
2375 for (auto &A
: M
.actions()) {
2376 auto *MI
= dyn_cast
<BuildMIAction
>(A
.get());
2380 for (auto *Def
: MI
->getCGI()->ImplicitDefs
) {
2381 if (!UsedRegs
.contains(Def
))
2382 MI
->setDeadImplicitDef(Def
);
2387 void GlobalISelEmitter::run(raw_ostream
&OS
) {
2388 if (!UseCoverageFile
.empty()) {
2389 RuleCoverage
= CodeGenCoverage();
2390 auto RuleCoverageBufOrErr
= MemoryBuffer::getFile(UseCoverageFile
);
2391 if (!RuleCoverageBufOrErr
) {
2392 PrintWarning(SMLoc(), "Missing rule coverage data");
2393 RuleCoverage
= std::nullopt
;
2395 if (!RuleCoverage
->parse(*RuleCoverageBufOrErr
.get(), Target
.getName())) {
2396 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
2397 RuleCoverage
= std::nullopt
;
2402 // Track the run-time opcode values
2403 gatherOpcodeValues();
2404 // Track the run-time LLT ID values
2405 gatherTypeIDValues();
2407 // Track the GINodeEquiv definitions.
2410 AllPatFrags
= RK
.getAllDerivedDefinitions("PatFrags");
2412 emitSourceFileHeader(
2413 ("Global Instruction Selector for the " + Target
.getName() + " target")
2416 std::vector
<RuleMatcher
> Rules
;
2417 // Look through the SelectionDAG patterns we found, possibly emitting some.
2418 for (const PatternToMatch
&Pat
: CGP
.ptms()) {
2421 auto MatcherOrErr
= runOnPattern(Pat
);
2423 // The pattern analysis can fail, indicating an unsupported pattern.
2424 // Report that if we've been asked to do so.
2425 if (auto Err
= MatcherOrErr
.takeError()) {
2426 if (WarnOnSkippedPatterns
) {
2427 PrintWarning(Pat
.getSrcRecord()->getLoc(),
2428 "Skipped pattern: " + toString(std::move(Err
)));
2430 consumeError(std::move(Err
));
2432 ++NumPatternImportsSkipped
;
2437 if (RuleCoverage
->isCovered(MatcherOrErr
->getRuleID()))
2438 ++NumPatternsTested
;
2440 PrintWarning(Pat
.getSrcRecord()->getLoc(),
2441 "Pattern is not covered by a test");
2443 Rules
.push_back(std::move(MatcherOrErr
.get()));
2444 postProcessRule(Rules
.back());
2447 // Comparison function to order records by name.
2448 auto orderByName
= [](const Record
*A
, const Record
*B
) {
2449 return A
->getName() < B
->getName();
2452 std::vector
<Record
*> ComplexPredicates
=
2453 RK
.getAllDerivedDefinitions("GIComplexOperandMatcher");
2454 llvm::sort(ComplexPredicates
, orderByName
);
2456 std::vector
<StringRef
> CustomRendererFns
;
2457 transform(RK
.getAllDerivedDefinitions("GICustomOperandRenderer"),
2458 std::back_inserter(CustomRendererFns
), [](const auto &Record
) {
2459 return Record
->getValueAsString("RendererFn");
2461 // Sort and remove duplicates to get a list of unique renderer functions, in
2462 // case some were mentioned more than once.
2463 llvm::sort(CustomRendererFns
);
2464 CustomRendererFns
.erase(
2465 std::unique(CustomRendererFns
.begin(), CustomRendererFns
.end()),
2466 CustomRendererFns
.end());
2468 // Create a table containing the LLT objects needed by the matcher and an enum
2469 // for the matcher to reference them with.
2470 std::vector
<LLTCodeGen
> TypeObjects
;
2471 append_range(TypeObjects
, KnownTypes
);
2472 llvm::sort(TypeObjects
);
2475 llvm::stable_sort(Rules
, [&](const RuleMatcher
&A
, const RuleMatcher
&B
) {
2476 int ScoreA
= RuleMatcherScores
[A
.getRuleID()];
2477 int ScoreB
= RuleMatcherScores
[B
.getRuleID()];
2478 if (ScoreA
> ScoreB
)
2480 if (ScoreB
> ScoreA
)
2482 if (A
.isHigherPriorityThan(B
)) {
2483 assert(!B
.isHigherPriorityThan(A
) && "Cannot be more important "
2484 "and less important at "
2491 unsigned MaxTemporaries
= 0;
2492 for (const auto &Rule
: Rules
)
2493 MaxTemporaries
= std::max(MaxTemporaries
, Rule
.countRendererFns());
2495 // Build match table
2496 const MatchTable Table
=
2497 buildMatchTable(Rules
, OptimizeMatchTable
, GenerateCoverage
);
2499 emitPredicateBitset(OS
, "GET_GLOBALISEL_PREDICATE_BITSET");
2500 emitTemporariesDecl(OS
, "GET_GLOBALISEL_TEMPORARIES_DECL");
2501 emitTemporariesInit(OS
, MaxTemporaries
, "GET_GLOBALISEL_TEMPORARIES_INIT");
2502 emitExecutorImpl(OS
, Table
, TypeObjects
, Rules
, ComplexPredicates
,
2503 CustomRendererFns
, "GET_GLOBALISEL_IMPL");
2504 emitPredicatesDecl(OS
, "GET_GLOBALISEL_PREDICATES_DECL");
2505 emitPredicatesInit(OS
, "GET_GLOBALISEL_PREDICATES_INIT");
2508 void GlobalISelEmitter::declareSubtargetFeature(Record
*Predicate
) {
2509 SubtargetFeatures
.try_emplace(Predicate
, Predicate
, SubtargetFeatures
.size());
2512 unsigned GlobalISelEmitter::declareHwModeCheck(StringRef HwModeFeatures
) {
2513 return HwModes
.emplace(HwModeFeatures
.str(), HwModes
.size()).first
->second
;
2516 } // end anonymous namespace
2518 //===----------------------------------------------------------------------===//
2520 static TableGen::Emitter::OptClass
<GlobalISelEmitter
>
2521 X("gen-global-isel", "Generate GlobalISel selector");