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