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