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