1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/IndexedMap.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
41 STATISTIC(NumCopies, "Number of copies coalesced");
43 static RegisterRegAlloc
44 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
47 class RAFast : public MachineFunctionPass {
50 RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1),
51 isBulkSpilling(false) {}
53 const TargetMachine *TM;
55 MachineRegisterInfo *MRI;
56 const TargetRegisterInfo *TRI;
57 const TargetInstrInfo *TII;
59 // Basic block currently being allocated.
60 MachineBasicBlock *MBB;
62 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
63 // values are spilled.
64 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
66 // Everything we know about a live virtual register.
68 MachineInstr *LastUse; // Last instr to use reg.
69 unsigned PhysReg; // Currently held here.
70 unsigned short LastOpNum; // OpNum on LastUse.
71 bool Dirty; // Register needs spill.
73 LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
77 typedef DenseMap<unsigned, LiveReg> LiveRegMap;
78 typedef LiveRegMap::value_type LiveRegEntry;
80 // LiveVirtRegs - This map contains entries for each virtual register
81 // that is currently available in a physical register.
82 LiveRegMap LiveVirtRegs;
84 DenseMap<unsigned, MachineInstr *> LiveDbgValueMap;
86 // RegState - Track the state of a physical register.
88 // A disabled register is not available for allocation, but an alias may
89 // be in use. A register can only be moved out of the disabled state if
90 // all aliases are disabled.
93 // A free register is not currently in use and can be allocated
94 // immediately without checking aliases.
97 // A reserved register has been assigned expolicitly (e.g., setting up a
98 // call parameter), and it remains reserved until it is used.
101 // A register state may also be a virtual register number, indication that
102 // the physical register is currently allocated to a virtual register. In
103 // that case, LiveVirtRegs contains the inverse mapping.
106 // PhysRegState - One of the RegState enums, or a virtreg.
107 std::vector<unsigned> PhysRegState;
109 // UsedInInstr - BitVector of physregs that are used in the current
110 // instruction, and so cannot be allocated.
111 BitVector UsedInInstr;
113 // Allocatable - vector of allocatable physical registers.
114 BitVector Allocatable;
116 // SkippedInstrs - Descriptors of instructions whose clobber list was ignored
117 // because all registers were spilled. It is still necessary to mark all the
118 // clobbered registers as used by the function.
119 SmallPtrSet<const TargetInstrDesc*, 4> SkippedInstrs;
121 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
122 // completely after spilling all live registers. LiveRegMap entries should
129 spillImpossible = ~0u
132 virtual const char *getPassName() const {
133 return "Fast Register Allocator";
136 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
137 AU.setPreservesCFG();
138 AU.addRequiredID(PHIEliminationID);
139 AU.addRequiredID(TwoAddressInstructionPassID);
140 MachineFunctionPass::getAnalysisUsage(AU);
144 bool runOnMachineFunction(MachineFunction &Fn);
145 void AllocateBasicBlock();
146 void handleThroughOperands(MachineInstr *MI,
147 SmallVectorImpl<unsigned> &VirtDead);
148 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
149 bool isLastUseOfLocalReg(MachineOperand&);
151 void addKillFlag(const LiveReg&);
152 void killVirtReg(LiveRegMap::iterator);
153 void killVirtReg(unsigned VirtReg);
154 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
155 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
157 void usePhysReg(MachineOperand&);
158 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
159 unsigned calcSpillCost(unsigned PhysReg) const;
160 void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
161 void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
162 LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
163 unsigned VirtReg, unsigned Hint);
164 LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
165 unsigned VirtReg, unsigned Hint);
166 void spillAll(MachineInstr *MI);
167 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
172 /// getStackSpaceFor - This allocates space for the specified virtual register
173 /// to be held on the stack.
174 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
175 // Find the location Reg would belong...
176 int SS = StackSlotForVirtReg[VirtReg];
178 return SS; // Already has space allocated?
180 // Allocate a new stack object for this spill location...
181 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
185 StackSlotForVirtReg[VirtReg] = FrameIdx;
189 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
190 /// its virtual register, and it is guaranteed to be a block-local register.
192 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
193 // Check for non-debug uses or defs following MO.
194 // This is the most likely way to fail - fast path it.
195 MachineOperand *Next = &MO;
196 while ((Next = Next->getNextOperandForReg()))
197 if (!Next->isDebug())
200 // If the register has ever been spilled or reloaded, we conservatively assume
201 // it is a global register used in multiple blocks.
202 if (StackSlotForVirtReg[MO.getReg()] != -1)
205 // Check that the use/def chain has exactly one operand - MO.
206 return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
209 /// addKillFlag - Set kill flags on last use of a virtual register.
210 void RAFast::addKillFlag(const LiveReg &LR) {
211 if (!LR.LastUse) return;
212 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
213 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
214 if (MO.getReg() == LR.PhysReg)
217 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
221 /// killVirtReg - Mark virtreg as no longer available.
222 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
223 addKillFlag(LRI->second);
224 const LiveReg &LR = LRI->second;
225 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
226 PhysRegState[LR.PhysReg] = regFree;
227 // Erase from LiveVirtRegs unless we're spilling in bulk.
229 LiveVirtRegs.erase(LRI);
232 /// killVirtReg - Mark virtreg as no longer available.
233 void RAFast::killVirtReg(unsigned VirtReg) {
234 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
235 "killVirtReg needs a virtual register");
236 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
237 if (LRI != LiveVirtRegs.end())
241 /// spillVirtReg - This method spills the value specified by VirtReg into the
242 /// corresponding stack slot if needed. If isKill is set, the register is also
244 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
245 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
246 "Spilling a physical register is illegal!");
247 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
248 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
249 spillVirtReg(MI, LRI);
252 /// spillVirtReg - Do the actual work of spilling.
253 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
254 LiveRegMap::iterator LRI) {
255 LiveReg &LR = LRI->second;
256 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
259 // If this physreg is used by the instruction, we want to kill it on the
260 // instruction, not on the spill.
261 bool SpillKill = LR.LastUse != MI;
263 DEBUG(dbgs() << "Spilling %reg" << LRI->first
264 << " in " << TRI->getName(LR.PhysReg));
265 const TargetRegisterClass *RC = MRI->getRegClass(LRI->first);
266 int FI = getStackSpaceFor(LRI->first, RC);
267 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
268 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
269 ++NumStores; // Update statistics
271 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
272 // identify spilled location as the place to find corresponding variable's
274 if (MachineInstr *DBG = LiveDbgValueMap.lookup(LRI->first)) {
275 const MDNode *MDPtr =
276 DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
278 if (DBG->getOperand(1).isImm())
279 Offset = DBG->getOperand(1).getImm();
280 DebugLoc DL = MI->getDebugLoc();
281 if (MachineInstr *NewDV =
282 TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
283 MachineBasicBlock *MBB = DBG->getParent();
284 MBB->insert(MI, NewDV);
285 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
286 LiveDbgValueMap[LRI->first] = NewDV;
290 LR.LastUse = 0; // Don't kill register again
295 /// spillAll - Spill all dirty virtregs without killing them.
296 void RAFast::spillAll(MachineInstr *MI) {
297 if (LiveVirtRegs.empty()) return;
298 isBulkSpilling = true;
299 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
300 // of spilling here is deterministic, if arbitrary.
301 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
304 LiveVirtRegs.clear();
305 isBulkSpilling = false;
308 /// usePhysReg - Handle the direct use of a physical register.
309 /// Check that the register is not used by a virtreg.
310 /// Kill the physreg, marking it free.
311 /// This may add implicit kills to MO->getParent() and invalidate MO.
312 void RAFast::usePhysReg(MachineOperand &MO) {
313 unsigned PhysReg = MO.getReg();
314 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
315 "Bad usePhysReg operand");
317 switch (PhysRegState[PhysReg]) {
321 PhysRegState[PhysReg] = regFree;
324 UsedInInstr.set(PhysReg);
328 // The physreg was allocated to a virtual register. That means to value we
329 // wanted has been clobbered.
330 llvm_unreachable("Instruction uses an allocated register");
333 // Maybe a superregister is reserved?
334 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
335 unsigned Alias = *AS; ++AS) {
336 switch (PhysRegState[Alias]) {
340 assert(TRI->isSuperRegister(PhysReg, Alias) &&
341 "Instruction is not using a subregister of a reserved register");
342 // Leave the superregister in the working set.
343 PhysRegState[Alias] = regFree;
344 UsedInInstr.set(Alias);
345 MO.getParent()->addRegisterKilled(Alias, TRI, true);
348 if (TRI->isSuperRegister(PhysReg, Alias)) {
349 // Leave the superregister in the working set.
350 UsedInInstr.set(Alias);
351 MO.getParent()->addRegisterKilled(Alias, TRI, true);
354 // Some other alias was in the working set - clear it.
355 PhysRegState[Alias] = regDisabled;
358 llvm_unreachable("Instruction uses an alias of an allocated register");
362 // All aliases are disabled, bring register into working set.
363 PhysRegState[PhysReg] = regFree;
364 UsedInInstr.set(PhysReg);
368 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
369 /// virtregs. This is very similar to defineVirtReg except the physreg is
370 /// reserved instead of allocated.
371 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
373 UsedInInstr.set(PhysReg);
374 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
378 spillVirtReg(MI, VirtReg);
382 PhysRegState[PhysReg] = NewState;
386 // This is a disabled register, disable all aliases.
387 PhysRegState[PhysReg] = NewState;
388 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
389 unsigned Alias = *AS; ++AS) {
390 UsedInInstr.set(Alias);
391 switch (unsigned VirtReg = PhysRegState[Alias]) {
395 spillVirtReg(MI, VirtReg);
399 PhysRegState[Alias] = regDisabled;
400 if (TRI->isSuperRegister(PhysReg, Alias))
408 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
409 // aliases so it is free for allocation.
410 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
411 // can be allocated directly.
412 // Returns spillImpossible when PhysReg or an alias can't be spilled.
413 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
414 if (UsedInInstr.test(PhysReg))
415 return spillImpossible;
416 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
422 return spillImpossible;
424 return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
427 // This is a disabled register, add up const of aliases.
429 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
430 unsigned Alias = *AS; ++AS) {
431 if (UsedInInstr.test(Alias))
432 return spillImpossible;
433 switch (unsigned VirtReg = PhysRegState[Alias]) {
440 return spillImpossible;
442 Cost += LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
450 /// assignVirtToPhysReg - This method updates local state so that we know
451 /// that PhysReg is the proper container for VirtReg now. The physical
452 /// register must not be used for anything else when this is called.
454 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
455 DEBUG(dbgs() << "Assigning %reg" << LRE.first << " to "
456 << TRI->getName(PhysReg) << "\n");
457 PhysRegState[PhysReg] = LRE.first;
458 assert(!LRE.second.PhysReg && "Already assigned a physreg");
459 LRE.second.PhysReg = PhysReg;
462 /// allocVirtReg - Allocate a physical register for VirtReg.
463 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
464 const unsigned VirtReg = LRE.first;
466 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
467 "Can only allocate virtual registers");
469 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
471 // Ignore invalid hints.
472 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
473 !RC->contains(Hint) || !Allocatable.test(Hint)))
476 // Take hint when possible.
478 switch(calcSpillCost(Hint)) {
480 definePhysReg(MI, Hint, regFree);
483 return assignVirtToPhysReg(LRE, Hint);
484 case spillImpossible:
489 TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
490 TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
492 // First try to find a completely free register.
493 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
494 unsigned PhysReg = *I;
495 if (PhysRegState[PhysReg] == regFree && !UsedInInstr.test(PhysReg))
496 return assignVirtToPhysReg(LRE, PhysReg);
499 DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
502 unsigned BestReg = 0, BestCost = spillImpossible;
503 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
504 unsigned Cost = calcSpillCost(*I);
505 // Cost is 0 when all aliases are already disabled.
507 return assignVirtToPhysReg(LRE, *I);
509 BestReg = *I, BestCost = Cost;
513 definePhysReg(MI, BestReg, regFree);
514 return assignVirtToPhysReg(LRE, BestReg);
517 // Nothing we can do.
519 raw_string_ostream Msg(msg);
520 Msg << "Ran out of registers during register allocation!";
521 if (MI->isInlineAsm()) {
522 Msg << "\nPlease check your inline asm statement for "
523 << "invalid constraints:\n";
526 report_fatal_error(Msg.str());
529 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
530 RAFast::LiveRegMap::iterator
531 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
532 unsigned VirtReg, unsigned Hint) {
533 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
534 "Not a virtual register");
535 LiveRegMap::iterator LRI;
537 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
538 LiveReg &LR = LRI->second;
540 // If there is no hint, peek at the only use of this register.
541 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
542 MRI->hasOneNonDBGUse(VirtReg)) {
543 const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
544 // It's a copy, use the destination register as a hint.
545 if (UseMI.isCopyLike())
546 Hint = UseMI.getOperand(0).getReg();
548 allocVirtReg(MI, *LRI, Hint);
549 } else if (LR.LastUse) {
550 // Redefining a live register - kill at the last use, unless it is this
551 // instruction defining VirtReg multiple times.
552 if (LR.LastUse != MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
555 assert(LR.PhysReg && "Register not assigned");
557 LR.LastOpNum = OpNum;
559 UsedInInstr.set(LR.PhysReg);
563 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
564 RAFast::LiveRegMap::iterator
565 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
566 unsigned VirtReg, unsigned Hint) {
567 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
568 "Not a virtual register");
569 LiveRegMap::iterator LRI;
571 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
572 LiveReg &LR = LRI->second;
573 MachineOperand &MO = MI->getOperand(OpNum);
575 allocVirtReg(MI, *LRI, Hint);
576 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
577 int FrameIndex = getStackSpaceFor(VirtReg, RC);
578 DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
579 << TRI->getName(LR.PhysReg) << "\n");
580 TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
582 } else if (LR.Dirty) {
583 if (isLastUseOfLocalReg(MO)) {
584 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
589 } else if (MO.isKill()) {
590 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
592 } else if (MO.isDead()) {
593 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
596 } else if (MO.isKill()) {
597 // We must remove kill flags from uses of reloaded registers because the
598 // register would be killed immediately, and there might be a second use:
599 // %foo = OR %x<kill>, %x
600 // This would cause a second reload of %x into a different register.
601 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
603 } else if (MO.isDead()) {
604 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
607 assert(LR.PhysReg && "Register not assigned");
609 LR.LastOpNum = OpNum;
610 UsedInInstr.set(LR.PhysReg);
614 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
615 // subregs. This may invalidate any operand pointers.
616 // Return true if the operand kills its register.
617 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
618 MachineOperand &MO = MI->getOperand(OpNum);
619 if (!MO.getSubReg()) {
621 return MO.isKill() || MO.isDead();
624 // Handle subregister index.
625 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
628 // A kill flag implies killing the full register. Add corresponding super
631 MI->addRegisterKilled(PhysReg, TRI, true);
637 // Handle special instruction operand like early clobbers and tied ops when
638 // there are additional physreg defines.
639 void RAFast::handleThroughOperands(MachineInstr *MI,
640 SmallVectorImpl<unsigned> &VirtDead) {
641 DEBUG(dbgs() << "Scanning for through registers:");
642 SmallSet<unsigned, 8> ThroughRegs;
643 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
644 MachineOperand &MO = MI->getOperand(i);
645 if (!MO.isReg()) continue;
646 unsigned Reg = MO.getReg();
647 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
648 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
649 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
650 if (ThroughRegs.insert(Reg))
651 DEBUG(dbgs() << " %reg" << Reg);
655 // If any physreg defines collide with preallocated through registers,
656 // we must spill and reallocate.
657 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
658 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
659 MachineOperand &MO = MI->getOperand(i);
660 if (!MO.isReg() || !MO.isDef()) continue;
661 unsigned Reg = MO.getReg();
662 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
663 UsedInInstr.set(Reg);
664 if (ThroughRegs.count(PhysRegState[Reg]))
665 definePhysReg(MI, Reg, regFree);
666 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
667 UsedInInstr.set(*AS);
668 if (ThroughRegs.count(PhysRegState[*AS]))
669 definePhysReg(MI, *AS, regFree);
673 SmallVector<unsigned, 8> PartialDefs;
674 DEBUG(dbgs() << "Allocating tied uses and early clobbers.\n");
675 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
676 MachineOperand &MO = MI->getOperand(i);
677 if (!MO.isReg()) continue;
678 unsigned Reg = MO.getReg();
679 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
682 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
683 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
685 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
686 unsigned PhysReg = LRI->second.PhysReg;
687 setPhysReg(MI, i, PhysReg);
688 // Note: we don't update the def operand yet. That would cause the normal
689 // def-scan to attempt spilling.
690 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
691 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
692 // Reload the register, but don't assign to the operand just yet.
693 // That would confuse the later phys-def processing pass.
694 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
695 PartialDefs.push_back(LRI->second.PhysReg);
696 } else if (MO.isEarlyClobber()) {
697 // Note: defineVirtReg may invalidate MO.
698 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
699 unsigned PhysReg = LRI->second.PhysReg;
700 if (setPhysReg(MI, i, PhysReg))
701 VirtDead.push_back(Reg);
705 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
707 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
708 MachineOperand &MO = MI->getOperand(i);
709 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
710 unsigned Reg = MO.getReg();
711 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
712 UsedInInstr.set(Reg);
713 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
714 UsedInInstr.set(*AS);
717 // Also mark PartialDefs as used to avoid reallocation.
718 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
719 UsedInInstr.set(PartialDefs[i]);
722 void RAFast::AllocateBasicBlock() {
723 DEBUG(dbgs() << "\nAllocating " << *MBB);
725 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
726 assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
728 MachineBasicBlock::iterator MII = MBB->begin();
730 // Add live-in registers as live.
731 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
732 E = MBB->livein_end(); I != E; ++I)
733 definePhysReg(MII, *I, regReserved);
735 SmallVector<unsigned, 8> VirtDead;
736 SmallVector<MachineInstr*, 32> Coalesced;
738 // Otherwise, sequentially allocate each instruction in the MBB.
739 while (MII != MBB->end()) {
740 MachineInstr *MI = MII++;
741 const TargetInstrDesc &TID = MI->getDesc();
743 dbgs() << "\n>> " << *MI << "Regs:";
744 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
745 if (PhysRegState[Reg] == regDisabled) continue;
746 dbgs() << " " << TRI->getName(Reg);
747 switch(PhysRegState[Reg]) {
754 dbgs() << "=%reg" << PhysRegState[Reg];
755 if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
757 assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
763 // Check that LiveVirtRegs is the inverse.
764 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
765 e = LiveVirtRegs.end(); i != e; ++i) {
766 assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
768 assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
770 assert(PhysRegState[i->second.PhysReg] == i->first &&
775 // Debug values are not allowed to change codegen in any way.
776 if (MI->isDebugValue()) {
777 bool ScanDbgValue = true;
778 while (ScanDbgValue) {
779 ScanDbgValue = false;
780 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
781 MachineOperand &MO = MI->getOperand(i);
782 if (!MO.isReg()) continue;
783 unsigned Reg = MO.getReg();
784 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
785 LiveDbgValueMap[Reg] = MI;
786 LiveRegMap::iterator LRI = LiveVirtRegs.find(Reg);
787 if (LRI != LiveVirtRegs.end())
788 setPhysReg(MI, i, LRI->second.PhysReg);
790 int SS = StackSlotForVirtReg[Reg];
792 MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
794 // Modify DBG_VALUE now that the value is in a spill slot.
795 int64_t Offset = MI->getOperand(1).getImm();
796 const MDNode *MDPtr =
797 MI->getOperand(MI->getNumOperands()-1).getMetadata();
798 DebugLoc DL = MI->getDebugLoc();
799 if (MachineInstr *NewDV =
800 TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
801 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
802 MachineBasicBlock *MBB = MI->getParent();
803 MBB->insert(MBB->erase(MI), NewDV);
804 // Scan NewDV operands from the beginning.
809 MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
818 // If this is a copy, we may be able to coalesce.
819 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
821 CopyDst = MI->getOperand(0).getReg();
822 CopySrc = MI->getOperand(1).getReg();
823 CopyDstSub = MI->getOperand(0).getSubReg();
824 CopySrcSub = MI->getOperand(1).getSubReg();
827 // Track registers used by instruction.
831 // Mark physreg uses and early clobbers as used.
832 // Find the end of the virtreg operands
833 unsigned VirtOpEnd = 0;
834 bool hasTiedOps = false;
835 bool hasEarlyClobbers = false;
836 bool hasPartialRedefs = false;
837 bool hasPhysDefs = false;
838 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
839 MachineOperand &MO = MI->getOperand(i);
840 if (!MO.isReg()) continue;
841 unsigned Reg = MO.getReg();
843 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
846 hasTiedOps = hasTiedOps ||
847 TID.getOperandConstraint(i, TOI::TIED_TO) != -1;
849 if (MO.isEarlyClobber())
850 hasEarlyClobbers = true;
851 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
852 hasPartialRedefs = true;
856 if (!Allocatable.test(Reg)) continue;
859 } else if (MO.isEarlyClobber()) {
860 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
861 regFree : regReserved);
862 hasEarlyClobbers = true;
867 // The instruction may have virtual register operands that must be allocated
868 // the same register at use-time and def-time: early clobbers and tied
869 // operands. If there are also physical defs, these registers must avoid
870 // both physical defs and uses, making them more constrained than normal
872 // Similarly, if there are multiple defs and tied operands, we must make sure
873 // the same register is allocated to uses and defs.
874 // We didn't detect inline asm tied operands above, so just make this extra
875 // pass for all inline asm.
876 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
877 (hasTiedOps && (hasPhysDefs || TID.getNumDefs() > 1))) {
878 handleThroughOperands(MI, VirtDead);
879 // Don't attempt coalescing when we have funny stuff going on.
881 // Pretend we have early clobbers so the use operands get marked below.
882 // This is not necessary for the common case of a single tied use.
883 hasEarlyClobbers = true;
887 // Allocate virtreg uses.
888 for (unsigned i = 0; i != VirtOpEnd; ++i) {
889 MachineOperand &MO = MI->getOperand(i);
890 if (!MO.isReg()) continue;
891 unsigned Reg = MO.getReg();
892 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
894 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
895 unsigned PhysReg = LRI->second.PhysReg;
896 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
897 if (setPhysReg(MI, i, PhysReg))
902 MRI->addPhysRegsUsed(UsedInInstr);
904 // Track registers defined by instruction - early clobbers and tied uses at
907 if (hasEarlyClobbers) {
908 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
909 MachineOperand &MO = MI->getOperand(i);
910 if (!MO.isReg()) continue;
911 unsigned Reg = MO.getReg();
912 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
913 // Look for physreg defs and tied uses.
914 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
915 UsedInInstr.set(Reg);
916 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
917 UsedInInstr.set(*AS);
921 unsigned DefOpEnd = MI->getNumOperands();
923 // Spill all virtregs before a call. This serves two purposes: 1. If an
924 // exception is thrown, the landing pad is going to expect to find registers
925 // in their spill slots, and 2. we don't have to wade through all the
926 // <imp-def> operands on the call instruction.
927 DefOpEnd = VirtOpEnd;
928 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
931 // The imp-defs are skipped below, but we still need to mark those
932 // registers as used by the function.
933 SkippedInstrs.insert(&TID);
937 // Allocate defs and collect dead defs.
938 for (unsigned i = 0; i != DefOpEnd; ++i) {
939 MachineOperand &MO = MI->getOperand(i);
940 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
942 unsigned Reg = MO.getReg();
944 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
945 if (!Allocatable.test(Reg)) continue;
946 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
947 regFree : regReserved);
950 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
951 unsigned PhysReg = LRI->second.PhysReg;
952 if (setPhysReg(MI, i, PhysReg)) {
953 VirtDead.push_back(Reg);
954 CopyDst = 0; // cancel coalescing;
956 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
959 // Kill dead defs after the scan to ensure that multiple defs of the same
960 // register are allocated identically. We didn't need to do this for uses
961 // because we are crerating our own kill flags, and they are always at the
963 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
964 killVirtReg(VirtDead[i]);
967 MRI->addPhysRegsUsed(UsedInInstr);
969 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
970 DEBUG(dbgs() << "-- coalescing: " << *MI);
971 Coalesced.push_back(MI);
973 DEBUG(dbgs() << "<< " << *MI);
977 // Spill all physical registers holding virtual registers now.
978 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
979 spillAll(MBB->getFirstTerminator());
981 // Erase all the coalesced copies. We are delaying it until now because
982 // LiveVirtRegs might refer to the instrs.
983 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
984 MBB->erase(Coalesced[i]);
985 NumCopies += Coalesced.size();
990 /// runOnMachineFunction - Register allocate the whole function
992 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
993 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
994 << "********** Function: "
995 << ((Value*)Fn.getFunction())->getName() << '\n');
997 MRI = &MF->getRegInfo();
998 TM = &Fn.getTarget();
999 TRI = TM->getRegisterInfo();
1000 TII = TM->getInstrInfo();
1002 UsedInInstr.resize(TRI->getNumRegs());
1003 Allocatable = TRI->getAllocatableSet(*MF);
1005 // initialize the virtual->physical register map to have a 'null'
1006 // mapping for all virtual registers
1007 unsigned LastVirtReg = MRI->getLastVirtReg();
1008 StackSlotForVirtReg.grow(LastVirtReg);
1010 // Loop over all of the basic blocks, eliminating virtual register references
1011 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1012 MBBi != MBBe; ++MBBi) {
1014 AllocateBasicBlock();
1017 // Make sure the set of used physregs is closed under subreg operations.
1018 MRI->closePhysRegsUsed(*TRI);
1020 // Add the clobber lists for all the instructions we skipped earlier.
1021 for (SmallPtrSet<const TargetInstrDesc*, 4>::const_iterator
1022 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1023 if (const unsigned *Defs = (*I)->getImplicitDefs())
1025 MRI->setPhysRegUsed(*Defs++);
1027 SkippedInstrs.clear();
1028 StackSlotForVirtReg.clear();
1029 LiveDbgValueMap.clear();
1033 FunctionPass *llvm::createFastRegisterAllocator() {
1034 return new RAFast();