LLVM 23.0.0git
RegUsageInfoCollector.cpp
Go to the documentation of this file.
1//===-- RegUsageInfoCollector.cpp - Register Usage Information Collector --===//
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/// This pass is required to take advantage of the interprocedural register
10/// allocation infrastructure.
11///
12/// This pass is simple MachineFunction pass which collects register usage
13/// details by iterating through each physical registers and checking
14/// MRI::isPhysRegUsed() then creates a RegMask based on this details.
15/// The pass then stores this RegMask in PhysicalRegisterUsageInfo.cpp
16///
17//===----------------------------------------------------------------------===//
18
20#include "llvm/ADT/Statistic.h"
25#include "llvm/CodeGen/Passes.h"
28#include "llvm/IR/Function.h"
30#include "llvm/Support/Debug.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "ip-regalloc"
36
37STATISTIC(NumCSROpt,
38 "Number of functions optimized for callee saved registers");
39
40namespace {
41
42class RegUsageInfoCollector {
44
45public:
47 bool run(MachineFunction &MF);
48
49 // Call getCalleeSaves and then also set the bits for subregs and
50 // fully saved superregs.
51 static void computeCalleeSavedRegs(BitVector &SavedRegs, MachineFunction &MF);
52};
53
54class RegUsageInfoCollectorLegacy : public MachineFunctionPass {
55public:
56 static char ID;
57 RegUsageInfoCollectorLegacy() : MachineFunctionPass(ID) {}
58
59 StringRef getPassName() const override {
60 return "Register Usage Information Collector Pass";
61 }
62
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.addRequired<PhysicalRegisterUsageInfoWrapperLegacy>();
65 AU.setPreservesAll();
67 }
68
69 bool runOnMachineFunction(MachineFunction &MF) override;
70};
71} // end of anonymous namespace
72
73char RegUsageInfoCollectorLegacy::ID = 0;
74
75INITIALIZE_PASS_BEGIN(RegUsageInfoCollectorLegacy, "RegUsageInfoCollector",
76 "Register Usage Information Collector", false, false)
78INITIALIZE_PASS_END(RegUsageInfoCollectorLegacy, "RegUsageInfoCollector",
79 "Register Usage Information Collector", false, false)
80
82 return new RegUsageInfoCollectorLegacy();
83}
84
85// TODO: Move to hook somwehere?
86
87// Return true if it is useful to track the used registers for IPRA / no CSR
88// optimizations. This is not useful for entry points, and computing the
89// register usage information is expensive.
90static bool isCallableFunction(const MachineFunction &MF) {
91 switch (MF.getFunction().getCallingConv()) {
100 return false;
101 default:
102 return true;
103 }
104}
105
109 Module &MFA = *MF.getFunction().getParent();
111 .getCachedResult<PhysicalRegisterUsageAnalysis>(MFA);
112 assert(PRUI && "PhysicalRegisterUsageAnalysis not available");
113 RegUsageInfoCollector(*PRUI).run(MF);
114 return PreservedAnalyses::all();
115}
116
117bool RegUsageInfoCollectorLegacy::runOnMachineFunction(MachineFunction &MF) {
119 getAnalysis<PhysicalRegisterUsageInfoWrapperLegacy>().getPRUI();
120 return RegUsageInfoCollector(PRUI).run(MF);
121}
122
123bool RegUsageInfoCollector::run(MachineFunction &MF) {
126 const TargetMachine &TM = MF.getTarget();
127
129 dbgs()
130 << " -------------------- Register Usage Information Collector Pass"
131 << " -------------------- \nFunction Name : " << MF.getName() << '\n');
132
133 // Analyzing the register usage may be expensive on some targets.
134 if (!isCallableFunction(MF)) {
135 LLVM_DEBUG(dbgs() << "Not analyzing non-callable function\n");
136 return false;
137 }
138
139 // If there are no callers, there's no point in computing more precise
140 // register usage here.
141 if (MF.getFunction().use_empty()) {
142 LLVM_DEBUG(dbgs() << "Not analyzing function with no callers\n");
143 return false;
144 }
145
146 std::vector<uint32_t> RegMask;
147
148 // Compute the size of the bit vector to represent all the registers.
149 // The bit vector is broken into 32-bit chunks, thus takes the ceil of
150 // the number of registers divided by 32 for the size.
151 unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
152 RegMask.resize(RegMaskSize, ~((uint32_t)0));
153
154 const Function &F = MF.getFunction();
155
156 PRUI.setTargetMachine(TM);
157
158 LLVM_DEBUG(dbgs() << "Clobbered Registers: ");
159
160 BitVector SavedRegs;
161 computeCalleeSavedRegs(SavedRegs, MF);
162
163 const BitVector &UsedPhysRegsMask = MRI->getUsedPhysRegsMask();
164 auto SetRegAsDefined = [&RegMask](MCRegister Reg) {
165 RegMask[Reg.id() / 32] &= ~(1u << Reg.id() % 32);
166 };
167
168 // Don't include $noreg in any regmasks.
169 SetRegAsDefined(MCRegister());
170
171 // Some targets can clobber registers "inside" a call, typically in
172 // linker-generated code.
173 for (const MCPhysReg Reg : TRI->getIntraCallClobberedRegs(&MF))
174 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
175 SetRegAsDefined(*AI);
176
177 // Scan all the physical registers. When a register is defined in the current
178 // function set it and all the aliasing registers as defined in the regmask.
179 // FIXME: Rewrite to use regunits.
180 for (unsigned PReg = 1, PRegE = TRI->getNumRegs(); PReg < PRegE; ++PReg) {
181 // Don't count registers that are saved and restored.
182 if (SavedRegs.test(PReg))
183 continue;
184 // If a register is defined by an instruction mark it as defined together
185 // with all it's unsaved aliases.
186 if (!MRI->def_empty(PReg)) {
187 for (MCRegAliasIterator AI(PReg, TRI, true); AI.isValid(); ++AI)
188 if (!SavedRegs.test((*AI).id()))
189 SetRegAsDefined(*AI);
190 continue;
191 }
192 // If a register is in the UsedPhysRegsMask set then mark it as defined.
193 // All clobbered aliases will also be in the set, so we can skip setting
194 // as defined all the aliases here.
195 if (UsedPhysRegsMask.test(PReg))
196 SetRegAsDefined(PReg);
197 }
198
201 ++NumCSROpt;
202 LLVM_DEBUG(dbgs() << MF.getName()
203 << " function optimized for not having CSR.\n");
204 }
205
207 for (unsigned PReg = 1, PRegE = TRI->getNumRegs(); PReg < PRegE; ++PReg) {
208 if (MachineOperand::clobbersPhysReg(&(RegMask[0]), PReg))
209 dbgs() << printReg(PReg, TRI) << " ";
210 }
211
212 dbgs() << " \n----------------------------------------\n";
213 );
214
215 PRUI.storeUpdateRegUsageInfo(F, RegMask);
216
217 return false;
218}
219
220void RegUsageInfoCollector::
221computeCalleeSavedRegs(BitVector &SavedRegs, MachineFunction &MF) {
224
225 // Target will return the set of registers that it saves/restores as needed.
226 SavedRegs.clear();
227 TFI.getCalleeSaves(MF, SavedRegs);
228 if (SavedRegs.none())
229 return;
230
231 // Insert subregs.
232 const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
233 for (unsigned i = 0; CSRegs[i]; ++i) {
234 MCPhysReg Reg = CSRegs[i];
235 if (SavedRegs.test(Reg)) {
236 // Save subregisters
237 for (MCPhysReg SR : TRI.subregs(Reg))
238 SavedRegs.set(SR);
239 }
240 }
241}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define F(x, y, z)
Definition MD5.cpp:54
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
static bool isCallableFunction(const MachineFunction &MF)
This pass is required to take advantage of the interprocedural register allocation infrastructure.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool test(unsigned Idx) const
Definition BitVector.h:480
void clear()
clear - Removes all bits from the bitvector.
Definition BitVector.h:354
BitVector & set()
Definition BitVector.h:370
bool none() const
none - Returns true if none of the bits are set.
Definition BitVector.h:207
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:270
Module * getParent()
Get the module that this global value is contained inside of...
MCRegAliasIterator enumerates all registers aliasing Reg.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
static unsigned getRegMaskSize(unsigned NumRegs)
Returns number of elements needed for a regmask array.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void setTargetMachine(const TargetMachine &TM)
Set TargetMachine which is used to print analysis.
void storeUpdateRegUsageInfo(const Function &FP, ArrayRef< uint32_t > RegMask)
To store RegMask for given Function *.
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 run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
constexpr unsigned id() const
Definition Register.h:100
Information about stack frame layout on the target.
virtual void getCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const
Returns the callee-saved registers as computed by determineCalleeSaves in the BitVector SavedRegs.
virtual bool isProfitableForNoCSROpt(const Function &F) const
Check if the no-CSR optimisation is profitable for the given function.
static bool isSafeForNoCSROpt(const Function &F)
Check if given function is safe for not having callee saved registers.
Primary interface to the complete machine description for the target machine.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
bool use_empty() const
Definition Value.h:346
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI FunctionPass * createRegUsageInfoCollector()
This pass is executed POST-RA to collect which physical registers are preserved by given machine func...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21