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