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