1 //===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements the InstructionSelect class.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
14 #include "llvm/ADT/PostOrderIterator.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
18 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
19 #include "llvm/CodeGen/GlobalISel/Utils.h"
20 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/TargetRegistry.h"
31 
32 #define DEBUG_TYPE "instruction-select"
33 
34 using namespace llvm;
35 
36 #ifdef LLVM_GISEL_COV_PREFIX
37 static cl::opt<std::string>
38     CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
39                    cl::desc("Record GlobalISel rule coverage files of this "
40                             "prefix if instrumentation was generated"));
41 #else
42 static const std::string CoveragePrefix = "";
43 #endif
44 
45 char InstructionSelect::ID = 0;
46 INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE,
47                       "Select target instructions out of generic instructions",
48                       false, false)
49 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
50 INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE,
51                     "Select target instructions out of generic instructions",
52                     false, false)
53 
54 InstructionSelect::InstructionSelect() : MachineFunctionPass(ID) {
55   initializeInstructionSelectPass(*PassRegistry::getPassRegistry());
56 }
57 
58 void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const {
59   AU.addRequired<TargetPassConfig>();
60   MachineFunctionPass::getAnalysisUsage(AU);
61 }
62 
63 bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) {
64   const MachineRegisterInfo &MRI = MF.getRegInfo();
65 
66   // No matter what happens, whether we successfully select the function or not,
67   // nothing is going to use the vreg types after us.  Make sure they disappear.
68   auto ClearVRegTypesOnReturn =
69       make_scope_exit([&]() { MRI.getVRegToType().clear(); });
70 
71   // If the ISel pipeline failed, do not bother running that pass.
72   if (MF.getProperties().hasProperty(
73           MachineFunctionProperties::Property::FailedISel))
74     return false;
75 
76   DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
77 
78   const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
79   const InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector();
80   CodeGenCoverage CoverageInfo;
81   assert(ISel && "Cannot work without InstructionSelector");
82 
83   // An optimization remark emitter. Used to report failures.
84   MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
85 
86   // FIXME: There are many other MF/MFI fields we need to initialize.
87 
88 #ifndef NDEBUG
89   // Check that our input is fully legal: we require the function to have the
90   // Legalized property, so it should be.
91   // FIXME: This should be in the MachineVerifier, but it can't use the
92   // LegalizerInfo as it's currently in the separate GlobalISel library.
93   // The RegBankSelected property is already checked in the verifier. Note
94   // that it has the same layering problem, but we only use inline methods so
95   // end up not needing to link against the GlobalISel library.
96   if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo())
97     for (MachineBasicBlock &MBB : MF)
98       for (MachineInstr &MI : MBB)
99         if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) {
100           reportGISelFailure(MF, TPC, MORE, "gisel-select",
101                              "instruction is not legal", MI);
102           return false;
103         }
104 
105 #endif
106   // FIXME: We could introduce new blocks and will need to fix the outer loop.
107   // Until then, keep track of the number of blocks to assert that we don't.
108   const size_t NumBlocks = MF.size();
109 
110   for (MachineBasicBlock *MBB : post_order(&MF)) {
111     if (MBB->empty())
112       continue;
113 
114     // Select instructions in reverse block order. We permit erasing so have
115     // to resort to manually iterating and recognizing the begin (rend) case.
116     bool ReachedBegin = false;
117     for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
118          !ReachedBegin;) {
119 #ifndef NDEBUG
120       // Keep track of the insertion range for debug printing.
121       const auto AfterIt = std::next(MII);
122 #endif
123       // Select this instruction.
124       MachineInstr &MI = *MII;
125 
126       // And have our iterator point to the next instruction, if there is one.
127       if (MII == Begin)
128         ReachedBegin = true;
129       else
130         --MII;
131 
132       DEBUG(dbgs() << "Selecting: \n  " << MI);
133 
134       // We could have folded this instruction away already, making it dead.
135       // If so, erase it.
136       if (isTriviallyDead(MI, MRI)) {
137         DEBUG(dbgs() << "Is dead; erasing.\n");
138         MI.eraseFromParentAndMarkDBGValuesForRemoval();
139         continue;
140       }
141 
142       if (!ISel->select(MI, CoverageInfo)) {
143         // FIXME: It would be nice to dump all inserted instructions.  It's
144         // not obvious how, esp. considering select() can insert after MI.
145         reportGISelFailure(MF, TPC, MORE, "gisel-select", "cannot select", MI);
146         return false;
147       }
148 
149       // Dump the range of instructions that MI expanded into.
150       DEBUG({
151         auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII);
152         dbgs() << "Into:\n";
153         for (auto &InsertedMI : make_range(InsertedBegin, AfterIt))
154           dbgs() << "  " << InsertedMI;
155         dbgs() << '\n';
156       });
157     }
158   }
159 
160   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
161 
162   for (MachineBasicBlock &MBB : MF) {
163     if (MBB.empty())
164       continue;
165 
166     // Try to find redundant copies b/w vregs of the same register class.
167     bool ReachedBegin = false;
168     for (auto MII = std::prev(MBB.end()), Begin = MBB.begin(); !ReachedBegin;) {
169       // Select this instruction.
170       MachineInstr &MI = *MII;
171 
172       // And have our iterator point to the next instruction, if there is one.
173       if (MII == Begin)
174         ReachedBegin = true;
175       else
176         --MII;
177       if (MI.getOpcode() != TargetOpcode::COPY)
178         continue;
179       unsigned SrcReg = MI.getOperand(1).getReg();
180       unsigned DstReg = MI.getOperand(0).getReg();
181       if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
182           TargetRegisterInfo::isVirtualRegister(DstReg)) {
183         MachineRegisterInfo &MRI = MF.getRegInfo();
184         auto SrcRC = MRI.getRegClass(SrcReg);
185         auto DstRC = MRI.getRegClass(DstReg);
186         if (SrcRC == DstRC) {
187           MRI.replaceRegWith(DstReg, SrcReg);
188           MI.eraseFromParentAndMarkDBGValuesForRemoval();
189         }
190       }
191     }
192   }
193 
194   // Now that selection is complete, there are no more generic vregs.  Verify
195   // that the size of the now-constrained vreg is unchanged and that it has a
196   // register class.
197   for (auto &VRegToType : MRI.getVRegToType()) {
198     unsigned VReg = VRegToType.first;
199     auto *RC = MRI.getRegClassOrNull(VReg);
200     MachineInstr *MI = nullptr;
201     if (!MRI.def_empty(VReg))
202       MI = &*MRI.def_instr_begin(VReg);
203     else if (!MRI.use_empty(VReg))
204       MI = &*MRI.use_instr_begin(VReg);
205 
206     if (MI && !RC) {
207       reportGISelFailure(MF, TPC, MORE, "gisel-select",
208                          "VReg has no regclass after selection", *MI);
209       return false;
210     } else if (!RC)
211       continue;
212 
213     if (VRegToType.second.isValid() &&
214         VRegToType.second.getSizeInBits() > TRI.getRegSizeInBits(*RC)) {
215       reportGISelFailure(MF, TPC, MORE, "gisel-select",
216                          "VReg has explicit size different from class size",
217                          *MI);
218       return false;
219     }
220   }
221 
222   if (MF.size() != NumBlocks) {
223     MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
224                                       MF.getFunction().getSubprogram(),
225                                       /*MBB=*/nullptr);
226     R << "inserting blocks is not supported yet";
227     reportGISelFailure(MF, TPC, MORE, R);
228     return false;
229   }
230 
231   auto &TLI = *MF.getSubtarget().getTargetLowering();
232   TLI.finalizeLowering(MF);
233 
234   CoverageInfo.emit(CoveragePrefix,
235                     MF.getSubtarget()
236                         .getTargetLowering()
237                         ->getTargetMachine()
238                         .getTarget()
239                         .getBackendName());
240 
241   // FIXME: Should we accurately track changes?
242   return true;
243 }
244