LLVM  mainline
ScheduleDAGInstrs.cpp
Go to the documentation of this file.
00001 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
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 implements the ScheduleDAGInstrs class, which implements re-scheduling
00011 // of MachineInstrs.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
00016 #include "llvm/ADT/IntEqClasses.h"
00017 #include "llvm/ADT/MapVector.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/SmallSet.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/ValueTracking.h"
00022 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00023 #include "llvm/CodeGen/MachineFunctionPass.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineInstrBuilder.h"
00026 #include "llvm/CodeGen/MachineMemOperand.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/CodeGen/PseudoSourceValue.h"
00029 #include "llvm/CodeGen/RegisterPressure.h"
00030 #include "llvm/CodeGen/ScheduleDFS.h"
00031 #include "llvm/IR/Operator.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/Format.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetInstrInfo.h"
00037 #include "llvm/Target/TargetMachine.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <queue>
00041 
00042 using namespace llvm;
00043 
00044 #define DEBUG_TYPE "misched"
00045 
00046 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
00047     cl::ZeroOrMore, cl::init(false),
00048     cl::desc("Enable use of AA during MI DAG construction"));
00049 
00050 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
00051     cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
00052 
00053 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
00054                                      const MachineLoopInfo *mli,
00055                                      bool RemoveKillFlags)
00056     : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
00057       RemoveKillFlags(RemoveKillFlags), CanHandleTerminators(false),
00058       TrackLaneMasks(false), FirstDbgValue(nullptr) {
00059   DbgValues.clear();
00060 
00061   const TargetSubtargetInfo &ST = mf.getSubtarget();
00062   SchedModel.init(ST.getSchedModel(), &ST, TII);
00063 }
00064 
00065 /// getUnderlyingObjectFromInt - This is the function that does the work of
00066 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
00067 static const Value *getUnderlyingObjectFromInt(const Value *V) {
00068   do {
00069     if (const Operator *U = dyn_cast<Operator>(V)) {
00070       // If we find a ptrtoint, we can transfer control back to the
00071       // regular getUnderlyingObjectFromInt.
00072       if (U->getOpcode() == Instruction::PtrToInt)
00073         return U->getOperand(0);
00074       // If we find an add of a constant, a multiplied value, or a phi, it's
00075       // likely that the other operand will lead us to the base
00076       // object. We don't have to worry about the case where the
00077       // object address is somehow being computed by the multiply,
00078       // because our callers only care when the result is an
00079       // identifiable object.
00080       if (U->getOpcode() != Instruction::Add ||
00081           (!isa<ConstantInt>(U->getOperand(1)) &&
00082            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
00083            !isa<PHINode>(U->getOperand(1))))
00084         return V;
00085       V = U->getOperand(0);
00086     } else {
00087       return V;
00088     }
00089     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
00090   } while (1);
00091 }
00092 
00093 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
00094 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
00095 static void getUnderlyingObjects(const Value *V,
00096                                  SmallVectorImpl<Value *> &Objects,
00097                                  const DataLayout &DL) {
00098   SmallPtrSet<const Value *, 16> Visited;
00099   SmallVector<const Value *, 4> Working(1, V);
00100   do {
00101     V = Working.pop_back_val();
00102 
00103     SmallVector<Value *, 4> Objs;
00104     GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
00105 
00106     for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
00107          I != IE; ++I) {
00108       V = *I;
00109       if (!Visited.insert(V).second)
00110         continue;
00111       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
00112         const Value *O =
00113           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
00114         if (O->getType()->isPointerTy()) {
00115           Working.push_back(O);
00116           continue;
00117         }
00118       }
00119       Objects.push_back(const_cast<Value *>(V));
00120     }
00121   } while (!Working.empty());
00122 }
00123 
00124 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
00125 typedef SmallVector<PointerIntPair<ValueType, 1, bool>, 4>
00126 UnderlyingObjectsVector;
00127 
00128 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
00129 /// information and it can be tracked to a normal reference to a known
00130 /// object, return the Value for that object.
00131 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
00132                                          const MachineFrameInfo *MFI,
00133                                          UnderlyingObjectsVector &Objects,
00134                                          const DataLayout &DL) {
00135   if (!MI->hasOneMemOperand() ||
00136       (!(*MI->memoperands_begin())->getValue() &&
00137        !(*MI->memoperands_begin())->getPseudoValue()) ||
00138       (*MI->memoperands_begin())->isVolatile())
00139     return;
00140 
00141   if (const PseudoSourceValue *PSV =
00142       (*MI->memoperands_begin())->getPseudoValue()) {
00143     // Function that contain tail calls don't have unique PseudoSourceValue
00144     // objects. Two PseudoSourceValues might refer to the same or overlapping
00145     // locations. The client code calling this function assumes this is not the
00146     // case. So return a conservative answer of no known object.
00147     if (MFI->hasTailCall())
00148       return;
00149 
00150     // For now, ignore PseudoSourceValues which may alias LLVM IR values
00151     // because the code that uses this function has no way to cope with
00152     // such aliases.
00153     if (!PSV->isAliased(MFI)) {
00154       bool MayAlias = PSV->mayAlias(MFI);
00155       Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
00156     }
00157     return;
00158   }
00159 
00160   const Value *V = (*MI->memoperands_begin())->getValue();
00161   if (!V)
00162     return;
00163 
00164   SmallVector<Value *, 4> Objs;
00165   getUnderlyingObjects(V, Objs, DL);
00166 
00167   for (Value *V : Objs) {
00168     if (!isIdentifiedObject(V)) {
00169       Objects.clear();
00170       return;
00171     }
00172 
00173     Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
00174   }
00175 }
00176 
00177 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
00178   BB = bb;
00179 }
00180 
00181 void ScheduleDAGInstrs::finishBlock() {
00182   // Subclasses should no longer refer to the old block.
00183   BB = nullptr;
00184 }
00185 
00186 /// Initialize the DAG and common scheduler state for the current scheduling
00187 /// region. This does not actually create the DAG, only clears it. The
00188 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
00189 /// region.
00190 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
00191                                     MachineBasicBlock::iterator begin,
00192                                     MachineBasicBlock::iterator end,
00193                                     unsigned regioninstrs) {
00194   assert(bb == BB && "startBlock should set BB");
00195   RegionBegin = begin;
00196   RegionEnd = end;
00197   NumRegionInstrs = regioninstrs;
00198 }
00199 
00200 /// Close the current scheduling region. Don't clear any state in case the
00201 /// driver wants to refer to the previous scheduling region.
00202 void ScheduleDAGInstrs::exitRegion() {
00203   // Nothing to do.
00204 }
00205 
00206 /// addSchedBarrierDeps - Add dependencies from instructions in the current
00207 /// list of instructions being scheduled to scheduling barrier by adding
00208 /// the exit SU to the register defs and use list. This is because we want to
00209 /// make sure instructions which define registers that are either used by
00210 /// the terminator or are live-out are properly scheduled. This is
00211 /// especially important when the definition latency of the return value(s)
00212 /// are too high to be hidden by the branch or when the liveout registers
00213 /// used by instructions in the fallthrough block.
00214 void ScheduleDAGInstrs::addSchedBarrierDeps() {
00215   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
00216   ExitSU.setInstr(ExitMI);
00217   bool AllDepKnown = ExitMI &&
00218     (ExitMI->isCall() || ExitMI->isBarrier());
00219   if (ExitMI && AllDepKnown) {
00220     // If it's a call or a barrier, add dependencies on the defs and uses of
00221     // instruction.
00222     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
00223       const MachineOperand &MO = ExitMI->getOperand(i);
00224       if (!MO.isReg() || MO.isDef()) continue;
00225       unsigned Reg = MO.getReg();
00226       if (Reg == 0) continue;
00227 
00228       if (TRI->isPhysicalRegister(Reg))
00229         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
00230       else if (MO.readsReg()) // ignore undef operands
00231         addVRegUseDeps(&ExitSU, i);
00232     }
00233   } else {
00234     // For others, e.g. fallthrough, conditional branch, assume the exit
00235     // uses all the registers that are livein to the successor blocks.
00236     assert(Uses.empty() && "Uses in set before adding deps?");
00237     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00238            SE = BB->succ_end(); SI != SE; ++SI)
00239       for (const auto &LI : (*SI)->liveins()) {
00240         if (!Uses.contains(LI.PhysReg))
00241           Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
00242       }
00243   }
00244 }
00245 
00246 /// MO is an operand of SU's instruction that defines a physical register. Add
00247 /// data dependencies from SU to any uses of the physical register.
00248 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
00249   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
00250   assert(MO.isDef() && "expect physreg def");
00251 
00252   // Ask the target if address-backscheduling is desirable, and if so how much.
00253   const TargetSubtargetInfo &ST = MF.getSubtarget();
00254 
00255   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
00256        Alias.isValid(); ++Alias) {
00257     if (!Uses.contains(*Alias))
00258       continue;
00259     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
00260       SUnit *UseSU = I->SU;
00261       if (UseSU == SU)
00262         continue;
00263 
00264       // Adjust the dependence latency using operand def/use information,
00265       // then allow the target to perform its own adjustments.
00266       int UseOp = I->OpIdx;
00267       MachineInstr *RegUse = nullptr;
00268       SDep Dep;
00269       if (UseOp < 0)
00270         Dep = SDep(SU, SDep::Artificial);
00271       else {
00272         // Set the hasPhysRegDefs only for physreg defs that have a use within
00273         // the scheduling region.
00274         SU->hasPhysRegDefs = true;
00275         Dep = SDep(SU, SDep::Data, *Alias);
00276         RegUse = UseSU->getInstr();
00277       }
00278       Dep.setLatency(
00279         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
00280                                          UseOp));
00281 
00282       ST.adjustSchedDependency(SU, UseSU, Dep);
00283       UseSU->addPred(Dep);
00284     }
00285   }
00286 }
00287 
00288 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
00289 /// this SUnit to following instructions in the same scheduling region that
00290 /// depend the physical register referenced at OperIdx.
00291 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
00292   MachineInstr *MI = SU->getInstr();
00293   MachineOperand &MO = MI->getOperand(OperIdx);
00294 
00295   // Optionally add output and anti dependencies. For anti
00296   // dependencies we use a latency of 0 because for a multi-issue
00297   // target we want to allow the defining instruction to issue
00298   // in the same cycle as the using instruction.
00299   // TODO: Using a latency of 1 here for output dependencies assumes
00300   //       there's no cost for reusing registers.
00301   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
00302   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
00303        Alias.isValid(); ++Alias) {
00304     if (!Defs.contains(*Alias))
00305       continue;
00306     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
00307       SUnit *DefSU = I->SU;
00308       if (DefSU == &ExitSU)
00309         continue;
00310       if (DefSU != SU &&
00311           (Kind != SDep::Output || !MO.isDead() ||
00312            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
00313         if (Kind == SDep::Anti)
00314           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
00315         else {
00316           SDep Dep(SU, Kind, /*Reg=*/*Alias);
00317           Dep.setLatency(
00318             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
00319           DefSU->addPred(Dep);
00320         }
00321       }
00322     }
00323   }
00324 
00325   if (!MO.isDef()) {
00326     SU->hasPhysRegUses = true;
00327     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
00328     // retrieve the existing SUnits list for this register's uses.
00329     // Push this SUnit on the use list.
00330     Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
00331     if (RemoveKillFlags)
00332       MO.setIsKill(false);
00333   }
00334   else {
00335     addPhysRegDataDeps(SU, OperIdx);
00336     unsigned Reg = MO.getReg();
00337 
00338     // clear this register's use list
00339     if (Uses.contains(Reg))
00340       Uses.eraseAll(Reg);
00341 
00342     if (!MO.isDead()) {
00343       Defs.eraseAll(Reg);
00344     } else if (SU->isCall) {
00345       // Calls will not be reordered because of chain dependencies (see
00346       // below). Since call operands are dead, calls may continue to be added
00347       // to the DefList making dependence checking quadratic in the size of
00348       // the block. Instead, we leave only one call at the back of the
00349       // DefList.
00350       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
00351       Reg2SUnitsMap::iterator B = P.first;
00352       Reg2SUnitsMap::iterator I = P.second;
00353       for (bool isBegin = I == B; !isBegin; /* empty */) {
00354         isBegin = (--I) == B;
00355         if (!I->SU->isCall)
00356           break;
00357         I = Defs.erase(I);
00358       }
00359     }
00360 
00361     // Defs are pushed in the order they are visited and never reordered.
00362     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
00363   }
00364 }
00365 
00366 LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
00367 {
00368   unsigned Reg = MO.getReg();
00369   // No point in tracking lanemasks if we don't have interesting subregisters.
00370   const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
00371   if (!RC.HasDisjunctSubRegs)
00372     return ~0u;
00373 
00374   unsigned SubReg = MO.getSubReg();
00375   if (SubReg == 0)
00376     return RC.getLaneMask();
00377   return TRI->getSubRegIndexLaneMask(SubReg);
00378 }
00379 
00380 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
00381 /// to instructions that occur later in the same scheduling region if they read
00382 /// from or write to the virtual register defined at OperIdx.
00383 ///
00384 /// TODO: Hoist loop induction variable increments. This has to be
00385 /// reevaluated. Generally, IV scheduling should be done before coalescing.
00386 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
00387   MachineInstr *MI = SU->getInstr();
00388   MachineOperand &MO = MI->getOperand(OperIdx);
00389   unsigned Reg = MO.getReg();
00390 
00391   LaneBitmask DefLaneMask;
00392   LaneBitmask KillLaneMask;
00393   if (TrackLaneMasks) {
00394     bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
00395     DefLaneMask = getLaneMaskForMO(MO);
00396     // If we have a <read-undef> flag, none of the lane values comes from an
00397     // earlier instruction.
00398     KillLaneMask = IsKill ? ~0u : DefLaneMask;
00399 
00400     // Clear undef flag, we'll re-add it later once we know which subregister
00401     // Def is first.
00402     MO.setIsUndef(false);
00403   } else {
00404     DefLaneMask = ~0u;
00405     KillLaneMask = ~0u;
00406   }
00407 
00408   if (MO.isDead()) {
00409     assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
00410            "Dead defs should have no uses");
00411   } else {
00412     // Add data dependence to all uses we found so far.
00413     const TargetSubtargetInfo &ST = MF.getSubtarget();
00414     for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
00415          E = CurrentVRegUses.end(); I != E; /*empty*/) {
00416       LaneBitmask LaneMask = I->LaneMask;
00417       // Ignore uses of other lanes.
00418       if ((LaneMask & KillLaneMask) == 0) {
00419         ++I;
00420         continue;
00421       }
00422 
00423       if ((LaneMask & DefLaneMask) != 0) {
00424         SUnit *UseSU = I->SU;
00425         MachineInstr *Use = UseSU->getInstr();
00426         SDep Dep(SU, SDep::Data, Reg);
00427         Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
00428                                                         I->OperandIndex));
00429         ST.adjustSchedDependency(SU, UseSU, Dep);
00430         UseSU->addPred(Dep);
00431       }
00432 
00433       LaneMask &= ~KillLaneMask;
00434       // If we found a Def for all lanes of this use, remove it from the list.
00435       if (LaneMask != 0) {
00436         I->LaneMask = LaneMask;
00437         ++I;
00438       } else
00439         I = CurrentVRegUses.erase(I);
00440     }
00441   }
00442 
00443   // Shortcut: Singly defined vregs do not have output/anti dependencies.
00444   if (MRI.hasOneDef(Reg))
00445     return;
00446 
00447   // Add output dependence to the next nearest defs of this vreg.
00448   //
00449   // Unless this definition is dead, the output dependence should be
00450   // transitively redundant with antidependencies from this definition's
00451   // uses. We're conservative for now until we have a way to guarantee the uses
00452   // are not eliminated sometime during scheduling. The output dependence edge
00453   // is also useful if output latency exceeds def-use latency.
00454   LaneBitmask LaneMask = DefLaneMask;
00455   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
00456                                      CurrentVRegDefs.end())) {
00457     // Ignore defs for other lanes.
00458     if ((V2SU.LaneMask & LaneMask) == 0)
00459       continue;
00460     // Add an output dependence.
00461     SUnit *DefSU = V2SU.SU;
00462     // Ignore additional defs of the same lanes in one instruction. This can
00463     // happen because lanemasks are shared for targets with too many
00464     // subregisters. We also use some representration tricks/hacks where we
00465     // add super-register defs/uses, to imply that although we only access parts
00466     // of the reg we care about the full one.
00467     if (DefSU == SU)
00468       continue;
00469     SDep Dep(SU, SDep::Output, Reg);
00470     Dep.setLatency(
00471       SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
00472     DefSU->addPred(Dep);
00473 
00474     // Update current definition. This can get tricky if the def was about a
00475     // bigger lanemask before. We then have to shrink it and create a new
00476     // VReg2SUnit for the non-overlapping part.
00477     LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
00478     LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
00479     if (NonOverlapMask != 0)
00480       CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, V2SU.SU));
00481     V2SU.SU = SU;
00482     V2SU.LaneMask = OverlapMask;
00483   }
00484   // If there was no CurrentVRegDefs entry for some lanes yet, create one.
00485   if (LaneMask != 0)
00486     CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
00487 }
00488 
00489 /// addVRegUseDeps - Add a register data dependency if the instruction that
00490 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
00491 /// register antidependency from this SUnit to instructions that occur later in
00492 /// the same scheduling region if they write the virtual register.
00493 ///
00494 /// TODO: Handle ExitSU "uses" properly.
00495 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
00496   const MachineInstr *MI = SU->getInstr();
00497   const MachineOperand &MO = MI->getOperand(OperIdx);
00498   unsigned Reg = MO.getReg();
00499 
00500   // Remember the use. Data dependencies will be added when we find the def.
00501   LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO) : ~0u;
00502   CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
00503 
00504   // Add antidependences to the following defs of the vreg.
00505   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
00506                                      CurrentVRegDefs.end())) {
00507     // Ignore defs for unrelated lanes.
00508     LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
00509     if ((PrevDefLaneMask & LaneMask) == 0)
00510       continue;
00511     if (V2SU.SU == SU)
00512       continue;
00513 
00514     V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
00515   }
00516 }
00517 
00518 /// Return true if MI is an instruction we are unable to reason about
00519 /// (like a call or something with unmodeled side effects).
00520 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
00521   return MI->isCall() || MI->hasUnmodeledSideEffects() ||
00522          (MI->hasOrderedMemoryRef() &&
00523           (!MI->mayLoad() || !MI->isInvariantLoad(AA)));
00524 }
00525 
00526 // This MI might have either incomplete info, or known to be unsafe
00527 // to deal with (i.e. volatile object).
00528 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
00529                                         const MachineFrameInfo *MFI,
00530                                         const DataLayout &DL) {
00531   if (!MI || MI->memoperands_empty())
00532     return true;
00533   // We purposefully do no check for hasOneMemOperand() here
00534   // in hope to trigger an assert downstream in order to
00535   // finish implementation.
00536   if ((*MI->memoperands_begin())->isVolatile() ||
00537        MI->hasUnmodeledSideEffects())
00538     return true;
00539 
00540   if ((*MI->memoperands_begin())->getPseudoValue()) {
00541     // Similarly to getUnderlyingObjectForInstr:
00542     // For now, ignore PseudoSourceValues which may alias LLVM IR values
00543     // because the code that uses this function has no way to cope with
00544     // such aliases.
00545     return true;
00546   }
00547 
00548   const Value *V = (*MI->memoperands_begin())->getValue();
00549   if (!V)
00550     return true;
00551 
00552   SmallVector<Value *, 4> Objs;
00553   getUnderlyingObjects(V, Objs, DL);
00554   for (Value *V : Objs) {
00555     // Does this pointer refer to a distinct and identifiable object?
00556     if (!isIdentifiedObject(V))
00557       return true;
00558   }
00559 
00560   return false;
00561 }
00562 
00563 /// This returns true if the two MIs need a chain edge between them.
00564 /// If these are not even memory operations, we still may need
00565 /// chain deps between them. The question really is - could
00566 /// these two MIs be reordered during scheduling from memory dependency
00567 /// point of view.
00568 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00569                              const DataLayout &DL, MachineInstr *MIa,
00570                              MachineInstr *MIb) {
00571   const MachineFunction *MF = MIa->getParent()->getParent();
00572   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00573 
00574   // Cover a trivial case - no edge is need to itself.
00575   if (MIa == MIb)
00576     return false;
00577  
00578   // Let the target decide if memory accesses cannot possibly overlap.
00579   if ((MIa->mayLoad() || MIa->mayStore()) &&
00580       (MIb->mayLoad() || MIb->mayStore()))
00581     if (TII->areMemAccessesTriviallyDisjoint(MIa, MIb, AA))
00582       return false;
00583 
00584   // FIXME: Need to handle multiple memory operands to support all targets.
00585   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
00586     return true;
00587 
00588   if (isUnsafeMemoryObject(MIa, MFI, DL) || isUnsafeMemoryObject(MIb, MFI, DL))
00589     return true;
00590 
00591   // If we are dealing with two "normal" loads, we do not need an edge
00592   // between them - they could be reordered.
00593   if (!MIa->mayStore() && !MIb->mayStore())
00594     return false;
00595 
00596   // To this point analysis is generic. From here on we do need AA.
00597   if (!AA)
00598     return true;
00599 
00600   MachineMemOperand *MMOa = *MIa->memoperands_begin();
00601   MachineMemOperand *MMOb = *MIb->memoperands_begin();
00602 
00603   if (!MMOa->getValue() || !MMOb->getValue())
00604     return true;
00605 
00606   // The following interface to AA is fashioned after DAGCombiner::isAlias
00607   // and operates with MachineMemOperand offset with some important
00608   // assumptions:
00609   //   - LLVM fundamentally assumes flat address spaces.
00610   //   - MachineOperand offset can *only* result from legalization and
00611   //     cannot affect queries other than the trivial case of overlap
00612   //     checking.
00613   //   - These offsets never wrap and never step outside
00614   //     of allocated objects.
00615   //   - There should never be any negative offsets here.
00616   //
00617   // FIXME: Modify API to hide this math from "user"
00618   // FIXME: Even before we go to AA we can reason locally about some
00619   // memory objects. It can save compile time, and possibly catch some
00620   // corner cases not currently covered.
00621 
00622   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
00623   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
00624 
00625   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
00626   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
00627   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
00628 
00629   AliasResult AAResult =
00630       AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
00631                                UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
00632                 MemoryLocation(MMOb->getValue(), Overlapb,
00633                                UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
00634 
00635   return (AAResult != NoAlias);
00636 }
00637 
00638 /// This recursive function iterates over chain deps of SUb looking for
00639 /// "latest" node that needs a chain edge to SUa.
00640 static unsigned iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00641                                  const DataLayout &DL, SUnit *SUa, SUnit *SUb,
00642                                  SUnit *ExitSU, unsigned *Depth,
00643                                  SmallPtrSetImpl<const SUnit *> &Visited) {
00644   if (!SUa || !SUb || SUb == ExitSU)
00645     return *Depth;
00646 
00647   // Remember visited nodes.
00648   if (!Visited.insert(SUb).second)
00649       return *Depth;
00650   // If there is _some_ dependency already in place, do not
00651   // descend any further.
00652   // TODO: Need to make sure that if that dependency got eliminated or ignored
00653   // for any reason in the future, we would not violate DAG topology.
00654   // Currently it does not happen, but makes an implicit assumption about
00655   // future implementation.
00656   //
00657   // Independently, if we encounter node that is some sort of global
00658   // object (like a call) we already have full set of dependencies to it
00659   // and we can stop descending.
00660   if (SUa->isSucc(SUb) ||
00661       isGlobalMemoryObject(AA, SUb->getInstr()))
00662     return *Depth;
00663 
00664   // If we do need an edge, or we have exceeded depth budget,
00665   // add that edge to the predecessors chain of SUb,
00666   // and stop descending.
00667   if (*Depth > 200 ||
00668       MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
00669     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
00670     return *Depth;
00671   }
00672   // Track current depth.
00673   (*Depth)++;
00674   // Iterate over memory dependencies only.
00675   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
00676        I != E; ++I)
00677     if (I->isNormalMemoryOrBarrier())
00678       iterateChainSucc(AA, MFI, DL, SUa, I->getSUnit(), ExitSU, Depth, Visited);
00679   return *Depth;
00680 }
00681 
00682 /// This function assumes that "downward" from SU there exist
00683 /// tail/leaf of already constructed DAG. It iterates downward and
00684 /// checks whether SU can be aliasing any node dominated
00685 /// by it.
00686 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00687                             const DataLayout &DL, SUnit *SU, SUnit *ExitSU,
00688                             std::set<SUnit *> &CheckList,
00689                             unsigned LatencyToLoad) {
00690   if (!SU)
00691     return;
00692 
00693   SmallPtrSet<const SUnit*, 16> Visited;
00694   unsigned Depth = 0;
00695 
00696   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
00697        I != IE; ++I) {
00698     if (SU == *I)
00699       continue;
00700     if (MIsNeedChainEdge(AA, MFI, DL, SU->getInstr(), (*I)->getInstr())) {
00701       SDep Dep(SU, SDep::MayAliasMem);
00702       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
00703       (*I)->addPred(Dep);
00704     }
00705 
00706     // Iterate recursively over all previously added memory chain
00707     // successors. Keep track of visited nodes.
00708     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
00709          JE = (*I)->Succs.end(); J != JE; ++J)
00710       if (J->isNormalMemoryOrBarrier())
00711         iterateChainSucc(AA, MFI, DL, SU, J->getSUnit(), ExitSU, &Depth,
00712                          Visited);
00713   }
00714 }
00715 
00716 /// Check whether two objects need a chain edge, if so, add it
00717 /// otherwise remember the rejected SU.
00718 static inline void addChainDependency(AliasAnalysis *AA,
00719                                       const MachineFrameInfo *MFI,
00720                                       const DataLayout &DL, SUnit *SUa,
00721                                       SUnit *SUb, std::set<SUnit *> &RejectList,
00722                                       unsigned TrueMemOrderLatency = 0,
00723                                       bool isNormalMemory = false) {
00724   // If this is a false dependency,
00725   // do not add the edge, but remember the rejected node.
00726   if (MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
00727     SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
00728     Dep.setLatency(TrueMemOrderLatency);
00729     SUb->addPred(Dep);
00730   }
00731   else {
00732     // Duplicate entries should be ignored.
00733     RejectList.insert(SUb);
00734     DEBUG(dbgs() << "\tReject chain dep between SU("
00735           << SUa->NodeNum << ") and SU("
00736           << SUb->NodeNum << ")\n");
00737   }
00738 }
00739 
00740 /// Create an SUnit for each real instruction, numbered in top-down topological
00741 /// order. The instruction order A < B, implies that no edge exists from B to A.
00742 ///
00743 /// Map each real instruction to its SUnit.
00744 ///
00745 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
00746 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
00747 /// instead of pointers.
00748 ///
00749 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
00750 /// the original instruction list.
00751 void ScheduleDAGInstrs::initSUnits() {
00752   // We'll be allocating one SUnit for each real instruction in the region,
00753   // which is contained within a basic block.
00754   SUnits.reserve(NumRegionInstrs);
00755 
00756   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
00757     MachineInstr *MI = I;
00758     if (MI->isDebugValue())
00759       continue;
00760 
00761     SUnit *SU = newSUnit(MI);
00762     MISUnitMap[MI] = SU;
00763 
00764     SU->isCall = MI->isCall();
00765     SU->isCommutable = MI->isCommutable();
00766 
00767     // Assign the Latency field of SU using target-provided information.
00768     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
00769 
00770     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
00771     //
00772     // Reserved resources block an instruction from issuing and stall the
00773     // entire pipeline. These are identified by BufferSize=0.
00774     //
00775     // Unbuffered resources prevent execution of subsequent instructions that
00776     // require the same resources. This is used for in-order execution pipelines
00777     // within an out-of-order core. These are identified by BufferSize=1.
00778     if (SchedModel.hasInstrSchedModel()) {
00779       const MCSchedClassDesc *SC = getSchedClass(SU);
00780       for (TargetSchedModel::ProcResIter
00781              PI = SchedModel.getWriteProcResBegin(SC),
00782              PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
00783         switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
00784         case 0:
00785           SU->hasReservedResource = true;
00786           break;
00787         case 1:
00788           SU->isUnbuffered = true;
00789           break;
00790         default:
00791           break;
00792         }
00793       }
00794     }
00795   }
00796 }
00797 
00798 void ScheduleDAGInstrs::collectVRegUses(SUnit *SU) {
00799   const MachineInstr *MI = SU->getInstr();
00800   for (const MachineOperand &MO : MI->operands()) {
00801     if (!MO.isReg())
00802       continue;
00803     if (!MO.readsReg())
00804       continue;
00805     if (TrackLaneMasks && !MO.isUse())
00806       continue;
00807 
00808     unsigned Reg = MO.getReg();
00809     if (!TargetRegisterInfo::isVirtualRegister(Reg))
00810       continue;
00811 
00812     // Ignore re-defs.
00813     if (TrackLaneMasks) {
00814       bool FoundDef = false;
00815       for (const MachineOperand &MO2 : MI->operands()) {
00816         if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
00817           FoundDef = true;
00818           break;
00819         }
00820       }
00821       if (FoundDef)
00822         continue;
00823     }
00824 
00825     // Record this local VReg use.
00826     VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
00827     for (; UI != VRegUses.end(); ++UI) {
00828       if (UI->SU == SU)
00829         break;
00830     }
00831     if (UI == VRegUses.end())
00832       VRegUses.insert(VReg2SUnit(Reg, 0, SU));
00833   }
00834 }
00835 
00836 /// If RegPressure is non-null, compute register pressure as a side effect. The
00837 /// DAG builder is an efficient place to do it because it already visits
00838 /// operands.
00839 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
00840                                         RegPressureTracker *RPTracker,
00841                                         PressureDiffs *PDiffs,
00842                                         LiveIntervals *LIS,
00843                                         bool TrackLaneMasks) {
00844   const TargetSubtargetInfo &ST = MF.getSubtarget();
00845   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
00846                                                        : ST.useAA();
00847   AliasAnalysis *AAForDep = UseAA ? AA : nullptr;
00848 
00849   this->TrackLaneMasks = TrackLaneMasks;
00850   MISUnitMap.clear();
00851   ScheduleDAG::clearDAG();
00852 
00853   // Create an SUnit for each real instruction.
00854   initSUnits();
00855 
00856   if (PDiffs)
00857     PDiffs->init(SUnits.size());
00858 
00859   // We build scheduling units by walking a block's instruction list from bottom
00860   // to top.
00861 
00862   // Remember where a generic side-effecting instruction is as we proceed.
00863   SUnit *BarrierChain = nullptr, *AliasChain = nullptr;
00864 
00865   // Memory references to specific known memory locations are tracked
00866   // so that they can be given more precise dependencies. We track
00867   // separately the known memory locations that may alias and those
00868   // that are known not to alias
00869   MapVector<ValueType, std::vector<SUnit *> > AliasMemDefs, NonAliasMemDefs;
00870   MapVector<ValueType, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
00871   std::set<SUnit*> RejectMemNodes;
00872 
00873   // Remove any stale debug info; sometimes BuildSchedGraph is called again
00874   // without emitting the info from the previous call.
00875   DbgValues.clear();
00876   FirstDbgValue = nullptr;
00877 
00878   assert(Defs.empty() && Uses.empty() &&
00879          "Only BuildGraph should update Defs/Uses");
00880   Defs.setUniverse(TRI->getNumRegs());
00881   Uses.setUniverse(TRI->getNumRegs());
00882 
00883   assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
00884   assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
00885   unsigned NumVirtRegs = MRI.getNumVirtRegs();
00886   CurrentVRegDefs.setUniverse(NumVirtRegs);
00887   CurrentVRegUses.setUniverse(NumVirtRegs);
00888 
00889   VRegUses.clear();
00890   VRegUses.setUniverse(NumVirtRegs);
00891 
00892   // Model data dependencies between instructions being scheduled and the
00893   // ExitSU.
00894   addSchedBarrierDeps();
00895 
00896   // Walk the list of instructions, from bottom moving up.
00897   MachineInstr *DbgMI = nullptr;
00898   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
00899        MII != MIE; --MII) {
00900     MachineInstr *MI = std::prev(MII);
00901     if (MI && DbgMI) {
00902       DbgValues.push_back(std::make_pair(DbgMI, MI));
00903       DbgMI = nullptr;
00904     }
00905 
00906     if (MI->isDebugValue()) {
00907       DbgMI = MI;
00908       continue;
00909     }
00910     SUnit *SU = MISUnitMap[MI];
00911     assert(SU && "No SUnit mapped to this MI");
00912 
00913     if (RPTracker) {
00914       collectVRegUses(SU);
00915 
00916       RegisterOperands RegOpers;
00917       RegOpers.collect(*MI, *TRI, MRI, TrackLaneMasks, false);
00918       if (TrackLaneMasks) {
00919         SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
00920         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
00921       }
00922       if (PDiffs != nullptr)
00923         PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
00924 
00925       RPTracker->recedeSkipDebugValues();
00926       assert(&*RPTracker->getPos() == MI && "RPTracker in sync");
00927       RPTracker->recede(RegOpers);
00928     }
00929 
00930     assert(
00931         (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) &&
00932         "Cannot schedule terminators or labels!");
00933 
00934     // Add register-based dependencies (data, anti, and output).
00935     bool HasVRegDef = false;
00936     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
00937       const MachineOperand &MO = MI->getOperand(j);
00938       if (!MO.isReg()) continue;
00939       unsigned Reg = MO.getReg();
00940       if (Reg == 0) continue;
00941 
00942       if (TRI->isPhysicalRegister(Reg))
00943         addPhysRegDeps(SU, j);
00944       else {
00945         if (MO.isDef()) {
00946           HasVRegDef = true;
00947           addVRegDefDeps(SU, j);
00948         }
00949         else if (MO.readsReg()) // ignore undef operands
00950           addVRegUseDeps(SU, j);
00951       }
00952     }
00953     // If we haven't seen any uses in this scheduling region, create a
00954     // dependence edge to ExitSU to model the live-out latency. This is required
00955     // for vreg defs with no in-region use, and prefetches with no vreg def.
00956     //
00957     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
00958     // check currently relies on being called before adding chain deps.
00959     if (SU->NumSuccs == 0 && SU->Latency > 1
00960         && (HasVRegDef || MI->mayLoad())) {
00961       SDep Dep(SU, SDep::Artificial);
00962       Dep.setLatency(SU->Latency - 1);
00963       ExitSU.addPred(Dep);
00964     }
00965 
00966     // Add chain dependencies.
00967     // Chain dependencies used to enforce memory order should have
00968     // latency of 0 (except for true dependency of Store followed by
00969     // aliased Load... we estimate that with a single cycle of latency
00970     // assuming the hardware will bypass)
00971     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
00972     // after stack slots are lowered to actual addresses.
00973     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
00974     // produce more precise dependence information.
00975     unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
00976     if (isGlobalMemoryObject(AA, MI)) {
00977       // Be conservative with these and add dependencies on all memory
00978       // references, even those that are known to not alias.
00979       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00980              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
00981         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
00982           I->second[i]->addPred(SDep(SU, SDep::Barrier));
00983         }
00984       }
00985       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00986              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
00987         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
00988           SDep Dep(SU, SDep::Barrier);
00989           Dep.setLatency(TrueMemOrderLatency);
00990           I->second[i]->addPred(Dep);
00991         }
00992       }
00993       // Add SU to the barrier chain.
00994       if (BarrierChain)
00995         BarrierChain->addPred(SDep(SU, SDep::Barrier));
00996       BarrierChain = SU;
00997       // This is a barrier event that acts as a pivotal node in the DAG,
00998       // so it is safe to clear list of exposed nodes.
00999       adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU, RejectMemNodes,
01000                       TrueMemOrderLatency);
01001       RejectMemNodes.clear();
01002       NonAliasMemDefs.clear();
01003       NonAliasMemUses.clear();
01004 
01005       // fall-through
01006     new_alias_chain:
01007       // Chain all possibly aliasing memory references through SU.
01008       if (AliasChain) {
01009         unsigned ChainLatency = 0;
01010         if (AliasChain->getInstr()->mayLoad())
01011           ChainLatency = TrueMemOrderLatency;
01012         addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU, AliasChain,
01013                            RejectMemNodes, ChainLatency);
01014       }
01015       AliasChain = SU;
01016       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
01017         addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01018                            PendingLoads[k], RejectMemNodes,
01019                            TrueMemOrderLatency);
01020       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01021            AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) {
01022         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01023           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01024                              I->second[i], RejectMemNodes);
01025       }
01026       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01027            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
01028         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01029           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01030                              I->second[i], RejectMemNodes, TrueMemOrderLatency);
01031       }
01032       // This call must come after calls to addChainDependency() since it
01033       // consumes the 'RejectMemNodes' list that addChainDependency() possibly
01034       // adds to.
01035       adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU, RejectMemNodes,
01036                       TrueMemOrderLatency);
01037       PendingLoads.clear();
01038       AliasMemDefs.clear();
01039       AliasMemUses.clear();
01040     } else if (MI->mayStore()) {
01041       // Add dependence on barrier chain, if needed.
01042       // There is no point to check aliasing on barrier event. Even if
01043       // SU and barrier _could_ be reordered, they should not. In addition,
01044       // we have lost all RejectMemNodes below barrier.
01045       if (BarrierChain)
01046         BarrierChain->addPred(SDep(SU, SDep::Barrier));
01047 
01048       UnderlyingObjectsVector Objs;
01049       getUnderlyingObjectsForInstr(MI, MFI, Objs, MF.getDataLayout());
01050 
01051       if (Objs.empty()) {
01052         // Treat all other stores conservatively.
01053         goto new_alias_chain;
01054       }
01055 
01056       bool MayAlias = false;
01057       for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
01058            K != KE; ++K) {
01059         ValueType V = K->getPointer();
01060         bool ThisMayAlias = K->getInt();
01061         if (ThisMayAlias)
01062           MayAlias = true;
01063 
01064         // A store to a specific PseudoSourceValue. Add precise dependencies.
01065         // Record the def in MemDefs, first adding a dep if there is
01066         // an existing def.
01067         MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01068           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
01069         MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
01070           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
01071         if (I != IE) {
01072           for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01073             addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01074                                I->second[i], RejectMemNodes, 0, true);
01075 
01076           // If we're not using AA, then we only need one store per object.
01077           if (!AAForDep)
01078             I->second.clear();
01079           I->second.push_back(SU);
01080         } else {
01081           if (ThisMayAlias) {
01082             if (!AAForDep)
01083               AliasMemDefs[V].clear();
01084             AliasMemDefs[V].push_back(SU);
01085           } else {
01086             if (!AAForDep)
01087               NonAliasMemDefs[V].clear();
01088             NonAliasMemDefs[V].push_back(SU);
01089           }
01090         }
01091         // Handle the uses in MemUses, if there are any.
01092         MapVector<ValueType, std::vector<SUnit *> >::iterator J =
01093           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
01094         MapVector<ValueType, std::vector<SUnit *> >::iterator JE =
01095           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
01096         if (J != JE) {
01097           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
01098             addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01099                                J->second[i], RejectMemNodes,
01100                                TrueMemOrderLatency, true);
01101           J->second.clear();
01102         }
01103       }
01104       if (MayAlias) {
01105         // Add dependencies from all the PendingLoads, i.e. loads
01106         // with no underlying object.
01107         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
01108           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01109                              PendingLoads[k], RejectMemNodes,
01110                              TrueMemOrderLatency);
01111         // Add dependence on alias chain, if needed.
01112         if (AliasChain)
01113           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU, AliasChain,
01114                              RejectMemNodes);
01115       }
01116       // This call must come after calls to addChainDependency() since it
01117       // consumes the 'RejectMemNodes' list that addChainDependency() possibly
01118       // adds to.
01119       adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU, RejectMemNodes,
01120                       TrueMemOrderLatency);
01121     } else if (MI->mayLoad()) {
01122       bool MayAlias = true;
01123       if (MI->isInvariantLoad(AA)) {
01124         // Invariant load, no chain dependencies needed!
01125       } else {
01126         UnderlyingObjectsVector Objs;
01127         getUnderlyingObjectsForInstr(MI, MFI, Objs, MF.getDataLayout());
01128 
01129         if (Objs.empty()) {
01130           // A load with no underlying object. Depend on all
01131           // potentially aliasing stores.
01132           for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01133                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
01134             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01135               addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01136                                  I->second[i], RejectMemNodes);
01137 
01138           PendingLoads.push_back(SU);
01139           MayAlias = true;
01140         } else {
01141           MayAlias = false;
01142         }
01143 
01144         for (UnderlyingObjectsVector::iterator
01145              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
01146           ValueType V = J->getPointer();
01147           bool ThisMayAlias = J->getInt();
01148 
01149           if (ThisMayAlias)
01150             MayAlias = true;
01151 
01152           // A load from a specific PseudoSourceValue. Add precise dependencies.
01153           MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01154             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
01155           MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
01156             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
01157           if (I != IE)
01158             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01159               addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
01160                                  I->second[i], RejectMemNodes, 0, true);
01161           if (ThisMayAlias)
01162             AliasMemUses[V].push_back(SU);
01163           else
01164             NonAliasMemUses[V].push_back(SU);
01165         }
01166         // Add dependencies on alias and barrier chains, if needed.
01167         if (MayAlias && AliasChain)
01168           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU, AliasChain,
01169                              RejectMemNodes);
01170         if (MayAlias)
01171           // This call must come after calls to addChainDependency() since it
01172           // consumes the 'RejectMemNodes' list that addChainDependency()
01173           // possibly adds to.
01174           adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU,
01175                           RejectMemNodes, /*Latency=*/0);
01176         if (BarrierChain)
01177           BarrierChain->addPred(SDep(SU, SDep::Barrier));
01178       }
01179     }
01180   }
01181   if (DbgMI)
01182     FirstDbgValue = DbgMI;
01183 
01184   Defs.clear();
01185   Uses.clear();
01186   CurrentVRegDefs.clear();
01187   CurrentVRegUses.clear();
01188   PendingLoads.clear();
01189 }
01190 
01191 /// \brief Initialize register live-range state for updating kills.
01192 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
01193   // Start with no live registers.
01194   LiveRegs.reset();
01195 
01196   // Examine the live-in regs of all successors.
01197   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
01198        SE = BB->succ_end(); SI != SE; ++SI) {
01199     for (const auto &LI : (*SI)->liveins()) {
01200       // Repeat, for reg and all subregs.
01201       for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
01202            SubRegs.isValid(); ++SubRegs)
01203         LiveRegs.set(*SubRegs);
01204     }
01205   }
01206 }
01207 
01208 /// \brief If we change a kill flag on the bundle instruction implicit register
01209 /// operands, then we also need to propagate that to any instructions inside
01210 /// the bundle which had the same kill state.
01211 static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
01212                                  bool NewKillState) {
01213   if (MI->getOpcode() != TargetOpcode::BUNDLE)
01214     return;
01215 
01216   // Walk backwards from the last instruction in the bundle to the first.
01217   // Once we set a kill flag on an instruction, we bail out, as otherwise we
01218   // might set it on too many operands.  We will clear as many flags as we
01219   // can though.
01220   MachineBasicBlock::instr_iterator Begin = MI->getIterator();
01221   MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
01222   while (Begin != End) {
01223     for (MachineOperand &MO : (--End)->operands()) {
01224       if (!MO.isReg() || MO.isDef() || Reg != MO.getReg())
01225         continue;
01226 
01227       // DEBUG_VALUE nodes do not contribute to code generation and should
01228       // always be ignored.  Failure to do so may result in trying to modify
01229       // KILL flags on DEBUG_VALUE nodes, which is distressing.
01230       if (MO.isDebug())
01231         continue;
01232 
01233       // If the register has the internal flag then it could be killing an
01234       // internal def of the register.  In this case, just skip.  We only want
01235       // to toggle the flag on operands visible outside the bundle.
01236       if (MO.isInternalRead())
01237         continue;
01238 
01239       if (MO.isKill() == NewKillState)
01240         continue;
01241       MO.setIsKill(NewKillState);
01242       if (NewKillState)
01243         return;
01244     }
01245   }
01246 }
01247 
01248 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
01249   // Setting kill flag...
01250   if (!MO.isKill()) {
01251     MO.setIsKill(true);
01252     toggleBundleKillFlag(MI, MO.getReg(), true);
01253     return false;
01254   }
01255 
01256   // If MO itself is live, clear the kill flag...
01257   if (LiveRegs.test(MO.getReg())) {
01258     MO.setIsKill(false);
01259     toggleBundleKillFlag(MI, MO.getReg(), false);
01260     return false;
01261   }
01262 
01263   // If any subreg of MO is live, then create an imp-def for that
01264   // subreg and keep MO marked as killed.
01265   MO.setIsKill(false);
01266   toggleBundleKillFlag(MI, MO.getReg(), false);
01267   bool AllDead = true;
01268   const unsigned SuperReg = MO.getReg();
01269   MachineInstrBuilder MIB(MF, MI);
01270   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
01271     if (LiveRegs.test(*SubRegs)) {
01272       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
01273       AllDead = false;
01274     }
01275   }
01276 
01277   if(AllDead) {
01278     MO.setIsKill(true);
01279     toggleBundleKillFlag(MI, MO.getReg(), true);
01280   }
01281   return false;
01282 }
01283 
01284 // FIXME: Reuse the LivePhysRegs utility for this.
01285 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
01286   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
01287 
01288   LiveRegs.resize(TRI->getNumRegs());
01289   BitVector killedRegs(TRI->getNumRegs());
01290 
01291   startBlockForKills(MBB);
01292 
01293   // Examine block from end to start...
01294   unsigned Count = MBB->size();
01295   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
01296        I != E; --Count) {
01297     MachineInstr *MI = --I;
01298     if (MI->isDebugValue())
01299       continue;
01300 
01301     // Update liveness.  Registers that are defed but not used in this
01302     // instruction are now dead. Mark register and all subregs as they
01303     // are completely defined.
01304     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01305       MachineOperand &MO = MI->getOperand(i);
01306       if (MO.isRegMask())
01307         LiveRegs.clearBitsNotInMask(MO.getRegMask());
01308       if (!MO.isReg()) continue;
01309       unsigned Reg = MO.getReg();
01310       if (Reg == 0) continue;
01311       if (!MO.isDef()) continue;
01312       // Ignore two-addr defs.
01313       if (MI->isRegTiedToUseOperand(i)) continue;
01314 
01315       // Repeat for reg and all subregs.
01316       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01317            SubRegs.isValid(); ++SubRegs)
01318         LiveRegs.reset(*SubRegs);
01319     }
01320 
01321     // Examine all used registers and set/clear kill flag. When a
01322     // register is used multiple times we only set the kill flag on
01323     // the first use. Don't set kill flags on undef operands.
01324     killedRegs.reset();
01325     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01326       MachineOperand &MO = MI->getOperand(i);
01327       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01328       unsigned Reg = MO.getReg();
01329       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01330 
01331       bool kill = false;
01332       if (!killedRegs.test(Reg)) {
01333         kill = true;
01334         // A register is not killed if any subregs are live...
01335         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
01336           if (LiveRegs.test(*SubRegs)) {
01337             kill = false;
01338             break;
01339           }
01340         }
01341 
01342         // If subreg is not live, then register is killed if it became
01343         // live in this instruction
01344         if (kill)
01345           kill = !LiveRegs.test(Reg);
01346       }
01347 
01348       if (MO.isKill() != kill) {
01349         DEBUG(dbgs() << "Fixing " << MO << " in ");
01350         // Warning: toggleKillFlag may invalidate MO.
01351         toggleKillFlag(MI, MO);
01352         DEBUG(MI->dump());
01353         DEBUG(if (MI->getOpcode() == TargetOpcode::BUNDLE) {
01354           MachineBasicBlock::instr_iterator Begin = MI->getIterator();
01355           MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
01356           while (++Begin != End)
01357             DEBUG(Begin->dump());
01358         });
01359       }
01360 
01361       killedRegs.set(Reg);
01362     }
01363 
01364     // Mark any used register (that is not using undef) and subregs as
01365     // now live...
01366     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01367       MachineOperand &MO = MI->getOperand(i);
01368       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01369       unsigned Reg = MO.getReg();
01370       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01371 
01372       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01373            SubRegs.isValid(); ++SubRegs)
01374         LiveRegs.set(*SubRegs);
01375     }
01376   }
01377 }
01378 
01379 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
01380 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01381   SU->getInstr()->dump();
01382 #endif
01383 }
01384 
01385 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
01386   std::string s;
01387   raw_string_ostream oss(s);
01388   if (SU == &EntrySU)
01389     oss << "<entry>";
01390   else if (SU == &ExitSU)
01391     oss << "<exit>";
01392   else
01393     SU->getInstr()->print(oss, /*SkipOpers=*/true);
01394   return oss.str();
01395 }
01396 
01397 /// Return the basic block label. It is not necessarilly unique because a block
01398 /// contains multiple scheduling regions. But it is fine for visualization.
01399 std::string ScheduleDAGInstrs::getDAGName() const {
01400   return "dag." + BB->getFullName();
01401 }
01402 
01403 //===----------------------------------------------------------------------===//
01404 // SchedDFSResult Implementation
01405 //===----------------------------------------------------------------------===//
01406 
01407 namespace llvm {
01408 /// \brief Internal state used to compute SchedDFSResult.
01409 class SchedDFSImpl {
01410   SchedDFSResult &R;
01411 
01412   /// Join DAG nodes into equivalence classes by their subtree.
01413   IntEqClasses SubtreeClasses;
01414   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
01415   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
01416 
01417   struct RootData {
01418     unsigned NodeID;
01419     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
01420     unsigned SubInstrCount; // Instr count in this tree only, not children.
01421 
01422     RootData(unsigned id): NodeID(id),
01423                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
01424                            SubInstrCount(0) {}
01425 
01426     unsigned getSparseSetIndex() const { return NodeID; }
01427   };
01428 
01429   SparseSet<RootData> RootSet;
01430 
01431 public:
01432   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
01433     RootSet.setUniverse(R.DFSNodeData.size());
01434   }
01435 
01436   /// Return true if this node been visited by the DFS traversal.
01437   ///
01438   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
01439   /// ID. Later, SubtreeID is updated but remains valid.
01440   bool isVisited(const SUnit *SU) const {
01441     return R.DFSNodeData[SU->NodeNum].SubtreeID
01442       != SchedDFSResult::InvalidSubtreeID;
01443   }
01444 
01445   /// Initialize this node's instruction count. We don't need to flag the node
01446   /// visited until visitPostorder because the DAG cannot have cycles.
01447   void visitPreorder(const SUnit *SU) {
01448     R.DFSNodeData[SU->NodeNum].InstrCount =
01449       SU->getInstr()->isTransient() ? 0 : 1;
01450   }
01451 
01452   /// Called once for each node after all predecessors are visited. Revisit this
01453   /// node's predecessors and potentially join them now that we know the ILP of
01454   /// the other predecessors.
01455   void visitPostorderNode(const SUnit *SU) {
01456     // Mark this node as the root of a subtree. It may be joined with its
01457     // successors later.
01458     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
01459     RootData RData(SU->NodeNum);
01460     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
01461 
01462     // If any predecessors are still in their own subtree, they either cannot be
01463     // joined or are large enough to remain separate. If this parent node's
01464     // total instruction count is not greater than a child subtree by at least
01465     // the subtree limit, then try to join it now since splitting subtrees is
01466     // only useful if multiple high-pressure paths are possible.
01467     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
01468     for (SUnit::const_pred_iterator
01469            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
01470       if (PI->getKind() != SDep::Data)
01471         continue;
01472       unsigned PredNum = PI->getSUnit()->NodeNum;
01473       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
01474         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
01475 
01476       // Either link or merge the TreeData entry from the child to the parent.
01477       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
01478         // If the predecessor's parent is invalid, this is a tree edge and the
01479         // current node is the parent.
01480         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
01481           RootSet[PredNum].ParentNodeID = SU->NodeNum;
01482       }
01483       else if (RootSet.count(PredNum)) {
01484         // The predecessor is not a root, but is still in the root set. This
01485         // must be the new parent that it was just joined to. Note that
01486         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
01487         // set to the original parent.
01488         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
01489         RootSet.erase(PredNum);
01490       }
01491     }
01492     RootSet[SU->NodeNum] = RData;
01493   }
01494 
01495   /// Called once for each tree edge after calling visitPostOrderNode on the
01496   /// predecessor. Increment the parent node's instruction count and
01497   /// preemptively join this subtree to its parent's if it is small enough.
01498   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
01499     R.DFSNodeData[Succ->NodeNum].InstrCount
01500       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
01501     joinPredSubtree(PredDep, Succ);
01502   }
01503 
01504   /// Add a connection for cross edges.
01505   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
01506     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
01507   }
01508 
01509   /// Set each node's subtree ID to the representative ID and record connections
01510   /// between trees.
01511   void finalize() {
01512     SubtreeClasses.compress();
01513     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
01514     assert(SubtreeClasses.getNumClasses() == RootSet.size()
01515            && "number of roots should match trees");
01516     for (SparseSet<RootData>::const_iterator
01517            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
01518       unsigned TreeID = SubtreeClasses[RI->NodeID];
01519       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
01520         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
01521       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
01522       // Note that SubInstrCount may be greater than InstrCount if we joined
01523       // subtrees across a cross edge. InstrCount will be attributed to the
01524       // original parent, while SubInstrCount will be attributed to the joined
01525       // parent.
01526     }
01527     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
01528     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
01529     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
01530     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
01531       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
01532       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
01533             << R.DFSNodeData[Idx].SubtreeID << '\n');
01534     }
01535     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
01536            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
01537          I != E; ++I) {
01538       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
01539       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
01540       if (PredTree == SuccTree)
01541         continue;
01542       unsigned Depth = I->first->getDepth();
01543       addConnection(PredTree, SuccTree, Depth);
01544       addConnection(SuccTree, PredTree, Depth);
01545     }
01546   }
01547 
01548 protected:
01549   /// Join the predecessor subtree with the successor that is its DFS
01550   /// parent. Apply some heuristics before joining.
01551   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
01552                        bool CheckLimit = true) {
01553     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
01554 
01555     // Check if the predecessor is already joined.
01556     const SUnit *PredSU = PredDep.getSUnit();
01557     unsigned PredNum = PredSU->NodeNum;
01558     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
01559       return false;
01560 
01561     // Four is the magic number of successors before a node is considered a
01562     // pinch point.
01563     unsigned NumDataSucs = 0;
01564     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
01565            SE = PredSU->Succs.end(); SI != SE; ++SI) {
01566       if (SI->getKind() == SDep::Data) {
01567         if (++NumDataSucs >= 4)
01568           return false;
01569       }
01570     }
01571     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
01572       return false;
01573     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
01574     SubtreeClasses.join(Succ->NodeNum, PredNum);
01575     return true;
01576   }
01577 
01578   /// Called by finalize() to record a connection between trees.
01579   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
01580     if (!Depth)
01581       return;
01582 
01583     do {
01584       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
01585         R.SubtreeConnections[FromTree];
01586       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
01587              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
01588         if (I->TreeID == ToTree) {
01589           I->Level = std::max(I->Level, Depth);
01590           return;
01591         }
01592       }
01593       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
01594       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
01595     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
01596   }
01597 };
01598 } // namespace llvm
01599 
01600 namespace {
01601 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
01602 class SchedDAGReverseDFS {
01603   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
01604 public:
01605   bool isComplete() const { return DFSStack.empty(); }
01606 
01607   void follow(const SUnit *SU) {
01608     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
01609   }
01610   void advance() { ++DFSStack.back().second; }
01611 
01612   const SDep *backtrack() {
01613     DFSStack.pop_back();
01614     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
01615   }
01616 
01617   const SUnit *getCurr() const { return DFSStack.back().first; }
01618 
01619   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
01620 
01621   SUnit::const_pred_iterator getPredEnd() const {
01622     return getCurr()->Preds.end();
01623   }
01624 };
01625 } // anonymous
01626 
01627 static bool hasDataSucc(const SUnit *SU) {
01628   for (SUnit::const_succ_iterator
01629          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
01630     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
01631       return true;
01632   }
01633   return false;
01634 }
01635 
01636 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
01637 /// search from this root.
01638 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
01639   if (!IsBottomUp)
01640     llvm_unreachable("Top-down ILP metric is unimplemnted");
01641 
01642   SchedDFSImpl Impl(*this);
01643   for (ArrayRef<SUnit>::const_iterator
01644          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
01645     const SUnit *SU = &*SI;
01646     if (Impl.isVisited(SU) || hasDataSucc(SU))
01647       continue;
01648 
01649     SchedDAGReverseDFS DFS;
01650     Impl.visitPreorder(SU);
01651     DFS.follow(SU);
01652     for (;;) {
01653       // Traverse the leftmost path as far as possible.
01654       while (DFS.getPred() != DFS.getPredEnd()) {
01655         const SDep &PredDep = *DFS.getPred();
01656         DFS.advance();
01657         // Ignore non-data edges.
01658         if (PredDep.getKind() != SDep::Data
01659             || PredDep.getSUnit()->isBoundaryNode()) {
01660           continue;
01661         }
01662         // An already visited edge is a cross edge, assuming an acyclic DAG.
01663         if (Impl.isVisited(PredDep.getSUnit())) {
01664           Impl.visitCrossEdge(PredDep, DFS.getCurr());
01665           continue;
01666         }
01667         Impl.visitPreorder(PredDep.getSUnit());
01668         DFS.follow(PredDep.getSUnit());
01669       }
01670       // Visit the top of the stack in postorder and backtrack.
01671       const SUnit *Child = DFS.getCurr();
01672       const SDep *PredDep = DFS.backtrack();
01673       Impl.visitPostorderNode(Child);
01674       if (PredDep)
01675         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
01676       if (DFS.isComplete())
01677         break;
01678     }
01679   }
01680   Impl.finalize();
01681 }
01682 
01683 /// The root of the given SubtreeID was just scheduled. For all subtrees
01684 /// connected to this tree, record the depth of the connection so that the
01685 /// nearest connected subtrees can be prioritized.
01686 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
01687   for (SmallVectorImpl<Connection>::const_iterator
01688          I = SubtreeConnections[SubtreeID].begin(),
01689          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
01690     SubtreeConnectLevels[I->TreeID] =
01691       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
01692     DEBUG(dbgs() << "  Tree: " << I->TreeID
01693           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
01694   }
01695 }
01696 
01697 LLVM_DUMP_METHOD
01698 void ILPValue::print(raw_ostream &OS) const {
01699   OS << InstrCount << " / " << Length << " = ";
01700   if (!Length)
01701     OS << "BADILP";
01702   else
01703     OS << format("%g", ((double)InstrCount / Length));
01704 }
01705 
01706 LLVM_DUMP_METHOD
01707 void ILPValue::dump() const {
01708   dbgs() << *this << '\n';
01709 }
01710 
01711 namespace llvm {
01712 
01713 LLVM_DUMP_METHOD
01714 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
01715   Val.print(OS);
01716   return OS;
01717 }
01718 
01719 } // namespace llvm