blob: 7bb020a65e7e369f2fba3d46d7cd84701fc9268e [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
79 // PhysRegsUseOrder - This contains a list of the physical registers that
80 // currently have a virtual register value in them. This list provides an
81 // ordering of registers, imposing a reallocation order. This list is only
82 // used if all registers are allocated and we have to spill one, in which
83 // case we spill the least recently used register. Entries at the front of
84 // the list are the least recently used registers, entries at the back are
85 // the most recently used.
86 //
87 std::vector<unsigned> PhysRegsUseOrder;
88
Evan Chenga94efbd2008-01-17 02:08:17 +000089 // Virt2LastUseMap - This maps each virtual register to its last use
90 // (MachineInstr*, operand index pair).
91 IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
92 Virt2LastUseMap;
93
94 std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
Dan Gohman1e57df32008-02-10 18:45:23 +000095 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
Evan Chenga94efbd2008-01-17 02:08:17 +000096 return Virt2LastUseMap[Reg];
97 }
98
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099 // VirtRegModified - This bitset contains information about which virtual
100 // registers need to be spilled back to memory when their registers are
101 // scavenged. If a virtual register has simply been rematerialized, there
102 // is no reason to spill it to memory when we need the register back.
103 //
Evan Cheng9e66d8c2008-01-17 00:35:26 +0000104 BitVector VirtRegModified;
Owen Anderson9196a392008-07-08 22:24:50 +0000105
106 // UsedInMultipleBlocks - Tracks whether a particular register is used in
107 // more than one block.
108 BitVector UsedInMultipleBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109
110 void markVirtRegModified(unsigned Reg, bool Val = true) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000111 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
112 Reg -= TargetRegisterInfo::FirstVirtualRegister;
Evan Cheng9e66d8c2008-01-17 00:35:26 +0000113 if (Val)
114 VirtRegModified.set(Reg);
115 else
116 VirtRegModified.reset(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 }
118
119 bool isVirtRegModified(unsigned Reg) const {
Dan Gohman1e57df32008-02-10 18:45:23 +0000120 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
121 assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 && "Illegal virtual register!");
Dan Gohman1e57df32008-02-10 18:45:23 +0000123 return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124 }
125
126 void AddToPhysRegsUseOrder(unsigned Reg) {
127 std::vector<unsigned>::iterator It =
128 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
129 if (It != PhysRegsUseOrder.end())
130 PhysRegsUseOrder.erase(It);
131 PhysRegsUseOrder.push_back(Reg);
132 }
133
134 void MarkPhysRegRecentlyUsed(unsigned Reg) {
135 if (PhysRegsUseOrder.empty() ||
136 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
137
138 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
139 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
140 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
141 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
142 // Add it to the end of the list
143 PhysRegsUseOrder.push_back(RegMatch);
144 if (RegMatch == Reg)
145 return; // Found an exact match, exit early
146 }
147 }
148
149 public:
150 virtual const char *getPassName() const {
151 return "Local Register Allocator";
152 }
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +0000155 AU.setPreservesCFG();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 AU.addRequiredID(PHIEliminationID);
157 AU.addRequiredID(TwoAddressInstructionPassID);
158 MachineFunctionPass::getAnalysisUsage(AU);
159 }
160
161 private:
162 /// runOnMachineFunction - Register allocate the whole function
163 bool runOnMachineFunction(MachineFunction &Fn);
164
165 /// AllocateBasicBlock - Register allocate the specified basic block.
166 void AllocateBasicBlock(MachineBasicBlock &MBB);
167
168
169 /// areRegsEqual - This method returns true if the specified registers are
170 /// related to each other. To do this, it checks to see if they are equal
171 /// or if the first register is in the alias set of the second register.
172 ///
173 bool areRegsEqual(unsigned R1, unsigned R2) const {
174 if (R1 == R2) return true;
Dan Gohman1e57df32008-02-10 18:45:23 +0000175 for (const unsigned *AliasSet = TRI->getAliasSet(R2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 *AliasSet; ++AliasSet) {
177 if (*AliasSet == R1) return true;
178 }
179 return false;
180 }
181
182 /// getStackSpaceFor - This returns the frame index of the specified virtual
183 /// register on the stack, allocating space if necessary.
184 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
185
186 /// removePhysReg - This method marks the specified physical register as no
187 /// longer being in use.
188 ///
189 void removePhysReg(unsigned PhysReg);
190
191 /// spillVirtReg - This method spills the value specified by PhysReg into
192 /// the virtual register slot specified by VirtReg. It then updates the RA
193 /// data structures to indicate the fact that PhysReg is now available.
194 ///
195 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
196 unsigned VirtReg, unsigned PhysReg);
197
198 /// spillPhysReg - This method spills the specified physical register into
199 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
200 /// true, then the request is ignored if the physical register does not
201 /// contain a virtual register.
202 ///
203 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
204 unsigned PhysReg, bool OnlyVirtRegs = false);
205
206 /// assignVirtToPhysReg - This method updates local state so that we know
207 /// that PhysReg is the proper container for VirtReg now. The physical
208 /// register must not be used for anything else when this is called.
209 ///
210 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
211
212 /// isPhysRegAvailable - Return true if the specified physical register is
213 /// free and available for use. This also includes checking to see if
214 /// aliased registers are all free...
215 ///
216 bool isPhysRegAvailable(unsigned PhysReg) const;
217
218 /// getFreeReg - Look to see if there is a free register available in the
219 /// specified register class. If not, return 0.
220 ///
221 unsigned getFreeReg(const TargetRegisterClass *RC);
222
223 /// getReg - Find a physical register to hold the specified virtual
224 /// register. If all compatible physical registers are used, this method
225 /// spills the last used virtual register to the stack, and uses that
Evan Cheng308d1852009-01-29 01:13:00 +0000226 /// register. If NoFree is true, that means the caller knows there isn't
227 /// a free register, do not call getFreeReg().
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng308d1852009-01-29 01:13:00 +0000229 unsigned VirtReg, bool NoFree = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230
Bob Wilsond983fb42009-05-07 21:19:45 +0000231 /// reloadVirtReg - This method transforms the specified virtual
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 /// register use to refer to a physical register. This method may do this
233 /// in one of several ways: if the register is available in a physical
234 /// register already, it uses that physical register. If the value is not
235 /// in a physical register, and if there are physical registers available,
236 /// it loads it into a register. If register pressure is high, and it is
237 /// possible, it tries to fold the load of the virtual register into the
238 /// instruction itself. It avoids doing this if register pressure is low to
239 /// improve the chance that subsequent instructions can use the reloaded
240 /// value. This method returns the modified instruction.
241 ///
242 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng548bc502009-01-29 02:20:59 +0000243 unsigned OpNum, SmallSet<unsigned, 4> &RRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244
Owen Andersonff01ccf2008-07-09 20:14:53 +0000245 /// ComputeLocalLiveness - Computes liveness of registers within a basic
246 /// block, setting the killed/dead flags as appropriate.
247 void ComputeLocalLiveness(MachineBasicBlock& MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248
249 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
250 unsigned PhysReg);
251 };
252 char RALocal::ID = 0;
253}
254
255/// getStackSpaceFor - This allocates space for the specified virtual register
256/// to be held on the stack.
257int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
258 // Find the location Reg would belong...
Evan Cheng33dc9712008-07-10 18:23:23 +0000259 int SS = StackSlotForVirtReg[VirtReg];
260 if (SS != -1)
261 return SS; // Already has space allocated?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262
263 // Allocate a new stack object for this spill location...
David Greene6424ab92009-11-12 20:49:22 +0000264 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
265 RC->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266
267 // Assign the slot...
Evan Cheng33dc9712008-07-10 18:23:23 +0000268 StackSlotForVirtReg[VirtReg] = FrameIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 return FrameIdx;
270}
271
272
273/// removePhysReg - This method marks the specified physical register as no
274/// longer being in use.
275///
276void RALocal::removePhysReg(unsigned PhysReg) {
277 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
278
279 std::vector<unsigned>::iterator It =
280 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
281 if (It != PhysRegsUseOrder.end())
282 PhysRegsUseOrder.erase(It);
283}
284
285
286/// spillVirtReg - This method spills the value specified by PhysReg into the
287/// virtual register slot specified by VirtReg. It then updates the RA data
288/// structures to indicate the fact that PhysReg is now available.
289///
290void RALocal::spillVirtReg(MachineBasicBlock &MBB,
291 MachineBasicBlock::iterator I,
292 unsigned VirtReg, unsigned PhysReg) {
293 assert(VirtReg && "Spilling a physical register is illegal!"
294 " Must not have appropriate kill for the register or use exists beyond"
295 " the intended one.");
Bill Wendling9dcc0632009-08-22 20:38:09 +0000296 DEBUG(errs() << " Spilling register " << TRI->getName(PhysReg)
297 << " containing %reg" << VirtReg);
Owen Anderson81875432008-01-01 21:11:32 +0000298
Evan Chenga94efbd2008-01-17 02:08:17 +0000299 if (!isVirtRegModified(VirtReg)) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000300 DEBUG(errs() << " which has not been modified, so no store necessary!");
Evan Chenga94efbd2008-01-17 02:08:17 +0000301 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
302 if (LastUse.first)
303 LastUse.first->getOperand(LastUse.second).setIsKill();
Evan Chenga1d9dfb2008-02-06 19:16:53 +0000304 } else {
305 // Otherwise, there is a virtual register corresponding to this physical
306 // register. We only need to spill it into its stack slot if it has been
307 // modified.
Chris Lattner1b989192007-12-31 04:13:23 +0000308 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 int FrameIndex = getStackSpaceFor(VirtReg, RC);
Bill Wendling9dcc0632009-08-22 20:38:09 +0000310 DEBUG(errs() << " to stack slot #" << FrameIndex);
Evan Chenga1d9dfb2008-02-06 19:16:53 +0000311 // If the instruction reads the register that's spilled, (e.g. this can
312 // happen if it is a move to a physical register), then the spill
313 // instruction is not a kill.
Evan Chengc7daf1f2008-03-05 00:59:57 +0000314 bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
Evan Chengb4272522008-02-11 08:30:52 +0000315 TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 ++NumStores; // Update statistics
317 }
318
319 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
320
Bill Wendling9dcc0632009-08-22 20:38:09 +0000321 DEBUG(errs() << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 removePhysReg(PhysReg);
323}
324
325
326/// spillPhysReg - This method spills the specified physical register into the
327/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
328/// then the request is ignored if the physical register does not contain a
329/// virtual register.
330///
331void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
332 unsigned PhysReg, bool OnlyVirtRegs) {
333 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
334 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
335 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
336 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
337 } else {
338 // If the selected register aliases any other registers, we must make
339 // sure that one of the aliases isn't alive.
Dan Gohman1e57df32008-02-10 18:45:23 +0000340 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 *AliasSet; ++AliasSet)
342 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
343 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
344 if (PhysRegsUsed[*AliasSet])
345 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
346 }
347}
348
349
350/// assignVirtToPhysReg - This method updates local state so that we know
351/// that PhysReg is the proper container for VirtReg now. The physical
352/// register must not be used for anything else when this is called.
353///
354void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
355 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
356 // Update information to note the fact that this register was just used, and
357 // it holds VirtReg.
358 PhysRegsUsed[PhysReg] = VirtReg;
359 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
360 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
361}
362
363
364/// isPhysRegAvailable - Return true if the specified physical register is free
365/// and available for use. This also includes checking to see if aliased
366/// registers are all free...
367///
368bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
369 if (PhysRegsUsed[PhysReg] != -1) return false;
370
371 // If the selected register aliases any other allocated registers, it is
372 // not free!
Dan Gohman1e57df32008-02-10 18:45:23 +0000373 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 *AliasSet; ++AliasSet)
Evan Chengf90128d2008-02-22 20:30:53 +0000375 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 return false; // Can't use this reg then.
377 return true;
378}
379
380
381/// getFreeReg - Look to see if there is a free register available in the
382/// specified register class. If not, return 0.
383///
384unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
385 // Get iterators defining the range of registers that are valid to allocate in
386 // this class, which also specifies the preferred allocation order.
387 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
388 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
389
390 for (; RI != RE; ++RI)
391 if (isPhysRegAvailable(*RI)) { // Is reg unused?
392 assert(*RI != 0 && "Cannot use register!");
393 return *RI; // Found an unused register!
394 }
395 return 0;
396}
397
398
399/// getReg - Find a physical register to hold the specified virtual
400/// register. If all compatible physical registers are used, this method spills
401/// the last used virtual register to the stack, and uses that register.
402///
403unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
Evan Cheng308d1852009-01-29 01:13:00 +0000404 unsigned VirtReg, bool NoFree) {
Chris Lattner1b989192007-12-31 04:13:23 +0000405 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406
407 // First check to see if we have a free register of the requested type...
Evan Cheng308d1852009-01-29 01:13:00 +0000408 unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409
410 // If we didn't find an unused register, scavenge one now!
411 if (PhysReg == 0) {
412 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
413
414 // Loop over all of the preallocated registers from the least recently used
415 // to the most recently used. When we find one that is capable of holding
416 // our register, use it.
417 for (unsigned i = 0; PhysReg == 0; ++i) {
418 assert(i != PhysRegsUseOrder.size() &&
419 "Couldn't find a register of the appropriate class!");
420
421 unsigned R = PhysRegsUseOrder[i];
422
423 // We can only use this register if it holds a virtual register (ie, it
424 // can be spilled). Do not use it if it is an explicitly allocated
425 // physical register!
426 assert(PhysRegsUsed[R] != -1 &&
427 "PhysReg in PhysRegsUseOrder, but is not allocated?");
428 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
429 // If the current register is compatible, use it.
430 if (RC->contains(R)) {
431 PhysReg = R;
432 break;
433 } else {
434 // If one of the registers aliased to the current register is
435 // compatible, use it.
Dan Gohman1e57df32008-02-10 18:45:23 +0000436 for (const unsigned *AliasIt = TRI->getAliasSet(R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 *AliasIt; ++AliasIt) {
438 if (RC->contains(*AliasIt) &&
439 // If this is pinned down for some reason, don't use it. For
440 // example, if CL is pinned, and we run across CH, don't use
441 // CH as justification for using scavenging ECX (which will
442 // fail).
443 PhysRegsUsed[*AliasIt] != 0 &&
444
445 // Make sure the register is allocatable. Don't allocate SIL on
446 // x86-32.
447 PhysRegsUsed[*AliasIt] != -2) {
448 PhysReg = *AliasIt; // Take an aliased register
449 break;
450 }
451 }
452 }
453 }
454 }
455
456 assert(PhysReg && "Physical register not assigned!?!?");
457
458 // At this point PhysRegsUseOrder[i] is the least recently used register of
459 // compatible register class. Spill it to memory and reap its remains.
460 spillPhysReg(MBB, I, PhysReg);
461 }
462
463 // Now that we know which register we need to assign this to, do it now!
464 assignVirtToPhysReg(VirtReg, PhysReg);
465 return PhysReg;
466}
467
468
Bob Wilson219866c2009-05-07 21:20:42 +0000469/// reloadVirtReg - This method transforms the specified virtual
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470/// register use to refer to a physical register. This method may do this in
471/// one of several ways: if the register is available in a physical register
472/// already, it uses that physical register. If the value is not in a physical
473/// register, and if there are physical registers available, it loads it into a
474/// register. If register pressure is high, and it is possible, it tries to
475/// fold the load of the virtual register into the instruction itself. It
476/// avoids doing this if register pressure is low to improve the chance that
477/// subsequent instructions can use the reloaded value. This method returns the
478/// modified instruction.
479///
480MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng548bc502009-01-29 02:20:59 +0000481 unsigned OpNum,
482 SmallSet<unsigned, 4> &ReloadedRegs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 unsigned VirtReg = MI->getOperand(OpNum).getReg();
484
485 // If the virtual register is already available, just update the instruction
486 // and return.
487 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
Bill Wendlingf49e8392008-02-29 18:52:01 +0000488 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 MI->getOperand(OpNum).setReg(PR); // Assign the input register
Bill Wendlingf49e8392008-02-29 18:52:01 +0000490 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 return MI;
492 }
493
494 // Otherwise, we need to fold it into the current instruction, or reload it.
495 // If we have registers available to hold the value, use them.
Chris Lattner1b989192007-12-31 04:13:23 +0000496 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 unsigned PhysReg = getFreeReg(RC);
498 int FrameIndex = getStackSpaceFor(VirtReg, RC);
499
500 if (PhysReg) { // Register is available, allocate it!
501 assignVirtToPhysReg(VirtReg, PhysReg);
502 } else { // No registers available.
Evan Cheng71f91ed2008-02-07 19:46:55 +0000503 // Force some poor hapless value out of the register file to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 // make room for the new register, and reload it.
Evan Cheng308d1852009-01-29 01:13:00 +0000505 PhysReg = getReg(MBB, MI, VirtReg, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 }
507
508 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
509
Bill Wendling9dcc0632009-08-22 20:38:09 +0000510 DEBUG(errs() << " Reloading %reg" << VirtReg << " into "
511 << TRI->getName(PhysReg) << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512
513 // Add move instruction(s)
Owen Anderson81875432008-01-01 21:11:32 +0000514 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 ++NumLoads; // Update statistics
516
Chris Lattner1b989192007-12-31 04:13:23 +0000517 MF->getRegInfo().setPhysRegUsed(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
Evan Chenga94efbd2008-01-17 02:08:17 +0000519 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Evan Cheng548bc502009-01-29 02:20:59 +0000520
521 if (!ReloadedRegs.insert(PhysReg)) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000522 std::string msg;
523 raw_string_ostream Msg(msg);
524 Msg << "Ran out of registers during register allocation!";
Evan Cheng548bc502009-01-29 02:20:59 +0000525 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000526 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng548bc502009-01-29 02:20:59 +0000527 << "constraints:\n";
Edwin Törökced9ff82009-07-11 13:10:19 +0000528 MI->print(Msg, TM);
Evan Cheng548bc502009-01-29 02:20:59 +0000529 }
Edwin Törökced9ff82009-07-11 13:10:19 +0000530 llvm_report_error(Msg.str());
Evan Cheng548bc502009-01-29 02:20:59 +0000531 }
532 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
533 *SubRegs; ++SubRegs) {
534 if (!ReloadedRegs.insert(*SubRegs)) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000535 std::string msg;
536 raw_string_ostream Msg(msg);
537 Msg << "Ran out of registers during register allocation!";
Evan Cheng548bc502009-01-29 02:20:59 +0000538 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000539 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng548bc502009-01-29 02:20:59 +0000540 << "constraints:\n";
Edwin Törökced9ff82009-07-11 13:10:19 +0000541 MI->print(Msg, TM);
Evan Cheng548bc502009-01-29 02:20:59 +0000542 }
Edwin Törökced9ff82009-07-11 13:10:19 +0000543 llvm_report_error(Msg.str());
Evan Cheng548bc502009-01-29 02:20:59 +0000544 }
545 }
546
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 return MI;
548}
549
550/// isReadModWriteImplicitKill - True if this is an implicit kill for a
551/// read/mod/write register, i.e. update partial register.
552static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
553 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
554 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000555 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 MO.isDef() && !MO.isDead())
557 return true;
558 }
559 return false;
560}
561
562/// isReadModWriteImplicitDef - True if this is an implicit def for a
563/// read/mod/write register, i.e. update partial register.
564static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
565 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
566 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000567 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 !MO.isDef() && MO.isKill())
569 return true;
570 }
571 return false;
572}
573
Owen Anderson9196a392008-07-08 22:24:50 +0000574// precedes - Helper function to determine with MachineInstr A
575// precedes MachineInstr B within the same MBB.
576static bool precedes(MachineBasicBlock::iterator A,
577 MachineBasicBlock::iterator B) {
578 if (A == B)
579 return false;
580
581 MachineBasicBlock::iterator I = A->getParent()->begin();
582 while (I != A->getParent()->end()) {
583 if (I == A)
584 return true;
585 else if (I == B)
586 return false;
587
588 ++I;
589 }
590
591 return false;
592}
593
Owen Andersonff01ccf2008-07-09 20:14:53 +0000594/// ComputeLocalLiveness - Computes liveness of registers within a basic
595/// block, setting the killed/dead flags as appropriate.
596void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
Owen Anderson9196a392008-07-08 22:24:50 +0000597 MachineRegisterInfo& MRI = MBB.getParent()->getRegInfo();
598 // Keep track of the most recently seen previous use or def of each reg,
599 // so that we can update them with dead/kill markers.
Owen Anderson8050fa12008-07-10 01:56:35 +0000600 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
Owen Anderson9196a392008-07-08 22:24:50 +0000601 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
602 I != E; ++I) {
603 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
604 MachineOperand& MO = I->getOperand(i);
605 // Uses don't trigger any flags, but we need to save
606 // them for later. Also, we have to process these
607 // _before_ processing the defs, since an instr
608 // uses regs before it defs them.
Owen Andersona4d28702008-10-08 04:30:51 +0000609 if (MO.isReg() && MO.getReg() && MO.isUse()) {
Owen Anderson9196a392008-07-08 22:24:50 +0000610 LastUseDef[MO.getReg()] = std::make_pair(I, i);
Owen Andersona4d28702008-10-08 04:30:51 +0000611
612
613 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) continue;
614
Evan Cheng548bc502009-01-29 02:20:59 +0000615 const unsigned* Aliases = TRI->getAliasSet(MO.getReg());
616 if (Aliases) {
617 while (*Aliases) {
Owen Andersona4d28702008-10-08 04:30:51 +0000618 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Evan Cheng548bc502009-01-29 02:20:59 +0000619 alias = LastUseDef.find(*Aliases);
Owen Andersona4d28702008-10-08 04:30:51 +0000620
Evan Cheng548bc502009-01-29 02:20:59 +0000621 if (alias != LastUseDef.end() && alias->second.first != I)
622 LastUseDef[*Aliases] = std::make_pair(I, i);
Owen Andersona4d28702008-10-08 04:30:51 +0000623
Evan Cheng548bc502009-01-29 02:20:59 +0000624 ++Aliases;
Owen Andersona4d28702008-10-08 04:30:51 +0000625 }
626 }
627 }
Owen Anderson9196a392008-07-08 22:24:50 +0000628 }
629
630 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
631 MachineOperand& MO = I->getOperand(i);
632 // Defs others than 2-addr redefs _do_ trigger flag changes:
633 // - A def followed by a def is dead
634 // - A use followed by a def is a kill
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000635 if (MO.isReg() && MO.getReg() && MO.isDef()) {
Owen Anderson8050fa12008-07-10 01:56:35 +0000636 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Owen Anderson9196a392008-07-08 22:24:50 +0000637 last = LastUseDef.find(MO.getReg());
638 if (last != LastUseDef.end()) {
Owen Anderson348946a2008-07-10 01:53:01 +0000639 // Check if this is a two address instruction. If so, then
640 // the def does not kill the use.
Evan Chengf1107fd2008-07-10 07:35:43 +0000641 if (last->second.first == I &&
Bob Wilsonaded9952009-04-09 17:16:43 +0000642 I->isRegTiedToUseOperand(i))
Evan Chengf1107fd2008-07-10 07:35:43 +0000643 continue;
Owen Anderson77162402008-07-09 21:15:10 +0000644
Owen Anderson9196a392008-07-08 22:24:50 +0000645 MachineOperand& lastUD =
646 last->second.first->getOperand(last->second.second);
647 if (lastUD.isDef())
648 lastUD.setIsDead(true);
Evan Chengf1107fd2008-07-10 07:35:43 +0000649 else
Owen Anderson9196a392008-07-08 22:24:50 +0000650 lastUD.setIsKill(true);
651 }
652
653 LastUseDef[MO.getReg()] = std::make_pair(I, i);
654 }
655 }
656 }
657
658 // Live-out (of the function) registers contain return values of the function,
659 // so we need to make sure they are alive at return time.
660 if (!MBB.empty() && MBB.back().getDesc().isReturn()) {
661 MachineInstr* Ret = &MBB.back();
662 for (MachineRegisterInfo::liveout_iterator
663 I = MF->getRegInfo().liveout_begin(),
664 E = MF->getRegInfo().liveout_end(); I != E; ++I)
665 if (!Ret->readsRegister(*I)) {
666 Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
667 LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
668 }
669 }
670
671 // Finally, loop over the final use/def of each reg
672 // in the block and determine if it is dead.
Owen Anderson8050fa12008-07-10 01:56:35 +0000673 for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Owen Anderson9196a392008-07-08 22:24:50 +0000674 I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
675 MachineInstr* MI = I->second.first;
676 unsigned idx = I->second.second;
677 MachineOperand& MO = MI->getOperand(idx);
678
679 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
680
681 // A crude approximation of "live-out" calculation
682 bool usedOutsideBlock = isPhysReg ? false :
683 UsedInMultipleBlocks.test(MO.getReg() -
684 TargetRegisterInfo::FirstVirtualRegister);
685 if (!isPhysReg && !usedOutsideBlock)
686 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
687 UE = MRI.reg_end(); UI != UE; ++UI)
688 // Two cases:
689 // - used in another block
690 // - used in the same block before it is defined (loop)
691 if (UI->getParent() != &MBB ||
Owen Anderson074e69a2008-07-08 23:36:37 +0000692 (MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI))) {
Owen Anderson9196a392008-07-08 22:24:50 +0000693 UsedInMultipleBlocks.set(MO.getReg() -
694 TargetRegisterInfo::FirstVirtualRegister);
695 usedOutsideBlock = true;
696 break;
697 }
698
699 // Physical registers and those that are not live-out of the block
700 // are killed/dead at their last use/def within this block.
701 if (isPhysReg || !usedOutsideBlock) {
Dan Gohmanec06ecd2008-10-04 00:31:14 +0000702 if (MO.isUse()) {
703 // Don't mark uses that are tied to defs as kills.
Evan Cheng48555e82009-03-19 20:30:06 +0000704 if (!MI->isRegTiedToDefOperand(idx))
Dan Gohmanec06ecd2008-10-04 00:31:14 +0000705 MO.setIsKill(true);
706 } else
Owen Anderson9196a392008-07-08 22:24:50 +0000707 MO.setIsDead(true);
708 }
709 }
Owen Andersonff01ccf2008-07-09 20:14:53 +0000710}
711
712void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
713 // loop over each instruction
714 MachineBasicBlock::iterator MII = MBB.begin();
715
Bill Wendling9dcc0632009-08-22 20:38:09 +0000716 DEBUG({
717 const BasicBlock *LBB = MBB.getBasicBlock();
718 if (LBB)
719 errs() << "\nStarting RegAlloc of BB: " << LBB->getName();
720 });
Owen Andersonff01ccf2008-07-09 20:14:53 +0000721
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000722 // Add live-in registers as active.
723 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
Owen Andersonff01ccf2008-07-09 20:14:53 +0000724 E = MBB.livein_end(); I != E; ++I) {
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000725 unsigned Reg = *I;
726 MF->getRegInfo().setPhysRegUsed(Reg);
727 PhysRegsUsed[Reg] = 0; // It is free and reserved now
728 AddToPhysRegsUseOrder(Reg);
729 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
730 *SubRegs; ++SubRegs) {
731 if (PhysRegsUsed[*SubRegs] != -2) {
732 AddToPhysRegsUseOrder(*SubRegs);
733 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
734 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Owen Andersonff01ccf2008-07-09 20:14:53 +0000735 }
Evan Chengb0f4d5f2009-01-29 18:37:30 +0000736 }
Owen Andersonff01ccf2008-07-09 20:14:53 +0000737 }
738
739 ComputeLocalLiveness(MBB);
Owen Anderson9196a392008-07-08 22:24:50 +0000740
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 // Otherwise, sequentially allocate each instruction in the MBB.
742 while (MII != MBB.end()) {
743 MachineInstr *MI = MII++;
Chris Lattner5b930372008-01-07 07:27:27 +0000744 const TargetInstrDesc &TID = MI->getDesc();
Bill Wendling9dcc0632009-08-22 20:38:09 +0000745 DEBUG({
746 errs() << "\nStarting RegAlloc of: " << *MI;
747 errs() << " Regs have values: ";
748 for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
749 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
750 errs() << "[" << TRI->getName(i)
751 << ",%reg" << PhysRegsUsed[i] << "] ";
752 errs() << '\n';
753 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754
755 // Loop over the implicit uses, making sure that they are at the head of the
756 // use order list, so they don't get reallocated.
757 if (TID.ImplicitUses) {
758 for (const unsigned *ImplicitUses = TID.ImplicitUses;
759 *ImplicitUses; ++ImplicitUses)
760 MarkPhysRegRecentlyUsed(*ImplicitUses);
761 }
762
763 SmallVector<unsigned, 8> Kills;
764 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
765 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000766 if (MO.isReg() && MO.isKill()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 if (!MO.isImplicit())
768 Kills.push_back(MO.getReg());
769 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
770 // These are extra physical register kills when a sub-register
771 // is defined (def of a sub-register is a read/mod/write of the
772 // larger registers). Ignore.
773 Kills.push_back(MO.getReg());
774 }
775 }
776
Dale Johannesen47e30e42008-09-24 23:13:09 +0000777 // If any physical regs are earlyclobber, spill any value they might
778 // have in them, then mark them unallocatable.
779 // If any virtual regs are earlyclobber, allocate them now (before
780 // freeing inputs that are killed).
781 if (MI->getOpcode()==TargetInstrInfo::INLINEASM) {
782 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
783 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000784 if (MO.isReg() && MO.isDef() && MO.isEarlyClobber() &&
Dale Johannesen47e30e42008-09-24 23:13:09 +0000785 MO.getReg()) {
786 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
787 unsigned DestVirtReg = MO.getReg();
788 unsigned DestPhysReg;
789
790 // If DestVirtReg already has a value, use it.
791 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
792 DestPhysReg = getReg(MBB, MI, DestVirtReg);
793 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
794 markVirtRegModified(DestVirtReg);
795 getVirtRegLastUse(DestVirtReg) =
796 std::make_pair((MachineInstr*)0, 0);
Bill Wendling9dcc0632009-08-22 20:38:09 +0000797 DEBUG(errs() << " Assigning " << TRI->getName(DestPhysReg)
798 << " to %reg" << DestVirtReg << "\n");
Dale Johannesen47e30e42008-09-24 23:13:09 +0000799 MO.setReg(DestPhysReg); // Assign the earlyclobber register
800 } else {
801 unsigned Reg = MO.getReg();
802 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
803 // These are extra physical register defs when a sub-register
804 // is defined (def of a sub-register is a read/mod/write of the
805 // larger registers). Ignore.
806 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
807
808 MF->getRegInfo().setPhysRegUsed(Reg);
809 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
810 PhysRegsUsed[Reg] = 0; // It is free and reserved now
811 AddToPhysRegsUseOrder(Reg);
812
Evan Cheng548bc502009-01-29 02:20:59 +0000813 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
814 *SubRegs; ++SubRegs) {
815 if (PhysRegsUsed[*SubRegs] != -2) {
816 MF->getRegInfo().setPhysRegUsed(*SubRegs);
817 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
818 AddToPhysRegsUseOrder(*SubRegs);
Dale Johannesen47e30e42008-09-24 23:13:09 +0000819 }
820 }
821 }
822 }
823 }
824 }
825
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 // Get the used operands into registers. This has the potential to spill
827 // incoming values if we are out of registers. Note that we completely
828 // ignore physical register uses here. We assume that if an explicit
829 // physical register is referenced by the instruction, that it is guaranteed
830 // to be live-in, or the input is badly hosed.
831 //
Evan Cheng548bc502009-01-29 02:20:59 +0000832 SmallSet<unsigned, 4> ReloadedRegs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
834 MachineOperand& MO = MI->getOperand(i);
835 // here we are looking for only used operands (never def&use)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000836 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000837 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Cheng548bc502009-01-29 02:20:59 +0000838 MI = reloadVirtReg(MBB, MI, i, ReloadedRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 }
840
841 // If this instruction is the last user of this register, kill the
842 // value, freeing the register being used, so it doesn't need to be
843 // spilled to memory.
844 //
845 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
846 unsigned VirtReg = Kills[i];
847 unsigned PhysReg = VirtReg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000848 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 // If the virtual register was never materialized into a register, it
850 // might not be in the map, but it won't hurt to zero it out anyway.
851 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
852 PhysReg = PhysRegSlot;
853 PhysRegSlot = 0;
854 } else if (PhysRegsUsed[PhysReg] == -2) {
855 // Unallocatable register dead, ignore.
856 continue;
857 } else {
Evan Cheng358d8dd2007-10-22 19:42:28 +0000858 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 "Silently clearing a virtual register?");
860 }
861
862 if (PhysReg) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000863 DEBUG(errs() << " Last use of " << TRI->getName(PhysReg)
864 << "[%reg" << VirtReg <<"], removing it from live set\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 removePhysReg(PhysReg);
Evan Cheng548bc502009-01-29 02:20:59 +0000866 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
867 *SubRegs; ++SubRegs) {
868 if (PhysRegsUsed[*SubRegs] != -2) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000869 DEBUG(errs() << " Last use of "
870 << TRI->getName(*SubRegs) << "[%reg" << VirtReg
871 <<"], removing it from live set\n");
Evan Cheng548bc502009-01-29 02:20:59 +0000872 removePhysReg(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 }
874 }
875 }
876 }
877
878 // Loop over all of the operands of the instruction, spilling registers that
879 // are defined, and marking explicit destinations in the PhysRegsUsed map.
880 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
881 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000882 if (MO.isReg() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
Dale Johannesen47e30e42008-09-24 23:13:09 +0000883 !MO.isEarlyClobber() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000884 TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885 unsigned Reg = MO.getReg();
886 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
887 // These are extra physical register defs when a sub-register
888 // is defined (def of a sub-register is a read/mod/write of the
889 // larger registers). Ignore.
890 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
891
Chris Lattner1b989192007-12-31 04:13:23 +0000892 MF->getRegInfo().setPhysRegUsed(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
894 PhysRegsUsed[Reg] = 0; // It is free and reserved now
895 AddToPhysRegsUseOrder(Reg);
896
Evan Cheng548bc502009-01-29 02:20:59 +0000897 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
898 *SubRegs; ++SubRegs) {
899 if (PhysRegsUsed[*SubRegs] != -2) {
900 MF->getRegInfo().setPhysRegUsed(*SubRegs);
901 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
902 AddToPhysRegsUseOrder(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 }
904 }
905 }
906 }
907
908 // Loop over the implicit defs, spilling them as well.
909 if (TID.ImplicitDefs) {
910 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
911 *ImplicitDefs; ++ImplicitDefs) {
912 unsigned Reg = *ImplicitDefs;
913 if (PhysRegsUsed[Reg] != -2) {
914 spillPhysReg(MBB, MI, Reg, true);
915 AddToPhysRegsUseOrder(Reg);
916 PhysRegsUsed[Reg] = 0; // It is free and reserved now
917 }
Chris Lattner1b989192007-12-31 04:13:23 +0000918 MF->getRegInfo().setPhysRegUsed(Reg);
Evan Cheng548bc502009-01-29 02:20:59 +0000919 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
920 *SubRegs; ++SubRegs) {
921 if (PhysRegsUsed[*SubRegs] != -2) {
922 AddToPhysRegsUseOrder(*SubRegs);
923 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
924 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 }
926 }
927 }
928 }
929
930 SmallVector<unsigned, 8> DeadDefs;
931 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
932 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000933 if (MO.isReg() && MO.isDead())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 DeadDefs.push_back(MO.getReg());
935 }
936
937 // Okay, we have allocated all of the source operands and spilled any values
938 // that would be destroyed by defs of this instruction. Loop over the
939 // explicit defs and assign them to a register, spilling incoming values if
940 // we need to scavenge a register.
941 //
942 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
943 MachineOperand& MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000944 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Dale Johannesen47e30e42008-09-24 23:13:09 +0000945 !MO.isEarlyClobber() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000946 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 unsigned DestVirtReg = MO.getReg();
948 unsigned DestPhysReg;
949
950 // If DestVirtReg already has a value, use it.
951 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
952 DestPhysReg = getReg(MBB, MI, DestVirtReg);
Chris Lattner1b989192007-12-31 04:13:23 +0000953 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 markVirtRegModified(DestVirtReg);
Evan Chenga94efbd2008-01-17 02:08:17 +0000955 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
Bill Wendling9dcc0632009-08-22 20:38:09 +0000956 DEBUG(errs() << " Assigning " << TRI->getName(DestPhysReg)
957 << " to %reg" << DestVirtReg << "\n");
Dan Gohman7f31037a2008-07-09 20:12:26 +0000958 MO.setReg(DestPhysReg); // Assign the output register
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959 }
960 }
961
962 // If this instruction defines any registers that are immediately dead,
963 // kill them now.
964 //
965 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
966 unsigned VirtReg = DeadDefs[i];
967 unsigned PhysReg = VirtReg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000968 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
970 PhysReg = PhysRegSlot;
971 assert(PhysReg != 0);
972 PhysRegSlot = 0;
973 } else if (PhysRegsUsed[PhysReg] == -2) {
974 // Unallocatable register dead, ignore.
975 continue;
976 }
977
978 if (PhysReg) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000979 DEBUG(errs() << " Register " << TRI->getName(PhysReg)
980 << " [%reg" << VirtReg
981 << "] is never used, removing it from live set\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 removePhysReg(PhysReg);
Dan Gohman1e57df32008-02-10 18:45:23 +0000983 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 *AliasSet; ++AliasSet) {
985 if (PhysRegsUsed[*AliasSet] != -2) {
Bill Wendling9dcc0632009-08-22 20:38:09 +0000986 DEBUG(errs() << " Register " << TRI->getName(*AliasSet)
987 << " [%reg" << *AliasSet
988 << "] is never used, removing it from live set\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 removePhysReg(*AliasSet);
990 }
991 }
992 }
993 }
994
Bob Wilsona43eb6b2009-05-07 23:47:03 +0000995 // Finally, if this is a noop copy instruction, zap it. (Except that if
996 // the copy is dead, it must be kept to avoid messing up liveness info for
997 // the register scavenger. See pr4100.)
Evan Chengf97496a2009-01-20 19:12:24 +0000998 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
999 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
Bob Wilsona43eb6b2009-05-07 23:47:03 +00001000 SrcReg == DstReg && DeadDefs.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 MBB.erase(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 }
1003
1004 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1005
1006 // Spill all physical registers holding virtual registers now.
Dan Gohman1e57df32008-02-10 18:45:23 +00001007 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001008 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 if (unsigned VirtReg = PhysRegsUsed[i])
1010 spillVirtReg(MBB, MI, VirtReg, i);
1011 else
1012 removePhysReg(i);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014
1015#if 0
1016 // This checking code is very expensive.
1017 bool AllOk = true;
Dan Gohman1e57df32008-02-10 18:45:23 +00001018 for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
Chris Lattner1b989192007-12-31 04:13:23 +00001019 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 if (unsigned PR = Virt2PhysRegMap[i]) {
1021 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
1022 AllOk = false;
1023 }
1024 assert(AllOk && "Virtual registers still in phys regs?");
1025#endif
1026
1027 // Clear any physical register which appear live at the end of the basic
1028 // block, but which do not hold any virtual registers. e.g., the stack
1029 // pointer.
1030 PhysRegsUseOrder.clear();
1031}
1032
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033/// runOnMachineFunction - Register allocate the whole function
1034///
1035bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
Bill Wendling9dcc0632009-08-22 20:38:09 +00001036 DEBUG(errs() << "Machine Function\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 MF = &Fn;
1038 TM = &Fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +00001039 TRI = TM->getRegisterInfo();
Owen Andersonbf15ae22008-01-07 01:35:56 +00001040 TII = TM->getInstrInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041
Dan Gohman1e57df32008-02-10 18:45:23 +00001042 PhysRegsUsed.assign(TRI->getNumRegs(), -1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043
1044 // At various places we want to efficiently check to see whether a register
1045 // is allocatable. To handle this, we mark all unallocatable registers as
1046 // being pinned down, permanently.
1047 {
Dan Gohman1e57df32008-02-10 18:45:23 +00001048 BitVector Allocable = TRI->getAllocatableSet(Fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
1050 if (!Allocable[i])
1051 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
1052 }
1053
1054 // initialize the virtual->physical register map to have a 'null'
1055 // mapping for all virtual registers
Evan Cheng9e66d8c2008-01-17 00:35:26 +00001056 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
Evan Cheng33dc9712008-07-10 18:23:23 +00001057 StackSlotForVirtReg.grow(LastVirtReg);
Evan Cheng9e66d8c2008-01-17 00:35:26 +00001058 Virt2PhysRegMap.grow(LastVirtReg);
Evan Chenga94efbd2008-01-17 02:08:17 +00001059 Virt2LastUseMap.grow(LastVirtReg);
Dan Gohman1e57df32008-02-10 18:45:23 +00001060 VirtRegModified.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
Owen Anderson9196a392008-07-08 22:24:50 +00001061 UsedInMultipleBlocks.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
1062
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063 // Loop over all of the basic blocks, eliminating virtual register references
1064 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
1065 MBB != MBBe; ++MBB)
1066 AllocateBasicBlock(*MBB);
1067
1068 StackSlotForVirtReg.clear();
1069 PhysRegsUsed.clear();
1070 VirtRegModified.clear();
Owen Anderson9196a392008-07-08 22:24:50 +00001071 UsedInMultipleBlocks.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 Virt2PhysRegMap.clear();
Evan Chenga94efbd2008-01-17 02:08:17 +00001073 Virt2LastUseMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 return true;
1075}
1076
1077FunctionPass *llvm::createLocalRegisterAllocator() {
1078 return new RALocal();
1079}