xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
10b57cec5SDimitry Andric //===- lib/CodeGen/GlobalISel/LegalizerInfo.cpp - Legalizer ---------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Implement an interface to specify and query how an illegal operation on a
100b57cec5SDimitry Andric // given type should be expanded.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // Issues to be resolved:
130b57cec5SDimitry Andric //   + Make it fast.
140b57cec5SDimitry Andric //   + Support weird types like i3, <7 x i3>, ...
150b57cec5SDimitry Andric //   + Operations with more than one type (ICMP, CMPXCHG, intrinsics, ...)
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
260b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
270b57cec5SDimitry Andric #include "llvm/MC/MCInstrInfo.h"
280b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
290b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
300b57cec5SDimitry Andric #include "llvm/Support/LowLevelTypeImpl.h"
310b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
320b57cec5SDimitry Andric #include <algorithm>
330b57cec5SDimitry Andric #include <map>
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric using namespace LegalizeActions;
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric #define DEBUG_TYPE "legalizer-info"
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric cl::opt<bool> llvm::DisableGISelLegalityCheck(
410b57cec5SDimitry Andric     "disable-gisel-legality-check",
420b57cec5SDimitry Andric     cl::desc("Don't verify that MIR is fully legal between GlobalISel passes"),
430b57cec5SDimitry Andric     cl::Hidden);
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric raw_ostream &llvm::operator<<(raw_ostream &OS, LegalizeAction Action) {
460b57cec5SDimitry Andric   switch (Action) {
470b57cec5SDimitry Andric   case Legal:
480b57cec5SDimitry Andric     OS << "Legal";
490b57cec5SDimitry Andric     break;
500b57cec5SDimitry Andric   case NarrowScalar:
510b57cec5SDimitry Andric     OS << "NarrowScalar";
520b57cec5SDimitry Andric     break;
530b57cec5SDimitry Andric   case WidenScalar:
540b57cec5SDimitry Andric     OS << "WidenScalar";
550b57cec5SDimitry Andric     break;
560b57cec5SDimitry Andric   case FewerElements:
570b57cec5SDimitry Andric     OS << "FewerElements";
580b57cec5SDimitry Andric     break;
590b57cec5SDimitry Andric   case MoreElements:
600b57cec5SDimitry Andric     OS << "MoreElements";
610b57cec5SDimitry Andric     break;
62*5ffd83dbSDimitry Andric   case Bitcast:
63*5ffd83dbSDimitry Andric     OS << "Bitcast";
64*5ffd83dbSDimitry Andric     break;
650b57cec5SDimitry Andric   case Lower:
660b57cec5SDimitry Andric     OS << "Lower";
670b57cec5SDimitry Andric     break;
680b57cec5SDimitry Andric   case Libcall:
690b57cec5SDimitry Andric     OS << "Libcall";
700b57cec5SDimitry Andric     break;
710b57cec5SDimitry Andric   case Custom:
720b57cec5SDimitry Andric     OS << "Custom";
730b57cec5SDimitry Andric     break;
740b57cec5SDimitry Andric   case Unsupported:
750b57cec5SDimitry Andric     OS << "Unsupported";
760b57cec5SDimitry Andric     break;
770b57cec5SDimitry Andric   case NotFound:
780b57cec5SDimitry Andric     OS << "NotFound";
790b57cec5SDimitry Andric     break;
800b57cec5SDimitry Andric   case UseLegacyRules:
810b57cec5SDimitry Andric     OS << "UseLegacyRules";
820b57cec5SDimitry Andric     break;
830b57cec5SDimitry Andric   }
840b57cec5SDimitry Andric   return OS;
850b57cec5SDimitry Andric }
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric raw_ostream &LegalityQuery::print(raw_ostream &OS) const {
880b57cec5SDimitry Andric   OS << Opcode << ", Tys={";
890b57cec5SDimitry Andric   for (const auto &Type : Types) {
900b57cec5SDimitry Andric     OS << Type << ", ";
910b57cec5SDimitry Andric   }
920b57cec5SDimitry Andric   OS << "}, Opcode=";
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   OS << Opcode << ", MMOs={";
950b57cec5SDimitry Andric   for (const auto &MMODescr : MMODescrs) {
960b57cec5SDimitry Andric     OS << MMODescr.SizeInBits << ", ";
970b57cec5SDimitry Andric   }
980b57cec5SDimitry Andric   OS << "}";
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   return OS;
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric #ifndef NDEBUG
1040b57cec5SDimitry Andric // Make sure the rule won't (trivially) loop forever.
1050b57cec5SDimitry Andric static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q,
1060b57cec5SDimitry Andric                              const std::pair<unsigned, LLT> &Mutation) {
1070b57cec5SDimitry Andric   switch (Rule.getAction()) {
1080b57cec5SDimitry Andric   case Custom:
1090b57cec5SDimitry Andric   case Lower:
1100b57cec5SDimitry Andric   case MoreElements:
1110b57cec5SDimitry Andric   case FewerElements:
1120b57cec5SDimitry Andric     break;
1130b57cec5SDimitry Andric   default:
1140b57cec5SDimitry Andric     return Q.Types[Mutation.first] != Mutation.second;
1150b57cec5SDimitry Andric   }
1160b57cec5SDimitry Andric   return true;
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric // Make sure the returned mutation makes sense for the match type.
1200b57cec5SDimitry Andric static bool mutationIsSane(const LegalizeRule &Rule,
1210b57cec5SDimitry Andric                            const LegalityQuery &Q,
1220b57cec5SDimitry Andric                            std::pair<unsigned, LLT> Mutation) {
1230b57cec5SDimitry Andric   // If the user wants a custom mutation, then we can't really say much about
1240b57cec5SDimitry Andric   // it. Return true, and trust that they're doing the right thing.
1250b57cec5SDimitry Andric   if (Rule.getAction() == Custom)
1260b57cec5SDimitry Andric     return true;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   const unsigned TypeIdx = Mutation.first;
1290b57cec5SDimitry Andric   const LLT OldTy = Q.Types[TypeIdx];
1300b57cec5SDimitry Andric   const LLT NewTy = Mutation.second;
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   switch (Rule.getAction()) {
1330b57cec5SDimitry Andric   case FewerElements:
1340b57cec5SDimitry Andric     if (!OldTy.isVector())
1350b57cec5SDimitry Andric       return false;
136480093f4SDimitry Andric     LLVM_FALLTHROUGH;
137480093f4SDimitry Andric   case MoreElements: {
138480093f4SDimitry Andric     // MoreElements can go from scalar to vector.
139480093f4SDimitry Andric     const unsigned OldElts = OldTy.isVector() ? OldTy.getNumElements() : 1;
1400b57cec5SDimitry Andric     if (NewTy.isVector()) {
1410b57cec5SDimitry Andric       if (Rule.getAction() == FewerElements) {
1420b57cec5SDimitry Andric         // Make sure the element count really decreased.
143480093f4SDimitry Andric         if (NewTy.getNumElements() >= OldElts)
1440b57cec5SDimitry Andric           return false;
1450b57cec5SDimitry Andric       } else {
1460b57cec5SDimitry Andric         // Make sure the element count really increased.
147480093f4SDimitry Andric         if (NewTy.getNumElements() <= OldElts)
1480b57cec5SDimitry Andric           return false;
1490b57cec5SDimitry Andric       }
1500b57cec5SDimitry Andric     }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric     // Make sure the element type didn't change.
153480093f4SDimitry Andric     return NewTy.getScalarType() == OldTy.getScalarType();
1540b57cec5SDimitry Andric   }
1550b57cec5SDimitry Andric   case NarrowScalar:
1560b57cec5SDimitry Andric   case WidenScalar: {
1570b57cec5SDimitry Andric     if (OldTy.isVector()) {
1580b57cec5SDimitry Andric       // Number of elements should not change.
1590b57cec5SDimitry Andric       if (!NewTy.isVector() || OldTy.getNumElements() != NewTy.getNumElements())
1600b57cec5SDimitry Andric         return false;
1610b57cec5SDimitry Andric     } else {
1620b57cec5SDimitry Andric       // Both types must be vectors
1630b57cec5SDimitry Andric       if (NewTy.isVector())
1640b57cec5SDimitry Andric         return false;
1650b57cec5SDimitry Andric     }
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric     if (Rule.getAction() == NarrowScalar)  {
1680b57cec5SDimitry Andric       // Make sure the size really decreased.
1690b57cec5SDimitry Andric       if (NewTy.getScalarSizeInBits() >= OldTy.getScalarSizeInBits())
1700b57cec5SDimitry Andric         return false;
1710b57cec5SDimitry Andric     } else {
1720b57cec5SDimitry Andric       // Make sure the size really increased.
1730b57cec5SDimitry Andric       if (NewTy.getScalarSizeInBits() <= OldTy.getScalarSizeInBits())
1740b57cec5SDimitry Andric         return false;
1750b57cec5SDimitry Andric     }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric     return true;
1780b57cec5SDimitry Andric   }
179*5ffd83dbSDimitry Andric   case Bitcast: {
180*5ffd83dbSDimitry Andric     return OldTy != NewTy && OldTy.getSizeInBits() == NewTy.getSizeInBits();
181*5ffd83dbSDimitry Andric   }
1820b57cec5SDimitry Andric   default:
1830b57cec5SDimitry Andric     return true;
1840b57cec5SDimitry Andric   }
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric #endif
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric LegalizeActionStep LegalizeRuleSet::apply(const LegalityQuery &Query) const {
1890b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Applying legalizer ruleset to: "; Query.print(dbgs());
1900b57cec5SDimitry Andric              dbgs() << "\n");
1910b57cec5SDimitry Andric   if (Rules.empty()) {
1920b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. fallback to legacy rules (no rules defined)\n");
1930b57cec5SDimitry Andric     return {LegalizeAction::UseLegacyRules, 0, LLT{}};
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric   for (const LegalizeRule &Rule : Rules) {
1960b57cec5SDimitry Andric     if (Rule.match(Query)) {
1970b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. match\n");
1980b57cec5SDimitry Andric       std::pair<unsigned, LLT> Mutation = Rule.determineMutation(Query);
1990b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. .. " << Rule.getAction() << ", "
2000b57cec5SDimitry Andric                         << Mutation.first << ", " << Mutation.second << "\n");
2010b57cec5SDimitry Andric       assert(mutationIsSane(Rule, Query, Mutation) &&
2020b57cec5SDimitry Andric              "legality mutation invalid for match");
2030b57cec5SDimitry Andric       assert(hasNoSimpleLoops(Rule, Query, Mutation) && "Simple loop detected");
2040b57cec5SDimitry Andric       return {Rule.getAction(), Mutation.first, Mutation.second};
2050b57cec5SDimitry Andric     } else
2060b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. no match\n");
2070b57cec5SDimitry Andric   }
2080b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << ".. unsupported\n");
2090b57cec5SDimitry Andric   return {LegalizeAction::Unsupported, 0, LLT{}};
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric bool LegalizeRuleSet::verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const {
2130b57cec5SDimitry Andric #ifndef NDEBUG
2140b57cec5SDimitry Andric   if (Rules.empty()) {
2150b57cec5SDimitry Andric     LLVM_DEBUG(
2160b57cec5SDimitry Andric         dbgs() << ".. type index coverage check SKIPPED: no rules defined\n");
2170b57cec5SDimitry Andric     return true;
2180b57cec5SDimitry Andric   }
2190b57cec5SDimitry Andric   const int64_t FirstUncovered = TypeIdxsCovered.find_first_unset();
2200b57cec5SDimitry Andric   if (FirstUncovered < 0) {
2210b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. type index coverage check SKIPPED:"
2220b57cec5SDimitry Andric                          " user-defined predicate detected\n");
2230b57cec5SDimitry Andric     return true;
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric   const bool AllCovered = (FirstUncovered >= NumTypeIdxs);
2268bcb0991SDimitry Andric   if (NumTypeIdxs > 0)
2270b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. the first uncovered type index: " << FirstUncovered
2280b57cec5SDimitry Andric                       << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
2290b57cec5SDimitry Andric   return AllCovered;
2300b57cec5SDimitry Andric #else
2310b57cec5SDimitry Andric   return true;
2320b57cec5SDimitry Andric #endif
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
2358bcb0991SDimitry Andric bool LegalizeRuleSet::verifyImmIdxsCoverage(unsigned NumImmIdxs) const {
2368bcb0991SDimitry Andric #ifndef NDEBUG
2378bcb0991SDimitry Andric   if (Rules.empty()) {
2388bcb0991SDimitry Andric     LLVM_DEBUG(
2398bcb0991SDimitry Andric         dbgs() << ".. imm index coverage check SKIPPED: no rules defined\n");
2408bcb0991SDimitry Andric     return true;
2418bcb0991SDimitry Andric   }
2428bcb0991SDimitry Andric   const int64_t FirstUncovered = ImmIdxsCovered.find_first_unset();
2438bcb0991SDimitry Andric   if (FirstUncovered < 0) {
2448bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << ".. imm index coverage check SKIPPED:"
2458bcb0991SDimitry Andric                          " user-defined predicate detected\n");
2468bcb0991SDimitry Andric     return true;
2478bcb0991SDimitry Andric   }
2488bcb0991SDimitry Andric   const bool AllCovered = (FirstUncovered >= NumImmIdxs);
2498bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << ".. the first uncovered imm index: " << FirstUncovered
2508bcb0991SDimitry Andric                     << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
2518bcb0991SDimitry Andric   return AllCovered;
2528bcb0991SDimitry Andric #else
2538bcb0991SDimitry Andric   return true;
2548bcb0991SDimitry Andric #endif
2558bcb0991SDimitry Andric }
2568bcb0991SDimitry Andric 
2570b57cec5SDimitry Andric LegalizerInfo::LegalizerInfo() : TablesInitialized(false) {
2580b57cec5SDimitry Andric   // Set defaults.
2590b57cec5SDimitry Andric   // FIXME: these two (G_ANYEXT and G_TRUNC?) can be legalized to the
2600b57cec5SDimitry Andric   // fundamental load/store Jakob proposed. Once loads & stores are supported.
2610b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_ANYEXT, 1, {{1, Legal}});
2620b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_ZEXT, 1, {{1, Legal}});
2630b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_SEXT, 1, {{1, Legal}});
2640b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_TRUNC, 0, {{1, Legal}});
2650b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_TRUNC, 1, {{1, Legal}});
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_INTRINSIC, 0, {{1, Legal}});
2680b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS, 0, {{1, Legal}});
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2710b57cec5SDimitry Andric       TargetOpcode::G_IMPLICIT_DEF, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2720b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2730b57cec5SDimitry Andric       TargetOpcode::G_ADD, 0, widenToLargerTypesAndNarrowToLargest);
2740b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2750b57cec5SDimitry Andric       TargetOpcode::G_OR, 0, widenToLargerTypesAndNarrowToLargest);
2760b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2770b57cec5SDimitry Andric       TargetOpcode::G_LOAD, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2780b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2790b57cec5SDimitry Andric       TargetOpcode::G_STORE, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2820b57cec5SDimitry Andric       TargetOpcode::G_BRCOND, 0, widenToLargerTypesUnsupportedOtherwise);
2830b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2840b57cec5SDimitry Andric       TargetOpcode::G_INSERT, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2850b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2860b57cec5SDimitry Andric       TargetOpcode::G_EXTRACT, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2870b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2880b57cec5SDimitry Andric       TargetOpcode::G_EXTRACT, 1, narrowToSmallerAndUnsupportedIfTooSmall);
2890b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_FNEG, 0, {{1, Lower}});
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric void LegalizerInfo::computeTables() {
2930b57cec5SDimitry Andric   assert(TablesInitialized == false);
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   for (unsigned OpcodeIdx = 0; OpcodeIdx <= LastOp - FirstOp; ++OpcodeIdx) {
2960b57cec5SDimitry Andric     const unsigned Opcode = FirstOp + OpcodeIdx;
2970b57cec5SDimitry Andric     for (unsigned TypeIdx = 0; TypeIdx != SpecifiedActions[OpcodeIdx].size();
2980b57cec5SDimitry Andric          ++TypeIdx) {
2990b57cec5SDimitry Andric       // 0. Collect information specified through the setAction API, i.e.
3000b57cec5SDimitry Andric       // for specific bit sizes.
3010b57cec5SDimitry Andric       // For scalar types:
3020b57cec5SDimitry Andric       SizeAndActionsVec ScalarSpecifiedActions;
3030b57cec5SDimitry Andric       // For pointer types:
3040b57cec5SDimitry Andric       std::map<uint16_t, SizeAndActionsVec> AddressSpace2SpecifiedActions;
3050b57cec5SDimitry Andric       // For vector types:
3060b57cec5SDimitry Andric       std::map<uint16_t, SizeAndActionsVec> ElemSize2SpecifiedActions;
3070b57cec5SDimitry Andric       for (auto LLT2Action : SpecifiedActions[OpcodeIdx][TypeIdx]) {
3080b57cec5SDimitry Andric         const LLT Type = LLT2Action.first;
3090b57cec5SDimitry Andric         const LegalizeAction Action = LLT2Action.second;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric         auto SizeAction = std::make_pair(Type.getSizeInBits(), Action);
3120b57cec5SDimitry Andric         if (Type.isPointer())
3130b57cec5SDimitry Andric           AddressSpace2SpecifiedActions[Type.getAddressSpace()].push_back(
3140b57cec5SDimitry Andric               SizeAction);
3150b57cec5SDimitry Andric         else if (Type.isVector())
3160b57cec5SDimitry Andric           ElemSize2SpecifiedActions[Type.getElementType().getSizeInBits()]
3170b57cec5SDimitry Andric               .push_back(SizeAction);
3180b57cec5SDimitry Andric         else
3190b57cec5SDimitry Andric           ScalarSpecifiedActions.push_back(SizeAction);
3200b57cec5SDimitry Andric       }
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric       // 1. Handle scalar types
3230b57cec5SDimitry Andric       {
3240b57cec5SDimitry Andric         // Decide how to handle bit sizes for which no explicit specification
3250b57cec5SDimitry Andric         // was given.
3260b57cec5SDimitry Andric         SizeChangeStrategy S = &unsupportedForDifferentSizes;
3270b57cec5SDimitry Andric         if (TypeIdx < ScalarSizeChangeStrategies[OpcodeIdx].size() &&
3280b57cec5SDimitry Andric             ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx] != nullptr)
3290b57cec5SDimitry Andric           S = ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx];
3300b57cec5SDimitry Andric         llvm::sort(ScalarSpecifiedActions);
3310b57cec5SDimitry Andric         checkPartialSizeAndActionsVector(ScalarSpecifiedActions);
3320b57cec5SDimitry Andric         setScalarAction(Opcode, TypeIdx, S(ScalarSpecifiedActions));
3330b57cec5SDimitry Andric       }
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric       // 2. Handle pointer types
3360b57cec5SDimitry Andric       for (auto PointerSpecifiedActions : AddressSpace2SpecifiedActions) {
3370b57cec5SDimitry Andric         llvm::sort(PointerSpecifiedActions.second);
3380b57cec5SDimitry Andric         checkPartialSizeAndActionsVector(PointerSpecifiedActions.second);
3390b57cec5SDimitry Andric         // For pointer types, we assume that there isn't a meaningfull way
3400b57cec5SDimitry Andric         // to change the number of bits used in the pointer.
3410b57cec5SDimitry Andric         setPointerAction(
3420b57cec5SDimitry Andric             Opcode, TypeIdx, PointerSpecifiedActions.first,
3430b57cec5SDimitry Andric             unsupportedForDifferentSizes(PointerSpecifiedActions.second));
3440b57cec5SDimitry Andric       }
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric       // 3. Handle vector types
3470b57cec5SDimitry Andric       SizeAndActionsVec ElementSizesSeen;
3480b57cec5SDimitry Andric       for (auto VectorSpecifiedActions : ElemSize2SpecifiedActions) {
3490b57cec5SDimitry Andric         llvm::sort(VectorSpecifiedActions.second);
3500b57cec5SDimitry Andric         const uint16_t ElementSize = VectorSpecifiedActions.first;
3510b57cec5SDimitry Andric         ElementSizesSeen.push_back({ElementSize, Legal});
3520b57cec5SDimitry Andric         checkPartialSizeAndActionsVector(VectorSpecifiedActions.second);
3530b57cec5SDimitry Andric         // For vector types, we assume that the best way to adapt the number
3540b57cec5SDimitry Andric         // of elements is to the next larger number of elements type for which
3550b57cec5SDimitry Andric         // the vector type is legal, unless there is no such type. In that case,
3560b57cec5SDimitry Andric         // legalize towards a vector type with a smaller number of elements.
3570b57cec5SDimitry Andric         SizeAndActionsVec NumElementsActions;
3580b57cec5SDimitry Andric         for (SizeAndAction BitsizeAndAction : VectorSpecifiedActions.second) {
3590b57cec5SDimitry Andric           assert(BitsizeAndAction.first % ElementSize == 0);
3600b57cec5SDimitry Andric           const uint16_t NumElements = BitsizeAndAction.first / ElementSize;
3610b57cec5SDimitry Andric           NumElementsActions.push_back({NumElements, BitsizeAndAction.second});
3620b57cec5SDimitry Andric         }
3630b57cec5SDimitry Andric         setVectorNumElementAction(
3640b57cec5SDimitry Andric             Opcode, TypeIdx, ElementSize,
3650b57cec5SDimitry Andric             moreToWiderTypesAndLessToWidest(NumElementsActions));
3660b57cec5SDimitry Andric       }
3670b57cec5SDimitry Andric       llvm::sort(ElementSizesSeen);
3680b57cec5SDimitry Andric       SizeChangeStrategy VectorElementSizeChangeStrategy =
3690b57cec5SDimitry Andric           &unsupportedForDifferentSizes;
3700b57cec5SDimitry Andric       if (TypeIdx < VectorElementSizeChangeStrategies[OpcodeIdx].size() &&
3710b57cec5SDimitry Andric           VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx] != nullptr)
3720b57cec5SDimitry Andric         VectorElementSizeChangeStrategy =
3730b57cec5SDimitry Andric             VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx];
3740b57cec5SDimitry Andric       setScalarInVectorAction(
3750b57cec5SDimitry Andric           Opcode, TypeIdx, VectorElementSizeChangeStrategy(ElementSizesSeen));
3760b57cec5SDimitry Andric     }
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   TablesInitialized = true;
3800b57cec5SDimitry Andric }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric // FIXME: inefficient implementation for now. Without ComputeValueVTs we're
3830b57cec5SDimitry Andric // probably going to need specialized lookup structures for various types before
3840b57cec5SDimitry Andric // we have any hope of doing well with something like <13 x i3>. Even the common
3850b57cec5SDimitry Andric // cases should do better than what we have now.
3860b57cec5SDimitry Andric std::pair<LegalizeAction, LLT>
3870b57cec5SDimitry Andric LegalizerInfo::getAspectAction(const InstrAspect &Aspect) const {
3880b57cec5SDimitry Andric   assert(TablesInitialized && "backend forgot to call computeTables");
3890b57cec5SDimitry Andric   // These *have* to be implemented for now, they're the fundamental basis of
3900b57cec5SDimitry Andric   // how everything else is transformed.
3910b57cec5SDimitry Andric   if (Aspect.Type.isScalar() || Aspect.Type.isPointer())
3920b57cec5SDimitry Andric     return findScalarLegalAction(Aspect);
3930b57cec5SDimitry Andric   assert(Aspect.Type.isVector());
3940b57cec5SDimitry Andric   return findVectorLegalAction(Aspect);
3950b57cec5SDimitry Andric }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric /// Helper function to get LLT for the given type index.
3980b57cec5SDimitry Andric static LLT getTypeFromTypeIdx(const MachineInstr &MI,
3990b57cec5SDimitry Andric                               const MachineRegisterInfo &MRI, unsigned OpIdx,
4000b57cec5SDimitry Andric                               unsigned TypeIdx) {
4010b57cec5SDimitry Andric   assert(TypeIdx < MI.getNumOperands() && "Unexpected TypeIdx");
4020b57cec5SDimitry Andric   // G_UNMERGE_VALUES has variable number of operands, but there is only
4030b57cec5SDimitry Andric   // one source type and one destination type as all destinations must be the
4040b57cec5SDimitry Andric   // same type. So, get the last operand if TypeIdx == 1.
4050b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && TypeIdx == 1)
4060b57cec5SDimitry Andric     return MRI.getType(MI.getOperand(MI.getNumOperands() - 1).getReg());
4070b57cec5SDimitry Andric   return MRI.getType(MI.getOperand(OpIdx).getReg());
4080b57cec5SDimitry Andric }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric unsigned LegalizerInfo::getOpcodeIdxForOpcode(unsigned Opcode) const {
4110b57cec5SDimitry Andric   assert(Opcode >= FirstOp && Opcode <= LastOp && "Unsupported opcode");
4120b57cec5SDimitry Andric   return Opcode - FirstOp;
4130b57cec5SDimitry Andric }
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric unsigned LegalizerInfo::getActionDefinitionsIdx(unsigned Opcode) const {
4160b57cec5SDimitry Andric   unsigned OpcodeIdx = getOpcodeIdxForOpcode(Opcode);
4170b57cec5SDimitry Andric   if (unsigned Alias = RulesForOpcode[OpcodeIdx].getAlias()) {
4180b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. opcode " << Opcode << " is aliased to " << Alias
4190b57cec5SDimitry Andric                       << "\n");
4200b57cec5SDimitry Andric     OpcodeIdx = getOpcodeIdxForOpcode(Alias);
4210b57cec5SDimitry Andric     assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 && "Cannot chain aliases");
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   return OpcodeIdx;
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric const LegalizeRuleSet &
4280b57cec5SDimitry Andric LegalizerInfo::getActionDefinitions(unsigned Opcode) const {
4290b57cec5SDimitry Andric   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
4300b57cec5SDimitry Andric   return RulesForOpcode[OpcodeIdx];
4310b57cec5SDimitry Andric }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(unsigned Opcode) {
4340b57cec5SDimitry Andric   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
4350b57cec5SDimitry Andric   auto &Result = RulesForOpcode[OpcodeIdx];
4360b57cec5SDimitry Andric   assert(!Result.isAliasedByAnother() && "Modifying this opcode will modify aliases");
4370b57cec5SDimitry Andric   return Result;
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(
4410b57cec5SDimitry Andric     std::initializer_list<unsigned> Opcodes) {
4420b57cec5SDimitry Andric   unsigned Representative = *Opcodes.begin();
4430b57cec5SDimitry Andric 
4448bcb0991SDimitry Andric   assert(!llvm::empty(Opcodes) && Opcodes.begin() + 1 != Opcodes.end() &&
4450b57cec5SDimitry Andric          "Initializer list must have at least two opcodes");
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   for (auto I = Opcodes.begin() + 1, E = Opcodes.end(); I != E; ++I)
4480b57cec5SDimitry Andric     aliasActionDefinitions(Representative, *I);
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   auto &Return = getActionDefinitionsBuilder(Representative);
4510b57cec5SDimitry Andric   Return.setIsAliasedByAnother();
4520b57cec5SDimitry Andric   return Return;
4530b57cec5SDimitry Andric }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric void LegalizerInfo::aliasActionDefinitions(unsigned OpcodeTo,
4560b57cec5SDimitry Andric                                            unsigned OpcodeFrom) {
4570b57cec5SDimitry Andric   assert(OpcodeTo != OpcodeFrom && "Cannot alias to self");
4580b57cec5SDimitry Andric   assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp && "Unsupported opcode");
4590b57cec5SDimitry Andric   const unsigned OpcodeFromIdx = getOpcodeIdxForOpcode(OpcodeFrom);
4600b57cec5SDimitry Andric   RulesForOpcode[OpcodeFromIdx].aliasTo(OpcodeTo);
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric LegalizeActionStep
4640b57cec5SDimitry Andric LegalizerInfo::getAction(const LegalityQuery &Query) const {
4650b57cec5SDimitry Andric   LegalizeActionStep Step = getActionDefinitions(Query.Opcode).apply(Query);
4660b57cec5SDimitry Andric   if (Step.Action != LegalizeAction::UseLegacyRules) {
4670b57cec5SDimitry Andric     return Step;
4680b57cec5SDimitry Andric   }
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   for (unsigned i = 0; i < Query.Types.size(); ++i) {
4710b57cec5SDimitry Andric     auto Action = getAspectAction({Query.Opcode, i, Query.Types[i]});
4720b57cec5SDimitry Andric     if (Action.first != Legal) {
4730b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. (legacy) Type " << i << " Action="
4740b57cec5SDimitry Andric                         << Action.first << ", " << Action.second << "\n");
4750b57cec5SDimitry Andric       return {Action.first, i, Action.second};
4760b57cec5SDimitry Andric     } else
4770b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. (legacy) Type " << i << " Legal\n");
4780b57cec5SDimitry Andric   }
4790b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << ".. (legacy) Legal\n");
4800b57cec5SDimitry Andric   return {Legal, 0, LLT{}};
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric LegalizeActionStep
4840b57cec5SDimitry Andric LegalizerInfo::getAction(const MachineInstr &MI,
4850b57cec5SDimitry Andric                          const MachineRegisterInfo &MRI) const {
4860b57cec5SDimitry Andric   SmallVector<LLT, 2> Types;
4870b57cec5SDimitry Andric   SmallBitVector SeenTypes(8);
4880b57cec5SDimitry Andric   const MCOperandInfo *OpInfo = MI.getDesc().OpInfo;
4890b57cec5SDimitry Andric   // FIXME: probably we'll need to cache the results here somehow?
4900b57cec5SDimitry Andric   for (unsigned i = 0; i < MI.getDesc().getNumOperands(); ++i) {
4910b57cec5SDimitry Andric     if (!OpInfo[i].isGenericType())
4920b57cec5SDimitry Andric       continue;
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric     // We must only record actions once for each TypeIdx; otherwise we'd
4950b57cec5SDimitry Andric     // try to legalize operands multiple times down the line.
4960b57cec5SDimitry Andric     unsigned TypeIdx = OpInfo[i].getGenericTypeIndex();
4970b57cec5SDimitry Andric     if (SeenTypes[TypeIdx])
4980b57cec5SDimitry Andric       continue;
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric     SeenTypes.set(TypeIdx);
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric     LLT Ty = getTypeFromTypeIdx(MI, MRI, i, TypeIdx);
5030b57cec5SDimitry Andric     Types.push_back(Ty);
5040b57cec5SDimitry Andric   }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   SmallVector<LegalityQuery::MemDesc, 2> MemDescrs;
5070b57cec5SDimitry Andric   for (const auto &MMO : MI.memoperands())
5080b57cec5SDimitry Andric     MemDescrs.push_back({8 * MMO->getSize() /* in bits */,
509*5ffd83dbSDimitry Andric                          8 * MMO->getAlign().value(), MMO->getOrdering()});
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   return getAction({MI.getOpcode(), Types, MemDescrs});
5120b57cec5SDimitry Andric }
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric bool LegalizerInfo::isLegal(const MachineInstr &MI,
5150b57cec5SDimitry Andric                             const MachineRegisterInfo &MRI) const {
5160b57cec5SDimitry Andric   return getAction(MI, MRI).Action == Legal;
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric bool LegalizerInfo::isLegalOrCustom(const MachineInstr &MI,
5200b57cec5SDimitry Andric                                     const MachineRegisterInfo &MRI) const {
5210b57cec5SDimitry Andric   auto Action = getAction(MI, MRI).Action;
5220b57cec5SDimitry Andric   // If the action is custom, it may not necessarily modify the instruction,
5230b57cec5SDimitry Andric   // so we have to assume it's legal.
5240b57cec5SDimitry Andric   return Action == Legal || Action == Custom;
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric LegalizerInfo::SizeAndActionsVec
5280b57cec5SDimitry Andric LegalizerInfo::increaseToLargerTypesAndDecreaseToLargest(
5290b57cec5SDimitry Andric     const SizeAndActionsVec &v, LegalizeAction IncreaseAction,
5300b57cec5SDimitry Andric     LegalizeAction DecreaseAction) {
5310b57cec5SDimitry Andric   SizeAndActionsVec result;
5320b57cec5SDimitry Andric   unsigned LargestSizeSoFar = 0;
5330b57cec5SDimitry Andric   if (v.size() >= 1 && v[0].first != 1)
5340b57cec5SDimitry Andric     result.push_back({1, IncreaseAction});
5350b57cec5SDimitry Andric   for (size_t i = 0; i < v.size(); ++i) {
5360b57cec5SDimitry Andric     result.push_back(v[i]);
5370b57cec5SDimitry Andric     LargestSizeSoFar = v[i].first;
5380b57cec5SDimitry Andric     if (i + 1 < v.size() && v[i + 1].first != v[i].first + 1) {
5390b57cec5SDimitry Andric       result.push_back({LargestSizeSoFar + 1, IncreaseAction});
5400b57cec5SDimitry Andric       LargestSizeSoFar = v[i].first + 1;
5410b57cec5SDimitry Andric     }
5420b57cec5SDimitry Andric   }
5430b57cec5SDimitry Andric   result.push_back({LargestSizeSoFar + 1, DecreaseAction});
5440b57cec5SDimitry Andric   return result;
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric LegalizerInfo::SizeAndActionsVec
5480b57cec5SDimitry Andric LegalizerInfo::decreaseToSmallerTypesAndIncreaseToSmallest(
5490b57cec5SDimitry Andric     const SizeAndActionsVec &v, LegalizeAction DecreaseAction,
5500b57cec5SDimitry Andric     LegalizeAction IncreaseAction) {
5510b57cec5SDimitry Andric   SizeAndActionsVec result;
5520b57cec5SDimitry Andric   if (v.size() == 0 || v[0].first != 1)
5530b57cec5SDimitry Andric     result.push_back({1, IncreaseAction});
5540b57cec5SDimitry Andric   for (size_t i = 0; i < v.size(); ++i) {
5550b57cec5SDimitry Andric     result.push_back(v[i]);
5560b57cec5SDimitry Andric     if (i + 1 == v.size() || v[i + 1].first != v[i].first + 1) {
5570b57cec5SDimitry Andric       result.push_back({v[i].first + 1, DecreaseAction});
5580b57cec5SDimitry Andric     }
5590b57cec5SDimitry Andric   }
5600b57cec5SDimitry Andric   return result;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric LegalizerInfo::SizeAndAction
5640b57cec5SDimitry Andric LegalizerInfo::findAction(const SizeAndActionsVec &Vec, const uint32_t Size) {
5650b57cec5SDimitry Andric   assert(Size >= 1);
5660b57cec5SDimitry Andric   // Find the last element in Vec that has a bitsize equal to or smaller than
5670b57cec5SDimitry Andric   // the requested bit size.
5680b57cec5SDimitry Andric   // That is the element just before the first element that is bigger than Size.
5690b57cec5SDimitry Andric   auto It = partition_point(
5700b57cec5SDimitry Andric       Vec, [=](const SizeAndAction &A) { return A.first <= Size; });
5710b57cec5SDimitry Andric   assert(It != Vec.begin() && "Does Vec not start with size 1?");
5720b57cec5SDimitry Andric   int VecIdx = It - Vec.begin() - 1;
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric   LegalizeAction Action = Vec[VecIdx].second;
5750b57cec5SDimitry Andric   switch (Action) {
5760b57cec5SDimitry Andric   case Legal:
577*5ffd83dbSDimitry Andric   case Bitcast:
5780b57cec5SDimitry Andric   case Lower:
5790b57cec5SDimitry Andric   case Libcall:
5800b57cec5SDimitry Andric   case Custom:
5810b57cec5SDimitry Andric     return {Size, Action};
5820b57cec5SDimitry Andric   case FewerElements:
5830b57cec5SDimitry Andric     // FIXME: is this special case still needed and correct?
5840b57cec5SDimitry Andric     // Special case for scalarization:
5850b57cec5SDimitry Andric     if (Vec == SizeAndActionsVec({{1, FewerElements}}))
5860b57cec5SDimitry Andric       return {1, FewerElements};
5870b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
5880b57cec5SDimitry Andric   case NarrowScalar: {
5890b57cec5SDimitry Andric     // The following needs to be a loop, as for now, we do allow needing to
5900b57cec5SDimitry Andric     // go over "Unsupported" bit sizes before finding a legalizable bit size.
5910b57cec5SDimitry Andric     // e.g. (s8, WidenScalar), (s9, Unsupported), (s32, Legal). if Size==8,
5920b57cec5SDimitry Andric     // we need to iterate over s9, and then to s32 to return (s32, Legal).
5930b57cec5SDimitry Andric     // If we want to get rid of the below loop, we should have stronger asserts
5940b57cec5SDimitry Andric     // when building the SizeAndActionsVecs, probably not allowing
5950b57cec5SDimitry Andric     // "Unsupported" unless at the ends of the vector.
5960b57cec5SDimitry Andric     for (int i = VecIdx - 1; i >= 0; --i)
5970b57cec5SDimitry Andric       if (!needsLegalizingToDifferentSize(Vec[i].second) &&
5980b57cec5SDimitry Andric           Vec[i].second != Unsupported)
5990b57cec5SDimitry Andric         return {Vec[i].first, Action};
6000b57cec5SDimitry Andric     llvm_unreachable("");
6010b57cec5SDimitry Andric   }
6020b57cec5SDimitry Andric   case WidenScalar:
6030b57cec5SDimitry Andric   case MoreElements: {
6040b57cec5SDimitry Andric     // See above, the following needs to be a loop, at least for now.
6050b57cec5SDimitry Andric     for (std::size_t i = VecIdx + 1; i < Vec.size(); ++i)
6060b57cec5SDimitry Andric       if (!needsLegalizingToDifferentSize(Vec[i].second) &&
6070b57cec5SDimitry Andric           Vec[i].second != Unsupported)
6080b57cec5SDimitry Andric         return {Vec[i].first, Action};
6090b57cec5SDimitry Andric     llvm_unreachable("");
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric   case Unsupported:
6120b57cec5SDimitry Andric     return {Size, Unsupported};
6130b57cec5SDimitry Andric   case NotFound:
6140b57cec5SDimitry Andric   case UseLegacyRules:
6150b57cec5SDimitry Andric     llvm_unreachable("NotFound");
6160b57cec5SDimitry Andric   }
6170b57cec5SDimitry Andric   llvm_unreachable("Action has an unknown enum value");
6180b57cec5SDimitry Andric }
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric std::pair<LegalizeAction, LLT>
6210b57cec5SDimitry Andric LegalizerInfo::findScalarLegalAction(const InstrAspect &Aspect) const {
6220b57cec5SDimitry Andric   assert(Aspect.Type.isScalar() || Aspect.Type.isPointer());
6230b57cec5SDimitry Andric   if (Aspect.Opcode < FirstOp || Aspect.Opcode > LastOp)
6240b57cec5SDimitry Andric     return {NotFound, LLT()};
6250b57cec5SDimitry Andric   const unsigned OpcodeIdx = getOpcodeIdxForOpcode(Aspect.Opcode);
6260b57cec5SDimitry Andric   if (Aspect.Type.isPointer() &&
6270b57cec5SDimitry Andric       AddrSpace2PointerActions[OpcodeIdx].find(Aspect.Type.getAddressSpace()) ==
6280b57cec5SDimitry Andric           AddrSpace2PointerActions[OpcodeIdx].end()) {
6290b57cec5SDimitry Andric     return {NotFound, LLT()};
6300b57cec5SDimitry Andric   }
6310b57cec5SDimitry Andric   const SmallVector<SizeAndActionsVec, 1> &Actions =
6320b57cec5SDimitry Andric       Aspect.Type.isPointer()
6330b57cec5SDimitry Andric           ? AddrSpace2PointerActions[OpcodeIdx]
6340b57cec5SDimitry Andric                 .find(Aspect.Type.getAddressSpace())
6350b57cec5SDimitry Andric                 ->second
6360b57cec5SDimitry Andric           : ScalarActions[OpcodeIdx];
6370b57cec5SDimitry Andric   if (Aspect.Idx >= Actions.size())
6380b57cec5SDimitry Andric     return {NotFound, LLT()};
6390b57cec5SDimitry Andric   const SizeAndActionsVec &Vec = Actions[Aspect.Idx];
6400b57cec5SDimitry Andric   // FIXME: speed up this search, e.g. by using a results cache for repeated
6410b57cec5SDimitry Andric   // queries?
6420b57cec5SDimitry Andric   auto SizeAndAction = findAction(Vec, Aspect.Type.getSizeInBits());
6430b57cec5SDimitry Andric   return {SizeAndAction.second,
6440b57cec5SDimitry Andric           Aspect.Type.isScalar() ? LLT::scalar(SizeAndAction.first)
6450b57cec5SDimitry Andric                                  : LLT::pointer(Aspect.Type.getAddressSpace(),
6460b57cec5SDimitry Andric                                                 SizeAndAction.first)};
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric std::pair<LegalizeAction, LLT>
6500b57cec5SDimitry Andric LegalizerInfo::findVectorLegalAction(const InstrAspect &Aspect) const {
6510b57cec5SDimitry Andric   assert(Aspect.Type.isVector());
6520b57cec5SDimitry Andric   // First legalize the vector element size, then legalize the number of
6530b57cec5SDimitry Andric   // lanes in the vector.
6540b57cec5SDimitry Andric   if (Aspect.Opcode < FirstOp || Aspect.Opcode > LastOp)
6550b57cec5SDimitry Andric     return {NotFound, Aspect.Type};
6560b57cec5SDimitry Andric   const unsigned OpcodeIdx = getOpcodeIdxForOpcode(Aspect.Opcode);
6570b57cec5SDimitry Andric   const unsigned TypeIdx = Aspect.Idx;
6580b57cec5SDimitry Andric   if (TypeIdx >= ScalarInVectorActions[OpcodeIdx].size())
6590b57cec5SDimitry Andric     return {NotFound, Aspect.Type};
6600b57cec5SDimitry Andric   const SizeAndActionsVec &ElemSizeVec =
6610b57cec5SDimitry Andric       ScalarInVectorActions[OpcodeIdx][TypeIdx];
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric   LLT IntermediateType;
6640b57cec5SDimitry Andric   auto ElementSizeAndAction =
6650b57cec5SDimitry Andric       findAction(ElemSizeVec, Aspect.Type.getScalarSizeInBits());
6660b57cec5SDimitry Andric   IntermediateType =
6670b57cec5SDimitry Andric       LLT::vector(Aspect.Type.getNumElements(), ElementSizeAndAction.first);
6680b57cec5SDimitry Andric   if (ElementSizeAndAction.second != Legal)
6690b57cec5SDimitry Andric     return {ElementSizeAndAction.second, IntermediateType};
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   auto i = NumElements2Actions[OpcodeIdx].find(
6720b57cec5SDimitry Andric       IntermediateType.getScalarSizeInBits());
6730b57cec5SDimitry Andric   if (i == NumElements2Actions[OpcodeIdx].end()) {
6740b57cec5SDimitry Andric     return {NotFound, IntermediateType};
6750b57cec5SDimitry Andric   }
6760b57cec5SDimitry Andric   const SizeAndActionsVec &NumElementsVec = (*i).second[TypeIdx];
6770b57cec5SDimitry Andric   auto NumElementsAndAction =
6780b57cec5SDimitry Andric       findAction(NumElementsVec, IntermediateType.getNumElements());
6790b57cec5SDimitry Andric   return {NumElementsAndAction.second,
6800b57cec5SDimitry Andric           LLT::vector(NumElementsAndAction.first,
6810b57cec5SDimitry Andric                       IntermediateType.getScalarSizeInBits())};
6820b57cec5SDimitry Andric }
6830b57cec5SDimitry Andric 
684480093f4SDimitry Andric unsigned LegalizerInfo::getExtOpcodeForWideningConstant(LLT SmallTy) const {
685480093f4SDimitry Andric   return SmallTy.isByteSized() ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
686480093f4SDimitry Andric }
687480093f4SDimitry Andric 
6880b57cec5SDimitry Andric /// \pre Type indices of every opcode form a dense set starting from 0.
6890b57cec5SDimitry Andric void LegalizerInfo::verify(const MCInstrInfo &MII) const {
6900b57cec5SDimitry Andric #ifndef NDEBUG
6910b57cec5SDimitry Andric   std::vector<unsigned> FailedOpcodes;
6920b57cec5SDimitry Andric   for (unsigned Opcode = FirstOp; Opcode <= LastOp; ++Opcode) {
6930b57cec5SDimitry Andric     const MCInstrDesc &MCID = MII.get(Opcode);
6940b57cec5SDimitry Andric     const unsigned NumTypeIdxs = std::accumulate(
6950b57cec5SDimitry Andric         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
6960b57cec5SDimitry Andric         [](unsigned Acc, const MCOperandInfo &OpInfo) {
6970b57cec5SDimitry Andric           return OpInfo.isGenericType()
6980b57cec5SDimitry Andric                      ? std::max(OpInfo.getGenericTypeIndex() + 1U, Acc)
6990b57cec5SDimitry Andric                      : Acc;
7000b57cec5SDimitry Andric         });
7018bcb0991SDimitry Andric     const unsigned NumImmIdxs = std::accumulate(
7028bcb0991SDimitry Andric         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
7038bcb0991SDimitry Andric         [](unsigned Acc, const MCOperandInfo &OpInfo) {
7048bcb0991SDimitry Andric           return OpInfo.isGenericImm()
7058bcb0991SDimitry Andric                      ? std::max(OpInfo.getGenericImmIndex() + 1U, Acc)
7068bcb0991SDimitry Andric                      : Acc;
7078bcb0991SDimitry Andric         });
7080b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << MII.getName(Opcode) << " (opcode " << Opcode
7090b57cec5SDimitry Andric                       << "): " << NumTypeIdxs << " type ind"
7108bcb0991SDimitry Andric                       << (NumTypeIdxs == 1 ? "ex" : "ices") << ", "
7118bcb0991SDimitry Andric                       << NumImmIdxs << " imm ind"
7128bcb0991SDimitry Andric                       << (NumImmIdxs == 1 ? "ex" : "ices") << "\n");
7130b57cec5SDimitry Andric     const LegalizeRuleSet &RuleSet = getActionDefinitions(Opcode);
7140b57cec5SDimitry Andric     if (!RuleSet.verifyTypeIdxsCoverage(NumTypeIdxs))
7150b57cec5SDimitry Andric       FailedOpcodes.push_back(Opcode);
7168bcb0991SDimitry Andric     else if (!RuleSet.verifyImmIdxsCoverage(NumImmIdxs))
7178bcb0991SDimitry Andric       FailedOpcodes.push_back(Opcode);
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric   if (!FailedOpcodes.empty()) {
7200b57cec5SDimitry Andric     errs() << "The following opcodes have ill-defined legalization rules:";
7210b57cec5SDimitry Andric     for (unsigned Opcode : FailedOpcodes)
7220b57cec5SDimitry Andric       errs() << " " << MII.getName(Opcode);
7230b57cec5SDimitry Andric     errs() << "\n";
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric     report_fatal_error("ill-defined LegalizerInfo"
7260b57cec5SDimitry Andric                        ", try -debug-only=legalizer-info for details");
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric #endif
7290b57cec5SDimitry Andric }
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric #ifndef NDEBUG
7320b57cec5SDimitry Andric // FIXME: This should be in the MachineVerifier, but it can't use the
7330b57cec5SDimitry Andric // LegalizerInfo as it's currently in the separate GlobalISel library.
7340b57cec5SDimitry Andric // Note that RegBankSelected property already checked in the verifier
7350b57cec5SDimitry Andric // has the same layering problem, but we only use inline methods so
7360b57cec5SDimitry Andric // end up not needing to link against the GlobalISel library.
7370b57cec5SDimitry Andric const MachineInstr *llvm::machineFunctionIsIllegal(const MachineFunction &MF) {
7380b57cec5SDimitry Andric   if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) {
7390b57cec5SDimitry Andric     const MachineRegisterInfo &MRI = MF.getRegInfo();
7400b57cec5SDimitry Andric     for (const MachineBasicBlock &MBB : MF)
7410b57cec5SDimitry Andric       for (const MachineInstr &MI : MBB)
7420b57cec5SDimitry Andric         if (isPreISelGenericOpcode(MI.getOpcode()) &&
7430b57cec5SDimitry Andric             !MLI->isLegalOrCustom(MI, MRI))
7440b57cec5SDimitry Andric           return &MI;
7450b57cec5SDimitry Andric   }
7460b57cec5SDimitry Andric   return nullptr;
7470b57cec5SDimitry Andric }
7480b57cec5SDimitry Andric #endif
749