10b57cec5SDimitry Andric //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // This SMS implementation is a target-independent back-end pass. When enabled,
120b57cec5SDimitry Andric // the pass runs just prior to the register allocation pass, while the machine
130b57cec5SDimitry Andric // IR is in SSA form. If software pipelining is successful, then the original
140b57cec5SDimitry Andric // loop is replaced by the optimized loop. The optimized loop contains one or
150b57cec5SDimitry Andric // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
160b57cec5SDimitry Andric // the instructions cannot be scheduled in a given MII, we increase the MII by
170b57cec5SDimitry Andric // one and try again.
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
200b57cec5SDimitry Andric // represent loop carried dependences in the DAG as order edges to the Phi
210b57cec5SDimitry Andric // nodes. We also perform several passes over the DAG to eliminate unnecessary
220b57cec5SDimitry Andric // edges that inhibit the ability to pipeline. The implementation uses the
230b57cec5SDimitry Andric // DFAPacketizer class to compute the minimum initiation interval and the check
240b57cec5SDimitry Andric // where an instruction may be inserted in the pipelined schedule.
250b57cec5SDimitry Andric //
260b57cec5SDimitry Andric // In order for the SMS pass to work, several target specific hooks need to be
270b57cec5SDimitry Andric // implemented to get information about the loop structure and to rewrite
280b57cec5SDimitry Andric // instructions.
290b57cec5SDimitry Andric //
300b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
310b57cec5SDimitry Andric
320b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
330b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
340b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
350b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
360b57cec5SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
37*5f7ddb14SDimitry Andric #include "llvm/ADT/SetOperations.h"
380b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
390b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
400b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
410b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
420b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
430b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
440b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
450b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
460b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/DFAPacketizer.h"
480b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
490b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
500b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
510b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
520b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
530b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
540b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
550b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
560b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
570b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
580b57cec5SDimitry Andric #include "llvm/CodeGen/MachinePipeliner.h"
590b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
608bcb0991SDimitry Andric #include "llvm/CodeGen/ModuloSchedule.h"
610b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
620b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAG.h"
630b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAGMutation.h"
640b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
650b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
660b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
670b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
680b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
690b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
700b57cec5SDimitry Andric #include "llvm/IR/Function.h"
710b57cec5SDimitry Andric #include "llvm/MC/LaneBitmask.h"
720b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
730b57cec5SDimitry Andric #include "llvm/MC/MCInstrItineraries.h"
740b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
750b57cec5SDimitry Andric #include "llvm/Pass.h"
760b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
770b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
780b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
790b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
800b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
810b57cec5SDimitry Andric #include <algorithm>
820b57cec5SDimitry Andric #include <cassert>
830b57cec5SDimitry Andric #include <climits>
840b57cec5SDimitry Andric #include <cstdint>
850b57cec5SDimitry Andric #include <deque>
860b57cec5SDimitry Andric #include <functional>
870b57cec5SDimitry Andric #include <iterator>
880b57cec5SDimitry Andric #include <map>
890b57cec5SDimitry Andric #include <memory>
900b57cec5SDimitry Andric #include <tuple>
910b57cec5SDimitry Andric #include <utility>
920b57cec5SDimitry Andric #include <vector>
930b57cec5SDimitry Andric
940b57cec5SDimitry Andric using namespace llvm;
950b57cec5SDimitry Andric
960b57cec5SDimitry Andric #define DEBUG_TYPE "pipeliner"
970b57cec5SDimitry Andric
980b57cec5SDimitry Andric STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
990b57cec5SDimitry Andric STATISTIC(NumPipelined, "Number of loops software pipelined");
1000b57cec5SDimitry Andric STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
1010b57cec5SDimitry Andric STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
1020b57cec5SDimitry Andric STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
1030b57cec5SDimitry Andric STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
1040b57cec5SDimitry Andric STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
1050b57cec5SDimitry Andric STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
1060b57cec5SDimitry Andric STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
1070b57cec5SDimitry Andric STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
1080b57cec5SDimitry Andric STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
1090b57cec5SDimitry Andric
1100b57cec5SDimitry Andric /// A command line option to turn software pipelining on or off.
1110b57cec5SDimitry Andric static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
1120b57cec5SDimitry Andric cl::ZeroOrMore,
1130b57cec5SDimitry Andric cl::desc("Enable Software Pipelining"));
1140b57cec5SDimitry Andric
1150b57cec5SDimitry Andric /// A command line option to enable SWP at -Os.
1160b57cec5SDimitry Andric static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
1170b57cec5SDimitry Andric cl::desc("Enable SWP at Os."), cl::Hidden,
1180b57cec5SDimitry Andric cl::init(false));
1190b57cec5SDimitry Andric
1200b57cec5SDimitry Andric /// A command line argument to limit minimum initial interval for pipelining.
1210b57cec5SDimitry Andric static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
1220b57cec5SDimitry Andric cl::desc("Size limit for the MII."),
1230b57cec5SDimitry Andric cl::Hidden, cl::init(27));
1240b57cec5SDimitry Andric
1250b57cec5SDimitry Andric /// A command line argument to limit the number of stages in the pipeline.
1260b57cec5SDimitry Andric static cl::opt<int>
1270b57cec5SDimitry Andric SwpMaxStages("pipeliner-max-stages",
1280b57cec5SDimitry Andric cl::desc("Maximum stages allowed in the generated scheduled."),
1290b57cec5SDimitry Andric cl::Hidden, cl::init(3));
1300b57cec5SDimitry Andric
1310b57cec5SDimitry Andric /// A command line option to disable the pruning of chain dependences due to
1320b57cec5SDimitry Andric /// an unrelated Phi.
1330b57cec5SDimitry Andric static cl::opt<bool>
1340b57cec5SDimitry Andric SwpPruneDeps("pipeliner-prune-deps",
1350b57cec5SDimitry Andric cl::desc("Prune dependences between unrelated Phi nodes."),
1360b57cec5SDimitry Andric cl::Hidden, cl::init(true));
1370b57cec5SDimitry Andric
1380b57cec5SDimitry Andric /// A command line option to disable the pruning of loop carried order
1390b57cec5SDimitry Andric /// dependences.
1400b57cec5SDimitry Andric static cl::opt<bool>
1410b57cec5SDimitry Andric SwpPruneLoopCarried("pipeliner-prune-loop-carried",
1420b57cec5SDimitry Andric cl::desc("Prune loop carried order dependences."),
1430b57cec5SDimitry Andric cl::Hidden, cl::init(true));
1440b57cec5SDimitry Andric
1450b57cec5SDimitry Andric #ifndef NDEBUG
1460b57cec5SDimitry Andric static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
1470b57cec5SDimitry Andric #endif
1480b57cec5SDimitry Andric
1490b57cec5SDimitry Andric static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
1500b57cec5SDimitry Andric cl::ReallyHidden, cl::init(false),
1510b57cec5SDimitry Andric cl::ZeroOrMore, cl::desc("Ignore RecMII"));
1520b57cec5SDimitry Andric
1530b57cec5SDimitry Andric static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
1540b57cec5SDimitry Andric cl::init(false));
1550b57cec5SDimitry Andric static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
1560b57cec5SDimitry Andric cl::init(false));
1570b57cec5SDimitry Andric
1588bcb0991SDimitry Andric static cl::opt<bool> EmitTestAnnotations(
1598bcb0991SDimitry Andric "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
1608bcb0991SDimitry Andric cl::desc("Instead of emitting the pipelined code, annotate instructions "
1618bcb0991SDimitry Andric "with the generated schedule for feeding into the "
1628bcb0991SDimitry Andric "-modulo-schedule-test pass"));
1638bcb0991SDimitry Andric
1648bcb0991SDimitry Andric static cl::opt<bool> ExperimentalCodeGen(
1658bcb0991SDimitry Andric "pipeliner-experimental-cg", cl::Hidden, cl::init(false),
1668bcb0991SDimitry Andric cl::desc(
1678bcb0991SDimitry Andric "Use the experimental peeling code generator for software pipelining"));
1688bcb0991SDimitry Andric
1690b57cec5SDimitry Andric namespace llvm {
1700b57cec5SDimitry Andric
1710b57cec5SDimitry Andric // A command line option to enable the CopyToPhi DAG mutation.
1720b57cec5SDimitry Andric cl::opt<bool>
1730b57cec5SDimitry Andric SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
1740b57cec5SDimitry Andric cl::init(true), cl::ZeroOrMore,
1750b57cec5SDimitry Andric cl::desc("Enable CopyToPhi DAG Mutation"));
1760b57cec5SDimitry Andric
1770b57cec5SDimitry Andric } // end namespace llvm
1780b57cec5SDimitry Andric
1790b57cec5SDimitry Andric unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
1800b57cec5SDimitry Andric char MachinePipeliner::ID = 0;
1810b57cec5SDimitry Andric #ifndef NDEBUG
1820b57cec5SDimitry Andric int MachinePipeliner::NumTries = 0;
1830b57cec5SDimitry Andric #endif
1840b57cec5SDimitry Andric char &llvm::MachinePipelinerID = MachinePipeliner::ID;
1850b57cec5SDimitry Andric
1860b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
1870b57cec5SDimitry Andric "Modulo Software Pipelining", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)1880b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1890b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1900b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1910b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1920b57cec5SDimitry Andric INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
1930b57cec5SDimitry Andric "Modulo Software Pipelining", false, false)
1940b57cec5SDimitry Andric
1950b57cec5SDimitry Andric /// The "main" function for implementing Swing Modulo Scheduling.
1960b57cec5SDimitry Andric bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
1970b57cec5SDimitry Andric if (skipFunction(mf.getFunction()))
1980b57cec5SDimitry Andric return false;
1990b57cec5SDimitry Andric
2000b57cec5SDimitry Andric if (!EnableSWP)
2010b57cec5SDimitry Andric return false;
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric if (mf.getFunction().getAttributes().hasAttribute(
2040b57cec5SDimitry Andric AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
2050b57cec5SDimitry Andric !EnableSWPOptSize.getPosition())
2060b57cec5SDimitry Andric return false;
2070b57cec5SDimitry Andric
2080b57cec5SDimitry Andric if (!mf.getSubtarget().enableMachinePipeliner())
2090b57cec5SDimitry Andric return false;
2100b57cec5SDimitry Andric
2110b57cec5SDimitry Andric // Cannot pipeline loops without instruction itineraries if we are using
2120b57cec5SDimitry Andric // DFA for the pipeliner.
2130b57cec5SDimitry Andric if (mf.getSubtarget().useDFAforSMS() &&
2140b57cec5SDimitry Andric (!mf.getSubtarget().getInstrItineraryData() ||
2150b57cec5SDimitry Andric mf.getSubtarget().getInstrItineraryData()->isEmpty()))
2160b57cec5SDimitry Andric return false;
2170b57cec5SDimitry Andric
2180b57cec5SDimitry Andric MF = &mf;
2190b57cec5SDimitry Andric MLI = &getAnalysis<MachineLoopInfo>();
2200b57cec5SDimitry Andric MDT = &getAnalysis<MachineDominatorTree>();
2215ffd83dbSDimitry Andric ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2220b57cec5SDimitry Andric TII = MF->getSubtarget().getInstrInfo();
2230b57cec5SDimitry Andric RegClassInfo.runOnMachineFunction(*MF);
2240b57cec5SDimitry Andric
2250b57cec5SDimitry Andric for (auto &L : *MLI)
2260b57cec5SDimitry Andric scheduleLoop(*L);
2270b57cec5SDimitry Andric
2280b57cec5SDimitry Andric return false;
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric /// Attempt to perform the SMS algorithm on the specified loop. This function is
2320b57cec5SDimitry Andric /// the main entry point for the algorithm. The function identifies candidate
2330b57cec5SDimitry Andric /// loops, calculates the minimum initiation interval, and attempts to schedule
2340b57cec5SDimitry Andric /// the loop.
scheduleLoop(MachineLoop & L)2350b57cec5SDimitry Andric bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
2360b57cec5SDimitry Andric bool Changed = false;
2370b57cec5SDimitry Andric for (auto &InnerLoop : L)
2380b57cec5SDimitry Andric Changed |= scheduleLoop(*InnerLoop);
2390b57cec5SDimitry Andric
2400b57cec5SDimitry Andric #ifndef NDEBUG
2410b57cec5SDimitry Andric // Stop trying after reaching the limit (if any).
2420b57cec5SDimitry Andric int Limit = SwpLoopLimit;
2430b57cec5SDimitry Andric if (Limit >= 0) {
2440b57cec5SDimitry Andric if (NumTries >= SwpLoopLimit)
2450b57cec5SDimitry Andric return Changed;
2460b57cec5SDimitry Andric NumTries++;
2470b57cec5SDimitry Andric }
2480b57cec5SDimitry Andric #endif
2490b57cec5SDimitry Andric
2500b57cec5SDimitry Andric setPragmaPipelineOptions(L);
2510b57cec5SDimitry Andric if (!canPipelineLoop(L)) {
2520b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
2535ffd83dbSDimitry Andric ORE->emit([&]() {
2545ffd83dbSDimitry Andric return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
2555ffd83dbSDimitry Andric L.getStartLoc(), L.getHeader())
2565ffd83dbSDimitry Andric << "Failed to pipeline loop";
2575ffd83dbSDimitry Andric });
2585ffd83dbSDimitry Andric
2590b57cec5SDimitry Andric return Changed;
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric
2620b57cec5SDimitry Andric ++NumTrytoPipeline;
2630b57cec5SDimitry Andric
2640b57cec5SDimitry Andric Changed = swingModuloScheduler(L);
2650b57cec5SDimitry Andric
2660b57cec5SDimitry Andric return Changed;
2670b57cec5SDimitry Andric }
2680b57cec5SDimitry Andric
setPragmaPipelineOptions(MachineLoop & L)2690b57cec5SDimitry Andric void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
2705ffd83dbSDimitry Andric // Reset the pragma for the next loop in iteration.
2715ffd83dbSDimitry Andric disabledByPragma = false;
272af732203SDimitry Andric II_setByPragma = 0;
2735ffd83dbSDimitry Andric
2740b57cec5SDimitry Andric MachineBasicBlock *LBLK = L.getTopBlock();
2750b57cec5SDimitry Andric
2760b57cec5SDimitry Andric if (LBLK == nullptr)
2770b57cec5SDimitry Andric return;
2780b57cec5SDimitry Andric
2790b57cec5SDimitry Andric const BasicBlock *BBLK = LBLK->getBasicBlock();
2800b57cec5SDimitry Andric if (BBLK == nullptr)
2810b57cec5SDimitry Andric return;
2820b57cec5SDimitry Andric
2830b57cec5SDimitry Andric const Instruction *TI = BBLK->getTerminator();
2840b57cec5SDimitry Andric if (TI == nullptr)
2850b57cec5SDimitry Andric return;
2860b57cec5SDimitry Andric
2870b57cec5SDimitry Andric MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
2880b57cec5SDimitry Andric if (LoopID == nullptr)
2890b57cec5SDimitry Andric return;
2900b57cec5SDimitry Andric
2910b57cec5SDimitry Andric assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
2920b57cec5SDimitry Andric assert(LoopID->getOperand(0) == LoopID && "invalid loop");
2930b57cec5SDimitry Andric
2940b57cec5SDimitry Andric for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
2950b57cec5SDimitry Andric MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
2960b57cec5SDimitry Andric
2970b57cec5SDimitry Andric if (MD == nullptr)
2980b57cec5SDimitry Andric continue;
2990b57cec5SDimitry Andric
3000b57cec5SDimitry Andric MDString *S = dyn_cast<MDString>(MD->getOperand(0));
3010b57cec5SDimitry Andric
3020b57cec5SDimitry Andric if (S == nullptr)
3030b57cec5SDimitry Andric continue;
3040b57cec5SDimitry Andric
3050b57cec5SDimitry Andric if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
3060b57cec5SDimitry Andric assert(MD->getNumOperands() == 2 &&
3070b57cec5SDimitry Andric "Pipeline initiation interval hint metadata should have two operands.");
3080b57cec5SDimitry Andric II_setByPragma =
3090b57cec5SDimitry Andric mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
3100b57cec5SDimitry Andric assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
3110b57cec5SDimitry Andric } else if (S->getString() == "llvm.loop.pipeline.disable") {
3120b57cec5SDimitry Andric disabledByPragma = true;
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric }
3150b57cec5SDimitry Andric }
3160b57cec5SDimitry Andric
3170b57cec5SDimitry Andric /// Return true if the loop can be software pipelined. The algorithm is
3180b57cec5SDimitry Andric /// restricted to loops with a single basic block. Make sure that the
3190b57cec5SDimitry Andric /// branch in the loop can be analyzed.
canPipelineLoop(MachineLoop & L)3200b57cec5SDimitry Andric bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
3215ffd83dbSDimitry Andric if (L.getNumBlocks() != 1) {
3225ffd83dbSDimitry Andric ORE->emit([&]() {
3235ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
3245ffd83dbSDimitry Andric L.getStartLoc(), L.getHeader())
3255ffd83dbSDimitry Andric << "Not a single basic block: "
3265ffd83dbSDimitry Andric << ore::NV("NumBlocks", L.getNumBlocks());
3275ffd83dbSDimitry Andric });
3280b57cec5SDimitry Andric return false;
3295ffd83dbSDimitry Andric }
3300b57cec5SDimitry Andric
3315ffd83dbSDimitry Andric if (disabledByPragma) {
3325ffd83dbSDimitry Andric ORE->emit([&]() {
3335ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
3345ffd83dbSDimitry Andric L.getStartLoc(), L.getHeader())
3355ffd83dbSDimitry Andric << "Disabled by Pragma.";
3365ffd83dbSDimitry Andric });
3370b57cec5SDimitry Andric return false;
3385ffd83dbSDimitry Andric }
3390b57cec5SDimitry Andric
3400b57cec5SDimitry Andric // Check if the branch can't be understood because we can't do pipelining
3410b57cec5SDimitry Andric // if that's the case.
3420b57cec5SDimitry Andric LI.TBB = nullptr;
3430b57cec5SDimitry Andric LI.FBB = nullptr;
3440b57cec5SDimitry Andric LI.BrCond.clear();
3450b57cec5SDimitry Andric if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
3465ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
3470b57cec5SDimitry Andric NumFailBranch++;
3485ffd83dbSDimitry Andric ORE->emit([&]() {
3495ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
3505ffd83dbSDimitry Andric L.getStartLoc(), L.getHeader())
3515ffd83dbSDimitry Andric << "The branch can't be understood";
3525ffd83dbSDimitry Andric });
3530b57cec5SDimitry Andric return false;
3540b57cec5SDimitry Andric }
3550b57cec5SDimitry Andric
3560b57cec5SDimitry Andric LI.LoopInductionVar = nullptr;
3570b57cec5SDimitry Andric LI.LoopCompare = nullptr;
3588bcb0991SDimitry Andric if (!TII->analyzeLoopForPipelining(L.getTopBlock())) {
3595ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
3600b57cec5SDimitry Andric NumFailLoop++;
3615ffd83dbSDimitry Andric ORE->emit([&]() {
3625ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
3635ffd83dbSDimitry Andric L.getStartLoc(), L.getHeader())
3645ffd83dbSDimitry Andric << "The loop structure is not supported";
3655ffd83dbSDimitry Andric });
3660b57cec5SDimitry Andric return false;
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric
3690b57cec5SDimitry Andric if (!L.getLoopPreheader()) {
3705ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
3710b57cec5SDimitry Andric NumFailPreheader++;
3725ffd83dbSDimitry Andric ORE->emit([&]() {
3735ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
3745ffd83dbSDimitry Andric L.getStartLoc(), L.getHeader())
3755ffd83dbSDimitry Andric << "No loop preheader found";
3765ffd83dbSDimitry Andric });
3770b57cec5SDimitry Andric return false;
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric
3800b57cec5SDimitry Andric // Remove any subregisters from inputs to phi nodes.
3810b57cec5SDimitry Andric preprocessPhiNodes(*L.getHeader());
3820b57cec5SDimitry Andric return true;
3830b57cec5SDimitry Andric }
3840b57cec5SDimitry Andric
preprocessPhiNodes(MachineBasicBlock & B)3850b57cec5SDimitry Andric void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
3860b57cec5SDimitry Andric MachineRegisterInfo &MRI = MF->getRegInfo();
3870b57cec5SDimitry Andric SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
3880b57cec5SDimitry Andric
3890b57cec5SDimitry Andric for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
3900b57cec5SDimitry Andric MachineOperand &DefOp = PI.getOperand(0);
3910b57cec5SDimitry Andric assert(DefOp.getSubReg() == 0);
3920b57cec5SDimitry Andric auto *RC = MRI.getRegClass(DefOp.getReg());
3930b57cec5SDimitry Andric
3940b57cec5SDimitry Andric for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
3950b57cec5SDimitry Andric MachineOperand &RegOp = PI.getOperand(i);
3960b57cec5SDimitry Andric if (RegOp.getSubReg() == 0)
3970b57cec5SDimitry Andric continue;
3980b57cec5SDimitry Andric
3990b57cec5SDimitry Andric // If the operand uses a subregister, replace it with a new register
4000b57cec5SDimitry Andric // without subregisters, and generate a copy to the new register.
4018bcb0991SDimitry Andric Register NewReg = MRI.createVirtualRegister(RC);
4020b57cec5SDimitry Andric MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
4030b57cec5SDimitry Andric MachineBasicBlock::iterator At = PredB.getFirstTerminator();
4040b57cec5SDimitry Andric const DebugLoc &DL = PredB.findDebugLoc(At);
4050b57cec5SDimitry Andric auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
4060b57cec5SDimitry Andric .addReg(RegOp.getReg(), getRegState(RegOp),
4070b57cec5SDimitry Andric RegOp.getSubReg());
4080b57cec5SDimitry Andric Slots.insertMachineInstrInMaps(*Copy);
4090b57cec5SDimitry Andric RegOp.setReg(NewReg);
4100b57cec5SDimitry Andric RegOp.setSubReg(0);
4110b57cec5SDimitry Andric }
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric }
4140b57cec5SDimitry Andric
4150b57cec5SDimitry Andric /// The SMS algorithm consists of the following main steps:
4160b57cec5SDimitry Andric /// 1. Computation and analysis of the dependence graph.
4170b57cec5SDimitry Andric /// 2. Ordering of the nodes (instructions).
4180b57cec5SDimitry Andric /// 3. Attempt to Schedule the loop.
swingModuloScheduler(MachineLoop & L)4190b57cec5SDimitry Andric bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
4200b57cec5SDimitry Andric assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
4210b57cec5SDimitry Andric
4220b57cec5SDimitry Andric SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
4230b57cec5SDimitry Andric II_setByPragma);
4240b57cec5SDimitry Andric
4250b57cec5SDimitry Andric MachineBasicBlock *MBB = L.getHeader();
4260b57cec5SDimitry Andric // The kernel should not include any terminator instructions. These
4270b57cec5SDimitry Andric // will be added back later.
4280b57cec5SDimitry Andric SMS.startBlock(MBB);
4290b57cec5SDimitry Andric
4300b57cec5SDimitry Andric // Compute the number of 'real' instructions in the basic block by
4310b57cec5SDimitry Andric // ignoring terminators.
4320b57cec5SDimitry Andric unsigned size = MBB->size();
4330b57cec5SDimitry Andric for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
4340b57cec5SDimitry Andric E = MBB->instr_end();
4350b57cec5SDimitry Andric I != E; ++I, --size)
4360b57cec5SDimitry Andric ;
4370b57cec5SDimitry Andric
4380b57cec5SDimitry Andric SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
4390b57cec5SDimitry Andric SMS.schedule();
4400b57cec5SDimitry Andric SMS.exitRegion();
4410b57cec5SDimitry Andric
4420b57cec5SDimitry Andric SMS.finishBlock();
4430b57cec5SDimitry Andric return SMS.hasNewSchedule();
4440b57cec5SDimitry Andric }
4450b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const446af732203SDimitry Andric void MachinePipeliner::getAnalysisUsage(AnalysisUsage &AU) const {
447af732203SDimitry Andric AU.addRequired<AAResultsWrapperPass>();
448af732203SDimitry Andric AU.addPreserved<AAResultsWrapperPass>();
449af732203SDimitry Andric AU.addRequired<MachineLoopInfo>();
450af732203SDimitry Andric AU.addRequired<MachineDominatorTree>();
451af732203SDimitry Andric AU.addRequired<LiveIntervals>();
452af732203SDimitry Andric AU.addRequired<MachineOptimizationRemarkEmitterPass>();
453af732203SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
454af732203SDimitry Andric }
455af732203SDimitry Andric
setMII(unsigned ResMII,unsigned RecMII)4560b57cec5SDimitry Andric void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
4570b57cec5SDimitry Andric if (II_setByPragma > 0)
4580b57cec5SDimitry Andric MII = II_setByPragma;
4590b57cec5SDimitry Andric else
4600b57cec5SDimitry Andric MII = std::max(ResMII, RecMII);
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric
setMAX_II()4630b57cec5SDimitry Andric void SwingSchedulerDAG::setMAX_II() {
4640b57cec5SDimitry Andric if (II_setByPragma > 0)
4650b57cec5SDimitry Andric MAX_II = II_setByPragma;
4660b57cec5SDimitry Andric else
4670b57cec5SDimitry Andric MAX_II = MII + 10;
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric
4700b57cec5SDimitry Andric /// We override the schedule function in ScheduleDAGInstrs to implement the
4710b57cec5SDimitry Andric /// scheduling part of the Swing Modulo Scheduling algorithm.
schedule()4720b57cec5SDimitry Andric void SwingSchedulerDAG::schedule() {
4730b57cec5SDimitry Andric AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
4740b57cec5SDimitry Andric buildSchedGraph(AA);
4750b57cec5SDimitry Andric addLoopCarriedDependences(AA);
4760b57cec5SDimitry Andric updatePhiDependences();
4770b57cec5SDimitry Andric Topo.InitDAGTopologicalSorting();
4780b57cec5SDimitry Andric changeDependences();
4790b57cec5SDimitry Andric postprocessDAG();
4800b57cec5SDimitry Andric LLVM_DEBUG(dump());
4810b57cec5SDimitry Andric
4820b57cec5SDimitry Andric NodeSetType NodeSets;
4830b57cec5SDimitry Andric findCircuits(NodeSets);
4840b57cec5SDimitry Andric NodeSetType Circuits = NodeSets;
4850b57cec5SDimitry Andric
4860b57cec5SDimitry Andric // Calculate the MII.
4870b57cec5SDimitry Andric unsigned ResMII = calculateResMII();
4880b57cec5SDimitry Andric unsigned RecMII = calculateRecMII(NodeSets);
4890b57cec5SDimitry Andric
4900b57cec5SDimitry Andric fuseRecs(NodeSets);
4910b57cec5SDimitry Andric
4920b57cec5SDimitry Andric // This flag is used for testing and can cause correctness problems.
4930b57cec5SDimitry Andric if (SwpIgnoreRecMII)
4940b57cec5SDimitry Andric RecMII = 0;
4950b57cec5SDimitry Andric
4960b57cec5SDimitry Andric setMII(ResMII, RecMII);
4970b57cec5SDimitry Andric setMAX_II();
4980b57cec5SDimitry Andric
4990b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
5000b57cec5SDimitry Andric << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
5010b57cec5SDimitry Andric
5020b57cec5SDimitry Andric // Can't schedule a loop without a valid MII.
5030b57cec5SDimitry Andric if (MII == 0) {
5045ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
5050b57cec5SDimitry Andric NumFailZeroMII++;
5065ffd83dbSDimitry Andric Pass.ORE->emit([&]() {
5075ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(
5085ffd83dbSDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
5095ffd83dbSDimitry Andric << "Invalid Minimal Initiation Interval: 0";
5105ffd83dbSDimitry Andric });
5110b57cec5SDimitry Andric return;
5120b57cec5SDimitry Andric }
5130b57cec5SDimitry Andric
5140b57cec5SDimitry Andric // Don't pipeline large loops.
5150b57cec5SDimitry Andric if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
5160b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
5170b57cec5SDimitry Andric << ", we don't pipleline large loops\n");
5180b57cec5SDimitry Andric NumFailLargeMaxMII++;
5195ffd83dbSDimitry Andric Pass.ORE->emit([&]() {
5205ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(
5215ffd83dbSDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
5225ffd83dbSDimitry Andric << "Minimal Initiation Interval too large: "
5235ffd83dbSDimitry Andric << ore::NV("MII", (int)MII) << " > "
5245ffd83dbSDimitry Andric << ore::NV("SwpMaxMii", SwpMaxMii) << "."
5255ffd83dbSDimitry Andric << "Refer to -pipeliner-max-mii.";
5265ffd83dbSDimitry Andric });
5270b57cec5SDimitry Andric return;
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric
5300b57cec5SDimitry Andric computeNodeFunctions(NodeSets);
5310b57cec5SDimitry Andric
5320b57cec5SDimitry Andric registerPressureFilter(NodeSets);
5330b57cec5SDimitry Andric
5340b57cec5SDimitry Andric colocateNodeSets(NodeSets);
5350b57cec5SDimitry Andric
5360b57cec5SDimitry Andric checkNodeSets(NodeSets);
5370b57cec5SDimitry Andric
5380b57cec5SDimitry Andric LLVM_DEBUG({
5390b57cec5SDimitry Andric for (auto &I : NodeSets) {
5400b57cec5SDimitry Andric dbgs() << " Rec NodeSet ";
5410b57cec5SDimitry Andric I.dump();
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric });
5440b57cec5SDimitry Andric
5450b57cec5SDimitry Andric llvm::stable_sort(NodeSets, std::greater<NodeSet>());
5460b57cec5SDimitry Andric
5470b57cec5SDimitry Andric groupRemainingNodes(NodeSets);
5480b57cec5SDimitry Andric
5490b57cec5SDimitry Andric removeDuplicateNodes(NodeSets);
5500b57cec5SDimitry Andric
5510b57cec5SDimitry Andric LLVM_DEBUG({
5520b57cec5SDimitry Andric for (auto &I : NodeSets) {
5530b57cec5SDimitry Andric dbgs() << " NodeSet ";
5540b57cec5SDimitry Andric I.dump();
5550b57cec5SDimitry Andric }
5560b57cec5SDimitry Andric });
5570b57cec5SDimitry Andric
5580b57cec5SDimitry Andric computeNodeOrder(NodeSets);
5590b57cec5SDimitry Andric
5600b57cec5SDimitry Andric // check for node order issues
5610b57cec5SDimitry Andric checkValidNodeOrder(Circuits);
5620b57cec5SDimitry Andric
5630b57cec5SDimitry Andric SMSchedule Schedule(Pass.MF);
5640b57cec5SDimitry Andric Scheduled = schedulePipeline(Schedule);
5650b57cec5SDimitry Andric
5660b57cec5SDimitry Andric if (!Scheduled){
5670b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "No schedule found, return\n");
5680b57cec5SDimitry Andric NumFailNoSchedule++;
5695ffd83dbSDimitry Andric Pass.ORE->emit([&]() {
5705ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(
5715ffd83dbSDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
5725ffd83dbSDimitry Andric << "Unable to find schedule";
5735ffd83dbSDimitry Andric });
5740b57cec5SDimitry Andric return;
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric
5770b57cec5SDimitry Andric unsigned numStages = Schedule.getMaxStageCount();
5780b57cec5SDimitry Andric // No need to generate pipeline if there are no overlapped iterations.
5790b57cec5SDimitry Andric if (numStages == 0) {
5805ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
5810b57cec5SDimitry Andric NumFailZeroStage++;
5825ffd83dbSDimitry Andric Pass.ORE->emit([&]() {
5835ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(
5845ffd83dbSDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
5855ffd83dbSDimitry Andric << "No need to pipeline - no overlapped iterations in schedule.";
5865ffd83dbSDimitry Andric });
5870b57cec5SDimitry Andric return;
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric // Check that the maximum stage count is less than user-defined limit.
5900b57cec5SDimitry Andric if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
5910b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
5920b57cec5SDimitry Andric << " : too many stages, abort\n");
5930b57cec5SDimitry Andric NumFailLargeMaxStage++;
5945ffd83dbSDimitry Andric Pass.ORE->emit([&]() {
5955ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(
5965ffd83dbSDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
5975ffd83dbSDimitry Andric << "Too many stages in schedule: "
5985ffd83dbSDimitry Andric << ore::NV("numStages", (int)numStages) << " > "
5995ffd83dbSDimitry Andric << ore::NV("SwpMaxStages", SwpMaxStages)
6005ffd83dbSDimitry Andric << ". Refer to -pipeliner-max-stages.";
6015ffd83dbSDimitry Andric });
6020b57cec5SDimitry Andric return;
6030b57cec5SDimitry Andric }
6040b57cec5SDimitry Andric
6055ffd83dbSDimitry Andric Pass.ORE->emit([&]() {
6065ffd83dbSDimitry Andric return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
6075ffd83dbSDimitry Andric Loop.getHeader())
6085ffd83dbSDimitry Andric << "Pipelined succesfully!";
6095ffd83dbSDimitry Andric });
6105ffd83dbSDimitry Andric
6118bcb0991SDimitry Andric // Generate the schedule as a ModuloSchedule.
6128bcb0991SDimitry Andric DenseMap<MachineInstr *, int> Cycles, Stages;
6138bcb0991SDimitry Andric std::vector<MachineInstr *> OrderedInsts;
6148bcb0991SDimitry Andric for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
6158bcb0991SDimitry Andric ++Cycle) {
6168bcb0991SDimitry Andric for (SUnit *SU : Schedule.getInstructions(Cycle)) {
6178bcb0991SDimitry Andric OrderedInsts.push_back(SU->getInstr());
6188bcb0991SDimitry Andric Cycles[SU->getInstr()] = Cycle;
6198bcb0991SDimitry Andric Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
6208bcb0991SDimitry Andric }
6218bcb0991SDimitry Andric }
6228bcb0991SDimitry Andric DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
6238bcb0991SDimitry Andric for (auto &KV : NewMIs) {
6248bcb0991SDimitry Andric Cycles[KV.first] = Cycles[KV.second];
6258bcb0991SDimitry Andric Stages[KV.first] = Stages[KV.second];
6268bcb0991SDimitry Andric NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
6278bcb0991SDimitry Andric }
6288bcb0991SDimitry Andric
6298bcb0991SDimitry Andric ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
6308bcb0991SDimitry Andric std::move(Stages));
6318bcb0991SDimitry Andric if (EmitTestAnnotations) {
6328bcb0991SDimitry Andric assert(NewInstrChanges.empty() &&
6338bcb0991SDimitry Andric "Cannot serialize a schedule with InstrChanges!");
6348bcb0991SDimitry Andric ModuloScheduleTestAnnotater MSTI(MF, MS);
6358bcb0991SDimitry Andric MSTI.annotate();
6368bcb0991SDimitry Andric return;
6378bcb0991SDimitry Andric }
6388bcb0991SDimitry Andric // The experimental code generator can't work if there are InstChanges.
6398bcb0991SDimitry Andric if (ExperimentalCodeGen && NewInstrChanges.empty()) {
6408bcb0991SDimitry Andric PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
6418bcb0991SDimitry Andric MSE.expand();
6428bcb0991SDimitry Andric } else {
6438bcb0991SDimitry Andric ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
6448bcb0991SDimitry Andric MSE.expand();
6458bcb0991SDimitry Andric MSE.cleanup();
6468bcb0991SDimitry Andric }
6470b57cec5SDimitry Andric ++NumPipelined;
6480b57cec5SDimitry Andric }
6490b57cec5SDimitry Andric
6500b57cec5SDimitry Andric /// Clean up after the software pipeliner runs.
finishBlock()6510b57cec5SDimitry Andric void SwingSchedulerDAG::finishBlock() {
6528bcb0991SDimitry Andric for (auto &KV : NewMIs)
6538bcb0991SDimitry Andric MF.DeleteMachineInstr(KV.second);
6540b57cec5SDimitry Andric NewMIs.clear();
6550b57cec5SDimitry Andric
6560b57cec5SDimitry Andric // Call the superclass.
6570b57cec5SDimitry Andric ScheduleDAGInstrs::finishBlock();
6580b57cec5SDimitry Andric }
6590b57cec5SDimitry Andric
6600b57cec5SDimitry Andric /// Return the register values for the operands of a Phi instruction.
6610b57cec5SDimitry Andric /// This function assume the instruction is a Phi.
getPhiRegs(MachineInstr & Phi,MachineBasicBlock * Loop,unsigned & InitVal,unsigned & LoopVal)6620b57cec5SDimitry Andric static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
6630b57cec5SDimitry Andric unsigned &InitVal, unsigned &LoopVal) {
6640b57cec5SDimitry Andric assert(Phi.isPHI() && "Expecting a Phi.");
6650b57cec5SDimitry Andric
6660b57cec5SDimitry Andric InitVal = 0;
6670b57cec5SDimitry Andric LoopVal = 0;
6680b57cec5SDimitry Andric for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
6690b57cec5SDimitry Andric if (Phi.getOperand(i + 1).getMBB() != Loop)
6700b57cec5SDimitry Andric InitVal = Phi.getOperand(i).getReg();
6710b57cec5SDimitry Andric else
6720b57cec5SDimitry Andric LoopVal = Phi.getOperand(i).getReg();
6730b57cec5SDimitry Andric
6740b57cec5SDimitry Andric assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric
6770b57cec5SDimitry Andric /// Return the Phi register value that comes the loop block.
getLoopPhiReg(MachineInstr & Phi,MachineBasicBlock * LoopBB)6780b57cec5SDimitry Andric static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
6790b57cec5SDimitry Andric for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
6800b57cec5SDimitry Andric if (Phi.getOperand(i + 1).getMBB() == LoopBB)
6810b57cec5SDimitry Andric return Phi.getOperand(i).getReg();
6820b57cec5SDimitry Andric return 0;
6830b57cec5SDimitry Andric }
6840b57cec5SDimitry Andric
6850b57cec5SDimitry Andric /// Return true if SUb can be reached from SUa following the chain edges.
isSuccOrder(SUnit * SUa,SUnit * SUb)6860b57cec5SDimitry Andric static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
6870b57cec5SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
6880b57cec5SDimitry Andric SmallVector<SUnit *, 8> Worklist;
6890b57cec5SDimitry Andric Worklist.push_back(SUa);
6900b57cec5SDimitry Andric while (!Worklist.empty()) {
6910b57cec5SDimitry Andric const SUnit *SU = Worklist.pop_back_val();
6920b57cec5SDimitry Andric for (auto &SI : SU->Succs) {
6930b57cec5SDimitry Andric SUnit *SuccSU = SI.getSUnit();
6940b57cec5SDimitry Andric if (SI.getKind() == SDep::Order) {
6950b57cec5SDimitry Andric if (Visited.count(SuccSU))
6960b57cec5SDimitry Andric continue;
6970b57cec5SDimitry Andric if (SuccSU == SUb)
6980b57cec5SDimitry Andric return true;
6990b57cec5SDimitry Andric Worklist.push_back(SuccSU);
7000b57cec5SDimitry Andric Visited.insert(SuccSU);
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric }
7040b57cec5SDimitry Andric return false;
7050b57cec5SDimitry Andric }
7060b57cec5SDimitry Andric
7070b57cec5SDimitry Andric /// Return true if the instruction causes a chain between memory
7080b57cec5SDimitry Andric /// references before and after it.
isDependenceBarrier(MachineInstr & MI,AliasAnalysis * AA)7090b57cec5SDimitry Andric static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
7100b57cec5SDimitry Andric return MI.isCall() || MI.mayRaiseFPException() ||
7110b57cec5SDimitry Andric MI.hasUnmodeledSideEffects() ||
7120b57cec5SDimitry Andric (MI.hasOrderedMemoryRef() &&
7130b57cec5SDimitry Andric (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric
7160b57cec5SDimitry Andric /// Return the underlying objects for the memory references of an instruction.
7170b57cec5SDimitry Andric /// This function calls the code in ValueTracking, but first checks that the
7180b57cec5SDimitry Andric /// instruction has a memory operand.
getUnderlyingObjects(const MachineInstr * MI,SmallVectorImpl<const Value * > & Objs)7190b57cec5SDimitry Andric static void getUnderlyingObjects(const MachineInstr *MI,
720af732203SDimitry Andric SmallVectorImpl<const Value *> &Objs) {
7210b57cec5SDimitry Andric if (!MI->hasOneMemOperand())
7220b57cec5SDimitry Andric return;
7230b57cec5SDimitry Andric MachineMemOperand *MM = *MI->memoperands_begin();
7240b57cec5SDimitry Andric if (!MM->getValue())
7250b57cec5SDimitry Andric return;
726af732203SDimitry Andric getUnderlyingObjects(MM->getValue(), Objs);
7270b57cec5SDimitry Andric for (const Value *V : Objs) {
7280b57cec5SDimitry Andric if (!isIdentifiedObject(V)) {
7290b57cec5SDimitry Andric Objs.clear();
7300b57cec5SDimitry Andric return;
7310b57cec5SDimitry Andric }
7320b57cec5SDimitry Andric Objs.push_back(V);
7330b57cec5SDimitry Andric }
7340b57cec5SDimitry Andric }
7350b57cec5SDimitry Andric
7360b57cec5SDimitry Andric /// Add a chain edge between a load and store if the store can be an
7370b57cec5SDimitry Andric /// alias of the load on a subsequent iteration, i.e., a loop carried
7380b57cec5SDimitry Andric /// dependence. This code is very similar to the code in ScheduleDAGInstrs
7390b57cec5SDimitry Andric /// but that code doesn't create loop carried dependences.
addLoopCarriedDependences(AliasAnalysis * AA)7400b57cec5SDimitry Andric void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
7410b57cec5SDimitry Andric MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
7420b57cec5SDimitry Andric Value *UnknownValue =
7430b57cec5SDimitry Andric UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
7440b57cec5SDimitry Andric for (auto &SU : SUnits) {
7450b57cec5SDimitry Andric MachineInstr &MI = *SU.getInstr();
7460b57cec5SDimitry Andric if (isDependenceBarrier(MI, AA))
7470b57cec5SDimitry Andric PendingLoads.clear();
7480b57cec5SDimitry Andric else if (MI.mayLoad()) {
7490b57cec5SDimitry Andric SmallVector<const Value *, 4> Objs;
750af732203SDimitry Andric ::getUnderlyingObjects(&MI, Objs);
7510b57cec5SDimitry Andric if (Objs.empty())
7520b57cec5SDimitry Andric Objs.push_back(UnknownValue);
7530b57cec5SDimitry Andric for (auto V : Objs) {
7540b57cec5SDimitry Andric SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
7550b57cec5SDimitry Andric SUs.push_back(&SU);
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric } else if (MI.mayStore()) {
7580b57cec5SDimitry Andric SmallVector<const Value *, 4> Objs;
759af732203SDimitry Andric ::getUnderlyingObjects(&MI, Objs);
7600b57cec5SDimitry Andric if (Objs.empty())
7610b57cec5SDimitry Andric Objs.push_back(UnknownValue);
7620b57cec5SDimitry Andric for (auto V : Objs) {
7630b57cec5SDimitry Andric MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
7640b57cec5SDimitry Andric PendingLoads.find(V);
7650b57cec5SDimitry Andric if (I == PendingLoads.end())
7660b57cec5SDimitry Andric continue;
7670b57cec5SDimitry Andric for (auto Load : I->second) {
7680b57cec5SDimitry Andric if (isSuccOrder(Load, &SU))
7690b57cec5SDimitry Andric continue;
7700b57cec5SDimitry Andric MachineInstr &LdMI = *Load->getInstr();
7710b57cec5SDimitry Andric // First, perform the cheaper check that compares the base register.
7720b57cec5SDimitry Andric // If they are the same and the load offset is less than the store
7730b57cec5SDimitry Andric // offset, then mark the dependence as loop carried potentially.
7740b57cec5SDimitry Andric const MachineOperand *BaseOp1, *BaseOp2;
7750b57cec5SDimitry Andric int64_t Offset1, Offset2;
7765ffd83dbSDimitry Andric bool Offset1IsScalable, Offset2IsScalable;
7775ffd83dbSDimitry Andric if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1,
7785ffd83dbSDimitry Andric Offset1IsScalable, TRI) &&
7795ffd83dbSDimitry Andric TII->getMemOperandWithOffset(MI, BaseOp2, Offset2,
7805ffd83dbSDimitry Andric Offset2IsScalable, TRI)) {
7810b57cec5SDimitry Andric if (BaseOp1->isIdenticalTo(*BaseOp2) &&
7825ffd83dbSDimitry Andric Offset1IsScalable == Offset2IsScalable &&
7830b57cec5SDimitry Andric (int)Offset1 < (int)Offset2) {
7848bcb0991SDimitry Andric assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) &&
7850b57cec5SDimitry Andric "What happened to the chain edge?");
7860b57cec5SDimitry Andric SDep Dep(Load, SDep::Barrier);
7870b57cec5SDimitry Andric Dep.setLatency(1);
7880b57cec5SDimitry Andric SU.addPred(Dep);
7890b57cec5SDimitry Andric continue;
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric // Second, the more expensive check that uses alias analysis on the
7930b57cec5SDimitry Andric // base registers. If they alias, and the load offset is less than
7940b57cec5SDimitry Andric // the store offset, the mark the dependence as loop carried.
7950b57cec5SDimitry Andric if (!AA) {
7960b57cec5SDimitry Andric SDep Dep(Load, SDep::Barrier);
7970b57cec5SDimitry Andric Dep.setLatency(1);
7980b57cec5SDimitry Andric SU.addPred(Dep);
7990b57cec5SDimitry Andric continue;
8000b57cec5SDimitry Andric }
8010b57cec5SDimitry Andric MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
8020b57cec5SDimitry Andric MachineMemOperand *MMO2 = *MI.memoperands_begin();
8030b57cec5SDimitry Andric if (!MMO1->getValue() || !MMO2->getValue()) {
8040b57cec5SDimitry Andric SDep Dep(Load, SDep::Barrier);
8050b57cec5SDimitry Andric Dep.setLatency(1);
8060b57cec5SDimitry Andric SU.addPred(Dep);
8070b57cec5SDimitry Andric continue;
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric if (MMO1->getValue() == MMO2->getValue() &&
8100b57cec5SDimitry Andric MMO1->getOffset() <= MMO2->getOffset()) {
8110b57cec5SDimitry Andric SDep Dep(Load, SDep::Barrier);
8120b57cec5SDimitry Andric Dep.setLatency(1);
8130b57cec5SDimitry Andric SU.addPred(Dep);
8140b57cec5SDimitry Andric continue;
8150b57cec5SDimitry Andric }
816*5f7ddb14SDimitry Andric if (!AA->isNoAlias(
817af732203SDimitry Andric MemoryLocation::getAfter(MMO1->getValue(), MMO1->getAAInfo()),
818*5f7ddb14SDimitry Andric MemoryLocation::getAfter(MMO2->getValue(),
819*5f7ddb14SDimitry Andric MMO2->getAAInfo()))) {
8200b57cec5SDimitry Andric SDep Dep(Load, SDep::Barrier);
8210b57cec5SDimitry Andric Dep.setLatency(1);
8220b57cec5SDimitry Andric SU.addPred(Dep);
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric }
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric }
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric
8300b57cec5SDimitry Andric /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
8310b57cec5SDimitry Andric /// processes dependences for PHIs. This function adds true dependences
8320b57cec5SDimitry Andric /// from a PHI to a use, and a loop carried dependence from the use to the
8330b57cec5SDimitry Andric /// PHI. The loop carried dependence is represented as an anti dependence
8340b57cec5SDimitry Andric /// edge. This function also removes chain dependences between unrelated
8350b57cec5SDimitry Andric /// PHIs.
updatePhiDependences()8360b57cec5SDimitry Andric void SwingSchedulerDAG::updatePhiDependences() {
8370b57cec5SDimitry Andric SmallVector<SDep, 4> RemoveDeps;
8380b57cec5SDimitry Andric const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
8390b57cec5SDimitry Andric
8400b57cec5SDimitry Andric // Iterate over each DAG node.
8410b57cec5SDimitry Andric for (SUnit &I : SUnits) {
8420b57cec5SDimitry Andric RemoveDeps.clear();
8430b57cec5SDimitry Andric // Set to true if the instruction has an operand defined by a Phi.
8440b57cec5SDimitry Andric unsigned HasPhiUse = 0;
8450b57cec5SDimitry Andric unsigned HasPhiDef = 0;
8460b57cec5SDimitry Andric MachineInstr *MI = I.getInstr();
8470b57cec5SDimitry Andric // Iterate over each operand, and we process the definitions.
8480b57cec5SDimitry Andric for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
8490b57cec5SDimitry Andric MOE = MI->operands_end();
8500b57cec5SDimitry Andric MOI != MOE; ++MOI) {
8510b57cec5SDimitry Andric if (!MOI->isReg())
8520b57cec5SDimitry Andric continue;
8538bcb0991SDimitry Andric Register Reg = MOI->getReg();
8540b57cec5SDimitry Andric if (MOI->isDef()) {
8550b57cec5SDimitry Andric // If the register is used by a Phi, then create an anti dependence.
8560b57cec5SDimitry Andric for (MachineRegisterInfo::use_instr_iterator
8570b57cec5SDimitry Andric UI = MRI.use_instr_begin(Reg),
8580b57cec5SDimitry Andric UE = MRI.use_instr_end();
8590b57cec5SDimitry Andric UI != UE; ++UI) {
8600b57cec5SDimitry Andric MachineInstr *UseMI = &*UI;
8610b57cec5SDimitry Andric SUnit *SU = getSUnit(UseMI);
8620b57cec5SDimitry Andric if (SU != nullptr && UseMI->isPHI()) {
8630b57cec5SDimitry Andric if (!MI->isPHI()) {
8640b57cec5SDimitry Andric SDep Dep(SU, SDep::Anti, Reg);
8650b57cec5SDimitry Andric Dep.setLatency(1);
8660b57cec5SDimitry Andric I.addPred(Dep);
8670b57cec5SDimitry Andric } else {
8680b57cec5SDimitry Andric HasPhiDef = Reg;
8690b57cec5SDimitry Andric // Add a chain edge to a dependent Phi that isn't an existing
8700b57cec5SDimitry Andric // predecessor.
8710b57cec5SDimitry Andric if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
8720b57cec5SDimitry Andric I.addPred(SDep(SU, SDep::Barrier));
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric } else if (MOI->isUse()) {
8770b57cec5SDimitry Andric // If the register is defined by a Phi, then create a true dependence.
8780b57cec5SDimitry Andric MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
8790b57cec5SDimitry Andric if (DefMI == nullptr)
8800b57cec5SDimitry Andric continue;
8810b57cec5SDimitry Andric SUnit *SU = getSUnit(DefMI);
8820b57cec5SDimitry Andric if (SU != nullptr && DefMI->isPHI()) {
8830b57cec5SDimitry Andric if (!MI->isPHI()) {
8840b57cec5SDimitry Andric SDep Dep(SU, SDep::Data, Reg);
8850b57cec5SDimitry Andric Dep.setLatency(0);
8865ffd83dbSDimitry Andric ST.adjustSchedDependency(SU, 0, &I, MI->getOperandNo(MOI), Dep);
8870b57cec5SDimitry Andric I.addPred(Dep);
8880b57cec5SDimitry Andric } else {
8890b57cec5SDimitry Andric HasPhiUse = Reg;
8900b57cec5SDimitry Andric // Add a chain edge to a dependent Phi that isn't an existing
8910b57cec5SDimitry Andric // predecessor.
8920b57cec5SDimitry Andric if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
8930b57cec5SDimitry Andric I.addPred(SDep(SU, SDep::Barrier));
8940b57cec5SDimitry Andric }
8950b57cec5SDimitry Andric }
8960b57cec5SDimitry Andric }
8970b57cec5SDimitry Andric }
8980b57cec5SDimitry Andric // Remove order dependences from an unrelated Phi.
8990b57cec5SDimitry Andric if (!SwpPruneDeps)
9000b57cec5SDimitry Andric continue;
9010b57cec5SDimitry Andric for (auto &PI : I.Preds) {
9020b57cec5SDimitry Andric MachineInstr *PMI = PI.getSUnit()->getInstr();
9030b57cec5SDimitry Andric if (PMI->isPHI() && PI.getKind() == SDep::Order) {
9040b57cec5SDimitry Andric if (I.getInstr()->isPHI()) {
9050b57cec5SDimitry Andric if (PMI->getOperand(0).getReg() == HasPhiUse)
9060b57cec5SDimitry Andric continue;
9070b57cec5SDimitry Andric if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
9080b57cec5SDimitry Andric continue;
9090b57cec5SDimitry Andric }
9100b57cec5SDimitry Andric RemoveDeps.push_back(PI);
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric }
9130b57cec5SDimitry Andric for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
9140b57cec5SDimitry Andric I.removePred(RemoveDeps[i]);
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric }
9170b57cec5SDimitry Andric
9180b57cec5SDimitry Andric /// Iterate over each DAG node and see if we can change any dependences
9190b57cec5SDimitry Andric /// in order to reduce the recurrence MII.
changeDependences()9200b57cec5SDimitry Andric void SwingSchedulerDAG::changeDependences() {
9210b57cec5SDimitry Andric // See if an instruction can use a value from the previous iteration.
9220b57cec5SDimitry Andric // If so, we update the base and offset of the instruction and change
9230b57cec5SDimitry Andric // the dependences.
9240b57cec5SDimitry Andric for (SUnit &I : SUnits) {
9250b57cec5SDimitry Andric unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
9260b57cec5SDimitry Andric int64_t NewOffset = 0;
9270b57cec5SDimitry Andric if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
9280b57cec5SDimitry Andric NewOffset))
9290b57cec5SDimitry Andric continue;
9300b57cec5SDimitry Andric
9310b57cec5SDimitry Andric // Get the MI and SUnit for the instruction that defines the original base.
9328bcb0991SDimitry Andric Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
9330b57cec5SDimitry Andric MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
9340b57cec5SDimitry Andric if (!DefMI)
9350b57cec5SDimitry Andric continue;
9360b57cec5SDimitry Andric SUnit *DefSU = getSUnit(DefMI);
9370b57cec5SDimitry Andric if (!DefSU)
9380b57cec5SDimitry Andric continue;
9390b57cec5SDimitry Andric // Get the MI and SUnit for the instruction that defins the new base.
9400b57cec5SDimitry Andric MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
9410b57cec5SDimitry Andric if (!LastMI)
9420b57cec5SDimitry Andric continue;
9430b57cec5SDimitry Andric SUnit *LastSU = getSUnit(LastMI);
9440b57cec5SDimitry Andric if (!LastSU)
9450b57cec5SDimitry Andric continue;
9460b57cec5SDimitry Andric
9470b57cec5SDimitry Andric if (Topo.IsReachable(&I, LastSU))
9480b57cec5SDimitry Andric continue;
9490b57cec5SDimitry Andric
9500b57cec5SDimitry Andric // Remove the dependence. The value now depends on a prior iteration.
9510b57cec5SDimitry Andric SmallVector<SDep, 4> Deps;
952*5f7ddb14SDimitry Andric for (const SDep &P : I.Preds)
953*5f7ddb14SDimitry Andric if (P.getSUnit() == DefSU)
954*5f7ddb14SDimitry Andric Deps.push_back(P);
9550b57cec5SDimitry Andric for (int i = 0, e = Deps.size(); i != e; i++) {
9560b57cec5SDimitry Andric Topo.RemovePred(&I, Deps[i].getSUnit());
9570b57cec5SDimitry Andric I.removePred(Deps[i]);
9580b57cec5SDimitry Andric }
9590b57cec5SDimitry Andric // Remove the chain dependence between the instructions.
9600b57cec5SDimitry Andric Deps.clear();
9610b57cec5SDimitry Andric for (auto &P : LastSU->Preds)
9620b57cec5SDimitry Andric if (P.getSUnit() == &I && P.getKind() == SDep::Order)
9630b57cec5SDimitry Andric Deps.push_back(P);
9640b57cec5SDimitry Andric for (int i = 0, e = Deps.size(); i != e; i++) {
9650b57cec5SDimitry Andric Topo.RemovePred(LastSU, Deps[i].getSUnit());
9660b57cec5SDimitry Andric LastSU->removePred(Deps[i]);
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric
9690b57cec5SDimitry Andric // Add a dependence between the new instruction and the instruction
9700b57cec5SDimitry Andric // that defines the new base.
9710b57cec5SDimitry Andric SDep Dep(&I, SDep::Anti, NewBase);
9720b57cec5SDimitry Andric Topo.AddPred(LastSU, &I);
9730b57cec5SDimitry Andric LastSU->addPred(Dep);
9740b57cec5SDimitry Andric
9750b57cec5SDimitry Andric // Remember the base and offset information so that we can update the
9760b57cec5SDimitry Andric // instruction during code generation.
9770b57cec5SDimitry Andric InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric }
9800b57cec5SDimitry Andric
9810b57cec5SDimitry Andric namespace {
9820b57cec5SDimitry Andric
9830b57cec5SDimitry Andric // FuncUnitSorter - Comparison operator used to sort instructions by
9840b57cec5SDimitry Andric // the number of functional unit choices.
9850b57cec5SDimitry Andric struct FuncUnitSorter {
9860b57cec5SDimitry Andric const InstrItineraryData *InstrItins;
9870b57cec5SDimitry Andric const MCSubtargetInfo *STI;
9885ffd83dbSDimitry Andric DenseMap<InstrStage::FuncUnits, unsigned> Resources;
9890b57cec5SDimitry Andric
FuncUnitSorter__anon6bac73c50d11::FuncUnitSorter9900b57cec5SDimitry Andric FuncUnitSorter(const TargetSubtargetInfo &TSI)
9910b57cec5SDimitry Andric : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
9920b57cec5SDimitry Andric
9930b57cec5SDimitry Andric // Compute the number of functional unit alternatives needed
9940b57cec5SDimitry Andric // at each stage, and take the minimum value. We prioritize the
9950b57cec5SDimitry Andric // instructions by the least number of choices first.
minFuncUnits__anon6bac73c50d11::FuncUnitSorter9965ffd83dbSDimitry Andric unsigned minFuncUnits(const MachineInstr *Inst,
9975ffd83dbSDimitry Andric InstrStage::FuncUnits &F) const {
9980b57cec5SDimitry Andric unsigned SchedClass = Inst->getDesc().getSchedClass();
9990b57cec5SDimitry Andric unsigned min = UINT_MAX;
10000b57cec5SDimitry Andric if (InstrItins && !InstrItins->isEmpty()) {
10010b57cec5SDimitry Andric for (const InstrStage &IS :
10020b57cec5SDimitry Andric make_range(InstrItins->beginStage(SchedClass),
10030b57cec5SDimitry Andric InstrItins->endStage(SchedClass))) {
10045ffd83dbSDimitry Andric InstrStage::FuncUnits funcUnits = IS.getUnits();
10050b57cec5SDimitry Andric unsigned numAlternatives = countPopulation(funcUnits);
10060b57cec5SDimitry Andric if (numAlternatives < min) {
10070b57cec5SDimitry Andric min = numAlternatives;
10080b57cec5SDimitry Andric F = funcUnits;
10090b57cec5SDimitry Andric }
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric return min;
10120b57cec5SDimitry Andric }
10130b57cec5SDimitry Andric if (STI && STI->getSchedModel().hasInstrSchedModel()) {
10140b57cec5SDimitry Andric const MCSchedClassDesc *SCDesc =
10150b57cec5SDimitry Andric STI->getSchedModel().getSchedClassDesc(SchedClass);
10160b57cec5SDimitry Andric if (!SCDesc->isValid())
10170b57cec5SDimitry Andric // No valid Schedule Class Desc for schedClass, should be
10180b57cec5SDimitry Andric // Pseudo/PostRAPseudo
10190b57cec5SDimitry Andric return min;
10200b57cec5SDimitry Andric
10210b57cec5SDimitry Andric for (const MCWriteProcResEntry &PRE :
10220b57cec5SDimitry Andric make_range(STI->getWriteProcResBegin(SCDesc),
10230b57cec5SDimitry Andric STI->getWriteProcResEnd(SCDesc))) {
10240b57cec5SDimitry Andric if (!PRE.Cycles)
10250b57cec5SDimitry Andric continue;
10260b57cec5SDimitry Andric const MCProcResourceDesc *ProcResource =
10270b57cec5SDimitry Andric STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
10280b57cec5SDimitry Andric unsigned NumUnits = ProcResource->NumUnits;
10290b57cec5SDimitry Andric if (NumUnits < min) {
10300b57cec5SDimitry Andric min = NumUnits;
10310b57cec5SDimitry Andric F = PRE.ProcResourceIdx;
10320b57cec5SDimitry Andric }
10330b57cec5SDimitry Andric }
10340b57cec5SDimitry Andric return min;
10350b57cec5SDimitry Andric }
10360b57cec5SDimitry Andric llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
10370b57cec5SDimitry Andric }
10380b57cec5SDimitry Andric
10390b57cec5SDimitry Andric // Compute the critical resources needed by the instruction. This
10400b57cec5SDimitry Andric // function records the functional units needed by instructions that
10410b57cec5SDimitry Andric // must use only one functional unit. We use this as a tie breaker
10420b57cec5SDimitry Andric // for computing the resource MII. The instrutions that require
10430b57cec5SDimitry Andric // the same, highly used, functional unit have high priority.
calcCriticalResources__anon6bac73c50d11::FuncUnitSorter10440b57cec5SDimitry Andric void calcCriticalResources(MachineInstr &MI) {
10450b57cec5SDimitry Andric unsigned SchedClass = MI.getDesc().getSchedClass();
10460b57cec5SDimitry Andric if (InstrItins && !InstrItins->isEmpty()) {
10470b57cec5SDimitry Andric for (const InstrStage &IS :
10480b57cec5SDimitry Andric make_range(InstrItins->beginStage(SchedClass),
10490b57cec5SDimitry Andric InstrItins->endStage(SchedClass))) {
10505ffd83dbSDimitry Andric InstrStage::FuncUnits FuncUnits = IS.getUnits();
10510b57cec5SDimitry Andric if (countPopulation(FuncUnits) == 1)
10520b57cec5SDimitry Andric Resources[FuncUnits]++;
10530b57cec5SDimitry Andric }
10540b57cec5SDimitry Andric return;
10550b57cec5SDimitry Andric }
10560b57cec5SDimitry Andric if (STI && STI->getSchedModel().hasInstrSchedModel()) {
10570b57cec5SDimitry Andric const MCSchedClassDesc *SCDesc =
10580b57cec5SDimitry Andric STI->getSchedModel().getSchedClassDesc(SchedClass);
10590b57cec5SDimitry Andric if (!SCDesc->isValid())
10600b57cec5SDimitry Andric // No valid Schedule Class Desc for schedClass, should be
10610b57cec5SDimitry Andric // Pseudo/PostRAPseudo
10620b57cec5SDimitry Andric return;
10630b57cec5SDimitry Andric
10640b57cec5SDimitry Andric for (const MCWriteProcResEntry &PRE :
10650b57cec5SDimitry Andric make_range(STI->getWriteProcResBegin(SCDesc),
10660b57cec5SDimitry Andric STI->getWriteProcResEnd(SCDesc))) {
10670b57cec5SDimitry Andric if (!PRE.Cycles)
10680b57cec5SDimitry Andric continue;
10690b57cec5SDimitry Andric Resources[PRE.ProcResourceIdx]++;
10700b57cec5SDimitry Andric }
10710b57cec5SDimitry Andric return;
10720b57cec5SDimitry Andric }
10730b57cec5SDimitry Andric llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
10740b57cec5SDimitry Andric }
10750b57cec5SDimitry Andric
10760b57cec5SDimitry Andric /// Return true if IS1 has less priority than IS2.
operator ()__anon6bac73c50d11::FuncUnitSorter10770b57cec5SDimitry Andric bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
10785ffd83dbSDimitry Andric InstrStage::FuncUnits F1 = 0, F2 = 0;
10790b57cec5SDimitry Andric unsigned MFUs1 = minFuncUnits(IS1, F1);
10800b57cec5SDimitry Andric unsigned MFUs2 = minFuncUnits(IS2, F2);
10818bcb0991SDimitry Andric if (MFUs1 == MFUs2)
10820b57cec5SDimitry Andric return Resources.lookup(F1) < Resources.lookup(F2);
10830b57cec5SDimitry Andric return MFUs1 > MFUs2;
10840b57cec5SDimitry Andric }
10850b57cec5SDimitry Andric };
10860b57cec5SDimitry Andric
10870b57cec5SDimitry Andric } // end anonymous namespace
10880b57cec5SDimitry Andric
10890b57cec5SDimitry Andric /// Calculate the resource constrained minimum initiation interval for the
10900b57cec5SDimitry Andric /// specified loop. We use the DFA to model the resources needed for
10910b57cec5SDimitry Andric /// each instruction, and we ignore dependences. A different DFA is created
10920b57cec5SDimitry Andric /// for each cycle that is required. When adding a new instruction, we attempt
10930b57cec5SDimitry Andric /// to add it to each existing DFA, until a legal space is found. If the
10940b57cec5SDimitry Andric /// instruction cannot be reserved in an existing DFA, we create a new one.
calculateResMII()10950b57cec5SDimitry Andric unsigned SwingSchedulerDAG::calculateResMII() {
10960b57cec5SDimitry Andric
10970b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "calculateResMII:\n");
10980b57cec5SDimitry Andric SmallVector<ResourceManager*, 8> Resources;
10990b57cec5SDimitry Andric MachineBasicBlock *MBB = Loop.getHeader();
11000b57cec5SDimitry Andric Resources.push_back(new ResourceManager(&MF.getSubtarget()));
11010b57cec5SDimitry Andric
11020b57cec5SDimitry Andric // Sort the instructions by the number of available choices for scheduling,
11030b57cec5SDimitry Andric // least to most. Use the number of critical resources as the tie breaker.
11040b57cec5SDimitry Andric FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
11050b57cec5SDimitry Andric for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
11060b57cec5SDimitry Andric E = MBB->getFirstTerminator();
11070b57cec5SDimitry Andric I != E; ++I)
11080b57cec5SDimitry Andric FUS.calcCriticalResources(*I);
11090b57cec5SDimitry Andric PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
11100b57cec5SDimitry Andric FuncUnitOrder(FUS);
11110b57cec5SDimitry Andric
11120b57cec5SDimitry Andric for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
11130b57cec5SDimitry Andric E = MBB->getFirstTerminator();
11140b57cec5SDimitry Andric I != E; ++I)
11150b57cec5SDimitry Andric FuncUnitOrder.push(&*I);
11160b57cec5SDimitry Andric
11170b57cec5SDimitry Andric while (!FuncUnitOrder.empty()) {
11180b57cec5SDimitry Andric MachineInstr *MI = FuncUnitOrder.top();
11190b57cec5SDimitry Andric FuncUnitOrder.pop();
11200b57cec5SDimitry Andric if (TII->isZeroCost(MI->getOpcode()))
11210b57cec5SDimitry Andric continue;
11220b57cec5SDimitry Andric // Attempt to reserve the instruction in an existing DFA. At least one
11230b57cec5SDimitry Andric // DFA is needed for each cycle.
11240b57cec5SDimitry Andric unsigned NumCycles = getSUnit(MI)->Latency;
11250b57cec5SDimitry Andric unsigned ReservedCycles = 0;
11260b57cec5SDimitry Andric SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
11270b57cec5SDimitry Andric SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
11280b57cec5SDimitry Andric LLVM_DEBUG({
11290b57cec5SDimitry Andric dbgs() << "Trying to reserve resource for " << NumCycles
11300b57cec5SDimitry Andric << " cycles for \n";
11310b57cec5SDimitry Andric MI->dump();
11320b57cec5SDimitry Andric });
11330b57cec5SDimitry Andric for (unsigned C = 0; C < NumCycles; ++C)
11340b57cec5SDimitry Andric while (RI != RE) {
11350b57cec5SDimitry Andric if ((*RI)->canReserveResources(*MI)) {
11360b57cec5SDimitry Andric (*RI)->reserveResources(*MI);
11370b57cec5SDimitry Andric ++ReservedCycles;
11380b57cec5SDimitry Andric break;
11390b57cec5SDimitry Andric }
11400b57cec5SDimitry Andric RI++;
11410b57cec5SDimitry Andric }
11420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
11430b57cec5SDimitry Andric << ", NumCycles:" << NumCycles << "\n");
11440b57cec5SDimitry Andric // Add new DFAs, if needed, to reserve resources.
11450b57cec5SDimitry Andric for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
11460b57cec5SDimitry Andric LLVM_DEBUG(if (SwpDebugResource) dbgs()
11470b57cec5SDimitry Andric << "NewResource created to reserve resources"
11480b57cec5SDimitry Andric << "\n");
11490b57cec5SDimitry Andric ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
11500b57cec5SDimitry Andric assert(NewResource->canReserveResources(*MI) && "Reserve error.");
11510b57cec5SDimitry Andric NewResource->reserveResources(*MI);
11520b57cec5SDimitry Andric Resources.push_back(NewResource);
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric }
11550b57cec5SDimitry Andric int Resmii = Resources.size();
11565ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
11570b57cec5SDimitry Andric // Delete the memory for each of the DFAs that were created earlier.
11580b57cec5SDimitry Andric for (ResourceManager *RI : Resources) {
11590b57cec5SDimitry Andric ResourceManager *D = RI;
11600b57cec5SDimitry Andric delete D;
11610b57cec5SDimitry Andric }
11620b57cec5SDimitry Andric Resources.clear();
11630b57cec5SDimitry Andric return Resmii;
11640b57cec5SDimitry Andric }
11650b57cec5SDimitry Andric
11660b57cec5SDimitry Andric /// Calculate the recurrence-constrainted minimum initiation interval.
11670b57cec5SDimitry Andric /// Iterate over each circuit. Compute the delay(c) and distance(c)
11680b57cec5SDimitry Andric /// for each circuit. The II needs to satisfy the inequality
11690b57cec5SDimitry Andric /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
11700b57cec5SDimitry Andric /// II that satisfies the inequality, and the RecMII is the maximum
11710b57cec5SDimitry Andric /// of those values.
calculateRecMII(NodeSetType & NodeSets)11720b57cec5SDimitry Andric unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
11730b57cec5SDimitry Andric unsigned RecMII = 0;
11740b57cec5SDimitry Andric
11750b57cec5SDimitry Andric for (NodeSet &Nodes : NodeSets) {
11760b57cec5SDimitry Andric if (Nodes.empty())
11770b57cec5SDimitry Andric continue;
11780b57cec5SDimitry Andric
11790b57cec5SDimitry Andric unsigned Delay = Nodes.getLatency();
11800b57cec5SDimitry Andric unsigned Distance = 1;
11810b57cec5SDimitry Andric
11820b57cec5SDimitry Andric // ii = ceil(delay / distance)
11830b57cec5SDimitry Andric unsigned CurMII = (Delay + Distance - 1) / Distance;
11840b57cec5SDimitry Andric Nodes.setRecMII(CurMII);
11850b57cec5SDimitry Andric if (CurMII > RecMII)
11860b57cec5SDimitry Andric RecMII = CurMII;
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric
11890b57cec5SDimitry Andric return RecMII;
11900b57cec5SDimitry Andric }
11910b57cec5SDimitry Andric
11920b57cec5SDimitry Andric /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
11930b57cec5SDimitry Andric /// but we do this to find the circuits, and then change them back.
swapAntiDependences(std::vector<SUnit> & SUnits)11940b57cec5SDimitry Andric static void swapAntiDependences(std::vector<SUnit> &SUnits) {
11950b57cec5SDimitry Andric SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
11960b57cec5SDimitry Andric for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
11970b57cec5SDimitry Andric SUnit *SU = &SUnits[i];
11980b57cec5SDimitry Andric for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
11990b57cec5SDimitry Andric IP != EP; ++IP) {
12000b57cec5SDimitry Andric if (IP->getKind() != SDep::Anti)
12010b57cec5SDimitry Andric continue;
12020b57cec5SDimitry Andric DepsAdded.push_back(std::make_pair(SU, *IP));
12030b57cec5SDimitry Andric }
12040b57cec5SDimitry Andric }
1205*5f7ddb14SDimitry Andric for (std::pair<SUnit *, SDep> &P : DepsAdded) {
12060b57cec5SDimitry Andric // Remove this anti dependency and add one in the reverse direction.
1207*5f7ddb14SDimitry Andric SUnit *SU = P.first;
1208*5f7ddb14SDimitry Andric SDep &D = P.second;
12090b57cec5SDimitry Andric SUnit *TargetSU = D.getSUnit();
12100b57cec5SDimitry Andric unsigned Reg = D.getReg();
12110b57cec5SDimitry Andric unsigned Lat = D.getLatency();
12120b57cec5SDimitry Andric SU->removePred(D);
12130b57cec5SDimitry Andric SDep Dep(SU, SDep::Anti, Reg);
12140b57cec5SDimitry Andric Dep.setLatency(Lat);
12150b57cec5SDimitry Andric TargetSU->addPred(Dep);
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric }
12180b57cec5SDimitry Andric
12190b57cec5SDimitry Andric /// Create the adjacency structure of the nodes in the graph.
createAdjacencyStructure(SwingSchedulerDAG * DAG)12200b57cec5SDimitry Andric void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
12210b57cec5SDimitry Andric SwingSchedulerDAG *DAG) {
12220b57cec5SDimitry Andric BitVector Added(SUnits.size());
12230b57cec5SDimitry Andric DenseMap<int, int> OutputDeps;
12240b57cec5SDimitry Andric for (int i = 0, e = SUnits.size(); i != e; ++i) {
12250b57cec5SDimitry Andric Added.reset();
12260b57cec5SDimitry Andric // Add any successor to the adjacency matrix and exclude duplicates.
12270b57cec5SDimitry Andric for (auto &SI : SUnits[i].Succs) {
12280b57cec5SDimitry Andric // Only create a back-edge on the first and last nodes of a dependence
12290b57cec5SDimitry Andric // chain. This records any chains and adds them later.
12300b57cec5SDimitry Andric if (SI.getKind() == SDep::Output) {
12310b57cec5SDimitry Andric int N = SI.getSUnit()->NodeNum;
12320b57cec5SDimitry Andric int BackEdge = i;
12330b57cec5SDimitry Andric auto Dep = OutputDeps.find(BackEdge);
12340b57cec5SDimitry Andric if (Dep != OutputDeps.end()) {
12350b57cec5SDimitry Andric BackEdge = Dep->second;
12360b57cec5SDimitry Andric OutputDeps.erase(Dep);
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric OutputDeps[N] = BackEdge;
12390b57cec5SDimitry Andric }
12400b57cec5SDimitry Andric // Do not process a boundary node, an artificial node.
12410b57cec5SDimitry Andric // A back-edge is processed only if it goes to a Phi.
12420b57cec5SDimitry Andric if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
12430b57cec5SDimitry Andric (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
12440b57cec5SDimitry Andric continue;
12450b57cec5SDimitry Andric int N = SI.getSUnit()->NodeNum;
12460b57cec5SDimitry Andric if (!Added.test(N)) {
12470b57cec5SDimitry Andric AdjK[i].push_back(N);
12480b57cec5SDimitry Andric Added.set(N);
12490b57cec5SDimitry Andric }
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric // A chain edge between a store and a load is treated as a back-edge in the
12520b57cec5SDimitry Andric // adjacency matrix.
12530b57cec5SDimitry Andric for (auto &PI : SUnits[i].Preds) {
12540b57cec5SDimitry Andric if (!SUnits[i].getInstr()->mayStore() ||
12550b57cec5SDimitry Andric !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
12560b57cec5SDimitry Andric continue;
12570b57cec5SDimitry Andric if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
12580b57cec5SDimitry Andric int N = PI.getSUnit()->NodeNum;
12590b57cec5SDimitry Andric if (!Added.test(N)) {
12600b57cec5SDimitry Andric AdjK[i].push_back(N);
12610b57cec5SDimitry Andric Added.set(N);
12620b57cec5SDimitry Andric }
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric }
12650b57cec5SDimitry Andric }
12660b57cec5SDimitry Andric // Add back-edges in the adjacency matrix for the output dependences.
12670b57cec5SDimitry Andric for (auto &OD : OutputDeps)
12680b57cec5SDimitry Andric if (!Added.test(OD.second)) {
12690b57cec5SDimitry Andric AdjK[OD.first].push_back(OD.second);
12700b57cec5SDimitry Andric Added.set(OD.second);
12710b57cec5SDimitry Andric }
12720b57cec5SDimitry Andric }
12730b57cec5SDimitry Andric
12740b57cec5SDimitry Andric /// Identify an elementary circuit in the dependence graph starting at the
12750b57cec5SDimitry Andric /// specified node.
circuit(int V,int S,NodeSetType & NodeSets,bool HasBackedge)12760b57cec5SDimitry Andric bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
12770b57cec5SDimitry Andric bool HasBackedge) {
12780b57cec5SDimitry Andric SUnit *SV = &SUnits[V];
12790b57cec5SDimitry Andric bool F = false;
12800b57cec5SDimitry Andric Stack.insert(SV);
12810b57cec5SDimitry Andric Blocked.set(V);
12820b57cec5SDimitry Andric
12830b57cec5SDimitry Andric for (auto W : AdjK[V]) {
12840b57cec5SDimitry Andric if (NumPaths > MaxPaths)
12850b57cec5SDimitry Andric break;
12860b57cec5SDimitry Andric if (W < S)
12870b57cec5SDimitry Andric continue;
12880b57cec5SDimitry Andric if (W == S) {
12890b57cec5SDimitry Andric if (!HasBackedge)
12900b57cec5SDimitry Andric NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
12910b57cec5SDimitry Andric F = true;
12920b57cec5SDimitry Andric ++NumPaths;
12930b57cec5SDimitry Andric break;
12940b57cec5SDimitry Andric } else if (!Blocked.test(W)) {
12950b57cec5SDimitry Andric if (circuit(W, S, NodeSets,
12960b57cec5SDimitry Andric Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
12970b57cec5SDimitry Andric F = true;
12980b57cec5SDimitry Andric }
12990b57cec5SDimitry Andric }
13000b57cec5SDimitry Andric
13010b57cec5SDimitry Andric if (F)
13020b57cec5SDimitry Andric unblock(V);
13030b57cec5SDimitry Andric else {
13040b57cec5SDimitry Andric for (auto W : AdjK[V]) {
13050b57cec5SDimitry Andric if (W < S)
13060b57cec5SDimitry Andric continue;
13070b57cec5SDimitry Andric if (B[W].count(SV) == 0)
13080b57cec5SDimitry Andric B[W].insert(SV);
13090b57cec5SDimitry Andric }
13100b57cec5SDimitry Andric }
13110b57cec5SDimitry Andric Stack.pop_back();
13120b57cec5SDimitry Andric return F;
13130b57cec5SDimitry Andric }
13140b57cec5SDimitry Andric
13150b57cec5SDimitry Andric /// Unblock a node in the circuit finding algorithm.
unblock(int U)13160b57cec5SDimitry Andric void SwingSchedulerDAG::Circuits::unblock(int U) {
13170b57cec5SDimitry Andric Blocked.reset(U);
13180b57cec5SDimitry Andric SmallPtrSet<SUnit *, 4> &BU = B[U];
13190b57cec5SDimitry Andric while (!BU.empty()) {
13200b57cec5SDimitry Andric SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
13210b57cec5SDimitry Andric assert(SI != BU.end() && "Invalid B set.");
13220b57cec5SDimitry Andric SUnit *W = *SI;
13230b57cec5SDimitry Andric BU.erase(W);
13240b57cec5SDimitry Andric if (Blocked.test(W->NodeNum))
13250b57cec5SDimitry Andric unblock(W->NodeNum);
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric }
13280b57cec5SDimitry Andric
13290b57cec5SDimitry Andric /// Identify all the elementary circuits in the dependence graph using
13300b57cec5SDimitry Andric /// Johnson's circuit algorithm.
findCircuits(NodeSetType & NodeSets)13310b57cec5SDimitry Andric void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
13320b57cec5SDimitry Andric // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
13330b57cec5SDimitry Andric // but we do this to find the circuits, and then change them back.
13340b57cec5SDimitry Andric swapAntiDependences(SUnits);
13350b57cec5SDimitry Andric
13360b57cec5SDimitry Andric Circuits Cir(SUnits, Topo);
13370b57cec5SDimitry Andric // Create the adjacency structure.
13380b57cec5SDimitry Andric Cir.createAdjacencyStructure(this);
13390b57cec5SDimitry Andric for (int i = 0, e = SUnits.size(); i != e; ++i) {
13400b57cec5SDimitry Andric Cir.reset();
13410b57cec5SDimitry Andric Cir.circuit(i, i, NodeSets);
13420b57cec5SDimitry Andric }
13430b57cec5SDimitry Andric
13440b57cec5SDimitry Andric // Change the dependences back so that we've created a DAG again.
13450b57cec5SDimitry Andric swapAntiDependences(SUnits);
13460b57cec5SDimitry Andric }
13470b57cec5SDimitry Andric
13480b57cec5SDimitry Andric // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
13490b57cec5SDimitry Andric // is loop-carried to the USE in next iteration. This will help pipeliner avoid
13500b57cec5SDimitry Andric // additional copies that are needed across iterations. An artificial dependence
13510b57cec5SDimitry Andric // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
13520b57cec5SDimitry Andric
13530b57cec5SDimitry Andric // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
13540b57cec5SDimitry Andric // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
13550b57cec5SDimitry Andric // PHI-------True-Dep------> USEOfPhi
13560b57cec5SDimitry Andric
13570b57cec5SDimitry Andric // The mutation creates
13580b57cec5SDimitry Andric // USEOfPHI -------Artificial-Dep---> SRCOfCopy
13590b57cec5SDimitry Andric
13600b57cec5SDimitry Andric // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
13610b57cec5SDimitry Andric // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
13620b57cec5SDimitry Andric // late to avoid additional copies across iterations. The possible scheduling
13630b57cec5SDimitry Andric // order would be
13640b57cec5SDimitry Andric // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
13650b57cec5SDimitry Andric
apply(ScheduleDAGInstrs * DAG)13660b57cec5SDimitry Andric void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
13670b57cec5SDimitry Andric for (SUnit &SU : DAG->SUnits) {
13680b57cec5SDimitry Andric // Find the COPY/REG_SEQUENCE instruction.
13690b57cec5SDimitry Andric if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
13700b57cec5SDimitry Andric continue;
13710b57cec5SDimitry Andric
13720b57cec5SDimitry Andric // Record the loop carried PHIs.
13730b57cec5SDimitry Andric SmallVector<SUnit *, 4> PHISUs;
13740b57cec5SDimitry Andric // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
13750b57cec5SDimitry Andric SmallVector<SUnit *, 4> SrcSUs;
13760b57cec5SDimitry Andric
13770b57cec5SDimitry Andric for (auto &Dep : SU.Preds) {
13780b57cec5SDimitry Andric SUnit *TmpSU = Dep.getSUnit();
13790b57cec5SDimitry Andric MachineInstr *TmpMI = TmpSU->getInstr();
13800b57cec5SDimitry Andric SDep::Kind DepKind = Dep.getKind();
13810b57cec5SDimitry Andric // Save the loop carried PHI.
13820b57cec5SDimitry Andric if (DepKind == SDep::Anti && TmpMI->isPHI())
13830b57cec5SDimitry Andric PHISUs.push_back(TmpSU);
13840b57cec5SDimitry Andric // Save the source of COPY/REG_SEQUENCE.
13850b57cec5SDimitry Andric // If the source has no pre-decessors, we will end up creating cycles.
13860b57cec5SDimitry Andric else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
13870b57cec5SDimitry Andric SrcSUs.push_back(TmpSU);
13880b57cec5SDimitry Andric }
13890b57cec5SDimitry Andric
13900b57cec5SDimitry Andric if (PHISUs.size() == 0 || SrcSUs.size() == 0)
13910b57cec5SDimitry Andric continue;
13920b57cec5SDimitry Andric
13930b57cec5SDimitry Andric // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
13940b57cec5SDimitry Andric // SUnit to the container.
13950b57cec5SDimitry Andric SmallVector<SUnit *, 8> UseSUs;
1396480093f4SDimitry Andric // Do not use iterator based loop here as we are updating the container.
1397480093f4SDimitry Andric for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
1398480093f4SDimitry Andric for (auto &Dep : PHISUs[Index]->Succs) {
13990b57cec5SDimitry Andric if (Dep.getKind() != SDep::Data)
14000b57cec5SDimitry Andric continue;
14010b57cec5SDimitry Andric
14020b57cec5SDimitry Andric SUnit *TmpSU = Dep.getSUnit();
14030b57cec5SDimitry Andric MachineInstr *TmpMI = TmpSU->getInstr();
14040b57cec5SDimitry Andric if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
14050b57cec5SDimitry Andric PHISUs.push_back(TmpSU);
14060b57cec5SDimitry Andric continue;
14070b57cec5SDimitry Andric }
14080b57cec5SDimitry Andric UseSUs.push_back(TmpSU);
14090b57cec5SDimitry Andric }
14100b57cec5SDimitry Andric }
14110b57cec5SDimitry Andric
14120b57cec5SDimitry Andric if (UseSUs.size() == 0)
14130b57cec5SDimitry Andric continue;
14140b57cec5SDimitry Andric
14150b57cec5SDimitry Andric SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
14160b57cec5SDimitry Andric // Add the artificial dependencies if it does not form a cycle.
14170b57cec5SDimitry Andric for (auto I : UseSUs) {
14180b57cec5SDimitry Andric for (auto Src : SrcSUs) {
14190b57cec5SDimitry Andric if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
14200b57cec5SDimitry Andric Src->addPred(SDep(I, SDep::Artificial));
14210b57cec5SDimitry Andric SDAG->Topo.AddPred(Src, I);
14220b57cec5SDimitry Andric }
14230b57cec5SDimitry Andric }
14240b57cec5SDimitry Andric }
14250b57cec5SDimitry Andric }
14260b57cec5SDimitry Andric }
14270b57cec5SDimitry Andric
14280b57cec5SDimitry Andric /// Return true for DAG nodes that we ignore when computing the cost functions.
14290b57cec5SDimitry Andric /// We ignore the back-edge recurrence in order to avoid unbounded recursion
14300b57cec5SDimitry Andric /// in the calculation of the ASAP, ALAP, etc functions.
ignoreDependence(const SDep & D,bool isPred)14310b57cec5SDimitry Andric static bool ignoreDependence(const SDep &D, bool isPred) {
14320b57cec5SDimitry Andric if (D.isArtificial())
14330b57cec5SDimitry Andric return true;
14340b57cec5SDimitry Andric return D.getKind() == SDep::Anti && isPred;
14350b57cec5SDimitry Andric }
14360b57cec5SDimitry Andric
14370b57cec5SDimitry Andric /// Compute several functions need to order the nodes for scheduling.
14380b57cec5SDimitry Andric /// ASAP - Earliest time to schedule a node.
14390b57cec5SDimitry Andric /// ALAP - Latest time to schedule a node.
14400b57cec5SDimitry Andric /// MOV - Mobility function, difference between ALAP and ASAP.
14410b57cec5SDimitry Andric /// D - Depth of each node.
14420b57cec5SDimitry Andric /// H - Height of each node.
computeNodeFunctions(NodeSetType & NodeSets)14430b57cec5SDimitry Andric void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
14440b57cec5SDimitry Andric ScheduleInfo.resize(SUnits.size());
14450b57cec5SDimitry Andric
14460b57cec5SDimitry Andric LLVM_DEBUG({
1447*5f7ddb14SDimitry Andric for (int I : Topo) {
1448*5f7ddb14SDimitry Andric const SUnit &SU = SUnits[I];
14490b57cec5SDimitry Andric dumpNode(SU);
14500b57cec5SDimitry Andric }
14510b57cec5SDimitry Andric });
14520b57cec5SDimitry Andric
14530b57cec5SDimitry Andric int maxASAP = 0;
14540b57cec5SDimitry Andric // Compute ASAP and ZeroLatencyDepth.
1455*5f7ddb14SDimitry Andric for (int I : Topo) {
14560b57cec5SDimitry Andric int asap = 0;
14570b57cec5SDimitry Andric int zeroLatencyDepth = 0;
1458*5f7ddb14SDimitry Andric SUnit *SU = &SUnits[I];
14590b57cec5SDimitry Andric for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
14600b57cec5SDimitry Andric EP = SU->Preds.end();
14610b57cec5SDimitry Andric IP != EP; ++IP) {
14620b57cec5SDimitry Andric SUnit *pred = IP->getSUnit();
14630b57cec5SDimitry Andric if (IP->getLatency() == 0)
14640b57cec5SDimitry Andric zeroLatencyDepth =
14650b57cec5SDimitry Andric std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
14660b57cec5SDimitry Andric if (ignoreDependence(*IP, true))
14670b57cec5SDimitry Andric continue;
14680b57cec5SDimitry Andric asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
14690b57cec5SDimitry Andric getDistance(pred, SU, *IP) * MII));
14700b57cec5SDimitry Andric }
14710b57cec5SDimitry Andric maxASAP = std::max(maxASAP, asap);
1472*5f7ddb14SDimitry Andric ScheduleInfo[I].ASAP = asap;
1473*5f7ddb14SDimitry Andric ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric
14760b57cec5SDimitry Andric // Compute ALAP, ZeroLatencyHeight, and MOV.
14770b57cec5SDimitry Andric for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
14780b57cec5SDimitry Andric E = Topo.rend();
14790b57cec5SDimitry Andric I != E; ++I) {
14800b57cec5SDimitry Andric int alap = maxASAP;
14810b57cec5SDimitry Andric int zeroLatencyHeight = 0;
14820b57cec5SDimitry Andric SUnit *SU = &SUnits[*I];
14830b57cec5SDimitry Andric for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
14840b57cec5SDimitry Andric ES = SU->Succs.end();
14850b57cec5SDimitry Andric IS != ES; ++IS) {
14860b57cec5SDimitry Andric SUnit *succ = IS->getSUnit();
14870b57cec5SDimitry Andric if (IS->getLatency() == 0)
14880b57cec5SDimitry Andric zeroLatencyHeight =
14890b57cec5SDimitry Andric std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
14900b57cec5SDimitry Andric if (ignoreDependence(*IS, true))
14910b57cec5SDimitry Andric continue;
14920b57cec5SDimitry Andric alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
14930b57cec5SDimitry Andric getDistance(SU, succ, *IS) * MII));
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric
14960b57cec5SDimitry Andric ScheduleInfo[*I].ALAP = alap;
14970b57cec5SDimitry Andric ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
14980b57cec5SDimitry Andric }
14990b57cec5SDimitry Andric
15000b57cec5SDimitry Andric // After computing the node functions, compute the summary for each node set.
15010b57cec5SDimitry Andric for (NodeSet &I : NodeSets)
15020b57cec5SDimitry Andric I.computeNodeSetInfo(this);
15030b57cec5SDimitry Andric
15040b57cec5SDimitry Andric LLVM_DEBUG({
15050b57cec5SDimitry Andric for (unsigned i = 0; i < SUnits.size(); i++) {
15060b57cec5SDimitry Andric dbgs() << "\tNode " << i << ":\n";
15070b57cec5SDimitry Andric dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
15080b57cec5SDimitry Andric dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
15090b57cec5SDimitry Andric dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
15100b57cec5SDimitry Andric dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
15110b57cec5SDimitry Andric dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
15120b57cec5SDimitry Andric dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
15130b57cec5SDimitry Andric dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric });
15160b57cec5SDimitry Andric }
15170b57cec5SDimitry Andric
15180b57cec5SDimitry Andric /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
15190b57cec5SDimitry Andric /// as the predecessors of the elements of NodeOrder that are not also in
15200b57cec5SDimitry Andric /// NodeOrder.
pred_L(SetVector<SUnit * > & NodeOrder,SmallSetVector<SUnit *,8> & Preds,const NodeSet * S=nullptr)15210b57cec5SDimitry Andric static bool pred_L(SetVector<SUnit *> &NodeOrder,
15220b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> &Preds,
15230b57cec5SDimitry Andric const NodeSet *S = nullptr) {
15240b57cec5SDimitry Andric Preds.clear();
15250b57cec5SDimitry Andric for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
15260b57cec5SDimitry Andric I != E; ++I) {
1527*5f7ddb14SDimitry Andric for (const SDep &Pred : (*I)->Preds) {
1528*5f7ddb14SDimitry Andric if (S && S->count(Pred.getSUnit()) == 0)
15290b57cec5SDimitry Andric continue;
1530*5f7ddb14SDimitry Andric if (ignoreDependence(Pred, true))
15310b57cec5SDimitry Andric continue;
1532*5f7ddb14SDimitry Andric if (NodeOrder.count(Pred.getSUnit()) == 0)
1533*5f7ddb14SDimitry Andric Preds.insert(Pred.getSUnit());
15340b57cec5SDimitry Andric }
15350b57cec5SDimitry Andric // Back-edges are predecessors with an anti-dependence.
1536*5f7ddb14SDimitry Andric for (const SDep &Succ : (*I)->Succs) {
1537*5f7ddb14SDimitry Andric if (Succ.getKind() != SDep::Anti)
15380b57cec5SDimitry Andric continue;
1539*5f7ddb14SDimitry Andric if (S && S->count(Succ.getSUnit()) == 0)
15400b57cec5SDimitry Andric continue;
1541*5f7ddb14SDimitry Andric if (NodeOrder.count(Succ.getSUnit()) == 0)
1542*5f7ddb14SDimitry Andric Preds.insert(Succ.getSUnit());
15430b57cec5SDimitry Andric }
15440b57cec5SDimitry Andric }
15450b57cec5SDimitry Andric return !Preds.empty();
15460b57cec5SDimitry Andric }
15470b57cec5SDimitry Andric
15480b57cec5SDimitry Andric /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
15490b57cec5SDimitry Andric /// as the successors of the elements of NodeOrder that are not also in
15500b57cec5SDimitry Andric /// NodeOrder.
succ_L(SetVector<SUnit * > & NodeOrder,SmallSetVector<SUnit *,8> & Succs,const NodeSet * S=nullptr)15510b57cec5SDimitry Andric static bool succ_L(SetVector<SUnit *> &NodeOrder,
15520b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> &Succs,
15530b57cec5SDimitry Andric const NodeSet *S = nullptr) {
15540b57cec5SDimitry Andric Succs.clear();
15550b57cec5SDimitry Andric for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
15560b57cec5SDimitry Andric I != E; ++I) {
1557*5f7ddb14SDimitry Andric for (SDep &Succ : (*I)->Succs) {
1558*5f7ddb14SDimitry Andric if (S && S->count(Succ.getSUnit()) == 0)
15590b57cec5SDimitry Andric continue;
1560*5f7ddb14SDimitry Andric if (ignoreDependence(Succ, false))
15610b57cec5SDimitry Andric continue;
1562*5f7ddb14SDimitry Andric if (NodeOrder.count(Succ.getSUnit()) == 0)
1563*5f7ddb14SDimitry Andric Succs.insert(Succ.getSUnit());
15640b57cec5SDimitry Andric }
1565*5f7ddb14SDimitry Andric for (SDep &Pred : (*I)->Preds) {
1566*5f7ddb14SDimitry Andric if (Pred.getKind() != SDep::Anti)
15670b57cec5SDimitry Andric continue;
1568*5f7ddb14SDimitry Andric if (S && S->count(Pred.getSUnit()) == 0)
15690b57cec5SDimitry Andric continue;
1570*5f7ddb14SDimitry Andric if (NodeOrder.count(Pred.getSUnit()) == 0)
1571*5f7ddb14SDimitry Andric Succs.insert(Pred.getSUnit());
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric }
15740b57cec5SDimitry Andric return !Succs.empty();
15750b57cec5SDimitry Andric }
15760b57cec5SDimitry Andric
15770b57cec5SDimitry Andric /// Return true if there is a path from the specified node to any of the nodes
15780b57cec5SDimitry Andric /// in DestNodes. Keep track and return the nodes in any path.
computePath(SUnit * Cur,SetVector<SUnit * > & Path,SetVector<SUnit * > & DestNodes,SetVector<SUnit * > & Exclude,SmallPtrSet<SUnit *,8> & Visited)15790b57cec5SDimitry Andric static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
15800b57cec5SDimitry Andric SetVector<SUnit *> &DestNodes,
15810b57cec5SDimitry Andric SetVector<SUnit *> &Exclude,
15820b57cec5SDimitry Andric SmallPtrSet<SUnit *, 8> &Visited) {
15830b57cec5SDimitry Andric if (Cur->isBoundaryNode())
15840b57cec5SDimitry Andric return false;
1585af732203SDimitry Andric if (Exclude.contains(Cur))
15860b57cec5SDimitry Andric return false;
1587af732203SDimitry Andric if (DestNodes.contains(Cur))
15880b57cec5SDimitry Andric return true;
15890b57cec5SDimitry Andric if (!Visited.insert(Cur).second)
1590af732203SDimitry Andric return Path.contains(Cur);
15910b57cec5SDimitry Andric bool FoundPath = false;
15920b57cec5SDimitry Andric for (auto &SI : Cur->Succs)
15930b57cec5SDimitry Andric FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
15940b57cec5SDimitry Andric for (auto &PI : Cur->Preds)
15950b57cec5SDimitry Andric if (PI.getKind() == SDep::Anti)
15960b57cec5SDimitry Andric FoundPath |=
15970b57cec5SDimitry Andric computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
15980b57cec5SDimitry Andric if (FoundPath)
15990b57cec5SDimitry Andric Path.insert(Cur);
16000b57cec5SDimitry Andric return FoundPath;
16010b57cec5SDimitry Andric }
16020b57cec5SDimitry Andric
16030b57cec5SDimitry Andric /// Compute the live-out registers for the instructions in a node-set.
16040b57cec5SDimitry Andric /// The live-out registers are those that are defined in the node-set,
16050b57cec5SDimitry Andric /// but not used. Except for use operands of Phis.
computeLiveOuts(MachineFunction & MF,RegPressureTracker & RPTracker,NodeSet & NS)16060b57cec5SDimitry Andric static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
16070b57cec5SDimitry Andric NodeSet &NS) {
16080b57cec5SDimitry Andric const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
16090b57cec5SDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo();
16100b57cec5SDimitry Andric SmallVector<RegisterMaskPair, 8> LiveOutRegs;
16110b57cec5SDimitry Andric SmallSet<unsigned, 4> Uses;
16120b57cec5SDimitry Andric for (SUnit *SU : NS) {
16130b57cec5SDimitry Andric const MachineInstr *MI = SU->getInstr();
16140b57cec5SDimitry Andric if (MI->isPHI())
16150b57cec5SDimitry Andric continue;
16160b57cec5SDimitry Andric for (const MachineOperand &MO : MI->operands())
16170b57cec5SDimitry Andric if (MO.isReg() && MO.isUse()) {
16188bcb0991SDimitry Andric Register Reg = MO.getReg();
16198bcb0991SDimitry Andric if (Register::isVirtualRegister(Reg))
16200b57cec5SDimitry Andric Uses.insert(Reg);
16210b57cec5SDimitry Andric else if (MRI.isAllocatable(Reg))
1622af732203SDimitry Andric for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1623af732203SDimitry Andric ++Units)
16240b57cec5SDimitry Andric Uses.insert(*Units);
16250b57cec5SDimitry Andric }
16260b57cec5SDimitry Andric }
16270b57cec5SDimitry Andric for (SUnit *SU : NS)
16280b57cec5SDimitry Andric for (const MachineOperand &MO : SU->getInstr()->operands())
16290b57cec5SDimitry Andric if (MO.isReg() && MO.isDef() && !MO.isDead()) {
16308bcb0991SDimitry Andric Register Reg = MO.getReg();
16318bcb0991SDimitry Andric if (Register::isVirtualRegister(Reg)) {
16320b57cec5SDimitry Andric if (!Uses.count(Reg))
16330b57cec5SDimitry Andric LiveOutRegs.push_back(RegisterMaskPair(Reg,
16340b57cec5SDimitry Andric LaneBitmask::getNone()));
16350b57cec5SDimitry Andric } else if (MRI.isAllocatable(Reg)) {
1636af732203SDimitry Andric for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1637af732203SDimitry Andric ++Units)
16380b57cec5SDimitry Andric if (!Uses.count(*Units))
16390b57cec5SDimitry Andric LiveOutRegs.push_back(RegisterMaskPair(*Units,
16400b57cec5SDimitry Andric LaneBitmask::getNone()));
16410b57cec5SDimitry Andric }
16420b57cec5SDimitry Andric }
16430b57cec5SDimitry Andric RPTracker.addLiveRegs(LiveOutRegs);
16440b57cec5SDimitry Andric }
16450b57cec5SDimitry Andric
16460b57cec5SDimitry Andric /// A heuristic to filter nodes in recurrent node-sets if the register
16470b57cec5SDimitry Andric /// pressure of a set is too high.
registerPressureFilter(NodeSetType & NodeSets)16480b57cec5SDimitry Andric void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
16490b57cec5SDimitry Andric for (auto &NS : NodeSets) {
16500b57cec5SDimitry Andric // Skip small node-sets since they won't cause register pressure problems.
16510b57cec5SDimitry Andric if (NS.size() <= 2)
16520b57cec5SDimitry Andric continue;
16530b57cec5SDimitry Andric IntervalPressure RecRegPressure;
16540b57cec5SDimitry Andric RegPressureTracker RecRPTracker(RecRegPressure);
16550b57cec5SDimitry Andric RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
16560b57cec5SDimitry Andric computeLiveOuts(MF, RecRPTracker, NS);
16570b57cec5SDimitry Andric RecRPTracker.closeBottom();
16580b57cec5SDimitry Andric
16590b57cec5SDimitry Andric std::vector<SUnit *> SUnits(NS.begin(), NS.end());
16600b57cec5SDimitry Andric llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
16610b57cec5SDimitry Andric return A->NodeNum > B->NodeNum;
16620b57cec5SDimitry Andric });
16630b57cec5SDimitry Andric
16640b57cec5SDimitry Andric for (auto &SU : SUnits) {
16650b57cec5SDimitry Andric // Since we're computing the register pressure for a subset of the
16660b57cec5SDimitry Andric // instructions in a block, we need to set the tracker for each
16670b57cec5SDimitry Andric // instruction in the node-set. The tracker is set to the instruction
16680b57cec5SDimitry Andric // just after the one we're interested in.
16690b57cec5SDimitry Andric MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
16700b57cec5SDimitry Andric RecRPTracker.setPos(std::next(CurInstI));
16710b57cec5SDimitry Andric
16720b57cec5SDimitry Andric RegPressureDelta RPDelta;
16730b57cec5SDimitry Andric ArrayRef<PressureChange> CriticalPSets;
16740b57cec5SDimitry Andric RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
16750b57cec5SDimitry Andric CriticalPSets,
16760b57cec5SDimitry Andric RecRegPressure.MaxSetPressure);
16770b57cec5SDimitry Andric if (RPDelta.Excess.isValid()) {
16780b57cec5SDimitry Andric LLVM_DEBUG(
16790b57cec5SDimitry Andric dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
16800b57cec5SDimitry Andric << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
16810b57cec5SDimitry Andric << ":" << RPDelta.Excess.getUnitInc());
16820b57cec5SDimitry Andric NS.setExceedPressure(SU);
16830b57cec5SDimitry Andric break;
16840b57cec5SDimitry Andric }
16850b57cec5SDimitry Andric RecRPTracker.recede();
16860b57cec5SDimitry Andric }
16870b57cec5SDimitry Andric }
16880b57cec5SDimitry Andric }
16890b57cec5SDimitry Andric
16900b57cec5SDimitry Andric /// A heuristic to colocate node sets that have the same set of
16910b57cec5SDimitry Andric /// successors.
colocateNodeSets(NodeSetType & NodeSets)16920b57cec5SDimitry Andric void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
16930b57cec5SDimitry Andric unsigned Colocate = 0;
16940b57cec5SDimitry Andric for (int i = 0, e = NodeSets.size(); i < e; ++i) {
16950b57cec5SDimitry Andric NodeSet &N1 = NodeSets[i];
16960b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> S1;
16970b57cec5SDimitry Andric if (N1.empty() || !succ_L(N1, S1))
16980b57cec5SDimitry Andric continue;
16990b57cec5SDimitry Andric for (int j = i + 1; j < e; ++j) {
17000b57cec5SDimitry Andric NodeSet &N2 = NodeSets[j];
17010b57cec5SDimitry Andric if (N1.compareRecMII(N2) != 0)
17020b57cec5SDimitry Andric continue;
17030b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> S2;
17040b57cec5SDimitry Andric if (N2.empty() || !succ_L(N2, S2))
17050b57cec5SDimitry Andric continue;
1706*5f7ddb14SDimitry Andric if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
17070b57cec5SDimitry Andric N1.setColocate(++Colocate);
17080b57cec5SDimitry Andric N2.setColocate(Colocate);
17090b57cec5SDimitry Andric break;
17100b57cec5SDimitry Andric }
17110b57cec5SDimitry Andric }
17120b57cec5SDimitry Andric }
17130b57cec5SDimitry Andric }
17140b57cec5SDimitry Andric
17150b57cec5SDimitry Andric /// Check if the existing node-sets are profitable. If not, then ignore the
17160b57cec5SDimitry Andric /// recurrent node-sets, and attempt to schedule all nodes together. This is
17170b57cec5SDimitry Andric /// a heuristic. If the MII is large and all the recurrent node-sets are small,
17180b57cec5SDimitry Andric /// then it's best to try to schedule all instructions together instead of
17190b57cec5SDimitry Andric /// starting with the recurrent node-sets.
checkNodeSets(NodeSetType & NodeSets)17200b57cec5SDimitry Andric void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
17210b57cec5SDimitry Andric // Look for loops with a large MII.
17220b57cec5SDimitry Andric if (MII < 17)
17230b57cec5SDimitry Andric return;
17240b57cec5SDimitry Andric // Check if the node-set contains only a simple add recurrence.
17250b57cec5SDimitry Andric for (auto &NS : NodeSets) {
17260b57cec5SDimitry Andric if (NS.getRecMII() > 2)
17270b57cec5SDimitry Andric return;
17280b57cec5SDimitry Andric if (NS.getMaxDepth() > MII)
17290b57cec5SDimitry Andric return;
17300b57cec5SDimitry Andric }
17310b57cec5SDimitry Andric NodeSets.clear();
17320b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
17330b57cec5SDimitry Andric }
17340b57cec5SDimitry Andric
17350b57cec5SDimitry Andric /// Add the nodes that do not belong to a recurrence set into groups
17360b57cec5SDimitry Andric /// based upon connected componenets.
groupRemainingNodes(NodeSetType & NodeSets)17370b57cec5SDimitry Andric void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
17380b57cec5SDimitry Andric SetVector<SUnit *> NodesAdded;
17390b57cec5SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
17400b57cec5SDimitry Andric // Add the nodes that are on a path between the previous node sets and
17410b57cec5SDimitry Andric // the current node set.
17420b57cec5SDimitry Andric for (NodeSet &I : NodeSets) {
17430b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> N;
17440b57cec5SDimitry Andric // Add the nodes from the current node set to the previous node set.
17450b57cec5SDimitry Andric if (succ_L(I, N)) {
17460b57cec5SDimitry Andric SetVector<SUnit *> Path;
17470b57cec5SDimitry Andric for (SUnit *NI : N) {
17480b57cec5SDimitry Andric Visited.clear();
17490b57cec5SDimitry Andric computePath(NI, Path, NodesAdded, I, Visited);
17500b57cec5SDimitry Andric }
17510b57cec5SDimitry Andric if (!Path.empty())
17520b57cec5SDimitry Andric I.insert(Path.begin(), Path.end());
17530b57cec5SDimitry Andric }
17540b57cec5SDimitry Andric // Add the nodes from the previous node set to the current node set.
17550b57cec5SDimitry Andric N.clear();
17560b57cec5SDimitry Andric if (succ_L(NodesAdded, N)) {
17570b57cec5SDimitry Andric SetVector<SUnit *> Path;
17580b57cec5SDimitry Andric for (SUnit *NI : N) {
17590b57cec5SDimitry Andric Visited.clear();
17600b57cec5SDimitry Andric computePath(NI, Path, I, NodesAdded, Visited);
17610b57cec5SDimitry Andric }
17620b57cec5SDimitry Andric if (!Path.empty())
17630b57cec5SDimitry Andric I.insert(Path.begin(), Path.end());
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric NodesAdded.insert(I.begin(), I.end());
17660b57cec5SDimitry Andric }
17670b57cec5SDimitry Andric
17680b57cec5SDimitry Andric // Create a new node set with the connected nodes of any successor of a node
17690b57cec5SDimitry Andric // in a recurrent set.
17700b57cec5SDimitry Andric NodeSet NewSet;
17710b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> N;
17720b57cec5SDimitry Andric if (succ_L(NodesAdded, N))
17730b57cec5SDimitry Andric for (SUnit *I : N)
17740b57cec5SDimitry Andric addConnectedNodes(I, NewSet, NodesAdded);
17750b57cec5SDimitry Andric if (!NewSet.empty())
17760b57cec5SDimitry Andric NodeSets.push_back(NewSet);
17770b57cec5SDimitry Andric
17780b57cec5SDimitry Andric // Create a new node set with the connected nodes of any predecessor of a node
17790b57cec5SDimitry Andric // in a recurrent set.
17800b57cec5SDimitry Andric NewSet.clear();
17810b57cec5SDimitry Andric if (pred_L(NodesAdded, N))
17820b57cec5SDimitry Andric for (SUnit *I : N)
17830b57cec5SDimitry Andric addConnectedNodes(I, NewSet, NodesAdded);
17840b57cec5SDimitry Andric if (!NewSet.empty())
17850b57cec5SDimitry Andric NodeSets.push_back(NewSet);
17860b57cec5SDimitry Andric
17870b57cec5SDimitry Andric // Create new nodes sets with the connected nodes any remaining node that
17880b57cec5SDimitry Andric // has no predecessor.
1789*5f7ddb14SDimitry Andric for (SUnit &SU : SUnits) {
1790*5f7ddb14SDimitry Andric if (NodesAdded.count(&SU) == 0) {
17910b57cec5SDimitry Andric NewSet.clear();
1792*5f7ddb14SDimitry Andric addConnectedNodes(&SU, NewSet, NodesAdded);
17930b57cec5SDimitry Andric if (!NewSet.empty())
17940b57cec5SDimitry Andric NodeSets.push_back(NewSet);
17950b57cec5SDimitry Andric }
17960b57cec5SDimitry Andric }
17970b57cec5SDimitry Andric }
17980b57cec5SDimitry Andric
17990b57cec5SDimitry Andric /// Add the node to the set, and add all of its connected nodes to the set.
addConnectedNodes(SUnit * SU,NodeSet & NewSet,SetVector<SUnit * > & NodesAdded)18000b57cec5SDimitry Andric void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
18010b57cec5SDimitry Andric SetVector<SUnit *> &NodesAdded) {
18020b57cec5SDimitry Andric NewSet.insert(SU);
18030b57cec5SDimitry Andric NodesAdded.insert(SU);
18040b57cec5SDimitry Andric for (auto &SI : SU->Succs) {
18050b57cec5SDimitry Andric SUnit *Successor = SI.getSUnit();
18060b57cec5SDimitry Andric if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
18070b57cec5SDimitry Andric addConnectedNodes(Successor, NewSet, NodesAdded);
18080b57cec5SDimitry Andric }
18090b57cec5SDimitry Andric for (auto &PI : SU->Preds) {
18100b57cec5SDimitry Andric SUnit *Predecessor = PI.getSUnit();
18110b57cec5SDimitry Andric if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
18120b57cec5SDimitry Andric addConnectedNodes(Predecessor, NewSet, NodesAdded);
18130b57cec5SDimitry Andric }
18140b57cec5SDimitry Andric }
18150b57cec5SDimitry Andric
18160b57cec5SDimitry Andric /// Return true if Set1 contains elements in Set2. The elements in common
18170b57cec5SDimitry Andric /// are returned in a different container.
isIntersect(SmallSetVector<SUnit *,8> & Set1,const NodeSet & Set2,SmallSetVector<SUnit *,8> & Result)18180b57cec5SDimitry Andric static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
18190b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> &Result) {
18200b57cec5SDimitry Andric Result.clear();
18210b57cec5SDimitry Andric for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
18220b57cec5SDimitry Andric SUnit *SU = Set1[i];
18230b57cec5SDimitry Andric if (Set2.count(SU) != 0)
18240b57cec5SDimitry Andric Result.insert(SU);
18250b57cec5SDimitry Andric }
18260b57cec5SDimitry Andric return !Result.empty();
18270b57cec5SDimitry Andric }
18280b57cec5SDimitry Andric
18290b57cec5SDimitry Andric /// Merge the recurrence node sets that have the same initial node.
fuseRecs(NodeSetType & NodeSets)18300b57cec5SDimitry Andric void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
18310b57cec5SDimitry Andric for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
18320b57cec5SDimitry Andric ++I) {
18330b57cec5SDimitry Andric NodeSet &NI = *I;
18340b57cec5SDimitry Andric for (NodeSetType::iterator J = I + 1; J != E;) {
18350b57cec5SDimitry Andric NodeSet &NJ = *J;
18360b57cec5SDimitry Andric if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
18370b57cec5SDimitry Andric if (NJ.compareRecMII(NI) > 0)
18380b57cec5SDimitry Andric NI.setRecMII(NJ.getRecMII());
1839*5f7ddb14SDimitry Andric for (SUnit *SU : *J)
1840*5f7ddb14SDimitry Andric I->insert(SU);
18410b57cec5SDimitry Andric NodeSets.erase(J);
18420b57cec5SDimitry Andric E = NodeSets.end();
18430b57cec5SDimitry Andric } else {
18440b57cec5SDimitry Andric ++J;
18450b57cec5SDimitry Andric }
18460b57cec5SDimitry Andric }
18470b57cec5SDimitry Andric }
18480b57cec5SDimitry Andric }
18490b57cec5SDimitry Andric
18500b57cec5SDimitry Andric /// Remove nodes that have been scheduled in previous NodeSets.
removeDuplicateNodes(NodeSetType & NodeSets)18510b57cec5SDimitry Andric void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
18520b57cec5SDimitry Andric for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
18530b57cec5SDimitry Andric ++I)
18540b57cec5SDimitry Andric for (NodeSetType::iterator J = I + 1; J != E;) {
18550b57cec5SDimitry Andric J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
18560b57cec5SDimitry Andric
18570b57cec5SDimitry Andric if (J->empty()) {
18580b57cec5SDimitry Andric NodeSets.erase(J);
18590b57cec5SDimitry Andric E = NodeSets.end();
18600b57cec5SDimitry Andric } else {
18610b57cec5SDimitry Andric ++J;
18620b57cec5SDimitry Andric }
18630b57cec5SDimitry Andric }
18640b57cec5SDimitry Andric }
18650b57cec5SDimitry Andric
18660b57cec5SDimitry Andric /// Compute an ordered list of the dependence graph nodes, which
18670b57cec5SDimitry Andric /// indicates the order that the nodes will be scheduled. This is a
18680b57cec5SDimitry Andric /// two-level algorithm. First, a partial order is created, which
18690b57cec5SDimitry Andric /// consists of a list of sets ordered from highest to lowest priority.
computeNodeOrder(NodeSetType & NodeSets)18700b57cec5SDimitry Andric void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
18710b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> R;
18720b57cec5SDimitry Andric NodeOrder.clear();
18730b57cec5SDimitry Andric
18740b57cec5SDimitry Andric for (auto &Nodes : NodeSets) {
18750b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
18760b57cec5SDimitry Andric OrderKind Order;
18770b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> N;
1878*5f7ddb14SDimitry Andric if (pred_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
18790b57cec5SDimitry Andric R.insert(N.begin(), N.end());
18800b57cec5SDimitry Andric Order = BottomUp;
18810b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
1882*5f7ddb14SDimitry Andric } else if (succ_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
18830b57cec5SDimitry Andric R.insert(N.begin(), N.end());
18840b57cec5SDimitry Andric Order = TopDown;
18850b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Top down (succs) ");
18860b57cec5SDimitry Andric } else if (isIntersect(N, Nodes, R)) {
18870b57cec5SDimitry Andric // If some of the successors are in the existing node-set, then use the
18880b57cec5SDimitry Andric // top-down ordering.
18890b57cec5SDimitry Andric Order = TopDown;
18900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Top down (intersect) ");
18910b57cec5SDimitry Andric } else if (NodeSets.size() == 1) {
18920b57cec5SDimitry Andric for (auto &N : Nodes)
18930b57cec5SDimitry Andric if (N->Succs.size() == 0)
18940b57cec5SDimitry Andric R.insert(N);
18950b57cec5SDimitry Andric Order = BottomUp;
18960b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Bottom up (all) ");
18970b57cec5SDimitry Andric } else {
18980b57cec5SDimitry Andric // Find the node with the highest ASAP.
18990b57cec5SDimitry Andric SUnit *maxASAP = nullptr;
19000b57cec5SDimitry Andric for (SUnit *SU : Nodes) {
19010b57cec5SDimitry Andric if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
19020b57cec5SDimitry Andric (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
19030b57cec5SDimitry Andric maxASAP = SU;
19040b57cec5SDimitry Andric }
19050b57cec5SDimitry Andric R.insert(maxASAP);
19060b57cec5SDimitry Andric Order = BottomUp;
19070b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Bottom up (default) ");
19080b57cec5SDimitry Andric }
19090b57cec5SDimitry Andric
19100b57cec5SDimitry Andric while (!R.empty()) {
19110b57cec5SDimitry Andric if (Order == TopDown) {
19120b57cec5SDimitry Andric // Choose the node with the maximum height. If more than one, choose
19130b57cec5SDimitry Andric // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
19140b57cec5SDimitry Andric // choose the node with the lowest MOV.
19150b57cec5SDimitry Andric while (!R.empty()) {
19160b57cec5SDimitry Andric SUnit *maxHeight = nullptr;
19170b57cec5SDimitry Andric for (SUnit *I : R) {
19180b57cec5SDimitry Andric if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
19190b57cec5SDimitry Andric maxHeight = I;
19200b57cec5SDimitry Andric else if (getHeight(I) == getHeight(maxHeight) &&
19210b57cec5SDimitry Andric getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
19220b57cec5SDimitry Andric maxHeight = I;
19230b57cec5SDimitry Andric else if (getHeight(I) == getHeight(maxHeight) &&
19240b57cec5SDimitry Andric getZeroLatencyHeight(I) ==
19250b57cec5SDimitry Andric getZeroLatencyHeight(maxHeight) &&
19260b57cec5SDimitry Andric getMOV(I) < getMOV(maxHeight))
19270b57cec5SDimitry Andric maxHeight = I;
19280b57cec5SDimitry Andric }
19290b57cec5SDimitry Andric NodeOrder.insert(maxHeight);
19300b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
19310b57cec5SDimitry Andric R.remove(maxHeight);
19320b57cec5SDimitry Andric for (const auto &I : maxHeight->Succs) {
19330b57cec5SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
19340b57cec5SDimitry Andric continue;
1935af732203SDimitry Andric if (NodeOrder.contains(I.getSUnit()))
19360b57cec5SDimitry Andric continue;
19370b57cec5SDimitry Andric if (ignoreDependence(I, false))
19380b57cec5SDimitry Andric continue;
19390b57cec5SDimitry Andric R.insert(I.getSUnit());
19400b57cec5SDimitry Andric }
19410b57cec5SDimitry Andric // Back-edges are predecessors with an anti-dependence.
19420b57cec5SDimitry Andric for (const auto &I : maxHeight->Preds) {
19430b57cec5SDimitry Andric if (I.getKind() != SDep::Anti)
19440b57cec5SDimitry Andric continue;
19450b57cec5SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
19460b57cec5SDimitry Andric continue;
1947af732203SDimitry Andric if (NodeOrder.contains(I.getSUnit()))
19480b57cec5SDimitry Andric continue;
19490b57cec5SDimitry Andric R.insert(I.getSUnit());
19500b57cec5SDimitry Andric }
19510b57cec5SDimitry Andric }
19520b57cec5SDimitry Andric Order = BottomUp;
19530b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
19540b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> N;
19550b57cec5SDimitry Andric if (pred_L(NodeOrder, N, &Nodes))
19560b57cec5SDimitry Andric R.insert(N.begin(), N.end());
19570b57cec5SDimitry Andric } else {
19580b57cec5SDimitry Andric // Choose the node with the maximum depth. If more than one, choose
19590b57cec5SDimitry Andric // the node with the maximum ZeroLatencyDepth. If still more than one,
19600b57cec5SDimitry Andric // choose the node with the lowest MOV.
19610b57cec5SDimitry Andric while (!R.empty()) {
19620b57cec5SDimitry Andric SUnit *maxDepth = nullptr;
19630b57cec5SDimitry Andric for (SUnit *I : R) {
19640b57cec5SDimitry Andric if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
19650b57cec5SDimitry Andric maxDepth = I;
19660b57cec5SDimitry Andric else if (getDepth(I) == getDepth(maxDepth) &&
19670b57cec5SDimitry Andric getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
19680b57cec5SDimitry Andric maxDepth = I;
19690b57cec5SDimitry Andric else if (getDepth(I) == getDepth(maxDepth) &&
19700b57cec5SDimitry Andric getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
19710b57cec5SDimitry Andric getMOV(I) < getMOV(maxDepth))
19720b57cec5SDimitry Andric maxDepth = I;
19730b57cec5SDimitry Andric }
19740b57cec5SDimitry Andric NodeOrder.insert(maxDepth);
19750b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
19760b57cec5SDimitry Andric R.remove(maxDepth);
19770b57cec5SDimitry Andric if (Nodes.isExceedSU(maxDepth)) {
19780b57cec5SDimitry Andric Order = TopDown;
19790b57cec5SDimitry Andric R.clear();
19800b57cec5SDimitry Andric R.insert(Nodes.getNode(0));
19810b57cec5SDimitry Andric break;
19820b57cec5SDimitry Andric }
19830b57cec5SDimitry Andric for (const auto &I : maxDepth->Preds) {
19840b57cec5SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
19850b57cec5SDimitry Andric continue;
1986af732203SDimitry Andric if (NodeOrder.contains(I.getSUnit()))
19870b57cec5SDimitry Andric continue;
19880b57cec5SDimitry Andric R.insert(I.getSUnit());
19890b57cec5SDimitry Andric }
19900b57cec5SDimitry Andric // Back-edges are predecessors with an anti-dependence.
19910b57cec5SDimitry Andric for (const auto &I : maxDepth->Succs) {
19920b57cec5SDimitry Andric if (I.getKind() != SDep::Anti)
19930b57cec5SDimitry Andric continue;
19940b57cec5SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
19950b57cec5SDimitry Andric continue;
1996af732203SDimitry Andric if (NodeOrder.contains(I.getSUnit()))
19970b57cec5SDimitry Andric continue;
19980b57cec5SDimitry Andric R.insert(I.getSUnit());
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric }
20010b57cec5SDimitry Andric Order = TopDown;
20020b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
20030b57cec5SDimitry Andric SmallSetVector<SUnit *, 8> N;
20040b57cec5SDimitry Andric if (succ_L(NodeOrder, N, &Nodes))
20050b57cec5SDimitry Andric R.insert(N.begin(), N.end());
20060b57cec5SDimitry Andric }
20070b57cec5SDimitry Andric }
20080b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
20090b57cec5SDimitry Andric }
20100b57cec5SDimitry Andric
20110b57cec5SDimitry Andric LLVM_DEBUG({
20120b57cec5SDimitry Andric dbgs() << "Node order: ";
20130b57cec5SDimitry Andric for (SUnit *I : NodeOrder)
20140b57cec5SDimitry Andric dbgs() << " " << I->NodeNum << " ";
20150b57cec5SDimitry Andric dbgs() << "\n";
20160b57cec5SDimitry Andric });
20170b57cec5SDimitry Andric }
20180b57cec5SDimitry Andric
20190b57cec5SDimitry Andric /// Process the nodes in the computed order and create the pipelined schedule
20200b57cec5SDimitry Andric /// of the instructions, if possible. Return true if a schedule is found.
schedulePipeline(SMSchedule & Schedule)20210b57cec5SDimitry Andric bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
20220b57cec5SDimitry Andric
20230b57cec5SDimitry Andric if (NodeOrder.empty()){
20240b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
20250b57cec5SDimitry Andric return false;
20260b57cec5SDimitry Andric }
20270b57cec5SDimitry Andric
20280b57cec5SDimitry Andric bool scheduleFound = false;
20290b57cec5SDimitry Andric // Keep increasing II until a valid schedule is found.
2030*5f7ddb14SDimitry Andric for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
20310b57cec5SDimitry Andric Schedule.reset();
20320b57cec5SDimitry Andric Schedule.setInitiationInterval(II);
20330b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
20340b57cec5SDimitry Andric
20350b57cec5SDimitry Andric SetVector<SUnit *>::iterator NI = NodeOrder.begin();
20360b57cec5SDimitry Andric SetVector<SUnit *>::iterator NE = NodeOrder.end();
20370b57cec5SDimitry Andric do {
20380b57cec5SDimitry Andric SUnit *SU = *NI;
20390b57cec5SDimitry Andric
20400b57cec5SDimitry Andric // Compute the schedule time for the instruction, which is based
20410b57cec5SDimitry Andric // upon the scheduled time for any predecessors/successors.
20420b57cec5SDimitry Andric int EarlyStart = INT_MIN;
20430b57cec5SDimitry Andric int LateStart = INT_MAX;
20440b57cec5SDimitry Andric // These values are set when the size of the schedule window is limited
20450b57cec5SDimitry Andric // due to chain dependences.
20460b57cec5SDimitry Andric int SchedEnd = INT_MAX;
20470b57cec5SDimitry Andric int SchedStart = INT_MIN;
20480b57cec5SDimitry Andric Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
20490b57cec5SDimitry Andric II, this);
20500b57cec5SDimitry Andric LLVM_DEBUG({
20510b57cec5SDimitry Andric dbgs() << "\n";
20520b57cec5SDimitry Andric dbgs() << "Inst (" << SU->NodeNum << ") ";
20530b57cec5SDimitry Andric SU->getInstr()->dump();
20540b57cec5SDimitry Andric dbgs() << "\n";
20550b57cec5SDimitry Andric });
20560b57cec5SDimitry Andric LLVM_DEBUG({
20570b57cec5SDimitry Andric dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
20580b57cec5SDimitry Andric LateStart, SchedEnd, SchedStart);
20590b57cec5SDimitry Andric });
20600b57cec5SDimitry Andric
20610b57cec5SDimitry Andric if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
20620b57cec5SDimitry Andric SchedStart > LateStart)
20630b57cec5SDimitry Andric scheduleFound = false;
20640b57cec5SDimitry Andric else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
20650b57cec5SDimitry Andric SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
20660b57cec5SDimitry Andric scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
20670b57cec5SDimitry Andric } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
20680b57cec5SDimitry Andric SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
20690b57cec5SDimitry Andric scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
20700b57cec5SDimitry Andric } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
20710b57cec5SDimitry Andric SchedEnd =
20720b57cec5SDimitry Andric std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
20730b57cec5SDimitry Andric // When scheduling a Phi it is better to start at the late cycle and go
20740b57cec5SDimitry Andric // backwards. The default order may insert the Phi too far away from
20750b57cec5SDimitry Andric // its first dependence.
20760b57cec5SDimitry Andric if (SU->getInstr()->isPHI())
20770b57cec5SDimitry Andric scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
20780b57cec5SDimitry Andric else
20790b57cec5SDimitry Andric scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
20800b57cec5SDimitry Andric } else {
20810b57cec5SDimitry Andric int FirstCycle = Schedule.getFirstCycle();
20820b57cec5SDimitry Andric scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
20830b57cec5SDimitry Andric FirstCycle + getASAP(SU) + II - 1, II);
20840b57cec5SDimitry Andric }
20850b57cec5SDimitry Andric // Even if we find a schedule, make sure the schedule doesn't exceed the
20860b57cec5SDimitry Andric // allowable number of stages. We keep trying if this happens.
20870b57cec5SDimitry Andric if (scheduleFound)
20880b57cec5SDimitry Andric if (SwpMaxStages > -1 &&
20890b57cec5SDimitry Andric Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
20900b57cec5SDimitry Andric scheduleFound = false;
20910b57cec5SDimitry Andric
20920b57cec5SDimitry Andric LLVM_DEBUG({
20930b57cec5SDimitry Andric if (!scheduleFound)
20940b57cec5SDimitry Andric dbgs() << "\tCan't schedule\n";
20950b57cec5SDimitry Andric });
20960b57cec5SDimitry Andric } while (++NI != NE && scheduleFound);
20970b57cec5SDimitry Andric
20980b57cec5SDimitry Andric // If a schedule is found, check if it is a valid schedule too.
20990b57cec5SDimitry Andric if (scheduleFound)
21000b57cec5SDimitry Andric scheduleFound = Schedule.isValidSchedule(this);
21010b57cec5SDimitry Andric }
21020b57cec5SDimitry Andric
2103*5f7ddb14SDimitry Andric LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2104*5f7ddb14SDimitry Andric << " (II=" << Schedule.getInitiationInterval()
21050b57cec5SDimitry Andric << ")\n");
21060b57cec5SDimitry Andric
21075ffd83dbSDimitry Andric if (scheduleFound) {
21080b57cec5SDimitry Andric Schedule.finalizeSchedule(this);
21095ffd83dbSDimitry Andric Pass.ORE->emit([&]() {
21105ffd83dbSDimitry Andric return MachineOptimizationRemarkAnalysis(
21115ffd83dbSDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2112*5f7ddb14SDimitry Andric << "Schedule found with Initiation Interval: "
2113*5f7ddb14SDimitry Andric << ore::NV("II", Schedule.getInitiationInterval())
21145ffd83dbSDimitry Andric << ", MaxStageCount: "
21155ffd83dbSDimitry Andric << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
21165ffd83dbSDimitry Andric });
21175ffd83dbSDimitry Andric } else
21180b57cec5SDimitry Andric Schedule.reset();
21190b57cec5SDimitry Andric
21200b57cec5SDimitry Andric return scheduleFound && Schedule.getMaxStageCount() > 0;
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric
21230b57cec5SDimitry Andric /// Return true if we can compute the amount the instruction changes
21240b57cec5SDimitry Andric /// during each iteration. Set Delta to the amount of the change.
computeDelta(MachineInstr & MI,unsigned & Delta)21250b57cec5SDimitry Andric bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
21260b57cec5SDimitry Andric const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
21270b57cec5SDimitry Andric const MachineOperand *BaseOp;
21280b57cec5SDimitry Andric int64_t Offset;
21295ffd83dbSDimitry Andric bool OffsetIsScalable;
21305ffd83dbSDimitry Andric if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
21315ffd83dbSDimitry Andric return false;
21325ffd83dbSDimitry Andric
21335ffd83dbSDimitry Andric // FIXME: This algorithm assumes instructions have fixed-size offsets.
21345ffd83dbSDimitry Andric if (OffsetIsScalable)
21350b57cec5SDimitry Andric return false;
21360b57cec5SDimitry Andric
21370b57cec5SDimitry Andric if (!BaseOp->isReg())
21380b57cec5SDimitry Andric return false;
21390b57cec5SDimitry Andric
21408bcb0991SDimitry Andric Register BaseReg = BaseOp->getReg();
21410b57cec5SDimitry Andric
21420b57cec5SDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo();
21430b57cec5SDimitry Andric // Check if there is a Phi. If so, get the definition in the loop.
21440b57cec5SDimitry Andric MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
21450b57cec5SDimitry Andric if (BaseDef && BaseDef->isPHI()) {
21460b57cec5SDimitry Andric BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
21470b57cec5SDimitry Andric BaseDef = MRI.getVRegDef(BaseReg);
21480b57cec5SDimitry Andric }
21490b57cec5SDimitry Andric if (!BaseDef)
21500b57cec5SDimitry Andric return false;
21510b57cec5SDimitry Andric
21520b57cec5SDimitry Andric int D = 0;
21530b57cec5SDimitry Andric if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
21540b57cec5SDimitry Andric return false;
21550b57cec5SDimitry Andric
21560b57cec5SDimitry Andric Delta = D;
21570b57cec5SDimitry Andric return true;
21580b57cec5SDimitry Andric }
21590b57cec5SDimitry Andric
21600b57cec5SDimitry Andric /// Check if we can change the instruction to use an offset value from the
21610b57cec5SDimitry Andric /// previous iteration. If so, return true and set the base and offset values
21620b57cec5SDimitry Andric /// so that we can rewrite the load, if necessary.
21630b57cec5SDimitry Andric /// v1 = Phi(v0, v3)
21640b57cec5SDimitry Andric /// v2 = load v1, 0
21650b57cec5SDimitry Andric /// v3 = post_store v1, 4, x
21660b57cec5SDimitry Andric /// This function enables the load to be rewritten as v2 = load v3, 4.
canUseLastOffsetValue(MachineInstr * MI,unsigned & BasePos,unsigned & OffsetPos,unsigned & NewBase,int64_t & Offset)21670b57cec5SDimitry Andric bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
21680b57cec5SDimitry Andric unsigned &BasePos,
21690b57cec5SDimitry Andric unsigned &OffsetPos,
21700b57cec5SDimitry Andric unsigned &NewBase,
21710b57cec5SDimitry Andric int64_t &Offset) {
21720b57cec5SDimitry Andric // Get the load instruction.
21730b57cec5SDimitry Andric if (TII->isPostIncrement(*MI))
21740b57cec5SDimitry Andric return false;
21750b57cec5SDimitry Andric unsigned BasePosLd, OffsetPosLd;
21760b57cec5SDimitry Andric if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
21770b57cec5SDimitry Andric return false;
21788bcb0991SDimitry Andric Register BaseReg = MI->getOperand(BasePosLd).getReg();
21790b57cec5SDimitry Andric
21800b57cec5SDimitry Andric // Look for the Phi instruction.
21810b57cec5SDimitry Andric MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
21820b57cec5SDimitry Andric MachineInstr *Phi = MRI.getVRegDef(BaseReg);
21830b57cec5SDimitry Andric if (!Phi || !Phi->isPHI())
21840b57cec5SDimitry Andric return false;
21850b57cec5SDimitry Andric // Get the register defined in the loop block.
21860b57cec5SDimitry Andric unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
21870b57cec5SDimitry Andric if (!PrevReg)
21880b57cec5SDimitry Andric return false;
21890b57cec5SDimitry Andric
21900b57cec5SDimitry Andric // Check for the post-increment load/store instruction.
21910b57cec5SDimitry Andric MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
21920b57cec5SDimitry Andric if (!PrevDef || PrevDef == MI)
21930b57cec5SDimitry Andric return false;
21940b57cec5SDimitry Andric
21950b57cec5SDimitry Andric if (!TII->isPostIncrement(*PrevDef))
21960b57cec5SDimitry Andric return false;
21970b57cec5SDimitry Andric
21980b57cec5SDimitry Andric unsigned BasePos1 = 0, OffsetPos1 = 0;
21990b57cec5SDimitry Andric if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
22000b57cec5SDimitry Andric return false;
22010b57cec5SDimitry Andric
22020b57cec5SDimitry Andric // Make sure that the instructions do not access the same memory location in
22030b57cec5SDimitry Andric // the next iteration.
22040b57cec5SDimitry Andric int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
22050b57cec5SDimitry Andric int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
22060b57cec5SDimitry Andric MachineInstr *NewMI = MF.CloneMachineInstr(MI);
22070b57cec5SDimitry Andric NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
22080b57cec5SDimitry Andric bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
22090b57cec5SDimitry Andric MF.DeleteMachineInstr(NewMI);
22100b57cec5SDimitry Andric if (!Disjoint)
22110b57cec5SDimitry Andric return false;
22120b57cec5SDimitry Andric
22130b57cec5SDimitry Andric // Set the return value once we determine that we return true.
22140b57cec5SDimitry Andric BasePos = BasePosLd;
22150b57cec5SDimitry Andric OffsetPos = OffsetPosLd;
22160b57cec5SDimitry Andric NewBase = PrevReg;
22170b57cec5SDimitry Andric Offset = StoreOffset;
22180b57cec5SDimitry Andric return true;
22190b57cec5SDimitry Andric }
22200b57cec5SDimitry Andric
22210b57cec5SDimitry Andric /// Apply changes to the instruction if needed. The changes are need
22220b57cec5SDimitry Andric /// to improve the scheduling and depend up on the final schedule.
applyInstrChange(MachineInstr * MI,SMSchedule & Schedule)22230b57cec5SDimitry Andric void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
22240b57cec5SDimitry Andric SMSchedule &Schedule) {
22250b57cec5SDimitry Andric SUnit *SU = getSUnit(MI);
22260b57cec5SDimitry Andric DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
22270b57cec5SDimitry Andric InstrChanges.find(SU);
22280b57cec5SDimitry Andric if (It != InstrChanges.end()) {
22290b57cec5SDimitry Andric std::pair<unsigned, int64_t> RegAndOffset = It->second;
22300b57cec5SDimitry Andric unsigned BasePos, OffsetPos;
22310b57cec5SDimitry Andric if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
22320b57cec5SDimitry Andric return;
22338bcb0991SDimitry Andric Register BaseReg = MI->getOperand(BasePos).getReg();
22340b57cec5SDimitry Andric MachineInstr *LoopDef = findDefInLoop(BaseReg);
22350b57cec5SDimitry Andric int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
22360b57cec5SDimitry Andric int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
22370b57cec5SDimitry Andric int BaseStageNum = Schedule.stageScheduled(SU);
22380b57cec5SDimitry Andric int BaseCycleNum = Schedule.cycleScheduled(SU);
22390b57cec5SDimitry Andric if (BaseStageNum < DefStageNum) {
22400b57cec5SDimitry Andric MachineInstr *NewMI = MF.CloneMachineInstr(MI);
22410b57cec5SDimitry Andric int OffsetDiff = DefStageNum - BaseStageNum;
22420b57cec5SDimitry Andric if (DefCycleNum < BaseCycleNum) {
22430b57cec5SDimitry Andric NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
22440b57cec5SDimitry Andric if (OffsetDiff > 0)
22450b57cec5SDimitry Andric --OffsetDiff;
22460b57cec5SDimitry Andric }
22470b57cec5SDimitry Andric int64_t NewOffset =
22480b57cec5SDimitry Andric MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
22490b57cec5SDimitry Andric NewMI->getOperand(OffsetPos).setImm(NewOffset);
22500b57cec5SDimitry Andric SU->setInstr(NewMI);
22510b57cec5SDimitry Andric MISUnitMap[NewMI] = SU;
22528bcb0991SDimitry Andric NewMIs[MI] = NewMI;
22530b57cec5SDimitry Andric }
22540b57cec5SDimitry Andric }
22550b57cec5SDimitry Andric }
22560b57cec5SDimitry Andric
22578bcb0991SDimitry Andric /// Return the instruction in the loop that defines the register.
22588bcb0991SDimitry Andric /// If the definition is a Phi, then follow the Phi operand to
22598bcb0991SDimitry Andric /// the instruction in the loop.
findDefInLoop(Register Reg)2260af732203SDimitry Andric MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
22618bcb0991SDimitry Andric SmallPtrSet<MachineInstr *, 8> Visited;
22628bcb0991SDimitry Andric MachineInstr *Def = MRI.getVRegDef(Reg);
22638bcb0991SDimitry Andric while (Def->isPHI()) {
22648bcb0991SDimitry Andric if (!Visited.insert(Def).second)
22658bcb0991SDimitry Andric break;
22668bcb0991SDimitry Andric for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
22678bcb0991SDimitry Andric if (Def->getOperand(i + 1).getMBB() == BB) {
22688bcb0991SDimitry Andric Def = MRI.getVRegDef(Def->getOperand(i).getReg());
22698bcb0991SDimitry Andric break;
22708bcb0991SDimitry Andric }
22718bcb0991SDimitry Andric }
22728bcb0991SDimitry Andric return Def;
22738bcb0991SDimitry Andric }
22748bcb0991SDimitry Andric
22750b57cec5SDimitry Andric /// Return true for an order or output dependence that is loop carried
22760b57cec5SDimitry Andric /// potentially. A dependence is loop carried if the destination defines a valu
22770b57cec5SDimitry Andric /// that may be used or defined by the source in a subsequent iteration.
isLoopCarriedDep(SUnit * Source,const SDep & Dep,bool isSucc)22780b57cec5SDimitry Andric bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
22790b57cec5SDimitry Andric bool isSucc) {
22800b57cec5SDimitry Andric if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
22810b57cec5SDimitry Andric Dep.isArtificial())
22820b57cec5SDimitry Andric return false;
22830b57cec5SDimitry Andric
22840b57cec5SDimitry Andric if (!SwpPruneLoopCarried)
22850b57cec5SDimitry Andric return true;
22860b57cec5SDimitry Andric
22870b57cec5SDimitry Andric if (Dep.getKind() == SDep::Output)
22880b57cec5SDimitry Andric return true;
22890b57cec5SDimitry Andric
22900b57cec5SDimitry Andric MachineInstr *SI = Source->getInstr();
22910b57cec5SDimitry Andric MachineInstr *DI = Dep.getSUnit()->getInstr();
22920b57cec5SDimitry Andric if (!isSucc)
22930b57cec5SDimitry Andric std::swap(SI, DI);
22940b57cec5SDimitry Andric assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
22950b57cec5SDimitry Andric
22960b57cec5SDimitry Andric // Assume ordered loads and stores may have a loop carried dependence.
22970b57cec5SDimitry Andric if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
22980b57cec5SDimitry Andric SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
22990b57cec5SDimitry Andric SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
23000b57cec5SDimitry Andric return true;
23010b57cec5SDimitry Andric
23020b57cec5SDimitry Andric // Only chain dependences between a load and store can be loop carried.
23030b57cec5SDimitry Andric if (!DI->mayStore() || !SI->mayLoad())
23040b57cec5SDimitry Andric return false;
23050b57cec5SDimitry Andric
23060b57cec5SDimitry Andric unsigned DeltaS, DeltaD;
23070b57cec5SDimitry Andric if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
23080b57cec5SDimitry Andric return true;
23090b57cec5SDimitry Andric
23100b57cec5SDimitry Andric const MachineOperand *BaseOpS, *BaseOpD;
23110b57cec5SDimitry Andric int64_t OffsetS, OffsetD;
23125ffd83dbSDimitry Andric bool OffsetSIsScalable, OffsetDIsScalable;
23130b57cec5SDimitry Andric const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
23145ffd83dbSDimitry Andric if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
23155ffd83dbSDimitry Andric TRI) ||
23165ffd83dbSDimitry Andric !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
23175ffd83dbSDimitry Andric TRI))
23180b57cec5SDimitry Andric return true;
23190b57cec5SDimitry Andric
23205ffd83dbSDimitry Andric assert(!OffsetSIsScalable && !OffsetDIsScalable &&
23215ffd83dbSDimitry Andric "Expected offsets to be byte offsets");
23225ffd83dbSDimitry Andric
23230b57cec5SDimitry Andric if (!BaseOpS->isIdenticalTo(*BaseOpD))
23240b57cec5SDimitry Andric return true;
23250b57cec5SDimitry Andric
23260b57cec5SDimitry Andric // Check that the base register is incremented by a constant value for each
23270b57cec5SDimitry Andric // iteration.
23280b57cec5SDimitry Andric MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
23290b57cec5SDimitry Andric if (!Def || !Def->isPHI())
23300b57cec5SDimitry Andric return true;
23310b57cec5SDimitry Andric unsigned InitVal = 0;
23320b57cec5SDimitry Andric unsigned LoopVal = 0;
23330b57cec5SDimitry Andric getPhiRegs(*Def, BB, InitVal, LoopVal);
23340b57cec5SDimitry Andric MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
23350b57cec5SDimitry Andric int D = 0;
23360b57cec5SDimitry Andric if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
23370b57cec5SDimitry Andric return true;
23380b57cec5SDimitry Andric
23390b57cec5SDimitry Andric uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
23400b57cec5SDimitry Andric uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
23410b57cec5SDimitry Andric
23420b57cec5SDimitry Andric // This is the main test, which checks the offset values and the loop
23430b57cec5SDimitry Andric // increment value to determine if the accesses may be loop carried.
23440b57cec5SDimitry Andric if (AccessSizeS == MemoryLocation::UnknownSize ||
23450b57cec5SDimitry Andric AccessSizeD == MemoryLocation::UnknownSize)
23460b57cec5SDimitry Andric return true;
23470b57cec5SDimitry Andric
23480b57cec5SDimitry Andric if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
23490b57cec5SDimitry Andric return true;
23500b57cec5SDimitry Andric
23510b57cec5SDimitry Andric return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
23520b57cec5SDimitry Andric }
23530b57cec5SDimitry Andric
postprocessDAG()23540b57cec5SDimitry Andric void SwingSchedulerDAG::postprocessDAG() {
23550b57cec5SDimitry Andric for (auto &M : Mutations)
23560b57cec5SDimitry Andric M->apply(this);
23570b57cec5SDimitry Andric }
23580b57cec5SDimitry Andric
23590b57cec5SDimitry Andric /// Try to schedule the node at the specified StartCycle and continue
23600b57cec5SDimitry Andric /// until the node is schedule or the EndCycle is reached. This function
23610b57cec5SDimitry Andric /// returns true if the node is scheduled. This routine may search either
23620b57cec5SDimitry Andric /// forward or backward for a place to insert the instruction based upon
23630b57cec5SDimitry Andric /// the relative values of StartCycle and EndCycle.
insert(SUnit * SU,int StartCycle,int EndCycle,int II)23640b57cec5SDimitry Andric bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
23650b57cec5SDimitry Andric bool forward = true;
23660b57cec5SDimitry Andric LLVM_DEBUG({
23670b57cec5SDimitry Andric dbgs() << "Trying to insert node between " << StartCycle << " and "
23680b57cec5SDimitry Andric << EndCycle << " II: " << II << "\n";
23690b57cec5SDimitry Andric });
23700b57cec5SDimitry Andric if (StartCycle > EndCycle)
23710b57cec5SDimitry Andric forward = false;
23720b57cec5SDimitry Andric
23730b57cec5SDimitry Andric // The terminating condition depends on the direction.
23740b57cec5SDimitry Andric int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
23750b57cec5SDimitry Andric for (int curCycle = StartCycle; curCycle != termCycle;
23760b57cec5SDimitry Andric forward ? ++curCycle : --curCycle) {
23770b57cec5SDimitry Andric
23780b57cec5SDimitry Andric // Add the already scheduled instructions at the specified cycle to the
23790b57cec5SDimitry Andric // DFA.
23800b57cec5SDimitry Andric ProcItinResources.clearResources();
23810b57cec5SDimitry Andric for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
23820b57cec5SDimitry Andric checkCycle <= LastCycle; checkCycle += II) {
23830b57cec5SDimitry Andric std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
23840b57cec5SDimitry Andric
2385*5f7ddb14SDimitry Andric for (SUnit *CI : cycleInstrs) {
2386*5f7ddb14SDimitry Andric if (ST.getInstrInfo()->isZeroCost(CI->getInstr()->getOpcode()))
23870b57cec5SDimitry Andric continue;
2388*5f7ddb14SDimitry Andric assert(ProcItinResources.canReserveResources(*CI->getInstr()) &&
23890b57cec5SDimitry Andric "These instructions have already been scheduled.");
2390*5f7ddb14SDimitry Andric ProcItinResources.reserveResources(*CI->getInstr());
23910b57cec5SDimitry Andric }
23920b57cec5SDimitry Andric }
23930b57cec5SDimitry Andric if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
23940b57cec5SDimitry Andric ProcItinResources.canReserveResources(*SU->getInstr())) {
23950b57cec5SDimitry Andric LLVM_DEBUG({
23960b57cec5SDimitry Andric dbgs() << "\tinsert at cycle " << curCycle << " ";
23970b57cec5SDimitry Andric SU->getInstr()->dump();
23980b57cec5SDimitry Andric });
23990b57cec5SDimitry Andric
24000b57cec5SDimitry Andric ScheduledInstrs[curCycle].push_back(SU);
24010b57cec5SDimitry Andric InstrToCycle.insert(std::make_pair(SU, curCycle));
24020b57cec5SDimitry Andric if (curCycle > LastCycle)
24030b57cec5SDimitry Andric LastCycle = curCycle;
24040b57cec5SDimitry Andric if (curCycle < FirstCycle)
24050b57cec5SDimitry Andric FirstCycle = curCycle;
24060b57cec5SDimitry Andric return true;
24070b57cec5SDimitry Andric }
24080b57cec5SDimitry Andric LLVM_DEBUG({
24090b57cec5SDimitry Andric dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
24100b57cec5SDimitry Andric SU->getInstr()->dump();
24110b57cec5SDimitry Andric });
24120b57cec5SDimitry Andric }
24130b57cec5SDimitry Andric return false;
24140b57cec5SDimitry Andric }
24150b57cec5SDimitry Andric
24160b57cec5SDimitry Andric // Return the cycle of the earliest scheduled instruction in the chain.
earliestCycleInChain(const SDep & Dep)24170b57cec5SDimitry Andric int SMSchedule::earliestCycleInChain(const SDep &Dep) {
24180b57cec5SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
24190b57cec5SDimitry Andric SmallVector<SDep, 8> Worklist;
24200b57cec5SDimitry Andric Worklist.push_back(Dep);
24210b57cec5SDimitry Andric int EarlyCycle = INT_MAX;
24220b57cec5SDimitry Andric while (!Worklist.empty()) {
24230b57cec5SDimitry Andric const SDep &Cur = Worklist.pop_back_val();
24240b57cec5SDimitry Andric SUnit *PrevSU = Cur.getSUnit();
24250b57cec5SDimitry Andric if (Visited.count(PrevSU))
24260b57cec5SDimitry Andric continue;
24270b57cec5SDimitry Andric std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
24280b57cec5SDimitry Andric if (it == InstrToCycle.end())
24290b57cec5SDimitry Andric continue;
24300b57cec5SDimitry Andric EarlyCycle = std::min(EarlyCycle, it->second);
24310b57cec5SDimitry Andric for (const auto &PI : PrevSU->Preds)
24325ffd83dbSDimitry Andric if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output)
24330b57cec5SDimitry Andric Worklist.push_back(PI);
24340b57cec5SDimitry Andric Visited.insert(PrevSU);
24350b57cec5SDimitry Andric }
24360b57cec5SDimitry Andric return EarlyCycle;
24370b57cec5SDimitry Andric }
24380b57cec5SDimitry Andric
24390b57cec5SDimitry Andric // Return the cycle of the latest scheduled instruction in the chain.
latestCycleInChain(const SDep & Dep)24400b57cec5SDimitry Andric int SMSchedule::latestCycleInChain(const SDep &Dep) {
24410b57cec5SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
24420b57cec5SDimitry Andric SmallVector<SDep, 8> Worklist;
24430b57cec5SDimitry Andric Worklist.push_back(Dep);
24440b57cec5SDimitry Andric int LateCycle = INT_MIN;
24450b57cec5SDimitry Andric while (!Worklist.empty()) {
24460b57cec5SDimitry Andric const SDep &Cur = Worklist.pop_back_val();
24470b57cec5SDimitry Andric SUnit *SuccSU = Cur.getSUnit();
24480b57cec5SDimitry Andric if (Visited.count(SuccSU))
24490b57cec5SDimitry Andric continue;
24500b57cec5SDimitry Andric std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
24510b57cec5SDimitry Andric if (it == InstrToCycle.end())
24520b57cec5SDimitry Andric continue;
24530b57cec5SDimitry Andric LateCycle = std::max(LateCycle, it->second);
24540b57cec5SDimitry Andric for (const auto &SI : SuccSU->Succs)
24555ffd83dbSDimitry Andric if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output)
24560b57cec5SDimitry Andric Worklist.push_back(SI);
24570b57cec5SDimitry Andric Visited.insert(SuccSU);
24580b57cec5SDimitry Andric }
24590b57cec5SDimitry Andric return LateCycle;
24600b57cec5SDimitry Andric }
24610b57cec5SDimitry Andric
24620b57cec5SDimitry Andric /// If an instruction has a use that spans multiple iterations, then
24630b57cec5SDimitry Andric /// return true. These instructions are characterized by having a back-ege
24640b57cec5SDimitry Andric /// to a Phi, which contains a reference to another Phi.
multipleIterations(SUnit * SU,SwingSchedulerDAG * DAG)24650b57cec5SDimitry Andric static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
24660b57cec5SDimitry Andric for (auto &P : SU->Preds)
24670b57cec5SDimitry Andric if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
24680b57cec5SDimitry Andric for (auto &S : P.getSUnit()->Succs)
24690b57cec5SDimitry Andric if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
24700b57cec5SDimitry Andric return P.getSUnit();
24710b57cec5SDimitry Andric return nullptr;
24720b57cec5SDimitry Andric }
24730b57cec5SDimitry Andric
24740b57cec5SDimitry Andric /// Compute the scheduling start slot for the instruction. The start slot
24750b57cec5SDimitry Andric /// depends on any predecessor or successor nodes scheduled already.
computeStart(SUnit * SU,int * MaxEarlyStart,int * MinLateStart,int * MinEnd,int * MaxStart,int II,SwingSchedulerDAG * DAG)24760b57cec5SDimitry Andric void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
24770b57cec5SDimitry Andric int *MinEnd, int *MaxStart, int II,
24780b57cec5SDimitry Andric SwingSchedulerDAG *DAG) {
24790b57cec5SDimitry Andric // Iterate over each instruction that has been scheduled already. The start
24800b57cec5SDimitry Andric // slot computation depends on whether the previously scheduled instruction
24810b57cec5SDimitry Andric // is a predecessor or successor of the specified instruction.
24820b57cec5SDimitry Andric for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
24830b57cec5SDimitry Andric
24840b57cec5SDimitry Andric // Iterate over each instruction in the current cycle.
24850b57cec5SDimitry Andric for (SUnit *I : getInstructions(cycle)) {
24860b57cec5SDimitry Andric // Because we're processing a DAG for the dependences, we recognize
24870b57cec5SDimitry Andric // the back-edge in recurrences by anti dependences.
24880b57cec5SDimitry Andric for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
24890b57cec5SDimitry Andric const SDep &Dep = SU->Preds[i];
24900b57cec5SDimitry Andric if (Dep.getSUnit() == I) {
24910b57cec5SDimitry Andric if (!DAG->isBackedge(SU, Dep)) {
24920b57cec5SDimitry Andric int EarlyStart = cycle + Dep.getLatency() -
24930b57cec5SDimitry Andric DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
24940b57cec5SDimitry Andric *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
24950b57cec5SDimitry Andric if (DAG->isLoopCarriedDep(SU, Dep, false)) {
24960b57cec5SDimitry Andric int End = earliestCycleInChain(Dep) + (II - 1);
24970b57cec5SDimitry Andric *MinEnd = std::min(*MinEnd, End);
24980b57cec5SDimitry Andric }
24990b57cec5SDimitry Andric } else {
25000b57cec5SDimitry Andric int LateStart = cycle - Dep.getLatency() +
25010b57cec5SDimitry Andric DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
25020b57cec5SDimitry Andric *MinLateStart = std::min(*MinLateStart, LateStart);
25030b57cec5SDimitry Andric }
25040b57cec5SDimitry Andric }
25050b57cec5SDimitry Andric // For instruction that requires multiple iterations, make sure that
25060b57cec5SDimitry Andric // the dependent instruction is not scheduled past the definition.
25070b57cec5SDimitry Andric SUnit *BE = multipleIterations(I, DAG);
25080b57cec5SDimitry Andric if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
25090b57cec5SDimitry Andric !SU->isPred(I))
25100b57cec5SDimitry Andric *MinLateStart = std::min(*MinLateStart, cycle);
25110b57cec5SDimitry Andric }
25120b57cec5SDimitry Andric for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
25130b57cec5SDimitry Andric if (SU->Succs[i].getSUnit() == I) {
25140b57cec5SDimitry Andric const SDep &Dep = SU->Succs[i];
25150b57cec5SDimitry Andric if (!DAG->isBackedge(SU, Dep)) {
25160b57cec5SDimitry Andric int LateStart = cycle - Dep.getLatency() +
25170b57cec5SDimitry Andric DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
25180b57cec5SDimitry Andric *MinLateStart = std::min(*MinLateStart, LateStart);
25190b57cec5SDimitry Andric if (DAG->isLoopCarriedDep(SU, Dep)) {
25200b57cec5SDimitry Andric int Start = latestCycleInChain(Dep) + 1 - II;
25210b57cec5SDimitry Andric *MaxStart = std::max(*MaxStart, Start);
25220b57cec5SDimitry Andric }
25230b57cec5SDimitry Andric } else {
25240b57cec5SDimitry Andric int EarlyStart = cycle + Dep.getLatency() -
25250b57cec5SDimitry Andric DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
25260b57cec5SDimitry Andric *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
25270b57cec5SDimitry Andric }
25280b57cec5SDimitry Andric }
25290b57cec5SDimitry Andric }
25300b57cec5SDimitry Andric }
25310b57cec5SDimitry Andric }
25320b57cec5SDimitry Andric }
25330b57cec5SDimitry Andric
25340b57cec5SDimitry Andric /// Order the instructions within a cycle so that the definitions occur
25350b57cec5SDimitry Andric /// before the uses. Returns true if the instruction is added to the start
25360b57cec5SDimitry Andric /// of the list, or false if added to the end.
orderDependence(SwingSchedulerDAG * SSD,SUnit * SU,std::deque<SUnit * > & Insts)25370b57cec5SDimitry Andric void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
25380b57cec5SDimitry Andric std::deque<SUnit *> &Insts) {
25390b57cec5SDimitry Andric MachineInstr *MI = SU->getInstr();
25400b57cec5SDimitry Andric bool OrderBeforeUse = false;
25410b57cec5SDimitry Andric bool OrderAfterDef = false;
25420b57cec5SDimitry Andric bool OrderBeforeDef = false;
25430b57cec5SDimitry Andric unsigned MoveDef = 0;
25440b57cec5SDimitry Andric unsigned MoveUse = 0;
25450b57cec5SDimitry Andric int StageInst1 = stageScheduled(SU);
25460b57cec5SDimitry Andric
25470b57cec5SDimitry Andric unsigned Pos = 0;
25480b57cec5SDimitry Andric for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
25490b57cec5SDimitry Andric ++I, ++Pos) {
25500b57cec5SDimitry Andric for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
25510b57cec5SDimitry Andric MachineOperand &MO = MI->getOperand(i);
25528bcb0991SDimitry Andric if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
25530b57cec5SDimitry Andric continue;
25540b57cec5SDimitry Andric
25558bcb0991SDimitry Andric Register Reg = MO.getReg();
25560b57cec5SDimitry Andric unsigned BasePos, OffsetPos;
25570b57cec5SDimitry Andric if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
25580b57cec5SDimitry Andric if (MI->getOperand(BasePos).getReg() == Reg)
25590b57cec5SDimitry Andric if (unsigned NewReg = SSD->getInstrBaseReg(SU))
25600b57cec5SDimitry Andric Reg = NewReg;
25610b57cec5SDimitry Andric bool Reads, Writes;
25620b57cec5SDimitry Andric std::tie(Reads, Writes) =
25630b57cec5SDimitry Andric (*I)->getInstr()->readsWritesVirtualRegister(Reg);
25640b57cec5SDimitry Andric if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
25650b57cec5SDimitry Andric OrderBeforeUse = true;
25660b57cec5SDimitry Andric if (MoveUse == 0)
25670b57cec5SDimitry Andric MoveUse = Pos;
25680b57cec5SDimitry Andric } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
25690b57cec5SDimitry Andric // Add the instruction after the scheduled instruction.
25700b57cec5SDimitry Andric OrderAfterDef = true;
25710b57cec5SDimitry Andric MoveDef = Pos;
25720b57cec5SDimitry Andric } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
25730b57cec5SDimitry Andric if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
25740b57cec5SDimitry Andric OrderBeforeUse = true;
25750b57cec5SDimitry Andric if (MoveUse == 0)
25760b57cec5SDimitry Andric MoveUse = Pos;
25770b57cec5SDimitry Andric } else {
25780b57cec5SDimitry Andric OrderAfterDef = true;
25790b57cec5SDimitry Andric MoveDef = Pos;
25800b57cec5SDimitry Andric }
25810b57cec5SDimitry Andric } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
25820b57cec5SDimitry Andric OrderBeforeUse = true;
25830b57cec5SDimitry Andric if (MoveUse == 0)
25840b57cec5SDimitry Andric MoveUse = Pos;
25850b57cec5SDimitry Andric if (MoveUse != 0) {
25860b57cec5SDimitry Andric OrderAfterDef = true;
25870b57cec5SDimitry Andric MoveDef = Pos - 1;
25880b57cec5SDimitry Andric }
25890b57cec5SDimitry Andric } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
25900b57cec5SDimitry Andric // Add the instruction before the scheduled instruction.
25910b57cec5SDimitry Andric OrderBeforeUse = true;
25920b57cec5SDimitry Andric if (MoveUse == 0)
25930b57cec5SDimitry Andric MoveUse = Pos;
25940b57cec5SDimitry Andric } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
25950b57cec5SDimitry Andric isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
25960b57cec5SDimitry Andric if (MoveUse == 0) {
25970b57cec5SDimitry Andric OrderBeforeDef = true;
25980b57cec5SDimitry Andric MoveUse = Pos;
25990b57cec5SDimitry Andric }
26000b57cec5SDimitry Andric }
26010b57cec5SDimitry Andric }
26020b57cec5SDimitry Andric // Check for order dependences between instructions. Make sure the source
26030b57cec5SDimitry Andric // is ordered before the destination.
26040b57cec5SDimitry Andric for (auto &S : SU->Succs) {
26050b57cec5SDimitry Andric if (S.getSUnit() != *I)
26060b57cec5SDimitry Andric continue;
26070b57cec5SDimitry Andric if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
26080b57cec5SDimitry Andric OrderBeforeUse = true;
26090b57cec5SDimitry Andric if (Pos < MoveUse)
26100b57cec5SDimitry Andric MoveUse = Pos;
26110b57cec5SDimitry Andric }
26120b57cec5SDimitry Andric // We did not handle HW dependences in previous for loop,
26130b57cec5SDimitry Andric // and we normally set Latency = 0 for Anti deps,
26140b57cec5SDimitry Andric // so may have nodes in same cycle with Anti denpendent on HW regs.
26150b57cec5SDimitry Andric else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
26160b57cec5SDimitry Andric OrderBeforeUse = true;
26170b57cec5SDimitry Andric if ((MoveUse == 0) || (Pos < MoveUse))
26180b57cec5SDimitry Andric MoveUse = Pos;
26190b57cec5SDimitry Andric }
26200b57cec5SDimitry Andric }
26210b57cec5SDimitry Andric for (auto &P : SU->Preds) {
26220b57cec5SDimitry Andric if (P.getSUnit() != *I)
26230b57cec5SDimitry Andric continue;
26240b57cec5SDimitry Andric if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
26250b57cec5SDimitry Andric OrderAfterDef = true;
26260b57cec5SDimitry Andric MoveDef = Pos;
26270b57cec5SDimitry Andric }
26280b57cec5SDimitry Andric }
26290b57cec5SDimitry Andric }
26300b57cec5SDimitry Andric
26310b57cec5SDimitry Andric // A circular dependence.
26320b57cec5SDimitry Andric if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
26330b57cec5SDimitry Andric OrderBeforeUse = false;
26340b57cec5SDimitry Andric
26350b57cec5SDimitry Andric // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
26360b57cec5SDimitry Andric // to a loop-carried dependence.
26370b57cec5SDimitry Andric if (OrderBeforeDef)
26380b57cec5SDimitry Andric OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
26390b57cec5SDimitry Andric
26400b57cec5SDimitry Andric // The uncommon case when the instruction order needs to be updated because
26410b57cec5SDimitry Andric // there is both a use and def.
26420b57cec5SDimitry Andric if (OrderBeforeUse && OrderAfterDef) {
26430b57cec5SDimitry Andric SUnit *UseSU = Insts.at(MoveUse);
26440b57cec5SDimitry Andric SUnit *DefSU = Insts.at(MoveDef);
26450b57cec5SDimitry Andric if (MoveUse > MoveDef) {
26460b57cec5SDimitry Andric Insts.erase(Insts.begin() + MoveUse);
26470b57cec5SDimitry Andric Insts.erase(Insts.begin() + MoveDef);
26480b57cec5SDimitry Andric } else {
26490b57cec5SDimitry Andric Insts.erase(Insts.begin() + MoveDef);
26500b57cec5SDimitry Andric Insts.erase(Insts.begin() + MoveUse);
26510b57cec5SDimitry Andric }
26520b57cec5SDimitry Andric orderDependence(SSD, UseSU, Insts);
26530b57cec5SDimitry Andric orderDependence(SSD, SU, Insts);
26540b57cec5SDimitry Andric orderDependence(SSD, DefSU, Insts);
26550b57cec5SDimitry Andric return;
26560b57cec5SDimitry Andric }
26570b57cec5SDimitry Andric // Put the new instruction first if there is a use in the list. Otherwise,
26580b57cec5SDimitry Andric // put it at the end of the list.
26590b57cec5SDimitry Andric if (OrderBeforeUse)
26600b57cec5SDimitry Andric Insts.push_front(SU);
26610b57cec5SDimitry Andric else
26620b57cec5SDimitry Andric Insts.push_back(SU);
26630b57cec5SDimitry Andric }
26640b57cec5SDimitry Andric
26650b57cec5SDimitry Andric /// Return true if the scheduled Phi has a loop carried operand.
isLoopCarried(SwingSchedulerDAG * SSD,MachineInstr & Phi)26660b57cec5SDimitry Andric bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
26670b57cec5SDimitry Andric if (!Phi.isPHI())
26680b57cec5SDimitry Andric return false;
26690b57cec5SDimitry Andric assert(Phi.isPHI() && "Expecting a Phi.");
26700b57cec5SDimitry Andric SUnit *DefSU = SSD->getSUnit(&Phi);
26710b57cec5SDimitry Andric unsigned DefCycle = cycleScheduled(DefSU);
26720b57cec5SDimitry Andric int DefStage = stageScheduled(DefSU);
26730b57cec5SDimitry Andric
26740b57cec5SDimitry Andric unsigned InitVal = 0;
26750b57cec5SDimitry Andric unsigned LoopVal = 0;
26760b57cec5SDimitry Andric getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
26770b57cec5SDimitry Andric SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
26780b57cec5SDimitry Andric if (!UseSU)
26790b57cec5SDimitry Andric return true;
26800b57cec5SDimitry Andric if (UseSU->getInstr()->isPHI())
26810b57cec5SDimitry Andric return true;
26820b57cec5SDimitry Andric unsigned LoopCycle = cycleScheduled(UseSU);
26830b57cec5SDimitry Andric int LoopStage = stageScheduled(UseSU);
26840b57cec5SDimitry Andric return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
26850b57cec5SDimitry Andric }
26860b57cec5SDimitry Andric
26870b57cec5SDimitry Andric /// Return true if the instruction is a definition that is loop carried
26880b57cec5SDimitry Andric /// and defines the use on the next iteration.
26890b57cec5SDimitry Andric /// v1 = phi(v2, v3)
26900b57cec5SDimitry Andric /// (Def) v3 = op v1
26910b57cec5SDimitry Andric /// (MO) = v1
26920b57cec5SDimitry Andric /// If MO appears before Def, then then v1 and v3 may get assigned to the same
26930b57cec5SDimitry Andric /// register.
isLoopCarriedDefOfUse(SwingSchedulerDAG * SSD,MachineInstr * Def,MachineOperand & MO)26940b57cec5SDimitry Andric bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
26950b57cec5SDimitry Andric MachineInstr *Def, MachineOperand &MO) {
26960b57cec5SDimitry Andric if (!MO.isReg())
26970b57cec5SDimitry Andric return false;
26980b57cec5SDimitry Andric if (Def->isPHI())
26990b57cec5SDimitry Andric return false;
27000b57cec5SDimitry Andric MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
27010b57cec5SDimitry Andric if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
27020b57cec5SDimitry Andric return false;
27030b57cec5SDimitry Andric if (!isLoopCarried(SSD, *Phi))
27040b57cec5SDimitry Andric return false;
27050b57cec5SDimitry Andric unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
27060b57cec5SDimitry Andric for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
27070b57cec5SDimitry Andric MachineOperand &DMO = Def->getOperand(i);
27080b57cec5SDimitry Andric if (!DMO.isReg() || !DMO.isDef())
27090b57cec5SDimitry Andric continue;
27100b57cec5SDimitry Andric if (DMO.getReg() == LoopReg)
27110b57cec5SDimitry Andric return true;
27120b57cec5SDimitry Andric }
27130b57cec5SDimitry Andric return false;
27140b57cec5SDimitry Andric }
27150b57cec5SDimitry Andric
27160b57cec5SDimitry Andric // Check if the generated schedule is valid. This function checks if
27170b57cec5SDimitry Andric // an instruction that uses a physical register is scheduled in a
27180b57cec5SDimitry Andric // different stage than the definition. The pipeliner does not handle
27190b57cec5SDimitry Andric // physical register values that may cross a basic block boundary.
isValidSchedule(SwingSchedulerDAG * SSD)27200b57cec5SDimitry Andric bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
2721*5f7ddb14SDimitry Andric for (SUnit &SU : SSD->SUnits) {
27220b57cec5SDimitry Andric if (!SU.hasPhysRegDefs)
27230b57cec5SDimitry Andric continue;
27240b57cec5SDimitry Andric int StageDef = stageScheduled(&SU);
27250b57cec5SDimitry Andric assert(StageDef != -1 && "Instruction should have been scheduled.");
27260b57cec5SDimitry Andric for (auto &SI : SU.Succs)
27270b57cec5SDimitry Andric if (SI.isAssignedRegDep())
27288bcb0991SDimitry Andric if (Register::isPhysicalRegister(SI.getReg()))
27290b57cec5SDimitry Andric if (stageScheduled(SI.getSUnit()) != StageDef)
27300b57cec5SDimitry Andric return false;
27310b57cec5SDimitry Andric }
27320b57cec5SDimitry Andric return true;
27330b57cec5SDimitry Andric }
27340b57cec5SDimitry Andric
27350b57cec5SDimitry Andric /// A property of the node order in swing-modulo-scheduling is
27360b57cec5SDimitry Andric /// that for nodes outside circuits the following holds:
27370b57cec5SDimitry Andric /// none of them is scheduled after both a successor and a
27380b57cec5SDimitry Andric /// predecessor.
27390b57cec5SDimitry Andric /// The method below checks whether the property is met.
27400b57cec5SDimitry Andric /// If not, debug information is printed and statistics information updated.
27410b57cec5SDimitry Andric /// Note that we do not use an assert statement.
27420b57cec5SDimitry Andric /// The reason is that although an invalid node oder may prevent
27430b57cec5SDimitry Andric /// the pipeliner from finding a pipelined schedule for arbitrary II,
27440b57cec5SDimitry Andric /// it does not lead to the generation of incorrect code.
checkValidNodeOrder(const NodeSetType & Circuits) const27450b57cec5SDimitry Andric void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
27460b57cec5SDimitry Andric
27470b57cec5SDimitry Andric // a sorted vector that maps each SUnit to its index in the NodeOrder
27480b57cec5SDimitry Andric typedef std::pair<SUnit *, unsigned> UnitIndex;
27490b57cec5SDimitry Andric std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
27500b57cec5SDimitry Andric
27510b57cec5SDimitry Andric for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
27520b57cec5SDimitry Andric Indices.push_back(std::make_pair(NodeOrder[i], i));
27530b57cec5SDimitry Andric
27540b57cec5SDimitry Andric auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
27550b57cec5SDimitry Andric return std::get<0>(i1) < std::get<0>(i2);
27560b57cec5SDimitry Andric };
27570b57cec5SDimitry Andric
27580b57cec5SDimitry Andric // sort, so that we can perform a binary search
27590b57cec5SDimitry Andric llvm::sort(Indices, CompareKey);
27600b57cec5SDimitry Andric
27610b57cec5SDimitry Andric bool Valid = true;
27620b57cec5SDimitry Andric (void)Valid;
27630b57cec5SDimitry Andric // for each SUnit in the NodeOrder, check whether
27640b57cec5SDimitry Andric // it appears after both a successor and a predecessor
27650b57cec5SDimitry Andric // of the SUnit. If this is the case, and the SUnit
27660b57cec5SDimitry Andric // is not part of circuit, then the NodeOrder is not
27670b57cec5SDimitry Andric // valid.
27680b57cec5SDimitry Andric for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
27690b57cec5SDimitry Andric SUnit *SU = NodeOrder[i];
27700b57cec5SDimitry Andric unsigned Index = i;
27710b57cec5SDimitry Andric
27720b57cec5SDimitry Andric bool PredBefore = false;
27730b57cec5SDimitry Andric bool SuccBefore = false;
27740b57cec5SDimitry Andric
27750b57cec5SDimitry Andric SUnit *Succ;
27760b57cec5SDimitry Andric SUnit *Pred;
27770b57cec5SDimitry Andric (void)Succ;
27780b57cec5SDimitry Andric (void)Pred;
27790b57cec5SDimitry Andric
27800b57cec5SDimitry Andric for (SDep &PredEdge : SU->Preds) {
27810b57cec5SDimitry Andric SUnit *PredSU = PredEdge.getSUnit();
27820b57cec5SDimitry Andric unsigned PredIndex = std::get<1>(
27830b57cec5SDimitry Andric *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
27840b57cec5SDimitry Andric if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
27850b57cec5SDimitry Andric PredBefore = true;
27860b57cec5SDimitry Andric Pred = PredSU;
27870b57cec5SDimitry Andric break;
27880b57cec5SDimitry Andric }
27890b57cec5SDimitry Andric }
27900b57cec5SDimitry Andric
27910b57cec5SDimitry Andric for (SDep &SuccEdge : SU->Succs) {
27920b57cec5SDimitry Andric SUnit *SuccSU = SuccEdge.getSUnit();
27930b57cec5SDimitry Andric // Do not process a boundary node, it was not included in NodeOrder,
27940b57cec5SDimitry Andric // hence not in Indices either, call to std::lower_bound() below will
27950b57cec5SDimitry Andric // return Indices.end().
27960b57cec5SDimitry Andric if (SuccSU->isBoundaryNode())
27970b57cec5SDimitry Andric continue;
27980b57cec5SDimitry Andric unsigned SuccIndex = std::get<1>(
27990b57cec5SDimitry Andric *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
28000b57cec5SDimitry Andric if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
28010b57cec5SDimitry Andric SuccBefore = true;
28020b57cec5SDimitry Andric Succ = SuccSU;
28030b57cec5SDimitry Andric break;
28040b57cec5SDimitry Andric }
28050b57cec5SDimitry Andric }
28060b57cec5SDimitry Andric
28070b57cec5SDimitry Andric if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
28080b57cec5SDimitry Andric // instructions in circuits are allowed to be scheduled
28090b57cec5SDimitry Andric // after both a successor and predecessor.
28100b57cec5SDimitry Andric bool InCircuit = llvm::any_of(
28110b57cec5SDimitry Andric Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
28120b57cec5SDimitry Andric if (InCircuit)
28130b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
28140b57cec5SDimitry Andric else {
28150b57cec5SDimitry Andric Valid = false;
28160b57cec5SDimitry Andric NumNodeOrderIssues++;
28170b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Predecessor ";);
28180b57cec5SDimitry Andric }
28190b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
28200b57cec5SDimitry Andric << " are scheduled before node " << SU->NodeNum
28210b57cec5SDimitry Andric << "\n";);
28220b57cec5SDimitry Andric }
28230b57cec5SDimitry Andric }
28240b57cec5SDimitry Andric
28250b57cec5SDimitry Andric LLVM_DEBUG({
28260b57cec5SDimitry Andric if (!Valid)
28270b57cec5SDimitry Andric dbgs() << "Invalid node order found!\n";
28280b57cec5SDimitry Andric });
28290b57cec5SDimitry Andric }
28300b57cec5SDimitry Andric
28310b57cec5SDimitry Andric /// Attempt to fix the degenerate cases when the instruction serialization
28320b57cec5SDimitry Andric /// causes the register lifetimes to overlap. For example,
28330b57cec5SDimitry Andric /// p' = store_pi(p, b)
28340b57cec5SDimitry Andric /// = load p, offset
28350b57cec5SDimitry Andric /// In this case p and p' overlap, which means that two registers are needed.
28360b57cec5SDimitry Andric /// Instead, this function changes the load to use p' and updates the offset.
fixupRegisterOverlaps(std::deque<SUnit * > & Instrs)28370b57cec5SDimitry Andric void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
28380b57cec5SDimitry Andric unsigned OverlapReg = 0;
28390b57cec5SDimitry Andric unsigned NewBaseReg = 0;
28400b57cec5SDimitry Andric for (SUnit *SU : Instrs) {
28410b57cec5SDimitry Andric MachineInstr *MI = SU->getInstr();
28420b57cec5SDimitry Andric for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
28430b57cec5SDimitry Andric const MachineOperand &MO = MI->getOperand(i);
28440b57cec5SDimitry Andric // Look for an instruction that uses p. The instruction occurs in the
28450b57cec5SDimitry Andric // same cycle but occurs later in the serialized order.
28460b57cec5SDimitry Andric if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
28470b57cec5SDimitry Andric // Check that the instruction appears in the InstrChanges structure,
28480b57cec5SDimitry Andric // which contains instructions that can have the offset updated.
28490b57cec5SDimitry Andric DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
28500b57cec5SDimitry Andric InstrChanges.find(SU);
28510b57cec5SDimitry Andric if (It != InstrChanges.end()) {
28520b57cec5SDimitry Andric unsigned BasePos, OffsetPos;
28530b57cec5SDimitry Andric // Update the base register and adjust the offset.
28540b57cec5SDimitry Andric if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
28550b57cec5SDimitry Andric MachineInstr *NewMI = MF.CloneMachineInstr(MI);
28560b57cec5SDimitry Andric NewMI->getOperand(BasePos).setReg(NewBaseReg);
28570b57cec5SDimitry Andric int64_t NewOffset =
28580b57cec5SDimitry Andric MI->getOperand(OffsetPos).getImm() - It->second.second;
28590b57cec5SDimitry Andric NewMI->getOperand(OffsetPos).setImm(NewOffset);
28600b57cec5SDimitry Andric SU->setInstr(NewMI);
28610b57cec5SDimitry Andric MISUnitMap[NewMI] = SU;
28628bcb0991SDimitry Andric NewMIs[MI] = NewMI;
28630b57cec5SDimitry Andric }
28640b57cec5SDimitry Andric }
28650b57cec5SDimitry Andric OverlapReg = 0;
28660b57cec5SDimitry Andric NewBaseReg = 0;
28670b57cec5SDimitry Andric break;
28680b57cec5SDimitry Andric }
28690b57cec5SDimitry Andric // Look for an instruction of the form p' = op(p), which uses and defines
28700b57cec5SDimitry Andric // two virtual registers that get allocated to the same physical register.
28710b57cec5SDimitry Andric unsigned TiedUseIdx = 0;
28720b57cec5SDimitry Andric if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
28730b57cec5SDimitry Andric // OverlapReg is p in the example above.
28740b57cec5SDimitry Andric OverlapReg = MI->getOperand(TiedUseIdx).getReg();
28750b57cec5SDimitry Andric // NewBaseReg is p' in the example above.
28760b57cec5SDimitry Andric NewBaseReg = MI->getOperand(i).getReg();
28770b57cec5SDimitry Andric break;
28780b57cec5SDimitry Andric }
28790b57cec5SDimitry Andric }
28800b57cec5SDimitry Andric }
28810b57cec5SDimitry Andric }
28820b57cec5SDimitry Andric
28830b57cec5SDimitry Andric /// After the schedule has been formed, call this function to combine
28840b57cec5SDimitry Andric /// the instructions from the different stages/cycles. That is, this
28850b57cec5SDimitry Andric /// function creates a schedule that represents a single iteration.
finalizeSchedule(SwingSchedulerDAG * SSD)28860b57cec5SDimitry Andric void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
28870b57cec5SDimitry Andric // Move all instructions to the first stage from later stages.
28880b57cec5SDimitry Andric for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
28890b57cec5SDimitry Andric for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
28900b57cec5SDimitry Andric ++stage) {
28910b57cec5SDimitry Andric std::deque<SUnit *> &cycleInstrs =
28920b57cec5SDimitry Andric ScheduledInstrs[cycle + (stage * InitiationInterval)];
28930b57cec5SDimitry Andric for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
28940b57cec5SDimitry Andric E = cycleInstrs.rend();
28950b57cec5SDimitry Andric I != E; ++I)
28960b57cec5SDimitry Andric ScheduledInstrs[cycle].push_front(*I);
28970b57cec5SDimitry Andric }
28980b57cec5SDimitry Andric }
28990b57cec5SDimitry Andric
29000b57cec5SDimitry Andric // Erase all the elements in the later stages. Only one iteration should
29010b57cec5SDimitry Andric // remain in the scheduled list, and it contains all the instructions.
29020b57cec5SDimitry Andric for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
29030b57cec5SDimitry Andric ScheduledInstrs.erase(cycle);
29040b57cec5SDimitry Andric
29050b57cec5SDimitry Andric // Change the registers in instruction as specified in the InstrChanges
29060b57cec5SDimitry Andric // map. We need to use the new registers to create the correct order.
29070b57cec5SDimitry Andric for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
29080b57cec5SDimitry Andric SUnit *SU = &SSD->SUnits[i];
29090b57cec5SDimitry Andric SSD->applyInstrChange(SU->getInstr(), *this);
29100b57cec5SDimitry Andric }
29110b57cec5SDimitry Andric
29120b57cec5SDimitry Andric // Reorder the instructions in each cycle to fix and improve the
29130b57cec5SDimitry Andric // generated code.
29140b57cec5SDimitry Andric for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
29150b57cec5SDimitry Andric std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
29160b57cec5SDimitry Andric std::deque<SUnit *> newOrderPhi;
2917*5f7ddb14SDimitry Andric for (SUnit *SU : cycleInstrs) {
29180b57cec5SDimitry Andric if (SU->getInstr()->isPHI())
29190b57cec5SDimitry Andric newOrderPhi.push_back(SU);
29200b57cec5SDimitry Andric }
29210b57cec5SDimitry Andric std::deque<SUnit *> newOrderI;
2922*5f7ddb14SDimitry Andric for (SUnit *SU : cycleInstrs) {
29230b57cec5SDimitry Andric if (!SU->getInstr()->isPHI())
29240b57cec5SDimitry Andric orderDependence(SSD, SU, newOrderI);
29250b57cec5SDimitry Andric }
29260b57cec5SDimitry Andric // Replace the old order with the new order.
29270b57cec5SDimitry Andric cycleInstrs.swap(newOrderPhi);
2928af732203SDimitry Andric llvm::append_range(cycleInstrs, newOrderI);
29290b57cec5SDimitry Andric SSD->fixupRegisterOverlaps(cycleInstrs);
29300b57cec5SDimitry Andric }
29310b57cec5SDimitry Andric
29320b57cec5SDimitry Andric LLVM_DEBUG(dump(););
29330b57cec5SDimitry Andric }
29340b57cec5SDimitry Andric
print(raw_ostream & os) const29350b57cec5SDimitry Andric void NodeSet::print(raw_ostream &os) const {
29360b57cec5SDimitry Andric os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
29370b57cec5SDimitry Andric << " depth " << MaxDepth << " col " << Colocate << "\n";
29380b57cec5SDimitry Andric for (const auto &I : Nodes)
29390b57cec5SDimitry Andric os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
29400b57cec5SDimitry Andric os << "\n";
29410b57cec5SDimitry Andric }
29420b57cec5SDimitry Andric
29430b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
29440b57cec5SDimitry Andric /// Print the schedule information to the given output.
print(raw_ostream & os) const29450b57cec5SDimitry Andric void SMSchedule::print(raw_ostream &os) const {
29460b57cec5SDimitry Andric // Iterate over each cycle.
29470b57cec5SDimitry Andric for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
29480b57cec5SDimitry Andric // Iterate over each instruction in the cycle.
29490b57cec5SDimitry Andric const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
29500b57cec5SDimitry Andric for (SUnit *CI : cycleInstrs->second) {
29510b57cec5SDimitry Andric os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
29520b57cec5SDimitry Andric os << "(" << CI->NodeNum << ") ";
29530b57cec5SDimitry Andric CI->getInstr()->print(os);
29540b57cec5SDimitry Andric os << "\n";
29550b57cec5SDimitry Andric }
29560b57cec5SDimitry Andric }
29570b57cec5SDimitry Andric }
29580b57cec5SDimitry Andric
29590b57cec5SDimitry Andric /// Utility function used for debugging to print the schedule.
dump() const29600b57cec5SDimitry Andric LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
dump() const29610b57cec5SDimitry Andric LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
29620b57cec5SDimitry Andric
29630b57cec5SDimitry Andric #endif
29640b57cec5SDimitry Andric
initProcResourceVectors(const MCSchedModel & SM,SmallVectorImpl<uint64_t> & Masks)29650b57cec5SDimitry Andric void ResourceManager::initProcResourceVectors(
29660b57cec5SDimitry Andric const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
29670b57cec5SDimitry Andric unsigned ProcResourceID = 0;
29680b57cec5SDimitry Andric
29690b57cec5SDimitry Andric // We currently limit the resource kinds to 64 and below so that we can use
29700b57cec5SDimitry Andric // uint64_t for Masks
29710b57cec5SDimitry Andric assert(SM.getNumProcResourceKinds() < 64 &&
29720b57cec5SDimitry Andric "Too many kinds of resources, unsupported");
29730b57cec5SDimitry Andric // Create a unique bitmask for every processor resource unit.
29740b57cec5SDimitry Andric // Skip resource at index 0, since it always references 'InvalidUnit'.
29750b57cec5SDimitry Andric Masks.resize(SM.getNumProcResourceKinds());
29760b57cec5SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
29770b57cec5SDimitry Andric const MCProcResourceDesc &Desc = *SM.getProcResource(I);
29780b57cec5SDimitry Andric if (Desc.SubUnitsIdxBegin)
29790b57cec5SDimitry Andric continue;
29800b57cec5SDimitry Andric Masks[I] = 1ULL << ProcResourceID;
29810b57cec5SDimitry Andric ProcResourceID++;
29820b57cec5SDimitry Andric }
29830b57cec5SDimitry Andric // Create a unique bitmask for every processor resource group.
29840b57cec5SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
29850b57cec5SDimitry Andric const MCProcResourceDesc &Desc = *SM.getProcResource(I);
29860b57cec5SDimitry Andric if (!Desc.SubUnitsIdxBegin)
29870b57cec5SDimitry Andric continue;
29880b57cec5SDimitry Andric Masks[I] = 1ULL << ProcResourceID;
29890b57cec5SDimitry Andric for (unsigned U = 0; U < Desc.NumUnits; ++U)
29900b57cec5SDimitry Andric Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
29910b57cec5SDimitry Andric ProcResourceID++;
29920b57cec5SDimitry Andric }
29930b57cec5SDimitry Andric LLVM_DEBUG({
29940b57cec5SDimitry Andric if (SwpShowResMask) {
29950b57cec5SDimitry Andric dbgs() << "ProcResourceDesc:\n";
29960b57cec5SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
29970b57cec5SDimitry Andric const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
29980b57cec5SDimitry Andric dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
29990b57cec5SDimitry Andric ProcResource->Name, I, Masks[I],
30000b57cec5SDimitry Andric ProcResource->NumUnits);
30010b57cec5SDimitry Andric }
30020b57cec5SDimitry Andric dbgs() << " -----------------\n";
30030b57cec5SDimitry Andric }
30040b57cec5SDimitry Andric });
30050b57cec5SDimitry Andric }
30060b57cec5SDimitry Andric
canReserveResources(const MCInstrDesc * MID) const30070b57cec5SDimitry Andric bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
30080b57cec5SDimitry Andric
30090b57cec5SDimitry Andric LLVM_DEBUG({
30100b57cec5SDimitry Andric if (SwpDebugResource)
30110b57cec5SDimitry Andric dbgs() << "canReserveResources:\n";
30120b57cec5SDimitry Andric });
30130b57cec5SDimitry Andric if (UseDFA)
30140b57cec5SDimitry Andric return DFAResources->canReserveResources(MID);
30150b57cec5SDimitry Andric
30160b57cec5SDimitry Andric unsigned InsnClass = MID->getSchedClass();
30170b57cec5SDimitry Andric const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
30180b57cec5SDimitry Andric if (!SCDesc->isValid()) {
30190b57cec5SDimitry Andric LLVM_DEBUG({
30200b57cec5SDimitry Andric dbgs() << "No valid Schedule Class Desc for schedClass!\n";
30210b57cec5SDimitry Andric dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
30220b57cec5SDimitry Andric });
30230b57cec5SDimitry Andric return true;
30240b57cec5SDimitry Andric }
30250b57cec5SDimitry Andric
30260b57cec5SDimitry Andric const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
30270b57cec5SDimitry Andric const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
30280b57cec5SDimitry Andric for (; I != E; ++I) {
30290b57cec5SDimitry Andric if (!I->Cycles)
30300b57cec5SDimitry Andric continue;
30310b57cec5SDimitry Andric const MCProcResourceDesc *ProcResource =
30320b57cec5SDimitry Andric SM.getProcResource(I->ProcResourceIdx);
30330b57cec5SDimitry Andric unsigned NumUnits = ProcResource->NumUnits;
30340b57cec5SDimitry Andric LLVM_DEBUG({
30350b57cec5SDimitry Andric if (SwpDebugResource)
30360b57cec5SDimitry Andric dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
30370b57cec5SDimitry Andric ProcResource->Name, I->ProcResourceIdx,
30380b57cec5SDimitry Andric ProcResourceCount[I->ProcResourceIdx], NumUnits,
30390b57cec5SDimitry Andric I->Cycles);
30400b57cec5SDimitry Andric });
30410b57cec5SDimitry Andric if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
30420b57cec5SDimitry Andric return false;
30430b57cec5SDimitry Andric }
30440b57cec5SDimitry Andric LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
30450b57cec5SDimitry Andric return true;
30460b57cec5SDimitry Andric }
30470b57cec5SDimitry Andric
reserveResources(const MCInstrDesc * MID)30480b57cec5SDimitry Andric void ResourceManager::reserveResources(const MCInstrDesc *MID) {
30490b57cec5SDimitry Andric LLVM_DEBUG({
30500b57cec5SDimitry Andric if (SwpDebugResource)
30510b57cec5SDimitry Andric dbgs() << "reserveResources:\n";
30520b57cec5SDimitry Andric });
30530b57cec5SDimitry Andric if (UseDFA)
30540b57cec5SDimitry Andric return DFAResources->reserveResources(MID);
30550b57cec5SDimitry Andric
30560b57cec5SDimitry Andric unsigned InsnClass = MID->getSchedClass();
30570b57cec5SDimitry Andric const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
30580b57cec5SDimitry Andric if (!SCDesc->isValid()) {
30590b57cec5SDimitry Andric LLVM_DEBUG({
30600b57cec5SDimitry Andric dbgs() << "No valid Schedule Class Desc for schedClass!\n";
30610b57cec5SDimitry Andric dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
30620b57cec5SDimitry Andric });
30630b57cec5SDimitry Andric return;
30640b57cec5SDimitry Andric }
30650b57cec5SDimitry Andric for (const MCWriteProcResEntry &PRE :
30660b57cec5SDimitry Andric make_range(STI->getWriteProcResBegin(SCDesc),
30670b57cec5SDimitry Andric STI->getWriteProcResEnd(SCDesc))) {
30680b57cec5SDimitry Andric if (!PRE.Cycles)
30690b57cec5SDimitry Andric continue;
30700b57cec5SDimitry Andric ++ProcResourceCount[PRE.ProcResourceIdx];
30710b57cec5SDimitry Andric LLVM_DEBUG({
30720b57cec5SDimitry Andric if (SwpDebugResource) {
30730b57cec5SDimitry Andric const MCProcResourceDesc *ProcResource =
30740b57cec5SDimitry Andric SM.getProcResource(PRE.ProcResourceIdx);
30750b57cec5SDimitry Andric dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
30760b57cec5SDimitry Andric ProcResource->Name, PRE.ProcResourceIdx,
30770b57cec5SDimitry Andric ProcResourceCount[PRE.ProcResourceIdx],
30780b57cec5SDimitry Andric ProcResource->NumUnits, PRE.Cycles);
30790b57cec5SDimitry Andric }
30800b57cec5SDimitry Andric });
30810b57cec5SDimitry Andric }
30820b57cec5SDimitry Andric LLVM_DEBUG({
30830b57cec5SDimitry Andric if (SwpDebugResource)
30840b57cec5SDimitry Andric dbgs() << "reserveResources: done!\n\n";
30850b57cec5SDimitry Andric });
30860b57cec5SDimitry Andric }
30870b57cec5SDimitry Andric
canReserveResources(const MachineInstr & MI) const30880b57cec5SDimitry Andric bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
30890b57cec5SDimitry Andric return canReserveResources(&MI.getDesc());
30900b57cec5SDimitry Andric }
30910b57cec5SDimitry Andric
reserveResources(const MachineInstr & MI)30920b57cec5SDimitry Andric void ResourceManager::reserveResources(const MachineInstr &MI) {
30930b57cec5SDimitry Andric return reserveResources(&MI.getDesc());
30940b57cec5SDimitry Andric }
30950b57cec5SDimitry Andric
clearResources()30960b57cec5SDimitry Andric void ResourceManager::clearResources() {
30970b57cec5SDimitry Andric if (UseDFA)
30980b57cec5SDimitry Andric return DFAResources->clearResources();
30990b57cec5SDimitry Andric std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
31000b57cec5SDimitry Andric }
3101