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 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/IndexedMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/SparseSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
38 #define DEBUG_TYPE "regalloc"
40 STATISTIC(NumStores, "Number of stores added");
41 STATISTIC(NumLoads , "Number of loads added");
42 STATISTIC(NumCopies, "Number of copies coalesced");
44 static RegisterRegAlloc
45 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
48 class RAFast : public MachineFunctionPass {
51 RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
52 isBulkSpilling(false) {}
56 MachineRegisterInfo *MRI;
57 const TargetRegisterInfo *TRI;
58 const TargetInstrInfo *TII;
59 RegisterClassInfo RegClassInfo;
61 // Basic block currently being allocated.
62 MachineBasicBlock *MBB;
64 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
65 // values are spilled.
66 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
68 // Everything we know about a live virtual register.
70 MachineInstr *LastUse; // Last instr to use reg.
71 unsigned VirtReg; // Virtual register number.
72 unsigned PhysReg; // Currently held here.
73 unsigned short LastOpNum; // OpNum on LastUse.
74 bool Dirty; // Register needs spill.
76 explicit LiveReg(unsigned v)
77 : LastUse(nullptr), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false){}
79 unsigned getSparseSetIndex() const {
80 return TargetRegisterInfo::virtReg2Index(VirtReg);
84 typedef SparseSet<LiveReg> LiveRegMap;
86 // LiveVirtRegs - This map contains entries for each virtual register
87 // that is currently available in a physical register.
88 LiveRegMap LiveVirtRegs;
90 DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
92 // RegState - Track the state of a physical register.
94 // A disabled register is not available for allocation, but an alias may
95 // be in use. A register can only be moved out of the disabled state if
96 // all aliases are disabled.
99 // A free register is not currently in use and can be allocated
100 // immediately without checking aliases.
103 // A reserved register has been assigned explicitly (e.g., setting up a
104 // call parameter), and it remains reserved until it is used.
107 // A register state may also be a virtual register number, indication that
108 // the physical register is currently allocated to a virtual register. In
109 // that case, LiveVirtRegs contains the inverse mapping.
112 // PhysRegState - One of the RegState enums, or a virtreg.
113 std::vector<unsigned> PhysRegState;
115 // Set of register units.
116 typedef SparseSet<unsigned> UsedInInstrSet;
118 // Set of register units that are used in the current instruction, and so
119 // cannot be allocated.
120 UsedInInstrSet UsedInInstr;
122 // Mark a physreg as used in this instruction.
123 void markRegUsedInInstr(unsigned PhysReg) {
124 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
125 UsedInInstr.insert(*Units);
128 // Check if a physreg or any of its aliases are used in this instruction.
129 bool isRegUsedInInstr(unsigned PhysReg) const {
130 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
131 if (UsedInInstr.count(*Units))
136 // SkippedInstrs - Descriptors of instructions whose clobber list was
137 // ignored because all registers were spilled. It is still necessary to
138 // mark all the clobbered registers as used by the function.
139 SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
141 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
142 // completely after spilling all live registers. LiveRegMap entries should
149 spillImpossible = ~0u
152 StringRef getPassName() const override { return "Fast Register Allocator"; }
154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.setPreservesCFG();
156 MachineFunctionPass::getAnalysisUsage(AU);
159 MachineFunctionProperties getRequiredProperties() const override {
160 return MachineFunctionProperties().set(
161 MachineFunctionProperties::Property::NoPHIs);
164 MachineFunctionProperties getSetProperties() const override {
165 return MachineFunctionProperties().set(
166 MachineFunctionProperties::Property::NoVRegs);
170 bool runOnMachineFunction(MachineFunction &Fn) override;
171 void AllocateBasicBlock();
172 void handleThroughOperands(MachineInstr *MI,
173 SmallVectorImpl<unsigned> &VirtDead);
174 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
175 bool isLastUseOfLocalReg(MachineOperand&);
177 void addKillFlag(const LiveReg&);
178 void killVirtReg(LiveRegMap::iterator);
179 void killVirtReg(unsigned VirtReg);
180 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
181 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
183 void usePhysReg(MachineOperand&);
184 void definePhysReg(MachineInstr &MI, unsigned PhysReg, RegState NewState);
185 unsigned calcSpillCost(unsigned PhysReg) const;
186 void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
187 LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
188 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
190 LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
191 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
193 LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
194 LiveRegMap::iterator allocVirtReg(MachineInstr &MI, LiveRegMap::iterator,
196 LiveRegMap::iterator defineVirtReg(MachineInstr &MI, unsigned OpNum,
197 unsigned VirtReg, unsigned Hint);
198 LiveRegMap::iterator reloadVirtReg(MachineInstr &MI, unsigned OpNum,
199 unsigned VirtReg, unsigned Hint);
200 void spillAll(MachineBasicBlock::iterator MI);
201 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
206 /// getStackSpaceFor - This allocates space for the specified virtual register
207 /// to be held on the stack.
208 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
209 // Find the location Reg would belong...
210 int SS = StackSlotForVirtReg[VirtReg];
212 return SS; // Already has space allocated?
214 // Allocate a new stack object for this spill location...
215 int FrameIdx = MF->getFrameInfo().CreateSpillStackObject(RC->getSize(),
219 StackSlotForVirtReg[VirtReg] = FrameIdx;
223 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
224 /// its virtual register, and it is guaranteed to be a block-local register.
226 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
227 // If the register has ever been spilled or reloaded, we conservatively assume
228 // it is a global register used in multiple blocks.
229 if (StackSlotForVirtReg[MO.getReg()] != -1)
232 // Check that the use/def chain has exactly one operand - MO.
233 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
236 return ++I == MRI->reg_nodbg_end();
239 /// addKillFlag - Set kill flags on last use of a virtual register.
240 void RAFast::addKillFlag(const LiveReg &LR) {
241 if (!LR.LastUse) return;
242 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
243 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
244 if (MO.getReg() == LR.PhysReg)
247 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
251 /// killVirtReg - Mark virtreg as no longer available.
252 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
254 assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
255 "Broken RegState mapping");
256 PhysRegState[LRI->PhysReg] = regFree;
257 // Erase from LiveVirtRegs unless we're spilling in bulk.
259 LiveVirtRegs.erase(LRI);
262 /// killVirtReg - Mark virtreg as no longer available.
263 void RAFast::killVirtReg(unsigned VirtReg) {
264 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
265 "killVirtReg needs a virtual register");
266 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
267 if (LRI != LiveVirtRegs.end())
271 /// spillVirtReg - This method spills the value specified by VirtReg into the
272 /// corresponding stack slot if needed.
273 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
274 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
275 "Spilling a physical register is illegal!");
276 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
277 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
278 spillVirtReg(MI, LRI);
281 /// spillVirtReg - Do the actual work of spilling.
282 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
283 LiveRegMap::iterator LRI) {
285 assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
288 // If this physreg is used by the instruction, we want to kill it on the
289 // instruction, not on the spill.
290 bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
292 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
293 << " in " << PrintReg(LR.PhysReg, TRI));
294 const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
295 int FI = getStackSpaceFor(LRI->VirtReg, RC);
296 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
297 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
298 ++NumStores; // Update statistics
300 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
301 // identify spilled location as the place to find corresponding variable's
303 SmallVectorImpl<MachineInstr *> &LRIDbgValues =
304 LiveDbgValueMap[LRI->VirtReg];
305 for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
306 MachineInstr *DBG = LRIDbgValues[li];
307 MachineInstr *NewDV = buildDbgValueForSpill(*MBB, MI, *DBG, FI);
308 assert(NewDV->getParent() == MBB && "dangling parent pointer");
310 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
312 // Now this register is spilled there is should not be any DBG_VALUE
313 // pointing to this register because they are all pointing to spilled value
315 LRIDbgValues.clear();
317 LR.LastUse = nullptr; // Don't kill register again
322 /// spillAll - Spill all dirty virtregs without killing them.
323 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
324 if (LiveVirtRegs.empty()) return;
325 isBulkSpilling = true;
326 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
327 // of spilling here is deterministic, if arbitrary.
328 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
331 LiveVirtRegs.clear();
332 isBulkSpilling = false;
335 /// usePhysReg - Handle the direct use of a physical register.
336 /// Check that the register is not used by a virtreg.
337 /// Kill the physreg, marking it free.
338 /// This may add implicit kills to MO->getParent() and invalidate MO.
339 void RAFast::usePhysReg(MachineOperand &MO) {
340 unsigned PhysReg = MO.getReg();
341 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
342 "Bad usePhysReg operand");
344 // Ignore undef uses.
348 markRegUsedInInstr(PhysReg);
349 switch (PhysRegState[PhysReg]) {
353 PhysRegState[PhysReg] = regFree;
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");
364 // Maybe a superregister is reserved?
365 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
366 unsigned Alias = *AI;
367 switch (PhysRegState[Alias]) {
371 // Either PhysReg is a subregister of Alias and we mark the
372 // whole register as free, or PhysReg is the superregister of
373 // Alias and we mark all the aliases as disabled before freeing
375 // In the latter case, since PhysReg was disabled, this means that
376 // its value is defined only by physical sub-registers. This check
377 // is performed by the assert of the default case in this loop.
378 // Note: The value of the superregister may only be partial
379 // defined, that is why regDisabled is a valid state for aliases.
380 assert((TRI->isSuperRegister(PhysReg, Alias) ||
381 TRI->isSuperRegister(Alias, PhysReg)) &&
382 "Instruction is not using a subregister of a reserved register");
385 if (TRI->isSuperRegister(PhysReg, Alias)) {
386 // Leave the superregister in the working set.
387 PhysRegState[Alias] = regFree;
388 MO.getParent()->addRegisterKilled(Alias, TRI, true);
391 // Some other alias was in the working set - clear it.
392 PhysRegState[Alias] = regDisabled;
395 llvm_unreachable("Instruction uses an alias of an allocated register");
399 // All aliases are disabled, bring register into working set.
400 PhysRegState[PhysReg] = regFree;
404 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
405 /// virtregs. This is very similar to defineVirtReg except the physreg is
406 /// reserved instead of allocated.
407 void RAFast::definePhysReg(MachineInstr &MI, unsigned PhysReg,
409 markRegUsedInInstr(PhysReg);
410 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
414 spillVirtReg(MI, VirtReg);
418 PhysRegState[PhysReg] = NewState;
422 // This is a disabled register, disable all aliases.
423 PhysRegState[PhysReg] = NewState;
424 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
425 unsigned Alias = *AI;
426 switch (unsigned VirtReg = PhysRegState[Alias]) {
430 spillVirtReg(MI, VirtReg);
434 PhysRegState[Alias] = regDisabled;
435 if (TRI->isSuperRegister(PhysReg, Alias))
443 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
444 // aliases so it is free for allocation.
445 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
446 // can be allocated directly.
447 // Returns spillImpossible when PhysReg or an alias can't be spilled.
448 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
449 if (isRegUsedInInstr(PhysReg)) {
450 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
451 return spillImpossible;
453 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
459 DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
460 << PrintReg(PhysReg, TRI) << " is reserved already.\n");
461 return spillImpossible;
463 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
464 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
465 return I->Dirty ? spillDirty : spillClean;
469 // This is a disabled register, add up cost of aliases.
470 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
472 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
473 unsigned Alias = *AI;
474 switch (unsigned VirtReg = PhysRegState[Alias]) {
481 return spillImpossible;
483 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
484 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
485 Cost += I->Dirty ? spillDirty : spillClean;
494 /// assignVirtToPhysReg - This method updates local state so that we know
495 /// that PhysReg is the proper container for VirtReg now. The physical
496 /// register must not be used for anything else when this is called.
498 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
499 DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
500 << PrintReg(PhysReg, TRI) << "\n");
501 PhysRegState[PhysReg] = LR.VirtReg;
502 assert(!LR.PhysReg && "Already assigned a physreg");
503 LR.PhysReg = PhysReg;
506 RAFast::LiveRegMap::iterator
507 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
508 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
509 assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
510 assignVirtToPhysReg(*LRI, PhysReg);
514 /// allocVirtReg - Allocate a physical register for VirtReg.
515 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr &MI,
516 LiveRegMap::iterator LRI,
518 const unsigned VirtReg = LRI->VirtReg;
520 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
521 "Can only allocate virtual registers");
523 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
525 // Ignore invalid hints.
526 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
527 !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
530 // Take hint when possible.
532 // Ignore the hint if we would have to spill a dirty register.
533 unsigned Cost = calcSpillCost(Hint);
534 if (Cost < spillDirty) {
536 definePhysReg(MI, Hint, regFree);
537 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
538 // That invalidates LRI, so run a new lookup for VirtReg.
539 return assignVirtToPhysReg(VirtReg, Hint);
543 ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
545 // First try to find a completely free register.
546 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
547 unsigned PhysReg = *I;
548 if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
549 assignVirtToPhysReg(*LRI, PhysReg);
554 DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
555 << TRI->getRegClassName(RC) << "\n");
557 unsigned BestReg = 0, BestCost = spillImpossible;
558 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
559 unsigned Cost = calcSpillCost(*I);
560 DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
561 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
562 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
563 // Cost is 0 when all aliases are already disabled.
565 assignVirtToPhysReg(*LRI, *I);
569 BestReg = *I, BestCost = Cost;
573 definePhysReg(MI, BestReg, regFree);
574 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
575 // That invalidates LRI, so run a new lookup for VirtReg.
576 return assignVirtToPhysReg(VirtReg, BestReg);
579 // Nothing we can do. Report an error and keep going with a bad allocation.
580 if (MI.isInlineAsm())
581 MI.emitError("inline assembly requires more registers than available");
583 MI.emitError("ran out of registers during register allocation");
584 definePhysReg(MI, *AO.begin(), regFree);
585 return assignVirtToPhysReg(VirtReg, *AO.begin());
588 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
589 RAFast::LiveRegMap::iterator RAFast::defineVirtReg(MachineInstr &MI,
593 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
594 "Not a virtual register");
595 LiveRegMap::iterator LRI;
597 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
599 // If there is no hint, peek at the only use of this register.
600 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
601 MRI->hasOneNonDBGUse(VirtReg)) {
602 const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
603 // It's a copy, use the destination register as a hint.
604 if (UseMI.isCopyLike())
605 Hint = UseMI.getOperand(0).getReg();
607 LRI = allocVirtReg(MI, LRI, Hint);
608 } else if (LRI->LastUse) {
609 // Redefining a live register - kill at the last use, unless it is this
610 // instruction defining VirtReg multiple times.
611 if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
614 assert(LRI->PhysReg && "Register not assigned");
616 LRI->LastOpNum = OpNum;
618 markRegUsedInInstr(LRI->PhysReg);
622 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
623 RAFast::LiveRegMap::iterator RAFast::reloadVirtReg(MachineInstr &MI,
627 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
628 "Not a virtual register");
629 LiveRegMap::iterator LRI;
631 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
632 MachineOperand &MO = MI.getOperand(OpNum);
634 LRI = allocVirtReg(MI, LRI, Hint);
635 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
636 int FrameIndex = getStackSpaceFor(VirtReg, RC);
637 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
638 << PrintReg(LRI->PhysReg, TRI) << "\n");
639 TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
641 } else if (LRI->Dirty) {
642 if (isLastUseOfLocalReg(MO)) {
643 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
648 } else if (MO.isKill()) {
649 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
651 } else if (MO.isDead()) {
652 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
655 } else if (MO.isKill()) {
656 // We must remove kill flags from uses of reloaded registers because the
657 // register would be killed immediately, and there might be a second use:
658 // %foo = OR %x<kill>, %x
659 // This would cause a second reload of %x into a different register.
660 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
662 } else if (MO.isDead()) {
663 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
666 assert(LRI->PhysReg && "Register not assigned");
668 LRI->LastOpNum = OpNum;
669 markRegUsedInInstr(LRI->PhysReg);
673 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
674 // subregs. This may invalidate any operand pointers.
675 // Return true if the operand kills its register.
676 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
677 MachineOperand &MO = MI->getOperand(OpNum);
678 bool Dead = MO.isDead();
679 if (!MO.getSubReg()) {
681 return MO.isKill() || Dead;
684 // Handle subregister index.
685 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
688 // A kill flag implies killing the full register. Add corresponding super
691 MI->addRegisterKilled(PhysReg, TRI, true);
695 // A <def,read-undef> of a sub-register requires an implicit def of the full
697 if (MO.isDef() && MO.isUndef())
698 MI->addRegisterDefined(PhysReg, TRI);
703 // Handle special instruction operand like early clobbers and tied ops when
704 // there are additional physreg defines.
705 void RAFast::handleThroughOperands(MachineInstr *MI,
706 SmallVectorImpl<unsigned> &VirtDead) {
707 DEBUG(dbgs() << "Scanning for through registers:");
708 SmallSet<unsigned, 8> ThroughRegs;
709 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
710 MachineOperand &MO = MI->getOperand(i);
711 if (!MO.isReg()) continue;
712 unsigned Reg = MO.getReg();
713 if (!TargetRegisterInfo::isVirtualRegister(Reg))
715 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
716 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
717 if (ThroughRegs.insert(Reg).second)
718 DEBUG(dbgs() << ' ' << PrintReg(Reg));
722 // If any physreg defines collide with preallocated through registers,
723 // we must spill and reallocate.
724 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
725 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
726 MachineOperand &MO = MI->getOperand(i);
727 if (!MO.isReg() || !MO.isDef()) continue;
728 unsigned Reg = MO.getReg();
729 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
730 markRegUsedInInstr(Reg);
731 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
732 if (ThroughRegs.count(PhysRegState[*AI]))
733 definePhysReg(*MI, *AI, regFree);
737 SmallVector<unsigned, 8> PartialDefs;
738 DEBUG(dbgs() << "Allocating tied uses.\n");
739 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
740 MachineOperand &MO = MI->getOperand(i);
741 if (!MO.isReg()) continue;
742 unsigned Reg = MO.getReg();
743 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
746 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
747 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
749 LiveRegMap::iterator LRI = reloadVirtReg(*MI, i, Reg, 0);
750 unsigned PhysReg = LRI->PhysReg;
751 setPhysReg(MI, i, PhysReg);
752 // Note: we don't update the def operand yet. That would cause the normal
753 // def-scan to attempt spilling.
754 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
755 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
756 // Reload the register, but don't assign to the operand just yet.
757 // That would confuse the later phys-def processing pass.
758 LiveRegMap::iterator LRI = reloadVirtReg(*MI, i, Reg, 0);
759 PartialDefs.push_back(LRI->PhysReg);
763 DEBUG(dbgs() << "Allocating early clobbers.\n");
764 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
765 MachineOperand &MO = MI->getOperand(i);
766 if (!MO.isReg()) continue;
767 unsigned Reg = MO.getReg();
768 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
769 if (!MO.isEarlyClobber())
771 // Note: defineVirtReg may invalidate MO.
772 LiveRegMap::iterator LRI = defineVirtReg(*MI, i, Reg, 0);
773 unsigned PhysReg = LRI->PhysReg;
774 if (setPhysReg(MI, i, PhysReg))
775 VirtDead.push_back(Reg);
778 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
780 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
781 MachineOperand &MO = MI->getOperand(i);
782 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
783 unsigned Reg = MO.getReg();
784 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
785 DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
786 << " as used in instr\n");
787 markRegUsedInInstr(Reg);
790 // Also mark PartialDefs as used to avoid reallocation.
791 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
792 markRegUsedInInstr(PartialDefs[i]);
795 void RAFast::AllocateBasicBlock() {
796 DEBUG(dbgs() << "\nAllocating " << *MBB);
798 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
799 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
801 MachineBasicBlock::iterator MII = MBB->begin();
803 // Add live-in registers as live.
804 for (const auto &LI : MBB->liveins())
805 if (MRI->isAllocatable(LI.PhysReg))
806 definePhysReg(*MII, LI.PhysReg, regReserved);
808 SmallVector<unsigned, 8> VirtDead;
809 SmallVector<MachineInstr*, 32> Coalesced;
811 // Otherwise, sequentially allocate each instruction in the MBB.
812 while (MII != MBB->end()) {
813 MachineInstr *MI = &*MII++;
814 const MCInstrDesc &MCID = MI->getDesc();
816 dbgs() << "\n>> " << *MI << "Regs:";
817 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
818 if (PhysRegState[Reg] == regDisabled) continue;
819 dbgs() << " " << TRI->getName(Reg);
820 switch(PhysRegState[Reg]) {
827 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
828 LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
829 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
832 assert(I->PhysReg == Reg && "Bad inverse map");
838 // Check that LiveVirtRegs is the inverse.
839 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
840 e = LiveVirtRegs.end(); i != e; ++i) {
841 assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
843 assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
845 assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
849 // Debug values are not allowed to change codegen in any way.
850 if (MI->isDebugValue()) {
851 bool ScanDbgValue = true;
852 while (ScanDbgValue) {
853 ScanDbgValue = false;
854 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
855 MachineOperand &MO = MI->getOperand(i);
856 if (!MO.isReg()) continue;
857 unsigned Reg = MO.getReg();
858 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
859 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
860 if (LRI != LiveVirtRegs.end())
861 setPhysReg(MI, i, LRI->PhysReg);
863 int SS = StackSlotForVirtReg[Reg];
865 // We can't allocate a physreg for a DebugValue, sorry!
866 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
870 // Modify DBG_VALUE now that the value is in a spill slot.
871 bool IsIndirect = MI->isIndirectDebugValue();
872 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
873 const MDNode *Var = MI->getDebugVariable();
874 const MDNode *Expr = MI->getDebugExpression();
875 DebugLoc DL = MI->getDebugLoc();
876 MachineBasicBlock *MBB = MI->getParent();
878 cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
879 "Expected inlined-at fields to agree");
880 MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(MI), DL,
881 TII->get(TargetOpcode::DBG_VALUE))
886 DEBUG(dbgs() << "Modifying debug info due to spill:"
888 // Scan NewDV operands from the beginning.
894 LiveDbgValueMap[Reg].push_back(MI);
901 // If this is a copy, we may be able to coalesce.
902 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
904 CopyDst = MI->getOperand(0).getReg();
905 CopySrc = MI->getOperand(1).getReg();
906 CopyDstSub = MI->getOperand(0).getSubReg();
907 CopySrcSub = MI->getOperand(1).getSubReg();
910 // Track registers used by instruction.
914 // Mark physreg uses and early clobbers as used.
915 // Find the end of the virtreg operands
916 unsigned VirtOpEnd = 0;
917 bool hasTiedOps = false;
918 bool hasEarlyClobbers = false;
919 bool hasPartialRedefs = false;
920 bool hasPhysDefs = false;
921 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
922 MachineOperand &MO = MI->getOperand(i);
923 // Make sure MRI knows about registers clobbered by regmasks.
924 if (MO.isRegMask()) {
925 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
928 if (!MO.isReg()) continue;
929 unsigned Reg = MO.getReg();
931 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
934 hasTiedOps = hasTiedOps ||
935 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
937 if (MO.isEarlyClobber())
938 hasEarlyClobbers = true;
939 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
940 hasPartialRedefs = true;
944 if (!MRI->isAllocatable(Reg)) continue;
947 } else if (MO.isEarlyClobber()) {
948 definePhysReg(*MI, Reg,
949 (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
950 hasEarlyClobbers = true;
955 // The instruction may have virtual register operands that must be allocated
956 // the same register at use-time and def-time: early clobbers and tied
957 // operands. If there are also physical defs, these registers must avoid
958 // both physical defs and uses, making them more constrained than normal
960 // Similarly, if there are multiple defs and tied operands, we must make
961 // sure the same register is allocated to uses and defs.
962 // We didn't detect inline asm tied operands above, so just make this extra
963 // pass for all inline asm.
964 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
965 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
966 handleThroughOperands(MI, VirtDead);
967 // Don't attempt coalescing when we have funny stuff going on.
969 // Pretend we have early clobbers so the use operands get marked below.
970 // This is not necessary for the common case of a single tied use.
971 hasEarlyClobbers = true;
975 // Allocate virtreg uses.
976 for (unsigned i = 0; i != VirtOpEnd; ++i) {
977 MachineOperand &MO = MI->getOperand(i);
978 if (!MO.isReg()) continue;
979 unsigned Reg = MO.getReg();
980 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
982 LiveRegMap::iterator LRI = reloadVirtReg(*MI, i, Reg, CopyDst);
983 unsigned PhysReg = LRI->PhysReg;
984 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
985 if (setPhysReg(MI, i, PhysReg))
990 // Track registers defined by instruction - early clobbers and tied uses at
993 if (hasEarlyClobbers) {
994 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
995 MachineOperand &MO = MI->getOperand(i);
996 if (!MO.isReg()) continue;
997 unsigned Reg = MO.getReg();
998 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
999 // Look for physreg defs and tied uses.
1000 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
1001 markRegUsedInInstr(Reg);
1005 unsigned DefOpEnd = MI->getNumOperands();
1007 // Spill all virtregs before a call. This serves one purpose: If an
1008 // exception is thrown, the landing pad is going to expect to find
1009 // registers in their spill slots.
1010 // Note: although this is appealing to just consider all definitions
1011 // as call-clobbered, this is not correct because some of those
1012 // definitions may be used later on and we do not want to reuse
1013 // those for virtual registers in between.
1014 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1017 // The imp-defs are skipped below, but we still need to mark those
1018 // registers as used by the function.
1019 SkippedInstrs.insert(&MCID);
1023 // Allocate defs and collect dead defs.
1024 for (unsigned i = 0; i != DefOpEnd; ++i) {
1025 MachineOperand &MO = MI->getOperand(i);
1026 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1028 unsigned Reg = MO.getReg();
1030 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1031 if (!MRI->isAllocatable(Reg)) continue;
1032 definePhysReg(*MI, Reg, MO.isDead() ? regFree : regReserved);
1035 LiveRegMap::iterator LRI = defineVirtReg(*MI, i, Reg, CopySrc);
1036 unsigned PhysReg = LRI->PhysReg;
1037 if (setPhysReg(MI, i, PhysReg)) {
1038 VirtDead.push_back(Reg);
1039 CopyDst = 0; // cancel coalescing;
1041 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1044 // Kill dead defs after the scan to ensure that multiple defs of the same
1045 // register are allocated identically. We didn't need to do this for uses
1046 // because we are crerating our own kill flags, and they are always at the
1048 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1049 killVirtReg(VirtDead[i]);
1052 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1053 DEBUG(dbgs() << "-- coalescing: " << *MI);
1054 Coalesced.push_back(MI);
1056 DEBUG(dbgs() << "<< " << *MI);
1060 // Spill all physical registers holding virtual registers now.
1061 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1062 spillAll(MBB->getFirstTerminator());
1064 // Erase all the coalesced copies. We are delaying it until now because
1065 // LiveVirtRegs might refer to the instrs.
1066 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1067 MBB->erase(Coalesced[i]);
1068 NumCopies += Coalesced.size();
1073 /// runOnMachineFunction - Register allocate the whole function
1075 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1076 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1077 << "********** Function: " << Fn.getName() << '\n');
1079 MRI = &MF->getRegInfo();
1080 TRI = MF->getSubtarget().getRegisterInfo();
1081 TII = MF->getSubtarget().getInstrInfo();
1082 MRI->freezeReservedRegs(Fn);
1083 RegClassInfo.runOnMachineFunction(Fn);
1084 UsedInInstr.clear();
1085 UsedInInstr.setUniverse(TRI->getNumRegUnits());
1087 // initialize the virtual->physical register map to have a 'null'
1088 // mapping for all virtual registers
1089 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1090 LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
1092 // Loop over all of the basic blocks, eliminating virtual register references
1093 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1094 MBBi != MBBe; ++MBBi) {
1096 AllocateBasicBlock();
1099 // All machine operands and other references to virtual registers have been
1100 // replaced. Remove the virtual registers.
1101 MRI->clearVirtRegs();
1103 SkippedInstrs.clear();
1104 StackSlotForVirtReg.clear();
1105 LiveDbgValueMap.clear();
1109 FunctionPass *llvm::createFastRegisterAllocator() {
1110 return new RAFast();