xref: /llvm-project/llvm/lib/CodeGen/RegAllocFast.cpp (revision 1bc8b3258e6d42f702fb11eb60d84d0e23935e3e)
1 //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file This register allocator allocates registers to a basic block at a
10 /// time, attempting to keep values in registers and reusing registers as
11 /// appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/RegAllocFast.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/IndexedMap.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/SparseSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineOperand.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/RegAllocCommon.h"
33 #include "llvm/CodeGen/RegAllocRegistry.h"
34 #include "llvm/CodeGen/RegisterClassInfo.h"
35 #include "llvm/CodeGen/TargetInstrInfo.h"
36 #include "llvm/CodeGen/TargetOpcodes.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/InitializePasses.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <cassert>
46 #include <tuple>
47 #include <vector>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "regalloc"
52 
53 STATISTIC(NumStores, "Number of stores added");
54 STATISTIC(NumLoads, "Number of loads added");
55 STATISTIC(NumCoalesced, "Number of copies coalesced");
56 
57 // FIXME: Remove this switch when all testcases are fixed!
58 static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
59                                        cl::Hidden);
60 
61 static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator",
62                                      createFastRegisterAllocator);
63 
64 namespace {
65 
66 /// Assign ascending index for instructions in machine basic block. The index
67 /// can be used to determine dominance between instructions in same MBB.
68 class InstrPosIndexes {
69 public:
70   void unsetInitialized() { IsInitialized = false; }
71 
72   void init(const MachineBasicBlock &MBB) {
73     CurMBB = &MBB;
74     Instr2PosIndex.clear();
75     uint64_t LastIndex = 0;
76     for (const MachineInstr &MI : MBB) {
77       LastIndex += InstrDist;
78       Instr2PosIndex[&MI] = LastIndex;
79     }
80   }
81 
82   /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to assign
83   /// index without affecting existing instruction's index. Return true if all
84   /// instructions index has been reassigned.
85   bool getIndex(const MachineInstr &MI, uint64_t &Index) {
86     if (!IsInitialized) {
87       init(*MI.getParent());
88       IsInitialized = true;
89       Index = Instr2PosIndex.at(&MI);
90       return true;
91     }
92 
93     assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
94     auto It = Instr2PosIndex.find(&MI);
95     if (It != Instr2PosIndex.end()) {
96       Index = It->second;
97       return false;
98     }
99 
100     // Distance is the number of consecutive unassigned instructions including
101     // MI. Start is the first instruction of them. End is the next of last
102     // instruction of them.
103     // e.g.
104     // |Instruction|  A   |  B   |  C   |  MI  |  D   |  E   |
105     // |   Index   | 1024 |      |      |      |      | 2048 |
106     //
107     // In this case, B, C, MI, D are unassigned. Distance is 4, Start is B, End
108     // is E.
109     unsigned Distance = 1;
110     MachineBasicBlock::const_iterator Start = MI.getIterator(),
111                                       End = std::next(Start);
112     while (Start != CurMBB->begin() &&
113            !Instr2PosIndex.count(&*std::prev(Start))) {
114       --Start;
115       ++Distance;
116     }
117     while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
118       ++End;
119       ++Distance;
120     }
121 
122     // LastIndex is initialized to last used index prior to MI or zero.
123     // In previous example, LastIndex is 1024, EndIndex is 2048;
124     uint64_t LastIndex =
125         Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
126     uint64_t Step;
127     if (End == CurMBB->end())
128       Step = static_cast<uint64_t>(InstrDist);
129     else {
130       // No instruction uses index zero.
131       uint64_t EndIndex = Instr2PosIndex.at(&*End);
132       assert(EndIndex > LastIndex && "Index must be ascending order");
133       unsigned NumAvailableIndexes = EndIndex - LastIndex - 1;
134       // We want index gap between two adjacent MI is as same as possible. Given
135       // total A available indexes, D is number of consecutive unassigned
136       // instructions, S is the step.
137       // |<- S-1 -> MI <- S-1 -> MI <- A-S*D ->|
138       // There're S-1 available indexes between unassigned instruction and its
139       // predecessor. There're A-S*D available indexes between the last
140       // unassigned instruction and its successor.
141       // Ideally, we want
142       //    S-1 = A-S*D
143       // then
144       //    S = (A+1)/(D+1)
145       // An valid S must be integer greater than zero, so
146       //    S <= (A+1)/(D+1)
147       // =>
148       //    A-S*D >= 0
149       // That means we can safely use (A+1)/(D+1) as step.
150       // In previous example, Step is 204, Index of B, C, MI, D is 1228, 1432,
151       // 1636, 1840.
152       Step = (NumAvailableIndexes + 1) / (Distance + 1);
153     }
154 
155     // Reassign index for all instructions if number of new inserted
156     // instructions exceed slot or all instructions are new.
157     if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
158       init(*CurMBB);
159       Index = Instr2PosIndex.at(&MI);
160       return true;
161     }
162 
163     for (auto I = Start; I != End; ++I) {
164       LastIndex += Step;
165       Instr2PosIndex[&*I] = LastIndex;
166     }
167     Index = Instr2PosIndex.at(&MI);
168     return false;
169   }
170 
171 private:
172   bool IsInitialized = false;
173   enum { InstrDist = 1024 };
174   const MachineBasicBlock *CurMBB = nullptr;
175   DenseMap<const MachineInstr *, uint64_t> Instr2PosIndex;
176 };
177 
178 class RegAllocFastImpl {
179 public:
180   RegAllocFastImpl(const RegClassFilterFunc F = allocateAllRegClasses,
181                    bool ClearVirtRegs_ = true)
182       : ShouldAllocateClass(F), StackSlotForVirtReg(-1),
183         ClearVirtRegs(ClearVirtRegs_) {}
184 
185 private:
186   MachineFrameInfo *MFI = nullptr;
187   MachineRegisterInfo *MRI = nullptr;
188   const TargetRegisterInfo *TRI = nullptr;
189   const TargetInstrInfo *TII = nullptr;
190   RegisterClassInfo RegClassInfo;
191   const RegClassFilterFunc ShouldAllocateClass;
192 
193   /// Basic block currently being allocated.
194   MachineBasicBlock *MBB = nullptr;
195 
196   /// Maps virtual regs to the frame index where these values are spilled.
197   IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
198 
199   /// Everything we know about a live virtual register.
200   struct LiveReg {
201     MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
202     Register VirtReg;                ///< Virtual register number.
203     MCPhysReg PhysReg = 0;           ///< Currently held here.
204     bool LiveOut = false;            ///< Register is possibly live out.
205     bool Reloaded = false;           ///< Register was reloaded.
206     bool Error = false;              ///< Could not allocate.
207 
208     explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
209 
210     unsigned getSparseSetIndex() const {
211       return Register::virtReg2Index(VirtReg);
212     }
213   };
214 
215   using LiveRegMap = SparseSet<LiveReg, identity<unsigned>, uint16_t>;
216   /// This map contains entries for each virtual register that is currently
217   /// available in a physical register.
218   LiveRegMap LiveVirtRegs;
219 
220   /// Stores assigned virtual registers present in the bundle MI.
221   DenseMap<Register, MCPhysReg> BundleVirtRegsMap;
222 
223   DenseMap<unsigned, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
224   /// List of DBG_VALUE that we encountered without the vreg being assigned
225   /// because they were placed after the last use of the vreg.
226   DenseMap<unsigned, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
227 
228   /// Has a bit set for every virtual register for which it was determined
229   /// that it is alive across blocks.
230   BitVector MayLiveAcrossBlocks;
231 
232   /// State of a register unit.
233   enum RegUnitState {
234     /// A free register is not currently in use and can be allocated
235     /// immediately without checking aliases.
236     regFree,
237 
238     /// A pre-assigned register has been assigned before register allocation
239     /// (e.g., setting up a call parameter).
240     regPreAssigned,
241 
242     /// Used temporarily in reloadAtBegin() to mark register units that are
243     /// live-in to the basic block.
244     regLiveIn,
245 
246     /// A register state may also be a virtual register number, indication
247     /// that the physical register is currently allocated to a virtual
248     /// register. In that case, LiveVirtRegs contains the inverse mapping.
249   };
250 
251   /// Maps each physical register to a RegUnitState enum or virtual register.
252   std::vector<unsigned> RegUnitStates;
253 
254   SmallVector<MachineInstr *, 32> Coalesced;
255 
256   using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
257   /// Set of register units that are used in the current instruction, and so
258   /// cannot be allocated.
259   RegUnitSet UsedInInstr;
260   RegUnitSet PhysRegUses;
261   SmallVector<uint16_t, 8> DefOperandIndexes;
262   // Register masks attached to the current instruction.
263   SmallVector<const uint32_t *> RegMasks;
264 
265   // Assign index for each instruction to quickly determine dominance.
266   InstrPosIndexes PosIndexes;
267 
268   void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
269   bool isPhysRegFree(MCPhysReg PhysReg) const;
270 
271   /// Mark a physreg as used in this instruction.
272   void markRegUsedInInstr(MCPhysReg PhysReg) {
273     for (MCRegUnit Unit : TRI->regunits(PhysReg))
274       UsedInInstr.insert(Unit);
275   }
276 
277   // Check if physreg is clobbered by instruction's regmask(s).
278   bool isClobberedByRegMasks(MCPhysReg PhysReg) const {
279     return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
280       return MachineOperand::clobbersPhysReg(Mask, PhysReg);
281     });
282   }
283 
284   /// Check if a physreg or any of its aliases are used in this instruction.
285   bool isRegUsedInInstr(MCPhysReg PhysReg, bool LookAtPhysRegUses) const {
286     if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
287       return true;
288     for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
289       if (UsedInInstr.count(Unit))
290         return true;
291       if (LookAtPhysRegUses && PhysRegUses.count(Unit))
292         return true;
293     }
294     return false;
295   }
296 
297   /// Mark physical register as being used in a register use operand.
298   /// This is only used by the special livethrough handling code.
299   void markPhysRegUsedInInstr(MCPhysReg PhysReg) {
300     for (MCRegUnit Unit : TRI->regunits(PhysReg))
301       PhysRegUses.insert(Unit);
302   }
303 
304   /// Remove mark of physical register being used in the instruction.
305   void unmarkRegUsedInInstr(MCPhysReg PhysReg) {
306     for (MCRegUnit Unit : TRI->regunits(PhysReg))
307       UsedInInstr.erase(Unit);
308   }
309 
310   enum : unsigned {
311     spillClean = 50,
312     spillDirty = 100,
313     spillPrefBonus = 20,
314     spillImpossible = ~0u
315   };
316 
317 public:
318   bool ClearVirtRegs;
319 
320   bool runOnMachineFunction(MachineFunction &MF);
321 
322 private:
323   void allocateBasicBlock(MachineBasicBlock &MBB);
324 
325   void addRegClassDefCounts(std::vector<unsigned> &RegClassDefCounts,
326                             Register Reg) const;
327 
328   void findAndSortDefOperandIndexes(const MachineInstr &MI);
329 
330   void allocateInstruction(MachineInstr &MI);
331   void handleDebugValue(MachineInstr &MI);
332   void handleBundle(MachineInstr &MI);
333 
334   bool usePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
335   bool definePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
336   bool displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
337   void freePhysReg(MCPhysReg PhysReg);
338 
339   unsigned calcSpillCost(MCPhysReg PhysReg) const;
340 
341   LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
342     return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
343   }
344 
345   LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
346     return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
347   }
348 
349   void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCPhysReg PhysReg);
350   void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
351                     bool LookAtPhysRegUses = false);
352   void allocVirtRegUndef(MachineOperand &MO);
353   void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
354                                  MCPhysReg Reg);
355   bool defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
356                                 Register VirtReg);
357   bool defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
358                      bool LookAtPhysRegUses = false);
359   bool useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
360 
361   MachineBasicBlock::iterator
362   getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
363                             SmallSet<Register, 2> &PrologLiveIns) const;
364 
365   void reloadAtBegin(MachineBasicBlock &MBB);
366   bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
367 
368   Register traceCopies(Register VirtReg) const;
369   Register traceCopyChain(Register Reg) const;
370 
371   bool shouldAllocateRegister(const Register Reg) const;
372   int getStackSpaceFor(Register VirtReg);
373   void spill(MachineBasicBlock::iterator Before, Register VirtReg,
374              MCPhysReg AssignedReg, bool Kill, bool LiveOut);
375   void reload(MachineBasicBlock::iterator Before, Register VirtReg,
376               MCPhysReg PhysReg);
377 
378   bool mayLiveOut(Register VirtReg);
379   bool mayLiveIn(Register VirtReg);
380 
381   void dumpState() const;
382 };
383 
384 class RegAllocFast : public MachineFunctionPass {
385   RegAllocFastImpl Impl;
386 
387 public:
388   static char ID;
389 
390   RegAllocFast(const RegClassFilterFunc F = allocateAllRegClasses,
391                bool ClearVirtRegs_ = true)
392       : MachineFunctionPass(ID), Impl(F, ClearVirtRegs_) {}
393 
394   bool runOnMachineFunction(MachineFunction &MF) override {
395     return Impl.runOnMachineFunction(MF);
396   }
397 
398   StringRef getPassName() const override { return "Fast Register Allocator"; }
399 
400   void getAnalysisUsage(AnalysisUsage &AU) const override {
401     AU.setPreservesCFG();
402     MachineFunctionPass::getAnalysisUsage(AU);
403   }
404 
405   MachineFunctionProperties getRequiredProperties() const override {
406     return MachineFunctionProperties().set(
407         MachineFunctionProperties::Property::NoPHIs);
408   }
409 
410   MachineFunctionProperties getSetProperties() const override {
411     if (Impl.ClearVirtRegs) {
412       return MachineFunctionProperties().set(
413           MachineFunctionProperties::Property::NoVRegs);
414     }
415 
416     return MachineFunctionProperties();
417   }
418 
419   MachineFunctionProperties getClearedProperties() const override {
420     return MachineFunctionProperties().set(
421         MachineFunctionProperties::Property::IsSSA);
422   }
423 };
424 
425 } // end anonymous namespace
426 
427 char RegAllocFast::ID = 0;
428 
429 INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
430                 false)
431 
432 bool RegAllocFastImpl::shouldAllocateRegister(const Register Reg) const {
433   assert(Reg.isVirtual());
434   const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
435   return ShouldAllocateClass(*TRI, RC);
436 }
437 
438 void RegAllocFastImpl::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
439   for (MCRegUnit Unit : TRI->regunits(PhysReg))
440     RegUnitStates[Unit] = NewState;
441 }
442 
443 bool RegAllocFastImpl::isPhysRegFree(MCPhysReg PhysReg) const {
444   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
445     if (RegUnitStates[Unit] != regFree)
446       return false;
447   }
448   return true;
449 }
450 
451 /// This allocates space for the specified virtual register to be held on the
452 /// stack.
453 int RegAllocFastImpl::getStackSpaceFor(Register VirtReg) {
454   // Find the location Reg would belong...
455   int SS = StackSlotForVirtReg[VirtReg];
456   // Already has space allocated?
457   if (SS != -1)
458     return SS;
459 
460   // Allocate a new stack object for this spill location...
461   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
462   unsigned Size = TRI->getSpillSize(RC);
463   Align Alignment = TRI->getSpillAlign(RC);
464   int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
465 
466   // Assign the slot.
467   StackSlotForVirtReg[VirtReg] = FrameIdx;
468   return FrameIdx;
469 }
470 
471 static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
472                       const MachineInstr &B) {
473   uint64_t IndexA, IndexB;
474   PosIndexes.getIndex(A, IndexA);
475   if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
476     PosIndexes.getIndex(A, IndexA);
477   return IndexA < IndexB;
478 }
479 
480 /// Returns false if \p VirtReg is known to not live out of the current block.
481 bool RegAllocFastImpl::mayLiveOut(Register VirtReg) {
482   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
483     // Cannot be live-out if there are no successors.
484     return !MBB->succ_empty();
485   }
486 
487   const MachineInstr *SelfLoopDef = nullptr;
488 
489   // If this block loops back to itself, it is necessary to check whether the
490   // use comes after the def.
491   if (MBB->isSuccessor(MBB)) {
492     // Find the first def in the self loop MBB.
493     for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
494       if (DefInst.getParent() != MBB) {
495         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
496         return true;
497       } else {
498         if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
499           SelfLoopDef = &DefInst;
500       }
501     }
502     if (!SelfLoopDef) {
503       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
504       return true;
505     }
506   }
507 
508   // See if the first \p Limit uses of the register are all in the current
509   // block.
510   static const unsigned Limit = 8;
511   unsigned C = 0;
512   for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
513     if (UseInst.getParent() != MBB || ++C >= Limit) {
514       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
515       // Cannot be live-out if there are no successors.
516       return !MBB->succ_empty();
517     }
518 
519     if (SelfLoopDef) {
520       // Try to handle some simple cases to avoid spilling and reloading every
521       // value inside a self looping block.
522       if (SelfLoopDef == &UseInst ||
523           !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
524         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
525         return true;
526       }
527     }
528   }
529 
530   return false;
531 }
532 
533 /// Returns false if \p VirtReg is known to not be live into the current block.
534 bool RegAllocFastImpl::mayLiveIn(Register VirtReg) {
535   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
536     return !MBB->pred_empty();
537 
538   // See if the first \p Limit def of the register are all in the current block.
539   static const unsigned Limit = 8;
540   unsigned C = 0;
541   for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
542     if (DefInst.getParent() != MBB || ++C >= Limit) {
543       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
544       return !MBB->pred_empty();
545     }
546   }
547 
548   return false;
549 }
550 
551 /// Insert spill instruction for \p AssignedReg before \p Before. Update
552 /// DBG_VALUEs with \p VirtReg operands with the stack slot.
553 void RegAllocFastImpl::spill(MachineBasicBlock::iterator Before,
554                              Register VirtReg, MCPhysReg AssignedReg, bool Kill,
555                              bool LiveOut) {
556   LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
557                     << printReg(AssignedReg, TRI));
558   int FI = getStackSpaceFor(VirtReg);
559   LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
560 
561   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
562   TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI,
563                            VirtReg);
564   ++NumStores;
565 
566   MachineBasicBlock::iterator FirstTerm = MBB->getFirstTerminator();
567 
568   // When we spill a virtual register, we will have spill instructions behind
569   // every definition of it, meaning we can switch all the DBG_VALUEs over
570   // to just reference the stack slot.
571   SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
572   SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
573       SpilledOperandsMap;
574   for (MachineOperand *MO : LRIDbgOperands)
575     SpilledOperandsMap[MO->getParent()].push_back(MO);
576   for (auto MISpilledOperands : SpilledOperandsMap) {
577     MachineInstr &DBG = *MISpilledOperands.first;
578     // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
579     if (DBG.isDebugValueList())
580       continue;
581     MachineInstr *NewDV = buildDbgValueForSpill(
582         *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
583     assert(NewDV->getParent() == MBB && "dangling parent pointer");
584     (void)NewDV;
585     LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
586 
587     if (LiveOut) {
588       // We need to insert a DBG_VALUE at the end of the block if the spill slot
589       // is live out, but there is another use of the value after the
590       // spill. This will allow LiveDebugValues to see the correct live out
591       // value to propagate to the successors.
592       MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
593       MBB->insert(FirstTerm, ClonedDV);
594       LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
595     }
596 
597     // Rewrite unassigned dbg_values to use the stack slot.
598     // TODO We can potentially do this for list debug values as well if we know
599     // how the dbg_values are getting unassigned.
600     if (DBG.isNonListDebugValue()) {
601       MachineOperand &MO = DBG.getDebugOperand(0);
602       if (MO.isReg() && MO.getReg() == 0) {
603         updateDbgValueForSpill(DBG, FI, 0);
604       }
605     }
606   }
607   // Now this register is spilled there is should not be any DBG_VALUE
608   // pointing to this register because they are all pointing to spilled value
609   // now.
610   LRIDbgOperands.clear();
611 }
612 
613 /// Insert reload instruction for \p PhysReg before \p Before.
614 void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
615                               Register VirtReg, MCPhysReg PhysReg) {
616   LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
617                     << printReg(PhysReg, TRI) << '\n');
618   int FI = getStackSpaceFor(VirtReg);
619   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
620   TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI, VirtReg);
621   ++NumLoads;
622 }
623 
624 /// Get basic block begin insertion point.
625 /// This is not just MBB.begin() because surprisingly we have EH_LABEL
626 /// instructions marking the begin of a basic block. This means we must insert
627 /// new instructions after such labels...
628 MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
629     MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
630   MachineBasicBlock::iterator I = MBB.begin();
631   while (I != MBB.end()) {
632     if (I->isLabel()) {
633       ++I;
634       continue;
635     }
636 
637     // Most reloads should be inserted after prolog instructions.
638     if (!TII->isBasicBlockPrologue(*I))
639       break;
640 
641     // However if a prolog instruction reads a register that needs to be
642     // reloaded, the reload should be inserted before the prolog.
643     for (MachineOperand &MO : I->operands()) {
644       if (MO.isReg())
645         PrologLiveIns.insert(MO.getReg());
646     }
647 
648     ++I;
649   }
650 
651   return I;
652 }
653 
654 /// Reload all currently assigned virtual registers.
655 void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &MBB) {
656   if (LiveVirtRegs.empty())
657     return;
658 
659   for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
660     MCPhysReg Reg = P.PhysReg;
661     // Set state to live-in. This possibly overrides mappings to virtual
662     // registers but we don't care anymore at this point.
663     setPhysRegState(Reg, regLiveIn);
664   }
665 
666   SmallSet<Register, 2> PrologLiveIns;
667 
668   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
669   // of spilling here is deterministic, if arbitrary.
670   MachineBasicBlock::iterator InsertBefore =
671       getMBBBeginInsertionPoint(MBB, PrologLiveIns);
672   for (const LiveReg &LR : LiveVirtRegs) {
673     MCPhysReg PhysReg = LR.PhysReg;
674     if (PhysReg == 0)
675       continue;
676 
677     MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
678     if (RegUnitStates[FirstUnit] == regLiveIn)
679       continue;
680 
681     assert((&MBB != &MBB.getParent()->front() || IgnoreMissingDefs) &&
682            "no reload in start block. Missing vreg def?");
683 
684     if (PrologLiveIns.count(PhysReg)) {
685       // FIXME: Theoretically this should use an insert point skipping labels
686       // but I'm not sure how labels should interact with prolog instruction
687       // that need reloads.
688       reload(MBB.begin(), LR.VirtReg, PhysReg);
689     } else
690       reload(InsertBefore, LR.VirtReg, PhysReg);
691   }
692   LiveVirtRegs.clear();
693 }
694 
695 /// Handle the direct use of a physical register.  Check that the register is
696 /// not used by a virtreg. Kill the physreg, marking it free. This may add
697 /// implicit kills to MO->getParent() and invalidate MO.
698 bool RegAllocFastImpl::usePhysReg(MachineInstr &MI, MCPhysReg Reg) {
699   assert(Register::isPhysicalRegister(Reg) && "expected physreg");
700   bool displacedAny = displacePhysReg(MI, Reg);
701   setPhysRegState(Reg, regPreAssigned);
702   markRegUsedInInstr(Reg);
703   return displacedAny;
704 }
705 
706 bool RegAllocFastImpl::definePhysReg(MachineInstr &MI, MCPhysReg Reg) {
707   bool displacedAny = displacePhysReg(MI, Reg);
708   setPhysRegState(Reg, regPreAssigned);
709   return displacedAny;
710 }
711 
712 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
713 /// similar to defineVirtReg except the physreg is reserved instead of
714 /// allocated.
715 bool RegAllocFastImpl::displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg) {
716   bool displacedAny = false;
717 
718   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
719     switch (unsigned VirtReg = RegUnitStates[Unit]) {
720     default: {
721       LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
722       assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
723       MachineBasicBlock::iterator ReloadBefore =
724           std::next((MachineBasicBlock::iterator)MI.getIterator());
725       reload(ReloadBefore, VirtReg, LRI->PhysReg);
726 
727       setPhysRegState(LRI->PhysReg, regFree);
728       LRI->PhysReg = 0;
729       LRI->Reloaded = true;
730       displacedAny = true;
731       break;
732     }
733     case regPreAssigned:
734       RegUnitStates[Unit] = regFree;
735       displacedAny = true;
736       break;
737     case regFree:
738       break;
739     }
740   }
741   return displacedAny;
742 }
743 
744 void RegAllocFastImpl::freePhysReg(MCPhysReg PhysReg) {
745   LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
746 
747   MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
748   switch (unsigned VirtReg = RegUnitStates[FirstUnit]) {
749   case regFree:
750     LLVM_DEBUG(dbgs() << '\n');
751     return;
752   case regPreAssigned:
753     LLVM_DEBUG(dbgs() << '\n');
754     setPhysRegState(PhysReg, regFree);
755     return;
756   default: {
757     LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
758     assert(LRI != LiveVirtRegs.end());
759     LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
760     setPhysRegState(LRI->PhysReg, regFree);
761     LRI->PhysReg = 0;
762   }
763     return;
764   }
765 }
766 
767 /// Return the cost of spilling clearing out PhysReg and aliases so it is free
768 /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
769 /// disabled - it can be allocated directly.
770 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
771 unsigned RegAllocFastImpl::calcSpillCost(MCPhysReg PhysReg) const {
772   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
773     switch (unsigned VirtReg = RegUnitStates[Unit]) {
774     case regFree:
775       break;
776     case regPreAssigned:
777       LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
778                         << printReg(PhysReg, TRI) << '\n');
779       return spillImpossible;
780     default: {
781       bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
782                        findLiveVirtReg(VirtReg)->LiveOut;
783       return SureSpill ? spillClean : spillDirty;
784     }
785     }
786   }
787   return 0;
788 }
789 
790 void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
791                                                  Register VirtReg,
792                                                  MCPhysReg Reg) {
793   auto UDBGValIter = DanglingDbgValues.find(VirtReg);
794   if (UDBGValIter == DanglingDbgValues.end())
795     return;
796 
797   SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
798   for (MachineInstr *DbgValue : Dangling) {
799     assert(DbgValue->isDebugValue());
800     if (!DbgValue->hasDebugOperandForReg(VirtReg))
801       continue;
802 
803     // Test whether the physreg survives from the definition to the DBG_VALUE.
804     MCPhysReg SetToReg = Reg;
805     unsigned Limit = 20;
806     for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
807                                      E = DbgValue->getIterator();
808          I != E; ++I) {
809       if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
810         LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
811                           << '\n');
812         SetToReg = 0;
813         break;
814       }
815     }
816     for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
817       MO.setReg(SetToReg);
818       if (SetToReg != 0)
819         MO.setIsRenamable();
820     }
821   }
822   Dangling.clear();
823 }
824 
825 /// This method updates local state so that we know that PhysReg is the
826 /// proper container for VirtReg now.  The physical register must not be used
827 /// for anything else when this is called.
828 void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
829                                            MCPhysReg PhysReg) {
830   Register VirtReg = LR.VirtReg;
831   LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
832                     << printReg(PhysReg, TRI) << '\n');
833   assert(LR.PhysReg == 0 && "Already assigned a physreg");
834   assert(PhysReg != 0 && "Trying to assign no register");
835   LR.PhysReg = PhysReg;
836   setPhysRegState(PhysReg, VirtReg);
837 
838   assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
839 }
840 
841 static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
842 
843 Register RegAllocFastImpl::traceCopyChain(Register Reg) const {
844   static const unsigned ChainLengthLimit = 3;
845   unsigned C = 0;
846   do {
847     if (Reg.isPhysical())
848       return Reg;
849     assert(Reg.isVirtual());
850 
851     MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
852     if (!VRegDef || !isCoalescable(*VRegDef))
853       return 0;
854     Reg = VRegDef->getOperand(1).getReg();
855   } while (++C <= ChainLengthLimit);
856   return 0;
857 }
858 
859 /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
860 /// chain of copies to check whether we reach a physical register we can
861 /// coalesce with.
862 Register RegAllocFastImpl::traceCopies(Register VirtReg) const {
863   static const unsigned DefLimit = 3;
864   unsigned C = 0;
865   for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
866     if (isCoalescable(MI)) {
867       Register Reg = MI.getOperand(1).getReg();
868       Reg = traceCopyChain(Reg);
869       if (Reg.isValid())
870         return Reg;
871     }
872 
873     if (++C >= DefLimit)
874       break;
875   }
876   return Register();
877 }
878 
879 /// Allocates a physical register for VirtReg.
880 void RegAllocFastImpl::allocVirtReg(MachineInstr &MI, LiveReg &LR,
881                                     Register Hint0, bool LookAtPhysRegUses) {
882   const Register VirtReg = LR.VirtReg;
883   assert(LR.PhysReg == 0);
884 
885   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
886   LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
887                     << " in class " << TRI->getRegClassName(&RC)
888                     << " with hint " << printReg(Hint0, TRI) << '\n');
889 
890   // Take hint when possible.
891   if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
892       !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
893     // Take hint if the register is currently free.
894     if (isPhysRegFree(Hint0)) {
895       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
896                         << '\n');
897       assignVirtToPhysReg(MI, LR, Hint0);
898       return;
899     } else {
900       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
901                         << " occupied\n");
902     }
903   } else {
904     Hint0 = Register();
905   }
906 
907   // Try other hint.
908   Register Hint1 = traceCopies(VirtReg);
909   if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
910       !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
911     // Take hint if the register is currently free.
912     if (isPhysRegFree(Hint1)) {
913       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
914                         << '\n');
915       assignVirtToPhysReg(MI, LR, Hint1);
916       return;
917     } else {
918       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
919                         << " occupied\n");
920     }
921   } else {
922     Hint1 = Register();
923   }
924 
925   MCPhysReg BestReg = 0;
926   unsigned BestCost = spillImpossible;
927   ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
928   for (MCPhysReg PhysReg : AllocationOrder) {
929     LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
930     if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
931       LLVM_DEBUG(dbgs() << "already used in instr.\n");
932       continue;
933     }
934 
935     unsigned Cost = calcSpillCost(PhysReg);
936     LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
937     // Immediate take a register with cost 0.
938     if (Cost == 0) {
939       assignVirtToPhysReg(MI, LR, PhysReg);
940       return;
941     }
942 
943     if (PhysReg == Hint0 || PhysReg == Hint1)
944       Cost -= spillPrefBonus;
945 
946     if (Cost < BestCost) {
947       BestReg = PhysReg;
948       BestCost = Cost;
949     }
950   }
951 
952   if (!BestReg) {
953     // Nothing we can do: Report an error and keep going with an invalid
954     // allocation.
955     if (MI.isInlineAsm())
956       MI.emitError("inline assembly requires more registers than available");
957     else
958       MI.emitError("ran out of registers during register allocation");
959 
960     LR.Error = true;
961     LR.PhysReg = 0;
962     return;
963   }
964 
965   displacePhysReg(MI, BestReg);
966   assignVirtToPhysReg(MI, LR, BestReg);
967 }
968 
969 void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
970   assert(MO.isUndef() && "expected undef use");
971   Register VirtReg = MO.getReg();
972   assert(VirtReg.isVirtual() && "Expected virtreg");
973   if (!shouldAllocateRegister(VirtReg))
974     return;
975 
976   LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
977   MCPhysReg PhysReg;
978   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
979     PhysReg = LRI->PhysReg;
980   } else {
981     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
982     ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
983     assert(!AllocationOrder.empty() && "Allocation order must not be empty");
984     PhysReg = AllocationOrder[0];
985   }
986 
987   unsigned SubRegIdx = MO.getSubReg();
988   if (SubRegIdx != 0) {
989     PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
990     MO.setSubReg(0);
991   }
992   MO.setReg(PhysReg);
993   MO.setIsRenamable(true);
994 }
995 
996 /// Variation of defineVirtReg() with special handling for livethrough regs
997 /// (tied or earlyclobber) that may interfere with preassigned uses.
998 /// \return true if MI's MachineOperands were re-arranged/invalidated.
999 bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1000                                                 unsigned OpNum,
1001                                                 Register VirtReg) {
1002   if (!shouldAllocateRegister(VirtReg))
1003     return false;
1004   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1005   if (LRI != LiveVirtRegs.end()) {
1006     MCPhysReg PrevReg = LRI->PhysReg;
1007     if (PrevReg != 0 && isRegUsedInInstr(PrevReg, true)) {
1008       LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1009                         << " (tied/earlyclobber resolution)\n");
1010       freePhysReg(PrevReg);
1011       LRI->PhysReg = 0;
1012       allocVirtReg(MI, *LRI, 0, true);
1013       MachineBasicBlock::iterator InsertBefore =
1014           std::next((MachineBasicBlock::iterator)MI.getIterator());
1015       LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1016                         << printReg(PrevReg, TRI) << '\n');
1017       BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1018               TII->get(TargetOpcode::COPY), PrevReg)
1019           .addReg(LRI->PhysReg, llvm::RegState::Kill);
1020     }
1021     MachineOperand &MO = MI.getOperand(OpNum);
1022     if (MO.getSubReg() && !MO.isUndef()) {
1023       LRI->LastUse = &MI;
1024     }
1025   }
1026   return defineVirtReg(MI, OpNum, VirtReg, true);
1027 }
1028 
1029 /// Allocates a register for VirtReg definition. Typically the register is
1030 /// already assigned from a use of the virtreg, however we still need to
1031 /// perform an allocation if:
1032 /// - It is a dead definition without any uses.
1033 /// - The value is live out and all uses are in different basic blocks.
1034 ///
1035 /// \return true if MI's MachineOperands were re-arranged/invalidated.
1036 bool RegAllocFastImpl::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1037                                      Register VirtReg, bool LookAtPhysRegUses) {
1038   assert(VirtReg.isVirtual() && "Not a virtual register");
1039   if (!shouldAllocateRegister(VirtReg))
1040     return false;
1041   MachineOperand &MO = MI.getOperand(OpNum);
1042   LiveRegMap::iterator LRI;
1043   bool New;
1044   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1045   if (New) {
1046     if (!MO.isDead()) {
1047       if (mayLiveOut(VirtReg)) {
1048         LRI->LiveOut = true;
1049       } else {
1050         // It is a dead def without the dead flag; add the flag now.
1051         MO.setIsDead(true);
1052       }
1053     }
1054   }
1055   if (LRI->PhysReg == 0) {
1056     allocVirtReg(MI, *LRI, 0, LookAtPhysRegUses);
1057     // If no physical register is available for LRI, we assign one at random
1058     // and bail out of this function immediately.
1059     if (LRI->Error) {
1060       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1061       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1062       if (AllocationOrder.empty())
1063         return setPhysReg(MI, MO, MCRegister::NoRegister);
1064       return setPhysReg(MI, MO, *AllocationOrder.begin());
1065     }
1066   } else {
1067     assert(!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) &&
1068            "TODO: preassign mismatch");
1069     LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1070                       << " use existing assignment to "
1071                       << printReg(LRI->PhysReg, TRI) << '\n');
1072   }
1073 
1074   MCPhysReg PhysReg = LRI->PhysReg;
1075   if (LRI->Reloaded || LRI->LiveOut) {
1076     if (!MI.isImplicitDef()) {
1077       MachineBasicBlock::iterator SpillBefore =
1078           std::next((MachineBasicBlock::iterator)MI.getIterator());
1079       LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1080                         << " RL: " << LRI->Reloaded << '\n');
1081       bool Kill = LRI->LastUse == nullptr;
1082       spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1083 
1084       // We need to place additional spills for each indirect destination of an
1085       // INLINEASM_BR.
1086       if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1087         int FI = StackSlotForVirtReg[VirtReg];
1088         const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1089         for (MachineOperand &MO : MI.operands()) {
1090           if (MO.isMBB()) {
1091             MachineBasicBlock *Succ = MO.getMBB();
1092             TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1093                                      &RC, TRI, VirtReg);
1094             ++NumStores;
1095             Succ->addLiveIn(PhysReg);
1096           }
1097         }
1098       }
1099 
1100       LRI->LastUse = nullptr;
1101     }
1102     LRI->LiveOut = false;
1103     LRI->Reloaded = false;
1104   }
1105   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1106     BundleVirtRegsMap[VirtReg] = PhysReg;
1107   }
1108   markRegUsedInInstr(PhysReg);
1109   return setPhysReg(MI, MO, PhysReg);
1110 }
1111 
1112 /// Allocates a register for a VirtReg use.
1113 /// \return true if MI's MachineOperands were re-arranged/invalidated.
1114 bool RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1115                                   Register VirtReg) {
1116   assert(VirtReg.isVirtual() && "Not a virtual register");
1117   if (!shouldAllocateRegister(VirtReg))
1118     return false;
1119   LiveRegMap::iterator LRI;
1120   bool New;
1121   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1122   if (New) {
1123     if (!MO.isKill()) {
1124       if (mayLiveOut(VirtReg)) {
1125         LRI->LiveOut = true;
1126       } else {
1127         // It is a last (killing) use without the kill flag; add the flag now.
1128         MO.setIsKill(true);
1129       }
1130     }
1131   } else {
1132     assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1133   }
1134 
1135   // If necessary allocate a register.
1136   if (LRI->PhysReg == 0) {
1137     assert(!MO.isTied() && "tied op should be allocated");
1138     Register Hint;
1139     if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1140       Hint = MI.getOperand(0).getReg();
1141       if (Hint.isVirtual()) {
1142         assert(!shouldAllocateRegister(Hint));
1143         Hint = Register();
1144       } else {
1145         assert(Hint.isPhysical() &&
1146                "Copy destination should already be assigned");
1147       }
1148     }
1149     allocVirtReg(MI, *LRI, Hint, false);
1150     if (LRI->Error) {
1151       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1152       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1153       if (AllocationOrder.empty())
1154         return setPhysReg(MI, MO, MCRegister::NoRegister);
1155       return setPhysReg(MI, MO, *AllocationOrder.begin());
1156     }
1157   }
1158 
1159   LRI->LastUse = &MI;
1160 
1161   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1162     BundleVirtRegsMap[VirtReg] = LRI->PhysReg;
1163   }
1164   markRegUsedInInstr(LRI->PhysReg);
1165   return setPhysReg(MI, MO, LRI->PhysReg);
1166 }
1167 
1168 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
1169 /// \return true if MI's MachineOperands were re-arranged/invalidated.
1170 bool RegAllocFastImpl::setPhysReg(MachineInstr &MI, MachineOperand &MO,
1171                                   MCPhysReg PhysReg) {
1172   if (!MO.getSubReg()) {
1173     MO.setReg(PhysReg);
1174     MO.setIsRenamable(true);
1175     return false;
1176   }
1177 
1178   // Handle subregister index.
1179   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : MCRegister());
1180   MO.setIsRenamable(true);
1181   // Note: We leave the subreg number around a little longer in case of defs.
1182   // This is so that the register freeing logic in allocateInstruction can still
1183   // recognize this as subregister defs. The code there will clear the number.
1184   if (!MO.isDef())
1185     MO.setSubReg(0);
1186 
1187   // A kill flag implies killing the full register. Add corresponding super
1188   // register kill.
1189   if (MO.isKill()) {
1190     MI.addRegisterKilled(PhysReg, TRI, true);
1191     // Conservatively assume implicit MOs were re-arranged
1192     return true;
1193   }
1194 
1195   // A <def,read-undef> of a sub-register requires an implicit def of the full
1196   // register.
1197   if (MO.isDef() && MO.isUndef()) {
1198     if (MO.isDead())
1199       MI.addRegisterDead(PhysReg, TRI, true);
1200     else
1201       MI.addRegisterDefined(PhysReg, TRI);
1202     // Conservatively assume implicit MOs were re-arranged
1203     return true;
1204   }
1205   return false;
1206 }
1207 
1208 #ifndef NDEBUG
1209 
1210 void RegAllocFastImpl::dumpState() const {
1211   for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
1212        ++Unit) {
1213     switch (unsigned VirtReg = RegUnitStates[Unit]) {
1214     case regFree:
1215       break;
1216     case regPreAssigned:
1217       dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1218       break;
1219     case regLiveIn:
1220       llvm_unreachable("Should not have regLiveIn in map");
1221     default: {
1222       dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1223       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1224       assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1225       if (I->LiveOut || I->Reloaded) {
1226         dbgs() << '[';
1227         if (I->LiveOut)
1228           dbgs() << 'O';
1229         if (I->Reloaded)
1230           dbgs() << 'R';
1231         dbgs() << ']';
1232       }
1233       assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1234       break;
1235     }
1236     }
1237   }
1238   dbgs() << '\n';
1239   // Check that LiveVirtRegs is the inverse.
1240   for (const LiveReg &LR : LiveVirtRegs) {
1241     Register VirtReg = LR.VirtReg;
1242     assert(VirtReg.isVirtual() && "Bad map key");
1243     MCPhysReg PhysReg = LR.PhysReg;
1244     if (PhysReg != 0) {
1245       assert(Register::isPhysicalRegister(PhysReg) && "mapped to physreg");
1246       for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1247         assert(RegUnitStates[Unit] == VirtReg && "inverse map valid");
1248       }
1249     }
1250   }
1251 }
1252 #endif
1253 
1254 /// Count number of defs consumed from each register class by \p Reg
1255 void RegAllocFastImpl::addRegClassDefCounts(
1256     std::vector<unsigned> &RegClassDefCounts, Register Reg) const {
1257   assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1258 
1259   if (Reg.isVirtual()) {
1260     if (!shouldAllocateRegister(Reg))
1261       return;
1262     const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1263     for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1264          RCIdx != RCIdxEnd; ++RCIdx) {
1265       const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1266       // FIXME: Consider aliasing sub/super registers.
1267       if (OpRC->hasSubClassEq(IdxRC))
1268         ++RegClassDefCounts[RCIdx];
1269     }
1270 
1271     return;
1272   }
1273 
1274   for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1275        RCIdx != RCIdxEnd; ++RCIdx) {
1276     const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1277     for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1278       if (IdxRC->contains(*Alias)) {
1279         ++RegClassDefCounts[RCIdx];
1280         break;
1281       }
1282     }
1283   }
1284 }
1285 
1286 /// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1287 /// that are to be allocated. Those are ordered in a way that small classes,
1288 /// early clobbers and livethroughs are allocated first.
1289 void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1290   DefOperandIndexes.clear();
1291 
1292   // Track number of defs which may consume a register from the class.
1293   std::vector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1294   assert(RegClassDefCounts[0] == 0);
1295 
1296   LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1297   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1298     const MachineOperand &MO = MI.getOperand(I);
1299     if (!MO.isReg())
1300       continue;
1301     Register Reg = MO.getReg();
1302     if (MO.readsReg()) {
1303       if (Reg.isPhysical()) {
1304         LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1305         markPhysRegUsedInInstr(Reg);
1306       }
1307     }
1308 
1309     if (MO.isDef()) {
1310       if (Reg.isVirtual() && shouldAllocateRegister(Reg))
1311         DefOperandIndexes.push_back(I);
1312 
1313       addRegClassDefCounts(RegClassDefCounts, Reg);
1314     }
1315   }
1316 
1317   llvm::sort(DefOperandIndexes, [&](uint16_t I0, uint16_t I1) {
1318     const MachineOperand &MO0 = MI.getOperand(I0);
1319     const MachineOperand &MO1 = MI.getOperand(I1);
1320     Register Reg0 = MO0.getReg();
1321     Register Reg1 = MO1.getReg();
1322     const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1323     const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1324 
1325     // Identify regclass that are easy to use up completely just in this
1326     // instruction.
1327     unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
1328     unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
1329 
1330     bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1331     bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1332     if (SmallClass0 > SmallClass1)
1333       return true;
1334     if (SmallClass0 < SmallClass1)
1335       return false;
1336 
1337     // Allocate early clobbers and livethrough operands first.
1338     bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
1339                         (MO0.getSubReg() == 0 && !MO0.isUndef());
1340     bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
1341                         (MO1.getSubReg() == 0 && !MO1.isUndef());
1342     if (Livethrough0 > Livethrough1)
1343       return true;
1344     if (Livethrough0 < Livethrough1)
1345       return false;
1346 
1347     // Tie-break rule: operand index.
1348     return I0 < I1;
1349   });
1350 }
1351 
1352 // Returns true if MO is tied and the operand it's tied to is not Undef (not
1353 // Undef is not the same thing as Def).
1354 static bool isTiedToNotUndef(const MachineOperand &MO) {
1355   if (!MO.isTied())
1356     return false;
1357   const MachineInstr &MI = *MO.getParent();
1358   unsigned TiedIdx = MI.findTiedOperandIdx(MI.getOperandNo(&MO));
1359   const MachineOperand &TiedMO = MI.getOperand(TiedIdx);
1360   return !TiedMO.isUndef();
1361 }
1362 
1363 void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1364   // The basic algorithm here is:
1365   // 1. Mark registers of def operands as free
1366   // 2. Allocate registers to use operands and place reload instructions for
1367   //    registers displaced by the allocation.
1368   //
1369   // However we need to handle some corner cases:
1370   // - pre-assigned defs and uses need to be handled before the other def/use
1371   //   operands are processed to avoid the allocation heuristics clashing with
1372   //   the pre-assignment.
1373   // - The "free def operands" step has to come last instead of first for tied
1374   //   operands and early-clobbers.
1375 
1376   UsedInInstr.clear();
1377   RegMasks.clear();
1378   BundleVirtRegsMap.clear();
1379 
1380   // Scan for special cases; Apply pre-assigned register defs to state.
1381   bool HasPhysRegUse = false;
1382   bool HasRegMask = false;
1383   bool HasVRegDef = false;
1384   bool HasDef = false;
1385   bool HasEarlyClobber = false;
1386   bool NeedToAssignLiveThroughs = false;
1387   for (MachineOperand &MO : MI.operands()) {
1388     if (MO.isReg()) {
1389       Register Reg = MO.getReg();
1390       if (Reg.isVirtual()) {
1391         if (!shouldAllocateRegister(Reg))
1392           continue;
1393         if (MO.isDef()) {
1394           HasDef = true;
1395           HasVRegDef = true;
1396           if (MO.isEarlyClobber()) {
1397             HasEarlyClobber = true;
1398             NeedToAssignLiveThroughs = true;
1399           }
1400           if (isTiedToNotUndef(MO) || (MO.getSubReg() != 0 && !MO.isUndef()))
1401             NeedToAssignLiveThroughs = true;
1402         }
1403       } else if (Reg.isPhysical()) {
1404         if (!MRI->isReserved(Reg)) {
1405           if (MO.isDef()) {
1406             HasDef = true;
1407             bool displacedAny = definePhysReg(MI, Reg);
1408             if (MO.isEarlyClobber())
1409               HasEarlyClobber = true;
1410             if (!displacedAny)
1411               MO.setIsDead(true);
1412           }
1413           if (MO.readsReg())
1414             HasPhysRegUse = true;
1415         }
1416       }
1417     } else if (MO.isRegMask()) {
1418       HasRegMask = true;
1419       RegMasks.push_back(MO.getRegMask());
1420     }
1421   }
1422 
1423   // Allocate virtreg defs.
1424   if (HasDef) {
1425     if (HasVRegDef) {
1426       // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
1427       // multiple times to ensure no operand is missed.
1428       bool ReArrangedImplicitOps = true;
1429 
1430       // Special handling for early clobbers, tied operands or subregister defs:
1431       // Compared to "normal" defs these:
1432       // - Must not use a register that is pre-assigned for a use operand.
1433       // - In order to solve tricky inline assembly constraints we change the
1434       //   heuristic to figure out a good operand order before doing
1435       //   assignments.
1436       if (NeedToAssignLiveThroughs) {
1437         PhysRegUses.clear();
1438 
1439         while (ReArrangedImplicitOps) {
1440           ReArrangedImplicitOps = false;
1441           findAndSortDefOperandIndexes(MI);
1442           for (uint16_t OpIdx : DefOperandIndexes) {
1443             MachineOperand &MO = MI.getOperand(OpIdx);
1444             LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1445             Register Reg = MO.getReg();
1446             if (MO.isEarlyClobber() || isTiedToNotUndef(MO) ||
1447                 (MO.getSubReg() && !MO.isUndef())) {
1448               ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1449             } else {
1450               ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
1451             }
1452             // Implicit operands of MI were re-arranged,
1453             // re-compute DefOperandIndexes.
1454             if (ReArrangedImplicitOps)
1455               break;
1456           }
1457         }
1458       } else {
1459         // Assign virtual register defs.
1460         while (ReArrangedImplicitOps) {
1461           ReArrangedImplicitOps = false;
1462           for (MachineOperand &MO : MI.operands()) {
1463             if (!MO.isReg() || !MO.isDef())
1464               continue;
1465             Register Reg = MO.getReg();
1466             if (Reg.isVirtual()) {
1467               ReArrangedImplicitOps =
1468                   defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
1469               if (ReArrangedImplicitOps)
1470                 break;
1471             }
1472           }
1473         }
1474       }
1475     }
1476 
1477     // Free registers occupied by defs.
1478     // Iterate operands in reverse order, so we see the implicit super register
1479     // defs first (we added them earlier in case of <def,read-undef>).
1480     for (MachineOperand &MO : reverse(MI.operands())) {
1481       if (!MO.isReg() || !MO.isDef())
1482         continue;
1483 
1484       Register Reg = MO.getReg();
1485 
1486       // subreg defs don't free the full register. We left the subreg number
1487       // around as a marker in setPhysReg() to recognize this case here.
1488       if (Reg.isPhysical() && MO.getSubReg() != 0) {
1489         MO.setSubReg(0);
1490         continue;
1491       }
1492 
1493       assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1494              "tied def assigned to clobbered register");
1495 
1496       // Do not free tied operands and early clobbers.
1497       if (isTiedToNotUndef(MO) || MO.isEarlyClobber())
1498         continue;
1499       if (!Reg)
1500         continue;
1501       if (Reg.isVirtual()) {
1502         assert(!shouldAllocateRegister(Reg));
1503         continue;
1504       }
1505       assert(Reg.isPhysical());
1506       if (MRI->isReserved(Reg))
1507         continue;
1508       freePhysReg(Reg);
1509       unmarkRegUsedInInstr(Reg);
1510     }
1511   }
1512 
1513   // Displace clobbered registers.
1514   if (HasRegMask) {
1515     assert(!RegMasks.empty() && "expected RegMask");
1516     // MRI bookkeeping.
1517     for (const auto *RM : RegMasks)
1518       MRI->addPhysRegsUsedFromRegMask(RM);
1519 
1520     // Displace clobbered registers.
1521     for (const LiveReg &LR : LiveVirtRegs) {
1522       MCPhysReg PhysReg = LR.PhysReg;
1523       if (PhysReg != 0 && isClobberedByRegMasks(PhysReg))
1524         displacePhysReg(MI, PhysReg);
1525     }
1526   }
1527 
1528   // Apply pre-assigned register uses to state.
1529   if (HasPhysRegUse) {
1530     for (MachineOperand &MO : MI.operands()) {
1531       if (!MO.isReg() || !MO.readsReg())
1532         continue;
1533       Register Reg = MO.getReg();
1534       if (!Reg.isPhysical())
1535         continue;
1536       if (MRI->isReserved(Reg))
1537         continue;
1538       if (!usePhysReg(MI, Reg))
1539         MO.setIsKill(true);
1540     }
1541   }
1542 
1543   // Allocate virtreg uses and insert reloads as necessary.
1544   // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
1545   // times to ensure no operand is missed.
1546   bool HasUndefUse = false;
1547   bool ReArrangedImplicitMOs = true;
1548   while (ReArrangedImplicitMOs) {
1549     ReArrangedImplicitMOs = false;
1550     for (MachineOperand &MO : MI.operands()) {
1551       if (!MO.isReg() || !MO.isUse())
1552         continue;
1553       Register Reg = MO.getReg();
1554       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1555         continue;
1556 
1557       if (MO.isUndef()) {
1558         HasUndefUse = true;
1559         continue;
1560       }
1561 
1562       // Populate MayLiveAcrossBlocks in case the use block is allocated before
1563       // the def block (removing the vreg uses).
1564       mayLiveIn(Reg);
1565 
1566       assert(!MO.isInternalRead() && "Bundles not supported");
1567       assert(MO.readsReg() && "reading use");
1568       ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
1569       if (ReArrangedImplicitMOs)
1570         break;
1571     }
1572   }
1573 
1574   // Allocate undef operands. This is a separate step because in a situation
1575   // like  ` = OP undef %X, %X`    both operands need the same register assign
1576   // so we should perform the normal assignment first.
1577   if (HasUndefUse) {
1578     for (MachineOperand &MO : MI.all_uses()) {
1579       Register Reg = MO.getReg();
1580       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1581         continue;
1582 
1583       assert(MO.isUndef() && "Should only have undef virtreg uses left");
1584       allocVirtRegUndef(MO);
1585     }
1586   }
1587 
1588   // Free early clobbers.
1589   if (HasEarlyClobber) {
1590     for (MachineOperand &MO : reverse(MI.all_defs())) {
1591       if (!MO.isEarlyClobber())
1592         continue;
1593       assert(!MO.getSubReg() && "should be already handled in def processing");
1594 
1595       Register Reg = MO.getReg();
1596       if (!Reg)
1597         continue;
1598       if (Reg.isVirtual()) {
1599         assert(!shouldAllocateRegister(Reg));
1600         continue;
1601       }
1602       assert(Reg.isPhysical() && "should have register assigned");
1603 
1604       // We sometimes get odd situations like:
1605       //    early-clobber %x0 = INSTRUCTION %x0
1606       // which is semantically questionable as the early-clobber should
1607       // apply before the use. But in practice we consider the use to
1608       // happen before the early clobber now. Don't free the early clobber
1609       // register in this case.
1610       if (MI.readsRegister(Reg, TRI))
1611         continue;
1612 
1613       freePhysReg(Reg);
1614     }
1615   }
1616 
1617   LLVM_DEBUG(dbgs() << "<< " << MI);
1618   if (MI.isCopy() && MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
1619       MI.getNumOperands() == 2) {
1620     LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1621     Coalesced.push_back(&MI);
1622   }
1623 }
1624 
1625 void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1626   // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1627   // mostly constants and frame indices.
1628   assert(MI.isDebugValue() && "not a DBG_VALUE*");
1629   for (const auto &MO : MI.debug_operands()) {
1630     if (!MO.isReg())
1631       continue;
1632     Register Reg = MO.getReg();
1633     if (!Reg.isVirtual())
1634       continue;
1635     if (!shouldAllocateRegister(Reg))
1636       continue;
1637 
1638     // Already spilled to a stackslot?
1639     int SS = StackSlotForVirtReg[Reg];
1640     if (SS != -1) {
1641       // Modify DBG_VALUE now that the value is in a spill slot.
1642       updateDbgValueForSpill(MI, SS, Reg);
1643       LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1644       continue;
1645     }
1646 
1647     // See if this virtual register has already been allocated to a physical
1648     // register or spilled to a stack slot.
1649     LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1650     SmallVector<MachineOperand *> DbgOps;
1651     for (MachineOperand &Op : MI.getDebugOperandsForReg(Reg))
1652       DbgOps.push_back(&Op);
1653 
1654     if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1655       // Update every use of Reg within MI.
1656       for (auto &RegMO : DbgOps)
1657         setPhysReg(MI, *RegMO, LRI->PhysReg);
1658     } else {
1659       DanglingDbgValues[Reg].push_back(&MI);
1660     }
1661 
1662     // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1663     // that future spills of Reg will have DBG_VALUEs.
1664     LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1665   }
1666 }
1667 
1668 void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1669   MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1670   ++BundledMI;
1671   while (BundledMI->isBundledWithPred()) {
1672     for (MachineOperand &MO : BundledMI->operands()) {
1673       if (!MO.isReg())
1674         continue;
1675 
1676       Register Reg = MO.getReg();
1677       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1678         continue;
1679 
1680       DenseMap<Register, MCPhysReg>::iterator DI;
1681       DI = BundleVirtRegsMap.find(Reg);
1682       assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1683 
1684       setPhysReg(MI, MO, DI->second);
1685     }
1686 
1687     ++BundledMI;
1688   }
1689 }
1690 
1691 void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1692   this->MBB = &MBB;
1693   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1694 
1695   PosIndexes.unsetInitialized();
1696   RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1697   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1698 
1699   for (const auto &LiveReg : MBB.liveouts())
1700     setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1701 
1702   Coalesced.clear();
1703 
1704   // Traverse block in reverse order allocating instructions one by one.
1705   for (MachineInstr &MI : reverse(MBB)) {
1706     LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
1707 
1708     // Special handling for debug values. Note that they are not allowed to
1709     // affect codegen of the other instructions in any way.
1710     if (MI.isDebugValue()) {
1711       handleDebugValue(MI);
1712       continue;
1713     }
1714 
1715     allocateInstruction(MI);
1716 
1717     // Once BUNDLE header is assigned registers, same assignments need to be
1718     // done for bundled MIs.
1719     if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1720       handleBundle(MI);
1721     }
1722   }
1723 
1724   LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1725 
1726   // Spill all physical registers holding virtual registers now.
1727   LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1728   reloadAtBegin(MBB);
1729 
1730   // Erase all the coalesced copies. We are delaying it until now because
1731   // LiveVirtRegs might refer to the instrs.
1732   for (MachineInstr *MI : Coalesced)
1733     MBB.erase(MI);
1734   NumCoalesced += Coalesced.size();
1735 
1736   for (auto &UDBGPair : DanglingDbgValues) {
1737     for (MachineInstr *DbgValue : UDBGPair.second) {
1738       assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1739       // Nothing to do if the vreg was spilled in the meantime.
1740       if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1741         continue;
1742       LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1743                         << '\n');
1744       DbgValue->setDebugValueUndef();
1745     }
1746   }
1747   DanglingDbgValues.clear();
1748 
1749   LLVM_DEBUG(MBB.dump());
1750 }
1751 
1752 bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF) {
1753   LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1754                     << "********** Function: " << MF.getName() << '\n');
1755   MRI = &MF.getRegInfo();
1756   const TargetSubtargetInfo &STI = MF.getSubtarget();
1757   TRI = STI.getRegisterInfo();
1758   TII = STI.getInstrInfo();
1759   MFI = &MF.getFrameInfo();
1760   MRI->freezeReservedRegs();
1761   RegClassInfo.runOnMachineFunction(MF);
1762   unsigned NumRegUnits = TRI->getNumRegUnits();
1763   UsedInInstr.clear();
1764   UsedInInstr.setUniverse(NumRegUnits);
1765   PhysRegUses.clear();
1766   PhysRegUses.setUniverse(NumRegUnits);
1767 
1768   // initialize the virtual->physical register map to have a 'null'
1769   // mapping for all virtual registers
1770   unsigned NumVirtRegs = MRI->getNumVirtRegs();
1771   StackSlotForVirtReg.resize(NumVirtRegs);
1772   LiveVirtRegs.setUniverse(NumVirtRegs);
1773   MayLiveAcrossBlocks.clear();
1774   MayLiveAcrossBlocks.resize(NumVirtRegs);
1775 
1776   // Loop over all of the basic blocks, eliminating virtual register references
1777   for (MachineBasicBlock &MBB : MF)
1778     allocateBasicBlock(MBB);
1779 
1780   if (ClearVirtRegs) {
1781     // All machine operands and other references to virtual registers have been
1782     // replaced. Remove the virtual registers.
1783     MRI->clearVirtRegs();
1784   }
1785 
1786   StackSlotForVirtReg.clear();
1787   LiveDbgValueMap.clear();
1788   return true;
1789 }
1790 
1791 PreservedAnalyses RegAllocFastPass::run(MachineFunction &MF,
1792                                         MachineFunctionAnalysisManager &) {
1793   RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
1794   bool Changed = Impl.runOnMachineFunction(MF);
1795   if (!Changed)
1796     return PreservedAnalyses::all();
1797   auto PA = getMachineFunctionPassPreservedAnalyses();
1798   PA.preserveSet<CFGAnalyses>();
1799   return PA;
1800 }
1801 
1802 void RegAllocFastPass::printPipeline(
1803     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1804   bool PrintFilterName = Opts.FilterName != "all";
1805   bool PrintNoClearVRegs = !Opts.ClearVRegs;
1806   bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
1807 
1808   OS << "regallocfast";
1809   if (PrintFilterName || PrintNoClearVRegs) {
1810     OS << '<';
1811     if (PrintFilterName)
1812       OS << "filter=" << Opts.FilterName;
1813     if (PrintSemicolon)
1814       OS << ';';
1815     if (PrintNoClearVRegs)
1816       OS << "no-clear-vregs";
1817     OS << '>';
1818   }
1819 }
1820 
1821 FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
1822 
1823 FunctionPass *llvm::createFastRegisterAllocator(RegClassFilterFunc Ftor,
1824                                                 bool ClearVirtRegs) {
1825   return new RegAllocFast(Ftor, ClearVirtRegs);
1826 }
1827