LLVM API Documentation

CriticalAntiDepBreaker.cpp
Go to the documentation of this file.
00001 //===----- CriticalAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the CriticalAntiDepBreaker class, which
00011 // implements register anti-dependence breaking along a blocks
00012 // critical path during post-RA scheduler.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "CriticalAntiDepBreaker.h"
00017 #include "llvm/CodeGen/MachineBasicBlock.h"
00018 #include "llvm/CodeGen/MachineFrameInfo.h"
00019 #include "llvm/Support/Debug.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include "llvm/Support/raw_ostream.h"
00022 #include "llvm/Target/TargetInstrInfo.h"
00023 #include "llvm/Target/TargetMachine.h"
00024 #include "llvm/Target/TargetRegisterInfo.h"
00025 #include "llvm/Target/TargetSubtargetInfo.h"
00026 
00027 using namespace llvm;
00028 
00029 #define DEBUG_TYPE "post-RA-sched"
00030 
00031 CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,
00032                                                const RegisterClassInfo &RCI)
00033     : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
00034       TII(MF.getSubtarget().getInstrInfo()),
00035       TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
00036       Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
00037       DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
00038 
00039 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
00040 }
00041 
00042 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
00043   const unsigned BBSize = BB->size();
00044   for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
00045     // Clear out the register class data.
00046     Classes[i] = nullptr;
00047 
00048     // Initialize the indices to indicate that no registers are live.
00049     KillIndices[i] = ~0u;
00050     DefIndices[i] = BBSize;
00051   }
00052 
00053   // Clear "do not change" set.
00054   KeepRegs.reset();
00055 
00056   bool IsReturnBlock = (BBSize != 0 && BB->back().isReturn());
00057 
00058   // Examine the live-in regs of all successors.
00059   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00060          SE = BB->succ_end(); SI != SE; ++SI)
00061     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
00062            E = (*SI)->livein_end(); I != E; ++I) {
00063       for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
00064         unsigned Reg = *AI;
00065         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00066         KillIndices[Reg] = BBSize;
00067         DefIndices[Reg] = ~0u;
00068       }
00069     }
00070 
00071   // Mark live-out callee-saved registers. In a return block this is
00072   // all callee-saved registers. In non-return this is any
00073   // callee-saved register that is not saved in the prolog.
00074   const MachineFrameInfo *MFI = MF.getFrameInfo();
00075   BitVector Pristine = MFI->getPristineRegs(BB);
00076   for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
00077     if (!IsReturnBlock && !Pristine.test(*I)) continue;
00078     for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
00079       unsigned Reg = *AI;
00080       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00081       KillIndices[Reg] = BBSize;
00082       DefIndices[Reg] = ~0u;
00083     }
00084   }
00085 }
00086 
00087 void CriticalAntiDepBreaker::FinishBlock() {
00088   RegRefs.clear();
00089   KeepRegs.reset();
00090 }
00091 
00092 void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
00093                                      unsigned InsertPosIndex) {
00094   // Kill instructions can define registers but are really nops, and there might
00095   // be a real definition earlier that needs to be paired with uses dominated by
00096   // this kill.
00097 
00098   // FIXME: It may be possible to remove the isKill() restriction once PR18663
00099   // has been properly fixed. There can be value in processing kills as seen in
00100   // the AggressiveAntiDepBreaker class.
00101   if (MI->isDebugValue() || MI->isKill())
00102     return;
00103   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
00104 
00105   for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
00106     if (KillIndices[Reg] != ~0u) {
00107       // If Reg is currently live, then mark that it can't be renamed as
00108       // we don't know the extent of its live-range anymore (now that it
00109       // has been scheduled).
00110       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00111       KillIndices[Reg] = Count;
00112     } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
00113       // Any register which was defined within the previous scheduling region
00114       // may have been rescheduled and its lifetime may overlap with registers
00115       // in ways not reflected in our current liveness state. For each such
00116       // register, adjust the liveness state to be conservatively correct.
00117       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00118 
00119       // Move the def index to the end of the previous region, to reflect
00120       // that the def could theoretically have been scheduled at the end.
00121       DefIndices[Reg] = InsertPosIndex;
00122     }
00123   }
00124 
00125   PrescanInstruction(MI);
00126   ScanInstruction(MI, Count);
00127 }
00128 
00129 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
00130 /// critical path.
00131 static const SDep *CriticalPathStep(const SUnit *SU) {
00132   const SDep *Next = nullptr;
00133   unsigned NextDepth = 0;
00134   // Find the predecessor edge with the greatest depth.
00135   for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
00136        P != PE; ++P) {
00137     const SUnit *PredSU = P->getSUnit();
00138     unsigned PredLatency = P->getLatency();
00139     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
00140     // In the case of a latency tie, prefer an anti-dependency edge over
00141     // other types of edges.
00142     if (NextDepth < PredTotalLatency ||
00143         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
00144       NextDepth = PredTotalLatency;
00145       Next = &*P;
00146     }
00147   }
00148   return Next;
00149 }
00150 
00151 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
00152   // It's not safe to change register allocation for source operands of
00153   // instructions that have special allocation requirements. Also assume all
00154   // registers used in a call must not be changed (ABI).
00155   // FIXME: The issue with predicated instruction is more complex. We are being
00156   // conservative here because the kill markers cannot be trusted after
00157   // if-conversion:
00158   // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
00159   // ...
00160   // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
00161   // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
00162   // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
00163   //
00164   // The first R6 kill is not really a kill since it's killed by a predicated
00165   // instruction which may not be executed. The second R6 def may or may not
00166   // re-define R6 so it's not safe to change it since the last R6 use cannot be
00167   // changed.
00168   bool Special = MI->isCall() ||
00169     MI->hasExtraSrcRegAllocReq() ||
00170     TII->isPredicated(MI);
00171 
00172   // Scan the register operands for this instruction and update
00173   // Classes and RegRefs.
00174   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00175     MachineOperand &MO = MI->getOperand(i);
00176     if (!MO.isReg()) continue;
00177     unsigned Reg = MO.getReg();
00178     if (Reg == 0) continue;
00179     const TargetRegisterClass *NewRC = nullptr;
00180 
00181     if (i < MI->getDesc().getNumOperands())
00182       NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
00183 
00184     // For now, only allow the register to be changed if its register
00185     // class is consistent across all uses.
00186     if (!Classes[Reg] && NewRC)
00187       Classes[Reg] = NewRC;
00188     else if (!NewRC || Classes[Reg] != NewRC)
00189       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00190 
00191     // Now check for aliases.
00192     for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
00193       // If an alias of the reg is used during the live range, give up.
00194       // Note that this allows us to skip checking if AntiDepReg
00195       // overlaps with any of the aliases, among other things.
00196       unsigned AliasReg = *AI;
00197       if (Classes[AliasReg]) {
00198         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
00199         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00200       }
00201     }
00202 
00203     // If we're still willing to consider this register, note the reference.
00204     if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
00205       RegRefs.insert(std::make_pair(Reg, &MO));
00206 
00207     // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
00208     // it or any of its sub or super regs. We need to use KeepRegs to mark the
00209     // reg because not all uses of the same reg within an instruction are
00210     // necessarily tagged as tied.
00211     // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
00212     // def register but not the second (see PR20020 for details).
00213     // FIXME: can this check be relaxed to account for undef uses
00214     // of a register? In the above 'xor' example, the uses of %eax are undef, so
00215     // earlier instructions could still replace %eax even though the 'xor'
00216     // itself can't be changed.
00217     if (MI->isRegTiedToUseOperand(i) &&
00218         Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
00219       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
00220            SubRegs.isValid(); ++SubRegs) {
00221         KeepRegs.set(*SubRegs);
00222       }
00223       for (MCSuperRegIterator SuperRegs(Reg, TRI);
00224            SuperRegs.isValid(); ++SuperRegs) {
00225         KeepRegs.set(*SuperRegs);
00226       }
00227     }
00228 
00229     if (MO.isUse() && Special) {
00230       if (!KeepRegs.test(Reg)) {
00231         for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
00232              SubRegs.isValid(); ++SubRegs)
00233           KeepRegs.set(*SubRegs);
00234       }
00235     }
00236   }
00237 }
00238 
00239 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
00240                                              unsigned Count) {
00241   // Update liveness.
00242   // Proceeding upwards, registers that are defed but not used in this
00243   // instruction are now dead.
00244   assert(!MI->isKill() && "Attempting to scan a kill instruction");
00245 
00246   if (!TII->isPredicated(MI)) {
00247     // Predicated defs are modeled as read + write, i.e. similar to two
00248     // address updates.
00249     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00250       MachineOperand &MO = MI->getOperand(i);
00251 
00252       if (MO.isRegMask())
00253         for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
00254           if (MO.clobbersPhysReg(i)) {
00255             DefIndices[i] = Count;
00256             KillIndices[i] = ~0u;
00257             KeepRegs.reset(i);
00258             Classes[i] = nullptr;
00259             RegRefs.erase(i);
00260           }
00261 
00262       if (!MO.isReg()) continue;
00263       unsigned Reg = MO.getReg();
00264       if (Reg == 0) continue;
00265       if (!MO.isDef()) continue;
00266 
00267       // If we've already marked this reg as unchangeable, carry on.
00268       if (KeepRegs.test(Reg)) continue;
00269       
00270       // Ignore two-addr defs.
00271       if (MI->isRegTiedToUseOperand(i)) continue;
00272 
00273       // For the reg itself and all subregs: update the def to current;
00274       // reset the kill state, any restrictions, and references.
00275       for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) {
00276         unsigned SubregReg = *SRI;
00277         DefIndices[SubregReg] = Count;
00278         KillIndices[SubregReg] = ~0u;
00279         KeepRegs.reset(SubregReg);
00280         Classes[SubregReg] = nullptr;
00281         RegRefs.erase(SubregReg);
00282       }
00283       // Conservatively mark super-registers as unusable.
00284       for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
00285         Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
00286     }
00287   }
00288   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00289     MachineOperand &MO = MI->getOperand(i);
00290     if (!MO.isReg()) continue;
00291     unsigned Reg = MO.getReg();
00292     if (Reg == 0) continue;
00293     if (!MO.isUse()) continue;
00294 
00295     const TargetRegisterClass *NewRC = nullptr;
00296     if (i < MI->getDesc().getNumOperands())
00297       NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
00298 
00299     // For now, only allow the register to be changed if its register
00300     // class is consistent across all uses.
00301     if (!Classes[Reg] && NewRC)
00302       Classes[Reg] = NewRC;
00303     else if (!NewRC || Classes[Reg] != NewRC)
00304       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00305 
00306     RegRefs.insert(std::make_pair(Reg, &MO));
00307 
00308     // It wasn't previously live but now it is, this is a kill.
00309     // Repeat for all aliases.
00310     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
00311       unsigned AliasReg = *AI;
00312       if (KillIndices[AliasReg] == ~0u) {
00313         KillIndices[AliasReg] = Count;
00314         DefIndices[AliasReg] = ~0u;
00315       }
00316     }
00317   }
00318 }
00319 
00320 // Check all machine operands that reference the antidependent register and must
00321 // be replaced by NewReg. Return true if any of their parent instructions may
00322 // clobber the new register.
00323 //
00324 // Note: AntiDepReg may be referenced by a two-address instruction such that
00325 // it's use operand is tied to a def operand. We guard against the case in which
00326 // the two-address instruction also defines NewReg, as may happen with
00327 // pre/postincrement loads. In this case, both the use and def operands are in
00328 // RegRefs because the def is inserted by PrescanInstruction and not erased
00329 // during ScanInstruction. So checking for an instruction with definitions of
00330 // both NewReg and AntiDepReg covers it.
00331 bool
00332 CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
00333                                                 RegRefIter RegRefEnd,
00334                                                 unsigned NewReg)
00335 {
00336   for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
00337     MachineOperand *RefOper = I->second;
00338 
00339     // Don't allow the instruction defining AntiDepReg to earlyclobber its
00340     // operands, in case they may be assigned to NewReg. In this case antidep
00341     // breaking must fail, but it's too rare to bother optimizing.
00342     if (RefOper->isDef() && RefOper->isEarlyClobber())
00343       return true;
00344 
00345     // Handle cases in which this instruction defines NewReg.
00346     MachineInstr *MI = RefOper->getParent();
00347     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00348       const MachineOperand &CheckOper = MI->getOperand(i);
00349 
00350       if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
00351         return true;
00352 
00353       if (!CheckOper.isReg() || !CheckOper.isDef() ||
00354           CheckOper.getReg() != NewReg)
00355         continue;
00356 
00357       // Don't allow the instruction to define NewReg and AntiDepReg.
00358       // When AntiDepReg is renamed it will be an illegal op.
00359       if (RefOper->isDef())
00360         return true;
00361 
00362       // Don't allow an instruction using AntiDepReg to be earlyclobbered by
00363       // NewReg.
00364       if (CheckOper.isEarlyClobber())
00365         return true;
00366 
00367       // Don't allow inline asm to define NewReg at all. Who knows what it's
00368       // doing with it.
00369       if (MI->isInlineAsm())
00370         return true;
00371     }
00372   }
00373   return false;
00374 }
00375 
00376 unsigned CriticalAntiDepBreaker::
00377 findSuitableFreeRegister(RegRefIter RegRefBegin,
00378                          RegRefIter RegRefEnd,
00379                          unsigned AntiDepReg,
00380                          unsigned LastNewReg,
00381                          const TargetRegisterClass *RC,
00382                          SmallVectorImpl<unsigned> &Forbid)
00383 {
00384   ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
00385   for (unsigned i = 0; i != Order.size(); ++i) {
00386     unsigned NewReg = Order[i];
00387     // Don't replace a register with itself.
00388     if (NewReg == AntiDepReg) continue;
00389     // Don't replace a register with one that was recently used to repair
00390     // an anti-dependence with this AntiDepReg, because that would
00391     // re-introduce that anti-dependence.
00392     if (NewReg == LastNewReg) continue;
00393     // If any instructions that define AntiDepReg also define the NewReg, it's
00394     // not suitable.  For example, Instruction with multiple definitions can
00395     // result in this condition.
00396     if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
00397     // If NewReg is dead and NewReg's most recent def is not before
00398     // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
00399     assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
00400            && "Kill and Def maps aren't consistent for AntiDepReg!");
00401     assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
00402            && "Kill and Def maps aren't consistent for NewReg!");
00403     if (KillIndices[NewReg] != ~0u ||
00404         Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
00405         KillIndices[AntiDepReg] > DefIndices[NewReg])
00406       continue;
00407     // If NewReg overlaps any of the forbidden registers, we can't use it.
00408     bool Forbidden = false;
00409     for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
00410            ite = Forbid.end(); it != ite; ++it)
00411       if (TRI->regsOverlap(NewReg, *it)) {
00412         Forbidden = true;
00413         break;
00414       }
00415     if (Forbidden) continue;
00416     return NewReg;
00417   }
00418 
00419   // No registers are free and available!
00420   return 0;
00421 }
00422 
00423 unsigned CriticalAntiDepBreaker::
00424 BreakAntiDependencies(const std::vector<SUnit>& SUnits,
00425                       MachineBasicBlock::iterator Begin,
00426                       MachineBasicBlock::iterator End,
00427                       unsigned InsertPosIndex,
00428                       DbgValueVector &DbgValues) {
00429   // The code below assumes that there is at least one instruction,
00430   // so just duck out immediately if the block is empty.
00431   if (SUnits.empty()) return 0;
00432 
00433   // Keep a map of the MachineInstr*'s back to the SUnit representing them.
00434   // This is used for updating debug information.
00435   //
00436   // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
00437   DenseMap<MachineInstr*,const SUnit*> MISUnitMap;
00438 
00439   // Find the node at the bottom of the critical path.
00440   const SUnit *Max = nullptr;
00441   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
00442     const SUnit *SU = &SUnits[i];
00443     MISUnitMap[SU->getInstr()] = SU;
00444     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
00445       Max = SU;
00446   }
00447 
00448 #ifndef NDEBUG
00449   {
00450     DEBUG(dbgs() << "Critical path has total latency "
00451           << (Max->getDepth() + Max->Latency) << "\n");
00452     DEBUG(dbgs() << "Available regs:");
00453     for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
00454       if (KillIndices[Reg] == ~0u)
00455         DEBUG(dbgs() << " " << TRI->getName(Reg));
00456     }
00457     DEBUG(dbgs() << '\n');
00458   }
00459 #endif
00460 
00461   // Track progress along the critical path through the SUnit graph as we walk
00462   // the instructions.
00463   const SUnit *CriticalPathSU = Max;
00464   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
00465 
00466   // Consider this pattern:
00467   //   A = ...
00468   //   ... = A
00469   //   A = ...
00470   //   ... = A
00471   //   A = ...
00472   //   ... = A
00473   //   A = ...
00474   //   ... = A
00475   // There are three anti-dependencies here, and without special care,
00476   // we'd break all of them using the same register:
00477   //   A = ...
00478   //   ... = A
00479   //   B = ...
00480   //   ... = B
00481   //   B = ...
00482   //   ... = B
00483   //   B = ...
00484   //   ... = B
00485   // because at each anti-dependence, B is the first register that
00486   // isn't A which is free.  This re-introduces anti-dependencies
00487   // at all but one of the original anti-dependencies that we were
00488   // trying to break.  To avoid this, keep track of the most recent
00489   // register that each register was replaced with, avoid
00490   // using it to repair an anti-dependence on the same register.
00491   // This lets us produce this:
00492   //   A = ...
00493   //   ... = A
00494   //   B = ...
00495   //   ... = B
00496   //   C = ...
00497   //   ... = C
00498   //   B = ...
00499   //   ... = B
00500   // This still has an anti-dependence on B, but at least it isn't on the
00501   // original critical path.
00502   //
00503   // TODO: If we tracked more than one register here, we could potentially
00504   // fix that remaining critical edge too. This is a little more involved,
00505   // because unlike the most recent register, less recent registers should
00506   // still be considered, though only if no other registers are available.
00507   std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
00508 
00509   // Attempt to break anti-dependence edges on the critical path. Walk the
00510   // instructions from the bottom up, tracking information about liveness
00511   // as we go to help determine which registers are available.
00512   unsigned Broken = 0;
00513   unsigned Count = InsertPosIndex - 1;
00514   for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
00515     MachineInstr *MI = --I;
00516     // Kill instructions can define registers but are really nops, and there
00517     // might be a real definition earlier that needs to be paired with uses
00518     // dominated by this kill.
00519     
00520     // FIXME: It may be possible to remove the isKill() restriction once PR18663
00521     // has been properly fixed. There can be value in processing kills as seen
00522     // in the AggressiveAntiDepBreaker class.
00523     if (MI->isDebugValue() || MI->isKill())
00524       continue;
00525 
00526     // Check if this instruction has a dependence on the critical path that
00527     // is an anti-dependence that we may be able to break. If it is, set
00528     // AntiDepReg to the non-zero register associated with the anti-dependence.
00529     //
00530     // We limit our attention to the critical path as a heuristic to avoid
00531     // breaking anti-dependence edges that aren't going to significantly
00532     // impact the overall schedule. There are a limited number of registers
00533     // and we want to save them for the important edges.
00534     //
00535     // TODO: Instructions with multiple defs could have multiple
00536     // anti-dependencies. The current code here only knows how to break one
00537     // edge per instruction. Note that we'd have to be able to break all of
00538     // the anti-dependencies in an instruction in order to be effective.
00539     unsigned AntiDepReg = 0;
00540     if (MI == CriticalPathMI) {
00541       if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
00542         const SUnit *NextSU = Edge->getSUnit();
00543 
00544         // Only consider anti-dependence edges.
00545         if (Edge->getKind() == SDep::Anti) {
00546           AntiDepReg = Edge->getReg();
00547           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
00548           if (!MRI.isAllocatable(AntiDepReg))
00549             // Don't break anti-dependencies on non-allocatable registers.
00550             AntiDepReg = 0;
00551           else if (KeepRegs.test(AntiDepReg))
00552             // Don't break anti-dependencies if a use down below requires
00553             // this exact register.
00554             AntiDepReg = 0;
00555           else {
00556             // If the SUnit has other dependencies on the SUnit that it
00557             // anti-depends on, don't bother breaking the anti-dependency
00558             // since those edges would prevent such units from being
00559             // scheduled past each other regardless.
00560             //
00561             // Also, if there are dependencies on other SUnits with the
00562             // same register as the anti-dependency, don't attempt to
00563             // break it.
00564             for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
00565                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
00566               if (P->getSUnit() == NextSU ?
00567                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
00568                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
00569                 AntiDepReg = 0;
00570                 break;
00571               }
00572           }
00573         }
00574         CriticalPathSU = NextSU;
00575         CriticalPathMI = CriticalPathSU->getInstr();
00576       } else {
00577         // We've reached the end of the critical path.
00578         CriticalPathSU = nullptr;
00579         CriticalPathMI = nullptr;
00580       }
00581     }
00582 
00583     PrescanInstruction(MI);
00584 
00585     SmallVector<unsigned, 2> ForbidRegs;
00586 
00587     // If MI's defs have a special allocation requirement, don't allow
00588     // any def registers to be changed. Also assume all registers
00589     // defined in a call must not be changed (ABI).
00590     if (MI->isCall() || MI->hasExtraDefRegAllocReq() || TII->isPredicated(MI))
00591       // If this instruction's defs have special allocation requirement, don't
00592       // break this anti-dependency.
00593       AntiDepReg = 0;
00594     else if (AntiDepReg) {
00595       // If this instruction has a use of AntiDepReg, breaking it
00596       // is invalid.  If the instruction defines other registers,
00597       // save a list of them so that we don't pick a new register
00598       // that overlaps any of them.
00599       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00600         MachineOperand &MO = MI->getOperand(i);
00601         if (!MO.isReg()) continue;
00602         unsigned Reg = MO.getReg();
00603         if (Reg == 0) continue;
00604         if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
00605           AntiDepReg = 0;
00606           break;
00607         }
00608         if (MO.isDef() && Reg != AntiDepReg)
00609           ForbidRegs.push_back(Reg);
00610       }
00611     }
00612 
00613     // Determine AntiDepReg's register class, if it is live and is
00614     // consistently used within a single class.
00615     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
00616                                                     : nullptr;
00617     assert((AntiDepReg == 0 || RC != nullptr) &&
00618            "Register should be live if it's causing an anti-dependence!");
00619     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
00620       AntiDepReg = 0;
00621 
00622     // Look for a suitable register to use to break the anti-dependence.
00623     //
00624     // TODO: Instead of picking the first free register, consider which might
00625     // be the best.
00626     if (AntiDepReg != 0) {
00627       std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
00628                 std::multimap<unsigned, MachineOperand *>::iterator>
00629         Range = RegRefs.equal_range(AntiDepReg);
00630       if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
00631                                                      AntiDepReg,
00632                                                      LastNewReg[AntiDepReg],
00633                                                      RC, ForbidRegs)) {
00634         DEBUG(dbgs() << "Breaking anti-dependence edge on "
00635               << TRI->getName(AntiDepReg)
00636               << " with " << RegRefs.count(AntiDepReg) << " references"
00637               << " using " << TRI->getName(NewReg) << "!\n");
00638 
00639         // Update the references to the old register to refer to the new
00640         // register.
00641         for (std::multimap<unsigned, MachineOperand *>::iterator
00642              Q = Range.first, QE = Range.second; Q != QE; ++Q) {
00643           Q->second->setReg(NewReg);
00644           // If the SU for the instruction being updated has debug information
00645           // related to the anti-dependency register, make sure to update that
00646           // as well.
00647           const SUnit *SU = MISUnitMap[Q->second->getParent()];
00648           if (!SU) continue;
00649           for (DbgValueVector::iterator DVI = DbgValues.begin(),
00650                  DVE = DbgValues.end(); DVI != DVE; ++DVI)
00651             if (DVI->second == Q->second->getParent())
00652               UpdateDbgValue(DVI->first, AntiDepReg, NewReg);
00653         }
00654 
00655         // We just went back in time and modified history; the
00656         // liveness information for the anti-dependence reg is now
00657         // inconsistent. Set the state as if it were dead.
00658         Classes[NewReg] = Classes[AntiDepReg];
00659         DefIndices[NewReg] = DefIndices[AntiDepReg];
00660         KillIndices[NewReg] = KillIndices[AntiDepReg];
00661         assert(((KillIndices[NewReg] == ~0u) !=
00662                 (DefIndices[NewReg] == ~0u)) &&
00663              "Kill and Def maps aren't consistent for NewReg!");
00664 
00665         Classes[AntiDepReg] = nullptr;
00666         DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
00667         KillIndices[AntiDepReg] = ~0u;
00668         assert(((KillIndices[AntiDepReg] == ~0u) !=
00669                 (DefIndices[AntiDepReg] == ~0u)) &&
00670              "Kill and Def maps aren't consistent for AntiDepReg!");
00671 
00672         RegRefs.erase(AntiDepReg);
00673         LastNewReg[AntiDepReg] = NewReg;
00674         ++Broken;
00675       }
00676     }
00677 
00678     ScanInstruction(MI, Count);
00679   }
00680 
00681   return Broken;
00682 }