d3ffcc78471b7b5de53778b15d6455977fe25049
[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 #include "CriticalAntiDepBreaker.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25
26 using namespace llvm;
27
28 #define DEBUG_TYPE "post-RA-sched"
29
30 CriticalAntiDepBreaker::
31 CriticalAntiDepBreaker(MachineFunction& MFi, const RegisterClassInfo &RCI) :
32   AntiDepBreaker(), MF(MFi),
33   MRI(MF.getRegInfo()),
34   TII(MF.getTarget().getInstrInfo()),
35   TRI(MF.getTarget().getRegisterInfo()),
36   RegClassInfo(RCI),
37   Classes(TRI->getNumRegs(), nullptr),
38   KillIndices(TRI->getNumRegs(), 0),
39   DefIndices(TRI->getNumRegs(), 0),
40   KeepRegs(TRI->getNumRegs(), false) {}
41
42 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
43 }
44
45 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
46   const unsigned BBSize = BB->size();
47   for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
48     // Clear out the register class data.
49     Classes[i] = nullptr;
50
51     // Initialize the indices to indicate that no registers are live.
52     KillIndices[i] = ~0u;
53     DefIndices[i] = BBSize;
54   }
55
56   // Clear "do not change" set.
57   KeepRegs.reset();
58
59   bool IsReturnBlock = (BBSize != 0 && BB->back().isReturn());
60
61   // Examine the live-in regs of all successors.
62   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
63          SE = BB->succ_end(); SI != SE; ++SI)
64     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
65            E = (*SI)->livein_end(); I != E; ++I) {
66       for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
67         unsigned Reg = *AI;
68         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
69         KillIndices[Reg] = BBSize;
70         DefIndices[Reg] = ~0u;
71       }
72     }
73
74   // Mark live-out callee-saved registers. In a return block this is
75   // all callee-saved registers. In non-return this is any
76   // callee-saved register that is not saved in the prolog.
77   const MachineFrameInfo *MFI = MF.getFrameInfo();
78   BitVector Pristine = MFI->getPristineRegs(BB);
79   for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
80     if (!IsReturnBlock && !Pristine.test(*I)) continue;
81     for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
82       unsigned Reg = *AI;
83       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
84       KillIndices[Reg] = BBSize;
85       DefIndices[Reg] = ~0u;
86     }
87   }
88 }
89
90 void CriticalAntiDepBreaker::FinishBlock() {
91   RegRefs.clear();
92   KeepRegs.reset();
93 }
94
95 void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
96                                      unsigned InsertPosIndex) {
97   if (MI->isDebugValue())
98     return;
99   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
100
101   for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
102     if (KillIndices[Reg] != ~0u) {
103       // If Reg is currently live, then mark that it can't be renamed as
104       // we don't know the extent of its live-range anymore (now that it
105       // has been scheduled).
106       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
107       KillIndices[Reg] = Count;
108     } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
109       // Any register which was defined within the previous scheduling region
110       // may have been rescheduled and its lifetime may overlap with registers
111       // in ways not reflected in our current liveness state. For each such
112       // register, adjust the liveness state to be conservatively correct.
113       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
114
115       // Move the def index to the end of the previous region, to reflect
116       // that the def could theoretically have been scheduled at the end.
117       DefIndices[Reg] = InsertPosIndex;
118     }
119   }
120
121   PrescanInstruction(MI);
122   ScanInstruction(MI, Count);
123 }
124
125 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
126 /// critical path.
127 static const SDep *CriticalPathStep(const SUnit *SU) {
128   const SDep *Next = nullptr;
129   unsigned NextDepth = 0;
130   // Find the predecessor edge with the greatest depth.
131   for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
132        P != PE; ++P) {
133     const SUnit *PredSU = P->getSUnit();
134     unsigned PredLatency = P->getLatency();
135     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
136     // In the case of a latency tie, prefer an anti-dependency edge over
137     // other types of edges.
138     if (NextDepth < PredTotalLatency ||
139         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
140       NextDepth = PredTotalLatency;
141       Next = &*P;
142     }
143   }
144   return Next;
145 }
146
147 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
148   // It's not safe to change register allocation for source operands of
149   // instructions that have special allocation requirements. Also assume all
150   // registers used in a call must not be changed (ABI).
151   // FIXME: The issue with predicated instruction is more complex. We are being
152   // conservative here because the kill markers cannot be trusted after
153   // if-conversion:
154   // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
155   // ...
156   // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
157   // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
158   // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
159   //
160   // The first R6 kill is not really a kill since it's killed by a predicated
161   // instruction which may not be executed. The second R6 def may or may not
162   // re-define R6 so it's not safe to change it since the last R6 use cannot be
163   // changed.
164   bool Special = MI->isCall() ||
165     MI->hasExtraSrcRegAllocReq() ||
166     TII->isPredicated(MI);
167
168   // Scan the register operands for this instruction and update
169   // Classes and RegRefs.
170   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
171     MachineOperand &MO = MI->getOperand(i);
172     if (!MO.isReg()) continue;
173     unsigned Reg = MO.getReg();
174     if (Reg == 0) continue;
175     const TargetRegisterClass *NewRC = nullptr;
176
177     if (i < MI->getDesc().getNumOperands())
178       NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
179
180     // For now, only allow the register to be changed if its register
181     // class is consistent across all uses.
182     if (!Classes[Reg] && NewRC)
183       Classes[Reg] = NewRC;
184     else if (!NewRC || Classes[Reg] != NewRC)
185       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
186
187     // Now check for aliases.
188     for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
189       // If an alias of the reg is used during the live range, give up.
190       // Note that this allows us to skip checking if AntiDepReg
191       // overlaps with any of the aliases, among other things.
192       unsigned AliasReg = *AI;
193       if (Classes[AliasReg]) {
194         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
195         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
196       }
197     }
198
199     // If we're still willing to consider this register, note the reference.
200     if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
201       RegRefs.insert(std::make_pair(Reg, &MO));
202
203     // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
204     // it or any of its sub or super regs. We need to use KeepRegs to mark the
205     // reg because not all uses of the same reg within an instruction are
206     // necessarily tagged as tied.
207     // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
208     // def register but not the second (see PR20020 for details).
209     // FIXME: can this check be relaxed to account for undef uses
210     // of a register? In the above 'xor' example, the uses of %eax are undef, so
211     // earlier instructions could still replace %eax even though the 'xor'
212     // itself can't be changed.
213     if (MI->isRegTiedToUseOperand(i) &&
214         Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
215       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
216            SubRegs.isValid(); ++SubRegs) {
217         KeepRegs.set(*SubRegs);
218       }
219       for (MCSuperRegIterator SuperRegs(Reg, TRI);
220            SuperRegs.isValid(); ++SuperRegs) {
221         KeepRegs.set(*SuperRegs);
222       }
223     }
224
225     if (MO.isUse() && Special) {
226       if (!KeepRegs.test(Reg)) {
227         for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
228              SubRegs.isValid(); ++SubRegs)
229           KeepRegs.set(*SubRegs);
230       }
231     }
232   }
233 }
234
235 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
236                                              unsigned Count) {
237   // Update liveness.
238   // Proceeding upwards, registers that are defed but not used in this
239   // instruction are now dead.
240
241   if (!TII->isPredicated(MI)) {
242     // Predicated defs are modeled as read + write, i.e. similar to two
243     // address updates.
244     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
245       MachineOperand &MO = MI->getOperand(i);
246
247       if (MO.isRegMask())
248         for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
249           if (MO.clobbersPhysReg(i)) {
250             DefIndices[i] = Count;
251             KillIndices[i] = ~0u;
252             KeepRegs.reset(i);
253             Classes[i] = nullptr;
254             RegRefs.erase(i);
255           }
256
257       if (!MO.isReg()) continue;
258       unsigned Reg = MO.getReg();
259       if (Reg == 0) continue;
260       if (!MO.isDef()) continue;
261
262       // If we've already marked this reg as unchangeable, carry on.
263       if (KeepRegs.test(Reg)) continue;
264       
265       // Ignore two-addr defs.
266       if (MI->isRegTiedToUseOperand(i)) continue;
267
268       // FIXME: we should use a SubRegIterator that includes self (as above), so
269       // we don't have to repeat all this code for the reg itself.
270       DefIndices[Reg] = Count;
271       KillIndices[Reg] = ~0u;
272       assert(((KillIndices[Reg] == ~0u) !=
273               (DefIndices[Reg] == ~0u)) &&
274              "Kill and Def maps aren't consistent for Reg!");
275       KeepRegs.reset(Reg);
276       Classes[Reg] = nullptr;
277       RegRefs.erase(Reg);
278       // Repeat, for all subregs.
279       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
280         unsigned SubregReg = *SubRegs;
281         DefIndices[SubregReg] = Count;
282         KillIndices[SubregReg] = ~0u;
283         KeepRegs.reset(SubregReg);
284         Classes[SubregReg] = nullptr;
285         RegRefs.erase(SubregReg);
286       }
287       // Conservatively mark super-registers as unusable.
288       for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
289         Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
290     }
291   }
292   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
293     MachineOperand &MO = MI->getOperand(i);
294     if (!MO.isReg()) continue;
295     unsigned Reg = MO.getReg();
296     if (Reg == 0) continue;
297     if (!MO.isUse()) continue;
298
299     const TargetRegisterClass *NewRC = nullptr;
300     if (i < MI->getDesc().getNumOperands())
301       NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
302
303     // For now, only allow the register to be changed if its register
304     // class is consistent across all uses.
305     if (!Classes[Reg] && NewRC)
306       Classes[Reg] = NewRC;
307     else if (!NewRC || Classes[Reg] != NewRC)
308       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
309
310     RegRefs.insert(std::make_pair(Reg, &MO));
311
312     // FIXME: we should use an MCRegAliasIterator that includes self so we don't
313     // have to repeat all this code for the reg itself.
314     
315     // It wasn't previously live but now it is, this is a kill.
316     if (KillIndices[Reg] == ~0u) {
317       KillIndices[Reg] = Count;
318       DefIndices[Reg] = ~0u;
319           assert(((KillIndices[Reg] == ~0u) !=
320                   (DefIndices[Reg] == ~0u)) &&
321                "Kill and Def maps aren't consistent for Reg!");
322     }
323     // Repeat, for all aliases.
324     for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
325       unsigned AliasReg = *AI;
326       if (KillIndices[AliasReg] == ~0u) {
327         KillIndices[AliasReg] = Count;
328         DefIndices[AliasReg] = ~0u;
329       }
330     }
331   }
332 }
333
334 // Check all machine operands that reference the antidependent register and must
335 // be replaced by NewReg. Return true if any of their parent instructions may
336 // clobber the new register.
337 //
338 // Note: AntiDepReg may be referenced by a two-address instruction such that
339 // it's use operand is tied to a def operand. We guard against the case in which
340 // the two-address instruction also defines NewReg, as may happen with
341 // pre/postincrement loads. In this case, both the use and def operands are in
342 // RegRefs because the def is inserted by PrescanInstruction and not erased
343 // during ScanInstruction. So checking for an instruction with definitions of
344 // both NewReg and AntiDepReg covers it.
345 bool
346 CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
347                                                 RegRefIter RegRefEnd,
348                                                 unsigned NewReg)
349 {
350   for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
351     MachineOperand *RefOper = I->second;
352
353     // Don't allow the instruction defining AntiDepReg to earlyclobber its
354     // operands, in case they may be assigned to NewReg. In this case antidep
355     // breaking must fail, but it's too rare to bother optimizing.
356     if (RefOper->isDef() && RefOper->isEarlyClobber())
357       return true;
358
359     // Handle cases in which this instruction defines NewReg.
360     MachineInstr *MI = RefOper->getParent();
361     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
362       const MachineOperand &CheckOper = MI->getOperand(i);
363
364       if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
365         return true;
366
367       if (!CheckOper.isReg() || !CheckOper.isDef() ||
368           CheckOper.getReg() != NewReg)
369         continue;
370
371       // Don't allow the instruction to define NewReg and AntiDepReg.
372       // When AntiDepReg is renamed it will be an illegal op.
373       if (RefOper->isDef())
374         return true;
375
376       // Don't allow an instruction using AntiDepReg to be earlyclobbered by
377       // NewReg.
378       if (CheckOper.isEarlyClobber())
379         return true;
380
381       // Don't allow inline asm to define NewReg at all. Who knows what it's
382       // doing with it.
383       if (MI->isInlineAsm())
384         return true;
385     }
386   }
387   return false;
388 }
389
390 unsigned CriticalAntiDepBreaker::
391 findSuitableFreeRegister(RegRefIter RegRefBegin,
392                          RegRefIter RegRefEnd,
393                          unsigned AntiDepReg,
394                          unsigned LastNewReg,
395                          const TargetRegisterClass *RC,
396                          SmallVectorImpl<unsigned> &Forbid)
397 {
398   ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
399   for (unsigned i = 0; i != Order.size(); ++i) {
400     unsigned NewReg = Order[i];
401     // Don't replace a register with itself.
402     if (NewReg == AntiDepReg) continue;
403     // Don't replace a register with one that was recently used to repair
404     // an anti-dependence with this AntiDepReg, because that would
405     // re-introduce that anti-dependence.
406     if (NewReg == LastNewReg) continue;
407     // If any instructions that define AntiDepReg also define the NewReg, it's
408     // not suitable.  For example, Instruction with multiple definitions can
409     // result in this condition.
410     if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
411     // If NewReg is dead and NewReg's most recent def is not before
412     // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
413     assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
414            && "Kill and Def maps aren't consistent for AntiDepReg!");
415     assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
416            && "Kill and Def maps aren't consistent for NewReg!");
417     if (KillIndices[NewReg] != ~0u ||
418         Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
419         KillIndices[AntiDepReg] > DefIndices[NewReg])
420       continue;
421     // If NewReg overlaps any of the forbidden registers, we can't use it.
422     bool Forbidden = false;
423     for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
424            ite = Forbid.end(); it != ite; ++it)
425       if (TRI->regsOverlap(NewReg, *it)) {
426         Forbidden = true;
427         break;
428       }
429     if (Forbidden) continue;
430     return NewReg;
431   }
432
433   // No registers are free and available!
434   return 0;
435 }
436
437 unsigned CriticalAntiDepBreaker::
438 BreakAntiDependencies(const std::vector<SUnit>& SUnits,
439                       MachineBasicBlock::iterator Begin,
440                       MachineBasicBlock::iterator End,
441                       unsigned InsertPosIndex,
442                       DbgValueVector &DbgValues) {
443   // The code below assumes that there is at least one instruction,
444   // so just duck out immediately if the block is empty.
445   if (SUnits.empty()) return 0;
446
447   // Keep a map of the MachineInstr*'s back to the SUnit representing them.
448   // This is used for updating debug information.
449   //
450   // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
451   DenseMap<MachineInstr*,const SUnit*> MISUnitMap;
452
453   // Find the node at the bottom of the critical path.
454   const SUnit *Max = nullptr;
455   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
456     const SUnit *SU = &SUnits[i];
457     MISUnitMap[SU->getInstr()] = SU;
458     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
459       Max = SU;
460   }
461
462 #ifndef NDEBUG
463   {
464     DEBUG(dbgs() << "Critical path has total latency "
465           << (Max->getDepth() + Max->Latency) << "\n");
466     DEBUG(dbgs() << "Available regs:");
467     for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
468       if (KillIndices[Reg] == ~0u)
469         DEBUG(dbgs() << " " << TRI->getName(Reg));
470     }
471     DEBUG(dbgs() << '\n');
472   }
473 #endif
474
475   // Track progress along the critical path through the SUnit graph as we walk
476   // the instructions.
477   const SUnit *CriticalPathSU = Max;
478   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
479
480   // Consider this pattern:
481   //   A = ...
482   //   ... = A
483   //   A = ...
484   //   ... = A
485   //   A = ...
486   //   ... = A
487   //   A = ...
488   //   ... = A
489   // There are three anti-dependencies here, and without special care,
490   // we'd break all of them using the same register:
491   //   A = ...
492   //   ... = A
493   //   B = ...
494   //   ... = B
495   //   B = ...
496   //   ... = B
497   //   B = ...
498   //   ... = B
499   // because at each anti-dependence, B is the first register that
500   // isn't A which is free.  This re-introduces anti-dependencies
501   // at all but one of the original anti-dependencies that we were
502   // trying to break.  To avoid this, keep track of the most recent
503   // register that each register was replaced with, avoid
504   // using it to repair an anti-dependence on the same register.
505   // This lets us produce this:
506   //   A = ...
507   //   ... = A
508   //   B = ...
509   //   ... = B
510   //   C = ...
511   //   ... = C
512   //   B = ...
513   //   ... = B
514   // This still has an anti-dependence on B, but at least it isn't on the
515   // original critical path.
516   //
517   // TODO: If we tracked more than one register here, we could potentially
518   // fix that remaining critical edge too. This is a little more involved,
519   // because unlike the most recent register, less recent registers should
520   // still be considered, though only if no other registers are available.
521   std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
522
523   // Attempt to break anti-dependence edges on the critical path. Walk the
524   // instructions from the bottom up, tracking information about liveness
525   // as we go to help determine which registers are available.
526   unsigned Broken = 0;
527   unsigned Count = InsertPosIndex - 1;
528   for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
529     MachineInstr *MI = --I;
530     if (MI->isDebugValue())
531       continue;
532
533     // Check if this instruction has a dependence on the critical path that
534     // is an anti-dependence that we may be able to break. If it is, set
535     // AntiDepReg to the non-zero register associated with the anti-dependence.
536     //
537     // We limit our attention to the critical path as a heuristic to avoid
538     // breaking anti-dependence edges that aren't going to significantly
539     // impact the overall schedule. There are a limited number of registers
540     // and we want to save them for the important edges.
541     //
542     // TODO: Instructions with multiple defs could have multiple
543     // anti-dependencies. The current code here only knows how to break one
544     // edge per instruction. Note that we'd have to be able to break all of
545     // the anti-dependencies in an instruction in order to be effective.
546     unsigned AntiDepReg = 0;
547     if (MI == CriticalPathMI) {
548       if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
549         const SUnit *NextSU = Edge->getSUnit();
550
551         // Only consider anti-dependence edges.
552         if (Edge->getKind() == SDep::Anti) {
553           AntiDepReg = Edge->getReg();
554           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
555           if (!MRI.isAllocatable(AntiDepReg))
556             // Don't break anti-dependencies on non-allocatable registers.
557             AntiDepReg = 0;
558           else if (KeepRegs.test(AntiDepReg))
559             // Don't break anti-dependencies if a use down below requires
560             // this exact register.
561             AntiDepReg = 0;
562           else {
563             // If the SUnit has other dependencies on the SUnit that it
564             // anti-depends on, don't bother breaking the anti-dependency
565             // since those edges would prevent such units from being
566             // scheduled past each other regardless.
567             //
568             // Also, if there are dependencies on other SUnits with the
569             // same register as the anti-dependency, don't attempt to
570             // break it.
571             for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
572                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
573               if (P->getSUnit() == NextSU ?
574                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
575                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
576                 AntiDepReg = 0;
577                 break;
578               }
579           }
580         }
581         CriticalPathSU = NextSU;
582         CriticalPathMI = CriticalPathSU->getInstr();
583       } else {
584         // We've reached the end of the critical path.
585         CriticalPathSU = nullptr;
586         CriticalPathMI = nullptr;
587       }
588     }
589
590     PrescanInstruction(MI);
591
592     SmallVector<unsigned, 2> ForbidRegs;
593
594     // If MI's defs have a special allocation requirement, don't allow
595     // any def registers to be changed. Also assume all registers
596     // defined in a call must not be changed (ABI).
597     if (MI->isCall() || MI->hasExtraDefRegAllocReq() || TII->isPredicated(MI))
598       // If this instruction's defs have special allocation requirement, don't
599       // break this anti-dependency.
600       AntiDepReg = 0;
601     else if (AntiDepReg) {
602       // If this instruction has a use of AntiDepReg, breaking it
603       // is invalid.  If the instruction defines other registers,
604       // save a list of them so that we don't pick a new register
605       // that overlaps any of them.
606       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
607         MachineOperand &MO = MI->getOperand(i);
608         if (!MO.isReg()) continue;
609         unsigned Reg = MO.getReg();
610         if (Reg == 0) continue;
611         if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
612           AntiDepReg = 0;
613           break;
614         }
615         if (MO.isDef() && Reg != AntiDepReg)
616           ForbidRegs.push_back(Reg);
617       }
618     }
619
620     // Determine AntiDepReg's register class, if it is live and is
621     // consistently used within a single class.
622     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
623                                                     : nullptr;
624     assert((AntiDepReg == 0 || RC != nullptr) &&
625            "Register should be live if it's causing an anti-dependence!");
626     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
627       AntiDepReg = 0;
628
629     // Look for a suitable register to use to break the anti-dependence.
630     //
631     // TODO: Instead of picking the first free register, consider which might
632     // be the best.
633     if (AntiDepReg != 0) {
634       std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
635                 std::multimap<unsigned, MachineOperand *>::iterator>
636         Range = RegRefs.equal_range(AntiDepReg);
637       if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
638                                                      AntiDepReg,
639                                                      LastNewReg[AntiDepReg],
640                                                      RC, ForbidRegs)) {
641         DEBUG(dbgs() << "Breaking anti-dependence edge on "
642               << TRI->getName(AntiDepReg)
643               << " with " << RegRefs.count(AntiDepReg) << " references"
644               << " using " << TRI->getName(NewReg) << "!\n");
645
646         // Update the references to the old register to refer to the new
647         // register.
648         for (std::multimap<unsigned, MachineOperand *>::iterator
649              Q = Range.first, QE = Range.second; Q != QE; ++Q) {
650           Q->second->setReg(NewReg);
651           // If the SU for the instruction being updated has debug information
652           // related to the anti-dependency register, make sure to update that
653           // as well.
654           const SUnit *SU = MISUnitMap[Q->second->getParent()];
655           if (!SU) continue;
656           for (DbgValueVector::iterator DVI = DbgValues.begin(),
657                  DVE = DbgValues.end(); DVI != DVE; ++DVI)
658             if (DVI->second == Q->second->getParent())
659               UpdateDbgValue(DVI->first, AntiDepReg, NewReg);
660         }
661
662         // We just went back in time and modified history; the
663         // liveness information for the anti-dependence reg is now
664         // inconsistent. Set the state as if it were dead.
665         Classes[NewReg] = Classes[AntiDepReg];
666         DefIndices[NewReg] = DefIndices[AntiDepReg];
667         KillIndices[NewReg] = KillIndices[AntiDepReg];
668         assert(((KillIndices[NewReg] == ~0u) !=
669                 (DefIndices[NewReg] == ~0u)) &&
670              "Kill and Def maps aren't consistent for NewReg!");
671
672         Classes[AntiDepReg] = nullptr;
673         DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
674         KillIndices[AntiDepReg] = ~0u;
675         assert(((KillIndices[AntiDepReg] == ~0u) !=
676                 (DefIndices[AntiDepReg] == ~0u)) &&
677              "Kill and Def maps aren't consistent for AntiDepReg!");
678
679         RegRefs.erase(AntiDepReg);
680         LastNewReg[AntiDepReg] = NewReg;
681         ++Broken;
682       }
683     }
684
685     ScanInstruction(MI, Count);
686   }
687
688   return Broken;
689 }