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