2 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/Target/GlobalISel/Target.td.
14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15 /// backend, filters out the ones that are unsupported, maps
16 /// SelectionDAG-specific constructs to their GlobalISel counterpart
17 /// (when applicable: MVT to LLT; SDNode to generic Instruction).
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
23 /// The generated file defines a single method:
24 /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25 /// intended to be used in InstructionSelector::select as the first-step
26 /// selector for the patterns that don't require complex C++.
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
31 //===----------------------------------------------------------------------===//
33 #include "Basic/CodeGenIntrinsics.h"
34 #include "Common/CodeGenDAGPatterns.h"
35 #include "Common/CodeGenInstruction.h"
36 #include "Common/CodeGenRegisters.h"
37 #include "Common/CodeGenTarget.h"
38 #include "Common/GlobalISel/GlobalISelMatchTable.h"
39 #include "Common/GlobalISel/GlobalISelMatchTableExecutorEmitter.h"
40 #include "Common/InfoByHwMode.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/CodeGenTypes/LowLevelType.h"
43 #include "llvm/CodeGenTypes/MachineValueType.h"
44 #include "llvm/Support/CodeGenCoverage.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Error.h"
47 #include "llvm/Support/ScopedPrinter.h"
48 #include "llvm/TableGen/Error.h"
49 #include "llvm/TableGen/Record.h"
50 #include "llvm/TableGen/TableGenBackend.h"
54 using namespace llvm::gi
;
56 using action_iterator
= RuleMatcher::action_iterator
;
58 #define DEBUG_TYPE "gisel-emitter"
60 STATISTIC(NumPatternTotal
, "Total number of patterns");
61 STATISTIC(NumPatternImported
, "Number of patterns imported from SelectionDAG");
62 STATISTIC(NumPatternImportsSkipped
, "Number of SelectionDAG imports skipped");
63 STATISTIC(NumPatternsTested
,
64 "Number of patterns executed according to coverage information");
66 cl::OptionCategory
GlobalISelEmitterCat("Options for -gen-global-isel");
68 static cl::opt
<bool> WarnOnSkippedPatterns(
69 "warn-on-skipped-patterns",
70 cl::desc("Explain why a pattern was skipped for inclusion "
71 "in the GlobalISel selector"),
72 cl::init(false), cl::cat(GlobalISelEmitterCat
));
74 static cl::opt
<bool> GenerateCoverage(
75 "instrument-gisel-coverage",
76 cl::desc("Generate coverage instrumentation for GlobalISel"),
77 cl::init(false), cl::cat(GlobalISelEmitterCat
));
79 static cl::opt
<std::string
> UseCoverageFile(
80 "gisel-coverage-file", cl::init(""),
81 cl::desc("Specify file to retrieve coverage information from"),
82 cl::cat(GlobalISelEmitterCat
));
84 static cl::opt
<bool> OptimizeMatchTable(
85 "optimize-match-table",
86 cl::desc("Generate an optimized version of the match table"),
87 cl::init(true), cl::cat(GlobalISelEmitterCat
));
91 static std::string
explainPredicates(const TreePatternNode
&N
) {
92 std::string Explanation
;
93 StringRef Separator
= "";
94 for (const TreePredicateCall
&Call
: N
.getPredicateCalls()) {
95 const TreePredicateFn
&P
= Call
.Fn
;
97 (Separator
+ P
.getOrigPatFragRecord()->getRecord()->getName()).str();
100 if (P
.isAlwaysTrue())
101 Explanation
+= " always-true";
102 if (P
.isImmediatePattern())
103 Explanation
+= " immediate";
106 Explanation
+= " unindexed";
108 if (P
.isNonExtLoad())
109 Explanation
+= " non-extload";
110 if (P
.isAnyExtLoad())
111 Explanation
+= " extload";
112 if (P
.isSignExtLoad())
113 Explanation
+= " sextload";
114 if (P
.isZeroExtLoad())
115 Explanation
+= " zextload";
117 if (P
.isNonTruncStore())
118 Explanation
+= " non-truncstore";
119 if (P
.isTruncStore())
120 Explanation
+= " truncstore";
122 if (const Record
*VT
= P
.getMemoryVT())
123 Explanation
+= (" MemVT=" + VT
->getName()).str();
124 if (const Record
*VT
= P
.getScalarMemoryVT())
125 Explanation
+= (" ScalarVT(MemVT)=" + VT
->getName()).str();
127 if (const ListInit
*AddrSpaces
= P
.getAddressSpaces()) {
128 raw_string_ostream
OS(Explanation
);
129 OS
<< " AddressSpaces=[";
131 StringRef AddrSpaceSeparator
;
132 for (const Init
*Val
: AddrSpaces
->getValues()) {
133 const IntInit
*IntVal
= dyn_cast
<IntInit
>(Val
);
137 OS
<< AddrSpaceSeparator
<< IntVal
->getValue();
138 AddrSpaceSeparator
= ", ";
144 int64_t MinAlign
= P
.getMinAlignment();
146 Explanation
+= " MinAlign=" + utostr(MinAlign
);
148 if (P
.isAtomicOrderingMonotonic())
149 Explanation
+= " monotonic";
150 if (P
.isAtomicOrderingAcquire())
151 Explanation
+= " acquire";
152 if (P
.isAtomicOrderingRelease())
153 Explanation
+= " release";
154 if (P
.isAtomicOrderingAcquireRelease())
155 Explanation
+= " acq_rel";
156 if (P
.isAtomicOrderingSequentiallyConsistent())
157 Explanation
+= " seq_cst";
158 if (P
.isAtomicOrderingAcquireOrStronger())
159 Explanation
+= " >=acquire";
160 if (P
.isAtomicOrderingWeakerThanAcquire())
161 Explanation
+= " <acquire";
162 if (P
.isAtomicOrderingReleaseOrStronger())
163 Explanation
+= " >=release";
164 if (P
.isAtomicOrderingWeakerThanRelease())
165 Explanation
+= " <release";
170 std::string
explainOperator(const Record
*Operator
) {
171 if (Operator
->isSubClassOf("SDNode"))
172 return (" (" + Operator
->getValueAsString("Opcode") + ")").str();
174 if (Operator
->isSubClassOf("Intrinsic"))
175 return (" (Operator is an Intrinsic, " + Operator
->getName() + ")").str();
177 if (Operator
->isSubClassOf("ComplexPattern"))
178 return (" (Operator is an unmapped ComplexPattern, " + Operator
->getName() +
182 if (Operator
->isSubClassOf("SDNodeXForm"))
183 return (" (Operator is an unmapped SDNodeXForm, " + Operator
->getName() +
187 return (" (Operator " + Operator
->getName() + " not understood)").str();
190 /// Helper function to let the emitter report skip reason error messages.
191 static Error
failedImport(const Twine
&Reason
) {
192 return make_error
<StringError
>(Reason
, inconvertibleErrorCode());
195 static Error
isTrivialOperatorNode(const TreePatternNode
&N
) {
196 std::string Explanation
;
197 std::string Separator
;
199 bool HasUnsupportedPredicate
= false;
200 for (const TreePredicateCall
&Call
: N
.getPredicateCalls()) {
201 const TreePredicateFn
&Predicate
= Call
.Fn
;
203 if (Predicate
.isAlwaysTrue())
206 if (Predicate
.isImmediatePattern())
209 if (Predicate
.hasNoUse() || Predicate
.hasOneUse())
212 if (Predicate
.isNonExtLoad() || Predicate
.isAnyExtLoad() ||
213 Predicate
.isSignExtLoad() || Predicate
.isZeroExtLoad())
216 if (Predicate
.isNonTruncStore() || Predicate
.isTruncStore())
219 if (Predicate
.isLoad() && Predicate
.getMemoryVT())
222 if (Predicate
.isLoad() || Predicate
.isStore()) {
223 if (Predicate
.isUnindexed())
227 if (Predicate
.isLoad() || Predicate
.isStore() || Predicate
.isAtomic()) {
228 const ListInit
*AddrSpaces
= Predicate
.getAddressSpaces();
229 if (AddrSpaces
&& !AddrSpaces
->empty())
232 if (Predicate
.getMinAlignment() > 0)
236 if (Predicate
.isAtomic() && Predicate
.getMemoryVT())
239 if (Predicate
.isAtomic() &&
240 (Predicate
.isAtomicOrderingMonotonic() ||
241 Predicate
.isAtomicOrderingAcquire() ||
242 Predicate
.isAtomicOrderingRelease() ||
243 Predicate
.isAtomicOrderingAcquireRelease() ||
244 Predicate
.isAtomicOrderingSequentiallyConsistent() ||
245 Predicate
.isAtomicOrderingAcquireOrStronger() ||
246 Predicate
.isAtomicOrderingWeakerThanAcquire() ||
247 Predicate
.isAtomicOrderingReleaseOrStronger() ||
248 Predicate
.isAtomicOrderingWeakerThanRelease()))
251 if (Predicate
.hasGISelPredicateCode())
254 HasUnsupportedPredicate
= true;
255 Explanation
= Separator
+ "Has a predicate (" + explainPredicates(N
) + ")";
257 Explanation
+= (Separator
+ "first-failing:" +
258 Predicate
.getOrigPatFragRecord()->getRecord()->getName())
263 if (!HasUnsupportedPredicate
)
264 return Error::success();
266 return failedImport(Explanation
);
269 static const Record
*getInitValueAsRegClass(const Init
*V
) {
270 if (const DefInit
*VDefInit
= dyn_cast
<DefInit
>(V
)) {
271 if (VDefInit
->getDef()->isSubClassOf("RegisterOperand"))
272 return VDefInit
->getDef()->getValueAsDef("RegClass");
273 if (VDefInit
->getDef()->isSubClassOf("RegisterClass"))
274 return VDefInit
->getDef();
279 static std::string
getScopedName(unsigned Scope
, const std::string
&Name
) {
280 return ("pred:" + Twine(Scope
) + ":" + Name
).str();
283 static std::string
getMangledRootDefName(StringRef DefOperandName
) {
284 return ("DstI[" + DefOperandName
+ "]").str();
287 //===- GlobalISelEmitter class --------------------------------------------===//
289 static Expected
<LLTCodeGen
> getInstResultType(const TreePatternNode
&Dst
,
290 const CodeGenTarget
&Target
) {
291 // While we allow more than one output (both implicit and explicit defs)
292 // below, we only expect one explicit def here.
293 assert(Dst
.getOperator()->isSubClassOf("Instruction"));
294 CodeGenInstruction
&InstInfo
= Target
.getInstruction(Dst
.getOperator());
295 if (!InstInfo
.Operands
.NumDefs
)
296 return failedImport("Dst pattern child needs a def");
298 ArrayRef
<TypeSetByHwMode
> ChildTypes
= Dst
.getExtTypes();
299 if (ChildTypes
.size() < 1)
300 return failedImport("Dst pattern child has no result");
302 // If there are multiple results, just take the first one (this is how
303 // SelectionDAG does it).
304 std::optional
<LLTCodeGen
> MaybeOpTy
;
305 if (ChildTypes
.front().isMachineValueType()) {
306 MaybeOpTy
= MVTToLLT(ChildTypes
.front().getMachineValueType().SimpleTy
);
310 return failedImport("Dst operand has an unsupported type");
314 class GlobalISelEmitter final
: public GlobalISelMatchTableExecutorEmitter
{
316 explicit GlobalISelEmitter(const RecordKeeper
&RK
);
318 void emitAdditionalImpl(raw_ostream
&OS
) override
;
320 void emitMIPredicateFns(raw_ostream
&OS
) override
;
321 void emitI64ImmPredicateFns(raw_ostream
&OS
) override
;
322 void emitAPFloatImmPredicateFns(raw_ostream
&OS
) override
;
323 void emitAPIntImmPredicateFns(raw_ostream
&OS
) override
;
324 void emitTestSimplePredicate(raw_ostream
&OS
) override
;
325 void emitRunCustomAction(raw_ostream
&OS
) override
;
327 void postProcessRule(RuleMatcher
&M
);
329 const CodeGenTarget
&getTarget() const override
{ return Target
; }
330 StringRef
getClassName() const override
{ return ClassName
; }
332 void run(raw_ostream
&OS
);
335 std::string ClassName
;
337 const RecordKeeper
&RK
;
338 const CodeGenDAGPatterns CGP
;
339 const CodeGenTarget
&Target
;
340 CodeGenRegBank
&CGRegs
;
342 ArrayRef
<const Record
*> AllPatFrags
;
344 /// Keep track of the equivalence between SDNodes and Instruction by mapping
345 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
346 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
347 /// This is defined using 'GINodeEquiv' in the target description.
348 DenseMap
<const Record
*, const Record
*> NodeEquivs
;
350 /// Keep track of the equivalence between ComplexPattern's and
351 /// GIComplexOperandMatcher. Map entries are specified by subclassing
352 /// GIComplexPatternEquiv.
353 DenseMap
<const Record
*, const Record
*> ComplexPatternEquivs
;
355 /// Keep track of the equivalence between SDNodeXForm's and
356 /// GICustomOperandRenderer. Map entries are specified by subclassing
357 /// GISDNodeXFormEquiv.
358 DenseMap
<const Record
*, const Record
*> SDNodeXFormEquivs
;
360 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
361 /// This adds compatibility for RuleMatchers to use this for ordering rules.
362 DenseMap
<uint64_t, int> RuleMatcherScores
;
364 // Rule coverage information.
365 std::optional
<CodeGenCoverage
> RuleCoverage
;
367 /// Variables used to help with collecting of named operands for predicates
368 /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
369 /// to the number of named operands that predicate expects. Store locations in
370 /// StoreIdxForName correspond to the order in which operand names appear in
371 /// predicate's argument list.
372 /// When we visit named operand and WaitingForNamedOperands is not zero, add
373 /// matcher that will record operand and decrease counter.
374 unsigned WaitingForNamedOperands
= 0;
375 StringMap
<unsigned> StoreIdxForName
;
377 void gatherOpcodeValues();
378 void gatherTypeIDValues();
379 void gatherNodeEquivs();
381 const Record
*findNodeEquiv(const Record
*N
) const;
382 const CodeGenInstruction
*getEquivNode(const Record
&Equiv
,
383 const TreePatternNode
&N
) const;
385 Error
importRulePredicates(RuleMatcher
&M
,
386 ArrayRef
<const Record
*> Predicates
);
387 Expected
<InstructionMatcher
&>
388 createAndImportSelDAGMatcher(RuleMatcher
&Rule
,
389 InstructionMatcher
&InsnMatcher
,
390 const TreePatternNode
&Src
, unsigned &TempOpIdx
);
391 Error
importComplexPatternOperandMatcher(OperandMatcher
&OM
, const Record
*R
,
392 unsigned &TempOpIdx
) const;
393 Error
importChildMatcher(RuleMatcher
&Rule
, InstructionMatcher
&InsnMatcher
,
394 const TreePatternNode
&SrcChild
,
395 bool OperandIsAPointer
, bool OperandIsImmArg
,
396 unsigned OpIdx
, unsigned &TempOpIdx
);
398 Expected
<BuildMIAction
&> createAndImportInstructionRenderer(
399 RuleMatcher
&M
, InstructionMatcher
&InsnMatcher
,
400 const TreePatternNode
&Src
, const TreePatternNode
&Dst
);
401 Expected
<action_iterator
> createAndImportSubInstructionRenderer(
402 action_iterator InsertPt
, RuleMatcher
&M
, const TreePatternNode
&Dst
,
403 const TreePatternNode
&Src
, unsigned TempReg
);
404 Expected
<action_iterator
>
405 createInstructionRenderer(action_iterator InsertPt
, RuleMatcher
&M
,
406 const TreePatternNode
&Dst
);
408 Expected
<action_iterator
>
409 importExplicitDefRenderers(action_iterator InsertPt
, RuleMatcher
&M
,
410 BuildMIAction
&DstMIBuilder
,
411 const TreePatternNode
&Src
,
412 const TreePatternNode
&Dst
, unsigned Start
= 0);
414 Expected
<action_iterator
> importExplicitUseRenderers(
415 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
416 const llvm::TreePatternNode
&Dst
, const TreePatternNode
&Src
);
417 Expected
<action_iterator
> importExplicitUseRenderer(
418 action_iterator InsertPt
, RuleMatcher
&Rule
, BuildMIAction
&DstMIBuilder
,
419 const TreePatternNode
&DstChild
, const TreePatternNode
&Src
);
420 Error
importDefaultOperandRenderers(action_iterator InsertPt
, RuleMatcher
&M
,
421 BuildMIAction
&DstMIBuilder
,
422 const DAGDefaultOperand
&DefaultOp
) const;
423 Error
importImplicitDefRenderers(BuildMIAction
&DstMIBuilder
,
424 ArrayRef
<const Record
*> ImplicitDefs
) const;
426 /// Analyze pattern \p P, returning a matcher for it if possible.
427 /// Otherwise, return an Error explaining why we don't support it.
428 Expected
<RuleMatcher
> runOnPattern(const PatternToMatch
&P
);
430 void declareSubtargetFeature(const Record
*Predicate
);
432 unsigned declareHwModeCheck(StringRef HwModeFeatures
);
434 MatchTable
buildMatchTable(MutableArrayRef
<RuleMatcher
> Rules
, bool Optimize
,
437 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
438 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
439 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
440 /// If no register class is found, return std::nullopt.
441 std::optional
<const CodeGenRegisterClass
*>
442 inferSuperRegisterClassForNode(const TypeSetByHwMode
&Ty
,
443 const TreePatternNode
&SuperRegNode
,
444 const TreePatternNode
&SubRegIdxNode
);
445 std::optional
<CodeGenSubRegIndex
*>
446 inferSubRegIndexForNode(const TreePatternNode
&SubRegIdxNode
);
448 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
449 /// Return std::nullopt if no such class exists.
450 std::optional
<const CodeGenRegisterClass
*>
451 inferSuperRegisterClass(const TypeSetByHwMode
&Ty
,
452 const TreePatternNode
&SubRegIdxNode
);
454 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
455 std::optional
<const CodeGenRegisterClass
*>
456 getRegClassFromLeaf(const TreePatternNode
&Leaf
);
458 /// Return a CodeGenRegisterClass for \p N if one can be found. Return
459 /// std::nullopt otherwise.
460 std::optional
<const CodeGenRegisterClass
*>
461 inferRegClassFromPattern(const TreePatternNode
&N
);
463 Error
constrainOperands(action_iterator InsertPt
, RuleMatcher
&M
,
464 unsigned InsnID
, const TreePatternNode
&Dst
);
466 /// Return the size of the MemoryVT in this predicate, if possible.
467 std::optional
<unsigned>
468 getMemSizeBitsFromPredicate(const TreePredicateFn
&Predicate
);
470 // Add builtin predicates.
471 Expected
<InstructionMatcher
&>
472 addBuiltinPredicates(const Record
*SrcGIEquivOrNull
,
473 const TreePredicateFn
&Predicate
,
474 InstructionMatcher
&InsnMatcher
, bool &HasAddedMatcher
);
477 StringRef
getPatFragPredicateEnumName(const Record
*R
) { return R
->getName(); }
479 void GlobalISelEmitter::gatherOpcodeValues() {
480 InstructionOpcodeMatcher::initOpcodeValuesMap(Target
);
483 void GlobalISelEmitter::gatherTypeIDValues() {
484 LLTOperandMatcher::initTypeIDValuesMap();
487 void GlobalISelEmitter::gatherNodeEquivs() {
488 assert(NodeEquivs
.empty());
489 for (const Record
*Equiv
: RK
.getAllDerivedDefinitions("GINodeEquiv"))
490 NodeEquivs
[Equiv
->getValueAsDef("Node")] = Equiv
;
492 assert(ComplexPatternEquivs
.empty());
493 for (const Record
*Equiv
:
494 RK
.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
495 const Record
*SelDAGEquiv
= Equiv
->getValueAsDef("SelDAGEquivalent");
498 ComplexPatternEquivs
[SelDAGEquiv
] = Equiv
;
501 assert(SDNodeXFormEquivs
.empty());
502 for (const Record
*Equiv
:
503 RK
.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
504 const Record
*SelDAGEquiv
= Equiv
->getValueAsDef("SelDAGEquivalent");
507 SDNodeXFormEquivs
[SelDAGEquiv
] = Equiv
;
511 const Record
*GlobalISelEmitter::findNodeEquiv(const Record
*N
) const {
512 return NodeEquivs
.lookup(N
);
515 const CodeGenInstruction
*
516 GlobalISelEmitter::getEquivNode(const Record
&Equiv
,
517 const TreePatternNode
&N
) const {
518 if (N
.getNumChildren() >= 1) {
519 // setcc operation maps to two different G_* instructions based on the type.
520 if (!Equiv
.isValueUnset("IfFloatingPoint") &&
521 MVT(N
.getChild(0).getSimpleType(0)).isFloatingPoint())
522 return &Target
.getInstruction(Equiv
.getValueAsDef("IfFloatingPoint"));
525 if (!Equiv
.isValueUnset("IfConvergent") &&
526 N
.getIntrinsicInfo(CGP
)->isConvergent
)
527 return &Target
.getInstruction(Equiv
.getValueAsDef("IfConvergent"));
529 for (const TreePredicateCall
&Call
: N
.getPredicateCalls()) {
530 const TreePredicateFn
&Predicate
= Call
.Fn
;
531 if (!Equiv
.isValueUnset("IfSignExtend") &&
532 (Predicate
.isLoad() || Predicate
.isAtomic()) &&
533 Predicate
.isSignExtLoad())
534 return &Target
.getInstruction(Equiv
.getValueAsDef("IfSignExtend"));
535 if (!Equiv
.isValueUnset("IfZeroExtend") &&
536 (Predicate
.isLoad() || Predicate
.isAtomic()) &&
537 Predicate
.isZeroExtLoad())
538 return &Target
.getInstruction(Equiv
.getValueAsDef("IfZeroExtend"));
541 return &Target
.getInstruction(Equiv
.getValueAsDef("I"));
544 GlobalISelEmitter::GlobalISelEmitter(const RecordKeeper
&RK
)
545 : GlobalISelMatchTableExecutorEmitter(), RK(RK
), CGP(RK
),
546 Target(CGP
.getTargetInfo()), CGRegs(Target
.getRegBank()) {
547 ClassName
= Target
.getName().str() + "InstructionSelector";
550 //===- Emitter ------------------------------------------------------------===//
552 Error
GlobalISelEmitter::importRulePredicates(
553 RuleMatcher
&M
, ArrayRef
<const Record
*> Predicates
) {
554 for (const Record
*Pred
: Predicates
) {
555 if (Pred
->getValueAsString("CondString").empty())
557 declareSubtargetFeature(Pred
);
558 M
.addRequiredFeature(Pred
);
561 return Error::success();
564 std::optional
<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(
565 const TreePredicateFn
&Predicate
) {
566 std::optional
<LLTCodeGen
> MemTyOrNone
=
567 MVTToLLT(getValueType(Predicate
.getMemoryVT()));
572 // Align so unusual types like i1 don't get rounded down.
573 return llvm::alignTo(
574 static_cast<unsigned>(MemTyOrNone
->get().getSizeInBits()), 8);
577 Expected
<InstructionMatcher
&> GlobalISelEmitter::addBuiltinPredicates(
578 const Record
*SrcGIEquivOrNull
, const TreePredicateFn
&Predicate
,
579 InstructionMatcher
&InsnMatcher
, bool &HasAddedMatcher
) {
580 if (Predicate
.isLoad() || Predicate
.isStore() || Predicate
.isAtomic()) {
581 if (const ListInit
*AddrSpaces
= Predicate
.getAddressSpaces()) {
582 SmallVector
<unsigned, 4> ParsedAddrSpaces
;
584 for (const Init
*Val
: AddrSpaces
->getValues()) {
585 const IntInit
*IntVal
= dyn_cast
<IntInit
>(Val
);
587 return failedImport("Address space is not an integer");
588 ParsedAddrSpaces
.push_back(IntVal
->getValue());
591 if (!ParsedAddrSpaces
.empty()) {
592 InsnMatcher
.addPredicate
<MemoryAddressSpacePredicateMatcher
>(
593 0, ParsedAddrSpaces
);
598 int64_t MinAlign
= Predicate
.getMinAlignment();
600 InsnMatcher
.addPredicate
<MemoryAlignmentPredicateMatcher
>(0, MinAlign
);
605 // G_LOAD is used for both non-extending and any-extending loads.
606 if (Predicate
.isLoad() && Predicate
.isNonExtLoad()) {
607 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
608 0, MemoryVsLLTSizePredicateMatcher::EqualTo
, 0);
611 if (Predicate
.isLoad() && Predicate
.isAnyExtLoad()) {
612 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
613 0, MemoryVsLLTSizePredicateMatcher::LessThan
, 0);
617 if (Predicate
.isStore()) {
618 if (Predicate
.isTruncStore()) {
619 if (Predicate
.getMemoryVT() != nullptr) {
620 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
621 auto MemSizeInBits
= getMemSizeBitsFromPredicate(Predicate
);
623 return failedImport("MemVT could not be converted to LLT");
625 InsnMatcher
.addPredicate
<MemorySizePredicateMatcher
>(0, *MemSizeInBits
/
628 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
629 0, MemoryVsLLTSizePredicateMatcher::LessThan
, 0);
633 if (Predicate
.isNonTruncStore()) {
634 // We need to check the sizes match here otherwise we could incorrectly
635 // match truncating stores with non-truncating ones.
636 InsnMatcher
.addPredicate
<MemoryVsLLTSizePredicateMatcher
>(
637 0, MemoryVsLLTSizePredicateMatcher::EqualTo
, 0);
641 assert(SrcGIEquivOrNull
!= nullptr && "Invalid SrcGIEquivOrNull value");
642 // No check required. We already did it by swapping the opcode.
643 if (!SrcGIEquivOrNull
->isValueUnset("IfSignExtend") &&
644 Predicate
.isSignExtLoad())
647 // No check required. We already did it by swapping the opcode.
648 if (!SrcGIEquivOrNull
->isValueUnset("IfZeroExtend") &&
649 Predicate
.isZeroExtLoad())
652 // No check required. G_STORE by itself is a non-extending store.
653 if (Predicate
.isNonTruncStore())
656 if (Predicate
.isLoad() || Predicate
.isStore() || Predicate
.isAtomic()) {
657 if (Predicate
.getMemoryVT() != nullptr) {
658 auto MemSizeInBits
= getMemSizeBitsFromPredicate(Predicate
);
660 return failedImport("MemVT could not be converted to LLT");
662 InsnMatcher
.addPredicate
<MemorySizePredicateMatcher
>(0,
668 if (Predicate
.isLoad() || Predicate
.isStore()) {
669 // No check required. A G_LOAD/G_STORE is an unindexed load.
670 if (Predicate
.isUnindexed())
674 if (Predicate
.isAtomic()) {
675 if (Predicate
.isAtomicOrderingMonotonic()) {
676 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("Monotonic");
679 if (Predicate
.isAtomicOrderingAcquire()) {
680 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("Acquire");
683 if (Predicate
.isAtomicOrderingRelease()) {
684 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("Release");
687 if (Predicate
.isAtomicOrderingAcquireRelease()) {
688 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
692 if (Predicate
.isAtomicOrderingSequentiallyConsistent()) {
693 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
694 "SequentiallyConsistent");
699 if (Predicate
.isAtomicOrderingAcquireOrStronger()) {
700 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
701 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger
);
704 if (Predicate
.isAtomicOrderingWeakerThanAcquire()) {
705 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
706 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan
);
710 if (Predicate
.isAtomicOrderingReleaseOrStronger()) {
711 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
712 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger
);
715 if (Predicate
.isAtomicOrderingWeakerThanRelease()) {
716 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
717 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan
);
720 HasAddedMatcher
= false;
724 Expected
<InstructionMatcher
&> GlobalISelEmitter::createAndImportSelDAGMatcher(
725 RuleMatcher
&Rule
, InstructionMatcher
&InsnMatcher
,
726 const TreePatternNode
&Src
, unsigned &TempOpIdx
) {
727 const auto SavedFlags
= Rule
.setGISelFlags(Src
.getGISelFlagsRecord());
729 const Record
*SrcGIEquivOrNull
= nullptr;
730 const CodeGenInstruction
*SrcGIOrNull
= nullptr;
732 // Start with the defined operands (i.e., the results of the root operator).
734 const Init
*SrcInit
= Src
.getLeafValue();
735 if (isa
<IntInit
>(SrcInit
)) {
736 InsnMatcher
.addPredicate
<InstructionOpcodeMatcher
>(
737 &Target
.getInstruction(RK
.getDef("G_CONSTANT")));
740 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
742 SrcGIEquivOrNull
= findNodeEquiv(Src
.getOperator());
743 if (!SrcGIEquivOrNull
)
744 return failedImport("Pattern operator lacks an equivalent Instruction" +
745 explainOperator(Src
.getOperator()));
746 SrcGIOrNull
= getEquivNode(*SrcGIEquivOrNull
, Src
);
748 // The operators look good: match the opcode
749 InsnMatcher
.addPredicate
<InstructionOpcodeMatcher
>(SrcGIOrNull
);
753 for (const TypeSetByHwMode
&VTy
: Src
.getExtTypes()) {
754 // Results don't have a name unless they are the root node. The caller will
755 // set the name if appropriate.
756 const bool OperandIsAPointer
=
757 SrcGIOrNull
&& SrcGIOrNull
->isOutOperandAPointer(OpIdx
);
758 OperandMatcher
&OM
= InsnMatcher
.addOperand(OpIdx
++, "", TempOpIdx
);
759 if (auto Error
= OM
.addTypeCheckPredicate(VTy
, OperandIsAPointer
))
760 return failedImport(toString(std::move(Error
)) +
761 " for result of Src pattern operator");
764 for (const TreePredicateCall
&Call
: Src
.getPredicateCalls()) {
765 const TreePredicateFn
&Predicate
= Call
.Fn
;
766 bool HasAddedBuiltinMatcher
= true;
767 if (Predicate
.isAlwaysTrue())
770 if (Predicate
.isImmediatePattern()) {
771 InsnMatcher
.addPredicate
<InstructionImmPredicateMatcher
>(Predicate
);
775 auto InsnMatcherOrError
= addBuiltinPredicates(
776 SrcGIEquivOrNull
, Predicate
, InsnMatcher
, HasAddedBuiltinMatcher
);
777 if (auto Error
= InsnMatcherOrError
.takeError())
778 return std::move(Error
);
780 // FIXME: This should be part of addBuiltinPredicates(). If we add this at
781 // the start of addBuiltinPredicates() without returning, then there might
782 // be cases where we hit the last return before which the
783 // HasAddedBuiltinMatcher will be set to false. The predicate could be
784 // missed if we add it in the middle or at the end due to return statements
785 // after the addPredicate<>() calls.
786 if (Predicate
.hasNoUse()) {
787 InsnMatcher
.addPredicate
<NoUsePredicateMatcher
>();
788 HasAddedBuiltinMatcher
= true;
790 if (Predicate
.hasOneUse()) {
791 InsnMatcher
.addPredicate
<OneUsePredicateMatcher
>();
792 HasAddedBuiltinMatcher
= true;
795 if (Predicate
.hasGISelPredicateCode()) {
796 if (Predicate
.usesOperands()) {
797 assert(WaitingForNamedOperands
== 0 &&
798 "previous predicate didn't find all operands or "
799 "nested predicate that uses operands");
800 TreePattern
*TP
= Predicate
.getOrigPatFragRecord();
801 WaitingForNamedOperands
= TP
->getNumArgs();
802 for (unsigned I
= 0; I
< WaitingForNamedOperands
; ++I
)
803 StoreIdxForName
[getScopedName(Call
.Scope
, TP
->getArgName(I
))] = I
;
805 InsnMatcher
.addPredicate
<GenericInstructionPredicateMatcher
>(Predicate
);
808 if (!HasAddedBuiltinMatcher
) {
809 return failedImport("Src pattern child has predicate (" +
810 explainPredicates(Src
) + ")");
814 if (SrcGIEquivOrNull
&&
815 SrcGIEquivOrNull
->getValueAsBit("CheckMMOIsNonAtomic"))
816 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>("NotAtomic");
817 else if (SrcGIEquivOrNull
&&
818 SrcGIEquivOrNull
->getValueAsBit("CheckMMOIsAtomic")) {
819 InsnMatcher
.addPredicate
<AtomicOrderingMMOPredicateMatcher
>(
820 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger
);
824 const Init
*SrcInit
= Src
.getLeafValue();
825 if (const IntInit
*SrcIntInit
= dyn_cast
<IntInit
>(SrcInit
)) {
827 InsnMatcher
.addOperand(OpIdx
++, Src
.getName(), TempOpIdx
);
828 OM
.addPredicate
<LiteralIntOperandMatcher
>(SrcIntInit
->getValue());
831 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
833 assert(SrcGIOrNull
&&
834 "Expected to have already found an equivalent Instruction");
835 if (SrcGIOrNull
->TheDef
->getName() == "G_CONSTANT" ||
836 SrcGIOrNull
->TheDef
->getName() == "G_FCONSTANT") {
837 // imm/fpimm still have operands but we don't need to do anything with it
838 // here since we don't support ImmLeaf predicates yet. However, we still
839 // need to note the hidden operand to get GIM_CheckNumOperands correct.
840 InsnMatcher
.addOperand(OpIdx
++, "", TempOpIdx
);
844 if (SrcGIOrNull
->TheDef
->getName() == "G_FRAME_INDEX") {
845 InsnMatcher
.addOperand(OpIdx
++, Src
.getName(), TempOpIdx
);
849 // Special case because the operand order is changed from setcc. The
850 // predicate operand needs to be swapped from the last operand to the first
853 unsigned NumChildren
= Src
.getNumChildren();
854 bool IsFCmp
= SrcGIOrNull
->TheDef
->getName() == "G_FCMP";
856 if (IsFCmp
|| SrcGIOrNull
->TheDef
->getName() == "G_ICMP") {
857 const TreePatternNode
&SrcChild
= Src
.getChild(NumChildren
- 1);
858 if (SrcChild
.isLeaf()) {
859 const DefInit
*DI
= dyn_cast
<DefInit
>(SrcChild
.getLeafValue());
860 const Record
*CCDef
= DI
? DI
->getDef() : nullptr;
861 if (!CCDef
|| !CCDef
->isSubClassOf("CondCode"))
862 return failedImport("Unable to handle CondCode");
865 InsnMatcher
.addOperand(OpIdx
++, SrcChild
.getName(), TempOpIdx
);
866 StringRef PredType
= IsFCmp
? CCDef
->getValueAsString("FCmpPredicate")
867 : CCDef
->getValueAsString("ICmpPredicate");
869 if (!PredType
.empty()) {
870 OM
.addPredicate
<CmpPredicateOperandMatcher
>(std::string(PredType
));
871 // Process the other 2 operands normally.
877 // Match the used operands (i.e. the children of the operator).
879 SrcGIOrNull
->TheDef
->getName() == "G_INTRINSIC" ||
880 SrcGIOrNull
->TheDef
->getName() == "G_INTRINSIC_W_SIDE_EFFECTS" ||
881 SrcGIOrNull
->TheDef
->getName() == "G_INTRINSIC_CONVERGENT" ||
882 SrcGIOrNull
->TheDef
->getName() ==
883 "G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS";
884 const CodeGenIntrinsic
*II
= Src
.getIntrinsicInfo(CGP
);
885 if (IsIntrinsic
&& !II
)
886 return failedImport("Expected IntInit containing intrinsic ID)");
888 for (unsigned I
= 0; I
!= NumChildren
; ++I
) {
889 const TreePatternNode
&SrcChild
= Src
.getChild(I
);
891 // We need to determine the meaning of a literal integer based on the
892 // context. If this is a field required to be an immediate (such as an
893 // immarg intrinsic argument), the required predicates are different than
894 // a constant which may be materialized in a register. If we have an
895 // argument that is required to be an immediate, we should not emit an LLT
896 // type check, and should not be looking for a G_CONSTANT defined
898 bool OperandIsImmArg
= SrcGIOrNull
->isInOperandImmArg(I
);
900 // SelectionDAG allows pointers to be represented with iN since it doesn't
901 // distinguish between pointers and integers but they are different types
902 // in GlobalISel. Coerce integers to pointers to address space 0 if the
903 // context indicates a pointer.
905 bool OperandIsAPointer
= SrcGIOrNull
->isInOperandAPointer(I
);
908 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
909 // following the defs is an intrinsic ID.
912 InsnMatcher
.addOperand(OpIdx
++, SrcChild
.getName(), TempOpIdx
);
913 OM
.addPredicate
<IntrinsicIDOperandMatcher
>(II
);
917 // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
919 // Note that we have to look at the i-1th parameter, because we don't
920 // have the intrinsic ID in the intrinsic's parameter list.
921 OperandIsAPointer
|= II
->isParamAPointer(I
- 1);
922 OperandIsImmArg
|= II
->isParamImmArg(I
- 1);
926 importChildMatcher(Rule
, InsnMatcher
, SrcChild
, OperandIsAPointer
,
927 OperandIsImmArg
, OpIdx
++, TempOpIdx
))
928 return std::move(Error
);
935 Error
GlobalISelEmitter::importComplexPatternOperandMatcher(
936 OperandMatcher
&OM
, const Record
*R
, unsigned &TempOpIdx
) const {
937 const auto &ComplexPattern
= ComplexPatternEquivs
.find(R
);
938 if (ComplexPattern
== ComplexPatternEquivs
.end())
939 return failedImport("SelectionDAG ComplexPattern (" + R
->getName() +
940 ") not mapped to GlobalISel");
942 OM
.addPredicate
<ComplexPatternOperandMatcher
>(OM
, *ComplexPattern
->second
);
944 return Error::success();
947 // Get the name to use for a pattern operand. For an anonymous physical register
948 // input, this should use the register name.
949 static StringRef
getSrcChildName(const TreePatternNode
&SrcChild
,
950 const Record
*&PhysReg
) {
951 StringRef SrcChildName
= SrcChild
.getName();
952 if (SrcChildName
.empty() && SrcChild
.isLeaf()) {
953 if (auto *ChildDefInit
= dyn_cast
<DefInit
>(SrcChild
.getLeafValue())) {
954 auto *ChildRec
= ChildDefInit
->getDef();
955 if (ChildRec
->isSubClassOf("Register")) {
956 SrcChildName
= ChildRec
->getName();
965 Error
GlobalISelEmitter::importChildMatcher(
966 RuleMatcher
&Rule
, InstructionMatcher
&InsnMatcher
,
967 const TreePatternNode
&SrcChild
, bool OperandIsAPointer
,
968 bool OperandIsImmArg
, unsigned OpIdx
, unsigned &TempOpIdx
) {
970 const Record
*PhysReg
= nullptr;
971 std::string SrcChildName
= std::string(getSrcChildName(SrcChild
, PhysReg
));
972 if (!SrcChild
.isLeaf() &&
973 SrcChild
.getOperator()->isSubClassOf("ComplexPattern")) {
974 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
975 // "MY_PAT:op1:op2" and the ones with same "name" represent same operand.
976 std::string PatternName
= std::string(SrcChild
.getOperator()->getName());
977 for (unsigned I
= 0; I
< SrcChild
.getNumChildren(); ++I
) {
979 PatternName
+= SrcChild
.getChild(I
).getName();
981 SrcChildName
= PatternName
;
985 PhysReg
? InsnMatcher
.addPhysRegInput(PhysReg
, OpIdx
, TempOpIdx
)
986 : InsnMatcher
.addOperand(OpIdx
, SrcChildName
, TempOpIdx
);
987 if (OM
.isSameAsAnotherOperand())
988 return Error::success();
990 ArrayRef
<TypeSetByHwMode
> ChildTypes
= SrcChild
.getExtTypes();
991 if (ChildTypes
.size() != 1)
992 return failedImport("Src pattern child has multiple results");
994 // Check MBB's before the type check since they are not a known type.
995 if (!SrcChild
.isLeaf()) {
996 if (SrcChild
.getOperator()->isSubClassOf("SDNode")) {
997 auto &ChildSDNI
= CGP
.getSDNodeInfo(SrcChild
.getOperator());
998 if (ChildSDNI
.getSDClassName() == "BasicBlockSDNode") {
999 OM
.addPredicate
<MBBOperandMatcher
>();
1000 return Error::success();
1002 if (SrcChild
.getOperator()->getName() == "timm") {
1003 OM
.addPredicate
<ImmOperandMatcher
>();
1005 // Add predicates, if any
1006 for (const TreePredicateCall
&Call
: SrcChild
.getPredicateCalls()) {
1007 const TreePredicateFn
&Predicate
= Call
.Fn
;
1009 // Only handle immediate patterns for now
1010 if (Predicate
.isImmediatePattern()) {
1011 OM
.addPredicate
<OperandImmPredicateMatcher
>(Predicate
);
1015 return Error::success();
1018 } else if (auto *ChildDefInit
= dyn_cast
<DefInit
>(SrcChild
.getLeafValue())) {
1019 auto *ChildRec
= ChildDefInit
->getDef();
1020 if (ChildRec
->isSubClassOf("ValueType") && !SrcChild
.hasName()) {
1021 // An unnamed ValueType as in (sext_inreg GPR:$foo, i8). GISel represents
1022 // this as a literal constant with the scalar size.
1023 MVT::SimpleValueType VT
= llvm::getValueType(ChildRec
);
1024 OM
.addPredicate
<LiteralIntOperandMatcher
>(MVT(VT
).getScalarSizeInBits());
1025 return Error::success();
1029 // Immediate arguments have no meaningful type to check as they don't have
1031 if (!OperandIsImmArg
) {
1033 OM
.addTypeCheckPredicate(ChildTypes
.front(), OperandIsAPointer
))
1034 return failedImport(toString(std::move(Error
)) + " for Src operand (" +
1035 to_string(SrcChild
) + ")");
1038 // Try look up SrcChild for a (named) predicate operand if there is any.
1039 if (WaitingForNamedOperands
) {
1040 auto &ScopedNames
= SrcChild
.getNamesAsPredicateArg();
1041 if (!ScopedNames
.empty()) {
1042 auto PA
= ScopedNames
.begin();
1043 std::string Name
= getScopedName(PA
->getScope(), PA
->getIdentifier());
1044 OM
.addPredicate
<RecordNamedOperandMatcher
>(StoreIdxForName
[Name
], Name
);
1045 --WaitingForNamedOperands
;
1049 // Check for nested instructions.
1050 if (!SrcChild
.isLeaf()) {
1051 if (SrcChild
.getOperator()->isSubClassOf("ComplexPattern")) {
1052 // When a ComplexPattern is used as an operator, it should do the same
1053 // thing as when used as a leaf. However, the children of the operator
1054 // name the sub-operands that make up the complex operand and we must
1055 // prepare to reference them in the renderer too.
1056 unsigned RendererID
= TempOpIdx
;
1057 if (auto Error
= importComplexPatternOperandMatcher(
1058 OM
, SrcChild
.getOperator(), TempOpIdx
))
1061 for (unsigned I
= 0, E
= SrcChild
.getNumChildren(); I
!= E
; ++I
) {
1062 auto &SubOperand
= SrcChild
.getChild(I
);
1063 if (!SubOperand
.getName().empty()) {
1064 if (auto Error
= Rule
.defineComplexSubOperand(
1065 SubOperand
.getName(), SrcChild
.getOperator(), RendererID
, I
,
1071 return Error::success();
1074 auto MaybeInsnOperand
= OM
.addPredicate
<InstructionOperandMatcher
>(
1075 InsnMatcher
.getRuleMatcher(), SrcChild
.getName());
1076 if (!MaybeInsnOperand
) {
1077 // This isn't strictly true. If the user were to provide exactly the same
1078 // matchers as the original operand then we could allow it. However, it's
1079 // simpler to not permit the redundant specification.
1080 return failedImport(
1081 "Nested instruction cannot be the same as another operand");
1084 // Map the node to a gMIR instruction.
1085 InstructionOperandMatcher
&InsnOperand
= **MaybeInsnOperand
;
1086 auto InsnMatcherOrError
= createAndImportSelDAGMatcher(
1087 Rule
, InsnOperand
.getInsnMatcher(), SrcChild
, TempOpIdx
);
1088 if (auto Error
= InsnMatcherOrError
.takeError())
1091 return Error::success();
1094 if (SrcChild
.hasAnyPredicate())
1095 return failedImport("Src pattern child has unsupported predicate");
1097 // Check for constant immediates.
1098 if (auto *ChildInt
= dyn_cast
<IntInit
>(SrcChild
.getLeafValue())) {
1099 if (OperandIsImmArg
) {
1100 // Checks for argument directly in operand list
1101 OM
.addPredicate
<LiteralIntOperandMatcher
>(ChildInt
->getValue());
1103 // Checks for materialized constant
1104 OM
.addPredicate
<ConstantIntOperandMatcher
>(ChildInt
->getValue());
1106 return Error::success();
1109 // Check for def's like register classes or ComplexPattern's.
1110 if (auto *ChildDefInit
= dyn_cast
<DefInit
>(SrcChild
.getLeafValue())) {
1111 auto *ChildRec
= ChildDefInit
->getDef();
1113 // Check for register classes.
1114 if (ChildRec
->isSubClassOf("RegisterClass") ||
1115 ChildRec
->isSubClassOf("RegisterOperand")) {
1116 OM
.addPredicate
<RegisterBankOperandMatcher
>(
1117 Target
.getRegisterClass(getInitValueAsRegClass(ChildDefInit
)));
1118 return Error::success();
1121 if (ChildRec
->isSubClassOf("Register")) {
1122 // This just be emitted as a copy to the specific register.
1123 ValueTypeByHwMode VT
= ChildTypes
.front().getValueTypeByHwMode();
1124 const CodeGenRegisterClass
*RC
=
1125 CGRegs
.getMinimalPhysRegClass(ChildRec
, &VT
);
1127 return failedImport(
1128 "Could not determine physical register class of pattern source");
1131 OM
.addPredicate
<RegisterBankOperandMatcher
>(*RC
);
1132 return Error::success();
1135 // Check for ValueType.
1136 if (ChildRec
->isSubClassOf("ValueType")) {
1137 // We already added a type check as standard practice so this doesn't need
1139 return Error::success();
1142 // Check for ComplexPattern's.
1143 if (ChildRec
->isSubClassOf("ComplexPattern"))
1144 return importComplexPatternOperandMatcher(OM
, ChildRec
, TempOpIdx
);
1146 if (ChildRec
->isSubClassOf("ImmLeaf")) {
1147 return failedImport(
1148 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1151 // Place holder for SRCVALUE nodes. Nothing to do here.
1152 if (ChildRec
->getName() == "srcvalue")
1153 return Error::success();
1155 const bool ImmAllOnesV
= ChildRec
->getName() == "immAllOnesV";
1156 if (ImmAllOnesV
|| ChildRec
->getName() == "immAllZerosV") {
1157 auto MaybeInsnOperand
= OM
.addPredicate
<InstructionOperandMatcher
>(
1158 InsnMatcher
.getRuleMatcher(), SrcChild
.getName(), false);
1159 InstructionOperandMatcher
&InsnOperand
= **MaybeInsnOperand
;
1161 ValueTypeByHwMode VTy
= ChildTypes
.front().getValueTypeByHwMode();
1163 const CodeGenInstruction
&BuildVector
=
1164 Target
.getInstruction(RK
.getDef("G_BUILD_VECTOR"));
1165 const CodeGenInstruction
&BuildVectorTrunc
=
1166 Target
.getInstruction(RK
.getDef("G_BUILD_VECTOR_TRUNC"));
1168 // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
1169 // as an alternative.
1170 InsnOperand
.getInsnMatcher().addPredicate
<InstructionOpcodeMatcher
>(
1171 ArrayRef({&BuildVector
, &BuildVectorTrunc
}));
1173 // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
1174 // theoretically not emit any opcode check, but getOpcodeMatcher currently
1176 OperandMatcher
&OM
=
1177 InsnOperand
.getInsnMatcher().addOperand(0, "", TempOpIdx
);
1179 OM
.addTypeCheckPredicate(TypeSetByHwMode(VTy
), false /* OperandIsAPointer */))
1180 return failedImport(toString(std::move(Error
)) +
1181 " for result of Src pattern operator");
1183 InsnOperand
.getInsnMatcher().addPredicate
<VectorSplatImmPredicateMatcher
>(
1184 ImmAllOnesV
? VectorSplatImmPredicateMatcher::AllOnes
1185 : VectorSplatImmPredicateMatcher::AllZeros
);
1186 return Error::success();
1189 return failedImport(
1190 "Src pattern child def is an unsupported tablegen class");
1193 return failedImport("Src pattern child is an unsupported kind");
1196 Expected
<action_iterator
> GlobalISelEmitter::importExplicitUseRenderer(
1197 action_iterator InsertPt
, RuleMatcher
&Rule
, BuildMIAction
&DstMIBuilder
,
1198 const TreePatternNode
&DstChild
, const TreePatternNode
&Src
) {
1200 const auto &SubOperand
= Rule
.getComplexSubOperand(DstChild
.getName());
1202 DstMIBuilder
.addRenderer
<RenderComplexPatternOperand
>(
1203 *std::get
<0>(*SubOperand
), DstChild
.getName(), std::get
<1>(*SubOperand
),
1204 std::get
<2>(*SubOperand
));
1208 if (!DstChild
.isLeaf()) {
1209 if (DstChild
.getOperator()->isSubClassOf("SDNodeXForm")) {
1210 auto &Child
= DstChild
.getChild(0);
1211 auto I
= SDNodeXFormEquivs
.find(DstChild
.getOperator());
1212 if (I
!= SDNodeXFormEquivs
.end()) {
1213 const Record
*XFormOpc
=
1214 DstChild
.getOperator()->getValueAsDef("Opcode");
1215 if (XFormOpc
->getName() == "timm") {
1216 // If this is a TargetConstant, there won't be a corresponding
1217 // instruction to transform. Instead, this will refer directly to an
1218 // operand in an instruction's operand list.
1219 DstMIBuilder
.addRenderer
<CustomOperandRenderer
>(*I
->second
,
1222 DstMIBuilder
.addRenderer
<CustomRenderer
>(*I
->second
, Child
.getName());
1227 return failedImport("SDNodeXForm " + Child
.getName() +
1228 " has no custom renderer");
1231 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
1232 // inline, but in MI it's just another operand.
1233 if (DstChild
.getOperator()->isSubClassOf("SDNode")) {
1234 auto &ChildSDNI
= CGP
.getSDNodeInfo(DstChild
.getOperator());
1235 if (ChildSDNI
.getSDClassName() == "BasicBlockSDNode") {
1236 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstChild
.getName());
1241 // Similarly, imm is an operator in TreePatternNode's view but must be
1242 // rendered as operands.
1243 // FIXME: The target should be able to choose sign-extended when appropriate
1245 if (DstChild
.getOperator()->getName() == "timm") {
1246 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstChild
.getName());
1249 if (DstChild
.getOperator()->getName() == "tframeindex") {
1250 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstChild
.getName());
1253 if (DstChild
.getOperator()->getName() == "imm") {
1254 DstMIBuilder
.addRenderer
<CopyConstantAsImmRenderer
>(DstChild
.getName());
1257 if (DstChild
.getOperator()->getName() == "fpimm") {
1258 DstMIBuilder
.addRenderer
<CopyFConstantAsFPImmRenderer
>(
1259 DstChild
.getName());
1263 if (DstChild
.getOperator()->isSubClassOf("Instruction")) {
1264 auto OpTy
= getInstResultType(DstChild
, Target
);
1266 return OpTy
.takeError();
1268 unsigned TempRegID
= Rule
.allocateTempRegID();
1270 Rule
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *OpTy
, TempRegID
);
1271 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
);
1273 auto InsertPtOrError
= createAndImportSubInstructionRenderer(
1274 ++InsertPt
, Rule
, DstChild
, Src
, TempRegID
);
1275 if (auto Error
= InsertPtOrError
.takeError())
1276 return std::move(Error
);
1277 return InsertPtOrError
.get();
1280 return failedImport("Dst pattern child isn't a leaf node or an MBB" +
1281 llvm::to_string(DstChild
));
1284 // It could be a specific immediate in which case we should just check for
1286 if (const IntInit
*ChildIntInit
=
1287 dyn_cast
<IntInit
>(DstChild
.getLeafValue())) {
1288 DstMIBuilder
.addRenderer
<ImmRenderer
>(ChildIntInit
->getValue());
1292 // Otherwise, we're looking for a bog-standard RegisterClass operand.
1293 if (auto *ChildDefInit
= dyn_cast
<DefInit
>(DstChild
.getLeafValue())) {
1294 auto *ChildRec
= ChildDefInit
->getDef();
1296 ArrayRef
<TypeSetByHwMode
> ChildTypes
= DstChild
.getExtTypes();
1297 if (ChildTypes
.size() != 1)
1298 return failedImport("Dst pattern child has multiple results");
1300 std::optional
<LLTCodeGen
> OpTyOrNone
;
1301 if (ChildTypes
.front().isMachineValueType())
1302 OpTyOrNone
= MVTToLLT(ChildTypes
.front().getMachineValueType().SimpleTy
);
1304 return failedImport("Dst operand has an unsupported type");
1306 if (ChildRec
->isSubClassOf("Register")) {
1307 DstMIBuilder
.addRenderer
<AddRegisterRenderer
>(Target
, ChildRec
);
1311 if (ChildRec
->isSubClassOf("RegisterClass") ||
1312 ChildRec
->isSubClassOf("RegisterOperand") ||
1313 ChildRec
->isSubClassOf("ValueType")) {
1314 if (ChildRec
->isSubClassOf("RegisterOperand") &&
1315 !ChildRec
->isValueUnset("GIZeroRegister")) {
1316 DstMIBuilder
.addRenderer
<CopyOrAddZeroRegRenderer
>(
1317 DstChild
.getName(), ChildRec
->getValueAsDef("GIZeroRegister"));
1321 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstChild
.getName());
1325 if (ChildRec
->isSubClassOf("SubRegIndex")) {
1326 CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(ChildRec
);
1327 DstMIBuilder
.addRenderer
<ImmRenderer
>(SubIdx
->EnumValue
);
1331 if (ChildRec
->isSubClassOf("ComplexPattern")) {
1332 const auto &ComplexPattern
= ComplexPatternEquivs
.find(ChildRec
);
1333 if (ComplexPattern
== ComplexPatternEquivs
.end())
1334 return failedImport(
1335 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1337 const OperandMatcher
&OM
= Rule
.getOperandMatcher(DstChild
.getName());
1338 DstMIBuilder
.addRenderer
<RenderComplexPatternOperand
>(
1339 *ComplexPattern
->second
, DstChild
.getName(),
1340 OM
.getAllocatedTemporariesBaseID());
1344 return failedImport(
1345 "Dst pattern child def is an unsupported tablegen class");
1348 // Handle the case where the MVT/register class is omitted in the dest pattern
1349 // but MVT exists in the source pattern.
1350 if (isa
<UnsetInit
>(DstChild
.getLeafValue())) {
1351 for (unsigned NumOp
= 0; NumOp
< Src
.getNumChildren(); NumOp
++)
1352 if (Src
.getChild(NumOp
).getName() == DstChild
.getName()) {
1353 DstMIBuilder
.addRenderer
<CopyRenderer
>(Src
.getChild(NumOp
).getName());
1357 return failedImport("Dst pattern child is an unsupported kind");
1360 Expected
<BuildMIAction
&> GlobalISelEmitter::createAndImportInstructionRenderer(
1361 RuleMatcher
&M
, InstructionMatcher
&InsnMatcher
, const TreePatternNode
&Src
,
1362 const TreePatternNode
&Dst
) {
1363 auto InsertPtOrError
= createInstructionRenderer(M
.actions_end(), M
, Dst
);
1364 if (auto Error
= InsertPtOrError
.takeError())
1365 return std::move(Error
);
1367 action_iterator InsertPt
= InsertPtOrError
.get();
1368 BuildMIAction
&DstMIBuilder
= *static_cast<BuildMIAction
*>(InsertPt
->get());
1370 for (auto PhysInput
: InsnMatcher
.getPhysRegInputs()) {
1371 InsertPt
= M
.insertAction
<BuildMIAction
>(
1372 InsertPt
, M
.allocateOutputInsnID(),
1373 &Target
.getInstruction(RK
.getDef("COPY")));
1374 BuildMIAction
&CopyToPhysRegMIBuilder
=
1375 *static_cast<BuildMIAction
*>(InsertPt
->get());
1376 CopyToPhysRegMIBuilder
.addRenderer
<AddRegisterRenderer
>(
1377 Target
, PhysInput
.first
, true);
1378 CopyToPhysRegMIBuilder
.addRenderer
<CopyPhysRegRenderer
>(PhysInput
.first
);
1382 importExplicitDefRenderers(InsertPt
, M
, DstMIBuilder
, Src
, Dst
)
1384 return std::move(Error
);
1387 importExplicitUseRenderers(InsertPt
, M
, DstMIBuilder
, Dst
, Src
)
1389 return std::move(Error
);
1391 return DstMIBuilder
;
1394 Expected
<action_iterator
>
1395 GlobalISelEmitter::createAndImportSubInstructionRenderer(
1396 const action_iterator InsertPt
, RuleMatcher
&M
, const TreePatternNode
&Dst
,
1397 const TreePatternNode
&Src
, unsigned TempRegID
) {
1398 auto InsertPtOrError
= createInstructionRenderer(InsertPt
, M
, Dst
);
1400 // TODO: Assert there's exactly one result.
1402 if (auto Error
= InsertPtOrError
.takeError())
1403 return std::move(Error
);
1405 BuildMIAction
&DstMIBuilder
=
1406 *static_cast<BuildMIAction
*>(InsertPtOrError
.get()->get());
1408 // Assign the result to TempReg.
1409 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
, true);
1411 // Handle additional (ignored) results.
1412 if (DstMIBuilder
.getCGI()->Operands
.NumDefs
> 1) {
1413 InsertPtOrError
= importExplicitDefRenderers(
1414 std::prev(*InsertPtOrError
), M
, DstMIBuilder
, Src
, Dst
, /*Start=*/1);
1415 if (auto Error
= InsertPtOrError
.takeError())
1416 return std::move(Error
);
1419 InsertPtOrError
= importExplicitUseRenderers(InsertPtOrError
.get(), M
,
1420 DstMIBuilder
, Dst
, Src
);
1421 if (auto Error
= InsertPtOrError
.takeError())
1422 return std::move(Error
);
1425 constrainOperands(InsertPt
, M
, DstMIBuilder
.getInsnID(), Dst
))
1426 return std::move(Error
);
1428 return InsertPtOrError
.get();
1431 Expected
<action_iterator
> GlobalISelEmitter::createInstructionRenderer(
1432 action_iterator InsertPt
, RuleMatcher
&M
, const TreePatternNode
&Dst
) {
1433 const Record
*DstOp
= Dst
.getOperator();
1434 if (!DstOp
->isSubClassOf("Instruction")) {
1435 if (DstOp
->isSubClassOf("ValueType"))
1436 return failedImport(
1437 "Pattern operator isn't an instruction (it's a ValueType)");
1438 return failedImport("Pattern operator isn't an instruction");
1440 CodeGenInstruction
*DstI
= &Target
.getInstruction(DstOp
);
1442 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
1443 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
1444 StringRef Name
= DstI
->TheDef
->getName();
1445 if (Name
== "COPY_TO_REGCLASS" || Name
== "EXTRACT_SUBREG")
1446 DstI
= &Target
.getInstruction(RK
.getDef("COPY"));
1448 return M
.insertAction
<BuildMIAction
>(InsertPt
, M
.allocateOutputInsnID(),
1452 Expected
<action_iterator
> GlobalISelEmitter::importExplicitDefRenderers(
1453 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
1454 const TreePatternNode
&Src
, const TreePatternNode
&Dst
, unsigned Start
) {
1455 const CodeGenInstruction
*DstI
= DstMIBuilder
.getCGI();
1456 const unsigned SrcNumDefs
= Src
.getExtTypes().size();
1457 const unsigned DstNumDefs
= DstI
->Operands
.NumDefs
;
1458 if (DstNumDefs
== 0)
1461 for (unsigned I
= Start
; I
< SrcNumDefs
; ++I
) {
1462 std::string OpName
= getMangledRootDefName(DstI
->Operands
[I
].Name
);
1463 // CopyRenderer saves a StringRef, so cannot pass OpName itself -
1464 // let's use a string with an appropriate lifetime.
1465 StringRef PermanentRef
= M
.getOperandMatcher(OpName
).getSymbolicName();
1466 DstMIBuilder
.addRenderer
<CopyRenderer
>(PermanentRef
);
1469 // Some instructions have multiple defs, but are missing a type entry
1470 // (e.g. s_cc_out operands).
1471 if (Dst
.getExtTypes().size() < DstNumDefs
)
1472 return failedImport("unhandled discarded def");
1474 for (unsigned I
= SrcNumDefs
; I
< DstNumDefs
; ++I
) {
1475 const TypeSetByHwMode
&ExtTy
= Dst
.getExtType(I
);
1476 if (!ExtTy
.isMachineValueType())
1477 return failedImport("unsupported typeset");
1479 auto OpTy
= MVTToLLT(ExtTy
.getMachineValueType().SimpleTy
);
1481 return failedImport("unsupported type");
1483 unsigned TempRegID
= M
.allocateTempRegID();
1485 M
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *OpTy
, TempRegID
);
1486 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
, true, nullptr, true);
1492 Expected
<action_iterator
> GlobalISelEmitter::importExplicitUseRenderers(
1493 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
1494 const llvm::TreePatternNode
&Dst
, const llvm::TreePatternNode
&Src
) {
1495 const CodeGenInstruction
*DstI
= DstMIBuilder
.getCGI();
1496 CodeGenInstruction
*OrigDstI
= &Target
.getInstruction(Dst
.getOperator());
1498 StringRef Name
= OrigDstI
->TheDef
->getName();
1499 unsigned ExpectedDstINumUses
= Dst
.getNumChildren();
1501 // EXTRACT_SUBREG needs to use a subregister COPY.
1502 if (Name
== "EXTRACT_SUBREG") {
1503 if (!Dst
.getChild(1).isLeaf())
1504 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
1505 const DefInit
*SubRegInit
=
1506 dyn_cast
<DefInit
>(Dst
.getChild(1).getLeafValue());
1508 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1510 CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1511 const TreePatternNode
&ValChild
= Dst
.getChild(0);
1512 if (!ValChild
.isLeaf()) {
1513 // We really have to handle the source instruction, and then insert a
1514 // copy from the subregister.
1515 auto ExtractSrcTy
= getInstResultType(ValChild
, Target
);
1517 return ExtractSrcTy
.takeError();
1519 unsigned TempRegID
= M
.allocateTempRegID();
1520 InsertPt
= M
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *ExtractSrcTy
,
1523 auto InsertPtOrError
= createAndImportSubInstructionRenderer(
1524 ++InsertPt
, M
, ValChild
, Src
, TempRegID
);
1525 if (auto Error
= InsertPtOrError
.takeError())
1526 return std::move(Error
);
1528 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
, false, SubIdx
);
1532 // If this is a source operand, this is just a subregister copy.
1533 const Record
*RCDef
= getInitValueAsRegClass(ValChild
.getLeafValue());
1535 return failedImport("EXTRACT_SUBREG child #0 could not "
1536 "be coerced to a register class");
1538 CodeGenRegisterClass
*RC
= CGRegs
.getRegClass(RCDef
);
1540 const auto SrcRCDstRCPair
=
1541 RC
->getMatchingSubClassWithSubRegs(CGRegs
, SubIdx
);
1542 if (SrcRCDstRCPair
) {
1543 assert(SrcRCDstRCPair
->second
&& "Couldn't find a matching subclass");
1544 if (SrcRCDstRCPair
->first
!= RC
)
1545 return failedImport("EXTRACT_SUBREG requires an additional COPY");
1548 StringRef RegOperandName
= Dst
.getChild(0).getName();
1549 if (const auto &SubOperand
= M
.getComplexSubOperand(RegOperandName
)) {
1550 DstMIBuilder
.addRenderer
<RenderComplexPatternOperand
>(
1551 *std::get
<0>(*SubOperand
), RegOperandName
, std::get
<1>(*SubOperand
),
1552 std::get
<2>(*SubOperand
), SubIdx
);
1556 DstMIBuilder
.addRenderer
<CopySubRegRenderer
>(RegOperandName
, SubIdx
);
1560 if (Name
== "REG_SEQUENCE") {
1561 if (!Dst
.getChild(0).isLeaf())
1562 return failedImport("REG_SEQUENCE child #0 is not a leaf");
1564 const Record
*RCDef
=
1565 getInitValueAsRegClass(Dst
.getChild(0).getLeafValue());
1567 return failedImport("REG_SEQUENCE child #0 could not "
1568 "be coerced to a register class");
1570 if ((ExpectedDstINumUses
- 1) % 2 != 0)
1571 return failedImport("Malformed REG_SEQUENCE");
1573 for (unsigned I
= 1; I
!= ExpectedDstINumUses
; I
+= 2) {
1574 const TreePatternNode
&ValChild
= Dst
.getChild(I
);
1575 const TreePatternNode
&SubRegChild
= Dst
.getChild(I
+ 1);
1577 if (const DefInit
*SubRegInit
=
1578 dyn_cast
<DefInit
>(SubRegChild
.getLeafValue())) {
1579 CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1581 auto InsertPtOrError
=
1582 importExplicitUseRenderer(InsertPt
, M
, DstMIBuilder
, ValChild
, Src
);
1583 if (auto Error
= InsertPtOrError
.takeError())
1584 return std::move(Error
);
1585 InsertPt
= InsertPtOrError
.get();
1586 DstMIBuilder
.addRenderer
<SubRegIndexRenderer
>(SubIdx
);
1593 // Render the explicit uses.
1594 unsigned DstINumUses
= OrigDstI
->Operands
.size() - OrigDstI
->Operands
.NumDefs
;
1595 if (Name
== "COPY_TO_REGCLASS") {
1596 DstINumUses
--; // Ignore the class constraint.
1597 ExpectedDstINumUses
--;
1600 // NumResults - This is the number of results produced by the instruction in
1602 unsigned NumResults
= OrigDstI
->Operands
.NumDefs
;
1604 // Number of operands we know the output instruction must have. If it is
1605 // variadic, we could have more operands.
1606 unsigned NumFixedOperands
= DstI
->Operands
.size();
1608 // Loop over all of the fixed operands of the instruction pattern, emitting
1609 // code to fill them all in. The node 'N' usually has number children equal to
1610 // the number of input operands of the instruction. However, in cases where
1611 // there are predicate operands for an instruction, we need to fill in the
1612 // 'execute always' values. Match up the node operands to the instruction
1613 // operands to do this.
1616 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
1617 // number of operands at the end of the list which have default values.
1618 // Those can come from the pattern if it provides enough arguments, or be
1619 // filled in with the default if the pattern hasn't provided them. But any
1620 // operand with a default value _before_ the last mandatory one will be
1621 // filled in with their defaults unconditionally.
1622 unsigned NonOverridableOperands
= NumFixedOperands
;
1623 while (NonOverridableOperands
> NumResults
&&
1624 CGP
.operandHasDefault(DstI
->Operands
[NonOverridableOperands
- 1].Rec
))
1625 --NonOverridableOperands
;
1627 unsigned NumDefaultOps
= 0;
1628 for (unsigned I
= 0; I
!= DstINumUses
; ++I
) {
1629 unsigned InstOpNo
= DstI
->Operands
.NumDefs
+ I
;
1631 // Determine what to emit for this operand.
1632 const Record
*OperandNode
= DstI
->Operands
[InstOpNo
].Rec
;
1634 // If the operand has default values, introduce them now.
1635 if (CGP
.operandHasDefault(OperandNode
) &&
1636 (InstOpNo
< NonOverridableOperands
|| Child
>= Dst
.getNumChildren())) {
1637 // This is a predicate or optional def operand which the pattern has not
1638 // overridden, or which we aren't letting it override; emit the 'default
1641 const Record
*OperandNode
= DstI
->Operands
[InstOpNo
].Rec
;
1642 if (auto Error
= importDefaultOperandRenderers(
1643 InsertPt
, M
, DstMIBuilder
, CGP
.getDefaultOperand(OperandNode
)))
1644 return std::move(Error
);
1650 auto InsertPtOrError
= importExplicitUseRenderer(InsertPt
, M
, DstMIBuilder
,
1651 Dst
.getChild(Child
), Src
);
1652 if (auto Error
= InsertPtOrError
.takeError())
1653 return std::move(Error
);
1654 InsertPt
= InsertPtOrError
.get();
1658 if (NumDefaultOps
+ ExpectedDstINumUses
!= DstINumUses
)
1659 return failedImport("Expected " + llvm::to_string(DstINumUses
) +
1660 " used operands but found " +
1661 llvm::to_string(ExpectedDstINumUses
) +
1662 " explicit ones and " + llvm::to_string(NumDefaultOps
) +
1668 Error
GlobalISelEmitter::importDefaultOperandRenderers(
1669 action_iterator InsertPt
, RuleMatcher
&M
, BuildMIAction
&DstMIBuilder
,
1670 const DAGDefaultOperand
&DefaultOp
) const {
1671 for (const auto &Op
: DefaultOp
.DefaultOps
) {
1672 const auto &N
= *Op
;
1674 return failedImport("Could not add default op");
1676 const auto *DefaultOp
= N
.getLeafValue();
1678 if (const DefInit
*DefaultDefOp
= dyn_cast
<DefInit
>(DefaultOp
)) {
1679 std::optional
<LLTCodeGen
> OpTyOrNone
= MVTToLLT(N
.getSimpleType(0));
1680 auto *Def
= DefaultDefOp
->getDef();
1681 if (Def
->getName() == "undef_tied_input") {
1682 unsigned TempRegID
= M
.allocateTempRegID();
1683 M
.insertAction
<MakeTempRegisterAction
>(InsertPt
, *OpTyOrNone
,
1685 InsertPt
= M
.insertAction
<BuildMIAction
>(
1686 InsertPt
, M
.allocateOutputInsnID(),
1687 &Target
.getInstruction(RK
.getDef("IMPLICIT_DEF")));
1688 BuildMIAction
&IDMIBuilder
=
1689 *static_cast<BuildMIAction
*>(InsertPt
->get());
1690 IDMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
);
1691 DstMIBuilder
.addRenderer
<TempRegRenderer
>(TempRegID
);
1693 DstMIBuilder
.addRenderer
<AddRegisterRenderer
>(Target
, Def
);
1698 if (const IntInit
*DefaultIntOp
= dyn_cast
<IntInit
>(DefaultOp
)) {
1699 DstMIBuilder
.addRenderer
<ImmRenderer
>(DefaultIntOp
->getValue());
1703 return failedImport("Could not add default op");
1706 return Error::success();
1709 Error
GlobalISelEmitter::importImplicitDefRenderers(
1710 BuildMIAction
&DstMIBuilder
, ArrayRef
<const Record
*> ImplicitDefs
) const {
1711 if (!ImplicitDefs
.empty())
1712 return failedImport("Pattern defines a physical register");
1713 return Error::success();
1716 Error
GlobalISelEmitter::constrainOperands(action_iterator InsertPt
,
1717 RuleMatcher
&M
, unsigned InsnID
,
1718 const TreePatternNode
&Dst
) {
1719 const Record
*DstOp
= Dst
.getOperator();
1720 const CodeGenInstruction
&DstI
= Target
.getInstruction(DstOp
);
1721 StringRef DstIName
= DstI
.TheDef
->getName();
1723 if (DstIName
== "COPY_TO_REGCLASS") {
1724 // COPY_TO_REGCLASS does not provide operand constraints itself but the
1725 // result is constrained to the class given by the second child.
1726 const Record
*DstIOpRec
=
1727 getInitValueAsRegClass(Dst
.getChild(1).getLeafValue());
1729 if (DstIOpRec
== nullptr)
1730 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
1732 M
.insertAction
<ConstrainOperandToRegClassAction
>(
1733 InsertPt
, InsnID
, 0, Target
.getRegisterClass(DstIOpRec
));
1734 } else if (DstIName
== "EXTRACT_SUBREG") {
1735 auto SuperClass
= inferRegClassFromPattern(Dst
.getChild(0));
1737 return failedImport(
1738 "Cannot infer register class from EXTRACT_SUBREG operand #0");
1740 auto SubIdx
= inferSubRegIndexForNode(Dst
.getChild(1));
1742 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1744 // It would be nice to leave this constraint implicit but we're required
1745 // to pick a register class so constrain the result to a register class
1746 // that can hold the correct MVT.
1748 // FIXME: This may introduce an extra copy if the chosen class doesn't
1749 // actually contain the subregisters.
1750 const auto SrcRCDstRCPair
=
1751 (*SuperClass
)->getMatchingSubClassWithSubRegs(CGRegs
, *SubIdx
);
1752 if (!SrcRCDstRCPair
) {
1753 return failedImport("subreg index is incompatible "
1754 "with inferred reg class");
1757 assert(SrcRCDstRCPair
->second
&& "Couldn't find a matching subclass");
1758 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 0,
1759 *SrcRCDstRCPair
->second
);
1760 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 1,
1761 *SrcRCDstRCPair
->first
);
1762 } else if (DstIName
== "INSERT_SUBREG") {
1763 // We need to constrain the destination, a super regsister source, and a
1764 // subregister source.
1765 auto SubClass
= inferRegClassFromPattern(Dst
.getChild(1));
1767 return failedImport(
1768 "Cannot infer register class from INSERT_SUBREG operand #1");
1769 auto SuperClass
= inferSuperRegisterClassForNode(
1770 Dst
.getExtType(0), Dst
.getChild(0), Dst
.getChild(2));
1772 return failedImport(
1773 "Cannot infer register class for INSERT_SUBREG operand #0");
1774 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 0,
1776 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 1,
1778 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 2,
1780 } else if (DstIName
== "SUBREG_TO_REG") {
1781 // We need to constrain the destination and subregister source.
1782 // Attempt to infer the subregister source from the first child. If it has
1783 // an explicitly given register class, we'll use that. Otherwise, we will
1785 auto SubClass
= inferRegClassFromPattern(Dst
.getChild(1));
1787 return failedImport(
1788 "Cannot infer register class from SUBREG_TO_REG child #1");
1789 // We don't have a child to look at that might have a super register node.
1791 inferSuperRegisterClass(Dst
.getExtType(0), Dst
.getChild(2));
1793 return failedImport(
1794 "Cannot infer register class for SUBREG_TO_REG operand #0");
1795 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 0,
1797 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 2,
1799 } else if (DstIName
== "REG_SEQUENCE") {
1800 auto SuperClass
= inferRegClassFromPattern(Dst
.getChild(0));
1802 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, 0,
1805 unsigned Num
= Dst
.getNumChildren();
1806 for (unsigned I
= 1; I
!= Num
; I
+= 2) {
1807 const TreePatternNode
&SubRegChild
= Dst
.getChild(I
+ 1);
1809 auto SubIdx
= inferSubRegIndexForNode(SubRegChild
);
1811 return failedImport("REG_SEQUENCE child is not a subreg index");
1813 const auto SrcRCDstRCPair
=
1814 (*SuperClass
)->getMatchingSubClassWithSubRegs(CGRegs
, *SubIdx
);
1816 M
.insertAction
<ConstrainOperandToRegClassAction
>(InsertPt
, InsnID
, I
,
1817 *SrcRCDstRCPair
->second
);
1820 M
.insertAction
<ConstrainOperandsToDefinitionAction
>(InsertPt
, InsnID
);
1823 return Error::success();
1826 std::optional
<const CodeGenRegisterClass
*>
1827 GlobalISelEmitter::getRegClassFromLeaf(const TreePatternNode
&Leaf
) {
1828 assert(Leaf
.isLeaf() && "Expected leaf?");
1829 const Record
*RCRec
= getInitValueAsRegClass(Leaf
.getLeafValue());
1831 return std::nullopt
;
1832 const CodeGenRegisterClass
*RC
= CGRegs
.getRegClass(RCRec
);
1834 return std::nullopt
;
1838 std::optional
<const CodeGenRegisterClass
*>
1839 GlobalISelEmitter::inferRegClassFromPattern(const TreePatternNode
&N
) {
1841 return getRegClassFromLeaf(N
);
1843 // We don't have a leaf node, so we have to try and infer something. Check
1844 // that we have an instruction that we can infer something from.
1846 // Only handle things that produce at least one value (if multiple values,
1847 // just take the first one).
1848 if (N
.getNumTypes() < 1)
1849 return std::nullopt
;
1850 const Record
*OpRec
= N
.getOperator();
1852 // We only want instructions.
1853 if (!OpRec
->isSubClassOf("Instruction"))
1854 return std::nullopt
;
1856 // Don't want to try and infer things when there could potentially be more
1857 // than one candidate register class.
1858 auto &Inst
= Target
.getInstruction(OpRec
);
1860 // Handle any special-case instructions which we can safely infer register
1862 StringRef InstName
= Inst
.TheDef
->getName();
1863 bool IsRegSequence
= InstName
== "REG_SEQUENCE";
1864 if (IsRegSequence
|| InstName
== "COPY_TO_REGCLASS") {
1865 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
1866 // has the desired register class as the first child.
1867 const TreePatternNode
&RCChild
= N
.getChild(IsRegSequence
? 0 : 1);
1868 if (!RCChild
.isLeaf())
1869 return std::nullopt
;
1870 return getRegClassFromLeaf(RCChild
);
1872 if (InstName
== "INSERT_SUBREG") {
1873 const TreePatternNode
&Child0
= N
.getChild(0);
1874 assert(Child0
.getNumTypes() == 1 && "Unexpected number of types!");
1875 const TypeSetByHwMode
&VTy
= Child0
.getExtType(0);
1876 return inferSuperRegisterClassForNode(VTy
, Child0
, N
.getChild(2));
1878 if (InstName
== "EXTRACT_SUBREG") {
1879 assert(N
.getNumTypes() == 1 && "Unexpected number of types!");
1880 const TypeSetByHwMode
&VTy
= N
.getExtType(0);
1881 return inferSuperRegisterClass(VTy
, N
.getChild(1));
1884 // Handle destination record types that we can safely infer a register class
1886 const auto &DstIOperand
= Inst
.Operands
[0];
1887 const Record
*DstIOpRec
= DstIOperand
.Rec
;
1888 if (DstIOpRec
->isSubClassOf("RegisterOperand")) {
1889 DstIOpRec
= DstIOpRec
->getValueAsDef("RegClass");
1890 const CodeGenRegisterClass
&RC
= Target
.getRegisterClass(DstIOpRec
);
1894 if (DstIOpRec
->isSubClassOf("RegisterClass")) {
1895 const CodeGenRegisterClass
&RC
= Target
.getRegisterClass(DstIOpRec
);
1899 return std::nullopt
;
1902 std::optional
<const CodeGenRegisterClass
*>
1903 GlobalISelEmitter::inferSuperRegisterClass(
1904 const TypeSetByHwMode
&Ty
, const TreePatternNode
&SubRegIdxNode
) {
1905 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
1906 if (!Ty
.isValueTypeByHwMode(false))
1907 return std::nullopt
;
1908 if (!SubRegIdxNode
.isLeaf())
1909 return std::nullopt
;
1910 const DefInit
*SubRegInit
= dyn_cast
<DefInit
>(SubRegIdxNode
.getLeafValue());
1912 return std::nullopt
;
1913 const CodeGenSubRegIndex
*SubIdx
= CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1915 // Use the information we found above to find a minimal register class which
1916 // supports the subregister and type we want.
1918 Target
.getSuperRegForSubReg(Ty
.getValueTypeByHwMode(), CGRegs
, SubIdx
,
1919 /* MustBeAllocatable */ true);
1921 return std::nullopt
;
1925 std::optional
<const CodeGenRegisterClass
*>
1926 GlobalISelEmitter::inferSuperRegisterClassForNode(
1927 const TypeSetByHwMode
&Ty
, const TreePatternNode
&SuperRegNode
,
1928 const TreePatternNode
&SubRegIdxNode
) {
1929 // Check if we already have a defined register class for the super register
1930 // node. If we do, then we should preserve that rather than inferring anything
1931 // from the subregister index node. We can assume that whoever wrote the
1932 // pattern in the first place made sure that the super register and
1933 // subregister are compatible.
1934 if (std::optional
<const CodeGenRegisterClass
*> SuperRegisterClass
=
1935 inferRegClassFromPattern(SuperRegNode
))
1936 return *SuperRegisterClass
;
1937 return inferSuperRegisterClass(Ty
, SubRegIdxNode
);
1940 std::optional
<CodeGenSubRegIndex
*> GlobalISelEmitter::inferSubRegIndexForNode(
1941 const TreePatternNode
&SubRegIdxNode
) {
1942 if (!SubRegIdxNode
.isLeaf())
1943 return std::nullopt
;
1945 const DefInit
*SubRegInit
= dyn_cast
<DefInit
>(SubRegIdxNode
.getLeafValue());
1947 return std::nullopt
;
1948 return CGRegs
.getSubRegIdx(SubRegInit
->getDef());
1951 Expected
<RuleMatcher
> GlobalISelEmitter::runOnPattern(const PatternToMatch
&P
) {
1952 // Keep track of the matchers and actions to emit.
1953 int Score
= P
.getPatternComplexity(CGP
);
1954 RuleMatcher
M(P
.getSrcRecord()->getLoc());
1955 RuleMatcherScores
[M
.getRuleID()] = Score
;
1956 M
.addAction
<DebugCommentAction
>(llvm::to_string(P
.getSrcPattern()) +
1958 llvm::to_string(P
.getDstPattern()));
1960 SmallVector
<const Record
*, 4> Predicates
;
1961 P
.getPredicateRecords(Predicates
);
1962 if (auto Error
= importRulePredicates(M
, Predicates
))
1963 return std::move(Error
);
1965 if (!P
.getHwModeFeatures().empty())
1966 M
.addHwModeIdx(declareHwModeCheck(P
.getHwModeFeatures()));
1968 // Next, analyze the pattern operators.
1969 TreePatternNode
&Src
= P
.getSrcPattern();
1970 TreePatternNode
&Dst
= P
.getDstPattern();
1972 // If the root of either pattern isn't a simple operator, ignore it.
1973 if (auto Err
= isTrivialOperatorNode(Dst
))
1974 return failedImport("Dst pattern root isn't a trivial operator (" +
1975 toString(std::move(Err
)) + ")");
1976 if (auto Err
= isTrivialOperatorNode(Src
))
1977 return failedImport("Src pattern root isn't a trivial operator (" +
1978 toString(std::move(Err
)) + ")");
1980 // The different predicates and matchers created during
1981 // addInstructionMatcher use the RuleMatcher M to set up their
1982 // instruction ID (InsnVarID) that are going to be used when
1983 // M is going to be emitted.
1984 // However, the code doing the emission still relies on the IDs
1985 // returned during that process by the RuleMatcher when issuing
1986 // the recordInsn opcodes.
1988 // 1. The order in which we created the predicates
1989 // and such must be the same as the order in which we emit them,
1991 // 2. We need to reset the generation of the IDs in M somewhere between
1992 // addInstructionMatcher and emit
1994 // FIXME: Long term, we don't want to have to rely on this implicit
1995 // naming being the same. One possible solution would be to have
1996 // explicit operator for operation capture and reference those.
1997 // The plus side is that it would expose opportunities to share
1998 // the capture accross rules. The downside is that it would
1999 // introduce a dependency between predicates (captures must happen
2000 // before their first use.)
2001 InstructionMatcher
&InsnMatcherTemp
= M
.addInstructionMatcher(Src
.getName());
2002 unsigned TempOpIdx
= 0;
2004 const auto SavedFlags
= M
.setGISelFlags(P
.getSrcRecord());
2006 auto InsnMatcherOrError
=
2007 createAndImportSelDAGMatcher(M
, InsnMatcherTemp
, Src
, TempOpIdx
);
2008 if (auto Error
= InsnMatcherOrError
.takeError())
2009 return std::move(Error
);
2010 InstructionMatcher
&InsnMatcher
= InsnMatcherOrError
.get();
2013 if (const Record
*RCDef
= getInitValueAsRegClass(Dst
.getLeafValue())) {
2014 const CodeGenRegisterClass
&RC
= Target
.getRegisterClass(RCDef
);
2016 // We need to replace the def and all its uses with the specified
2017 // operand. However, we must also insert COPY's wherever needed.
2018 // For now, emit a copy and let the register allocator clean up.
2019 auto &DstI
= Target
.getInstruction(RK
.getDef("COPY"));
2020 const auto &DstIOperand
= DstI
.Operands
[0];
2022 OperandMatcher
&OM0
= InsnMatcher
.getOperand(0);
2023 OM0
.setSymbolicName(DstIOperand
.Name
);
2024 M
.defineOperand(OM0
.getSymbolicName(), OM0
);
2025 OM0
.addPredicate
<RegisterBankOperandMatcher
>(RC
);
2027 auto &DstMIBuilder
=
2028 M
.addAction
<BuildMIAction
>(M
.allocateOutputInsnID(), &DstI
);
2029 DstMIBuilder
.addRenderer
<CopyRenderer
>(DstIOperand
.Name
);
2030 DstMIBuilder
.addRenderer
<CopyRenderer
>(Dst
.getName());
2031 M
.addAction
<ConstrainOperandToRegClassAction
>(0, 0, RC
);
2034 unsigned RootInsnID
= M
.getInsnVarID(InsnMatcher
);
2035 M
.addAction
<EraseInstAction
>(RootInsnID
);
2037 // We're done with this pattern! It's eligible for GISel emission; return
2039 ++NumPatternImported
;
2040 return std::move(M
);
2043 return failedImport("Dst pattern root isn't a known leaf");
2046 // Start with the defined operands (i.e., the results of the root operator).
2047 const Record
*DstOp
= Dst
.getOperator();
2048 if (!DstOp
->isSubClassOf("Instruction"))
2049 return failedImport("Pattern operator isn't an instruction");
2051 auto &DstI
= Target
.getInstruction(DstOp
);
2052 StringRef DstIName
= DstI
.TheDef
->getName();
2054 // Count both implicit and explicit defs in the dst instruction.
2055 // This avoids errors importing patterns that have inherent implicit defs.
2056 unsigned DstExpDefs
= DstI
.Operands
.NumDefs
,
2057 DstNumDefs
= DstI
.ImplicitDefs
.size() + DstExpDefs
,
2058 SrcNumDefs
= Src
.getExtTypes().size();
2059 if (DstNumDefs
< SrcNumDefs
) {
2060 if (DstNumDefs
!= 0)
2061 return failedImport("Src pattern result has more defs than dst MI (" +
2062 to_string(SrcNumDefs
) + " def(s) vs " +
2063 to_string(DstNumDefs
) + " def(s))");
2065 bool FoundNoUsePred
= false;
2066 for (const auto &Pred
: InsnMatcher
.predicates()) {
2067 if ((FoundNoUsePred
= isa
<NoUsePredicateMatcher
>(Pred
.get())))
2070 if (!FoundNoUsePred
)
2071 return failedImport("Src pattern result has " + to_string(SrcNumDefs
) +
2072 " def(s) without the HasNoUse predicate set to true "
2073 "but Dst MI has no def");
2076 // The root of the match also has constraints on the register bank so that it
2077 // matches the result instruction.
2079 unsigned N
= std::min(DstExpDefs
, SrcNumDefs
);
2080 for (unsigned I
= 0; I
< N
; ++I
) {
2081 const TypeSetByHwMode
&VTy
= Src
.getExtType(I
);
2083 const auto &DstIOperand
= DstI
.Operands
[OpIdx
];
2084 PointerUnion
<const Record
*, const CodeGenRegisterClass
*> MatchedRC
=
2086 if (DstIName
== "COPY_TO_REGCLASS") {
2087 MatchedRC
= getInitValueAsRegClass(Dst
.getChild(1).getLeafValue());
2089 if (MatchedRC
.isNull())
2090 return failedImport(
2091 "COPY_TO_REGCLASS operand #1 isn't a register class");
2092 } else if (DstIName
== "REG_SEQUENCE") {
2093 MatchedRC
= getInitValueAsRegClass(Dst
.getChild(0).getLeafValue());
2094 if (MatchedRC
.isNull())
2095 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
2096 } else if (DstIName
== "EXTRACT_SUBREG") {
2097 auto InferredClass
= inferRegClassFromPattern(Dst
.getChild(0));
2099 return failedImport(
2100 "Could not infer class for EXTRACT_SUBREG operand #0");
2102 // We can assume that a subregister is in the same bank as it's super
2104 MatchedRC
= (*InferredClass
)->getDef();
2105 } else if (DstIName
== "INSERT_SUBREG") {
2106 auto MaybeSuperClass
=
2107 inferSuperRegisterClassForNode(VTy
, Dst
.getChild(0), Dst
.getChild(2));
2108 if (!MaybeSuperClass
)
2109 return failedImport(
2110 "Cannot infer register class for INSERT_SUBREG operand #0");
2111 // Move to the next pattern here, because the register class we found
2112 // doesn't necessarily have a record associated with it. So, we can't
2113 // set DstIOpRec using this.
2114 MatchedRC
= *MaybeSuperClass
;
2115 } else if (DstIName
== "SUBREG_TO_REG") {
2116 auto MaybeRegClass
= inferSuperRegisterClass(VTy
, Dst
.getChild(2));
2118 return failedImport(
2119 "Cannot infer register class for SUBREG_TO_REG operand #0");
2120 MatchedRC
= *MaybeRegClass
;
2121 } else if (cast
<const Record
*>(MatchedRC
)->isSubClassOf("RegisterOperand"))
2122 MatchedRC
= cast
<const Record
*>(MatchedRC
)->getValueAsDef("RegClass");
2123 else if (!cast
<const Record
*>(MatchedRC
)->isSubClassOf("RegisterClass"))
2124 return failedImport("Dst MI def isn't a register class" + to_string(Dst
));
2126 OperandMatcher
&OM
= InsnMatcher
.getOperand(OpIdx
);
2127 // The operand names declared in the DstI instruction are unrelated to
2128 // those used in pattern's source and destination DAGs, so mangle the
2129 // former to prevent implicitly adding unexpected
2130 // GIM_CheckIsSameOperand predicates by the defineOperand method.
2131 OM
.setSymbolicName(getMangledRootDefName(DstIOperand
.Name
));
2132 M
.defineOperand(OM
.getSymbolicName(), OM
);
2133 if (auto *R
= dyn_cast
<const Record
*>(MatchedRC
))
2134 MatchedRC
= &Target
.getRegisterClass(R
);
2135 OM
.addPredicate
<RegisterBankOperandMatcher
>(
2136 *cast
<const CodeGenRegisterClass
*>(MatchedRC
));
2140 auto DstMIBuilderOrError
=
2141 createAndImportInstructionRenderer(M
, InsnMatcher
, Src
, Dst
);
2142 if (auto Error
= DstMIBuilderOrError
.takeError())
2143 return std::move(Error
);
2144 BuildMIAction
&DstMIBuilder
= DstMIBuilderOrError
.get();
2146 // Render the implicit defs.
2147 // These are only added to the root of the result.
2148 if (auto Error
= importImplicitDefRenderers(DstMIBuilder
, P
.getDstRegs()))
2149 return std::move(Error
);
2151 DstMIBuilder
.chooseInsnToMutate(M
);
2153 // Constrain the registers to classes. This is normally derived from the
2154 // emitted instruction but a few instructions require special handling.
2156 constrainOperands(M
.actions_end(), M
, DstMIBuilder
.getInsnID(), Dst
))
2157 return std::move(Error
);
2160 unsigned RootInsnID
= M
.getInsnVarID(InsnMatcher
);
2161 M
.addAction
<EraseInstAction
>(RootInsnID
);
2163 // We're done with this pattern! It's eligible for GISel emission; return it.
2164 ++NumPatternImported
;
2165 return std::move(M
);
2169 GlobalISelEmitter::buildMatchTable(MutableArrayRef
<RuleMatcher
> Rules
,
2170 bool Optimize
, bool WithCoverage
) {
2171 std::vector
<Matcher
*> InputRules
;
2172 for (Matcher
&Rule
: Rules
)
2173 InputRules
.push_back(&Rule
);
2176 return MatchTable::buildTable(InputRules
, WithCoverage
);
2178 unsigned CurrentOrdering
= 0;
2179 StringMap
<unsigned> OpcodeOrder
;
2180 for (RuleMatcher
&Rule
: Rules
) {
2181 const StringRef Opcode
= Rule
.getOpcode();
2182 assert(!Opcode
.empty() && "Didn't expect an undefined opcode");
2183 if (OpcodeOrder
.count(Opcode
) == 0)
2184 OpcodeOrder
[Opcode
] = CurrentOrdering
++;
2187 llvm::stable_sort(InputRules
, [&OpcodeOrder
](const Matcher
*A
,
2189 auto *L
= static_cast<const RuleMatcher
*>(A
);
2190 auto *R
= static_cast<const RuleMatcher
*>(B
);
2191 return std::tuple(OpcodeOrder
[L
->getOpcode()],
2192 L
->insnmatchers_front().getNumOperandMatchers()) <
2193 std::tuple(OpcodeOrder
[R
->getOpcode()],
2194 R
->insnmatchers_front().getNumOperandMatchers());
2197 for (Matcher
*Rule
: InputRules
)
2200 std::vector
<std::unique_ptr
<Matcher
>> MatcherStorage
;
2201 std::vector
<Matcher
*> OptRules
=
2202 optimizeRules
<GroupMatcher
>(InputRules
, MatcherStorage
);
2204 for (Matcher
*Rule
: OptRules
)
2207 OptRules
= optimizeRules
<SwitchMatcher
>(OptRules
, MatcherStorage
);
2209 return MatchTable::buildTable(OptRules
, WithCoverage
);
2212 void GlobalISelEmitter::emitAdditionalImpl(raw_ostream
&OS
) {
2213 OS
<< "bool " << getClassName()
2214 << "::selectImpl(MachineInstr &I, CodeGenCoverage "
2215 "&CoverageInfo) const {\n"
2216 << " const PredicateBitset AvailableFeatures = "
2217 "getAvailableFeatures();\n"
2218 << " MachineIRBuilder B(I);\n"
2219 << " State.MIs.clear();\n"
2220 << " State.MIs.push_back(&I);\n\n"
2221 << " if (executeMatchTable(*this, State, ExecInfo, B"
2222 << ", getMatchTable(), TII, MF->getRegInfo(), TRI, RBI, AvailableFeatures"
2223 << ", &CoverageInfo)) {\n"
2224 << " return true;\n"
2226 << " return false;\n"
2230 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream
&OS
) {
2231 std::vector
<const Record
*> MatchedRecords
;
2232 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2233 std::back_inserter(MatchedRecords
), [](const Record
*R
) {
2234 return !R
->getValueAsString("GISelPredicateCode").empty();
2236 emitMIPredicateFnsImpl
<const Record
*>(
2238 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
2239 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
2240 " const auto &Operands = State.RecordedOperands;\n"
2241 " (void)Operands;\n"
2243 ArrayRef
<const Record
*>(MatchedRecords
), &getPatFragPredicateEnumName
,
2244 [](const Record
*R
) { return R
->getValueAsString("GISelPredicateCode"); },
2245 "PatFrag predicates.");
2248 void GlobalISelEmitter::emitI64ImmPredicateFns(raw_ostream
&OS
) {
2249 std::vector
<const Record
*> MatchedRecords
;
2250 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2251 std::back_inserter(MatchedRecords
), [](const Record
*R
) {
2253 return !R
->getValueAsString("ImmediateCode").empty() &&
2254 !R
->getValueAsBitOrUnset("IsAPFloat", Unset
) &&
2255 !R
->getValueAsBit("IsAPInt");
2257 emitImmPredicateFnsImpl
<const Record
*>(
2258 OS
, "I64", "int64_t", ArrayRef
<const Record
*>(MatchedRecords
),
2259 &getPatFragPredicateEnumName
,
2260 [](const Record
*R
) { return R
->getValueAsString("ImmediateCode"); },
2261 "PatFrag predicates.");
2264 void GlobalISelEmitter::emitAPFloatImmPredicateFns(raw_ostream
&OS
) {
2265 std::vector
<const Record
*> MatchedRecords
;
2266 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2267 std::back_inserter(MatchedRecords
), [](const Record
*R
) {
2269 return !R
->getValueAsString("ImmediateCode").empty() &&
2270 R
->getValueAsBitOrUnset("IsAPFloat", Unset
);
2272 emitImmPredicateFnsImpl
<const Record
*>(
2273 OS
, "APFloat", "const APFloat &",
2274 ArrayRef
<const Record
*>(MatchedRecords
), &getPatFragPredicateEnumName
,
2275 [](const Record
*R
) { return R
->getValueAsString("ImmediateCode"); },
2276 "PatFrag predicates.");
2279 void GlobalISelEmitter::emitAPIntImmPredicateFns(raw_ostream
&OS
) {
2280 std::vector
<const Record
*> MatchedRecords
;
2281 std::copy_if(AllPatFrags
.begin(), AllPatFrags
.end(),
2282 std::back_inserter(MatchedRecords
), [](const Record
*R
) {
2283 return !R
->getValueAsString("ImmediateCode").empty() &&
2284 R
->getValueAsBit("IsAPInt");
2286 emitImmPredicateFnsImpl
<const Record
*>(
2287 OS
, "APInt", "const APInt &", ArrayRef
<const Record
*>(MatchedRecords
),
2288 &getPatFragPredicateEnumName
,
2289 [](const Record
*R
) { return R
->getValueAsString("ImmediateCode"); },
2290 "PatFrag predicates.");
2293 void GlobalISelEmitter::emitTestSimplePredicate(raw_ostream
&OS
) {
2294 OS
<< "bool " << getClassName() << "::testSimplePredicate(unsigned) const {\n"
2295 << " llvm_unreachable(\"" + getClassName() +
2296 " does not support simple predicates!\");\n"
2297 << " return false;\n"
2301 void GlobalISelEmitter::emitRunCustomAction(raw_ostream
&OS
) {
2302 OS
<< "bool " << getClassName()
2303 << "::runCustomAction(unsigned, const MatcherState&, NewMIVector &) const "
2305 << " llvm_unreachable(\"" + getClassName() +
2306 " does not support custom C++ actions!\");\n"
2310 void GlobalISelEmitter::postProcessRule(RuleMatcher
&M
) {
2311 SmallPtrSet
<const Record
*, 16> UsedRegs
;
2313 // TODO: deal with subregs?
2314 for (auto &A
: M
.actions()) {
2315 auto *MI
= dyn_cast
<BuildMIAction
>(A
.get());
2319 for (auto *Use
: MI
->getCGI()->ImplicitUses
)
2320 UsedRegs
.insert(Use
);
2323 for (auto &A
: M
.actions()) {
2324 auto *MI
= dyn_cast
<BuildMIAction
>(A
.get());
2328 for (auto *Def
: MI
->getCGI()->ImplicitDefs
) {
2329 if (!UsedRegs
.contains(Def
))
2330 MI
->setDeadImplicitDef(Def
);
2335 void GlobalISelEmitter::run(raw_ostream
&OS
) {
2336 if (!UseCoverageFile
.empty()) {
2337 RuleCoverage
= CodeGenCoverage();
2338 auto RuleCoverageBufOrErr
= MemoryBuffer::getFile(UseCoverageFile
);
2339 if (!RuleCoverageBufOrErr
) {
2340 PrintWarning(SMLoc(), "Missing rule coverage data");
2341 RuleCoverage
= std::nullopt
;
2343 if (!RuleCoverage
->parse(*RuleCoverageBufOrErr
.get(), Target
.getName())) {
2344 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
2345 RuleCoverage
= std::nullopt
;
2350 // Track the run-time opcode values
2351 gatherOpcodeValues();
2352 // Track the run-time LLT ID values
2353 gatherTypeIDValues();
2355 // Track the GINodeEquiv definitions.
2358 AllPatFrags
= RK
.getAllDerivedDefinitions("PatFrags");
2360 emitSourceFileHeader(
2361 ("Global Instruction Selector for the " + Target
.getName() + " target")
2364 std::vector
<RuleMatcher
> Rules
;
2365 // Look through the SelectionDAG patterns we found, possibly emitting some.
2366 for (const PatternToMatch
&Pat
: CGP
.ptms()) {
2369 if (Pat
.getGISelShouldIgnore())
2370 continue; // skip without warning
2371 auto MatcherOrErr
= runOnPattern(Pat
);
2373 // The pattern analysis can fail, indicating an unsupported pattern.
2374 // Report that if we've been asked to do so.
2375 if (auto Err
= MatcherOrErr
.takeError()) {
2376 if (WarnOnSkippedPatterns
) {
2377 PrintWarning(Pat
.getSrcRecord()->getLoc(),
2378 "Skipped pattern: " + toString(std::move(Err
)));
2380 consumeError(std::move(Err
));
2382 ++NumPatternImportsSkipped
;
2387 if (RuleCoverage
->isCovered(MatcherOrErr
->getRuleID()))
2388 ++NumPatternsTested
;
2390 PrintWarning(Pat
.getSrcRecord()->getLoc(),
2391 "Pattern is not covered by a test");
2393 Rules
.push_back(std::move(MatcherOrErr
.get()));
2394 postProcessRule(Rules
.back());
2397 // Comparison function to order records by name.
2398 auto OrderByName
= [](const Record
*A
, const Record
*B
) {
2399 return A
->getName() < B
->getName();
2402 std::vector
<const Record
*> ComplexPredicates
=
2403 RK
.getAllDerivedDefinitions("GIComplexOperandMatcher");
2404 llvm::sort(ComplexPredicates
, OrderByName
);
2406 std::vector
<StringRef
> CustomRendererFns
;
2407 transform(RK
.getAllDerivedDefinitions("GICustomOperandRenderer"),
2408 std::back_inserter(CustomRendererFns
), [](const auto &Record
) {
2409 return Record
->getValueAsString("RendererFn");
2411 // Sort and remove duplicates to get a list of unique renderer functions, in
2412 // case some were mentioned more than once.
2413 llvm::sort(CustomRendererFns
);
2414 CustomRendererFns
.erase(llvm::unique(CustomRendererFns
),
2415 CustomRendererFns
.end());
2417 // Create a table containing the LLT objects needed by the matcher and an enum
2418 // for the matcher to reference them with.
2419 std::vector
<LLTCodeGen
> TypeObjects
;
2420 append_range(TypeObjects
, KnownTypes
);
2421 llvm::sort(TypeObjects
);
2424 llvm::stable_sort(Rules
, [&](const RuleMatcher
&A
, const RuleMatcher
&B
) {
2425 int ScoreA
= RuleMatcherScores
[A
.getRuleID()];
2426 int ScoreB
= RuleMatcherScores
[B
.getRuleID()];
2427 if (ScoreA
> ScoreB
)
2429 if (ScoreB
> ScoreA
)
2431 if (A
.isHigherPriorityThan(B
)) {
2432 assert(!B
.isHigherPriorityThan(A
) && "Cannot be more important "
2433 "and less important at "
2440 unsigned MaxTemporaries
= 0;
2441 for (const auto &Rule
: Rules
)
2442 MaxTemporaries
= std::max(MaxTemporaries
, Rule
.countRendererFns());
2444 // Build match table
2445 const MatchTable Table
=
2446 buildMatchTable(Rules
, OptimizeMatchTable
, GenerateCoverage
);
2448 emitPredicateBitset(OS
, "GET_GLOBALISEL_PREDICATE_BITSET");
2449 emitTemporariesDecl(OS
, "GET_GLOBALISEL_TEMPORARIES_DECL");
2450 emitTemporariesInit(OS
, MaxTemporaries
, "GET_GLOBALISEL_TEMPORARIES_INIT");
2451 emitExecutorImpl(OS
, Table
, TypeObjects
, Rules
, ComplexPredicates
,
2452 CustomRendererFns
, "GET_GLOBALISEL_IMPL");
2453 emitPredicatesDecl(OS
, "GET_GLOBALISEL_PREDICATES_DECL");
2454 emitPredicatesInit(OS
, "GET_GLOBALISEL_PREDICATES_INIT");
2457 void GlobalISelEmitter::declareSubtargetFeature(const Record
*Predicate
) {
2458 SubtargetFeatures
.try_emplace(Predicate
, Predicate
, SubtargetFeatures
.size());
2461 unsigned GlobalISelEmitter::declareHwModeCheck(StringRef HwModeFeatures
) {
2462 return HwModes
.emplace(HwModeFeatures
.str(), HwModes
.size()).first
->second
;
2465 } // end anonymous namespace
2467 //===----------------------------------------------------------------------===//
2469 static TableGen::Emitter::OptClass
<GlobalISelEmitter
>
2470 X("gen-global-isel", "Generate GlobalISel selector");