[sanitizer] Improve FreeBSD ASLR detection
[llvm-project.git] / llvm / lib / CodeGen / RegAllocBasic.cpp
bloba9816b13e798081b75a87e3b4093e519ad6915c6
1 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
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 file defines the RABasic function pass, which provides a minimal
10 // implementation of the basic register allocator.
12 //===----------------------------------------------------------------------===//
14 #include "AllocationOrder.h"
15 #include "LiveDebugVariables.h"
16 #include "RegAllocBase.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervals.h"
20 #include "llvm/CodeGen/LiveRangeEdit.h"
21 #include "llvm/CodeGen/LiveRegMatrix.h"
22 #include "llvm/CodeGen/LiveStacks.h"
23 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegAllocRegistry.h"
30 #include "llvm/CodeGen/Spiller.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cstdlib>
37 #include <queue>
39 using namespace llvm;
41 #define DEBUG_TYPE "regalloc"
43 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
44 createBasicRegisterAllocator);
46 namespace {
47 struct CompSpillWeight {
48 bool operator()(LiveInterval *A, LiveInterval *B) const {
49 return A->weight() < B->weight();
54 namespace {
55 /// RABasic provides a minimal implementation of the basic register allocation
56 /// algorithm. It prioritizes live virtual registers by spill weight and spills
57 /// whenever a register is unavailable. This is not practical in production but
58 /// provides a useful baseline both for measuring other allocators and comparing
59 /// the speed of the basic algorithm against other styles of allocators.
60 class RABasic : public MachineFunctionPass,
61 public RegAllocBase,
62 private LiveRangeEdit::Delegate {
63 // context
64 MachineFunction *MF;
66 // state
67 std::unique_ptr<Spiller> SpillerInstance;
68 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
69 CompSpillWeight> Queue;
71 // Scratch space. Allocated here to avoid repeated malloc calls in
72 // selectOrSplit().
73 BitVector UsableRegs;
75 bool LRE_CanEraseVirtReg(Register) override;
76 void LRE_WillShrinkVirtReg(Register) override;
78 public:
79 RABasic(const RegClassFilterFunc F = allocateAllRegClasses);
81 /// Return the pass name.
82 StringRef getPassName() const override { return "Basic Register Allocator"; }
84 /// RABasic analysis usage.
85 void getAnalysisUsage(AnalysisUsage &AU) const override;
87 void releaseMemory() override;
89 Spiller &spiller() override { return *SpillerInstance; }
91 void enqueueImpl(LiveInterval *LI) override {
92 Queue.push(LI);
95 LiveInterval *dequeue() override {
96 if (Queue.empty())
97 return nullptr;
98 LiveInterval *LI = Queue.top();
99 Queue.pop();
100 return LI;
103 MCRegister selectOrSplit(LiveInterval &VirtReg,
104 SmallVectorImpl<Register> &SplitVRegs) override;
106 /// Perform register allocation.
107 bool runOnMachineFunction(MachineFunction &mf) override;
109 MachineFunctionProperties getRequiredProperties() const override {
110 return MachineFunctionProperties().set(
111 MachineFunctionProperties::Property::NoPHIs);
114 MachineFunctionProperties getClearedProperties() const override {
115 return MachineFunctionProperties().set(
116 MachineFunctionProperties::Property::IsSSA);
119 // Helper for spilling all live virtual registers currently unified under preg
120 // that interfere with the most recently queried lvr. Return true if spilling
121 // was successful, and append any new spilled/split intervals to splitLVRs.
122 bool spillInterferences(LiveInterval &VirtReg, MCRegister PhysReg,
123 SmallVectorImpl<Register> &SplitVRegs);
125 static char ID;
128 char RABasic::ID = 0;
130 } // end anonymous namespace
132 char &llvm::RABasicID = RABasic::ID;
134 INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
135 false, false)
136 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
137 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
138 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
139 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
140 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
141 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
142 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
143 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
144 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
145 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
146 INITIALIZE_PASS_END(RABasic, "regallocbasic", "Basic Register Allocator", false,
147 false)
149 bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
150 LiveInterval &LI = LIS->getInterval(VirtReg);
151 if (VRM->hasPhys(VirtReg)) {
152 Matrix->unassign(LI);
153 aboutToRemoveInterval(LI);
154 return true;
156 // Unassigned virtreg is probably in the priority queue.
157 // RegAllocBase will erase it after dequeueing.
158 // Nonetheless, clear the live-range so that the debug
159 // dump will show the right state for that VirtReg.
160 LI.clear();
161 return false;
164 void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
165 if (!VRM->hasPhys(VirtReg))
166 return;
168 // Register is assigned, put it back on the queue for reassignment.
169 LiveInterval &LI = LIS->getInterval(VirtReg);
170 Matrix->unassign(LI);
171 enqueue(&LI);
174 RABasic::RABasic(RegClassFilterFunc F):
175 MachineFunctionPass(ID),
176 RegAllocBase(F) {
179 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
180 AU.setPreservesCFG();
181 AU.addRequired<AAResultsWrapperPass>();
182 AU.addPreserved<AAResultsWrapperPass>();
183 AU.addRequired<LiveIntervals>();
184 AU.addPreserved<LiveIntervals>();
185 AU.addPreserved<SlotIndexes>();
186 AU.addRequired<LiveDebugVariables>();
187 AU.addPreserved<LiveDebugVariables>();
188 AU.addRequired<LiveStacks>();
189 AU.addPreserved<LiveStacks>();
190 AU.addRequired<MachineBlockFrequencyInfo>();
191 AU.addPreserved<MachineBlockFrequencyInfo>();
192 AU.addRequiredID(MachineDominatorsID);
193 AU.addPreservedID(MachineDominatorsID);
194 AU.addRequired<MachineLoopInfo>();
195 AU.addPreserved<MachineLoopInfo>();
196 AU.addRequired<VirtRegMap>();
197 AU.addPreserved<VirtRegMap>();
198 AU.addRequired<LiveRegMatrix>();
199 AU.addPreserved<LiveRegMatrix>();
200 MachineFunctionPass::getAnalysisUsage(AU);
203 void RABasic::releaseMemory() {
204 SpillerInstance.reset();
208 // Spill or split all live virtual registers currently unified under PhysReg
209 // that interfere with VirtReg. The newly spilled or split live intervals are
210 // returned by appending them to SplitVRegs.
211 bool RABasic::spillInterferences(LiveInterval &VirtReg, MCRegister PhysReg,
212 SmallVectorImpl<Register> &SplitVRegs) {
213 // Record each interference and determine if all are spillable before mutating
214 // either the union or live intervals.
215 SmallVector<LiveInterval*, 8> Intfs;
217 // Collect interferences assigned to any alias of the physical register.
218 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
219 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
220 for (auto *Intf : reverse(Q.interferingVRegs())) {
221 if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
222 return false;
223 Intfs.push_back(Intf);
226 LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
227 << " interferences with " << VirtReg << "\n");
228 assert(!Intfs.empty() && "expected interference");
230 // Spill each interfering vreg allocated to PhysReg or an alias.
231 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
232 LiveInterval &Spill = *Intfs[i];
234 // Skip duplicates.
235 if (!VRM->hasPhys(Spill.reg()))
236 continue;
238 // Deallocate the interfering vreg by removing it from the union.
239 // A LiveInterval instance may not be in a union during modification!
240 Matrix->unassign(Spill);
242 // Spill the extracted interval.
243 LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
244 spiller().spill(LRE);
246 return true;
249 // Driver for the register assignment and splitting heuristics.
250 // Manages iteration over the LiveIntervalUnions.
252 // This is a minimal implementation of register assignment and splitting that
253 // spills whenever we run out of registers.
255 // selectOrSplit can only be called once per live virtual register. We then do a
256 // single interference test for each register the correct class until we find an
257 // available register. So, the number of interference tests in the worst case is
258 // |vregs| * |machineregs|. And since the number of interference tests is
259 // minimal, there is no value in caching them outside the scope of
260 // selectOrSplit().
261 MCRegister RABasic::selectOrSplit(LiveInterval &VirtReg,
262 SmallVectorImpl<Register> &SplitVRegs) {
263 // Populate a list of physical register spill candidates.
264 SmallVector<MCRegister, 8> PhysRegSpillCands;
266 // Check for an available register in this class.
267 auto Order =
268 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
269 for (MCRegister PhysReg : Order) {
270 assert(PhysReg.isValid());
271 // Check for interference in PhysReg
272 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
273 case LiveRegMatrix::IK_Free:
274 // PhysReg is available, allocate it.
275 return PhysReg;
277 case LiveRegMatrix::IK_VirtReg:
278 // Only virtual registers in the way, we may be able to spill them.
279 PhysRegSpillCands.push_back(PhysReg);
280 continue;
282 default:
283 // RegMask or RegUnit interference.
284 continue;
288 // Try to spill another interfering reg with less spill weight.
289 for (MCRegister &PhysReg : PhysRegSpillCands) {
290 if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
291 continue;
293 assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
294 "Interference after spill.");
295 // Tell the caller to allocate to this newly freed physical register.
296 return PhysReg;
299 // No other spill candidates were found, so spill the current VirtReg.
300 LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
301 if (!VirtReg.isSpillable())
302 return ~0u;
303 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
304 spiller().spill(LRE);
306 // The live virtual register requesting allocation was spilled, so tell
307 // the caller not to allocate anything during this round.
308 return 0;
311 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
312 LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
313 << "********** Function: " << mf.getName() << '\n');
315 MF = &mf;
316 RegAllocBase::init(getAnalysis<VirtRegMap>(),
317 getAnalysis<LiveIntervals>(),
318 getAnalysis<LiveRegMatrix>());
319 VirtRegAuxInfo VRAI(*MF, *LIS, *VRM, getAnalysis<MachineLoopInfo>(),
320 getAnalysis<MachineBlockFrequencyInfo>());
321 VRAI.calculateSpillWeightsAndHints();
323 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, VRAI));
325 allocatePhysRegs();
326 postOptimization();
328 // Diagnostic output before rewriting
329 LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
331 releaseMemory();
332 return true;
335 FunctionPass* llvm::createBasicRegisterAllocator() {
336 return new RABasic();
339 FunctionPass* llvm::createBasicRegisterAllocator(RegClassFilterFunc F) {
340 return new RABasic(F);