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