LLVM 24.0.0git
BreakFalseDeps.cpp
Go to the documentation of this file.
1//==- llvm/CodeGen/BreakFalseDeps.cpp - Break False Dependency Fix -*- C++ -*==//
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/// \file Break False Dependency pass.
10///
11/// Some instructions have false dependencies which cause unnecessary stalls.
12/// For example, instructions may write part of a register and implicitly
13/// need to read the other parts of the register. This may cause unwanted
14/// stalls preventing otherwise unrelated instructions from executing in
15/// parallel in an out-of-order CPU.
16/// This pass is aimed at identifying and avoiding these dependencies.
17//
18//===----------------------------------------------------------------------===//
19
28#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCRegister.h"
31#include "llvm/Support/Debug.h"
32
33using namespace llvm;
34
35namespace {
36
37class BreakFalseDeps {
38private:
39 MachineFunction *MF = nullptr;
40 const TargetInstrInfo *TII = nullptr;
41 const TargetRegisterInfo *TRI = nullptr;
42 RegisterClassInfo RegClassInfo;
43
44 /// List of undefined register reads in this block in forward order.
45 std::vector<std::pair<MachineInstr *, unsigned>> UndefReads;
46
47 /// Storage for register unit liveness.
48 LivePhysRegs LiveRegSet;
49
50 function_ref<ReachingDefInfo &()> GetRDI;
51 ReachingDefInfo *RDI = nullptr;
52
53 /// True if the pass insert instructions or updates registers, false
54 /// otherwise.
55 bool Changed = false;
56
57public:
58 BreakFalseDeps(function_ref<ReachingDefInfo &()> GetRDI) : GetRDI(GetRDI) {}
59
60 bool run(MachineFunction &CurMF);
61
62private:
63 ReachingDefInfo &getRDI() {
64 if (!RDI)
65 RDI = &GetRDI();
66 return *RDI;
67 }
68
69 /// Process he given basic block.
70 void processBasicBlock(MachineBasicBlock *MBB);
71
72 /// Update def-ages for registers defined by MI.
73 /// Also break dependencies on partial defs and undef uses.
74 void processDefs(MachineInstr *MI);
75
76 /// Helps avoid false dependencies on undef registers by updating the
77 /// machine instructions' undef operand to use a register that the instruction
78 /// is truly dependent on, or use a register with clearance higher than Pref.
79 /// Returns true if it was able to find a true dependency, thus not requiring
80 /// a dependency breaking instruction regardless of clearance.
81 bool pickBestRegisterForUndef(MachineInstr *MI, unsigned OpIdx,
82 unsigned Pref);
83
84 /// Return true to if it makes sense to break dependence on a partial
85 /// def or undef use.
86 bool shouldBreakDependence(MachineInstr *, unsigned OpIdx, unsigned Pref);
87
88 /// Break false dependencies on undefined register reads.
89 /// Walk the block backward computing precise liveness. This is expensive, so
90 /// we only do it on demand. Note that the occurrence of undefined register
91 /// reads that should be broken is very rare, but when they occur we may have
92 /// many in a single block.
93 void processUndefReads(MachineBasicBlock *);
94};
95
96class BreakFalseDepsLegacy : public MachineFunctionPass {
97public:
98 static char ID; // Pass identification, replacement for typeid
99
100 BreakFalseDepsLegacy() : MachineFunctionPass(ID) {}
101
102 void getAnalysisUsage(AnalysisUsage &AU) const override {
103 AU.setPreservesCFG();
104 AU.addRequired<ReachingDefInfoWrapperPass>();
106 }
107
108 bool runOnMachineFunction(MachineFunction &MF) override;
109
110 MachineFunctionProperties getRequiredProperties() const override {
111 return MachineFunctionProperties().setNoVRegs();
112 }
113};
114
115} // namespace
116
117#define DEBUG_TYPE "break-false-deps"
118
119char BreakFalseDepsLegacy::ID = 0;
120INITIALIZE_PASS_BEGIN(BreakFalseDepsLegacy, DEBUG_TYPE, "BreakFalseDeps", false,
121 false)
123INITIALIZE_PASS_END(BreakFalseDepsLegacy, DEBUG_TYPE, "BreakFalseDeps", false,
124 false)
125
127 return new BreakFalseDepsLegacy();
128}
129
130bool BreakFalseDeps::pickBestRegisterForUndef(MachineInstr *MI, unsigned OpIdx,
131 unsigned Pref) {
132
133 // We can't change tied operands.
134 if (MI->isRegTiedToDefOperand(OpIdx))
135 return false;
136
137 MachineOperand &MO = MI->getOperand(OpIdx);
138 assert(MO.isUndef() && "Expected undef machine operand");
139
140 // We can't change registers that aren't renamable.
141 if (!MO.isRenamable())
142 return false;
143
144 MCRegister OriginalReg = MO.getReg().asMCReg();
145
146 // Update only undef operands that have reg units that are mapped to one root.
147 for (MCRegUnit Unit : TRI->regunits(OriginalReg)) {
148 unsigned NumRoots = 0;
149 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
150 NumRoots++;
151 if (NumRoots > 1)
152 return false;
153 }
154 }
155
156 // Get the undef operand's register class
157 const TargetRegisterClass *OpRC = TII->getRegClass(MI->getDesc(), OpIdx);
158 assert(OpRC && "Not a valid register class");
159
160 // If the instruction has a true dependency, we can hide the false depdency
161 // behind it.
162 for (MachineOperand &CurrMO : MI->all_uses()) {
163 if (CurrMO.isUndef() || !OpRC->contains(CurrMO.getReg()))
164 continue;
165 // We found a true dependency - replace the undef register with the true
166 // dependency.
167 MO.setReg(CurrMO.getReg());
168 Changed = true;
169 return true;
170 }
171
172 // Go over all registers in the register class and find the register with
173 // max clearance or clearance higher than Pref.
174 unsigned MaxClearance = 0;
175 MCRegister MaxClearanceReg = OriginalReg;
176 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(OpRC);
177 for (MCPhysReg Reg : Order) {
178 unsigned Clearance = getRDI().getClearance(MI, Reg);
179 if (Clearance <= MaxClearance)
180 continue;
181 MaxClearance = Clearance;
182 MaxClearanceReg = Reg;
183
184 if (MaxClearance > Pref)
185 break;
186 }
187
188 // Update the operand if we found a register with better clearance.
189 if (MaxClearanceReg != OriginalReg) {
190 MO.setReg(MaxClearanceReg);
191 Changed = true;
192 }
193
194 return false;
195}
196
197bool BreakFalseDeps::shouldBreakDependence(MachineInstr *MI, unsigned OpIdx,
198 unsigned Pref) {
199 MCRegister Reg = MI->getOperand(OpIdx).getReg().asMCReg();
200 unsigned Clearance = getRDI().getClearance(MI, Reg);
201 LLVM_DEBUG(dbgs() << "Clearance: " << Clearance << ", want " << Pref);
202
203 if (Pref > Clearance) {
204 LLVM_DEBUG(dbgs() << ": Break dependency.\n");
205 return true;
206 }
207 LLVM_DEBUG(dbgs() << ": OK .\n");
208 return false;
209}
210
211void BreakFalseDeps::processDefs(MachineInstr *MI) {
212 assert(!MI->isDebugInstr() && "Won't process debug values");
213
214 const MCInstrDesc &MCID = MI->getDesc();
215
216 // Break dependence on undef uses. Do this before updating LiveRegs below.
217 // This can remove a false dependence with no additional instructions.
218 for (unsigned i = MCID.getNumDefs(), e = MCID.getNumOperands(); i != e; ++i) {
219 MachineOperand &MO = MI->getOperand(i);
220 if (!MO.isReg() || !MO.getReg() || !MO.isUse() || !MO.isUndef())
221 continue;
222
223 unsigned Pref = TII->getUndefRegClearance(*MI, i);
224 if (Pref) {
225 bool HadTrueDependency = pickBestRegisterForUndef(MI, i, Pref);
226 // We don't need to bother trying to break a dependency if this
227 // instruction has a true dependency on that register through another
228 // operand - we'll have to wait for it to be available regardless.
229 if (!HadTrueDependency && shouldBreakDependence(MI, i, Pref))
230 UndefReads.push_back(std::make_pair(MI, i));
231 }
232 }
233
234 // The code below allows the target to create a new instruction to break the
235 // dependence. That opposes the goal of minimizing size, so bail out now.
236 if (MF->getFunction().hasMinSize())
237 return;
238
239 for (unsigned i = 0,
240 e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
241 i != e; ++i) {
242 MachineOperand &MO = MI->getOperand(i);
243 if (!MO.isReg() || !MO.getReg())
244 continue;
245 if (MO.isUse())
246 continue;
247 // Check clearance before partial register updates.
248 unsigned Pref = TII->getPartialRegUpdateClearance(*MI, i);
249 if (Pref && shouldBreakDependence(MI, i, Pref)) {
250 TII->breakPartialRegDependency(*MI, i);
251 Changed = true;
252 }
253 }
254}
255
256void BreakFalseDeps::processUndefReads(MachineBasicBlock *MBB) {
257 if (UndefReads.empty())
258 return;
259
260 // The code below allows the target to create a new instruction to break the
261 // dependence. That opposes the goal of minimizing size, so bail out now.
262 if (MF->getFunction().hasMinSize())
263 return;
264
265 // Collect this block's live out register units.
266 LiveRegSet.init(*TRI);
267 // We do not need to care about pristine registers as they are just preserved
268 // but not actually used in the function.
269 LiveRegSet.addLiveOutsNoPristines(*MBB);
270
271 MachineInstr *UndefMI = UndefReads.back().first;
272 unsigned OpIdx = UndefReads.back().second;
273
274 for (MachineInstr &I : llvm::reverse(*MBB)) {
275 // Update liveness, including the current instruction's defs.
276 LiveRegSet.stepBackward(I);
277
278 if (UndefMI == &I) {
279 if (!LiveRegSet.contains(UndefMI->getOperand(OpIdx).getReg())) {
280 TII->breakPartialRegDependency(*UndefMI, OpIdx);
281 Changed = true;
282 }
283
284 UndefReads.pop_back();
285 if (UndefReads.empty())
286 return;
287
288 UndefMI = UndefReads.back().first;
289 OpIdx = UndefReads.back().second;
290 }
291 }
292}
293
294void BreakFalseDeps::processBasicBlock(MachineBasicBlock *MBB) {
295 UndefReads.clear();
296 // If this block is not done, it makes little sense to make any decisions
297 // based on clearance information. We need to make a second pass anyway,
298 // and by then we'll have better information, so we can avoid doing the work
299 // to try and break dependencies now.
300 for (MachineInstr &MI : *MBB) {
301 if (!MI.isDebugInstr())
302 processDefs(&MI);
303 }
304 processUndefReads(MBB);
305}
306
307bool BreakFalseDeps::run(MachineFunction &CurMF) {
308 MF = &CurMF;
309 TII = MF->getSubtarget().getInstrInfo();
311 RegClassInfo.runOnMachineFunction(CurMF, /*Rev=*/true);
312
313 LLVM_DEBUG(dbgs() << "********** BREAK FALSE DEPENDENCIES **********\n");
314
315 // Skip Dead blocks due to ReachingDefAnalysis has no idea about instructions
316 // in them.
317 df_iterator_default_set<MachineBasicBlock *> Reachable;
318 for (MachineBasicBlock *MBB : depth_first_ext(&CurMF, Reachable))
319 (void)MBB /* Mark all reachable blocks */;
320
321 // Traverse the basic blocks.
322 for (MachineBasicBlock &MBB : CurMF)
323 if (Reachable.count(&MBB))
325
326 return Changed;
327}
328
329bool BreakFalseDepsLegacy::runOnMachineFunction(MachineFunction &MF) {
330 if (skipFunction(MF.getFunction()))
331 return false;
332
333 return BreakFalseDeps([&]() -> ReachingDefInfo & {
334 return getAnalysis<ReachingDefInfoWrapperPass>().getRDI();
335 })
336 .run(MF);
337}
338
339PreservedAnalyses
342 MFPropsModifier _(*this, MF);
343 if (BreakFalseDeps([&]() -> ReachingDefInfo & {
344 return MFAM.getResult<ReachingDefAnalysis>(MF);
345 }).run(MF)) {
348 return PA;
349 }
350 return PreservedAnalyses::all();
351}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
BreakFalseDeps
This file contains the declaration of the BreakFalseDepsPass class, used to identify and avoid false ...
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
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
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool processBasicBlock(MachineBasicBlock &MBB, BlockStateMap &BlockStates, DirtySuccessorsWorkList &DirtySuccessors, bool IsX86INTR, const TargetInstrInfo *TII)
Loop over all of the instructions in the basic block, inserting vzeroupper instructions before functi...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
LLVM_ABI void stepBackward(const MachineInstr &MI)
Simulates liveness when stepping backwards over an instruction(bundle).
void init(const TargetRegisterInfo &TRI)
(re-)initializes and clears the set.
LLVM_ABI void addLiveOutsNoPristines(const MachineBasicBlock &MBB)
Adds all live-out registers of basic block MBB but skips pristine registers.
bool contains(MCRegister Reg) const
Returns true if register Reg is contained in the set.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
MCRegUnitRootIterator enumerates the root registers of a register unit.
bool isValid() const
Check if the iterator is at the end of the list.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
An RAII based helper class to modify MachineFunctionProperties when running pass.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
LLVM_ABI bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
Register getReg() const
getReg - Returns the register number.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
This class provides the reaching def analysis.
LLVM_ABI void runOnMachineFunction(const MachineFunction &MF, bool Rev=false)
runOnFunction - Prepare to answer questions about MF.
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI FunctionPass * createBreakFalseDepsLegacyPass()
Creates Break False Dependencies pass.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58