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
14#include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
15#include "llvm/ADT/SmallBitVector.h"
16#include "llvm/CodeGen/MachineInstr.h"
17#include "llvm/CodeGen/MachineOperand.h"
18#include "llvm/CodeGen/MachineRegisterInfo.h"
19#include "llvm/CodeGen/TargetOpcodes.h"
20#include "llvm/CodeGenTypes/LowLevelType.h"
21#include "llvm/MC/MCInstrDesc.h"
22#include "llvm/MC/MCInstrInfo.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26
27using namespace llvm;
28using namespace LegalizeActions;
29
30#define DEBUG_TYPE "legalizer-info"
31
32cl::opt<bool> llvm::DisableGISelLegalityCheck(
33 "disable-gisel-legality-check",
34 cl::desc("Don't verify that MIR is fully legal between GlobalISel passes"),
35 cl::Hidden);
36
37static cl::opt<bool> VerboseVerifyLegalizerInfo(
38 "verbose-gisel-verify-legalizer-info",
39 cl::desc("Print more information to dbgs about GlobalISel legalizer rules "
40 "being verified"),
41 cl::Hidden);
42
43raw_ostream &llvm::operator<<(raw_ostream &OS, LegalizeAction Action) {
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
82raw_ostream &LegalityQuery::print(raw_ostream &OS) const {
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() ?
139 OldTy.getElementCount() : ElementCount::getFixed(1);
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
190LegalizeActionStep LegalizeRuleSet::apply(const LegalityQuery &Query) const {
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()) {
213 if (VerboseVerifyLegalizerInfo) {
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) {
221 if (VerboseVerifyLegalizerInfo) {
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) {
229 if (VerboseVerifyLegalizerInfo) {
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()) {
244 if (VerboseVerifyLegalizerInfo) {
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) {
252 if (VerboseVerifyLegalizerInfo) {
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);
259 if (VerboseVerifyLegalizerInfo) {
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.
270static LLT getTypeFromTypeIdx(const MachineInstr &MI,
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(Reg: MI.getOperand(i: MI.getNumOperands() - 1).getReg());
279 return MRI.getType(Reg: MI.getOperand(i: 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()) {
290 if (VerboseVerifyLegalizerInfo) {
291 LLVM_DEBUG(dbgs() << ".. opcode " << Opcode << " is aliased to " << Alias
292 << "\n");
293 }
294 OpcodeIdx = getOpcodeIdxForOpcode(Opcode: Alias);
295 assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 && "Cannot chain aliases");
296 }
297
298 return OpcodeIdx;
299}
300
301const LegalizeRuleSet &
302LegalizerInfo::getActionDefinitions(unsigned Opcode) const {
303 unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
304 return RulesForOpcode[OpcodeIdx];
305}
306
307LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(unsigned Opcode) {
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
314LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(
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(RangeOrContainer&: Opcodes))
322 aliasActionDefinitions(OpcodeTo: Representative, OpcodeFrom: Op);
323
324 auto &Return = getActionDefinitionsBuilder(Opcode: Representative);
325 Return.setIsAliasedByAnother();
326 return Return;
327}
328
329void LegalizerInfo::aliasActionDefinitions(unsigned OpcodeTo,
330 unsigned OpcodeFrom) {
331 assert(OpcodeTo != OpcodeFrom && "Cannot alias to self");
332 assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp && "Unsupported opcode");
333 const unsigned OpcodeFromIdx = getOpcodeIdxForOpcode(Opcode: OpcodeFrom);
334 RulesForOpcode[OpcodeFromIdx].aliasTo(Opcode: OpcodeTo);
335}
336
337LegalizeActionStep
338LegalizerInfo::getAction(const LegalityQuery &Query) const {
339 return getActionDefinitions(Opcode: Query.Opcode).apply(Query);
340}
341
342LegalizeActionStep
343LegalizerInfo::getAction(const MachineInstr &MI,
344 const MachineRegisterInfo &MRI) const {
345 SmallVector<LLT, 8> Types;
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, OpIdx: i, TypeIdx);
362 Types.push_back(Elt: Ty);
363 }
364
365 SmallVector<LegalityQuery::MemDesc, 2> MemDescrs;
366 for (const auto &MMO : MI.memoperands())
367 MemDescrs.push_back(Elt: {*MMO});
368
369 return getAction(Query: {MI.getOpcode(), Types, MemDescrs});
370}
371
372bool LegalizerInfo::isLegal(const MachineInstr &MI,
373 const MachineRegisterInfo &MRI) const {
374 return getAction(MI, MRI).Action == Legal;
375}
376
377bool LegalizerInfo::isLegalOrCustom(const MachineInstr &MI,
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
385unsigned LegalizerInfo::getExtOpcodeForWideningConstant(LLT SmallTy) const {
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 });
409 if (VerboseVerifyLegalizerInfo) {
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.
441const MachineInstr *llvm::machineFunctionIsIllegal(const MachineFunction &MF) {
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
453