1 //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 /// \file This register allocator allocates registers to a basic block at a
10 /// time, attempting to keep values in registers and reusing registers as
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/IndexedMap.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/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegAllocRegistry.h"
31 #include "llvm/CodeGen/RegisterClassInfo.h"
32 #include "llvm/CodeGen/TargetInstrInfo.h"
33 #include "llvm/CodeGen/TargetOpcodes.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/MC/MCInstrDesc.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/raw_ostream.h"
53 #define DEBUG_TYPE "regalloc"
55 STATISTIC(NumStores, "Number of stores added");
56 STATISTIC(NumLoads , "Number of loads added");
57 STATISTIC(NumCoalesced, "Number of copies coalesced");
59 static RegisterRegAlloc
60 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
64 class RegAllocFast : public MachineFunctionPass {
68 RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {}
71 MachineFrameInfo *MFI;
72 MachineRegisterInfo *MRI;
73 const TargetRegisterInfo *TRI;
74 const TargetInstrInfo *TII;
75 RegisterClassInfo RegClassInfo;
77 /// Basic block currently being allocated.
78 MachineBasicBlock *MBB;
80 /// Maps virtual regs to the frame index where these values are spilled.
81 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
83 /// Everything we know about a live virtual register.
85 MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
86 Register VirtReg; ///< Virtual register number.
87 MCPhysReg PhysReg = 0; ///< Currently held here.
88 unsigned short LastOpNum = 0; ///< OpNum on LastUse.
89 bool Dirty = false; ///< Register needs spill.
91 explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
93 unsigned getSparseSetIndex() const {
94 return Register::virtReg2Index(VirtReg);
98 using LiveRegMap = SparseSet<LiveReg>;
99 /// This map contains entries for each virtual register that is currently
100 /// available in a physical register.
101 LiveRegMap LiveVirtRegs;
103 DenseMap<unsigned, SmallVector<MachineInstr *, 2>> LiveDbgValueMap;
105 /// Has a bit set for every virtual register for which it was determined
106 /// that it is alive across blocks.
107 BitVector MayLiveAcrossBlocks;
109 /// State of a register unit.
111 /// A free register is not currently in use and can be allocated
112 /// immediately without checking aliases.
115 /// A reserved register has been assigned explicitly (e.g., setting up a
116 /// call parameter), and it remains reserved until it is used.
119 /// A register state may also be a virtual register number, indication
120 /// that the physical register is currently allocated to a virtual
121 /// register. In that case, LiveVirtRegs contains the inverse mapping.
124 /// Maps each physical register to a RegUnitState enum or virtual register.
125 std::vector<unsigned> RegUnitStates;
127 SmallVector<Register, 16> VirtDead;
128 SmallVector<MachineInstr *, 32> Coalesced;
130 using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
131 /// Set of register units that are used in the current instruction, and so
132 /// cannot be allocated.
133 RegUnitSet UsedInInstr;
135 void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
137 /// Mark a physreg as used in this instruction.
138 void markRegUsedInInstr(MCPhysReg PhysReg) {
139 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
140 UsedInInstr.insert(*Units);
143 /// Check if a physreg or any of its aliases are used in this instruction.
144 bool isRegUsedInInstr(MCPhysReg PhysReg) const {
145 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
146 if (UsedInInstr.count(*Units))
155 spillImpossible = ~0u
159 StringRef getPassName() const override { return "Fast Register Allocator"; }
161 void getAnalysisUsage(AnalysisUsage &AU) const override {
162 AU.setPreservesCFG();
163 MachineFunctionPass::getAnalysisUsage(AU);
166 MachineFunctionProperties getRequiredProperties() const override {
167 return MachineFunctionProperties().set(
168 MachineFunctionProperties::Property::NoPHIs);
171 MachineFunctionProperties getSetProperties() const override {
172 return MachineFunctionProperties().set(
173 MachineFunctionProperties::Property::NoVRegs);
177 bool runOnMachineFunction(MachineFunction &MF) override;
179 void allocateBasicBlock(MachineBasicBlock &MBB);
180 void allocateInstruction(MachineInstr &MI);
181 void handleDebugValue(MachineInstr &MI);
182 void handleThroughOperands(MachineInstr &MI,
183 SmallVectorImpl<Register> &VirtDead);
184 bool isLastUseOfLocalReg(const MachineOperand &MO) const;
186 void addKillFlag(const LiveReg &LRI);
188 bool verifyRegStateMapping(const LiveReg &LR) const;
191 void killVirtReg(LiveReg &LR);
192 void killVirtReg(Register VirtReg);
193 void spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR);
194 void spillVirtReg(MachineBasicBlock::iterator MI, Register VirtReg);
196 void usePhysReg(MachineOperand &MO);
197 void definePhysReg(MachineBasicBlock::iterator MI, MCPhysReg PhysReg,
199 unsigned calcSpillCost(MCPhysReg PhysReg) const;
200 void assignVirtToPhysReg(LiveReg &, MCPhysReg PhysReg);
202 LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
203 return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
206 LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
207 return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
210 void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint);
211 void allocVirtRegUndef(MachineOperand &MO);
212 MCPhysReg defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
214 LiveReg &reloadVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
216 void spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut);
217 bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
219 Register traceCopies(Register VirtReg) const;
220 Register traceCopyChain(Register Reg) const;
222 int getStackSpaceFor(Register VirtReg);
223 void spill(MachineBasicBlock::iterator Before, Register VirtReg,
224 MCPhysReg AssignedReg, bool Kill);
225 void reload(MachineBasicBlock::iterator Before, Register VirtReg,
228 bool mayLiveOut(Register VirtReg);
229 bool mayLiveIn(Register VirtReg);
231 void dumpState() const;
234 } // end anonymous namespace
236 char RegAllocFast::ID = 0;
238 INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
241 void RegAllocFast::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
242 for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI)
243 RegUnitStates[*UI] = NewState;
246 /// This allocates space for the specified virtual register to be held on the
248 int RegAllocFast::getStackSpaceFor(Register VirtReg) {
249 // Find the location Reg would belong...
250 int SS = StackSlotForVirtReg[VirtReg];
251 // Already has space allocated?
255 // Allocate a new stack object for this spill location...
256 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
257 unsigned Size = TRI->getSpillSize(RC);
258 Align Alignment = TRI->getSpillAlign(RC);
259 int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
262 StackSlotForVirtReg[VirtReg] = FrameIdx;
266 /// Returns false if \p VirtReg is known to not live out of the current block.
267 bool RegAllocFast::mayLiveOut(Register VirtReg) {
268 if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
269 // Cannot be live-out if there are no successors.
270 return !MBB->succ_empty();
273 // If this block loops back to itself, it would be necessary to check whether
274 // the use comes after the def.
275 if (MBB->isSuccessor(MBB)) {
276 MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
280 // See if the first \p Limit uses of the register are all in the current
282 static const unsigned Limit = 8;
284 for (const MachineInstr &UseInst : MRI->reg_nodbg_instructions(VirtReg)) {
285 if (UseInst.getParent() != MBB || ++C >= Limit) {
286 MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
287 // Cannot be live-out if there are no successors.
288 return !MBB->succ_empty();
295 /// Returns false if \p VirtReg is known to not be live into the current block.
296 bool RegAllocFast::mayLiveIn(Register VirtReg) {
297 if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
298 return !MBB->pred_empty();
300 // See if the first \p Limit def of the register are all in the current block.
301 static const unsigned Limit = 8;
303 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
304 if (DefInst.getParent() != MBB || ++C >= Limit) {
305 MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
306 return !MBB->pred_empty();
313 /// Insert spill instruction for \p AssignedReg before \p Before. Update
314 /// DBG_VALUEs with \p VirtReg operands with the stack slot.
315 void RegAllocFast::spill(MachineBasicBlock::iterator Before, Register VirtReg,
316 MCPhysReg AssignedReg, bool Kill) {
317 LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI)
318 << " in " << printReg(AssignedReg, TRI));
319 int FI = getStackSpaceFor(VirtReg);
320 LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
322 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
323 TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI);
326 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
327 // identify spilled location as the place to find corresponding variable's
329 SmallVectorImpl<MachineInstr *> &LRIDbgValues = LiveDbgValueMap[VirtReg];
330 for (MachineInstr *DBG : LRIDbgValues) {
331 MachineInstr *NewDV = buildDbgValueForSpill(*MBB, Before, *DBG, FI);
332 assert(NewDV->getParent() == MBB && "dangling parent pointer");
334 LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
336 // Now this register is spilled there is should not be any DBG_VALUE
337 // pointing to this register because they are all pointing to spilled value
339 LRIDbgValues.clear();
342 /// Insert reload instruction for \p PhysReg before \p Before.
343 void RegAllocFast::reload(MachineBasicBlock::iterator Before, Register VirtReg,
345 LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
346 << printReg(PhysReg, TRI) << '\n');
347 int FI = getStackSpaceFor(VirtReg);
348 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
349 TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI);
353 /// Return true if MO is the only remaining reference to its virtual register,
354 /// and it is guaranteed to be a block-local register.
355 bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand &MO) const {
356 // If the register has ever been spilled or reloaded, we conservatively assume
357 // it is a global register used in multiple blocks.
358 if (StackSlotForVirtReg[MO.getReg()] != -1)
361 // Check that the use/def chain has exactly one operand - MO.
362 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
365 return ++I == MRI->reg_nodbg_end();
368 /// Set kill flags on last use of a virtual register.
369 void RegAllocFast::addKillFlag(const LiveReg &LR) {
370 if (!LR.LastUse) return;
371 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
372 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
373 if (MO.getReg() == LR.PhysReg)
375 // else, don't do anything we are problably redefining a
376 // subreg of this register and given we don't track which
377 // lanes are actually dead, we cannot insert a kill flag here.
378 // Otherwise we may end up in a situation like this:
379 // ... = (MO) physreg:sub1, implicit killed physreg
380 // ... <== Here we would allow later pass to reuse physreg:sub1
381 // which is potentially wrong.
383 // ... = LR.sub1 <== This is going to use physreg:sub1
388 bool RegAllocFast::verifyRegStateMapping(const LiveReg &LR) const {
389 for (MCRegUnitIterator UI(LR.PhysReg, TRI); UI.isValid(); ++UI) {
390 if (RegUnitStates[*UI] != LR.VirtReg)
398 /// Mark virtreg as no longer available.
399 void RegAllocFast::killVirtReg(LiveReg &LR) {
400 assert(verifyRegStateMapping(LR) && "Broken RegState mapping");
402 MCPhysReg PhysReg = LR.PhysReg;
403 setPhysRegState(PhysReg, regFree);
407 /// Mark virtreg as no longer available.
408 void RegAllocFast::killVirtReg(Register VirtReg) {
409 assert(Register::isVirtualRegister(VirtReg) &&
410 "killVirtReg needs a virtual register");
411 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
412 if (LRI != LiveVirtRegs.end() && LRI->PhysReg)
416 /// This method spills the value specified by VirtReg into the corresponding
417 /// stack slot if needed.
418 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
420 assert(Register::isVirtualRegister(VirtReg) &&
421 "Spilling a physical register is illegal!");
422 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
423 assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
424 "Spilling unmapped virtual register");
425 spillVirtReg(MI, *LRI);
428 /// Do the actual work of spilling.
429 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR) {
430 assert(verifyRegStateMapping(LR) && "Broken RegState mapping");
432 MCPhysReg PhysReg = LR.PhysReg;
435 // If this physreg is used by the instruction, we want to kill it on the
436 // instruction, not on the spill.
437 bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
440 spill(MI, LR.VirtReg, PhysReg, SpillKill);
443 LR.LastUse = nullptr; // Don't kill register again
448 /// Spill all dirty virtregs without killing them.
449 void RegAllocFast::spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut) {
450 if (LiveVirtRegs.empty())
452 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
453 // of spilling here is deterministic, if arbitrary.
454 for (LiveReg &LR : LiveVirtRegs) {
457 if (OnlyLiveOut && !mayLiveOut(LR.VirtReg))
459 spillVirtReg(MI, LR);
461 LiveVirtRegs.clear();
464 /// Handle the direct use of a physical register. Check that the register is
465 /// not used by a virtreg. Kill the physreg, marking it free. This may add
466 /// implicit kills to MO->getParent() and invalidate MO.
467 void RegAllocFast::usePhysReg(MachineOperand &MO) {
468 // Ignore undef uses.
472 Register PhysReg = MO.getReg();
473 assert(PhysReg.isPhysical() && "Bad usePhysReg operand");
475 markRegUsedInInstr(PhysReg);
477 for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
478 switch (RegUnitStates[*UI]) {
480 RegUnitStates[*UI] = regFree;
485 llvm_unreachable("Unexpected reg unit state");
489 // All aliases are disabled, bring register into working set.
490 setPhysRegState(PhysReg, regFree);
494 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
495 /// similar to defineVirtReg except the physreg is reserved instead of
497 void RegAllocFast::definePhysReg(MachineBasicBlock::iterator MI,
498 MCPhysReg PhysReg, unsigned NewState) {
499 for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
500 switch (unsigned VirtReg = RegUnitStates[*UI]) {
502 spillVirtReg(MI, VirtReg);
510 markRegUsedInInstr(PhysReg);
511 setPhysRegState(PhysReg, NewState);
514 /// Return the cost of spilling clearing out PhysReg and aliases so it is free
515 /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
516 /// disabled - it can be allocated directly.
517 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
518 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
519 if (isRegUsedInInstr(PhysReg)) {
520 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI)
521 << " is already used in instr.\n");
522 return spillImpossible;
525 for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
526 switch (unsigned VirtReg = RegUnitStates[*UI]) {
530 LLVM_DEBUG(dbgs() << printReg(VirtReg, TRI) << " corresponding "
531 << printReg(PhysReg, TRI) << " is reserved already.\n");
532 return spillImpossible;
534 LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
535 assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
536 "Missing VirtReg entry");
537 return LRI->Dirty ? spillDirty : spillClean;
544 /// This method updates local state so that we know that PhysReg is the
545 /// proper container for VirtReg now. The physical register must not be used
546 /// for anything else when this is called.
547 void RegAllocFast::assignVirtToPhysReg(LiveReg &LR, MCPhysReg PhysReg) {
548 Register VirtReg = LR.VirtReg;
549 LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
550 << printReg(PhysReg, TRI) << '\n');
551 assert(LR.PhysReg == 0 && "Already assigned a physreg");
552 assert(PhysReg != 0 && "Trying to assign no register");
553 LR.PhysReg = PhysReg;
554 setPhysRegState(PhysReg, VirtReg);
557 static bool isCoalescable(const MachineInstr &MI) {
558 return MI.isFullCopy();
561 Register RegAllocFast::traceCopyChain(Register Reg) const {
562 static const unsigned ChainLengthLimit = 3;
565 if (Reg.isPhysical())
567 assert(Reg.isVirtual());
569 MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
570 if (!VRegDef || !isCoalescable(*VRegDef))
572 Reg = VRegDef->getOperand(1).getReg();
573 } while (++C <= ChainLengthLimit);
577 /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
578 /// chain of copies to check whether we reach a physical register we can
580 Register RegAllocFast::traceCopies(Register VirtReg) const {
581 static const unsigned DefLimit = 3;
583 for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
584 if (isCoalescable(MI)) {
585 Register Reg = MI.getOperand(1).getReg();
586 Reg = traceCopyChain(Reg);
597 /// Allocates a physical register for VirtReg.
598 void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint0) {
599 const Register VirtReg = LR.VirtReg;
601 assert(Register::isVirtualRegister(VirtReg) &&
602 "Can only allocate virtual registers");
604 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
605 LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
606 << " in class " << TRI->getRegClassName(&RC)
607 << " with hint " << printReg(Hint0, TRI) << '\n');
609 // Take hint when possible.
610 if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) &&
611 RC.contains(Hint0)) {
612 // Ignore the hint if we would have to spill a dirty register.
613 unsigned Cost = calcSpillCost(Hint0);
614 if (Cost < spillDirty) {
615 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
618 definePhysReg(MI, Hint0, regFree);
619 assignVirtToPhysReg(LR, Hint0);
622 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
630 Register Hint1 = traceCopies(VirtReg);
631 if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) &&
632 RC.contains(Hint1) && !isRegUsedInInstr(Hint1)) {
633 // Ignore the hint if we would have to spill a dirty register.
634 unsigned Cost = calcSpillCost(Hint1);
635 if (Cost < spillDirty) {
636 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
639 definePhysReg(MI, Hint1, regFree);
640 assignVirtToPhysReg(LR, Hint1);
643 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
650 MCPhysReg BestReg = 0;
651 unsigned BestCost = spillImpossible;
652 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
653 for (MCPhysReg PhysReg : AllocationOrder) {
654 LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
655 unsigned Cost = calcSpillCost(PhysReg);
656 LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
657 // Immediate take a register with cost 0.
659 assignVirtToPhysReg(LR, PhysReg);
663 if (PhysReg == Hint1 || PhysReg == Hint0)
664 Cost -= spillPrefBonus;
666 if (Cost < BestCost) {
673 // Nothing we can do: Report an error and keep going with an invalid
675 if (MI.isInlineAsm())
676 MI.emitError("inline assembly requires more registers than available");
678 MI.emitError("ran out of registers during register allocation");
679 definePhysReg(MI, *AllocationOrder.begin(), regFree);
680 assignVirtToPhysReg(LR, *AllocationOrder.begin());
684 definePhysReg(MI, BestReg, regFree);
685 assignVirtToPhysReg(LR, BestReg);
688 void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
689 assert(MO.isUndef() && "expected undef use");
690 Register VirtReg = MO.getReg();
691 assert(Register::isVirtualRegister(VirtReg) && "Expected virtreg");
693 LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
695 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
696 PhysReg = LRI->PhysReg;
698 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
699 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
700 assert(!AllocationOrder.empty() && "Allocation order must not be empty");
701 PhysReg = AllocationOrder[0];
704 unsigned SubRegIdx = MO.getSubReg();
705 if (SubRegIdx != 0) {
706 PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
710 MO.setIsRenamable(true);
713 /// Allocates a register for VirtReg and mark it as dirty.
714 MCPhysReg RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
715 Register VirtReg, Register Hint) {
716 assert(Register::isVirtualRegister(VirtReg) && "Not a virtual register");
717 LiveRegMap::iterator LRI;
719 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
721 // If there is no hint, peek at the only use of this register.
722 if ((!Hint || !Hint.isPhysical()) &&
723 MRI->hasOneNonDBGUse(VirtReg)) {
724 const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
725 // It's a copy, use the destination register as a hint.
726 if (UseMI.isCopyLike())
727 Hint = UseMI.getOperand(0).getReg();
729 allocVirtReg(MI, *LRI, Hint);
730 } else if (LRI->LastUse) {
731 // Redefining a live register - kill at the last use, unless it is this
732 // instruction defining VirtReg multiple times.
733 if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
736 assert(LRI->PhysReg && "Register not assigned");
738 LRI->LastOpNum = OpNum;
740 markRegUsedInInstr(LRI->PhysReg);
744 /// Make sure VirtReg is available in a physreg and return it.
745 RegAllocFast::LiveReg &RegAllocFast::reloadVirtReg(MachineInstr &MI,
749 assert(Register::isVirtualRegister(VirtReg) && "Not a virtual register");
750 LiveRegMap::iterator LRI;
752 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
753 MachineOperand &MO = MI.getOperand(OpNum);
755 allocVirtReg(MI, *LRI, Hint);
756 reload(MI, VirtReg, LRI->PhysReg);
757 } else if (LRI->Dirty) {
758 if (isLastUseOfLocalReg(MO)) {
759 LLVM_DEBUG(dbgs() << "Killing last use: " << MO << '\n');
764 } else if (MO.isKill()) {
765 LLVM_DEBUG(dbgs() << "Clearing dubious kill: " << MO << '\n');
767 } else if (MO.isDead()) {
768 LLVM_DEBUG(dbgs() << "Clearing dubious dead: " << MO << '\n');
771 } else if (MO.isKill()) {
772 // We must remove kill flags from uses of reloaded registers because the
773 // register would be killed immediately, and there might be a second use:
774 // %foo = OR killed %x, %x
775 // This would cause a second reload of %x into a different register.
776 LLVM_DEBUG(dbgs() << "Clearing clean kill: " << MO << '\n');
778 } else if (MO.isDead()) {
779 LLVM_DEBUG(dbgs() << "Clearing clean dead: " << MO << '\n');
782 assert(LRI->PhysReg && "Register not assigned");
784 LRI->LastOpNum = OpNum;
785 markRegUsedInInstr(LRI->PhysReg);
789 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
790 /// may invalidate any operand pointers. Return true if the operand kills its
792 bool RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
794 bool Dead = MO.isDead();
795 if (!MO.getSubReg()) {
797 MO.setIsRenamable(true);
798 return MO.isKill() || Dead;
801 // Handle subregister index.
802 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : Register());
803 MO.setIsRenamable(true);
806 // A kill flag implies killing the full register. Add corresponding super
809 MI.addRegisterKilled(PhysReg, TRI, true);
813 // A <def,read-undef> of a sub-register requires an implicit def of the full
815 if (MO.isDef() && MO.isUndef())
816 MI.addRegisterDefined(PhysReg, TRI);
821 // Handles special instruction operand like early clobbers and tied ops when
822 // there are additional physreg defines.
823 void RegAllocFast::handleThroughOperands(MachineInstr &MI,
824 SmallVectorImpl<Register> &VirtDead) {
825 LLVM_DEBUG(dbgs() << "Scanning for through registers:");
826 SmallSet<Register, 8> ThroughRegs;
827 for (const MachineOperand &MO : MI.operands()) {
828 if (!MO.isReg()) continue;
829 Register Reg = MO.getReg();
830 if (!Reg.isVirtual())
832 if (MO.isEarlyClobber() || (MO.isUse() && MO.isTied()) ||
833 (MO.getSubReg() && MI.readsVirtualRegister(Reg))) {
834 if (ThroughRegs.insert(Reg).second)
835 LLVM_DEBUG(dbgs() << ' ' << printReg(Reg));
839 // If any physreg defines collide with preallocated through registers,
840 // we must spill and reallocate.
841 LLVM_DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
842 for (const MachineOperand &MO : MI.operands()) {
843 if (!MO.isReg() || !MO.isDef()) continue;
844 Register Reg = MO.getReg();
845 if (!Reg || !Reg.isPhysical())
847 markRegUsedInInstr(Reg);
849 for (MCRegUnitIterator UI(Reg, TRI); UI.isValid(); ++UI) {
850 if (!ThroughRegs.count(RegUnitStates[*UI]))
853 // Need to spill any aliasing registers.
854 for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) {
855 for (MCSuperRegIterator SI(*RI, TRI, true); SI.isValid(); ++SI) {
856 definePhysReg(MI, *SI, regFree);
862 SmallVector<Register, 8> PartialDefs;
863 LLVM_DEBUG(dbgs() << "Allocating tied uses.\n");
864 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
865 MachineOperand &MO = MI.getOperand(I);
866 if (!MO.isReg()) continue;
867 Register Reg = MO.getReg();
868 if (!Register::isVirtualRegister(Reg))
871 if (!MO.isTied()) continue;
872 LLVM_DEBUG(dbgs() << "Operand " << I << "(" << MO
873 << ") is tied to operand " << MI.findTiedOperandIdx(I)
875 LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
876 MCPhysReg PhysReg = LR.PhysReg;
877 setPhysReg(MI, MO, PhysReg);
878 // Note: we don't update the def operand yet. That would cause the normal
879 // def-scan to attempt spilling.
880 } else if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) {
881 LLVM_DEBUG(dbgs() << "Partial redefine: " << MO << '\n');
882 // Reload the register, but don't assign to the operand just yet.
883 // That would confuse the later phys-def processing pass.
884 LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
885 PartialDefs.push_back(LR.PhysReg);
889 LLVM_DEBUG(dbgs() << "Allocating early clobbers.\n");
890 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
891 const MachineOperand &MO = MI.getOperand(I);
892 if (!MO.isReg()) continue;
893 Register Reg = MO.getReg();
894 if (!Register::isVirtualRegister(Reg))
896 if (!MO.isEarlyClobber())
898 // Note: defineVirtReg may invalidate MO.
899 MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, 0);
900 if (setPhysReg(MI, MI.getOperand(I), PhysReg))
901 VirtDead.push_back(Reg);
904 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
906 for (const MachineOperand &MO : MI.operands()) {
907 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
908 Register Reg = MO.getReg();
909 if (!Reg || !Reg.isPhysical())
911 LLVM_DEBUG(dbgs() << "\tSetting " << printReg(Reg, TRI)
912 << " as used in instr\n");
913 markRegUsedInInstr(Reg);
916 // Also mark PartialDefs as used to avoid reallocation.
917 for (Register PartialDef : PartialDefs)
918 markRegUsedInInstr(PartialDef);
923 void RegAllocFast::dumpState() const {
924 for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
926 switch (unsigned VirtReg = RegUnitStates[Unit]) {
930 dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
933 dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
934 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
935 assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
938 assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
944 // Check that LiveVirtRegs is the inverse.
945 for (const LiveReg &LR : LiveVirtRegs) {
946 Register VirtReg = LR.VirtReg;
947 assert(VirtReg.isVirtual() && "Bad map key");
948 MCPhysReg PhysReg = LR.PhysReg;
950 assert(Register::isPhysicalRegister(PhysReg) &&
951 "mapped to physreg");
952 for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
953 assert(RegUnitStates[*UI] == VirtReg && "inverse map valid");
960 void RegAllocFast::allocateInstruction(MachineInstr &MI) {
961 const MCInstrDesc &MCID = MI.getDesc();
963 // If this is a copy, we may be able to coalesce.
966 unsigned CopySrcSub = 0;
967 unsigned CopyDstSub = 0;
969 CopyDstReg = MI.getOperand(0).getReg();
970 CopySrcReg = MI.getOperand(1).getReg();
971 CopyDstSub = MI.getOperand(0).getSubReg();
972 CopySrcSub = MI.getOperand(1).getSubReg();
975 // Track registers used by instruction.
979 // Mark physreg uses and early clobbers as used.
980 // Find the end of the virtreg operands
981 unsigned VirtOpEnd = 0;
982 bool hasTiedOps = false;
983 bool hasEarlyClobbers = false;
984 bool hasPartialRedefs = false;
985 bool hasPhysDefs = false;
986 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
987 MachineOperand &MO = MI.getOperand(i);
988 // Make sure MRI knows about registers clobbered by regmasks.
989 if (MO.isRegMask()) {
990 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
993 if (!MO.isReg()) continue;
994 Register Reg = MO.getReg();
996 if (Register::isVirtualRegister(Reg)) {
999 hasTiedOps = hasTiedOps ||
1000 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
1002 if (MO.isEarlyClobber())
1003 hasEarlyClobbers = true;
1004 if (MO.getSubReg() && MI.readsVirtualRegister(Reg))
1005 hasPartialRedefs = true;
1009 if (!MRI->isAllocatable(Reg)) continue;
1012 } else if (MO.isEarlyClobber()) {
1013 definePhysReg(MI, Reg,
1014 (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
1015 hasEarlyClobbers = true;
1020 // The instruction may have virtual register operands that must be allocated
1021 // the same register at use-time and def-time: early clobbers and tied
1022 // operands. If there are also physical defs, these registers must avoid
1023 // both physical defs and uses, making them more constrained than normal
1025 // Similarly, if there are multiple defs and tied operands, we must make
1026 // sure the same register is allocated to uses and defs.
1027 // We didn't detect inline asm tied operands above, so just make this extra
1028 // pass for all inline asm.
1029 if (MI.isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
1030 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
1031 handleThroughOperands(MI, VirtDead);
1032 // Don't attempt coalescing when we have funny stuff going on.
1033 CopyDstReg = Register();
1034 // Pretend we have early clobbers so the use operands get marked below.
1035 // This is not necessary for the common case of a single tied use.
1036 hasEarlyClobbers = true;
1040 // Allocate virtreg uses.
1041 bool HasUndefUse = false;
1042 for (unsigned I = 0; I != VirtOpEnd; ++I) {
1043 MachineOperand &MO = MI.getOperand(I);
1044 if (!MO.isReg()) continue;
1045 Register Reg = MO.getReg();
1046 if (!Reg.isVirtual())
1051 // There is no need to allocate a register for an undef use.
1055 // Populate MayLiveAcrossBlocks in case the use block is allocated before
1056 // the def block (removing the vreg uses).
1059 LiveReg &LR = reloadVirtReg(MI, I, Reg, CopyDstReg);
1060 MCPhysReg PhysReg = LR.PhysReg;
1061 CopySrcReg = (CopySrcReg == Reg || CopySrcReg == PhysReg) ? PhysReg : 0;
1062 if (setPhysReg(MI, MO, PhysReg))
1067 // Allocate undef operands. This is a separate step because in a situation
1068 // like ` = OP undef %X, %X` both operands need the same register assign
1069 // so we should perform the normal assignment first.
1071 for (MachineOperand &MO : MI.uses()) {
1072 if (!MO.isReg() || !MO.isUse())
1074 Register Reg = MO.getReg();
1075 if (!Reg.isVirtual())
1078 assert(MO.isUndef() && "Should only have undef virtreg uses left");
1079 allocVirtRegUndef(MO);
1083 // Track registers defined by instruction - early clobbers and tied uses at
1085 UsedInInstr.clear();
1086 if (hasEarlyClobbers) {
1087 for (const MachineOperand &MO : MI.operands()) {
1088 if (!MO.isReg()) continue;
1089 Register Reg = MO.getReg();
1090 if (!Reg || !Reg.isPhysical())
1092 // Look for physreg defs and tied uses.
1093 if (!MO.isDef() && !MO.isTied()) continue;
1094 markRegUsedInInstr(Reg);
1098 unsigned DefOpEnd = MI.getNumOperands();
1100 // Spill all virtregs before a call. This serves one purpose: If an
1101 // exception is thrown, the landing pad is going to expect to find
1102 // registers in their spill slots.
1103 // Note: although this is appealing to just consider all definitions
1104 // as call-clobbered, this is not correct because some of those
1105 // definitions may be used later on and we do not want to reuse
1106 // those for virtual registers in between.
1107 LLVM_DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1108 spillAll(MI, /*OnlyLiveOut*/ false);
1112 // Mark all physreg defs as used before allocating virtreg defs.
1113 for (unsigned I = 0; I != DefOpEnd; ++I) {
1114 const MachineOperand &MO = MI.getOperand(I);
1115 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1117 Register Reg = MO.getReg();
1119 if (!Reg || !Reg.isPhysical() || !MRI->isAllocatable(Reg))
1121 definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
1125 // Allocate defs and collect dead defs.
1126 for (unsigned I = 0; I != DefOpEnd; ++I) {
1127 const MachineOperand &MO = MI.getOperand(I);
1128 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1130 Register Reg = MO.getReg();
1132 // We have already dealt with phys regs in the previous scan.
1133 if (Reg.isPhysical())
1135 MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, CopySrcReg);
1136 if (setPhysReg(MI, MI.getOperand(I), PhysReg)) {
1137 VirtDead.push_back(Reg);
1138 CopyDstReg = Register(); // cancel coalescing;
1140 CopyDstReg = (CopyDstReg == Reg || CopyDstReg == PhysReg) ? PhysReg : 0;
1143 // Kill dead defs after the scan to ensure that multiple defs of the same
1144 // register are allocated identically. We didn't need to do this for uses
1145 // because we are crerating our own kill flags, and they are always at the
1147 for (Register VirtReg : VirtDead)
1148 killVirtReg(VirtReg);
1151 LLVM_DEBUG(dbgs() << "<< " << MI);
1152 if (CopyDstReg && CopyDstReg == CopySrcReg && CopyDstSub == CopySrcSub) {
1153 LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1154 Coalesced.push_back(&MI);
1158 void RegAllocFast::handleDebugValue(MachineInstr &MI) {
1159 MachineOperand &MO = MI.getDebugOperand(0);
1161 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1162 // mostly constants and frame indices.
1165 Register Reg = MO.getReg();
1166 if (!Register::isVirtualRegister(Reg))
1169 // See if this virtual register has already been allocated to a physical
1170 // register or spilled to a stack slot.
1171 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1172 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1173 setPhysReg(MI, MO, LRI->PhysReg);
1175 int SS = StackSlotForVirtReg[Reg];
1177 // Modify DBG_VALUE now that the value is in a spill slot.
1178 updateDbgValueForSpill(MI, SS);
1179 LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << MI);
1183 // We can't allocate a physreg for a DebugValue, sorry!
1184 LLVM_DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
1185 MO.setReg(Register());
1188 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1189 // that future spills of Reg will have DBG_VALUEs.
1190 LiveDbgValueMap[Reg].push_back(&MI);
1193 void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
1195 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1197 RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1198 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1200 MachineBasicBlock::iterator MII = MBB.begin();
1202 // Add live-in registers as live.
1203 for (const MachineBasicBlock::RegisterMaskPair &LI : MBB.liveins())
1204 if (MRI->isAllocatable(LI.PhysReg))
1205 definePhysReg(MII, LI.PhysReg, regReserved);
1210 // Otherwise, sequentially allocate each instruction in the MBB.
1211 for (MachineInstr &MI : MBB) {
1213 dbgs() << "\n>> " << MI << "Regs:";
1217 // Special handling for debug values. Note that they are not allowed to
1218 // affect codegen of the other instructions in any way.
1219 if (MI.isDebugValue()) {
1220 handleDebugValue(MI);
1224 allocateInstruction(MI);
1227 // Spill all physical registers holding virtual registers now.
1228 LLVM_DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1229 spillAll(MBB.getFirstTerminator(), /*OnlyLiveOut*/ true);
1231 // Erase all the coalesced copies. We are delaying it until now because
1232 // LiveVirtRegs might refer to the instrs.
1233 for (MachineInstr *MI : Coalesced)
1235 NumCoalesced += Coalesced.size();
1237 LLVM_DEBUG(MBB.dump());
1240 bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
1241 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1242 << "********** Function: " << MF.getName() << '\n');
1243 MRI = &MF.getRegInfo();
1244 const TargetSubtargetInfo &STI = MF.getSubtarget();
1245 TRI = STI.getRegisterInfo();
1246 TII = STI.getInstrInfo();
1247 MFI = &MF.getFrameInfo();
1248 MRI->freezeReservedRegs(MF);
1249 RegClassInfo.runOnMachineFunction(MF);
1250 UsedInInstr.clear();
1251 UsedInInstr.setUniverse(TRI->getNumRegUnits());
1253 // initialize the virtual->physical register map to have a 'null'
1254 // mapping for all virtual registers
1255 unsigned NumVirtRegs = MRI->getNumVirtRegs();
1256 StackSlotForVirtReg.resize(NumVirtRegs);
1257 LiveVirtRegs.setUniverse(NumVirtRegs);
1258 MayLiveAcrossBlocks.clear();
1259 MayLiveAcrossBlocks.resize(NumVirtRegs);
1261 // Loop over all of the basic blocks, eliminating virtual register references
1262 for (MachineBasicBlock &MBB : MF)
1263 allocateBasicBlock(MBB);
1265 // All machine operands and other references to virtual registers have been
1266 // replaced. Remove the virtual registers.
1267 MRI->clearVirtRegs();
1269 StackSlotForVirtReg.clear();
1270 LiveDbgValueMap.clear();
1274 FunctionPass *llvm::createFastRegisterAllocator() {
1275 return new RegAllocFast();