LLVM API Documentation

AggressiveAntiDepBreaker.cpp
Go to the documentation of this file.
00001 //===----- AggressiveAntiDepBreaker.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 AggressiveAntiDepBreaker class, which
00011 // implements register anti-dependence breaking during post-RA
00012 // scheduling. It attempts to break all anti-dependencies within a
00013 // block.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "AggressiveAntiDepBreaker.h"
00018 #include "llvm/CodeGen/MachineBasicBlock.h"
00019 #include "llvm/CodeGen/MachineFrameInfo.h"
00020 #include "llvm/CodeGen/MachineInstr.h"
00021 #include "llvm/CodeGen/RegisterClassInfo.h"
00022 #include "llvm/Support/CommandLine.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/ErrorHandling.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include "llvm/Target/TargetInstrInfo.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 #include "llvm/Target/TargetRegisterInfo.h"
00029 using namespace llvm;
00030 
00031 #define DEBUG_TYPE "post-RA-sched"
00032 
00033 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
00034 static cl::opt<int>
00035 DebugDiv("agg-antidep-debugdiv",
00036          cl::desc("Debug control for aggressive anti-dep breaker"),
00037          cl::init(0), cl::Hidden);
00038 static cl::opt<int>
00039 DebugMod("agg-antidep-debugmod",
00040          cl::desc("Debug control for aggressive anti-dep breaker"),
00041          cl::init(0), cl::Hidden);
00042 
00043 AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs,
00044                                                MachineBasicBlock *BB) :
00045   NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0),
00046   GroupNodeIndices(TargetRegs, 0),
00047   KillIndices(TargetRegs, 0),
00048   DefIndices(TargetRegs, 0)
00049 {
00050   const unsigned BBSize = BB->size();
00051   for (unsigned i = 0; i < NumTargetRegs; ++i) {
00052     // Initialize all registers to be in their own group. Initially we
00053     // assign the register to the same-indexed GroupNode.
00054     GroupNodeIndices[i] = i;
00055     // Initialize the indices to indicate that no registers are live.
00056     KillIndices[i] = ~0u;
00057     DefIndices[i] = BBSize;
00058   }
00059 }
00060 
00061 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg) {
00062   unsigned Node = GroupNodeIndices[Reg];
00063   while (GroupNodes[Node] != Node)
00064     Node = GroupNodes[Node];
00065 
00066   return Node;
00067 }
00068 
00069 void AggressiveAntiDepState::GetGroupRegs(
00070   unsigned Group,
00071   std::vector<unsigned> &Regs,
00072   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
00073 {
00074   for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
00075     if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
00076       Regs.push_back(Reg);
00077   }
00078 }
00079 
00080 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
00081 {
00082   assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
00083   assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
00084 
00085   // find group for each register
00086   unsigned Group1 = GetGroup(Reg1);
00087   unsigned Group2 = GetGroup(Reg2);
00088 
00089   // if either group is 0, then that must become the parent
00090   unsigned Parent = (Group1 == 0) ? Group1 : Group2;
00091   unsigned Other = (Parent == Group1) ? Group2 : Group1;
00092   GroupNodes.at(Other) = Parent;
00093   return Parent;
00094 }
00095 
00096 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
00097 {
00098   // Create a new GroupNode for Reg. Reg's existing GroupNode must
00099   // stay as is because there could be other GroupNodes referring to
00100   // it.
00101   unsigned idx = GroupNodes.size();
00102   GroupNodes.push_back(idx);
00103   GroupNodeIndices[Reg] = idx;
00104   return idx;
00105 }
00106 
00107 bool AggressiveAntiDepState::IsLive(unsigned Reg)
00108 {
00109   // KillIndex must be defined and DefIndex not defined for a register
00110   // to be live.
00111   return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
00112 }
00113 
00114 AggressiveAntiDepBreaker::AggressiveAntiDepBreaker(
00115     MachineFunction &MFi, const RegisterClassInfo &RCI,
00116     TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
00117     : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
00118       TII(MF.getSubtarget().getInstrInfo()),
00119       TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
00120       State(nullptr) {
00121   /* Collect a bitset of all registers that are only broken if they
00122      are on the critical path. */
00123   for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
00124     BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
00125     if (CriticalPathSet.none())
00126       CriticalPathSet = CPSet;
00127     else
00128       CriticalPathSet |= CPSet;
00129    }
00130 
00131   DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
00132   DEBUG(for (int r = CriticalPathSet.find_first(); r != -1;
00133              r = CriticalPathSet.find_next(r))
00134           dbgs() << " " << TRI->getName(r));
00135   DEBUG(dbgs() << '\n');
00136 }
00137 
00138 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
00139   delete State;
00140 }
00141 
00142 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
00143   assert(!State);
00144   State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
00145 
00146   bool IsReturnBlock = (!BB->empty() && BB->back().isReturn());
00147   std::vector<unsigned> &KillIndices = State->GetKillIndices();
00148   std::vector<unsigned> &DefIndices = State->GetDefIndices();
00149 
00150   // Examine the live-in regs of all successors.
00151   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00152          SE = BB->succ_end(); SI != SE; ++SI)
00153     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
00154            E = (*SI)->livein_end(); I != E; ++I) {
00155       for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
00156         unsigned Reg = *AI;
00157         State->UnionGroups(Reg, 0);
00158         KillIndices[Reg] = BB->size();
00159         DefIndices[Reg] = ~0u;
00160       }
00161     }
00162 
00163   // Mark live-out callee-saved registers. In a return block this is
00164   // all callee-saved registers. In non-return this is any
00165   // callee-saved register that is not saved in the prolog.
00166   const MachineFrameInfo *MFI = MF.getFrameInfo();
00167   BitVector Pristine = MFI->getPristineRegs(BB);
00168   for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
00169     unsigned Reg = *I;
00170     if (!IsReturnBlock && !Pristine.test(Reg)) continue;
00171     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
00172       unsigned AliasReg = *AI;
00173       State->UnionGroups(AliasReg, 0);
00174       KillIndices[AliasReg] = BB->size();
00175       DefIndices[AliasReg] = ~0u;
00176     }
00177   }
00178 }
00179 
00180 void AggressiveAntiDepBreaker::FinishBlock() {
00181   delete State;
00182   State = nullptr;
00183 }
00184 
00185 void AggressiveAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
00186                                        unsigned InsertPosIndex) {
00187   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
00188 
00189   std::set<unsigned> PassthruRegs;
00190   GetPassthruRegs(MI, PassthruRegs);
00191   PrescanInstruction(MI, Count, PassthruRegs);
00192   ScanInstruction(MI, Count);
00193 
00194   DEBUG(dbgs() << "Observe: ");
00195   DEBUG(MI->dump());
00196   DEBUG(dbgs() << "\tRegs:");
00197 
00198   std::vector<unsigned> &DefIndices = State->GetDefIndices();
00199   for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
00200     // If Reg is current live, then mark that it can't be renamed as
00201     // we don't know the extent of its live-range anymore (now that it
00202     // has been scheduled). If it is not live but was defined in the
00203     // previous schedule region, then set its def index to the most
00204     // conservative location (i.e. the beginning of the previous
00205     // schedule region).
00206     if (State->IsLive(Reg)) {
00207       DEBUG(if (State->GetGroup(Reg) != 0)
00208               dbgs() << " " << TRI->getName(Reg) << "=g" <<
00209                 State->GetGroup(Reg) << "->g0(region live-out)");
00210       State->UnionGroups(Reg, 0);
00211     } else if ((DefIndices[Reg] < InsertPosIndex)
00212                && (DefIndices[Reg] >= Count)) {
00213       DefIndices[Reg] = Count;
00214     }
00215   }
00216   DEBUG(dbgs() << '\n');
00217 }
00218 
00219 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr *MI,
00220                                                 MachineOperand& MO)
00221 {
00222   if (!MO.isReg() || !MO.isImplicit())
00223     return false;
00224 
00225   unsigned Reg = MO.getReg();
00226   if (Reg == 0)
00227     return false;
00228 
00229   MachineOperand *Op = nullptr;
00230   if (MO.isDef())
00231     Op = MI->findRegisterUseOperand(Reg, true);
00232   else
00233     Op = MI->findRegisterDefOperand(Reg);
00234 
00235   return(Op && Op->isImplicit());
00236 }
00237 
00238 void AggressiveAntiDepBreaker::GetPassthruRegs(MachineInstr *MI,
00239                                            std::set<unsigned>& PassthruRegs) {
00240   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00241     MachineOperand &MO = MI->getOperand(i);
00242     if (!MO.isReg()) continue;
00243     if ((MO.isDef() && MI->isRegTiedToUseOperand(i)) ||
00244         IsImplicitDefUse(MI, MO)) {
00245       const unsigned Reg = MO.getReg();
00246       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
00247            SubRegs.isValid(); ++SubRegs)
00248         PassthruRegs.insert(*SubRegs);
00249     }
00250   }
00251 }
00252 
00253 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
00254 /// in SU that we want to consider for breaking.
00255 static void AntiDepEdges(const SUnit *SU, std::vector<const SDep*>& Edges) {
00256   SmallSet<unsigned, 4> RegSet;
00257   for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
00258        P != PE; ++P) {
00259     if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
00260       unsigned Reg = P->getReg();
00261       if (RegSet.count(Reg) == 0) {
00262         Edges.push_back(&*P);
00263         RegSet.insert(Reg);
00264       }
00265     }
00266   }
00267 }
00268 
00269 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
00270 /// critical path.
00271 static const SUnit *CriticalPathStep(const SUnit *SU) {
00272   const SDep *Next = nullptr;
00273   unsigned NextDepth = 0;
00274   // Find the predecessor edge with the greatest depth.
00275   if (SU) {
00276     for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
00277          P != PE; ++P) {
00278       const SUnit *PredSU = P->getSUnit();
00279       unsigned PredLatency = P->getLatency();
00280       unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
00281       // In the case of a latency tie, prefer an anti-dependency edge over
00282       // other types of edges.
00283       if (NextDepth < PredTotalLatency ||
00284           (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
00285         NextDepth = PredTotalLatency;
00286         Next = &*P;
00287       }
00288     }
00289   }
00290 
00291   return (Next) ? Next->getSUnit() : nullptr;
00292 }
00293 
00294 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
00295                                              const char *tag,
00296                                              const char *header,
00297                                              const char *footer) {
00298   std::vector<unsigned> &KillIndices = State->GetKillIndices();
00299   std::vector<unsigned> &DefIndices = State->GetDefIndices();
00300   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
00301     RegRefs = State->GetRegRefs();
00302 
00303   if (!State->IsLive(Reg)) {
00304     KillIndices[Reg] = KillIdx;
00305     DefIndices[Reg] = ~0u;
00306     RegRefs.erase(Reg);
00307     State->LeaveGroup(Reg);
00308     DEBUG(if (header) {
00309         dbgs() << header << TRI->getName(Reg); header = nullptr; });
00310     DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
00311   }
00312   // Repeat for subregisters.
00313   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00314     unsigned SubregReg = *SubRegs;
00315     if (!State->IsLive(SubregReg)) {
00316       KillIndices[SubregReg] = KillIdx;
00317       DefIndices[SubregReg] = ~0u;
00318       RegRefs.erase(SubregReg);
00319       State->LeaveGroup(SubregReg);
00320       DEBUG(if (header) {
00321           dbgs() << header << TRI->getName(Reg); header = nullptr; });
00322       DEBUG(dbgs() << " " << TRI->getName(SubregReg) << "->g" <<
00323             State->GetGroup(SubregReg) << tag);
00324     }
00325   }
00326 
00327   DEBUG(if (!header && footer) dbgs() << footer);
00328 }
00329 
00330 void AggressiveAntiDepBreaker::PrescanInstruction(MachineInstr *MI,
00331                                                   unsigned Count,
00332                                              std::set<unsigned>& PassthruRegs) {
00333   std::vector<unsigned> &DefIndices = State->GetDefIndices();
00334   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
00335     RegRefs = State->GetRegRefs();
00336 
00337   // Handle dead defs by simulating a last-use of the register just
00338   // after the def. A dead def can occur because the def is truly
00339   // dead, or because only a subregister is live at the def. If we
00340   // don't do this the dead def will be incorrectly merged into the
00341   // previous def.
00342   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00343     MachineOperand &MO = MI->getOperand(i);
00344     if (!MO.isReg() || !MO.isDef()) continue;
00345     unsigned Reg = MO.getReg();
00346     if (Reg == 0) continue;
00347 
00348     HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
00349   }
00350 
00351   DEBUG(dbgs() << "\tDef Groups:");
00352   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00353     MachineOperand &MO = MI->getOperand(i);
00354     if (!MO.isReg() || !MO.isDef()) continue;
00355     unsigned Reg = MO.getReg();
00356     if (Reg == 0) continue;
00357 
00358     DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg));
00359 
00360     // If MI's defs have a special allocation requirement, don't allow
00361     // any def registers to be changed. Also assume all registers
00362     // defined in a call must not be changed (ABI).
00363     if (MI->isCall() || MI->hasExtraDefRegAllocReq() ||
00364         TII->isPredicated(MI)) {
00365       DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
00366       State->UnionGroups(Reg, 0);
00367     }
00368 
00369     // Any aliased that are live at this point are completely or
00370     // partially defined here, so group those aliases with Reg.
00371     for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
00372       unsigned AliasReg = *AI;
00373       if (State->IsLive(AliasReg)) {
00374         State->UnionGroups(Reg, AliasReg);
00375         DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << "(via " <<
00376               TRI->getName(AliasReg) << ")");
00377       }
00378     }
00379 
00380     // Note register reference...
00381     const TargetRegisterClass *RC = nullptr;
00382     if (i < MI->getDesc().getNumOperands())
00383       RC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
00384     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
00385     RegRefs.insert(std::make_pair(Reg, RR));
00386   }
00387 
00388   DEBUG(dbgs() << '\n');
00389 
00390   // Scan the register defs for this instruction and update
00391   // live-ranges.
00392   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00393     MachineOperand &MO = MI->getOperand(i);
00394     if (!MO.isReg() || !MO.isDef()) continue;
00395     unsigned Reg = MO.getReg();
00396     if (Reg == 0) continue;
00397     // Ignore KILLs and passthru registers for liveness...
00398     if (MI->isKill() || (PassthruRegs.count(Reg) != 0))
00399       continue;
00400 
00401     // Update def for Reg and aliases.
00402     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
00403       // We need to be careful here not to define already-live super registers.
00404       // If the super register is already live, then this definition is not
00405       // a definition of the whole super register (just a partial insertion
00406       // into it). Earlier subregister definitions (which we've not yet visited
00407       // because we're iterating bottom-up) need to be linked to the same group
00408       // as this definition.
00409       if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI))
00410         continue;
00411 
00412       DefIndices[*AI] = Count;
00413     }
00414   }
00415 }
00416 
00417 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr *MI,
00418                                                unsigned Count) {
00419   DEBUG(dbgs() << "\tUse Groups:");
00420   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
00421     RegRefs = State->GetRegRefs();
00422 
00423   // If MI's uses have special allocation requirement, don't allow
00424   // any use registers to be changed. Also assume all registers
00425   // used in a call must not be changed (ABI).
00426   // FIXME: The issue with predicated instruction is more complex. We are being
00427   // conservatively here because the kill markers cannot be trusted after
00428   // if-conversion:
00429   // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
00430   // ...
00431   // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
00432   // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
00433   // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
00434   //
00435   // The first R6 kill is not really a kill since it's killed by a predicated
00436   // instruction which may not be executed. The second R6 def may or may not
00437   // re-define R6 so it's not safe to change it since the last R6 use cannot be
00438   // changed.
00439   bool Special = MI->isCall() ||
00440     MI->hasExtraSrcRegAllocReq() ||
00441     TII->isPredicated(MI);
00442 
00443   // Scan the register uses for this instruction and update
00444   // live-ranges, groups and RegRefs.
00445   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00446     MachineOperand &MO = MI->getOperand(i);
00447     if (!MO.isReg() || !MO.isUse()) continue;
00448     unsigned Reg = MO.getReg();
00449     if (Reg == 0) continue;
00450 
00451     DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" <<
00452           State->GetGroup(Reg));
00453 
00454     // It wasn't previously live but now it is, this is a kill. Forget
00455     // the previous live-range information and start a new live-range
00456     // for the register.
00457     HandleLastUse(Reg, Count, "(last-use)");
00458 
00459     if (Special) {
00460       DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
00461       State->UnionGroups(Reg, 0);
00462     }
00463 
00464     // Note register reference...
00465     const TargetRegisterClass *RC = nullptr;
00466     if (i < MI->getDesc().getNumOperands())
00467       RC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
00468     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
00469     RegRefs.insert(std::make_pair(Reg, RR));
00470   }
00471 
00472   DEBUG(dbgs() << '\n');
00473 
00474   // Form a group of all defs and uses of a KILL instruction to ensure
00475   // that all registers are renamed as a group.
00476   if (MI->isKill()) {
00477     DEBUG(dbgs() << "\tKill Group:");
00478 
00479     unsigned FirstReg = 0;
00480     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00481       MachineOperand &MO = MI->getOperand(i);
00482       if (!MO.isReg()) continue;
00483       unsigned Reg = MO.getReg();
00484       if (Reg == 0) continue;
00485 
00486       if (FirstReg != 0) {
00487         DEBUG(dbgs() << "=" << TRI->getName(Reg));
00488         State->UnionGroups(FirstReg, Reg);
00489       } else {
00490         DEBUG(dbgs() << " " << TRI->getName(Reg));
00491         FirstReg = Reg;
00492       }
00493     }
00494 
00495     DEBUG(dbgs() << "->g" << State->GetGroup(FirstReg) << '\n');
00496   }
00497 }
00498 
00499 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
00500   BitVector BV(TRI->getNumRegs(), false);
00501   bool first = true;
00502 
00503   // Check all references that need rewriting for Reg. For each, use
00504   // the corresponding register class to narrow the set of registers
00505   // that are appropriate for renaming.
00506   std::pair<std::multimap<unsigned,
00507                      AggressiveAntiDepState::RegisterReference>::iterator,
00508             std::multimap<unsigned,
00509                      AggressiveAntiDepState::RegisterReference>::iterator>
00510     Range = State->GetRegRefs().equal_range(Reg);
00511   for (std::multimap<unsigned,
00512        AggressiveAntiDepState::RegisterReference>::iterator Q = Range.first,
00513        QE = Range.second; Q != QE; ++Q) {
00514     const TargetRegisterClass *RC = Q->second.RC;
00515     if (!RC) continue;
00516 
00517     BitVector RCBV = TRI->getAllocatableSet(MF, RC);
00518     if (first) {
00519       BV |= RCBV;
00520       first = false;
00521     } else {
00522       BV &= RCBV;
00523     }
00524 
00525     DEBUG(dbgs() << " " << RC->getName());
00526   }
00527 
00528   return BV;
00529 }
00530 
00531 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
00532                                 unsigned AntiDepGroupIndex,
00533                                 RenameOrderType& RenameOrder,
00534                                 std::map<unsigned, unsigned> &RenameMap) {
00535   std::vector<unsigned> &KillIndices = State->GetKillIndices();
00536   std::vector<unsigned> &DefIndices = State->GetDefIndices();
00537   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
00538     RegRefs = State->GetRegRefs();
00539 
00540   // Collect all referenced registers in the same group as
00541   // AntiDepReg. These all need to be renamed together if we are to
00542   // break the anti-dependence.
00543   std::vector<unsigned> Regs;
00544   State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
00545   assert(Regs.size() > 0 && "Empty register group!");
00546   if (Regs.size() == 0)
00547     return false;
00548 
00549   // Find the "superest" register in the group. At the same time,
00550   // collect the BitVector of registers that can be used to rename
00551   // each register.
00552   DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
00553         << ":\n");
00554   std::map<unsigned, BitVector> RenameRegisterMap;
00555   unsigned SuperReg = 0;
00556   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
00557     unsigned Reg = Regs[i];
00558     if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
00559       SuperReg = Reg;
00560 
00561     // If Reg has any references, then collect possible rename regs
00562     if (RegRefs.count(Reg) > 0) {
00563       DEBUG(dbgs() << "\t\t" << TRI->getName(Reg) << ":");
00564 
00565       BitVector BV = GetRenameRegisters(Reg);
00566       RenameRegisterMap.insert(std::pair<unsigned, BitVector>(Reg, BV));
00567 
00568       DEBUG(dbgs() << " ::");
00569       DEBUG(for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
00570               dbgs() << " " << TRI->getName(r));
00571       DEBUG(dbgs() << "\n");
00572     }
00573   }
00574 
00575   // All group registers should be a subreg of SuperReg.
00576   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
00577     unsigned Reg = Regs[i];
00578     if (Reg == SuperReg) continue;
00579     bool IsSub = TRI->isSubRegister(SuperReg, Reg);
00580     // FIXME: remove this once PR18663 has been properly fixed. For now,
00581     // return a conservative answer:
00582     // assert(IsSub && "Expecting group subregister");
00583     if (!IsSub)
00584       return false;
00585   }
00586 
00587 #ifndef NDEBUG
00588   // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
00589   if (DebugDiv > 0) {
00590     static int renamecnt = 0;
00591     if (renamecnt++ % DebugDiv != DebugMod)
00592       return false;
00593 
00594     dbgs() << "*** Performing rename " << TRI->getName(SuperReg) <<
00595       " for debug ***\n";
00596   }
00597 #endif
00598 
00599   // Check each possible rename register for SuperReg in round-robin
00600   // order. If that register is available, and the corresponding
00601   // registers are available for the other group subregisters, then we
00602   // can use those registers to rename.
00603 
00604   // FIXME: Using getMinimalPhysRegClass is very conservative. We should
00605   // check every use of the register and find the largest register class
00606   // that can be used in all of them.
00607   const TargetRegisterClass *SuperRC =
00608     TRI->getMinimalPhysRegClass(SuperReg, MVT::Other);
00609 
00610   ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(SuperRC);
00611   if (Order.empty()) {
00612     DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
00613     return false;
00614   }
00615 
00616   DEBUG(dbgs() << "\tFind Registers:");
00617 
00618   if (RenameOrder.count(SuperRC) == 0)
00619     RenameOrder.insert(RenameOrderType::value_type(SuperRC, Order.size()));
00620 
00621   unsigned OrigR = RenameOrder[SuperRC];
00622   unsigned EndR = ((OrigR == Order.size()) ? 0 : OrigR);
00623   unsigned R = OrigR;
00624   do {
00625     if (R == 0) R = Order.size();
00626     --R;
00627     const unsigned NewSuperReg = Order[R];
00628     // Don't consider non-allocatable registers
00629     if (!MRI.isAllocatable(NewSuperReg)) continue;
00630     // Don't replace a register with itself.
00631     if (NewSuperReg == SuperReg) continue;
00632 
00633     DEBUG(dbgs() << " [" << TRI->getName(NewSuperReg) << ':');
00634     RenameMap.clear();
00635 
00636     // For each referenced group register (which must be a SuperReg or
00637     // a subregister of SuperReg), find the corresponding subregister
00638     // of NewSuperReg and make sure it is free to be renamed.
00639     for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
00640       unsigned Reg = Regs[i];
00641       unsigned NewReg = 0;
00642       if (Reg == SuperReg) {
00643         NewReg = NewSuperReg;
00644       } else {
00645         unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
00646         if (NewSubRegIdx != 0)
00647           NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
00648       }
00649 
00650       DEBUG(dbgs() << " " << TRI->getName(NewReg));
00651 
00652       // Check if Reg can be renamed to NewReg.
00653       BitVector BV = RenameRegisterMap[Reg];
00654       if (!BV.test(NewReg)) {
00655         DEBUG(dbgs() << "(no rename)");
00656         goto next_super_reg;
00657       }
00658 
00659       // If NewReg is dead and NewReg's most recent def is not before
00660       // Regs's kill, it's safe to replace Reg with NewReg. We
00661       // must also check all aliases of NewReg, because we can't define a
00662       // register when any sub or super is already live.
00663       if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
00664         DEBUG(dbgs() << "(live)");
00665         goto next_super_reg;
00666       } else {
00667         bool found = false;
00668         for (MCRegAliasIterator AI(NewReg, TRI, false); AI.isValid(); ++AI) {
00669           unsigned AliasReg = *AI;
00670           if (State->IsLive(AliasReg) ||
00671               (KillIndices[Reg] > DefIndices[AliasReg])) {
00672             DEBUG(dbgs() << "(alias " << TRI->getName(AliasReg) << " live)");
00673             found = true;
00674             break;
00675           }
00676         }
00677         if (found)
00678           goto next_super_reg;
00679       }
00680 
00681       // Record that 'Reg' can be renamed to 'NewReg'.
00682       RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
00683     }
00684 
00685     // If we fall-out here, then every register in the group can be
00686     // renamed, as recorded in RenameMap.
00687     RenameOrder.erase(SuperRC);
00688     RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
00689     DEBUG(dbgs() << "]\n");
00690     return true;
00691 
00692   next_super_reg:
00693     DEBUG(dbgs() << ']');
00694   } while (R != EndR);
00695 
00696   DEBUG(dbgs() << '\n');
00697 
00698   // No registers are free and available!
00699   return false;
00700 }
00701 
00702 /// BreakAntiDependencies - Identifiy anti-dependencies within the
00703 /// ScheduleDAG and break them by renaming registers.
00704 ///
00705 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
00706                               const std::vector<SUnit>& SUnits,
00707                               MachineBasicBlock::iterator Begin,
00708                               MachineBasicBlock::iterator End,
00709                               unsigned InsertPosIndex,
00710                               DbgValueVector &DbgValues) {
00711 
00712   std::vector<unsigned> &KillIndices = State->GetKillIndices();
00713   std::vector<unsigned> &DefIndices = State->GetDefIndices();
00714   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
00715     RegRefs = State->GetRegRefs();
00716 
00717   // The code below assumes that there is at least one instruction,
00718   // so just duck out immediately if the block is empty.
00719   if (SUnits.empty()) return 0;
00720 
00721   // For each regclass the next register to use for renaming.
00722   RenameOrderType RenameOrder;
00723 
00724   // ...need a map from MI to SUnit.
00725   std::map<MachineInstr *, const SUnit *> MISUnitMap;
00726   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
00727     const SUnit *SU = &SUnits[i];
00728     MISUnitMap.insert(std::pair<MachineInstr *, const SUnit *>(SU->getInstr(),
00729                                                                SU));
00730   }
00731 
00732   // Track progress along the critical path through the SUnit graph as
00733   // we walk the instructions. This is needed for regclasses that only
00734   // break critical-path anti-dependencies.
00735   const SUnit *CriticalPathSU = nullptr;
00736   MachineInstr *CriticalPathMI = nullptr;
00737   if (CriticalPathSet.any()) {
00738     for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
00739       const SUnit *SU = &SUnits[i];
00740       if (!CriticalPathSU ||
00741           ((SU->getDepth() + SU->Latency) >
00742            (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
00743         CriticalPathSU = SU;
00744       }
00745     }
00746 
00747     CriticalPathMI = CriticalPathSU->getInstr();
00748   }
00749 
00750 #ifndef NDEBUG
00751   DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
00752   DEBUG(dbgs() << "Available regs:");
00753   for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
00754     if (!State->IsLive(Reg))
00755       DEBUG(dbgs() << " " << TRI->getName(Reg));
00756   }
00757   DEBUG(dbgs() << '\n');
00758 #endif
00759 
00760   // Attempt to break anti-dependence edges. Walk the instructions
00761   // from the bottom up, tracking information about liveness as we go
00762   // to help determine which registers are available.
00763   unsigned Broken = 0;
00764   unsigned Count = InsertPosIndex - 1;
00765   for (MachineBasicBlock::iterator I = End, E = Begin;
00766        I != E; --Count) {
00767     MachineInstr *MI = --I;
00768 
00769     if (MI->isDebugValue())
00770       continue;
00771 
00772     DEBUG(dbgs() << "Anti: ");
00773     DEBUG(MI->dump());
00774 
00775     std::set<unsigned> PassthruRegs;
00776     GetPassthruRegs(MI, PassthruRegs);
00777 
00778     // Process the defs in MI...
00779     PrescanInstruction(MI, Count, PassthruRegs);
00780 
00781     // The dependence edges that represent anti- and output-
00782     // dependencies that are candidates for breaking.
00783     std::vector<const SDep *> Edges;
00784     const SUnit *PathSU = MISUnitMap[MI];
00785     AntiDepEdges(PathSU, Edges);
00786 
00787     // If MI is not on the critical path, then we don't rename
00788     // registers in the CriticalPathSet.
00789     BitVector *ExcludeRegs = nullptr;
00790     if (MI == CriticalPathMI) {
00791       CriticalPathSU = CriticalPathStep(CriticalPathSU);
00792       CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : nullptr;
00793     } else if (CriticalPathSet.any()) {
00794       ExcludeRegs = &CriticalPathSet;
00795     }
00796 
00797     // Ignore KILL instructions (they form a group in ScanInstruction
00798     // but don't cause any anti-dependence breaking themselves)
00799     if (!MI->isKill()) {
00800       // Attempt to break each anti-dependency...
00801       for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
00802         const SDep *Edge = Edges[i];
00803         SUnit *NextSU = Edge->getSUnit();
00804 
00805         if ((Edge->getKind() != SDep::Anti) &&
00806             (Edge->getKind() != SDep::Output)) continue;
00807 
00808         unsigned AntiDepReg = Edge->getReg();
00809         DEBUG(dbgs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
00810         assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
00811 
00812         if (!MRI.isAllocatable(AntiDepReg)) {
00813           // Don't break anti-dependencies on non-allocatable registers.
00814           DEBUG(dbgs() << " (non-allocatable)\n");
00815           continue;
00816         } else if (ExcludeRegs && ExcludeRegs->test(AntiDepReg)) {
00817           // Don't break anti-dependencies for critical path registers
00818           // if not on the critical path
00819           DEBUG(dbgs() << " (not critical-path)\n");
00820           continue;
00821         } else if (PassthruRegs.count(AntiDepReg) != 0) {
00822           // If the anti-dep register liveness "passes-thru", then
00823           // don't try to change it. It will be changed along with
00824           // the use if required to break an earlier antidep.
00825           DEBUG(dbgs() << " (passthru)\n");
00826           continue;
00827         } else {
00828           // No anti-dep breaking for implicit deps
00829           MachineOperand *AntiDepOp = MI->findRegisterDefOperand(AntiDepReg);
00830           assert(AntiDepOp && "Can't find index for defined register operand");
00831           if (!AntiDepOp || AntiDepOp->isImplicit()) {
00832             DEBUG(dbgs() << " (implicit)\n");
00833             continue;
00834           }
00835 
00836           // If the SUnit has other dependencies on the SUnit that
00837           // it anti-depends on, don't bother breaking the
00838           // anti-dependency since those edges would prevent such
00839           // units from being scheduled past each other
00840           // regardless.
00841           //
00842           // Also, if there are dependencies on other SUnits with the
00843           // same register as the anti-dependency, don't attempt to
00844           // break it.
00845           for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
00846                  PE = PathSU->Preds.end(); P != PE; ++P) {
00847             if (P->getSUnit() == NextSU ?
00848                 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
00849                 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
00850               AntiDepReg = 0;
00851               break;
00852             }
00853           }
00854           for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
00855                  PE = PathSU->Preds.end(); P != PE; ++P) {
00856             if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
00857                 (P->getKind() != SDep::Output)) {
00858               DEBUG(dbgs() << " (real dependency)\n");
00859               AntiDepReg = 0;
00860               break;
00861             } else if ((P->getSUnit() != NextSU) &&
00862                        (P->getKind() == SDep::Data) &&
00863                        (P->getReg() == AntiDepReg)) {
00864               DEBUG(dbgs() << " (other dependency)\n");
00865               AntiDepReg = 0;
00866               break;
00867             }
00868           }
00869 
00870           if (AntiDepReg == 0) continue;
00871         }
00872 
00873         assert(AntiDepReg != 0);
00874         if (AntiDepReg == 0) continue;
00875 
00876         // Determine AntiDepReg's register group.
00877         const unsigned GroupIndex = State->GetGroup(AntiDepReg);
00878         if (GroupIndex == 0) {
00879           DEBUG(dbgs() << " (zero group)\n");
00880           continue;
00881         }
00882 
00883         DEBUG(dbgs() << '\n');
00884 
00885         // Look for a suitable register to use to break the anti-dependence.
00886         std::map<unsigned, unsigned> RenameMap;
00887         if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
00888           DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
00889                 << TRI->getName(AntiDepReg) << ":");
00890 
00891           // Handle each group register...
00892           for (std::map<unsigned, unsigned>::iterator
00893                  S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
00894             unsigned CurrReg = S->first;
00895             unsigned NewReg = S->second;
00896 
00897             DEBUG(dbgs() << " " << TRI->getName(CurrReg) << "->" <<
00898                   TRI->getName(NewReg) << "(" <<
00899                   RegRefs.count(CurrReg) << " refs)");
00900 
00901             // Update the references to the old register CurrReg to
00902             // refer to the new register NewReg.
00903             std::pair<std::multimap<unsigned,
00904                            AggressiveAntiDepState::RegisterReference>::iterator,
00905                       std::multimap<unsigned,
00906                            AggressiveAntiDepState::RegisterReference>::iterator>
00907               Range = RegRefs.equal_range(CurrReg);
00908             for (std::multimap<unsigned,
00909                  AggressiveAntiDepState::RegisterReference>::iterator
00910                    Q = Range.first, QE = Range.second; Q != QE; ++Q) {
00911               Q->second.Operand->setReg(NewReg);
00912               // If the SU for the instruction being updated has debug
00913               // information related to the anti-dependency register, make
00914               // sure to update that as well.
00915               const SUnit *SU = MISUnitMap[Q->second.Operand->getParent()];
00916               if (!SU) continue;
00917               for (DbgValueVector::iterator DVI = DbgValues.begin(),
00918                      DVE = DbgValues.end(); DVI != DVE; ++DVI)
00919                 if (DVI->second == Q->second.Operand->getParent())
00920                   UpdateDbgValue(DVI->first, AntiDepReg, NewReg);
00921             }
00922 
00923             // We just went back in time and modified history; the
00924             // liveness information for CurrReg is now inconsistent. Set
00925             // the state as if it were dead.
00926             State->UnionGroups(NewReg, 0);
00927             RegRefs.erase(NewReg);
00928             DefIndices[NewReg] = DefIndices[CurrReg];
00929             KillIndices[NewReg] = KillIndices[CurrReg];
00930 
00931             State->UnionGroups(CurrReg, 0);
00932             RegRefs.erase(CurrReg);
00933             DefIndices[CurrReg] = KillIndices[CurrReg];
00934             KillIndices[CurrReg] = ~0u;
00935             assert(((KillIndices[CurrReg] == ~0u) !=
00936                     (DefIndices[CurrReg] == ~0u)) &&
00937                    "Kill and Def maps aren't consistent for AntiDepReg!");
00938           }
00939 
00940           ++Broken;
00941           DEBUG(dbgs() << '\n');
00942         }
00943       }
00944     }
00945 
00946     ScanInstruction(MI, Count);
00947   }
00948 
00949   return Broken;
00950 }