<rdar://problem/6721894>. Allow multiple registers to be renamed together (super...
[oota-llvm.git] / lib / CodeGen / AggressiveAntiDepBreaker.cpp
1 //===----- AggressiveAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===//
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 file implements the AggressiveAntiDepBreaker class, which
11 // implements register anti-dependence breaking during post-RA
12 // scheduling. It attempts to break all anti-dependencies within a
13 // block.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "post-RA-sched"
18 #include "AggressiveAntiDepBreaker.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetRegisterInfo.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 using namespace llvm;
30
31 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
32 static cl::opt<int>
33 DebugDiv("agg-antidep-debugdiv",
34                       cl::desc("Debug control for aggressive anti-dep breaker"),
35                       cl::init(0), cl::Hidden);
36 static cl::opt<int>
37 DebugMod("agg-antidep-debugmod",
38                       cl::desc("Debug control for aggressive anti-dep breaker"),
39                       cl::init(0), cl::Hidden);
40
41 AggressiveAntiDepState::AggressiveAntiDepState(MachineBasicBlock *BB) :
42   GroupNodes(TargetRegisterInfo::FirstVirtualRegister, 0) {
43   // Initialize all registers to be in their own group. Initially we
44   // assign the register to the same-indexed GroupNode.
45   for (unsigned i = 0; i < TargetRegisterInfo::FirstVirtualRegister; ++i)
46     GroupNodeIndices[i] = i;
47
48   // Initialize the indices to indicate that no registers are live.
49   std::fill(KillIndices, array_endof(KillIndices), ~0u);
50   std::fill(DefIndices, array_endof(DefIndices), BB->size());
51 }
52
53 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg)
54 {
55   unsigned Node = GroupNodeIndices[Reg];
56   while (GroupNodes[Node] != Node)
57     Node = GroupNodes[Node];
58
59   return Node;
60 }
61
62 void AggressiveAntiDepState::GetGroupRegs(
63   unsigned Group,
64   std::vector<unsigned> &Regs,
65   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
66 {
67   for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg) {
68     if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
69       Regs.push_back(Reg);
70   }
71 }
72
73 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
74 {
75   assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
76   assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
77   
78   // find group for each register
79   unsigned Group1 = GetGroup(Reg1);
80   unsigned Group2 = GetGroup(Reg2);
81   
82   // if either group is 0, then that must become the parent
83   unsigned Parent = (Group1 == 0) ? Group1 : Group2;
84   unsigned Other = (Parent == Group1) ? Group2 : Group1;
85   GroupNodes.at(Other) = Parent;
86   return Parent;
87 }
88   
89 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
90 {
91   // Create a new GroupNode for Reg. Reg's existing GroupNode must
92   // stay as is because there could be other GroupNodes referring to
93   // it.
94   unsigned idx = GroupNodes.size();
95   GroupNodes.push_back(idx);
96   GroupNodeIndices[Reg] = idx;
97   return idx;
98 }
99
100 bool AggressiveAntiDepState::IsLive(unsigned Reg)
101 {
102   // KillIndex must be defined and DefIndex not defined for a register
103   // to be live.
104   return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
105 }
106
107
108
109 AggressiveAntiDepBreaker::
110 AggressiveAntiDepBreaker(MachineFunction& MFi,
111                          TargetSubtarget::RegClassVector& CriticalPathRCs) : 
112   AntiDepBreaker(), MF(MFi),
113   MRI(MF.getRegInfo()),
114   TRI(MF.getTarget().getRegisterInfo()),
115   AllocatableSet(TRI->getAllocatableSet(MF)),
116   State(NULL) {
117   /* Collect a bitset of all registers that are only broken if they
118      are on the critical path. */
119   for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
120     BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
121     if (CriticalPathSet.none())
122       CriticalPathSet = CPSet;
123     else
124       CriticalPathSet |= CPSet;
125    }
126  
127   DEBUG(errs() << "AntiDep Critical-Path Registers:");
128   DEBUG(for (int r = CriticalPathSet.find_first(); r != -1; 
129              r = CriticalPathSet.find_next(r))
130           errs() << " " << TRI->getName(r));
131   DEBUG(errs() << '\n');
132 }
133
134 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
135   delete State;
136 }
137
138 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
139   assert(State == NULL);
140   State = new AggressiveAntiDepState(BB);
141
142   bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
143   unsigned *KillIndices = State->GetKillIndices();
144   unsigned *DefIndices = State->GetDefIndices();
145
146   // Determine the live-out physregs for this block.
147   if (IsReturnBlock) {
148     // In a return block, examine the function live-out regs.
149     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
150          E = MRI.liveout_end(); I != E; ++I) {
151       unsigned Reg = *I;
152       State->UnionGroups(Reg, 0);
153       KillIndices[Reg] = BB->size();
154       DefIndices[Reg] = ~0u;
155       // Repeat, for all aliases.
156       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
157         unsigned AliasReg = *Alias;
158         State->UnionGroups(AliasReg, 0);
159         KillIndices[AliasReg] = BB->size();
160         DefIndices[AliasReg] = ~0u;
161       }
162     }
163   } else {
164     // In a non-return block, examine the live-in regs of all successors.
165     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
166          SE = BB->succ_end(); SI != SE; ++SI)
167       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
168            E = (*SI)->livein_end(); I != E; ++I) {
169         unsigned Reg = *I;
170         State->UnionGroups(Reg, 0);
171         KillIndices[Reg] = BB->size();
172         DefIndices[Reg] = ~0u;
173         // Repeat, for all aliases.
174         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
175           unsigned AliasReg = *Alias;
176           State->UnionGroups(AliasReg, 0);
177           KillIndices[AliasReg] = BB->size();
178           DefIndices[AliasReg] = ~0u;
179         }
180       }
181   }
182
183   // Mark live-out callee-saved registers. In a return block this is
184   // all callee-saved registers. In non-return this is any
185   // callee-saved register that is not saved in the prolog.
186   const MachineFrameInfo *MFI = MF.getFrameInfo();
187   BitVector Pristine = MFI->getPristineRegs(BB);
188   for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
189     unsigned Reg = *I;
190     if (!IsReturnBlock && !Pristine.test(Reg)) continue;
191     State->UnionGroups(Reg, 0);
192     KillIndices[Reg] = BB->size();
193     DefIndices[Reg] = ~0u;
194     // Repeat, for all aliases.
195     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
196       unsigned AliasReg = *Alias;
197       State->UnionGroups(AliasReg, 0);
198       KillIndices[AliasReg] = BB->size();
199       DefIndices[AliasReg] = ~0u;
200     }
201   }
202 }
203
204 void AggressiveAntiDepBreaker::FinishBlock() {
205   delete State;
206   State = NULL;
207 }
208
209 void AggressiveAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
210                                      unsigned InsertPosIndex) {
211   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
212
213   std::set<unsigned> PassthruRegs;
214   GetPassthruRegs(MI, PassthruRegs);
215   PrescanInstruction(MI, Count, PassthruRegs);
216   ScanInstruction(MI, Count);
217
218   DEBUG(errs() << "Observe: ");
219   DEBUG(MI->dump());
220   DEBUG(errs() << "\tRegs:");
221
222   unsigned *DefIndices = State->GetDefIndices();
223   for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg) {
224     // If Reg is current live, then mark that it can't be renamed as
225     // we don't know the extent of its live-range anymore (now that it
226     // has been scheduled). If it is not live but was defined in the
227     // previous schedule region, then set its def index to the most
228     // conservative location (i.e. the beginning of the previous
229     // schedule region).
230     if (State->IsLive(Reg)) {
231       DEBUG(if (State->GetGroup(Reg) != 0)
232               errs() << " " << TRI->getName(Reg) << "=g" << 
233                 State->GetGroup(Reg) << "->g0(region live-out)");
234       State->UnionGroups(Reg, 0);
235     } else if ((DefIndices[Reg] < InsertPosIndex) && (DefIndices[Reg] >= Count)) {
236       DefIndices[Reg] = Count;
237     }
238   }
239   DEBUG(errs() << '\n');
240 }
241
242 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr *MI,
243                                             MachineOperand& MO)
244 {
245   if (!MO.isReg() || !MO.isImplicit())
246     return false;
247
248   unsigned Reg = MO.getReg();
249   if (Reg == 0)
250     return false;
251
252   MachineOperand *Op = NULL;
253   if (MO.isDef())
254     Op = MI->findRegisterUseOperand(Reg, true);
255   else
256     Op = MI->findRegisterDefOperand(Reg);
257
258   return((Op != NULL) && Op->isImplicit());
259 }
260
261 void AggressiveAntiDepBreaker::GetPassthruRegs(MachineInstr *MI,
262                                            std::set<unsigned>& PassthruRegs) {
263   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
264     MachineOperand &MO = MI->getOperand(i);
265     if (!MO.isReg()) continue;
266     if ((MO.isDef() && MI->isRegTiedToUseOperand(i)) || 
267         IsImplicitDefUse(MI, MO)) {
268       const unsigned Reg = MO.getReg();
269       PassthruRegs.insert(Reg);
270       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
271            *Subreg; ++Subreg) {
272         PassthruRegs.insert(*Subreg);
273       }
274     }
275   }
276 }
277
278 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
279 /// in SU that we want to consider for breaking.
280 static void AntiDepEdges(SUnit *SU, std::vector<SDep*>& Edges) {
281   SmallSet<unsigned, 4> RegSet;
282   for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
283        P != PE; ++P) {
284     if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
285       unsigned Reg = P->getReg();
286       if (RegSet.count(Reg) == 0) {
287         Edges.push_back(&*P);
288         RegSet.insert(Reg);
289       }
290     }
291   }
292 }
293
294 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
295 /// critical path.
296 static SUnit *CriticalPathStep(SUnit *SU) {
297   SDep *Next = 0;
298   unsigned NextDepth = 0;
299   // Find the predecessor edge with the greatest depth.
300   if (SU != 0) {
301     for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
302          P != PE; ++P) {
303       SUnit *PredSU = P->getSUnit();
304       unsigned PredLatency = P->getLatency();
305       unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
306       // In the case of a latency tie, prefer an anti-dependency edge over
307       // other types of edges.
308       if (NextDepth < PredTotalLatency ||
309           (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
310         NextDepth = PredTotalLatency;
311         Next = &*P;
312       }
313     }
314   }
315
316   return (Next) ? Next->getSUnit() : 0;
317 }
318
319 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
320                                              const char *tag, const char *header,
321                                              const char *footer) {
322   unsigned *KillIndices = State->GetKillIndices();
323   unsigned *DefIndices = State->GetDefIndices();
324   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>& 
325     RegRefs = State->GetRegRefs();
326
327   if (!State->IsLive(Reg)) {
328     KillIndices[Reg] = KillIdx;
329     DefIndices[Reg] = ~0u;
330     RegRefs.erase(Reg);
331     State->LeaveGroup(Reg);
332     DEBUG(if (header != NULL) {
333         errs() << header << TRI->getName(Reg); header = NULL; });
334     DEBUG(errs() << "->g" << State->GetGroup(Reg) << tag);
335   }
336   // Repeat for subregisters.
337   for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
338        *Subreg; ++Subreg) {
339     unsigned SubregReg = *Subreg;
340     if (!State->IsLive(SubregReg)) {
341       KillIndices[SubregReg] = KillIdx;
342       DefIndices[SubregReg] = ~0u;
343       RegRefs.erase(SubregReg);
344       State->LeaveGroup(SubregReg);
345       DEBUG(if (header != NULL) {
346           errs() << header << TRI->getName(Reg); header = NULL; });
347       DEBUG(errs() << " " << TRI->getName(SubregReg) << "->g" <<
348             State->GetGroup(SubregReg) << tag);
349     }
350   }
351
352   DEBUG(if ((header == NULL) && (footer != NULL)) errs() << footer);
353 }
354
355 void AggressiveAntiDepBreaker::PrescanInstruction(MachineInstr *MI, unsigned Count,
356                                               std::set<unsigned>& PassthruRegs) {
357   unsigned *DefIndices = State->GetDefIndices();
358   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>& 
359     RegRefs = State->GetRegRefs();
360
361   // Handle dead defs by simulating a last-use of the register just
362   // after the def. A dead def can occur because the def is truely
363   // dead, or because only a subregister is live at the def. If we
364   // don't do this the dead def will be incorrectly merged into the
365   // previous def.
366   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
367     MachineOperand &MO = MI->getOperand(i);
368     if (!MO.isReg() || !MO.isDef()) continue;
369     unsigned Reg = MO.getReg();
370     if (Reg == 0) continue;
371     
372     HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
373   }
374
375   DEBUG(errs() << "\tDef Groups:");
376   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
377     MachineOperand &MO = MI->getOperand(i);
378     if (!MO.isReg() || !MO.isDef()) continue;
379     unsigned Reg = MO.getReg();
380     if (Reg == 0) continue;
381
382     DEBUG(errs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg)); 
383
384     // If MI's defs have a special allocation requirement, don't allow
385     // any def registers to be changed. Also assume all registers
386     // defined in a call must not be changed (ABI).
387     if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq()) {
388       DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
389       State->UnionGroups(Reg, 0);
390     }
391
392     // Any aliased that are live at this point are completely or
393     // partially defined here, so group those aliases with Reg.
394     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
395       unsigned AliasReg = *Alias;
396       if (State->IsLive(AliasReg)) {
397         State->UnionGroups(Reg, AliasReg);
398         DEBUG(errs() << "->g" << State->GetGroup(Reg) << "(via " << 
399               TRI->getName(AliasReg) << ")");
400       }
401     }
402     
403     // Note register reference...
404     const TargetRegisterClass *RC = NULL;
405     if (i < MI->getDesc().getNumOperands())
406       RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
407     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
408     RegRefs.insert(std::make_pair(Reg, RR));
409   }
410
411   DEBUG(errs() << '\n');
412
413   // Scan the register defs for this instruction and update
414   // live-ranges.
415   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
416     MachineOperand &MO = MI->getOperand(i);
417     if (!MO.isReg() || !MO.isDef()) continue;
418     unsigned Reg = MO.getReg();
419     if (Reg == 0) continue;
420     // Ignore KILLs and passthru registers for liveness...
421     if ((MI->getOpcode() == TargetInstrInfo::KILL) ||
422         (PassthruRegs.count(Reg) != 0))
423       continue;
424
425     // Update def for Reg and aliases.
426     DefIndices[Reg] = Count;
427     for (const unsigned *Alias = TRI->getAliasSet(Reg);
428          *Alias; ++Alias) {
429       unsigned AliasReg = *Alias;
430       DefIndices[AliasReg] = Count;
431     }
432   }
433 }
434
435 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr *MI,
436                                            unsigned Count) {
437   DEBUG(errs() << "\tUse Groups:");
438   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>& 
439     RegRefs = State->GetRegRefs();
440
441   // Scan the register uses for this instruction and update
442   // live-ranges, groups and RegRefs.
443   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
444     MachineOperand &MO = MI->getOperand(i);
445     if (!MO.isReg() || !MO.isUse()) continue;
446     unsigned Reg = MO.getReg();
447     if (Reg == 0) continue;
448     
449     DEBUG(errs() << " " << TRI->getName(Reg) << "=g" << 
450           State->GetGroup(Reg)); 
451
452     // It wasn't previously live but now it is, this is a kill. Forget
453     // the previous live-range information and start a new live-range
454     // for the register.
455     HandleLastUse(Reg, Count, "(last-use)");
456
457     // If MI's uses have special allocation requirement, don't allow
458     // any use registers to be changed. Also assume all registers
459     // used in a call must not be changed (ABI).
460     if (MI->getDesc().isCall() || MI->getDesc().hasExtraSrcRegAllocReq()) {
461       DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
462       State->UnionGroups(Reg, 0);
463     }
464
465     // Note register reference...
466     const TargetRegisterClass *RC = NULL;
467     if (i < MI->getDesc().getNumOperands())
468       RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
469     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
470     RegRefs.insert(std::make_pair(Reg, RR));
471   }
472   
473   DEBUG(errs() << '\n');
474
475   // Form a group of all defs and uses of a KILL instruction to ensure
476   // that all registers are renamed as a group.
477   if (MI->getOpcode() == TargetInstrInfo::KILL) {
478     DEBUG(errs() << "\tKill Group:");
479
480     unsigned FirstReg = 0;
481     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
482       MachineOperand &MO = MI->getOperand(i);
483       if (!MO.isReg()) continue;
484       unsigned Reg = MO.getReg();
485       if (Reg == 0) continue;
486       
487       if (FirstReg != 0) {
488         DEBUG(errs() << "=" << TRI->getName(Reg));
489         State->UnionGroups(FirstReg, Reg);
490       } else {
491         DEBUG(errs() << " " << TRI->getName(Reg));
492         FirstReg = Reg;
493       }
494     }
495   
496     DEBUG(errs() << "->g" << State->GetGroup(FirstReg) << '\n');
497   }
498 }
499
500 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
501   BitVector BV(TRI->getNumRegs(), false);
502   bool first = true;
503
504   // Check all references that need rewriting for Reg. For each, use
505   // the corresponding register class to narrow the set of registers
506   // that are appropriate for renaming.
507   std::pair<std::multimap<unsigned, 
508                      AggressiveAntiDepState::RegisterReference>::iterator,
509             std::multimap<unsigned,
510                      AggressiveAntiDepState::RegisterReference>::iterator>
511     Range = State->GetRegRefs().equal_range(Reg);
512   for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
513          Q = Range.first, QE = Range.second; Q != QE; ++Q) {
514     const TargetRegisterClass *RC = Q->second.RC;
515     if (RC == NULL) continue;
516
517     BitVector RCBV = TRI->getAllocatableSet(MF, RC);
518     if (first) {
519       BV |= RCBV;
520       first = false;
521     } else {
522       BV &= RCBV;
523     }
524
525     DEBUG(errs() << " " << RC->getName());
526   }
527   
528   return BV;
529 }  
530
531 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
532                                 unsigned AntiDepGroupIndex,
533                                 RenameOrderType& RenameOrder,
534                                 std::map<unsigned, unsigned> &RenameMap) {
535   unsigned *KillIndices = State->GetKillIndices();
536   unsigned *DefIndices = State->GetDefIndices();
537   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>& 
538     RegRefs = State->GetRegRefs();
539
540   // Collect all referenced registers in the same group as
541   // AntiDepReg. These all need to be renamed together if we are to
542   // break the anti-dependence.
543   std::vector<unsigned> Regs;
544   State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
545   assert(Regs.size() > 0 && "Empty register group!");
546   if (Regs.size() == 0)
547     return false;
548
549   // Find the "superest" register in the group. At the same time,
550   // collect the BitVector of registers that can be used to rename
551   // each register.
552   DEBUG(errs() << "\tRename Candidates for Group g" << AntiDepGroupIndex << ":\n");
553   std::map<unsigned, BitVector> RenameRegisterMap;
554   unsigned SuperReg = 0;
555   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
556     unsigned Reg = Regs[i];
557     if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
558       SuperReg = Reg;
559
560     // If Reg has any references, then collect possible rename regs
561     if (RegRefs.count(Reg) > 0) {
562       DEBUG(errs() << "\t\t" << TRI->getName(Reg) << ":");
563     
564       BitVector BV = GetRenameRegisters(Reg);
565       RenameRegisterMap.insert(std::pair<unsigned, BitVector>(Reg, BV));
566
567       DEBUG(errs() << " ::");
568       DEBUG(for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
569               errs() << " " << TRI->getName(r));
570       DEBUG(errs() << "\n");
571     }
572   }
573
574   // All group registers should be a subreg of SuperReg.
575   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
576     unsigned Reg = Regs[i];
577     if (Reg == SuperReg) continue;
578     bool IsSub = TRI->isSubRegister(SuperReg, Reg);
579     assert(IsSub && "Expecting group subregister");
580     if (!IsSub)
581       return false;
582   }
583
584 #ifndef NDEBUG
585   // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
586   if (DebugDiv > 0) {
587     static int renamecnt = 0;
588     if (renamecnt++ % DebugDiv != DebugMod)
589       return false;
590     
591     errs() << "*** Performing rename " << TRI->getName(SuperReg) <<
592       " for debug ***\n";
593   }
594 #endif
595
596   // Check each possible rename register for SuperReg in round-robin
597   // order. If that register is available, and the corresponding
598   // registers are available for the other group subregisters, then we
599   // can use those registers to rename.
600   const TargetRegisterClass *SuperRC = 
601     TRI->getPhysicalRegisterRegClass(SuperReg, MVT::Other);
602   
603   const TargetRegisterClass::iterator RB = SuperRC->allocation_order_begin(MF);
604   const TargetRegisterClass::iterator RE = SuperRC->allocation_order_end(MF);
605   if (RB == RE) {
606     DEBUG(errs() << "\tEmpty Super Regclass!!\n");
607     return false;
608   }
609
610   DEBUG(errs() << "\tFind Registers:");
611
612   if (RenameOrder.count(SuperRC) == 0)
613     RenameOrder.insert(RenameOrderType::value_type(SuperRC, RE));
614
615   const TargetRegisterClass::iterator OrigR = RenameOrder[SuperRC];
616   const TargetRegisterClass::iterator EndR = ((OrigR == RE) ? RB : OrigR);
617   TargetRegisterClass::iterator R = OrigR;
618   do {
619     if (R == RB) R = RE;
620     --R;
621     const unsigned NewSuperReg = *R;
622     // Don't replace a register with itself.
623     if (NewSuperReg == SuperReg) continue;
624     
625     DEBUG(errs() << " [" << TRI->getName(NewSuperReg) << ':');
626     RenameMap.clear();
627
628     // For each referenced group register (which must be a SuperReg or
629     // a subregister of SuperReg), find the corresponding subregister
630     // of NewSuperReg and make sure it is free to be renamed.
631     for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
632       unsigned Reg = Regs[i];
633       unsigned NewReg = 0;
634       if (Reg == SuperReg) {
635         NewReg = NewSuperReg;
636       } else {
637         unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
638         if (NewSubRegIdx != 0)
639           NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
640       }
641
642       DEBUG(errs() << " " << TRI->getName(NewReg));
643       
644       // Check if Reg can be renamed to NewReg.
645       BitVector BV = RenameRegisterMap[Reg];
646       if (!BV.test(NewReg)) {
647         DEBUG(errs() << "(no rename)");
648         goto next_super_reg;
649       }
650
651       // If NewReg is dead and NewReg's most recent def is not before
652       // Regs's kill, it's safe to replace Reg with NewReg. We
653       // must also check all aliases of NewReg, because we can't define a
654       // register when any sub or super is already live.
655       if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
656         DEBUG(errs() << "(live)");
657         goto next_super_reg;
658       } else {
659         bool found = false;
660         for (const unsigned *Alias = TRI->getAliasSet(NewReg);
661              *Alias; ++Alias) {
662           unsigned AliasReg = *Alias;
663           if (State->IsLive(AliasReg) || (KillIndices[Reg] > DefIndices[AliasReg])) {
664             DEBUG(errs() << "(alias " << TRI->getName(AliasReg) << " live)");
665             found = true;
666             break;
667           }
668         }
669         if (found)
670           goto next_super_reg;
671       }
672       
673       // Record that 'Reg' can be renamed to 'NewReg'.
674       RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
675     }
676     
677     // If we fall-out here, then every register in the group can be
678     // renamed, as recorded in RenameMap.
679     RenameOrder.erase(SuperRC);
680     RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
681     DEBUG(errs() << "]\n");
682     return true;
683
684   next_super_reg:
685     DEBUG(errs() << ']');
686   } while (R != EndR);
687
688   DEBUG(errs() << '\n');
689
690   // No registers are free and available!
691   return false;
692 }
693
694 /// BreakAntiDependencies - Identifiy anti-dependencies within the
695 /// ScheduleDAG and break them by renaming registers.
696 ///
697 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
698                               std::vector<SUnit>& SUnits,
699                               MachineBasicBlock::iterator& Begin,
700                               MachineBasicBlock::iterator& End,
701                               unsigned InsertPosIndex) {
702   unsigned *KillIndices = State->GetKillIndices();
703   unsigned *DefIndices = State->GetDefIndices();
704   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>& 
705     RegRefs = State->GetRegRefs();
706
707   // The code below assumes that there is at least one instruction,
708   // so just duck out immediately if the block is empty.
709   if (SUnits.empty()) return 0;
710   
711   // For each regclass the next register to use for renaming.
712   RenameOrderType RenameOrder;
713
714   // ...need a map from MI to SUnit.
715   std::map<MachineInstr *, SUnit *> MISUnitMap;
716   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
717     SUnit *SU = &SUnits[i];
718     MISUnitMap.insert(std::pair<MachineInstr *, SUnit *>(SU->getInstr(), SU));
719   }
720
721   // Track progress along the critical path through the SUnit graph as
722   // we walk the instructions. This is needed for regclasses that only
723   // break critical-path anti-dependencies.
724   SUnit *CriticalPathSU = 0;
725   MachineInstr *CriticalPathMI = 0;
726   if (CriticalPathSet.any()) {
727     for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
728       SUnit *SU = &SUnits[i];
729       if (!CriticalPathSU || 
730           ((SU->getDepth() + SU->Latency) > 
731            (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
732         CriticalPathSU = SU;
733       }
734     }
735     
736     CriticalPathMI = CriticalPathSU->getInstr();
737   }
738
739 #ifndef NDEBUG 
740   DEBUG(errs() << "\n===== Aggressive anti-dependency breaking\n");
741   DEBUG(errs() << "Available regs:");
742   for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
743     if (!State->IsLive(Reg))
744       DEBUG(errs() << " " << TRI->getName(Reg));
745   }
746   DEBUG(errs() << '\n');
747 #endif
748
749   // Attempt to break anti-dependence edges. Walk the instructions
750   // from the bottom up, tracking information about liveness as we go
751   // to help determine which registers are available.
752   unsigned Broken = 0;
753   unsigned Count = InsertPosIndex - 1;
754   for (MachineBasicBlock::iterator I = End, E = Begin;
755        I != E; --Count) {
756     MachineInstr *MI = --I;
757
758     DEBUG(errs() << "Anti: ");
759     DEBUG(MI->dump());
760
761     std::set<unsigned> PassthruRegs;
762     GetPassthruRegs(MI, PassthruRegs);
763
764     // Process the defs in MI...
765     PrescanInstruction(MI, Count, PassthruRegs);
766     
767     // The dependence edges that represent anti- and output-
768     // dependencies that are candidates for breaking.
769     std::vector<SDep*> Edges;
770     SUnit *PathSU = MISUnitMap[MI];
771     AntiDepEdges(PathSU, Edges);
772
773     // If MI is not on the critical path, then we don't rename
774     // registers in the CriticalPathSet.
775     BitVector *ExcludeRegs = NULL;
776     if (MI == CriticalPathMI) {
777       CriticalPathSU = CriticalPathStep(CriticalPathSU);
778       CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : 0;
779     } else { 
780       ExcludeRegs = &CriticalPathSet;
781     }
782
783     // Ignore KILL instructions (they form a group in ScanInstruction
784     // but don't cause any anti-dependence breaking themselves)
785     if (MI->getOpcode() != TargetInstrInfo::KILL) {
786       // Attempt to break each anti-dependency...
787       for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
788         SDep *Edge = Edges[i];
789         SUnit *NextSU = Edge->getSUnit();
790         
791         if ((Edge->getKind() != SDep::Anti) &&
792             (Edge->getKind() != SDep::Output)) continue;
793         
794         unsigned AntiDepReg = Edge->getReg();
795         DEBUG(errs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
796         assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
797         
798         if (!AllocatableSet.test(AntiDepReg)) {
799           // Don't break anti-dependencies on non-allocatable registers.
800           DEBUG(errs() << " (non-allocatable)\n");
801           continue;
802         } else if ((ExcludeRegs != NULL) && ExcludeRegs->test(AntiDepReg)) {
803           // Don't break anti-dependencies for critical path registers
804           // if not on the critical path
805           DEBUG(errs() << " (not critical-path)\n");
806           continue;
807         } else if (PassthruRegs.count(AntiDepReg) != 0) {
808           // If the anti-dep register liveness "passes-thru", then
809           // don't try to change it. It will be changed along with
810           // the use if required to break an earlier antidep.
811           DEBUG(errs() << " (passthru)\n");
812           continue;
813         } else {
814           // No anti-dep breaking for implicit deps
815           MachineOperand *AntiDepOp = MI->findRegisterDefOperand(AntiDepReg);
816           assert(AntiDepOp != NULL && "Can't find index for defined register operand");
817           if ((AntiDepOp == NULL) || AntiDepOp->isImplicit()) {
818             DEBUG(errs() << " (implicit)\n");
819             continue;
820           }
821           
822           // If the SUnit has other dependencies on the SUnit that
823           // it anti-depends on, don't bother breaking the
824           // anti-dependency since those edges would prevent such
825           // units from being scheduled past each other
826           // regardless.
827           //
828           // Also, if there are dependencies on other SUnits with the
829           // same register as the anti-dependency, don't attempt to
830           // break it.
831           for (SUnit::pred_iterator P = PathSU->Preds.begin(),
832                  PE = PathSU->Preds.end(); P != PE; ++P) {
833             if (P->getSUnit() == NextSU ?
834                 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
835                 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
836               AntiDepReg = 0;
837               break;
838             }
839           }
840           for (SUnit::pred_iterator P = PathSU->Preds.begin(),
841                  PE = PathSU->Preds.end(); P != PE; ++P) {
842             if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
843                 (P->getKind() != SDep::Output)) {
844               DEBUG(errs() << " (real dependency)\n");
845               AntiDepReg = 0;
846               break;
847             } else if ((P->getSUnit() != NextSU) && 
848                        (P->getKind() == SDep::Data) && 
849                        (P->getReg() == AntiDepReg)) {
850               DEBUG(errs() << " (other dependency)\n");
851               AntiDepReg = 0;
852               break;
853             }
854           }
855           
856           if (AntiDepReg == 0) continue;
857         }
858         
859         assert(AntiDepReg != 0);
860         if (AntiDepReg == 0) continue;
861         
862         // Determine AntiDepReg's register group.
863         const unsigned GroupIndex = State->GetGroup(AntiDepReg);
864         if (GroupIndex == 0) {
865           DEBUG(errs() << " (zero group)\n");
866           continue;
867         }
868         
869         DEBUG(errs() << '\n');
870         
871         // Look for a suitable register to use to break the anti-dependence.
872         std::map<unsigned, unsigned> RenameMap;
873         if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
874           DEBUG(errs() << "\tBreaking anti-dependence edge on "
875                 << TRI->getName(AntiDepReg) << ":");
876           
877           // Handle each group register...
878           for (std::map<unsigned, unsigned>::iterator
879                  S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
880             unsigned CurrReg = S->first;
881             unsigned NewReg = S->second;
882             
883             DEBUG(errs() << " " << TRI->getName(CurrReg) << "->" << 
884                   TRI->getName(NewReg) << "(" <<  
885                   RegRefs.count(CurrReg) << " refs)");
886             
887             // Update the references to the old register CurrReg to
888             // refer to the new register NewReg.
889             std::pair<std::multimap<unsigned, 
890                               AggressiveAntiDepState::RegisterReference>::iterator,
891                       std::multimap<unsigned,
892                               AggressiveAntiDepState::RegisterReference>::iterator>
893               Range = RegRefs.equal_range(CurrReg);
894             for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
895                    Q = Range.first, QE = Range.second; Q != QE; ++Q) {
896               Q->second.Operand->setReg(NewReg);
897             }
898             
899             // We just went back in time and modified history; the
900             // liveness information for CurrReg is now inconsistent. Set
901             // the state as if it were dead.
902             State->UnionGroups(NewReg, 0);
903             RegRefs.erase(NewReg);
904             DefIndices[NewReg] = DefIndices[CurrReg];
905             KillIndices[NewReg] = KillIndices[CurrReg];
906             
907             State->UnionGroups(CurrReg, 0);
908             RegRefs.erase(CurrReg);
909             DefIndices[CurrReg] = KillIndices[CurrReg];
910             KillIndices[CurrReg] = ~0u;
911             assert(((KillIndices[CurrReg] == ~0u) !=
912                     (DefIndices[CurrReg] == ~0u)) &&
913                    "Kill and Def maps aren't consistent for AntiDepReg!");
914           }
915           
916           ++Broken;
917           DEBUG(errs() << '\n');
918         }
919       }
920     }
921
922     ScanInstruction(MI, Count);
923   }
924   
925   return Broken;
926 }