blob: efda552c587347494c5fe0c229494db782d8734e [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This register allocator allocates registers to a basic block at a time,
11// attempting to keep values in registers and reusing registers as appropriate.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
16#include "llvm/BasicBlock.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000017#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/CodeGen/MachineInstr.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000020#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng04d9d0b2008-02-06 08:00:32 +000021#include "llvm/CodeGen/Passes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/CodeGen/RegAllocRegistry.h"
23#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/Compiler.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Owen Anderson8050fa12008-07-10 01:56:35 +000030#include "llvm/ADT/DenseMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/ADT/IndexedMap.h"
Evan Cheng548bc502009-01-29 02:20:59 +000032#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
Evan Chenga1d9dfb2008-02-06 19:16:53 +000035#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include <algorithm>
37using namespace llvm;
38
39STATISTIC(NumStores, "Number of stores added");
40STATISTIC(NumLoads , "Number of loads added");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041
Dan Gohman089efff2008-05-13 00:00:25 +000042static RegisterRegAlloc
Dan Gohman669b9bf2008-10-14 20:25:08 +000043 localRegAlloc("local", "local register allocator",
Dan Gohman089efff2008-05-13 00:00:25 +000044 createLocalRegisterAllocator);
45
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000047 class RALocal : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048 public:
49 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +000050 RALocal() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051 private:
52 const TargetMachine *TM;
53 MachineFunction *MF;
Dan Gohman1e57df32008-02-10 18:45:23 +000054 const TargetRegisterInfo *TRI;
Owen Andersonbf15ae22008-01-07 01:35:56 +000055 const TargetInstrInfo *TII;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056
57 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
58 // values are spilled.
Evan Cheng33dc9712008-07-10 18:23:23 +000059 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060
61 // Virt2PhysRegMap - This map contains entries for each virtual register
62 // that is currently available in a physical register.
63 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
64
65 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
66 return Virt2PhysRegMap[VirtReg];
67 }
68
69 // PhysRegsUsed - This array is effectively a map, containing entries for
70 // each physical register that currently has a value (ie, it is in
71 // Virt2PhysRegMap). The value mapped to is the virtual register
72 // corresponding to the physical register (the inverse of the
73 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
74 // because it is used by a future instruction, and to -2 if it is not
75 // allocatable. If the entry for a physical register is -1, then the
76 // physical register is "not in the map".
77 //
78 std::vector<int> PhysRegsUsed;
79
80 // PhysRegsUseOrder - This contains a list of the physical registers that
81 // currently have a virtual register value in them. This list provides an
82 // ordering of registers, imposing a reallocation order. This list is only
83 // used if all registers are allocated and we have to spill one, in which
84 // case we spill the least recently used register. Entries at the front of
85 // the list are the least recently used registers, entries at the back are
86 // the most recently used.
87 //
88 std::vector<unsigned> PhysRegsUseOrder;
89
Evan Chenga94efbd2008-01-17 02:08:17 +000090 // Virt2LastUseMap - This maps each virtual register to its last use
91 // (MachineInstr*, operand index pair).
92 IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
93 Virt2LastUseMap;
94
95 std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
Dan Gohman1e57df32008-02-10 18:45:23 +000096 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
Evan Chenga94efbd2008-01-17 02:08:17 +000097 return Virt2LastUseMap[Reg];
98 }
99
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100 // VirtRegModified - This bitset contains information about which virtual
101 // registers need to be spilled back to memory when their registers are
102 // scavenged. If a virtual register has simply been rematerialized, there
103 // is no reason to spill it to memory when we need the register back.
104 //
Evan Cheng9e66d8c2008-01-17 00:35:26 +0000105 BitVector VirtRegModified;
Owen Anderson9196a392008-07-08 22:24:50 +0000106
107 // UsedInMultipleBlocks - Tracks whether a particular register is used in
108 // more than one block.
109 BitVector UsedInMultipleBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000110
111 void markVirtRegModified(unsigned Reg, bool Val = true) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000112 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
113 Reg -= TargetRegisterInfo::FirstVirtualRegister;
Evan Cheng9e66d8c2008-01-17 00:35:26 +0000114 if (Val)
115 VirtRegModified.set(Reg);
116 else
117 VirtRegModified.reset(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 }
119
120 bool isVirtRegModified(unsigned Reg) const {
Dan Gohman1e57df32008-02-10 18:45:23 +0000121 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
122 assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 && "Illegal virtual register!");
Dan Gohman1e57df32008-02-10 18:45:23 +0000124 return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 }
126
127 void AddToPhysRegsUseOrder(unsigned Reg) {
128 std::vector<unsigned>::iterator It =
129 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
130 if (It != PhysRegsUseOrder.end())
131 PhysRegsUseOrder.erase(It);
132 PhysRegsUseOrder.push_back(Reg);
133 }
134
135 void MarkPhysRegRecentlyUsed(unsigned Reg) {
136 if (PhysRegsUseOrder.empty() ||
137 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
138
139 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
140 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
141 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
142 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
143 // Add it to the end of the list
144 PhysRegsUseOrder.push_back(RegMatch);
145 if (RegMatch == Reg)
146 return; // Found an exact match, exit early
147 }
148 }
149
150 public:
151 virtual const char *getPassName() const {
152 return "Local Register Allocator";
153 }
154
155 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +0000156 AU.setPreservesCFG();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 AU.addRequiredID(PHIEliminationID);
158 AU.addRequiredID(TwoAddressInstructionPassID);
159 MachineFunctionPass::getAnalysisUsage(AU);
160 }
161
162 private:
163 /// runOnMachineFunction - Register allocate the whole function
164 bool runOnMachineFunction(MachineFunction &Fn);
165
166 /// AllocateBasicBlock - Register allocate the specified basic block.
167 void AllocateBasicBlock(MachineBasicBlock &MBB);
168
169
170 /// areRegsEqual - This method returns true if the specified registers are
171 /// related to each other. To do this, it checks to see if they are equal
172 /// or if the first register is in the alias set of the second register.
173 ///
174 bool areRegsEqual(unsigned R1, unsigned R2) const {
175 if (R1 == R2) return true;
Dan Gohman1e57df32008-02-10 18:45:23 +0000176 for (const unsigned *AliasSet = TRI->getAliasSet(R2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 *AliasSet; ++AliasSet) {
178 if (*AliasSet == R1) return true;
179 }
180 return false;
181 }
182
183 /// getStackSpaceFor - This returns the frame index of the specified virtual
184 /// register on the stack, allocating space if necessary.
185 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
186
187 /// removePhysReg - This method marks the specified physical register as no
188 /// longer being in use.
189 ///
190 void removePhysReg(unsigned PhysReg);
191
192 /// spillVirtReg - This method spills the value specified by PhysReg into
193 /// the virtual register slot specified by VirtReg. It then updates the RA
194 /// data structures to indicate the fact that PhysReg is now available.
195 ///
196 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
197 unsigned VirtReg, unsigned PhysReg);
198
199 /// spillPhysReg - This method spills the specified physical register into
200 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
201 /// true, then the request is ignored if the physical register does not
202 /// contain a virtual register.
203 ///
204 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
205 unsigned PhysReg, bool OnlyVirtRegs = false);
206
207 /// assignVirtToPhysReg - This method updates local state so that we know
208 /// that PhysReg is the proper container for VirtReg now. The physical
209 /// register must not be used for anything else when this is called.
210 ///
211 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
212
213 /// isPhysRegAvailable - Return true if the specified physical register is
214 /// free and available for use. This also includes checking to see if
215 /// aliased registers are all free...
216 ///
217 bool isPhysRegAvailable(unsigned PhysReg) const;
218
219 /// getFreeReg - Look to see if there is a free register available in the
220 /// specified register class. If not, return 0.
221 ///
222 unsigned getFreeReg(const TargetRegisterClass *RC);
223
224 /// getReg - Find a physical register to hold the specified virtual
225 /// register. If all compatible physical registers are used, this method
226 /// spills the last used virtual register to the stack, and uses that
Evan Cheng308d1852009-01-29 01:13:00 +0000227 /// register. If NoFree is true, that means the caller knows there isn't
228 /// a free register, do not call getFreeReg().
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng308d1852009-01-29 01:13:00 +0000230 unsigned VirtReg, bool NoFree = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231
Bob Wilsond983fb42009-05-07 21:19:45 +0000232 /// reloadVirtReg - This method transforms the specified virtual
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 /// register use to refer to a physical register. This method may do this
234 /// in one of several ways: if the register is available in a physical
235 /// register already, it uses that physical register. If the value is not
236 /// in a physical register, and if there are physical registers available,
237 /// it loads it into a register. If register pressure is high, and it is
238 /// possible, it tries to fold the load of the virtual register into the
239 /// instruction itself. It avoids doing this if register pressure is low to
240 /// improve the chance that subsequent instructions can use the reloaded
241 /// value. This method returns the modified instruction.
242 ///
243 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng548bc502009-01-29 02:20:59 +0000244 unsigned OpNum, SmallSet<unsigned, 4> &RRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245
Owen Andersonff01ccf2008-07-09 20:14:53 +0000246 /// ComputeLocalLiveness - Computes liveness of registers within a basic
247 /// block, setting the killed/dead flags as appropriate.
248 void ComputeLocalLiveness(MachineBasicBlock& MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249
250 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
251 unsigned PhysReg);
252 };
253 char RALocal::ID = 0;
254}
255
256/// getStackSpaceFor - This allocates space for the specified virtual register
257/// to be held on the stack.
258int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
259 // Find the location Reg would belong...
Evan Cheng33dc9712008-07-10 18:23:23 +0000260 int SS = StackSlotForVirtReg[VirtReg];
261 if (SS != -1)
262 return SS; // Already has space allocated?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263
264 // Allocate a new stack object for this spill location...
265 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
Evan Cheng5505bc12009-10-17 09:20:14 +0000266 RC->getAlignment(),true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267
268 // Assign the slot...
Evan Cheng33dc9712008-07-10 18:23:23 +0000269 StackSlotForVirtReg[VirtReg] = FrameIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 return FrameIdx;
271}
272
273
274/// removePhysReg - This method marks the specified physical register as no
275/// longer being in use.
276///
277void RALocal::removePhysReg(unsigned PhysReg) {
278 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
279
280 std::vector<unsigned>::iterator It =
281 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
282 if (It != PhysRegsUseOrder.end())
283 PhysRegsUseOrder.erase(It);
284}
285
286
287/// spillVirtReg - This method spills the value specified by PhysReg into the
288/// virtual register slot specified by VirtReg. It then updates the RA data
289/// structures to indicate the fact that PhysReg is now available.
290///
291void RALocal::spillVirtReg(MachineBasicBlock &MBB,
292 MachineBasicBlock::iterator I,
293 unsigned VirtReg, unsigned PhysReg) {
294 assert(VirtReg && "Spilling a physical register is illegal!"
295 " Must not have appropriate kill for the register or use exists beyond"
296 " the intended one.");
Bill Wendling9dcc0632009-08-22 20:38:09 +0000297 DEBUG(errs() << " Spilling register " << TRI->getName(PhysReg)
298 << " containing %reg" << VirtReg);
Owen Anderson81875432008-01-01 21:11:32 +0000299
Evan Chenga94efbd2008-01-17 02:08:17 +0000300 if (!isVirtRegModified(VirtReg)) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000301 DEBUG(errs() << " which has not been modified, so no store necessary!");
Evan Chenga94efbd2008-01-17 02:08:17 +0000302 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
303 if (LastUse.first)
304 LastUse.first->getOperand(LastUse.second).setIsKill();
Evan Chenga1d9dfb2008-02-06 19:16:53 +0000305 } else {
306 // Otherwise, there is a virtual register corresponding to this physical
307 // register. We only need to spill it into its stack slot if it has been
308 // modified.
Chris Lattner1b989192007-12-31 04:13:23 +0000309 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310 int FrameIndex = getStackSpaceFor(VirtReg, RC);
Bill Wendling9dcc0632009-08-22 20:38:09 +0000311 DEBUG(errs() << " to stack slot #" << FrameIndex);
Evan Chenga1d9dfb2008-02-06 19:16:53 +0000312 // If the instruction reads the register that's spilled, (e.g. this can
313 // happen if it is a move to a physical register), then the spill
314 // instruction is not a kill.
Evan Chengc7daf1f2008-03-05 00:59:57 +0000315 bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
Evan Chengb4272522008-02-11 08:30:52 +0000316 TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 ++NumStores; // Update statistics
318 }
319
320 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
321
Bill Wendling9dcc0632009-08-22 20:38:09 +0000322 DEBUG(errs() << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 removePhysReg(PhysReg);
324}
325
326
327/// spillPhysReg - This method spills the specified physical register into the
328/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
329/// then the request is ignored if the physical register does not contain a
330/// virtual register.
331///
332void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
333 unsigned PhysReg, bool OnlyVirtRegs) {
334 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
335 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
336 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
337 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
338 } else {
339 // If the selected register aliases any other registers, we must make
340 // sure that one of the aliases isn't alive.
Dan Gohman1e57df32008-02-10 18:45:23 +0000341 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 *AliasSet; ++AliasSet)
343 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
344 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
345 if (PhysRegsUsed[*AliasSet])
346 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
347 }
348}
349
350
351/// assignVirtToPhysReg - This method updates local state so that we know
352/// that PhysReg is the proper container for VirtReg now. The physical
353/// register must not be used for anything else when this is called.
354///
355void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
356 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
357 // Update information to note the fact that this register was just used, and
358 // it holds VirtReg.
359 PhysRegsUsed[PhysReg] = VirtReg;
360 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
361 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
362}
363
364
365/// isPhysRegAvailable - Return true if the specified physical register is free
366/// and available for use. This also includes checking to see if aliased
367/// registers are all free...
368///
369bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
370 if (PhysRegsUsed[PhysReg] != -1) return false;
371
372 // If the selected register aliases any other allocated registers, it is
373 // not free!
Dan Gohman1e57df32008-02-10 18:45:23 +0000374 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 *AliasSet; ++AliasSet)
Evan Chengf90128d2008-02-22 20:30:53 +0000376 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 return false; // Can't use this reg then.
378 return true;
379}
380
381
382/// getFreeReg - Look to see if there is a free register available in the
383/// specified register class. If not, return 0.
384///
385unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
386 // Get iterators defining the range of registers that are valid to allocate in
387 // this class, which also specifies the preferred allocation order.
388 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
389 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
390
391 for (; RI != RE; ++RI)
392 if (isPhysRegAvailable(*RI)) { // Is reg unused?
393 assert(*RI != 0 && "Cannot use register!");
394 return *RI; // Found an unused register!
395 }
396 return 0;
397}
398
399
400/// getReg - Find a physical register to hold the specified virtual
401/// register. If all compatible physical registers are used, this method spills
402/// the last used virtual register to the stack, and uses that register.
403///
404unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
Evan Cheng308d1852009-01-29 01:13:00 +0000405 unsigned VirtReg, bool NoFree) {
Chris Lattner1b989192007-12-31 04:13:23 +0000406 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407
408 // First check to see if we have a free register of the requested type...
Evan Cheng308d1852009-01-29 01:13:00 +0000409 unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410
411 // If we didn't find an unused register, scavenge one now!
412 if (PhysReg == 0) {
413 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
414
415 // Loop over all of the preallocated registers from the least recently used
416 // to the most recently used. When we find one that is capable of holding
417 // our register, use it.
418 for (unsigned i = 0; PhysReg == 0; ++i) {
419 assert(i != PhysRegsUseOrder.size() &&
420 "Couldn't find a register of the appropriate class!");
421
422 unsigned R = PhysRegsUseOrder[i];
423
424 // We can only use this register if it holds a virtual register (ie, it
425 // can be spilled). Do not use it if it is an explicitly allocated
426 // physical register!
427 assert(PhysRegsUsed[R] != -1 &&
428 "PhysReg in PhysRegsUseOrder, but is not allocated?");
429 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
430 // If the current register is compatible, use it.
431 if (RC->contains(R)) {
432 PhysReg = R;
433 break;
434 } else {
435 // If one of the registers aliased to the current register is
436 // compatible, use it.
Dan Gohman1e57df32008-02-10 18:45:23 +0000437 for (const unsigned *AliasIt = TRI->getAliasSet(R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 *AliasIt; ++AliasIt) {
439 if (RC->contains(*AliasIt) &&
440 // If this is pinned down for some reason, don't use it. For
441 // example, if CL is pinned, and we run across CH, don't use
442 // CH as justification for using scavenging ECX (which will
443 // fail).
444 PhysRegsUsed[*AliasIt] != 0 &&
445
446 // Make sure the register is allocatable. Don't allocate SIL on
447 // x86-32.
448 PhysRegsUsed[*AliasIt] != -2) {
449 PhysReg = *AliasIt; // Take an aliased register
450 break;
451 }
452 }
453 }
454 }
455 }
456
457 assert(PhysReg && "Physical register not assigned!?!?");
458
459 // At this point PhysRegsUseOrder[i] is the least recently used register of
460 // compatible register class. Spill it to memory and reap its remains.
461 spillPhysReg(MBB, I, PhysReg);
462 }
463
464 // Now that we know which register we need to assign this to, do it now!
465 assignVirtToPhysReg(VirtReg, PhysReg);
466 return PhysReg;
467}
468
469
Bob Wilson219866c2009-05-07 21:20:42 +0000470/// reloadVirtReg - This method transforms the specified virtual
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471/// register use to refer to a physical register. This method may do this in
472/// one of several ways: if the register is available in a physical register
473/// already, it uses that physical register. If the value is not in a physical
474/// register, and if there are physical registers available, it loads it into a
475/// register. If register pressure is high, and it is possible, it tries to
476/// fold the load of the virtual register into the instruction itself. It
477/// avoids doing this if register pressure is low to improve the chance that
478/// subsequent instructions can use the reloaded value. This method returns the
479/// modified instruction.
480///
481MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng548bc502009-01-29 02:20:59 +0000482 unsigned OpNum,
483 SmallSet<unsigned, 4> &ReloadedRegs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 unsigned VirtReg = MI->getOperand(OpNum).getReg();
485
486 // If the virtual register is already available, just update the instruction
487 // and return.
488 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
Bill Wendlingf49e8392008-02-29 18:52:01 +0000489 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490 MI->getOperand(OpNum).setReg(PR); // Assign the input register
Bill Wendlingf49e8392008-02-29 18:52:01 +0000491 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492 return MI;
493 }
494
495 // Otherwise, we need to fold it into the current instruction, or reload it.
496 // If we have registers available to hold the value, use them.
Chris Lattner1b989192007-12-31 04:13:23 +0000497 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 unsigned PhysReg = getFreeReg(RC);
499 int FrameIndex = getStackSpaceFor(VirtReg, RC);
500
501 if (PhysReg) { // Register is available, allocate it!
502 assignVirtToPhysReg(VirtReg, PhysReg);
503 } else { // No registers available.
Evan Cheng71f91ed2008-02-07 19:46:55 +0000504 // Force some poor hapless value out of the register file to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 // make room for the new register, and reload it.
Evan Cheng308d1852009-01-29 01:13:00 +0000506 PhysReg = getReg(MBB, MI, VirtReg, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507 }
508
509 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
510
Bill Wendling9dcc0632009-08-22 20:38:09 +0000511 DEBUG(errs() << " Reloading %reg" << VirtReg << " into "
512 << TRI->getName(PhysReg) << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513
514 // Add move instruction(s)
Owen Anderson81875432008-01-01 21:11:32 +0000515 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 ++NumLoads; // Update statistics
517
Chris Lattner1b989192007-12-31 04:13:23 +0000518 MF->getRegInfo().setPhysRegUsed(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
Evan Chenga94efbd2008-01-17 02:08:17 +0000520 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Evan Cheng548bc502009-01-29 02:20:59 +0000521
522 if (!ReloadedRegs.insert(PhysReg)) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000523 std::string msg;
524 raw_string_ostream Msg(msg);
525 Msg << "Ran out of registers during register allocation!";
Evan Cheng548bc502009-01-29 02:20:59 +0000526 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000527 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng548bc502009-01-29 02:20:59 +0000528 << "constraints:\n";
Edwin Törökced9ff82009-07-11 13:10:19 +0000529 MI->print(Msg, TM);
Evan Cheng548bc502009-01-29 02:20:59 +0000530 }
Edwin Törökced9ff82009-07-11 13:10:19 +0000531 llvm_report_error(Msg.str());
Evan Cheng548bc502009-01-29 02:20:59 +0000532 }
533 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
534 *SubRegs; ++SubRegs) {
535 if (!ReloadedRegs.insert(*SubRegs)) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000536 std::string msg;
537 raw_string_ostream Msg(msg);
538 Msg << "Ran out of registers during register allocation!";
Evan Cheng548bc502009-01-29 02:20:59 +0000539 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000540 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng548bc502009-01-29 02:20:59 +0000541 << "constraints:\n";
Edwin Törökced9ff82009-07-11 13:10:19 +0000542 MI->print(Msg, TM);
Evan Cheng548bc502009-01-29 02:20:59 +0000543 }
Edwin Törökced9ff82009-07-11 13:10:19 +0000544 llvm_report_error(Msg.str());
Evan Cheng548bc502009-01-29 02:20:59 +0000545 }
546 }
547
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 return MI;
549}
550
551/// isReadModWriteImplicitKill - True if this is an implicit kill for a
552/// read/mod/write register, i.e. update partial register.
553static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
554 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
555 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000556 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000557 MO.isDef() && !MO.isDead())
558 return true;
559 }
560 return false;
561}
562
563/// isReadModWriteImplicitDef - True if this is an implicit def for a
564/// read/mod/write register, i.e. update partial register.
565static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
566 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
567 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000568 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 !MO.isDef() && MO.isKill())
570 return true;
571 }
572 return false;
573}
574
Owen Anderson9196a392008-07-08 22:24:50 +0000575// precedes - Helper function to determine with MachineInstr A
576// precedes MachineInstr B within the same MBB.
577static bool precedes(MachineBasicBlock::iterator A,
578 MachineBasicBlock::iterator B) {
579 if (A == B)
580 return false;
581
582 MachineBasicBlock::iterator I = A->getParent()->begin();
583 while (I != A->getParent()->end()) {
584 if (I == A)
585 return true;
586 else if (I == B)
587 return false;
588
589 ++I;
590 }
591
592 return false;
593}
594
Owen Andersonff01ccf2008-07-09 20:14:53 +0000595/// ComputeLocalLiveness - Computes liveness of registers within a basic
596/// block, setting the killed/dead flags as appropriate.
597void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
Owen Anderson9196a392008-07-08 22:24:50 +0000598 MachineRegisterInfo& MRI = MBB.getParent()->getRegInfo();
599 // Keep track of the most recently seen previous use or def of each reg,
600 // so that we can update them with dead/kill markers.
Owen Anderson8050fa12008-07-10 01:56:35 +0000601 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
Owen Anderson9196a392008-07-08 22:24:50 +0000602 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
603 I != E; ++I) {
604 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
605 MachineOperand& MO = I->getOperand(i);
606 // Uses don't trigger any flags, but we need to save
607 // them for later. Also, we have to process these
608 // _before_ processing the defs, since an instr
609 // uses regs before it defs them.
Owen Andersona4d28702008-10-08 04:30:51 +0000610 if (MO.isReg() && MO.getReg() && MO.isUse()) {
Owen Anderson9196a392008-07-08 22:24:50 +0000611 LastUseDef[MO.getReg()] = std::make_pair(I, i);
Owen Andersona4d28702008-10-08 04:30:51 +0000612
613
614 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) continue;
615
Evan Cheng548bc502009-01-29 02:20:59 +0000616 const unsigned* Aliases = TRI->getAliasSet(MO.getReg());
617 if (Aliases) {
618 while (*Aliases) {
Owen Andersona4d28702008-10-08 04:30:51 +0000619 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Evan Cheng548bc502009-01-29 02:20:59 +0000620 alias = LastUseDef.find(*Aliases);
Owen Andersona4d28702008-10-08 04:30:51 +0000621
Evan Cheng548bc502009-01-29 02:20:59 +0000622 if (alias != LastUseDef.end() && alias->second.first != I)
623 LastUseDef[*Aliases] = std::make_pair(I, i);
Owen Andersona4d28702008-10-08 04:30:51 +0000624
Evan Cheng548bc502009-01-29 02:20:59 +0000625 ++Aliases;
Owen Andersona4d28702008-10-08 04:30:51 +0000626 }
627 }
628 }
Owen Anderson9196a392008-07-08 22:24:50 +0000629 }
630
631 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
632 MachineOperand& MO = I->getOperand(i);
633 // Defs others than 2-addr redefs _do_ trigger flag changes:
634 // - A def followed by a def is dead
635 // - A use followed by a def is a kill
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000636 if (MO.isReg() && MO.getReg() && MO.isDef()) {
Owen Anderson8050fa12008-07-10 01:56:35 +0000637 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Owen Anderson9196a392008-07-08 22:24:50 +0000638 last = LastUseDef.find(MO.getReg());
639 if (last != LastUseDef.end()) {
Owen Anderson348946a2008-07-10 01:53:01 +0000640 // Check if this is a two address instruction. If so, then
641 // the def does not kill the use.
Evan Chengf1107fd2008-07-10 07:35:43 +0000642 if (last->second.first == I &&
Bob Wilsonaded9952009-04-09 17:16:43 +0000643 I->isRegTiedToUseOperand(i))
Evan Chengf1107fd2008-07-10 07:35:43 +0000644 continue;
Owen Anderson77162402008-07-09 21:15:10 +0000645
Owen Anderson9196a392008-07-08 22:24:50 +0000646 MachineOperand& lastUD =
647 last->second.first->getOperand(last->second.second);
648 if (lastUD.isDef())
649 lastUD.setIsDead(true);
Evan Chengf1107fd2008-07-10 07:35:43 +0000650 else
Owen Anderson9196a392008-07-08 22:24:50 +0000651 lastUD.setIsKill(true);
652 }
653
654 LastUseDef[MO.getReg()] = std::make_pair(I, i);
655 }
656 }
657 }
658
659 // Live-out (of the function) registers contain return values of the function,
660 // so we need to make sure they are alive at return time.
661 if (!MBB.empty() && MBB.back().getDesc().isReturn()) {
662 MachineInstr* Ret = &MBB.back();
663 for (MachineRegisterInfo::liveout_iterator
664 I = MF->getRegInfo().liveout_begin(),
665 E = MF->getRegInfo().liveout_end(); I != E; ++I)
666 if (!Ret->readsRegister(*I)) {
667 Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
668 LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
669 }
670 }
671
672 // Finally, loop over the final use/def of each reg
673 // in the block and determine if it is dead.
Owen Anderson8050fa12008-07-10 01:56:35 +0000674 for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Owen Anderson9196a392008-07-08 22:24:50 +0000675 I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
676 MachineInstr* MI = I->second.first;
677 unsigned idx = I->second.second;
678 MachineOperand& MO = MI->getOperand(idx);
679
680 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
681
682 // A crude approximation of "live-out" calculation
683 bool usedOutsideBlock = isPhysReg ? false :
684 UsedInMultipleBlocks.test(MO.getReg() -
685 TargetRegisterInfo::FirstVirtualRegister);
686 if (!isPhysReg && !usedOutsideBlock)
687 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
688 UE = MRI.reg_end(); UI != UE; ++UI)
689 // Two cases:
690 // - used in another block
691 // - used in the same block before it is defined (loop)
692 if (UI->getParent() != &MBB ||
Owen Anderson074e69a2008-07-08 23:36:37 +0000693 (MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI))) {
Owen Anderson9196a392008-07-08 22:24:50 +0000694 UsedInMultipleBlocks.set(MO.getReg() -
695 TargetRegisterInfo::FirstVirtualRegister);
696 usedOutsideBlock = true;
697 break;
698 }
699
700 // Physical registers and those that are not live-out of the block
701 // are killed/dead at their last use/def within this block.
702 if (isPhysReg || !usedOutsideBlock) {
Dan Gohmanec06ecd2008-10-04 00:31:14 +0000703 if (MO.isUse()) {
704 // Don't mark uses that are tied to defs as kills.
Evan Cheng48555e82009-03-19 20:30:06 +0000705 if (!MI->isRegTiedToDefOperand(idx))
Dan Gohmanec06ecd2008-10-04 00:31:14 +0000706 MO.setIsKill(true);
707 } else
Owen Anderson9196a392008-07-08 22:24:50 +0000708 MO.setIsDead(true);
709 }
710 }
Owen Andersonff01ccf2008-07-09 20:14:53 +0000711}
712
713void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
714 // loop over each instruction
715 MachineBasicBlock::iterator MII = MBB.begin();
716
Bill Wendling9dcc0632009-08-22 20:38:09 +0000717 DEBUG({
718 const BasicBlock *LBB = MBB.getBasicBlock();
719 if (LBB)
720 errs() << "\nStarting RegAlloc of BB: " << LBB->getName();
721 });
Owen Andersonff01ccf2008-07-09 20:14:53 +0000722
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000723 // Add live-in registers as active.
724 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
Owen Andersonff01ccf2008-07-09 20:14:53 +0000725 E = MBB.livein_end(); I != E; ++I) {
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000726 unsigned Reg = *I;
727 MF->getRegInfo().setPhysRegUsed(Reg);
728 PhysRegsUsed[Reg] = 0; // It is free and reserved now
729 AddToPhysRegsUseOrder(Reg);
730 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
731 *SubRegs; ++SubRegs) {
732 if (PhysRegsUsed[*SubRegs] != -2) {
733 AddToPhysRegsUseOrder(*SubRegs);
734 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
735 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Owen Andersonff01ccf2008-07-09 20:14:53 +0000736 }
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000737 }
Owen Andersonff01ccf2008-07-09 20:14:53 +0000738 }
739
740 ComputeLocalLiveness(MBB);
Owen Anderson9196a392008-07-08 22:24:50 +0000741
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 // Otherwise, sequentially allocate each instruction in the MBB.
743 while (MII != MBB.end()) {
744 MachineInstr *MI = MII++;
Chris Lattner5b930372008-01-07 07:27:27 +0000745 const TargetInstrDesc &TID = MI->getDesc();
Bill Wendling9dcc0632009-08-22 20:38:09 +0000746 DEBUG({
747 errs() << "\nStarting RegAlloc of: " << *MI;
748 errs() << " Regs have values: ";
749 for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
750 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
751 errs() << "[" << TRI->getName(i)
752 << ",%reg" << PhysRegsUsed[i] << "] ";
753 errs() << '\n';
754 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755
756 // Loop over the implicit uses, making sure that they are at the head of the
757 // use order list, so they don't get reallocated.
758 if (TID.ImplicitUses) {
759 for (const unsigned *ImplicitUses = TID.ImplicitUses;
760 *ImplicitUses; ++ImplicitUses)
761 MarkPhysRegRecentlyUsed(*ImplicitUses);
762 }
763
764 SmallVector<unsigned, 8> Kills;
765 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
766 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000767 if (MO.isReg() && MO.isKill()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 if (!MO.isImplicit())
769 Kills.push_back(MO.getReg());
770 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
771 // These are extra physical register kills when a sub-register
772 // is defined (def of a sub-register is a read/mod/write of the
773 // larger registers). Ignore.
774 Kills.push_back(MO.getReg());
775 }
776 }
777
Dale Johannesen47e30e42008-09-24 23:13:09 +0000778 // If any physical regs are earlyclobber, spill any value they might
779 // have in them, then mark them unallocatable.
780 // If any virtual regs are earlyclobber, allocate them now (before
781 // freeing inputs that are killed).
782 if (MI->getOpcode()==TargetInstrInfo::INLINEASM) {
783 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
784 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000785 if (MO.isReg() && MO.isDef() && MO.isEarlyClobber() &&
Dale Johannesen47e30e42008-09-24 23:13:09 +0000786 MO.getReg()) {
787 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
788 unsigned DestVirtReg = MO.getReg();
789 unsigned DestPhysReg;
790
791 // If DestVirtReg already has a value, use it.
792 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
793 DestPhysReg = getReg(MBB, MI, DestVirtReg);
794 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
795 markVirtRegModified(DestVirtReg);
796 getVirtRegLastUse(DestVirtReg) =
797 std::make_pair((MachineInstr*)0, 0);
Bill Wendling9dcc0632009-08-22 20:38:09 +0000798 DEBUG(errs() << " Assigning " << TRI->getName(DestPhysReg)
799 << " to %reg" << DestVirtReg << "\n");
Dale Johannesen47e30e42008-09-24 23:13:09 +0000800 MO.setReg(DestPhysReg); // Assign the earlyclobber register
801 } else {
802 unsigned Reg = MO.getReg();
803 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
804 // These are extra physical register defs when a sub-register
805 // is defined (def of a sub-register is a read/mod/write of the
806 // larger registers). Ignore.
807 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
808
809 MF->getRegInfo().setPhysRegUsed(Reg);
810 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
811 PhysRegsUsed[Reg] = 0; // It is free and reserved now
812 AddToPhysRegsUseOrder(Reg);
813
Evan Cheng548bc502009-01-29 02:20:59 +0000814 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
815 *SubRegs; ++SubRegs) {
816 if (PhysRegsUsed[*SubRegs] != -2) {
817 MF->getRegInfo().setPhysRegUsed(*SubRegs);
818 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
819 AddToPhysRegsUseOrder(*SubRegs);
Dale Johannesen47e30e42008-09-24 23:13:09 +0000820 }
821 }
822 }
823 }
824 }
825 }
826
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 // Get the used operands into registers. This has the potential to spill
828 // incoming values if we are out of registers. Note that we completely
829 // ignore physical register uses here. We assume that if an explicit
830 // physical register is referenced by the instruction, that it is guaranteed
831 // to be live-in, or the input is badly hosed.
832 //
Evan Cheng548bc502009-01-29 02:20:59 +0000833 SmallSet<unsigned, 4> ReloadedRegs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
835 MachineOperand& MO = MI->getOperand(i);
836 // here we are looking for only used operands (never def&use)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000837 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000838 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Cheng548bc502009-01-29 02:20:59 +0000839 MI = reloadVirtReg(MBB, MI, i, ReloadedRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000840 }
841
842 // If this instruction is the last user of this register, kill the
843 // value, freeing the register being used, so it doesn't need to be
844 // spilled to memory.
845 //
846 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
847 unsigned VirtReg = Kills[i];
848 unsigned PhysReg = VirtReg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000849 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 // If the virtual register was never materialized into a register, it
851 // might not be in the map, but it won't hurt to zero it out anyway.
852 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
853 PhysReg = PhysRegSlot;
854 PhysRegSlot = 0;
855 } else if (PhysRegsUsed[PhysReg] == -2) {
856 // Unallocatable register dead, ignore.
857 continue;
858 } else {
Evan Cheng358d8dd2007-10-22 19:42:28 +0000859 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 "Silently clearing a virtual register?");
861 }
862
863 if (PhysReg) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000864 DEBUG(errs() << " Last use of " << TRI->getName(PhysReg)
865 << "[%reg" << VirtReg <<"], removing it from live set\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 removePhysReg(PhysReg);
Evan Cheng548bc502009-01-29 02:20:59 +0000867 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
868 *SubRegs; ++SubRegs) {
869 if (PhysRegsUsed[*SubRegs] != -2) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000870 DEBUG(errs() << " Last use of "
871 << TRI->getName(*SubRegs) << "[%reg" << VirtReg
872 <<"], removing it from live set\n");
Evan Cheng548bc502009-01-29 02:20:59 +0000873 removePhysReg(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874 }
875 }
876 }
877 }
878
879 // Loop over all of the operands of the instruction, spilling registers that
880 // are defined, and marking explicit destinations in the PhysRegsUsed map.
881 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
882 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000883 if (MO.isReg() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
Dale Johannesen47e30e42008-09-24 23:13:09 +0000884 !MO.isEarlyClobber() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000885 TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886 unsigned Reg = MO.getReg();
887 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
888 // These are extra physical register defs when a sub-register
889 // is defined (def of a sub-register is a read/mod/write of the
890 // larger registers). Ignore.
891 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
892
Chris Lattner1b989192007-12-31 04:13:23 +0000893 MF->getRegInfo().setPhysRegUsed(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
895 PhysRegsUsed[Reg] = 0; // It is free and reserved now
896 AddToPhysRegsUseOrder(Reg);
897
Evan Cheng548bc502009-01-29 02:20:59 +0000898 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
899 *SubRegs; ++SubRegs) {
900 if (PhysRegsUsed[*SubRegs] != -2) {
901 MF->getRegInfo().setPhysRegUsed(*SubRegs);
902 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
903 AddToPhysRegsUseOrder(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904 }
905 }
906 }
907 }
908
909 // Loop over the implicit defs, spilling them as well.
910 if (TID.ImplicitDefs) {
911 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
912 *ImplicitDefs; ++ImplicitDefs) {
913 unsigned Reg = *ImplicitDefs;
914 if (PhysRegsUsed[Reg] != -2) {
915 spillPhysReg(MBB, MI, Reg, true);
916 AddToPhysRegsUseOrder(Reg);
917 PhysRegsUsed[Reg] = 0; // It is free and reserved now
918 }
Chris Lattner1b989192007-12-31 04:13:23 +0000919 MF->getRegInfo().setPhysRegUsed(Reg);
Evan Cheng548bc502009-01-29 02:20:59 +0000920 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
921 *SubRegs; ++SubRegs) {
922 if (PhysRegsUsed[*SubRegs] != -2) {
923 AddToPhysRegsUseOrder(*SubRegs);
924 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
925 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 }
927 }
928 }
929 }
930
931 SmallVector<unsigned, 8> DeadDefs;
932 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
933 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000934 if (MO.isReg() && MO.isDead())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 DeadDefs.push_back(MO.getReg());
936 }
937
938 // Okay, we have allocated all of the source operands and spilled any values
939 // that would be destroyed by defs of this instruction. Loop over the
940 // explicit defs and assign them to a register, spilling incoming values if
941 // we need to scavenge a register.
942 //
943 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
944 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000945 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Dale Johannesen47e30e42008-09-24 23:13:09 +0000946 !MO.isEarlyClobber() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000947 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 unsigned DestVirtReg = MO.getReg();
949 unsigned DestPhysReg;
950
951 // If DestVirtReg already has a value, use it.
952 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
953 DestPhysReg = getReg(MBB, MI, DestVirtReg);
Chris Lattner1b989192007-12-31 04:13:23 +0000954 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 markVirtRegModified(DestVirtReg);
Evan Chenga94efbd2008-01-17 02:08:17 +0000956 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
Bill Wendling9dcc0632009-08-22 20:38:09 +0000957 DEBUG(errs() << " Assigning " << TRI->getName(DestPhysReg)
958 << " to %reg" << DestVirtReg << "\n");
Dan Gohman7f31037a2008-07-09 20:12:26 +0000959 MO.setReg(DestPhysReg); // Assign the output register
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 }
961 }
962
963 // If this instruction defines any registers that are immediately dead,
964 // kill them now.
965 //
966 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
967 unsigned VirtReg = DeadDefs[i];
968 unsigned PhysReg = VirtReg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000969 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
971 PhysReg = PhysRegSlot;
972 assert(PhysReg != 0);
973 PhysRegSlot = 0;
974 } else if (PhysRegsUsed[PhysReg] == -2) {
975 // Unallocatable register dead, ignore.
976 continue;
977 }
978
979 if (PhysReg) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000980 DEBUG(errs() << " Register " << TRI->getName(PhysReg)
981 << " [%reg" << VirtReg
982 << "] is never used, removing it from live set\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 removePhysReg(PhysReg);
Dan Gohman1e57df32008-02-10 18:45:23 +0000984 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 *AliasSet; ++AliasSet) {
986 if (PhysRegsUsed[*AliasSet] != -2) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000987 DEBUG(errs() << " Register " << TRI->getName(*AliasSet)
988 << " [%reg" << *AliasSet
989 << "] is never used, removing it from live set\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 removePhysReg(*AliasSet);
991 }
992 }
993 }
994 }
995
Bob Wilsona43eb6b2009-05-07 23:47:03 +0000996 // Finally, if this is a noop copy instruction, zap it. (Except that if
997 // the copy is dead, it must be kept to avoid messing up liveness info for
998 // the register scavenger. See pr4100.)
Evan Chengf97496a2009-01-20 19:12:24 +0000999 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
1000 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
Bob Wilsona43eb6b2009-05-07 23:47:03 +00001001 SrcReg == DstReg && DeadDefs.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 MBB.erase(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 }
1004
1005 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1006
1007 // Spill all physical registers holding virtual registers now.
Dan Gohman1e57df32008-02-10 18:45:23 +00001008 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001009 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 if (unsigned VirtReg = PhysRegsUsed[i])
1011 spillVirtReg(MBB, MI, VirtReg, i);
1012 else
1013 removePhysReg(i);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001014 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015
1016#if 0
1017 // This checking code is very expensive.
1018 bool AllOk = true;
Dan Gohman1e57df32008-02-10 18:45:23 +00001019 for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
Chris Lattner1b989192007-12-31 04:13:23 +00001020 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 if (unsigned PR = Virt2PhysRegMap[i]) {
1022 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
1023 AllOk = false;
1024 }
1025 assert(AllOk && "Virtual registers still in phys regs?");
1026#endif
1027
1028 // Clear any physical register which appear live at the end of the basic
1029 // block, but which do not hold any virtual registers. e.g., the stack
1030 // pointer.
1031 PhysRegsUseOrder.clear();
1032}
1033
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034/// runOnMachineFunction - Register allocate the whole function
1035///
1036bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
Bill Wendling9dcc0632009-08-22 20:38:09 +00001037 DEBUG(errs() << "Machine Function\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 MF = &Fn;
1039 TM = &Fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +00001040 TRI = TM->getRegisterInfo();
Owen Andersonbf15ae22008-01-07 01:35:56 +00001041 TII = TM->getInstrInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042
Dan Gohman1e57df32008-02-10 18:45:23 +00001043 PhysRegsUsed.assign(TRI->getNumRegs(), -1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044
1045 // At various places we want to efficiently check to see whether a register
1046 // is allocatable. To handle this, we mark all unallocatable registers as
1047 // being pinned down, permanently.
1048 {
Dan Gohman1e57df32008-02-10 18:45:23 +00001049 BitVector Allocable = TRI->getAllocatableSet(Fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
1051 if (!Allocable[i])
1052 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
1053 }
1054
1055 // initialize the virtual->physical register map to have a 'null'
1056 // mapping for all virtual registers
Evan Cheng9e66d8c2008-01-17 00:35:26 +00001057 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
Evan Cheng33dc9712008-07-10 18:23:23 +00001058 StackSlotForVirtReg.grow(LastVirtReg);
Evan Cheng9e66d8c2008-01-17 00:35:26 +00001059 Virt2PhysRegMap.grow(LastVirtReg);
Evan Chenga94efbd2008-01-17 02:08:17 +00001060 Virt2LastUseMap.grow(LastVirtReg);
Dan Gohman1e57df32008-02-10 18:45:23 +00001061 VirtRegModified.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
Owen Anderson9196a392008-07-08 22:24:50 +00001062 UsedInMultipleBlocks.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
1063
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 // Loop over all of the basic blocks, eliminating virtual register references
1065 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
1066 MBB != MBBe; ++MBB)
1067 AllocateBasicBlock(*MBB);
1068
1069 StackSlotForVirtReg.clear();
1070 PhysRegsUsed.clear();
1071 VirtRegModified.clear();
Owen Anderson9196a392008-07-08 22:24:50 +00001072 UsedInMultipleBlocks.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 Virt2PhysRegMap.clear();
Evan Chenga94efbd2008-01-17 02:08:17 +00001074 Virt2LastUseMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001075 return true;
1076}
1077
1078FunctionPass *llvm::createLocalRegisterAllocator() {
1079 return new RALocal();
1080}