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 = buildDbgValueForSpill(*MBB, Before, *DBG, FI);
412     assert(NewDV->getParent() == MBB && "dangling parent pointer");
413     (void)NewDV;
414     LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
415 
416     if (LiveOut) {
417       // We need to insert a DBG_VALUE at the end of the block if the spill slot
418       // is live out, but there is another use of the value after the
419       // spill. This will allow LiveDebugValues to see the correct live out
420       // value to propagate to the successors.
421       MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
422       MBB->insert(FirstTerm, ClonedDV);
423       LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
424     }
425 
426     // Rewrite unassigned dbg_values to use the stack slot.
427     // TODO We can potentially do this for list debug values as well if we know
428     // how the dbg_values are getting unassigned.
429     if (DBG->isNonListDebugValue()) {
430       MachineOperand &MO = DBG->getDebugOperand(0);
431       if (MO.isReg() && MO.getReg() == 0) {
432         updateDbgValueForSpill(*DBG, FI);
433       }
434     }
435   }
436   // Now this register is spilled there is should not be any DBG_VALUE
437   // pointing to this register because they are all pointing to spilled value
438   // now.
439   LRIDbgValues.clear();
440 }
441 
442 /// Insert reload instruction for \p PhysReg before \p Before.
443 void RegAllocFast::reload(MachineBasicBlock::iterator Before, Register VirtReg,
444                           MCPhysReg PhysReg) {
445   LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
446                     << printReg(PhysReg, TRI) << '\n');
447   int FI = getStackSpaceFor(VirtReg);
448   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
449   TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI);
450   ++NumLoads;
451 }
452 
453 /// Get basic block begin insertion point.
454 /// This is not just MBB.begin() because surprisingly we have EH_LABEL
455 /// instructions marking the begin of a basic block. This means we must insert
456 /// new instructions after such labels...
457 MachineBasicBlock::iterator
458 RegAllocFast::getMBBBeginInsertionPoint(
459   MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
460   MachineBasicBlock::iterator I = MBB.begin();
461   while (I != MBB.end()) {
462     if (I->isLabel()) {
463       ++I;
464       continue;
465     }
466 
467     // Most reloads should be inserted after prolog instructions.
468     if (!TII->isBasicBlockPrologue(*I))
469       break;
470 
471     // However if a prolog instruction reads a register that needs to be
472     // reloaded, the reload should be inserted before the prolog.
473     for (MachineOperand &MO : I->operands()) {
474       if (MO.isReg())
475         PrologLiveIns.insert(MO.getReg());
476     }
477 
478     ++I;
479   }
480 
481   return I;
482 }
483 
484 /// Reload all currently assigned virtual registers.
485 void RegAllocFast::reloadAtBegin(MachineBasicBlock &MBB) {
486   if (LiveVirtRegs.empty())
487     return;
488 
489   for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
490     MCPhysReg Reg = P.PhysReg;
491     // Set state to live-in. This possibly overrides mappings to virtual
492     // registers but we don't care anymore at this point.
493     setPhysRegState(Reg, regLiveIn);
494   }
495 
496 
497   SmallSet<Register, 2> PrologLiveIns;
498 
499   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
500   // of spilling here is deterministic, if arbitrary.
501   MachineBasicBlock::iterator InsertBefore
502     = getMBBBeginInsertionPoint(MBB, PrologLiveIns);
503   for (const LiveReg &LR : LiveVirtRegs) {
504     MCPhysReg PhysReg = LR.PhysReg;
505     if (PhysReg == 0)
506       continue;
507 
508     MCRegister FirstUnit = *MCRegUnitIterator(PhysReg, TRI);
509     if (RegUnitStates[FirstUnit] == regLiveIn)
510       continue;
511 
512     assert((&MBB != &MBB.getParent()->front() || IgnoreMissingDefs) &&
513            "no reload in start block. Missing vreg def?");
514 
515     if (PrologLiveIns.count(PhysReg)) {
516       // FIXME: Theoretically this should use an insert point skipping labels
517       // but I'm not sure how labels should interact with prolog instruction
518       // that need reloads.
519       reload(MBB.begin(), LR.VirtReg, PhysReg);
520     } else
521       reload(InsertBefore, LR.VirtReg, PhysReg);
522   }
523   LiveVirtRegs.clear();
524 }
525 
526 /// Handle the direct use of a physical register.  Check that the register is
527 /// not used by a virtreg. Kill the physreg, marking it free. This may add
528 /// implicit kills to MO->getParent() and invalidate MO.
529 bool RegAllocFast::usePhysReg(MachineInstr &MI, MCPhysReg Reg) {
530   assert(Register::isPhysicalRegister(Reg) && "expected physreg");
531   bool displacedAny = displacePhysReg(MI, Reg);
532   setPhysRegState(Reg, regPreAssigned);
533   markRegUsedInInstr(Reg);
534   return displacedAny;
535 }
536 
537 bool RegAllocFast::definePhysReg(MachineInstr &MI, MCPhysReg Reg) {
538   bool displacedAny = displacePhysReg(MI, Reg);
539   setPhysRegState(Reg, regPreAssigned);
540   return displacedAny;
541 }
542 
543 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
544 /// similar to defineVirtReg except the physreg is reserved instead of
545 /// allocated.
546 bool RegAllocFast::displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg) {
547   bool displacedAny = false;
548 
549   for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
550     unsigned Unit = *UI;
551     switch (unsigned VirtReg = RegUnitStates[Unit]) {
552     default: {
553       LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
554       assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
555       MachineBasicBlock::iterator ReloadBefore =
556           std::next((MachineBasicBlock::iterator)MI.getIterator());
557       reload(ReloadBefore, VirtReg, LRI->PhysReg);
558 
559       setPhysRegState(LRI->PhysReg, regFree);
560       LRI->PhysReg = 0;
561       LRI->Reloaded = true;
562       displacedAny = true;
563       break;
564     }
565     case regPreAssigned:
566       RegUnitStates[Unit] = regFree;
567       displacedAny = true;
568       break;
569     case regFree:
570       break;
571     }
572   }
573   return displacedAny;
574 }
575 
576 void RegAllocFast::freePhysReg(MCPhysReg PhysReg) {
577   LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
578 
579   MCRegister FirstUnit = *MCRegUnitIterator(PhysReg, TRI);
580   switch (unsigned VirtReg = RegUnitStates[FirstUnit]) {
581   case regFree:
582     LLVM_DEBUG(dbgs() << '\n');
583     return;
584   case regPreAssigned:
585     LLVM_DEBUG(dbgs() << '\n');
586     setPhysRegState(PhysReg, regFree);
587     return;
588   default: {
589       LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
590       assert(LRI != LiveVirtRegs.end());
591       LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
592       setPhysRegState(LRI->PhysReg, regFree);
593       LRI->PhysReg = 0;
594     }
595     return;
596   }
597 }
598 
599 /// Return the cost of spilling clearing out PhysReg and aliases so it is free
600 /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
601 /// disabled - it can be allocated directly.
602 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
603 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
604   for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
605     switch (unsigned VirtReg = RegUnitStates[*UI]) {
606     case regFree:
607       break;
608     case regPreAssigned:
609       LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
610                         << printReg(PhysReg, TRI) << '\n');
611       return spillImpossible;
612     default: {
613       bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
614                        findLiveVirtReg(VirtReg)->LiveOut;
615       return SureSpill ? spillClean : spillDirty;
616     }
617     }
618   }
619   return 0;
620 }
621 
622 void RegAllocFast::assignDanglingDebugValues(MachineInstr &Definition,
623                                              Register VirtReg, MCPhysReg Reg) {
624   auto UDBGValIter = DanglingDbgValues.find(VirtReg);
625   if (UDBGValIter == DanglingDbgValues.end())
626     return;
627 
628   SmallVectorImpl<MachineInstr*> &Dangling = UDBGValIter->second;
629   for (MachineInstr *DbgValue : Dangling) {
630     assert(DbgValue->isDebugValue());
631     if (!DbgValue->hasDebugOperandForReg(VirtReg))
632       continue;
633 
634     // Test whether the physreg survives from the definition to the DBG_VALUE.
635     MCPhysReg SetToReg = Reg;
636     unsigned Limit = 20;
637     for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
638          E = DbgValue->getIterator(); I != E; ++I) {
639       if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
640         LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
641                    << '\n');
642         SetToReg = 0;
643         break;
644       }
645     }
646     for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
647       MO.setReg(SetToReg);
648       if (SetToReg != 0)
649         MO.setIsRenamable();
650     }
651   }
652   Dangling.clear();
653 }
654 
655 /// This method updates local state so that we know that PhysReg is the
656 /// proper container for VirtReg now.  The physical register must not be used
657 /// for anything else when this is called.
658 void RegAllocFast::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
659                                        MCPhysReg PhysReg) {
660   Register VirtReg = LR.VirtReg;
661   LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
662                     << printReg(PhysReg, TRI) << '\n');
663   assert(LR.PhysReg == 0 && "Already assigned a physreg");
664   assert(PhysReg != 0 && "Trying to assign no register");
665   LR.PhysReg = PhysReg;
666   setPhysRegState(PhysReg, VirtReg);
667 
668   assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
669 }
670 
671 static bool isCoalescable(const MachineInstr &MI) {
672   return MI.isFullCopy();
673 }
674 
675 Register RegAllocFast::traceCopyChain(Register Reg) const {
676   static const unsigned ChainLengthLimit = 3;
677   unsigned C = 0;
678   do {
679     if (Reg.isPhysical())
680       return Reg;
681     assert(Reg.isVirtual());
682 
683     MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
684     if (!VRegDef || !isCoalescable(*VRegDef))
685       return 0;
686     Reg = VRegDef->getOperand(1).getReg();
687   } while (++C <= ChainLengthLimit);
688   return 0;
689 }
690 
691 /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
692 /// chain of copies to check whether we reach a physical register we can
693 /// coalesce with.
694 Register RegAllocFast::traceCopies(Register VirtReg) const {
695   static const unsigned DefLimit = 3;
696   unsigned C = 0;
697   for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
698     if (isCoalescable(MI)) {
699       Register Reg = MI.getOperand(1).getReg();
700       Reg = traceCopyChain(Reg);
701       if (Reg.isValid())
702         return Reg;
703     }
704 
705     if (++C >= DefLimit)
706       break;
707   }
708   return Register();
709 }
710 
711 /// Allocates a physical register for VirtReg.
712 void RegAllocFast::allocVirtReg(MachineInstr &MI, LiveReg &LR,
713                                 Register Hint0, bool LookAtPhysRegUses) {
714   const Register VirtReg = LR.VirtReg;
715   assert(LR.PhysReg == 0);
716 
717   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
718   LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
719                     << " in class " << TRI->getRegClassName(&RC)
720                     << " with hint " << printReg(Hint0, TRI) << '\n');
721 
722   // Take hint when possible.
723   if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
724       !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
725     // Take hint if the register is currently free.
726     if (isPhysRegFree(Hint0)) {
727       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
728                         << '\n');
729       assignVirtToPhysReg(MI, LR, Hint0);
730       return;
731     } else {
732       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
733                         << " occupied\n");
734     }
735   } else {
736     Hint0 = Register();
737   }
738 
739 
740   // Try other hint.
741   Register Hint1 = traceCopies(VirtReg);
742   if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
743       !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
744     // Take hint if the register is currently free.
745     if (isPhysRegFree(Hint1)) {
746       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
747                  << '\n');
748       assignVirtToPhysReg(MI, LR, Hint1);
749       return;
750     } else {
751       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
752                  << " occupied\n");
753     }
754   } else {
755     Hint1 = Register();
756   }
757 
758   MCPhysReg BestReg = 0;
759   unsigned BestCost = spillImpossible;
760   ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
761   for (MCPhysReg PhysReg : AllocationOrder) {
762     LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
763     if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
764       LLVM_DEBUG(dbgs() << "already used in instr.\n");
765       continue;
766     }
767 
768     unsigned Cost = calcSpillCost(PhysReg);
769     LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
770     // Immediate take a register with cost 0.
771     if (Cost == 0) {
772       assignVirtToPhysReg(MI, LR, PhysReg);
773       return;
774     }
775 
776     if (PhysReg == Hint0 || PhysReg == Hint1)
777       Cost -= spillPrefBonus;
778 
779     if (Cost < BestCost) {
780       BestReg = PhysReg;
781       BestCost = Cost;
782     }
783   }
784 
785   if (!BestReg) {
786     // Nothing we can do: Report an error and keep going with an invalid
787     // allocation.
788     if (MI.isInlineAsm())
789       MI.emitError("inline assembly requires more registers than available");
790     else
791       MI.emitError("ran out of registers during register allocation");
792 
793     LR.Error = true;
794     LR.PhysReg = 0;
795     return;
796   }
797 
798   displacePhysReg(MI, BestReg);
799   assignVirtToPhysReg(MI, LR, BestReg);
800 }
801 
802 void RegAllocFast::allocVirtRegUndef(MachineOperand &MO) {
803   assert(MO.isUndef() && "expected undef use");
804   Register VirtReg = MO.getReg();
805   assert(Register::isVirtualRegister(VirtReg) && "Expected virtreg");
806 
807   LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
808   MCPhysReg PhysReg;
809   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
810     PhysReg = LRI->PhysReg;
811   } else {
812     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
813     ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
814     assert(!AllocationOrder.empty() && "Allocation order must not be empty");
815     PhysReg = AllocationOrder[0];
816   }
817 
818   unsigned SubRegIdx = MO.getSubReg();
819   if (SubRegIdx != 0) {
820     PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
821     MO.setSubReg(0);
822   }
823   MO.setReg(PhysReg);
824   MO.setIsRenamable(true);
825 }
826 
827 /// Variation of defineVirtReg() with special handling for livethrough regs
828 /// (tied or earlyclobber) that may interfere with preassigned uses.
829 void RegAllocFast::defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
830                                             Register VirtReg) {
831   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
832   if (LRI != LiveVirtRegs.end()) {
833     MCPhysReg PrevReg = LRI->PhysReg;
834     if (PrevReg != 0 && isRegUsedInInstr(PrevReg, true)) {
835       LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
836                         << " (tied/earlyclobber resolution)\n");
837       freePhysReg(PrevReg);
838       LRI->PhysReg = 0;
839       allocVirtReg(MI, *LRI, 0, true);
840       MachineBasicBlock::iterator InsertBefore =
841         std::next((MachineBasicBlock::iterator)MI.getIterator());
842       LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
843                         << printReg(PrevReg, TRI) << '\n');
844       BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
845               TII->get(TargetOpcode::COPY), PrevReg)
846         .addReg(LRI->PhysReg, llvm::RegState::Kill);
847     }
848     MachineOperand &MO = MI.getOperand(OpNum);
849     if (MO.getSubReg() && !MO.isUndef()) {
850       LRI->LastUse = &MI;
851     }
852   }
853   return defineVirtReg(MI, OpNum, VirtReg, true);
854 }
855 
856 /// Allocates a register for VirtReg definition. Typically the register is
857 /// already assigned from a use of the virtreg, however we still need to
858 /// perform an allocation if:
859 /// - It is a dead definition without any uses.
860 /// - The value is live out and all uses are in different basic blocks.
861 void RegAllocFast::defineVirtReg(MachineInstr &MI, unsigned OpNum,
862                                  Register VirtReg, bool LookAtPhysRegUses) {
863   assert(VirtReg.isVirtual() && "Not a virtual register");
864   MachineOperand &MO = MI.getOperand(OpNum);
865   LiveRegMap::iterator LRI;
866   bool New;
867   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
868   if (New) {
869     if (!MO.isDead()) {
870       if (mayLiveOut(VirtReg)) {
871         LRI->LiveOut = true;
872       } else {
873         // It is a dead def without the dead flag; add the flag now.
874         MO.setIsDead(true);
875       }
876     }
877   }
878   if (LRI->PhysReg == 0)
879     allocVirtReg(MI, *LRI, 0, LookAtPhysRegUses);
880   else {
881     assert(!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) &&
882            "TODO: preassign mismatch");
883     LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
884                       << " use existing assignment to "
885                       << printReg(LRI->PhysReg, TRI) << '\n');
886   }
887 
888   MCPhysReg PhysReg = LRI->PhysReg;
889   assert(PhysReg != 0 && "Register not assigned");
890   if (LRI->Reloaded || LRI->LiveOut) {
891     if (!MI.isImplicitDef()) {
892       MachineBasicBlock::iterator SpillBefore =
893           std::next((MachineBasicBlock::iterator)MI.getIterator());
894       LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut << " RL: "
895                         << LRI->Reloaded << '\n');
896       bool Kill = LRI->LastUse == nullptr;
897       spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
898       LRI->LastUse = nullptr;
899     }
900     LRI->LiveOut = false;
901     LRI->Reloaded = false;
902   }
903   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
904     BundleVirtRegsMap[VirtReg] = PhysReg;
905   }
906   markRegUsedInInstr(PhysReg);
907   setPhysReg(MI, MO, PhysReg);
908 }
909 
910 /// Allocates a register for a VirtReg use.
911 void RegAllocFast::useVirtReg(MachineInstr &MI, unsigned OpNum,
912                               Register VirtReg) {
913   assert(VirtReg.isVirtual() && "Not a virtual register");
914   MachineOperand &MO = MI.getOperand(OpNum);
915   LiveRegMap::iterator LRI;
916   bool New;
917   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
918   if (New) {
919     MachineOperand &MO = MI.getOperand(OpNum);
920     if (!MO.isKill()) {
921       if (mayLiveOut(VirtReg)) {
922         LRI->LiveOut = true;
923       } else {
924         // It is a last (killing) use without the kill flag; add the flag now.
925         MO.setIsKill(true);
926       }
927     }
928   } else {
929     assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
930   }
931 
932   // If necessary allocate a register.
933   if (LRI->PhysReg == 0) {
934     assert(!MO.isTied() && "tied op should be allocated");
935     Register Hint;
936     if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
937       Hint = MI.getOperand(0).getReg();
938       assert(Hint.isPhysical() &&
939              "Copy destination should already be assigned");
940     }
941     allocVirtReg(MI, *LRI, Hint, false);
942     if (LRI->Error) {
943       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
944       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
945       setPhysReg(MI, MO, *AllocationOrder.begin());
946       return;
947     }
948   }
949 
950   LRI->LastUse = &MI;
951 
952   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
953     BundleVirtRegsMap[VirtReg] = LRI->PhysReg;
954   }
955   markRegUsedInInstr(LRI->PhysReg);
956   setPhysReg(MI, MO, LRI->PhysReg);
957 }
958 
959 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
960 /// may invalidate any operand pointers.  Return true if the operand kills its
961 /// register.
962 void RegAllocFast::setPhysReg(MachineInstr &MI, MachineOperand &MO,
963                               MCPhysReg PhysReg) {
964   if (!MO.getSubReg()) {
965     MO.setReg(PhysReg);
966     MO.setIsRenamable(true);
967     return;
968   }
969 
970   // Handle subregister index.
971   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : MCRegister());
972   MO.setIsRenamable(true);
973   // Note: We leave the subreg number around a little longer in case of defs.
974   // This is so that the register freeing logic in allocateInstruction can still
975   // recognize this as subregister defs. The code there will clear the number.
976   if (!MO.isDef())
977     MO.setSubReg(0);
978 
979   // A kill flag implies killing the full register. Add corresponding super
980   // register kill.
981   if (MO.isKill()) {
982     MI.addRegisterKilled(PhysReg, TRI, true);
983     return;
984   }
985 
986   // A <def,read-undef> of a sub-register requires an implicit def of the full
987   // register.
988   if (MO.isDef() && MO.isUndef()) {
989     if (MO.isDead())
990       MI.addRegisterDead(PhysReg, TRI, true);
991     else
992       MI.addRegisterDefined(PhysReg, TRI);
993   }
994 }
995 
996 #ifndef NDEBUG
997 
998 void RegAllocFast::dumpState() const {
999   for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
1000        ++Unit) {
1001     switch (unsigned VirtReg = RegUnitStates[Unit]) {
1002     case regFree:
1003       break;
1004     case regPreAssigned:
1005       dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1006       break;
1007     case regLiveIn:
1008       llvm_unreachable("Should not have regLiveIn in map");
1009     default: {
1010       dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1011       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1012       assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1013       if (I->LiveOut || I->Reloaded) {
1014         dbgs() << '[';
1015         if (I->LiveOut) dbgs() << 'O';
1016         if (I->Reloaded) dbgs() << 'R';
1017         dbgs() << ']';
1018       }
1019       assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1020       break;
1021     }
1022     }
1023   }
1024   dbgs() << '\n';
1025   // Check that LiveVirtRegs is the inverse.
1026   for (const LiveReg &LR : LiveVirtRegs) {
1027     Register VirtReg = LR.VirtReg;
1028     assert(VirtReg.isVirtual() && "Bad map key");
1029     MCPhysReg PhysReg = LR.PhysReg;
1030     if (PhysReg != 0) {
1031       assert(Register::isPhysicalRegister(PhysReg) &&
1032              "mapped to physreg");
1033       for (MCRegUnitIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
1034         assert(RegUnitStates[*UI] == VirtReg && "inverse map valid");
1035       }
1036     }
1037   }
1038 }
1039 #endif
1040 
1041 /// Count number of defs consumed from each register class by \p Reg
1042 void RegAllocFast::addRegClassDefCounts(std::vector<unsigned> &RegClassDefCounts,
1043                                         Register Reg) const {
1044   assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1045 
1046   if (Reg.isVirtual()) {
1047     const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1048     for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1049          RCIdx != RCIdxEnd; ++RCIdx) {
1050       const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1051       // FIXME: Consider aliasing sub/super registers.
1052       if (OpRC->hasSubClassEq(IdxRC))
1053         ++RegClassDefCounts[RCIdx];
1054     }
1055 
1056     return;
1057   }
1058 
1059   for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1060        RCIdx != RCIdxEnd; ++RCIdx) {
1061     const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1062     for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1063       if (IdxRC->contains(*Alias)) {
1064         ++RegClassDefCounts[RCIdx];
1065         break;
1066       }
1067     }
1068   }
1069 }
1070 
1071 void RegAllocFast::allocateInstruction(MachineInstr &MI) {
1072   // The basic algorithm here is:
1073   // 1. Mark registers of def operands as free
1074   // 2. Allocate registers to use operands and place reload instructions for
1075   //    registers displaced by the allocation.
1076   //
1077   // However we need to handle some corner cases:
1078   // - pre-assigned defs and uses need to be handled before the other def/use
1079   //   operands are processed to avoid the allocation heuristics clashing with
1080   //   the pre-assignment.
1081   // - The "free def operands" step has to come last instead of first for tied
1082   //   operands and early-clobbers.
1083 
1084   UsedInInstr.clear();
1085   BundleVirtRegsMap.clear();
1086 
1087   // Scan for special cases; Apply pre-assigned register defs to state.
1088   bool HasPhysRegUse = false;
1089   bool HasRegMask = false;
1090   bool HasVRegDef = false;
1091   bool HasDef = false;
1092   bool HasEarlyClobber = false;
1093   bool NeedToAssignLiveThroughs = false;
1094   for (MachineOperand &MO : MI.operands()) {
1095     if (MO.isReg()) {
1096       Register Reg = MO.getReg();
1097       if (Reg.isVirtual()) {
1098         if (MO.isDef()) {
1099           HasDef = true;
1100           HasVRegDef = true;
1101           if (MO.isEarlyClobber()) {
1102             HasEarlyClobber = true;
1103             NeedToAssignLiveThroughs = true;
1104           }
1105           if (MO.isTied() || (MO.getSubReg() != 0 && !MO.isUndef()))
1106             NeedToAssignLiveThroughs = true;
1107         }
1108       } else if (Reg.isPhysical()) {
1109         if (!MRI->isReserved(Reg)) {
1110           if (MO.isDef()) {
1111             HasDef = true;
1112             bool displacedAny = definePhysReg(MI, Reg);
1113             if (MO.isEarlyClobber())
1114               HasEarlyClobber = true;
1115             if (!displacedAny)
1116               MO.setIsDead(true);
1117           }
1118           if (MO.readsReg())
1119             HasPhysRegUse = true;
1120         }
1121       }
1122     } else if (MO.isRegMask()) {
1123       HasRegMask = true;
1124     }
1125   }
1126 
1127   // Allocate virtreg defs.
1128   if (HasDef) {
1129     if (HasVRegDef) {
1130       // Special handling for early clobbers, tied operands or subregister defs:
1131       // Compared to "normal" defs these:
1132       // - Must not use a register that is pre-assigned for a use operand.
1133       // - In order to solve tricky inline assembly constraints we change the
1134       //   heuristic to figure out a good operand order before doing
1135       //   assignments.
1136       if (NeedToAssignLiveThroughs) {
1137         DefOperandIndexes.clear();
1138         PhysRegUses.clear();
1139 
1140         // Track number of defs which may consume a register from the class.
1141         std::vector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1142         assert(RegClassDefCounts[0] == 0);
1143 
1144         LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1145         for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1146           const MachineOperand &MO = MI.getOperand(I);
1147           if (!MO.isReg())
1148             continue;
1149           Register Reg = MO.getReg();
1150           if (MO.readsReg()) {
1151             if (Reg.isPhysical()) {
1152               LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI)
1153                                 << '\n');
1154               markPhysRegUsedInInstr(Reg);
1155             }
1156           }
1157 
1158           if (MO.isDef()) {
1159             if (Reg.isVirtual())
1160               DefOperandIndexes.push_back(I);
1161 
1162             addRegClassDefCounts(RegClassDefCounts, Reg);
1163           }
1164         }
1165 
1166         llvm::sort(DefOperandIndexes, [&](uint16_t I0, uint16_t I1) {
1167           const MachineOperand &MO0 = MI.getOperand(I0);
1168           const MachineOperand &MO1 = MI.getOperand(I1);
1169           Register Reg0 = MO0.getReg();
1170           Register Reg1 = MO1.getReg();
1171           const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1172           const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1173 
1174           // Identify regclass that are easy to use up completely just in this
1175           // instruction.
1176           unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
1177           unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
1178 
1179           bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1180           bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1181           if (SmallClass0 > SmallClass1)
1182             return true;
1183           if (SmallClass0 < SmallClass1)
1184             return false;
1185 
1186           // Allocate early clobbers and livethrough operands first.
1187           bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
1188                               (MO0.getSubReg() == 0 && !MO0.isUndef());
1189           bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
1190                               (MO1.getSubReg() == 0 && !MO1.isUndef());
1191           if (Livethrough0 > Livethrough1)
1192             return true;
1193           if (Livethrough0 < Livethrough1)
1194             return false;
1195 
1196           // Tie-break rule: operand index.
1197           return I0 < I1;
1198         });
1199 
1200         for (uint16_t OpIdx : DefOperandIndexes) {
1201           MachineOperand &MO = MI.getOperand(OpIdx);
1202           LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1203           unsigned Reg = MO.getReg();
1204           if (MO.isEarlyClobber() || MO.isTied() ||
1205               (MO.getSubReg() && !MO.isUndef())) {
1206             defineLiveThroughVirtReg(MI, OpIdx, Reg);
1207           } else {
1208             defineVirtReg(MI, OpIdx, Reg);
1209           }
1210         }
1211       } else {
1212         // Assign virtual register defs.
1213         for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1214           MachineOperand &MO = MI.getOperand(I);
1215           if (!MO.isReg() || !MO.isDef())
1216             continue;
1217           Register Reg = MO.getReg();
1218           if (Reg.isVirtual())
1219             defineVirtReg(MI, I, Reg);
1220         }
1221       }
1222     }
1223 
1224     // Free registers occupied by defs.
1225     // Iterate operands in reverse order, so we see the implicit super register
1226     // defs first (we added them earlier in case of <def,read-undef>).
1227     for (unsigned I = MI.getNumOperands(); I-- > 0;) {
1228       MachineOperand &MO = MI.getOperand(I);
1229       if (!MO.isReg() || !MO.isDef())
1230         continue;
1231 
1232       // subreg defs don't free the full register. We left the subreg number
1233       // around as a marker in setPhysReg() to recognize this case here.
1234       if (MO.getSubReg() != 0) {
1235         MO.setSubReg(0);
1236         continue;
1237       }
1238 
1239       // Do not free tied operands and early clobbers.
1240       if (MO.isTied() || MO.isEarlyClobber())
1241         continue;
1242       Register Reg = MO.getReg();
1243       if (!Reg)
1244         continue;
1245       assert(Reg.isPhysical());
1246       if (MRI->isReserved(Reg))
1247         continue;
1248       freePhysReg(Reg);
1249       unmarkRegUsedInInstr(Reg);
1250     }
1251   }
1252 
1253   // Displace clobbered registers.
1254   if (HasRegMask) {
1255     for (const MachineOperand &MO : MI.operands()) {
1256       if (MO.isRegMask()) {
1257         // MRI bookkeeping.
1258         MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
1259 
1260         // Displace clobbered registers.
1261         const uint32_t *Mask = MO.getRegMask();
1262         for (const LiveReg &LR : LiveVirtRegs) {
1263           MCPhysReg PhysReg = LR.PhysReg;
1264           if (PhysReg != 0 && MachineOperand::clobbersPhysReg(Mask, PhysReg))
1265             displacePhysReg(MI, PhysReg);
1266         }
1267       }
1268     }
1269   }
1270 
1271   // Apply pre-assigned register uses to state.
1272   if (HasPhysRegUse) {
1273     for (MachineOperand &MO : MI.operands()) {
1274       if (!MO.isReg() || !MO.readsReg())
1275         continue;
1276       Register Reg = MO.getReg();
1277       if (!Reg.isPhysical())
1278         continue;
1279       if (MRI->isReserved(Reg))
1280         continue;
1281       bool displacedAny = usePhysReg(MI, Reg);
1282       if (!displacedAny && !MRI->isReserved(Reg))
1283         MO.setIsKill(true);
1284     }
1285   }
1286 
1287   // Allocate virtreg uses and insert reloads as necessary.
1288   bool HasUndefUse = false;
1289   for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
1290     MachineOperand &MO = MI.getOperand(I);
1291     if (!MO.isReg() || !MO.isUse())
1292       continue;
1293     Register Reg = MO.getReg();
1294     if (!Reg.isVirtual())
1295       continue;
1296 
1297     if (MO.isUndef()) {
1298       HasUndefUse = true;
1299       continue;
1300     }
1301 
1302 
1303     // Populate MayLiveAcrossBlocks in case the use block is allocated before
1304     // the def block (removing the vreg uses).
1305     mayLiveIn(Reg);
1306 
1307 
1308     assert(!MO.isInternalRead() && "Bundles not supported");
1309     assert(MO.readsReg() && "reading use");
1310     useVirtReg(MI, I, Reg);
1311   }
1312 
1313   // Allocate undef operands. This is a separate step because in a situation
1314   // like  ` = OP undef %X, %X`    both operands need the same register assign
1315   // so we should perform the normal assignment first.
1316   if (HasUndefUse) {
1317     for (MachineOperand &MO : MI.uses()) {
1318       if (!MO.isReg() || !MO.isUse())
1319         continue;
1320       Register Reg = MO.getReg();
1321       if (!Reg.isVirtual())
1322         continue;
1323 
1324       assert(MO.isUndef() && "Should only have undef virtreg uses left");
1325       allocVirtRegUndef(MO);
1326     }
1327   }
1328 
1329   // Free early clobbers.
1330   if (HasEarlyClobber) {
1331     for (unsigned I = MI.getNumOperands(); I-- > 0; ) {
1332       MachineOperand &MO = MI.getOperand(I);
1333       if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber())
1334         continue;
1335       // subreg defs don't free the full register. We left the subreg number
1336       // around as a marker in setPhysReg() to recognize this case here.
1337       if (MO.getSubReg() != 0) {
1338         MO.setSubReg(0);
1339         continue;
1340       }
1341 
1342       Register Reg = MO.getReg();
1343       if (!Reg)
1344         continue;
1345       assert(Reg.isPhysical() && "should have register assigned");
1346 
1347       // We sometimes get odd situations like:
1348       //    early-clobber %x0 = INSTRUCTION %x0
1349       // which is semantically questionable as the early-clobber should
1350       // apply before the use. But in practice we consider the use to
1351       // happen before the early clobber now. Don't free the early clobber
1352       // register in this case.
1353       if (MI.readsRegister(Reg, TRI))
1354         continue;
1355 
1356       freePhysReg(Reg);
1357     }
1358   }
1359 
1360   LLVM_DEBUG(dbgs() << "<< " << MI);
1361   if (MI.isCopy() && MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
1362       MI.getNumOperands() == 2) {
1363     LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1364     Coalesced.push_back(&MI);
1365   }
1366 }
1367 
1368 void RegAllocFast::handleDebugValue(MachineInstr &MI) {
1369   SmallSet<Register, 4> SeenRegisters;
1370   for (MachineOperand &MO : MI.debug_operands()) {
1371     // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1372     // mostly constants and frame indices.
1373     if (!MO.isReg())
1374       continue;
1375     Register Reg = MO.getReg();
1376     if (!Register::isVirtualRegister(Reg))
1377       continue;
1378     // Only process each register once per MI, each use of that register will
1379     // be updated if necessary.
1380     if (!SeenRegisters.insert(Reg).second)
1381       continue;
1382 
1383     // Already spilled to a stackslot?
1384     int SS = StackSlotForVirtReg[Reg];
1385     if (SS != -1) {
1386       // Modify DBG_VALUE now that the value is in a spill slot.
1387       updateDbgValueForSpill(MI, SS);
1388       LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1389       continue;
1390     }
1391 
1392     // See if this virtual register has already been allocated to a physical
1393     // register or spilled to a stack slot.
1394     LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1395     if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1396       // Update every use of Reg within MI.
1397       for (auto &RegMO : MI.getDebugOperandsForReg(Reg))
1398         setPhysReg(MI, RegMO, LRI->PhysReg);
1399     } else {
1400       DanglingDbgValues[Reg].push_back(&MI);
1401     }
1402 
1403     // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1404     // that future spills of Reg will have DBG_VALUEs.
1405     LiveDbgValueMap[Reg].push_back(&MI);
1406   }
1407 }
1408 
1409 void RegAllocFast::handleBundle(MachineInstr &MI) {
1410   MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1411   ++BundledMI;
1412   while (BundledMI->isBundledWithPred()) {
1413     for (unsigned I = 0; I < BundledMI->getNumOperands(); ++I) {
1414       MachineOperand &MO = BundledMI->getOperand(I);
1415       if (!MO.isReg())
1416         continue;
1417 
1418       Register Reg = MO.getReg();
1419       if (!Reg.isVirtual())
1420         continue;
1421 
1422       DenseMap<Register, MCPhysReg>::iterator DI;
1423       DI = BundleVirtRegsMap.find(Reg);
1424       assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1425 
1426       setPhysReg(MI, MO, DI->second);
1427     }
1428 
1429     ++BundledMI;
1430   }
1431 }
1432 
1433 void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
1434   this->MBB = &MBB;
1435   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1436 
1437   RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1438   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1439 
1440   for (MachineBasicBlock *Succ : MBB.successors()) {
1441     for (const MachineBasicBlock::RegisterMaskPair &LI : Succ->liveins())
1442       setPhysRegState(LI.PhysReg, regPreAssigned);
1443   }
1444 
1445   Coalesced.clear();
1446 
1447   // Traverse block in reverse order allocating instructions one by one.
1448   for (MachineInstr &MI : reverse(MBB)) {
1449     LLVM_DEBUG(
1450       dbgs() << "\n>> " << MI << "Regs:";
1451       dumpState()
1452     );
1453 
1454     // Special handling for debug values. Note that they are not allowed to
1455     // affect codegen of the other instructions in any way.
1456     if (MI.isDebugValue()) {
1457       handleDebugValue(MI);
1458       continue;
1459     }
1460 
1461     allocateInstruction(MI);
1462 
1463     // Once BUNDLE header is assigned registers, same assignments need to be
1464     // done for bundled MIs.
1465     if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1466       handleBundle(MI);
1467     }
1468   }
1469 
1470   LLVM_DEBUG(
1471     dbgs() << "Begin Regs:";
1472     dumpState()
1473   );
1474 
1475   // Spill all physical registers holding virtual registers now.
1476   LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1477   reloadAtBegin(MBB);
1478 
1479   // Erase all the coalesced copies. We are delaying it until now because
1480   // LiveVirtRegs might refer to the instrs.
1481   for (MachineInstr *MI : Coalesced)
1482     MBB.erase(MI);
1483   NumCoalesced += Coalesced.size();
1484 
1485   for (auto &UDBGPair : DanglingDbgValues) {
1486     for (MachineInstr *DbgValue : UDBGPair.second) {
1487       assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1488       // Nothing to do if the vreg was spilled in the meantime.
1489       if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1490         continue;
1491       LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1492                  << '\n');
1493       DbgValue->setDebugValueUndef();
1494     }
1495   }
1496   DanglingDbgValues.clear();
1497 
1498   LLVM_DEBUG(MBB.dump());
1499 }
1500 
1501 bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
1502   LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1503                     << "********** Function: " << MF.getName() << '\n');
1504   MRI = &MF.getRegInfo();
1505   const TargetSubtargetInfo &STI = MF.getSubtarget();
1506   TRI = STI.getRegisterInfo();
1507   TII = STI.getInstrInfo();
1508   MFI = &MF.getFrameInfo();
1509   MRI->freezeReservedRegs(MF);
1510   RegClassInfo.runOnMachineFunction(MF);
1511   unsigned NumRegUnits = TRI->getNumRegUnits();
1512   UsedInInstr.clear();
1513   UsedInInstr.setUniverse(NumRegUnits);
1514   PhysRegUses.clear();
1515   PhysRegUses.setUniverse(NumRegUnits);
1516 
1517   // initialize the virtual->physical register map to have a 'null'
1518   // mapping for all virtual registers
1519   unsigned NumVirtRegs = MRI->getNumVirtRegs();
1520   StackSlotForVirtReg.resize(NumVirtRegs);
1521   LiveVirtRegs.setUniverse(NumVirtRegs);
1522   MayLiveAcrossBlocks.clear();
1523   MayLiveAcrossBlocks.resize(NumVirtRegs);
1524 
1525   // Loop over all of the basic blocks, eliminating virtual register references
1526   for (MachineBasicBlock &MBB : MF)
1527     allocateBasicBlock(MBB);
1528 
1529   // All machine operands and other references to virtual registers have been
1530   // replaced. Remove the virtual registers.
1531   MRI->clearVirtRegs();
1532 
1533   StackSlotForVirtReg.clear();
1534   LiveDbgValueMap.clear();
1535   return true;
1536 }
1537 
1538 FunctionPass *llvm::createFastRegisterAllocator() {
1539   return new RegAllocFast();
1540 }
1541