blob: 40d5e9e5094c5379ea12060b35a4844690226131 [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"
Edwin Törökced9ff82009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
Owen Anderson8050fa12008-07-10 01:56:35 +000029#include "llvm/ADT/DenseMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/ADT/IndexedMap.h"
Evan Cheng548bc502009-01-29 02:20:59 +000031#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Evan Chenga1d9dfb2008-02-06 19:16:53 +000034#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include <algorithm>
36using namespace llvm;
37
38STATISTIC(NumStores, "Number of stores added");
39STATISTIC(NumLoads , "Number of loads added");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040
Dan Gohman089efff2008-05-13 00:00:25 +000041static RegisterRegAlloc
Dan Gohman669b9bf2008-10-14 20:25:08 +000042 localRegAlloc("local", "local register allocator",
Dan Gohman089efff2008-05-13 00:00:25 +000043 createLocalRegisterAllocator);
44
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000046 class RALocal : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 public:
48 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +000049 RALocal() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050 private:
51 const TargetMachine *TM;
52 MachineFunction *MF;
Dan Gohman1e57df32008-02-10 18:45:23 +000053 const TargetRegisterInfo *TRI;
Owen Andersonbf15ae22008-01-07 01:35:56 +000054 const TargetInstrInfo *TII;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055
56 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
57 // values are spilled.
Evan Cheng33dc9712008-07-10 18:23:23 +000058 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059
60 // Virt2PhysRegMap - This map contains entries for each virtual register
61 // that is currently available in a physical register.
62 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
63
64 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
65 return Virt2PhysRegMap[VirtReg];
66 }
67
68 // PhysRegsUsed - This array is effectively a map, containing entries for
69 // each physical register that currently has a value (ie, it is in
70 // Virt2PhysRegMap). The value mapped to is the virtual register
71 // corresponding to the physical register (the inverse of the
72 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
73 // because it is used by a future instruction, and to -2 if it is not
74 // allocatable. If the entry for a physical register is -1, then the
75 // physical register is "not in the map".
76 //
77 std::vector<int> PhysRegsUsed;
78
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +000079 // InstrNum - Number of the current instruction. This is used for the
80 // PhysLastUse map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 //
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +000082 unsigned InstrNum;
83
84 // PhysLastUse - Store the instruction number of the last use of each physical
85 // register. This is used to find the least recently used register. when
86 // spilling.
87 //
88 std::vector<unsigned> PhysLastUse;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089
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!");
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000122 assert(Reg - TargetRegisterInfo::FirstVirtualRegister <
123 VirtRegModified.size() && "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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 void MarkPhysRegRecentlyUsed(unsigned Reg) {
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000128 PhysLastUse[Reg] = InstrNum;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 }
130
131 public:
132 virtual const char *getPassName() const {
133 return "Local Register Allocator";
134 }
135
136 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +0000137 AU.setPreservesCFG();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 AU.addRequiredID(PHIEliminationID);
139 AU.addRequiredID(TwoAddressInstructionPassID);
140 MachineFunctionPass::getAnalysisUsage(AU);
141 }
142
143 private:
144 /// runOnMachineFunction - Register allocate the whole function
145 bool runOnMachineFunction(MachineFunction &Fn);
146
147 /// AllocateBasicBlock - Register allocate the specified basic block.
148 void AllocateBasicBlock(MachineBasicBlock &MBB);
149
150
151 /// areRegsEqual - This method returns true if the specified registers are
152 /// related to each other. To do this, it checks to see if they are equal
153 /// or if the first register is in the alias set of the second register.
154 ///
155 bool areRegsEqual(unsigned R1, unsigned R2) const {
156 if (R1 == R2) return true;
Dan Gohman1e57df32008-02-10 18:45:23 +0000157 for (const unsigned *AliasSet = TRI->getAliasSet(R2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 *AliasSet; ++AliasSet) {
159 if (*AliasSet == R1) return true;
160 }
161 return false;
162 }
163
164 /// getStackSpaceFor - This returns the frame index of the specified virtual
165 /// register on the stack, allocating space if necessary.
166 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
167
168 /// removePhysReg - This method marks the specified physical register as no
169 /// longer being in use.
170 ///
171 void removePhysReg(unsigned PhysReg);
172
173 /// spillVirtReg - This method spills the value specified by PhysReg into
174 /// the virtual register slot specified by VirtReg. It then updates the RA
175 /// data structures to indicate the fact that PhysReg is now available.
176 ///
177 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
178 unsigned VirtReg, unsigned PhysReg);
179
180 /// spillPhysReg - This method spills the specified physical register into
181 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
182 /// true, then the request is ignored if the physical register does not
183 /// contain a virtual register.
184 ///
185 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
186 unsigned PhysReg, bool OnlyVirtRegs = false);
187
188 /// assignVirtToPhysReg - This method updates local state so that we know
189 /// that PhysReg is the proper container for VirtReg now. The physical
190 /// register must not be used for anything else when this is called.
191 ///
192 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
193
194 /// isPhysRegAvailable - Return true if the specified physical register is
195 /// free and available for use. This also includes checking to see if
196 /// aliased registers are all free...
197 ///
198 bool isPhysRegAvailable(unsigned PhysReg) const;
199
200 /// getFreeReg - Look to see if there is a free register available in the
201 /// specified register class. If not, return 0.
202 ///
203 unsigned getFreeReg(const TargetRegisterClass *RC);
204
205 /// getReg - Find a physical register to hold the specified virtual
206 /// register. If all compatible physical registers are used, this method
207 /// spills the last used virtual register to the stack, and uses that
Evan Cheng308d1852009-01-29 01:13:00 +0000208 /// register. If NoFree is true, that means the caller knows there isn't
209 /// a free register, do not call getFreeReg().
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng308d1852009-01-29 01:13:00 +0000211 unsigned VirtReg, bool NoFree = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212
Bob Wilsond983fb42009-05-07 21:19:45 +0000213 /// reloadVirtReg - This method transforms the specified virtual
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 /// register use to refer to a physical register. This method may do this
215 /// in one of several ways: if the register is available in a physical
216 /// register already, it uses that physical register. If the value is not
217 /// in a physical register, and if there are physical registers available,
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000218 /// it loads it into a register: PhysReg if that is an available physical
219 /// register, otherwise any physical register of the right class.
220 /// If register pressure is high, and it is possible, it tries to fold the
221 /// load of the virtual register into the instruction itself. It avoids
222 /// doing this if register pressure is low to improve the chance that
223 /// subsequent instructions can use the reloaded value. This method
224 /// returns the modified instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 ///
226 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000227 unsigned OpNum, SmallSet<unsigned, 4> &RRegs,
228 unsigned PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229
Owen Andersonff01ccf2008-07-09 20:14:53 +0000230 /// ComputeLocalLiveness - Computes liveness of registers within a basic
231 /// block, setting the killed/dead flags as appropriate.
232 void ComputeLocalLiveness(MachineBasicBlock& MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233
234 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
235 unsigned PhysReg);
236 };
237 char RALocal::ID = 0;
238}
239
240/// getStackSpaceFor - This allocates space for the specified virtual register
241/// to be held on the stack.
242int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
243 // Find the location Reg would belong...
Evan Cheng33dc9712008-07-10 18:23:23 +0000244 int SS = StackSlotForVirtReg[VirtReg];
245 if (SS != -1)
246 return SS; // Already has space allocated?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247
248 // Allocate a new stack object for this spill location...
David Greene6424ab92009-11-12 20:49:22 +0000249 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
250 RC->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000252 // Assign the slot.
Evan Cheng33dc9712008-07-10 18:23:23 +0000253 StackSlotForVirtReg[VirtReg] = FrameIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 return FrameIdx;
255}
256
257
258/// removePhysReg - This method marks the specified physical register as no
259/// longer being in use.
260///
261void RALocal::removePhysReg(unsigned PhysReg) {
262 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263}
264
265
266/// spillVirtReg - This method spills the value specified by PhysReg into the
267/// virtual register slot specified by VirtReg. It then updates the RA data
268/// structures to indicate the fact that PhysReg is now available.
269///
270void RALocal::spillVirtReg(MachineBasicBlock &MBB,
271 MachineBasicBlock::iterator I,
272 unsigned VirtReg, unsigned PhysReg) {
273 assert(VirtReg && "Spilling a physical register is illegal!"
274 " Must not have appropriate kill for the register or use exists beyond"
275 " the intended one.");
David Greene3dbc2a72010-01-05 01:26:05 +0000276 DEBUG(dbgs() << " Spilling register " << TRI->getName(PhysReg)
Bill Wendling9dcc0632009-08-22 20:38:09 +0000277 << " containing %reg" << VirtReg);
Owen Anderson81875432008-01-01 21:11:32 +0000278
Evan Chenga94efbd2008-01-17 02:08:17 +0000279 if (!isVirtRegModified(VirtReg)) {
David Greene3dbc2a72010-01-05 01:26:05 +0000280 DEBUG(dbgs() << " which has not been modified, so no store necessary!");
Evan Chenga94efbd2008-01-17 02:08:17 +0000281 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
282 if (LastUse.first)
283 LastUse.first->getOperand(LastUse.second).setIsKill();
Evan Chenga1d9dfb2008-02-06 19:16:53 +0000284 } else {
285 // Otherwise, there is a virtual register corresponding to this physical
286 // register. We only need to spill it into its stack slot if it has been
287 // modified.
Chris Lattner1b989192007-12-31 04:13:23 +0000288 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 int FrameIndex = getStackSpaceFor(VirtReg, RC);
David Greene3dbc2a72010-01-05 01:26:05 +0000290 DEBUG(dbgs() << " to stack slot #" << FrameIndex);
Evan Chenga1d9dfb2008-02-06 19:16:53 +0000291 // If the instruction reads the register that's spilled, (e.g. this can
292 // happen if it is a move to a physical register), then the spill
293 // instruction is not a kill.
Evan Chengc7daf1f2008-03-05 00:59:57 +0000294 bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
Evan Chengb4272522008-02-11 08:30:52 +0000295 TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 ++NumStores; // Update statistics
297 }
298
299 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
300
David Greene3dbc2a72010-01-05 01:26:05 +0000301 DEBUG(dbgs() << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 removePhysReg(PhysReg);
303}
304
305
306/// spillPhysReg - This method spills the specified physical register into the
307/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
308/// then the request is ignored if the physical register does not contain a
309/// virtual register.
310///
311void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
312 unsigned PhysReg, bool OnlyVirtRegs) {
313 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
314 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
315 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
316 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000317 return;
318 }
319
320 // If the selected register aliases any other registers, we must make
321 // sure that one of the aliases isn't alive.
322 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
323 *AliasSet; ++AliasSet) {
324 if (PhysRegsUsed[*AliasSet] == -1 || // Spill aliased register.
325 PhysRegsUsed[*AliasSet] == -2) // If allocatable.
326 continue;
327
328 if (PhysRegsUsed[*AliasSet])
329 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330 }
331}
332
333
334/// assignVirtToPhysReg - This method updates local state so that we know
335/// that PhysReg is the proper container for VirtReg now. The physical
336/// register must not be used for anything else when this is called.
337///
338void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
339 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
340 // Update information to note the fact that this register was just used, and
341 // it holds VirtReg.
342 PhysRegsUsed[PhysReg] = VirtReg;
343 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000344 MarkPhysRegRecentlyUsed(PhysReg); // New use of PhysReg
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345}
346
347
348/// isPhysRegAvailable - Return true if the specified physical register is free
349/// and available for use. This also includes checking to see if aliased
350/// registers are all free...
351///
352bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
353 if (PhysRegsUsed[PhysReg] != -1) return false;
354
355 // If the selected register aliases any other allocated registers, it is
356 // not free!
Dan Gohman1e57df32008-02-10 18:45:23 +0000357 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 *AliasSet; ++AliasSet)
Evan Chengf90128d2008-02-22 20:30:53 +0000359 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 return false; // Can't use this reg then.
361 return true;
362}
363
364
365/// getFreeReg - Look to see if there is a free register available in the
366/// specified register class. If not, return 0.
367///
368unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
369 // Get iterators defining the range of registers that are valid to allocate in
370 // this class, which also specifies the preferred allocation order.
371 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
372 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
373
374 for (; RI != RE; ++RI)
375 if (isPhysRegAvailable(*RI)) { // Is reg unused?
376 assert(*RI != 0 && "Cannot use register!");
377 return *RI; // Found an unused register!
378 }
379 return 0;
380}
381
382
383/// getReg - Find a physical register to hold the specified virtual
384/// register. If all compatible physical registers are used, this method spills
385/// the last used virtual register to the stack, and uses that register.
386///
387unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
Evan Cheng308d1852009-01-29 01:13:00 +0000388 unsigned VirtReg, bool NoFree) {
Chris Lattner1b989192007-12-31 04:13:23 +0000389 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390
391 // First check to see if we have a free register of the requested type...
Evan Cheng308d1852009-01-29 01:13:00 +0000392 unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000394 if (PhysReg != 0) {
395 // Assign the register.
396 assignVirtToPhysReg(VirtReg, PhysReg);
397 return PhysReg;
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000398 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000400 // Find the least recently used register in the allocation order.
401 unsigned Oldest = 0;
402 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
403 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
404 for (; RI != RE; ++RI) {
405 unsigned Age = InstrNum-PhysLastUse[*RI];
406 if (Age <= Oldest && PhysReg) continue;
407 PhysReg = *RI;
408 Oldest = Age;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 }
410
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000411 assert(PhysReg && "Physical register not assigned!?!?");
412
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000413 // Spill it to memory and reap its remains.
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000414 spillPhysReg(MBB, I, PhysReg);
415
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 // Now that we know which register we need to assign this to, do it now!
417 assignVirtToPhysReg(VirtReg, PhysReg);
418 return PhysReg;
419}
420
421
Bob Wilson219866c2009-05-07 21:20:42 +0000422/// reloadVirtReg - This method transforms the specified virtual
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423/// register use to refer to a physical register. This method may do this in
424/// one of several ways: if the register is available in a physical register
425/// already, it uses that physical register. If the value is not in a physical
426/// register, and if there are physical registers available, it loads it into a
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000427/// register: PhysReg if that is an available physical register, otherwise any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428/// register. If register pressure is high, and it is possible, it tries to
429/// fold the load of the virtual register into the instruction itself. It
430/// avoids doing this if register pressure is low to improve the chance that
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000431/// subsequent instructions can use the reloaded value. This method returns
432/// the modified instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433///
434MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng548bc502009-01-29 02:20:59 +0000435 unsigned OpNum,
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000436 SmallSet<unsigned, 4> &ReloadedRegs,
437 unsigned PhysReg) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 unsigned VirtReg = MI->getOperand(OpNum).getReg();
439
440 // If the virtual register is already available, just update the instruction
441 // and return.
442 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 MI->getOperand(OpNum).setReg(PR); // Assign the input register
Dale Johannesen55057292010-02-16 01:27:47 +0000444 if (!MI->isDebugValue()) {
445 // Do not do these for DBG_VALUE as they can affect codegen.
446 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
Dale Johannesene7dda272010-02-15 01:45:47 +0000447 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Dale Johannesen55057292010-02-16 01:27:47 +0000448 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 return MI;
450 }
451
452 // Otherwise, we need to fold it into the current instruction, or reload it.
453 // If we have registers available to hold the value, use them.
Chris Lattner1b989192007-12-31 04:13:23 +0000454 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000455 // If we already have a PhysReg (this happens when the instruction is a
456 // reg-to-reg copy with a PhysReg destination) use that.
457 if (!PhysReg || !TargetRegisterInfo::isPhysicalRegister(PhysReg) ||
458 !isPhysRegAvailable(PhysReg))
459 PhysReg = getFreeReg(RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 int FrameIndex = getStackSpaceFor(VirtReg, RC);
461
462 if (PhysReg) { // Register is available, allocate it!
463 assignVirtToPhysReg(VirtReg, PhysReg);
464 } else { // No registers available.
Evan Cheng71f91ed2008-02-07 19:46:55 +0000465 // Force some poor hapless value out of the register file to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 // make room for the new register, and reload it.
Evan Cheng308d1852009-01-29 01:13:00 +0000467 PhysReg = getReg(MBB, MI, VirtReg, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468 }
469
470 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
471
David Greene3dbc2a72010-01-05 01:26:05 +0000472 DEBUG(dbgs() << " Reloading %reg" << VirtReg << " into "
Bill Wendling9dcc0632009-08-22 20:38:09 +0000473 << TRI->getName(PhysReg) << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474
475 // Add move instruction(s)
Owen Anderson81875432008-01-01 21:11:32 +0000476 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 ++NumLoads; // Update statistics
478
Chris Lattner1b989192007-12-31 04:13:23 +0000479 MF->getRegInfo().setPhysRegUsed(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
Evan Chenga94efbd2008-01-17 02:08:17 +0000481 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Evan Cheng548bc502009-01-29 02:20:59 +0000482
483 if (!ReloadedRegs.insert(PhysReg)) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000484 std::string msg;
485 raw_string_ostream Msg(msg);
486 Msg << "Ran out of registers during register allocation!";
Chris Lattner4052b292010-02-09 19:54:29 +0000487 if (MI->isInlineAsm()) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000488 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng548bc502009-01-29 02:20:59 +0000489 << "constraints:\n";
Edwin Törökced9ff82009-07-11 13:10:19 +0000490 MI->print(Msg, TM);
Evan Cheng548bc502009-01-29 02:20:59 +0000491 }
Chris Lattner8316f2d2010-04-07 22:58:41 +0000492 report_fatal_error(Msg.str());
Evan Cheng548bc502009-01-29 02:20:59 +0000493 }
494 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
495 *SubRegs; ++SubRegs) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000496 if (ReloadedRegs.insert(*SubRegs)) continue;
497
498 std::string msg;
499 raw_string_ostream Msg(msg);
500 Msg << "Ran out of registers during register allocation!";
501 if (MI->isInlineAsm()) {
502 Msg << "\nPlease check your inline asm statement for invalid "
503 << "constraints:\n";
504 MI->print(Msg, TM);
Evan Cheng548bc502009-01-29 02:20:59 +0000505 }
Chris Lattner8316f2d2010-04-07 22:58:41 +0000506 report_fatal_error(Msg.str());
Evan Cheng548bc502009-01-29 02:20:59 +0000507 }
508
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 return MI;
510}
511
512/// isReadModWriteImplicitKill - True if this is an implicit kill for a
513/// read/mod/write register, i.e. update partial register.
514static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
515 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000516 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000517 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 MO.isDef() && !MO.isDead())
519 return true;
520 }
521 return false;
522}
523
524/// isReadModWriteImplicitDef - True if this is an implicit def for a
525/// read/mod/write register, i.e. update partial register.
526static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
527 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000528 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000529 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 !MO.isDef() && MO.isKill())
531 return true;
532 }
533 return false;
534}
535
Owen Anderson9196a392008-07-08 22:24:50 +0000536// precedes - Helper function to determine with MachineInstr A
537// precedes MachineInstr B within the same MBB.
538static bool precedes(MachineBasicBlock::iterator A,
539 MachineBasicBlock::iterator B) {
540 if (A == B)
541 return false;
542
543 MachineBasicBlock::iterator I = A->getParent()->begin();
544 while (I != A->getParent()->end()) {
545 if (I == A)
546 return true;
547 else if (I == B)
548 return false;
549
550 ++I;
551 }
552
553 return false;
554}
555
Owen Andersonff01ccf2008-07-09 20:14:53 +0000556/// ComputeLocalLiveness - Computes liveness of registers within a basic
557/// block, setting the killed/dead flags as appropriate.
558void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000559 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
Owen Anderson9196a392008-07-08 22:24:50 +0000560 // Keep track of the most recently seen previous use or def of each reg,
561 // so that we can update them with dead/kill markers.
Owen Anderson8050fa12008-07-10 01:56:35 +0000562 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
Owen Anderson9196a392008-07-08 22:24:50 +0000563 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
564 I != E; ++I) {
Dale Johannesene7dda272010-02-15 01:45:47 +0000565 if (I->isDebugValue())
566 continue;
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000567
Owen Anderson9196a392008-07-08 22:24:50 +0000568 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000569 MachineOperand &MO = I->getOperand(i);
Owen Anderson9196a392008-07-08 22:24:50 +0000570 // Uses don't trigger any flags, but we need to save
571 // them for later. Also, we have to process these
572 // _before_ processing the defs, since an instr
573 // uses regs before it defs them.
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000574 if (!MO.isReg() || !MO.getReg() || !MO.isUse())
575 continue;
576
577 LastUseDef[MO.getReg()] = std::make_pair(I, i);
578
579 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) continue;
580
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000581 for (const unsigned *A = TRI->getAliasSet(MO.getReg()); *A; ++A) {
582 std::pair<MachineInstr*, unsigned> &LUD = LastUseDef[*A];
583 if (LUD.first != I)
584 LUD = std::make_pair(I, i);
Owen Andersona4d28702008-10-08 04:30:51 +0000585 }
Owen Anderson9196a392008-07-08 22:24:50 +0000586 }
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000587
Owen Anderson9196a392008-07-08 22:24:50 +0000588 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000589 MachineOperand &MO = I->getOperand(i);
Owen Anderson9196a392008-07-08 22:24:50 +0000590 // Defs others than 2-addr redefs _do_ trigger flag changes:
591 // - A def followed by a def is dead
592 // - A use followed by a def is a kill
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000593 if (!MO.isReg() || !MO.getReg() || !MO.isDef()) continue;
594
595 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
596 last = LastUseDef.find(MO.getReg());
597 if (last != LastUseDef.end()) {
598 // Check if this is a two address instruction. If so, then
599 // the def does not kill the use.
600 if (last->second.first == I &&
601 I->isRegTiedToUseOperand(i))
602 continue;
Owen Anderson9196a392008-07-08 22:24:50 +0000603
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000604 MachineOperand &lastUD =
605 last->second.first->getOperand(last->second.second);
606 if (lastUD.isDef())
607 lastUD.setIsDead(true);
608 else
609 lastUD.setIsKill(true);
Owen Anderson9196a392008-07-08 22:24:50 +0000610 }
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000611
612 LastUseDef[MO.getReg()] = std::make_pair(I, i);
Owen Anderson9196a392008-07-08 22:24:50 +0000613 }
614 }
615
616 // Live-out (of the function) registers contain return values of the function,
617 // so we need to make sure they are alive at return time.
Bill Wendling617d39e2010-03-16 02:01:51 +0000618 MachineBasicBlock::iterator Ret = MBB.getFirstTerminator();
619 bool BBEndsInReturn = (Ret != MBB.end() && Ret->getDesc().isReturn());
620
621 if (BBEndsInReturn)
Owen Anderson9196a392008-07-08 22:24:50 +0000622 for (MachineRegisterInfo::liveout_iterator
623 I = MF->getRegInfo().liveout_begin(),
624 E = MF->getRegInfo().liveout_end(); I != E; ++I)
625 if (!Ret->readsRegister(*I)) {
626 Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
627 LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
628 }
Owen Anderson9196a392008-07-08 22:24:50 +0000629
630 // Finally, loop over the final use/def of each reg
631 // in the block and determine if it is dead.
Owen Anderson8050fa12008-07-10 01:56:35 +0000632 for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Owen Anderson9196a392008-07-08 22:24:50 +0000633 I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000634 MachineInstr *MI = I->second.first;
Owen Anderson9196a392008-07-08 22:24:50 +0000635 unsigned idx = I->second.second;
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000636 MachineOperand &MO = MI->getOperand(idx);
Owen Anderson9196a392008-07-08 22:24:50 +0000637
638 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
639
640 // A crude approximation of "live-out" calculation
641 bool usedOutsideBlock = isPhysReg ? false :
642 UsedInMultipleBlocks.test(MO.getReg() -
643 TargetRegisterInfo::FirstVirtualRegister);
Bill Wendling5c3a53f2010-03-16 01:05:35 +0000644
645 // If the machine BB ends in a return instruction, then the value isn't used
646 // outside of the BB.
647 if (!isPhysReg && (!usedOutsideBlock || BBEndsInReturn)) {
Dale Johannesen55057292010-02-16 01:27:47 +0000648 // DBG_VALUE complicates this: if the only refs of a register outside
649 // this block are DBG_VALUE, we can't keep the reg live just for that,
650 // as it will cause the reg to be spilled at the end of this block when
651 // it wouldn't have been otherwise. Nullify the DBG_VALUEs when that
652 // happens.
653 bool UsedByDebugValueOnly = false;
Owen Anderson9196a392008-07-08 22:24:50 +0000654 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
Bill Wendling5c3a53f2010-03-16 01:05:35 +0000655 UE = MRI.reg_end(); UI != UE; ++UI) {
Owen Anderson9196a392008-07-08 22:24:50 +0000656 // Two cases:
657 // - used in another block
658 // - used in the same block before it is defined (loop)
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000659 if (UI->getParent() == &MBB &&
660 !(MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI)))
661 continue;
662
663 if (UI->isDebugValue()) {
664 UsedByDebugValueOnly = true;
665 continue;
Owen Anderson9196a392008-07-08 22:24:50 +0000666 }
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000667
668 // A non-DBG_VALUE use means we can leave DBG_VALUE uses alone.
669 UsedInMultipleBlocks.set(MO.getReg() -
670 TargetRegisterInfo::FirstVirtualRegister);
671 usedOutsideBlock = true;
672 UsedByDebugValueOnly = false;
673 break;
Bill Wendling5c3a53f2010-03-16 01:05:35 +0000674 }
675
Dale Johannesen55057292010-02-16 01:27:47 +0000676 if (UsedByDebugValueOnly)
677 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
678 UE = MRI.reg_end(); UI != UE; ++UI)
679 if (UI->isDebugValue() &&
680 (UI->getParent() != &MBB ||
681 (MO.isDef() && precedes(&*UI, MI))))
682 UI.getOperand().setReg(0U);
683 }
684
Bill Wendling5c3a53f2010-03-16 01:05:35 +0000685 // Physical registers and those that are not live-out of the block are
686 // killed/dead at their last use/def within this block.
Dan Gohman35922002010-03-18 18:07:13 +0000687 if (isPhysReg || !usedOutsideBlock || BBEndsInReturn) {
Dan Gohmanec06ecd2008-10-04 00:31:14 +0000688 if (MO.isUse()) {
689 // Don't mark uses that are tied to defs as kills.
Evan Cheng48555e82009-03-19 20:30:06 +0000690 if (!MI->isRegTiedToDefOperand(idx))
Dan Gohmanec06ecd2008-10-04 00:31:14 +0000691 MO.setIsKill(true);
Bill Wendling5c3a53f2010-03-16 01:05:35 +0000692 } else {
Owen Anderson9196a392008-07-08 22:24:50 +0000693 MO.setIsDead(true);
Bill Wendling5c3a53f2010-03-16 01:05:35 +0000694 }
Dan Gohman35922002010-03-18 18:07:13 +0000695 }
Owen Anderson9196a392008-07-08 22:24:50 +0000696 }
Owen Andersonff01ccf2008-07-09 20:14:53 +0000697}
698
699void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
700 // loop over each instruction
701 MachineBasicBlock::iterator MII = MBB.begin();
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000702
Bill Wendling9dcc0632009-08-22 20:38:09 +0000703 DEBUG({
704 const BasicBlock *LBB = MBB.getBasicBlock();
705 if (LBB)
David Greene3dbc2a72010-01-05 01:26:05 +0000706 dbgs() << "\nStarting RegAlloc of BB: " << LBB->getName();
Bill Wendling9dcc0632009-08-22 20:38:09 +0000707 });
Owen Andersonff01ccf2008-07-09 20:14:53 +0000708
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000709 // Add live-in registers as active.
710 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
Owen Andersonff01ccf2008-07-09 20:14:53 +0000711 E = MBB.livein_end(); I != E; ++I) {
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000712 unsigned Reg = *I;
713 MF->getRegInfo().setPhysRegUsed(Reg);
714 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000715 MarkPhysRegRecentlyUsed(Reg);
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000716 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
717 *SubRegs; ++SubRegs) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000718 if (PhysRegsUsed[*SubRegs] == -2) continue;
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000719 MarkPhysRegRecentlyUsed(*SubRegs);
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000720 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
721 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000722 }
Owen Andersonff01ccf2008-07-09 20:14:53 +0000723 }
724
725 ComputeLocalLiveness(MBB);
Owen Anderson9196a392008-07-08 22:24:50 +0000726
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 // Otherwise, sequentially allocate each instruction in the MBB.
728 while (MII != MBB.end()) {
729 MachineInstr *MI = MII++;
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000730 ++InstrNum;
Chris Lattner5b930372008-01-07 07:27:27 +0000731 const TargetInstrDesc &TID = MI->getDesc();
Bill Wendling9dcc0632009-08-22 20:38:09 +0000732 DEBUG({
David Greene3dbc2a72010-01-05 01:26:05 +0000733 dbgs() << "\nStarting RegAlloc of: " << *MI;
734 dbgs() << " Regs have values: ";
Bill Wendling9dcc0632009-08-22 20:38:09 +0000735 for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
736 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
David Greene3dbc2a72010-01-05 01:26:05 +0000737 dbgs() << "[" << TRI->getName(i)
Bill Wendling9dcc0632009-08-22 20:38:09 +0000738 << ",%reg" << PhysRegsUsed[i] << "] ";
David Greene3dbc2a72010-01-05 01:26:05 +0000739 dbgs() << '\n';
Bill Wendling9dcc0632009-08-22 20:38:09 +0000740 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000742 // Determine whether this is a copy instruction. The cases where the
743 // source or destination are phys regs are handled specially.
744 unsigned SrcCopyReg, DstCopyReg, SrcCopySubReg, DstCopySubReg;
Dale Johannesenda4d84a2010-02-03 01:40:33 +0000745 unsigned SrcCopyPhysReg = 0U;
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000746 bool isCopy = TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
747 SrcCopySubReg, DstCopySubReg);
Dale Johannesenda4d84a2010-02-03 01:40:33 +0000748 if (isCopy && TargetRegisterInfo::isVirtualRegister(SrcCopyReg))
749 SrcCopyPhysReg = getVirt2PhysRegMapSlot(SrcCopyReg);
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000750
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 // Loop over the implicit uses, making sure that they are at the head of the
752 // use order list, so they don't get reallocated.
753 if (TID.ImplicitUses) {
754 for (const unsigned *ImplicitUses = TID.ImplicitUses;
755 *ImplicitUses; ++ImplicitUses)
756 MarkPhysRegRecentlyUsed(*ImplicitUses);
757 }
758
759 SmallVector<unsigned, 8> Kills;
760 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000761 MachineOperand &MO = MI->getOperand(i);
762 if (!MO.isReg() || !MO.isKill()) continue;
763
764 if (!MO.isImplicit())
765 Kills.push_back(MO.getReg());
766 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
767 // These are extra physical register kills when a sub-register
768 // is defined (def of a sub-register is a read/mod/write of the
769 // larger registers). Ignore.
770 Kills.push_back(MO.getReg());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 }
772
Dale Johannesen47e30e42008-09-24 23:13:09 +0000773 // If any physical regs are earlyclobber, spill any value they might
774 // have in them, then mark them unallocatable.
775 // If any virtual regs are earlyclobber, allocate them now (before
776 // freeing inputs that are killed).
Chris Lattner4052b292010-02-09 19:54:29 +0000777 if (MI->isInlineAsm()) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000778 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
779 MachineOperand &MO = MI->getOperand(i);
780 if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber() ||
781 !MO.getReg())
782 continue;
783
784 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
785 unsigned DestVirtReg = MO.getReg();
786 unsigned DestPhysReg;
Dale Johannesen47e30e42008-09-24 23:13:09 +0000787
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000788 // If DestVirtReg already has a value, use it.
789 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
790 DestPhysReg = getReg(MBB, MI, DestVirtReg);
791 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
792 markVirtRegModified(DestVirtReg);
793 getVirtRegLastUse(DestVirtReg) =
794 std::make_pair((MachineInstr*)0, 0);
795 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
796 << " to %reg" << DestVirtReg << "\n");
797 MO.setReg(DestPhysReg); // Assign the earlyclobber register
798 } else {
799 unsigned Reg = MO.getReg();
800 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
801 // These are extra physical register defs when a sub-register
802 // is defined (def of a sub-register is a read/mod/write of the
803 // larger registers). Ignore.
804 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
Dale Johannesen47e30e42008-09-24 23:13:09 +0000805
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000806 MF->getRegInfo().setPhysRegUsed(Reg);
807 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
808 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000809 MarkPhysRegRecentlyUsed(Reg);
Dale Johannesen47e30e42008-09-24 23:13:09 +0000810
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000811 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
812 *SubRegs; ++SubRegs) {
813 if (PhysRegsUsed[*SubRegs] == -2) continue;
814 MF->getRegInfo().setPhysRegUsed(*SubRegs);
815 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000816 MarkPhysRegRecentlyUsed(*SubRegs);
Dale Johannesen47e30e42008-09-24 23:13:09 +0000817 }
818 }
819 }
820 }
821
Dale Johannesene186ea02010-02-10 00:11:11 +0000822 // If a DBG_VALUE says something is located in a spilled register,
823 // change the DBG_VALUE to be undef, which prevents the register
Dale Johannesen3940d842010-01-30 00:57:47 +0000824 // from being reloaded here. Doing that would change the generated
825 // code, unless another use immediately follows this instruction.
Chris Lattner4052b292010-02-09 19:54:29 +0000826 if (MI->isDebugValue() &&
Dale Johannesen3940d842010-01-30 00:57:47 +0000827 MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
828 unsigned VirtReg = MI->getOperand(0).getReg();
829 if (VirtReg && TargetRegisterInfo::isVirtualRegister(VirtReg) &&
830 !getVirt2PhysRegMapSlot(VirtReg))
831 MI->getOperand(0).setReg(0U);
832 }
833
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 // Get the used operands into registers. This has the potential to spill
835 // incoming values if we are out of registers. Note that we completely
836 // ignore physical register uses here. We assume that if an explicit
837 // physical register is referenced by the instruction, that it is guaranteed
838 // to be live-in, or the input is badly hosed.
839 //
Evan Cheng548bc502009-01-29 02:20:59 +0000840 SmallSet<unsigned, 4> ReloadedRegs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000842 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 // here we are looking for only used operands (never def&use)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000844 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000845 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Dale Johannesen5d25f9b2009-12-16 00:29:41 +0000846 MI = reloadVirtReg(MBB, MI, i, ReloadedRegs,
847 isCopy ? DstCopyReg : 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 }
849
850 // If this instruction is the last user of this register, kill the
851 // value, freeing the register being used, so it doesn't need to be
852 // spilled to memory.
853 //
854 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
855 unsigned VirtReg = Kills[i];
856 unsigned PhysReg = VirtReg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000857 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 // If the virtual register was never materialized into a register, it
859 // might not be in the map, but it won't hurt to zero it out anyway.
860 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
861 PhysReg = PhysRegSlot;
862 PhysRegSlot = 0;
863 } else if (PhysRegsUsed[PhysReg] == -2) {
864 // Unallocatable register dead, ignore.
865 continue;
866 } else {
Evan Cheng358d8dd2007-10-22 19:42:28 +0000867 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 "Silently clearing a virtual register?");
869 }
870
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000871 if (!PhysReg) continue;
872
873 DEBUG(dbgs() << " Last use of " << TRI->getName(PhysReg)
874 << "[%reg" << VirtReg <<"], removing it from live set\n");
875 removePhysReg(PhysReg);
876 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
877 *SubRegs; ++SubRegs) {
878 if (PhysRegsUsed[*SubRegs] != -2) {
879 DEBUG(dbgs() << " Last use of "
880 << TRI->getName(*SubRegs) << "[%reg" << VirtReg
881 <<"], removing it from live set\n");
882 removePhysReg(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000883 }
884 }
885 }
886
887 // Loop over all of the operands of the instruction, spilling registers that
888 // are defined, and marking explicit destinations in the PhysRegsUsed map.
889 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000890 MachineOperand &MO = MI->getOperand(i);
891 if (!MO.isReg() || !MO.isDef() || MO.isImplicit() || !MO.getReg() ||
892 MO.isEarlyClobber() ||
893 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
894 continue;
895
896 unsigned Reg = MO.getReg();
897 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
898 // These are extra physical register defs when a sub-register
899 // is defined (def of a sub-register is a read/mod/write of the
900 // larger registers). Ignore.
901 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000903 MF->getRegInfo().setPhysRegUsed(Reg);
904 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
905 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000906 MarkPhysRegRecentlyUsed(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000908 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
909 *SubRegs; ++SubRegs) {
910 if (PhysRegsUsed[*SubRegs] == -2) continue;
911
912 MF->getRegInfo().setPhysRegUsed(*SubRegs);
913 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000914 MarkPhysRegRecentlyUsed(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 }
916 }
917
918 // Loop over the implicit defs, spilling them as well.
919 if (TID.ImplicitDefs) {
920 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
921 *ImplicitDefs; ++ImplicitDefs) {
922 unsigned Reg = *ImplicitDefs;
923 if (PhysRegsUsed[Reg] != -2) {
924 spillPhysReg(MBB, MI, Reg, true);
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000925 MarkPhysRegRecentlyUsed(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 PhysRegsUsed[Reg] = 0; // It is free and reserved now
927 }
Chris Lattner1b989192007-12-31 04:13:23 +0000928 MF->getRegInfo().setPhysRegUsed(Reg);
Evan Cheng548bc502009-01-29 02:20:59 +0000929 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
930 *SubRegs; ++SubRegs) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000931 if (PhysRegsUsed[*SubRegs] == -2) continue;
932
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +0000933 MarkPhysRegRecentlyUsed(*SubRegs);
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000934 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
935 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936 }
937 }
938 }
939
940 SmallVector<unsigned, 8> DeadDefs;
941 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000942 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000943 if (MO.isReg() && MO.isDead())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 DeadDefs.push_back(MO.getReg());
945 }
946
947 // Okay, we have allocated all of the source operands and spilled any values
948 // that would be destroyed by defs of this instruction. Loop over the
949 // explicit defs and assign them to a register, spilling incoming values if
950 // we need to scavenge a register.
951 //
952 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000953 MachineOperand &MO = MI->getOperand(i);
954 if (!MO.isReg() || !MO.isDef() || !MO.getReg() ||
955 MO.isEarlyClobber() ||
956 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
957 continue;
958
959 unsigned DestVirtReg = MO.getReg();
960 unsigned DestPhysReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000962 // If DestVirtReg already has a value, use it.
963 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg))) {
964 // If this is a copy try to reuse the input as the output;
965 // that will make the copy go away.
966 // If this is a copy, the source reg is a phys reg, and
967 // that reg is available, use that phys reg for DestPhysReg.
968 // If this is a copy, the source reg is a virtual reg, and
969 // the phys reg that was assigned to that virtual reg is now
970 // available, use that phys reg for DestPhysReg. (If it's now
971 // available that means this was the last use of the source.)
972 if (isCopy &&
973 TargetRegisterInfo::isPhysicalRegister(SrcCopyReg) &&
974 isPhysRegAvailable(SrcCopyReg)) {
975 DestPhysReg = SrcCopyReg;
976 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
977 } else if (isCopy &&
978 TargetRegisterInfo::isVirtualRegister(SrcCopyReg) &&
979 SrcCopyPhysReg && isPhysRegAvailable(SrcCopyPhysReg) &&
980 MF->getRegInfo().getRegClass(DestVirtReg)->
981 contains(SrcCopyPhysReg)) {
982 DestPhysReg = SrcCopyPhysReg;
983 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
984 } else
985 DestPhysReg = getReg(MBB, MI, DestVirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 }
Chris Lattnera7ea0fb2010-03-31 05:15:22 +0000987 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
988 markVirtRegModified(DestVirtReg);
989 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
990 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
991 << " to %reg" << DestVirtReg << "\n");
992 MO.setReg(DestPhysReg); // Assign the output register
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 }
994
995 // If this instruction defines any registers that are immediately dead,
996 // kill them now.
997 //
998 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
999 unsigned VirtReg = DeadDefs[i];
1000 unsigned PhysReg = VirtReg;
Dan Gohman1e57df32008-02-10 18:45:23 +00001001 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
1003 PhysReg = PhysRegSlot;
1004 assert(PhysReg != 0);
1005 PhysRegSlot = 0;
1006 } else if (PhysRegsUsed[PhysReg] == -2) {
1007 // Unallocatable register dead, ignore.
1008 continue;
Chris Lattnera7ea0fb2010-03-31 05:15:22 +00001009 } else if (!PhysReg)
1010 continue;
1011
1012 DEBUG(dbgs() << " Register " << TRI->getName(PhysReg)
1013 << " [%reg" << VirtReg
1014 << "] is never used, removing it from live set\n");
1015 removePhysReg(PhysReg);
1016 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
1017 *AliasSet; ++AliasSet) {
1018 if (PhysRegsUsed[*AliasSet] != -2) {
1019 DEBUG(dbgs() << " Register " << TRI->getName(*AliasSet)
1020 << " [%reg" << *AliasSet
1021 << "] is never used, removing it from live set\n");
1022 removePhysReg(*AliasSet);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 }
1024 }
1025 }
1026
Bob Wilsona43eb6b2009-05-07 23:47:03 +00001027 // Finally, if this is a noop copy instruction, zap it. (Except that if
1028 // the copy is dead, it must be kept to avoid messing up liveness info for
1029 // the register scavenger. See pr4100.)
Dale Johannesen5d25f9b2009-12-16 00:29:41 +00001030 if (TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
1031 SrcCopySubReg, DstCopySubReg) &&
1032 SrcCopyReg == DstCopyReg && DeadDefs.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 MBB.erase(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 }
1035
1036 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1037
1038 // Spill all physical registers holding virtual registers now.
Dan Gohman1e57df32008-02-10 18:45:23 +00001039 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001040 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 if (unsigned VirtReg = PhysRegsUsed[i])
1042 spillVirtReg(MBB, MI, VirtReg, i);
1043 else
1044 removePhysReg(i);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001045 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
1047#if 0
1048 // This checking code is very expensive.
1049 bool AllOk = true;
Dan Gohman1e57df32008-02-10 18:45:23 +00001050 for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
Chris Lattner1b989192007-12-31 04:13:23 +00001051 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 if (unsigned PR = Virt2PhysRegMap[i]) {
1053 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
1054 AllOk = false;
1055 }
1056 assert(AllOk && "Virtual registers still in phys regs?");
1057#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058}
1059
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060/// runOnMachineFunction - Register allocate the whole function
1061///
1062bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
David Greene3dbc2a72010-01-05 01:26:05 +00001063 DEBUG(dbgs() << "Machine Function\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 MF = &Fn;
1065 TM = &Fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +00001066 TRI = TM->getRegisterInfo();
Owen Andersonbf15ae22008-01-07 01:35:56 +00001067 TII = TM->getInstrInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068
Dan Gohman1e57df32008-02-10 18:45:23 +00001069 PhysRegsUsed.assign(TRI->getNumRegs(), -1);
Jakob Stoklund Olesen2de80f52010-04-16 23:32:37 +00001070 InstrNum = 0;
1071 PhysLastUse.assign(TRI->getNumRegs(), 0);
1072
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 // At various places we want to efficiently check to see whether a register
1074 // is allocatable. To handle this, we mark all unallocatable registers as
1075 // being pinned down, permanently.
1076 {
Dan Gohman1e57df32008-02-10 18:45:23 +00001077 BitVector Allocable = TRI->getAllocatableSet(Fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
1079 if (!Allocable[i])
1080 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
1081 }
1082
1083 // initialize the virtual->physical register map to have a 'null'
1084 // mapping for all virtual registers
Evan Cheng9e66d8c2008-01-17 00:35:26 +00001085 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
Evan Cheng33dc9712008-07-10 18:23:23 +00001086 StackSlotForVirtReg.grow(LastVirtReg);
Evan Cheng9e66d8c2008-01-17 00:35:26 +00001087 Virt2PhysRegMap.grow(LastVirtReg);
Evan Chenga94efbd2008-01-17 02:08:17 +00001088 Virt2LastUseMap.grow(LastVirtReg);
Chris Lattnera7ea0fb2010-03-31 05:15:22 +00001089 VirtRegModified.resize(LastVirtReg+1 -
1090 TargetRegisterInfo::FirstVirtualRegister);
1091 UsedInMultipleBlocks.resize(LastVirtReg+1 -
1092 TargetRegisterInfo::FirstVirtualRegister);
Owen Anderson9196a392008-07-08 22:24:50 +00001093
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 // Loop over all of the basic blocks, eliminating virtual register references
1095 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
1096 MBB != MBBe; ++MBB)
1097 AllocateBasicBlock(*MBB);
1098
1099 StackSlotForVirtReg.clear();
1100 PhysRegsUsed.clear();
1101 VirtRegModified.clear();
Owen Anderson9196a392008-07-08 22:24:50 +00001102 UsedInMultipleBlocks.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 Virt2PhysRegMap.clear();
Evan Chenga94efbd2008-01-17 02:08:17 +00001104 Virt2LastUseMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 return true;
1106}
1107
1108FunctionPass *llvm::createLocalRegisterAllocator() {
1109 return new RALocal();
1110}