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