132a40564SEugene Zelenko //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===// 2254f889dSBrendon Cahoon // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6254f889dSBrendon Cahoon // 7254f889dSBrendon Cahoon //===----------------------------------------------------------------------===// 8254f889dSBrendon Cahoon // 9254f889dSBrendon Cahoon // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner. 10254f889dSBrendon Cahoon // 11254f889dSBrendon Cahoon // This SMS implementation is a target-independent back-end pass. When enabled, 12254f889dSBrendon Cahoon // the pass runs just prior to the register allocation pass, while the machine 13254f889dSBrendon Cahoon // IR is in SSA form. If software pipelining is successful, then the original 14254f889dSBrendon Cahoon // loop is replaced by the optimized loop. The optimized loop contains one or 15254f889dSBrendon Cahoon // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If 16254f889dSBrendon Cahoon // the instructions cannot be scheduled in a given MII, we increase the MII by 17254f889dSBrendon Cahoon // one and try again. 18254f889dSBrendon Cahoon // 19254f889dSBrendon Cahoon // The SMS implementation is an extension of the ScheduleDAGInstrs class. We 20254f889dSBrendon Cahoon // represent loop carried dependences in the DAG as order edges to the Phi 21254f889dSBrendon Cahoon // nodes. We also perform several passes over the DAG to eliminate unnecessary 22254f889dSBrendon Cahoon // edges that inhibit the ability to pipeline. The implementation uses the 23254f889dSBrendon Cahoon // DFAPacketizer class to compute the minimum initiation interval and the check 24254f889dSBrendon Cahoon // where an instruction may be inserted in the pipelined schedule. 25254f889dSBrendon Cahoon // 26254f889dSBrendon Cahoon // In order for the SMS pass to work, several target specific hooks need to be 27254f889dSBrendon Cahoon // implemented to get information about the loop structure and to rewrite 28254f889dSBrendon Cahoon // instructions. 29254f889dSBrendon Cahoon // 30254f889dSBrendon Cahoon //===----------------------------------------------------------------------===// 31254f889dSBrendon Cahoon 32cdc71612SEugene Zelenko #include "llvm/ADT/ArrayRef.h" 33cdc71612SEugene Zelenko #include "llvm/ADT/BitVector.h" 34254f889dSBrendon Cahoon #include "llvm/ADT/DenseMap.h" 35254f889dSBrendon Cahoon #include "llvm/ADT/MapVector.h" 36254f889dSBrendon Cahoon #include "llvm/ADT/PriorityQueue.h" 37254f889dSBrendon Cahoon #include "llvm/ADT/SetVector.h" 38254f889dSBrendon Cahoon #include "llvm/ADT/SmallPtrSet.h" 39254f889dSBrendon Cahoon #include "llvm/ADT/SmallSet.h" 40cdc71612SEugene Zelenko #include "llvm/ADT/SmallVector.h" 41254f889dSBrendon Cahoon #include "llvm/ADT/Statistic.h" 426bda14b3SChandler Carruth #include "llvm/ADT/iterator_range.h" 43254f889dSBrendon Cahoon #include "llvm/Analysis/AliasAnalysis.h" 44cdc71612SEugene Zelenko #include "llvm/Analysis/MemoryLocation.h" 45254f889dSBrendon Cahoon #include "llvm/Analysis/ValueTracking.h" 46254f889dSBrendon Cahoon #include "llvm/CodeGen/DFAPacketizer.h" 47f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h" 48254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineBasicBlock.h" 49254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineDominators.h" 50cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h" 51cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunctionPass.h" 52cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineInstr.h" 53254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineInstrBuilder.h" 54254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineLoopInfo.h" 55cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineMemOperand.h" 56cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineOperand.h" 57fa2e3583SAdrian Prantl #include "llvm/CodeGen/MachinePipeliner.h" 58254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineRegisterInfo.h" 59790a779fSJames Molloy #include "llvm/CodeGen/ModuloSchedule.h" 60254f889dSBrendon Cahoon #include "llvm/CodeGen/RegisterPressure.h" 61cdc71612SEugene Zelenko #include "llvm/CodeGen/ScheduleDAG.h" 6288391248SKrzysztof Parzyszek #include "llvm/CodeGen/ScheduleDAGMutation.h" 63b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetOpcodes.h" 64b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h" 65b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h" 66432a3883SNico Weber #include "llvm/Config/llvm-config.h" 67cdc71612SEugene Zelenko #include "llvm/IR/Attributes.h" 68cdc71612SEugene Zelenko #include "llvm/IR/DebugLoc.h" 6932a40564SEugene Zelenko #include "llvm/IR/Function.h" 7032a40564SEugene Zelenko #include "llvm/MC/LaneBitmask.h" 7132a40564SEugene Zelenko #include "llvm/MC/MCInstrDesc.h" 72254f889dSBrendon Cahoon #include "llvm/MC/MCInstrItineraries.h" 7332a40564SEugene Zelenko #include "llvm/MC/MCRegisterInfo.h" 7432a40564SEugene Zelenko #include "llvm/Pass.h" 75254f889dSBrendon Cahoon #include "llvm/Support/CommandLine.h" 7632a40564SEugene Zelenko #include "llvm/Support/Compiler.h" 77254f889dSBrendon Cahoon #include "llvm/Support/Debug.h" 78cdc71612SEugene Zelenko #include "llvm/Support/MathExtras.h" 79254f889dSBrendon Cahoon #include "llvm/Support/raw_ostream.h" 80cdc71612SEugene Zelenko #include <algorithm> 81cdc71612SEugene Zelenko #include <cassert> 82254f889dSBrendon Cahoon #include <climits> 83cdc71612SEugene Zelenko #include <cstdint> 84254f889dSBrendon Cahoon #include <deque> 85cdc71612SEugene Zelenko #include <functional> 86cdc71612SEugene Zelenko #include <iterator> 87254f889dSBrendon Cahoon #include <map> 8832a40564SEugene Zelenko #include <memory> 89cdc71612SEugene Zelenko #include <tuple> 90cdc71612SEugene Zelenko #include <utility> 91cdc71612SEugene Zelenko #include <vector> 92254f889dSBrendon Cahoon 93254f889dSBrendon Cahoon using namespace llvm; 94254f889dSBrendon Cahoon 95254f889dSBrendon Cahoon #define DEBUG_TYPE "pipeliner" 96254f889dSBrendon Cahoon 97254f889dSBrendon Cahoon STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline"); 98254f889dSBrendon Cahoon STATISTIC(NumPipelined, "Number of loops software pipelined"); 994b8bcf00SRoorda, Jan-Willem STATISTIC(NumNodeOrderIssues, "Number of node order issues found"); 10018e7bf5cSJinsong Ji STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch"); 10118e7bf5cSJinsong Ji STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop"); 10218e7bf5cSJinsong Ji STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader"); 10318e7bf5cSJinsong Ji STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large"); 10418e7bf5cSJinsong Ji STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII"); 10518e7bf5cSJinsong Ji STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found"); 10618e7bf5cSJinsong Ji STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage"); 10718e7bf5cSJinsong Ji STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages"); 108254f889dSBrendon Cahoon 109254f889dSBrendon Cahoon /// A command line option to turn software pipelining on or off. 110b7d3311cSBenjamin Kramer static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true), 111b7d3311cSBenjamin Kramer cl::ZeroOrMore, 112b7d3311cSBenjamin Kramer cl::desc("Enable Software Pipelining")); 113254f889dSBrendon Cahoon 114254f889dSBrendon Cahoon /// A command line option to enable SWP at -Os. 115254f889dSBrendon Cahoon static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size", 116254f889dSBrendon Cahoon cl::desc("Enable SWP at Os."), cl::Hidden, 117254f889dSBrendon Cahoon cl::init(false)); 118254f889dSBrendon Cahoon 119254f889dSBrendon Cahoon /// A command line argument to limit minimum initial interval for pipelining. 120254f889dSBrendon Cahoon static cl::opt<int> SwpMaxMii("pipeliner-max-mii", 1218f976ba0SHiroshi Inoue cl::desc("Size limit for the MII."), 122254f889dSBrendon Cahoon cl::Hidden, cl::init(27)); 123254f889dSBrendon Cahoon 124254f889dSBrendon Cahoon /// A command line argument to limit the number of stages in the pipeline. 125254f889dSBrendon Cahoon static cl::opt<int> 126254f889dSBrendon Cahoon SwpMaxStages("pipeliner-max-stages", 127254f889dSBrendon Cahoon cl::desc("Maximum stages allowed in the generated scheduled."), 128254f889dSBrendon Cahoon cl::Hidden, cl::init(3)); 129254f889dSBrendon Cahoon 130254f889dSBrendon Cahoon /// A command line option to disable the pruning of chain dependences due to 131254f889dSBrendon Cahoon /// an unrelated Phi. 132254f889dSBrendon Cahoon static cl::opt<bool> 133254f889dSBrendon Cahoon SwpPruneDeps("pipeliner-prune-deps", 134254f889dSBrendon Cahoon cl::desc("Prune dependences between unrelated Phi nodes."), 135254f889dSBrendon Cahoon cl::Hidden, cl::init(true)); 136254f889dSBrendon Cahoon 137254f889dSBrendon Cahoon /// A command line option to disable the pruning of loop carried order 138254f889dSBrendon Cahoon /// dependences. 139254f889dSBrendon Cahoon static cl::opt<bool> 140254f889dSBrendon Cahoon SwpPruneLoopCarried("pipeliner-prune-loop-carried", 141254f889dSBrendon Cahoon cl::desc("Prune loop carried order dependences."), 142254f889dSBrendon Cahoon cl::Hidden, cl::init(true)); 143254f889dSBrendon Cahoon 144254f889dSBrendon Cahoon #ifndef NDEBUG 145254f889dSBrendon Cahoon static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1)); 146254f889dSBrendon Cahoon #endif 147254f889dSBrendon Cahoon 148254f889dSBrendon Cahoon static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii", 149254f889dSBrendon Cahoon cl::ReallyHidden, cl::init(false), 150254f889dSBrendon Cahoon cl::ZeroOrMore, cl::desc("Ignore RecMII")); 151254f889dSBrendon Cahoon 152ba43840bSJinsong Ji static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden, 153ba43840bSJinsong Ji cl::init(false)); 154ba43840bSJinsong Ji static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden, 155ba43840bSJinsong Ji cl::init(false)); 156ba43840bSJinsong Ji 15793549957SJames Molloy static cl::opt<bool> EmitTestAnnotations( 15893549957SJames Molloy "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false), 15993549957SJames Molloy cl::desc("Instead of emitting the pipelined code, annotate instructions " 16093549957SJames Molloy "with the generated schedule for feeding into the " 16193549957SJames Molloy "-modulo-schedule-test pass")); 16293549957SJames Molloy 163fef9f590SJames Molloy static cl::opt<bool> ExperimentalCodeGen( 164fef9f590SJames Molloy "pipeliner-experimental-cg", cl::Hidden, cl::init(false), 165fef9f590SJames Molloy cl::desc( 166fef9f590SJames Molloy "Use the experimental peeling code generator for software pipelining")); 167fef9f590SJames Molloy 168fa2e3583SAdrian Prantl namespace llvm { 169fa2e3583SAdrian Prantl 17062ac69d4SSumanth Gundapaneni // A command line option to enable the CopyToPhi DAG mutation. 171fa2e3583SAdrian Prantl cl::opt<bool> 17200d4c386SAleksandr Urakov SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden, 17362ac69d4SSumanth Gundapaneni cl::init(true), cl::ZeroOrMore, 17462ac69d4SSumanth Gundapaneni cl::desc("Enable CopyToPhi DAG Mutation")); 17562ac69d4SSumanth Gundapaneni 176fa2e3583SAdrian Prantl } // end namespace llvm 177254f889dSBrendon Cahoon 178254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5; 179254f889dSBrendon Cahoon char MachinePipeliner::ID = 0; 180254f889dSBrendon Cahoon #ifndef NDEBUG 181254f889dSBrendon Cahoon int MachinePipeliner::NumTries = 0; 182254f889dSBrendon Cahoon #endif 183254f889dSBrendon Cahoon char &llvm::MachinePipelinerID = MachinePipeliner::ID; 18432a40564SEugene Zelenko 1851527baabSMatthias Braun INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE, 186254f889dSBrendon Cahoon "Modulo Software Pipelining", false, false) 187254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 188254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 189254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 190254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 1911527baabSMatthias Braun INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE, 192254f889dSBrendon Cahoon "Modulo Software Pipelining", false, false) 193254f889dSBrendon Cahoon 194254f889dSBrendon Cahoon /// The "main" function for implementing Swing Modulo Scheduling. 195254f889dSBrendon Cahoon bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) { 196f1caa283SMatthias Braun if (skipFunction(mf.getFunction())) 197254f889dSBrendon Cahoon return false; 198254f889dSBrendon Cahoon 199254f889dSBrendon Cahoon if (!EnableSWP) 200254f889dSBrendon Cahoon return false; 201254f889dSBrendon Cahoon 202f1caa283SMatthias Braun if (mf.getFunction().getAttributes().hasAttribute( 203b518054bSReid Kleckner AttributeList::FunctionIndex, Attribute::OptimizeForSize) && 204254f889dSBrendon Cahoon !EnableSWPOptSize.getPosition()) 205254f889dSBrendon Cahoon return false; 206254f889dSBrendon Cahoon 207ef2d6d99SJinsong Ji if (!mf.getSubtarget().enableMachinePipeliner()) 208ef2d6d99SJinsong Ji return false; 209ef2d6d99SJinsong Ji 210f6cb3bcbSJinsong Ji // Cannot pipeline loops without instruction itineraries if we are using 211f6cb3bcbSJinsong Ji // DFA for the pipeliner. 212f6cb3bcbSJinsong Ji if (mf.getSubtarget().useDFAforSMS() && 213f6cb3bcbSJinsong Ji (!mf.getSubtarget().getInstrItineraryData() || 214f6cb3bcbSJinsong Ji mf.getSubtarget().getInstrItineraryData()->isEmpty())) 215f6cb3bcbSJinsong Ji return false; 216f6cb3bcbSJinsong Ji 217254f889dSBrendon Cahoon MF = &mf; 218254f889dSBrendon Cahoon MLI = &getAnalysis<MachineLoopInfo>(); 219254f889dSBrendon Cahoon MDT = &getAnalysis<MachineDominatorTree>(); 220254f889dSBrendon Cahoon TII = MF->getSubtarget().getInstrInfo(); 221254f889dSBrendon Cahoon RegClassInfo.runOnMachineFunction(*MF); 222254f889dSBrendon Cahoon 223254f889dSBrendon Cahoon for (auto &L : *MLI) 224254f889dSBrendon Cahoon scheduleLoop(*L); 225254f889dSBrendon Cahoon 226254f889dSBrendon Cahoon return false; 227254f889dSBrendon Cahoon } 228254f889dSBrendon Cahoon 229254f889dSBrendon Cahoon /// Attempt to perform the SMS algorithm on the specified loop. This function is 230254f889dSBrendon Cahoon /// the main entry point for the algorithm. The function identifies candidate 231254f889dSBrendon Cahoon /// loops, calculates the minimum initiation interval, and attempts to schedule 232254f889dSBrendon Cahoon /// the loop. 233254f889dSBrendon Cahoon bool MachinePipeliner::scheduleLoop(MachineLoop &L) { 234254f889dSBrendon Cahoon bool Changed = false; 235254f889dSBrendon Cahoon for (auto &InnerLoop : L) 236254f889dSBrendon Cahoon Changed |= scheduleLoop(*InnerLoop); 237254f889dSBrendon Cahoon 238254f889dSBrendon Cahoon #ifndef NDEBUG 239254f889dSBrendon Cahoon // Stop trying after reaching the limit (if any). 240254f889dSBrendon Cahoon int Limit = SwpLoopLimit; 241254f889dSBrendon Cahoon if (Limit >= 0) { 242254f889dSBrendon Cahoon if (NumTries >= SwpLoopLimit) 243254f889dSBrendon Cahoon return Changed; 244254f889dSBrendon Cahoon NumTries++; 245254f889dSBrendon Cahoon } 246254f889dSBrendon Cahoon #endif 247254f889dSBrendon Cahoon 24859d99731SBrendon Cahoon setPragmaPipelineOptions(L); 24959d99731SBrendon Cahoon if (!canPipelineLoop(L)) { 25059d99731SBrendon Cahoon LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n"); 251254f889dSBrendon Cahoon return Changed; 25259d99731SBrendon Cahoon } 253254f889dSBrendon Cahoon 254254f889dSBrendon Cahoon ++NumTrytoPipeline; 255254f889dSBrendon Cahoon 256254f889dSBrendon Cahoon Changed = swingModuloScheduler(L); 257254f889dSBrendon Cahoon 258254f889dSBrendon Cahoon return Changed; 259254f889dSBrendon Cahoon } 260254f889dSBrendon Cahoon 26159d99731SBrendon Cahoon void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) { 262a04ab2ecSSumanth Gundapaneni // Reset the pragma for the next loop in iteration. 263a04ab2ecSSumanth Gundapaneni disabledByPragma = false; 264a04ab2ecSSumanth Gundapaneni 26559d99731SBrendon Cahoon MachineBasicBlock *LBLK = L.getTopBlock(); 26659d99731SBrendon Cahoon 26759d99731SBrendon Cahoon if (LBLK == nullptr) 26859d99731SBrendon Cahoon return; 26959d99731SBrendon Cahoon 27059d99731SBrendon Cahoon const BasicBlock *BBLK = LBLK->getBasicBlock(); 27159d99731SBrendon Cahoon if (BBLK == nullptr) 27259d99731SBrendon Cahoon return; 27359d99731SBrendon Cahoon 27459d99731SBrendon Cahoon const Instruction *TI = BBLK->getTerminator(); 27559d99731SBrendon Cahoon if (TI == nullptr) 27659d99731SBrendon Cahoon return; 27759d99731SBrendon Cahoon 27859d99731SBrendon Cahoon MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop); 27959d99731SBrendon Cahoon if (LoopID == nullptr) 28059d99731SBrendon Cahoon return; 28159d99731SBrendon Cahoon 28259d99731SBrendon Cahoon assert(LoopID->getNumOperands() > 0 && "requires atleast one operand"); 28359d99731SBrendon Cahoon assert(LoopID->getOperand(0) == LoopID && "invalid loop"); 28459d99731SBrendon Cahoon 28559d99731SBrendon Cahoon for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 28659d99731SBrendon Cahoon MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 28759d99731SBrendon Cahoon 28859d99731SBrendon Cahoon if (MD == nullptr) 28959d99731SBrendon Cahoon continue; 29059d99731SBrendon Cahoon 29159d99731SBrendon Cahoon MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 29259d99731SBrendon Cahoon 29359d99731SBrendon Cahoon if (S == nullptr) 29459d99731SBrendon Cahoon continue; 29559d99731SBrendon Cahoon 29659d99731SBrendon Cahoon if (S->getString() == "llvm.loop.pipeline.initiationinterval") { 29759d99731SBrendon Cahoon assert(MD->getNumOperands() == 2 && 29859d99731SBrendon Cahoon "Pipeline initiation interval hint metadata should have two operands."); 29959d99731SBrendon Cahoon II_setByPragma = 30059d99731SBrendon Cahoon mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 30159d99731SBrendon Cahoon assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive."); 30259d99731SBrendon Cahoon } else if (S->getString() == "llvm.loop.pipeline.disable") { 30359d99731SBrendon Cahoon disabledByPragma = true; 30459d99731SBrendon Cahoon } 30559d99731SBrendon Cahoon } 30659d99731SBrendon Cahoon } 30759d99731SBrendon Cahoon 308254f889dSBrendon Cahoon /// Return true if the loop can be software pipelined. The algorithm is 309254f889dSBrendon Cahoon /// restricted to loops with a single basic block. Make sure that the 310254f889dSBrendon Cahoon /// branch in the loop can be analyzed. 311254f889dSBrendon Cahoon bool MachinePipeliner::canPipelineLoop(MachineLoop &L) { 312254f889dSBrendon Cahoon if (L.getNumBlocks() != 1) 313254f889dSBrendon Cahoon return false; 314254f889dSBrendon Cahoon 31559d99731SBrendon Cahoon if (disabledByPragma) 31659d99731SBrendon Cahoon return false; 31759d99731SBrendon Cahoon 318254f889dSBrendon Cahoon // Check if the branch can't be understood because we can't do pipelining 319254f889dSBrendon Cahoon // if that's the case. 320254f889dSBrendon Cahoon LI.TBB = nullptr; 321254f889dSBrendon Cahoon LI.FBB = nullptr; 322254f889dSBrendon Cahoon LI.BrCond.clear(); 32318e7bf5cSJinsong Ji if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) { 32418e7bf5cSJinsong Ji LLVM_DEBUG( 32518e7bf5cSJinsong Ji dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n"); 32618e7bf5cSJinsong Ji NumFailBranch++; 327254f889dSBrendon Cahoon return false; 32818e7bf5cSJinsong Ji } 329254f889dSBrendon Cahoon 330254f889dSBrendon Cahoon LI.LoopInductionVar = nullptr; 331254f889dSBrendon Cahoon LI.LoopCompare = nullptr; 3328a74eca3SJames Molloy if (!TII->analyzeLoopForPipelining(L.getTopBlock())) { 33318e7bf5cSJinsong Ji LLVM_DEBUG( 33418e7bf5cSJinsong Ji dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n"); 33518e7bf5cSJinsong Ji NumFailLoop++; 336254f889dSBrendon Cahoon return false; 33718e7bf5cSJinsong Ji } 338254f889dSBrendon Cahoon 33918e7bf5cSJinsong Ji if (!L.getLoopPreheader()) { 34018e7bf5cSJinsong Ji LLVM_DEBUG( 34118e7bf5cSJinsong Ji dbgs() << "Preheader not found, can NOT pipeline current Loop\n"); 34218e7bf5cSJinsong Ji NumFailPreheader++; 343254f889dSBrendon Cahoon return false; 34418e7bf5cSJinsong Ji } 345254f889dSBrendon Cahoon 346c715a5d2SKrzysztof Parzyszek // Remove any subregisters from inputs to phi nodes. 347c715a5d2SKrzysztof Parzyszek preprocessPhiNodes(*L.getHeader()); 348254f889dSBrendon Cahoon return true; 349254f889dSBrendon Cahoon } 350254f889dSBrendon Cahoon 351c715a5d2SKrzysztof Parzyszek void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) { 352c715a5d2SKrzysztof Parzyszek MachineRegisterInfo &MRI = MF->getRegInfo(); 353c715a5d2SKrzysztof Parzyszek SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes(); 354c715a5d2SKrzysztof Parzyszek 355c715a5d2SKrzysztof Parzyszek for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) { 356c715a5d2SKrzysztof Parzyszek MachineOperand &DefOp = PI.getOperand(0); 357c715a5d2SKrzysztof Parzyszek assert(DefOp.getSubReg() == 0); 358c715a5d2SKrzysztof Parzyszek auto *RC = MRI.getRegClass(DefOp.getReg()); 359c715a5d2SKrzysztof Parzyszek 360c715a5d2SKrzysztof Parzyszek for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) { 361c715a5d2SKrzysztof Parzyszek MachineOperand &RegOp = PI.getOperand(i); 362c715a5d2SKrzysztof Parzyszek if (RegOp.getSubReg() == 0) 363c715a5d2SKrzysztof Parzyszek continue; 364c715a5d2SKrzysztof Parzyszek 365c715a5d2SKrzysztof Parzyszek // If the operand uses a subregister, replace it with a new register 366c715a5d2SKrzysztof Parzyszek // without subregisters, and generate a copy to the new register. 3670c476111SDaniel Sanders Register NewReg = MRI.createVirtualRegister(RC); 368c715a5d2SKrzysztof Parzyszek MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB(); 369c715a5d2SKrzysztof Parzyszek MachineBasicBlock::iterator At = PredB.getFirstTerminator(); 370c715a5d2SKrzysztof Parzyszek const DebugLoc &DL = PredB.findDebugLoc(At); 371c715a5d2SKrzysztof Parzyszek auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg) 372c715a5d2SKrzysztof Parzyszek .addReg(RegOp.getReg(), getRegState(RegOp), 373c715a5d2SKrzysztof Parzyszek RegOp.getSubReg()); 374c715a5d2SKrzysztof Parzyszek Slots.insertMachineInstrInMaps(*Copy); 375c715a5d2SKrzysztof Parzyszek RegOp.setReg(NewReg); 376c715a5d2SKrzysztof Parzyszek RegOp.setSubReg(0); 377c715a5d2SKrzysztof Parzyszek } 378c715a5d2SKrzysztof Parzyszek } 379c715a5d2SKrzysztof Parzyszek } 380c715a5d2SKrzysztof Parzyszek 381254f889dSBrendon Cahoon /// The SMS algorithm consists of the following main steps: 382254f889dSBrendon Cahoon /// 1. Computation and analysis of the dependence graph. 383254f889dSBrendon Cahoon /// 2. Ordering of the nodes (instructions). 384254f889dSBrendon Cahoon /// 3. Attempt to Schedule the loop. 385254f889dSBrendon Cahoon bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) { 386254f889dSBrendon Cahoon assert(L.getBlocks().size() == 1 && "SMS works on single blocks only."); 387254f889dSBrendon Cahoon 38859d99731SBrendon Cahoon SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo, 38959d99731SBrendon Cahoon II_setByPragma); 390254f889dSBrendon Cahoon 391254f889dSBrendon Cahoon MachineBasicBlock *MBB = L.getHeader(); 392254f889dSBrendon Cahoon // The kernel should not include any terminator instructions. These 393254f889dSBrendon Cahoon // will be added back later. 394254f889dSBrendon Cahoon SMS.startBlock(MBB); 395254f889dSBrendon Cahoon 396254f889dSBrendon Cahoon // Compute the number of 'real' instructions in the basic block by 397254f889dSBrendon Cahoon // ignoring terminators. 398254f889dSBrendon Cahoon unsigned size = MBB->size(); 399254f889dSBrendon Cahoon for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(), 400254f889dSBrendon Cahoon E = MBB->instr_end(); 401254f889dSBrendon Cahoon I != E; ++I, --size) 402254f889dSBrendon Cahoon ; 403254f889dSBrendon Cahoon 404254f889dSBrendon Cahoon SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size); 405254f889dSBrendon Cahoon SMS.schedule(); 406254f889dSBrendon Cahoon SMS.exitRegion(); 407254f889dSBrendon Cahoon 408254f889dSBrendon Cahoon SMS.finishBlock(); 409254f889dSBrendon Cahoon return SMS.hasNewSchedule(); 410254f889dSBrendon Cahoon } 411254f889dSBrendon Cahoon 41259d99731SBrendon Cahoon void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) { 41359d99731SBrendon Cahoon if (II_setByPragma > 0) 41459d99731SBrendon Cahoon MII = II_setByPragma; 41559d99731SBrendon Cahoon else 41659d99731SBrendon Cahoon MII = std::max(ResMII, RecMII); 41759d99731SBrendon Cahoon } 41859d99731SBrendon Cahoon 41959d99731SBrendon Cahoon void SwingSchedulerDAG::setMAX_II() { 42059d99731SBrendon Cahoon if (II_setByPragma > 0) 42159d99731SBrendon Cahoon MAX_II = II_setByPragma; 42259d99731SBrendon Cahoon else 42359d99731SBrendon Cahoon MAX_II = MII + 10; 42459d99731SBrendon Cahoon } 42559d99731SBrendon Cahoon 426254f889dSBrendon Cahoon /// We override the schedule function in ScheduleDAGInstrs to implement the 427254f889dSBrendon Cahoon /// scheduling part of the Swing Modulo Scheduling algorithm. 428254f889dSBrendon Cahoon void SwingSchedulerDAG::schedule() { 429254f889dSBrendon Cahoon AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults(); 430254f889dSBrendon Cahoon buildSchedGraph(AA); 431254f889dSBrendon Cahoon addLoopCarriedDependences(AA); 432254f889dSBrendon Cahoon updatePhiDependences(); 433254f889dSBrendon Cahoon Topo.InitDAGTopologicalSorting(); 434254f889dSBrendon Cahoon changeDependences(); 43562ac69d4SSumanth Gundapaneni postprocessDAG(); 436726e12cfSMatthias Braun LLVM_DEBUG(dump()); 437254f889dSBrendon Cahoon 438254f889dSBrendon Cahoon NodeSetType NodeSets; 439254f889dSBrendon Cahoon findCircuits(NodeSets); 4404b8bcf00SRoorda, Jan-Willem NodeSetType Circuits = NodeSets; 441254f889dSBrendon Cahoon 442254f889dSBrendon Cahoon // Calculate the MII. 443254f889dSBrendon Cahoon unsigned ResMII = calculateResMII(); 444254f889dSBrendon Cahoon unsigned RecMII = calculateRecMII(NodeSets); 445254f889dSBrendon Cahoon 446254f889dSBrendon Cahoon fuseRecs(NodeSets); 447254f889dSBrendon Cahoon 448254f889dSBrendon Cahoon // This flag is used for testing and can cause correctness problems. 449254f889dSBrendon Cahoon if (SwpIgnoreRecMII) 450254f889dSBrendon Cahoon RecMII = 0; 451254f889dSBrendon Cahoon 45259d99731SBrendon Cahoon setMII(ResMII, RecMII); 45359d99731SBrendon Cahoon setMAX_II(); 45459d99731SBrendon Cahoon 45559d99731SBrendon Cahoon LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II 45659d99731SBrendon Cahoon << " (rec=" << RecMII << ", res=" << ResMII << ")\n"); 457254f889dSBrendon Cahoon 458254f889dSBrendon Cahoon // Can't schedule a loop without a valid MII. 45918e7bf5cSJinsong Ji if (MII == 0) { 46018e7bf5cSJinsong Ji LLVM_DEBUG( 46118e7bf5cSJinsong Ji dbgs() 46218e7bf5cSJinsong Ji << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n"); 46318e7bf5cSJinsong Ji NumFailZeroMII++; 464254f889dSBrendon Cahoon return; 46518e7bf5cSJinsong Ji } 466254f889dSBrendon Cahoon 467254f889dSBrendon Cahoon // Don't pipeline large loops. 46818e7bf5cSJinsong Ji if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) { 46918e7bf5cSJinsong Ji LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii 47018e7bf5cSJinsong Ji << ", we don't pipleline large loops\n"); 47118e7bf5cSJinsong Ji NumFailLargeMaxMII++; 472254f889dSBrendon Cahoon return; 47318e7bf5cSJinsong Ji } 474254f889dSBrendon Cahoon 475254f889dSBrendon Cahoon computeNodeFunctions(NodeSets); 476254f889dSBrendon Cahoon 477254f889dSBrendon Cahoon registerPressureFilter(NodeSets); 478254f889dSBrendon Cahoon 479254f889dSBrendon Cahoon colocateNodeSets(NodeSets); 480254f889dSBrendon Cahoon 481254f889dSBrendon Cahoon checkNodeSets(NodeSets); 482254f889dSBrendon Cahoon 483d34e60caSNicola Zaghen LLVM_DEBUG({ 484254f889dSBrendon Cahoon for (auto &I : NodeSets) { 485254f889dSBrendon Cahoon dbgs() << " Rec NodeSet "; 486254f889dSBrendon Cahoon I.dump(); 487254f889dSBrendon Cahoon } 488254f889dSBrendon Cahoon }); 489254f889dSBrendon Cahoon 490efd94c56SFangrui Song llvm::stable_sort(NodeSets, std::greater<NodeSet>()); 491254f889dSBrendon Cahoon 492254f889dSBrendon Cahoon groupRemainingNodes(NodeSets); 493254f889dSBrendon Cahoon 494254f889dSBrendon Cahoon removeDuplicateNodes(NodeSets); 495254f889dSBrendon Cahoon 496d34e60caSNicola Zaghen LLVM_DEBUG({ 497254f889dSBrendon Cahoon for (auto &I : NodeSets) { 498254f889dSBrendon Cahoon dbgs() << " NodeSet "; 499254f889dSBrendon Cahoon I.dump(); 500254f889dSBrendon Cahoon } 501254f889dSBrendon Cahoon }); 502254f889dSBrendon Cahoon 503254f889dSBrendon Cahoon computeNodeOrder(NodeSets); 504254f889dSBrendon Cahoon 5054b8bcf00SRoorda, Jan-Willem // check for node order issues 5064b8bcf00SRoorda, Jan-Willem checkValidNodeOrder(Circuits); 5074b8bcf00SRoorda, Jan-Willem 508254f889dSBrendon Cahoon SMSchedule Schedule(Pass.MF); 509254f889dSBrendon Cahoon Scheduled = schedulePipeline(Schedule); 510254f889dSBrendon Cahoon 51118e7bf5cSJinsong Ji if (!Scheduled){ 51218e7bf5cSJinsong Ji LLVM_DEBUG(dbgs() << "No schedule found, return\n"); 51318e7bf5cSJinsong Ji NumFailNoSchedule++; 514254f889dSBrendon Cahoon return; 51518e7bf5cSJinsong Ji } 516254f889dSBrendon Cahoon 517254f889dSBrendon Cahoon unsigned numStages = Schedule.getMaxStageCount(); 518254f889dSBrendon Cahoon // No need to generate pipeline if there are no overlapped iterations. 51918e7bf5cSJinsong Ji if (numStages == 0) { 52018e7bf5cSJinsong Ji LLVM_DEBUG( 52118e7bf5cSJinsong Ji dbgs() << "No overlapped iterations, no need to generate pipeline\n"); 52218e7bf5cSJinsong Ji NumFailZeroStage++; 523254f889dSBrendon Cahoon return; 52418e7bf5cSJinsong Ji } 525254f889dSBrendon Cahoon // Check that the maximum stage count is less than user-defined limit. 52618e7bf5cSJinsong Ji if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) { 52718e7bf5cSJinsong Ji LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages 52818e7bf5cSJinsong Ji << " : too many stages, abort\n"); 52918e7bf5cSJinsong Ji NumFailLargeMaxStage++; 530254f889dSBrendon Cahoon return; 53118e7bf5cSJinsong Ji } 532254f889dSBrendon Cahoon 533790a779fSJames Molloy // Generate the schedule as a ModuloSchedule. 534790a779fSJames Molloy DenseMap<MachineInstr *, int> Cycles, Stages; 535790a779fSJames Molloy std::vector<MachineInstr *> OrderedInsts; 536790a779fSJames Molloy for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle(); 537790a779fSJames Molloy ++Cycle) { 538790a779fSJames Molloy for (SUnit *SU : Schedule.getInstructions(Cycle)) { 539790a779fSJames Molloy OrderedInsts.push_back(SU->getInstr()); 540790a779fSJames Molloy Cycles[SU->getInstr()] = Cycle; 541790a779fSJames Molloy Stages[SU->getInstr()] = Schedule.stageScheduled(SU); 542790a779fSJames Molloy } 543790a779fSJames Molloy } 544790a779fSJames Molloy DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges; 545790a779fSJames Molloy for (auto &KV : NewMIs) { 546790a779fSJames Molloy Cycles[KV.first] = Cycles[KV.second]; 547790a779fSJames Molloy Stages[KV.first] = Stages[KV.second]; 548790a779fSJames Molloy NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)]; 549790a779fSJames Molloy } 550790a779fSJames Molloy 551790a779fSJames Molloy ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles), 552790a779fSJames Molloy std::move(Stages)); 55393549957SJames Molloy if (EmitTestAnnotations) { 55493549957SJames Molloy assert(NewInstrChanges.empty() && 55593549957SJames Molloy "Cannot serialize a schedule with InstrChanges!"); 55693549957SJames Molloy ModuloScheduleTestAnnotater MSTI(MF, MS); 55793549957SJames Molloy MSTI.annotate(); 55893549957SJames Molloy return; 55993549957SJames Molloy } 560fef9f590SJames Molloy // The experimental code generator can't work if there are InstChanges. 561fef9f590SJames Molloy if (ExperimentalCodeGen && NewInstrChanges.empty()) { 562fef9f590SJames Molloy PeelingModuloScheduleExpander MSE(MF, MS, &LIS); 5639026518eSJames Molloy MSE.expand(); 564fef9f590SJames Molloy } else { 565790a779fSJames Molloy ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges)); 566790a779fSJames Molloy MSE.expand(); 567fef9f590SJames Molloy MSE.cleanup(); 568fef9f590SJames Molloy } 569254f889dSBrendon Cahoon ++NumPipelined; 570254f889dSBrendon Cahoon } 571254f889dSBrendon Cahoon 572254f889dSBrendon Cahoon /// Clean up after the software pipeliner runs. 573254f889dSBrendon Cahoon void SwingSchedulerDAG::finishBlock() { 574790a779fSJames Molloy for (auto &KV : NewMIs) 575790a779fSJames Molloy MF.DeleteMachineInstr(KV.second); 576254f889dSBrendon Cahoon NewMIs.clear(); 577254f889dSBrendon Cahoon 578254f889dSBrendon Cahoon // Call the superclass. 579254f889dSBrendon Cahoon ScheduleDAGInstrs::finishBlock(); 580254f889dSBrendon Cahoon } 581254f889dSBrendon Cahoon 582254f889dSBrendon Cahoon /// Return the register values for the operands of a Phi instruction. 583254f889dSBrendon Cahoon /// This function assume the instruction is a Phi. 584254f889dSBrendon Cahoon static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop, 585254f889dSBrendon Cahoon unsigned &InitVal, unsigned &LoopVal) { 586254f889dSBrendon Cahoon assert(Phi.isPHI() && "Expecting a Phi."); 587254f889dSBrendon Cahoon 588254f889dSBrendon Cahoon InitVal = 0; 589254f889dSBrendon Cahoon LoopVal = 0; 590254f889dSBrendon Cahoon for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) 591254f889dSBrendon Cahoon if (Phi.getOperand(i + 1).getMBB() != Loop) 592254f889dSBrendon Cahoon InitVal = Phi.getOperand(i).getReg(); 593fbfb19b1SSimon Pilgrim else 594254f889dSBrendon Cahoon LoopVal = Phi.getOperand(i).getReg(); 595254f889dSBrendon Cahoon 596254f889dSBrendon Cahoon assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure."); 597254f889dSBrendon Cahoon } 598254f889dSBrendon Cahoon 5998f976ba0SHiroshi Inoue /// Return the Phi register value that comes the loop block. 600254f889dSBrendon Cahoon static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) { 601254f889dSBrendon Cahoon for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) 602254f889dSBrendon Cahoon if (Phi.getOperand(i + 1).getMBB() == LoopBB) 603254f889dSBrendon Cahoon return Phi.getOperand(i).getReg(); 604254f889dSBrendon Cahoon return 0; 605254f889dSBrendon Cahoon } 606254f889dSBrendon Cahoon 607254f889dSBrendon Cahoon /// Return true if SUb can be reached from SUa following the chain edges. 608254f889dSBrendon Cahoon static bool isSuccOrder(SUnit *SUa, SUnit *SUb) { 609254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 610254f889dSBrendon Cahoon SmallVector<SUnit *, 8> Worklist; 611254f889dSBrendon Cahoon Worklist.push_back(SUa); 612254f889dSBrendon Cahoon while (!Worklist.empty()) { 613254f889dSBrendon Cahoon const SUnit *SU = Worklist.pop_back_val(); 614254f889dSBrendon Cahoon for (auto &SI : SU->Succs) { 615254f889dSBrendon Cahoon SUnit *SuccSU = SI.getSUnit(); 616254f889dSBrendon Cahoon if (SI.getKind() == SDep::Order) { 617254f889dSBrendon Cahoon if (Visited.count(SuccSU)) 618254f889dSBrendon Cahoon continue; 619254f889dSBrendon Cahoon if (SuccSU == SUb) 620254f889dSBrendon Cahoon return true; 621254f889dSBrendon Cahoon Worklist.push_back(SuccSU); 622254f889dSBrendon Cahoon Visited.insert(SuccSU); 623254f889dSBrendon Cahoon } 624254f889dSBrendon Cahoon } 625254f889dSBrendon Cahoon } 626254f889dSBrendon Cahoon return false; 627254f889dSBrendon Cahoon } 628254f889dSBrendon Cahoon 629254f889dSBrendon Cahoon /// Return true if the instruction causes a chain between memory 630254f889dSBrendon Cahoon /// references before and after it. 631254f889dSBrendon Cahoon static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) { 6326c5d5ce5SUlrich Weigand return MI.isCall() || MI.mayRaiseFPException() || 6336c5d5ce5SUlrich Weigand MI.hasUnmodeledSideEffects() || 634254f889dSBrendon Cahoon (MI.hasOrderedMemoryRef() && 635d98cf00cSJustin Lebar (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA))); 636254f889dSBrendon Cahoon } 637254f889dSBrendon Cahoon 638254f889dSBrendon Cahoon /// Return the underlying objects for the memory references of an instruction. 639254f889dSBrendon Cahoon /// This function calls the code in ValueTracking, but first checks that the 640254f889dSBrendon Cahoon /// instruction has a memory operand. 64171e8c6f2SBjorn Pettersson static void getUnderlyingObjects(const MachineInstr *MI, 64271e8c6f2SBjorn Pettersson SmallVectorImpl<const Value *> &Objs, 643254f889dSBrendon Cahoon const DataLayout &DL) { 644254f889dSBrendon Cahoon if (!MI->hasOneMemOperand()) 645254f889dSBrendon Cahoon return; 646254f889dSBrendon Cahoon MachineMemOperand *MM = *MI->memoperands_begin(); 647254f889dSBrendon Cahoon if (!MM->getValue()) 648254f889dSBrendon Cahoon return; 64971e8c6f2SBjorn Pettersson GetUnderlyingObjects(MM->getValue(), Objs, DL); 65071e8c6f2SBjorn Pettersson for (const Value *V : Objs) { 6519f041b18SKrzysztof Parzyszek if (!isIdentifiedObject(V)) { 6529f041b18SKrzysztof Parzyszek Objs.clear(); 6539f041b18SKrzysztof Parzyszek return; 6549f041b18SKrzysztof Parzyszek } 6559f041b18SKrzysztof Parzyszek Objs.push_back(V); 6569f041b18SKrzysztof Parzyszek } 657254f889dSBrendon Cahoon } 658254f889dSBrendon Cahoon 659254f889dSBrendon Cahoon /// Add a chain edge between a load and store if the store can be an 660254f889dSBrendon Cahoon /// alias of the load on a subsequent iteration, i.e., a loop carried 661254f889dSBrendon Cahoon /// dependence. This code is very similar to the code in ScheduleDAGInstrs 662254f889dSBrendon Cahoon /// but that code doesn't create loop carried dependences. 663254f889dSBrendon Cahoon void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) { 66471e8c6f2SBjorn Pettersson MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads; 6659f041b18SKrzysztof Parzyszek Value *UnknownValue = 6669f041b18SKrzysztof Parzyszek UndefValue::get(Type::getVoidTy(MF.getFunction().getContext())); 667254f889dSBrendon Cahoon for (auto &SU : SUnits) { 668254f889dSBrendon Cahoon MachineInstr &MI = *SU.getInstr(); 669254f889dSBrendon Cahoon if (isDependenceBarrier(MI, AA)) 670254f889dSBrendon Cahoon PendingLoads.clear(); 671254f889dSBrendon Cahoon else if (MI.mayLoad()) { 67271e8c6f2SBjorn Pettersson SmallVector<const Value *, 4> Objs; 673254f889dSBrendon Cahoon getUnderlyingObjects(&MI, Objs, MF.getDataLayout()); 6749f041b18SKrzysztof Parzyszek if (Objs.empty()) 6759f041b18SKrzysztof Parzyszek Objs.push_back(UnknownValue); 676254f889dSBrendon Cahoon for (auto V : Objs) { 677254f889dSBrendon Cahoon SmallVector<SUnit *, 4> &SUs = PendingLoads[V]; 678254f889dSBrendon Cahoon SUs.push_back(&SU); 679254f889dSBrendon Cahoon } 680254f889dSBrendon Cahoon } else if (MI.mayStore()) { 68171e8c6f2SBjorn Pettersson SmallVector<const Value *, 4> Objs; 682254f889dSBrendon Cahoon getUnderlyingObjects(&MI, Objs, MF.getDataLayout()); 6839f041b18SKrzysztof Parzyszek if (Objs.empty()) 6849f041b18SKrzysztof Parzyszek Objs.push_back(UnknownValue); 685254f889dSBrendon Cahoon for (auto V : Objs) { 68671e8c6f2SBjorn Pettersson MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I = 687254f889dSBrendon Cahoon PendingLoads.find(V); 688254f889dSBrendon Cahoon if (I == PendingLoads.end()) 689254f889dSBrendon Cahoon continue; 690254f889dSBrendon Cahoon for (auto Load : I->second) { 691254f889dSBrendon Cahoon if (isSuccOrder(Load, &SU)) 692254f889dSBrendon Cahoon continue; 693254f889dSBrendon Cahoon MachineInstr &LdMI = *Load->getInstr(); 694254f889dSBrendon Cahoon // First, perform the cheaper check that compares the base register. 695254f889dSBrendon Cahoon // If they are the same and the load offset is less than the store 696254f889dSBrendon Cahoon // offset, then mark the dependence as loop carried potentially. 697238c9d63SBjorn Pettersson const MachineOperand *BaseOp1, *BaseOp2; 698254f889dSBrendon Cahoon int64_t Offset1, Offset2; 6998fbc9258SSander de Smalen bool Offset1IsScalable, Offset2IsScalable; 7008fbc9258SSander de Smalen if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, 7018fbc9258SSander de Smalen Offset1IsScalable, TRI) && 7028fbc9258SSander de Smalen TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, 7038fbc9258SSander de Smalen Offset2IsScalable, TRI)) { 704d7eebd6dSFrancis Visoiu Mistrih if (BaseOp1->isIdenticalTo(*BaseOp2) && 7058fbc9258SSander de Smalen Offset1IsScalable == Offset2IsScalable && 706d7eebd6dSFrancis Visoiu Mistrih (int)Offset1 < (int)Offset2) { 707f5524f04SChangpeng Fang assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) && 708254f889dSBrendon Cahoon "What happened to the chain edge?"); 709c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 710c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 711c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 712254f889dSBrendon Cahoon continue; 713254f889dSBrendon Cahoon } 7149f041b18SKrzysztof Parzyszek } 715254f889dSBrendon Cahoon // Second, the more expensive check that uses alias analysis on the 716254f889dSBrendon Cahoon // base registers. If they alias, and the load offset is less than 717254f889dSBrendon Cahoon // the store offset, the mark the dependence as loop carried. 718254f889dSBrendon Cahoon if (!AA) { 719c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 720c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 721c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 722254f889dSBrendon Cahoon continue; 723254f889dSBrendon Cahoon } 724254f889dSBrendon Cahoon MachineMemOperand *MMO1 = *LdMI.memoperands_begin(); 725254f889dSBrendon Cahoon MachineMemOperand *MMO2 = *MI.memoperands_begin(); 726254f889dSBrendon Cahoon if (!MMO1->getValue() || !MMO2->getValue()) { 727c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 728c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 729c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 730254f889dSBrendon Cahoon continue; 731254f889dSBrendon Cahoon } 732254f889dSBrendon Cahoon if (MMO1->getValue() == MMO2->getValue() && 733254f889dSBrendon Cahoon MMO1->getOffset() <= MMO2->getOffset()) { 734c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 735c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 736c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 737254f889dSBrendon Cahoon continue; 738254f889dSBrendon Cahoon } 739254f889dSBrendon Cahoon AliasResult AAResult = AA->alias( 7406ef8002cSGeorge Burgess IV MemoryLocation(MMO1->getValue(), LocationSize::unknown(), 741254f889dSBrendon Cahoon MMO1->getAAInfo()), 7426ef8002cSGeorge Burgess IV MemoryLocation(MMO2->getValue(), LocationSize::unknown(), 743254f889dSBrendon Cahoon MMO2->getAAInfo())); 744254f889dSBrendon Cahoon 745c715a5d2SKrzysztof Parzyszek if (AAResult != NoAlias) { 746c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 747c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 748c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 749c715a5d2SKrzysztof Parzyszek } 750254f889dSBrendon Cahoon } 751254f889dSBrendon Cahoon } 752254f889dSBrendon Cahoon } 753254f889dSBrendon Cahoon } 754254f889dSBrendon Cahoon } 755254f889dSBrendon Cahoon 756254f889dSBrendon Cahoon /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer 757254f889dSBrendon Cahoon /// processes dependences for PHIs. This function adds true dependences 758254f889dSBrendon Cahoon /// from a PHI to a use, and a loop carried dependence from the use to the 759254f889dSBrendon Cahoon /// PHI. The loop carried dependence is represented as an anti dependence 760254f889dSBrendon Cahoon /// edge. This function also removes chain dependences between unrelated 761254f889dSBrendon Cahoon /// PHIs. 762254f889dSBrendon Cahoon void SwingSchedulerDAG::updatePhiDependences() { 763254f889dSBrendon Cahoon SmallVector<SDep, 4> RemoveDeps; 764254f889dSBrendon Cahoon const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>(); 765254f889dSBrendon Cahoon 766254f889dSBrendon Cahoon // Iterate over each DAG node. 767254f889dSBrendon Cahoon for (SUnit &I : SUnits) { 768254f889dSBrendon Cahoon RemoveDeps.clear(); 769254f889dSBrendon Cahoon // Set to true if the instruction has an operand defined by a Phi. 770254f889dSBrendon Cahoon unsigned HasPhiUse = 0; 771254f889dSBrendon Cahoon unsigned HasPhiDef = 0; 772254f889dSBrendon Cahoon MachineInstr *MI = I.getInstr(); 773254f889dSBrendon Cahoon // Iterate over each operand, and we process the definitions. 774254f889dSBrendon Cahoon for (MachineInstr::mop_iterator MOI = MI->operands_begin(), 775254f889dSBrendon Cahoon MOE = MI->operands_end(); 776254f889dSBrendon Cahoon MOI != MOE; ++MOI) { 777254f889dSBrendon Cahoon if (!MOI->isReg()) 778254f889dSBrendon Cahoon continue; 7790c476111SDaniel Sanders Register Reg = MOI->getReg(); 780254f889dSBrendon Cahoon if (MOI->isDef()) { 781254f889dSBrendon Cahoon // If the register is used by a Phi, then create an anti dependence. 782254f889dSBrendon Cahoon for (MachineRegisterInfo::use_instr_iterator 783254f889dSBrendon Cahoon UI = MRI.use_instr_begin(Reg), 784254f889dSBrendon Cahoon UE = MRI.use_instr_end(); 785254f889dSBrendon Cahoon UI != UE; ++UI) { 786254f889dSBrendon Cahoon MachineInstr *UseMI = &*UI; 787254f889dSBrendon Cahoon SUnit *SU = getSUnit(UseMI); 788cdc71612SEugene Zelenko if (SU != nullptr && UseMI->isPHI()) { 789254f889dSBrendon Cahoon if (!MI->isPHI()) { 790254f889dSBrendon Cahoon SDep Dep(SU, SDep::Anti, Reg); 791c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 792254f889dSBrendon Cahoon I.addPred(Dep); 793254f889dSBrendon Cahoon } else { 794254f889dSBrendon Cahoon HasPhiDef = Reg; 795254f889dSBrendon Cahoon // Add a chain edge to a dependent Phi that isn't an existing 796254f889dSBrendon Cahoon // predecessor. 797254f889dSBrendon Cahoon if (SU->NodeNum < I.NodeNum && !I.isPred(SU)) 798254f889dSBrendon Cahoon I.addPred(SDep(SU, SDep::Barrier)); 799254f889dSBrendon Cahoon } 800254f889dSBrendon Cahoon } 801254f889dSBrendon Cahoon } 802254f889dSBrendon Cahoon } else if (MOI->isUse()) { 803254f889dSBrendon Cahoon // If the register is defined by a Phi, then create a true dependence. 804254f889dSBrendon Cahoon MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg); 805cdc71612SEugene Zelenko if (DefMI == nullptr) 806254f889dSBrendon Cahoon continue; 807254f889dSBrendon Cahoon SUnit *SU = getSUnit(DefMI); 808cdc71612SEugene Zelenko if (SU != nullptr && DefMI->isPHI()) { 809254f889dSBrendon Cahoon if (!MI->isPHI()) { 810254f889dSBrendon Cahoon SDep Dep(SU, SDep::Data, Reg); 811254f889dSBrendon Cahoon Dep.setLatency(0); 812*c819ef96SFraser Cormack ST.adjustSchedDependency(SU, 0, &I, MI->getOperandNo(MOI), Dep); 813254f889dSBrendon Cahoon I.addPred(Dep); 814254f889dSBrendon Cahoon } else { 815254f889dSBrendon Cahoon HasPhiUse = Reg; 816254f889dSBrendon Cahoon // Add a chain edge to a dependent Phi that isn't an existing 817254f889dSBrendon Cahoon // predecessor. 818254f889dSBrendon Cahoon if (SU->NodeNum < I.NodeNum && !I.isPred(SU)) 819254f889dSBrendon Cahoon I.addPred(SDep(SU, SDep::Barrier)); 820254f889dSBrendon Cahoon } 821254f889dSBrendon Cahoon } 822254f889dSBrendon Cahoon } 823254f889dSBrendon Cahoon } 824254f889dSBrendon Cahoon // Remove order dependences from an unrelated Phi. 825254f889dSBrendon Cahoon if (!SwpPruneDeps) 826254f889dSBrendon Cahoon continue; 827254f889dSBrendon Cahoon for (auto &PI : I.Preds) { 828254f889dSBrendon Cahoon MachineInstr *PMI = PI.getSUnit()->getInstr(); 829254f889dSBrendon Cahoon if (PMI->isPHI() && PI.getKind() == SDep::Order) { 830254f889dSBrendon Cahoon if (I.getInstr()->isPHI()) { 831254f889dSBrendon Cahoon if (PMI->getOperand(0).getReg() == HasPhiUse) 832254f889dSBrendon Cahoon continue; 833254f889dSBrendon Cahoon if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef) 834254f889dSBrendon Cahoon continue; 835254f889dSBrendon Cahoon } 836254f889dSBrendon Cahoon RemoveDeps.push_back(PI); 837254f889dSBrendon Cahoon } 838254f889dSBrendon Cahoon } 839254f889dSBrendon Cahoon for (int i = 0, e = RemoveDeps.size(); i != e; ++i) 840254f889dSBrendon Cahoon I.removePred(RemoveDeps[i]); 841254f889dSBrendon Cahoon } 842254f889dSBrendon Cahoon } 843254f889dSBrendon Cahoon 844254f889dSBrendon Cahoon /// Iterate over each DAG node and see if we can change any dependences 845254f889dSBrendon Cahoon /// in order to reduce the recurrence MII. 846254f889dSBrendon Cahoon void SwingSchedulerDAG::changeDependences() { 847254f889dSBrendon Cahoon // See if an instruction can use a value from the previous iteration. 848254f889dSBrendon Cahoon // If so, we update the base and offset of the instruction and change 849254f889dSBrendon Cahoon // the dependences. 850254f889dSBrendon Cahoon for (SUnit &I : SUnits) { 851254f889dSBrendon Cahoon unsigned BasePos = 0, OffsetPos = 0, NewBase = 0; 852254f889dSBrendon Cahoon int64_t NewOffset = 0; 853254f889dSBrendon Cahoon if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase, 854254f889dSBrendon Cahoon NewOffset)) 855254f889dSBrendon Cahoon continue; 856254f889dSBrendon Cahoon 857254f889dSBrendon Cahoon // Get the MI and SUnit for the instruction that defines the original base. 8580c476111SDaniel Sanders Register OrigBase = I.getInstr()->getOperand(BasePos).getReg(); 859254f889dSBrendon Cahoon MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase); 860254f889dSBrendon Cahoon if (!DefMI) 861254f889dSBrendon Cahoon continue; 862254f889dSBrendon Cahoon SUnit *DefSU = getSUnit(DefMI); 863254f889dSBrendon Cahoon if (!DefSU) 864254f889dSBrendon Cahoon continue; 865254f889dSBrendon Cahoon // Get the MI and SUnit for the instruction that defins the new base. 866254f889dSBrendon Cahoon MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase); 867254f889dSBrendon Cahoon if (!LastMI) 868254f889dSBrendon Cahoon continue; 869254f889dSBrendon Cahoon SUnit *LastSU = getSUnit(LastMI); 870254f889dSBrendon Cahoon if (!LastSU) 871254f889dSBrendon Cahoon continue; 872254f889dSBrendon Cahoon 873254f889dSBrendon Cahoon if (Topo.IsReachable(&I, LastSU)) 874254f889dSBrendon Cahoon continue; 875254f889dSBrendon Cahoon 876254f889dSBrendon Cahoon // Remove the dependence. The value now depends on a prior iteration. 877254f889dSBrendon Cahoon SmallVector<SDep, 4> Deps; 878254f889dSBrendon Cahoon for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E; 879254f889dSBrendon Cahoon ++P) 880254f889dSBrendon Cahoon if (P->getSUnit() == DefSU) 881254f889dSBrendon Cahoon Deps.push_back(*P); 882254f889dSBrendon Cahoon for (int i = 0, e = Deps.size(); i != e; i++) { 883254f889dSBrendon Cahoon Topo.RemovePred(&I, Deps[i].getSUnit()); 884254f889dSBrendon Cahoon I.removePred(Deps[i]); 885254f889dSBrendon Cahoon } 886254f889dSBrendon Cahoon // Remove the chain dependence between the instructions. 887254f889dSBrendon Cahoon Deps.clear(); 888254f889dSBrendon Cahoon for (auto &P : LastSU->Preds) 889254f889dSBrendon Cahoon if (P.getSUnit() == &I && P.getKind() == SDep::Order) 890254f889dSBrendon Cahoon Deps.push_back(P); 891254f889dSBrendon Cahoon for (int i = 0, e = Deps.size(); i != e; i++) { 892254f889dSBrendon Cahoon Topo.RemovePred(LastSU, Deps[i].getSUnit()); 893254f889dSBrendon Cahoon LastSU->removePred(Deps[i]); 894254f889dSBrendon Cahoon } 895254f889dSBrendon Cahoon 896254f889dSBrendon Cahoon // Add a dependence between the new instruction and the instruction 897254f889dSBrendon Cahoon // that defines the new base. 898254f889dSBrendon Cahoon SDep Dep(&I, SDep::Anti, NewBase); 8998916e438SSumanth Gundapaneni Topo.AddPred(LastSU, &I); 900254f889dSBrendon Cahoon LastSU->addPred(Dep); 901254f889dSBrendon Cahoon 902254f889dSBrendon Cahoon // Remember the base and offset information so that we can update the 903254f889dSBrendon Cahoon // instruction during code generation. 904254f889dSBrendon Cahoon InstrChanges[&I] = std::make_pair(NewBase, NewOffset); 905254f889dSBrendon Cahoon } 906254f889dSBrendon Cahoon } 907254f889dSBrendon Cahoon 908254f889dSBrendon Cahoon namespace { 909cdc71612SEugene Zelenko 910254f889dSBrendon Cahoon // FuncUnitSorter - Comparison operator used to sort instructions by 911254f889dSBrendon Cahoon // the number of functional unit choices. 912254f889dSBrendon Cahoon struct FuncUnitSorter { 913254f889dSBrendon Cahoon const InstrItineraryData *InstrItins; 914f6cb3bcbSJinsong Ji const MCSubtargetInfo *STI; 915c3f36accSBevin Hansson DenseMap<InstrStage::FuncUnits, unsigned> Resources; 916254f889dSBrendon Cahoon 917f6cb3bcbSJinsong Ji FuncUnitSorter(const TargetSubtargetInfo &TSI) 918f6cb3bcbSJinsong Ji : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {} 91932a40564SEugene Zelenko 920254f889dSBrendon Cahoon // Compute the number of functional unit alternatives needed 921254f889dSBrendon Cahoon // at each stage, and take the minimum value. We prioritize the 922254f889dSBrendon Cahoon // instructions by the least number of choices first. 923c3f36accSBevin Hansson unsigned minFuncUnits(const MachineInstr *Inst, 924c3f36accSBevin Hansson InstrStage::FuncUnits &F) const { 925f6cb3bcbSJinsong Ji unsigned SchedClass = Inst->getDesc().getSchedClass(); 926254f889dSBrendon Cahoon unsigned min = UINT_MAX; 927f6cb3bcbSJinsong Ji if (InstrItins && !InstrItins->isEmpty()) { 928f6cb3bcbSJinsong Ji for (const InstrStage &IS : 929f6cb3bcbSJinsong Ji make_range(InstrItins->beginStage(SchedClass), 930f6cb3bcbSJinsong Ji InstrItins->endStage(SchedClass))) { 931c3f36accSBevin Hansson InstrStage::FuncUnits funcUnits = IS.getUnits(); 932254f889dSBrendon Cahoon unsigned numAlternatives = countPopulation(funcUnits); 933254f889dSBrendon Cahoon if (numAlternatives < min) { 934254f889dSBrendon Cahoon min = numAlternatives; 935254f889dSBrendon Cahoon F = funcUnits; 936254f889dSBrendon Cahoon } 937254f889dSBrendon Cahoon } 938254f889dSBrendon Cahoon return min; 939254f889dSBrendon Cahoon } 940f6cb3bcbSJinsong Ji if (STI && STI->getSchedModel().hasInstrSchedModel()) { 941f6cb3bcbSJinsong Ji const MCSchedClassDesc *SCDesc = 942f6cb3bcbSJinsong Ji STI->getSchedModel().getSchedClassDesc(SchedClass); 943f6cb3bcbSJinsong Ji if (!SCDesc->isValid()) 944f6cb3bcbSJinsong Ji // No valid Schedule Class Desc for schedClass, should be 945f6cb3bcbSJinsong Ji // Pseudo/PostRAPseudo 946f6cb3bcbSJinsong Ji return min; 947f6cb3bcbSJinsong Ji 948f6cb3bcbSJinsong Ji for (const MCWriteProcResEntry &PRE : 949f6cb3bcbSJinsong Ji make_range(STI->getWriteProcResBegin(SCDesc), 950f6cb3bcbSJinsong Ji STI->getWriteProcResEnd(SCDesc))) { 951f6cb3bcbSJinsong Ji if (!PRE.Cycles) 952f6cb3bcbSJinsong Ji continue; 953f6cb3bcbSJinsong Ji const MCProcResourceDesc *ProcResource = 954f6cb3bcbSJinsong Ji STI->getSchedModel().getProcResource(PRE.ProcResourceIdx); 955f6cb3bcbSJinsong Ji unsigned NumUnits = ProcResource->NumUnits; 956f6cb3bcbSJinsong Ji if (NumUnits < min) { 957f6cb3bcbSJinsong Ji min = NumUnits; 958f6cb3bcbSJinsong Ji F = PRE.ProcResourceIdx; 959f6cb3bcbSJinsong Ji } 960f6cb3bcbSJinsong Ji } 961f6cb3bcbSJinsong Ji return min; 962f6cb3bcbSJinsong Ji } 963f6cb3bcbSJinsong Ji llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!"); 964f6cb3bcbSJinsong Ji } 965254f889dSBrendon Cahoon 966254f889dSBrendon Cahoon // Compute the critical resources needed by the instruction. This 967254f889dSBrendon Cahoon // function records the functional units needed by instructions that 968254f889dSBrendon Cahoon // must use only one functional unit. We use this as a tie breaker 969254f889dSBrendon Cahoon // for computing the resource MII. The instrutions that require 970254f889dSBrendon Cahoon // the same, highly used, functional unit have high priority. 971254f889dSBrendon Cahoon void calcCriticalResources(MachineInstr &MI) { 972254f889dSBrendon Cahoon unsigned SchedClass = MI.getDesc().getSchedClass(); 973f6cb3bcbSJinsong Ji if (InstrItins && !InstrItins->isEmpty()) { 974f6cb3bcbSJinsong Ji for (const InstrStage &IS : 975f6cb3bcbSJinsong Ji make_range(InstrItins->beginStage(SchedClass), 976f6cb3bcbSJinsong Ji InstrItins->endStage(SchedClass))) { 977c3f36accSBevin Hansson InstrStage::FuncUnits FuncUnits = IS.getUnits(); 978254f889dSBrendon Cahoon if (countPopulation(FuncUnits) == 1) 979254f889dSBrendon Cahoon Resources[FuncUnits]++; 980254f889dSBrendon Cahoon } 981f6cb3bcbSJinsong Ji return; 982f6cb3bcbSJinsong Ji } 983f6cb3bcbSJinsong Ji if (STI && STI->getSchedModel().hasInstrSchedModel()) { 984f6cb3bcbSJinsong Ji const MCSchedClassDesc *SCDesc = 985f6cb3bcbSJinsong Ji STI->getSchedModel().getSchedClassDesc(SchedClass); 986f6cb3bcbSJinsong Ji if (!SCDesc->isValid()) 987f6cb3bcbSJinsong Ji // No valid Schedule Class Desc for schedClass, should be 988f6cb3bcbSJinsong Ji // Pseudo/PostRAPseudo 989f6cb3bcbSJinsong Ji return; 990f6cb3bcbSJinsong Ji 991f6cb3bcbSJinsong Ji for (const MCWriteProcResEntry &PRE : 992f6cb3bcbSJinsong Ji make_range(STI->getWriteProcResBegin(SCDesc), 993f6cb3bcbSJinsong Ji STI->getWriteProcResEnd(SCDesc))) { 994f6cb3bcbSJinsong Ji if (!PRE.Cycles) 995f6cb3bcbSJinsong Ji continue; 996f6cb3bcbSJinsong Ji Resources[PRE.ProcResourceIdx]++; 997f6cb3bcbSJinsong Ji } 998f6cb3bcbSJinsong Ji return; 999f6cb3bcbSJinsong Ji } 1000f6cb3bcbSJinsong Ji llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!"); 1001254f889dSBrendon Cahoon } 1002254f889dSBrendon Cahoon 1003254f889dSBrendon Cahoon /// Return true if IS1 has less priority than IS2. 1004254f889dSBrendon Cahoon bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const { 1005c3f36accSBevin Hansson InstrStage::FuncUnits F1 = 0, F2 = 0; 1006254f889dSBrendon Cahoon unsigned MFUs1 = minFuncUnits(IS1, F1); 1007254f889dSBrendon Cahoon unsigned MFUs2 = minFuncUnits(IS2, F2); 10086349ce5cSJinsong Ji if (MFUs1 == MFUs2) 1009254f889dSBrendon Cahoon return Resources.lookup(F1) < Resources.lookup(F2); 1010254f889dSBrendon Cahoon return MFUs1 > MFUs2; 1011254f889dSBrendon Cahoon } 1012254f889dSBrendon Cahoon }; 1013cdc71612SEugene Zelenko 1014cdc71612SEugene Zelenko } // end anonymous namespace 1015254f889dSBrendon Cahoon 1016254f889dSBrendon Cahoon /// Calculate the resource constrained minimum initiation interval for the 1017254f889dSBrendon Cahoon /// specified loop. We use the DFA to model the resources needed for 1018254f889dSBrendon Cahoon /// each instruction, and we ignore dependences. A different DFA is created 1019254f889dSBrendon Cahoon /// for each cycle that is required. When adding a new instruction, we attempt 1020254f889dSBrendon Cahoon /// to add it to each existing DFA, until a legal space is found. If the 1021254f889dSBrendon Cahoon /// instruction cannot be reserved in an existing DFA, we create a new one. 1022254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateResMII() { 1023f6cb3bcbSJinsong Ji 102418e7bf5cSJinsong Ji LLVM_DEBUG(dbgs() << "calculateResMII:\n"); 1025f6cb3bcbSJinsong Ji SmallVector<ResourceManager*, 8> Resources; 1026254f889dSBrendon Cahoon MachineBasicBlock *MBB = Loop.getHeader(); 1027f6cb3bcbSJinsong Ji Resources.push_back(new ResourceManager(&MF.getSubtarget())); 1028254f889dSBrendon Cahoon 1029254f889dSBrendon Cahoon // Sort the instructions by the number of available choices for scheduling, 1030254f889dSBrendon Cahoon // least to most. Use the number of critical resources as the tie breaker. 1031f6cb3bcbSJinsong Ji FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget()); 1032254f889dSBrendon Cahoon for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(), 1033254f889dSBrendon Cahoon E = MBB->getFirstTerminator(); 1034254f889dSBrendon Cahoon I != E; ++I) 1035254f889dSBrendon Cahoon FUS.calcCriticalResources(*I); 1036254f889dSBrendon Cahoon PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter> 1037254f889dSBrendon Cahoon FuncUnitOrder(FUS); 1038254f889dSBrendon Cahoon 1039254f889dSBrendon Cahoon for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(), 1040254f889dSBrendon Cahoon E = MBB->getFirstTerminator(); 1041254f889dSBrendon Cahoon I != E; ++I) 1042254f889dSBrendon Cahoon FuncUnitOrder.push(&*I); 1043254f889dSBrendon Cahoon 1044254f889dSBrendon Cahoon while (!FuncUnitOrder.empty()) { 1045254f889dSBrendon Cahoon MachineInstr *MI = FuncUnitOrder.top(); 1046254f889dSBrendon Cahoon FuncUnitOrder.pop(); 1047254f889dSBrendon Cahoon if (TII->isZeroCost(MI->getOpcode())) 1048254f889dSBrendon Cahoon continue; 1049254f889dSBrendon Cahoon // Attempt to reserve the instruction in an existing DFA. At least one 1050254f889dSBrendon Cahoon // DFA is needed for each cycle. 1051254f889dSBrendon Cahoon unsigned NumCycles = getSUnit(MI)->Latency; 1052254f889dSBrendon Cahoon unsigned ReservedCycles = 0; 1053f6cb3bcbSJinsong Ji SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin(); 1054f6cb3bcbSJinsong Ji SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end(); 105518e7bf5cSJinsong Ji LLVM_DEBUG({ 105618e7bf5cSJinsong Ji dbgs() << "Trying to reserve resource for " << NumCycles 105718e7bf5cSJinsong Ji << " cycles for \n"; 105818e7bf5cSJinsong Ji MI->dump(); 105918e7bf5cSJinsong Ji }); 1060254f889dSBrendon Cahoon for (unsigned C = 0; C < NumCycles; ++C) 1061254f889dSBrendon Cahoon while (RI != RE) { 1062fee855b5SJinsong Ji if ((*RI)->canReserveResources(*MI)) { 1063fee855b5SJinsong Ji (*RI)->reserveResources(*MI); 1064254f889dSBrendon Cahoon ++ReservedCycles; 1065254f889dSBrendon Cahoon break; 1066254f889dSBrendon Cahoon } 1067fee855b5SJinsong Ji RI++; 1068254f889dSBrendon Cahoon } 106918e7bf5cSJinsong Ji LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles 107018e7bf5cSJinsong Ji << ", NumCycles:" << NumCycles << "\n"); 1071254f889dSBrendon Cahoon // Add new DFAs, if needed, to reserve resources. 1072254f889dSBrendon Cahoon for (unsigned C = ReservedCycles; C < NumCycles; ++C) { 1073ba43840bSJinsong Ji LLVM_DEBUG(if (SwpDebugResource) dbgs() 1074ba43840bSJinsong Ji << "NewResource created to reserve resources" 107518e7bf5cSJinsong Ji << "\n"); 1076f6cb3bcbSJinsong Ji ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget()); 1077254f889dSBrendon Cahoon assert(NewResource->canReserveResources(*MI) && "Reserve error."); 1078254f889dSBrendon Cahoon NewResource->reserveResources(*MI); 1079254f889dSBrendon Cahoon Resources.push_back(NewResource); 1080254f889dSBrendon Cahoon } 1081254f889dSBrendon Cahoon } 1082254f889dSBrendon Cahoon int Resmii = Resources.size(); 108318e7bf5cSJinsong Ji LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n"); 1084254f889dSBrendon Cahoon // Delete the memory for each of the DFAs that were created earlier. 1085f6cb3bcbSJinsong Ji for (ResourceManager *RI : Resources) { 1086f6cb3bcbSJinsong Ji ResourceManager *D = RI; 1087254f889dSBrendon Cahoon delete D; 1088254f889dSBrendon Cahoon } 1089254f889dSBrendon Cahoon Resources.clear(); 1090254f889dSBrendon Cahoon return Resmii; 1091254f889dSBrendon Cahoon } 1092254f889dSBrendon Cahoon 1093254f889dSBrendon Cahoon /// Calculate the recurrence-constrainted minimum initiation interval. 1094254f889dSBrendon Cahoon /// Iterate over each circuit. Compute the delay(c) and distance(c) 1095254f889dSBrendon Cahoon /// for each circuit. The II needs to satisfy the inequality 1096254f889dSBrendon Cahoon /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest 1097c73b6d6bSHiroshi Inoue /// II that satisfies the inequality, and the RecMII is the maximum 1098254f889dSBrendon Cahoon /// of those values. 1099254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) { 1100254f889dSBrendon Cahoon unsigned RecMII = 0; 1101254f889dSBrendon Cahoon 1102254f889dSBrendon Cahoon for (NodeSet &Nodes : NodeSets) { 110332a40564SEugene Zelenko if (Nodes.empty()) 1104254f889dSBrendon Cahoon continue; 1105254f889dSBrendon Cahoon 1106a2122044SKrzysztof Parzyszek unsigned Delay = Nodes.getLatency(); 1107254f889dSBrendon Cahoon unsigned Distance = 1; 1108254f889dSBrendon Cahoon 1109254f889dSBrendon Cahoon // ii = ceil(delay / distance) 1110254f889dSBrendon Cahoon unsigned CurMII = (Delay + Distance - 1) / Distance; 1111254f889dSBrendon Cahoon Nodes.setRecMII(CurMII); 1112254f889dSBrendon Cahoon if (CurMII > RecMII) 1113254f889dSBrendon Cahoon RecMII = CurMII; 1114254f889dSBrendon Cahoon } 1115254f889dSBrendon Cahoon 1116254f889dSBrendon Cahoon return RecMII; 1117254f889dSBrendon Cahoon } 1118254f889dSBrendon Cahoon 1119254f889dSBrendon Cahoon /// Swap all the anti dependences in the DAG. That means it is no longer a DAG, 1120254f889dSBrendon Cahoon /// but we do this to find the circuits, and then change them back. 1121254f889dSBrendon Cahoon static void swapAntiDependences(std::vector<SUnit> &SUnits) { 1122254f889dSBrendon Cahoon SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded; 1123254f889dSBrendon Cahoon for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 1124254f889dSBrendon Cahoon SUnit *SU = &SUnits[i]; 1125254f889dSBrendon Cahoon for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end(); 1126254f889dSBrendon Cahoon IP != EP; ++IP) { 1127254f889dSBrendon Cahoon if (IP->getKind() != SDep::Anti) 1128254f889dSBrendon Cahoon continue; 1129254f889dSBrendon Cahoon DepsAdded.push_back(std::make_pair(SU, *IP)); 1130254f889dSBrendon Cahoon } 1131254f889dSBrendon Cahoon } 1132254f889dSBrendon Cahoon for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(), 1133254f889dSBrendon Cahoon E = DepsAdded.end(); 1134254f889dSBrendon Cahoon I != E; ++I) { 1135254f889dSBrendon Cahoon // Remove this anti dependency and add one in the reverse direction. 1136254f889dSBrendon Cahoon SUnit *SU = I->first; 1137254f889dSBrendon Cahoon SDep &D = I->second; 1138254f889dSBrendon Cahoon SUnit *TargetSU = D.getSUnit(); 1139254f889dSBrendon Cahoon unsigned Reg = D.getReg(); 1140254f889dSBrendon Cahoon unsigned Lat = D.getLatency(); 1141254f889dSBrendon Cahoon SU->removePred(D); 1142254f889dSBrendon Cahoon SDep Dep(SU, SDep::Anti, Reg); 1143254f889dSBrendon Cahoon Dep.setLatency(Lat); 1144254f889dSBrendon Cahoon TargetSU->addPred(Dep); 1145254f889dSBrendon Cahoon } 1146254f889dSBrendon Cahoon } 1147254f889dSBrendon Cahoon 1148254f889dSBrendon Cahoon /// Create the adjacency structure of the nodes in the graph. 1149254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::createAdjacencyStructure( 1150254f889dSBrendon Cahoon SwingSchedulerDAG *DAG) { 1151254f889dSBrendon Cahoon BitVector Added(SUnits.size()); 11528e1363dfSKrzysztof Parzyszek DenseMap<int, int> OutputDeps; 1153254f889dSBrendon Cahoon for (int i = 0, e = SUnits.size(); i != e; ++i) { 1154254f889dSBrendon Cahoon Added.reset(); 1155254f889dSBrendon Cahoon // Add any successor to the adjacency matrix and exclude duplicates. 1156254f889dSBrendon Cahoon for (auto &SI : SUnits[i].Succs) { 11578e1363dfSKrzysztof Parzyszek // Only create a back-edge on the first and last nodes of a dependence 11588e1363dfSKrzysztof Parzyszek // chain. This records any chains and adds them later. 11598e1363dfSKrzysztof Parzyszek if (SI.getKind() == SDep::Output) { 11608e1363dfSKrzysztof Parzyszek int N = SI.getSUnit()->NodeNum; 11618e1363dfSKrzysztof Parzyszek int BackEdge = i; 11628e1363dfSKrzysztof Parzyszek auto Dep = OutputDeps.find(BackEdge); 11638e1363dfSKrzysztof Parzyszek if (Dep != OutputDeps.end()) { 11648e1363dfSKrzysztof Parzyszek BackEdge = Dep->second; 11658e1363dfSKrzysztof Parzyszek OutputDeps.erase(Dep); 11668e1363dfSKrzysztof Parzyszek } 11678e1363dfSKrzysztof Parzyszek OutputDeps[N] = BackEdge; 11688e1363dfSKrzysztof Parzyszek } 1169ada0f511SSumanth Gundapaneni // Do not process a boundary node, an artificial node. 1170ada0f511SSumanth Gundapaneni // A back-edge is processed only if it goes to a Phi. 1171ada0f511SSumanth Gundapaneni if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() || 1172254f889dSBrendon Cahoon (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI())) 1173254f889dSBrendon Cahoon continue; 1174254f889dSBrendon Cahoon int N = SI.getSUnit()->NodeNum; 1175254f889dSBrendon Cahoon if (!Added.test(N)) { 1176254f889dSBrendon Cahoon AdjK[i].push_back(N); 1177254f889dSBrendon Cahoon Added.set(N); 1178254f889dSBrendon Cahoon } 1179254f889dSBrendon Cahoon } 1180254f889dSBrendon Cahoon // A chain edge between a store and a load is treated as a back-edge in the 1181254f889dSBrendon Cahoon // adjacency matrix. 1182254f889dSBrendon Cahoon for (auto &PI : SUnits[i].Preds) { 1183254f889dSBrendon Cahoon if (!SUnits[i].getInstr()->mayStore() || 11848e1363dfSKrzysztof Parzyszek !DAG->isLoopCarriedDep(&SUnits[i], PI, false)) 1185254f889dSBrendon Cahoon continue; 1186254f889dSBrendon Cahoon if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) { 1187254f889dSBrendon Cahoon int N = PI.getSUnit()->NodeNum; 1188254f889dSBrendon Cahoon if (!Added.test(N)) { 1189254f889dSBrendon Cahoon AdjK[i].push_back(N); 1190254f889dSBrendon Cahoon Added.set(N); 1191254f889dSBrendon Cahoon } 1192254f889dSBrendon Cahoon } 1193254f889dSBrendon Cahoon } 1194254f889dSBrendon Cahoon } 1195dad8c6a1SHiroshi Inoue // Add back-edges in the adjacency matrix for the output dependences. 11968e1363dfSKrzysztof Parzyszek for (auto &OD : OutputDeps) 11978e1363dfSKrzysztof Parzyszek if (!Added.test(OD.second)) { 11988e1363dfSKrzysztof Parzyszek AdjK[OD.first].push_back(OD.second); 11998e1363dfSKrzysztof Parzyszek Added.set(OD.second); 12008e1363dfSKrzysztof Parzyszek } 1201254f889dSBrendon Cahoon } 1202254f889dSBrendon Cahoon 1203254f889dSBrendon Cahoon /// Identify an elementary circuit in the dependence graph starting at the 1204254f889dSBrendon Cahoon /// specified node. 1205254f889dSBrendon Cahoon bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets, 1206254f889dSBrendon Cahoon bool HasBackedge) { 1207254f889dSBrendon Cahoon SUnit *SV = &SUnits[V]; 1208254f889dSBrendon Cahoon bool F = false; 1209254f889dSBrendon Cahoon Stack.insert(SV); 1210254f889dSBrendon Cahoon Blocked.set(V); 1211254f889dSBrendon Cahoon 1212254f889dSBrendon Cahoon for (auto W : AdjK[V]) { 1213254f889dSBrendon Cahoon if (NumPaths > MaxPaths) 1214254f889dSBrendon Cahoon break; 1215254f889dSBrendon Cahoon if (W < S) 1216254f889dSBrendon Cahoon continue; 1217254f889dSBrendon Cahoon if (W == S) { 1218254f889dSBrendon Cahoon if (!HasBackedge) 1219254f889dSBrendon Cahoon NodeSets.push_back(NodeSet(Stack.begin(), Stack.end())); 1220254f889dSBrendon Cahoon F = true; 1221254f889dSBrendon Cahoon ++NumPaths; 1222254f889dSBrendon Cahoon break; 1223254f889dSBrendon Cahoon } else if (!Blocked.test(W)) { 122477418a37SSumanth Gundapaneni if (circuit(W, S, NodeSets, 122577418a37SSumanth Gundapaneni Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge)) 1226254f889dSBrendon Cahoon F = true; 1227254f889dSBrendon Cahoon } 1228254f889dSBrendon Cahoon } 1229254f889dSBrendon Cahoon 1230254f889dSBrendon Cahoon if (F) 1231254f889dSBrendon Cahoon unblock(V); 1232254f889dSBrendon Cahoon else { 1233254f889dSBrendon Cahoon for (auto W : AdjK[V]) { 1234254f889dSBrendon Cahoon if (W < S) 1235254f889dSBrendon Cahoon continue; 1236254f889dSBrendon Cahoon if (B[W].count(SV) == 0) 1237254f889dSBrendon Cahoon B[W].insert(SV); 1238254f889dSBrendon Cahoon } 1239254f889dSBrendon Cahoon } 1240254f889dSBrendon Cahoon Stack.pop_back(); 1241254f889dSBrendon Cahoon return F; 1242254f889dSBrendon Cahoon } 1243254f889dSBrendon Cahoon 1244254f889dSBrendon Cahoon /// Unblock a node in the circuit finding algorithm. 1245254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::unblock(int U) { 1246254f889dSBrendon Cahoon Blocked.reset(U); 1247254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 4> &BU = B[U]; 1248254f889dSBrendon Cahoon while (!BU.empty()) { 1249254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin(); 1250254f889dSBrendon Cahoon assert(SI != BU.end() && "Invalid B set."); 1251254f889dSBrendon Cahoon SUnit *W = *SI; 1252254f889dSBrendon Cahoon BU.erase(W); 1253254f889dSBrendon Cahoon if (Blocked.test(W->NodeNum)) 1254254f889dSBrendon Cahoon unblock(W->NodeNum); 1255254f889dSBrendon Cahoon } 1256254f889dSBrendon Cahoon } 1257254f889dSBrendon Cahoon 1258254f889dSBrendon Cahoon /// Identify all the elementary circuits in the dependence graph using 1259254f889dSBrendon Cahoon /// Johnson's circuit algorithm. 1260254f889dSBrendon Cahoon void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) { 1261254f889dSBrendon Cahoon // Swap all the anti dependences in the DAG. That means it is no longer a DAG, 1262254f889dSBrendon Cahoon // but we do this to find the circuits, and then change them back. 1263254f889dSBrendon Cahoon swapAntiDependences(SUnits); 1264254f889dSBrendon Cahoon 126577418a37SSumanth Gundapaneni Circuits Cir(SUnits, Topo); 1266254f889dSBrendon Cahoon // Create the adjacency structure. 1267254f889dSBrendon Cahoon Cir.createAdjacencyStructure(this); 1268254f889dSBrendon Cahoon for (int i = 0, e = SUnits.size(); i != e; ++i) { 1269254f889dSBrendon Cahoon Cir.reset(); 1270254f889dSBrendon Cahoon Cir.circuit(i, i, NodeSets); 1271254f889dSBrendon Cahoon } 1272254f889dSBrendon Cahoon 1273254f889dSBrendon Cahoon // Change the dependences back so that we've created a DAG again. 1274254f889dSBrendon Cahoon swapAntiDependences(SUnits); 1275254f889dSBrendon Cahoon } 1276254f889dSBrendon Cahoon 127762ac69d4SSumanth Gundapaneni // Create artificial dependencies between the source of COPY/REG_SEQUENCE that 127862ac69d4SSumanth Gundapaneni // is loop-carried to the USE in next iteration. This will help pipeliner avoid 127962ac69d4SSumanth Gundapaneni // additional copies that are needed across iterations. An artificial dependence 128062ac69d4SSumanth Gundapaneni // edge is added from USE to SOURCE of COPY/REG_SEQUENCE. 128162ac69d4SSumanth Gundapaneni 128262ac69d4SSumanth Gundapaneni // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried) 128362ac69d4SSumanth Gundapaneni // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE 128462ac69d4SSumanth Gundapaneni // PHI-------True-Dep------> USEOfPhi 128562ac69d4SSumanth Gundapaneni 128662ac69d4SSumanth Gundapaneni // The mutation creates 128762ac69d4SSumanth Gundapaneni // USEOfPHI -------Artificial-Dep---> SRCOfCopy 128862ac69d4SSumanth Gundapaneni 128962ac69d4SSumanth Gundapaneni // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy 129062ac69d4SSumanth Gundapaneni // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled 129162ac69d4SSumanth Gundapaneni // late to avoid additional copies across iterations. The possible scheduling 129262ac69d4SSumanth Gundapaneni // order would be 129362ac69d4SSumanth Gundapaneni // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE. 129462ac69d4SSumanth Gundapaneni 129562ac69d4SSumanth Gundapaneni void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) { 129662ac69d4SSumanth Gundapaneni for (SUnit &SU : DAG->SUnits) { 129762ac69d4SSumanth Gundapaneni // Find the COPY/REG_SEQUENCE instruction. 129862ac69d4SSumanth Gundapaneni if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence()) 129962ac69d4SSumanth Gundapaneni continue; 130062ac69d4SSumanth Gundapaneni 130162ac69d4SSumanth Gundapaneni // Record the loop carried PHIs. 130262ac69d4SSumanth Gundapaneni SmallVector<SUnit *, 4> PHISUs; 130362ac69d4SSumanth Gundapaneni // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions. 130462ac69d4SSumanth Gundapaneni SmallVector<SUnit *, 4> SrcSUs; 130562ac69d4SSumanth Gundapaneni 130662ac69d4SSumanth Gundapaneni for (auto &Dep : SU.Preds) { 130762ac69d4SSumanth Gundapaneni SUnit *TmpSU = Dep.getSUnit(); 130862ac69d4SSumanth Gundapaneni MachineInstr *TmpMI = TmpSU->getInstr(); 130962ac69d4SSumanth Gundapaneni SDep::Kind DepKind = Dep.getKind(); 131062ac69d4SSumanth Gundapaneni // Save the loop carried PHI. 131162ac69d4SSumanth Gundapaneni if (DepKind == SDep::Anti && TmpMI->isPHI()) 131262ac69d4SSumanth Gundapaneni PHISUs.push_back(TmpSU); 131362ac69d4SSumanth Gundapaneni // Save the source of COPY/REG_SEQUENCE. 131462ac69d4SSumanth Gundapaneni // If the source has no pre-decessors, we will end up creating cycles. 131562ac69d4SSumanth Gundapaneni else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0) 131662ac69d4SSumanth Gundapaneni SrcSUs.push_back(TmpSU); 131762ac69d4SSumanth Gundapaneni } 131862ac69d4SSumanth Gundapaneni 131962ac69d4SSumanth Gundapaneni if (PHISUs.size() == 0 || SrcSUs.size() == 0) 132062ac69d4SSumanth Gundapaneni continue; 132162ac69d4SSumanth Gundapaneni 132262ac69d4SSumanth Gundapaneni // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this 132362ac69d4SSumanth Gundapaneni // SUnit to the container. 132462ac69d4SSumanth Gundapaneni SmallVector<SUnit *, 8> UseSUs; 13257c7e368aSSumanth Gundapaneni // Do not use iterator based loop here as we are updating the container. 13267c7e368aSSumanth Gundapaneni for (size_t Index = 0; Index < PHISUs.size(); ++Index) { 13277c7e368aSSumanth Gundapaneni for (auto &Dep : PHISUs[Index]->Succs) { 132862ac69d4SSumanth Gundapaneni if (Dep.getKind() != SDep::Data) 132962ac69d4SSumanth Gundapaneni continue; 133062ac69d4SSumanth Gundapaneni 133162ac69d4SSumanth Gundapaneni SUnit *TmpSU = Dep.getSUnit(); 133262ac69d4SSumanth Gundapaneni MachineInstr *TmpMI = TmpSU->getInstr(); 133362ac69d4SSumanth Gundapaneni if (TmpMI->isPHI() || TmpMI->isRegSequence()) { 133462ac69d4SSumanth Gundapaneni PHISUs.push_back(TmpSU); 133562ac69d4SSumanth Gundapaneni continue; 133662ac69d4SSumanth Gundapaneni } 133762ac69d4SSumanth Gundapaneni UseSUs.push_back(TmpSU); 133862ac69d4SSumanth Gundapaneni } 133962ac69d4SSumanth Gundapaneni } 134062ac69d4SSumanth Gundapaneni 134162ac69d4SSumanth Gundapaneni if (UseSUs.size() == 0) 134262ac69d4SSumanth Gundapaneni continue; 134362ac69d4SSumanth Gundapaneni 134462ac69d4SSumanth Gundapaneni SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG); 134562ac69d4SSumanth Gundapaneni // Add the artificial dependencies if it does not form a cycle. 134662ac69d4SSumanth Gundapaneni for (auto I : UseSUs) { 134762ac69d4SSumanth Gundapaneni for (auto Src : SrcSUs) { 134862ac69d4SSumanth Gundapaneni if (!SDAG->Topo.IsReachable(I, Src) && Src != I) { 134962ac69d4SSumanth Gundapaneni Src->addPred(SDep(I, SDep::Artificial)); 135062ac69d4SSumanth Gundapaneni SDAG->Topo.AddPred(Src, I); 135162ac69d4SSumanth Gundapaneni } 135262ac69d4SSumanth Gundapaneni } 135362ac69d4SSumanth Gundapaneni } 135462ac69d4SSumanth Gundapaneni } 135562ac69d4SSumanth Gundapaneni } 135662ac69d4SSumanth Gundapaneni 1357254f889dSBrendon Cahoon /// Return true for DAG nodes that we ignore when computing the cost functions. 1358c73b6d6bSHiroshi Inoue /// We ignore the back-edge recurrence in order to avoid unbounded recursion 1359254f889dSBrendon Cahoon /// in the calculation of the ASAP, ALAP, etc functions. 1360254f889dSBrendon Cahoon static bool ignoreDependence(const SDep &D, bool isPred) { 1361254f889dSBrendon Cahoon if (D.isArtificial()) 1362254f889dSBrendon Cahoon return true; 1363254f889dSBrendon Cahoon return D.getKind() == SDep::Anti && isPred; 1364254f889dSBrendon Cahoon } 1365254f889dSBrendon Cahoon 1366254f889dSBrendon Cahoon /// Compute several functions need to order the nodes for scheduling. 1367254f889dSBrendon Cahoon /// ASAP - Earliest time to schedule a node. 1368254f889dSBrendon Cahoon /// ALAP - Latest time to schedule a node. 1369254f889dSBrendon Cahoon /// MOV - Mobility function, difference between ALAP and ASAP. 1370254f889dSBrendon Cahoon /// D - Depth of each node. 1371254f889dSBrendon Cahoon /// H - Height of each node. 1372254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) { 1373254f889dSBrendon Cahoon ScheduleInfo.resize(SUnits.size()); 1374254f889dSBrendon Cahoon 1375d34e60caSNicola Zaghen LLVM_DEBUG({ 1376254f889dSBrendon Cahoon for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(), 1377254f889dSBrendon Cahoon E = Topo.end(); 1378254f889dSBrendon Cahoon I != E; ++I) { 1379726e12cfSMatthias Braun const SUnit &SU = SUnits[*I]; 1380726e12cfSMatthias Braun dumpNode(SU); 1381254f889dSBrendon Cahoon } 1382254f889dSBrendon Cahoon }); 1383254f889dSBrendon Cahoon 1384254f889dSBrendon Cahoon int maxASAP = 0; 13854b8bcf00SRoorda, Jan-Willem // Compute ASAP and ZeroLatencyDepth. 1386254f889dSBrendon Cahoon for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(), 1387254f889dSBrendon Cahoon E = Topo.end(); 1388254f889dSBrendon Cahoon I != E; ++I) { 1389254f889dSBrendon Cahoon int asap = 0; 13904b8bcf00SRoorda, Jan-Willem int zeroLatencyDepth = 0; 1391254f889dSBrendon Cahoon SUnit *SU = &SUnits[*I]; 1392254f889dSBrendon Cahoon for (SUnit::const_pred_iterator IP = SU->Preds.begin(), 1393254f889dSBrendon Cahoon EP = SU->Preds.end(); 1394254f889dSBrendon Cahoon IP != EP; ++IP) { 13954b8bcf00SRoorda, Jan-Willem SUnit *pred = IP->getSUnit(); 1396c715a5d2SKrzysztof Parzyszek if (IP->getLatency() == 0) 13974b8bcf00SRoorda, Jan-Willem zeroLatencyDepth = 13984b8bcf00SRoorda, Jan-Willem std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1); 1399254f889dSBrendon Cahoon if (ignoreDependence(*IP, true)) 1400254f889dSBrendon Cahoon continue; 1401c715a5d2SKrzysztof Parzyszek asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() - 1402254f889dSBrendon Cahoon getDistance(pred, SU, *IP) * MII)); 1403254f889dSBrendon Cahoon } 1404254f889dSBrendon Cahoon maxASAP = std::max(maxASAP, asap); 1405254f889dSBrendon Cahoon ScheduleInfo[*I].ASAP = asap; 14064b8bcf00SRoorda, Jan-Willem ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth; 1407254f889dSBrendon Cahoon } 1408254f889dSBrendon Cahoon 14094b8bcf00SRoorda, Jan-Willem // Compute ALAP, ZeroLatencyHeight, and MOV. 1410254f889dSBrendon Cahoon for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(), 1411254f889dSBrendon Cahoon E = Topo.rend(); 1412254f889dSBrendon Cahoon I != E; ++I) { 1413254f889dSBrendon Cahoon int alap = maxASAP; 14144b8bcf00SRoorda, Jan-Willem int zeroLatencyHeight = 0; 1415254f889dSBrendon Cahoon SUnit *SU = &SUnits[*I]; 1416254f889dSBrendon Cahoon for (SUnit::const_succ_iterator IS = SU->Succs.begin(), 1417254f889dSBrendon Cahoon ES = SU->Succs.end(); 1418254f889dSBrendon Cahoon IS != ES; ++IS) { 14194b8bcf00SRoorda, Jan-Willem SUnit *succ = IS->getSUnit(); 1420c715a5d2SKrzysztof Parzyszek if (IS->getLatency() == 0) 14214b8bcf00SRoorda, Jan-Willem zeroLatencyHeight = 14224b8bcf00SRoorda, Jan-Willem std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1); 1423254f889dSBrendon Cahoon if (ignoreDependence(*IS, true)) 1424254f889dSBrendon Cahoon continue; 1425c715a5d2SKrzysztof Parzyszek alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() + 1426254f889dSBrendon Cahoon getDistance(SU, succ, *IS) * MII)); 1427254f889dSBrendon Cahoon } 1428254f889dSBrendon Cahoon 1429254f889dSBrendon Cahoon ScheduleInfo[*I].ALAP = alap; 14304b8bcf00SRoorda, Jan-Willem ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight; 1431254f889dSBrendon Cahoon } 1432254f889dSBrendon Cahoon 1433254f889dSBrendon Cahoon // After computing the node functions, compute the summary for each node set. 1434254f889dSBrendon Cahoon for (NodeSet &I : NodeSets) 1435254f889dSBrendon Cahoon I.computeNodeSetInfo(this); 1436254f889dSBrendon Cahoon 1437d34e60caSNicola Zaghen LLVM_DEBUG({ 1438254f889dSBrendon Cahoon for (unsigned i = 0; i < SUnits.size(); i++) { 1439254f889dSBrendon Cahoon dbgs() << "\tNode " << i << ":\n"; 1440254f889dSBrendon Cahoon dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n"; 1441254f889dSBrendon Cahoon dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n"; 1442254f889dSBrendon Cahoon dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n"; 1443254f889dSBrendon Cahoon dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n"; 1444254f889dSBrendon Cahoon dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n"; 14454b8bcf00SRoorda, Jan-Willem dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n"; 14464b8bcf00SRoorda, Jan-Willem dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n"; 1447254f889dSBrendon Cahoon } 1448254f889dSBrendon Cahoon }); 1449254f889dSBrendon Cahoon } 1450254f889dSBrendon Cahoon 1451254f889dSBrendon Cahoon /// Compute the Pred_L(O) set, as defined in the paper. The set is defined 1452254f889dSBrendon Cahoon /// as the predecessors of the elements of NodeOrder that are not also in 1453254f889dSBrendon Cahoon /// NodeOrder. 1454254f889dSBrendon Cahoon static bool pred_L(SetVector<SUnit *> &NodeOrder, 1455254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> &Preds, 1456254f889dSBrendon Cahoon const NodeSet *S = nullptr) { 1457254f889dSBrendon Cahoon Preds.clear(); 1458254f889dSBrendon Cahoon for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end(); 1459254f889dSBrendon Cahoon I != E; ++I) { 1460254f889dSBrendon Cahoon for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end(); 1461254f889dSBrendon Cahoon PI != PE; ++PI) { 1462254f889dSBrendon Cahoon if (S && S->count(PI->getSUnit()) == 0) 1463254f889dSBrendon Cahoon continue; 1464254f889dSBrendon Cahoon if (ignoreDependence(*PI, true)) 1465254f889dSBrendon Cahoon continue; 1466254f889dSBrendon Cahoon if (NodeOrder.count(PI->getSUnit()) == 0) 1467254f889dSBrendon Cahoon Preds.insert(PI->getSUnit()); 1468254f889dSBrendon Cahoon } 1469254f889dSBrendon Cahoon // Back-edges are predecessors with an anti-dependence. 1470254f889dSBrendon Cahoon for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(), 1471254f889dSBrendon Cahoon ES = (*I)->Succs.end(); 1472254f889dSBrendon Cahoon IS != ES; ++IS) { 1473254f889dSBrendon Cahoon if (IS->getKind() != SDep::Anti) 1474254f889dSBrendon Cahoon continue; 1475254f889dSBrendon Cahoon if (S && S->count(IS->getSUnit()) == 0) 1476254f889dSBrendon Cahoon continue; 1477254f889dSBrendon Cahoon if (NodeOrder.count(IS->getSUnit()) == 0) 1478254f889dSBrendon Cahoon Preds.insert(IS->getSUnit()); 1479254f889dSBrendon Cahoon } 1480254f889dSBrendon Cahoon } 148132a40564SEugene Zelenko return !Preds.empty(); 1482254f889dSBrendon Cahoon } 1483254f889dSBrendon Cahoon 1484254f889dSBrendon Cahoon /// Compute the Succ_L(O) set, as defined in the paper. The set is defined 1485254f889dSBrendon Cahoon /// as the successors of the elements of NodeOrder that are not also in 1486254f889dSBrendon Cahoon /// NodeOrder. 1487254f889dSBrendon Cahoon static bool succ_L(SetVector<SUnit *> &NodeOrder, 1488254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> &Succs, 1489254f889dSBrendon Cahoon const NodeSet *S = nullptr) { 1490254f889dSBrendon Cahoon Succs.clear(); 1491254f889dSBrendon Cahoon for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end(); 1492254f889dSBrendon Cahoon I != E; ++I) { 1493254f889dSBrendon Cahoon for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end(); 1494254f889dSBrendon Cahoon SI != SE; ++SI) { 1495254f889dSBrendon Cahoon if (S && S->count(SI->getSUnit()) == 0) 1496254f889dSBrendon Cahoon continue; 1497254f889dSBrendon Cahoon if (ignoreDependence(*SI, false)) 1498254f889dSBrendon Cahoon continue; 1499254f889dSBrendon Cahoon if (NodeOrder.count(SI->getSUnit()) == 0) 1500254f889dSBrendon Cahoon Succs.insert(SI->getSUnit()); 1501254f889dSBrendon Cahoon } 1502254f889dSBrendon Cahoon for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(), 1503254f889dSBrendon Cahoon PE = (*I)->Preds.end(); 1504254f889dSBrendon Cahoon PI != PE; ++PI) { 1505254f889dSBrendon Cahoon if (PI->getKind() != SDep::Anti) 1506254f889dSBrendon Cahoon continue; 1507254f889dSBrendon Cahoon if (S && S->count(PI->getSUnit()) == 0) 1508254f889dSBrendon Cahoon continue; 1509254f889dSBrendon Cahoon if (NodeOrder.count(PI->getSUnit()) == 0) 1510254f889dSBrendon Cahoon Succs.insert(PI->getSUnit()); 1511254f889dSBrendon Cahoon } 1512254f889dSBrendon Cahoon } 151332a40564SEugene Zelenko return !Succs.empty(); 1514254f889dSBrendon Cahoon } 1515254f889dSBrendon Cahoon 1516254f889dSBrendon Cahoon /// Return true if there is a path from the specified node to any of the nodes 1517254f889dSBrendon Cahoon /// in DestNodes. Keep track and return the nodes in any path. 1518254f889dSBrendon Cahoon static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path, 1519254f889dSBrendon Cahoon SetVector<SUnit *> &DestNodes, 1520254f889dSBrendon Cahoon SetVector<SUnit *> &Exclude, 1521254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> &Visited) { 1522254f889dSBrendon Cahoon if (Cur->isBoundaryNode()) 1523254f889dSBrendon Cahoon return false; 1524254f889dSBrendon Cahoon if (Exclude.count(Cur) != 0) 1525254f889dSBrendon Cahoon return false; 1526254f889dSBrendon Cahoon if (DestNodes.count(Cur) != 0) 1527254f889dSBrendon Cahoon return true; 1528254f889dSBrendon Cahoon if (!Visited.insert(Cur).second) 1529254f889dSBrendon Cahoon return Path.count(Cur) != 0; 1530254f889dSBrendon Cahoon bool FoundPath = false; 1531254f889dSBrendon Cahoon for (auto &SI : Cur->Succs) 1532254f889dSBrendon Cahoon FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited); 1533254f889dSBrendon Cahoon for (auto &PI : Cur->Preds) 1534254f889dSBrendon Cahoon if (PI.getKind() == SDep::Anti) 1535254f889dSBrendon Cahoon FoundPath |= 1536254f889dSBrendon Cahoon computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited); 1537254f889dSBrendon Cahoon if (FoundPath) 1538254f889dSBrendon Cahoon Path.insert(Cur); 1539254f889dSBrendon Cahoon return FoundPath; 1540254f889dSBrendon Cahoon } 1541254f889dSBrendon Cahoon 1542254f889dSBrendon Cahoon /// Return true if Set1 is a subset of Set2. 1543254f889dSBrendon Cahoon template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) { 1544254f889dSBrendon Cahoon for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I) 1545254f889dSBrendon Cahoon if (Set2.count(*I) == 0) 1546254f889dSBrendon Cahoon return false; 1547254f889dSBrendon Cahoon return true; 1548254f889dSBrendon Cahoon } 1549254f889dSBrendon Cahoon 1550254f889dSBrendon Cahoon /// Compute the live-out registers for the instructions in a node-set. 1551254f889dSBrendon Cahoon /// The live-out registers are those that are defined in the node-set, 1552254f889dSBrendon Cahoon /// but not used. Except for use operands of Phis. 1553254f889dSBrendon Cahoon static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker, 1554254f889dSBrendon Cahoon NodeSet &NS) { 1555254f889dSBrendon Cahoon const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1556254f889dSBrendon Cahoon MachineRegisterInfo &MRI = MF.getRegInfo(); 1557254f889dSBrendon Cahoon SmallVector<RegisterMaskPair, 8> LiveOutRegs; 1558254f889dSBrendon Cahoon SmallSet<unsigned, 4> Uses; 1559254f889dSBrendon Cahoon for (SUnit *SU : NS) { 1560254f889dSBrendon Cahoon const MachineInstr *MI = SU->getInstr(); 1561254f889dSBrendon Cahoon if (MI->isPHI()) 1562254f889dSBrendon Cahoon continue; 1563fc371558SMatthias Braun for (const MachineOperand &MO : MI->operands()) 1564fc371558SMatthias Braun if (MO.isReg() && MO.isUse()) { 15650c476111SDaniel Sanders Register Reg = MO.getReg(); 15662bea69bfSDaniel Sanders if (Register::isVirtualRegister(Reg)) 1567254f889dSBrendon Cahoon Uses.insert(Reg); 1568254f889dSBrendon Cahoon else if (MRI.isAllocatable(Reg)) 1569254f889dSBrendon Cahoon for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 1570254f889dSBrendon Cahoon Uses.insert(*Units); 1571254f889dSBrendon Cahoon } 1572254f889dSBrendon Cahoon } 1573254f889dSBrendon Cahoon for (SUnit *SU : NS) 1574fc371558SMatthias Braun for (const MachineOperand &MO : SU->getInstr()->operands()) 1575fc371558SMatthias Braun if (MO.isReg() && MO.isDef() && !MO.isDead()) { 15760c476111SDaniel Sanders Register Reg = MO.getReg(); 15772bea69bfSDaniel Sanders if (Register::isVirtualRegister(Reg)) { 1578254f889dSBrendon Cahoon if (!Uses.count(Reg)) 157991b5cf84SKrzysztof Parzyszek LiveOutRegs.push_back(RegisterMaskPair(Reg, 158091b5cf84SKrzysztof Parzyszek LaneBitmask::getNone())); 1581254f889dSBrendon Cahoon } else if (MRI.isAllocatable(Reg)) { 1582254f889dSBrendon Cahoon for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 1583254f889dSBrendon Cahoon if (!Uses.count(*Units)) 158491b5cf84SKrzysztof Parzyszek LiveOutRegs.push_back(RegisterMaskPair(*Units, 158591b5cf84SKrzysztof Parzyszek LaneBitmask::getNone())); 1586254f889dSBrendon Cahoon } 1587254f889dSBrendon Cahoon } 1588254f889dSBrendon Cahoon RPTracker.addLiveRegs(LiveOutRegs); 1589254f889dSBrendon Cahoon } 1590254f889dSBrendon Cahoon 1591254f889dSBrendon Cahoon /// A heuristic to filter nodes in recurrent node-sets if the register 1592254f889dSBrendon Cahoon /// pressure of a set is too high. 1593254f889dSBrendon Cahoon void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) { 1594254f889dSBrendon Cahoon for (auto &NS : NodeSets) { 1595254f889dSBrendon Cahoon // Skip small node-sets since they won't cause register pressure problems. 1596254f889dSBrendon Cahoon if (NS.size() <= 2) 1597254f889dSBrendon Cahoon continue; 1598254f889dSBrendon Cahoon IntervalPressure RecRegPressure; 1599254f889dSBrendon Cahoon RegPressureTracker RecRPTracker(RecRegPressure); 1600254f889dSBrendon Cahoon RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true); 1601254f889dSBrendon Cahoon computeLiveOuts(MF, RecRPTracker, NS); 1602254f889dSBrendon Cahoon RecRPTracker.closeBottom(); 1603254f889dSBrendon Cahoon 1604254f889dSBrendon Cahoon std::vector<SUnit *> SUnits(NS.begin(), NS.end()); 16050cac726aSFangrui Song llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) { 1606254f889dSBrendon Cahoon return A->NodeNum > B->NodeNum; 1607254f889dSBrendon Cahoon }); 1608254f889dSBrendon Cahoon 1609254f889dSBrendon Cahoon for (auto &SU : SUnits) { 1610254f889dSBrendon Cahoon // Since we're computing the register pressure for a subset of the 1611254f889dSBrendon Cahoon // instructions in a block, we need to set the tracker for each 1612254f889dSBrendon Cahoon // instruction in the node-set. The tracker is set to the instruction 1613254f889dSBrendon Cahoon // just after the one we're interested in. 1614254f889dSBrendon Cahoon MachineBasicBlock::const_iterator CurInstI = SU->getInstr(); 1615254f889dSBrendon Cahoon RecRPTracker.setPos(std::next(CurInstI)); 1616254f889dSBrendon Cahoon 1617254f889dSBrendon Cahoon RegPressureDelta RPDelta; 1618254f889dSBrendon Cahoon ArrayRef<PressureChange> CriticalPSets; 1619254f889dSBrendon Cahoon RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta, 1620254f889dSBrendon Cahoon CriticalPSets, 1621254f889dSBrendon Cahoon RecRegPressure.MaxSetPressure); 1622254f889dSBrendon Cahoon if (RPDelta.Excess.isValid()) { 1623d34e60caSNicola Zaghen LLVM_DEBUG( 1624d34e60caSNicola Zaghen dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") " 1625254f889dSBrendon Cahoon << TRI->getRegPressureSetName(RPDelta.Excess.getPSet()) 1626254f889dSBrendon Cahoon << ":" << RPDelta.Excess.getUnitInc()); 1627254f889dSBrendon Cahoon NS.setExceedPressure(SU); 1628254f889dSBrendon Cahoon break; 1629254f889dSBrendon Cahoon } 1630254f889dSBrendon Cahoon RecRPTracker.recede(); 1631254f889dSBrendon Cahoon } 1632254f889dSBrendon Cahoon } 1633254f889dSBrendon Cahoon } 1634254f889dSBrendon Cahoon 1635254f889dSBrendon Cahoon /// A heuristic to colocate node sets that have the same set of 1636254f889dSBrendon Cahoon /// successors. 1637254f889dSBrendon Cahoon void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) { 1638254f889dSBrendon Cahoon unsigned Colocate = 0; 1639254f889dSBrendon Cahoon for (int i = 0, e = NodeSets.size(); i < e; ++i) { 1640254f889dSBrendon Cahoon NodeSet &N1 = NodeSets[i]; 1641254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> S1; 1642254f889dSBrendon Cahoon if (N1.empty() || !succ_L(N1, S1)) 1643254f889dSBrendon Cahoon continue; 1644254f889dSBrendon Cahoon for (int j = i + 1; j < e; ++j) { 1645254f889dSBrendon Cahoon NodeSet &N2 = NodeSets[j]; 1646254f889dSBrendon Cahoon if (N1.compareRecMII(N2) != 0) 1647254f889dSBrendon Cahoon continue; 1648254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> S2; 1649254f889dSBrendon Cahoon if (N2.empty() || !succ_L(N2, S2)) 1650254f889dSBrendon Cahoon continue; 1651254f889dSBrendon Cahoon if (isSubset(S1, S2) && S1.size() == S2.size()) { 1652254f889dSBrendon Cahoon N1.setColocate(++Colocate); 1653254f889dSBrendon Cahoon N2.setColocate(Colocate); 1654254f889dSBrendon Cahoon break; 1655254f889dSBrendon Cahoon } 1656254f889dSBrendon Cahoon } 1657254f889dSBrendon Cahoon } 1658254f889dSBrendon Cahoon } 1659254f889dSBrendon Cahoon 1660254f889dSBrendon Cahoon /// Check if the existing node-sets are profitable. If not, then ignore the 1661254f889dSBrendon Cahoon /// recurrent node-sets, and attempt to schedule all nodes together. This is 16623ca23341SKrzysztof Parzyszek /// a heuristic. If the MII is large and all the recurrent node-sets are small, 16633ca23341SKrzysztof Parzyszek /// then it's best to try to schedule all instructions together instead of 16643ca23341SKrzysztof Parzyszek /// starting with the recurrent node-sets. 1665254f889dSBrendon Cahoon void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) { 1666254f889dSBrendon Cahoon // Look for loops with a large MII. 16673ca23341SKrzysztof Parzyszek if (MII < 17) 1668254f889dSBrendon Cahoon return; 1669254f889dSBrendon Cahoon // Check if the node-set contains only a simple add recurrence. 16703ca23341SKrzysztof Parzyszek for (auto &NS : NodeSets) { 16713ca23341SKrzysztof Parzyszek if (NS.getRecMII() > 2) 1672254f889dSBrendon Cahoon return; 16733ca23341SKrzysztof Parzyszek if (NS.getMaxDepth() > MII) 16743ca23341SKrzysztof Parzyszek return; 16753ca23341SKrzysztof Parzyszek } 1676254f889dSBrendon Cahoon NodeSets.clear(); 1677d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n"); 1678254f889dSBrendon Cahoon return; 1679254f889dSBrendon Cahoon } 1680254f889dSBrendon Cahoon 1681254f889dSBrendon Cahoon /// Add the nodes that do not belong to a recurrence set into groups 1682254f889dSBrendon Cahoon /// based upon connected componenets. 1683254f889dSBrendon Cahoon void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) { 1684254f889dSBrendon Cahoon SetVector<SUnit *> NodesAdded; 1685254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 1686254f889dSBrendon Cahoon // Add the nodes that are on a path between the previous node sets and 1687254f889dSBrendon Cahoon // the current node set. 1688254f889dSBrendon Cahoon for (NodeSet &I : NodeSets) { 1689254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1690254f889dSBrendon Cahoon // Add the nodes from the current node set to the previous node set. 1691254f889dSBrendon Cahoon if (succ_L(I, N)) { 1692254f889dSBrendon Cahoon SetVector<SUnit *> Path; 1693254f889dSBrendon Cahoon for (SUnit *NI : N) { 1694254f889dSBrendon Cahoon Visited.clear(); 1695254f889dSBrendon Cahoon computePath(NI, Path, NodesAdded, I, Visited); 1696254f889dSBrendon Cahoon } 169732a40564SEugene Zelenko if (!Path.empty()) 1698254f889dSBrendon Cahoon I.insert(Path.begin(), Path.end()); 1699254f889dSBrendon Cahoon } 1700254f889dSBrendon Cahoon // Add the nodes from the previous node set to the current node set. 1701254f889dSBrendon Cahoon N.clear(); 1702254f889dSBrendon Cahoon if (succ_L(NodesAdded, N)) { 1703254f889dSBrendon Cahoon SetVector<SUnit *> Path; 1704254f889dSBrendon Cahoon for (SUnit *NI : N) { 1705254f889dSBrendon Cahoon Visited.clear(); 1706254f889dSBrendon Cahoon computePath(NI, Path, I, NodesAdded, Visited); 1707254f889dSBrendon Cahoon } 170832a40564SEugene Zelenko if (!Path.empty()) 1709254f889dSBrendon Cahoon I.insert(Path.begin(), Path.end()); 1710254f889dSBrendon Cahoon } 1711254f889dSBrendon Cahoon NodesAdded.insert(I.begin(), I.end()); 1712254f889dSBrendon Cahoon } 1713254f889dSBrendon Cahoon 1714254f889dSBrendon Cahoon // Create a new node set with the connected nodes of any successor of a node 1715254f889dSBrendon Cahoon // in a recurrent set. 1716254f889dSBrendon Cahoon NodeSet NewSet; 1717254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1718254f889dSBrendon Cahoon if (succ_L(NodesAdded, N)) 1719254f889dSBrendon Cahoon for (SUnit *I : N) 1720254f889dSBrendon Cahoon addConnectedNodes(I, NewSet, NodesAdded); 172132a40564SEugene Zelenko if (!NewSet.empty()) 1722254f889dSBrendon Cahoon NodeSets.push_back(NewSet); 1723254f889dSBrendon Cahoon 1724254f889dSBrendon Cahoon // Create a new node set with the connected nodes of any predecessor of a node 1725254f889dSBrendon Cahoon // in a recurrent set. 1726254f889dSBrendon Cahoon NewSet.clear(); 1727254f889dSBrendon Cahoon if (pred_L(NodesAdded, N)) 1728254f889dSBrendon Cahoon for (SUnit *I : N) 1729254f889dSBrendon Cahoon addConnectedNodes(I, NewSet, NodesAdded); 173032a40564SEugene Zelenko if (!NewSet.empty()) 1731254f889dSBrendon Cahoon NodeSets.push_back(NewSet); 1732254f889dSBrendon Cahoon 1733372ffa15SHiroshi Inoue // Create new nodes sets with the connected nodes any remaining node that 1734254f889dSBrendon Cahoon // has no predecessor. 1735254f889dSBrendon Cahoon for (unsigned i = 0; i < SUnits.size(); ++i) { 1736254f889dSBrendon Cahoon SUnit *SU = &SUnits[i]; 1737254f889dSBrendon Cahoon if (NodesAdded.count(SU) == 0) { 1738254f889dSBrendon Cahoon NewSet.clear(); 1739254f889dSBrendon Cahoon addConnectedNodes(SU, NewSet, NodesAdded); 174032a40564SEugene Zelenko if (!NewSet.empty()) 1741254f889dSBrendon Cahoon NodeSets.push_back(NewSet); 1742254f889dSBrendon Cahoon } 1743254f889dSBrendon Cahoon } 1744254f889dSBrendon Cahoon } 1745254f889dSBrendon Cahoon 174631f47b81SAlexey Lapshin /// Add the node to the set, and add all of its connected nodes to the set. 1747254f889dSBrendon Cahoon void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet, 1748254f889dSBrendon Cahoon SetVector<SUnit *> &NodesAdded) { 1749254f889dSBrendon Cahoon NewSet.insert(SU); 1750254f889dSBrendon Cahoon NodesAdded.insert(SU); 1751254f889dSBrendon Cahoon for (auto &SI : SU->Succs) { 1752254f889dSBrendon Cahoon SUnit *Successor = SI.getSUnit(); 1753254f889dSBrendon Cahoon if (!SI.isArtificial() && NodesAdded.count(Successor) == 0) 1754254f889dSBrendon Cahoon addConnectedNodes(Successor, NewSet, NodesAdded); 1755254f889dSBrendon Cahoon } 1756254f889dSBrendon Cahoon for (auto &PI : SU->Preds) { 1757254f889dSBrendon Cahoon SUnit *Predecessor = PI.getSUnit(); 1758254f889dSBrendon Cahoon if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0) 1759254f889dSBrendon Cahoon addConnectedNodes(Predecessor, NewSet, NodesAdded); 1760254f889dSBrendon Cahoon } 1761254f889dSBrendon Cahoon } 1762254f889dSBrendon Cahoon 1763254f889dSBrendon Cahoon /// Return true if Set1 contains elements in Set2. The elements in common 1764254f889dSBrendon Cahoon /// are returned in a different container. 1765254f889dSBrendon Cahoon static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2, 1766254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> &Result) { 1767254f889dSBrendon Cahoon Result.clear(); 1768254f889dSBrendon Cahoon for (unsigned i = 0, e = Set1.size(); i != e; ++i) { 1769254f889dSBrendon Cahoon SUnit *SU = Set1[i]; 1770254f889dSBrendon Cahoon if (Set2.count(SU) != 0) 1771254f889dSBrendon Cahoon Result.insert(SU); 1772254f889dSBrendon Cahoon } 1773254f889dSBrendon Cahoon return !Result.empty(); 1774254f889dSBrendon Cahoon } 1775254f889dSBrendon Cahoon 1776254f889dSBrendon Cahoon /// Merge the recurrence node sets that have the same initial node. 1777254f889dSBrendon Cahoon void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) { 1778254f889dSBrendon Cahoon for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E; 1779254f889dSBrendon Cahoon ++I) { 1780254f889dSBrendon Cahoon NodeSet &NI = *I; 1781254f889dSBrendon Cahoon for (NodeSetType::iterator J = I + 1; J != E;) { 1782254f889dSBrendon Cahoon NodeSet &NJ = *J; 1783254f889dSBrendon Cahoon if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) { 1784254f889dSBrendon Cahoon if (NJ.compareRecMII(NI) > 0) 1785254f889dSBrendon Cahoon NI.setRecMII(NJ.getRecMII()); 1786254f889dSBrendon Cahoon for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI; 1787254f889dSBrendon Cahoon ++NII) 1788254f889dSBrendon Cahoon I->insert(*NII); 1789254f889dSBrendon Cahoon NodeSets.erase(J); 1790254f889dSBrendon Cahoon E = NodeSets.end(); 1791254f889dSBrendon Cahoon } else { 1792254f889dSBrendon Cahoon ++J; 1793254f889dSBrendon Cahoon } 1794254f889dSBrendon Cahoon } 1795254f889dSBrendon Cahoon } 1796254f889dSBrendon Cahoon } 1797254f889dSBrendon Cahoon 1798254f889dSBrendon Cahoon /// Remove nodes that have been scheduled in previous NodeSets. 1799254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) { 1800254f889dSBrendon Cahoon for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E; 1801254f889dSBrendon Cahoon ++I) 1802254f889dSBrendon Cahoon for (NodeSetType::iterator J = I + 1; J != E;) { 1803254f889dSBrendon Cahoon J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); }); 1804254f889dSBrendon Cahoon 180532a40564SEugene Zelenko if (J->empty()) { 1806254f889dSBrendon Cahoon NodeSets.erase(J); 1807254f889dSBrendon Cahoon E = NodeSets.end(); 1808254f889dSBrendon Cahoon } else { 1809254f889dSBrendon Cahoon ++J; 1810254f889dSBrendon Cahoon } 1811254f889dSBrendon Cahoon } 1812254f889dSBrendon Cahoon } 1813254f889dSBrendon Cahoon 1814254f889dSBrendon Cahoon /// Compute an ordered list of the dependence graph nodes, which 1815254f889dSBrendon Cahoon /// indicates the order that the nodes will be scheduled. This is a 1816254f889dSBrendon Cahoon /// two-level algorithm. First, a partial order is created, which 1817254f889dSBrendon Cahoon /// consists of a list of sets ordered from highest to lowest priority. 1818254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) { 1819254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> R; 1820254f889dSBrendon Cahoon NodeOrder.clear(); 1821254f889dSBrendon Cahoon 1822254f889dSBrendon Cahoon for (auto &Nodes : NodeSets) { 1823d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n"); 1824254f889dSBrendon Cahoon OrderKind Order; 1825254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1826254f889dSBrendon Cahoon if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) { 1827254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1828254f889dSBrendon Cahoon Order = BottomUp; 1829d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Bottom up (preds) "); 1830254f889dSBrendon Cahoon } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) { 1831254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1832254f889dSBrendon Cahoon Order = TopDown; 1833d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Top down (succs) "); 1834254f889dSBrendon Cahoon } else if (isIntersect(N, Nodes, R)) { 1835254f889dSBrendon Cahoon // If some of the successors are in the existing node-set, then use the 1836254f889dSBrendon Cahoon // top-down ordering. 1837254f889dSBrendon Cahoon Order = TopDown; 1838d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Top down (intersect) "); 1839254f889dSBrendon Cahoon } else if (NodeSets.size() == 1) { 1840254f889dSBrendon Cahoon for (auto &N : Nodes) 1841254f889dSBrendon Cahoon if (N->Succs.size() == 0) 1842254f889dSBrendon Cahoon R.insert(N); 1843254f889dSBrendon Cahoon Order = BottomUp; 1844d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Bottom up (all) "); 1845254f889dSBrendon Cahoon } else { 1846254f889dSBrendon Cahoon // Find the node with the highest ASAP. 1847254f889dSBrendon Cahoon SUnit *maxASAP = nullptr; 1848254f889dSBrendon Cahoon for (SUnit *SU : Nodes) { 1849a2122044SKrzysztof Parzyszek if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) || 1850a2122044SKrzysztof Parzyszek (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum)) 1851254f889dSBrendon Cahoon maxASAP = SU; 1852254f889dSBrendon Cahoon } 1853254f889dSBrendon Cahoon R.insert(maxASAP); 1854254f889dSBrendon Cahoon Order = BottomUp; 1855d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Bottom up (default) "); 1856254f889dSBrendon Cahoon } 1857254f889dSBrendon Cahoon 1858254f889dSBrendon Cahoon while (!R.empty()) { 1859254f889dSBrendon Cahoon if (Order == TopDown) { 1860254f889dSBrendon Cahoon // Choose the node with the maximum height. If more than one, choose 1861a2122044SKrzysztof Parzyszek // the node wiTH the maximum ZeroLatencyHeight. If still more than one, 18624b8bcf00SRoorda, Jan-Willem // choose the node with the lowest MOV. 1863254f889dSBrendon Cahoon while (!R.empty()) { 1864254f889dSBrendon Cahoon SUnit *maxHeight = nullptr; 1865254f889dSBrendon Cahoon for (SUnit *I : R) { 1866cdc71612SEugene Zelenko if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight)) 1867254f889dSBrendon Cahoon maxHeight = I; 1868254f889dSBrendon Cahoon else if (getHeight(I) == getHeight(maxHeight) && 18694b8bcf00SRoorda, Jan-Willem getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight)) 1870254f889dSBrendon Cahoon maxHeight = I; 18714b8bcf00SRoorda, Jan-Willem else if (getHeight(I) == getHeight(maxHeight) && 18724b8bcf00SRoorda, Jan-Willem getZeroLatencyHeight(I) == 18734b8bcf00SRoorda, Jan-Willem getZeroLatencyHeight(maxHeight) && 18744b8bcf00SRoorda, Jan-Willem getMOV(I) < getMOV(maxHeight)) 1875254f889dSBrendon Cahoon maxHeight = I; 1876254f889dSBrendon Cahoon } 1877254f889dSBrendon Cahoon NodeOrder.insert(maxHeight); 1878d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " "); 1879254f889dSBrendon Cahoon R.remove(maxHeight); 1880254f889dSBrendon Cahoon for (const auto &I : maxHeight->Succs) { 1881254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1882254f889dSBrendon Cahoon continue; 1883254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1884254f889dSBrendon Cahoon continue; 1885254f889dSBrendon Cahoon if (ignoreDependence(I, false)) 1886254f889dSBrendon Cahoon continue; 1887254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1888254f889dSBrendon Cahoon } 1889254f889dSBrendon Cahoon // Back-edges are predecessors with an anti-dependence. 1890254f889dSBrendon Cahoon for (const auto &I : maxHeight->Preds) { 1891254f889dSBrendon Cahoon if (I.getKind() != SDep::Anti) 1892254f889dSBrendon Cahoon continue; 1893254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1894254f889dSBrendon Cahoon continue; 1895254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1896254f889dSBrendon Cahoon continue; 1897254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1898254f889dSBrendon Cahoon } 1899254f889dSBrendon Cahoon } 1900254f889dSBrendon Cahoon Order = BottomUp; 1901d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\n Switching order to bottom up "); 1902254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1903254f889dSBrendon Cahoon if (pred_L(NodeOrder, N, &Nodes)) 1904254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1905254f889dSBrendon Cahoon } else { 1906254f889dSBrendon Cahoon // Choose the node with the maximum depth. If more than one, choose 19074b8bcf00SRoorda, Jan-Willem // the node with the maximum ZeroLatencyDepth. If still more than one, 19084b8bcf00SRoorda, Jan-Willem // choose the node with the lowest MOV. 1909254f889dSBrendon Cahoon while (!R.empty()) { 1910254f889dSBrendon Cahoon SUnit *maxDepth = nullptr; 1911254f889dSBrendon Cahoon for (SUnit *I : R) { 1912cdc71612SEugene Zelenko if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth)) 1913254f889dSBrendon Cahoon maxDepth = I; 1914254f889dSBrendon Cahoon else if (getDepth(I) == getDepth(maxDepth) && 19154b8bcf00SRoorda, Jan-Willem getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth)) 1916254f889dSBrendon Cahoon maxDepth = I; 19174b8bcf00SRoorda, Jan-Willem else if (getDepth(I) == getDepth(maxDepth) && 19184b8bcf00SRoorda, Jan-Willem getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) && 19194b8bcf00SRoorda, Jan-Willem getMOV(I) < getMOV(maxDepth)) 1920254f889dSBrendon Cahoon maxDepth = I; 1921254f889dSBrendon Cahoon } 1922254f889dSBrendon Cahoon NodeOrder.insert(maxDepth); 1923d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " "); 1924254f889dSBrendon Cahoon R.remove(maxDepth); 1925254f889dSBrendon Cahoon if (Nodes.isExceedSU(maxDepth)) { 1926254f889dSBrendon Cahoon Order = TopDown; 1927254f889dSBrendon Cahoon R.clear(); 1928254f889dSBrendon Cahoon R.insert(Nodes.getNode(0)); 1929254f889dSBrendon Cahoon break; 1930254f889dSBrendon Cahoon } 1931254f889dSBrendon Cahoon for (const auto &I : maxDepth->Preds) { 1932254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1933254f889dSBrendon Cahoon continue; 1934254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1935254f889dSBrendon Cahoon continue; 1936254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1937254f889dSBrendon Cahoon } 1938254f889dSBrendon Cahoon // Back-edges are predecessors with an anti-dependence. 1939254f889dSBrendon Cahoon for (const auto &I : maxDepth->Succs) { 1940254f889dSBrendon Cahoon if (I.getKind() != SDep::Anti) 1941254f889dSBrendon Cahoon continue; 1942254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1943254f889dSBrendon Cahoon continue; 1944254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1945254f889dSBrendon Cahoon continue; 1946254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1947254f889dSBrendon Cahoon } 1948254f889dSBrendon Cahoon } 1949254f889dSBrendon Cahoon Order = TopDown; 1950d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\n Switching order to top down "); 1951254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1952254f889dSBrendon Cahoon if (succ_L(NodeOrder, N, &Nodes)) 1953254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1954254f889dSBrendon Cahoon } 1955254f889dSBrendon Cahoon } 1956d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n"); 1957254f889dSBrendon Cahoon } 1958254f889dSBrendon Cahoon 1959d34e60caSNicola Zaghen LLVM_DEBUG({ 1960254f889dSBrendon Cahoon dbgs() << "Node order: "; 1961254f889dSBrendon Cahoon for (SUnit *I : NodeOrder) 1962254f889dSBrendon Cahoon dbgs() << " " << I->NodeNum << " "; 1963254f889dSBrendon Cahoon dbgs() << "\n"; 1964254f889dSBrendon Cahoon }); 1965254f889dSBrendon Cahoon } 1966254f889dSBrendon Cahoon 1967254f889dSBrendon Cahoon /// Process the nodes in the computed order and create the pipelined schedule 1968254f889dSBrendon Cahoon /// of the instructions, if possible. Return true if a schedule is found. 1969254f889dSBrendon Cahoon bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) { 197018e7bf5cSJinsong Ji 197118e7bf5cSJinsong Ji if (NodeOrder.empty()){ 197218e7bf5cSJinsong Ji LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" ); 1973254f889dSBrendon Cahoon return false; 197418e7bf5cSJinsong Ji } 1975254f889dSBrendon Cahoon 1976254f889dSBrendon Cahoon bool scheduleFound = false; 197759d99731SBrendon Cahoon unsigned II = 0; 1978254f889dSBrendon Cahoon // Keep increasing II until a valid schedule is found. 197959d99731SBrendon Cahoon for (II = MII; II <= MAX_II && !scheduleFound; ++II) { 1980254f889dSBrendon Cahoon Schedule.reset(); 1981254f889dSBrendon Cahoon Schedule.setInitiationInterval(II); 1982d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n"); 1983254f889dSBrendon Cahoon 1984254f889dSBrendon Cahoon SetVector<SUnit *>::iterator NI = NodeOrder.begin(); 1985254f889dSBrendon Cahoon SetVector<SUnit *>::iterator NE = NodeOrder.end(); 1986254f889dSBrendon Cahoon do { 1987254f889dSBrendon Cahoon SUnit *SU = *NI; 1988254f889dSBrendon Cahoon 1989254f889dSBrendon Cahoon // Compute the schedule time for the instruction, which is based 1990254f889dSBrendon Cahoon // upon the scheduled time for any predecessors/successors. 1991254f889dSBrendon Cahoon int EarlyStart = INT_MIN; 1992254f889dSBrendon Cahoon int LateStart = INT_MAX; 1993254f889dSBrendon Cahoon // These values are set when the size of the schedule window is limited 1994254f889dSBrendon Cahoon // due to chain dependences. 1995254f889dSBrendon Cahoon int SchedEnd = INT_MAX; 1996254f889dSBrendon Cahoon int SchedStart = INT_MIN; 1997254f889dSBrendon Cahoon Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart, 1998254f889dSBrendon Cahoon II, this); 1999d34e60caSNicola Zaghen LLVM_DEBUG({ 200018e7bf5cSJinsong Ji dbgs() << "\n"; 2001254f889dSBrendon Cahoon dbgs() << "Inst (" << SU->NodeNum << ") "; 2002254f889dSBrendon Cahoon SU->getInstr()->dump(); 2003254f889dSBrendon Cahoon dbgs() << "\n"; 2004254f889dSBrendon Cahoon }); 2005d34e60caSNicola Zaghen LLVM_DEBUG({ 200618e7bf5cSJinsong Ji dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart, 200718e7bf5cSJinsong Ji LateStart, SchedEnd, SchedStart); 2008254f889dSBrendon Cahoon }); 2009254f889dSBrendon Cahoon 2010254f889dSBrendon Cahoon if (EarlyStart > LateStart || SchedEnd < EarlyStart || 2011254f889dSBrendon Cahoon SchedStart > LateStart) 2012254f889dSBrendon Cahoon scheduleFound = false; 2013254f889dSBrendon Cahoon else if (EarlyStart != INT_MIN && LateStart == INT_MAX) { 2014254f889dSBrendon Cahoon SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1); 2015254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II); 2016254f889dSBrendon Cahoon } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) { 2017254f889dSBrendon Cahoon SchedStart = std::max(SchedStart, LateStart - (int)II + 1); 2018254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II); 2019254f889dSBrendon Cahoon } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) { 2020254f889dSBrendon Cahoon SchedEnd = 2021254f889dSBrendon Cahoon std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1)); 2022254f889dSBrendon Cahoon // When scheduling a Phi it is better to start at the late cycle and go 2023254f889dSBrendon Cahoon // backwards. The default order may insert the Phi too far away from 2024254f889dSBrendon Cahoon // its first dependence. 2025254f889dSBrendon Cahoon if (SU->getInstr()->isPHI()) 2026254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II); 2027254f889dSBrendon Cahoon else 2028254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II); 2029254f889dSBrendon Cahoon } else { 2030254f889dSBrendon Cahoon int FirstCycle = Schedule.getFirstCycle(); 2031254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU), 2032254f889dSBrendon Cahoon FirstCycle + getASAP(SU) + II - 1, II); 2033254f889dSBrendon Cahoon } 2034254f889dSBrendon Cahoon // Even if we find a schedule, make sure the schedule doesn't exceed the 2035254f889dSBrendon Cahoon // allowable number of stages. We keep trying if this happens. 2036254f889dSBrendon Cahoon if (scheduleFound) 2037254f889dSBrendon Cahoon if (SwpMaxStages > -1 && 2038254f889dSBrendon Cahoon Schedule.getMaxStageCount() > (unsigned)SwpMaxStages) 2039254f889dSBrendon Cahoon scheduleFound = false; 2040254f889dSBrendon Cahoon 2041d34e60caSNicola Zaghen LLVM_DEBUG({ 2042254f889dSBrendon Cahoon if (!scheduleFound) 2043254f889dSBrendon Cahoon dbgs() << "\tCan't schedule\n"; 2044254f889dSBrendon Cahoon }); 2045254f889dSBrendon Cahoon } while (++NI != NE && scheduleFound); 2046254f889dSBrendon Cahoon 2047254f889dSBrendon Cahoon // If a schedule is found, check if it is a valid schedule too. 2048254f889dSBrendon Cahoon if (scheduleFound) 2049254f889dSBrendon Cahoon scheduleFound = Schedule.isValidSchedule(this); 2050254f889dSBrendon Cahoon } 2051254f889dSBrendon Cahoon 205259d99731SBrendon Cahoon LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II 205359d99731SBrendon Cahoon << ")\n"); 2054254f889dSBrendon Cahoon 2055254f889dSBrendon Cahoon if (scheduleFound) 2056254f889dSBrendon Cahoon Schedule.finalizeSchedule(this); 2057254f889dSBrendon Cahoon else 2058254f889dSBrendon Cahoon Schedule.reset(); 2059254f889dSBrendon Cahoon 2060254f889dSBrendon Cahoon return scheduleFound && Schedule.getMaxStageCount() > 0; 2061254f889dSBrendon Cahoon } 2062254f889dSBrendon Cahoon 2063254f889dSBrendon Cahoon /// Return true if we can compute the amount the instruction changes 2064254f889dSBrendon Cahoon /// during each iteration. Set Delta to the amount of the change. 2065254f889dSBrendon Cahoon bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) { 2066254f889dSBrendon Cahoon const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 2067238c9d63SBjorn Pettersson const MachineOperand *BaseOp; 2068254f889dSBrendon Cahoon int64_t Offset; 20698fbc9258SSander de Smalen bool OffsetIsScalable; 20708fbc9258SSander de Smalen if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI)) 20718fbc9258SSander de Smalen return false; 20728fbc9258SSander de Smalen 20738fbc9258SSander de Smalen // FIXME: This algorithm assumes instructions have fixed-size offsets. 20748fbc9258SSander de Smalen if (OffsetIsScalable) 2075254f889dSBrendon Cahoon return false; 2076254f889dSBrendon Cahoon 2077d7eebd6dSFrancis Visoiu Mistrih if (!BaseOp->isReg()) 2078d7eebd6dSFrancis Visoiu Mistrih return false; 2079d7eebd6dSFrancis Visoiu Mistrih 20800c476111SDaniel Sanders Register BaseReg = BaseOp->getReg(); 2081d7eebd6dSFrancis Visoiu Mistrih 2082254f889dSBrendon Cahoon MachineRegisterInfo &MRI = MF.getRegInfo(); 2083254f889dSBrendon Cahoon // Check if there is a Phi. If so, get the definition in the loop. 2084254f889dSBrendon Cahoon MachineInstr *BaseDef = MRI.getVRegDef(BaseReg); 2085254f889dSBrendon Cahoon if (BaseDef && BaseDef->isPHI()) { 2086254f889dSBrendon Cahoon BaseReg = getLoopPhiReg(*BaseDef, MI.getParent()); 2087254f889dSBrendon Cahoon BaseDef = MRI.getVRegDef(BaseReg); 2088254f889dSBrendon Cahoon } 2089254f889dSBrendon Cahoon if (!BaseDef) 2090254f889dSBrendon Cahoon return false; 2091254f889dSBrendon Cahoon 2092254f889dSBrendon Cahoon int D = 0; 20938fb181caSKrzysztof Parzyszek if (!TII->getIncrementValue(*BaseDef, D) && D >= 0) 2094254f889dSBrendon Cahoon return false; 2095254f889dSBrendon Cahoon 2096254f889dSBrendon Cahoon Delta = D; 2097254f889dSBrendon Cahoon return true; 2098254f889dSBrendon Cahoon } 2099254f889dSBrendon Cahoon 2100254f889dSBrendon Cahoon /// Check if we can change the instruction to use an offset value from the 2101254f889dSBrendon Cahoon /// previous iteration. If so, return true and set the base and offset values 2102254f889dSBrendon Cahoon /// so that we can rewrite the load, if necessary. 2103254f889dSBrendon Cahoon /// v1 = Phi(v0, v3) 2104254f889dSBrendon Cahoon /// v2 = load v1, 0 2105254f889dSBrendon Cahoon /// v3 = post_store v1, 4, x 2106254f889dSBrendon Cahoon /// This function enables the load to be rewritten as v2 = load v3, 4. 2107254f889dSBrendon Cahoon bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI, 2108254f889dSBrendon Cahoon unsigned &BasePos, 2109254f889dSBrendon Cahoon unsigned &OffsetPos, 2110254f889dSBrendon Cahoon unsigned &NewBase, 2111254f889dSBrendon Cahoon int64_t &Offset) { 2112254f889dSBrendon Cahoon // Get the load instruction. 21138fb181caSKrzysztof Parzyszek if (TII->isPostIncrement(*MI)) 2114254f889dSBrendon Cahoon return false; 2115254f889dSBrendon Cahoon unsigned BasePosLd, OffsetPosLd; 21168fb181caSKrzysztof Parzyszek if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd)) 2117254f889dSBrendon Cahoon return false; 21180c476111SDaniel Sanders Register BaseReg = MI->getOperand(BasePosLd).getReg(); 2119254f889dSBrendon Cahoon 2120254f889dSBrendon Cahoon // Look for the Phi instruction. 2121fdf9bf4fSJustin Bogner MachineRegisterInfo &MRI = MI->getMF()->getRegInfo(); 2122254f889dSBrendon Cahoon MachineInstr *Phi = MRI.getVRegDef(BaseReg); 2123254f889dSBrendon Cahoon if (!Phi || !Phi->isPHI()) 2124254f889dSBrendon Cahoon return false; 2125254f889dSBrendon Cahoon // Get the register defined in the loop block. 2126254f889dSBrendon Cahoon unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent()); 2127254f889dSBrendon Cahoon if (!PrevReg) 2128254f889dSBrendon Cahoon return false; 2129254f889dSBrendon Cahoon 2130254f889dSBrendon Cahoon // Check for the post-increment load/store instruction. 2131254f889dSBrendon Cahoon MachineInstr *PrevDef = MRI.getVRegDef(PrevReg); 2132254f889dSBrendon Cahoon if (!PrevDef || PrevDef == MI) 2133254f889dSBrendon Cahoon return false; 2134254f889dSBrendon Cahoon 21358fb181caSKrzysztof Parzyszek if (!TII->isPostIncrement(*PrevDef)) 2136254f889dSBrendon Cahoon return false; 2137254f889dSBrendon Cahoon 2138254f889dSBrendon Cahoon unsigned BasePos1 = 0, OffsetPos1 = 0; 21398fb181caSKrzysztof Parzyszek if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1)) 2140254f889dSBrendon Cahoon return false; 2141254f889dSBrendon Cahoon 214240df8a2bSKrzysztof Parzyszek // Make sure that the instructions do not access the same memory location in 214340df8a2bSKrzysztof Parzyszek // the next iteration. 2144254f889dSBrendon Cahoon int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm(); 2145254f889dSBrendon Cahoon int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm(); 214640df8a2bSKrzysztof Parzyszek MachineInstr *NewMI = MF.CloneMachineInstr(MI); 214740df8a2bSKrzysztof Parzyszek NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset); 214840df8a2bSKrzysztof Parzyszek bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef); 214940df8a2bSKrzysztof Parzyszek MF.DeleteMachineInstr(NewMI); 215040df8a2bSKrzysztof Parzyszek if (!Disjoint) 2151254f889dSBrendon Cahoon return false; 2152254f889dSBrendon Cahoon 2153254f889dSBrendon Cahoon // Set the return value once we determine that we return true. 2154254f889dSBrendon Cahoon BasePos = BasePosLd; 2155254f889dSBrendon Cahoon OffsetPos = OffsetPosLd; 2156254f889dSBrendon Cahoon NewBase = PrevReg; 2157254f889dSBrendon Cahoon Offset = StoreOffset; 2158254f889dSBrendon Cahoon return true; 2159254f889dSBrendon Cahoon } 2160254f889dSBrendon Cahoon 2161254f889dSBrendon Cahoon /// Apply changes to the instruction if needed. The changes are need 2162254f889dSBrendon Cahoon /// to improve the scheduling and depend up on the final schedule. 21638f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI, 21648f174ddeSKrzysztof Parzyszek SMSchedule &Schedule) { 2165254f889dSBrendon Cahoon SUnit *SU = getSUnit(MI); 2166254f889dSBrendon Cahoon DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = 2167254f889dSBrendon Cahoon InstrChanges.find(SU); 2168254f889dSBrendon Cahoon if (It != InstrChanges.end()) { 2169254f889dSBrendon Cahoon std::pair<unsigned, int64_t> RegAndOffset = It->second; 2170254f889dSBrendon Cahoon unsigned BasePos, OffsetPos; 21718fb181caSKrzysztof Parzyszek if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) 21728f174ddeSKrzysztof Parzyszek return; 21730c476111SDaniel Sanders Register BaseReg = MI->getOperand(BasePos).getReg(); 2174254f889dSBrendon Cahoon MachineInstr *LoopDef = findDefInLoop(BaseReg); 2175254f889dSBrendon Cahoon int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef)); 2176254f889dSBrendon Cahoon int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef)); 2177254f889dSBrendon Cahoon int BaseStageNum = Schedule.stageScheduled(SU); 2178254f889dSBrendon Cahoon int BaseCycleNum = Schedule.cycleScheduled(SU); 2179254f889dSBrendon Cahoon if (BaseStageNum < DefStageNum) { 2180254f889dSBrendon Cahoon MachineInstr *NewMI = MF.CloneMachineInstr(MI); 2181254f889dSBrendon Cahoon int OffsetDiff = DefStageNum - BaseStageNum; 2182254f889dSBrendon Cahoon if (DefCycleNum < BaseCycleNum) { 2183254f889dSBrendon Cahoon NewMI->getOperand(BasePos).setReg(RegAndOffset.first); 2184254f889dSBrendon Cahoon if (OffsetDiff > 0) 2185254f889dSBrendon Cahoon --OffsetDiff; 2186254f889dSBrendon Cahoon } 2187254f889dSBrendon Cahoon int64_t NewOffset = 2188254f889dSBrendon Cahoon MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff; 2189254f889dSBrendon Cahoon NewMI->getOperand(OffsetPos).setImm(NewOffset); 2190254f889dSBrendon Cahoon SU->setInstr(NewMI); 2191254f889dSBrendon Cahoon MISUnitMap[NewMI] = SU; 2192790a779fSJames Molloy NewMIs[MI] = NewMI; 2193254f889dSBrendon Cahoon } 2194254f889dSBrendon Cahoon } 2195254f889dSBrendon Cahoon } 2196254f889dSBrendon Cahoon 2197790a779fSJames Molloy /// Return the instruction in the loop that defines the register. 2198790a779fSJames Molloy /// If the definition is a Phi, then follow the Phi operand to 2199790a779fSJames Molloy /// the instruction in the loop. 2200790a779fSJames Molloy MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) { 2201790a779fSJames Molloy SmallPtrSet<MachineInstr *, 8> Visited; 2202790a779fSJames Molloy MachineInstr *Def = MRI.getVRegDef(Reg); 2203790a779fSJames Molloy while (Def->isPHI()) { 2204790a779fSJames Molloy if (!Visited.insert(Def).second) 2205790a779fSJames Molloy break; 2206790a779fSJames Molloy for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) 2207790a779fSJames Molloy if (Def->getOperand(i + 1).getMBB() == BB) { 2208790a779fSJames Molloy Def = MRI.getVRegDef(Def->getOperand(i).getReg()); 2209790a779fSJames Molloy break; 2210790a779fSJames Molloy } 2211790a779fSJames Molloy } 2212790a779fSJames Molloy return Def; 2213790a779fSJames Molloy } 2214790a779fSJames Molloy 22158e1363dfSKrzysztof Parzyszek /// Return true for an order or output dependence that is loop carried 22168e1363dfSKrzysztof Parzyszek /// potentially. A dependence is loop carried if the destination defines a valu 22178e1363dfSKrzysztof Parzyszek /// that may be used or defined by the source in a subsequent iteration. 22188e1363dfSKrzysztof Parzyszek bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep, 2219254f889dSBrendon Cahoon bool isSucc) { 22208e1363dfSKrzysztof Parzyszek if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) || 22218e1363dfSKrzysztof Parzyszek Dep.isArtificial()) 2222254f889dSBrendon Cahoon return false; 2223254f889dSBrendon Cahoon 2224254f889dSBrendon Cahoon if (!SwpPruneLoopCarried) 2225254f889dSBrendon Cahoon return true; 2226254f889dSBrendon Cahoon 22278e1363dfSKrzysztof Parzyszek if (Dep.getKind() == SDep::Output) 22288e1363dfSKrzysztof Parzyszek return true; 22298e1363dfSKrzysztof Parzyszek 2230254f889dSBrendon Cahoon MachineInstr *SI = Source->getInstr(); 2231254f889dSBrendon Cahoon MachineInstr *DI = Dep.getSUnit()->getInstr(); 2232254f889dSBrendon Cahoon if (!isSucc) 2233254f889dSBrendon Cahoon std::swap(SI, DI); 2234254f889dSBrendon Cahoon assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI."); 2235254f889dSBrendon Cahoon 2236254f889dSBrendon Cahoon // Assume ordered loads and stores may have a loop carried dependence. 2237254f889dSBrendon Cahoon if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() || 22386c5d5ce5SUlrich Weigand SI->mayRaiseFPException() || DI->mayRaiseFPException() || 2239254f889dSBrendon Cahoon SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef()) 2240254f889dSBrendon Cahoon return true; 2241254f889dSBrendon Cahoon 2242254f889dSBrendon Cahoon // Only chain dependences between a load and store can be loop carried. 2243254f889dSBrendon Cahoon if (!DI->mayStore() || !SI->mayLoad()) 2244254f889dSBrendon Cahoon return false; 2245254f889dSBrendon Cahoon 2246254f889dSBrendon Cahoon unsigned DeltaS, DeltaD; 2247254f889dSBrendon Cahoon if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD)) 2248254f889dSBrendon Cahoon return true; 2249254f889dSBrendon Cahoon 2250238c9d63SBjorn Pettersson const MachineOperand *BaseOpS, *BaseOpD; 2251254f889dSBrendon Cahoon int64_t OffsetS, OffsetD; 22528fbc9258SSander de Smalen bool OffsetSIsScalable, OffsetDIsScalable; 2253254f889dSBrendon Cahoon const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 22548fbc9258SSander de Smalen if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable, 22558fbc9258SSander de Smalen TRI) || 22568fbc9258SSander de Smalen !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable, 22578fbc9258SSander de Smalen TRI)) 2258254f889dSBrendon Cahoon return true; 2259254f889dSBrendon Cahoon 22608fbc9258SSander de Smalen assert(!OffsetSIsScalable && !OffsetDIsScalable && 22618fbc9258SSander de Smalen "Expected offsets to be byte offsets"); 22628fbc9258SSander de Smalen 2263d7eebd6dSFrancis Visoiu Mistrih if (!BaseOpS->isIdenticalTo(*BaseOpD)) 2264254f889dSBrendon Cahoon return true; 2265254f889dSBrendon Cahoon 22668c07d0c4SKrzysztof Parzyszek // Check that the base register is incremented by a constant value for each 22678c07d0c4SKrzysztof Parzyszek // iteration. 2268d7eebd6dSFrancis Visoiu Mistrih MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg()); 22698c07d0c4SKrzysztof Parzyszek if (!Def || !Def->isPHI()) 22708c07d0c4SKrzysztof Parzyszek return true; 22718c07d0c4SKrzysztof Parzyszek unsigned InitVal = 0; 22728c07d0c4SKrzysztof Parzyszek unsigned LoopVal = 0; 22738c07d0c4SKrzysztof Parzyszek getPhiRegs(*Def, BB, InitVal, LoopVal); 22748c07d0c4SKrzysztof Parzyszek MachineInstr *LoopDef = MRI.getVRegDef(LoopVal); 22758c07d0c4SKrzysztof Parzyszek int D = 0; 22768c07d0c4SKrzysztof Parzyszek if (!LoopDef || !TII->getIncrementValue(*LoopDef, D)) 22778c07d0c4SKrzysztof Parzyszek return true; 22788c07d0c4SKrzysztof Parzyszek 2279254f889dSBrendon Cahoon uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize(); 2280254f889dSBrendon Cahoon uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize(); 2281254f889dSBrendon Cahoon 2282254f889dSBrendon Cahoon // This is the main test, which checks the offset values and the loop 2283254f889dSBrendon Cahoon // increment value to determine if the accesses may be loop carried. 228457c3d4beSBrendon Cahoon if (AccessSizeS == MemoryLocation::UnknownSize || 228557c3d4beSBrendon Cahoon AccessSizeD == MemoryLocation::UnknownSize) 2286254f889dSBrendon Cahoon return true; 228757c3d4beSBrendon Cahoon 228857c3d4beSBrendon Cahoon if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD) 228957c3d4beSBrendon Cahoon return true; 229057c3d4beSBrendon Cahoon 229157c3d4beSBrendon Cahoon return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD); 2292254f889dSBrendon Cahoon } 2293254f889dSBrendon Cahoon 229488391248SKrzysztof Parzyszek void SwingSchedulerDAG::postprocessDAG() { 229588391248SKrzysztof Parzyszek for (auto &M : Mutations) 229688391248SKrzysztof Parzyszek M->apply(this); 229788391248SKrzysztof Parzyszek } 229888391248SKrzysztof Parzyszek 2299254f889dSBrendon Cahoon /// Try to schedule the node at the specified StartCycle and continue 2300254f889dSBrendon Cahoon /// until the node is schedule or the EndCycle is reached. This function 2301254f889dSBrendon Cahoon /// returns true if the node is scheduled. This routine may search either 2302254f889dSBrendon Cahoon /// forward or backward for a place to insert the instruction based upon 2303254f889dSBrendon Cahoon /// the relative values of StartCycle and EndCycle. 2304254f889dSBrendon Cahoon bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) { 2305254f889dSBrendon Cahoon bool forward = true; 230618e7bf5cSJinsong Ji LLVM_DEBUG({ 230718e7bf5cSJinsong Ji dbgs() << "Trying to insert node between " << StartCycle << " and " 230818e7bf5cSJinsong Ji << EndCycle << " II: " << II << "\n"; 230918e7bf5cSJinsong Ji }); 2310254f889dSBrendon Cahoon if (StartCycle > EndCycle) 2311254f889dSBrendon Cahoon forward = false; 2312254f889dSBrendon Cahoon 2313254f889dSBrendon Cahoon // The terminating condition depends on the direction. 2314254f889dSBrendon Cahoon int termCycle = forward ? EndCycle + 1 : EndCycle - 1; 2315254f889dSBrendon Cahoon for (int curCycle = StartCycle; curCycle != termCycle; 2316254f889dSBrendon Cahoon forward ? ++curCycle : --curCycle) { 2317254f889dSBrendon Cahoon 2318f6cb3bcbSJinsong Ji // Add the already scheduled instructions at the specified cycle to the 2319f6cb3bcbSJinsong Ji // DFA. 2320f6cb3bcbSJinsong Ji ProcItinResources.clearResources(); 2321254f889dSBrendon Cahoon for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II); 2322254f889dSBrendon Cahoon checkCycle <= LastCycle; checkCycle += II) { 2323254f889dSBrendon Cahoon std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle]; 2324254f889dSBrendon Cahoon 2325254f889dSBrendon Cahoon for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(), 2326254f889dSBrendon Cahoon E = cycleInstrs.end(); 2327254f889dSBrendon Cahoon I != E; ++I) { 2328254f889dSBrendon Cahoon if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode())) 2329254f889dSBrendon Cahoon continue; 2330f6cb3bcbSJinsong Ji assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) && 2331254f889dSBrendon Cahoon "These instructions have already been scheduled."); 2332f6cb3bcbSJinsong Ji ProcItinResources.reserveResources(*(*I)->getInstr()); 2333254f889dSBrendon Cahoon } 2334254f889dSBrendon Cahoon } 2335254f889dSBrendon Cahoon if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) || 2336f6cb3bcbSJinsong Ji ProcItinResources.canReserveResources(*SU->getInstr())) { 2337d34e60caSNicola Zaghen LLVM_DEBUG({ 2338254f889dSBrendon Cahoon dbgs() << "\tinsert at cycle " << curCycle << " "; 2339254f889dSBrendon Cahoon SU->getInstr()->dump(); 2340254f889dSBrendon Cahoon }); 2341254f889dSBrendon Cahoon 2342254f889dSBrendon Cahoon ScheduledInstrs[curCycle].push_back(SU); 2343254f889dSBrendon Cahoon InstrToCycle.insert(std::make_pair(SU, curCycle)); 2344254f889dSBrendon Cahoon if (curCycle > LastCycle) 2345254f889dSBrendon Cahoon LastCycle = curCycle; 2346254f889dSBrendon Cahoon if (curCycle < FirstCycle) 2347254f889dSBrendon Cahoon FirstCycle = curCycle; 2348254f889dSBrendon Cahoon return true; 2349254f889dSBrendon Cahoon } 2350d34e60caSNicola Zaghen LLVM_DEBUG({ 2351254f889dSBrendon Cahoon dbgs() << "\tfailed to insert at cycle " << curCycle << " "; 2352254f889dSBrendon Cahoon SU->getInstr()->dump(); 2353254f889dSBrendon Cahoon }); 2354254f889dSBrendon Cahoon } 2355254f889dSBrendon Cahoon return false; 2356254f889dSBrendon Cahoon } 2357254f889dSBrendon Cahoon 2358254f889dSBrendon Cahoon // Return the cycle of the earliest scheduled instruction in the chain. 2359254f889dSBrendon Cahoon int SMSchedule::earliestCycleInChain(const SDep &Dep) { 2360254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 2361254f889dSBrendon Cahoon SmallVector<SDep, 8> Worklist; 2362254f889dSBrendon Cahoon Worklist.push_back(Dep); 2363254f889dSBrendon Cahoon int EarlyCycle = INT_MAX; 2364254f889dSBrendon Cahoon while (!Worklist.empty()) { 2365254f889dSBrendon Cahoon const SDep &Cur = Worklist.pop_back_val(); 2366254f889dSBrendon Cahoon SUnit *PrevSU = Cur.getSUnit(); 2367254f889dSBrendon Cahoon if (Visited.count(PrevSU)) 2368254f889dSBrendon Cahoon continue; 2369254f889dSBrendon Cahoon std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU); 2370254f889dSBrendon Cahoon if (it == InstrToCycle.end()) 2371254f889dSBrendon Cahoon continue; 2372254f889dSBrendon Cahoon EarlyCycle = std::min(EarlyCycle, it->second); 2373254f889dSBrendon Cahoon for (const auto &PI : PrevSU->Preds) 23744a6ebc03SLama if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output) 2375254f889dSBrendon Cahoon Worklist.push_back(PI); 2376254f889dSBrendon Cahoon Visited.insert(PrevSU); 2377254f889dSBrendon Cahoon } 2378254f889dSBrendon Cahoon return EarlyCycle; 2379254f889dSBrendon Cahoon } 2380254f889dSBrendon Cahoon 2381254f889dSBrendon Cahoon // Return the cycle of the latest scheduled instruction in the chain. 2382254f889dSBrendon Cahoon int SMSchedule::latestCycleInChain(const SDep &Dep) { 2383254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 2384254f889dSBrendon Cahoon SmallVector<SDep, 8> Worklist; 2385254f889dSBrendon Cahoon Worklist.push_back(Dep); 2386254f889dSBrendon Cahoon int LateCycle = INT_MIN; 2387254f889dSBrendon Cahoon while (!Worklist.empty()) { 2388254f889dSBrendon Cahoon const SDep &Cur = Worklist.pop_back_val(); 2389254f889dSBrendon Cahoon SUnit *SuccSU = Cur.getSUnit(); 2390254f889dSBrendon Cahoon if (Visited.count(SuccSU)) 2391254f889dSBrendon Cahoon continue; 2392254f889dSBrendon Cahoon std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU); 2393254f889dSBrendon Cahoon if (it == InstrToCycle.end()) 2394254f889dSBrendon Cahoon continue; 2395254f889dSBrendon Cahoon LateCycle = std::max(LateCycle, it->second); 2396254f889dSBrendon Cahoon for (const auto &SI : SuccSU->Succs) 23974a6ebc03SLama if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output) 2398254f889dSBrendon Cahoon Worklist.push_back(SI); 2399254f889dSBrendon Cahoon Visited.insert(SuccSU); 2400254f889dSBrendon Cahoon } 2401254f889dSBrendon Cahoon return LateCycle; 2402254f889dSBrendon Cahoon } 2403254f889dSBrendon Cahoon 2404254f889dSBrendon Cahoon /// If an instruction has a use that spans multiple iterations, then 2405254f889dSBrendon Cahoon /// return true. These instructions are characterized by having a back-ege 2406254f889dSBrendon Cahoon /// to a Phi, which contains a reference to another Phi. 2407254f889dSBrendon Cahoon static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) { 2408254f889dSBrendon Cahoon for (auto &P : SU->Preds) 2409254f889dSBrendon Cahoon if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI()) 2410254f889dSBrendon Cahoon for (auto &S : P.getSUnit()->Succs) 2411b9b75b8cSKrzysztof Parzyszek if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI()) 2412254f889dSBrendon Cahoon return P.getSUnit(); 2413254f889dSBrendon Cahoon return nullptr; 2414254f889dSBrendon Cahoon } 2415254f889dSBrendon Cahoon 2416254f889dSBrendon Cahoon /// Compute the scheduling start slot for the instruction. The start slot 2417254f889dSBrendon Cahoon /// depends on any predecessor or successor nodes scheduled already. 2418254f889dSBrendon Cahoon void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart, 2419254f889dSBrendon Cahoon int *MinEnd, int *MaxStart, int II, 2420254f889dSBrendon Cahoon SwingSchedulerDAG *DAG) { 2421254f889dSBrendon Cahoon // Iterate over each instruction that has been scheduled already. The start 2422c73b6d6bSHiroshi Inoue // slot computation depends on whether the previously scheduled instruction 2423254f889dSBrendon Cahoon // is a predecessor or successor of the specified instruction. 2424254f889dSBrendon Cahoon for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) { 2425254f889dSBrendon Cahoon 2426254f889dSBrendon Cahoon // Iterate over each instruction in the current cycle. 2427254f889dSBrendon Cahoon for (SUnit *I : getInstructions(cycle)) { 2428254f889dSBrendon Cahoon // Because we're processing a DAG for the dependences, we recognize 2429254f889dSBrendon Cahoon // the back-edge in recurrences by anti dependences. 2430254f889dSBrendon Cahoon for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) { 2431254f889dSBrendon Cahoon const SDep &Dep = SU->Preds[i]; 2432254f889dSBrendon Cahoon if (Dep.getSUnit() == I) { 2433254f889dSBrendon Cahoon if (!DAG->isBackedge(SU, Dep)) { 2434c715a5d2SKrzysztof Parzyszek int EarlyStart = cycle + Dep.getLatency() - 2435254f889dSBrendon Cahoon DAG->getDistance(Dep.getSUnit(), SU, Dep) * II; 2436254f889dSBrendon Cahoon *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart); 24378e1363dfSKrzysztof Parzyszek if (DAG->isLoopCarriedDep(SU, Dep, false)) { 2438254f889dSBrendon Cahoon int End = earliestCycleInChain(Dep) + (II - 1); 2439254f889dSBrendon Cahoon *MinEnd = std::min(*MinEnd, End); 2440254f889dSBrendon Cahoon } 2441254f889dSBrendon Cahoon } else { 2442c715a5d2SKrzysztof Parzyszek int LateStart = cycle - Dep.getLatency() + 2443254f889dSBrendon Cahoon DAG->getDistance(SU, Dep.getSUnit(), Dep) * II; 2444254f889dSBrendon Cahoon *MinLateStart = std::min(*MinLateStart, LateStart); 2445254f889dSBrendon Cahoon } 2446254f889dSBrendon Cahoon } 2447254f889dSBrendon Cahoon // For instruction that requires multiple iterations, make sure that 2448254f889dSBrendon Cahoon // the dependent instruction is not scheduled past the definition. 2449254f889dSBrendon Cahoon SUnit *BE = multipleIterations(I, DAG); 2450254f889dSBrendon Cahoon if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() && 2451254f889dSBrendon Cahoon !SU->isPred(I)) 2452254f889dSBrendon Cahoon *MinLateStart = std::min(*MinLateStart, cycle); 2453254f889dSBrendon Cahoon } 2454a2122044SKrzysztof Parzyszek for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) { 2455254f889dSBrendon Cahoon if (SU->Succs[i].getSUnit() == I) { 2456254f889dSBrendon Cahoon const SDep &Dep = SU->Succs[i]; 2457254f889dSBrendon Cahoon if (!DAG->isBackedge(SU, Dep)) { 2458c715a5d2SKrzysztof Parzyszek int LateStart = cycle - Dep.getLatency() + 2459254f889dSBrendon Cahoon DAG->getDistance(SU, Dep.getSUnit(), Dep) * II; 2460254f889dSBrendon Cahoon *MinLateStart = std::min(*MinLateStart, LateStart); 24618e1363dfSKrzysztof Parzyszek if (DAG->isLoopCarriedDep(SU, Dep)) { 2462254f889dSBrendon Cahoon int Start = latestCycleInChain(Dep) + 1 - II; 2463254f889dSBrendon Cahoon *MaxStart = std::max(*MaxStart, Start); 2464254f889dSBrendon Cahoon } 2465254f889dSBrendon Cahoon } else { 2466c715a5d2SKrzysztof Parzyszek int EarlyStart = cycle + Dep.getLatency() - 2467254f889dSBrendon Cahoon DAG->getDistance(Dep.getSUnit(), SU, Dep) * II; 2468254f889dSBrendon Cahoon *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart); 2469254f889dSBrendon Cahoon } 2470254f889dSBrendon Cahoon } 2471254f889dSBrendon Cahoon } 2472254f889dSBrendon Cahoon } 2473254f889dSBrendon Cahoon } 2474a2122044SKrzysztof Parzyszek } 2475254f889dSBrendon Cahoon 2476254f889dSBrendon Cahoon /// Order the instructions within a cycle so that the definitions occur 2477254f889dSBrendon Cahoon /// before the uses. Returns true if the instruction is added to the start 2478254f889dSBrendon Cahoon /// of the list, or false if added to the end. 2479f13bbf1dSKrzysztof Parzyszek void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU, 2480254f889dSBrendon Cahoon std::deque<SUnit *> &Insts) { 2481254f889dSBrendon Cahoon MachineInstr *MI = SU->getInstr(); 2482254f889dSBrendon Cahoon bool OrderBeforeUse = false; 2483254f889dSBrendon Cahoon bool OrderAfterDef = false; 2484254f889dSBrendon Cahoon bool OrderBeforeDef = false; 2485254f889dSBrendon Cahoon unsigned MoveDef = 0; 2486254f889dSBrendon Cahoon unsigned MoveUse = 0; 2487254f889dSBrendon Cahoon int StageInst1 = stageScheduled(SU); 2488254f889dSBrendon Cahoon 2489254f889dSBrendon Cahoon unsigned Pos = 0; 2490254f889dSBrendon Cahoon for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E; 2491254f889dSBrendon Cahoon ++I, ++Pos) { 2492254f889dSBrendon Cahoon for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { 2493254f889dSBrendon Cahoon MachineOperand &MO = MI->getOperand(i); 24942bea69bfSDaniel Sanders if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg())) 2495254f889dSBrendon Cahoon continue; 2496f13bbf1dSKrzysztof Parzyszek 24970c476111SDaniel Sanders Register Reg = MO.getReg(); 2498254f889dSBrendon Cahoon unsigned BasePos, OffsetPos; 24998fb181caSKrzysztof Parzyszek if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) 2500254f889dSBrendon Cahoon if (MI->getOperand(BasePos).getReg() == Reg) 2501254f889dSBrendon Cahoon if (unsigned NewReg = SSD->getInstrBaseReg(SU)) 2502254f889dSBrendon Cahoon Reg = NewReg; 2503254f889dSBrendon Cahoon bool Reads, Writes; 2504254f889dSBrendon Cahoon std::tie(Reads, Writes) = 2505254f889dSBrendon Cahoon (*I)->getInstr()->readsWritesVirtualRegister(Reg); 2506254f889dSBrendon Cahoon if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) { 2507254f889dSBrendon Cahoon OrderBeforeUse = true; 2508f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 2509254f889dSBrendon Cahoon MoveUse = Pos; 2510254f889dSBrendon Cahoon } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) { 2511254f889dSBrendon Cahoon // Add the instruction after the scheduled instruction. 2512254f889dSBrendon Cahoon OrderAfterDef = true; 2513254f889dSBrendon Cahoon MoveDef = Pos; 2514254f889dSBrendon Cahoon } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) { 2515254f889dSBrendon Cahoon if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) { 2516254f889dSBrendon Cahoon OrderBeforeUse = true; 2517f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 2518254f889dSBrendon Cahoon MoveUse = Pos; 2519254f889dSBrendon Cahoon } else { 2520254f889dSBrendon Cahoon OrderAfterDef = true; 2521254f889dSBrendon Cahoon MoveDef = Pos; 2522254f889dSBrendon Cahoon } 2523254f889dSBrendon Cahoon } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) { 2524254f889dSBrendon Cahoon OrderBeforeUse = true; 2525f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 2526254f889dSBrendon Cahoon MoveUse = Pos; 2527254f889dSBrendon Cahoon if (MoveUse != 0) { 2528254f889dSBrendon Cahoon OrderAfterDef = true; 2529254f889dSBrendon Cahoon MoveDef = Pos - 1; 2530254f889dSBrendon Cahoon } 2531254f889dSBrendon Cahoon } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) { 2532254f889dSBrendon Cahoon // Add the instruction before the scheduled instruction. 2533254f889dSBrendon Cahoon OrderBeforeUse = true; 2534f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 2535254f889dSBrendon Cahoon MoveUse = Pos; 2536254f889dSBrendon Cahoon } else if (MO.isUse() && stageScheduled(*I) == StageInst1 && 2537254f889dSBrendon Cahoon isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) { 2538f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) { 2539254f889dSBrendon Cahoon OrderBeforeDef = true; 2540254f889dSBrendon Cahoon MoveUse = Pos; 2541254f889dSBrendon Cahoon } 2542254f889dSBrendon Cahoon } 2543f13bbf1dSKrzysztof Parzyszek } 2544254f889dSBrendon Cahoon // Check for order dependences between instructions. Make sure the source 2545254f889dSBrendon Cahoon // is ordered before the destination. 25468e1363dfSKrzysztof Parzyszek for (auto &S : SU->Succs) { 25478e1363dfSKrzysztof Parzyszek if (S.getSUnit() != *I) 25488e1363dfSKrzysztof Parzyszek continue; 25498e1363dfSKrzysztof Parzyszek if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) { 2550254f889dSBrendon Cahoon OrderBeforeUse = true; 25518e1363dfSKrzysztof Parzyszek if (Pos < MoveUse) 2552254f889dSBrendon Cahoon MoveUse = Pos; 2553254f889dSBrendon Cahoon } 255495770866SJinsong Ji // We did not handle HW dependences in previous for loop, 255595770866SJinsong Ji // and we normally set Latency = 0 for Anti deps, 255695770866SJinsong Ji // so may have nodes in same cycle with Anti denpendent on HW regs. 255795770866SJinsong Ji else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) { 255895770866SJinsong Ji OrderBeforeUse = true; 255995770866SJinsong Ji if ((MoveUse == 0) || (Pos < MoveUse)) 256095770866SJinsong Ji MoveUse = Pos; 256195770866SJinsong Ji } 2562254f889dSBrendon Cahoon } 25638e1363dfSKrzysztof Parzyszek for (auto &P : SU->Preds) { 25648e1363dfSKrzysztof Parzyszek if (P.getSUnit() != *I) 25658e1363dfSKrzysztof Parzyszek continue; 25668e1363dfSKrzysztof Parzyszek if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) { 2567254f889dSBrendon Cahoon OrderAfterDef = true; 2568254f889dSBrendon Cahoon MoveDef = Pos; 2569254f889dSBrendon Cahoon } 2570254f889dSBrendon Cahoon } 2571254f889dSBrendon Cahoon } 2572254f889dSBrendon Cahoon 2573254f889dSBrendon Cahoon // A circular dependence. 2574254f889dSBrendon Cahoon if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef) 2575254f889dSBrendon Cahoon OrderBeforeUse = false; 2576254f889dSBrendon Cahoon 2577254f889dSBrendon Cahoon // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due 2578254f889dSBrendon Cahoon // to a loop-carried dependence. 2579254f889dSBrendon Cahoon if (OrderBeforeDef) 2580254f889dSBrendon Cahoon OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef); 2581254f889dSBrendon Cahoon 2582254f889dSBrendon Cahoon // The uncommon case when the instruction order needs to be updated because 2583254f889dSBrendon Cahoon // there is both a use and def. 2584254f889dSBrendon Cahoon if (OrderBeforeUse && OrderAfterDef) { 2585254f889dSBrendon Cahoon SUnit *UseSU = Insts.at(MoveUse); 2586254f889dSBrendon Cahoon SUnit *DefSU = Insts.at(MoveDef); 2587254f889dSBrendon Cahoon if (MoveUse > MoveDef) { 2588254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveUse); 2589254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveDef); 2590254f889dSBrendon Cahoon } else { 2591254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveDef); 2592254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveUse); 2593254f889dSBrendon Cahoon } 2594f13bbf1dSKrzysztof Parzyszek orderDependence(SSD, UseSU, Insts); 2595f13bbf1dSKrzysztof Parzyszek orderDependence(SSD, SU, Insts); 2596254f889dSBrendon Cahoon orderDependence(SSD, DefSU, Insts); 2597f13bbf1dSKrzysztof Parzyszek return; 2598254f889dSBrendon Cahoon } 2599254f889dSBrendon Cahoon // Put the new instruction first if there is a use in the list. Otherwise, 2600254f889dSBrendon Cahoon // put it at the end of the list. 2601254f889dSBrendon Cahoon if (OrderBeforeUse) 2602254f889dSBrendon Cahoon Insts.push_front(SU); 2603254f889dSBrendon Cahoon else 2604254f889dSBrendon Cahoon Insts.push_back(SU); 2605254f889dSBrendon Cahoon } 2606254f889dSBrendon Cahoon 2607254f889dSBrendon Cahoon /// Return true if the scheduled Phi has a loop carried operand. 2608254f889dSBrendon Cahoon bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) { 2609254f889dSBrendon Cahoon if (!Phi.isPHI()) 2610254f889dSBrendon Cahoon return false; 2611c73b6d6bSHiroshi Inoue assert(Phi.isPHI() && "Expecting a Phi."); 2612254f889dSBrendon Cahoon SUnit *DefSU = SSD->getSUnit(&Phi); 2613254f889dSBrendon Cahoon unsigned DefCycle = cycleScheduled(DefSU); 2614254f889dSBrendon Cahoon int DefStage = stageScheduled(DefSU); 2615254f889dSBrendon Cahoon 2616254f889dSBrendon Cahoon unsigned InitVal = 0; 2617254f889dSBrendon Cahoon unsigned LoopVal = 0; 2618254f889dSBrendon Cahoon getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal); 2619254f889dSBrendon Cahoon SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal)); 2620254f889dSBrendon Cahoon if (!UseSU) 2621254f889dSBrendon Cahoon return true; 2622254f889dSBrendon Cahoon if (UseSU->getInstr()->isPHI()) 2623254f889dSBrendon Cahoon return true; 2624254f889dSBrendon Cahoon unsigned LoopCycle = cycleScheduled(UseSU); 2625254f889dSBrendon Cahoon int LoopStage = stageScheduled(UseSU); 26263d8482a8SSimon Pilgrim return (LoopCycle > DefCycle) || (LoopStage <= DefStage); 2627254f889dSBrendon Cahoon } 2628254f889dSBrendon Cahoon 2629254f889dSBrendon Cahoon /// Return true if the instruction is a definition that is loop carried 2630254f889dSBrendon Cahoon /// and defines the use on the next iteration. 2631254f889dSBrendon Cahoon /// v1 = phi(v2, v3) 2632254f889dSBrendon Cahoon /// (Def) v3 = op v1 2633254f889dSBrendon Cahoon /// (MO) = v1 2634254f889dSBrendon Cahoon /// If MO appears before Def, then then v1 and v3 may get assigned to the same 2635254f889dSBrendon Cahoon /// register. 2636254f889dSBrendon Cahoon bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, 2637254f889dSBrendon Cahoon MachineInstr *Def, MachineOperand &MO) { 2638254f889dSBrendon Cahoon if (!MO.isReg()) 2639254f889dSBrendon Cahoon return false; 2640254f889dSBrendon Cahoon if (Def->isPHI()) 2641254f889dSBrendon Cahoon return false; 2642254f889dSBrendon Cahoon MachineInstr *Phi = MRI.getVRegDef(MO.getReg()); 2643254f889dSBrendon Cahoon if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent()) 2644254f889dSBrendon Cahoon return false; 2645254f889dSBrendon Cahoon if (!isLoopCarried(SSD, *Phi)) 2646254f889dSBrendon Cahoon return false; 2647254f889dSBrendon Cahoon unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent()); 2648254f889dSBrendon Cahoon for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) { 2649254f889dSBrendon Cahoon MachineOperand &DMO = Def->getOperand(i); 2650254f889dSBrendon Cahoon if (!DMO.isReg() || !DMO.isDef()) 2651254f889dSBrendon Cahoon continue; 2652254f889dSBrendon Cahoon if (DMO.getReg() == LoopReg) 2653254f889dSBrendon Cahoon return true; 2654254f889dSBrendon Cahoon } 2655254f889dSBrendon Cahoon return false; 2656254f889dSBrendon Cahoon } 2657254f889dSBrendon Cahoon 2658254f889dSBrendon Cahoon // Check if the generated schedule is valid. This function checks if 2659254f889dSBrendon Cahoon // an instruction that uses a physical register is scheduled in a 2660254f889dSBrendon Cahoon // different stage than the definition. The pipeliner does not handle 2661254f889dSBrendon Cahoon // physical register values that may cross a basic block boundary. 2662254f889dSBrendon Cahoon bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) { 2663254f889dSBrendon Cahoon for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) { 2664254f889dSBrendon Cahoon SUnit &SU = SSD->SUnits[i]; 2665254f889dSBrendon Cahoon if (!SU.hasPhysRegDefs) 2666254f889dSBrendon Cahoon continue; 2667254f889dSBrendon Cahoon int StageDef = stageScheduled(&SU); 2668254f889dSBrendon Cahoon assert(StageDef != -1 && "Instruction should have been scheduled."); 2669254f889dSBrendon Cahoon for (auto &SI : SU.Succs) 2670254f889dSBrendon Cahoon if (SI.isAssignedRegDep()) 26712bea69bfSDaniel Sanders if (Register::isPhysicalRegister(SI.getReg())) 2672254f889dSBrendon Cahoon if (stageScheduled(SI.getSUnit()) != StageDef) 2673254f889dSBrendon Cahoon return false; 2674254f889dSBrendon Cahoon } 2675254f889dSBrendon Cahoon return true; 2676254f889dSBrendon Cahoon } 2677254f889dSBrendon Cahoon 26784b8bcf00SRoorda, Jan-Willem /// A property of the node order in swing-modulo-scheduling is 26794b8bcf00SRoorda, Jan-Willem /// that for nodes outside circuits the following holds: 26804b8bcf00SRoorda, Jan-Willem /// none of them is scheduled after both a successor and a 26814b8bcf00SRoorda, Jan-Willem /// predecessor. 26824b8bcf00SRoorda, Jan-Willem /// The method below checks whether the property is met. 26834b8bcf00SRoorda, Jan-Willem /// If not, debug information is printed and statistics information updated. 26844b8bcf00SRoorda, Jan-Willem /// Note that we do not use an assert statement. 26854b8bcf00SRoorda, Jan-Willem /// The reason is that although an invalid node oder may prevent 26864b8bcf00SRoorda, Jan-Willem /// the pipeliner from finding a pipelined schedule for arbitrary II, 26874b8bcf00SRoorda, Jan-Willem /// it does not lead to the generation of incorrect code. 26884b8bcf00SRoorda, Jan-Willem void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const { 26894b8bcf00SRoorda, Jan-Willem 26904b8bcf00SRoorda, Jan-Willem // a sorted vector that maps each SUnit to its index in the NodeOrder 26914b8bcf00SRoorda, Jan-Willem typedef std::pair<SUnit *, unsigned> UnitIndex; 26924b8bcf00SRoorda, Jan-Willem std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0)); 26934b8bcf00SRoorda, Jan-Willem 26944b8bcf00SRoorda, Jan-Willem for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) 26954b8bcf00SRoorda, Jan-Willem Indices.push_back(std::make_pair(NodeOrder[i], i)); 26964b8bcf00SRoorda, Jan-Willem 26974b8bcf00SRoorda, Jan-Willem auto CompareKey = [](UnitIndex i1, UnitIndex i2) { 26984b8bcf00SRoorda, Jan-Willem return std::get<0>(i1) < std::get<0>(i2); 26994b8bcf00SRoorda, Jan-Willem }; 27004b8bcf00SRoorda, Jan-Willem 27014b8bcf00SRoorda, Jan-Willem // sort, so that we can perform a binary search 27020cac726aSFangrui Song llvm::sort(Indices, CompareKey); 27034b8bcf00SRoorda, Jan-Willem 27044b8bcf00SRoorda, Jan-Willem bool Valid = true; 2705febf70a9SDavid L Kreitzer (void)Valid; 27064b8bcf00SRoorda, Jan-Willem // for each SUnit in the NodeOrder, check whether 27074b8bcf00SRoorda, Jan-Willem // it appears after both a successor and a predecessor 27084b8bcf00SRoorda, Jan-Willem // of the SUnit. If this is the case, and the SUnit 27094b8bcf00SRoorda, Jan-Willem // is not part of circuit, then the NodeOrder is not 27104b8bcf00SRoorda, Jan-Willem // valid. 27114b8bcf00SRoorda, Jan-Willem for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) { 27124b8bcf00SRoorda, Jan-Willem SUnit *SU = NodeOrder[i]; 27134b8bcf00SRoorda, Jan-Willem unsigned Index = i; 27144b8bcf00SRoorda, Jan-Willem 27154b8bcf00SRoorda, Jan-Willem bool PredBefore = false; 27164b8bcf00SRoorda, Jan-Willem bool SuccBefore = false; 27174b8bcf00SRoorda, Jan-Willem 27184b8bcf00SRoorda, Jan-Willem SUnit *Succ; 27194b8bcf00SRoorda, Jan-Willem SUnit *Pred; 2720febf70a9SDavid L Kreitzer (void)Succ; 2721febf70a9SDavid L Kreitzer (void)Pred; 27224b8bcf00SRoorda, Jan-Willem 27234b8bcf00SRoorda, Jan-Willem for (SDep &PredEdge : SU->Preds) { 27244b8bcf00SRoorda, Jan-Willem SUnit *PredSU = PredEdge.getSUnit(); 2725dc8de603SFangrui Song unsigned PredIndex = std::get<1>( 2726dc8de603SFangrui Song *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey)); 27274b8bcf00SRoorda, Jan-Willem if (!PredSU->getInstr()->isPHI() && PredIndex < Index) { 27284b8bcf00SRoorda, Jan-Willem PredBefore = true; 27294b8bcf00SRoorda, Jan-Willem Pred = PredSU; 27304b8bcf00SRoorda, Jan-Willem break; 27314b8bcf00SRoorda, Jan-Willem } 27324b8bcf00SRoorda, Jan-Willem } 27334b8bcf00SRoorda, Jan-Willem 27344b8bcf00SRoorda, Jan-Willem for (SDep &SuccEdge : SU->Succs) { 27354b8bcf00SRoorda, Jan-Willem SUnit *SuccSU = SuccEdge.getSUnit(); 27361c884458SJinsong Ji // Do not process a boundary node, it was not included in NodeOrder, 27371c884458SJinsong Ji // hence not in Indices either, call to std::lower_bound() below will 27381c884458SJinsong Ji // return Indices.end(). 27391c884458SJinsong Ji if (SuccSU->isBoundaryNode()) 27401c884458SJinsong Ji continue; 2741dc8de603SFangrui Song unsigned SuccIndex = std::get<1>( 2742dc8de603SFangrui Song *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey)); 27434b8bcf00SRoorda, Jan-Willem if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) { 27444b8bcf00SRoorda, Jan-Willem SuccBefore = true; 27454b8bcf00SRoorda, Jan-Willem Succ = SuccSU; 27464b8bcf00SRoorda, Jan-Willem break; 27474b8bcf00SRoorda, Jan-Willem } 27484b8bcf00SRoorda, Jan-Willem } 27494b8bcf00SRoorda, Jan-Willem 27504b8bcf00SRoorda, Jan-Willem if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) { 27514b8bcf00SRoorda, Jan-Willem // instructions in circuits are allowed to be scheduled 27524b8bcf00SRoorda, Jan-Willem // after both a successor and predecessor. 2753dc8de603SFangrui Song bool InCircuit = llvm::any_of( 2754dc8de603SFangrui Song Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); }); 27554b8bcf00SRoorda, Jan-Willem if (InCircuit) 2756d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";); 27574b8bcf00SRoorda, Jan-Willem else { 27584b8bcf00SRoorda, Jan-Willem Valid = false; 27594b8bcf00SRoorda, Jan-Willem NumNodeOrderIssues++; 2760d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Predecessor ";); 27614b8bcf00SRoorda, Jan-Willem } 2762d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum 2763d34e60caSNicola Zaghen << " are scheduled before node " << SU->NodeNum 2764d34e60caSNicola Zaghen << "\n";); 27654b8bcf00SRoorda, Jan-Willem } 27664b8bcf00SRoorda, Jan-Willem } 27674b8bcf00SRoorda, Jan-Willem 2768d34e60caSNicola Zaghen LLVM_DEBUG({ 27694b8bcf00SRoorda, Jan-Willem if (!Valid) 27704b8bcf00SRoorda, Jan-Willem dbgs() << "Invalid node order found!\n"; 27714b8bcf00SRoorda, Jan-Willem }); 27724b8bcf00SRoorda, Jan-Willem } 27734b8bcf00SRoorda, Jan-Willem 27748f174ddeSKrzysztof Parzyszek /// Attempt to fix the degenerate cases when the instruction serialization 27758f174ddeSKrzysztof Parzyszek /// causes the register lifetimes to overlap. For example, 27768f174ddeSKrzysztof Parzyszek /// p' = store_pi(p, b) 27778f174ddeSKrzysztof Parzyszek /// = load p, offset 27788f174ddeSKrzysztof Parzyszek /// In this case p and p' overlap, which means that two registers are needed. 27798f174ddeSKrzysztof Parzyszek /// Instead, this function changes the load to use p' and updates the offset. 27808f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) { 27818f174ddeSKrzysztof Parzyszek unsigned OverlapReg = 0; 27828f174ddeSKrzysztof Parzyszek unsigned NewBaseReg = 0; 27838f174ddeSKrzysztof Parzyszek for (SUnit *SU : Instrs) { 27848f174ddeSKrzysztof Parzyszek MachineInstr *MI = SU->getInstr(); 27858f174ddeSKrzysztof Parzyszek for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { 27868f174ddeSKrzysztof Parzyszek const MachineOperand &MO = MI->getOperand(i); 27878f174ddeSKrzysztof Parzyszek // Look for an instruction that uses p. The instruction occurs in the 27888f174ddeSKrzysztof Parzyszek // same cycle but occurs later in the serialized order. 27898f174ddeSKrzysztof Parzyszek if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) { 27908f174ddeSKrzysztof Parzyszek // Check that the instruction appears in the InstrChanges structure, 27918f174ddeSKrzysztof Parzyszek // which contains instructions that can have the offset updated. 27928f174ddeSKrzysztof Parzyszek DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = 27938f174ddeSKrzysztof Parzyszek InstrChanges.find(SU); 27948f174ddeSKrzysztof Parzyszek if (It != InstrChanges.end()) { 27958f174ddeSKrzysztof Parzyszek unsigned BasePos, OffsetPos; 27968f174ddeSKrzysztof Parzyszek // Update the base register and adjust the offset. 27978f174ddeSKrzysztof Parzyszek if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) { 279812bdcab5SKrzysztof Parzyszek MachineInstr *NewMI = MF.CloneMachineInstr(MI); 279912bdcab5SKrzysztof Parzyszek NewMI->getOperand(BasePos).setReg(NewBaseReg); 280012bdcab5SKrzysztof Parzyszek int64_t NewOffset = 280112bdcab5SKrzysztof Parzyszek MI->getOperand(OffsetPos).getImm() - It->second.second; 280212bdcab5SKrzysztof Parzyszek NewMI->getOperand(OffsetPos).setImm(NewOffset); 280312bdcab5SKrzysztof Parzyszek SU->setInstr(NewMI); 280412bdcab5SKrzysztof Parzyszek MISUnitMap[NewMI] = SU; 2805790a779fSJames Molloy NewMIs[MI] = NewMI; 28068f174ddeSKrzysztof Parzyszek } 28078f174ddeSKrzysztof Parzyszek } 28088f174ddeSKrzysztof Parzyszek OverlapReg = 0; 28098f174ddeSKrzysztof Parzyszek NewBaseReg = 0; 28108f174ddeSKrzysztof Parzyszek break; 28118f174ddeSKrzysztof Parzyszek } 28128f174ddeSKrzysztof Parzyszek // Look for an instruction of the form p' = op(p), which uses and defines 28138f174ddeSKrzysztof Parzyszek // two virtual registers that get allocated to the same physical register. 28148f174ddeSKrzysztof Parzyszek unsigned TiedUseIdx = 0; 28158f174ddeSKrzysztof Parzyszek if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) { 28168f174ddeSKrzysztof Parzyszek // OverlapReg is p in the example above. 28178f174ddeSKrzysztof Parzyszek OverlapReg = MI->getOperand(TiedUseIdx).getReg(); 28188f174ddeSKrzysztof Parzyszek // NewBaseReg is p' in the example above. 28198f174ddeSKrzysztof Parzyszek NewBaseReg = MI->getOperand(i).getReg(); 28208f174ddeSKrzysztof Parzyszek break; 28218f174ddeSKrzysztof Parzyszek } 28228f174ddeSKrzysztof Parzyszek } 28238f174ddeSKrzysztof Parzyszek } 28248f174ddeSKrzysztof Parzyszek } 28258f174ddeSKrzysztof Parzyszek 2826254f889dSBrendon Cahoon /// After the schedule has been formed, call this function to combine 2827254f889dSBrendon Cahoon /// the instructions from the different stages/cycles. That is, this 2828254f889dSBrendon Cahoon /// function creates a schedule that represents a single iteration. 2829254f889dSBrendon Cahoon void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) { 2830254f889dSBrendon Cahoon // Move all instructions to the first stage from later stages. 2831254f889dSBrendon Cahoon for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) { 2832254f889dSBrendon Cahoon for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage; 2833254f889dSBrendon Cahoon ++stage) { 2834254f889dSBrendon Cahoon std::deque<SUnit *> &cycleInstrs = 2835254f889dSBrendon Cahoon ScheduledInstrs[cycle + (stage * InitiationInterval)]; 2836254f889dSBrendon Cahoon for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(), 2837254f889dSBrendon Cahoon E = cycleInstrs.rend(); 2838254f889dSBrendon Cahoon I != E; ++I) 2839254f889dSBrendon Cahoon ScheduledInstrs[cycle].push_front(*I); 2840254f889dSBrendon Cahoon } 2841254f889dSBrendon Cahoon } 2842254f889dSBrendon Cahoon 2843254f889dSBrendon Cahoon // Erase all the elements in the later stages. Only one iteration should 2844254f889dSBrendon Cahoon // remain in the scheduled list, and it contains all the instructions. 2845254f889dSBrendon Cahoon for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle) 2846254f889dSBrendon Cahoon ScheduledInstrs.erase(cycle); 2847254f889dSBrendon Cahoon 2848254f889dSBrendon Cahoon // Change the registers in instruction as specified in the InstrChanges 2849254f889dSBrendon Cahoon // map. We need to use the new registers to create the correct order. 2850254f889dSBrendon Cahoon for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) { 2851254f889dSBrendon Cahoon SUnit *SU = &SSD->SUnits[i]; 28528f174ddeSKrzysztof Parzyszek SSD->applyInstrChange(SU->getInstr(), *this); 2853254f889dSBrendon Cahoon } 2854254f889dSBrendon Cahoon 2855254f889dSBrendon Cahoon // Reorder the instructions in each cycle to fix and improve the 2856254f889dSBrendon Cahoon // generated code. 2857254f889dSBrendon Cahoon for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) { 2858254f889dSBrendon Cahoon std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle]; 2859f13bbf1dSKrzysztof Parzyszek std::deque<SUnit *> newOrderPhi; 2860254f889dSBrendon Cahoon for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) { 2861254f889dSBrendon Cahoon SUnit *SU = cycleInstrs[i]; 2862f13bbf1dSKrzysztof Parzyszek if (SU->getInstr()->isPHI()) 2863f13bbf1dSKrzysztof Parzyszek newOrderPhi.push_back(SU); 2864254f889dSBrendon Cahoon } 2865254f889dSBrendon Cahoon std::deque<SUnit *> newOrderI; 2866254f889dSBrendon Cahoon for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) { 2867254f889dSBrendon Cahoon SUnit *SU = cycleInstrs[i]; 2868f13bbf1dSKrzysztof Parzyszek if (!SU->getInstr()->isPHI()) 2869254f889dSBrendon Cahoon orderDependence(SSD, SU, newOrderI); 2870254f889dSBrendon Cahoon } 2871254f889dSBrendon Cahoon // Replace the old order with the new order. 2872f13bbf1dSKrzysztof Parzyszek cycleInstrs.swap(newOrderPhi); 2873254f889dSBrendon Cahoon cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end()); 28748f174ddeSKrzysztof Parzyszek SSD->fixupRegisterOverlaps(cycleInstrs); 2875254f889dSBrendon Cahoon } 2876254f889dSBrendon Cahoon 2877d34e60caSNicola Zaghen LLVM_DEBUG(dump();); 2878254f889dSBrendon Cahoon } 2879254f889dSBrendon Cahoon 2880fa2e3583SAdrian Prantl void NodeSet::print(raw_ostream &os) const { 2881fa2e3583SAdrian Prantl os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV 2882fa2e3583SAdrian Prantl << " depth " << MaxDepth << " col " << Colocate << "\n"; 2883fa2e3583SAdrian Prantl for (const auto &I : Nodes) 2884fa2e3583SAdrian Prantl os << " SU(" << I->NodeNum << ") " << *(I->getInstr()); 2885fa2e3583SAdrian Prantl os << "\n"; 2886fa2e3583SAdrian Prantl } 2887fa2e3583SAdrian Prantl 2888615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2889254f889dSBrendon Cahoon /// Print the schedule information to the given output. 2890254f889dSBrendon Cahoon void SMSchedule::print(raw_ostream &os) const { 2891254f889dSBrendon Cahoon // Iterate over each cycle. 2892254f889dSBrendon Cahoon for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) { 2893254f889dSBrendon Cahoon // Iterate over each instruction in the cycle. 2894254f889dSBrendon Cahoon const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle); 2895254f889dSBrendon Cahoon for (SUnit *CI : cycleInstrs->second) { 2896254f889dSBrendon Cahoon os << "cycle " << cycle << " (" << stageScheduled(CI) << ") "; 2897254f889dSBrendon Cahoon os << "(" << CI->NodeNum << ") "; 2898254f889dSBrendon Cahoon CI->getInstr()->print(os); 2899254f889dSBrendon Cahoon os << "\n"; 2900254f889dSBrendon Cahoon } 2901254f889dSBrendon Cahoon } 2902254f889dSBrendon Cahoon } 2903254f889dSBrendon Cahoon 2904254f889dSBrendon Cahoon /// Utility function used for debugging to print the schedule. 29058c209aa8SMatthias Braun LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); } 2906fa2e3583SAdrian Prantl LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); } 2907fa2e3583SAdrian Prantl 29088c209aa8SMatthias Braun #endif 2909fa2e3583SAdrian Prantl 2910f6cb3bcbSJinsong Ji void ResourceManager::initProcResourceVectors( 2911f6cb3bcbSJinsong Ji const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) { 2912f6cb3bcbSJinsong Ji unsigned ProcResourceID = 0; 2913fa2e3583SAdrian Prantl 2914f6cb3bcbSJinsong Ji // We currently limit the resource kinds to 64 and below so that we can use 2915f6cb3bcbSJinsong Ji // uint64_t for Masks 2916f6cb3bcbSJinsong Ji assert(SM.getNumProcResourceKinds() < 64 && 2917f6cb3bcbSJinsong Ji "Too many kinds of resources, unsupported"); 2918f6cb3bcbSJinsong Ji // Create a unique bitmask for every processor resource unit. 2919f6cb3bcbSJinsong Ji // Skip resource at index 0, since it always references 'InvalidUnit'. 2920f6cb3bcbSJinsong Ji Masks.resize(SM.getNumProcResourceKinds()); 2921f6cb3bcbSJinsong Ji for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) { 2922f6cb3bcbSJinsong Ji const MCProcResourceDesc &Desc = *SM.getProcResource(I); 2923f6cb3bcbSJinsong Ji if (Desc.SubUnitsIdxBegin) 2924f6cb3bcbSJinsong Ji continue; 2925f6cb3bcbSJinsong Ji Masks[I] = 1ULL << ProcResourceID; 2926f6cb3bcbSJinsong Ji ProcResourceID++; 2927f6cb3bcbSJinsong Ji } 2928f6cb3bcbSJinsong Ji // Create a unique bitmask for every processor resource group. 2929f6cb3bcbSJinsong Ji for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) { 2930f6cb3bcbSJinsong Ji const MCProcResourceDesc &Desc = *SM.getProcResource(I); 2931f6cb3bcbSJinsong Ji if (!Desc.SubUnitsIdxBegin) 2932f6cb3bcbSJinsong Ji continue; 2933f6cb3bcbSJinsong Ji Masks[I] = 1ULL << ProcResourceID; 2934f6cb3bcbSJinsong Ji for (unsigned U = 0; U < Desc.NumUnits; ++U) 2935f6cb3bcbSJinsong Ji Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]]; 2936f6cb3bcbSJinsong Ji ProcResourceID++; 2937f6cb3bcbSJinsong Ji } 2938f6cb3bcbSJinsong Ji LLVM_DEBUG({ 2939ba43840bSJinsong Ji if (SwpShowResMask) { 2940f6cb3bcbSJinsong Ji dbgs() << "ProcResourceDesc:\n"; 2941f6cb3bcbSJinsong Ji for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) { 2942f6cb3bcbSJinsong Ji const MCProcResourceDesc *ProcResource = SM.getProcResource(I); 2943f6cb3bcbSJinsong Ji dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n", 2944ba43840bSJinsong Ji ProcResource->Name, I, Masks[I], 2945ba43840bSJinsong Ji ProcResource->NumUnits); 2946f6cb3bcbSJinsong Ji } 2947f6cb3bcbSJinsong Ji dbgs() << " -----------------\n"; 2948ba43840bSJinsong Ji } 2949f6cb3bcbSJinsong Ji }); 2950f6cb3bcbSJinsong Ji } 2951f6cb3bcbSJinsong Ji 2952f6cb3bcbSJinsong Ji bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const { 2953f6cb3bcbSJinsong Ji 2954ba43840bSJinsong Ji LLVM_DEBUG({ 2955ba43840bSJinsong Ji if (SwpDebugResource) 2956ba43840bSJinsong Ji dbgs() << "canReserveResources:\n"; 2957ba43840bSJinsong Ji }); 2958f6cb3bcbSJinsong Ji if (UseDFA) 2959f6cb3bcbSJinsong Ji return DFAResources->canReserveResources(MID); 2960f6cb3bcbSJinsong Ji 2961f6cb3bcbSJinsong Ji unsigned InsnClass = MID->getSchedClass(); 2962f6cb3bcbSJinsong Ji const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass); 2963f6cb3bcbSJinsong Ji if (!SCDesc->isValid()) { 2964f6cb3bcbSJinsong Ji LLVM_DEBUG({ 2965f6cb3bcbSJinsong Ji dbgs() << "No valid Schedule Class Desc for schedClass!\n"; 2966f6cb3bcbSJinsong Ji dbgs() << "isPseduo:" << MID->isPseudo() << "\n"; 2967f6cb3bcbSJinsong Ji }); 2968f6cb3bcbSJinsong Ji return true; 2969f6cb3bcbSJinsong Ji } 2970f6cb3bcbSJinsong Ji 2971f6cb3bcbSJinsong Ji const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc); 2972f6cb3bcbSJinsong Ji const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc); 2973f6cb3bcbSJinsong Ji for (; I != E; ++I) { 2974f6cb3bcbSJinsong Ji if (!I->Cycles) 2975f6cb3bcbSJinsong Ji continue; 2976f6cb3bcbSJinsong Ji const MCProcResourceDesc *ProcResource = 2977f6cb3bcbSJinsong Ji SM.getProcResource(I->ProcResourceIdx); 2978f6cb3bcbSJinsong Ji unsigned NumUnits = ProcResource->NumUnits; 2979f6cb3bcbSJinsong Ji LLVM_DEBUG({ 2980ba43840bSJinsong Ji if (SwpDebugResource) 2981f6cb3bcbSJinsong Ji dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n", 2982f6cb3bcbSJinsong Ji ProcResource->Name, I->ProcResourceIdx, 2983f6cb3bcbSJinsong Ji ProcResourceCount[I->ProcResourceIdx], NumUnits, 2984f6cb3bcbSJinsong Ji I->Cycles); 2985f6cb3bcbSJinsong Ji }); 2986f6cb3bcbSJinsong Ji if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits) 2987f6cb3bcbSJinsong Ji return false; 2988f6cb3bcbSJinsong Ji } 2989ba43840bSJinsong Ji LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";); 2990f6cb3bcbSJinsong Ji return true; 2991f6cb3bcbSJinsong Ji } 2992f6cb3bcbSJinsong Ji 2993f6cb3bcbSJinsong Ji void ResourceManager::reserveResources(const MCInstrDesc *MID) { 2994ba43840bSJinsong Ji LLVM_DEBUG({ 2995ba43840bSJinsong Ji if (SwpDebugResource) 2996ba43840bSJinsong Ji dbgs() << "reserveResources:\n"; 2997ba43840bSJinsong Ji }); 2998f6cb3bcbSJinsong Ji if (UseDFA) 2999f6cb3bcbSJinsong Ji return DFAResources->reserveResources(MID); 3000f6cb3bcbSJinsong Ji 3001f6cb3bcbSJinsong Ji unsigned InsnClass = MID->getSchedClass(); 3002f6cb3bcbSJinsong Ji const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass); 3003f6cb3bcbSJinsong Ji if (!SCDesc->isValid()) { 3004f6cb3bcbSJinsong Ji LLVM_DEBUG({ 3005f6cb3bcbSJinsong Ji dbgs() << "No valid Schedule Class Desc for schedClass!\n"; 3006f6cb3bcbSJinsong Ji dbgs() << "isPseduo:" << MID->isPseudo() << "\n"; 3007f6cb3bcbSJinsong Ji }); 3008f6cb3bcbSJinsong Ji return; 3009f6cb3bcbSJinsong Ji } 3010f6cb3bcbSJinsong Ji for (const MCWriteProcResEntry &PRE : 3011f6cb3bcbSJinsong Ji make_range(STI->getWriteProcResBegin(SCDesc), 3012f6cb3bcbSJinsong Ji STI->getWriteProcResEnd(SCDesc))) { 3013f6cb3bcbSJinsong Ji if (!PRE.Cycles) 3014f6cb3bcbSJinsong Ji continue; 3015f6cb3bcbSJinsong Ji ++ProcResourceCount[PRE.ProcResourceIdx]; 3016f6cb3bcbSJinsong Ji LLVM_DEBUG({ 3017ba43840bSJinsong Ji if (SwpDebugResource) { 3018c77aff7eSRichard Trieu const MCProcResourceDesc *ProcResource = 3019c77aff7eSRichard Trieu SM.getProcResource(PRE.ProcResourceIdx); 3020f6cb3bcbSJinsong Ji dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n", 3021f6cb3bcbSJinsong Ji ProcResource->Name, PRE.ProcResourceIdx, 3022e8698eadSRichard Trieu ProcResourceCount[PRE.ProcResourceIdx], 3023e8698eadSRichard Trieu ProcResource->NumUnits, PRE.Cycles); 3024ba43840bSJinsong Ji } 3025f6cb3bcbSJinsong Ji }); 3026f6cb3bcbSJinsong Ji } 3027ba43840bSJinsong Ji LLVM_DEBUG({ 3028ba43840bSJinsong Ji if (SwpDebugResource) 3029ba43840bSJinsong Ji dbgs() << "reserveResources: done!\n\n"; 3030ba43840bSJinsong Ji }); 3031f6cb3bcbSJinsong Ji } 3032f6cb3bcbSJinsong Ji 3033f6cb3bcbSJinsong Ji bool ResourceManager::canReserveResources(const MachineInstr &MI) const { 3034f6cb3bcbSJinsong Ji return canReserveResources(&MI.getDesc()); 3035f6cb3bcbSJinsong Ji } 3036f6cb3bcbSJinsong Ji 3037f6cb3bcbSJinsong Ji void ResourceManager::reserveResources(const MachineInstr &MI) { 3038f6cb3bcbSJinsong Ji return reserveResources(&MI.getDesc()); 3039f6cb3bcbSJinsong Ji } 3040f6cb3bcbSJinsong Ji 3041f6cb3bcbSJinsong Ji void ResourceManager::clearResources() { 3042f6cb3bcbSJinsong Ji if (UseDFA) 3043f6cb3bcbSJinsong Ji return DFAResources->clearResources(); 3044f6cb3bcbSJinsong Ji std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0); 3045f6cb3bcbSJinsong Ji } 3046