Be less aggressive about hinting in RAFast.
[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, MachineInstr *> 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 TargetInstrDesc*, 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     if (MachineInstr *DBG = LiveDbgValueMap.lookup(LRI->first)) {
276       const MDNode *MDPtr =
277         DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
278       int64_t Offset = 0;
279       if (DBG->getOperand(1).isImm())
280         Offset = DBG->getOperand(1).getImm();
281       DebugLoc DL;
282       if (MI == MBB->end()) {
283         // If MI is at basic block end then use last instruction's location.
284         MachineBasicBlock::iterator EI = MI;
285         DL = (--EI)->getDebugLoc();
286       }
287       else
288         DL = MI->getDebugLoc();
289       if (MachineInstr *NewDV =
290           TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
291         MachineBasicBlock *MBB = DBG->getParent();
292         MBB->insert(MI, NewDV);
293         DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
294         LiveDbgValueMap[LRI->first] = NewDV;
295       }
296     }
297     if (SpillKill)
298       LR.LastUse = 0; // Don't kill register again
299   }
300   killVirtReg(LRI);
301 }
302
303 /// spillAll - Spill all dirty virtregs without killing them.
304 void RAFast::spillAll(MachineInstr *MI) {
305   if (LiveVirtRegs.empty()) return;
306   isBulkSpilling = true;
307   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
308   // of spilling here is deterministic, if arbitrary.
309   for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
310        i != e; ++i)
311     spillVirtReg(MI, i);
312   LiveVirtRegs.clear();
313   isBulkSpilling = false;
314 }
315
316 /// usePhysReg - Handle the direct use of a physical register.
317 /// Check that the register is not used by a virtreg.
318 /// Kill the physreg, marking it free.
319 /// This may add implicit kills to MO->getParent() and invalidate MO.
320 void RAFast::usePhysReg(MachineOperand &MO) {
321   unsigned PhysReg = MO.getReg();
322   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
323          "Bad usePhysReg operand");
324
325   switch (PhysRegState[PhysReg]) {
326   case regDisabled:
327     break;
328   case regReserved:
329     PhysRegState[PhysReg] = regFree;
330     // Fall through
331   case regFree:
332     UsedInInstr.set(PhysReg);
333     MO.setIsKill();
334     return;
335   default:
336     // The physreg was allocated to a virtual register. That means the value we
337     // wanted has been clobbered.
338     llvm_unreachable("Instruction uses an allocated register");
339   }
340
341   // Maybe a superregister is reserved?
342   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
343        unsigned Alias = *AS; ++AS) {
344     switch (PhysRegState[Alias]) {
345     case regDisabled:
346       break;
347     case regReserved:
348       assert(TRI->isSuperRegister(PhysReg, Alias) &&
349              "Instruction is not using a subregister of a reserved register");
350       // Leave the superregister in the working set.
351       PhysRegState[Alias] = regFree;
352       UsedInInstr.set(Alias);
353       MO.getParent()->addRegisterKilled(Alias, TRI, true);
354       return;
355     case regFree:
356       if (TRI->isSuperRegister(PhysReg, Alias)) {
357         // Leave the superregister in the working set.
358         UsedInInstr.set(Alias);
359         MO.getParent()->addRegisterKilled(Alias, TRI, true);
360         return;
361       }
362       // Some other alias was in the working set - clear it.
363       PhysRegState[Alias] = regDisabled;
364       break;
365     default:
366       llvm_unreachable("Instruction uses an alias of an allocated register");
367     }
368   }
369
370   // All aliases are disabled, bring register into working set.
371   PhysRegState[PhysReg] = regFree;
372   UsedInInstr.set(PhysReg);
373   MO.setIsKill();
374 }
375
376 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
377 /// virtregs. This is very similar to defineVirtReg except the physreg is
378 /// reserved instead of allocated.
379 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
380                            RegState NewState) {
381   UsedInInstr.set(PhysReg);
382   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
383   case regDisabled:
384     break;
385   default:
386     spillVirtReg(MI, VirtReg);
387     // Fall through.
388   case regFree:
389   case regReserved:
390     PhysRegState[PhysReg] = NewState;
391     return;
392   }
393
394   // This is a disabled register, disable all aliases.
395   PhysRegState[PhysReg] = NewState;
396   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
397        unsigned Alias = *AS; ++AS) {
398     switch (unsigned VirtReg = PhysRegState[Alias]) {
399     case regDisabled:
400       break;
401     default:
402       spillVirtReg(MI, VirtReg);
403       // Fall through.
404     case regFree:
405     case regReserved:
406       PhysRegState[Alias] = regDisabled;
407       if (TRI->isSuperRegister(PhysReg, Alias))
408         return;
409       break;
410     }
411   }
412 }
413
414
415 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
416 // aliases so it is free for allocation.
417 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
418 // can be allocated directly.
419 // Returns spillImpossible when PhysReg or an alias can't be spilled.
420 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
421   if (UsedInInstr.test(PhysReg)) {
422     DEBUG(dbgs() << "PhysReg: " << PhysReg << " is already used in instr.\n");
423     return spillImpossible;
424   }
425   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
426   case regDisabled:
427     break;
428   case regFree:
429     return 0;
430   case regReserved:
431     DEBUG(dbgs() << "VirtReg: " << VirtReg << " corresponding to PhysReg: "
432           << PhysReg << " is reserved already.\n");
433     return spillImpossible;
434   default:
435     return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
436   }
437
438   // This is a disabled register, add up cost of aliases.
439   DEBUG(dbgs() << "\tRegister: " << PhysReg << " is disabled.\n");
440   unsigned Cost = 0;
441   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
442        unsigned Alias = *AS; ++AS) {
443     if (UsedInInstr.test(Alias))
444       return spillImpossible;
445     switch (unsigned VirtReg = PhysRegState[Alias]) {
446     case regDisabled:
447       break;
448     case regFree:
449       ++Cost;
450       break;
451     case regReserved:
452       return spillImpossible;
453     default:
454       Cost += LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
455       break;
456     }
457   }
458   return Cost;
459 }
460
461
462 /// assignVirtToPhysReg - This method updates local state so that we know
463 /// that PhysReg is the proper container for VirtReg now.  The physical
464 /// register must not be used for anything else when this is called.
465 ///
466 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
467   DEBUG(dbgs() << "Assigning " << PrintReg(LRE.first, TRI) << " to "
468                << PrintReg(PhysReg, TRI) << "\n");
469   PhysRegState[PhysReg] = LRE.first;
470   assert(!LRE.second.PhysReg && "Already assigned a physreg");
471   LRE.second.PhysReg = PhysReg;
472 }
473
474 /// allocVirtReg - Allocate a physical register for VirtReg.
475 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
476   const unsigned VirtReg = LRE.first;
477
478   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
479          "Can only allocate virtual registers");
480
481   const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
482
483   // Ignore invalid hints.
484   if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
485                !RC->contains(Hint) || !RegClassInfo.isAllocatable(Hint)))
486     Hint = 0;
487
488   // Take hint when possible.
489   if (Hint) {
490     // Ignore the hint if we would have to spill a dirty register.
491     unsigned Cost = calcSpillCost(Hint);
492     if (Cost < spillDirty) {
493       if (Cost)
494         definePhysReg(MI, Hint, regFree);
495       return assignVirtToPhysReg(LRE, Hint);
496     }
497   }
498
499   ArrayRef<unsigned> AO = RegClassInfo.getOrder(RC);
500
501   // First try to find a completely free register.
502   for (ArrayRef<unsigned>::iterator I = AO.begin(), E = AO.end(); I != E; ++I) {
503     unsigned PhysReg = *I;
504     if (PhysRegState[PhysReg] == regFree && !UsedInInstr.test(PhysReg))
505       return assignVirtToPhysReg(LRE, PhysReg);
506   }
507
508   DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
509                << RC->getName() << "\n");
510
511   unsigned BestReg = 0, BestCost = spillImpossible;
512   for (ArrayRef<unsigned>::iterator I = AO.begin(), E = AO.end(); I != E; ++I) {
513     unsigned Cost = calcSpillCost(*I);
514     DEBUG(dbgs() << "\tRegister: " << *I << "\n");
515     DEBUG(dbgs() << "\tCost: " << Cost << "\n");
516     DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
517     // Cost is 0 when all aliases are already disabled.
518     if (Cost == 0)
519       return assignVirtToPhysReg(LRE, *I);
520     if (Cost < BestCost)
521       BestReg = *I, BestCost = Cost;
522   }
523
524   if (BestReg) {
525     definePhysReg(MI, BestReg, regFree);
526     return assignVirtToPhysReg(LRE, BestReg);
527   }
528
529   // Nothing we can do.
530   std::string msg;
531   raw_string_ostream Msg(msg);
532   Msg << "Ran out of registers during register allocation!";
533   if (MI->isInlineAsm()) {
534     Msg << "\nPlease check your inline asm statement for "
535         << "invalid constraints:\n";
536     MI->print(Msg, TM);
537   }
538   report_fatal_error(Msg.str());
539 }
540
541 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
542 RAFast::LiveRegMap::iterator
543 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
544                       unsigned VirtReg, unsigned Hint) {
545   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
546          "Not a virtual register");
547   LiveRegMap::iterator LRI;
548   bool New;
549   tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
550   LiveReg &LR = LRI->second;
551   if (New) {
552     // If there is no hint, peek at the only use of this register.
553     if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
554         MRI->hasOneNonDBGUse(VirtReg)) {
555       const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
556       // It's a copy, use the destination register as a hint.
557       if (UseMI.isCopyLike())
558         Hint = UseMI.getOperand(0).getReg();
559     }
560     allocVirtReg(MI, *LRI, Hint);
561   } else if (LR.LastUse) {
562     // Redefining a live register - kill at the last use, unless it is this
563     // instruction defining VirtReg multiple times.
564     if (LR.LastUse != MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
565       addKillFlag(LR);
566   }
567   assert(LR.PhysReg && "Register not assigned");
568   LR.LastUse = MI;
569   LR.LastOpNum = OpNum;
570   LR.Dirty = true;
571   UsedInInstr.set(LR.PhysReg);
572   return LRI;
573 }
574
575 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
576 RAFast::LiveRegMap::iterator
577 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
578                       unsigned VirtReg, unsigned Hint) {
579   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
580          "Not a virtual register");
581   LiveRegMap::iterator LRI;
582   bool New;
583   tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
584   LiveReg &LR = LRI->second;
585   MachineOperand &MO = MI->getOperand(OpNum);
586   if (New) {
587     allocVirtReg(MI, *LRI, Hint);
588     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
589     int FrameIndex = getStackSpaceFor(VirtReg, RC);
590     DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
591                  << PrintReg(LR.PhysReg, TRI) << "\n");
592     TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
593     ++NumLoads;
594   } else if (LR.Dirty) {
595     if (isLastUseOfLocalReg(MO)) {
596       DEBUG(dbgs() << "Killing last use: " << MO << "\n");
597       if (MO.isUse())
598         MO.setIsKill();
599       else
600         MO.setIsDead();
601     } else if (MO.isKill()) {
602       DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
603       MO.setIsKill(false);
604     } else if (MO.isDead()) {
605       DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
606       MO.setIsDead(false);
607     }
608   } else if (MO.isKill()) {
609     // We must remove kill flags from uses of reloaded registers because the
610     // register would be killed immediately, and there might be a second use:
611     //   %foo = OR %x<kill>, %x
612     // This would cause a second reload of %x into a different register.
613     DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
614     MO.setIsKill(false);
615   } else if (MO.isDead()) {
616     DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
617     MO.setIsDead(false);
618   }
619   assert(LR.PhysReg && "Register not assigned");
620   LR.LastUse = MI;
621   LR.LastOpNum = OpNum;
622   UsedInInstr.set(LR.PhysReg);
623   return LRI;
624 }
625
626 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
627 // subregs. This may invalidate any operand pointers.
628 // Return true if the operand kills its register.
629 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
630   MachineOperand &MO = MI->getOperand(OpNum);
631   if (!MO.getSubReg()) {
632     MO.setReg(PhysReg);
633     return MO.isKill() || MO.isDead();
634   }
635
636   // Handle subregister index.
637   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
638   MO.setSubReg(0);
639
640   // A kill flag implies killing the full register. Add corresponding super
641   // register kill.
642   if (MO.isKill()) {
643     MI->addRegisterKilled(PhysReg, TRI, true);
644     return true;
645   }
646   return MO.isDead();
647 }
648
649 // Handle special instruction operand like early clobbers and tied ops when
650 // there are additional physreg defines.
651 void RAFast::handleThroughOperands(MachineInstr *MI,
652                                    SmallVectorImpl<unsigned> &VirtDead) {
653   DEBUG(dbgs() << "Scanning for through registers:");
654   SmallSet<unsigned, 8> ThroughRegs;
655   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
656     MachineOperand &MO = MI->getOperand(i);
657     if (!MO.isReg()) continue;
658     unsigned Reg = MO.getReg();
659     if (!TargetRegisterInfo::isVirtualRegister(Reg))
660       continue;
661     if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
662         (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
663       if (ThroughRegs.insert(Reg))
664         DEBUG(dbgs() << ' ' << PrintReg(Reg));
665     }
666   }
667
668   // If any physreg defines collide with preallocated through registers,
669   // we must spill and reallocate.
670   DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
671   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
672     MachineOperand &MO = MI->getOperand(i);
673     if (!MO.isReg() || !MO.isDef()) continue;
674     unsigned Reg = MO.getReg();
675     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
676     UsedInInstr.set(Reg);
677     if (ThroughRegs.count(PhysRegState[Reg]))
678       definePhysReg(MI, Reg, regFree);
679     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
680       UsedInInstr.set(*AS);
681       if (ThroughRegs.count(PhysRegState[*AS]))
682         definePhysReg(MI, *AS, regFree);
683     }
684   }
685
686   SmallVector<unsigned, 8> PartialDefs;
687   DEBUG(dbgs() << "Allocating tied uses and early clobbers.\n");
688   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
689     MachineOperand &MO = MI->getOperand(i);
690     if (!MO.isReg()) continue;
691     unsigned Reg = MO.getReg();
692     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
693     if (MO.isUse()) {
694       unsigned DefIdx = 0;
695       if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
696       DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
697         << DefIdx << ".\n");
698       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
699       unsigned PhysReg = LRI->second.PhysReg;
700       setPhysReg(MI, i, PhysReg);
701       // Note: we don't update the def operand yet. That would cause the normal
702       // def-scan to attempt spilling.
703     } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
704       DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
705       // Reload the register, but don't assign to the operand just yet.
706       // That would confuse the later phys-def processing pass.
707       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
708       PartialDefs.push_back(LRI->second.PhysReg);
709     } else if (MO.isEarlyClobber()) {
710       // Note: defineVirtReg may invalidate MO.
711       LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
712       unsigned PhysReg = LRI->second.PhysReg;
713       if (setPhysReg(MI, i, PhysReg))
714         VirtDead.push_back(Reg);
715     }
716   }
717
718   // Restore UsedInInstr to a state usable for allocating normal virtual uses.
719   UsedInInstr.reset();
720   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
721     MachineOperand &MO = MI->getOperand(i);
722     if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
723     unsigned Reg = MO.getReg();
724     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
725     DEBUG(dbgs() << "\tSetting reg " << Reg << " as used in instr\n");
726     UsedInInstr.set(Reg);
727   }
728
729   // Also mark PartialDefs as used to avoid reallocation.
730   for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
731     UsedInInstr.set(PartialDefs[i]);
732 }
733
734 void RAFast::AllocateBasicBlock() {
735   DEBUG(dbgs() << "\nAllocating " << *MBB);
736
737   // FIXME: This should probably be added by instruction selection instead?
738   // If the last instruction in the block is a return, make sure to mark it as
739   // using all of the live-out values in the function.  Things marked both call
740   // and return are tail calls; do not do this for them.  The tail callee need
741   // not take the same registers as input that it produces as output, and there
742   // are dependencies for its input registers elsewhere.
743   if (!MBB->empty() && MBB->back().getDesc().isReturn() &&
744       !MBB->back().getDesc().isCall()) {
745     MachineInstr *Ret = &MBB->back();
746
747     for (MachineRegisterInfo::liveout_iterator
748          I = MF->getRegInfo().liveout_begin(),
749          E = MF->getRegInfo().liveout_end(); I != E; ++I) {
750       assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
751              "Cannot have a live-out virtual register.");
752
753       // Add live-out registers as implicit uses.
754       Ret->addRegisterKilled(*I, TRI, true);
755     }
756   }
757
758   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
759   assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
760
761   MachineBasicBlock::iterator MII = MBB->begin();
762
763   // Add live-in registers as live.
764   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
765          E = MBB->livein_end(); I != E; ++I)
766     if (RegClassInfo.isAllocatable(*I))
767       definePhysReg(MII, *I, regReserved);
768
769   SmallVector<unsigned, 8> VirtDead;
770   SmallVector<MachineInstr*, 32> Coalesced;
771
772   // Otherwise, sequentially allocate each instruction in the MBB.
773   while (MII != MBB->end()) {
774     MachineInstr *MI = MII++;
775     const TargetInstrDesc &TID = MI->getDesc();
776     DEBUG({
777         dbgs() << "\n>> " << *MI << "Regs:";
778         for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
779           if (PhysRegState[Reg] == regDisabled) continue;
780           dbgs() << " " << TRI->getName(Reg);
781           switch(PhysRegState[Reg]) {
782           case regFree:
783             break;
784           case regReserved:
785             dbgs() << "*";
786             break;
787           default:
788             dbgs() << '=' << PrintReg(PhysRegState[Reg]);
789             if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
790               dbgs() << "*";
791             assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
792                    "Bad inverse map");
793             break;
794           }
795         }
796         dbgs() << '\n';
797         // Check that LiveVirtRegs is the inverse.
798         for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
799              e = LiveVirtRegs.end(); i != e; ++i) {
800            assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
801                   "Bad map key");
802            assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
803                   "Bad map value");
804            assert(PhysRegState[i->second.PhysReg] == i->first &&
805                   "Bad inverse map");
806         }
807       });
808
809     // Debug values are not allowed to change codegen in any way.
810     if (MI->isDebugValue()) {
811       bool ScanDbgValue = true;
812       while (ScanDbgValue) {
813         ScanDbgValue = false;
814         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
815           MachineOperand &MO = MI->getOperand(i);
816           if (!MO.isReg()) continue;
817           unsigned Reg = MO.getReg();
818           if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
819           LiveDbgValueMap[Reg] = MI;
820           LiveRegMap::iterator LRI = LiveVirtRegs.find(Reg);
821           if (LRI != LiveVirtRegs.end())
822             setPhysReg(MI, i, LRI->second.PhysReg);
823           else {
824             int SS = StackSlotForVirtReg[Reg];
825             if (SS == -1) {
826               // We can't allocate a physreg for a DebugValue, sorry!
827               DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
828               MO.setReg(0);
829             }
830             else {
831               // Modify DBG_VALUE now that the value is in a spill slot.
832               int64_t Offset = MI->getOperand(1).getImm();
833               const MDNode *MDPtr =
834                 MI->getOperand(MI->getNumOperands()-1).getMetadata();
835               DebugLoc DL = MI->getDebugLoc();
836               if (MachineInstr *NewDV =
837                   TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
838                 DEBUG(dbgs() << "Modifying debug info due to spill:" <<
839                       "\t" << *MI);
840                 MachineBasicBlock *MBB = MI->getParent();
841                 MBB->insert(MBB->erase(MI), NewDV);
842                 // Scan NewDV operands from the beginning.
843                 MI = NewDV;
844                 ScanDbgValue = true;
845                 break;
846               } else {
847                 // We can't allocate a physreg for a DebugValue; sorry!
848                 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
849                 MO.setReg(0);
850               }
851             }
852           }
853         }
854       }
855       // Next instruction.
856       continue;
857     }
858
859     // If this is a copy, we may be able to coalesce.
860     unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
861     if (MI->isCopy()) {
862       CopyDst = MI->getOperand(0).getReg();
863       CopySrc = MI->getOperand(1).getReg();
864       CopyDstSub = MI->getOperand(0).getSubReg();
865       CopySrcSub = MI->getOperand(1).getSubReg();
866     }
867
868     // Track registers used by instruction.
869     UsedInInstr.reset();
870
871     // First scan.
872     // Mark physreg uses and early clobbers as used.
873     // Find the end of the virtreg operands
874     unsigned VirtOpEnd = 0;
875     bool hasTiedOps = false;
876     bool hasEarlyClobbers = false;
877     bool hasPartialRedefs = false;
878     bool hasPhysDefs = false;
879     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
880       MachineOperand &MO = MI->getOperand(i);
881       if (!MO.isReg()) continue;
882       unsigned Reg = MO.getReg();
883       if (!Reg) continue;
884       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
885         VirtOpEnd = i+1;
886         if (MO.isUse()) {
887           hasTiedOps = hasTiedOps ||
888                                 TID.getOperandConstraint(i, TOI::TIED_TO) != -1;
889         } else {
890           if (MO.isEarlyClobber())
891             hasEarlyClobbers = true;
892           if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
893             hasPartialRedefs = true;
894         }
895         continue;
896       }
897       if (!RegClassInfo.isAllocatable(Reg)) continue;
898       if (MO.isUse()) {
899         usePhysReg(MO);
900       } else if (MO.isEarlyClobber()) {
901         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
902                                regFree : regReserved);
903         hasEarlyClobbers = true;
904       } else
905         hasPhysDefs = true;
906     }
907
908     // The instruction may have virtual register operands that must be allocated
909     // the same register at use-time and def-time: early clobbers and tied
910     // operands. If there are also physical defs, these registers must avoid
911     // both physical defs and uses, making them more constrained than normal
912     // operands.
913     // Similarly, if there are multiple defs and tied operands, we must make
914     // sure the same register is allocated to uses and defs.
915     // We didn't detect inline asm tied operands above, so just make this extra
916     // pass for all inline asm.
917     if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
918         (hasTiedOps && (hasPhysDefs || TID.getNumDefs() > 1))) {
919       handleThroughOperands(MI, VirtDead);
920       // Don't attempt coalescing when we have funny stuff going on.
921       CopyDst = 0;
922       // Pretend we have early clobbers so the use operands get marked below.
923       // This is not necessary for the common case of a single tied use.
924       hasEarlyClobbers = true;
925     }
926
927     // Second scan.
928     // Allocate virtreg uses.
929     for (unsigned i = 0; i != VirtOpEnd; ++i) {
930       MachineOperand &MO = MI->getOperand(i);
931       if (!MO.isReg()) continue;
932       unsigned Reg = MO.getReg();
933       if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
934       if (MO.isUse()) {
935         LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
936         unsigned PhysReg = LRI->second.PhysReg;
937         CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
938         if (setPhysReg(MI, i, PhysReg))
939           killVirtReg(LRI);
940       }
941     }
942
943     MRI->addPhysRegsUsed(UsedInInstr);
944
945     // Track registers defined by instruction - early clobbers and tied uses at
946     // this point.
947     UsedInInstr.reset();
948     if (hasEarlyClobbers) {
949       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
950         MachineOperand &MO = MI->getOperand(i);
951         if (!MO.isReg()) continue;
952         unsigned Reg = MO.getReg();
953         if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
954         // Look for physreg defs and tied uses.
955         if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
956         UsedInInstr.set(Reg);
957         for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
958           UsedInInstr.set(*AS);
959       }
960     }
961
962     unsigned DefOpEnd = MI->getNumOperands();
963     if (TID.isCall()) {
964       // Spill all virtregs before a call. This serves two purposes: 1. If an
965       // exception is thrown, the landing pad is going to expect to find
966       // registers in their spill slots, and 2. we don't have to wade through
967       // all the <imp-def> operands on the call instruction.
968       DefOpEnd = VirtOpEnd;
969       DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
970       spillAll(MI);
971
972       // The imp-defs are skipped below, but we still need to mark those
973       // registers as used by the function.
974       SkippedInstrs.insert(&TID);
975     }
976
977     // Third scan.
978     // Allocate defs and collect dead defs.
979     for (unsigned i = 0; i != DefOpEnd; ++i) {
980       MachineOperand &MO = MI->getOperand(i);
981       if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
982         continue;
983       unsigned Reg = MO.getReg();
984
985       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
986         if (!RegClassInfo.isAllocatable(Reg)) continue;
987         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
988                                regFree : regReserved);
989         continue;
990       }
991       LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
992       unsigned PhysReg = LRI->second.PhysReg;
993       if (setPhysReg(MI, i, PhysReg)) {
994         VirtDead.push_back(Reg);
995         CopyDst = 0; // cancel coalescing;
996       } else
997         CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
998     }
999
1000     // Kill dead defs after the scan to ensure that multiple defs of the same
1001     // register are allocated identically. We didn't need to do this for uses
1002     // because we are crerating our own kill flags, and they are always at the
1003     // last use.
1004     for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1005       killVirtReg(VirtDead[i]);
1006     VirtDead.clear();
1007
1008     MRI->addPhysRegsUsed(UsedInInstr);
1009
1010     if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1011       DEBUG(dbgs() << "-- coalescing: " << *MI);
1012       Coalesced.push_back(MI);
1013     } else {
1014       DEBUG(dbgs() << "<< " << *MI);
1015     }
1016   }
1017
1018   // Spill all physical registers holding virtual registers now.
1019   DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1020   spillAll(MBB->getFirstTerminator());
1021
1022   // Erase all the coalesced copies. We are delaying it until now because
1023   // LiveVirtRegs might refer to the instrs.
1024   for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1025     MBB->erase(Coalesced[i]);
1026   NumCopies += Coalesced.size();
1027
1028   DEBUG(MBB->dump());
1029 }
1030
1031 /// runOnMachineFunction - Register allocate the whole function
1032 ///
1033 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1034   DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1035                << "********** Function: "
1036                << ((Value*)Fn.getFunction())->getName() << '\n');
1037   MF = &Fn;
1038   MRI = &MF->getRegInfo();
1039   TM = &Fn.getTarget();
1040   TRI = TM->getRegisterInfo();
1041   TII = TM->getInstrInfo();
1042   RegClassInfo.runOnMachineFunction(Fn);
1043   UsedInInstr.resize(TRI->getNumRegs());
1044
1045   // initialize the virtual->physical register map to have a 'null'
1046   // mapping for all virtual registers
1047   StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1048
1049   // Loop over all of the basic blocks, eliminating virtual register references
1050   for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1051        MBBi != MBBe; ++MBBi) {
1052     MBB = &*MBBi;
1053     AllocateBasicBlock();
1054   }
1055
1056   // Make sure the set of used physregs is closed under subreg operations.
1057   MRI->closePhysRegsUsed(*TRI);
1058
1059   // Add the clobber lists for all the instructions we skipped earlier.
1060   for (SmallPtrSet<const TargetInstrDesc*, 4>::const_iterator
1061        I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1062     if (const unsigned *Defs = (*I)->getImplicitDefs())
1063       while (*Defs)
1064         MRI->setPhysRegUsed(*Defs++);
1065
1066   SkippedInstrs.clear();
1067   StackSlotForVirtReg.clear();
1068   LiveDbgValueMap.clear();
1069   return true;
1070 }
1071
1072 FunctionPass *llvm::createFastRegisterAllocator() {
1073   return new RAFast();
1074 }