RegAllocFast.cpp revision 7a029b6d7e58cb0f1010f14d99d7661e387cfb54
1//===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This register allocator allocates registers to a basic block at a time,
11// attempting to keep values in registers and reusing registers as appropriate.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
16#include "llvm/BasicBlock.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/CodeGen/MachineInstr.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/CodeGen/Passes.h"
22#include "llvm/CodeGen/RegAllocRegistry.h"
23#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/IndexedMap.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
35#include <algorithm>
36using namespace llvm;
37
38STATISTIC(NumStores, "Number of stores added");
39STATISTIC(NumLoads , "Number of loads added");
40STATISTIC(NumCopies, "Number of copies coalesced");
41
42static RegisterRegAlloc
43  fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
44
45namespace {
46  class RAFast : public MachineFunctionPass {
47  public:
48    static char ID;
49    RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1),
50               isBulkSpilling(false) {}
51  private:
52    const TargetMachine *TM;
53    MachineFunction *MF;
54    MachineRegisterInfo *MRI;
55    const TargetRegisterInfo *TRI;
56    const TargetInstrInfo *TII;
57
58    // Basic block currently being allocated.
59    MachineBasicBlock *MBB;
60
61    // StackSlotForVirtReg - Maps virtual regs to the frame index where these
62    // values are spilled.
63    IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
64
65    // Everything we know about a live virtual register.
66    struct LiveReg {
67      MachineInstr *LastUse;    // Last instr to use reg.
68      unsigned PhysReg;         // Currently held here.
69      unsigned short LastOpNum; // OpNum on LastUse.
70      bool Dirty;               // Register needs spill.
71
72      LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
73                              Dirty(false) {}
74    };
75
76    typedef DenseMap<unsigned, LiveReg> LiveRegMap;
77    typedef LiveRegMap::value_type LiveRegEntry;
78
79    // LiveVirtRegs - This map contains entries for each virtual register
80    // that is currently available in a physical register.
81    LiveRegMap LiveVirtRegs;
82
83    // RegState - Track the state of a physical register.
84    enum RegState {
85      // A disabled register is not available for allocation, but an alias may
86      // be in use. A register can only be moved out of the disabled state if
87      // all aliases are disabled.
88      regDisabled,
89
90      // A free register is not currently in use and can be allocated
91      // immediately without checking aliases.
92      regFree,
93
94      // A reserved register has been assigned expolicitly (e.g., setting up a
95      // call parameter), and it remains reserved until it is used.
96      regReserved
97
98      // A register state may also be a virtual register number, indication that
99      // the physical register is currently allocated to a virtual register. In
100      // that case, LiveVirtRegs contains the inverse mapping.
101    };
102
103    // PhysRegState - One of the RegState enums, or a virtreg.
104    std::vector<unsigned> PhysRegState;
105
106    // UsedInInstr - BitVector of physregs that are used in the current
107    // instruction, and so cannot be allocated.
108    BitVector UsedInInstr;
109
110    // Allocatable - vector of allocatable physical registers.
111    BitVector Allocatable;
112
113    // SkippedInstrs - Descriptors of instructions whose clobber list was ignored
114    // because all registers were spilled. It is still necessary to mark all the
115    // clobbered registers as used by the function.
116    SmallPtrSet<const TargetInstrDesc*, 4> SkippedInstrs;
117
118    // isBulkSpilling - This flag is set when LiveRegMap will be cleared
119    // completely after spilling all live registers. LiveRegMap entries should
120    // not be erased.
121    bool isBulkSpilling;
122
123    enum {
124      spillClean = 1,
125      spillDirty = 100,
126      spillImpossible = ~0u
127    };
128  public:
129    virtual const char *getPassName() const {
130      return "Fast Register Allocator";
131    }
132
133    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
134      AU.setPreservesCFG();
135      AU.addRequiredID(PHIEliminationID);
136      AU.addRequiredID(TwoAddressInstructionPassID);
137      MachineFunctionPass::getAnalysisUsage(AU);
138    }
139
140  private:
141    bool runOnMachineFunction(MachineFunction &Fn);
142    void AllocateBasicBlock();
143    void handleThroughOperands(MachineInstr *MI,
144                               SmallVectorImpl<unsigned> &VirtDead);
145    int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
146    bool isLastUseOfLocalReg(MachineOperand&);
147
148    void addKillFlag(const LiveReg&);
149    void killVirtReg(LiveRegMap::iterator);
150    void killVirtReg(unsigned VirtReg);
151    void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
152    void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
153
154    void usePhysReg(MachineOperand&);
155    void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
156    unsigned calcSpillCost(unsigned PhysReg) const;
157    void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
158    void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
159    LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
160                                       unsigned VirtReg, unsigned Hint);
161    LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
162                                       unsigned VirtReg, unsigned Hint);
163    void spillAll(MachineInstr *MI);
164    bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
165  };
166  char RAFast::ID = 0;
167}
168
169/// getStackSpaceFor - This allocates space for the specified virtual register
170/// to be held on the stack.
171int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
172  // Find the location Reg would belong...
173  int SS = StackSlotForVirtReg[VirtReg];
174  if (SS != -1)
175    return SS;          // Already has space allocated?
176
177  // Allocate a new stack object for this spill location...
178  int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
179                                                            RC->getAlignment());
180
181  // Assign the slot.
182  StackSlotForVirtReg[VirtReg] = FrameIdx;
183  return FrameIdx;
184}
185
186/// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
187/// its virtual register, and it is guaranteed to be a block-local register.
188///
189bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
190  // Check for non-debug uses or defs following MO.
191  // This is the most likely way to fail - fast path it.
192  MachineOperand *Next = &MO;
193  while ((Next = Next->getNextOperandForReg()))
194    if (!Next->isDebug())
195      return false;
196
197  // If the register has ever been spilled or reloaded, we conservatively assume
198  // it is a global register used in multiple blocks.
199  if (StackSlotForVirtReg[MO.getReg()] != -1)
200    return false;
201
202  // Check that the use/def chain has exactly one operand - MO.
203  return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
204}
205
206/// addKillFlag - Set kill flags on last use of a virtual register.
207void RAFast::addKillFlag(const LiveReg &LR) {
208  if (!LR.LastUse) return;
209  MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
210  if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
211    if (MO.getReg() == LR.PhysReg)
212      MO.setIsKill();
213    else
214      LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
215  }
216}
217
218/// killVirtReg - Mark virtreg as no longer available.
219void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
220  addKillFlag(LRI->second);
221  const LiveReg &LR = LRI->second;
222  assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
223  PhysRegState[LR.PhysReg] = regFree;
224  // Erase from LiveVirtRegs unless we're spilling in bulk.
225  if (!isBulkSpilling)
226    LiveVirtRegs.erase(LRI);
227}
228
229/// killVirtReg - Mark virtreg as no longer available.
230void RAFast::killVirtReg(unsigned VirtReg) {
231  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
232         "killVirtReg needs a virtual register");
233  LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
234  if (LRI != LiveVirtRegs.end())
235    killVirtReg(LRI);
236}
237
238/// spillVirtReg - This method spills the value specified by VirtReg into the
239/// corresponding stack slot if needed. If isKill is set, the register is also
240/// killed.
241void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
242  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
243         "Spilling a physical register is illegal!");
244  LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
245  assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
246  spillVirtReg(MI, LRI);
247}
248
249/// spillVirtReg - Do the actual work of spilling.
250void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
251                          LiveRegMap::iterator LRI) {
252  LiveReg &LR = LRI->second;
253  assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
254
255  if (LR.Dirty) {
256    // If this physreg is used by the instruction, we want to kill it on the
257    // instruction, not on the spill.
258    bool SpillKill = LR.LastUse != MI;
259    LR.Dirty = false;
260    DEBUG(dbgs() << "Spilling %reg" << LRI->first
261                 << " in " << TRI->getName(LR.PhysReg));
262    const TargetRegisterClass *RC = MRI->getRegClass(LRI->first);
263    int FI = getStackSpaceFor(LRI->first, RC);
264    DEBUG(dbgs() << " to stack slot #" << FI << "\n");
265    TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
266    ++NumStores;   // Update statistics
267
268    if (SpillKill)
269      LR.LastUse = 0; // Don't kill register again
270  }
271  killVirtReg(LRI);
272}
273
274/// spillAll - Spill all dirty virtregs without killing them.
275void RAFast::spillAll(MachineInstr *MI) {
276  if (LiveVirtRegs.empty()) return;
277  isBulkSpilling = true;
278  // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
279  // of spilling here is deterministic, if arbitrary.
280  for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
281       i != e; ++i)
282    spillVirtReg(MI, i);
283  LiveVirtRegs.clear();
284  isBulkSpilling = false;
285}
286
287/// usePhysReg - Handle the direct use of a physical register.
288/// Check that the register is not used by a virtreg.
289/// Kill the physreg, marking it free.
290/// This may add implicit kills to MO->getParent() and invalidate MO.
291void RAFast::usePhysReg(MachineOperand &MO) {
292  unsigned PhysReg = MO.getReg();
293  assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
294         "Bad usePhysReg operand");
295
296  switch (PhysRegState[PhysReg]) {
297  case regDisabled:
298    break;
299  case regReserved:
300    PhysRegState[PhysReg] = regFree;
301    // Fall through
302  case regFree:
303    UsedInInstr.set(PhysReg);
304    MO.setIsKill();
305    return;
306  default:
307    // The physreg was allocated to a virtual register. That means to value we
308    // wanted has been clobbered.
309    llvm_unreachable("Instruction uses an allocated register");
310  }
311
312  // Maybe a superregister is reserved?
313  for (const unsigned *AS = TRI->getAliasSet(PhysReg);
314       unsigned Alias = *AS; ++AS) {
315    switch (PhysRegState[Alias]) {
316    case regDisabled:
317      break;
318    case regReserved:
319      assert(TRI->isSuperRegister(PhysReg, Alias) &&
320             "Instruction is not using a subregister of a reserved register");
321      // Leave the superregister in the working set.
322      PhysRegState[Alias] = regFree;
323      UsedInInstr.set(Alias);
324      MO.getParent()->addRegisterKilled(Alias, TRI, true);
325      return;
326    case regFree:
327      if (TRI->isSuperRegister(PhysReg, Alias)) {
328        // Leave the superregister in the working set.
329        UsedInInstr.set(Alias);
330        MO.getParent()->addRegisterKilled(Alias, TRI, true);
331        return;
332      }
333      // Some other alias was in the working set - clear it.
334      PhysRegState[Alias] = regDisabled;
335      break;
336    default:
337      llvm_unreachable("Instruction uses an alias of an allocated register");
338    }
339  }
340
341  // All aliases are disabled, bring register into working set.
342  PhysRegState[PhysReg] = regFree;
343  UsedInInstr.set(PhysReg);
344  MO.setIsKill();
345}
346
347/// definePhysReg - Mark PhysReg as reserved or free after spilling any
348/// virtregs. This is very similar to defineVirtReg except the physreg is
349/// reserved instead of allocated.
350void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
351                           RegState NewState) {
352  UsedInInstr.set(PhysReg);
353  switch (unsigned VirtReg = PhysRegState[PhysReg]) {
354  case regDisabled:
355    break;
356  default:
357    spillVirtReg(MI, VirtReg);
358    // Fall through.
359  case regFree:
360  case regReserved:
361    PhysRegState[PhysReg] = NewState;
362    return;
363  }
364
365  // This is a disabled register, disable all aliases.
366  PhysRegState[PhysReg] = NewState;
367  for (const unsigned *AS = TRI->getAliasSet(PhysReg);
368       unsigned Alias = *AS; ++AS) {
369    UsedInInstr.set(Alias);
370    switch (unsigned VirtReg = PhysRegState[Alias]) {
371    case regDisabled:
372      break;
373    default:
374      spillVirtReg(MI, VirtReg);
375      // Fall through.
376    case regFree:
377    case regReserved:
378      PhysRegState[Alias] = regDisabled;
379      if (TRI->isSuperRegister(PhysReg, Alias))
380        return;
381      break;
382    }
383  }
384}
385
386
387// calcSpillCost - Return the cost of spilling clearing out PhysReg and
388// aliases so it is free for allocation.
389// Returns 0 when PhysReg is free or disabled with all aliases disabled - it
390// can be allocated directly.
391// Returns spillImpossible when PhysReg or an alias can't be spilled.
392unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
393  if (UsedInInstr.test(PhysReg))
394    return spillImpossible;
395  switch (unsigned VirtReg = PhysRegState[PhysReg]) {
396  case regDisabled:
397    break;
398  case regFree:
399    return 0;
400  case regReserved:
401    return spillImpossible;
402  default:
403    return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
404  }
405
406  // This is a disabled register, add up const of aliases.
407  unsigned Cost = 0;
408  for (const unsigned *AS = TRI->getAliasSet(PhysReg);
409       unsigned Alias = *AS; ++AS) {
410    if (UsedInInstr.test(Alias))
411      return spillImpossible;
412    switch (unsigned VirtReg = PhysRegState[Alias]) {
413    case regDisabled:
414      break;
415    case regFree:
416      ++Cost;
417      break;
418    case regReserved:
419      return spillImpossible;
420    default:
421      Cost += LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
422      break;
423    }
424  }
425  return Cost;
426}
427
428
429/// assignVirtToPhysReg - This method updates local state so that we know
430/// that PhysReg is the proper container for VirtReg now.  The physical
431/// register must not be used for anything else when this is called.
432///
433void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
434  DEBUG(dbgs() << "Assigning %reg" << LRE.first << " to "
435               << TRI->getName(PhysReg) << "\n");
436  PhysRegState[PhysReg] = LRE.first;
437  assert(!LRE.second.PhysReg && "Already assigned a physreg");
438  LRE.second.PhysReg = PhysReg;
439}
440
441/// allocVirtReg - Allocate a physical register for VirtReg.
442void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
443  const unsigned VirtReg = LRE.first;
444
445  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
446         "Can only allocate virtual registers");
447
448  const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
449
450  // Ignore invalid hints.
451  if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
452               !RC->contains(Hint) || !Allocatable.test(Hint)))
453    Hint = 0;
454
455  // Take hint when possible.
456  if (Hint) {
457    switch(calcSpillCost(Hint)) {
458    default:
459      definePhysReg(MI, Hint, regFree);
460      // Fall through.
461    case 0:
462      return assignVirtToPhysReg(LRE, Hint);
463    case spillImpossible:
464      break;
465    }
466  }
467
468  TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
469  TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
470
471  // First try to find a completely free register.
472  for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
473    unsigned PhysReg = *I;
474    if (PhysRegState[PhysReg] == regFree && !UsedInInstr.test(PhysReg))
475      return assignVirtToPhysReg(LRE, PhysReg);
476  }
477
478  DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
479               << "\n");
480
481  unsigned BestReg = 0, BestCost = spillImpossible;
482  for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
483    unsigned Cost = calcSpillCost(*I);
484    // Cost is 0 when all aliases are already disabled.
485    if (Cost == 0)
486      return assignVirtToPhysReg(LRE, *I);
487    if (Cost < BestCost)
488      BestReg = *I, BestCost = Cost;
489  }
490
491  if (BestReg) {
492    definePhysReg(MI, BestReg, regFree);
493    return assignVirtToPhysReg(LRE, BestReg);
494  }
495
496  // Nothing we can do.
497  std::string msg;
498  raw_string_ostream Msg(msg);
499  Msg << "Ran out of registers during register allocation!";
500  if (MI->isInlineAsm()) {
501    Msg << "\nPlease check your inline asm statement for "
502        << "invalid constraints:\n";
503    MI->print(Msg, TM);
504  }
505  report_fatal_error(Msg.str());
506}
507
508/// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
509RAFast::LiveRegMap::iterator
510RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
511                      unsigned VirtReg, unsigned Hint) {
512  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
513         "Not a virtual register");
514  LiveRegMap::iterator LRI;
515  bool New;
516  tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
517  LiveReg &LR = LRI->second;
518  if (New) {
519    // If there is no hint, peek at the only use of this register.
520    if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
521        MRI->hasOneNonDBGUse(VirtReg)) {
522      const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
523      unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
524      // It's a copy, use the destination register as a hint.
525      if (UseMI.isCopyLike())
526        Hint = UseMI.getOperand(0).getReg();
527      else if (TII->isMoveInstr(UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
528        Hint = DstReg;
529    }
530    allocVirtReg(MI, *LRI, Hint);
531  } else if (LR.LastUse) {
532    // Redefining a live register - kill at the last use, unless it is this
533    // instruction defining VirtReg multiple times.
534    if (LR.LastUse != MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
535      addKillFlag(LR);
536  }
537  assert(LR.PhysReg && "Register not assigned");
538  LR.LastUse = MI;
539  LR.LastOpNum = OpNum;
540  LR.Dirty = true;
541  UsedInInstr.set(LR.PhysReg);
542  return LRI;
543}
544
545/// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
546RAFast::LiveRegMap::iterator
547RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
548                      unsigned VirtReg, unsigned Hint) {
549  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
550         "Not a virtual register");
551  LiveRegMap::iterator LRI;
552  bool New;
553  tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
554  LiveReg &LR = LRI->second;
555  MachineOperand &MO = MI->getOperand(OpNum);
556  if (New) {
557    allocVirtReg(MI, *LRI, Hint);
558    const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
559    int FrameIndex = getStackSpaceFor(VirtReg, RC);
560    DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
561                 << TRI->getName(LR.PhysReg) << "\n");
562    TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
563    ++NumLoads;
564  } else if (LR.Dirty) {
565    if (isLastUseOfLocalReg(MO)) {
566      DEBUG(dbgs() << "Killing last use: " << MO << "\n");
567      if (MO.isUse())
568        MO.setIsKill();
569      else
570        MO.setIsDead();
571    } else if (MO.isKill()) {
572      DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
573      MO.setIsKill(false);
574    } else if (MO.isDead()) {
575      DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
576      MO.setIsDead(false);
577    }
578  } else if (MO.isKill()) {
579    // We must remove kill flags from uses of reloaded registers because the
580    // register would be killed immediately, and there might be a second use:
581    //   %foo = OR %x<kill>, %x
582    // This would cause a second reload of %x into a different register.
583    DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
584    MO.setIsKill(false);
585  } else if (MO.isDead()) {
586    DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
587    MO.setIsDead(false);
588  }
589  assert(LR.PhysReg && "Register not assigned");
590  LR.LastUse = MI;
591  LR.LastOpNum = OpNum;
592  UsedInInstr.set(LR.PhysReg);
593  return LRI;
594}
595
596// setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
597// subregs. This may invalidate any operand pointers.
598// Return true if the operand kills its register.
599bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
600  MachineOperand &MO = MI->getOperand(OpNum);
601  if (!MO.getSubReg()) {
602    MO.setReg(PhysReg);
603    return MO.isKill() || MO.isDead();
604  }
605
606  // Handle subregister index.
607  MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
608  MO.setSubReg(0);
609
610  // A kill flag implies killing the full register. Add corresponding super
611  // register kill.
612  if (MO.isKill()) {
613    MI->addRegisterKilled(PhysReg, TRI, true);
614    return true;
615  }
616  return MO.isDead();
617}
618
619// Handle special instruction operand like early clobbers and tied ops when
620// there are additional physreg defines.
621void RAFast::handleThroughOperands(MachineInstr *MI,
622                                   SmallVectorImpl<unsigned> &VirtDead) {
623  DEBUG(dbgs() << "Scanning for through registers:");
624  SmallSet<unsigned, 8> ThroughRegs;
625  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
626    MachineOperand &MO = MI->getOperand(i);
627    if (!MO.isReg()) continue;
628    unsigned Reg = MO.getReg();
629    if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
630    if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
631        (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
632      if (ThroughRegs.insert(Reg))
633        DEBUG(dbgs() << " %reg" << Reg);
634    }
635  }
636
637  // If any physreg defines collide with preallocated through registers,
638  // we must spill and reallocate.
639  DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
640  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
641    MachineOperand &MO = MI->getOperand(i);
642    if (!MO.isReg() || !MO.isDef()) continue;
643    unsigned Reg = MO.getReg();
644    if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
645    UsedInInstr.set(Reg);
646    if (ThroughRegs.count(PhysRegState[Reg]))
647      definePhysReg(MI, Reg, regFree);
648    for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
649      UsedInInstr.set(*AS);
650      if (ThroughRegs.count(PhysRegState[*AS]))
651        definePhysReg(MI, *AS, regFree);
652    }
653  }
654
655  SmallVector<unsigned, 8> PartialDefs;
656  DEBUG(dbgs() << "Allocating tied uses and early clobbers.\n");
657  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
658    MachineOperand &MO = MI->getOperand(i);
659    if (!MO.isReg()) continue;
660    unsigned Reg = MO.getReg();
661    if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
662    if (MO.isUse()) {
663      unsigned DefIdx = 0;
664      if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
665      DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
666        << DefIdx << ".\n");
667      LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
668      unsigned PhysReg = LRI->second.PhysReg;
669      setPhysReg(MI, i, PhysReg);
670      // Note: we don't update the def operand yet. That would cause the normal
671      // def-scan to attempt spilling.
672    } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
673      DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
674      // Reload the register, but don't assign to the operand just yet.
675      // That would confuse the later phys-def processing pass.
676      LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
677      PartialDefs.push_back(LRI->second.PhysReg);
678    } else if (MO.isEarlyClobber()) {
679      // Note: defineVirtReg may invalidate MO.
680      LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
681      unsigned PhysReg = LRI->second.PhysReg;
682      if (setPhysReg(MI, i, PhysReg))
683        VirtDead.push_back(Reg);
684    }
685  }
686
687  // Restore UsedInInstr to a state usable for allocating normal virtual uses.
688  UsedInInstr.reset();
689  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
690    MachineOperand &MO = MI->getOperand(i);
691    if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
692    unsigned Reg = MO.getReg();
693    if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
694    UsedInInstr.set(Reg);
695    for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
696      UsedInInstr.set(*AS);
697  }
698
699  // Also mark PartialDefs as used to avoid reallocation.
700  for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
701    UsedInInstr.set(PartialDefs[i]);
702}
703
704void RAFast::AllocateBasicBlock() {
705  DEBUG(dbgs() << "\nAllocating " << *MBB);
706
707  PhysRegState.assign(TRI->getNumRegs(), regDisabled);
708  assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
709
710  MachineBasicBlock::iterator MII = MBB->begin();
711
712  // Add live-in registers as live.
713  for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
714         E = MBB->livein_end(); I != E; ++I)
715    definePhysReg(MII, *I, regReserved);
716
717  SmallVector<unsigned, 8> VirtDead;
718  SmallVector<MachineInstr*, 32> Coalesced;
719
720  // Otherwise, sequentially allocate each instruction in the MBB.
721  while (MII != MBB->end()) {
722    MachineInstr *MI = MII++;
723    const TargetInstrDesc &TID = MI->getDesc();
724    DEBUG({
725        dbgs() << "\n>> " << *MI << "Regs:";
726        for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
727          if (PhysRegState[Reg] == regDisabled) continue;
728          dbgs() << " " << TRI->getName(Reg);
729          switch(PhysRegState[Reg]) {
730          case regFree:
731            break;
732          case regReserved:
733            dbgs() << "*";
734            break;
735          default:
736            dbgs() << "=%reg" << PhysRegState[Reg];
737            if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
738              dbgs() << "*";
739            assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
740                   "Bad inverse map");
741            break;
742          }
743        }
744        dbgs() << '\n';
745        // Check that LiveVirtRegs is the inverse.
746        for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
747             e = LiveVirtRegs.end(); i != e; ++i) {
748           assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
749                  "Bad map key");
750           assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
751                  "Bad map value");
752           assert(PhysRegState[i->second.PhysReg] == i->first &&
753                  "Bad inverse map");
754        }
755      });
756
757    // Debug values are not allowed to change codegen in any way.
758    if (MI->isDebugValue()) {
759      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
760        MachineOperand &MO = MI->getOperand(i);
761        if (!MO.isReg()) continue;
762        unsigned Reg = MO.getReg();
763        if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
764        LiveRegMap::iterator LRI = LiveVirtRegs.find(Reg);
765        if (LRI != LiveVirtRegs.end())
766          setPhysReg(MI, i, LRI->second.PhysReg);
767        else {
768          int SS = StackSlotForVirtReg[Reg];
769          if (SS == -1)
770            MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
771          else {
772            // Modify DBG_VALUE now that the value is in a spill slot.
773            uint64_t Offset = MI->getOperand(1).getImm();
774            const MDNode *MDPtr =
775              MI->getOperand(MI->getNumOperands()-1).getMetadata();
776            DebugLoc DL = MI->getDebugLoc();
777            if (MachineInstr *NewDV =
778                TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
779              DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
780              MachineBasicBlock *MBB = MI->getParent();
781              MBB->insert(MBB->erase(MI), NewDV);
782            } else
783              MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
784          }
785        }
786      }
787      // Next instruction.
788      continue;
789    }
790
791    // If this is a copy, we may be able to coalesce.
792    unsigned CopySrc, CopyDst, CopySrcSub, CopyDstSub;
793    if (MI->isCopy()) {
794      CopyDst = MI->getOperand(0).getReg();
795      CopySrc = MI->getOperand(1).getReg();
796      CopyDstSub = MI->getOperand(0).getSubReg();
797      CopySrcSub = MI->getOperand(1).getSubReg();
798    } else if (!TII->isMoveInstr(*MI, CopySrc, CopyDst, CopySrcSub, CopyDstSub))
799      CopySrc = CopyDst = 0;
800
801    // Track registers used by instruction.
802    UsedInInstr.reset();
803
804    // First scan.
805    // Mark physreg uses and early clobbers as used.
806    // Find the end of the virtreg operands
807    unsigned VirtOpEnd = 0;
808    bool hasTiedOps = false;
809    bool hasEarlyClobbers = false;
810    bool hasPartialRedefs = false;
811    bool hasPhysDefs = false;
812    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
813      MachineOperand &MO = MI->getOperand(i);
814      if (!MO.isReg()) continue;
815      unsigned Reg = MO.getReg();
816      if (!Reg) continue;
817      if (TargetRegisterInfo::isVirtualRegister(Reg)) {
818        VirtOpEnd = i+1;
819        if (MO.isUse()) {
820          hasTiedOps = hasTiedOps ||
821                                TID.getOperandConstraint(i, TOI::TIED_TO) != -1;
822        } else {
823          if (MO.isEarlyClobber())
824            hasEarlyClobbers = true;
825          if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
826            hasPartialRedefs = true;
827        }
828        continue;
829      }
830      if (!Allocatable.test(Reg)) continue;
831      if (MO.isUse()) {
832        usePhysReg(MO);
833      } else if (MO.isEarlyClobber()) {
834        definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
835                               regFree : regReserved);
836        hasEarlyClobbers = true;
837      } else
838        hasPhysDefs = true;
839    }
840
841    // The instruction may have virtual register operands that must be allocated
842    // the same register at use-time and def-time: early clobbers and tied
843    // operands. If there are also physical defs, these registers must avoid
844    // both physical defs and uses, making them more constrained than normal
845    // operands.
846    // We didn't detect inline asm tied operands above, so just make this extra
847    // pass for all inline asm.
848    if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
849        (hasTiedOps && hasPhysDefs)) {
850      handleThroughOperands(MI, VirtDead);
851      // Don't attempt coalescing when we have funny stuff going on.
852      CopyDst = 0;
853    }
854
855    // Second scan.
856    // Allocate virtreg uses.
857    for (unsigned i = 0; i != VirtOpEnd; ++i) {
858      MachineOperand &MO = MI->getOperand(i);
859      if (!MO.isReg()) continue;
860      unsigned Reg = MO.getReg();
861      if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
862      if (MO.isUse()) {
863        LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
864        unsigned PhysReg = LRI->second.PhysReg;
865        CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
866        if (setPhysReg(MI, i, PhysReg))
867          killVirtReg(LRI);
868      }
869    }
870
871    MRI->addPhysRegsUsed(UsedInInstr);
872
873    // Track registers defined by instruction - early clobbers at this point.
874    UsedInInstr.reset();
875    if (hasEarlyClobbers) {
876      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
877        MachineOperand &MO = MI->getOperand(i);
878        if (!MO.isReg() || !MO.isDef()) continue;
879        unsigned Reg = MO.getReg();
880        if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
881        UsedInInstr.set(Reg);
882        for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
883          UsedInInstr.set(*AS);
884      }
885    }
886
887    unsigned DefOpEnd = MI->getNumOperands();
888    if (TID.isCall()) {
889      // Spill all virtregs before a call. This serves two purposes: 1. If an
890      // exception is thrown, the landing pad is going to expect to find registers
891      // in their spill slots, and 2. we don't have to wade through all the
892      // <imp-def> operands on the call instruction.
893      DefOpEnd = VirtOpEnd;
894      DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
895      spillAll(MI);
896
897      // The imp-defs are skipped below, but we still need to mark those
898      // registers as used by the function.
899      SkippedInstrs.insert(&TID);
900    }
901
902    // Third scan.
903    // Allocate defs and collect dead defs.
904    for (unsigned i = 0; i != DefOpEnd; ++i) {
905      MachineOperand &MO = MI->getOperand(i);
906      if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
907        continue;
908      unsigned Reg = MO.getReg();
909
910      if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
911        if (!Allocatable.test(Reg)) continue;
912        definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
913                               regFree : regReserved);
914        continue;
915      }
916      LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
917      unsigned PhysReg = LRI->second.PhysReg;
918      if (setPhysReg(MI, i, PhysReg)) {
919        VirtDead.push_back(Reg);
920        CopyDst = 0; // cancel coalescing;
921      } else
922        CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
923    }
924
925    // Kill dead defs after the scan to ensure that multiple defs of the same
926    // register are allocated identically. We didn't need to do this for uses
927    // because we are crerating our own kill flags, and they are always at the
928    // last use.
929    for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
930      killVirtReg(VirtDead[i]);
931    VirtDead.clear();
932
933    MRI->addPhysRegsUsed(UsedInInstr);
934
935    if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
936      DEBUG(dbgs() << "-- coalescing: " << *MI);
937      Coalesced.push_back(MI);
938    } else {
939      DEBUG(dbgs() << "<< " << *MI);
940    }
941  }
942
943  // Spill all physical registers holding virtual registers now.
944  DEBUG(dbgs() << "Spilling live registers at end of block.\n");
945  spillAll(MBB->getFirstTerminator());
946
947  // Erase all the coalesced copies. We are delaying it until now because
948  // LiveVirtRegs might refer to the instrs.
949  for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
950    MBB->erase(Coalesced[i]);
951  NumCopies += Coalesced.size();
952
953  DEBUG(MBB->dump());
954}
955
956/// runOnMachineFunction - Register allocate the whole function
957///
958bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
959  DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
960               << "********** Function: "
961               << ((Value*)Fn.getFunction())->getName() << '\n');
962  MF = &Fn;
963  MRI = &MF->getRegInfo();
964  TM = &Fn.getTarget();
965  TRI = TM->getRegisterInfo();
966  TII = TM->getInstrInfo();
967
968  UsedInInstr.resize(TRI->getNumRegs());
969  Allocatable = TRI->getAllocatableSet(*MF);
970
971  // initialize the virtual->physical register map to have a 'null'
972  // mapping for all virtual registers
973  unsigned LastVirtReg = MRI->getLastVirtReg();
974  StackSlotForVirtReg.grow(LastVirtReg);
975
976  // Loop over all of the basic blocks, eliminating virtual register references
977  for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
978       MBBi != MBBe; ++MBBi) {
979    MBB = &*MBBi;
980    AllocateBasicBlock();
981  }
982
983  // Make sure the set of used physregs is closed under subreg operations.
984  MRI->closePhysRegsUsed(*TRI);
985
986  // Add the clobber lists for all the instructions we skipped earlier.
987  for (SmallPtrSet<const TargetInstrDesc*, 4>::const_iterator
988       I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
989    if (const unsigned *Defs = (*I)->getImplicitDefs())
990      while (*Defs)
991        MRI->setPhysRegUsed(*Defs++);
992
993  SkippedInstrs.clear();
994  StackSlotForVirtReg.clear();
995  return true;
996}
997
998FunctionPass *llvm::createFastRegisterAllocator() {
999  return new RAFast();
1000}
1001