10b57cec5SDimitry Andric //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file This register allocator allocates registers to a basic block at a
100b57cec5SDimitry Andric /// time, attempting to keep values in registers and reusing registers as
110b57cec5SDimitry Andric /// appropriate.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
170b57cec5SDimitry Andric #include "llvm/ADT/IndexedMap.h"
18349cc55cSDimitry Andric #include "llvm/ADT/MapVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SparseSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
31fe6060f1SDimitry Andric #include "llvm/CodeGen/RegAllocCommon.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/RegAllocRegistry.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
38480093f4SDimitry Andric #include "llvm/InitializePasses.h"
390b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
400b57cec5SDimitry Andric #include "llvm/Pass.h"
410b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
420b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
430b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
440b57cec5SDimitry Andric #include <cassert>
450b57cec5SDimitry Andric #include <tuple>
460b57cec5SDimitry Andric #include <vector>
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric using namespace llvm;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric #define DEBUG_TYPE "regalloc"
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric STATISTIC(NumStores, "Number of stores added");
530b57cec5SDimitry Andric STATISTIC(NumLoads, "Number of loads added");
540b57cec5SDimitry Andric STATISTIC(NumCoalesced, "Number of copies coalesced");
550b57cec5SDimitry Andric 
56e8d8bef9SDimitry Andric // FIXME: Remove this switch when all testcases are fixed!
57e8d8bef9SDimitry Andric static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
58e8d8bef9SDimitry Andric                                        cl::Hidden);
59e8d8bef9SDimitry Andric 
60c9157d92SDimitry Andric static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator",
61c9157d92SDimitry Andric                                      createFastRegisterAllocator);
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric namespace {
640b57cec5SDimitry Andric 
65*e710425bSDimitry Andric /// Assign ascending index for instructions in machine basic block. The index
66*e710425bSDimitry Andric /// can be used to determine dominance between instructions in same MBB.
67*e710425bSDimitry Andric class InstrPosIndexes {
68*e710425bSDimitry Andric public:
unsetInitialized()69*e710425bSDimitry Andric   void unsetInitialized() { IsInitialized = false; }
70*e710425bSDimitry Andric 
init(const MachineBasicBlock & MBB)71*e710425bSDimitry Andric   void init(const MachineBasicBlock &MBB) {
72*e710425bSDimitry Andric     CurMBB = &MBB;
73*e710425bSDimitry Andric     Instr2PosIndex.clear();
74*e710425bSDimitry Andric     uint64_t LastIndex = 0;
75*e710425bSDimitry Andric     for (const MachineInstr &MI : MBB) {
76*e710425bSDimitry Andric       LastIndex += InstrDist;
77*e710425bSDimitry Andric       Instr2PosIndex[&MI] = LastIndex;
78*e710425bSDimitry Andric     }
79*e710425bSDimitry Andric   }
80*e710425bSDimitry Andric 
81*e710425bSDimitry Andric   /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to assign
82*e710425bSDimitry Andric   /// index without affecting existing instruction's index. Return true if all
83*e710425bSDimitry Andric   /// instructions index has been reassigned.
getIndex(const MachineInstr & MI,uint64_t & Index)84*e710425bSDimitry Andric   bool getIndex(const MachineInstr &MI, uint64_t &Index) {
85*e710425bSDimitry Andric     if (!IsInitialized) {
86*e710425bSDimitry Andric       init(*MI.getParent());
87*e710425bSDimitry Andric       IsInitialized = true;
88*e710425bSDimitry Andric       Index = Instr2PosIndex.at(&MI);
89*e710425bSDimitry Andric       return true;
90*e710425bSDimitry Andric     }
91*e710425bSDimitry Andric 
92*e710425bSDimitry Andric     assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
93*e710425bSDimitry Andric     auto It = Instr2PosIndex.find(&MI);
94*e710425bSDimitry Andric     if (It != Instr2PosIndex.end()) {
95*e710425bSDimitry Andric       Index = It->second;
96*e710425bSDimitry Andric       return false;
97*e710425bSDimitry Andric     }
98*e710425bSDimitry Andric 
99*e710425bSDimitry Andric     // Distance is the number of consecutive unassigned instructions including
100*e710425bSDimitry Andric     // MI. Start is the first instruction of them. End is the next of last
101*e710425bSDimitry Andric     // instruction of them.
102*e710425bSDimitry Andric     // e.g.
103*e710425bSDimitry Andric     // |Instruction|  A   |  B   |  C   |  MI  |  D   |  E   |
104*e710425bSDimitry Andric     // |   Index   | 1024 |      |      |      |      | 2048 |
105*e710425bSDimitry Andric     //
106*e710425bSDimitry Andric     // In this case, B, C, MI, D are unassigned. Distance is 4, Start is B, End
107*e710425bSDimitry Andric     // is E.
108*e710425bSDimitry Andric     unsigned Distance = 1;
109*e710425bSDimitry Andric     MachineBasicBlock::const_iterator Start = MI.getIterator(),
110*e710425bSDimitry Andric                                       End = std::next(Start);
111*e710425bSDimitry Andric     while (Start != CurMBB->begin() &&
112*e710425bSDimitry Andric            !Instr2PosIndex.count(&*std::prev(Start))) {
113*e710425bSDimitry Andric       --Start;
114*e710425bSDimitry Andric       ++Distance;
115*e710425bSDimitry Andric     }
116*e710425bSDimitry Andric     while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
117*e710425bSDimitry Andric       ++End;
118*e710425bSDimitry Andric       ++Distance;
119*e710425bSDimitry Andric     }
120*e710425bSDimitry Andric 
121*e710425bSDimitry Andric     // LastIndex is initialized to last used index prior to MI or zero.
122*e710425bSDimitry Andric     // In previous example, LastIndex is 1024, EndIndex is 2048;
123*e710425bSDimitry Andric     uint64_t LastIndex =
124*e710425bSDimitry Andric         Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
125*e710425bSDimitry Andric     uint64_t Step;
126*e710425bSDimitry Andric     if (End == CurMBB->end())
127*e710425bSDimitry Andric       Step = static_cast<uint64_t>(InstrDist);
128*e710425bSDimitry Andric     else {
129*e710425bSDimitry Andric       // No instruction uses index zero.
130*e710425bSDimitry Andric       uint64_t EndIndex = Instr2PosIndex.at(&*End);
131*e710425bSDimitry Andric       assert(EndIndex > LastIndex && "Index must be ascending order");
132*e710425bSDimitry Andric       unsigned NumAvailableIndexes = EndIndex - LastIndex - 1;
133*e710425bSDimitry Andric       // We want index gap between two adjacent MI is as same as possible. Given
134*e710425bSDimitry Andric       // total A available indexes, D is number of consecutive unassigned
135*e710425bSDimitry Andric       // instructions, S is the step.
136*e710425bSDimitry Andric       // |<- S-1 -> MI <- S-1 -> MI <- A-S*D ->|
137*e710425bSDimitry Andric       // There're S-1 available indexes between unassigned instruction and its
138*e710425bSDimitry Andric       // predecessor. There're A-S*D available indexes between the last
139*e710425bSDimitry Andric       // unassigned instruction and its successor.
140*e710425bSDimitry Andric       // Ideally, we want
141*e710425bSDimitry Andric       //    S-1 = A-S*D
142*e710425bSDimitry Andric       // then
143*e710425bSDimitry Andric       //    S = (A+1)/(D+1)
144*e710425bSDimitry Andric       // An valid S must be integer greater than zero, so
145*e710425bSDimitry Andric       //    S <= (A+1)/(D+1)
146*e710425bSDimitry Andric       // =>
147*e710425bSDimitry Andric       //    A-S*D >= 0
148*e710425bSDimitry Andric       // That means we can safely use (A+1)/(D+1) as step.
149*e710425bSDimitry Andric       // In previous example, Step is 204, Index of B, C, MI, D is 1228, 1432,
150*e710425bSDimitry Andric       // 1636, 1840.
151*e710425bSDimitry Andric       Step = (NumAvailableIndexes + 1) / (Distance + 1);
152*e710425bSDimitry Andric     }
153*e710425bSDimitry Andric 
154*e710425bSDimitry Andric     // Reassign index for all instructions if number of new inserted
155*e710425bSDimitry Andric     // instructions exceed slot or all instructions are new.
156*e710425bSDimitry Andric     if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
157*e710425bSDimitry Andric       init(*CurMBB);
158*e710425bSDimitry Andric       Index = Instr2PosIndex.at(&MI);
159*e710425bSDimitry Andric       return true;
160*e710425bSDimitry Andric     }
161*e710425bSDimitry Andric 
162*e710425bSDimitry Andric     for (auto I = Start; I != End; ++I) {
163*e710425bSDimitry Andric       LastIndex += Step;
164*e710425bSDimitry Andric       Instr2PosIndex[&*I] = LastIndex;
165*e710425bSDimitry Andric     }
166*e710425bSDimitry Andric     Index = Instr2PosIndex.at(&MI);
167*e710425bSDimitry Andric     return false;
168*e710425bSDimitry Andric   }
169*e710425bSDimitry Andric 
170*e710425bSDimitry Andric private:
171*e710425bSDimitry Andric   bool IsInitialized = false;
172*e710425bSDimitry Andric   enum { InstrDist = 1024 };
173*e710425bSDimitry Andric   const MachineBasicBlock *CurMBB = nullptr;
174*e710425bSDimitry Andric   DenseMap<const MachineInstr *, uint64_t> Instr2PosIndex;
175*e710425bSDimitry Andric };
176*e710425bSDimitry Andric 
1770b57cec5SDimitry Andric class RegAllocFast : public MachineFunctionPass {
1780b57cec5SDimitry Andric public:
1790b57cec5SDimitry Andric   static char ID;
1800b57cec5SDimitry Andric 
RegAllocFast(const RegClassFilterFunc F=allocateAllRegClasses,bool ClearVirtRegs_=true)181fe6060f1SDimitry Andric   RegAllocFast(const RegClassFilterFunc F = allocateAllRegClasses,
182c9157d92SDimitry Andric                bool ClearVirtRegs_ = true)
183c9157d92SDimitry Andric       : MachineFunctionPass(ID), ShouldAllocateClass(F),
184c9157d92SDimitry Andric         StackSlotForVirtReg(-1), ClearVirtRegs(ClearVirtRegs_) {}
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric private:
187fe013be4SDimitry Andric   MachineFrameInfo *MFI = nullptr;
188fe013be4SDimitry Andric   MachineRegisterInfo *MRI = nullptr;
189fe013be4SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
190fe013be4SDimitry Andric   const TargetInstrInfo *TII = nullptr;
1910b57cec5SDimitry Andric   RegisterClassInfo RegClassInfo;
192fe6060f1SDimitry Andric   const RegClassFilterFunc ShouldAllocateClass;
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   /// Basic block currently being allocated.
195fe013be4SDimitry Andric   MachineBasicBlock *MBB = nullptr;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   /// Maps virtual regs to the frame index where these values are spilled.
1980b57cec5SDimitry Andric   IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
1990b57cec5SDimitry Andric 
200fe6060f1SDimitry Andric   bool ClearVirtRegs;
201fe6060f1SDimitry Andric 
2020b57cec5SDimitry Andric   /// Everything we know about a live virtual register.
2030b57cec5SDimitry Andric   struct LiveReg {
2040b57cec5SDimitry Andric     MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
205480093f4SDimitry Andric     Register VirtReg;                ///< Virtual register number.
2060b57cec5SDimitry Andric     MCPhysReg PhysReg = 0;           ///< Currently held here.
207e8d8bef9SDimitry Andric     bool LiveOut = false;            ///< Register is possibly live out.
208e8d8bef9SDimitry Andric     bool Reloaded = false;           ///< Register was reloaded.
209e8d8bef9SDimitry Andric     bool Error = false;              ///< Could not allocate.
2100b57cec5SDimitry Andric 
LiveReg__anonf5ca9da10111::RegAllocFast::LiveReg211480093f4SDimitry Andric     explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
2120b57cec5SDimitry Andric 
getSparseSetIndex__anonf5ca9da10111::RegAllocFast::LiveReg2130b57cec5SDimitry Andric     unsigned getSparseSetIndex() const {
2148bcb0991SDimitry Andric       return Register::virtReg2Index(VirtReg);
2150b57cec5SDimitry Andric     }
2160b57cec5SDimitry Andric   };
2170b57cec5SDimitry Andric 
218fe013be4SDimitry Andric   using LiveRegMap = SparseSet<LiveReg, identity<unsigned>, uint16_t>;
2190b57cec5SDimitry Andric   /// This map contains entries for each virtual register that is currently
2200b57cec5SDimitry Andric   /// available in a physical register.
2210b57cec5SDimitry Andric   LiveRegMap LiveVirtRegs;
2220b57cec5SDimitry Andric 
223e8d8bef9SDimitry Andric   /// Stores assigned virtual registers present in the bundle MI.
224e8d8bef9SDimitry Andric   DenseMap<Register, MCPhysReg> BundleVirtRegsMap;
225e8d8bef9SDimitry Andric 
226fe6060f1SDimitry Andric   DenseMap<unsigned, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
227e8d8bef9SDimitry Andric   /// List of DBG_VALUE that we encountered without the vreg being assigned
228e8d8bef9SDimitry Andric   /// because they were placed after the last use of the vreg.
229e8d8bef9SDimitry Andric   DenseMap<unsigned, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric   /// Has a bit set for every virtual register for which it was determined
2320b57cec5SDimitry Andric   /// that it is alive across blocks.
2330b57cec5SDimitry Andric   BitVector MayLiveAcrossBlocks;
2340b57cec5SDimitry Andric 
235e8d8bef9SDimitry Andric   /// State of a register unit.
236e8d8bef9SDimitry Andric   enum RegUnitState {
2370b57cec5SDimitry Andric     /// A free register is not currently in use and can be allocated
2380b57cec5SDimitry Andric     /// immediately without checking aliases.
2390b57cec5SDimitry Andric     regFree,
2400b57cec5SDimitry Andric 
241e8d8bef9SDimitry Andric     /// A pre-assigned register has been assigned before register allocation
242e8d8bef9SDimitry Andric     /// (e.g., setting up a call parameter).
243e8d8bef9SDimitry Andric     regPreAssigned,
244e8d8bef9SDimitry Andric 
245e8d8bef9SDimitry Andric     /// Used temporarily in reloadAtBegin() to mark register units that are
246e8d8bef9SDimitry Andric     /// live-in to the basic block.
247e8d8bef9SDimitry Andric     regLiveIn,
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric     /// A register state may also be a virtual register number, indication
2500b57cec5SDimitry Andric     /// that the physical register is currently allocated to a virtual
2510b57cec5SDimitry Andric     /// register. In that case, LiveVirtRegs contains the inverse mapping.
2520b57cec5SDimitry Andric   };
2530b57cec5SDimitry Andric 
254e8d8bef9SDimitry Andric   /// Maps each physical register to a RegUnitState enum or virtual register.
255e8d8bef9SDimitry Andric   std::vector<unsigned> RegUnitStates;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   SmallVector<MachineInstr *, 32> Coalesced;
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
2600b57cec5SDimitry Andric   /// Set of register units that are used in the current instruction, and so
2610b57cec5SDimitry Andric   /// cannot be allocated.
2620b57cec5SDimitry Andric   RegUnitSet UsedInInstr;
263e8d8bef9SDimitry Andric   RegUnitSet PhysRegUses;
264e8d8bef9SDimitry Andric   SmallVector<uint16_t, 8> DefOperandIndexes;
265fe6060f1SDimitry Andric   // Register masks attached to the current instruction.
266fe6060f1SDimitry Andric   SmallVector<const uint32_t *> RegMasks;
2670b57cec5SDimitry Andric 
268*e710425bSDimitry Andric   // Assign index for each instruction to quickly determine dominance.
269*e710425bSDimitry Andric   InstrPosIndexes PosIndexes;
270*e710425bSDimitry Andric 
2710b57cec5SDimitry Andric   void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
272e8d8bef9SDimitry Andric   bool isPhysRegFree(MCPhysReg PhysReg) const;
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   /// Mark a physreg as used in this instruction.
markRegUsedInInstr(MCPhysReg PhysReg)2750b57cec5SDimitry Andric   void markRegUsedInInstr(MCPhysReg PhysReg) {
276fe013be4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg))
277fe013be4SDimitry Andric       UsedInInstr.insert(Unit);
2780b57cec5SDimitry Andric   }
2790b57cec5SDimitry Andric 
280fe6060f1SDimitry Andric   // Check if physreg is clobbered by instruction's regmask(s).
isClobberedByRegMasks(MCPhysReg PhysReg) const281fe6060f1SDimitry Andric   bool isClobberedByRegMasks(MCPhysReg PhysReg) const {
282fe6060f1SDimitry Andric     return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
283fe6060f1SDimitry Andric       return MachineOperand::clobbersPhysReg(Mask, PhysReg);
284fe6060f1SDimitry Andric     });
285fe6060f1SDimitry Andric   }
286fe6060f1SDimitry Andric 
2870b57cec5SDimitry Andric   /// Check if a physreg or any of its aliases are used in this instruction.
isRegUsedInInstr(MCPhysReg PhysReg,bool LookAtPhysRegUses) const288e8d8bef9SDimitry Andric   bool isRegUsedInInstr(MCPhysReg PhysReg, bool LookAtPhysRegUses) const {
289fe6060f1SDimitry Andric     if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
290fe6060f1SDimitry Andric       return true;
291fe013be4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
292fe013be4SDimitry Andric       if (UsedInInstr.count(Unit))
2930b57cec5SDimitry Andric         return true;
294fe013be4SDimitry Andric       if (LookAtPhysRegUses && PhysRegUses.count(Unit))
295e8d8bef9SDimitry Andric         return true;
296e8d8bef9SDimitry Andric     }
2970b57cec5SDimitry Andric     return false;
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric 
300e8d8bef9SDimitry Andric   /// Mark physical register as being used in a register use operand.
301e8d8bef9SDimitry Andric   /// This is only used by the special livethrough handling code.
markPhysRegUsedInInstr(MCPhysReg PhysReg)302e8d8bef9SDimitry Andric   void markPhysRegUsedInInstr(MCPhysReg PhysReg) {
303fe013be4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg))
304fe013be4SDimitry Andric       PhysRegUses.insert(Unit);
305e8d8bef9SDimitry Andric   }
306e8d8bef9SDimitry Andric 
307e8d8bef9SDimitry Andric   /// Remove mark of physical register being used in the instruction.
unmarkRegUsedInInstr(MCPhysReg PhysReg)308e8d8bef9SDimitry Andric   void unmarkRegUsedInInstr(MCPhysReg PhysReg) {
309fe013be4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg))
310fe013be4SDimitry Andric       UsedInInstr.erase(Unit);
311e8d8bef9SDimitry Andric   }
312e8d8bef9SDimitry Andric 
3130b57cec5SDimitry Andric   enum : unsigned {
3140b57cec5SDimitry Andric     spillClean = 50,
3150b57cec5SDimitry Andric     spillDirty = 100,
3160b57cec5SDimitry Andric     spillPrefBonus = 20,
3170b57cec5SDimitry Andric     spillImpossible = ~0u
3180b57cec5SDimitry Andric   };
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric public:
getPassName() const3210b57cec5SDimitry Andric   StringRef getPassName() const override { return "Fast Register Allocator"; }
3220b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const3230b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
3240b57cec5SDimitry Andric     AU.setPreservesCFG();
3250b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
3260b57cec5SDimitry Andric   }
3270b57cec5SDimitry Andric 
getRequiredProperties() const3280b57cec5SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
3290b57cec5SDimitry Andric     return MachineFunctionProperties().set(
3300b57cec5SDimitry Andric         MachineFunctionProperties::Property::NoPHIs);
3310b57cec5SDimitry Andric   }
3320b57cec5SDimitry Andric 
getSetProperties() const3330b57cec5SDimitry Andric   MachineFunctionProperties getSetProperties() const override {
334fe6060f1SDimitry Andric     if (ClearVirtRegs) {
3350b57cec5SDimitry Andric       return MachineFunctionProperties().set(
3360b57cec5SDimitry Andric           MachineFunctionProperties::Property::NoVRegs);
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric 
339fe6060f1SDimitry Andric     return MachineFunctionProperties();
340fe6060f1SDimitry Andric   }
341fe6060f1SDimitry Andric 
getClearedProperties() const342e8d8bef9SDimitry Andric   MachineFunctionProperties getClearedProperties() const override {
343e8d8bef9SDimitry Andric     return MachineFunctionProperties().set(
344e8d8bef9SDimitry Andric         MachineFunctionProperties::Property::IsSSA);
345e8d8bef9SDimitry Andric   }
346e8d8bef9SDimitry Andric 
3470b57cec5SDimitry Andric private:
3480b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   void allocateBasicBlock(MachineBasicBlock &MBB);
351e8d8bef9SDimitry Andric 
352e8d8bef9SDimitry Andric   void addRegClassDefCounts(std::vector<unsigned> &RegClassDefCounts,
353e8d8bef9SDimitry Andric                             Register Reg) const;
354e8d8bef9SDimitry Andric 
355fe013be4SDimitry Andric   void findAndSortDefOperandIndexes(const MachineInstr &MI);
356fe013be4SDimitry Andric 
3570b57cec5SDimitry Andric   void allocateInstruction(MachineInstr &MI);
3580b57cec5SDimitry Andric   void handleDebugValue(MachineInstr &MI);
359e8d8bef9SDimitry Andric   void handleBundle(MachineInstr &MI);
3600b57cec5SDimitry Andric 
361e8d8bef9SDimitry Andric   bool usePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
362e8d8bef9SDimitry Andric   bool definePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
363e8d8bef9SDimitry Andric   bool displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
364e8d8bef9SDimitry Andric   void freePhysReg(MCPhysReg PhysReg);
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   unsigned calcSpillCost(MCPhysReg PhysReg) const;
3670b57cec5SDimitry Andric 
findLiveVirtReg(Register VirtReg)368480093f4SDimitry Andric   LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
3698bcb0991SDimitry Andric     return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
3700b57cec5SDimitry Andric   }
3710b57cec5SDimitry Andric 
findLiveVirtReg(Register VirtReg) const372480093f4SDimitry Andric   LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
3738bcb0991SDimitry Andric     return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
3740b57cec5SDimitry Andric   }
3750b57cec5SDimitry Andric 
376e8d8bef9SDimitry Andric   void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCPhysReg PhysReg);
377e8d8bef9SDimitry Andric   void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
378e8d8bef9SDimitry Andric                     bool LookAtPhysRegUses = false);
3790b57cec5SDimitry Andric   void allocVirtRegUndef(MachineOperand &MO);
380e8d8bef9SDimitry Andric   void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
381e8d8bef9SDimitry Andric                                  MCPhysReg Reg);
382fe013be4SDimitry Andric   bool defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
383e8d8bef9SDimitry Andric                                 Register VirtReg);
384fe013be4SDimitry Andric   bool defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
385e8d8bef9SDimitry Andric                      bool LookAtPhysRegUses = false);
386c9157d92SDimitry Andric   bool useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
387e8d8bef9SDimitry Andric 
388e8d8bef9SDimitry Andric   MachineBasicBlock::iterator
389e8d8bef9SDimitry Andric   getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
390e8d8bef9SDimitry Andric                             SmallSet<Register, 2> &PrologLiveIns) const;
391e8d8bef9SDimitry Andric 
392e8d8bef9SDimitry Andric   void reloadAtBegin(MachineBasicBlock &MBB);
393fe013be4SDimitry Andric   bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
3940b57cec5SDimitry Andric 
395480093f4SDimitry Andric   Register traceCopies(Register VirtReg) const;
396480093f4SDimitry Andric   Register traceCopyChain(Register Reg) const;
3970b57cec5SDimitry Andric 
398bdd1243dSDimitry Andric   bool shouldAllocateRegister(const Register Reg) const;
399480093f4SDimitry Andric   int getStackSpaceFor(Register VirtReg);
400480093f4SDimitry Andric   void spill(MachineBasicBlock::iterator Before, Register VirtReg,
401e8d8bef9SDimitry Andric              MCPhysReg AssignedReg, bool Kill, bool LiveOut);
402480093f4SDimitry Andric   void reload(MachineBasicBlock::iterator Before, Register VirtReg,
4030b57cec5SDimitry Andric               MCPhysReg PhysReg);
4040b57cec5SDimitry Andric 
405480093f4SDimitry Andric   bool mayLiveOut(Register VirtReg);
406480093f4SDimitry Andric   bool mayLiveIn(Register VirtReg);
4070b57cec5SDimitry Andric 
408e8d8bef9SDimitry Andric   void dumpState() const;
4090b57cec5SDimitry Andric };
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric } // end anonymous namespace
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric char RegAllocFast::ID = 0;
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
4160b57cec5SDimitry Andric                 false)
4170b57cec5SDimitry Andric 
shouldAllocateRegister(const Register Reg) const418bdd1243dSDimitry Andric bool RegAllocFast::shouldAllocateRegister(const Register Reg) const {
419bdd1243dSDimitry Andric   assert(Reg.isVirtual());
420bdd1243dSDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
421bdd1243dSDimitry Andric   return ShouldAllocateClass(*TRI, RC);
422bdd1243dSDimitry Andric }
423bdd1243dSDimitry Andric 
setPhysRegState(MCPhysReg PhysReg,unsigned NewState)4240b57cec5SDimitry Andric void RegAllocFast::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
425fe013be4SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg))
426fe013be4SDimitry Andric     RegUnitStates[Unit] = NewState;
427e8d8bef9SDimitry Andric }
428e8d8bef9SDimitry Andric 
isPhysRegFree(MCPhysReg PhysReg) const429e8d8bef9SDimitry Andric bool RegAllocFast::isPhysRegFree(MCPhysReg PhysReg) const {
430fe013be4SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
431fe013be4SDimitry Andric     if (RegUnitStates[Unit] != regFree)
432e8d8bef9SDimitry Andric       return false;
433e8d8bef9SDimitry Andric   }
434e8d8bef9SDimitry Andric   return true;
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric /// This allocates space for the specified virtual register to be held on the
4380b57cec5SDimitry Andric /// stack.
getStackSpaceFor(Register VirtReg)439480093f4SDimitry Andric int RegAllocFast::getStackSpaceFor(Register VirtReg) {
4400b57cec5SDimitry Andric   // Find the location Reg would belong...
4410b57cec5SDimitry Andric   int SS = StackSlotForVirtReg[VirtReg];
4420b57cec5SDimitry Andric   // Already has space allocated?
4430b57cec5SDimitry Andric   if (SS != -1)
4440b57cec5SDimitry Andric     return SS;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   // Allocate a new stack object for this spill location...
4470b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
4480b57cec5SDimitry Andric   unsigned Size = TRI->getSpillSize(RC);
4495ffd83dbSDimitry Andric   Align Alignment = TRI->getSpillAlign(RC);
4505ffd83dbSDimitry Andric   int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // Assign the slot.
4530b57cec5SDimitry Andric   StackSlotForVirtReg[VirtReg] = FrameIdx;
4540b57cec5SDimitry Andric   return FrameIdx;
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric 
dominates(InstrPosIndexes & PosIndexes,const MachineInstr & A,const MachineInstr & B)457*e710425bSDimitry Andric static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
458*e710425bSDimitry Andric                       const MachineInstr &B) {
459*e710425bSDimitry Andric   uint64_t IndexA, IndexB;
460*e710425bSDimitry Andric   PosIndexes.getIndex(A, IndexA);
461*e710425bSDimitry Andric   if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
462*e710425bSDimitry Andric     PosIndexes.getIndex(A, IndexA);
463*e710425bSDimitry Andric   return IndexA < IndexB;
464e8d8bef9SDimitry Andric }
465e8d8bef9SDimitry Andric 
4660b57cec5SDimitry Andric /// Returns false if \p VirtReg is known to not live out of the current block.
mayLiveOut(Register VirtReg)467480093f4SDimitry Andric bool RegAllocFast::mayLiveOut(Register VirtReg) {
4688bcb0991SDimitry Andric   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
4690b57cec5SDimitry Andric     // Cannot be live-out if there are no successors.
4700b57cec5SDimitry Andric     return !MBB->succ_empty();
4710b57cec5SDimitry Andric   }
4720b57cec5SDimitry Andric 
473e8d8bef9SDimitry Andric   const MachineInstr *SelfLoopDef = nullptr;
474e8d8bef9SDimitry Andric 
475e8d8bef9SDimitry Andric   // If this block loops back to itself, it is necessary to check whether the
476e8d8bef9SDimitry Andric   // use comes after the def.
4770b57cec5SDimitry Andric   if (MBB->isSuccessor(MBB)) {
47881ad6265SDimitry Andric     // Find the first def in the self loop MBB.
47981ad6265SDimitry Andric     for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
48081ad6265SDimitry Andric       if (DefInst.getParent() != MBB) {
48181ad6265SDimitry Andric         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
48281ad6265SDimitry Andric         return true;
48381ad6265SDimitry Andric       } else {
484*e710425bSDimitry Andric         if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
48581ad6265SDimitry Andric           SelfLoopDef = &DefInst;
48681ad6265SDimitry Andric       }
48781ad6265SDimitry Andric     }
488e8d8bef9SDimitry Andric     if (!SelfLoopDef) {
4898bcb0991SDimitry Andric       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
4900b57cec5SDimitry Andric       return true;
4910b57cec5SDimitry Andric     }
492e8d8bef9SDimitry Andric   }
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   // See if the first \p Limit uses of the register are all in the current
4950b57cec5SDimitry Andric   // block.
4960b57cec5SDimitry Andric   static const unsigned Limit = 8;
4970b57cec5SDimitry Andric   unsigned C = 0;
498e8d8bef9SDimitry Andric   for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
4990b57cec5SDimitry Andric     if (UseInst.getParent() != MBB || ++C >= Limit) {
5008bcb0991SDimitry Andric       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
5010b57cec5SDimitry Andric       // Cannot be live-out if there are no successors.
5020b57cec5SDimitry Andric       return !MBB->succ_empty();
5030b57cec5SDimitry Andric     }
504e8d8bef9SDimitry Andric 
505e8d8bef9SDimitry Andric     if (SelfLoopDef) {
506e8d8bef9SDimitry Andric       // Try to handle some simple cases to avoid spilling and reloading every
507e8d8bef9SDimitry Andric       // value inside a self looping block.
508e8d8bef9SDimitry Andric       if (SelfLoopDef == &UseInst ||
509*e710425bSDimitry Andric           !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
510e8d8bef9SDimitry Andric         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
511e8d8bef9SDimitry Andric         return true;
512e8d8bef9SDimitry Andric       }
513e8d8bef9SDimitry Andric     }
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   return false;
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric /// Returns false if \p VirtReg is known to not be live into the current block.
mayLiveIn(Register VirtReg)520480093f4SDimitry Andric bool RegAllocFast::mayLiveIn(Register VirtReg) {
5218bcb0991SDimitry Andric   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
5220b57cec5SDimitry Andric     return !MBB->pred_empty();
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   // See if the first \p Limit def of the register are all in the current block.
5250b57cec5SDimitry Andric   static const unsigned Limit = 8;
5260b57cec5SDimitry Andric   unsigned C = 0;
5270b57cec5SDimitry Andric   for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
5280b57cec5SDimitry Andric     if (DefInst.getParent() != MBB || ++C >= Limit) {
5298bcb0991SDimitry Andric       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
5300b57cec5SDimitry Andric       return !MBB->pred_empty();
5310b57cec5SDimitry Andric     }
5320b57cec5SDimitry Andric   }
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   return false;
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric /// Insert spill instruction for \p AssignedReg before \p Before. Update
5380b57cec5SDimitry Andric /// DBG_VALUEs with \p VirtReg operands with the stack slot.
spill(MachineBasicBlock::iterator Before,Register VirtReg,MCPhysReg AssignedReg,bool Kill,bool LiveOut)539480093f4SDimitry Andric void RegAllocFast::spill(MachineBasicBlock::iterator Before, Register VirtReg,
540e8d8bef9SDimitry Andric                          MCPhysReg AssignedReg, bool Kill, bool LiveOut) {
541c9157d92SDimitry Andric   LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
542c9157d92SDimitry Andric                     << printReg(AssignedReg, TRI));
5430b57cec5SDimitry Andric   int FI = getStackSpaceFor(VirtReg);
5440b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
547bdd1243dSDimitry Andric   TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI,
548bdd1243dSDimitry Andric                            VirtReg);
5490b57cec5SDimitry Andric   ++NumStores;
5500b57cec5SDimitry Andric 
551e8d8bef9SDimitry Andric   MachineBasicBlock::iterator FirstTerm = MBB->getFirstTerminator();
552e8d8bef9SDimitry Andric 
553e8d8bef9SDimitry Andric   // When we spill a virtual register, we will have spill instructions behind
554e8d8bef9SDimitry Andric   // every definition of it, meaning we can switch all the DBG_VALUEs over
555e8d8bef9SDimitry Andric   // to just reference the stack slot.
556fe6060f1SDimitry Andric   SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
557349cc55cSDimitry Andric   SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
558fe6060f1SDimitry Andric       SpilledOperandsMap;
559fe6060f1SDimitry Andric   for (MachineOperand *MO : LRIDbgOperands)
560fe6060f1SDimitry Andric     SpilledOperandsMap[MO->getParent()].push_back(MO);
561fe6060f1SDimitry Andric   for (auto MISpilledOperands : SpilledOperandsMap) {
562fe6060f1SDimitry Andric     MachineInstr &DBG = *MISpilledOperands.first;
56350d7464cSDimitry Andric     // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
56450d7464cSDimitry Andric     if (DBG.isDebugValueList())
56550d7464cSDimitry Andric       continue;
566fe6060f1SDimitry Andric     MachineInstr *NewDV = buildDbgValueForSpill(
567fe6060f1SDimitry Andric         *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
5680b57cec5SDimitry Andric     assert(NewDV->getParent() == MBB && "dangling parent pointer");
5690b57cec5SDimitry Andric     (void)NewDV;
5700b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
571e8d8bef9SDimitry Andric 
572e8d8bef9SDimitry Andric     if (LiveOut) {
573e8d8bef9SDimitry Andric       // We need to insert a DBG_VALUE at the end of the block if the spill slot
574e8d8bef9SDimitry Andric       // is live out, but there is another use of the value after the
575e8d8bef9SDimitry Andric       // spill. This will allow LiveDebugValues to see the correct live out
576e8d8bef9SDimitry Andric       // value to propagate to the successors.
577e8d8bef9SDimitry Andric       MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
578e8d8bef9SDimitry Andric       MBB->insert(FirstTerm, ClonedDV);
579e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
580e8d8bef9SDimitry Andric     }
581e8d8bef9SDimitry Andric 
582e8d8bef9SDimitry Andric     // Rewrite unassigned dbg_values to use the stack slot.
583fe6060f1SDimitry Andric     // TODO We can potentially do this for list debug values as well if we know
584fe6060f1SDimitry Andric     // how the dbg_values are getting unassigned.
585fe6060f1SDimitry Andric     if (DBG.isNonListDebugValue()) {
586fe6060f1SDimitry Andric       MachineOperand &MO = DBG.getDebugOperand(0);
587fe6060f1SDimitry Andric       if (MO.isReg() && MO.getReg() == 0) {
588fe6060f1SDimitry Andric         updateDbgValueForSpill(DBG, FI, 0);
589fe6060f1SDimitry Andric       }
590fe6060f1SDimitry Andric     }
5910b57cec5SDimitry Andric   }
5920b57cec5SDimitry Andric   // Now this register is spilled there is should not be any DBG_VALUE
5930b57cec5SDimitry Andric   // pointing to this register because they are all pointing to spilled value
5940b57cec5SDimitry Andric   // now.
595fe6060f1SDimitry Andric   LRIDbgOperands.clear();
5960b57cec5SDimitry Andric }
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric /// Insert reload instruction for \p PhysReg before \p Before.
reload(MachineBasicBlock::iterator Before,Register VirtReg,MCPhysReg PhysReg)599480093f4SDimitry Andric void RegAllocFast::reload(MachineBasicBlock::iterator Before, Register VirtReg,
6000b57cec5SDimitry Andric                           MCPhysReg PhysReg) {
6010b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
6020b57cec5SDimitry Andric                     << printReg(PhysReg, TRI) << '\n');
6030b57cec5SDimitry Andric   int FI = getStackSpaceFor(VirtReg);
6040b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
605bdd1243dSDimitry Andric   TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI, VirtReg);
6060b57cec5SDimitry Andric   ++NumLoads;
6070b57cec5SDimitry Andric }
6080b57cec5SDimitry Andric 
609e8d8bef9SDimitry Andric /// Get basic block begin insertion point.
610e8d8bef9SDimitry Andric /// This is not just MBB.begin() because surprisingly we have EH_LABEL
611e8d8bef9SDimitry Andric /// instructions marking the begin of a basic block. This means we must insert
612e8d8bef9SDimitry Andric /// new instructions after such labels...
getMBBBeginInsertionPoint(MachineBasicBlock & MBB,SmallSet<Register,2> & PrologLiveIns) const613c9157d92SDimitry Andric MachineBasicBlock::iterator RegAllocFast::getMBBBeginInsertionPoint(
614e8d8bef9SDimitry Andric     MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
615e8d8bef9SDimitry Andric   MachineBasicBlock::iterator I = MBB.begin();
616e8d8bef9SDimitry Andric   while (I != MBB.end()) {
617e8d8bef9SDimitry Andric     if (I->isLabel()) {
618e8d8bef9SDimitry Andric       ++I;
619e8d8bef9SDimitry Andric       continue;
6200b57cec5SDimitry Andric     }
6210b57cec5SDimitry Andric 
622e8d8bef9SDimitry Andric     // Most reloads should be inserted after prolog instructions.
623e8d8bef9SDimitry Andric     if (!TII->isBasicBlockPrologue(*I))
624e8d8bef9SDimitry Andric       break;
625e8d8bef9SDimitry Andric 
626e8d8bef9SDimitry Andric     // However if a prolog instruction reads a register that needs to be
627e8d8bef9SDimitry Andric     // reloaded, the reload should be inserted before the prolog.
628e8d8bef9SDimitry Andric     for (MachineOperand &MO : I->operands()) {
629e8d8bef9SDimitry Andric       if (MO.isReg())
630e8d8bef9SDimitry Andric         PrologLiveIns.insert(MO.getReg());
6310b57cec5SDimitry Andric     }
6320b57cec5SDimitry Andric 
633e8d8bef9SDimitry Andric     ++I;
6340b57cec5SDimitry Andric   }
6350b57cec5SDimitry Andric 
636e8d8bef9SDimitry Andric   return I;
6370b57cec5SDimitry Andric }
6380b57cec5SDimitry Andric 
639e8d8bef9SDimitry Andric /// Reload all currently assigned virtual registers.
reloadAtBegin(MachineBasicBlock & MBB)640e8d8bef9SDimitry Andric void RegAllocFast::reloadAtBegin(MachineBasicBlock &MBB) {
6410b57cec5SDimitry Andric   if (LiveVirtRegs.empty())
6420b57cec5SDimitry Andric     return;
643e8d8bef9SDimitry Andric 
644e8d8bef9SDimitry Andric   for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
645e8d8bef9SDimitry Andric     MCPhysReg Reg = P.PhysReg;
646e8d8bef9SDimitry Andric     // Set state to live-in. This possibly overrides mappings to virtual
647e8d8bef9SDimitry Andric     // registers but we don't care anymore at this point.
648e8d8bef9SDimitry Andric     setPhysRegState(Reg, regLiveIn);
649e8d8bef9SDimitry Andric   }
650e8d8bef9SDimitry Andric 
651e8d8bef9SDimitry Andric   SmallSet<Register, 2> PrologLiveIns;
652e8d8bef9SDimitry Andric 
6530b57cec5SDimitry Andric   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
6540b57cec5SDimitry Andric   // of spilling here is deterministic, if arbitrary.
655c9157d92SDimitry Andric   MachineBasicBlock::iterator InsertBefore =
656c9157d92SDimitry Andric       getMBBBeginInsertionPoint(MBB, PrologLiveIns);
657e8d8bef9SDimitry Andric   for (const LiveReg &LR : LiveVirtRegs) {
658e8d8bef9SDimitry Andric     MCPhysReg PhysReg = LR.PhysReg;
659e8d8bef9SDimitry Andric     if (PhysReg == 0)
6600b57cec5SDimitry Andric       continue;
661e8d8bef9SDimitry Andric 
662fe013be4SDimitry Andric     MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
663e8d8bef9SDimitry Andric     if (RegUnitStates[FirstUnit] == regLiveIn)
6640b57cec5SDimitry Andric       continue;
665e8d8bef9SDimitry Andric 
666e8d8bef9SDimitry Andric     assert((&MBB != &MBB.getParent()->front() || IgnoreMissingDefs) &&
667e8d8bef9SDimitry Andric            "no reload in start block. Missing vreg def?");
668e8d8bef9SDimitry Andric 
669e8d8bef9SDimitry Andric     if (PrologLiveIns.count(PhysReg)) {
670e8d8bef9SDimitry Andric       // FIXME: Theoretically this should use an insert point skipping labels
671e8d8bef9SDimitry Andric       // but I'm not sure how labels should interact with prolog instruction
672e8d8bef9SDimitry Andric       // that need reloads.
673e8d8bef9SDimitry Andric       reload(MBB.begin(), LR.VirtReg, PhysReg);
674e8d8bef9SDimitry Andric     } else
675e8d8bef9SDimitry Andric       reload(InsertBefore, LR.VirtReg, PhysReg);
6760b57cec5SDimitry Andric   }
6770b57cec5SDimitry Andric   LiveVirtRegs.clear();
6780b57cec5SDimitry Andric }
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric /// Handle the direct use of a physical register.  Check that the register is
6810b57cec5SDimitry Andric /// not used by a virtreg. Kill the physreg, marking it free. This may add
6820b57cec5SDimitry Andric /// implicit kills to MO->getParent() and invalidate MO.
usePhysReg(MachineInstr & MI,MCPhysReg Reg)683e8d8bef9SDimitry Andric bool RegAllocFast::usePhysReg(MachineInstr &MI, MCPhysReg Reg) {
684e8d8bef9SDimitry Andric   assert(Register::isPhysicalRegister(Reg) && "expected physreg");
685e8d8bef9SDimitry Andric   bool displacedAny = displacePhysReg(MI, Reg);
686e8d8bef9SDimitry Andric   setPhysRegState(Reg, regPreAssigned);
687e8d8bef9SDimitry Andric   markRegUsedInInstr(Reg);
688e8d8bef9SDimitry Andric   return displacedAny;
68916d6b3b3SDimitry Andric }
69016d6b3b3SDimitry Andric 
definePhysReg(MachineInstr & MI,MCPhysReg Reg)691e8d8bef9SDimitry Andric bool RegAllocFast::definePhysReg(MachineInstr &MI, MCPhysReg Reg) {
692e8d8bef9SDimitry Andric   bool displacedAny = displacePhysReg(MI, Reg);
693e8d8bef9SDimitry Andric   setPhysRegState(Reg, regPreAssigned);
694e8d8bef9SDimitry Andric   return displacedAny;
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
6980b57cec5SDimitry Andric /// similar to defineVirtReg except the physreg is reserved instead of
6990b57cec5SDimitry Andric /// allocated.
displacePhysReg(MachineInstr & MI,MCPhysReg PhysReg)700e8d8bef9SDimitry Andric bool RegAllocFast::displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg) {
701e8d8bef9SDimitry Andric   bool displacedAny = false;
702e8d8bef9SDimitry Andric 
703fe013be4SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
704e8d8bef9SDimitry Andric     switch (unsigned VirtReg = RegUnitStates[Unit]) {
705e8d8bef9SDimitry Andric     default: {
706e8d8bef9SDimitry Andric       LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
707e8d8bef9SDimitry Andric       assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
708e8d8bef9SDimitry Andric       MachineBasicBlock::iterator ReloadBefore =
709e8d8bef9SDimitry Andric           std::next((MachineBasicBlock::iterator)MI.getIterator());
710e8d8bef9SDimitry Andric       reload(ReloadBefore, VirtReg, LRI->PhysReg);
711e8d8bef9SDimitry Andric 
712e8d8bef9SDimitry Andric       setPhysRegState(LRI->PhysReg, regFree);
713e8d8bef9SDimitry Andric       LRI->PhysReg = 0;
714e8d8bef9SDimitry Andric       LRI->Reloaded = true;
715e8d8bef9SDimitry Andric       displacedAny = true;
71616d6b3b3SDimitry Andric       break;
717e8d8bef9SDimitry Andric     }
718e8d8bef9SDimitry Andric     case regPreAssigned:
719e8d8bef9SDimitry Andric       RegUnitStates[Unit] = regFree;
720e8d8bef9SDimitry Andric       displacedAny = true;
721e8d8bef9SDimitry Andric       break;
7220b57cec5SDimitry Andric     case regFree:
723e8d8bef9SDimitry Andric       break;
724e8d8bef9SDimitry Andric     }
725e8d8bef9SDimitry Andric   }
726e8d8bef9SDimitry Andric   return displacedAny;
72716d6b3b3SDimitry Andric }
72816d6b3b3SDimitry Andric 
freePhysReg(MCPhysReg PhysReg)729e8d8bef9SDimitry Andric void RegAllocFast::freePhysReg(MCPhysReg PhysReg) {
730e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
731e8d8bef9SDimitry Andric 
732fe013be4SDimitry Andric   MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
733e8d8bef9SDimitry Andric   switch (unsigned VirtReg = RegUnitStates[FirstUnit]) {
73416d6b3b3SDimitry Andric   case regFree:
735e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
73616d6b3b3SDimitry Andric     return;
737e8d8bef9SDimitry Andric   case regPreAssigned:
738e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
739e8d8bef9SDimitry Andric     setPhysRegState(PhysReg, regFree);
740e8d8bef9SDimitry Andric     return;
741e8d8bef9SDimitry Andric   default: {
742e8d8bef9SDimitry Andric     LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
743e8d8bef9SDimitry Andric     assert(LRI != LiveVirtRegs.end());
744e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
745e8d8bef9SDimitry Andric     setPhysRegState(LRI->PhysReg, regFree);
746e8d8bef9SDimitry Andric     LRI->PhysReg = 0;
7475ffd83dbSDimitry Andric   }
748e8d8bef9SDimitry Andric     return;
7490b57cec5SDimitry Andric   }
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric /// Return the cost of spilling clearing out PhysReg and aliases so it is free
7530b57cec5SDimitry Andric /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
7540b57cec5SDimitry Andric /// disabled - it can be allocated directly.
7550b57cec5SDimitry Andric /// \returns spillImpossible when PhysReg or an alias can't be spilled.
calcSpillCost(MCPhysReg PhysReg) const7560b57cec5SDimitry Andric unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
757fe013be4SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
758fe013be4SDimitry Andric     switch (unsigned VirtReg = RegUnitStates[Unit]) {
75916d6b3b3SDimitry Andric     case regFree:
760e8d8bef9SDimitry Andric       break;
761e8d8bef9SDimitry Andric     case regPreAssigned:
762e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
763e8d8bef9SDimitry Andric                         << printReg(PhysReg, TRI) << '\n');
7640b57cec5SDimitry Andric       return spillImpossible;
7650b57cec5SDimitry Andric     default: {
766e8d8bef9SDimitry Andric       bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
767e8d8bef9SDimitry Andric                        findLiveVirtReg(VirtReg)->LiveOut;
768e8d8bef9SDimitry Andric       return SureSpill ? spillClean : spillDirty;
7690b57cec5SDimitry Andric     }
7700b57cec5SDimitry Andric     }
771e8d8bef9SDimitry Andric   }
772e8d8bef9SDimitry Andric   return 0;
773e8d8bef9SDimitry Andric }
77416d6b3b3SDimitry Andric 
assignDanglingDebugValues(MachineInstr & Definition,Register VirtReg,MCPhysReg Reg)775e8d8bef9SDimitry Andric void RegAllocFast::assignDanglingDebugValues(MachineInstr &Definition,
776e8d8bef9SDimitry Andric                                              Register VirtReg, MCPhysReg Reg) {
777e8d8bef9SDimitry Andric   auto UDBGValIter = DanglingDbgValues.find(VirtReg);
778e8d8bef9SDimitry Andric   if (UDBGValIter == DanglingDbgValues.end())
779e8d8bef9SDimitry Andric     return;
780e8d8bef9SDimitry Andric 
781e8d8bef9SDimitry Andric   SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
782e8d8bef9SDimitry Andric   for (MachineInstr *DbgValue : Dangling) {
783e8d8bef9SDimitry Andric     assert(DbgValue->isDebugValue());
784fe6060f1SDimitry Andric     if (!DbgValue->hasDebugOperandForReg(VirtReg))
785e8d8bef9SDimitry Andric       continue;
786e8d8bef9SDimitry Andric 
787e8d8bef9SDimitry Andric     // Test whether the physreg survives from the definition to the DBG_VALUE.
788e8d8bef9SDimitry Andric     MCPhysReg SetToReg = Reg;
789e8d8bef9SDimitry Andric     unsigned Limit = 20;
790e8d8bef9SDimitry Andric     for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
791c9157d92SDimitry Andric                                      E = DbgValue->getIterator();
792c9157d92SDimitry Andric          I != E; ++I) {
793e8d8bef9SDimitry Andric       if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
794e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
795e8d8bef9SDimitry Andric                           << '\n');
796e8d8bef9SDimitry Andric         SetToReg = 0;
79716d6b3b3SDimitry Andric         break;
7980b57cec5SDimitry Andric       }
79916d6b3b3SDimitry Andric     }
800fe6060f1SDimitry Andric     for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
801e8d8bef9SDimitry Andric       MO.setReg(SetToReg);
802e8d8bef9SDimitry Andric       if (SetToReg != 0)
803e8d8bef9SDimitry Andric         MO.setIsRenamable();
80416d6b3b3SDimitry Andric     }
805fe6060f1SDimitry Andric   }
806e8d8bef9SDimitry Andric   Dangling.clear();
8070b57cec5SDimitry Andric }
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric /// This method updates local state so that we know that PhysReg is the
8100b57cec5SDimitry Andric /// proper container for VirtReg now.  The physical register must not be used
8110b57cec5SDimitry Andric /// for anything else when this is called.
assignVirtToPhysReg(MachineInstr & AtMI,LiveReg & LR,MCPhysReg PhysReg)812e8d8bef9SDimitry Andric void RegAllocFast::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
813e8d8bef9SDimitry Andric                                        MCPhysReg PhysReg) {
814480093f4SDimitry Andric   Register VirtReg = LR.VirtReg;
8150b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
8160b57cec5SDimitry Andric                     << printReg(PhysReg, TRI) << '\n');
8170b57cec5SDimitry Andric   assert(LR.PhysReg == 0 && "Already assigned a physreg");
8180b57cec5SDimitry Andric   assert(PhysReg != 0 && "Trying to assign no register");
8190b57cec5SDimitry Andric   LR.PhysReg = PhysReg;
8200b57cec5SDimitry Andric   setPhysRegState(PhysReg, VirtReg);
821e8d8bef9SDimitry Andric 
822e8d8bef9SDimitry Andric   assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric 
isCoalescable(const MachineInstr & MI)825c9157d92SDimitry Andric static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
8260b57cec5SDimitry Andric 
traceCopyChain(Register Reg) const827480093f4SDimitry Andric Register RegAllocFast::traceCopyChain(Register Reg) const {
8280b57cec5SDimitry Andric   static const unsigned ChainLengthLimit = 3;
8290b57cec5SDimitry Andric   unsigned C = 0;
8300b57cec5SDimitry Andric   do {
831480093f4SDimitry Andric     if (Reg.isPhysical())
8320b57cec5SDimitry Andric       return Reg;
833480093f4SDimitry Andric     assert(Reg.isVirtual());
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric     MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
8360b57cec5SDimitry Andric     if (!VRegDef || !isCoalescable(*VRegDef))
8370b57cec5SDimitry Andric       return 0;
8380b57cec5SDimitry Andric     Reg = VRegDef->getOperand(1).getReg();
8390b57cec5SDimitry Andric   } while (++C <= ChainLengthLimit);
8400b57cec5SDimitry Andric   return 0;
8410b57cec5SDimitry Andric }
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
8440b57cec5SDimitry Andric /// chain of copies to check whether we reach a physical register we can
8450b57cec5SDimitry Andric /// coalesce with.
traceCopies(Register VirtReg) const846480093f4SDimitry Andric Register RegAllocFast::traceCopies(Register VirtReg) const {
8470b57cec5SDimitry Andric   static const unsigned DefLimit = 3;
8480b57cec5SDimitry Andric   unsigned C = 0;
8490b57cec5SDimitry Andric   for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
8500b57cec5SDimitry Andric     if (isCoalescable(MI)) {
8518bcb0991SDimitry Andric       Register Reg = MI.getOperand(1).getReg();
8520b57cec5SDimitry Andric       Reg = traceCopyChain(Reg);
853480093f4SDimitry Andric       if (Reg.isValid())
8540b57cec5SDimitry Andric         return Reg;
8550b57cec5SDimitry Andric     }
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric     if (++C >= DefLimit)
8580b57cec5SDimitry Andric       break;
8590b57cec5SDimitry Andric   }
860480093f4SDimitry Andric   return Register();
8610b57cec5SDimitry Andric }
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric /// Allocates a physical register for VirtReg.
allocVirtReg(MachineInstr & MI,LiveReg & LR,Register Hint0,bool LookAtPhysRegUses)864c9157d92SDimitry Andric void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint0,
865c9157d92SDimitry Andric                                 bool LookAtPhysRegUses) {
866480093f4SDimitry Andric   const Register VirtReg = LR.VirtReg;
867e8d8bef9SDimitry Andric   assert(LR.PhysReg == 0);
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
8700b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
8710b57cec5SDimitry Andric                     << " in class " << TRI->getRegClassName(&RC)
8720b57cec5SDimitry Andric                     << " with hint " << printReg(Hint0, TRI) << '\n');
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   // Take hint when possible.
875e8d8bef9SDimitry Andric   if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
876e8d8bef9SDimitry Andric       !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
877e8d8bef9SDimitry Andric     // Take hint if the register is currently free.
878e8d8bef9SDimitry Andric     if (isPhysRegFree(Hint0)) {
8790b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
8800b57cec5SDimitry Andric                         << '\n');
881e8d8bef9SDimitry Andric       assignVirtToPhysReg(MI, LR, Hint0);
8820b57cec5SDimitry Andric       return;
8830b57cec5SDimitry Andric     } else {
884e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
8850b57cec5SDimitry Andric                         << " occupied\n");
8860b57cec5SDimitry Andric     }
8870b57cec5SDimitry Andric   } else {
888480093f4SDimitry Andric     Hint0 = Register();
8890b57cec5SDimitry Andric   }
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   // Try other hint.
892480093f4SDimitry Andric   Register Hint1 = traceCopies(VirtReg);
893e8d8bef9SDimitry Andric   if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
894e8d8bef9SDimitry Andric       !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
895e8d8bef9SDimitry Andric     // Take hint if the register is currently free.
896e8d8bef9SDimitry Andric     if (isPhysRegFree(Hint1)) {
8970b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
8980b57cec5SDimitry Andric                         << '\n');
899e8d8bef9SDimitry Andric       assignVirtToPhysReg(MI, LR, Hint1);
9000b57cec5SDimitry Andric       return;
9010b57cec5SDimitry Andric     } else {
902e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
9030b57cec5SDimitry Andric                         << " occupied\n");
9040b57cec5SDimitry Andric     }
9050b57cec5SDimitry Andric   } else {
906480093f4SDimitry Andric     Hint1 = Register();
9070b57cec5SDimitry Andric   }
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric   MCPhysReg BestReg = 0;
9100b57cec5SDimitry Andric   unsigned BestCost = spillImpossible;
9110b57cec5SDimitry Andric   ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
9120b57cec5SDimitry Andric   for (MCPhysReg PhysReg : AllocationOrder) {
9130b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
914e8d8bef9SDimitry Andric     if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
915e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "already used in instr.\n");
916e8d8bef9SDimitry Andric       continue;
917e8d8bef9SDimitry Andric     }
918e8d8bef9SDimitry Andric 
9190b57cec5SDimitry Andric     unsigned Cost = calcSpillCost(PhysReg);
9200b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
9210b57cec5SDimitry Andric     // Immediate take a register with cost 0.
9220b57cec5SDimitry Andric     if (Cost == 0) {
923e8d8bef9SDimitry Andric       assignVirtToPhysReg(MI, LR, PhysReg);
9240b57cec5SDimitry Andric       return;
9250b57cec5SDimitry Andric     }
9260b57cec5SDimitry Andric 
927e8d8bef9SDimitry Andric     if (PhysReg == Hint0 || PhysReg == Hint1)
9280b57cec5SDimitry Andric       Cost -= spillPrefBonus;
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric     if (Cost < BestCost) {
9310b57cec5SDimitry Andric       BestReg = PhysReg;
9320b57cec5SDimitry Andric       BestCost = Cost;
9330b57cec5SDimitry Andric     }
9340b57cec5SDimitry Andric   }
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   if (!BestReg) {
9370b57cec5SDimitry Andric     // Nothing we can do: Report an error and keep going with an invalid
9380b57cec5SDimitry Andric     // allocation.
9390b57cec5SDimitry Andric     if (MI.isInlineAsm())
9400b57cec5SDimitry Andric       MI.emitError("inline assembly requires more registers than available");
9410b57cec5SDimitry Andric     else
9420b57cec5SDimitry Andric       MI.emitError("ran out of registers during register allocation");
943e8d8bef9SDimitry Andric 
944e8d8bef9SDimitry Andric     LR.Error = true;
945e8d8bef9SDimitry Andric     LR.PhysReg = 0;
9460b57cec5SDimitry Andric     return;
9470b57cec5SDimitry Andric   }
9480b57cec5SDimitry Andric 
949e8d8bef9SDimitry Andric   displacePhysReg(MI, BestReg);
950e8d8bef9SDimitry Andric   assignVirtToPhysReg(MI, LR, BestReg);
9510b57cec5SDimitry Andric }
9520b57cec5SDimitry Andric 
allocVirtRegUndef(MachineOperand & MO)9530b57cec5SDimitry Andric void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
9540b57cec5SDimitry Andric   assert(MO.isUndef() && "expected undef use");
9558bcb0991SDimitry Andric   Register VirtReg = MO.getReg();
956bdd1243dSDimitry Andric   assert(VirtReg.isVirtual() && "Expected virtreg");
957bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
958bdd1243dSDimitry Andric     return;
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
9610b57cec5SDimitry Andric   MCPhysReg PhysReg;
9620b57cec5SDimitry Andric   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
9630b57cec5SDimitry Andric     PhysReg = LRI->PhysReg;
9640b57cec5SDimitry Andric   } else {
9650b57cec5SDimitry Andric     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
9660b57cec5SDimitry Andric     ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
9670b57cec5SDimitry Andric     assert(!AllocationOrder.empty() && "Allocation order must not be empty");
9680b57cec5SDimitry Andric     PhysReg = AllocationOrder[0];
9690b57cec5SDimitry Andric   }
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric   unsigned SubRegIdx = MO.getSubReg();
9720b57cec5SDimitry Andric   if (SubRegIdx != 0) {
9730b57cec5SDimitry Andric     PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
9740b57cec5SDimitry Andric     MO.setSubReg(0);
9750b57cec5SDimitry Andric   }
9760b57cec5SDimitry Andric   MO.setReg(PhysReg);
9770b57cec5SDimitry Andric   MO.setIsRenamable(true);
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric 
980e8d8bef9SDimitry Andric /// Variation of defineVirtReg() with special handling for livethrough regs
981e8d8bef9SDimitry Andric /// (tied or earlyclobber) that may interfere with preassigned uses.
982fe013be4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
defineLiveThroughVirtReg(MachineInstr & MI,unsigned OpNum,Register VirtReg)983fe013be4SDimitry Andric bool RegAllocFast::defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
984e8d8bef9SDimitry Andric                                             Register VirtReg) {
985bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
986fe013be4SDimitry Andric     return false;
987e8d8bef9SDimitry Andric   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
988e8d8bef9SDimitry Andric   if (LRI != LiveVirtRegs.end()) {
989e8d8bef9SDimitry Andric     MCPhysReg PrevReg = LRI->PhysReg;
990e8d8bef9SDimitry Andric     if (PrevReg != 0 && isRegUsedInInstr(PrevReg, true)) {
991e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
992e8d8bef9SDimitry Andric                         << " (tied/earlyclobber resolution)\n");
993e8d8bef9SDimitry Andric       freePhysReg(PrevReg);
994e8d8bef9SDimitry Andric       LRI->PhysReg = 0;
995e8d8bef9SDimitry Andric       allocVirtReg(MI, *LRI, 0, true);
996e8d8bef9SDimitry Andric       MachineBasicBlock::iterator InsertBefore =
997e8d8bef9SDimitry Andric           std::next((MachineBasicBlock::iterator)MI.getIterator());
998e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
999e8d8bef9SDimitry Andric                         << printReg(PrevReg, TRI) << '\n');
1000e8d8bef9SDimitry Andric       BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1001e8d8bef9SDimitry Andric               TII->get(TargetOpcode::COPY), PrevReg)
1002e8d8bef9SDimitry Andric           .addReg(LRI->PhysReg, llvm::RegState::Kill);
10030b57cec5SDimitry Andric     }
1004e8d8bef9SDimitry Andric     MachineOperand &MO = MI.getOperand(OpNum);
1005e8d8bef9SDimitry Andric     if (MO.getSubReg() && !MO.isUndef()) {
10060b57cec5SDimitry Andric       LRI->LastUse = &MI;
1007e8d8bef9SDimitry Andric     }
1008e8d8bef9SDimitry Andric   }
1009e8d8bef9SDimitry Andric   return defineVirtReg(MI, OpNum, VirtReg, true);
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric 
1012e8d8bef9SDimitry Andric /// Allocates a register for VirtReg definition. Typically the register is
1013e8d8bef9SDimitry Andric /// already assigned from a use of the virtreg, however we still need to
1014e8d8bef9SDimitry Andric /// perform an allocation if:
1015e8d8bef9SDimitry Andric /// - It is a dead definition without any uses.
1016e8d8bef9SDimitry Andric /// - The value is live out and all uses are in different basic blocks.
1017fe013be4SDimitry Andric ///
1018fe013be4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
defineVirtReg(MachineInstr & MI,unsigned OpNum,Register VirtReg,bool LookAtPhysRegUses)1019fe013be4SDimitry Andric bool RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1020e8d8bef9SDimitry Andric                                  Register VirtReg, bool LookAtPhysRegUses) {
1021e8d8bef9SDimitry Andric   assert(VirtReg.isVirtual() && "Not a virtual register");
1022bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
1023fe013be4SDimitry Andric     return false;
1024e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpNum);
10250b57cec5SDimitry Andric   LiveRegMap::iterator LRI;
10260b57cec5SDimitry Andric   bool New;
10270b57cec5SDimitry Andric   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1028e8d8bef9SDimitry Andric   if (New) {
1029e8d8bef9SDimitry Andric     if (!MO.isDead()) {
1030e8d8bef9SDimitry Andric       if (mayLiveOut(VirtReg)) {
1031e8d8bef9SDimitry Andric         LRI->LiveOut = true;
1032e8d8bef9SDimitry Andric       } else {
1033e8d8bef9SDimitry Andric         // It is a dead def without the dead flag; add the flag now.
1034e8d8bef9SDimitry Andric         MO.setIsDead(true);
1035e8d8bef9SDimitry Andric       }
1036e8d8bef9SDimitry Andric     }
1037e8d8bef9SDimitry Andric   }
1038c9157d92SDimitry Andric   if (LRI->PhysReg == 0) {
1039e8d8bef9SDimitry Andric     allocVirtReg(MI, *LRI, 0, LookAtPhysRegUses);
1040c9157d92SDimitry Andric     // If no physical register is available for LRI, we assign one at random
1041c9157d92SDimitry Andric     // and bail out of this function immediately.
1042c9157d92SDimitry Andric     if (LRI->Error) {
1043c9157d92SDimitry Andric       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1044c9157d92SDimitry Andric       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1045c9157d92SDimitry Andric       if (AllocationOrder.empty())
1046c9157d92SDimitry Andric         return setPhysReg(MI, MO, MCRegister::NoRegister);
1047c9157d92SDimitry Andric       return setPhysReg(MI, MO, *AllocationOrder.begin());
1048c9157d92SDimitry Andric     }
1049c9157d92SDimitry Andric   } else {
1050e8d8bef9SDimitry Andric     assert(!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) &&
1051e8d8bef9SDimitry Andric            "TODO: preassign mismatch");
1052e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1053e8d8bef9SDimitry Andric                       << " use existing assignment to "
1054e8d8bef9SDimitry Andric                       << printReg(LRI->PhysReg, TRI) << '\n');
1055e8d8bef9SDimitry Andric   }
1056e8d8bef9SDimitry Andric 
1057e8d8bef9SDimitry Andric   MCPhysReg PhysReg = LRI->PhysReg;
1058e8d8bef9SDimitry Andric   if (LRI->Reloaded || LRI->LiveOut) {
1059e8d8bef9SDimitry Andric     if (!MI.isImplicitDef()) {
1060e8d8bef9SDimitry Andric       MachineBasicBlock::iterator SpillBefore =
1061e8d8bef9SDimitry Andric           std::next((MachineBasicBlock::iterator)MI.getIterator());
1062c9157d92SDimitry Andric       LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1063c9157d92SDimitry Andric                         << " RL: " << LRI->Reloaded << '\n');
1064e8d8bef9SDimitry Andric       bool Kill = LRI->LastUse == nullptr;
1065e8d8bef9SDimitry Andric       spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1066fe013be4SDimitry Andric 
1067fe013be4SDimitry Andric       // We need to place additional spills for each indirect destination of an
1068fe013be4SDimitry Andric       // INLINEASM_BR.
1069fe013be4SDimitry Andric       if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1070fe013be4SDimitry Andric         int FI = StackSlotForVirtReg[VirtReg];
1071fe013be4SDimitry Andric         const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1072fe013be4SDimitry Andric         for (MachineOperand &MO : MI.operands()) {
1073fe013be4SDimitry Andric           if (MO.isMBB()) {
1074fe013be4SDimitry Andric             MachineBasicBlock *Succ = MO.getMBB();
1075c9157d92SDimitry Andric             TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1076c9157d92SDimitry Andric                                      &RC, TRI, VirtReg);
1077fe013be4SDimitry Andric             ++NumStores;
1078fe013be4SDimitry Andric             Succ->addLiveIn(PhysReg);
1079fe013be4SDimitry Andric           }
1080fe013be4SDimitry Andric         }
1081fe013be4SDimitry Andric       }
1082fe013be4SDimitry Andric 
1083e8d8bef9SDimitry Andric       LRI->LastUse = nullptr;
1084e8d8bef9SDimitry Andric     }
1085e8d8bef9SDimitry Andric     LRI->LiveOut = false;
1086e8d8bef9SDimitry Andric     LRI->Reloaded = false;
1087e8d8bef9SDimitry Andric   }
1088e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1089e8d8bef9SDimitry Andric     BundleVirtRegsMap[VirtReg] = PhysReg;
1090e8d8bef9SDimitry Andric   }
1091e8d8bef9SDimitry Andric   markRegUsedInInstr(PhysReg);
1092fe013be4SDimitry Andric   return setPhysReg(MI, MO, PhysReg);
1093e8d8bef9SDimitry Andric }
1094e8d8bef9SDimitry Andric 
1095e8d8bef9SDimitry Andric /// Allocates a register for a VirtReg use.
1096fe013be4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
useVirtReg(MachineInstr & MI,MachineOperand & MO,Register VirtReg)1097c9157d92SDimitry Andric bool RegAllocFast::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1098e8d8bef9SDimitry Andric                               Register VirtReg) {
1099e8d8bef9SDimitry Andric   assert(VirtReg.isVirtual() && "Not a virtual register");
1100bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
1101fe013be4SDimitry Andric     return false;
1102e8d8bef9SDimitry Andric   LiveRegMap::iterator LRI;
1103e8d8bef9SDimitry Andric   bool New;
1104e8d8bef9SDimitry Andric   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1105e8d8bef9SDimitry Andric   if (New) {
1106e8d8bef9SDimitry Andric     if (!MO.isKill()) {
1107e8d8bef9SDimitry Andric       if (mayLiveOut(VirtReg)) {
1108e8d8bef9SDimitry Andric         LRI->LiveOut = true;
1109e8d8bef9SDimitry Andric       } else {
1110e8d8bef9SDimitry Andric         // It is a last (killing) use without the kill flag; add the flag now.
1111e8d8bef9SDimitry Andric         MO.setIsKill(true);
11120b57cec5SDimitry Andric       }
11130b57cec5SDimitry Andric     }
1114e8d8bef9SDimitry Andric   } else {
1115e8d8bef9SDimitry Andric     assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1116e8d8bef9SDimitry Andric   }
1117e8d8bef9SDimitry Andric 
1118e8d8bef9SDimitry Andric   // If necessary allocate a register.
1119e8d8bef9SDimitry Andric   if (LRI->PhysReg == 0) {
1120e8d8bef9SDimitry Andric     assert(!MO.isTied() && "tied op should be allocated");
1121e8d8bef9SDimitry Andric     Register Hint;
1122e8d8bef9SDimitry Andric     if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1123e8d8bef9SDimitry Andric       Hint = MI.getOperand(0).getReg();
1124bdd1243dSDimitry Andric       if (Hint.isVirtual()) {
1125bdd1243dSDimitry Andric         assert(!shouldAllocateRegister(Hint));
1126bdd1243dSDimitry Andric         Hint = Register();
1127bdd1243dSDimitry Andric       } else {
1128e8d8bef9SDimitry Andric         assert(Hint.isPhysical() &&
1129e8d8bef9SDimitry Andric                "Copy destination should already be assigned");
1130e8d8bef9SDimitry Andric       }
1131bdd1243dSDimitry Andric     }
1132e8d8bef9SDimitry Andric     allocVirtReg(MI, *LRI, Hint, false);
1133e8d8bef9SDimitry Andric     if (LRI->Error) {
1134e8d8bef9SDimitry Andric       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1135e8d8bef9SDimitry Andric       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1136c9157d92SDimitry Andric       if (AllocationOrder.empty())
1137c9157d92SDimitry Andric         return setPhysReg(MI, MO, MCRegister::NoRegister);
1138fe013be4SDimitry Andric       return setPhysReg(MI, MO, *AllocationOrder.begin());
1139e8d8bef9SDimitry Andric     }
1140e8d8bef9SDimitry Andric   }
1141e8d8bef9SDimitry Andric 
11420b57cec5SDimitry Andric   LRI->LastUse = &MI;
1143e8d8bef9SDimitry Andric 
1144e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1145e8d8bef9SDimitry Andric     BundleVirtRegsMap[VirtReg] = LRI->PhysReg;
1146e8d8bef9SDimitry Andric   }
11470b57cec5SDimitry Andric   markRegUsedInInstr(LRI->PhysReg);
1148fe013be4SDimitry Andric   return setPhysReg(MI, MO, LRI->PhysReg);
11490b57cec5SDimitry Andric }
11500b57cec5SDimitry Andric 
1151fe013be4SDimitry Andric /// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
1152fe013be4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
setPhysReg(MachineInstr & MI,MachineOperand & MO,MCPhysReg PhysReg)1153fe013be4SDimitry Andric bool RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
11540b57cec5SDimitry Andric                               MCPhysReg PhysReg) {
11550b57cec5SDimitry Andric   if (!MO.getSubReg()) {
11560b57cec5SDimitry Andric     MO.setReg(PhysReg);
11570b57cec5SDimitry Andric     MO.setIsRenamable(true);
1158fe013be4SDimitry Andric     return false;
11590b57cec5SDimitry Andric   }
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   // Handle subregister index.
1162e8d8bef9SDimitry Andric   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : MCRegister());
11630b57cec5SDimitry Andric   MO.setIsRenamable(true);
1164e8d8bef9SDimitry Andric   // Note: We leave the subreg number around a little longer in case of defs.
1165e8d8bef9SDimitry Andric   // This is so that the register freeing logic in allocateInstruction can still
1166e8d8bef9SDimitry Andric   // recognize this as subregister defs. The code there will clear the number.
1167e8d8bef9SDimitry Andric   if (!MO.isDef())
11680b57cec5SDimitry Andric     MO.setSubReg(0);
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   // A kill flag implies killing the full register. Add corresponding super
11710b57cec5SDimitry Andric   // register kill.
11720b57cec5SDimitry Andric   if (MO.isKill()) {
11730b57cec5SDimitry Andric     MI.addRegisterKilled(PhysReg, TRI, true);
1174fe013be4SDimitry Andric     // Conservatively assume implicit MOs were re-arranged
1175fe013be4SDimitry Andric     return true;
11760b57cec5SDimitry Andric   }
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   // A <def,read-undef> of a sub-register requires an implicit def of the full
11790b57cec5SDimitry Andric   // register.
1180e8d8bef9SDimitry Andric   if (MO.isDef() && MO.isUndef()) {
1181e8d8bef9SDimitry Andric     if (MO.isDead())
1182e8d8bef9SDimitry Andric       MI.addRegisterDead(PhysReg, TRI, true);
1183e8d8bef9SDimitry Andric     else
11840b57cec5SDimitry Andric       MI.addRegisterDefined(PhysReg, TRI);
1185fe013be4SDimitry Andric     // Conservatively assume implicit MOs were re-arranged
1186fe013be4SDimitry Andric     return true;
11870b57cec5SDimitry Andric   }
1188fe013be4SDimitry Andric   return false;
11890b57cec5SDimitry Andric }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric #ifndef NDEBUG
1192e8d8bef9SDimitry Andric 
dumpState() const1193e8d8bef9SDimitry Andric void RegAllocFast::dumpState() const {
1194e8d8bef9SDimitry Andric   for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
1195e8d8bef9SDimitry Andric        ++Unit) {
1196e8d8bef9SDimitry Andric     switch (unsigned VirtReg = RegUnitStates[Unit]) {
11970b57cec5SDimitry Andric     case regFree:
11980b57cec5SDimitry Andric       break;
1199e8d8bef9SDimitry Andric     case regPreAssigned:
1200e8d8bef9SDimitry Andric       dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
12010b57cec5SDimitry Andric       break;
1202e8d8bef9SDimitry Andric     case regLiveIn:
1203e8d8bef9SDimitry Andric       llvm_unreachable("Should not have regLiveIn in map");
12040b57cec5SDimitry Andric     default: {
1205e8d8bef9SDimitry Andric       dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1206e8d8bef9SDimitry Andric       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1207e8d8bef9SDimitry Andric       assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1208e8d8bef9SDimitry Andric       if (I->LiveOut || I->Reloaded) {
1209e8d8bef9SDimitry Andric         dbgs() << '[';
1210c9157d92SDimitry Andric         if (I->LiveOut)
1211c9157d92SDimitry Andric           dbgs() << 'O';
1212c9157d92SDimitry Andric         if (I->Reloaded)
1213c9157d92SDimitry Andric           dbgs() << 'R';
1214e8d8bef9SDimitry Andric         dbgs() << ']';
1215e8d8bef9SDimitry Andric       }
1216e8d8bef9SDimitry Andric       assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
12170b57cec5SDimitry Andric       break;
12180b57cec5SDimitry Andric     }
12190b57cec5SDimitry Andric     }
12200b57cec5SDimitry Andric   }
12210b57cec5SDimitry Andric   dbgs() << '\n';
12220b57cec5SDimitry Andric   // Check that LiveVirtRegs is the inverse.
1223e8d8bef9SDimitry Andric   for (const LiveReg &LR : LiveVirtRegs) {
1224e8d8bef9SDimitry Andric     Register VirtReg = LR.VirtReg;
1225e8d8bef9SDimitry Andric     assert(VirtReg.isVirtual() && "Bad map key");
1226e8d8bef9SDimitry Andric     MCPhysReg PhysReg = LR.PhysReg;
1227e8d8bef9SDimitry Andric     if (PhysReg != 0) {
1228c9157d92SDimitry Andric       assert(Register::isPhysicalRegister(PhysReg) && "mapped to physreg");
1229fe013be4SDimitry Andric       for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1230fe013be4SDimitry Andric         assert(RegUnitStates[Unit] == VirtReg && "inverse map valid");
1231e8d8bef9SDimitry Andric       }
1232e8d8bef9SDimitry Andric     }
12330b57cec5SDimitry Andric   }
12340b57cec5SDimitry Andric }
12350b57cec5SDimitry Andric #endif
12360b57cec5SDimitry Andric 
1237e8d8bef9SDimitry Andric /// Count number of defs consumed from each register class by \p Reg
addRegClassDefCounts(std::vector<unsigned> & RegClassDefCounts,Register Reg) const1238c9157d92SDimitry Andric void RegAllocFast::addRegClassDefCounts(
1239c9157d92SDimitry Andric     std::vector<unsigned> &RegClassDefCounts, Register Reg) const {
1240e8d8bef9SDimitry Andric   assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1241e8d8bef9SDimitry Andric 
1242e8d8bef9SDimitry Andric   if (Reg.isVirtual()) {
1243bdd1243dSDimitry Andric     if (!shouldAllocateRegister(Reg))
1244bdd1243dSDimitry Andric       return;
1245e8d8bef9SDimitry Andric     const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1246e8d8bef9SDimitry Andric     for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1247e8d8bef9SDimitry Andric          RCIdx != RCIdxEnd; ++RCIdx) {
1248e8d8bef9SDimitry Andric       const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1249e8d8bef9SDimitry Andric       // FIXME: Consider aliasing sub/super registers.
1250e8d8bef9SDimitry Andric       if (OpRC->hasSubClassEq(IdxRC))
1251e8d8bef9SDimitry Andric         ++RegClassDefCounts[RCIdx];
1252e8d8bef9SDimitry Andric     }
1253e8d8bef9SDimitry Andric 
1254e8d8bef9SDimitry Andric     return;
1255e8d8bef9SDimitry Andric   }
1256e8d8bef9SDimitry Andric 
1257e8d8bef9SDimitry Andric   for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1258e8d8bef9SDimitry Andric        RCIdx != RCIdxEnd; ++RCIdx) {
1259e8d8bef9SDimitry Andric     const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1260e8d8bef9SDimitry Andric     for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1261e8d8bef9SDimitry Andric       if (IdxRC->contains(*Alias)) {
1262e8d8bef9SDimitry Andric         ++RegClassDefCounts[RCIdx];
1263e8d8bef9SDimitry Andric         break;
1264e8d8bef9SDimitry Andric       }
1265e8d8bef9SDimitry Andric     }
1266e8d8bef9SDimitry Andric   }
1267e8d8bef9SDimitry Andric }
1268e8d8bef9SDimitry Andric 
1269fe013be4SDimitry Andric /// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1270fe013be4SDimitry Andric /// that are to be allocated. Those are ordered in a way that small classes,
1271fe013be4SDimitry Andric /// early clobbers and livethroughs are allocated first.
findAndSortDefOperandIndexes(const MachineInstr & MI)1272fe013be4SDimitry Andric void RegAllocFast::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1273fe013be4SDimitry Andric   DefOperandIndexes.clear();
1274fe013be4SDimitry Andric 
1275fe013be4SDimitry Andric   // Track number of defs which may consume a register from the class.
1276fe013be4SDimitry Andric   std::vector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1277fe013be4SDimitry Andric   assert(RegClassDefCounts[0] == 0);
1278fe013be4SDimitry Andric 
1279fe013be4SDimitry Andric   LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1280fe013be4SDimitry Andric   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1281fe013be4SDimitry Andric     const MachineOperand &MO = MI.getOperand(I);
1282fe013be4SDimitry Andric     if (!MO.isReg())
1283fe013be4SDimitry Andric       continue;
1284fe013be4SDimitry Andric     Register Reg = MO.getReg();
1285fe013be4SDimitry Andric     if (MO.readsReg()) {
1286fe013be4SDimitry Andric       if (Reg.isPhysical()) {
1287fe013be4SDimitry Andric         LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1288fe013be4SDimitry Andric         markPhysRegUsedInInstr(Reg);
1289fe013be4SDimitry Andric       }
1290fe013be4SDimitry Andric     }
1291fe013be4SDimitry Andric 
1292fe013be4SDimitry Andric     if (MO.isDef()) {
1293fe013be4SDimitry Andric       if (Reg.isVirtual() && shouldAllocateRegister(Reg))
1294fe013be4SDimitry Andric         DefOperandIndexes.push_back(I);
1295fe013be4SDimitry Andric 
1296fe013be4SDimitry Andric       addRegClassDefCounts(RegClassDefCounts, Reg);
1297fe013be4SDimitry Andric     }
1298fe013be4SDimitry Andric   }
1299fe013be4SDimitry Andric 
1300fe013be4SDimitry Andric   llvm::sort(DefOperandIndexes, [&](uint16_t I0, uint16_t I1) {
1301fe013be4SDimitry Andric     const MachineOperand &MO0 = MI.getOperand(I0);
1302fe013be4SDimitry Andric     const MachineOperand &MO1 = MI.getOperand(I1);
1303fe013be4SDimitry Andric     Register Reg0 = MO0.getReg();
1304fe013be4SDimitry Andric     Register Reg1 = MO1.getReg();
1305fe013be4SDimitry Andric     const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1306fe013be4SDimitry Andric     const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1307fe013be4SDimitry Andric 
1308fe013be4SDimitry Andric     // Identify regclass that are easy to use up completely just in this
1309fe013be4SDimitry Andric     // instruction.
1310fe013be4SDimitry Andric     unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
1311fe013be4SDimitry Andric     unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
1312fe013be4SDimitry Andric 
1313fe013be4SDimitry Andric     bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1314fe013be4SDimitry Andric     bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1315fe013be4SDimitry Andric     if (SmallClass0 > SmallClass1)
1316fe013be4SDimitry Andric       return true;
1317fe013be4SDimitry Andric     if (SmallClass0 < SmallClass1)
1318fe013be4SDimitry Andric       return false;
1319fe013be4SDimitry Andric 
1320fe013be4SDimitry Andric     // Allocate early clobbers and livethrough operands first.
1321fe013be4SDimitry Andric     bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
1322fe013be4SDimitry Andric                         (MO0.getSubReg() == 0 && !MO0.isUndef());
1323fe013be4SDimitry Andric     bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
1324fe013be4SDimitry Andric                         (MO1.getSubReg() == 0 && !MO1.isUndef());
1325fe013be4SDimitry Andric     if (Livethrough0 > Livethrough1)
1326fe013be4SDimitry Andric       return true;
1327fe013be4SDimitry Andric     if (Livethrough0 < Livethrough1)
1328fe013be4SDimitry Andric       return false;
1329fe013be4SDimitry Andric 
1330fe013be4SDimitry Andric     // Tie-break rule: operand index.
1331fe013be4SDimitry Andric     return I0 < I1;
1332fe013be4SDimitry Andric   });
1333fe013be4SDimitry Andric }
1334fe013be4SDimitry Andric 
1335c9157d92SDimitry Andric // Returns true if MO is tied and the operand it's tied to is not Undef (not
1336c9157d92SDimitry Andric // Undef is not the same thing as Def).
isTiedToNotUndef(const MachineOperand & MO)1337c9157d92SDimitry Andric static bool isTiedToNotUndef(const MachineOperand &MO) {
1338c9157d92SDimitry Andric   if (!MO.isTied())
1339c9157d92SDimitry Andric     return false;
1340c9157d92SDimitry Andric   const MachineInstr &MI = *MO.getParent();
1341c9157d92SDimitry Andric   unsigned TiedIdx = MI.findTiedOperandIdx(MI.getOperandNo(&MO));
1342c9157d92SDimitry Andric   const MachineOperand &TiedMO = MI.getOperand(TiedIdx);
1343c9157d92SDimitry Andric   return !TiedMO.isUndef();
1344c9157d92SDimitry Andric }
1345c9157d92SDimitry Andric 
allocateInstruction(MachineInstr & MI)13460b57cec5SDimitry Andric void RegAllocFast::allocateInstruction(MachineInstr &MI) {
1347e8d8bef9SDimitry Andric   // The basic algorithm here is:
1348e8d8bef9SDimitry Andric   // 1. Mark registers of def operands as free
1349e8d8bef9SDimitry Andric   // 2. Allocate registers to use operands and place reload instructions for
1350e8d8bef9SDimitry Andric   //    registers displaced by the allocation.
1351e8d8bef9SDimitry Andric   //
1352e8d8bef9SDimitry Andric   // However we need to handle some corner cases:
1353e8d8bef9SDimitry Andric   // - pre-assigned defs and uses need to be handled before the other def/use
1354e8d8bef9SDimitry Andric   //   operands are processed to avoid the allocation heuristics clashing with
1355e8d8bef9SDimitry Andric   //   the pre-assignment.
1356e8d8bef9SDimitry Andric   // - The "free def operands" step has to come last instead of first for tied
1357e8d8bef9SDimitry Andric   //   operands and early-clobbers.
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric   UsedInInstr.clear();
1360fe6060f1SDimitry Andric   RegMasks.clear();
1361e8d8bef9SDimitry Andric   BundleVirtRegsMap.clear();
13620b57cec5SDimitry Andric 
1363e8d8bef9SDimitry Andric   // Scan for special cases; Apply pre-assigned register defs to state.
1364e8d8bef9SDimitry Andric   bool HasPhysRegUse = false;
1365e8d8bef9SDimitry Andric   bool HasRegMask = false;
1366e8d8bef9SDimitry Andric   bool HasVRegDef = false;
1367e8d8bef9SDimitry Andric   bool HasDef = false;
1368e8d8bef9SDimitry Andric   bool HasEarlyClobber = false;
1369e8d8bef9SDimitry Andric   bool NeedToAssignLiveThroughs = false;
1370c9157d92SDimitry Andric   for (MachineOperand &MO : MI.operands()) {
1371e8d8bef9SDimitry Andric     if (MO.isReg()) {
13728bcb0991SDimitry Andric       Register Reg = MO.getReg();
1373e8d8bef9SDimitry Andric       if (Reg.isVirtual()) {
1374bdd1243dSDimitry Andric         if (!shouldAllocateRegister(Reg))
1375bdd1243dSDimitry Andric           continue;
1376e8d8bef9SDimitry Andric         if (MO.isDef()) {
1377e8d8bef9SDimitry Andric           HasDef = true;
1378e8d8bef9SDimitry Andric           HasVRegDef = true;
1379e8d8bef9SDimitry Andric           if (MO.isEarlyClobber()) {
1380e8d8bef9SDimitry Andric             HasEarlyClobber = true;
1381e8d8bef9SDimitry Andric             NeedToAssignLiveThroughs = true;
13820b57cec5SDimitry Andric           }
1383c9157d92SDimitry Andric           if (isTiedToNotUndef(MO) || (MO.getSubReg() != 0 && !MO.isUndef()))
1384e8d8bef9SDimitry Andric             NeedToAssignLiveThroughs = true;
1385e8d8bef9SDimitry Andric         }
1386e8d8bef9SDimitry Andric       } else if (Reg.isPhysical()) {
1387e8d8bef9SDimitry Andric         if (!MRI->isReserved(Reg)) {
1388e8d8bef9SDimitry Andric           if (MO.isDef()) {
1389e8d8bef9SDimitry Andric             HasDef = true;
1390e8d8bef9SDimitry Andric             bool displacedAny = definePhysReg(MI, Reg);
1391e8d8bef9SDimitry Andric             if (MO.isEarlyClobber())
1392e8d8bef9SDimitry Andric               HasEarlyClobber = true;
1393e8d8bef9SDimitry Andric             if (!displacedAny)
1394e8d8bef9SDimitry Andric               MO.setIsDead(true);
1395e8d8bef9SDimitry Andric           }
1396e8d8bef9SDimitry Andric           if (MO.readsReg())
1397e8d8bef9SDimitry Andric             HasPhysRegUse = true;
1398e8d8bef9SDimitry Andric         }
1399e8d8bef9SDimitry Andric       }
1400e8d8bef9SDimitry Andric     } else if (MO.isRegMask()) {
1401e8d8bef9SDimitry Andric       HasRegMask = true;
1402fe6060f1SDimitry Andric       RegMasks.push_back(MO.getRegMask());
1403e8d8bef9SDimitry Andric     }
1404e8d8bef9SDimitry Andric   }
1405e8d8bef9SDimitry Andric 
1406e8d8bef9SDimitry Andric   // Allocate virtreg defs.
1407e8d8bef9SDimitry Andric   if (HasDef) {
1408e8d8bef9SDimitry Andric     if (HasVRegDef) {
1409fe013be4SDimitry Andric       // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
1410fe013be4SDimitry Andric       // multiple times to ensure no operand is missed.
1411fe013be4SDimitry Andric       bool ReArrangedImplicitOps = true;
1412fe013be4SDimitry Andric 
1413e8d8bef9SDimitry Andric       // Special handling for early clobbers, tied operands or subregister defs:
1414e8d8bef9SDimitry Andric       // Compared to "normal" defs these:
1415e8d8bef9SDimitry Andric       // - Must not use a register that is pre-assigned for a use operand.
1416e8d8bef9SDimitry Andric       // - In order to solve tricky inline assembly constraints we change the
1417e8d8bef9SDimitry Andric       //   heuristic to figure out a good operand order before doing
1418e8d8bef9SDimitry Andric       //   assignments.
1419e8d8bef9SDimitry Andric       if (NeedToAssignLiveThroughs) {
1420e8d8bef9SDimitry Andric         PhysRegUses.clear();
1421e8d8bef9SDimitry Andric 
1422fe013be4SDimitry Andric         while (ReArrangedImplicitOps) {
1423fe013be4SDimitry Andric           ReArrangedImplicitOps = false;
1424fe013be4SDimitry Andric           findAndSortDefOperandIndexes(MI);
1425e8d8bef9SDimitry Andric           for (uint16_t OpIdx : DefOperandIndexes) {
1426e8d8bef9SDimitry Andric             MachineOperand &MO = MI.getOperand(OpIdx);
1427e8d8bef9SDimitry Andric             LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1428c9157d92SDimitry Andric             Register Reg = MO.getReg();
1429c9157d92SDimitry Andric             if (MO.isEarlyClobber() || isTiedToNotUndef(MO) ||
1430e8d8bef9SDimitry Andric                 (MO.getSubReg() && !MO.isUndef())) {
1431fe013be4SDimitry Andric               ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1432e8d8bef9SDimitry Andric             } else {
1433fe013be4SDimitry Andric               ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
1434fe013be4SDimitry Andric             }
1435fe013be4SDimitry Andric             // Implicit operands of MI were re-arranged,
1436fe013be4SDimitry Andric             // re-compute DefOperandIndexes.
1437c9157d92SDimitry Andric             if (ReArrangedImplicitOps)
1438fe013be4SDimitry Andric               break;
1439fe013be4SDimitry Andric           }
1440e8d8bef9SDimitry Andric         }
1441e8d8bef9SDimitry Andric       } else {
1442e8d8bef9SDimitry Andric         // Assign virtual register defs.
1443fe013be4SDimitry Andric         while (ReArrangedImplicitOps) {
1444fe013be4SDimitry Andric           ReArrangedImplicitOps = false;
1445c9157d92SDimitry Andric           for (MachineOperand &MO : MI.operands()) {
1446e8d8bef9SDimitry Andric             if (!MO.isReg() || !MO.isDef())
1447e8d8bef9SDimitry Andric               continue;
1448e8d8bef9SDimitry Andric             Register Reg = MO.getReg();
1449fe013be4SDimitry Andric             if (Reg.isVirtual()) {
1450c9157d92SDimitry Andric               ReArrangedImplicitOps =
1451c9157d92SDimitry Andric                   defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
1452c9157d92SDimitry Andric               if (ReArrangedImplicitOps)
1453fe013be4SDimitry Andric                 break;
1454fe013be4SDimitry Andric             }
1455fe013be4SDimitry Andric           }
1456fe013be4SDimitry Andric         }
1457e8d8bef9SDimitry Andric       }
1458e8d8bef9SDimitry Andric     }
1459e8d8bef9SDimitry Andric 
1460e8d8bef9SDimitry Andric     // Free registers occupied by defs.
1461e8d8bef9SDimitry Andric     // Iterate operands in reverse order, so we see the implicit super register
1462e8d8bef9SDimitry Andric     // defs first (we added them earlier in case of <def,read-undef>).
1463c9157d92SDimitry Andric     for (MachineOperand &MO : reverse(MI.operands())) {
1464e8d8bef9SDimitry Andric       if (!MO.isReg() || !MO.isDef())
1465e8d8bef9SDimitry Andric         continue;
1466e8d8bef9SDimitry Andric 
1467fe013be4SDimitry Andric       Register Reg = MO.getReg();
1468fe013be4SDimitry Andric 
1469e8d8bef9SDimitry Andric       // subreg defs don't free the full register. We left the subreg number
1470e8d8bef9SDimitry Andric       // around as a marker in setPhysReg() to recognize this case here.
1471fe013be4SDimitry Andric       if (Reg.isPhysical() && MO.getSubReg() != 0) {
1472e8d8bef9SDimitry Andric         MO.setSubReg(0);
14730b57cec5SDimitry Andric         continue;
14740b57cec5SDimitry Andric       }
1475e8d8bef9SDimitry Andric 
1476fe6060f1SDimitry Andric       assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1477fe6060f1SDimitry Andric              "tied def assigned to clobbered register");
1478fe6060f1SDimitry Andric 
1479e8d8bef9SDimitry Andric       // Do not free tied operands and early clobbers.
1480c9157d92SDimitry Andric       if (isTiedToNotUndef(MO) || MO.isEarlyClobber())
1481e8d8bef9SDimitry Andric         continue;
1482e8d8bef9SDimitry Andric       if (!Reg)
1483e8d8bef9SDimitry Andric         continue;
1484bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
1485bdd1243dSDimitry Andric         assert(!shouldAllocateRegister(Reg));
1486bdd1243dSDimitry Andric         continue;
1487bdd1243dSDimitry Andric       }
1488e8d8bef9SDimitry Andric       assert(Reg.isPhysical());
1489e8d8bef9SDimitry Andric       if (MRI->isReserved(Reg))
1490e8d8bef9SDimitry Andric         continue;
1491e8d8bef9SDimitry Andric       freePhysReg(Reg);
1492e8d8bef9SDimitry Andric       unmarkRegUsedInInstr(Reg);
1493e8d8bef9SDimitry Andric     }
14940b57cec5SDimitry Andric   }
14950b57cec5SDimitry Andric 
1496e8d8bef9SDimitry Andric   // Displace clobbered registers.
1497e8d8bef9SDimitry Andric   if (HasRegMask) {
1498fe6060f1SDimitry Andric     assert(!RegMasks.empty() && "expected RegMask");
1499e8d8bef9SDimitry Andric     // MRI bookkeeping.
1500fe6060f1SDimitry Andric     for (const auto *RM : RegMasks)
1501fe6060f1SDimitry Andric       MRI->addPhysRegsUsedFromRegMask(RM);
1502e8d8bef9SDimitry Andric 
1503e8d8bef9SDimitry Andric     // Displace clobbered registers.
1504fe6060f1SDimitry Andric     for (const LiveReg &LR : LiveVirtRegs) {
1505fe6060f1SDimitry Andric       MCPhysReg PhysReg = LR.PhysReg;
1506fe6060f1SDimitry Andric       if (PhysReg != 0 && isClobberedByRegMasks(PhysReg))
1507e8d8bef9SDimitry Andric         displacePhysReg(MI, PhysReg);
1508e8d8bef9SDimitry Andric     }
1509e8d8bef9SDimitry Andric   }
15100b57cec5SDimitry Andric 
1511e8d8bef9SDimitry Andric   // Apply pre-assigned register uses to state.
1512e8d8bef9SDimitry Andric   if (HasPhysRegUse) {
1513e8d8bef9SDimitry Andric     for (MachineOperand &MO : MI.operands()) {
1514e8d8bef9SDimitry Andric       if (!MO.isReg() || !MO.readsReg())
1515e8d8bef9SDimitry Andric         continue;
1516e8d8bef9SDimitry Andric       Register Reg = MO.getReg();
1517e8d8bef9SDimitry Andric       if (!Reg.isPhysical())
1518e8d8bef9SDimitry Andric         continue;
1519e8d8bef9SDimitry Andric       if (MRI->isReserved(Reg))
1520e8d8bef9SDimitry Andric         continue;
1521c9157d92SDimitry Andric       if (!usePhysReg(MI, Reg))
1522e8d8bef9SDimitry Andric         MO.setIsKill(true);
1523e8d8bef9SDimitry Andric     }
1524e8d8bef9SDimitry Andric   }
1525e8d8bef9SDimitry Andric 
1526e8d8bef9SDimitry Andric   // Allocate virtreg uses and insert reloads as necessary.
1527fe013be4SDimitry Andric   // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
1528fe013be4SDimitry Andric   // times to ensure no operand is missed.
15290b57cec5SDimitry Andric   bool HasUndefUse = false;
1530fe013be4SDimitry Andric   bool ReArrangedImplicitMOs = true;
1531fe013be4SDimitry Andric   while (ReArrangedImplicitMOs) {
1532fe013be4SDimitry Andric     ReArrangedImplicitMOs = false;
1533c9157d92SDimitry Andric     for (MachineOperand &MO : MI.operands()) {
1534e8d8bef9SDimitry Andric       if (!MO.isReg() || !MO.isUse())
1535e8d8bef9SDimitry Andric         continue;
15368bcb0991SDimitry Andric       Register Reg = MO.getReg();
1537bdd1243dSDimitry Andric       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
15388bcb0991SDimitry Andric         continue;
1539e8d8bef9SDimitry Andric 
15400b57cec5SDimitry Andric       if (MO.isUndef()) {
15410b57cec5SDimitry Andric         HasUndefUse = true;
15420b57cec5SDimitry Andric         continue;
15430b57cec5SDimitry Andric       }
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric       // Populate MayLiveAcrossBlocks in case the use block is allocated before
15460b57cec5SDimitry Andric       // the def block (removing the vreg uses).
15470b57cec5SDimitry Andric       mayLiveIn(Reg);
15480b57cec5SDimitry Andric 
1549e8d8bef9SDimitry Andric       assert(!MO.isInternalRead() && "Bundles not supported");
1550e8d8bef9SDimitry Andric       assert(MO.readsReg() && "reading use");
1551c9157d92SDimitry Andric       ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
1552fe013be4SDimitry Andric       if (ReArrangedImplicitMOs)
1553fe013be4SDimitry Andric         break;
1554fe013be4SDimitry Andric     }
15550b57cec5SDimitry Andric   }
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric   // Allocate undef operands. This is a separate step because in a situation
15580b57cec5SDimitry Andric   // like  ` = OP undef %X, %X`    both operands need the same register assign
15590b57cec5SDimitry Andric   // so we should perform the normal assignment first.
15600b57cec5SDimitry Andric   if (HasUndefUse) {
1561fe013be4SDimitry Andric     for (MachineOperand &MO : MI.all_uses()) {
15628bcb0991SDimitry Andric       Register Reg = MO.getReg();
1563bdd1243dSDimitry Andric       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
15640b57cec5SDimitry Andric         continue;
15650b57cec5SDimitry Andric 
15660b57cec5SDimitry Andric       assert(MO.isUndef() && "Should only have undef virtreg uses left");
15670b57cec5SDimitry Andric       allocVirtRegUndef(MO);
15680b57cec5SDimitry Andric     }
15690b57cec5SDimitry Andric   }
15700b57cec5SDimitry Andric 
1571e8d8bef9SDimitry Andric   // Free early clobbers.
1572e8d8bef9SDimitry Andric   if (HasEarlyClobber) {
1573c9157d92SDimitry Andric     for (MachineOperand &MO : reverse(MI.all_defs())) {
1574fe013be4SDimitry Andric       if (!MO.isEarlyClobber())
1575e8d8bef9SDimitry Andric         continue;
1576bdd1243dSDimitry Andric       assert(!MO.getSubReg() && "should be already handled in def processing");
1577e8d8bef9SDimitry Andric 
15788bcb0991SDimitry Andric       Register Reg = MO.getReg();
1579e8d8bef9SDimitry Andric       if (!Reg)
15808bcb0991SDimitry Andric         continue;
1581bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
1582bdd1243dSDimitry Andric         assert(!shouldAllocateRegister(Reg));
1583bdd1243dSDimitry Andric         continue;
1584bdd1243dSDimitry Andric       }
1585e8d8bef9SDimitry Andric       assert(Reg.isPhysical() && "should have register assigned");
1586e8d8bef9SDimitry Andric 
1587e8d8bef9SDimitry Andric       // We sometimes get odd situations like:
1588e8d8bef9SDimitry Andric       //    early-clobber %x0 = INSTRUCTION %x0
1589e8d8bef9SDimitry Andric       // which is semantically questionable as the early-clobber should
1590e8d8bef9SDimitry Andric       // apply before the use. But in practice we consider the use to
1591e8d8bef9SDimitry Andric       // happen before the early clobber now. Don't free the early clobber
1592e8d8bef9SDimitry Andric       // register in this case.
1593e8d8bef9SDimitry Andric       if (MI.readsRegister(Reg, TRI))
1594e8d8bef9SDimitry Andric         continue;
1595e8d8bef9SDimitry Andric 
1596e8d8bef9SDimitry Andric       freePhysReg(Reg);
15970b57cec5SDimitry Andric     }
15980b57cec5SDimitry Andric   }
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "<< " << MI);
1601e8d8bef9SDimitry Andric   if (MI.isCopy() && MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
1602e8d8bef9SDimitry Andric       MI.getNumOperands() == 2) {
16030b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
16040b57cec5SDimitry Andric     Coalesced.push_back(&MI);
16050b57cec5SDimitry Andric   }
16060b57cec5SDimitry Andric }
16070b57cec5SDimitry Andric 
handleDebugValue(MachineInstr & MI)16080b57cec5SDimitry Andric void RegAllocFast::handleDebugValue(MachineInstr &MI) {
16090b57cec5SDimitry Andric   // Ignore DBG_VALUEs that aren't based on virtual registers. These are
16100b57cec5SDimitry Andric   // mostly constants and frame indices.
1611c9157d92SDimitry Andric   assert(MI.isDebugValue() && "not a DBG_VALUE*");
1612c9157d92SDimitry Andric   for (const auto &MO : MI.debug_operands()) {
1613c9157d92SDimitry Andric     if (!MO.isReg())
1614c9157d92SDimitry Andric       continue;
1615c9157d92SDimitry Andric     Register Reg = MO.getReg();
1616bdd1243dSDimitry Andric     if (!Reg.isVirtual())
1617bdd1243dSDimitry Andric       continue;
1618bdd1243dSDimitry Andric     if (!shouldAllocateRegister(Reg))
1619fe6060f1SDimitry Andric       continue;
16200b57cec5SDimitry Andric 
1621e8d8bef9SDimitry Andric     // Already spilled to a stackslot?
1622e8d8bef9SDimitry Andric     int SS = StackSlotForVirtReg[Reg];
1623e8d8bef9SDimitry Andric     if (SS != -1) {
1624e8d8bef9SDimitry Andric       // Modify DBG_VALUE now that the value is in a spill slot.
1625fe6060f1SDimitry Andric       updateDbgValueForSpill(MI, SS, Reg);
1626e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1627fe6060f1SDimitry Andric       continue;
1628e8d8bef9SDimitry Andric     }
1629e8d8bef9SDimitry Andric 
16300b57cec5SDimitry Andric     // See if this virtual register has already been allocated to a physical
16310b57cec5SDimitry Andric     // register or spilled to a stack slot.
16320b57cec5SDimitry Andric     LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1633fe6060f1SDimitry Andric     SmallVector<MachineOperand *> DbgOps;
1634fe6060f1SDimitry Andric     for (MachineOperand &Op : MI.getDebugOperandsForReg(Reg))
1635fe6060f1SDimitry Andric       DbgOps.push_back(&Op);
1636fe6060f1SDimitry Andric 
16370b57cec5SDimitry Andric     if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1638fe6060f1SDimitry Andric       // Update every use of Reg within MI.
1639fe6060f1SDimitry Andric       for (auto &RegMO : DbgOps)
1640fe6060f1SDimitry Andric         setPhysReg(MI, *RegMO, LRI->PhysReg);
16410b57cec5SDimitry Andric     } else {
1642e8d8bef9SDimitry Andric       DanglingDbgValues[Reg].push_back(&MI);
16430b57cec5SDimitry Andric     }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
16460b57cec5SDimitry Andric     // that future spills of Reg will have DBG_VALUEs.
1647fe6060f1SDimitry Andric     LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1648fe6060f1SDimitry Andric   }
16490b57cec5SDimitry Andric }
16500b57cec5SDimitry Andric 
handleBundle(MachineInstr & MI)1651e8d8bef9SDimitry Andric void RegAllocFast::handleBundle(MachineInstr &MI) {
1652e8d8bef9SDimitry Andric   MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1653e8d8bef9SDimitry Andric   ++BundledMI;
1654e8d8bef9SDimitry Andric   while (BundledMI->isBundledWithPred()) {
16554824e7fdSDimitry Andric     for (MachineOperand &MO : BundledMI->operands()) {
1656e8d8bef9SDimitry Andric       if (!MO.isReg())
1657e8d8bef9SDimitry Andric         continue;
1658e8d8bef9SDimitry Andric 
1659e8d8bef9SDimitry Andric       Register Reg = MO.getReg();
1660bdd1243dSDimitry Andric       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1661e8d8bef9SDimitry Andric         continue;
1662e8d8bef9SDimitry Andric 
1663e8d8bef9SDimitry Andric       DenseMap<Register, MCPhysReg>::iterator DI;
1664e8d8bef9SDimitry Andric       DI = BundleVirtRegsMap.find(Reg);
1665e8d8bef9SDimitry Andric       assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1666e8d8bef9SDimitry Andric 
1667e8d8bef9SDimitry Andric       setPhysReg(MI, MO, DI->second);
1668e8d8bef9SDimitry Andric     }
1669e8d8bef9SDimitry Andric 
1670e8d8bef9SDimitry Andric     ++BundledMI;
1671e8d8bef9SDimitry Andric   }
1672e8d8bef9SDimitry Andric }
1673e8d8bef9SDimitry Andric 
allocateBasicBlock(MachineBasicBlock & MBB)16740b57cec5SDimitry Andric void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
16750b57cec5SDimitry Andric   this->MBB = &MBB;
16760b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
16770b57cec5SDimitry Andric 
1678*e710425bSDimitry Andric   PosIndexes.unsetInitialized();
1679e8d8bef9SDimitry Andric   RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
16800b57cec5SDimitry Andric   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
16810b57cec5SDimitry Andric 
1682fcaf7f86SDimitry Andric   for (const auto &LiveReg : MBB.liveouts())
1683fe6060f1SDimitry Andric     setPhysRegState(LiveReg.PhysReg, regPreAssigned);
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   Coalesced.clear();
16860b57cec5SDimitry Andric 
1687e8d8bef9SDimitry Andric   // Traverse block in reverse order allocating instructions one by one.
1688e8d8bef9SDimitry Andric   for (MachineInstr &MI : reverse(MBB)) {
1689c9157d92SDimitry Andric     LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric     // Special handling for debug values. Note that they are not allowed to
16920b57cec5SDimitry Andric     // affect codegen of the other instructions in any way.
16930b57cec5SDimitry Andric     if (MI.isDebugValue()) {
16940b57cec5SDimitry Andric       handleDebugValue(MI);
16950b57cec5SDimitry Andric       continue;
16960b57cec5SDimitry Andric     }
16970b57cec5SDimitry Andric 
16980b57cec5SDimitry Andric     allocateInstruction(MI);
1699e8d8bef9SDimitry Andric 
1700e8d8bef9SDimitry Andric     // Once BUNDLE header is assigned registers, same assignments need to be
1701e8d8bef9SDimitry Andric     // done for bundled MIs.
1702e8d8bef9SDimitry Andric     if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1703e8d8bef9SDimitry Andric       handleBundle(MI);
1704e8d8bef9SDimitry Andric     }
17050b57cec5SDimitry Andric   }
17060b57cec5SDimitry Andric 
1707c9157d92SDimitry Andric   LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1708e8d8bef9SDimitry Andric 
17090b57cec5SDimitry Andric   // Spill all physical registers holding virtual registers now.
1710e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1711e8d8bef9SDimitry Andric   reloadAtBegin(MBB);
17120b57cec5SDimitry Andric 
17130b57cec5SDimitry Andric   // Erase all the coalesced copies. We are delaying it until now because
17140b57cec5SDimitry Andric   // LiveVirtRegs might refer to the instrs.
17150b57cec5SDimitry Andric   for (MachineInstr *MI : Coalesced)
17160b57cec5SDimitry Andric     MBB.erase(MI);
17170b57cec5SDimitry Andric   NumCoalesced += Coalesced.size();
17180b57cec5SDimitry Andric 
1719e8d8bef9SDimitry Andric   for (auto &UDBGPair : DanglingDbgValues) {
1720e8d8bef9SDimitry Andric     for (MachineInstr *DbgValue : UDBGPair.second) {
1721e8d8bef9SDimitry Andric       assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1722e8d8bef9SDimitry Andric       // Nothing to do if the vreg was spilled in the meantime.
1723fe6060f1SDimitry Andric       if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1724e8d8bef9SDimitry Andric         continue;
1725e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1726e8d8bef9SDimitry Andric                         << '\n');
1727fe6060f1SDimitry Andric       DbgValue->setDebugValueUndef();
1728e8d8bef9SDimitry Andric     }
1729e8d8bef9SDimitry Andric   }
1730e8d8bef9SDimitry Andric   DanglingDbgValues.clear();
1731e8d8bef9SDimitry Andric 
17320b57cec5SDimitry Andric   LLVM_DEBUG(MBB.dump());
17330b57cec5SDimitry Andric }
17340b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)17350b57cec5SDimitry Andric bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
17360b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
17370b57cec5SDimitry Andric                     << "********** Function: " << MF.getName() << '\n');
17380b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
17390b57cec5SDimitry Andric   const TargetSubtargetInfo &STI = MF.getSubtarget();
17400b57cec5SDimitry Andric   TRI = STI.getRegisterInfo();
17410b57cec5SDimitry Andric   TII = STI.getInstrInfo();
17420b57cec5SDimitry Andric   MFI = &MF.getFrameInfo();
17430b57cec5SDimitry Andric   MRI->freezeReservedRegs(MF);
17440b57cec5SDimitry Andric   RegClassInfo.runOnMachineFunction(MF);
1745e8d8bef9SDimitry Andric   unsigned NumRegUnits = TRI->getNumRegUnits();
17460b57cec5SDimitry Andric   UsedInInstr.clear();
1747e8d8bef9SDimitry Andric   UsedInInstr.setUniverse(NumRegUnits);
1748e8d8bef9SDimitry Andric   PhysRegUses.clear();
1749e8d8bef9SDimitry Andric   PhysRegUses.setUniverse(NumRegUnits);
17500b57cec5SDimitry Andric 
17510b57cec5SDimitry Andric   // initialize the virtual->physical register map to have a 'null'
17520b57cec5SDimitry Andric   // mapping for all virtual registers
17530b57cec5SDimitry Andric   unsigned NumVirtRegs = MRI->getNumVirtRegs();
17540b57cec5SDimitry Andric   StackSlotForVirtReg.resize(NumVirtRegs);
17550b57cec5SDimitry Andric   LiveVirtRegs.setUniverse(NumVirtRegs);
17560b57cec5SDimitry Andric   MayLiveAcrossBlocks.clear();
17570b57cec5SDimitry Andric   MayLiveAcrossBlocks.resize(NumVirtRegs);
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric   // Loop over all of the basic blocks, eliminating virtual register references
17600b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF)
17610b57cec5SDimitry Andric     allocateBasicBlock(MBB);
17620b57cec5SDimitry Andric 
1763fe6060f1SDimitry Andric   if (ClearVirtRegs) {
17640b57cec5SDimitry Andric     // All machine operands and other references to virtual registers have been
17650b57cec5SDimitry Andric     // replaced. Remove the virtual registers.
17660b57cec5SDimitry Andric     MRI->clearVirtRegs();
1767fe6060f1SDimitry Andric   }
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   StackSlotForVirtReg.clear();
17700b57cec5SDimitry Andric   LiveDbgValueMap.clear();
17710b57cec5SDimitry Andric   return true;
17720b57cec5SDimitry Andric }
17730b57cec5SDimitry Andric 
createFastRegisterAllocator()1774c9157d92SDimitry Andric FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
1775fe6060f1SDimitry Andric 
createFastRegisterAllocator(RegClassFilterFunc Ftor,bool ClearVirtRegs)1776fcaf7f86SDimitry Andric FunctionPass *llvm::createFastRegisterAllocator(RegClassFilterFunc Ftor,
1777fcaf7f86SDimitry Andric                                                 bool ClearVirtRegs) {
1778fe6060f1SDimitry Andric   return new RegAllocFast(Ftor, ClearVirtRegs);
1779fe6060f1SDimitry Andric }
1780