LLVM 22.0.0git
InstructionSelect.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==//
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/// \file
9/// This file implements the InstructionSelect class.
10//===----------------------------------------------------------------------===//
11
14#include "llvm/ADT/ScopeExit.h"
15#include "llvm/ADT/SetVector.h"
30#include "llvm/Config/config.h"
31#include "llvm/IR/Function.h"
34#include "llvm/Support/Debug.h"
37
38#define DEBUG_TYPE "instruction-select"
39
40using namespace llvm;
41
42DEBUG_COUNTER(GlobalISelCounter, "globalisel",
43 "Controls whether to select function with GlobalISel");
44
45#ifdef LLVM_GISEL_COV_PREFIX
47 CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
48 cl::desc("Record GlobalISel rule coverage files of this "
49 "prefix if instrumentation was generated"));
50#else
51static const std::string CoveragePrefix;
52#endif
53
56 "Select target instructions out of generic instructions",
57 false, false)
63 "Select target instructions out of generic instructions",
65
68
69/// This class observes instruction insertions/removals.
70/// InstructionSelect stores an iterator of the instruction prior to the one
71/// that is currently being selected to determine which instruction to select
72/// next. Previously this meant that selecting multiple instructions at once was
73/// illegal behavior due to potential invalidation of this iterator. This is
74/// a non-obvious limitation for selector implementers. Therefore, to allow
75/// deletion of arbitrary instructions, we detect this case and continue
76/// selection with the predecessor of the deleted instruction.
78#ifndef NDEBUG
80#endif
81public:
83
84 void changingInstr(MachineInstr &MI) override {
85 llvm_unreachable("InstructionSelect does not track changed instructions!");
86 }
87 void changedInstr(MachineInstr &MI) override {
88 llvm_unreachable("InstructionSelect does not track changed instructions!");
89 }
90
91 void createdInstr(MachineInstr &MI) override {
92 LLVM_DEBUG(dbgs() << "Creating: " << MI; CreatedInstrs.insert(&MI));
93 }
94
95 void erasingInstr(MachineInstr &MI) override {
96 LLVM_DEBUG(dbgs() << "Erasing: " << MI; CreatedInstrs.remove(&MI));
97 if (MII.getInstrIterator().getNodePtr() == &MI) {
98 // If the iterator points to the MI that will be erased (i.e. the MI prior
99 // to the MI that is currently being selected), the iterator would be
100 // invalidated. Continue selection with its predecessor.
101 ++MII;
102 LLVM_DEBUG(dbgs() << "Instruction removal updated iterator.\n");
103 }
104 }
105
107 LLVM_DEBUG({
108 if (CreatedInstrs.empty()) {
109 dbgs() << "Created no instructions.\n";
110 } else {
111 dbgs() << "Created:\n";
112 for (const auto *MI : CreatedInstrs) {
113 dbgs() << " " << *MI;
114 }
115 CreatedInstrs.clear();
116 }
117 });
118 }
119};
120
133
135 // If the ISel pipeline failed, do not bother running that pass.
136 if (MF.getProperties().hasFailedISel())
137 return false;
138
140
141 // FIXME: Properly override OptLevel in TargetMachine. See OptLevelChanger
142 CodeGenOptLevel OldOptLevel = OptLevel;
143 auto RestoreOptLevel = make_scope_exit([=]() { OptLevel = OldOptLevel; });
145 : MF.getTarget().getOptLevel();
146
150 if (PSI && PSI->hasProfileSummary())
152 }
153
154 return selectMachineFunction(MF);
155}
156
158 LLVM_DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
159 assert(ISel && "Cannot work without InstructionSelector");
160
161 CodeGenCoverage CoverageInfo;
162 ISel->setupMF(MF, VT, &CoverageInfo, PSI, BFI);
163
164 // An optimization remark emitter. Used to report failures.
165 MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
166 ISel->MORE = &MORE;
167
168 // FIXME: There are many other MF/MFI fields we need to initialize.
169
171#ifndef NDEBUG
172 // Check that our input is fully legal: we require the function to have the
173 // Legalized property, so it should be.
174 // FIXME: This should be in the MachineVerifier, as the RegBankSelected
175 // property check already is.
177 if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
178 reportGISelFailure(MF, MORE, "gisel-select", "instruction is not legal",
179 *MI);
180 return false;
181 }
182 // FIXME: We could introduce new blocks and will need to fix the outer loop.
183 // Until then, keep track of the number of blocks to assert that we don't.
184 const size_t NumBlocks = MF.size();
185#endif
186 // Keep track of selected blocks, so we can delete unreachable ones later.
187 DenseSet<MachineBasicBlock *> SelectedBlocks;
188
189 {
190 // Observe IR insertions and removals during selection.
191 // We only install a MachineFunction::Delegate instead of a
192 // GISelChangeObserver, because we do not want notifications about changed
193 // instructions. This prevents significant compile-time regressions from
194 // e.g. constrainOperandRegClass().
195 GISelObserverWrapper AllObservers;
196 MIIteratorMaintainer MIIMaintainer;
197 AllObservers.addObserver(&MIIMaintainer);
198 RAIIDelegateInstaller DelInstaller(MF, &AllObservers);
199 ISel->AllObservers = &AllObservers;
200
201 for (MachineBasicBlock *MBB : post_order(&MF)) {
202 ISel->CurMBB = MBB;
203 SelectedBlocks.insert(MBB);
204
205 // Select instructions in reverse block order.
206 MIIMaintainer.MII = MBB->rbegin();
207 for (auto End = MBB->rend(); MIIMaintainer.MII != End;) {
208 MachineInstr &MI = *MIIMaintainer.MII;
209 // Increment early to skip instructions inserted by select().
210 ++MIIMaintainer.MII;
211
212 LLVM_DEBUG(dbgs() << "\nSelect: " << MI);
213 if (!selectInstr(MI)) {
214 LLVM_DEBUG(dbgs() << "Selection failed!\n";
215 MIIMaintainer.reportFullyCreatedInstrs());
216 reportGISelFailure(MF, MORE, "gisel-select", "cannot select", MI);
217 return false;
218 }
219 LLVM_DEBUG(MIIMaintainer.reportFullyCreatedInstrs());
220 }
221 }
222 }
223
224 for (MachineBasicBlock &MBB : MF) {
225 if (MBB.empty())
226 continue;
227
228 if (!SelectedBlocks.contains(&MBB)) {
229 // This is an unreachable block and therefore hasn't been selected, since
230 // the main selection loop above uses a postorder block traversal.
231 // We delete all the instructions in this block since it's unreachable.
232 MBB.clear();
233 // Don't delete the block in case the block has it's address taken or is
234 // still being referenced by a phi somewhere.
235 continue;
236 }
237 // Try to find redundant copies b/w vregs of the same register class.
238 for (auto MII = MBB.rbegin(), End = MBB.rend(); MII != End;) {
239 MachineInstr &MI = *MII;
240 ++MII;
241
242 if (MI.getOpcode() != TargetOpcode::COPY)
243 continue;
244 Register SrcReg = MI.getOperand(1).getReg();
245 Register DstReg = MI.getOperand(0).getReg();
246 if (SrcReg.isVirtual() && DstReg.isVirtual()) {
247 auto SrcRC = MRI.getRegClass(SrcReg);
248 auto DstRC = MRI.getRegClass(DstReg);
249 if (SrcRC == DstRC) {
250 MRI.replaceRegWith(DstReg, SrcReg);
251 MI.eraseFromParent();
252 }
253 }
254 }
255 }
256
257#ifndef NDEBUG
259 // Now that selection is complete, there are no more generic vregs. Verify
260 // that the size of the now-constrained vreg is unchanged and that it has a
261 // register class.
262 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
264
265 MachineInstr *MI = nullptr;
266 if (!MRI.def_empty(VReg))
267 MI = &*MRI.def_instr_begin(VReg);
268 else if (!MRI.use_empty(VReg)) {
269 MI = &*MRI.use_instr_begin(VReg);
270 // Debug value instruction is permitted to use undefined vregs.
271 if (MI->isDebugValue())
272 continue;
273 }
274 if (!MI)
275 continue;
276
277 const TargetRegisterClass *RC = MRI.getRegClassOrNull(VReg);
278 if (!RC) {
279 reportGISelFailure(MF, MORE, "gisel-select",
280 "VReg has no regclass after selection", *MI);
281 return false;
282 }
283
284 const LLT Ty = MRI.getType(VReg);
285 if (Ty.isValid() &&
286 TypeSize::isKnownGT(Ty.getSizeInBits(), TRI.getRegSizeInBits(*RC))) {
288 MF, MORE, "gisel-select",
289 "VReg's low-level type and register class have different sizes", *MI);
290 return false;
291 }
292 }
293
294 if (MF.size() != NumBlocks) {
295 MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
297 /*MBB=*/nullptr);
298 R << "inserting blocks is not supported yet";
299 reportGISelFailure(MF, MORE, R);
300 return false;
301 }
302#endif
303
304 if (!DebugCounter::shouldExecute(GlobalISelCounter)) {
305 dbgs() << "Falling back for function " << MF.getName() << "\n";
306 MF.getProperties().setFailedISel();
307 return false;
308 }
309
310 // Determine if there are any calls in this machine function. Ported from
311 // SelectionDAG.
312 MachineFrameInfo &MFI = MF.getFrameInfo();
313 for (const auto &MBB : MF) {
314 if (MFI.hasCalls() && MF.hasInlineAsm())
315 break;
316
317 for (const auto &MI : MBB) {
318 if ((MI.isCall() && !MI.isReturn()) || MI.isStackAligningInlineAsm())
319 MFI.setHasCalls(true);
320 if (MI.isInlineAsm())
321 MF.setHasInlineAsm(true);
322 }
323 }
324
325 // FIXME: FinalizeISel pass calls finalizeLowering, so it's called twice.
326 auto &TLI = *MF.getSubtarget().getTargetLowering();
327 TLI.finalizeLowering(MF);
328
329 LLVM_DEBUG({
330 dbgs() << "Rules covered by selecting function: " << MF.getName() << ":";
331 for (auto RuleID : CoverageInfo.covered())
332 dbgs() << " id" << RuleID;
333 dbgs() << "\n\n";
334 });
335 CoverageInfo.emit(CoveragePrefix,
336 TLI.getTargetMachine().getTarget().getBackendName());
337
338 // If we successfully selected the function nothing is going to use the vreg
339 // types after us (otherwise MIRPrinter would need them). Make sure the types
340 // disappear.
341 MRI.clearVirtRegTypes();
342
343 // FIXME: Should we accurately track changes?
344 return true;
345}
346
348 MachineRegisterInfo &MRI = ISel->MF->getRegInfo();
349
350 // We could have folded this instruction away already, making it dead.
351 // If so, erase it.
352 if (isTriviallyDead(MI, MRI)) {
353 LLVM_DEBUG(dbgs() << "Is dead.\n");
355 MI.eraseFromParent();
356 return true;
357 }
358
359 // Eliminate hints or G_CONSTANT_FOLD_BARRIER.
360 if (isPreISelGenericOptimizationHint(MI.getOpcode()) ||
361 MI.getOpcode() == TargetOpcode::G_CONSTANT_FOLD_BARRIER) {
362 auto [DstReg, SrcReg] = MI.getFirst2Regs();
363
364 // At this point, the destination register class of the op may have
365 // been decided.
366 //
367 // Propagate that through to the source register.
368 const TargetRegisterClass *DstRC = MRI.getRegClassOrNull(DstReg);
369 if (DstRC)
370 MRI.setRegClass(SrcReg, DstRC);
371 assert(canReplaceReg(DstReg, SrcReg, MRI) &&
372 "Must be able to replace dst with src!");
373 MI.eraseFromParent();
374 MRI.replaceRegWith(DstReg, SrcReg);
375 return true;
376 }
377
378 if (MI.getOpcode() == TargetOpcode::G_INVOKE_REGION_START) {
379 MI.eraseFromParent();
380 return true;
381 }
382
383 return ISel->select(MI);
384}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This contains common code to allow clients to notify changes to machine instr.
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
static const std::string CoveragePrefix
Interface for Targets to specify which operations they can successfully select and how the others sho...
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file implements a set that has insertion order iteration characteristics.
#define LLVM_DEBUG(...)
Definition Debug.h:114
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This class observes instruction insertions/removals.
MachineBasicBlock::reverse_iterator MII
void erasingInstr(MachineInstr &MI) override
An instruction is about to be erased.
void changedInstr(MachineInstr &MI) override
This instruction was mutated in some way.
void changingInstr(MachineInstr &MI) override
This instruction is about to be mutated in some way.
void createdInstr(MachineInstr &MI) override
An instruction has been created and inserted into the function.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
iterator_range< const_covered_iterator > covered() const
bool emit(StringRef FilePrefix, StringRef BackendName) const
static bool shouldExecute(CounterInfo &Counter)
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:700
Abstract class that contains various methods for clients to notify about changes.
Simple wrapper observer that takes several observers, and calls each one for each event.
void addObserver(GISelChangeObserver *O)
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelValueTrackingInfoAnal...
This pass is responsible for selecting generic machine instructions to target-specific instructions.
InstructionSelector * ISel
bool selectMachineFunction(MachineFunction &MF)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
InstructionSelect(CodeGenOptLevel OL=CodeGenOptLevel::Default, char &PassID=ID)
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
ProfileSummaryInfo * PSI
bool selectInstr(MachineInstr &MI)
BlockFrequencyInfo * BFI
GISelValueTracking * VT
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasCalls() const
Return true if the current function has any function calls.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void setHasInlineAsm(bool B)
Set a flag that indicates that the function contains inline assembly.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
unsigned size() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
Diagnostic information for missed-optimization remarks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
A simple RAII based Delegate installer.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
virtual void finalizeLowering(MachineFunction &MF) const
Execute target specific actions to finalize target lowering.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual InstructionSelector * getInstructionSelector() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:223
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1729
iterator_range< po_iterator< T > > post_order(const T &G)
bool isPreISelGenericOptimizationHint(unsigned Opcode)
LLVM_ABI cl::opt< bool > DisableGISelLegalityCheck
LLVM_ABI bool canReplaceReg(Register DstReg, Register SrcReg, MachineRegisterInfo &MRI)
Check if DstReg can be replaced with SrcReg depending on the register constraints.
Definition Utils.cpp:201
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void reportGISelFailure(MachineFunction &MF, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext's diagnostic stream.
Definition Utils.cpp:259
const MachineInstr * machineFunctionIsIllegal(const MachineFunction &MF)
Checks that MIR is fully legal, returns an illegal instruction if it's not, nullptr otherwise.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1189
LLVM_ABI bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn't have oth...
Definition Utils.cpp:222
#define MORE()
Definition regcomp.c:246