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/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/IndexedMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/SparseSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegAllocRegistry.h"
31 #include "llvm/CodeGen/RegisterClassInfo.h"
32 #include "llvm/CodeGen/TargetInstrInfo.h"
33 #include "llvm/CodeGen/TargetOpcodes.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/MC/MCInstrDesc.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <cassert>
47 #include <tuple>
48 #include <vector>
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "regalloc"
53 
54 STATISTIC(NumStores, "Number of stores added");
55 STATISTIC(NumLoads , "Number of loads added");
56 STATISTIC(NumCoalesced, "Number of copies coalesced");
57 
58 static RegisterRegAlloc
59   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
60 
61 namespace {
62 
63   class RegAllocFast : public MachineFunctionPass {
64   public:
65     static char ID;
66 
67     RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {}
68 
69   private:
70     MachineFrameInfo *MFI;
71     MachineRegisterInfo *MRI;
72     const TargetRegisterInfo *TRI;
73     const TargetInstrInfo *TII;
74     RegisterClassInfo RegClassInfo;
75 
76     /// Basic block currently being allocated.
77     MachineBasicBlock *MBB;
78 
79     /// Maps virtual regs to the frame index where these values are spilled.
80     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
81 
82     /// Everything we know about a live virtual register.
83     struct LiveReg {
84       MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
85       unsigned VirtReg;                ///< Virtual register number.
86       MCPhysReg PhysReg = 0;           ///< Currently held here.
87       unsigned short LastOpNum = 0;    ///< OpNum on LastUse.
88       bool Dirty = false;              ///< Register needs spill.
89 
90       explicit LiveReg(unsigned VirtReg) : VirtReg(VirtReg) {}
91 
92       unsigned getSparseSetIndex() const {
93         return TargetRegisterInfo::virtReg2Index(VirtReg);
94       }
95     };
96 
97     using LiveRegMap = SparseSet<LiveReg>;
98     /// This map contains entries for each virtual register that is currently
99     /// available in a physical register.
100     LiveRegMap LiveVirtRegs;
101 
102     DenseMap<unsigned, SmallVector<MachineInstr *, 2>> LiveDbgValueMap;
103 
104     /// Has a bit set for every virtual register for which it was determined
105     /// that it is alive across blocks.
106     BitVector MayLiveAcrossBlocks;
107 
108     /// State of a physical register.
109     enum RegState {
110       /// A disabled register is not available for allocation, but an alias may
111       /// be in use. A register can only be moved out of the disabled state if
112       /// all aliases are disabled.
113       regDisabled,
114 
115       /// A free register is not currently in use and can be allocated
116       /// immediately without checking aliases.
117       regFree,
118 
119       /// A reserved register has been assigned explicitly (e.g., setting up a
120       /// call parameter), and it remains reserved until it is used.
121       regReserved
122 
123       /// A register state may also be a virtual register number, indication
124       /// that the physical register is currently allocated to a virtual
125       /// register. In that case, LiveVirtRegs contains the inverse mapping.
126     };
127 
128     /// Maps each physical register to a RegState enum or a virtual register.
129     std::vector<unsigned> PhysRegState;
130 
131     SmallVector<unsigned, 16> VirtDead;
132     SmallVector<MachineInstr *, 32> Coalesced;
133 
134     using RegUnitSet = SparseSet<uint16_t, identity<uint16_t>>;
135     /// Set of register units that are used in the current instruction, and so
136     /// cannot be allocated.
137     RegUnitSet UsedInInstr;
138 
139     void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
140 
141     /// Mark a physreg as used in this instruction.
142     void markRegUsedInInstr(MCPhysReg PhysReg) {
143       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
144         UsedInInstr.insert(*Units);
145     }
146 
147     /// Check if a physreg or any of its aliases are used in this instruction.
148     bool isRegUsedInInstr(MCPhysReg PhysReg) const {
149       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
150         if (UsedInInstr.count(*Units))
151           return true;
152       return false;
153     }
154 
155     enum : unsigned {
156       spillClean = 50,
157       spillDirty = 100,
158       spillImpossible = ~0u
159     };
160 
161   public:
162     StringRef getPassName() const override { return "Fast Register Allocator"; }
163 
164     void getAnalysisUsage(AnalysisUsage &AU) const override {
165       AU.setPreservesCFG();
166       MachineFunctionPass::getAnalysisUsage(AU);
167     }
168 
169     MachineFunctionProperties getRequiredProperties() const override {
170       return MachineFunctionProperties().set(
171           MachineFunctionProperties::Property::NoPHIs);
172     }
173 
174     MachineFunctionProperties getSetProperties() const override {
175       return MachineFunctionProperties().set(
176           MachineFunctionProperties::Property::NoVRegs);
177     }
178 
179   private:
180     bool runOnMachineFunction(MachineFunction &MF) override;
181 
182     void allocateBasicBlock(MachineBasicBlock &MBB);
183     void allocateInstruction(MachineInstr &MI);
184     void handleDebugValue(MachineInstr &MI);
185     void handleThroughOperands(MachineInstr &MI,
186                                SmallVectorImpl<unsigned> &VirtDead);
187     bool isLastUseOfLocalReg(const MachineOperand &MO) const;
188 
189     void addKillFlag(const LiveReg &LRI);
190     void killVirtReg(LiveReg &LR);
191     void killVirtReg(unsigned VirtReg);
192     void spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR);
193     void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
194 
195     void usePhysReg(MachineOperand &MO);
196     void definePhysReg(MachineBasicBlock::iterator MI, MCPhysReg PhysReg,
197                        RegState NewState);
198     unsigned calcSpillCost(MCPhysReg PhysReg) const;
199     void assignVirtToPhysReg(LiveReg &, MCPhysReg PhysReg);
200 
201     LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
202       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
203     }
204 
205     LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
206       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
207     }
208 
209     void allocVirtReg(MachineInstr &MI, LiveReg &LR, unsigned Hint);
210     void allocVirtRegUndef(MachineOperand &MO);
211     MCPhysReg defineVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg,
212                             unsigned Hint);
213     LiveReg &reloadVirtReg(MachineInstr &MI, unsigned OpNum, unsigned VirtReg,
214                            unsigned Hint);
215     void spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut);
216     bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
217 
218     int getStackSpaceFor(unsigned VirtReg);
219     void spill(MachineBasicBlock::iterator Before, unsigned VirtReg,
220                MCPhysReg AssignedReg, bool Kill);
221     void reload(MachineBasicBlock::iterator Before, unsigned VirtReg,
222                 MCPhysReg PhysReg);
223 
224     bool mayLiveOut(unsigned VirtReg);
225 
226     void dumpState();
227   };
228 
229 } // end anonymous namespace
230 
231 char RegAllocFast::ID = 0;
232 
233 INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
234                 false)
235 
236 void RegAllocFast::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
237   PhysRegState[PhysReg] = NewState;
238 }
239 
240 /// This allocates space for the specified virtual register to be held on the
241 /// stack.
242 int RegAllocFast::getStackSpaceFor(unsigned VirtReg) {
243   // Find the location Reg would belong...
244   int SS = StackSlotForVirtReg[VirtReg];
245   // Already has space allocated?
246   if (SS != -1)
247     return SS;
248 
249   // Allocate a new stack object for this spill location...
250   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
251   unsigned Size = TRI->getSpillSize(RC);
252   unsigned Align = TRI->getSpillAlignment(RC);
253   int FrameIdx = MFI->CreateSpillStackObject(Size, Align);
254 
255   // Assign the slot.
256   StackSlotForVirtReg[VirtReg] = FrameIdx;
257   return FrameIdx;
258 }
259 
260 /// Returns false if \p VirtReg is known to not live out of the current block.
261 bool RegAllocFast::mayLiveOut(unsigned VirtReg) {
262   if (MayLiveAcrossBlocks.test(TargetRegisterInfo::virtReg2Index(VirtReg))) {
263     // Cannot be live-out if there are no successors.
264     return !MBB->succ_empty();
265   }
266 
267   // If this block loops back to itself, it would be necessary to check whether
268   // the use comes after the def.
269   if (MBB->isSuccessor(MBB))
270     return true;
271 
272   // See if the first \p Limit uses of the register are all in the current
273   // block.
274   static const unsigned Limit = 8;
275   unsigned C = 0;
276   for (const MachineInstr &UseInst : MRI->reg_nodbg_instructions(VirtReg)) {
277     if (UseInst.getParent() != MBB || ++C >= Limit) {
278       MayLiveAcrossBlocks.set(TargetRegisterInfo::virtReg2Index(VirtReg));
279       // Cannot be live-out if there are no successors.
280       return !MBB->succ_empty();
281     }
282   }
283 
284   return false;
285 }
286 
287 /// Insert spill instruction for \p AssignedReg before \p Before. Update
288 /// DBG_VALUEs with \p VirtReg operands with the stack slot.
289 void RegAllocFast::spill(MachineBasicBlock::iterator Before, unsigned VirtReg,
290                          MCPhysReg AssignedReg, bool Kill) {
291   LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI)
292                     << " in " << printReg(AssignedReg, TRI));
293   int FI = getStackSpaceFor(VirtReg);
294   LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
295 
296   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
297   TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI);
298   ++NumStores;
299 
300   // If this register is used by DBG_VALUE then insert new DBG_VALUE to
301   // identify spilled location as the place to find corresponding variable's
302   // value.
303   SmallVectorImpl<MachineInstr *> &LRIDbgValues = LiveDbgValueMap[VirtReg];
304   for (MachineInstr *DBG : LRIDbgValues) {
305     MachineInstr *NewDV = buildDbgValueForSpill(*MBB, Before, *DBG, FI);
306     assert(NewDV->getParent() == MBB && "dangling parent pointer");
307     (void)NewDV;
308     LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
309   }
310   // Now this register is spilled there is should not be any DBG_VALUE
311   // pointing to this register because they are all pointing to spilled value
312   // now.
313   LRIDbgValues.clear();
314 }
315 
316 /// Insert reload instruction for \p PhysReg before \p Before.
317 void RegAllocFast::reload(MachineBasicBlock::iterator Before, unsigned VirtReg,
318                           MCPhysReg PhysReg) {
319   LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
320                     << printReg(PhysReg, TRI) << '\n');
321   int FI = getStackSpaceFor(VirtReg);
322   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
323   TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI);
324   ++NumLoads;
325 }
326 
327 /// Return true if MO is the only remaining reference to its virtual register,
328 /// and it is guaranteed to be a block-local register.
329 bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand &MO) const {
330   // If the register has ever been spilled or reloaded, we conservatively assume
331   // it is a global register used in multiple blocks.
332   if (StackSlotForVirtReg[MO.getReg()] != -1)
333     return false;
334 
335   // Check that the use/def chain has exactly one operand - MO.
336   MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
337   if (&*I != &MO)
338     return false;
339   return ++I == MRI->reg_nodbg_end();
340 }
341 
342 /// Set kill flags on last use of a virtual register.
343 void RegAllocFast::addKillFlag(const LiveReg &LR) {
344   if (!LR.LastUse) return;
345   MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
346   if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
347     if (MO.getReg() == LR.PhysReg)
348       MO.setIsKill();
349     // else, don't do anything we are problably redefining a
350     // subreg of this register and given we don't track which
351     // lanes are actually dead, we cannot insert a kill flag here.
352     // Otherwise we may end up in a situation like this:
353     // ... = (MO) physreg:sub1, implicit killed physreg
354     // ... <== Here we would allow later pass to reuse physreg:sub1
355     //         which is potentially wrong.
356     // LR:sub0 = ...
357     // ... = LR.sub1 <== This is going to use physreg:sub1
358   }
359 }
360 
361 /// Mark virtreg as no longer available.
362 void RegAllocFast::killVirtReg(LiveReg &LR) {
363   addKillFlag(LR);
364   assert(PhysRegState[LR.PhysReg] == LR.VirtReg &&
365          "Broken RegState mapping");
366   setPhysRegState(LR.PhysReg, regFree);
367   LR.PhysReg = 0;
368 }
369 
370 /// Mark virtreg as no longer available.
371 void RegAllocFast::killVirtReg(unsigned VirtReg) {
372   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
373          "killVirtReg needs a virtual register");
374   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
375   if (LRI != LiveVirtRegs.end() && LRI->PhysReg)
376     killVirtReg(*LRI);
377 }
378 
379 /// This method spills the value specified by VirtReg into the corresponding
380 /// stack slot if needed.
381 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
382                                 unsigned VirtReg) {
383   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
384          "Spilling a physical register is illegal!");
385   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
386   assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
387          "Spilling unmapped virtual register");
388   spillVirtReg(MI, *LRI);
389 }
390 
391 /// Do the actual work of spilling.
392 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI, LiveReg &LR) {
393   assert(PhysRegState[LR.PhysReg] == LR.VirtReg && "Broken RegState mapping");
394 
395   if (LR.Dirty) {
396     // If this physreg is used by the instruction, we want to kill it on the
397     // instruction, not on the spill.
398     bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
399     LR.Dirty = false;
400 
401     spill(MI, LR.VirtReg, LR.PhysReg, SpillKill);
402 
403     if (SpillKill)
404       LR.LastUse = nullptr; // Don't kill register again
405   }
406   killVirtReg(LR);
407 }
408 
409 /// Spill all dirty virtregs without killing them.
410 void RegAllocFast::spillAll(MachineBasicBlock::iterator MI, bool OnlyLiveOut) {
411   if (LiveVirtRegs.empty())
412     return;
413   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
414   // of spilling here is deterministic, if arbitrary.
415   for (LiveReg &LR : LiveVirtRegs) {
416     if (!LR.PhysReg)
417       continue;
418     if (OnlyLiveOut && !mayLiveOut(LR.VirtReg))
419       continue;
420     spillVirtReg(MI, LR);
421   }
422   LiveVirtRegs.clear();
423 }
424 
425 /// Handle the direct use of a physical register.  Check that the register is
426 /// not used by a virtreg. Kill the physreg, marking it free. This may add
427 /// implicit kills to MO->getParent() and invalidate MO.
428 void RegAllocFast::usePhysReg(MachineOperand &MO) {
429   // Ignore undef uses.
430   if (MO.isUndef())
431     return;
432 
433   unsigned PhysReg = MO.getReg();
434   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
435          "Bad usePhysReg operand");
436 
437   markRegUsedInInstr(PhysReg);
438   switch (PhysRegState[PhysReg]) {
439   case regDisabled:
440     break;
441   case regReserved:
442     PhysRegState[PhysReg] = regFree;
443     LLVM_FALLTHROUGH;
444   case regFree:
445     MO.setIsKill();
446     return;
447   default:
448     // The physreg was allocated to a virtual register. That means the value we
449     // wanted has been clobbered.
450     llvm_unreachable("Instruction uses an allocated register");
451   }
452 
453   // Maybe a superregister is reserved?
454   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
455     MCPhysReg Alias = *AI;
456     switch (PhysRegState[Alias]) {
457     case regDisabled:
458       break;
459     case regReserved:
460       // Either PhysReg is a subregister of Alias and we mark the
461       // whole register as free, or PhysReg is the superregister of
462       // Alias and we mark all the aliases as disabled before freeing
463       // PhysReg.
464       // In the latter case, since PhysReg was disabled, this means that
465       // its value is defined only by physical sub-registers. This check
466       // is performed by the assert of the default case in this loop.
467       // Note: The value of the superregister may only be partial
468       // defined, that is why regDisabled is a valid state for aliases.
469       assert((TRI->isSuperRegister(PhysReg, Alias) ||
470               TRI->isSuperRegister(Alias, PhysReg)) &&
471              "Instruction is not using a subregister of a reserved register");
472       LLVM_FALLTHROUGH;
473     case regFree:
474       if (TRI->isSuperRegister(PhysReg, Alias)) {
475         // Leave the superregister in the working set.
476         setPhysRegState(Alias, regFree);
477         MO.getParent()->addRegisterKilled(Alias, TRI, true);
478         return;
479       }
480       // Some other alias was in the working set - clear it.
481       setPhysRegState(Alias, regDisabled);
482       break;
483     default:
484       llvm_unreachable("Instruction uses an alias of an allocated register");
485     }
486   }
487 
488   // All aliases are disabled, bring register into working set.
489   setPhysRegState(PhysReg, regFree);
490   MO.setIsKill();
491 }
492 
493 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
494 /// similar to defineVirtReg except the physreg is reserved instead of
495 /// allocated.
496 void RegAllocFast::definePhysReg(MachineBasicBlock::iterator MI,
497                                  MCPhysReg PhysReg, RegState NewState) {
498   markRegUsedInInstr(PhysReg);
499   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
500   case regDisabled:
501     break;
502   default:
503     spillVirtReg(MI, VirtReg);
504     LLVM_FALLTHROUGH;
505   case regFree:
506   case regReserved:
507     setPhysRegState(PhysReg, NewState);
508     return;
509   }
510 
511   // This is a disabled register, disable all aliases.
512   setPhysRegState(PhysReg, NewState);
513   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
514     MCPhysReg Alias = *AI;
515     switch (unsigned VirtReg = PhysRegState[Alias]) {
516     case regDisabled:
517       break;
518     default:
519       spillVirtReg(MI, VirtReg);
520       LLVM_FALLTHROUGH;
521     case regFree:
522     case regReserved:
523       setPhysRegState(Alias, regDisabled);
524       if (TRI->isSuperRegister(PhysReg, Alias))
525         return;
526       break;
527     }
528   }
529 }
530 
531 /// Return the cost of spilling clearing out PhysReg and aliases so it is free
532 /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
533 /// disabled - it can be allocated directly.
534 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
535 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
536   if (isRegUsedInInstr(PhysReg)) {
537     LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI)
538                       << " is already used in instr.\n");
539     return spillImpossible;
540   }
541   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
542   case regDisabled:
543     break;
544   case regFree:
545     return 0;
546   case regReserved:
547     LLVM_DEBUG(dbgs() << printReg(VirtReg, TRI) << " corresponding "
548                       << printReg(PhysReg, TRI) << " is reserved already.\n");
549     return spillImpossible;
550   default: {
551     LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
552     assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
553            "Missing VirtReg entry");
554     return LRI->Dirty ? spillDirty : spillClean;
555   }
556   }
557 
558   // This is a disabled register, add up cost of aliases.
559   LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is disabled.\n");
560   unsigned Cost = 0;
561   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
562     MCPhysReg Alias = *AI;
563     switch (unsigned VirtReg = PhysRegState[Alias]) {
564     case regDisabled:
565       break;
566     case regFree:
567       ++Cost;
568       break;
569     case regReserved:
570       return spillImpossible;
571     default: {
572       LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
573       assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
574              "Missing VirtReg entry");
575       Cost += LRI->Dirty ? spillDirty : spillClean;
576       break;
577     }
578     }
579   }
580   return Cost;
581 }
582 
583 /// This method updates local state so that we know that PhysReg is the
584 /// proper container for VirtReg now.  The physical register must not be used
585 /// for anything else when this is called.
586 void RegAllocFast::assignVirtToPhysReg(LiveReg &LR, MCPhysReg PhysReg) {
587   unsigned VirtReg = LR.VirtReg;
588   LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
589                     << printReg(PhysReg, TRI) << '\n');
590   assert(LR.PhysReg == 0 && "Already assigned a physreg");
591   assert(PhysReg != 0 && "Trying to assign no register");
592   LR.PhysReg = PhysReg;
593   setPhysRegState(PhysReg, VirtReg);
594 }
595 
596 /// Allocates a physical register for VirtReg.
597 void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR, unsigned Hint) {
598   const unsigned VirtReg = LR.VirtReg;
599 
600   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
601          "Can only allocate virtual registers");
602 
603   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
604   LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
605                     << " in class " << TRI->getRegClassName(&RC)
606                     << " with hint " << printReg(Hint, TRI) << '\n');
607 
608   // Take hint when possible.
609   if (TargetRegisterInfo::isPhysicalRegister(Hint) &&
610       MRI->isAllocatable(Hint) && RC.contains(Hint)) {
611     // Ignore the hint if we would have to spill a dirty register.
612     unsigned Cost = calcSpillCost(Hint);
613     if (Cost < spillDirty) {
614       if (Cost)
615         definePhysReg(MI, Hint, regFree);
616       assignVirtToPhysReg(LR, Hint);
617       return;
618     }
619   }
620 
621   MCPhysReg BestReg = 0;
622   unsigned BestCost = spillImpossible;
623   ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
624   for (MCPhysReg PhysReg : AllocationOrder) {
625     LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
626     unsigned Cost = calcSpillCost(PhysReg);
627     LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
628     // Immediate take a register with cost 0.
629     if (Cost == 0) {
630       assignVirtToPhysReg(LR, PhysReg);
631       return;
632     }
633     if (Cost < BestCost) {
634       BestReg = PhysReg;
635       BestCost = Cost;
636     }
637   }
638 
639   if (!BestReg) {
640     // Nothing we can do: Report an error and keep going with an invalid
641     // allocation.
642     if (MI.isInlineAsm())
643       MI.emitError("inline assembly requires more registers than available");
644     else
645       MI.emitError("ran out of registers during register allocation");
646     definePhysReg(MI, *AllocationOrder.begin(), regFree);
647     assignVirtToPhysReg(LR, *AllocationOrder.begin());
648     return;
649   }
650 
651   definePhysReg(MI, BestReg, regFree);
652   assignVirtToPhysReg(LR, BestReg);
653 }
654 
655 void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
656   assert(MO.isUndef() && "expected undef use");
657   unsigned VirtReg = MO.getReg();
658   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Expected virtreg");
659 
660   LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
661   MCPhysReg PhysReg;
662   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
663     PhysReg = LRI->PhysReg;
664   } else {
665     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
666     ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
667     assert(!AllocationOrder.empty() && "Allocation order must not be empty");
668     PhysReg = AllocationOrder[0];
669   }
670 
671   unsigned SubRegIdx = MO.getSubReg();
672   if (SubRegIdx != 0) {
673     PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
674     MO.setSubReg(0);
675   }
676   MO.setReg(PhysReg);
677   MO.setIsRenamable(true);
678 }
679 
680 /// Allocates a register for VirtReg and mark it as dirty.
681 MCPhysReg RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
682                                       unsigned VirtReg, unsigned Hint) {
683   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
684          "Not a virtual register");
685   LiveRegMap::iterator LRI;
686   bool New;
687   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
688   if (!LRI->PhysReg) {
689     // If there is no hint, peek at the only use of this register.
690     if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
691         MRI->hasOneNonDBGUse(VirtReg)) {
692       const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
693       // It's a copy, use the destination register as a hint.
694       if (UseMI.isCopyLike())
695         Hint = UseMI.getOperand(0).getReg();
696     }
697     allocVirtReg(MI, *LRI, Hint);
698   } else if (LRI->LastUse) {
699     // Redefining a live register - kill at the last use, unless it is this
700     // instruction defining VirtReg multiple times.
701     if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
702       addKillFlag(*LRI);
703   }
704   assert(LRI->PhysReg && "Register not assigned");
705   LRI->LastUse = &MI;
706   LRI->LastOpNum = OpNum;
707   LRI->Dirty = true;
708   markRegUsedInInstr(LRI->PhysReg);
709   return LRI->PhysReg;
710 }
711 
712 /// Make sure VirtReg is available in a physreg and return it.
713 RegAllocFast::LiveReg &RegAllocFast::reloadVirtReg(MachineInstr &MI,
714                                                    unsigned OpNum,
715                                                    unsigned VirtReg,
716                                                    unsigned Hint) {
717   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
718          "Not a virtual register");
719   LiveRegMap::iterator LRI;
720   bool New;
721   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
722   MachineOperand &MO = MI.getOperand(OpNum);
723   if (!LRI->PhysReg) {
724     allocVirtReg(MI, *LRI, Hint);
725     reload(MI, VirtReg, LRI->PhysReg);
726   } else if (LRI->Dirty) {
727     if (isLastUseOfLocalReg(MO)) {
728       LLVM_DEBUG(dbgs() << "Killing last use: " << MO << '\n');
729       if (MO.isUse())
730         MO.setIsKill();
731       else
732         MO.setIsDead();
733     } else if (MO.isKill()) {
734       LLVM_DEBUG(dbgs() << "Clearing dubious kill: " << MO << '\n');
735       MO.setIsKill(false);
736     } else if (MO.isDead()) {
737       LLVM_DEBUG(dbgs() << "Clearing dubious dead: " << MO << '\n');
738       MO.setIsDead(false);
739     }
740   } else if (MO.isKill()) {
741     // We must remove kill flags from uses of reloaded registers because the
742     // register would be killed immediately, and there might be a second use:
743     //   %foo = OR killed %x, %x
744     // This would cause a second reload of %x into a different register.
745     LLVM_DEBUG(dbgs() << "Clearing clean kill: " << MO << '\n');
746     MO.setIsKill(false);
747   } else if (MO.isDead()) {
748     LLVM_DEBUG(dbgs() << "Clearing clean dead: " << MO << '\n');
749     MO.setIsDead(false);
750   }
751   assert(LRI->PhysReg && "Register not assigned");
752   LRI->LastUse = &MI;
753   LRI->LastOpNum = OpNum;
754   markRegUsedInInstr(LRI->PhysReg);
755   return *LRI;
756 }
757 
758 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
759 /// may invalidate any operand pointers.  Return true if the operand kills its
760 /// register.
761 bool RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
762                               MCPhysReg PhysReg) {
763   bool Dead = MO.isDead();
764   if (!MO.getSubReg()) {
765     MO.setReg(PhysReg);
766     MO.setIsRenamable(true);
767     return MO.isKill() || Dead;
768   }
769 
770   // Handle subregister index.
771   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
772   MO.setIsRenamable(true);
773   MO.setSubReg(0);
774 
775   // A kill flag implies killing the full register. Add corresponding super
776   // register kill.
777   if (MO.isKill()) {
778     MI.addRegisterKilled(PhysReg, TRI, true);
779     return true;
780   }
781 
782   // A <def,read-undef> of a sub-register requires an implicit def of the full
783   // register.
784   if (MO.isDef() && MO.isUndef())
785     MI.addRegisterDefined(PhysReg, TRI);
786 
787   return Dead;
788 }
789 
790 // Handles special instruction operand like early clobbers and tied ops when
791 // there are additional physreg defines.
792 void RegAllocFast::handleThroughOperands(MachineInstr &MI,
793                                          SmallVectorImpl<unsigned> &VirtDead) {
794   LLVM_DEBUG(dbgs() << "Scanning for through registers:");
795   SmallSet<unsigned, 8> ThroughRegs;
796   for (const MachineOperand &MO : MI.operands()) {
797     if (!MO.isReg()) continue;
798     unsigned Reg = MO.getReg();
799     if (!TargetRegisterInfo::isVirtualRegister(Reg))
800       continue;
801     if (MO.isEarlyClobber() || (MO.isUse() && MO.isTied()) ||
802         (MO.getSubReg() && MI.readsVirtualRegister(Reg))) {
803       if (ThroughRegs.insert(Reg).second)
804         LLVM_DEBUG(dbgs() << ' ' << printReg(Reg));
805     }
806   }
807 
808   // If any physreg defines collide with preallocated through registers,
809   // we must spill and reallocate.
810   LLVM_DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
811   for (const MachineOperand &MO : MI.operands()) {
812     if (!MO.isReg() || !MO.isDef()) continue;
813     unsigned Reg = MO.getReg();
814     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
815     markRegUsedInInstr(Reg);
816     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
817       if (ThroughRegs.count(PhysRegState[*AI]))
818         definePhysReg(MI, *AI, regFree);
819     }
820   }
821 
822   SmallVector<unsigned, 8> PartialDefs;
823   LLVM_DEBUG(dbgs() << "Allocating tied uses.\n");
824   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
825     MachineOperand &MO = MI.getOperand(I);
826     if (!MO.isReg()) continue;
827     unsigned Reg = MO.getReg();
828     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
829     if (MO.isUse()) {
830       if (!MO.isTied()) continue;
831       LLVM_DEBUG(dbgs() << "Operand " << I << "(" << MO
832                         << ") is tied to operand " << MI.findTiedOperandIdx(I)
833                         << ".\n");
834       LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
835       MCPhysReg PhysReg = LR.PhysReg;
836       setPhysReg(MI, MO, PhysReg);
837       // Note: we don't update the def operand yet. That would cause the normal
838       // def-scan to attempt spilling.
839     } else if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) {
840       LLVM_DEBUG(dbgs() << "Partial redefine: " << MO << '\n');
841       // Reload the register, but don't assign to the operand just yet.
842       // That would confuse the later phys-def processing pass.
843       LiveReg &LR = reloadVirtReg(MI, I, Reg, 0);
844       PartialDefs.push_back(LR.PhysReg);
845     }
846   }
847 
848   LLVM_DEBUG(dbgs() << "Allocating early clobbers.\n");
849   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
850     const MachineOperand &MO = MI.getOperand(I);
851     if (!MO.isReg()) continue;
852     unsigned Reg = MO.getReg();
853     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
854     if (!MO.isEarlyClobber())
855       continue;
856     // Note: defineVirtReg may invalidate MO.
857     MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, 0);
858     if (setPhysReg(MI, MI.getOperand(I), PhysReg))
859       VirtDead.push_back(Reg);
860   }
861 
862   // Restore UsedInInstr to a state usable for allocating normal virtual uses.
863   UsedInInstr.clear();
864   for (const MachineOperand &MO : MI.operands()) {
865     if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
866     unsigned Reg = MO.getReg();
867     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
868     LLVM_DEBUG(dbgs() << "\tSetting " << printReg(Reg, TRI)
869                       << " as used in instr\n");
870     markRegUsedInInstr(Reg);
871   }
872 
873   // Also mark PartialDefs as used to avoid reallocation.
874   for (unsigned PartialDef : PartialDefs)
875     markRegUsedInInstr(PartialDef);
876 }
877 
878 #ifndef NDEBUG
879 void RegAllocFast::dumpState() {
880   for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
881     if (PhysRegState[Reg] == regDisabled) continue;
882     dbgs() << " " << printReg(Reg, TRI);
883     switch(PhysRegState[Reg]) {
884     case regFree:
885       break;
886     case regReserved:
887       dbgs() << "*";
888       break;
889     default: {
890       dbgs() << '=' << printReg(PhysRegState[Reg]);
891       LiveRegMap::iterator LRI = findLiveVirtReg(PhysRegState[Reg]);
892       assert(LRI != LiveVirtRegs.end() && LRI->PhysReg &&
893              "Missing VirtReg entry");
894       if (LRI->Dirty)
895         dbgs() << "*";
896       assert(LRI->PhysReg == Reg && "Bad inverse map");
897       break;
898     }
899     }
900   }
901   dbgs() << '\n';
902   // Check that LiveVirtRegs is the inverse.
903   for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
904        e = LiveVirtRegs.end(); i != e; ++i) {
905     if (!i->PhysReg)
906       continue;
907     assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
908            "Bad map key");
909     assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
910            "Bad map value");
911     assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
912   }
913 }
914 #endif
915 
916 void RegAllocFast::allocateInstruction(MachineInstr &MI) {
917   const MCInstrDesc &MCID = MI.getDesc();
918 
919   // If this is a copy, we may be able to coalesce.
920   unsigned CopySrcReg = 0;
921   unsigned CopyDstReg = 0;
922   unsigned CopySrcSub = 0;
923   unsigned CopyDstSub = 0;
924   if (MI.isCopy()) {
925     CopyDstReg = MI.getOperand(0).getReg();
926     CopySrcReg = MI.getOperand(1).getReg();
927     CopyDstSub = MI.getOperand(0).getSubReg();
928     CopySrcSub = MI.getOperand(1).getSubReg();
929   }
930 
931   // Track registers used by instruction.
932   UsedInInstr.clear();
933 
934   // First scan.
935   // Mark physreg uses and early clobbers as used.
936   // Find the end of the virtreg operands
937   unsigned VirtOpEnd = 0;
938   bool hasTiedOps = false;
939   bool hasEarlyClobbers = false;
940   bool hasPartialRedefs = false;
941   bool hasPhysDefs = false;
942   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
943     MachineOperand &MO = MI.getOperand(i);
944     // Make sure MRI knows about registers clobbered by regmasks.
945     if (MO.isRegMask()) {
946       MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
947       continue;
948     }
949     if (!MO.isReg()) continue;
950     unsigned Reg = MO.getReg();
951     if (!Reg) continue;
952     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
953       VirtOpEnd = i+1;
954       if (MO.isUse()) {
955         hasTiedOps = hasTiedOps ||
956                             MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
957       } else {
958         if (MO.isEarlyClobber())
959           hasEarlyClobbers = true;
960         if (MO.getSubReg() && MI.readsVirtualRegister(Reg))
961           hasPartialRedefs = true;
962       }
963       continue;
964     }
965     if (!MRI->isAllocatable(Reg)) continue;
966     if (MO.isUse()) {
967       usePhysReg(MO);
968     } else if (MO.isEarlyClobber()) {
969       definePhysReg(MI, Reg,
970                     (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
971       hasEarlyClobbers = true;
972     } else
973       hasPhysDefs = true;
974   }
975 
976   // The instruction may have virtual register operands that must be allocated
977   // the same register at use-time and def-time: early clobbers and tied
978   // operands. If there are also physical defs, these registers must avoid
979   // both physical defs and uses, making them more constrained than normal
980   // operands.
981   // Similarly, if there are multiple defs and tied operands, we must make
982   // sure the same register is allocated to uses and defs.
983   // We didn't detect inline asm tied operands above, so just make this extra
984   // pass for all inline asm.
985   if (MI.isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
986       (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
987     handleThroughOperands(MI, VirtDead);
988     // Don't attempt coalescing when we have funny stuff going on.
989     CopyDstReg = 0;
990     // Pretend we have early clobbers so the use operands get marked below.
991     // This is not necessary for the common case of a single tied use.
992     hasEarlyClobbers = true;
993   }
994 
995   // Second scan.
996   // Allocate virtreg uses.
997   bool HasUndefUse = false;
998   for (unsigned I = 0; I != VirtOpEnd; ++I) {
999     MachineOperand &MO = MI.getOperand(I);
1000     if (!MO.isReg()) continue;
1001     unsigned Reg = MO.getReg();
1002     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
1003     if (MO.isUse()) {
1004       if (MO.isUndef()) {
1005         HasUndefUse = true;
1006         // There is no need to allocate a register for an undef use.
1007         continue;
1008       }
1009       LiveReg &LR = reloadVirtReg(MI, I, Reg, CopyDstReg);
1010       MCPhysReg PhysReg = LR.PhysReg;
1011       CopySrcReg = (CopySrcReg == Reg || CopySrcReg == PhysReg) ? PhysReg : 0;
1012       if (setPhysReg(MI, MO, PhysReg))
1013         killVirtReg(LR);
1014     }
1015   }
1016 
1017   // Allocate undef operands. This is a separate step because in a situation
1018   // like  ` = OP undef %X, %X`    both operands need the same register assign
1019   // so we should perform the normal assignment first.
1020   if (HasUndefUse) {
1021     for (MachineOperand &MO : MI.uses()) {
1022       if (!MO.isReg() || !MO.isUse())
1023         continue;
1024       unsigned Reg = MO.getReg();
1025       if (!TargetRegisterInfo::isVirtualRegister(Reg))
1026         continue;
1027 
1028       assert(MO.isUndef() && "Should only have undef virtreg uses left");
1029       allocVirtRegUndef(MO);
1030     }
1031   }
1032 
1033   // Track registers defined by instruction - early clobbers and tied uses at
1034   // this point.
1035   UsedInInstr.clear();
1036   if (hasEarlyClobbers) {
1037     for (const MachineOperand &MO : MI.operands()) {
1038       if (!MO.isReg()) continue;
1039       unsigned Reg = MO.getReg();
1040       if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1041       // Look for physreg defs and tied uses.
1042       if (!MO.isDef() && !MO.isTied()) continue;
1043       markRegUsedInInstr(Reg);
1044     }
1045   }
1046 
1047   unsigned DefOpEnd = MI.getNumOperands();
1048   if (MI.isCall()) {
1049     // Spill all virtregs before a call. This serves one purpose: If an
1050     // exception is thrown, the landing pad is going to expect to find
1051     // registers in their spill slots.
1052     // Note: although this is appealing to just consider all definitions
1053     // as call-clobbered, this is not correct because some of those
1054     // definitions may be used later on and we do not want to reuse
1055     // those for virtual registers in between.
1056     LLVM_DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
1057     spillAll(MI, /*OnlyLiveOut*/ false);
1058   }
1059 
1060   // Third scan.
1061   // Mark all physreg defs as used before allocating virtreg defs.
1062   for (unsigned I = 0; I != DefOpEnd; ++I) {
1063     const MachineOperand &MO = MI.getOperand(I);
1064     if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1065       continue;
1066     unsigned Reg = MO.getReg();
1067 
1068     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg) ||
1069         !MRI->isAllocatable(Reg))
1070       continue;
1071     definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
1072   }
1073 
1074   // Fourth scan.
1075   // Allocate defs and collect dead defs.
1076   for (unsigned I = 0; I != DefOpEnd; ++I) {
1077     const MachineOperand &MO = MI.getOperand(I);
1078     if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1079       continue;
1080     unsigned Reg = MO.getReg();
1081 
1082     // We have already dealt with phys regs in the previous scan.
1083     if (TargetRegisterInfo::isPhysicalRegister(Reg))
1084       continue;
1085     MCPhysReg PhysReg = defineVirtReg(MI, I, Reg, CopySrcReg);
1086     if (setPhysReg(MI, MI.getOperand(I), PhysReg)) {
1087       VirtDead.push_back(Reg);
1088       CopyDstReg = 0; // cancel coalescing;
1089     } else
1090       CopyDstReg = (CopyDstReg == Reg || CopyDstReg == PhysReg) ? PhysReg : 0;
1091   }
1092 
1093   // Kill dead defs after the scan to ensure that multiple defs of the same
1094   // register are allocated identically. We didn't need to do this for uses
1095   // because we are crerating our own kill flags, and they are always at the
1096   // last use.
1097   for (unsigned VirtReg : VirtDead)
1098     killVirtReg(VirtReg);
1099   VirtDead.clear();
1100 
1101   LLVM_DEBUG(dbgs() << "<< " << MI);
1102   if (CopyDstReg && CopyDstReg == CopySrcReg && CopyDstSub == CopySrcSub) {
1103     LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1104     Coalesced.push_back(&MI);
1105   }
1106 }
1107 
1108 void RegAllocFast::handleDebugValue(MachineInstr &MI) {
1109   MachineOperand &MO = MI.getOperand(0);
1110 
1111   // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1112   // mostly constants and frame indices.
1113   if (!MO.isReg())
1114     return;
1115   unsigned Reg = MO.getReg();
1116   if (!TargetRegisterInfo::isVirtualRegister(Reg))
1117     return;
1118 
1119   // See if this virtual register has already been allocated to a physical
1120   // register or spilled to a stack slot.
1121   LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1122   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1123     setPhysReg(MI, MO, LRI->PhysReg);
1124   } else {
1125     int SS = StackSlotForVirtReg[Reg];
1126     if (SS != -1) {
1127       // Modify DBG_VALUE now that the value is in a spill slot.
1128       updateDbgValueForSpill(MI, SS);
1129       LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << MI);
1130       return;
1131     }
1132 
1133     // We can't allocate a physreg for a DebugValue, sorry!
1134     LLVM_DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
1135     MO.setReg(0);
1136   }
1137 
1138   // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1139   // that future spills of Reg will have DBG_VALUEs.
1140   LiveDbgValueMap[Reg].push_back(&MI);
1141 }
1142 
1143 void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
1144   this->MBB = &MBB;
1145   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1146 
1147   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
1148   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1149 
1150   MachineBasicBlock::iterator MII = MBB.begin();
1151 
1152   // Add live-in registers as live.
1153   for (const MachineBasicBlock::RegisterMaskPair LI : MBB.liveins())
1154     if (MRI->isAllocatable(LI.PhysReg))
1155       definePhysReg(MII, LI.PhysReg, regReserved);
1156 
1157   VirtDead.clear();
1158   Coalesced.clear();
1159 
1160   // Otherwise, sequentially allocate each instruction in the MBB.
1161   for (MachineInstr &MI : MBB) {
1162     LLVM_DEBUG(
1163       dbgs() << "\n>> " << MI << "Regs:";
1164       dumpState()
1165     );
1166 
1167     // Special handling for debug values. Note that they are not allowed to
1168     // affect codegen of the other instructions in any way.
1169     if (MI.isDebugValue()) {
1170       handleDebugValue(MI);
1171       continue;
1172     }
1173 
1174     allocateInstruction(MI);
1175   }
1176 
1177   // Spill all physical registers holding virtual registers now.
1178   LLVM_DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1179   spillAll(MBB.getFirstTerminator(), /*OnlyLiveOut*/ true);
1180 
1181   // Erase all the coalesced copies. We are delaying it until now because
1182   // LiveVirtRegs might refer to the instrs.
1183   for (MachineInstr *MI : Coalesced)
1184     MBB.erase(MI);
1185   NumCoalesced += Coalesced.size();
1186 
1187   LLVM_DEBUG(MBB.dump());
1188 }
1189 
1190 bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
1191   LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1192                     << "********** Function: " << MF.getName() << '\n');
1193   MRI = &MF.getRegInfo();
1194   const TargetSubtargetInfo &STI = MF.getSubtarget();
1195   TRI = STI.getRegisterInfo();
1196   TII = STI.getInstrInfo();
1197   MFI = &MF.getFrameInfo();
1198   MRI->freezeReservedRegs(MF);
1199   RegClassInfo.runOnMachineFunction(MF);
1200   UsedInInstr.clear();
1201   UsedInInstr.setUniverse(TRI->getNumRegUnits());
1202 
1203   // initialize the virtual->physical register map to have a 'null'
1204   // mapping for all virtual registers
1205   unsigned NumVirtRegs = MRI->getNumVirtRegs();
1206   StackSlotForVirtReg.resize(NumVirtRegs);
1207   LiveVirtRegs.setUniverse(NumVirtRegs);
1208   MayLiveAcrossBlocks.clear();
1209   MayLiveAcrossBlocks.resize(NumVirtRegs);
1210 
1211   // Loop over all of the basic blocks, eliminating virtual register references
1212   for (MachineBasicBlock &MBB : MF)
1213     allocateBasicBlock(MBB);
1214 
1215   // All machine operands and other references to virtual registers have been
1216   // replaced. Remove the virtual registers.
1217   MRI->clearVirtRegs();
1218 
1219   StackSlotForVirtReg.clear();
1220   LiveDbgValueMap.clear();
1221   return true;
1222 }
1223 
1224 FunctionPass *llvm::createFastRegisterAllocator() {
1225   return new RegAllocFast();
1226 }
1227