Anti-dependency breaking needs to be careful regarding instructions with
[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(MachineInstr *MI,
292                                                  unsigned AntiDepReg,
293                                                  unsigned LastNewReg,
294                                                  const TargetRegisterClass *RC)
295 {
296   for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
297        RE = RC->allocation_order_end(MF); R != RE; ++R) {
298     unsigned NewReg = *R;
299     // Don't replace a register with itself.
300     if (NewReg == AntiDepReg) continue;
301     // Don't replace a register with one that was recently used to repair
302     // an anti-dependence with this AntiDepReg, because that would
303     // re-introduce that anti-dependence.
304     if (NewReg == LastNewReg) continue;
305     // If the instruction already has a def of the NewReg, it's not suitable.
306     // For example, Instruction with multiple definitions can result in this
307     // condition.
308     if (MI->modifiesRegister(NewReg, TRI)) continue;
309     // If NewReg is dead and NewReg's most recent def is not before
310     // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
311     assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
312            && "Kill and Def maps aren't consistent for AntiDepReg!");
313     assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
314            && "Kill and Def maps aren't consistent for NewReg!");
315     if (KillIndices[NewReg] != ~0u ||
316         Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
317         KillIndices[AntiDepReg] > DefIndices[NewReg])
318       continue;
319     return NewReg;
320   }
321
322   // No registers are free and available!
323   return 0;
324 }
325
326 unsigned CriticalAntiDepBreaker::
327 BreakAntiDependencies(std::vector<SUnit>& SUnits,
328                       MachineBasicBlock::iterator& Begin,
329                       MachineBasicBlock::iterator& End,
330                       unsigned InsertPosIndex) {
331   // The code below assumes that there is at least one instruction,
332   // so just duck out immediately if the block is empty.
333   if (SUnits.empty()) return 0;
334
335   // Find the node at the bottom of the critical path.
336   SUnit *Max = 0;
337   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
338     SUnit *SU = &SUnits[i];
339     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
340       Max = SU;
341   }
342
343 #ifndef NDEBUG
344   {
345     DEBUG(dbgs() << "Critical path has total latency "
346           << (Max->getDepth() + Max->Latency) << "\n");
347     DEBUG(dbgs() << "Available regs:");
348     for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
349       if (KillIndices[Reg] == ~0u)
350         DEBUG(dbgs() << " " << TRI->getName(Reg));
351     }
352     DEBUG(dbgs() << '\n');
353   }
354 #endif
355
356   // Track progress along the critical path through the SUnit graph as we walk
357   // the instructions.
358   SUnit *CriticalPathSU = Max;
359   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
360
361   // Consider this pattern:
362   //   A = ...
363   //   ... = A
364   //   A = ...
365   //   ... = A
366   //   A = ...
367   //   ... = A
368   //   A = ...
369   //   ... = A
370   // There are three anti-dependencies here, and without special care,
371   // we'd break all of them using the same register:
372   //   A = ...
373   //   ... = A
374   //   B = ...
375   //   ... = B
376   //   B = ...
377   //   ... = B
378   //   B = ...
379   //   ... = B
380   // because at each anti-dependence, B is the first register that
381   // isn't A which is free.  This re-introduces anti-dependencies
382   // at all but one of the original anti-dependencies that we were
383   // trying to break.  To avoid this, keep track of the most recent
384   // register that each register was replaced with, avoid
385   // using it to repair an anti-dependence on the same register.
386   // This lets us produce this:
387   //   A = ...
388   //   ... = A
389   //   B = ...
390   //   ... = B
391   //   C = ...
392   //   ... = C
393   //   B = ...
394   //   ... = B
395   // This still has an anti-dependence on B, but at least it isn't on the
396   // original critical path.
397   //
398   // TODO: If we tracked more than one register here, we could potentially
399   // fix that remaining critical edge too. This is a little more involved,
400   // because unlike the most recent register, less recent registers should
401   // still be considered, though only if no other registers are available.
402   unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
403
404   // Attempt to break anti-dependence edges on the critical path. Walk the
405   // instructions from the bottom up, tracking information about liveness
406   // as we go to help determine which registers are available.
407   unsigned Broken = 0;
408   unsigned Count = InsertPosIndex - 1;
409   for (MachineBasicBlock::iterator I = End, E = Begin;
410        I != E; --Count) {
411     MachineInstr *MI = --I;
412
413     // Check if this instruction has a dependence on the critical path that
414     // is an anti-dependence that we may be able to break. If it is, set
415     // AntiDepReg to the non-zero register associated with the anti-dependence.
416     //
417     // We limit our attention to the critical path as a heuristic to avoid
418     // breaking anti-dependence edges that aren't going to significantly
419     // impact the overall schedule. There are a limited number of registers
420     // and we want to save them for the important edges.
421     // 
422     // TODO: Instructions with multiple defs could have multiple
423     // anti-dependencies. The current code here only knows how to break one
424     // edge per instruction. Note that we'd have to be able to break all of
425     // the anti-dependencies in an instruction in order to be effective.
426     unsigned AntiDepReg = 0;
427     if (MI == CriticalPathMI) {
428       if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
429         SUnit *NextSU = Edge->getSUnit();
430
431         // Only consider anti-dependence edges.
432         if (Edge->getKind() == SDep::Anti) {
433           AntiDepReg = Edge->getReg();
434           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
435           if (!AllocatableSet.test(AntiDepReg))
436             // Don't break anti-dependencies on non-allocatable registers.
437             AntiDepReg = 0;
438           else if (KeepRegs.count(AntiDepReg))
439             // Don't break anti-dependencies if an use down below requires
440             // this exact register.
441             AntiDepReg = 0;
442           else {
443             // If the SUnit has other dependencies on the SUnit that it
444             // anti-depends on, don't bother breaking the anti-dependency
445             // since those edges would prevent such units from being
446             // scheduled past each other regardless.
447             //
448             // Also, if there are dependencies on other SUnits with the
449             // same register as the anti-dependency, don't attempt to
450             // break it.
451             for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
452                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
453               if (P->getSUnit() == NextSU ?
454                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
455                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
456                 AntiDepReg = 0;
457                 break;
458               }
459           }
460         }
461         CriticalPathSU = NextSU;
462         CriticalPathMI = CriticalPathSU->getInstr();
463       } else {
464         // We've reached the end of the critical path.
465         CriticalPathSU = 0;
466         CriticalPathMI = 0;
467       }
468     }
469
470     PrescanInstruction(MI);
471
472     if (MI->getDesc().hasExtraDefRegAllocReq())
473       // If this instruction's defs have special allocation requirement, don't
474       // break this anti-dependency.
475       AntiDepReg = 0;
476     else if (AntiDepReg) {
477       // If this instruction has a use of AntiDepReg, breaking it
478       // is invalid.
479       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
480         MachineOperand &MO = MI->getOperand(i);
481         if (!MO.isReg()) continue;
482         unsigned Reg = MO.getReg();
483         if (Reg == 0) continue;
484         if (MO.isUse() && AntiDepReg == Reg) {
485           AntiDepReg = 0;
486           break;
487         }
488       }
489     }
490
491     // Determine AntiDepReg's register class, if it is live and is
492     // consistently used within a single class.
493     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
494     assert((AntiDepReg == 0 || RC != NULL) &&
495            "Register should be live if it's causing an anti-dependence!");
496     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
497       AntiDepReg = 0;
498
499     // Look for a suitable register to use to break the anti-depenence.
500     //
501     // TODO: Instead of picking the first free register, consider which might
502     // be the best.
503     if (AntiDepReg != 0) {
504       if (unsigned NewReg = findSuitableFreeRegister(MI, AntiDepReg,
505                                                      LastNewReg[AntiDepReg],
506                                                      RC)) {
507         DEBUG(dbgs() << "Breaking anti-dependence edge on "
508               << TRI->getName(AntiDepReg)
509               << " with " << RegRefs.count(AntiDepReg) << " references"
510               << " using " << TRI->getName(NewReg) << "!\n");
511
512         // Update the references to the old register to refer to the new
513         // register.
514         std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
515                   std::multimap<unsigned, MachineOperand *>::iterator>
516            Range = RegRefs.equal_range(AntiDepReg);
517         for (std::multimap<unsigned, MachineOperand *>::iterator
518              Q = Range.first, QE = Range.second; Q != QE; ++Q)
519           Q->second->setReg(NewReg);
520
521         // We just went back in time and modified history; the
522         // liveness information for the anti-depenence reg is now
523         // inconsistent. Set the state as if it were dead.
524         Classes[NewReg] = Classes[AntiDepReg];
525         DefIndices[NewReg] = DefIndices[AntiDepReg];
526         KillIndices[NewReg] = KillIndices[AntiDepReg];
527         assert(((KillIndices[NewReg] == ~0u) !=
528                 (DefIndices[NewReg] == ~0u)) &&
529              "Kill and Def maps aren't consistent for NewReg!");
530
531         Classes[AntiDepReg] = 0;
532         DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
533         KillIndices[AntiDepReg] = ~0u;
534         assert(((KillIndices[AntiDepReg] == ~0u) !=
535                 (DefIndices[AntiDepReg] == ~0u)) &&
536              "Kill and Def maps aren't consistent for AntiDepReg!");
537
538         RegRefs.erase(AntiDepReg);
539         LastNewReg[AntiDepReg] = NewReg;
540         ++Broken;
541       }
542     }
543
544     ScanInstruction(MI, Count);
545   }
546
547   return Broken;
548 }