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/MC/MCInstrDesc.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LowLevelTypeImpl.h"
25 #include <algorithm>
26 
27 using namespace llvm;
28 using namespace LegalizeActions;
29 
30 #define DEBUG_TYPE "legalizer-info"
31 
32 cl::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 
37 raw_ostream &llvm::operator<<(raw_ostream &OS, LegalizeAction Action) {
38   switch (Action) {
39   case Legal:
40     OS << "Legal";
41     break;
42   case NarrowScalar:
43     OS << "NarrowScalar";
44     break;
45   case WidenScalar:
46     OS << "WidenScalar";
47     break;
48   case FewerElements:
49     OS << "FewerElements";
50     break;
51   case MoreElements:
52     OS << "MoreElements";
53     break;
54   case Bitcast:
55     OS << "Bitcast";
56     break;
57   case Lower:
58     OS << "Lower";
59     break;
60   case Libcall:
61     OS << "Libcall";
62     break;
63   case Custom:
64     OS << "Custom";
65     break;
66   case Unsupported:
67     OS << "Unsupported";
68     break;
69   case NotFound:
70     OS << "NotFound";
71     break;
72   case UseLegacyRules:
73     OS << "UseLegacyRules";
74     break;
75   }
76   return OS;
77 }
78 
79 raw_ostream &LegalityQuery::print(raw_ostream &OS) const {
80   OS << Opcode << ", Tys={";
81   for (const auto &Type : Types) {
82     OS << Type << ", ";
83   }
84   OS << "}, Opcode=";
85 
86   OS << Opcode << ", MMOs={";
87   for (const auto &MMODescr : MMODescrs) {
88     OS << MMODescr.MemoryTy << ", ";
89   }
90   OS << "}";
91 
92   return OS;
93 }
94 
95 #ifndef NDEBUG
96 // Make sure the rule won't (trivially) loop forever.
97 static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q,
98                              const std::pair<unsigned, LLT> &Mutation) {
99   switch (Rule.getAction()) {
100   case Legal:
101   case Custom:
102   case Lower:
103   case MoreElements:
104   case FewerElements:
105     break;
106   default:
107     return Q.Types[Mutation.first] != Mutation.second;
108   }
109   return true;
110 }
111 
112 // Make sure the returned mutation makes sense for the match type.
113 static bool mutationIsSane(const LegalizeRule &Rule,
114                            const LegalityQuery &Q,
115                            std::pair<unsigned, LLT> Mutation) {
116   // If the user wants a custom mutation, then we can't really say much about
117   // it. Return true, and trust that they're doing the right thing.
118   if (Rule.getAction() == Custom || Rule.getAction() == Legal)
119     return true;
120 
121   const unsigned TypeIdx = Mutation.first;
122   const LLT OldTy = Q.Types[TypeIdx];
123   const LLT NewTy = Mutation.second;
124 
125   switch (Rule.getAction()) {
126   case FewerElements:
127     if (!OldTy.isVector())
128       return false;
129     LLVM_FALLTHROUGH;
130   case MoreElements: {
131     // MoreElements can go from scalar to vector.
132     const unsigned OldElts = OldTy.isVector() ? OldTy.getNumElements() : 1;
133     if (NewTy.isVector()) {
134       if (Rule.getAction() == FewerElements) {
135         // Make sure the element count really decreased.
136         if (NewTy.getNumElements() >= OldElts)
137           return false;
138       } else {
139         // Make sure the element count really increased.
140         if (NewTy.getNumElements() <= OldElts)
141           return false;
142       }
143     } else if (Rule.getAction() == MoreElements)
144       return false;
145 
146     // Make sure the element type didn't change.
147     return NewTy.getScalarType() == OldTy.getScalarType();
148   }
149   case NarrowScalar:
150   case WidenScalar: {
151     if (OldTy.isVector()) {
152       // Number of elements should not change.
153       if (!NewTy.isVector() || OldTy.getNumElements() != NewTy.getNumElements())
154         return false;
155     } else {
156       // Both types must be vectors
157       if (NewTy.isVector())
158         return false;
159     }
160 
161     if (Rule.getAction() == NarrowScalar)  {
162       // Make sure the size really decreased.
163       if (NewTy.getScalarSizeInBits() >= OldTy.getScalarSizeInBits())
164         return false;
165     } else {
166       // Make sure the size really increased.
167       if (NewTy.getScalarSizeInBits() <= OldTy.getScalarSizeInBits())
168         return false;
169     }
170 
171     return true;
172   }
173   case Bitcast: {
174     return OldTy != NewTy && OldTy.getSizeInBits() == NewTy.getSizeInBits();
175   }
176   default:
177     return true;
178   }
179 }
180 #endif
181 
182 LegalizeActionStep LegalizeRuleSet::apply(const LegalityQuery &Query) const {
183   LLVM_DEBUG(dbgs() << "Applying legalizer ruleset to: "; Query.print(dbgs());
184              dbgs() << "\n");
185   if (Rules.empty()) {
186     LLVM_DEBUG(dbgs() << ".. fallback to legacy rules (no rules defined)\n");
187     return {LegalizeAction::UseLegacyRules, 0, LLT{}};
188   }
189   for (const LegalizeRule &Rule : Rules) {
190     if (Rule.match(Query)) {
191       LLVM_DEBUG(dbgs() << ".. match\n");
192       std::pair<unsigned, LLT> Mutation = Rule.determineMutation(Query);
193       LLVM_DEBUG(dbgs() << ".. .. " << Rule.getAction() << ", "
194                         << Mutation.first << ", " << Mutation.second << "\n");
195       assert(mutationIsSane(Rule, Query, Mutation) &&
196              "legality mutation invalid for match");
197       assert(hasNoSimpleLoops(Rule, Query, Mutation) && "Simple loop detected");
198       return {Rule.getAction(), Mutation.first, Mutation.second};
199     } else
200       LLVM_DEBUG(dbgs() << ".. no match\n");
201   }
202   LLVM_DEBUG(dbgs() << ".. unsupported\n");
203   return {LegalizeAction::Unsupported, 0, LLT{}};
204 }
205 
206 bool LegalizeRuleSet::verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const {
207 #ifndef NDEBUG
208   if (Rules.empty()) {
209     LLVM_DEBUG(
210         dbgs() << ".. type index coverage check SKIPPED: no rules defined\n");
211     return true;
212   }
213   const int64_t FirstUncovered = TypeIdxsCovered.find_first_unset();
214   if (FirstUncovered < 0) {
215     LLVM_DEBUG(dbgs() << ".. type index coverage check SKIPPED:"
216                          " user-defined predicate detected\n");
217     return true;
218   }
219   const bool AllCovered = (FirstUncovered >= NumTypeIdxs);
220   if (NumTypeIdxs > 0)
221     LLVM_DEBUG(dbgs() << ".. the first uncovered type index: " << FirstUncovered
222                       << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
223   return AllCovered;
224 #else
225   return true;
226 #endif
227 }
228 
229 bool LegalizeRuleSet::verifyImmIdxsCoverage(unsigned NumImmIdxs) const {
230 #ifndef NDEBUG
231   if (Rules.empty()) {
232     LLVM_DEBUG(
233         dbgs() << ".. imm index coverage check SKIPPED: no rules defined\n");
234     return true;
235   }
236   const int64_t FirstUncovered = ImmIdxsCovered.find_first_unset();
237   if (FirstUncovered < 0) {
238     LLVM_DEBUG(dbgs() << ".. imm index coverage check SKIPPED:"
239                          " user-defined predicate detected\n");
240     return true;
241   }
242   const bool AllCovered = (FirstUncovered >= NumImmIdxs);
243   LLVM_DEBUG(dbgs() << ".. the first uncovered imm index: " << FirstUncovered
244                     << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
245   return AllCovered;
246 #else
247   return true;
248 #endif
249 }
250 
251 /// Helper function to get LLT for the given type index.
252 static LLT getTypeFromTypeIdx(const MachineInstr &MI,
253                               const MachineRegisterInfo &MRI, unsigned OpIdx,
254                               unsigned TypeIdx) {
255   assert(TypeIdx < MI.getNumOperands() && "Unexpected TypeIdx");
256   // G_UNMERGE_VALUES has variable number of operands, but there is only
257   // one source type and one destination type as all destinations must be the
258   // same type. So, get the last operand if TypeIdx == 1.
259   if (MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && TypeIdx == 1)
260     return MRI.getType(MI.getOperand(MI.getNumOperands() - 1).getReg());
261   return MRI.getType(MI.getOperand(OpIdx).getReg());
262 }
263 
264 unsigned LegalizerInfo::getOpcodeIdxForOpcode(unsigned Opcode) const {
265   assert(Opcode >= FirstOp && Opcode <= LastOp && "Unsupported opcode");
266   return Opcode - FirstOp;
267 }
268 
269 unsigned LegalizerInfo::getActionDefinitionsIdx(unsigned Opcode) const {
270   unsigned OpcodeIdx = getOpcodeIdxForOpcode(Opcode);
271   if (unsigned Alias = RulesForOpcode[OpcodeIdx].getAlias()) {
272     LLVM_DEBUG(dbgs() << ".. opcode " << Opcode << " is aliased to " << Alias
273                       << "\n");
274     OpcodeIdx = getOpcodeIdxForOpcode(Alias);
275     assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 && "Cannot chain aliases");
276   }
277 
278   return OpcodeIdx;
279 }
280 
281 const LegalizeRuleSet &
282 LegalizerInfo::getActionDefinitions(unsigned Opcode) const {
283   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
284   return RulesForOpcode[OpcodeIdx];
285 }
286 
287 LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(unsigned Opcode) {
288   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
289   auto &Result = RulesForOpcode[OpcodeIdx];
290   assert(!Result.isAliasedByAnother() && "Modifying this opcode will modify aliases");
291   return Result;
292 }
293 
294 LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(
295     std::initializer_list<unsigned> Opcodes) {
296   unsigned Representative = *Opcodes.begin();
297 
298   assert(!llvm::empty(Opcodes) && Opcodes.begin() + 1 != Opcodes.end() &&
299          "Initializer list must have at least two opcodes");
300 
301   for (unsigned Op : llvm::drop_begin(Opcodes))
302     aliasActionDefinitions(Representative, Op);
303 
304   auto &Return = getActionDefinitionsBuilder(Representative);
305   Return.setIsAliasedByAnother();
306   return Return;
307 }
308 
309 void LegalizerInfo::aliasActionDefinitions(unsigned OpcodeTo,
310                                            unsigned OpcodeFrom) {
311   assert(OpcodeTo != OpcodeFrom && "Cannot alias to self");
312   assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp && "Unsupported opcode");
313   const unsigned OpcodeFromIdx = getOpcodeIdxForOpcode(OpcodeFrom);
314   RulesForOpcode[OpcodeFromIdx].aliasTo(OpcodeTo);
315 }
316 
317 LegalizeActionStep
318 LegalizerInfo::getAction(const LegalityQuery &Query) const {
319   LegalizeActionStep Step = getActionDefinitions(Query.Opcode).apply(Query);
320   if (Step.Action != LegalizeAction::UseLegacyRules) {
321     return Step;
322   }
323 
324   return getLegacyLegalizerInfo().getAction(Query);
325 }
326 
327 LegalizeActionStep
328 LegalizerInfo::getAction(const MachineInstr &MI,
329                          const MachineRegisterInfo &MRI) const {
330   SmallVector<LLT, 8> Types;
331   SmallBitVector SeenTypes(8);
332   const MCOperandInfo *OpInfo = MI.getDesc().OpInfo;
333   // FIXME: probably we'll need to cache the results here somehow?
334   for (unsigned i = 0; i < MI.getDesc().getNumOperands(); ++i) {
335     if (!OpInfo[i].isGenericType())
336       continue;
337 
338     // We must only record actions once for each TypeIdx; otherwise we'd
339     // try to legalize operands multiple times down the line.
340     unsigned TypeIdx = OpInfo[i].getGenericTypeIndex();
341     if (SeenTypes[TypeIdx])
342       continue;
343 
344     SeenTypes.set(TypeIdx);
345 
346     LLT Ty = getTypeFromTypeIdx(MI, MRI, i, TypeIdx);
347     Types.push_back(Ty);
348   }
349 
350   SmallVector<LegalityQuery::MemDesc, 2> MemDescrs;
351   for (const auto &MMO : MI.memoperands())
352     MemDescrs.push_back({*MMO});
353 
354   return getAction({MI.getOpcode(), Types, MemDescrs});
355 }
356 
357 bool LegalizerInfo::isLegal(const MachineInstr &MI,
358                             const MachineRegisterInfo &MRI) const {
359   return getAction(MI, MRI).Action == Legal;
360 }
361 
362 bool LegalizerInfo::isLegalOrCustom(const MachineInstr &MI,
363                                     const MachineRegisterInfo &MRI) const {
364   auto Action = getAction(MI, MRI).Action;
365   // If the action is custom, it may not necessarily modify the instruction,
366   // so we have to assume it's legal.
367   return Action == Legal || Action == Custom;
368 }
369 
370 unsigned LegalizerInfo::getExtOpcodeForWideningConstant(LLT SmallTy) const {
371   return SmallTy.isByteSized() ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
372 }
373 
374 /// \pre Type indices of every opcode form a dense set starting from 0.
375 void LegalizerInfo::verify(const MCInstrInfo &MII) const {
376 #ifndef NDEBUG
377   std::vector<unsigned> FailedOpcodes;
378   for (unsigned Opcode = FirstOp; Opcode <= LastOp; ++Opcode) {
379     const MCInstrDesc &MCID = MII.get(Opcode);
380     const unsigned NumTypeIdxs = std::accumulate(
381         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
382         [](unsigned Acc, const MCOperandInfo &OpInfo) {
383           return OpInfo.isGenericType()
384                      ? std::max(OpInfo.getGenericTypeIndex() + 1U, Acc)
385                      : Acc;
386         });
387     const unsigned NumImmIdxs = std::accumulate(
388         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
389         [](unsigned Acc, const MCOperandInfo &OpInfo) {
390           return OpInfo.isGenericImm()
391                      ? std::max(OpInfo.getGenericImmIndex() + 1U, Acc)
392                      : Acc;
393         });
394     LLVM_DEBUG(dbgs() << MII.getName(Opcode) << " (opcode " << Opcode
395                       << "): " << NumTypeIdxs << " type ind"
396                       << (NumTypeIdxs == 1 ? "ex" : "ices") << ", "
397                       << NumImmIdxs << " imm ind"
398                       << (NumImmIdxs == 1 ? "ex" : "ices") << "\n");
399     const LegalizeRuleSet &RuleSet = getActionDefinitions(Opcode);
400     if (!RuleSet.verifyTypeIdxsCoverage(NumTypeIdxs))
401       FailedOpcodes.push_back(Opcode);
402     else if (!RuleSet.verifyImmIdxsCoverage(NumImmIdxs))
403       FailedOpcodes.push_back(Opcode);
404   }
405   if (!FailedOpcodes.empty()) {
406     errs() << "The following opcodes have ill-defined legalization rules:";
407     for (unsigned Opcode : FailedOpcodes)
408       errs() << " " << MII.getName(Opcode);
409     errs() << "\n";
410 
411     report_fatal_error("ill-defined LegalizerInfo"
412                        ", try -debug-only=legalizer-info for details");
413   }
414 #endif
415 }
416 
417 #ifndef NDEBUG
418 // FIXME: This should be in the MachineVerifier, but it can't use the
419 // LegalizerInfo as it's currently in the separate GlobalISel library.
420 // Note that RegBankSelected property already checked in the verifier
421 // has the same layering problem, but we only use inline methods so
422 // end up not needing to link against the GlobalISel library.
423 const MachineInstr *llvm::machineFunctionIsIllegal(const MachineFunction &MF) {
424   if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) {
425     const MachineRegisterInfo &MRI = MF.getRegInfo();
426     for (const MachineBasicBlock &MBB : MF)
427       for (const MachineInstr &MI : MBB)
428         if (isPreISelGenericOpcode(MI.getOpcode()) &&
429             !MLI->isLegalOrCustom(MI, MRI))
430           return &MI;
431   }
432   return nullptr;
433 }
434 #endif
435