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