LLVM 23.0.0git
LegalizerInfo.cpp
Go to the documentation of this file.
1//===- lib/CodeGen/GlobalISel/LegalizerInfo.cpp - Legalizer ---------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// Implement an interface to specify and query how an illegal operation on a
10// given type should be expanded.
11//
12//===----------------------------------------------------------------------===//
13
21#include "llvm/MC/MCInstrDesc.h"
22#include "llvm/MC/MCInstrInfo.h"
23#include "llvm/Support/Debug.h"
25#include <algorithm>
26
27using namespace llvm;
28using namespace LegalizeActions;
29
30#define DEBUG_TYPE "legalizer-info"
31
33 "disable-gisel-legality-check",
34 cl::desc("Don't verify that MIR is fully legal between GlobalISel passes"),
36
38 "verbose-gisel-verify-legalizer-info",
39 cl::desc("Print more information to dbgs about GlobalISel legalizer rules "
40 "being verified"),
42
44 switch (Action) {
45 case Legal:
46 OS << "Legal";
47 break;
48 case NarrowScalar:
49 OS << "NarrowScalar";
50 break;
51 case WidenScalar:
52 OS << "WidenScalar";
53 break;
54 case FewerElements:
55 OS << "FewerElements";
56 break;
57 case MoreElements:
58 OS << "MoreElements";
59 break;
60 case Bitcast:
61 OS << "Bitcast";
62 break;
63 case Lower:
64 OS << "Lower";
65 break;
66 case Libcall:
67 OS << "Libcall";
68 break;
69 case Custom:
70 OS << "Custom";
71 break;
72 case Unsupported:
73 OS << "Unsupported";
74 break;
75 case NotFound:
76 OS << "NotFound";
77 break;
78 }
79 return OS;
80}
81
83 OS << "Opcode=" << Opcode << ", Tys={";
84 for (const auto &Type : Types) {
85 OS << Type << ", ";
86 }
87 OS << "}, MMOs={";
88 for (const auto &MMODescr : MMODescrs) {
89 OS << MMODescr.MemoryTy << ", ";
90 }
91 OS << "}";
92
93 return OS;
94}
95
96#ifndef NDEBUG
97// Make sure the rule won't (trivially) loop forever.
98static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q,
99 const std::pair<unsigned, LLT> &Mutation) {
100 switch (Rule.getAction()) {
101 case Legal:
102 case Custom:
103 case Lower:
104 case MoreElements:
105 case FewerElements:
106 case Libcall:
107 break;
108 default:
109 return Q.Types[Mutation.first] != Mutation.second;
110 }
111 return true;
112}
113
114// Make sure the returned mutation makes sense for the match type.
115static bool mutationIsSane(const LegalizeRule &Rule,
116 const LegalityQuery &Q,
117 std::pair<unsigned, LLT> Mutation) {
118 // If the user wants a custom mutation, then we can't really say much about
119 // it. Return true, and trust that they're doing the right thing.
120 if (Rule.getAction() == Custom || Rule.getAction() == Legal)
121 return true;
122
123 // Skip null mutation.
124 if (!Mutation.second.isValid())
125 return true;
126
127 const unsigned TypeIdx = Mutation.first;
128 const LLT OldTy = Q.Types[TypeIdx];
129 const LLT NewTy = Mutation.second;
130
131 switch (Rule.getAction()) {
132 case FewerElements:
133 if (!OldTy.isVector())
134 return false;
135 [[fallthrough]];
136 case MoreElements: {
137 // MoreElements can go from scalar to vector.
138 const ElementCount OldElts = OldTy.isVector() ?
140 if (NewTy.isVector()) {
141 if (Rule.getAction() == FewerElements) {
142 // Make sure the element count really decreased.
143 if (ElementCount::isKnownGE(NewTy.getElementCount(), OldElts))
144 return false;
145 } else {
146 // Make sure the element count really increased.
147 if (ElementCount::isKnownLE(NewTy.getElementCount(), OldElts))
148 return false;
149 }
150 } else if (Rule.getAction() == MoreElements)
151 return false;
152
153 // Make sure the element type didn't change.
154 return NewTy.getScalarType() == OldTy.getScalarType();
155 }
156 case NarrowScalar:
157 case WidenScalar: {
158 if (OldTy.isVector()) {
159 // Number of elements should not change.
160 if (!NewTy.isVector() ||
161 OldTy.getElementCount() != NewTy.getElementCount())
162 return false;
163 } else {
164 // Both types must be vectors
165 if (NewTy.isVector())
166 return false;
167 }
168
169 if (Rule.getAction() == NarrowScalar) {
170 // Make sure the size really decreased.
171 if (NewTy.getScalarSizeInBits() >= OldTy.getScalarSizeInBits())
172 return false;
173 } else {
174 // Make sure the size really increased.
175 if (NewTy.getScalarSizeInBits() <= OldTy.getScalarSizeInBits())
176 return false;
177 }
178
179 return true;
180 }
181 case Bitcast: {
182 return OldTy != NewTy && OldTy.getSizeInBits() == NewTy.getSizeInBits();
183 }
184 default:
185 return true;
186 }
187}
188#endif
189
191 LLVM_DEBUG(dbgs() << "Applying legalizer ruleset to: "; Query.print(dbgs());
192 dbgs() << "\n");
193 for (const LegalizeRule &Rule : Rules) {
194 if (Rule.match(Query)) {
195 LLVM_DEBUG(dbgs() << ".. match\n");
196 std::pair<unsigned, LLT> Mutation = Rule.determineMutation(Query);
197 LLVM_DEBUG(dbgs() << ".. .. " << Rule.getAction() << ", "
198 << Mutation.first << ", " << Mutation.second << "\n");
199 assert(mutationIsSane(Rule, Query, Mutation) &&
200 "legality mutation invalid for match");
201 assert(hasNoSimpleLoops(Rule, Query, Mutation) && "Simple loop detected");
202 return {Rule.getAction(), Mutation.first, Mutation.second};
203 } else
204 LLVM_DEBUG(dbgs() << ".. no match\n");
205 }
206 LLVM_DEBUG(dbgs() << ".. unsupported\n");
207 return {LegalizeAction::Unsupported, 0, LLT{}};
208}
209
210bool LegalizeRuleSet::verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const {
211#ifndef NDEBUG
212 if (Rules.empty()) {
214 LLVM_DEBUG(dbgs() << ".. type index coverage check SKIPPED: "
215 << "no rules defined\n");
216 }
217 return true;
218 }
219 const int64_t FirstUncovered = TypeIdxsCovered.find_first_unset();
220 if (FirstUncovered < 0) {
222 LLVM_DEBUG(dbgs() << ".. type index coverage check SKIPPED:"
223 " user-defined predicate detected\n");
224 }
225 return true;
226 }
227 const bool AllCovered = (FirstUncovered >= NumTypeIdxs);
228 if (NumTypeIdxs > 0) {
230 LLVM_DEBUG(dbgs() << ".. the first uncovered type index: "
231 << FirstUncovered << ", "
232 << (AllCovered ? "OK" : "FAIL") << "\n");
233 }
234 }
235 return AllCovered;
236#else
237 return true;
238#endif
239}
240
241bool LegalizeRuleSet::verifyImmIdxsCoverage(unsigned NumImmIdxs) const {
242#ifndef NDEBUG
243 if (Rules.empty()) {
245 LLVM_DEBUG(dbgs() << ".. imm index coverage check SKIPPED: "
246 << "no rules defined\n");
247 }
248 return true;
249 }
250 const int64_t FirstUncovered = ImmIdxsCovered.find_first_unset();
251 if (FirstUncovered < 0) {
253 LLVM_DEBUG(dbgs() << ".. imm index coverage check SKIPPED:"
254 " user-defined predicate detected\n");
255 }
256 return true;
257 }
258 const bool AllCovered = (FirstUncovered >= NumImmIdxs);
260 LLVM_DEBUG(dbgs() << ".. the first uncovered imm index: " << FirstUncovered
261 << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
262 }
263 return AllCovered;
264#else
265 return true;
266#endif
267}
268
269/// Helper function to get LLT for the given type index.
271 const MachineRegisterInfo &MRI, unsigned OpIdx,
272 unsigned TypeIdx) {
273 assert(TypeIdx < MI.getNumOperands() && "Unexpected TypeIdx");
274 // G_UNMERGE_VALUES has variable number of operands, but there is only
275 // one source type and one destination type as all destinations must be the
276 // same type. So, get the last operand if TypeIdx == 1.
277 if (MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && TypeIdx == 1)
278 return MRI.getType(MI.getOperand(MI.getNumOperands() - 1).getReg());
279 return MRI.getType(MI.getOperand(OpIdx).getReg());
280}
281
282unsigned LegalizerInfo::getOpcodeIdxForOpcode(unsigned Opcode) const {
283 assert(Opcode >= FirstOp && Opcode <= LastOp && "Unsupported opcode");
284 return Opcode - FirstOp;
285}
286
287unsigned LegalizerInfo::getActionDefinitionsIdx(unsigned Opcode) const {
288 unsigned OpcodeIdx = getOpcodeIdxForOpcode(Opcode);
289 if (unsigned Alias = RulesForOpcode[OpcodeIdx].getAlias()) {
291 LLVM_DEBUG(dbgs() << ".. opcode " << Opcode << " is aliased to " << Alias
292 << "\n");
293 }
294 OpcodeIdx = getOpcodeIdxForOpcode(Alias);
295 assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 && "Cannot chain aliases");
296 }
297
298 return OpcodeIdx;
299}
300
301const LegalizeRuleSet &
303 unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
304 return RulesForOpcode[OpcodeIdx];
305}
306
308 unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
309 auto &Result = RulesForOpcode[OpcodeIdx];
310 assert(!Result.isAliasedByAnother() && "Modifying this opcode will modify aliases");
311 return Result;
312}
313
315 std::initializer_list<unsigned> Opcodes) {
316 unsigned Representative = *Opcodes.begin();
317
318 assert(Opcodes.size() >= 2 &&
319 "Initializer list must have at least two opcodes");
320
321 for (unsigned Op : llvm::drop_begin(Opcodes))
322 aliasActionDefinitions(Representative, Op);
323
324 auto &Return = getActionDefinitionsBuilder(Representative);
325 Return.setIsAliasedByAnother();
326 return Return;
327}
328
330 unsigned OpcodeFrom) {
331 assert(OpcodeTo != OpcodeFrom && "Cannot alias to self");
332 assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp && "Unsupported opcode");
333 const unsigned OpcodeFromIdx = getOpcodeIdxForOpcode(OpcodeFrom);
334 RulesForOpcode[OpcodeFromIdx].aliasTo(OpcodeTo);
335}
336
339 return getActionDefinitions(Query.Opcode).apply(Query);
340}
341
344 const MachineRegisterInfo &MRI) const {
346 SmallBitVector SeenTypes(8);
347 ArrayRef<MCOperandInfo> OpInfo = MI.getDesc().operands();
348 // FIXME: probably we'll need to cache the results here somehow?
349 for (unsigned i = 0; i < MI.getDesc().getNumOperands(); ++i) {
350 if (!OpInfo[i].isGenericType())
351 continue;
352
353 // We must only record actions once for each TypeIdx; otherwise we'd
354 // try to legalize operands multiple times down the line.
355 unsigned TypeIdx = OpInfo[i].getGenericTypeIndex();
356 if (SeenTypes[TypeIdx])
357 continue;
358
359 SeenTypes.set(TypeIdx);
360
361 LLT Ty = getTypeFromTypeIdx(MI, MRI, i, TypeIdx);
362 Types.push_back(Ty);
363 }
364
366 for (const auto &MMO : MI.memoperands())
367 MemDescrs.push_back({*MMO});
368
369 return getAction({MI.getOpcode(), Types, MemDescrs});
370}
371
373 const MachineRegisterInfo &MRI) const {
374 return getAction(MI, MRI).Action == Legal;
375}
376
378 const MachineRegisterInfo &MRI) const {
379 auto Action = getAction(MI, MRI).Action;
380 // If the action is custom, it may not necessarily modify the instruction,
381 // so we have to assume it's legal.
382 return Action == Legal || Action == Custom;
383}
384
386 return SmallTy.isByteSized() ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
387}
388
389/// \pre Type indices of every opcode form a dense set starting from 0.
390void LegalizerInfo::verify(const MCInstrInfo &MII) const {
391#ifndef NDEBUG
392 std::vector<unsigned> FailedOpcodes;
393 for (unsigned Opcode = FirstOp; Opcode <= LastOp; ++Opcode) {
394 const MCInstrDesc &MCID = MII.get(Opcode);
395 const unsigned NumTypeIdxs = std::accumulate(
396 MCID.operands().begin(), MCID.operands().end(), 0U,
397 [](unsigned Acc, const MCOperandInfo &OpInfo) {
398 return OpInfo.isGenericType()
399 ? std::max(OpInfo.getGenericTypeIndex() + 1U, Acc)
400 : Acc;
401 });
402 const unsigned NumImmIdxs = std::accumulate(
403 MCID.operands().begin(), MCID.operands().end(), 0U,
404 [](unsigned Acc, const MCOperandInfo &OpInfo) {
405 return OpInfo.isGenericImm()
406 ? std::max(OpInfo.getGenericImmIndex() + 1U, Acc)
407 : Acc;
408 });
410 LLVM_DEBUG(dbgs() << MII.getName(Opcode) << " (opcode " << Opcode
411 << "): " << NumTypeIdxs << " type ind"
412 << (NumTypeIdxs == 1 ? "ex" : "ices") << ", "
413 << NumImmIdxs << " imm ind"
414 << (NumImmIdxs == 1 ? "ex" : "ices") << "\n");
415 }
416 const LegalizeRuleSet &RuleSet = getActionDefinitions(Opcode);
417 if (!RuleSet.verifyTypeIdxsCoverage(NumTypeIdxs))
418 FailedOpcodes.push_back(Opcode);
419 else if (!RuleSet.verifyImmIdxsCoverage(NumImmIdxs))
420 FailedOpcodes.push_back(Opcode);
421 }
422 if (!FailedOpcodes.empty()) {
423 errs() << "The following opcodes have ill-defined legalization rules:";
424 for (unsigned Opcode : FailedOpcodes)
425 errs() << " " << MII.getName(Opcode);
426 errs() << "\n";
427
428 report_fatal_error("ill-defined LegalizerInfo, try "
429 "-debug-only=legalizer-info and "
430 "-verbose-gisel-verify-legalizer-info for details");
431 }
432#endif
433}
434
435#ifndef NDEBUG
436// FIXME: This should be in the MachineVerifier, but it can't use the
437// LegalizerInfo as it's currently in the separate GlobalISel library.
438// Note that RegBankSelected property already checked in the verifier
439// has the same layering problem, but we only use inline methods so
440// end up not needing to link against the GlobalISel library.
442 if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) {
443 const MachineRegisterInfo &MRI = MF.getRegInfo();
444 for (const MachineBasicBlock &MBB : MF)
445 for (const MachineInstr &MI : MBB)
446 if (isPreISelGenericOpcode(MI.getOpcode()) &&
447 !MLI->isLegalOrCustom(MI, MRI))
448 return &MI;
449 }
450 return nullptr;
451}
452#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
IRTranslator LLVM IR MI
static cl::opt< bool > VerboseVerifyLegalizerInfo("verbose-gisel-verify-legalizer-info", cl::desc("Print more information to dbgs about GlobalISel legalizer rules " "being verified"), cl::Hidden)
static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q, const std::pair< unsigned, LLT > &Mutation)
static LLT getTypeFromTypeIdx(const MachineInstr &MI, const MachineRegisterInfo &MRI, unsigned OpIdx, unsigned TypeIdx)
Helper function to get LLT for the given type index.
static bool mutationIsSane(const LegalizeRule &Rule, const LegalityQuery &Q, std::pair< unsigned, LLT > Mutation)
Interface for Targets to specify which operations they can successfully select and how the others sho...
Implement a low-level type suitable for MachineInstr level instruction selection.
MachineInstr unsigned OpIdx
PowerPC VSX FMA Mutation
This file implements the SmallBitVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr unsigned getScalarSizeInBits() const
LLT getScalarType() const
constexpr bool isVector() const
constexpr bool isByteSized() const
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr ElementCount getElementCount() const
LLVM_ABI bool verifyImmIdxsCoverage(unsigned NumImmIdxs) const
Check if there is no imm index which is obviously not handled by the LegalizeRuleSet in any way at al...
LLVM_ABI bool verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const
Check if there is no type index which is obviously not handled by the LegalizeRuleSet in any way at a...
LLVM_ABI LegalizeActionStep apply(const LegalityQuery &Query) const
Apply the ruleset to the given LegalityQuery.
A single rule in a legalizer info ruleset.
LegalizeAction getAction() const
const LegalizeRuleSet & getActionDefinitions(unsigned Opcode) const
Get the action definitions for the given opcode.
LegalizeRuleSet & getActionDefinitionsBuilder(unsigned Opcode)
Get the action definition builder for the given opcode.
virtual unsigned getExtOpcodeForWideningConstant(LLT SmallTy) const
Return the opcode (SEXT/ZEXT/ANYEXT) that should be performed while widening a constant of type Small...
bool isLegalOrCustom(const LegalityQuery &Query) const
void aliasActionDefinitions(unsigned OpcodeTo, unsigned OpcodeFrom)
void verify(const MCInstrInfo &MII) const
Perform simple self-diagnostic and assert if there is anything obviously wrong with the actions set u...
unsigned getOpcodeIdxForOpcode(unsigned Opcode) const
bool isLegal(const LegalityQuery &Query) const
unsigned getActionDefinitionsIdx(unsigned Opcode) const
LegalizeActionStep getAction(const LegalityQuery &Query) const
Determine what action should be taken to legalize the described instruction.
Describe properties that are true of each instruction in the target description file.
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition MCInstrInfo.h:96
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:86
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
virtual const LegalizerInfo * getLegalizerInfo() const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ FewerElements
The (vector) operation should be implemented by splitting it into sub-vectors where the operation is ...
@ Libcall
The operation should be implemented as a call to some kind of runtime support library.
@ Unsupported
This operation is completely unsupported on the target.
@ Lower
The operation itself must be expressed in terms of simpler actions on this target.
@ WidenScalar
The operation should be implemented in terms of a wider scalar base-type.
@ Bitcast
Perform the operation on a different, but equivalently sized type.
@ NarrowScalar
The operation should be synthesized from multiple instructions acting on a narrower scalar base-type.
@ Custom
The target wants to do something special with this combination of operand and type.
@ NotFound
Sentinel value for when no action was found in the specified table.
@ MoreElements
The (vector) operation should be implemented by widening the input vector and ignoring the lanes adde...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel.
LLVM_ABI cl::opt< bool > DisableGISelLegalityCheck
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
const MachineInstr * machineFunctionIsIllegal(const MachineFunction &MF)
Checks that MIR is fully legal, returns an illegal instruction if it's not, nullptr otherwise.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
@ Custom
The result value requires a custom uniformity check.
Definition Uniformity.h:31
The LegalityQuery object bundles together all the information that's needed to decide whether a given...
ArrayRef< MemDesc > MMODescrs
Operations which require memory can use this to place requirements on the memory type for each MMO.
ArrayRef< LLT > Types
LLVM_ABI raw_ostream & print(raw_ostream &OS) const
The result of a query.
LegalizeAction Action
The action to take or the final answer.