Break anti-dependence breaking out into its own class.
[oota-llvm.git] / lib / CodeGen / CriticalAntiDepBreaker.cpp
1 //===----- CriticalAntiDepBreaker.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 CriticalAntiDepBreaker class, which
11 // implements register anti-dependence breaking along a blocks
12 // critical path during post-RA scheduler.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "critical-antidep"
17 #include "CriticalAntiDepBreaker.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 using namespace llvm;
27
28 CriticalAntiDepBreaker::
29 CriticalAntiDepBreaker(MachineFunction& MFi) : 
30   AntiDepBreaker(), MF(MFi),
31   MRI(MF.getRegInfo()),
32   TRI(MF.getTarget().getRegisterInfo()),
33   AllocatableSet(TRI->getAllocatableSet(MF))
34 {
35 }
36
37 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
38 }
39
40 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
41   // Clear out the register class data.
42   std::fill(Classes, array_endof(Classes),
43             static_cast<const TargetRegisterClass *>(0));
44
45   // Initialize the indices to indicate that no registers are live.
46   std::fill(KillIndices, array_endof(KillIndices), ~0u);
47   std::fill(DefIndices, array_endof(DefIndices), BB->size());
48
49   // Clear "do not change" set.
50   KeepRegs.clear();
51
52   bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
53
54   // Determine the live-out physregs for this block.
55   if (IsReturnBlock) {
56     // In a return block, examine the function live-out regs.
57     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
58          E = MRI.liveout_end(); I != E; ++I) {
59       unsigned Reg = *I;
60       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
61       KillIndices[Reg] = BB->size();
62       DefIndices[Reg] = ~0u;
63       // Repeat, for all aliases.
64       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
65         unsigned AliasReg = *Alias;
66         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
67         KillIndices[AliasReg] = BB->size();
68         DefIndices[AliasReg] = ~0u;
69       }
70     }
71   } else {
72     // In a non-return block, examine the live-in regs of all successors.
73     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
74          SE = BB->succ_end(); SI != SE; ++SI)
75       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
76            E = (*SI)->livein_end(); I != E; ++I) {
77         unsigned Reg = *I;
78         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
79         KillIndices[Reg] = BB->size();
80         DefIndices[Reg] = ~0u;
81         // Repeat, for all aliases.
82         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
83           unsigned AliasReg = *Alias;
84           Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
85           KillIndices[AliasReg] = BB->size();
86           DefIndices[AliasReg] = ~0u;
87         }
88       }
89   }
90
91   // Mark live-out callee-saved registers. In a return block this is
92   // all callee-saved registers. In non-return this is any
93   // callee-saved register that is not saved in the prolog.
94   const MachineFrameInfo *MFI = MF.getFrameInfo();
95   BitVector Pristine = MFI->getPristineRegs(BB);
96   for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
97     unsigned Reg = *I;
98     if (!IsReturnBlock && !Pristine.test(Reg)) continue;
99     Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
100     KillIndices[Reg] = BB->size();
101     DefIndices[Reg] = ~0u;
102     // Repeat, for all aliases.
103     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
104       unsigned AliasReg = *Alias;
105       Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
106       KillIndices[AliasReg] = BB->size();
107       DefIndices[AliasReg] = ~0u;
108     }
109   }
110 }
111
112 void CriticalAntiDepBreaker::FinishBlock() {
113   RegRefs.clear();
114   KeepRegs.clear();
115 }
116
117 void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
118                                      unsigned InsertPosIndex) {
119   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
120
121   // Any register which was defined within the previous scheduling region
122   // may have been rescheduled and its lifetime may overlap with registers
123   // in ways not reflected in our current liveness state. For each such
124   // register, adjust the liveness state to be conservatively correct.
125   for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
126     if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
127       assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
128       // Mark this register to be non-renamable.
129       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
130       // Move the def index to the end of the previous region, to reflect
131       // that the def could theoretically have been scheduled at the end.
132       DefIndices[Reg] = InsertPosIndex;
133     }
134
135   PrescanInstruction(MI);
136   ScanInstruction(MI, Count);
137 }
138
139 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
140 /// critical path.
141 static SDep *CriticalPathStep(SUnit *SU) {
142   SDep *Next = 0;
143   unsigned NextDepth = 0;
144   // Find the predecessor edge with the greatest depth.
145   for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
146        P != PE; ++P) {
147     SUnit *PredSU = P->getSUnit();
148     unsigned PredLatency = P->getLatency();
149     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
150     // In the case of a latency tie, prefer an anti-dependency edge over
151     // other types of edges.
152     if (NextDepth < PredTotalLatency ||
153         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
154       NextDepth = PredTotalLatency;
155       Next = &*P;
156     }
157   }
158   return Next;
159 }
160
161 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
162   // Scan the register operands for this instruction and update
163   // Classes and RegRefs.
164   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
165     MachineOperand &MO = MI->getOperand(i);
166     if (!MO.isReg()) continue;
167     unsigned Reg = MO.getReg();
168     if (Reg == 0) continue;
169     const TargetRegisterClass *NewRC = 0;
170     
171     if (i < MI->getDesc().getNumOperands())
172       NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
173
174     // For now, only allow the register to be changed if its register
175     // class is consistent across all uses.
176     if (!Classes[Reg] && NewRC)
177       Classes[Reg] = NewRC;
178     else if (!NewRC || Classes[Reg] != NewRC)
179       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
180
181     // Now check for aliases.
182     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
183       // If an alias of the reg is used during the live range, give up.
184       // Note that this allows us to skip checking if AntiDepReg
185       // overlaps with any of the aliases, among other things.
186       unsigned AliasReg = *Alias;
187       if (Classes[AliasReg]) {
188         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
189         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
190       }
191     }
192
193     // If we're still willing to consider this register, note the reference.
194     if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
195       RegRefs.insert(std::make_pair(Reg, &MO));
196
197     // It's not safe to change register allocation for source operands of
198     // that have special allocation requirements.
199     if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
200       if (KeepRegs.insert(Reg)) {
201         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
202              *Subreg; ++Subreg)
203           KeepRegs.insert(*Subreg);
204       }
205     }
206   }
207 }
208
209 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
210                                              unsigned Count) {
211   // Update liveness.
212   // Proceding upwards, registers that are defed but not used in this
213   // instruction are now dead.
214   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
215     MachineOperand &MO = MI->getOperand(i);
216     if (!MO.isReg()) continue;
217     unsigned Reg = MO.getReg();
218     if (Reg == 0) continue;
219     if (!MO.isDef()) continue;
220     // Ignore two-addr defs.
221     if (MI->isRegTiedToUseOperand(i)) continue;
222
223     DefIndices[Reg] = Count;
224     KillIndices[Reg] = ~0u;
225     assert(((KillIndices[Reg] == ~0u) !=
226             (DefIndices[Reg] == ~0u)) &&
227            "Kill and Def maps aren't consistent for Reg!");
228     KeepRegs.erase(Reg);
229     Classes[Reg] = 0;
230     RegRefs.erase(Reg);
231     // Repeat, for all subregs.
232     for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
233          *Subreg; ++Subreg) {
234       unsigned SubregReg = *Subreg;
235       DefIndices[SubregReg] = Count;
236       KillIndices[SubregReg] = ~0u;
237       KeepRegs.erase(SubregReg);
238       Classes[SubregReg] = 0;
239       RegRefs.erase(SubregReg);
240     }
241     // Conservatively mark super-registers as unusable.
242     for (const unsigned *Super = TRI->getSuperRegisters(Reg);
243          *Super; ++Super) {
244       unsigned SuperReg = *Super;
245       Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
246     }
247   }
248   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
249     MachineOperand &MO = MI->getOperand(i);
250     if (!MO.isReg()) continue;
251     unsigned Reg = MO.getReg();
252     if (Reg == 0) continue;
253     if (!MO.isUse()) continue;
254
255     const TargetRegisterClass *NewRC = 0;
256     if (i < MI->getDesc().getNumOperands())
257       NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
258
259     // For now, only allow the register to be changed if its register
260     // class is consistent across all uses.
261     if (!Classes[Reg] && NewRC)
262       Classes[Reg] = NewRC;
263     else if (!NewRC || Classes[Reg] != NewRC)
264       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
265
266     RegRefs.insert(std::make_pair(Reg, &MO));
267
268     // It wasn't previously live but now it is, this is a kill.
269     if (KillIndices[Reg] == ~0u) {
270       KillIndices[Reg] = Count;
271       DefIndices[Reg] = ~0u;
272           assert(((KillIndices[Reg] == ~0u) !=
273                   (DefIndices[Reg] == ~0u)) &&
274                "Kill and Def maps aren't consistent for Reg!");
275     }
276     // Repeat, for all aliases.
277     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
278       unsigned AliasReg = *Alias;
279       if (KillIndices[AliasReg] == ~0u) {
280         KillIndices[AliasReg] = Count;
281         DefIndices[AliasReg] = ~0u;
282       }
283     }
284   }
285 }
286
287 unsigned
288 CriticalAntiDepBreaker::findSuitableFreeRegister(unsigned AntiDepReg,
289                                                  unsigned LastNewReg,
290                                                  const TargetRegisterClass *RC) {
291   for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
292        RE = RC->allocation_order_end(MF); R != RE; ++R) {
293     unsigned NewReg = *R;
294     // Don't replace a register with itself.
295     if (NewReg == AntiDepReg) continue;
296     // Don't replace a register with one that was recently used to repair
297     // an anti-dependence with this AntiDepReg, because that would
298     // re-introduce that anti-dependence.
299     if (NewReg == LastNewReg) continue;
300     // If NewReg is dead and NewReg's most recent def is not before
301     // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
302     assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
303            "Kill and Def maps aren't consistent for AntiDepReg!");
304     assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
305            "Kill and Def maps aren't consistent for NewReg!");
306     if (KillIndices[NewReg] != ~0u ||
307         Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
308         KillIndices[AntiDepReg] > DefIndices[NewReg])
309       continue;
310     return NewReg;
311   }
312
313   // No registers are free and available!
314   return 0;
315 }
316
317 unsigned CriticalAntiDepBreaker::
318 BreakAntiDependencies(std::vector<SUnit>& SUnits,
319                       MachineBasicBlock::iterator& Begin,
320                       MachineBasicBlock::iterator& End,
321                       unsigned InsertPosIndex) {
322   // The code below assumes that there is at least one instruction,
323   // so just duck out immediately if the block is empty.
324   if (SUnits.empty()) return 0;
325
326   // Find the node at the bottom of the critical path.
327   SUnit *Max = 0;
328   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
329     SUnit *SU = &SUnits[i];
330     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
331       Max = SU;
332   }
333
334 #ifndef NDEBUG
335   {
336     DEBUG(errs() << "Critical path has total latency "
337           << (Max->getDepth() + Max->Latency) << "\n");
338     DEBUG(errs() << "Available regs:");
339     for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
340       if (KillIndices[Reg] == ~0u)
341         DEBUG(errs() << " " << TRI->getName(Reg));
342     }
343     DEBUG(errs() << '\n');
344   }
345 #endif
346
347   // Track progress along the critical path through the SUnit graph as we walk
348   // the instructions.
349   SUnit *CriticalPathSU = Max;
350   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
351
352   // Consider this pattern:
353   //   A = ...
354   //   ... = A
355   //   A = ...
356   //   ... = A
357   //   A = ...
358   //   ... = A
359   //   A = ...
360   //   ... = A
361   // There are three anti-dependencies here, and without special care,
362   // we'd break all of them using the same register:
363   //   A = ...
364   //   ... = A
365   //   B = ...
366   //   ... = B
367   //   B = ...
368   //   ... = B
369   //   B = ...
370   //   ... = B
371   // because at each anti-dependence, B is the first register that
372   // isn't A which is free.  This re-introduces anti-dependencies
373   // at all but one of the original anti-dependencies that we were
374   // trying to break.  To avoid this, keep track of the most recent
375   // register that each register was replaced with, avoid
376   // using it to repair an anti-dependence on the same register.
377   // This lets us produce this:
378   //   A = ...
379   //   ... = A
380   //   B = ...
381   //   ... = B
382   //   C = ...
383   //   ... = C
384   //   B = ...
385   //   ... = B
386   // This still has an anti-dependence on B, but at least it isn't on the
387   // original critical path.
388   //
389   // TODO: If we tracked more than one register here, we could potentially
390   // fix that remaining critical edge too. This is a little more involved,
391   // because unlike the most recent register, less recent registers should
392   // still be considered, though only if no other registers are available.
393   unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
394
395   // Attempt to break anti-dependence edges on the critical path. Walk the
396   // instructions from the bottom up, tracking information about liveness
397   // as we go to help determine which registers are available.
398   unsigned Broken = 0;
399   unsigned Count = InsertPosIndex - 1;
400   for (MachineBasicBlock::iterator I = End, E = Begin;
401        I != E; --Count) {
402     MachineInstr *MI = --I;
403
404     // Check if this instruction has a dependence on the critical path that
405     // is an anti-dependence that we may be able to break. If it is, set
406     // AntiDepReg to the non-zero register associated with the anti-dependence.
407     //
408     // We limit our attention to the critical path as a heuristic to avoid
409     // breaking anti-dependence edges that aren't going to significantly
410     // impact the overall schedule. There are a limited number of registers
411     // and we want to save them for the important edges.
412     // 
413     // TODO: Instructions with multiple defs could have multiple
414     // anti-dependencies. The current code here only knows how to break one
415     // edge per instruction. Note that we'd have to be able to break all of
416     // the anti-dependencies in an instruction in order to be effective.
417     unsigned AntiDepReg = 0;
418     if (MI == CriticalPathMI) {
419       if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
420         SUnit *NextSU = Edge->getSUnit();
421
422         // Only consider anti-dependence edges.
423         if (Edge->getKind() == SDep::Anti) {
424           AntiDepReg = Edge->getReg();
425           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
426           if (!AllocatableSet.test(AntiDepReg))
427             // Don't break anti-dependencies on non-allocatable registers.
428             AntiDepReg = 0;
429           else if (KeepRegs.count(AntiDepReg))
430             // Don't break anti-dependencies if an use down below requires
431             // this exact register.
432             AntiDepReg = 0;
433           else {
434             // If the SUnit has other dependencies on the SUnit that it
435             // anti-depends on, don't bother breaking the anti-dependency
436             // since those edges would prevent such units from being
437             // scheduled past each other regardless.
438             //
439             // Also, if there are dependencies on other SUnits with the
440             // same register as the anti-dependency, don't attempt to
441             // break it.
442             for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
443                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
444               if (P->getSUnit() == NextSU ?
445                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
446                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
447                 AntiDepReg = 0;
448                 break;
449               }
450           }
451         }
452         CriticalPathSU = NextSU;
453         CriticalPathMI = CriticalPathSU->getInstr();
454       } else {
455         // We've reached the end of the critical path.
456         CriticalPathSU = 0;
457         CriticalPathMI = 0;
458       }
459     }
460
461     PrescanInstruction(MI);
462
463     if (MI->getDesc().hasExtraDefRegAllocReq())
464       // If this instruction's defs have special allocation requirement, don't
465       // break this anti-dependency.
466       AntiDepReg = 0;
467     else if (AntiDepReg) {
468       // If this instruction has a use of AntiDepReg, breaking it
469       // is invalid.
470       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
471         MachineOperand &MO = MI->getOperand(i);
472         if (!MO.isReg()) continue;
473         unsigned Reg = MO.getReg();
474         if (Reg == 0) continue;
475         if (MO.isUse() && AntiDepReg == Reg) {
476           AntiDepReg = 0;
477           break;
478         }
479       }
480     }
481
482     // Determine AntiDepReg's register class, if it is live and is
483     // consistently used within a single class.
484     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
485     assert((AntiDepReg == 0 || RC != NULL) &&
486            "Register should be live if it's causing an anti-dependence!");
487     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
488       AntiDepReg = 0;
489
490     // Look for a suitable register to use to break the anti-depenence.
491     //
492     // TODO: Instead of picking the first free register, consider which might
493     // be the best.
494     if (AntiDepReg != 0) {
495       if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
496                                                      LastNewReg[AntiDepReg],
497                                                      RC)) {
498         DEBUG(errs() << "Breaking anti-dependence edge on "
499               << TRI->getName(AntiDepReg)
500               << " with " << RegRefs.count(AntiDepReg) << " references"
501               << " using " << TRI->getName(NewReg) << "!\n");
502
503         // Update the references to the old register to refer to the new
504         // register.
505         std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
506                   std::multimap<unsigned, MachineOperand *>::iterator>
507            Range = RegRefs.equal_range(AntiDepReg);
508         for (std::multimap<unsigned, MachineOperand *>::iterator
509              Q = Range.first, QE = Range.second; Q != QE; ++Q)
510           Q->second->setReg(NewReg);
511
512         // We just went back in time and modified history; the
513         // liveness information for the anti-depenence reg is now
514         // inconsistent. Set the state as if it were dead.
515         Classes[NewReg] = Classes[AntiDepReg];
516         DefIndices[NewReg] = DefIndices[AntiDepReg];
517         KillIndices[NewReg] = KillIndices[AntiDepReg];
518         assert(((KillIndices[NewReg] == ~0u) !=
519                 (DefIndices[NewReg] == ~0u)) &&
520              "Kill and Def maps aren't consistent for NewReg!");
521
522         Classes[AntiDepReg] = 0;
523         DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
524         KillIndices[AntiDepReg] = ~0u;
525         assert(((KillIndices[AntiDepReg] == ~0u) !=
526                 (DefIndices[AntiDepReg] == ~0u)) &&
527              "Kill and Def maps aren't consistent for AntiDepReg!");
528
529         RegRefs.erase(AntiDepReg);
530         LastNewReg[AntiDepReg] = NewReg;
531         ++Broken;
532       }
533     }
534
535     ScanInstruction(MI, Count);
536   }
537
538   return Broken;
539 }