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