1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/IndexedMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/SparseSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/RegAllocRegistry.h"
30 #include "llvm/CodeGen/RegisterClassInfo.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NumStores, "Number of stores added");
42 STATISTIC(NumLoads , "Number of loads added");
43 STATISTIC(NumCopies, "Number of copies coalesced");
44
45 static RegisterRegAlloc
46 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
47
48 namespace {
49 class RAFast : public MachineFunctionPass {
50 public:
51 static char ID;
RAFast()52 RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
53 isBulkSpilling(false) {}
54 private:
55 const TargetMachine *TM;
56 MachineFunction *MF;
57 MachineRegisterInfo *MRI;
58 const TargetRegisterInfo *TRI;
59 const TargetInstrInfo *TII;
60 RegisterClassInfo RegClassInfo;
61
62 // Basic block currently being allocated.
63 MachineBasicBlock *MBB;
64
65 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
66 // values are spilled.
67 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
68
69 // Everything we know about a live virtual register.
70 struct LiveReg {
71 MachineInstr *LastUse; // Last instr to use reg.
72 unsigned VirtReg; // Virtual register number.
73 unsigned PhysReg; // Currently held here.
74 unsigned short LastOpNum; // OpNum on LastUse.
75 bool Dirty; // Register needs spill.
76
LiveReg__anon867c21970111::RAFast::LiveReg77 explicit LiveReg(unsigned v)
78 : LastUse(0), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false) {}
79
getSparseSetIndex__anon867c21970111::RAFast::LiveReg80 unsigned getSparseSetIndex() const {
81 return TargetRegisterInfo::virtReg2Index(VirtReg);
82 }
83 };
84
85 typedef SparseSet<LiveReg> LiveRegMap;
86
87 // LiveVirtRegs - This map contains entries for each virtual register
88 // that is currently available in a physical register.
89 LiveRegMap LiveVirtRegs;
90
91 DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
92
93 // RegState - Track the state of a physical register.
94 enum RegState {
95 // A disabled register is not available for allocation, but an alias may
96 // be in use. A register can only be moved out of the disabled state if
97 // all aliases are disabled.
98 regDisabled,
99
100 // A free register is not currently in use and can be allocated
101 // immediately without checking aliases.
102 regFree,
103
104 // A reserved register has been assigned explicitly (e.g., setting up a
105 // call parameter), and it remains reserved until it is used.
106 regReserved
107
108 // A register state may also be a virtual register number, indication that
109 // the physical register is currently allocated to a virtual register. In
110 // that case, LiveVirtRegs contains the inverse mapping.
111 };
112
113 // PhysRegState - One of the RegState enums, or a virtreg.
114 std::vector<unsigned> PhysRegState;
115
116 // Set of register units.
117 typedef SparseSet<unsigned> UsedInInstrSet;
118
119 // Set of register units that are used in the current instruction, and so
120 // cannot be allocated.
121 UsedInInstrSet UsedInInstr;
122
123 // Mark a physreg as used in this instruction.
markRegUsedInInstr(unsigned PhysReg)124 void markRegUsedInInstr(unsigned PhysReg) {
125 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
126 UsedInInstr.insert(*Units);
127 }
128
129 // Check if a physreg or any of its aliases are used in this instruction.
isRegUsedInInstr(unsigned PhysReg) const130 bool isRegUsedInInstr(unsigned PhysReg) const {
131 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
132 if (UsedInInstr.count(*Units))
133 return true;
134 return false;
135 }
136
137 // SkippedInstrs - Descriptors of instructions whose clobber list was
138 // ignored because all registers were spilled. It is still necessary to
139 // mark all the clobbered registers as used by the function.
140 SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
141
142 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
143 // completely after spilling all live registers. LiveRegMap entries should
144 // not be erased.
145 bool isBulkSpilling;
146
147 enum {
148 spillClean = 1,
149 spillDirty = 100,
150 spillImpossible = ~0u
151 };
152 public:
getPassName() const153 virtual const char *getPassName() const {
154 return "Fast Register Allocator";
155 }
156
getAnalysisUsage(AnalysisUsage & AU) const157 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.setPreservesCFG();
159 MachineFunctionPass::getAnalysisUsage(AU);
160 }
161
162 private:
163 bool runOnMachineFunction(MachineFunction &Fn);
164 void AllocateBasicBlock();
165 void handleThroughOperands(MachineInstr *MI,
166 SmallVectorImpl<unsigned> &VirtDead);
167 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
168 bool isLastUseOfLocalReg(MachineOperand&);
169
170 void addKillFlag(const LiveReg&);
171 void killVirtReg(LiveRegMap::iterator);
172 void killVirtReg(unsigned VirtReg);
173 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
174 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
175
176 void usePhysReg(MachineOperand&);
177 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
178 unsigned calcSpillCost(unsigned PhysReg) const;
179 void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
findLiveVirtReg(unsigned VirtReg)180 LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
181 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
182 }
findLiveVirtReg(unsigned VirtReg) const183 LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
184 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
185 }
186 LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
187 LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterator,
188 unsigned Hint);
189 LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
190 unsigned VirtReg, unsigned Hint);
191 LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
192 unsigned VirtReg, unsigned Hint);
193 void spillAll(MachineBasicBlock::iterator MI);
194 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
195 };
196 char RAFast::ID = 0;
197 }
198
199 /// getStackSpaceFor - This allocates space for the specified virtual register
200 /// to be held on the stack.
getStackSpaceFor(unsigned VirtReg,const TargetRegisterClass * RC)201 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
202 // Find the location Reg would belong...
203 int SS = StackSlotForVirtReg[VirtReg];
204 if (SS != -1)
205 return SS; // Already has space allocated?
206
207 // Allocate a new stack object for this spill location...
208 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
209 RC->getAlignment());
210
211 // Assign the slot.
212 StackSlotForVirtReg[VirtReg] = FrameIdx;
213 return FrameIdx;
214 }
215
216 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
217 /// its virtual register, and it is guaranteed to be a block-local register.
218 ///
isLastUseOfLocalReg(MachineOperand & MO)219 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
220 // If the register has ever been spilled or reloaded, we conservatively assume
221 // it is a global register used in multiple blocks.
222 if (StackSlotForVirtReg[MO.getReg()] != -1)
223 return false;
224
225 // Check that the use/def chain has exactly one operand - MO.
226 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
227 if (&I.getOperand() != &MO)
228 return false;
229 return ++I == MRI->reg_nodbg_end();
230 }
231
232 /// addKillFlag - Set kill flags on last use of a virtual register.
addKillFlag(const LiveReg & LR)233 void RAFast::addKillFlag(const LiveReg &LR) {
234 if (!LR.LastUse) return;
235 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
236 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
237 if (MO.getReg() == LR.PhysReg)
238 MO.setIsKill();
239 else
240 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
241 }
242 }
243
244 /// killVirtReg - Mark virtreg as no longer available.
killVirtReg(LiveRegMap::iterator LRI)245 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
246 addKillFlag(*LRI);
247 assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
248 "Broken RegState mapping");
249 PhysRegState[LRI->PhysReg] = regFree;
250 // Erase from LiveVirtRegs unless we're spilling in bulk.
251 if (!isBulkSpilling)
252 LiveVirtRegs.erase(LRI);
253 }
254
255 /// killVirtReg - Mark virtreg as no longer available.
killVirtReg(unsigned VirtReg)256 void RAFast::killVirtReg(unsigned VirtReg) {
257 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
258 "killVirtReg needs a virtual register");
259 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
260 if (LRI != LiveVirtRegs.end())
261 killVirtReg(LRI);
262 }
263
264 /// spillVirtReg - This method spills the value specified by VirtReg into the
265 /// corresponding stack slot if needed.
spillVirtReg(MachineBasicBlock::iterator MI,unsigned VirtReg)266 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
267 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
268 "Spilling a physical register is illegal!");
269 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
270 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
271 spillVirtReg(MI, LRI);
272 }
273
274 /// spillVirtReg - Do the actual work of spilling.
spillVirtReg(MachineBasicBlock::iterator MI,LiveRegMap::iterator LRI)275 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
276 LiveRegMap::iterator LRI) {
277 LiveReg &LR = *LRI;
278 assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
279
280 if (LR.Dirty) {
281 // If this physreg is used by the instruction, we want to kill it on the
282 // instruction, not on the spill.
283 bool SpillKill = LR.LastUse != MI;
284 LR.Dirty = false;
285 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
286 << " in " << PrintReg(LR.PhysReg, TRI));
287 const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
288 int FI = getStackSpaceFor(LRI->VirtReg, RC);
289 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
290 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
291 ++NumStores; // Update statistics
292
293 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
294 // identify spilled location as the place to find corresponding variable's
295 // value.
296 SmallVectorImpl<MachineInstr *> &LRIDbgValues =
297 LiveDbgValueMap[LRI->VirtReg];
298 for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
299 MachineInstr *DBG = LRIDbgValues[li];
300 const MDNode *MDPtr = DBG->getOperand(2).getMetadata();
301 bool IsIndirect = DBG->getOperand(1).isImm(); // Register-indirect value?
302 uint64_t Offset = IsIndirect ? DBG->getOperand(1).getImm() : 0;
303 DebugLoc DL;
304 if (MI == MBB->end()) {
305 // If MI is at basic block end then use last instruction's location.
306 MachineBasicBlock::iterator EI = MI;
307 DL = (--EI)->getDebugLoc();
308 } else
309 DL = MI->getDebugLoc();
310 MachineBasicBlock *MBB = DBG->getParent();
311 MachineInstr *NewDV =
312 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::DBG_VALUE))
313 .addFrameIndex(FI).addImm(Offset).addMetadata(MDPtr);
314 (void)NewDV;
315 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
316 }
317 // Now this register is spilled there is should not be any DBG_VALUE
318 // pointing to this register because they are all pointing to spilled value
319 // now.
320 LRIDbgValues.clear();
321 if (SpillKill)
322 LR.LastUse = 0; // Don't kill register again
323 }
324 killVirtReg(LRI);
325 }
326
327 /// spillAll - Spill all dirty virtregs without killing them.
spillAll(MachineBasicBlock::iterator MI)328 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
329 if (LiveVirtRegs.empty()) return;
330 isBulkSpilling = true;
331 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
332 // of spilling here is deterministic, if arbitrary.
333 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
334 i != e; ++i)
335 spillVirtReg(MI, i);
336 LiveVirtRegs.clear();
337 isBulkSpilling = false;
338 }
339
340 /// usePhysReg - Handle the direct use of a physical register.
341 /// Check that the register is not used by a virtreg.
342 /// Kill the physreg, marking it free.
343 /// This may add implicit kills to MO->getParent() and invalidate MO.
usePhysReg(MachineOperand & MO)344 void RAFast::usePhysReg(MachineOperand &MO) {
345 unsigned PhysReg = MO.getReg();
346 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
347 "Bad usePhysReg operand");
348 markRegUsedInInstr(PhysReg);
349 switch (PhysRegState[PhysReg]) {
350 case regDisabled:
351 break;
352 case regReserved:
353 PhysRegState[PhysReg] = regFree;
354 // Fall through
355 case regFree:
356 MO.setIsKill();
357 return;
358 default:
359 // The physreg was allocated to a virtual register. That means the value we
360 // wanted has been clobbered.
361 llvm_unreachable("Instruction uses an allocated register");
362 }
363
364 // Maybe a superregister is reserved?
365 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
366 unsigned Alias = *AI;
367 switch (PhysRegState[Alias]) {
368 case regDisabled:
369 break;
370 case regReserved:
371 assert(TRI->isSuperRegister(PhysReg, Alias) &&
372 "Instruction is not using a subregister of a reserved register");
373 // Leave the superregister in the working set.
374 PhysRegState[Alias] = regFree;
375 MO.getParent()->addRegisterKilled(Alias, TRI, true);
376 return;
377 case regFree:
378 if (TRI->isSuperRegister(PhysReg, Alias)) {
379 // Leave the superregister in the working set.
380 MO.getParent()->addRegisterKilled(Alias, TRI, true);
381 return;
382 }
383 // Some other alias was in the working set - clear it.
384 PhysRegState[Alias] = regDisabled;
385 break;
386 default:
387 llvm_unreachable("Instruction uses an alias of an allocated register");
388 }
389 }
390
391 // All aliases are disabled, bring register into working set.
392 PhysRegState[PhysReg] = regFree;
393 MO.setIsKill();
394 }
395
396 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
397 /// virtregs. This is very similar to defineVirtReg except the physreg is
398 /// reserved instead of allocated.
definePhysReg(MachineInstr * MI,unsigned PhysReg,RegState NewState)399 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
400 RegState NewState) {
401 markRegUsedInInstr(PhysReg);
402 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
403 case regDisabled:
404 break;
405 default:
406 spillVirtReg(MI, VirtReg);
407 // Fall through.
408 case regFree:
409 case regReserved:
410 PhysRegState[PhysReg] = NewState;
411 return;
412 }
413
414 // This is a disabled register, disable all aliases.
415 PhysRegState[PhysReg] = NewState;
416 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
417 unsigned Alias = *AI;
418 switch (unsigned VirtReg = PhysRegState[Alias]) {
419 case regDisabled:
420 break;
421 default:
422 spillVirtReg(MI, VirtReg);
423 // Fall through.
424 case regFree:
425 case regReserved:
426 PhysRegState[Alias] = regDisabled;
427 if (TRI->isSuperRegister(PhysReg, Alias))
428 return;
429 break;
430 }
431 }
432 }
433
434
435 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
436 // aliases so it is free for allocation.
437 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
438 // can be allocated directly.
439 // Returns spillImpossible when PhysReg or an alias can't be spilled.
calcSpillCost(unsigned PhysReg) const440 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
441 if (isRegUsedInInstr(PhysReg)) {
442 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
443 return spillImpossible;
444 }
445 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
446 case regDisabled:
447 break;
448 case regFree:
449 return 0;
450 case regReserved:
451 DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
452 << PrintReg(PhysReg, TRI) << " is reserved already.\n");
453 return spillImpossible;
454 default: {
455 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
456 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
457 return I->Dirty ? spillDirty : spillClean;
458 }
459 }
460
461 // This is a disabled register, add up cost of aliases.
462 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
463 unsigned Cost = 0;
464 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
465 unsigned Alias = *AI;
466 switch (unsigned VirtReg = PhysRegState[Alias]) {
467 case regDisabled:
468 break;
469 case regFree:
470 ++Cost;
471 break;
472 case regReserved:
473 return spillImpossible;
474 default: {
475 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
476 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
477 Cost += I->Dirty ? spillDirty : spillClean;
478 break;
479 }
480 }
481 }
482 return Cost;
483 }
484
485
486 /// assignVirtToPhysReg - This method updates local state so that we know
487 /// that PhysReg is the proper container for VirtReg now. The physical
488 /// register must not be used for anything else when this is called.
489 ///
assignVirtToPhysReg(LiveReg & LR,unsigned PhysReg)490 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
491 DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
492 << PrintReg(PhysReg, TRI) << "\n");
493 PhysRegState[PhysReg] = LR.VirtReg;
494 assert(!LR.PhysReg && "Already assigned a physreg");
495 LR.PhysReg = PhysReg;
496 }
497
498 RAFast::LiveRegMap::iterator
assignVirtToPhysReg(unsigned VirtReg,unsigned PhysReg)499 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
500 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
501 assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
502 assignVirtToPhysReg(*LRI, PhysReg);
503 return LRI;
504 }
505
506 /// allocVirtReg - Allocate a physical register for VirtReg.
allocVirtReg(MachineInstr * MI,LiveRegMap::iterator LRI,unsigned Hint)507 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
508 LiveRegMap::iterator LRI,
509 unsigned Hint) {
510 const unsigned VirtReg = LRI->VirtReg;
511
512 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
513 "Can only allocate virtual registers");
514
515 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
516
517 // Ignore invalid hints.
518 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
519 !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
520 Hint = 0;
521
522 // Take hint when possible.
523 if (Hint) {
524 // Ignore the hint if we would have to spill a dirty register.
525 unsigned Cost = calcSpillCost(Hint);
526 if (Cost < spillDirty) {
527 if (Cost)
528 definePhysReg(MI, Hint, regFree);
529 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
530 // That invalidates LRI, so run a new lookup for VirtReg.
531 return assignVirtToPhysReg(VirtReg, Hint);
532 }
533 }
534
535 ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
536
537 // First try to find a completely free register.
538 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
539 unsigned PhysReg = *I;
540 if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
541 assignVirtToPhysReg(*LRI, PhysReg);
542 return LRI;
543 }
544 }
545
546 DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
547 << RC->getName() << "\n");
548
549 unsigned BestReg = 0, BestCost = spillImpossible;
550 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
551 unsigned Cost = calcSpillCost(*I);
552 DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
553 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
554 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
555 // Cost is 0 when all aliases are already disabled.
556 if (Cost == 0) {
557 assignVirtToPhysReg(*LRI, *I);
558 return LRI;
559 }
560 if (Cost < BestCost)
561 BestReg = *I, BestCost = Cost;
562 }
563
564 if (BestReg) {
565 definePhysReg(MI, BestReg, regFree);
566 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
567 // That invalidates LRI, so run a new lookup for VirtReg.
568 return assignVirtToPhysReg(VirtReg, BestReg);
569 }
570
571 // Nothing we can do. Report an error and keep going with a bad allocation.
572 MI->emitError("ran out of registers during register allocation");
573 definePhysReg(MI, *AO.begin(), regFree);
574 return assignVirtToPhysReg(VirtReg, *AO.begin());
575 }
576
577 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
578 RAFast::LiveRegMap::iterator
defineVirtReg(MachineInstr * MI,unsigned OpNum,unsigned VirtReg,unsigned Hint)579 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
580 unsigned VirtReg, unsigned Hint) {
581 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
582 "Not a virtual register");
583 LiveRegMap::iterator LRI;
584 bool New;
585 tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
586 if (New) {
587 // If there is no hint, peek at the only use of this register.
588 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
589 MRI->hasOneNonDBGUse(VirtReg)) {
590 const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
591 // It's a copy, use the destination register as a hint.
592 if (UseMI.isCopyLike())
593 Hint = UseMI.getOperand(0).getReg();
594 }
595 LRI = allocVirtReg(MI, LRI, Hint);
596 } else if (LRI->LastUse) {
597 // Redefining a live register - kill at the last use, unless it is this
598 // instruction defining VirtReg multiple times.
599 if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
600 addKillFlag(*LRI);
601 }
602 assert(LRI->PhysReg && "Register not assigned");
603 LRI->LastUse = MI;
604 LRI->LastOpNum = OpNum;
605 LRI->Dirty = true;
606 markRegUsedInInstr(LRI->PhysReg);
607 return LRI;
608 }
609
610 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
611 RAFast::LiveRegMap::iterator
reloadVirtReg(MachineInstr * MI,unsigned OpNum,unsigned VirtReg,unsigned Hint)612 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
613 unsigned VirtReg, unsigned Hint) {
614 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
615 "Not a virtual register");
616 LiveRegMap::iterator LRI;
617 bool New;
618 tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
619 MachineOperand &MO = MI->getOperand(OpNum);
620 if (New) {
621 LRI = allocVirtReg(MI, LRI, Hint);
622 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
623 int FrameIndex = getStackSpaceFor(VirtReg, RC);
624 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
625 << PrintReg(LRI->PhysReg, TRI) << "\n");
626 TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
627 ++NumLoads;
628 } else if (LRI->Dirty) {
629 if (isLastUseOfLocalReg(MO)) {
630 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
631 if (MO.isUse())
632 MO.setIsKill();
633 else
634 MO.setIsDead();
635 } else if (MO.isKill()) {
636 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
637 MO.setIsKill(false);
638 } else if (MO.isDead()) {
639 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
640 MO.setIsDead(false);
641 }
642 } else if (MO.isKill()) {
643 // We must remove kill flags from uses of reloaded registers because the
644 // register would be killed immediately, and there might be a second use:
645 // %foo = OR %x<kill>, %x
646 // This would cause a second reload of %x into a different register.
647 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
648 MO.setIsKill(false);
649 } else if (MO.isDead()) {
650 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
651 MO.setIsDead(false);
652 }
653 assert(LRI->PhysReg && "Register not assigned");
654 LRI->LastUse = MI;
655 LRI->LastOpNum = OpNum;
656 markRegUsedInInstr(LRI->PhysReg);
657 return LRI;
658 }
659
660 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
661 // subregs. This may invalidate any operand pointers.
662 // Return true if the operand kills its register.
setPhysReg(MachineInstr * MI,unsigned OpNum,unsigned PhysReg)663 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
664 MachineOperand &MO = MI->getOperand(OpNum);
665 bool Dead = MO.isDead();
666 if (!MO.getSubReg()) {
667 MO.setReg(PhysReg);
668 return MO.isKill() || Dead;
669 }
670
671 // Handle subregister index.
672 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
673 MO.setSubReg(0);
674
675 // A kill flag implies killing the full register. Add corresponding super
676 // register kill.
677 if (MO.isKill()) {
678 MI->addRegisterKilled(PhysReg, TRI, true);
679 return true;
680 }
681
682 // A <def,read-undef> of a sub-register requires an implicit def of the full
683 // register.
684 if (MO.isDef() && MO.isUndef())
685 MI->addRegisterDefined(PhysReg, TRI);
686
687 return Dead;
688 }
689
690 // Handle special instruction operand like early clobbers and tied ops when
691 // there are additional physreg defines.
handleThroughOperands(MachineInstr * MI,SmallVectorImpl<unsigned> & VirtDead)692 void RAFast::handleThroughOperands(MachineInstr *MI,
693 SmallVectorImpl<unsigned> &VirtDead) {
694 DEBUG(dbgs() << "Scanning for through registers:");
695 SmallSet<unsigned, 8> ThroughRegs;
696 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
697 MachineOperand &MO = MI->getOperand(i);
698 if (!MO.isReg()) continue;
699 unsigned Reg = MO.getReg();
700 if (!TargetRegisterInfo::isVirtualRegister(Reg))
701 continue;
702 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
703 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
704 if (ThroughRegs.insert(Reg))
705 DEBUG(dbgs() << ' ' << PrintReg(Reg));
706 }
707 }
708
709 // If any physreg defines collide with preallocated through registers,
710 // we must spill and reallocate.
711 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
712 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
713 MachineOperand &MO = MI->getOperand(i);
714 if (!MO.isReg() || !MO.isDef()) continue;
715 unsigned Reg = MO.getReg();
716 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
717 markRegUsedInInstr(Reg);
718 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
719 if (ThroughRegs.count(PhysRegState[*AI]))
720 definePhysReg(MI, *AI, regFree);
721 }
722 }
723
724 SmallVector<unsigned, 8> PartialDefs;
725 DEBUG(dbgs() << "Allocating tied uses.\n");
726 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
727 MachineOperand &MO = MI->getOperand(i);
728 if (!MO.isReg()) continue;
729 unsigned Reg = MO.getReg();
730 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
731 if (MO.isUse()) {
732 unsigned DefIdx = 0;
733 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
734 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
735 << DefIdx << ".\n");
736 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
737 unsigned PhysReg = LRI->PhysReg;
738 setPhysReg(MI, i, PhysReg);
739 // Note: we don't update the def operand yet. That would cause the normal
740 // def-scan to attempt spilling.
741 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
742 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
743 // Reload the register, but don't assign to the operand just yet.
744 // That would confuse the later phys-def processing pass.
745 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
746 PartialDefs.push_back(LRI->PhysReg);
747 }
748 }
749
750 DEBUG(dbgs() << "Allocating early clobbers.\n");
751 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
752 MachineOperand &MO = MI->getOperand(i);
753 if (!MO.isReg()) continue;
754 unsigned Reg = MO.getReg();
755 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
756 if (!MO.isEarlyClobber())
757 continue;
758 // Note: defineVirtReg may invalidate MO.
759 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
760 unsigned PhysReg = LRI->PhysReg;
761 if (setPhysReg(MI, i, PhysReg))
762 VirtDead.push_back(Reg);
763 }
764
765 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
766 UsedInInstr.clear();
767 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
768 MachineOperand &MO = MI->getOperand(i);
769 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
770 unsigned Reg = MO.getReg();
771 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
772 DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
773 << " as used in instr\n");
774 markRegUsedInInstr(Reg);
775 }
776
777 // Also mark PartialDefs as used to avoid reallocation.
778 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
779 markRegUsedInInstr(PartialDefs[i]);
780 }
781
AllocateBasicBlock()782 void RAFast::AllocateBasicBlock() {
783 DEBUG(dbgs() << "\nAllocating " << *MBB);
784
785 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
786 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
787
788 MachineBasicBlock::iterator MII = MBB->begin();
789
790 // Add live-in registers as live.
791 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
792 E = MBB->livein_end(); I != E; ++I)
793 if (MRI->isAllocatable(*I))
794 definePhysReg(MII, *I, regReserved);
795
796 SmallVector<unsigned, 8> VirtDead;
797 SmallVector<MachineInstr*, 32> Coalesced;
798
799 // Otherwise, sequentially allocate each instruction in the MBB.
800 while (MII != MBB->end()) {
801 MachineInstr *MI = MII++;
802 const MCInstrDesc &MCID = MI->getDesc();
803 DEBUG({
804 dbgs() << "\n>> " << *MI << "Regs:";
805 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
806 if (PhysRegState[Reg] == regDisabled) continue;
807 dbgs() << " " << TRI->getName(Reg);
808 switch(PhysRegState[Reg]) {
809 case regFree:
810 break;
811 case regReserved:
812 dbgs() << "*";
813 break;
814 default: {
815 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
816 LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
817 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
818 if (I->Dirty)
819 dbgs() << "*";
820 assert(I->PhysReg == Reg && "Bad inverse map");
821 break;
822 }
823 }
824 }
825 dbgs() << '\n';
826 // Check that LiveVirtRegs is the inverse.
827 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
828 e = LiveVirtRegs.end(); i != e; ++i) {
829 assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
830 "Bad map key");
831 assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
832 "Bad map value");
833 assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
834 }
835 });
836
837 // Debug values are not allowed to change codegen in any way.
838 if (MI->isDebugValue()) {
839 bool ScanDbgValue = true;
840 while (ScanDbgValue) {
841 ScanDbgValue = false;
842 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
843 MachineOperand &MO = MI->getOperand(i);
844 if (!MO.isReg()) continue;
845 unsigned Reg = MO.getReg();
846 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
847 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
848 if (LRI != LiveVirtRegs.end())
849 setPhysReg(MI, i, LRI->PhysReg);
850 else {
851 int SS = StackSlotForVirtReg[Reg];
852 if (SS == -1) {
853 // We can't allocate a physreg for a DebugValue, sorry!
854 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
855 MO.setReg(0);
856 }
857 else {
858 // Modify DBG_VALUE now that the value is in a spill slot.
859 bool IsIndirect = MI->getOperand(1).isImm();
860 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
861 const MDNode *MDPtr =
862 MI->getOperand(MI->getNumOperands()-1).getMetadata();
863 DebugLoc DL = MI->getDebugLoc();
864 MachineBasicBlock *MBB = MI->getParent();
865 MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(MI), DL,
866 TII->get(TargetOpcode::DBG_VALUE))
867 .addFrameIndex(SS).addImm(Offset).addMetadata(MDPtr);
868 DEBUG(dbgs() << "Modifying debug info due to spill:"
869 << "\t" << *NewDV);
870 // Scan NewDV operands from the beginning.
871 MI = NewDV;
872 ScanDbgValue = true;
873 break;
874 }
875 }
876 LiveDbgValueMap[Reg].push_back(MI);
877 }
878 }
879 // Next instruction.
880 continue;
881 }
882
883 // If this is a copy, we may be able to coalesce.
884 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
885 if (MI->isCopy()) {
886 CopyDst = MI->getOperand(0).getReg();
887 CopySrc = MI->getOperand(1).getReg();
888 CopyDstSub = MI->getOperand(0).getSubReg();
889 CopySrcSub = MI->getOperand(1).getSubReg();
890 }
891
892 // Track registers used by instruction.
893 UsedInInstr.clear();
894
895 // First scan.
896 // Mark physreg uses and early clobbers as used.
897 // Find the end of the virtreg operands
898 unsigned VirtOpEnd = 0;
899 bool hasTiedOps = false;
900 bool hasEarlyClobbers = false;
901 bool hasPartialRedefs = false;
902 bool hasPhysDefs = false;
903 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
904 MachineOperand &MO = MI->getOperand(i);
905 // Make sure MRI knows about registers clobbered by regmasks.
906 if (MO.isRegMask()) {
907 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
908 continue;
909 }
910 if (!MO.isReg()) continue;
911 unsigned Reg = MO.getReg();
912 if (!Reg) continue;
913 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
914 VirtOpEnd = i+1;
915 if (MO.isUse()) {
916 hasTiedOps = hasTiedOps ||
917 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
918 } else {
919 if (MO.isEarlyClobber())
920 hasEarlyClobbers = true;
921 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
922 hasPartialRedefs = true;
923 }
924 continue;
925 }
926 if (!MRI->isAllocatable(Reg)) continue;
927 if (MO.isUse()) {
928 usePhysReg(MO);
929 } else if (MO.isEarlyClobber()) {
930 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
931 regFree : regReserved);
932 hasEarlyClobbers = true;
933 } else
934 hasPhysDefs = true;
935 }
936
937 // The instruction may have virtual register operands that must be allocated
938 // the same register at use-time and def-time: early clobbers and tied
939 // operands. If there are also physical defs, these registers must avoid
940 // both physical defs and uses, making them more constrained than normal
941 // operands.
942 // Similarly, if there are multiple defs and tied operands, we must make
943 // sure the same register is allocated to uses and defs.
944 // We didn't detect inline asm tied operands above, so just make this extra
945 // pass for all inline asm.
946 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
947 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
948 handleThroughOperands(MI, VirtDead);
949 // Don't attempt coalescing when we have funny stuff going on.
950 CopyDst = 0;
951 // Pretend we have early clobbers so the use operands get marked below.
952 // This is not necessary for the common case of a single tied use.
953 hasEarlyClobbers = true;
954 }
955
956 // Second scan.
957 // Allocate virtreg uses.
958 for (unsigned i = 0; i != VirtOpEnd; ++i) {
959 MachineOperand &MO = MI->getOperand(i);
960 if (!MO.isReg()) continue;
961 unsigned Reg = MO.getReg();
962 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
963 if (MO.isUse()) {
964 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
965 unsigned PhysReg = LRI->PhysReg;
966 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
967 if (setPhysReg(MI, i, PhysReg))
968 killVirtReg(LRI);
969 }
970 }
971
972 for (UsedInInstrSet::iterator
973 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
974 MRI->setRegUnitUsed(*I);
975
976 // Track registers defined by instruction - early clobbers and tied uses at
977 // this point.
978 UsedInInstr.clear();
979 if (hasEarlyClobbers) {
980 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
981 MachineOperand &MO = MI->getOperand(i);
982 if (!MO.isReg()) continue;
983 unsigned Reg = MO.getReg();
984 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
985 // Look for physreg defs and tied uses.
986 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
987 markRegUsedInInstr(Reg);
988 }
989 }
990
991 unsigned DefOpEnd = MI->getNumOperands();
992 if (MI->isCall()) {
993 // Spill all virtregs before a call. This serves two purposes: 1. If an
994 // exception is thrown, the landing pad is going to expect to find
995 // registers in their spill slots, and 2. we don't have to wade through
996 // all the <imp-def> operands on the call instruction.
997 DefOpEnd = VirtOpEnd;
998 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
999 spillAll(MI);
1000
1001 // The imp-defs are skipped below, but we still need to mark those
1002 // registers as used by the function.
1003 SkippedInstrs.insert(&MCID);
1004 }
1005
1006 // Third scan.
1007 // Allocate defs and collect dead defs.
1008 for (unsigned i = 0; i != DefOpEnd; ++i) {
1009 MachineOperand &MO = MI->getOperand(i);
1010 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1011 continue;
1012 unsigned Reg = MO.getReg();
1013
1014 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1015 if (!MRI->isAllocatable(Reg)) continue;
1016 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
1017 regFree : regReserved);
1018 continue;
1019 }
1020 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
1021 unsigned PhysReg = LRI->PhysReg;
1022 if (setPhysReg(MI, i, PhysReg)) {
1023 VirtDead.push_back(Reg);
1024 CopyDst = 0; // cancel coalescing;
1025 } else
1026 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1027 }
1028
1029 // Kill dead defs after the scan to ensure that multiple defs of the same
1030 // register are allocated identically. We didn't need to do this for uses
1031 // because we are crerating our own kill flags, and they are always at the
1032 // last use.
1033 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1034 killVirtReg(VirtDead[i]);
1035 VirtDead.clear();
1036
1037 for (UsedInInstrSet::iterator
1038 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
1039 MRI->setRegUnitUsed(*I);
1040
1041 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1042 DEBUG(dbgs() << "-- coalescing: " << *MI);
1043 Coalesced.push_back(MI);
1044 } else {
1045 DEBUG(dbgs() << "<< " << *MI);
1046 }
1047 }
1048
1049 // Spill all physical registers holding virtual registers now.
1050 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1051 spillAll(MBB->getFirstTerminator());
1052
1053 // Erase all the coalesced copies. We are delaying it until now because
1054 // LiveVirtRegs might refer to the instrs.
1055 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1056 MBB->erase(Coalesced[i]);
1057 NumCopies += Coalesced.size();
1058
1059 DEBUG(MBB->dump());
1060 }
1061
1062 /// runOnMachineFunction - Register allocate the whole function
1063 ///
runOnMachineFunction(MachineFunction & Fn)1064 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1065 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1066 << "********** Function: " << Fn.getName() << '\n');
1067 MF = &Fn;
1068 MRI = &MF->getRegInfo();
1069 TM = &Fn.getTarget();
1070 TRI = TM->getRegisterInfo();
1071 TII = TM->getInstrInfo();
1072 MRI->freezeReservedRegs(Fn);
1073 RegClassInfo.runOnMachineFunction(Fn);
1074 UsedInInstr.clear();
1075 UsedInInstr.setUniverse(TRI->getNumRegUnits());
1076
1077 assert(!MRI->isSSA() && "regalloc requires leaving SSA");
1078
1079 // initialize the virtual->physical register map to have a 'null'
1080 // mapping for all virtual registers
1081 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1082 LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
1083
1084 // Loop over all of the basic blocks, eliminating virtual register references
1085 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1086 MBBi != MBBe; ++MBBi) {
1087 MBB = &*MBBi;
1088 AllocateBasicBlock();
1089 }
1090
1091 // Add the clobber lists for all the instructions we skipped earlier.
1092 for (SmallPtrSet<const MCInstrDesc*, 4>::const_iterator
1093 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1094 if (const uint16_t *Defs = (*I)->getImplicitDefs())
1095 while (*Defs)
1096 MRI->setPhysRegUsed(*Defs++);
1097
1098 // All machine operands and other references to virtual registers have been
1099 // replaced. Remove the virtual registers.
1100 MRI->clearVirtRegs();
1101
1102 SkippedInstrs.clear();
1103 StackSlotForVirtReg.clear();
1104 LiveDbgValueMap.clear();
1105 return true;
1106 }
1107
createFastRegisterAllocator()1108 FunctionPass *llvm::createFastRegisterAllocator() {
1109 return new RAFast();
1110 }
1111