Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1 | //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===// |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner. |
| 11 | // |
| 12 | // Software pipelining (SWP) is an instruction scheduling technique for loops |
Roorda, Jan-Willem | 20a0e55 | 2018-03-06 16:26:01 +0000 | [diff] [blame] | 13 | // that overlap loop iterations and exploits ILP via a compiler transformation. |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 14 | // |
| 15 | // Swing Modulo Scheduling is an implementation of software pipelining |
| 16 | // that generates schedules that are near optimal in terms of initiation |
| 17 | // interval, register requirements, and stage count. See the papers: |
| 18 | // |
| 19 | // "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa, |
| 20 | // A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Processings of the 1996 |
| 21 | // Conference on Parallel Architectures and Compilation Techiniques. |
| 22 | // |
| 23 | // "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J. |
| 24 | // Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE |
| 25 | // Transactions on Computers, Vol. 50, No. 3, 2001. |
| 26 | // |
| 27 | // "An Implementation of Swing Modulo Scheduling With Extensions for |
| 28 | // Superblocks", by T. Lattner, Master's Thesis, University of Illinois at |
| 29 | // Urbana-Chambpain, 2005. |
| 30 | // |
| 31 | // |
| 32 | // The SMS algorithm consists of three main steps after computing the minimal |
| 33 | // initiation interval (MII). |
| 34 | // 1) Analyze the dependence graph and compute information about each |
| 35 | // instruction in the graph. |
| 36 | // 2) Order the nodes (instructions) by priority based upon the heuristics |
| 37 | // described in the algorithm. |
| 38 | // 3) Attempt to schedule the nodes in the specified order using the MII. |
| 39 | // |
| 40 | // This SMS implementation is a target-independent back-end pass. When enabled, |
| 41 | // the pass runs just prior to the register allocation pass, while the machine |
| 42 | // IR is in SSA form. If software pipelining is successful, then the original |
| 43 | // loop is replaced by the optimized loop. The optimized loop contains one or |
| 44 | // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If |
| 45 | // the instructions cannot be scheduled in a given MII, we increase the MII by |
| 46 | // one and try again. |
| 47 | // |
| 48 | // The SMS implementation is an extension of the ScheduleDAGInstrs class. We |
| 49 | // represent loop carried dependences in the DAG as order edges to the Phi |
| 50 | // nodes. We also perform several passes over the DAG to eliminate unnecessary |
| 51 | // edges that inhibit the ability to pipeline. The implementation uses the |
| 52 | // DFAPacketizer class to compute the minimum initiation interval and the check |
| 53 | // where an instruction may be inserted in the pipelined schedule. |
| 54 | // |
| 55 | // In order for the SMS pass to work, several target specific hooks need to be |
| 56 | // implemented to get information about the loop structure and to rewrite |
| 57 | // instructions. |
| 58 | // |
| 59 | //===----------------------------------------------------------------------===// |
| 60 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 61 | #include "llvm/ADT/ArrayRef.h" |
| 62 | #include "llvm/ADT/BitVector.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 63 | #include "llvm/ADT/DenseMap.h" |
| 64 | #include "llvm/ADT/MapVector.h" |
| 65 | #include "llvm/ADT/PriorityQueue.h" |
| 66 | #include "llvm/ADT/SetVector.h" |
| 67 | #include "llvm/ADT/SmallPtrSet.h" |
| 68 | #include "llvm/ADT/SmallSet.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 69 | #include "llvm/ADT/SmallVector.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 70 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 71 | #include "llvm/ADT/iterator_range.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 72 | #include "llvm/Analysis/AliasAnalysis.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 73 | #include "llvm/Analysis/MemoryLocation.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 74 | #include "llvm/Analysis/ValueTracking.h" |
| 75 | #include "llvm/CodeGen/DFAPacketizer.h" |
Matthias Braun | f842297 | 2017-12-13 02:51:04 +0000 | [diff] [blame] | 76 | #include "llvm/CodeGen/LiveIntervals.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 77 | #include "llvm/CodeGen/MachineBasicBlock.h" |
| 78 | #include "llvm/CodeGen/MachineDominators.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 79 | #include "llvm/CodeGen/MachineFunction.h" |
| 80 | #include "llvm/CodeGen/MachineFunctionPass.h" |
| 81 | #include "llvm/CodeGen/MachineInstr.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 82 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 83 | #include "llvm/CodeGen/MachineLoopInfo.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 84 | #include "llvm/CodeGen/MachineMemOperand.h" |
| 85 | #include "llvm/CodeGen/MachineOperand.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 86 | #include "llvm/CodeGen/MachineRegisterInfo.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 87 | #include "llvm/CodeGen/RegisterClassInfo.h" |
| 88 | #include "llvm/CodeGen/RegisterPressure.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 89 | #include "llvm/CodeGen/ScheduleDAG.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 90 | #include "llvm/CodeGen/ScheduleDAGInstrs.h" |
Krzysztof Parzyszek | 8839124 | 2016-12-22 19:21:20 +0000 | [diff] [blame] | 91 | #include "llvm/CodeGen/ScheduleDAGMutation.h" |
David Blaikie | 3f833ed | 2017-11-08 01:01:31 +0000 | [diff] [blame] | 92 | #include "llvm/CodeGen/TargetInstrInfo.h" |
David Blaikie | b3bde2e | 2017-11-17 01:07:10 +0000 | [diff] [blame] | 93 | #include "llvm/CodeGen/TargetOpcodes.h" |
| 94 | #include "llvm/CodeGen/TargetRegisterInfo.h" |
| 95 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 96 | #include "llvm/IR/Attributes.h" |
| 97 | #include "llvm/IR/DebugLoc.h" |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 98 | #include "llvm/IR/Function.h" |
| 99 | #include "llvm/MC/LaneBitmask.h" |
| 100 | #include "llvm/MC/MCInstrDesc.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 101 | #include "llvm/MC/MCInstrItineraries.h" |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 102 | #include "llvm/MC/MCRegisterInfo.h" |
| 103 | #include "llvm/Pass.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 104 | #include "llvm/Support/CommandLine.h" |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 105 | #include "llvm/Support/Compiler.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 106 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 107 | #include "llvm/Support/MathExtras.h" |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 108 | #include "llvm/Support/raw_ostream.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 109 | #include <algorithm> |
| 110 | #include <cassert> |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 111 | #include <climits> |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 112 | #include <cstdint> |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 113 | #include <deque> |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 114 | #include <functional> |
| 115 | #include <iterator> |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 116 | #include <map> |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 117 | #include <memory> |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 118 | #include <tuple> |
| 119 | #include <utility> |
| 120 | #include <vector> |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 121 | |
| 122 | using namespace llvm; |
| 123 | |
| 124 | #define DEBUG_TYPE "pipeliner" |
| 125 | |
| 126 | STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline"); |
| 127 | STATISTIC(NumPipelined, "Number of loops software pipelined"); |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 128 | STATISTIC(NumNodeOrderIssues, "Number of node order issues found"); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 129 | |
| 130 | /// A command line option to turn software pipelining on or off. |
Benjamin Kramer | b7d3311 | 2016-08-06 11:13:10 +0000 | [diff] [blame] | 131 | static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true), |
| 132 | cl::ZeroOrMore, |
| 133 | cl::desc("Enable Software Pipelining")); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 134 | |
| 135 | /// A command line option to enable SWP at -Os. |
| 136 | static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size", |
| 137 | cl::desc("Enable SWP at Os."), cl::Hidden, |
| 138 | cl::init(false)); |
| 139 | |
| 140 | /// A command line argument to limit minimum initial interval for pipelining. |
| 141 | static cl::opt<int> SwpMaxMii("pipeliner-max-mii", |
Hiroshi Inoue | 8f976ba | 2018-01-17 12:29:38 +0000 | [diff] [blame] | 142 | cl::desc("Size limit for the MII."), |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 143 | cl::Hidden, cl::init(27)); |
| 144 | |
| 145 | /// A command line argument to limit the number of stages in the pipeline. |
| 146 | static cl::opt<int> |
| 147 | SwpMaxStages("pipeliner-max-stages", |
| 148 | cl::desc("Maximum stages allowed in the generated scheduled."), |
| 149 | cl::Hidden, cl::init(3)); |
| 150 | |
| 151 | /// A command line option to disable the pruning of chain dependences due to |
| 152 | /// an unrelated Phi. |
| 153 | static cl::opt<bool> |
| 154 | SwpPruneDeps("pipeliner-prune-deps", |
| 155 | cl::desc("Prune dependences between unrelated Phi nodes."), |
| 156 | cl::Hidden, cl::init(true)); |
| 157 | |
| 158 | /// A command line option to disable the pruning of loop carried order |
| 159 | /// dependences. |
| 160 | static cl::opt<bool> |
| 161 | SwpPruneLoopCarried("pipeliner-prune-loop-carried", |
| 162 | cl::desc("Prune loop carried order dependences."), |
| 163 | cl::Hidden, cl::init(true)); |
| 164 | |
| 165 | #ifndef NDEBUG |
| 166 | static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1)); |
| 167 | #endif |
| 168 | |
| 169 | static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii", |
| 170 | cl::ReallyHidden, cl::init(false), |
| 171 | cl::ZeroOrMore, cl::desc("Ignore RecMII")); |
| 172 | |
| 173 | namespace { |
| 174 | |
| 175 | class NodeSet; |
| 176 | class SMSchedule; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 177 | |
| 178 | /// The main class in the implementation of the target independent |
| 179 | /// software pipeliner pass. |
| 180 | class MachinePipeliner : public MachineFunctionPass { |
| 181 | public: |
| 182 | MachineFunction *MF = nullptr; |
| 183 | const MachineLoopInfo *MLI = nullptr; |
| 184 | const MachineDominatorTree *MDT = nullptr; |
| 185 | const InstrItineraryData *InstrItins; |
| 186 | const TargetInstrInfo *TII = nullptr; |
| 187 | RegisterClassInfo RegClassInfo; |
| 188 | |
| 189 | #ifndef NDEBUG |
| 190 | static int NumTries; |
| 191 | #endif |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 192 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 193 | /// Cache the target analysis information about the loop. |
| 194 | struct LoopInfo { |
| 195 | MachineBasicBlock *TBB = nullptr; |
| 196 | MachineBasicBlock *FBB = nullptr; |
| 197 | SmallVector<MachineOperand, 4> BrCond; |
| 198 | MachineInstr *LoopInductionVar = nullptr; |
| 199 | MachineInstr *LoopCompare = nullptr; |
| 200 | }; |
| 201 | LoopInfo LI; |
| 202 | |
| 203 | static char ID; |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 204 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 205 | MachinePipeliner() : MachineFunctionPass(ID) { |
| 206 | initializeMachinePipelinerPass(*PassRegistry::getPassRegistry()); |
| 207 | } |
| 208 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 209 | bool runOnMachineFunction(MachineFunction &MF) override; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 210 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 211 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 212 | AU.addRequired<AAResultsWrapperPass>(); |
| 213 | AU.addPreserved<AAResultsWrapperPass>(); |
| 214 | AU.addRequired<MachineLoopInfo>(); |
| 215 | AU.addRequired<MachineDominatorTree>(); |
| 216 | AU.addRequired<LiveIntervals>(); |
| 217 | MachineFunctionPass::getAnalysisUsage(AU); |
| 218 | } |
| 219 | |
| 220 | private: |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 221 | void preprocessPhiNodes(MachineBasicBlock &B); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 222 | bool canPipelineLoop(MachineLoop &L); |
| 223 | bool scheduleLoop(MachineLoop &L); |
| 224 | bool swingModuloScheduler(MachineLoop &L); |
| 225 | }; |
| 226 | |
| 227 | /// This class builds the dependence graph for the instructions in a loop, |
| 228 | /// and attempts to schedule the instructions using the SMS algorithm. |
| 229 | class SwingSchedulerDAG : public ScheduleDAGInstrs { |
| 230 | MachinePipeliner &Pass; |
| 231 | /// The minimum initiation interval between iterations for this schedule. |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 232 | unsigned MII = 0; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 233 | /// Set to true if a valid pipelined schedule is found for the loop. |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 234 | bool Scheduled = false; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 235 | MachineLoop &Loop; |
| 236 | LiveIntervals &LIS; |
| 237 | const RegisterClassInfo &RegClassInfo; |
| 238 | |
| 239 | /// A toplogical ordering of the SUnits, which is needed for changing |
| 240 | /// dependences and iterating over the SUnits. |
| 241 | ScheduleDAGTopologicalSort Topo; |
| 242 | |
| 243 | struct NodeInfo { |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 244 | int ASAP = 0; |
| 245 | int ALAP = 0; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 246 | int ZeroLatencyDepth = 0; |
| 247 | int ZeroLatencyHeight = 0; |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 248 | |
| 249 | NodeInfo() = default; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 250 | }; |
| 251 | /// Computed properties for each node in the graph. |
| 252 | std::vector<NodeInfo> ScheduleInfo; |
| 253 | |
| 254 | enum OrderKind { BottomUp = 0, TopDown = 1 }; |
| 255 | /// Computed node ordering for scheduling. |
| 256 | SetVector<SUnit *> NodeOrder; |
| 257 | |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 258 | using NodeSetType = SmallVector<NodeSet, 8>; |
| 259 | using ValueMapTy = DenseMap<unsigned, unsigned>; |
| 260 | using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>; |
| 261 | using InstrMapTy = DenseMap<MachineInstr *, MachineInstr *>; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 262 | |
| 263 | /// Instructions to change when emitting the final schedule. |
| 264 | DenseMap<SUnit *, std::pair<unsigned, int64_t>> InstrChanges; |
| 265 | |
| 266 | /// We may create a new instruction, so remember it because it |
| 267 | /// must be deleted when the pass is finished. |
| 268 | SmallPtrSet<MachineInstr *, 4> NewMIs; |
| 269 | |
Krzysztof Parzyszek | 8839124 | 2016-12-22 19:21:20 +0000 | [diff] [blame] | 270 | /// Ordered list of DAG postprocessing steps. |
| 271 | std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations; |
| 272 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 273 | /// Helper class to implement Johnson's circuit finding algorithm. |
| 274 | class Circuits { |
| 275 | std::vector<SUnit> &SUnits; |
| 276 | SetVector<SUnit *> Stack; |
| 277 | BitVector Blocked; |
| 278 | SmallVector<SmallPtrSet<SUnit *, 4>, 10> B; |
| 279 | SmallVector<SmallVector<int, 4>, 16> AdjK; |
| 280 | unsigned NumPaths; |
| 281 | static unsigned MaxPaths; |
| 282 | |
| 283 | public: |
| 284 | Circuits(std::vector<SUnit> &SUs) |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 285 | : SUnits(SUs), Blocked(SUs.size()), B(SUs.size()), AdjK(SUs.size()) {} |
| 286 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 287 | /// Reset the data structures used in the circuit algorithm. |
| 288 | void reset() { |
| 289 | Stack.clear(); |
| 290 | Blocked.reset(); |
| 291 | B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>()); |
| 292 | NumPaths = 0; |
| 293 | } |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 294 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 295 | void createAdjacencyStructure(SwingSchedulerDAG *DAG); |
| 296 | bool circuit(int V, int S, NodeSetType &NodeSets, bool HasBackedge = false); |
| 297 | void unblock(int U); |
| 298 | }; |
| 299 | |
| 300 | public: |
| 301 | SwingSchedulerDAG(MachinePipeliner &P, MachineLoop &L, LiveIntervals &lis, |
| 302 | const RegisterClassInfo &rci) |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 303 | : ScheduleDAGInstrs(*P.MF, P.MLI, false), Pass(P), Loop(L), LIS(lis), |
| 304 | RegClassInfo(rci), Topo(SUnits, &ExitSU) { |
Krzysztof Parzyszek | 8839124 | 2016-12-22 19:21:20 +0000 | [diff] [blame] | 305 | P.MF->getSubtarget().getSMSMutations(Mutations); |
| 306 | } |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 307 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 308 | void schedule() override; |
| 309 | void finishBlock() override; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 310 | |
| 311 | /// Return true if the loop kernel has been scheduled. |
| 312 | bool hasNewSchedule() { return Scheduled; } |
| 313 | |
| 314 | /// Return the earliest time an instruction may be scheduled. |
| 315 | int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; } |
| 316 | |
| 317 | /// Return the latest time an instruction my be scheduled. |
| 318 | int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; } |
| 319 | |
Hiroshi Inoue | 8f976ba | 2018-01-17 12:29:38 +0000 | [diff] [blame] | 320 | /// The mobility function, which the number of slots in which |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 321 | /// an instruction may be scheduled. |
| 322 | int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); } |
| 323 | |
| 324 | /// The depth, in the dependence graph, for a node. |
| 325 | int getDepth(SUnit *Node) { return Node->getDepth(); } |
| 326 | |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 327 | /// The maximum unweighted length of a path from an arbitrary node to the |
| 328 | /// given node in which each edge has latency 0 |
| 329 | int getZeroLatencyDepth(SUnit *Node) { |
| 330 | return ScheduleInfo[Node->NodeNum].ZeroLatencyDepth; |
| 331 | } |
| 332 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 333 | /// The height, in the dependence graph, for a node. |
| 334 | int getHeight(SUnit *Node) { return Node->getHeight(); } |
| 335 | |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 336 | /// The maximum unweighted length of a path from the given node to an |
| 337 | /// arbitrary node in which each edge has latency 0 |
| 338 | int getZeroLatencyHeight(SUnit *Node) { |
| 339 | return ScheduleInfo[Node->NodeNum].ZeroLatencyHeight; |
| 340 | } |
| 341 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 342 | /// Return true if the dependence is a back-edge in the data dependence graph. |
| 343 | /// Since the DAG doesn't contain cycles, we represent a cycle in the graph |
| 344 | /// using an anti dependence from a Phi to an instruction. |
| 345 | bool isBackedge(SUnit *Source, const SDep &Dep) { |
| 346 | if (Dep.getKind() != SDep::Anti) |
| 347 | return false; |
| 348 | return Source->getInstr()->isPHI() || Dep.getSUnit()->getInstr()->isPHI(); |
| 349 | } |
| 350 | |
| 351 | /// Return true if the dependence is an order dependence between non-Phis. |
| 352 | static bool isOrder(SUnit *Source, const SDep &Dep) { |
| 353 | if (Dep.getKind() != SDep::Order) |
| 354 | return false; |
| 355 | return (!Source->getInstr()->isPHI() && |
| 356 | !Dep.getSUnit()->getInstr()->isPHI()); |
| 357 | } |
| 358 | |
| 359 | bool isLoopCarriedOrder(SUnit *Source, const SDep &Dep, bool isSucc = true); |
| 360 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 361 | /// The distance function, which indicates that operation V of iteration I |
| 362 | /// depends on operations U of iteration I-distance. |
| 363 | unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep) { |
| 364 | // Instructions that feed a Phi have a distance of 1. Computing larger |
| 365 | // values for arrays requires data dependence information. |
| 366 | if (V->getInstr()->isPHI() && Dep.getKind() == SDep::Anti) |
| 367 | return 1; |
| 368 | return 0; |
| 369 | } |
| 370 | |
| 371 | /// Set the Minimum Initiation Interval for this schedule attempt. |
| 372 | void setMII(unsigned mii) { MII = mii; } |
| 373 | |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 374 | void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule); |
| 375 | |
| 376 | void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 377 | |
| 378 | /// Return the new base register that was stored away for the changed |
| 379 | /// instruction. |
| 380 | unsigned getInstrBaseReg(SUnit *SU) { |
| 381 | DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = |
| 382 | InstrChanges.find(SU); |
| 383 | if (It != InstrChanges.end()) |
| 384 | return It->second.first; |
| 385 | return 0; |
| 386 | } |
| 387 | |
Krzysztof Parzyszek | 8839124 | 2016-12-22 19:21:20 +0000 | [diff] [blame] | 388 | void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) { |
| 389 | Mutations.push_back(std::move(Mutation)); |
| 390 | } |
| 391 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 392 | private: |
| 393 | void addLoopCarriedDependences(AliasAnalysis *AA); |
| 394 | void updatePhiDependences(); |
| 395 | void changeDependences(); |
| 396 | unsigned calculateResMII(); |
| 397 | unsigned calculateRecMII(NodeSetType &RecNodeSets); |
| 398 | void findCircuits(NodeSetType &NodeSets); |
| 399 | void fuseRecs(NodeSetType &NodeSets); |
| 400 | void removeDuplicateNodes(NodeSetType &NodeSets); |
| 401 | void computeNodeFunctions(NodeSetType &NodeSets); |
| 402 | void registerPressureFilter(NodeSetType &NodeSets); |
| 403 | void colocateNodeSets(NodeSetType &NodeSets); |
| 404 | void checkNodeSets(NodeSetType &NodeSets); |
| 405 | void groupRemainingNodes(NodeSetType &NodeSets); |
| 406 | void addConnectedNodes(SUnit *SU, NodeSet &NewSet, |
| 407 | SetVector<SUnit *> &NodesAdded); |
| 408 | void computeNodeOrder(NodeSetType &NodeSets); |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 409 | void checkValidNodeOrder(const NodeSetType &Circuits) const; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 410 | bool schedulePipeline(SMSchedule &Schedule); |
| 411 | void generatePipelinedLoop(SMSchedule &Schedule); |
| 412 | void generateProlog(SMSchedule &Schedule, unsigned LastStage, |
| 413 | MachineBasicBlock *KernelBB, ValueMapTy *VRMap, |
| 414 | MBBVectorTy &PrologBBs); |
| 415 | void generateEpilog(SMSchedule &Schedule, unsigned LastStage, |
| 416 | MachineBasicBlock *KernelBB, ValueMapTy *VRMap, |
| 417 | MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs); |
| 418 | void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1, |
| 419 | MachineBasicBlock *BB2, MachineBasicBlock *KernelBB, |
| 420 | SMSchedule &Schedule, ValueMapTy *VRMap, |
| 421 | InstrMapTy &InstrMap, unsigned LastStageNum, |
| 422 | unsigned CurStageNum, bool IsLast); |
| 423 | void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1, |
| 424 | MachineBasicBlock *BB2, MachineBasicBlock *KernelBB, |
| 425 | SMSchedule &Schedule, ValueMapTy *VRMap, |
| 426 | InstrMapTy &InstrMap, unsigned LastStageNum, |
| 427 | unsigned CurStageNum, bool IsLast); |
| 428 | void removeDeadInstructions(MachineBasicBlock *KernelBB, |
| 429 | MBBVectorTy &EpilogBBs); |
| 430 | void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs, |
| 431 | SMSchedule &Schedule); |
| 432 | void addBranches(MBBVectorTy &PrologBBs, MachineBasicBlock *KernelBB, |
| 433 | MBBVectorTy &EpilogBBs, SMSchedule &Schedule, |
| 434 | ValueMapTy *VRMap); |
| 435 | bool computeDelta(MachineInstr &MI, unsigned &Delta); |
| 436 | void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI, |
| 437 | unsigned Num); |
| 438 | MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum, |
| 439 | unsigned InstStageNum); |
| 440 | MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum, |
| 441 | unsigned InstStageNum, |
| 442 | SMSchedule &Schedule); |
| 443 | void updateInstruction(MachineInstr *NewMI, bool LastDef, |
| 444 | unsigned CurStageNum, unsigned InstStageNum, |
| 445 | SMSchedule &Schedule, ValueMapTy *VRMap); |
| 446 | MachineInstr *findDefInLoop(unsigned Reg); |
| 447 | unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal, |
| 448 | unsigned LoopStage, ValueMapTy *VRMap, |
| 449 | MachineBasicBlock *BB); |
| 450 | void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum, |
| 451 | SMSchedule &Schedule, ValueMapTy *VRMap, |
| 452 | InstrMapTy &InstrMap); |
| 453 | void rewriteScheduledInstr(MachineBasicBlock *BB, SMSchedule &Schedule, |
| 454 | InstrMapTy &InstrMap, unsigned CurStageNum, |
| 455 | unsigned PhiNum, MachineInstr *Phi, |
| 456 | unsigned OldReg, unsigned NewReg, |
| 457 | unsigned PrevReg = 0); |
| 458 | bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos, |
| 459 | unsigned &OffsetPos, unsigned &NewBase, |
| 460 | int64_t &NewOffset); |
Krzysztof Parzyszek | 8839124 | 2016-12-22 19:21:20 +0000 | [diff] [blame] | 461 | void postprocessDAG(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 462 | }; |
| 463 | |
| 464 | /// A NodeSet contains a set of SUnit DAG nodes with additional information |
| 465 | /// that assigns a priority to the set. |
| 466 | class NodeSet { |
| 467 | SetVector<SUnit *> Nodes; |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 468 | bool HasRecurrence = false; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 469 | unsigned RecMII = 0; |
| 470 | int MaxMOV = 0; |
| 471 | int MaxDepth = 0; |
| 472 | unsigned Colocate = 0; |
| 473 | SUnit *ExceedPressure = nullptr; |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 474 | unsigned Latency = 0; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 475 | |
| 476 | public: |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 477 | using iterator = SetVector<SUnit *>::const_iterator; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 478 | |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 479 | NodeSet() = default; |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 480 | NodeSet(iterator S, iterator E) : Nodes(S, E), HasRecurrence(true) { |
| 481 | Latency = 0; |
| 482 | for (unsigned i = 0, e = Nodes.size(); i < e; ++i) |
| 483 | for (const SDep &Succ : Nodes[i]->Succs) |
| 484 | if (Nodes.count(Succ.getSUnit())) |
| 485 | Latency += Succ.getLatency(); |
| 486 | } |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 487 | |
| 488 | bool insert(SUnit *SU) { return Nodes.insert(SU); } |
| 489 | |
| 490 | void insert(iterator S, iterator E) { Nodes.insert(S, E); } |
| 491 | |
| 492 | template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) { |
| 493 | return Nodes.remove_if(P); |
| 494 | } |
| 495 | |
| 496 | unsigned count(SUnit *SU) const { return Nodes.count(SU); } |
| 497 | |
| 498 | bool hasRecurrence() { return HasRecurrence; }; |
| 499 | |
| 500 | unsigned size() const { return Nodes.size(); } |
| 501 | |
| 502 | bool empty() const { return Nodes.empty(); } |
| 503 | |
| 504 | SUnit *getNode(unsigned i) const { return Nodes[i]; }; |
| 505 | |
| 506 | void setRecMII(unsigned mii) { RecMII = mii; }; |
| 507 | |
| 508 | void setColocate(unsigned c) { Colocate = c; }; |
| 509 | |
| 510 | void setExceedPressure(SUnit *SU) { ExceedPressure = SU; } |
| 511 | |
| 512 | bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; } |
| 513 | |
| 514 | int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; } |
| 515 | |
| 516 | int getRecMII() { return RecMII; } |
| 517 | |
| 518 | /// Summarize node functions for the entire node set. |
| 519 | void computeNodeSetInfo(SwingSchedulerDAG *SSD) { |
| 520 | for (SUnit *SU : *this) { |
| 521 | MaxMOV = std::max(MaxMOV, SSD->getMOV(SU)); |
| 522 | MaxDepth = std::max(MaxDepth, SSD->getDepth(SU)); |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | void clear() { |
| 527 | Nodes.clear(); |
| 528 | RecMII = 0; |
| 529 | HasRecurrence = false; |
| 530 | MaxMOV = 0; |
| 531 | MaxDepth = 0; |
| 532 | Colocate = 0; |
| 533 | ExceedPressure = nullptr; |
| 534 | } |
| 535 | |
| 536 | operator SetVector<SUnit *> &() { return Nodes; } |
| 537 | |
| 538 | /// Sort the node sets by importance. First, rank them by recurrence MII, |
| 539 | /// then by mobility (least mobile done first), and finally by depth. |
| 540 | /// Each node set may contain a colocate value which is used as the first |
| 541 | /// tie breaker, if it's set. |
| 542 | bool operator>(const NodeSet &RHS) const { |
| 543 | if (RecMII == RHS.RecMII) { |
| 544 | if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate) |
| 545 | return Colocate < RHS.Colocate; |
| 546 | if (MaxMOV == RHS.MaxMOV) |
| 547 | return MaxDepth > RHS.MaxDepth; |
| 548 | return MaxMOV < RHS.MaxMOV; |
| 549 | } |
| 550 | return RecMII > RHS.RecMII; |
| 551 | } |
| 552 | |
| 553 | bool operator==(const NodeSet &RHS) const { |
| 554 | return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV && |
| 555 | MaxDepth == RHS.MaxDepth; |
| 556 | } |
| 557 | |
| 558 | bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); } |
| 559 | |
| 560 | iterator begin() { return Nodes.begin(); } |
| 561 | iterator end() { return Nodes.end(); } |
| 562 | |
| 563 | void print(raw_ostream &os) const { |
| 564 | os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV |
| 565 | << " depth " << MaxDepth << " col " << Colocate << "\n"; |
| 566 | for (const auto &I : Nodes) |
| 567 | os << " SU(" << I->NodeNum << ") " << *(I->getInstr()); |
| 568 | os << "\n"; |
| 569 | } |
| 570 | |
Aaron Ballman | 615eb47 | 2017-10-15 14:32:27 +0000 | [diff] [blame] | 571 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Matthias Braun | 8c209aa | 2017-01-28 02:02:38 +0000 | [diff] [blame] | 572 | LLVM_DUMP_METHOD void dump() const { print(dbgs()); } |
| 573 | #endif |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 574 | }; |
| 575 | |
| 576 | /// This class repesents the scheduled code. The main data structure is a |
| 577 | /// map from scheduled cycle to instructions. During scheduling, the |
| 578 | /// data structure explicitly represents all stages/iterations. When |
| 579 | /// the algorithm finshes, the schedule is collapsed into a single stage, |
| 580 | /// which represents instructions from different loop iterations. |
| 581 | /// |
| 582 | /// The SMS algorithm allows negative values for cycles, so the first cycle |
| 583 | /// in the schedule is the smallest cycle value. |
| 584 | class SMSchedule { |
| 585 | private: |
| 586 | /// Map from execution cycle to instructions. |
| 587 | DenseMap<int, std::deque<SUnit *>> ScheduledInstrs; |
| 588 | |
| 589 | /// Map from instruction to execution cycle. |
| 590 | std::map<SUnit *, int> InstrToCycle; |
| 591 | |
| 592 | /// Map for each register and the max difference between its uses and def. |
| 593 | /// The first element in the pair is the max difference in stages. The |
| 594 | /// second is true if the register defines a Phi value and loop value is |
| 595 | /// scheduled before the Phi. |
| 596 | std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff; |
| 597 | |
| 598 | /// Keep track of the first cycle value in the schedule. It starts |
| 599 | /// as zero, but the algorithm allows negative values. |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 600 | int FirstCycle = 0; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 601 | |
| 602 | /// Keep track of the last cycle value in the schedule. |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 603 | int LastCycle = 0; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 604 | |
| 605 | /// The initiation interval (II) for the schedule. |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 606 | int InitiationInterval = 0; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 607 | |
| 608 | /// Target machine information. |
| 609 | const TargetSubtargetInfo &ST; |
| 610 | |
| 611 | /// Virtual register information. |
| 612 | MachineRegisterInfo &MRI; |
| 613 | |
Benjamin Kramer | 3f6260c | 2017-02-16 20:26:51 +0000 | [diff] [blame] | 614 | std::unique_ptr<DFAPacketizer> Resources; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 615 | |
| 616 | public: |
| 617 | SMSchedule(MachineFunction *mf) |
| 618 | : ST(mf->getSubtarget()), MRI(mf->getRegInfo()), |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 619 | Resources(ST.getInstrInfo()->CreateTargetScheduleState(ST)) {} |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 620 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 621 | void reset() { |
| 622 | ScheduledInstrs.clear(); |
| 623 | InstrToCycle.clear(); |
| 624 | RegToStageDiff.clear(); |
| 625 | FirstCycle = 0; |
| 626 | LastCycle = 0; |
| 627 | InitiationInterval = 0; |
| 628 | } |
| 629 | |
| 630 | /// Set the initiation interval for this schedule. |
| 631 | void setInitiationInterval(int ii) { InitiationInterval = ii; } |
| 632 | |
| 633 | /// Return the first cycle in the completed schedule. This |
| 634 | /// can be a negative value. |
| 635 | int getFirstCycle() const { return FirstCycle; } |
| 636 | |
| 637 | /// Return the last cycle in the finalized schedule. |
| 638 | int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; } |
| 639 | |
| 640 | /// Return the cycle of the earliest scheduled instruction in the dependence |
| 641 | /// chain. |
| 642 | int earliestCycleInChain(const SDep &Dep); |
| 643 | |
| 644 | /// Return the cycle of the latest scheduled instruction in the dependence |
| 645 | /// chain. |
| 646 | int latestCycleInChain(const SDep &Dep); |
| 647 | |
| 648 | void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart, |
| 649 | int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG); |
| 650 | bool insert(SUnit *SU, int StartCycle, int EndCycle, int II); |
| 651 | |
| 652 | /// Iterators for the cycle to instruction map. |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 653 | using sched_iterator = DenseMap<int, std::deque<SUnit *>>::iterator; |
| 654 | using const_sched_iterator = |
| 655 | DenseMap<int, std::deque<SUnit *>>::const_iterator; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 656 | |
| 657 | /// Return true if the instruction is scheduled at the specified stage. |
| 658 | bool isScheduledAtStage(SUnit *SU, unsigned StageNum) { |
| 659 | return (stageScheduled(SU) == (int)StageNum); |
| 660 | } |
| 661 | |
| 662 | /// Return the stage for a scheduled instruction. Return -1 if |
| 663 | /// the instruction has not been scheduled. |
| 664 | int stageScheduled(SUnit *SU) const { |
| 665 | std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU); |
| 666 | if (it == InstrToCycle.end()) |
| 667 | return -1; |
| 668 | return (it->second - FirstCycle) / InitiationInterval; |
| 669 | } |
| 670 | |
| 671 | /// Return the cycle for a scheduled instruction. This function normalizes |
| 672 | /// the first cycle to be 0. |
| 673 | unsigned cycleScheduled(SUnit *SU) const { |
| 674 | std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU); |
| 675 | assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled."); |
| 676 | return (it->second - FirstCycle) % InitiationInterval; |
| 677 | } |
| 678 | |
| 679 | /// Return the maximum stage count needed for this schedule. |
| 680 | unsigned getMaxStageCount() { |
| 681 | return (LastCycle - FirstCycle) / InitiationInterval; |
| 682 | } |
| 683 | |
| 684 | /// Return the max. number of stages/iterations that can occur between a |
| 685 | /// register definition and its uses. |
| 686 | unsigned getStagesForReg(int Reg, unsigned CurStage) { |
| 687 | std::pair<unsigned, bool> Stages = RegToStageDiff[Reg]; |
| 688 | if (CurStage > getMaxStageCount() && Stages.first == 0 && Stages.second) |
| 689 | return 1; |
| 690 | return Stages.first; |
| 691 | } |
| 692 | |
| 693 | /// The number of stages for a Phi is a little different than other |
| 694 | /// instructions. The minimum value computed in RegToStageDiff is 1 |
| 695 | /// because we assume the Phi is needed for at least 1 iteration. |
| 696 | /// This is not the case if the loop value is scheduled prior to the |
| 697 | /// Phi in the same stage. This function returns the number of stages |
| 698 | /// or iterations needed between the Phi definition and any uses. |
| 699 | unsigned getStagesForPhi(int Reg) { |
| 700 | std::pair<unsigned, bool> Stages = RegToStageDiff[Reg]; |
| 701 | if (Stages.second) |
| 702 | return Stages.first; |
| 703 | return Stages.first - 1; |
| 704 | } |
| 705 | |
| 706 | /// Return the instructions that are scheduled at the specified cycle. |
| 707 | std::deque<SUnit *> &getInstructions(int cycle) { |
| 708 | return ScheduledInstrs[cycle]; |
| 709 | } |
| 710 | |
| 711 | bool isValidSchedule(SwingSchedulerDAG *SSD); |
| 712 | void finalizeSchedule(SwingSchedulerDAG *SSD); |
| 713 | bool orderDependence(SwingSchedulerDAG *SSD, SUnit *SU, |
| 714 | std::deque<SUnit *> &Insts); |
| 715 | bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi); |
| 716 | bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Inst, |
| 717 | MachineOperand &MO); |
| 718 | void print(raw_ostream &os) const; |
| 719 | void dump() const; |
| 720 | }; |
| 721 | |
| 722 | } // end anonymous namespace |
| 723 | |
| 724 | unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5; |
| 725 | char MachinePipeliner::ID = 0; |
| 726 | #ifndef NDEBUG |
| 727 | int MachinePipeliner::NumTries = 0; |
| 728 | #endif |
| 729 | char &llvm::MachinePipelinerID = MachinePipeliner::ID; |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 730 | |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 731 | INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE, |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 732 | "Modulo Software Pipelining", false, false) |
| 733 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
| 734 | INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) |
| 735 | INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) |
| 736 | INITIALIZE_PASS_DEPENDENCY(LiveIntervals) |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 737 | INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE, |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 738 | "Modulo Software Pipelining", false, false) |
| 739 | |
| 740 | /// The "main" function for implementing Swing Modulo Scheduling. |
| 741 | bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) { |
Matthias Braun | f1caa28 | 2017-12-15 22:22:58 +0000 | [diff] [blame] | 742 | if (skipFunction(mf.getFunction())) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 743 | return false; |
| 744 | |
| 745 | if (!EnableSWP) |
| 746 | return false; |
| 747 | |
Matthias Braun | f1caa28 | 2017-12-15 22:22:58 +0000 | [diff] [blame] | 748 | if (mf.getFunction().getAttributes().hasAttribute( |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame] | 749 | AttributeList::FunctionIndex, Attribute::OptimizeForSize) && |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 750 | !EnableSWPOptSize.getPosition()) |
| 751 | return false; |
| 752 | |
| 753 | MF = &mf; |
| 754 | MLI = &getAnalysis<MachineLoopInfo>(); |
| 755 | MDT = &getAnalysis<MachineDominatorTree>(); |
| 756 | TII = MF->getSubtarget().getInstrInfo(); |
| 757 | RegClassInfo.runOnMachineFunction(*MF); |
| 758 | |
| 759 | for (auto &L : *MLI) |
| 760 | scheduleLoop(*L); |
| 761 | |
| 762 | return false; |
| 763 | } |
| 764 | |
| 765 | /// Attempt to perform the SMS algorithm on the specified loop. This function is |
| 766 | /// the main entry point for the algorithm. The function identifies candidate |
| 767 | /// loops, calculates the minimum initiation interval, and attempts to schedule |
| 768 | /// the loop. |
| 769 | bool MachinePipeliner::scheduleLoop(MachineLoop &L) { |
| 770 | bool Changed = false; |
| 771 | for (auto &InnerLoop : L) |
| 772 | Changed |= scheduleLoop(*InnerLoop); |
| 773 | |
| 774 | #ifndef NDEBUG |
| 775 | // Stop trying after reaching the limit (if any). |
| 776 | int Limit = SwpLoopLimit; |
| 777 | if (Limit >= 0) { |
| 778 | if (NumTries >= SwpLoopLimit) |
| 779 | return Changed; |
| 780 | NumTries++; |
| 781 | } |
| 782 | #endif |
| 783 | |
| 784 | if (!canPipelineLoop(L)) |
| 785 | return Changed; |
| 786 | |
| 787 | ++NumTrytoPipeline; |
| 788 | |
| 789 | Changed = swingModuloScheduler(L); |
| 790 | |
| 791 | return Changed; |
| 792 | } |
| 793 | |
| 794 | /// Return true if the loop can be software pipelined. The algorithm is |
| 795 | /// restricted to loops with a single basic block. Make sure that the |
| 796 | /// branch in the loop can be analyzed. |
| 797 | bool MachinePipeliner::canPipelineLoop(MachineLoop &L) { |
| 798 | if (L.getNumBlocks() != 1) |
| 799 | return false; |
| 800 | |
| 801 | // Check if the branch can't be understood because we can't do pipelining |
| 802 | // if that's the case. |
| 803 | LI.TBB = nullptr; |
| 804 | LI.FBB = nullptr; |
| 805 | LI.BrCond.clear(); |
| 806 | if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) |
| 807 | return false; |
| 808 | |
| 809 | LI.LoopInductionVar = nullptr; |
| 810 | LI.LoopCompare = nullptr; |
| 811 | if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) |
| 812 | return false; |
| 813 | |
| 814 | if (!L.getLoopPreheader()) |
| 815 | return false; |
| 816 | |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 817 | // Remove any subregisters from inputs to phi nodes. |
| 818 | preprocessPhiNodes(*L.getHeader()); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 819 | return true; |
| 820 | } |
| 821 | |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 822 | void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) { |
| 823 | MachineRegisterInfo &MRI = MF->getRegInfo(); |
| 824 | SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes(); |
| 825 | |
| 826 | for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) { |
| 827 | MachineOperand &DefOp = PI.getOperand(0); |
| 828 | assert(DefOp.getSubReg() == 0); |
| 829 | auto *RC = MRI.getRegClass(DefOp.getReg()); |
| 830 | |
| 831 | for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) { |
| 832 | MachineOperand &RegOp = PI.getOperand(i); |
| 833 | if (RegOp.getSubReg() == 0) |
| 834 | continue; |
| 835 | |
| 836 | // If the operand uses a subregister, replace it with a new register |
| 837 | // without subregisters, and generate a copy to the new register. |
| 838 | unsigned NewReg = MRI.createVirtualRegister(RC); |
| 839 | MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB(); |
| 840 | MachineBasicBlock::iterator At = PredB.getFirstTerminator(); |
| 841 | const DebugLoc &DL = PredB.findDebugLoc(At); |
| 842 | auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg) |
| 843 | .addReg(RegOp.getReg(), getRegState(RegOp), |
| 844 | RegOp.getSubReg()); |
| 845 | Slots.insertMachineInstrInMaps(*Copy); |
| 846 | RegOp.setReg(NewReg); |
| 847 | RegOp.setSubReg(0); |
| 848 | } |
| 849 | } |
| 850 | } |
| 851 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 852 | /// The SMS algorithm consists of the following main steps: |
| 853 | /// 1. Computation and analysis of the dependence graph. |
| 854 | /// 2. Ordering of the nodes (instructions). |
| 855 | /// 3. Attempt to Schedule the loop. |
| 856 | bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) { |
| 857 | assert(L.getBlocks().size() == 1 && "SMS works on single blocks only."); |
| 858 | |
| 859 | SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo); |
| 860 | |
| 861 | MachineBasicBlock *MBB = L.getHeader(); |
| 862 | // The kernel should not include any terminator instructions. These |
| 863 | // will be added back later. |
| 864 | SMS.startBlock(MBB); |
| 865 | |
| 866 | // Compute the number of 'real' instructions in the basic block by |
| 867 | // ignoring terminators. |
| 868 | unsigned size = MBB->size(); |
| 869 | for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(), |
| 870 | E = MBB->instr_end(); |
| 871 | I != E; ++I, --size) |
| 872 | ; |
| 873 | |
| 874 | SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size); |
| 875 | SMS.schedule(); |
| 876 | SMS.exitRegion(); |
| 877 | |
| 878 | SMS.finishBlock(); |
| 879 | return SMS.hasNewSchedule(); |
| 880 | } |
| 881 | |
| 882 | /// We override the schedule function in ScheduleDAGInstrs to implement the |
| 883 | /// scheduling part of the Swing Modulo Scheduling algorithm. |
| 884 | void SwingSchedulerDAG::schedule() { |
| 885 | AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 886 | buildSchedGraph(AA); |
| 887 | addLoopCarriedDependences(AA); |
| 888 | updatePhiDependences(); |
| 889 | Topo.InitDAGTopologicalSorting(); |
Krzysztof Parzyszek | 8839124 | 2016-12-22 19:21:20 +0000 | [diff] [blame] | 890 | postprocessDAG(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 891 | changeDependences(); |
| 892 | DEBUG({ |
| 893 | for (unsigned su = 0, e = SUnits.size(); su != e; ++su) |
| 894 | SUnits[su].dumpAll(this); |
| 895 | }); |
| 896 | |
| 897 | NodeSetType NodeSets; |
| 898 | findCircuits(NodeSets); |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 899 | NodeSetType Circuits = NodeSets; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 900 | |
| 901 | // Calculate the MII. |
| 902 | unsigned ResMII = calculateResMII(); |
| 903 | unsigned RecMII = calculateRecMII(NodeSets); |
| 904 | |
| 905 | fuseRecs(NodeSets); |
| 906 | |
| 907 | // This flag is used for testing and can cause correctness problems. |
| 908 | if (SwpIgnoreRecMII) |
| 909 | RecMII = 0; |
| 910 | |
| 911 | MII = std::max(ResMII, RecMII); |
| 912 | DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII << ", res=" << ResMII |
| 913 | << ")\n"); |
| 914 | |
| 915 | // Can't schedule a loop without a valid MII. |
| 916 | if (MII == 0) |
| 917 | return; |
| 918 | |
| 919 | // Don't pipeline large loops. |
| 920 | if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) |
| 921 | return; |
| 922 | |
| 923 | computeNodeFunctions(NodeSets); |
| 924 | |
| 925 | registerPressureFilter(NodeSets); |
| 926 | |
| 927 | colocateNodeSets(NodeSets); |
| 928 | |
| 929 | checkNodeSets(NodeSets); |
| 930 | |
| 931 | DEBUG({ |
| 932 | for (auto &I : NodeSets) { |
| 933 | dbgs() << " Rec NodeSet "; |
| 934 | I.dump(); |
| 935 | } |
| 936 | }); |
| 937 | |
| 938 | std::sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>()); |
| 939 | |
| 940 | groupRemainingNodes(NodeSets); |
| 941 | |
| 942 | removeDuplicateNodes(NodeSets); |
| 943 | |
| 944 | DEBUG({ |
| 945 | for (auto &I : NodeSets) { |
| 946 | dbgs() << " NodeSet "; |
| 947 | I.dump(); |
| 948 | } |
| 949 | }); |
| 950 | |
| 951 | computeNodeOrder(NodeSets); |
| 952 | |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 953 | // check for node order issues |
| 954 | checkValidNodeOrder(Circuits); |
| 955 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 956 | SMSchedule Schedule(Pass.MF); |
| 957 | Scheduled = schedulePipeline(Schedule); |
| 958 | |
| 959 | if (!Scheduled) |
| 960 | return; |
| 961 | |
| 962 | unsigned numStages = Schedule.getMaxStageCount(); |
| 963 | // No need to generate pipeline if there are no overlapped iterations. |
| 964 | if (numStages == 0) |
| 965 | return; |
| 966 | |
| 967 | // Check that the maximum stage count is less than user-defined limit. |
| 968 | if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) |
| 969 | return; |
| 970 | |
| 971 | generatePipelinedLoop(Schedule); |
| 972 | ++NumPipelined; |
| 973 | } |
| 974 | |
| 975 | /// Clean up after the software pipeliner runs. |
| 976 | void SwingSchedulerDAG::finishBlock() { |
| 977 | for (MachineInstr *I : NewMIs) |
| 978 | MF.DeleteMachineInstr(I); |
| 979 | NewMIs.clear(); |
| 980 | |
| 981 | // Call the superclass. |
| 982 | ScheduleDAGInstrs::finishBlock(); |
| 983 | } |
| 984 | |
| 985 | /// Return the register values for the operands of a Phi instruction. |
| 986 | /// This function assume the instruction is a Phi. |
| 987 | static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop, |
| 988 | unsigned &InitVal, unsigned &LoopVal) { |
| 989 | assert(Phi.isPHI() && "Expecting a Phi."); |
| 990 | |
| 991 | InitVal = 0; |
| 992 | LoopVal = 0; |
| 993 | for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) |
| 994 | if (Phi.getOperand(i + 1).getMBB() != Loop) |
| 995 | InitVal = Phi.getOperand(i).getReg(); |
Simon Pilgrim | fbfb19b | 2017-03-16 19:52:00 +0000 | [diff] [blame] | 996 | else |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 997 | LoopVal = Phi.getOperand(i).getReg(); |
| 998 | |
| 999 | assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure."); |
| 1000 | } |
| 1001 | |
| 1002 | /// Return the Phi register value that comes from the incoming block. |
| 1003 | static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) { |
| 1004 | for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) |
| 1005 | if (Phi.getOperand(i + 1).getMBB() != LoopBB) |
| 1006 | return Phi.getOperand(i).getReg(); |
| 1007 | return 0; |
| 1008 | } |
| 1009 | |
Hiroshi Inoue | 8f976ba | 2018-01-17 12:29:38 +0000 | [diff] [blame] | 1010 | /// Return the Phi register value that comes the loop block. |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1011 | static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) { |
| 1012 | for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) |
| 1013 | if (Phi.getOperand(i + 1).getMBB() == LoopBB) |
| 1014 | return Phi.getOperand(i).getReg(); |
| 1015 | return 0; |
| 1016 | } |
| 1017 | |
| 1018 | /// Return true if SUb can be reached from SUa following the chain edges. |
| 1019 | static bool isSuccOrder(SUnit *SUa, SUnit *SUb) { |
| 1020 | SmallPtrSet<SUnit *, 8> Visited; |
| 1021 | SmallVector<SUnit *, 8> Worklist; |
| 1022 | Worklist.push_back(SUa); |
| 1023 | while (!Worklist.empty()) { |
| 1024 | const SUnit *SU = Worklist.pop_back_val(); |
| 1025 | for (auto &SI : SU->Succs) { |
| 1026 | SUnit *SuccSU = SI.getSUnit(); |
| 1027 | if (SI.getKind() == SDep::Order) { |
| 1028 | if (Visited.count(SuccSU)) |
| 1029 | continue; |
| 1030 | if (SuccSU == SUb) |
| 1031 | return true; |
| 1032 | Worklist.push_back(SuccSU); |
| 1033 | Visited.insert(SuccSU); |
| 1034 | } |
| 1035 | } |
| 1036 | } |
| 1037 | return false; |
| 1038 | } |
| 1039 | |
| 1040 | /// Return true if the instruction causes a chain between memory |
| 1041 | /// references before and after it. |
| 1042 | static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) { |
| 1043 | return MI.isCall() || MI.hasUnmodeledSideEffects() || |
| 1044 | (MI.hasOrderedMemoryRef() && |
Justin Lebar | d98cf00 | 2016-09-10 01:03:20 +0000 | [diff] [blame] | 1045 | (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA))); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1046 | } |
| 1047 | |
| 1048 | /// Return the underlying objects for the memory references of an instruction. |
| 1049 | /// This function calls the code in ValueTracking, but first checks that the |
| 1050 | /// instruction has a memory operand. |
| 1051 | static void getUnderlyingObjects(MachineInstr *MI, |
| 1052 | SmallVectorImpl<Value *> &Objs, |
| 1053 | const DataLayout &DL) { |
| 1054 | if (!MI->hasOneMemOperand()) |
| 1055 | return; |
| 1056 | MachineMemOperand *MM = *MI->memoperands_begin(); |
| 1057 | if (!MM->getValue()) |
| 1058 | return; |
| 1059 | GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL); |
| 1060 | } |
| 1061 | |
| 1062 | /// Add a chain edge between a load and store if the store can be an |
| 1063 | /// alias of the load on a subsequent iteration, i.e., a loop carried |
| 1064 | /// dependence. This code is very similar to the code in ScheduleDAGInstrs |
| 1065 | /// but that code doesn't create loop carried dependences. |
| 1066 | void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) { |
| 1067 | MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads; |
| 1068 | for (auto &SU : SUnits) { |
| 1069 | MachineInstr &MI = *SU.getInstr(); |
| 1070 | if (isDependenceBarrier(MI, AA)) |
| 1071 | PendingLoads.clear(); |
| 1072 | else if (MI.mayLoad()) { |
| 1073 | SmallVector<Value *, 4> Objs; |
| 1074 | getUnderlyingObjects(&MI, Objs, MF.getDataLayout()); |
| 1075 | for (auto V : Objs) { |
| 1076 | SmallVector<SUnit *, 4> &SUs = PendingLoads[V]; |
| 1077 | SUs.push_back(&SU); |
| 1078 | } |
| 1079 | } else if (MI.mayStore()) { |
| 1080 | SmallVector<Value *, 4> Objs; |
| 1081 | getUnderlyingObjects(&MI, Objs, MF.getDataLayout()); |
| 1082 | for (auto V : Objs) { |
| 1083 | MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I = |
| 1084 | PendingLoads.find(V); |
| 1085 | if (I == PendingLoads.end()) |
| 1086 | continue; |
| 1087 | for (auto Load : I->second) { |
| 1088 | if (isSuccOrder(Load, &SU)) |
| 1089 | continue; |
| 1090 | MachineInstr &LdMI = *Load->getInstr(); |
| 1091 | // First, perform the cheaper check that compares the base register. |
| 1092 | // If they are the same and the load offset is less than the store |
| 1093 | // offset, then mark the dependence as loop carried potentially. |
| 1094 | unsigned BaseReg1, BaseReg2; |
| 1095 | int64_t Offset1, Offset2; |
| 1096 | if (!TII->getMemOpBaseRegImmOfs(LdMI, BaseReg1, Offset1, TRI) || |
| 1097 | !TII->getMemOpBaseRegImmOfs(MI, BaseReg2, Offset2, TRI)) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1098 | SDep Dep(Load, SDep::Barrier); |
| 1099 | Dep.setLatency(1); |
| 1100 | SU.addPred(Dep); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1101 | continue; |
| 1102 | } |
| 1103 | if (BaseReg1 == BaseReg2 && (int)Offset1 < (int)Offset2) { |
| 1104 | assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) && |
| 1105 | "What happened to the chain edge?"); |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1106 | SDep Dep(Load, SDep::Barrier); |
| 1107 | Dep.setLatency(1); |
| 1108 | SU.addPred(Dep); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1109 | continue; |
| 1110 | } |
| 1111 | // Second, the more expensive check that uses alias analysis on the |
| 1112 | // base registers. If they alias, and the load offset is less than |
| 1113 | // the store offset, the mark the dependence as loop carried. |
| 1114 | if (!AA) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1115 | SDep Dep(Load, SDep::Barrier); |
| 1116 | Dep.setLatency(1); |
| 1117 | SU.addPred(Dep); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1118 | continue; |
| 1119 | } |
| 1120 | MachineMemOperand *MMO1 = *LdMI.memoperands_begin(); |
| 1121 | MachineMemOperand *MMO2 = *MI.memoperands_begin(); |
| 1122 | if (!MMO1->getValue() || !MMO2->getValue()) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1123 | SDep Dep(Load, SDep::Barrier); |
| 1124 | Dep.setLatency(1); |
| 1125 | SU.addPred(Dep); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1126 | continue; |
| 1127 | } |
| 1128 | if (MMO1->getValue() == MMO2->getValue() && |
| 1129 | MMO1->getOffset() <= MMO2->getOffset()) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1130 | SDep Dep(Load, SDep::Barrier); |
| 1131 | Dep.setLatency(1); |
| 1132 | SU.addPred(Dep); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1133 | continue; |
| 1134 | } |
| 1135 | AliasResult AAResult = AA->alias( |
| 1136 | MemoryLocation(MMO1->getValue(), MemoryLocation::UnknownSize, |
| 1137 | MMO1->getAAInfo()), |
| 1138 | MemoryLocation(MMO2->getValue(), MemoryLocation::UnknownSize, |
| 1139 | MMO2->getAAInfo())); |
| 1140 | |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1141 | if (AAResult != NoAlias) { |
| 1142 | SDep Dep(Load, SDep::Barrier); |
| 1143 | Dep.setLatency(1); |
| 1144 | SU.addPred(Dep); |
| 1145 | } |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1146 | } |
| 1147 | } |
| 1148 | } |
| 1149 | } |
| 1150 | } |
| 1151 | |
| 1152 | /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer |
| 1153 | /// processes dependences for PHIs. This function adds true dependences |
| 1154 | /// from a PHI to a use, and a loop carried dependence from the use to the |
| 1155 | /// PHI. The loop carried dependence is represented as an anti dependence |
| 1156 | /// edge. This function also removes chain dependences between unrelated |
| 1157 | /// PHIs. |
| 1158 | void SwingSchedulerDAG::updatePhiDependences() { |
| 1159 | SmallVector<SDep, 4> RemoveDeps; |
| 1160 | const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>(); |
| 1161 | |
| 1162 | // Iterate over each DAG node. |
| 1163 | for (SUnit &I : SUnits) { |
| 1164 | RemoveDeps.clear(); |
| 1165 | // Set to true if the instruction has an operand defined by a Phi. |
| 1166 | unsigned HasPhiUse = 0; |
| 1167 | unsigned HasPhiDef = 0; |
| 1168 | MachineInstr *MI = I.getInstr(); |
| 1169 | // Iterate over each operand, and we process the definitions. |
| 1170 | for (MachineInstr::mop_iterator MOI = MI->operands_begin(), |
| 1171 | MOE = MI->operands_end(); |
| 1172 | MOI != MOE; ++MOI) { |
| 1173 | if (!MOI->isReg()) |
| 1174 | continue; |
| 1175 | unsigned Reg = MOI->getReg(); |
| 1176 | if (MOI->isDef()) { |
| 1177 | // If the register is used by a Phi, then create an anti dependence. |
| 1178 | for (MachineRegisterInfo::use_instr_iterator |
| 1179 | UI = MRI.use_instr_begin(Reg), |
| 1180 | UE = MRI.use_instr_end(); |
| 1181 | UI != UE; ++UI) { |
| 1182 | MachineInstr *UseMI = &*UI; |
| 1183 | SUnit *SU = getSUnit(UseMI); |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 1184 | if (SU != nullptr && UseMI->isPHI()) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1185 | if (!MI->isPHI()) { |
| 1186 | SDep Dep(SU, SDep::Anti, Reg); |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1187 | Dep.setLatency(1); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1188 | I.addPred(Dep); |
| 1189 | } else { |
| 1190 | HasPhiDef = Reg; |
| 1191 | // Add a chain edge to a dependent Phi that isn't an existing |
| 1192 | // predecessor. |
| 1193 | if (SU->NodeNum < I.NodeNum && !I.isPred(SU)) |
| 1194 | I.addPred(SDep(SU, SDep::Barrier)); |
| 1195 | } |
| 1196 | } |
| 1197 | } |
| 1198 | } else if (MOI->isUse()) { |
| 1199 | // If the register is defined by a Phi, then create a true dependence. |
| 1200 | MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg); |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 1201 | if (DefMI == nullptr) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1202 | continue; |
| 1203 | SUnit *SU = getSUnit(DefMI); |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 1204 | if (SU != nullptr && DefMI->isPHI()) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1205 | if (!MI->isPHI()) { |
| 1206 | SDep Dep(SU, SDep::Data, Reg); |
| 1207 | Dep.setLatency(0); |
| 1208 | ST.adjustSchedDependency(SU, &I, Dep); |
| 1209 | I.addPred(Dep); |
| 1210 | } else { |
| 1211 | HasPhiUse = Reg; |
| 1212 | // Add a chain edge to a dependent Phi that isn't an existing |
| 1213 | // predecessor. |
| 1214 | if (SU->NodeNum < I.NodeNum && !I.isPred(SU)) |
| 1215 | I.addPred(SDep(SU, SDep::Barrier)); |
| 1216 | } |
| 1217 | } |
| 1218 | } |
| 1219 | } |
| 1220 | // Remove order dependences from an unrelated Phi. |
| 1221 | if (!SwpPruneDeps) |
| 1222 | continue; |
| 1223 | for (auto &PI : I.Preds) { |
| 1224 | MachineInstr *PMI = PI.getSUnit()->getInstr(); |
| 1225 | if (PMI->isPHI() && PI.getKind() == SDep::Order) { |
| 1226 | if (I.getInstr()->isPHI()) { |
| 1227 | if (PMI->getOperand(0).getReg() == HasPhiUse) |
| 1228 | continue; |
| 1229 | if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef) |
| 1230 | continue; |
| 1231 | } |
| 1232 | RemoveDeps.push_back(PI); |
| 1233 | } |
| 1234 | } |
| 1235 | for (int i = 0, e = RemoveDeps.size(); i != e; ++i) |
| 1236 | I.removePred(RemoveDeps[i]); |
| 1237 | } |
| 1238 | } |
| 1239 | |
| 1240 | /// Iterate over each DAG node and see if we can change any dependences |
| 1241 | /// in order to reduce the recurrence MII. |
| 1242 | void SwingSchedulerDAG::changeDependences() { |
| 1243 | // See if an instruction can use a value from the previous iteration. |
| 1244 | // If so, we update the base and offset of the instruction and change |
| 1245 | // the dependences. |
| 1246 | for (SUnit &I : SUnits) { |
| 1247 | unsigned BasePos = 0, OffsetPos = 0, NewBase = 0; |
| 1248 | int64_t NewOffset = 0; |
| 1249 | if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase, |
| 1250 | NewOffset)) |
| 1251 | continue; |
| 1252 | |
| 1253 | // Get the MI and SUnit for the instruction that defines the original base. |
| 1254 | unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg(); |
| 1255 | MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase); |
| 1256 | if (!DefMI) |
| 1257 | continue; |
| 1258 | SUnit *DefSU = getSUnit(DefMI); |
| 1259 | if (!DefSU) |
| 1260 | continue; |
| 1261 | // Get the MI and SUnit for the instruction that defins the new base. |
| 1262 | MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase); |
| 1263 | if (!LastMI) |
| 1264 | continue; |
| 1265 | SUnit *LastSU = getSUnit(LastMI); |
| 1266 | if (!LastSU) |
| 1267 | continue; |
| 1268 | |
| 1269 | if (Topo.IsReachable(&I, LastSU)) |
| 1270 | continue; |
| 1271 | |
| 1272 | // Remove the dependence. The value now depends on a prior iteration. |
| 1273 | SmallVector<SDep, 4> Deps; |
| 1274 | for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E; |
| 1275 | ++P) |
| 1276 | if (P->getSUnit() == DefSU) |
| 1277 | Deps.push_back(*P); |
| 1278 | for (int i = 0, e = Deps.size(); i != e; i++) { |
| 1279 | Topo.RemovePred(&I, Deps[i].getSUnit()); |
| 1280 | I.removePred(Deps[i]); |
| 1281 | } |
| 1282 | // Remove the chain dependence between the instructions. |
| 1283 | Deps.clear(); |
| 1284 | for (auto &P : LastSU->Preds) |
| 1285 | if (P.getSUnit() == &I && P.getKind() == SDep::Order) |
| 1286 | Deps.push_back(P); |
| 1287 | for (int i = 0, e = Deps.size(); i != e; i++) { |
| 1288 | Topo.RemovePred(LastSU, Deps[i].getSUnit()); |
| 1289 | LastSU->removePred(Deps[i]); |
| 1290 | } |
| 1291 | |
| 1292 | // Add a dependence between the new instruction and the instruction |
| 1293 | // that defines the new base. |
| 1294 | SDep Dep(&I, SDep::Anti, NewBase); |
| 1295 | LastSU->addPred(Dep); |
| 1296 | |
| 1297 | // Remember the base and offset information so that we can update the |
| 1298 | // instruction during code generation. |
| 1299 | InstrChanges[&I] = std::make_pair(NewBase, NewOffset); |
| 1300 | } |
| 1301 | } |
| 1302 | |
| 1303 | namespace { |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 1304 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1305 | // FuncUnitSorter - Comparison operator used to sort instructions by |
| 1306 | // the number of functional unit choices. |
| 1307 | struct FuncUnitSorter { |
| 1308 | const InstrItineraryData *InstrItins; |
| 1309 | DenseMap<unsigned, unsigned> Resources; |
| 1310 | |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1311 | FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {} |
| 1312 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1313 | // Compute the number of functional unit alternatives needed |
| 1314 | // at each stage, and take the minimum value. We prioritize the |
| 1315 | // instructions by the least number of choices first. |
| 1316 | unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const { |
| 1317 | unsigned schedClass = Inst->getDesc().getSchedClass(); |
| 1318 | unsigned min = UINT_MAX; |
| 1319 | for (const InstrStage *IS = InstrItins->beginStage(schedClass), |
| 1320 | *IE = InstrItins->endStage(schedClass); |
| 1321 | IS != IE; ++IS) { |
| 1322 | unsigned funcUnits = IS->getUnits(); |
| 1323 | unsigned numAlternatives = countPopulation(funcUnits); |
| 1324 | if (numAlternatives < min) { |
| 1325 | min = numAlternatives; |
| 1326 | F = funcUnits; |
| 1327 | } |
| 1328 | } |
| 1329 | return min; |
| 1330 | } |
| 1331 | |
| 1332 | // Compute the critical resources needed by the instruction. This |
| 1333 | // function records the functional units needed by instructions that |
| 1334 | // must use only one functional unit. We use this as a tie breaker |
| 1335 | // for computing the resource MII. The instrutions that require |
| 1336 | // the same, highly used, functional unit have high priority. |
| 1337 | void calcCriticalResources(MachineInstr &MI) { |
| 1338 | unsigned SchedClass = MI.getDesc().getSchedClass(); |
| 1339 | for (const InstrStage *IS = InstrItins->beginStage(SchedClass), |
| 1340 | *IE = InstrItins->endStage(SchedClass); |
| 1341 | IS != IE; ++IS) { |
| 1342 | unsigned FuncUnits = IS->getUnits(); |
| 1343 | if (countPopulation(FuncUnits) == 1) |
| 1344 | Resources[FuncUnits]++; |
| 1345 | } |
| 1346 | } |
| 1347 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1348 | /// Return true if IS1 has less priority than IS2. |
| 1349 | bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const { |
| 1350 | unsigned F1 = 0, F2 = 0; |
| 1351 | unsigned MFUs1 = minFuncUnits(IS1, F1); |
| 1352 | unsigned MFUs2 = minFuncUnits(IS2, F2); |
| 1353 | if (MFUs1 == 1 && MFUs2 == 1) |
| 1354 | return Resources.lookup(F1) < Resources.lookup(F2); |
| 1355 | return MFUs1 > MFUs2; |
| 1356 | } |
| 1357 | }; |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 1358 | |
| 1359 | } // end anonymous namespace |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1360 | |
| 1361 | /// Calculate the resource constrained minimum initiation interval for the |
| 1362 | /// specified loop. We use the DFA to model the resources needed for |
| 1363 | /// each instruction, and we ignore dependences. A different DFA is created |
| 1364 | /// for each cycle that is required. When adding a new instruction, we attempt |
| 1365 | /// to add it to each existing DFA, until a legal space is found. If the |
| 1366 | /// instruction cannot be reserved in an existing DFA, we create a new one. |
| 1367 | unsigned SwingSchedulerDAG::calculateResMII() { |
| 1368 | SmallVector<DFAPacketizer *, 8> Resources; |
| 1369 | MachineBasicBlock *MBB = Loop.getHeader(); |
| 1370 | Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget())); |
| 1371 | |
| 1372 | // Sort the instructions by the number of available choices for scheduling, |
| 1373 | // least to most. Use the number of critical resources as the tie breaker. |
| 1374 | FuncUnitSorter FUS = |
| 1375 | FuncUnitSorter(MF.getSubtarget().getInstrItineraryData()); |
| 1376 | for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(), |
| 1377 | E = MBB->getFirstTerminator(); |
| 1378 | I != E; ++I) |
| 1379 | FUS.calcCriticalResources(*I); |
| 1380 | PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter> |
| 1381 | FuncUnitOrder(FUS); |
| 1382 | |
| 1383 | for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(), |
| 1384 | E = MBB->getFirstTerminator(); |
| 1385 | I != E; ++I) |
| 1386 | FuncUnitOrder.push(&*I); |
| 1387 | |
| 1388 | while (!FuncUnitOrder.empty()) { |
| 1389 | MachineInstr *MI = FuncUnitOrder.top(); |
| 1390 | FuncUnitOrder.pop(); |
| 1391 | if (TII->isZeroCost(MI->getOpcode())) |
| 1392 | continue; |
| 1393 | // Attempt to reserve the instruction in an existing DFA. At least one |
| 1394 | // DFA is needed for each cycle. |
| 1395 | unsigned NumCycles = getSUnit(MI)->Latency; |
| 1396 | unsigned ReservedCycles = 0; |
| 1397 | SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin(); |
| 1398 | SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end(); |
| 1399 | for (unsigned C = 0; C < NumCycles; ++C) |
| 1400 | while (RI != RE) { |
| 1401 | if ((*RI++)->canReserveResources(*MI)) { |
| 1402 | ++ReservedCycles; |
| 1403 | break; |
| 1404 | } |
| 1405 | } |
| 1406 | // Start reserving resources using existing DFAs. |
| 1407 | for (unsigned C = 0; C < ReservedCycles; ++C) { |
| 1408 | --RI; |
| 1409 | (*RI)->reserveResources(*MI); |
| 1410 | } |
| 1411 | // Add new DFAs, if needed, to reserve resources. |
| 1412 | for (unsigned C = ReservedCycles; C < NumCycles; ++C) { |
| 1413 | DFAPacketizer *NewResource = |
| 1414 | TII->CreateTargetScheduleState(MF.getSubtarget()); |
| 1415 | assert(NewResource->canReserveResources(*MI) && "Reserve error."); |
| 1416 | NewResource->reserveResources(*MI); |
| 1417 | Resources.push_back(NewResource); |
| 1418 | } |
| 1419 | } |
| 1420 | int Resmii = Resources.size(); |
| 1421 | // Delete the memory for each of the DFAs that were created earlier. |
| 1422 | for (DFAPacketizer *RI : Resources) { |
| 1423 | DFAPacketizer *D = RI; |
| 1424 | delete D; |
| 1425 | } |
| 1426 | Resources.clear(); |
| 1427 | return Resmii; |
| 1428 | } |
| 1429 | |
| 1430 | /// Calculate the recurrence-constrainted minimum initiation interval. |
| 1431 | /// Iterate over each circuit. Compute the delay(c) and distance(c) |
| 1432 | /// for each circuit. The II needs to satisfy the inequality |
| 1433 | /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest |
| 1434 | /// II that satistifies the inequality, and the RecMII is the maximum |
| 1435 | /// of those values. |
| 1436 | unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) { |
| 1437 | unsigned RecMII = 0; |
| 1438 | |
| 1439 | for (NodeSet &Nodes : NodeSets) { |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1440 | if (Nodes.empty()) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1441 | continue; |
| 1442 | |
| 1443 | unsigned Delay = Nodes.size() - 1; |
| 1444 | unsigned Distance = 1; |
| 1445 | |
| 1446 | // ii = ceil(delay / distance) |
| 1447 | unsigned CurMII = (Delay + Distance - 1) / Distance; |
| 1448 | Nodes.setRecMII(CurMII); |
| 1449 | if (CurMII > RecMII) |
| 1450 | RecMII = CurMII; |
| 1451 | } |
| 1452 | |
| 1453 | return RecMII; |
| 1454 | } |
| 1455 | |
| 1456 | /// Swap all the anti dependences in the DAG. That means it is no longer a DAG, |
| 1457 | /// but we do this to find the circuits, and then change them back. |
| 1458 | static void swapAntiDependences(std::vector<SUnit> &SUnits) { |
| 1459 | SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded; |
| 1460 | for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { |
| 1461 | SUnit *SU = &SUnits[i]; |
| 1462 | for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end(); |
| 1463 | IP != EP; ++IP) { |
| 1464 | if (IP->getKind() != SDep::Anti) |
| 1465 | continue; |
| 1466 | DepsAdded.push_back(std::make_pair(SU, *IP)); |
| 1467 | } |
| 1468 | } |
| 1469 | for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(), |
| 1470 | E = DepsAdded.end(); |
| 1471 | I != E; ++I) { |
| 1472 | // Remove this anti dependency and add one in the reverse direction. |
| 1473 | SUnit *SU = I->first; |
| 1474 | SDep &D = I->second; |
| 1475 | SUnit *TargetSU = D.getSUnit(); |
| 1476 | unsigned Reg = D.getReg(); |
| 1477 | unsigned Lat = D.getLatency(); |
| 1478 | SU->removePred(D); |
| 1479 | SDep Dep(SU, SDep::Anti, Reg); |
| 1480 | Dep.setLatency(Lat); |
| 1481 | TargetSU->addPred(Dep); |
| 1482 | } |
| 1483 | } |
| 1484 | |
| 1485 | /// Create the adjacency structure of the nodes in the graph. |
| 1486 | void SwingSchedulerDAG::Circuits::createAdjacencyStructure( |
| 1487 | SwingSchedulerDAG *DAG) { |
| 1488 | BitVector Added(SUnits.size()); |
| 1489 | for (int i = 0, e = SUnits.size(); i != e; ++i) { |
| 1490 | Added.reset(); |
| 1491 | // Add any successor to the adjacency matrix and exclude duplicates. |
| 1492 | for (auto &SI : SUnits[i].Succs) { |
| 1493 | // Do not process a boundary node and a back-edge is processed only |
| 1494 | // if it goes to a Phi. |
| 1495 | if (SI.getSUnit()->isBoundaryNode() || |
| 1496 | (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI())) |
| 1497 | continue; |
| 1498 | int N = SI.getSUnit()->NodeNum; |
| 1499 | if (!Added.test(N)) { |
| 1500 | AdjK[i].push_back(N); |
| 1501 | Added.set(N); |
| 1502 | } |
| 1503 | } |
| 1504 | // A chain edge between a store and a load is treated as a back-edge in the |
| 1505 | // adjacency matrix. |
| 1506 | for (auto &PI : SUnits[i].Preds) { |
| 1507 | if (!SUnits[i].getInstr()->mayStore() || |
| 1508 | !DAG->isLoopCarriedOrder(&SUnits[i], PI, false)) |
| 1509 | continue; |
| 1510 | if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) { |
| 1511 | int N = PI.getSUnit()->NodeNum; |
| 1512 | if (!Added.test(N)) { |
| 1513 | AdjK[i].push_back(N); |
| 1514 | Added.set(N); |
| 1515 | } |
| 1516 | } |
| 1517 | } |
| 1518 | } |
| 1519 | } |
| 1520 | |
| 1521 | /// Identify an elementary circuit in the dependence graph starting at the |
| 1522 | /// specified node. |
| 1523 | bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets, |
| 1524 | bool HasBackedge) { |
| 1525 | SUnit *SV = &SUnits[V]; |
| 1526 | bool F = false; |
| 1527 | Stack.insert(SV); |
| 1528 | Blocked.set(V); |
| 1529 | |
| 1530 | for (auto W : AdjK[V]) { |
| 1531 | if (NumPaths > MaxPaths) |
| 1532 | break; |
| 1533 | if (W < S) |
| 1534 | continue; |
| 1535 | if (W == S) { |
| 1536 | if (!HasBackedge) |
| 1537 | NodeSets.push_back(NodeSet(Stack.begin(), Stack.end())); |
| 1538 | F = true; |
| 1539 | ++NumPaths; |
| 1540 | break; |
| 1541 | } else if (!Blocked.test(W)) { |
| 1542 | if (circuit(W, S, NodeSets, W < V ? true : HasBackedge)) |
| 1543 | F = true; |
| 1544 | } |
| 1545 | } |
| 1546 | |
| 1547 | if (F) |
| 1548 | unblock(V); |
| 1549 | else { |
| 1550 | for (auto W : AdjK[V]) { |
| 1551 | if (W < S) |
| 1552 | continue; |
| 1553 | if (B[W].count(SV) == 0) |
| 1554 | B[W].insert(SV); |
| 1555 | } |
| 1556 | } |
| 1557 | Stack.pop_back(); |
| 1558 | return F; |
| 1559 | } |
| 1560 | |
| 1561 | /// Unblock a node in the circuit finding algorithm. |
| 1562 | void SwingSchedulerDAG::Circuits::unblock(int U) { |
| 1563 | Blocked.reset(U); |
| 1564 | SmallPtrSet<SUnit *, 4> &BU = B[U]; |
| 1565 | while (!BU.empty()) { |
| 1566 | SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin(); |
| 1567 | assert(SI != BU.end() && "Invalid B set."); |
| 1568 | SUnit *W = *SI; |
| 1569 | BU.erase(W); |
| 1570 | if (Blocked.test(W->NodeNum)) |
| 1571 | unblock(W->NodeNum); |
| 1572 | } |
| 1573 | } |
| 1574 | |
| 1575 | /// Identify all the elementary circuits in the dependence graph using |
| 1576 | /// Johnson's circuit algorithm. |
| 1577 | void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) { |
| 1578 | // Swap all the anti dependences in the DAG. That means it is no longer a DAG, |
| 1579 | // but we do this to find the circuits, and then change them back. |
| 1580 | swapAntiDependences(SUnits); |
| 1581 | |
| 1582 | Circuits Cir(SUnits); |
| 1583 | // Create the adjacency structure. |
| 1584 | Cir.createAdjacencyStructure(this); |
| 1585 | for (int i = 0, e = SUnits.size(); i != e; ++i) { |
| 1586 | Cir.reset(); |
| 1587 | Cir.circuit(i, i, NodeSets); |
| 1588 | } |
| 1589 | |
| 1590 | // Change the dependences back so that we've created a DAG again. |
| 1591 | swapAntiDependences(SUnits); |
| 1592 | } |
| 1593 | |
| 1594 | /// Return true for DAG nodes that we ignore when computing the cost functions. |
| 1595 | /// We ignore the back-edge recurrence in order to avoid unbounded recurison |
| 1596 | /// in the calculation of the ASAP, ALAP, etc functions. |
| 1597 | static bool ignoreDependence(const SDep &D, bool isPred) { |
| 1598 | if (D.isArtificial()) |
| 1599 | return true; |
| 1600 | return D.getKind() == SDep::Anti && isPred; |
| 1601 | } |
| 1602 | |
| 1603 | /// Compute several functions need to order the nodes for scheduling. |
| 1604 | /// ASAP - Earliest time to schedule a node. |
| 1605 | /// ALAP - Latest time to schedule a node. |
| 1606 | /// MOV - Mobility function, difference between ALAP and ASAP. |
| 1607 | /// D - Depth of each node. |
| 1608 | /// H - Height of each node. |
| 1609 | void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1610 | ScheduleInfo.resize(SUnits.size()); |
| 1611 | |
| 1612 | DEBUG({ |
| 1613 | for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(), |
| 1614 | E = Topo.end(); |
| 1615 | I != E; ++I) { |
| 1616 | SUnit *SU = &SUnits[*I]; |
| 1617 | SU->dump(this); |
| 1618 | } |
| 1619 | }); |
| 1620 | |
| 1621 | int maxASAP = 0; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1622 | // Compute ASAP and ZeroLatencyDepth. |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1623 | for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(), |
| 1624 | E = Topo.end(); |
| 1625 | I != E; ++I) { |
| 1626 | int asap = 0; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1627 | int zeroLatencyDepth = 0; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1628 | SUnit *SU = &SUnits[*I]; |
| 1629 | for (SUnit::const_pred_iterator IP = SU->Preds.begin(), |
| 1630 | EP = SU->Preds.end(); |
| 1631 | IP != EP; ++IP) { |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1632 | SUnit *pred = IP->getSUnit(); |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1633 | if (IP->getLatency() == 0) |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1634 | zeroLatencyDepth = |
| 1635 | std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1636 | if (ignoreDependence(*IP, true)) |
| 1637 | continue; |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1638 | asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() - |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1639 | getDistance(pred, SU, *IP) * MII)); |
| 1640 | } |
| 1641 | maxASAP = std::max(maxASAP, asap); |
| 1642 | ScheduleInfo[*I].ASAP = asap; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1643 | ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1644 | } |
| 1645 | |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1646 | // Compute ALAP, ZeroLatencyHeight, and MOV. |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1647 | for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(), |
| 1648 | E = Topo.rend(); |
| 1649 | I != E; ++I) { |
| 1650 | int alap = maxASAP; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1651 | int zeroLatencyHeight = 0; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1652 | SUnit *SU = &SUnits[*I]; |
| 1653 | for (SUnit::const_succ_iterator IS = SU->Succs.begin(), |
| 1654 | ES = SU->Succs.end(); |
| 1655 | IS != ES; ++IS) { |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1656 | SUnit *succ = IS->getSUnit(); |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1657 | if (IS->getLatency() == 0) |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1658 | zeroLatencyHeight = |
| 1659 | std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1660 | if (ignoreDependence(*IS, true)) |
| 1661 | continue; |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 1662 | alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() + |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1663 | getDistance(SU, succ, *IS) * MII)); |
| 1664 | } |
| 1665 | |
| 1666 | ScheduleInfo[*I].ALAP = alap; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1667 | ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1668 | } |
| 1669 | |
| 1670 | // After computing the node functions, compute the summary for each node set. |
| 1671 | for (NodeSet &I : NodeSets) |
| 1672 | I.computeNodeSetInfo(this); |
| 1673 | |
| 1674 | DEBUG({ |
| 1675 | for (unsigned i = 0; i < SUnits.size(); i++) { |
| 1676 | dbgs() << "\tNode " << i << ":\n"; |
| 1677 | dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n"; |
| 1678 | dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n"; |
| 1679 | dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n"; |
| 1680 | dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n"; |
| 1681 | dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n"; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 1682 | dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n"; |
| 1683 | dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n"; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1684 | } |
| 1685 | }); |
| 1686 | } |
| 1687 | |
| 1688 | /// Compute the Pred_L(O) set, as defined in the paper. The set is defined |
| 1689 | /// as the predecessors of the elements of NodeOrder that are not also in |
| 1690 | /// NodeOrder. |
| 1691 | static bool pred_L(SetVector<SUnit *> &NodeOrder, |
| 1692 | SmallSetVector<SUnit *, 8> &Preds, |
| 1693 | const NodeSet *S = nullptr) { |
| 1694 | Preds.clear(); |
| 1695 | for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end(); |
| 1696 | I != E; ++I) { |
| 1697 | for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end(); |
| 1698 | PI != PE; ++PI) { |
| 1699 | if (S && S->count(PI->getSUnit()) == 0) |
| 1700 | continue; |
| 1701 | if (ignoreDependence(*PI, true)) |
| 1702 | continue; |
| 1703 | if (NodeOrder.count(PI->getSUnit()) == 0) |
| 1704 | Preds.insert(PI->getSUnit()); |
| 1705 | } |
| 1706 | // Back-edges are predecessors with an anti-dependence. |
| 1707 | for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(), |
| 1708 | ES = (*I)->Succs.end(); |
| 1709 | IS != ES; ++IS) { |
| 1710 | if (IS->getKind() != SDep::Anti) |
| 1711 | continue; |
| 1712 | if (S && S->count(IS->getSUnit()) == 0) |
| 1713 | continue; |
| 1714 | if (NodeOrder.count(IS->getSUnit()) == 0) |
| 1715 | Preds.insert(IS->getSUnit()); |
| 1716 | } |
| 1717 | } |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1718 | return !Preds.empty(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1719 | } |
| 1720 | |
| 1721 | /// Compute the Succ_L(O) set, as defined in the paper. The set is defined |
| 1722 | /// as the successors of the elements of NodeOrder that are not also in |
| 1723 | /// NodeOrder. |
| 1724 | static bool succ_L(SetVector<SUnit *> &NodeOrder, |
| 1725 | SmallSetVector<SUnit *, 8> &Succs, |
| 1726 | const NodeSet *S = nullptr) { |
| 1727 | Succs.clear(); |
| 1728 | for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end(); |
| 1729 | I != E; ++I) { |
| 1730 | for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end(); |
| 1731 | SI != SE; ++SI) { |
| 1732 | if (S && S->count(SI->getSUnit()) == 0) |
| 1733 | continue; |
| 1734 | if (ignoreDependence(*SI, false)) |
| 1735 | continue; |
| 1736 | if (NodeOrder.count(SI->getSUnit()) == 0) |
| 1737 | Succs.insert(SI->getSUnit()); |
| 1738 | } |
| 1739 | for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(), |
| 1740 | PE = (*I)->Preds.end(); |
| 1741 | PI != PE; ++PI) { |
| 1742 | if (PI->getKind() != SDep::Anti) |
| 1743 | continue; |
| 1744 | if (S && S->count(PI->getSUnit()) == 0) |
| 1745 | continue; |
| 1746 | if (NodeOrder.count(PI->getSUnit()) == 0) |
| 1747 | Succs.insert(PI->getSUnit()); |
| 1748 | } |
| 1749 | } |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1750 | return !Succs.empty(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1751 | } |
| 1752 | |
| 1753 | /// Return true if there is a path from the specified node to any of the nodes |
| 1754 | /// in DestNodes. Keep track and return the nodes in any path. |
| 1755 | static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path, |
| 1756 | SetVector<SUnit *> &DestNodes, |
| 1757 | SetVector<SUnit *> &Exclude, |
| 1758 | SmallPtrSet<SUnit *, 8> &Visited) { |
| 1759 | if (Cur->isBoundaryNode()) |
| 1760 | return false; |
| 1761 | if (Exclude.count(Cur) != 0) |
| 1762 | return false; |
| 1763 | if (DestNodes.count(Cur) != 0) |
| 1764 | return true; |
| 1765 | if (!Visited.insert(Cur).second) |
| 1766 | return Path.count(Cur) != 0; |
| 1767 | bool FoundPath = false; |
| 1768 | for (auto &SI : Cur->Succs) |
| 1769 | FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited); |
| 1770 | for (auto &PI : Cur->Preds) |
| 1771 | if (PI.getKind() == SDep::Anti) |
| 1772 | FoundPath |= |
| 1773 | computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited); |
| 1774 | if (FoundPath) |
| 1775 | Path.insert(Cur); |
| 1776 | return FoundPath; |
| 1777 | } |
| 1778 | |
| 1779 | /// Return true if Set1 is a subset of Set2. |
| 1780 | template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) { |
| 1781 | for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I) |
| 1782 | if (Set2.count(*I) == 0) |
| 1783 | return false; |
| 1784 | return true; |
| 1785 | } |
| 1786 | |
| 1787 | /// Compute the live-out registers for the instructions in a node-set. |
| 1788 | /// The live-out registers are those that are defined in the node-set, |
| 1789 | /// but not used. Except for use operands of Phis. |
| 1790 | static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker, |
| 1791 | NodeSet &NS) { |
| 1792 | const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); |
| 1793 | MachineRegisterInfo &MRI = MF.getRegInfo(); |
| 1794 | SmallVector<RegisterMaskPair, 8> LiveOutRegs; |
| 1795 | SmallSet<unsigned, 4> Uses; |
| 1796 | for (SUnit *SU : NS) { |
| 1797 | const MachineInstr *MI = SU->getInstr(); |
| 1798 | if (MI->isPHI()) |
| 1799 | continue; |
Matthias Braun | fc37155 | 2016-10-24 21:36:43 +0000 | [diff] [blame] | 1800 | for (const MachineOperand &MO : MI->operands()) |
| 1801 | if (MO.isReg() && MO.isUse()) { |
| 1802 | unsigned Reg = MO.getReg(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1803 | if (TargetRegisterInfo::isVirtualRegister(Reg)) |
| 1804 | Uses.insert(Reg); |
| 1805 | else if (MRI.isAllocatable(Reg)) |
| 1806 | for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) |
| 1807 | Uses.insert(*Units); |
| 1808 | } |
| 1809 | } |
| 1810 | for (SUnit *SU : NS) |
Matthias Braun | fc37155 | 2016-10-24 21:36:43 +0000 | [diff] [blame] | 1811 | for (const MachineOperand &MO : SU->getInstr()->operands()) |
| 1812 | if (MO.isReg() && MO.isDef() && !MO.isDead()) { |
| 1813 | unsigned Reg = MO.getReg(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1814 | if (TargetRegisterInfo::isVirtualRegister(Reg)) { |
| 1815 | if (!Uses.count(Reg)) |
Krzysztof Parzyszek | 91b5cf8 | 2016-12-15 14:36:06 +0000 | [diff] [blame] | 1816 | LiveOutRegs.push_back(RegisterMaskPair(Reg, |
| 1817 | LaneBitmask::getNone())); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1818 | } else if (MRI.isAllocatable(Reg)) { |
| 1819 | for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) |
| 1820 | if (!Uses.count(*Units)) |
Krzysztof Parzyszek | 91b5cf8 | 2016-12-15 14:36:06 +0000 | [diff] [blame] | 1821 | LiveOutRegs.push_back(RegisterMaskPair(*Units, |
| 1822 | LaneBitmask::getNone())); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1823 | } |
| 1824 | } |
| 1825 | RPTracker.addLiveRegs(LiveOutRegs); |
| 1826 | } |
| 1827 | |
| 1828 | /// A heuristic to filter nodes in recurrent node-sets if the register |
| 1829 | /// pressure of a set is too high. |
| 1830 | void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) { |
| 1831 | for (auto &NS : NodeSets) { |
| 1832 | // Skip small node-sets since they won't cause register pressure problems. |
| 1833 | if (NS.size() <= 2) |
| 1834 | continue; |
| 1835 | IntervalPressure RecRegPressure; |
| 1836 | RegPressureTracker RecRPTracker(RecRegPressure); |
| 1837 | RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true); |
| 1838 | computeLiveOuts(MF, RecRPTracker, NS); |
| 1839 | RecRPTracker.closeBottom(); |
| 1840 | |
| 1841 | std::vector<SUnit *> SUnits(NS.begin(), NS.end()); |
| 1842 | std::sort(SUnits.begin(), SUnits.end(), [](const SUnit *A, const SUnit *B) { |
| 1843 | return A->NodeNum > B->NodeNum; |
| 1844 | }); |
| 1845 | |
| 1846 | for (auto &SU : SUnits) { |
| 1847 | // Since we're computing the register pressure for a subset of the |
| 1848 | // instructions in a block, we need to set the tracker for each |
| 1849 | // instruction in the node-set. The tracker is set to the instruction |
| 1850 | // just after the one we're interested in. |
| 1851 | MachineBasicBlock::const_iterator CurInstI = SU->getInstr(); |
| 1852 | RecRPTracker.setPos(std::next(CurInstI)); |
| 1853 | |
| 1854 | RegPressureDelta RPDelta; |
| 1855 | ArrayRef<PressureChange> CriticalPSets; |
| 1856 | RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta, |
| 1857 | CriticalPSets, |
| 1858 | RecRegPressure.MaxSetPressure); |
| 1859 | if (RPDelta.Excess.isValid()) { |
| 1860 | DEBUG(dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") " |
| 1861 | << TRI->getRegPressureSetName(RPDelta.Excess.getPSet()) |
| 1862 | << ":" << RPDelta.Excess.getUnitInc()); |
| 1863 | NS.setExceedPressure(SU); |
| 1864 | break; |
| 1865 | } |
| 1866 | RecRPTracker.recede(); |
| 1867 | } |
| 1868 | } |
| 1869 | } |
| 1870 | |
| 1871 | /// A heuristic to colocate node sets that have the same set of |
| 1872 | /// successors. |
| 1873 | void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) { |
| 1874 | unsigned Colocate = 0; |
| 1875 | for (int i = 0, e = NodeSets.size(); i < e; ++i) { |
| 1876 | NodeSet &N1 = NodeSets[i]; |
| 1877 | SmallSetVector<SUnit *, 8> S1; |
| 1878 | if (N1.empty() || !succ_L(N1, S1)) |
| 1879 | continue; |
| 1880 | for (int j = i + 1; j < e; ++j) { |
| 1881 | NodeSet &N2 = NodeSets[j]; |
| 1882 | if (N1.compareRecMII(N2) != 0) |
| 1883 | continue; |
| 1884 | SmallSetVector<SUnit *, 8> S2; |
| 1885 | if (N2.empty() || !succ_L(N2, S2)) |
| 1886 | continue; |
| 1887 | if (isSubset(S1, S2) && S1.size() == S2.size()) { |
| 1888 | N1.setColocate(++Colocate); |
| 1889 | N2.setColocate(Colocate); |
| 1890 | break; |
| 1891 | } |
| 1892 | } |
| 1893 | } |
| 1894 | } |
| 1895 | |
| 1896 | /// Check if the existing node-sets are profitable. If not, then ignore the |
| 1897 | /// recurrent node-sets, and attempt to schedule all nodes together. This is |
| 1898 | /// a heuristic. If the MII is large and there is a non-recurrent node with |
| 1899 | /// a large depth compared to the MII, then it's best to try and schedule |
| 1900 | /// all instruction together instead of starting with the recurrent node-sets. |
| 1901 | void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) { |
| 1902 | // Look for loops with a large MII. |
| 1903 | if (MII <= 20) |
| 1904 | return; |
| 1905 | // Check if the node-set contains only a simple add recurrence. |
| 1906 | for (auto &NS : NodeSets) |
| 1907 | if (NS.size() > 2) |
| 1908 | return; |
| 1909 | // If the depth of any instruction is significantly larger than the MII, then |
| 1910 | // ignore the recurrent node-sets and treat all instructions equally. |
| 1911 | for (auto &SU : SUnits) |
| 1912 | if (SU.getDepth() > MII * 1.5) { |
| 1913 | NodeSets.clear(); |
| 1914 | DEBUG(dbgs() << "Clear recurrence node-sets\n"); |
| 1915 | return; |
| 1916 | } |
| 1917 | } |
| 1918 | |
| 1919 | /// Add the nodes that do not belong to a recurrence set into groups |
| 1920 | /// based upon connected componenets. |
| 1921 | void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) { |
| 1922 | SetVector<SUnit *> NodesAdded; |
| 1923 | SmallPtrSet<SUnit *, 8> Visited; |
| 1924 | // Add the nodes that are on a path between the previous node sets and |
| 1925 | // the current node set. |
| 1926 | for (NodeSet &I : NodeSets) { |
| 1927 | SmallSetVector<SUnit *, 8> N; |
| 1928 | // Add the nodes from the current node set to the previous node set. |
| 1929 | if (succ_L(I, N)) { |
| 1930 | SetVector<SUnit *> Path; |
| 1931 | for (SUnit *NI : N) { |
| 1932 | Visited.clear(); |
| 1933 | computePath(NI, Path, NodesAdded, I, Visited); |
| 1934 | } |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1935 | if (!Path.empty()) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1936 | I.insert(Path.begin(), Path.end()); |
| 1937 | } |
| 1938 | // Add the nodes from the previous node set to the current node set. |
| 1939 | N.clear(); |
| 1940 | if (succ_L(NodesAdded, N)) { |
| 1941 | SetVector<SUnit *> Path; |
| 1942 | for (SUnit *NI : N) { |
| 1943 | Visited.clear(); |
| 1944 | computePath(NI, Path, I, NodesAdded, Visited); |
| 1945 | } |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1946 | if (!Path.empty()) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1947 | I.insert(Path.begin(), Path.end()); |
| 1948 | } |
| 1949 | NodesAdded.insert(I.begin(), I.end()); |
| 1950 | } |
| 1951 | |
| 1952 | // Create a new node set with the connected nodes of any successor of a node |
| 1953 | // in a recurrent set. |
| 1954 | NodeSet NewSet; |
| 1955 | SmallSetVector<SUnit *, 8> N; |
| 1956 | if (succ_L(NodesAdded, N)) |
| 1957 | for (SUnit *I : N) |
| 1958 | addConnectedNodes(I, NewSet, NodesAdded); |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1959 | if (!NewSet.empty()) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1960 | NodeSets.push_back(NewSet); |
| 1961 | |
| 1962 | // Create a new node set with the connected nodes of any predecessor of a node |
| 1963 | // in a recurrent set. |
| 1964 | NewSet.clear(); |
| 1965 | if (pred_L(NodesAdded, N)) |
| 1966 | for (SUnit *I : N) |
| 1967 | addConnectedNodes(I, NewSet, NodesAdded); |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1968 | if (!NewSet.empty()) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1969 | NodeSets.push_back(NewSet); |
| 1970 | |
| 1971 | // Create new nodes sets with the connected nodes any any remaining node that |
| 1972 | // has no predecessor. |
| 1973 | for (unsigned i = 0; i < SUnits.size(); ++i) { |
| 1974 | SUnit *SU = &SUnits[i]; |
| 1975 | if (NodesAdded.count(SU) == 0) { |
| 1976 | NewSet.clear(); |
| 1977 | addConnectedNodes(SU, NewSet, NodesAdded); |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 1978 | if (!NewSet.empty()) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 1979 | NodeSets.push_back(NewSet); |
| 1980 | } |
| 1981 | } |
| 1982 | } |
| 1983 | |
| 1984 | /// Add the node to the set, and add all is its connected nodes to the set. |
| 1985 | void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet, |
| 1986 | SetVector<SUnit *> &NodesAdded) { |
| 1987 | NewSet.insert(SU); |
| 1988 | NodesAdded.insert(SU); |
| 1989 | for (auto &SI : SU->Succs) { |
| 1990 | SUnit *Successor = SI.getSUnit(); |
| 1991 | if (!SI.isArtificial() && NodesAdded.count(Successor) == 0) |
| 1992 | addConnectedNodes(Successor, NewSet, NodesAdded); |
| 1993 | } |
| 1994 | for (auto &PI : SU->Preds) { |
| 1995 | SUnit *Predecessor = PI.getSUnit(); |
| 1996 | if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0) |
| 1997 | addConnectedNodes(Predecessor, NewSet, NodesAdded); |
| 1998 | } |
| 1999 | } |
| 2000 | |
| 2001 | /// Return true if Set1 contains elements in Set2. The elements in common |
| 2002 | /// are returned in a different container. |
| 2003 | static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2, |
| 2004 | SmallSetVector<SUnit *, 8> &Result) { |
| 2005 | Result.clear(); |
| 2006 | for (unsigned i = 0, e = Set1.size(); i != e; ++i) { |
| 2007 | SUnit *SU = Set1[i]; |
| 2008 | if (Set2.count(SU) != 0) |
| 2009 | Result.insert(SU); |
| 2010 | } |
| 2011 | return !Result.empty(); |
| 2012 | } |
| 2013 | |
| 2014 | /// Merge the recurrence node sets that have the same initial node. |
| 2015 | void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) { |
| 2016 | for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E; |
| 2017 | ++I) { |
| 2018 | NodeSet &NI = *I; |
| 2019 | for (NodeSetType::iterator J = I + 1; J != E;) { |
| 2020 | NodeSet &NJ = *J; |
| 2021 | if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) { |
| 2022 | if (NJ.compareRecMII(NI) > 0) |
| 2023 | NI.setRecMII(NJ.getRecMII()); |
| 2024 | for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI; |
| 2025 | ++NII) |
| 2026 | I->insert(*NII); |
| 2027 | NodeSets.erase(J); |
| 2028 | E = NodeSets.end(); |
| 2029 | } else { |
| 2030 | ++J; |
| 2031 | } |
| 2032 | } |
| 2033 | } |
| 2034 | } |
| 2035 | |
| 2036 | /// Remove nodes that have been scheduled in previous NodeSets. |
| 2037 | void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) { |
| 2038 | for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E; |
| 2039 | ++I) |
| 2040 | for (NodeSetType::iterator J = I + 1; J != E;) { |
| 2041 | J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); }); |
| 2042 | |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 2043 | if (J->empty()) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2044 | NodeSets.erase(J); |
| 2045 | E = NodeSets.end(); |
| 2046 | } else { |
| 2047 | ++J; |
| 2048 | } |
| 2049 | } |
| 2050 | } |
| 2051 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2052 | /// Compute an ordered list of the dependence graph nodes, which |
| 2053 | /// indicates the order that the nodes will be scheduled. This is a |
| 2054 | /// two-level algorithm. First, a partial order is created, which |
| 2055 | /// consists of a list of sets ordered from highest to lowest priority. |
| 2056 | void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) { |
| 2057 | SmallSetVector<SUnit *, 8> R; |
| 2058 | NodeOrder.clear(); |
| 2059 | |
| 2060 | for (auto &Nodes : NodeSets) { |
| 2061 | DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n"); |
| 2062 | OrderKind Order; |
| 2063 | SmallSetVector<SUnit *, 8> N; |
| 2064 | if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) { |
| 2065 | R.insert(N.begin(), N.end()); |
| 2066 | Order = BottomUp; |
| 2067 | DEBUG(dbgs() << " Bottom up (preds) "); |
| 2068 | } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) { |
| 2069 | R.insert(N.begin(), N.end()); |
| 2070 | Order = TopDown; |
| 2071 | DEBUG(dbgs() << " Top down (succs) "); |
| 2072 | } else if (isIntersect(N, Nodes, R)) { |
| 2073 | // If some of the successors are in the existing node-set, then use the |
| 2074 | // top-down ordering. |
| 2075 | Order = TopDown; |
| 2076 | DEBUG(dbgs() << " Top down (intersect) "); |
| 2077 | } else if (NodeSets.size() == 1) { |
| 2078 | for (auto &N : Nodes) |
| 2079 | if (N->Succs.size() == 0) |
| 2080 | R.insert(N); |
| 2081 | Order = BottomUp; |
| 2082 | DEBUG(dbgs() << " Bottom up (all) "); |
| 2083 | } else { |
| 2084 | // Find the node with the highest ASAP. |
| 2085 | SUnit *maxASAP = nullptr; |
| 2086 | for (SUnit *SU : Nodes) { |
| 2087 | if (maxASAP == nullptr || getASAP(SU) >= getASAP(maxASAP)) |
| 2088 | maxASAP = SU; |
| 2089 | } |
| 2090 | R.insert(maxASAP); |
| 2091 | Order = BottomUp; |
| 2092 | DEBUG(dbgs() << " Bottom up (default) "); |
| 2093 | } |
| 2094 | |
| 2095 | while (!R.empty()) { |
| 2096 | if (Order == TopDown) { |
| 2097 | // Choose the node with the maximum height. If more than one, choose |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 2098 | // the node with the maximum ZeroLatencyHeight. If still more than one, |
| 2099 | // choose the node with the lowest MOV. |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2100 | while (!R.empty()) { |
| 2101 | SUnit *maxHeight = nullptr; |
| 2102 | for (SUnit *I : R) { |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 2103 | if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2104 | maxHeight = I; |
| 2105 | else if (getHeight(I) == getHeight(maxHeight) && |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 2106 | getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2107 | maxHeight = I; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 2108 | else if (getHeight(I) == getHeight(maxHeight) && |
| 2109 | getZeroLatencyHeight(I) == |
| 2110 | getZeroLatencyHeight(maxHeight) && |
| 2111 | getMOV(I) < getMOV(maxHeight)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2112 | maxHeight = I; |
| 2113 | } |
| 2114 | NodeOrder.insert(maxHeight); |
| 2115 | DEBUG(dbgs() << maxHeight->NodeNum << " "); |
| 2116 | R.remove(maxHeight); |
| 2117 | for (const auto &I : maxHeight->Succs) { |
| 2118 | if (Nodes.count(I.getSUnit()) == 0) |
| 2119 | continue; |
| 2120 | if (NodeOrder.count(I.getSUnit()) != 0) |
| 2121 | continue; |
| 2122 | if (ignoreDependence(I, false)) |
| 2123 | continue; |
| 2124 | R.insert(I.getSUnit()); |
| 2125 | } |
| 2126 | // Back-edges are predecessors with an anti-dependence. |
| 2127 | for (const auto &I : maxHeight->Preds) { |
| 2128 | if (I.getKind() != SDep::Anti) |
| 2129 | continue; |
| 2130 | if (Nodes.count(I.getSUnit()) == 0) |
| 2131 | continue; |
| 2132 | if (NodeOrder.count(I.getSUnit()) != 0) |
| 2133 | continue; |
| 2134 | R.insert(I.getSUnit()); |
| 2135 | } |
| 2136 | } |
| 2137 | Order = BottomUp; |
| 2138 | DEBUG(dbgs() << "\n Switching order to bottom up "); |
| 2139 | SmallSetVector<SUnit *, 8> N; |
| 2140 | if (pred_L(NodeOrder, N, &Nodes)) |
| 2141 | R.insert(N.begin(), N.end()); |
| 2142 | } else { |
| 2143 | // Choose the node with the maximum depth. If more than one, choose |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 2144 | // the node with the maximum ZeroLatencyDepth. If still more than one, |
| 2145 | // choose the node with the lowest MOV. |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2146 | while (!R.empty()) { |
| 2147 | SUnit *maxDepth = nullptr; |
| 2148 | for (SUnit *I : R) { |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 2149 | if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2150 | maxDepth = I; |
| 2151 | else if (getDepth(I) == getDepth(maxDepth) && |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 2152 | getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2153 | maxDepth = I; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 2154 | else if (getDepth(I) == getDepth(maxDepth) && |
| 2155 | getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) && |
| 2156 | getMOV(I) < getMOV(maxDepth)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2157 | maxDepth = I; |
| 2158 | } |
| 2159 | NodeOrder.insert(maxDepth); |
| 2160 | DEBUG(dbgs() << maxDepth->NodeNum << " "); |
| 2161 | R.remove(maxDepth); |
| 2162 | if (Nodes.isExceedSU(maxDepth)) { |
| 2163 | Order = TopDown; |
| 2164 | R.clear(); |
| 2165 | R.insert(Nodes.getNode(0)); |
| 2166 | break; |
| 2167 | } |
| 2168 | for (const auto &I : maxDepth->Preds) { |
| 2169 | if (Nodes.count(I.getSUnit()) == 0) |
| 2170 | continue; |
| 2171 | if (NodeOrder.count(I.getSUnit()) != 0) |
| 2172 | continue; |
| 2173 | if (I.getKind() == SDep::Anti) |
| 2174 | continue; |
| 2175 | R.insert(I.getSUnit()); |
| 2176 | } |
| 2177 | // Back-edges are predecessors with an anti-dependence. |
| 2178 | for (const auto &I : maxDepth->Succs) { |
| 2179 | if (I.getKind() != SDep::Anti) |
| 2180 | continue; |
| 2181 | if (Nodes.count(I.getSUnit()) == 0) |
| 2182 | continue; |
| 2183 | if (NodeOrder.count(I.getSUnit()) != 0) |
| 2184 | continue; |
| 2185 | R.insert(I.getSUnit()); |
| 2186 | } |
| 2187 | } |
| 2188 | Order = TopDown; |
| 2189 | DEBUG(dbgs() << "\n Switching order to top down "); |
| 2190 | SmallSetVector<SUnit *, 8> N; |
| 2191 | if (succ_L(NodeOrder, N, &Nodes)) |
| 2192 | R.insert(N.begin(), N.end()); |
| 2193 | } |
| 2194 | } |
| 2195 | DEBUG(dbgs() << "\nDone with Nodeset\n"); |
| 2196 | } |
| 2197 | |
| 2198 | DEBUG({ |
| 2199 | dbgs() << "Node order: "; |
| 2200 | for (SUnit *I : NodeOrder) |
| 2201 | dbgs() << " " << I->NodeNum << " "; |
| 2202 | dbgs() << "\n"; |
| 2203 | }); |
| 2204 | } |
| 2205 | |
| 2206 | /// Process the nodes in the computed order and create the pipelined schedule |
| 2207 | /// of the instructions, if possible. Return true if a schedule is found. |
| 2208 | bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) { |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 2209 | if (NodeOrder.empty()) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2210 | return false; |
| 2211 | |
| 2212 | bool scheduleFound = false; |
| 2213 | // Keep increasing II until a valid schedule is found. |
| 2214 | for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) { |
| 2215 | Schedule.reset(); |
| 2216 | Schedule.setInitiationInterval(II); |
| 2217 | DEBUG(dbgs() << "Try to schedule with " << II << "\n"); |
| 2218 | |
| 2219 | SetVector<SUnit *>::iterator NI = NodeOrder.begin(); |
| 2220 | SetVector<SUnit *>::iterator NE = NodeOrder.end(); |
| 2221 | do { |
| 2222 | SUnit *SU = *NI; |
| 2223 | |
| 2224 | // Compute the schedule time for the instruction, which is based |
| 2225 | // upon the scheduled time for any predecessors/successors. |
| 2226 | int EarlyStart = INT_MIN; |
| 2227 | int LateStart = INT_MAX; |
| 2228 | // These values are set when the size of the schedule window is limited |
| 2229 | // due to chain dependences. |
| 2230 | int SchedEnd = INT_MAX; |
| 2231 | int SchedStart = INT_MIN; |
| 2232 | Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart, |
| 2233 | II, this); |
| 2234 | DEBUG({ |
| 2235 | dbgs() << "Inst (" << SU->NodeNum << ") "; |
| 2236 | SU->getInstr()->dump(); |
| 2237 | dbgs() << "\n"; |
| 2238 | }); |
| 2239 | DEBUG({ |
| 2240 | dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart |
| 2241 | << " me: " << SchedEnd << " ms: " << SchedStart << "\n"; |
| 2242 | }); |
| 2243 | |
| 2244 | if (EarlyStart > LateStart || SchedEnd < EarlyStart || |
| 2245 | SchedStart > LateStart) |
| 2246 | scheduleFound = false; |
| 2247 | else if (EarlyStart != INT_MIN && LateStart == INT_MAX) { |
| 2248 | SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1); |
| 2249 | scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II); |
| 2250 | } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) { |
| 2251 | SchedStart = std::max(SchedStart, LateStart - (int)II + 1); |
| 2252 | scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II); |
| 2253 | } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) { |
| 2254 | SchedEnd = |
| 2255 | std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1)); |
| 2256 | // When scheduling a Phi it is better to start at the late cycle and go |
| 2257 | // backwards. The default order may insert the Phi too far away from |
| 2258 | // its first dependence. |
| 2259 | if (SU->getInstr()->isPHI()) |
| 2260 | scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II); |
| 2261 | else |
| 2262 | scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II); |
| 2263 | } else { |
| 2264 | int FirstCycle = Schedule.getFirstCycle(); |
| 2265 | scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU), |
| 2266 | FirstCycle + getASAP(SU) + II - 1, II); |
| 2267 | } |
| 2268 | // Even if we find a schedule, make sure the schedule doesn't exceed the |
| 2269 | // allowable number of stages. We keep trying if this happens. |
| 2270 | if (scheduleFound) |
| 2271 | if (SwpMaxStages > -1 && |
| 2272 | Schedule.getMaxStageCount() > (unsigned)SwpMaxStages) |
| 2273 | scheduleFound = false; |
| 2274 | |
| 2275 | DEBUG({ |
| 2276 | if (!scheduleFound) |
| 2277 | dbgs() << "\tCan't schedule\n"; |
| 2278 | }); |
| 2279 | } while (++NI != NE && scheduleFound); |
| 2280 | |
| 2281 | // If a schedule is found, check if it is a valid schedule too. |
| 2282 | if (scheduleFound) |
| 2283 | scheduleFound = Schedule.isValidSchedule(this); |
| 2284 | } |
| 2285 | |
| 2286 | DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n"); |
| 2287 | |
| 2288 | if (scheduleFound) |
| 2289 | Schedule.finalizeSchedule(this); |
| 2290 | else |
| 2291 | Schedule.reset(); |
| 2292 | |
| 2293 | return scheduleFound && Schedule.getMaxStageCount() > 0; |
| 2294 | } |
| 2295 | |
| 2296 | /// Given a schedule for the loop, generate a new version of the loop, |
| 2297 | /// and replace the old version. This function generates a prolog |
| 2298 | /// that contains the initial iterations in the pipeline, and kernel |
| 2299 | /// loop, and the epilogue that contains the code for the final |
| 2300 | /// iterations. |
| 2301 | void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) { |
| 2302 | // Create a new basic block for the kernel and add it to the CFG. |
| 2303 | MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock()); |
| 2304 | |
| 2305 | unsigned MaxStageCount = Schedule.getMaxStageCount(); |
| 2306 | |
| 2307 | // Remember the registers that are used in different stages. The index is |
| 2308 | // the iteration, or stage, that the instruction is scheduled in. This is |
| 2309 | // a map between register names in the orignal block and the names created |
| 2310 | // in each stage of the pipelined loop. |
| 2311 | ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2]; |
| 2312 | InstrMapTy InstrMap; |
| 2313 | |
| 2314 | SmallVector<MachineBasicBlock *, 4> PrologBBs; |
| 2315 | // Generate the prolog instructions that set up the pipeline. |
| 2316 | generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs); |
| 2317 | MF.insert(BB->getIterator(), KernelBB); |
| 2318 | |
| 2319 | // Rearrange the instructions to generate the new, pipelined loop, |
| 2320 | // and update register names as needed. |
| 2321 | for (int Cycle = Schedule.getFirstCycle(), |
| 2322 | LastCycle = Schedule.getFinalCycle(); |
| 2323 | Cycle <= LastCycle; ++Cycle) { |
| 2324 | std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle); |
| 2325 | // This inner loop schedules each instruction in the cycle. |
| 2326 | for (SUnit *CI : CycleInstrs) { |
| 2327 | if (CI->getInstr()->isPHI()) |
| 2328 | continue; |
| 2329 | unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr())); |
| 2330 | MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum); |
| 2331 | updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap); |
| 2332 | KernelBB->push_back(NewMI); |
| 2333 | InstrMap[NewMI] = CI->getInstr(); |
| 2334 | } |
| 2335 | } |
| 2336 | |
| 2337 | // Copy any terminator instructions to the new kernel, and update |
| 2338 | // names as needed. |
| 2339 | for (MachineBasicBlock::iterator I = BB->getFirstTerminator(), |
| 2340 | E = BB->instr_end(); |
| 2341 | I != E; ++I) { |
| 2342 | MachineInstr *NewMI = MF.CloneMachineInstr(&*I); |
| 2343 | updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap); |
| 2344 | KernelBB->push_back(NewMI); |
| 2345 | InstrMap[NewMI] = &*I; |
| 2346 | } |
| 2347 | |
| 2348 | KernelBB->transferSuccessors(BB); |
| 2349 | KernelBB->replaceSuccessor(BB, KernelBB); |
| 2350 | |
| 2351 | generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, |
| 2352 | VRMap, InstrMap, MaxStageCount, MaxStageCount, false); |
| 2353 | generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap, |
| 2354 | InstrMap, MaxStageCount, MaxStageCount, false); |
| 2355 | |
| 2356 | DEBUG(dbgs() << "New block\n"; KernelBB->dump();); |
| 2357 | |
| 2358 | SmallVector<MachineBasicBlock *, 4> EpilogBBs; |
| 2359 | // Generate the epilog instructions to complete the pipeline. |
| 2360 | generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs, |
| 2361 | PrologBBs); |
| 2362 | |
| 2363 | // We need this step because the register allocation doesn't handle some |
| 2364 | // situations well, so we insert copies to help out. |
| 2365 | splitLifetimes(KernelBB, EpilogBBs, Schedule); |
| 2366 | |
| 2367 | // Remove dead instructions due to loop induction variables. |
| 2368 | removeDeadInstructions(KernelBB, EpilogBBs); |
| 2369 | |
| 2370 | // Add branches between prolog and epilog blocks. |
| 2371 | addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap); |
| 2372 | |
| 2373 | // Remove the original loop since it's no longer referenced. |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 2374 | for (auto &I : *BB) |
| 2375 | LIS.RemoveMachineInstrFromMaps(I); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2376 | BB->clear(); |
| 2377 | BB->eraseFromParent(); |
| 2378 | |
| 2379 | delete[] VRMap; |
| 2380 | } |
| 2381 | |
| 2382 | /// Generate the pipeline prolog code. |
| 2383 | void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage, |
| 2384 | MachineBasicBlock *KernelBB, |
| 2385 | ValueMapTy *VRMap, |
| 2386 | MBBVectorTy &PrologBBs) { |
| 2387 | MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader(); |
Eugene Zelenko | 32a4056 | 2017-09-11 23:00:48 +0000 | [diff] [blame] | 2388 | assert(PreheaderBB != nullptr && |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2389 | "Need to add code to handle loops w/o preheader"); |
| 2390 | MachineBasicBlock *PredBB = PreheaderBB; |
| 2391 | InstrMapTy InstrMap; |
| 2392 | |
| 2393 | // Generate a basic block for each stage, not including the last stage, |
| 2394 | // which will be generated in the kernel. Each basic block may contain |
| 2395 | // instructions from multiple stages/iterations. |
| 2396 | for (unsigned i = 0; i < LastStage; ++i) { |
| 2397 | // Create and insert the prolog basic block prior to the original loop |
| 2398 | // basic block. The original loop is removed later. |
| 2399 | MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock()); |
| 2400 | PrologBBs.push_back(NewBB); |
| 2401 | MF.insert(BB->getIterator(), NewBB); |
| 2402 | NewBB->transferSuccessors(PredBB); |
| 2403 | PredBB->addSuccessor(NewBB); |
| 2404 | PredBB = NewBB; |
| 2405 | |
| 2406 | // Generate instructions for each appropriate stage. Process instructions |
| 2407 | // in original program order. |
| 2408 | for (int StageNum = i; StageNum >= 0; --StageNum) { |
| 2409 | for (MachineBasicBlock::iterator BBI = BB->instr_begin(), |
| 2410 | BBE = BB->getFirstTerminator(); |
| 2411 | BBI != BBE; ++BBI) { |
| 2412 | if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) { |
| 2413 | if (BBI->isPHI()) |
| 2414 | continue; |
| 2415 | MachineInstr *NewMI = |
| 2416 | cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule); |
| 2417 | updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule, |
| 2418 | VRMap); |
| 2419 | NewBB->push_back(NewMI); |
| 2420 | InstrMap[NewMI] = &*BBI; |
| 2421 | } |
| 2422 | } |
| 2423 | } |
| 2424 | rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap); |
| 2425 | DEBUG({ |
| 2426 | dbgs() << "prolog:\n"; |
| 2427 | NewBB->dump(); |
| 2428 | }); |
| 2429 | } |
| 2430 | |
| 2431 | PredBB->replaceSuccessor(BB, KernelBB); |
| 2432 | |
| 2433 | // Check if we need to remove the branch from the preheader to the original |
| 2434 | // loop, and replace it with a branch to the new loop. |
Matt Arsenault | 1b9fc8e | 2016-09-14 20:43:16 +0000 | [diff] [blame] | 2435 | unsigned numBranches = TII->removeBranch(*PreheaderBB); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2436 | if (numBranches) { |
| 2437 | SmallVector<MachineOperand, 0> Cond; |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 2438 | TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc()); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2439 | } |
| 2440 | } |
| 2441 | |
| 2442 | /// Generate the pipeline epilog code. The epilog code finishes the iterations |
| 2443 | /// that were started in either the prolog or the kernel. We create a basic |
| 2444 | /// block for each stage that needs to complete. |
| 2445 | void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage, |
| 2446 | MachineBasicBlock *KernelBB, |
| 2447 | ValueMapTy *VRMap, |
| 2448 | MBBVectorTy &EpilogBBs, |
| 2449 | MBBVectorTy &PrologBBs) { |
| 2450 | // We need to change the branch from the kernel to the first epilog block, so |
| 2451 | // this call to analyze branch uses the kernel rather than the original BB. |
| 2452 | MachineBasicBlock *TBB = nullptr, *FBB = nullptr; |
| 2453 | SmallVector<MachineOperand, 4> Cond; |
| 2454 | bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond); |
| 2455 | assert(!checkBranch && "generateEpilog must be able to analyze the branch"); |
| 2456 | if (checkBranch) |
| 2457 | return; |
| 2458 | |
| 2459 | MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin(); |
| 2460 | if (*LoopExitI == KernelBB) |
| 2461 | ++LoopExitI; |
| 2462 | assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor"); |
| 2463 | MachineBasicBlock *LoopExitBB = *LoopExitI; |
| 2464 | |
| 2465 | MachineBasicBlock *PredBB = KernelBB; |
| 2466 | MachineBasicBlock *EpilogStart = LoopExitBB; |
| 2467 | InstrMapTy InstrMap; |
| 2468 | |
| 2469 | // Generate a basic block for each stage, not including the last stage, |
| 2470 | // which was generated for the kernel. Each basic block may contain |
| 2471 | // instructions from multiple stages/iterations. |
| 2472 | int EpilogStage = LastStage + 1; |
| 2473 | for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) { |
| 2474 | MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(); |
| 2475 | EpilogBBs.push_back(NewBB); |
| 2476 | MF.insert(BB->getIterator(), NewBB); |
| 2477 | |
| 2478 | PredBB->replaceSuccessor(LoopExitBB, NewBB); |
| 2479 | NewBB->addSuccessor(LoopExitBB); |
| 2480 | |
| 2481 | if (EpilogStart == LoopExitBB) |
| 2482 | EpilogStart = NewBB; |
| 2483 | |
| 2484 | // Add instructions to the epilog depending on the current block. |
| 2485 | // Process instructions in original program order. |
| 2486 | for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) { |
| 2487 | for (auto &BBI : *BB) { |
| 2488 | if (BBI.isPHI()) |
| 2489 | continue; |
| 2490 | MachineInstr *In = &BBI; |
| 2491 | if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) { |
Krzysztof Parzyszek | 785b6ce | 2018-03-26 15:45:55 +0000 | [diff] [blame^] | 2492 | // Instructions with memoperands in the epilog are updated with |
| 2493 | // conservative values. |
| 2494 | MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2495 | updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap); |
| 2496 | NewBB->push_back(NewMI); |
| 2497 | InstrMap[NewMI] = In; |
| 2498 | } |
| 2499 | } |
| 2500 | } |
| 2501 | generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, |
| 2502 | VRMap, InstrMap, LastStage, EpilogStage, i == 1); |
| 2503 | generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap, |
| 2504 | InstrMap, LastStage, EpilogStage, i == 1); |
| 2505 | PredBB = NewBB; |
| 2506 | |
| 2507 | DEBUG({ |
| 2508 | dbgs() << "epilog:\n"; |
| 2509 | NewBB->dump(); |
| 2510 | }); |
| 2511 | } |
| 2512 | |
| 2513 | // Fix any Phi nodes in the loop exit block. |
| 2514 | for (MachineInstr &MI : *LoopExitBB) { |
| 2515 | if (!MI.isPHI()) |
| 2516 | break; |
| 2517 | for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) { |
| 2518 | MachineOperand &MO = MI.getOperand(i); |
| 2519 | if (MO.getMBB() == BB) |
| 2520 | MO.setMBB(PredBB); |
| 2521 | } |
| 2522 | } |
| 2523 | |
| 2524 | // Create a branch to the new epilog from the kernel. |
| 2525 | // Remove the original branch and add a new branch to the epilog. |
Matt Arsenault | 1b9fc8e | 2016-09-14 20:43:16 +0000 | [diff] [blame] | 2526 | TII->removeBranch(*KernelBB); |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 2527 | TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc()); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2528 | // Add a branch to the loop exit. |
| 2529 | if (EpilogBBs.size() > 0) { |
| 2530 | MachineBasicBlock *LastEpilogBB = EpilogBBs.back(); |
| 2531 | SmallVector<MachineOperand, 4> Cond1; |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 2532 | TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc()); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2533 | } |
| 2534 | } |
| 2535 | |
| 2536 | /// Replace all uses of FromReg that appear outside the specified |
| 2537 | /// basic block with ToReg. |
| 2538 | static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg, |
| 2539 | MachineBasicBlock *MBB, |
| 2540 | MachineRegisterInfo &MRI, |
| 2541 | LiveIntervals &LIS) { |
| 2542 | for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg), |
| 2543 | E = MRI.use_end(); |
| 2544 | I != E;) { |
| 2545 | MachineOperand &O = *I; |
| 2546 | ++I; |
| 2547 | if (O.getParent()->getParent() != MBB) |
| 2548 | O.setReg(ToReg); |
| 2549 | } |
| 2550 | if (!LIS.hasInterval(ToReg)) |
| 2551 | LIS.createEmptyInterval(ToReg); |
| 2552 | } |
| 2553 | |
| 2554 | /// Return true if the register has a use that occurs outside the |
| 2555 | /// specified loop. |
| 2556 | static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB, |
| 2557 | MachineRegisterInfo &MRI) { |
| 2558 | for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg), |
| 2559 | E = MRI.use_end(); |
| 2560 | I != E; ++I) |
| 2561 | if (I->getParent()->getParent() != BB) |
| 2562 | return true; |
| 2563 | return false; |
| 2564 | } |
| 2565 | |
| 2566 | /// Generate Phis for the specific block in the generated pipelined code. |
| 2567 | /// This function looks at the Phis from the original code to guide the |
| 2568 | /// creation of new Phis. |
| 2569 | void SwingSchedulerDAG::generateExistingPhis( |
| 2570 | MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2, |
| 2571 | MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap, |
| 2572 | InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum, |
| 2573 | bool IsLast) { |
Simon Pilgrim | 6bdc755 | 2017-03-31 10:59:37 +0000 | [diff] [blame] | 2574 | // Compute the stage number for the initial value of the Phi, which |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2575 | // comes from the prolog. The prolog to use depends on to which kernel/ |
| 2576 | // epilog that we're adding the Phi. |
| 2577 | unsigned PrologStage = 0; |
| 2578 | unsigned PrevStage = 0; |
| 2579 | bool InKernel = (LastStageNum == CurStageNum); |
| 2580 | if (InKernel) { |
| 2581 | PrologStage = LastStageNum - 1; |
| 2582 | PrevStage = CurStageNum; |
| 2583 | } else { |
| 2584 | PrologStage = LastStageNum - (CurStageNum - LastStageNum); |
| 2585 | PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1; |
| 2586 | } |
| 2587 | |
| 2588 | for (MachineBasicBlock::iterator BBI = BB->instr_begin(), |
| 2589 | BBE = BB->getFirstNonPHI(); |
| 2590 | BBI != BBE; ++BBI) { |
| 2591 | unsigned Def = BBI->getOperand(0).getReg(); |
| 2592 | |
| 2593 | unsigned InitVal = 0; |
| 2594 | unsigned LoopVal = 0; |
| 2595 | getPhiRegs(*BBI, BB, InitVal, LoopVal); |
| 2596 | |
| 2597 | unsigned PhiOp1 = 0; |
| 2598 | // The Phi value from the loop body typically is defined in the loop, but |
| 2599 | // not always. So, we need to check if the value is defined in the loop. |
| 2600 | unsigned PhiOp2 = LoopVal; |
| 2601 | if (VRMap[LastStageNum].count(LoopVal)) |
| 2602 | PhiOp2 = VRMap[LastStageNum][LoopVal]; |
| 2603 | |
| 2604 | int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI)); |
| 2605 | int LoopValStage = |
| 2606 | Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal))); |
| 2607 | unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum); |
| 2608 | if (NumStages == 0) { |
| 2609 | // We don't need to generate a Phi anymore, but we need to rename any uses |
| 2610 | // of the Phi value. |
| 2611 | unsigned NewReg = VRMap[PrevStage][LoopVal]; |
| 2612 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI, |
| 2613 | Def, NewReg); |
| 2614 | if (VRMap[CurStageNum].count(LoopVal)) |
| 2615 | VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal]; |
| 2616 | } |
| 2617 | // Adjust the number of Phis needed depending on the number of prologs left, |
| 2618 | // and the distance from where the Phi is first scheduled. |
| 2619 | unsigned NumPhis = NumStages; |
| 2620 | if (!InKernel && (int)PrologStage < LoopValStage) |
| 2621 | // The NumPhis is the maximum number of new Phis needed during the steady |
| 2622 | // state. If the Phi has not been scheduled in current prolog, then we |
| 2623 | // need to generate less Phis. |
| 2624 | NumPhis = std::max((int)NumPhis - (int)(LoopValStage - PrologStage), 1); |
| 2625 | // The number of Phis cannot exceed the number of prolog stages. Each |
| 2626 | // stage can potentially define two values. |
| 2627 | NumPhis = std::min(NumPhis, PrologStage + 2); |
| 2628 | |
| 2629 | unsigned NewReg = 0; |
| 2630 | |
| 2631 | unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled; |
| 2632 | // In the epilog, we may need to look back one stage to get the correct |
| 2633 | // Phi name because the epilog and prolog blocks execute the same stage. |
| 2634 | // The correct name is from the previous block only when the Phi has |
| 2635 | // been completely scheduled prior to the epilog, and Phi value is not |
| 2636 | // needed in multiple stages. |
| 2637 | int StageDiff = 0; |
| 2638 | if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 && |
| 2639 | NumPhis == 1) |
| 2640 | StageDiff = 1; |
| 2641 | // Adjust the computations below when the phi and the loop definition |
| 2642 | // are scheduled in different stages. |
| 2643 | if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage) |
| 2644 | StageDiff = StageScheduled - LoopValStage; |
| 2645 | for (unsigned np = 0; np < NumPhis; ++np) { |
| 2646 | // If the Phi hasn't been scheduled, then use the initial Phi operand |
| 2647 | // value. Otherwise, use the scheduled version of the instruction. This |
| 2648 | // is a little complicated when a Phi references another Phi. |
| 2649 | if (np > PrologStage || StageScheduled >= (int)LastStageNum) |
| 2650 | PhiOp1 = InitVal; |
| 2651 | // Check if the Phi has already been scheduled in a prolog stage. |
| 2652 | else if (PrologStage >= AccessStage + StageDiff + np && |
| 2653 | VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0) |
| 2654 | PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal]; |
| 2655 | // Check if the Phi has already been scheduled, but the loop intruction |
| 2656 | // is either another Phi, or doesn't occur in the loop. |
| 2657 | else if (PrologStage >= AccessStage + StageDiff + np) { |
| 2658 | // If the Phi references another Phi, we need to examine the other |
| 2659 | // Phi to get the correct value. |
| 2660 | PhiOp1 = LoopVal; |
| 2661 | MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1); |
| 2662 | int Indirects = 1; |
| 2663 | while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) { |
| 2664 | int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1)); |
| 2665 | if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects) |
| 2666 | PhiOp1 = getInitPhiReg(*InstOp1, BB); |
| 2667 | else |
| 2668 | PhiOp1 = getLoopPhiReg(*InstOp1, BB); |
| 2669 | InstOp1 = MRI.getVRegDef(PhiOp1); |
| 2670 | int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1)); |
| 2671 | int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0); |
| 2672 | if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np && |
| 2673 | VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) { |
| 2674 | PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1]; |
| 2675 | break; |
| 2676 | } |
| 2677 | ++Indirects; |
| 2678 | } |
| 2679 | } else |
| 2680 | PhiOp1 = InitVal; |
| 2681 | // If this references a generated Phi in the kernel, get the Phi operand |
| 2682 | // from the incoming block. |
| 2683 | if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) |
| 2684 | if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB) |
| 2685 | PhiOp1 = getInitPhiReg(*InstOp1, KernelBB); |
| 2686 | |
| 2687 | MachineInstr *PhiInst = MRI.getVRegDef(LoopVal); |
| 2688 | bool LoopDefIsPhi = PhiInst && PhiInst->isPHI(); |
| 2689 | // In the epilog, a map lookup is needed to get the value from the kernel, |
| 2690 | // or previous epilog block. How is does this depends on if the |
| 2691 | // instruction is scheduled in the previous block. |
| 2692 | if (!InKernel) { |
| 2693 | int StageDiffAdj = 0; |
| 2694 | if (LoopValStage != -1 && StageScheduled > LoopValStage) |
| 2695 | StageDiffAdj = StageScheduled - LoopValStage; |
| 2696 | // Use the loop value defined in the kernel, unless the kernel |
| 2697 | // contains the last definition of the Phi. |
| 2698 | if (np == 0 && PrevStage == LastStageNum && |
| 2699 | (StageScheduled != 0 || LoopValStage != 0) && |
| 2700 | VRMap[PrevStage - StageDiffAdj].count(LoopVal)) |
| 2701 | PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal]; |
| 2702 | // Use the value defined by the Phi. We add one because we switch |
| 2703 | // from looking at the loop value to the Phi definition. |
| 2704 | else if (np > 0 && PrevStage == LastStageNum && |
| 2705 | VRMap[PrevStage - np + 1].count(Def)) |
| 2706 | PhiOp2 = VRMap[PrevStage - np + 1][Def]; |
| 2707 | // Use the loop value defined in the kernel. |
| 2708 | else if ((unsigned)LoopValStage + StageDiffAdj > PrologStage + 1 && |
| 2709 | VRMap[PrevStage - StageDiffAdj - np].count(LoopVal)) |
| 2710 | PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal]; |
| 2711 | // Use the value defined by the Phi, unless we're generating the first |
| 2712 | // epilog and the Phi refers to a Phi in a different stage. |
| 2713 | else if (VRMap[PrevStage - np].count(Def) && |
| 2714 | (!LoopDefIsPhi || PrevStage != LastStageNum)) |
| 2715 | PhiOp2 = VRMap[PrevStage - np][Def]; |
| 2716 | } |
| 2717 | |
| 2718 | // Check if we can reuse an existing Phi. This occurs when a Phi |
| 2719 | // references another Phi, and the other Phi is scheduled in an |
| 2720 | // earlier stage. We can try to reuse an existing Phi up until the last |
| 2721 | // stage of the current Phi. |
Brendon Cahoon | 65b6ebc | 2016-08-16 14:29:24 +0000 | [diff] [blame] | 2722 | if (LoopDefIsPhi && (int)PrologStage >= StageScheduled) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2723 | int LVNumStages = Schedule.getStagesForPhi(LoopVal); |
| 2724 | int StageDiff = (StageScheduled - LoopValStage); |
| 2725 | LVNumStages -= StageDiff; |
| 2726 | if (LVNumStages > (int)np) { |
| 2727 | NewReg = PhiOp2; |
| 2728 | unsigned ReuseStage = CurStageNum; |
| 2729 | if (Schedule.isLoopCarried(this, *PhiInst)) |
| 2730 | ReuseStage -= LVNumStages; |
| 2731 | // Check if the Phi to reuse has been generated yet. If not, then |
| 2732 | // there is nothing to reuse. |
| 2733 | if (VRMap[ReuseStage].count(LoopVal)) { |
| 2734 | NewReg = VRMap[ReuseStage][LoopVal]; |
| 2735 | |
| 2736 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, |
| 2737 | &*BBI, Def, NewReg); |
| 2738 | // Update the map with the new Phi name. |
| 2739 | VRMap[CurStageNum - np][Def] = NewReg; |
| 2740 | PhiOp2 = NewReg; |
| 2741 | if (VRMap[LastStageNum - np - 1].count(LoopVal)) |
| 2742 | PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal]; |
| 2743 | |
| 2744 | if (IsLast && np == NumPhis - 1) |
| 2745 | replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS); |
| 2746 | continue; |
| 2747 | } |
Krzysztof Parzyszek | df24da2 | 2016-12-22 18:49:55 +0000 | [diff] [blame] | 2748 | } else if (InKernel && StageDiff > 0 && |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2749 | VRMap[CurStageNum - StageDiff - np].count(LoopVal)) |
| 2750 | PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal]; |
| 2751 | } |
| 2752 | |
| 2753 | const TargetRegisterClass *RC = MRI.getRegClass(Def); |
| 2754 | NewReg = MRI.createVirtualRegister(RC); |
| 2755 | |
| 2756 | MachineInstrBuilder NewPhi = |
| 2757 | BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(), |
| 2758 | TII->get(TargetOpcode::PHI), NewReg); |
| 2759 | NewPhi.addReg(PhiOp1).addMBB(BB1); |
| 2760 | NewPhi.addReg(PhiOp2).addMBB(BB2); |
| 2761 | if (np == 0) |
| 2762 | InstrMap[NewPhi] = &*BBI; |
| 2763 | |
| 2764 | // We define the Phis after creating the new pipelined code, so |
| 2765 | // we need to rename the Phi values in scheduled instructions. |
| 2766 | |
| 2767 | unsigned PrevReg = 0; |
| 2768 | if (InKernel && VRMap[PrevStage - np].count(LoopVal)) |
| 2769 | PrevReg = VRMap[PrevStage - np][LoopVal]; |
| 2770 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI, |
| 2771 | Def, NewReg, PrevReg); |
| 2772 | // If the Phi has been scheduled, use the new name for rewriting. |
| 2773 | if (VRMap[CurStageNum - np].count(Def)) { |
| 2774 | unsigned R = VRMap[CurStageNum - np][Def]; |
| 2775 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI, |
| 2776 | R, NewReg); |
| 2777 | } |
| 2778 | |
| 2779 | // Check if we need to rename any uses that occurs after the loop. The |
| 2780 | // register to replace depends on whether the Phi is scheduled in the |
| 2781 | // epilog. |
| 2782 | if (IsLast && np == NumPhis - 1) |
| 2783 | replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS); |
| 2784 | |
| 2785 | // In the kernel, a dependent Phi uses the value from this Phi. |
| 2786 | if (InKernel) |
| 2787 | PhiOp2 = NewReg; |
| 2788 | |
| 2789 | // Update the map with the new Phi name. |
| 2790 | VRMap[CurStageNum - np][Def] = NewReg; |
| 2791 | } |
| 2792 | |
| 2793 | while (NumPhis++ < NumStages) { |
| 2794 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis, |
| 2795 | &*BBI, Def, NewReg, 0); |
| 2796 | } |
| 2797 | |
| 2798 | // Check if we need to rename a Phi that has been eliminated due to |
| 2799 | // scheduling. |
| 2800 | if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal)) |
| 2801 | replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS); |
| 2802 | } |
| 2803 | } |
| 2804 | |
| 2805 | /// Generate Phis for the specified block in the generated pipelined code. |
| 2806 | /// These are new Phis needed because the definition is scheduled after the |
| 2807 | /// use in the pipelened sequence. |
| 2808 | void SwingSchedulerDAG::generatePhis( |
| 2809 | MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2, |
| 2810 | MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap, |
| 2811 | InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum, |
| 2812 | bool IsLast) { |
| 2813 | // Compute the stage number that contains the initial Phi value, and |
| 2814 | // the Phi from the previous stage. |
| 2815 | unsigned PrologStage = 0; |
| 2816 | unsigned PrevStage = 0; |
| 2817 | unsigned StageDiff = CurStageNum - LastStageNum; |
| 2818 | bool InKernel = (StageDiff == 0); |
| 2819 | if (InKernel) { |
| 2820 | PrologStage = LastStageNum - 1; |
| 2821 | PrevStage = CurStageNum; |
| 2822 | } else { |
| 2823 | PrologStage = LastStageNum - StageDiff; |
| 2824 | PrevStage = LastStageNum + StageDiff - 1; |
| 2825 | } |
| 2826 | |
| 2827 | for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(), |
| 2828 | BBE = BB->instr_end(); |
| 2829 | BBI != BBE; ++BBI) { |
| 2830 | for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) { |
| 2831 | MachineOperand &MO = BBI->getOperand(i); |
| 2832 | if (!MO.isReg() || !MO.isDef() || |
| 2833 | !TargetRegisterInfo::isVirtualRegister(MO.getReg())) |
| 2834 | continue; |
| 2835 | |
| 2836 | int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI)); |
| 2837 | assert(StageScheduled != -1 && "Expecting scheduled instruction."); |
| 2838 | unsigned Def = MO.getReg(); |
| 2839 | unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum); |
| 2840 | // An instruction scheduled in stage 0 and is used after the loop |
| 2841 | // requires a phi in the epilog for the last definition from either |
| 2842 | // the kernel or prolog. |
| 2843 | if (!InKernel && NumPhis == 0 && StageScheduled == 0 && |
| 2844 | hasUseAfterLoop(Def, BB, MRI)) |
| 2845 | NumPhis = 1; |
| 2846 | if (!InKernel && (unsigned)StageScheduled > PrologStage) |
| 2847 | continue; |
| 2848 | |
| 2849 | unsigned PhiOp2 = VRMap[PrevStage][Def]; |
| 2850 | if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2)) |
| 2851 | if (InstOp2->isPHI() && InstOp2->getParent() == NewBB) |
| 2852 | PhiOp2 = getLoopPhiReg(*InstOp2, BB2); |
| 2853 | // The number of Phis can't exceed the number of prolog stages. The |
| 2854 | // prolog stage number is zero based. |
| 2855 | if (NumPhis > PrologStage + 1 - StageScheduled) |
| 2856 | NumPhis = PrologStage + 1 - StageScheduled; |
| 2857 | for (unsigned np = 0; np < NumPhis; ++np) { |
| 2858 | unsigned PhiOp1 = VRMap[PrologStage][Def]; |
| 2859 | if (np <= PrologStage) |
| 2860 | PhiOp1 = VRMap[PrologStage - np][Def]; |
| 2861 | if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) { |
| 2862 | if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB) |
| 2863 | PhiOp1 = getInitPhiReg(*InstOp1, KernelBB); |
| 2864 | if (InstOp1->isPHI() && InstOp1->getParent() == NewBB) |
| 2865 | PhiOp1 = getInitPhiReg(*InstOp1, NewBB); |
| 2866 | } |
| 2867 | if (!InKernel) |
| 2868 | PhiOp2 = VRMap[PrevStage - np][Def]; |
| 2869 | |
| 2870 | const TargetRegisterClass *RC = MRI.getRegClass(Def); |
| 2871 | unsigned NewReg = MRI.createVirtualRegister(RC); |
| 2872 | |
| 2873 | MachineInstrBuilder NewPhi = |
| 2874 | BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(), |
| 2875 | TII->get(TargetOpcode::PHI), NewReg); |
| 2876 | NewPhi.addReg(PhiOp1).addMBB(BB1); |
| 2877 | NewPhi.addReg(PhiOp2).addMBB(BB2); |
| 2878 | if (np == 0) |
| 2879 | InstrMap[NewPhi] = &*BBI; |
| 2880 | |
| 2881 | // Rewrite uses and update the map. The actions depend upon whether |
| 2882 | // we generating code for the kernel or epilog blocks. |
| 2883 | if (InKernel) { |
| 2884 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, |
| 2885 | &*BBI, PhiOp1, NewReg); |
| 2886 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, |
| 2887 | &*BBI, PhiOp2, NewReg); |
| 2888 | |
| 2889 | PhiOp2 = NewReg; |
| 2890 | VRMap[PrevStage - np - 1][Def] = NewReg; |
| 2891 | } else { |
| 2892 | VRMap[CurStageNum - np][Def] = NewReg; |
| 2893 | if (np == NumPhis - 1) |
| 2894 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, |
| 2895 | &*BBI, Def, NewReg); |
| 2896 | } |
| 2897 | if (IsLast && np == NumPhis - 1) |
| 2898 | replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS); |
| 2899 | } |
| 2900 | } |
| 2901 | } |
| 2902 | } |
| 2903 | |
| 2904 | /// Remove instructions that generate values with no uses. |
| 2905 | /// Typically, these are induction variable operations that generate values |
| 2906 | /// used in the loop itself. A dead instruction has a definition with |
| 2907 | /// no uses, or uses that occur in the original loop only. |
| 2908 | void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB, |
| 2909 | MBBVectorTy &EpilogBBs) { |
| 2910 | // For each epilog block, check that the value defined by each instruction |
| 2911 | // is used. If not, delete it. |
| 2912 | for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(), |
| 2913 | MBE = EpilogBBs.rend(); |
| 2914 | MBB != MBE; ++MBB) |
| 2915 | for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(), |
| 2916 | ME = (*MBB)->instr_rend(); |
| 2917 | MI != ME;) { |
| 2918 | // From DeadMachineInstructionElem. Don't delete inline assembly. |
| 2919 | if (MI->isInlineAsm()) { |
| 2920 | ++MI; |
| 2921 | continue; |
| 2922 | } |
| 2923 | bool SawStore = false; |
| 2924 | // Check if it's safe to remove the instruction due to side effects. |
| 2925 | // We can, and want to, remove Phis here. |
| 2926 | if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) { |
| 2927 | ++MI; |
| 2928 | continue; |
| 2929 | } |
| 2930 | bool used = true; |
| 2931 | for (MachineInstr::mop_iterator MOI = MI->operands_begin(), |
| 2932 | MOE = MI->operands_end(); |
| 2933 | MOI != MOE; ++MOI) { |
| 2934 | if (!MOI->isReg() || !MOI->isDef()) |
| 2935 | continue; |
| 2936 | unsigned reg = MOI->getReg(); |
| 2937 | unsigned realUses = 0; |
| 2938 | for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg), |
| 2939 | EI = MRI.use_end(); |
| 2940 | UI != EI; ++UI) { |
| 2941 | // Check if there are any uses that occur only in the original |
| 2942 | // loop. If so, that's not a real use. |
| 2943 | if (UI->getParent()->getParent() != BB) { |
| 2944 | realUses++; |
| 2945 | used = true; |
| 2946 | break; |
| 2947 | } |
| 2948 | } |
| 2949 | if (realUses > 0) |
| 2950 | break; |
| 2951 | used = false; |
| 2952 | } |
| 2953 | if (!used) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 2954 | LIS.RemoveMachineInstrFromMaps(*MI); |
Duncan P. N. Exon Smith | 5c001c3 | 2016-08-30 00:13:12 +0000 | [diff] [blame] | 2955 | MI++->eraseFromParent(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2956 | continue; |
| 2957 | } |
| 2958 | ++MI; |
| 2959 | } |
| 2960 | // In the kernel block, check if we can remove a Phi that generates a value |
| 2961 | // used in an instruction removed in the epilog block. |
| 2962 | for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(), |
| 2963 | BBE = KernelBB->getFirstNonPHI(); |
| 2964 | BBI != BBE;) { |
| 2965 | MachineInstr *MI = &*BBI; |
| 2966 | ++BBI; |
| 2967 | unsigned reg = MI->getOperand(0).getReg(); |
| 2968 | if (MRI.use_begin(reg) == MRI.use_end()) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 2969 | LIS.RemoveMachineInstrFromMaps(*MI); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2970 | MI->eraseFromParent(); |
| 2971 | } |
| 2972 | } |
| 2973 | } |
| 2974 | |
| 2975 | /// For loop carried definitions, we split the lifetime of a virtual register |
| 2976 | /// that has uses past the definition in the next iteration. A copy with a new |
| 2977 | /// virtual register is inserted before the definition, which helps with |
| 2978 | /// generating a better register assignment. |
| 2979 | /// |
| 2980 | /// v1 = phi(a, v2) v1 = phi(a, v2) |
| 2981 | /// v2 = phi(b, v3) v2 = phi(b, v3) |
| 2982 | /// v3 = .. v4 = copy v1 |
| 2983 | /// .. = V1 v3 = .. |
| 2984 | /// .. = v4 |
| 2985 | void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB, |
| 2986 | MBBVectorTy &EpilogBBs, |
| 2987 | SMSchedule &Schedule) { |
| 2988 | const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); |
Bob Wilson | 90ecac0 | 2018-01-04 02:58:15 +0000 | [diff] [blame] | 2989 | for (auto &PHI : KernelBB->phis()) { |
| 2990 | unsigned Def = PHI.getOperand(0).getReg(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2991 | // Check for any Phi definition that used as an operand of another Phi |
| 2992 | // in the same block. |
| 2993 | for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def), |
| 2994 | E = MRI.use_instr_end(); |
| 2995 | I != E; ++I) { |
| 2996 | if (I->isPHI() && I->getParent() == KernelBB) { |
| 2997 | // Get the loop carried definition. |
Bob Wilson | 90ecac0 | 2018-01-04 02:58:15 +0000 | [diff] [blame] | 2998 | unsigned LCDef = getLoopPhiReg(PHI, KernelBB); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 2999 | if (!LCDef) |
| 3000 | continue; |
| 3001 | MachineInstr *MI = MRI.getVRegDef(LCDef); |
| 3002 | if (!MI || MI->getParent() != KernelBB || MI->isPHI()) |
| 3003 | continue; |
| 3004 | // Search through the rest of the block looking for uses of the Phi |
| 3005 | // definition. If one occurs, then split the lifetime. |
| 3006 | unsigned SplitReg = 0; |
| 3007 | for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI), |
| 3008 | KernelBB->instr_end())) |
| 3009 | if (BBJ.readsRegister(Def)) { |
| 3010 | // We split the lifetime when we find the first use. |
| 3011 | if (SplitReg == 0) { |
| 3012 | SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def)); |
| 3013 | BuildMI(*KernelBB, MI, MI->getDebugLoc(), |
| 3014 | TII->get(TargetOpcode::COPY), SplitReg) |
| 3015 | .addReg(Def); |
| 3016 | } |
| 3017 | BBJ.substituteRegister(Def, SplitReg, 0, *TRI); |
| 3018 | } |
| 3019 | if (!SplitReg) |
| 3020 | continue; |
| 3021 | // Search through each of the epilog blocks for any uses to be renamed. |
| 3022 | for (auto &Epilog : EpilogBBs) |
| 3023 | for (auto &I : *Epilog) |
| 3024 | if (I.readsRegister(Def)) |
| 3025 | I.substituteRegister(Def, SplitReg, 0, *TRI); |
| 3026 | break; |
| 3027 | } |
| 3028 | } |
| 3029 | } |
| 3030 | } |
| 3031 | |
| 3032 | /// Remove the incoming block from the Phis in a basic block. |
| 3033 | static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) { |
| 3034 | for (MachineInstr &MI : *BB) { |
| 3035 | if (!MI.isPHI()) |
| 3036 | break; |
| 3037 | for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) |
| 3038 | if (MI.getOperand(i + 1).getMBB() == Incoming) { |
| 3039 | MI.RemoveOperand(i + 1); |
| 3040 | MI.RemoveOperand(i); |
| 3041 | break; |
| 3042 | } |
| 3043 | } |
| 3044 | } |
| 3045 | |
| 3046 | /// Create branches from each prolog basic block to the appropriate epilog |
| 3047 | /// block. These edges are needed if the loop ends before reaching the |
| 3048 | /// kernel. |
| 3049 | void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs, |
| 3050 | MachineBasicBlock *KernelBB, |
| 3051 | MBBVectorTy &EpilogBBs, |
| 3052 | SMSchedule &Schedule, ValueMapTy *VRMap) { |
| 3053 | assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch"); |
| 3054 | MachineInstr *IndVar = Pass.LI.LoopInductionVar; |
| 3055 | MachineInstr *Cmp = Pass.LI.LoopCompare; |
| 3056 | MachineBasicBlock *LastPro = KernelBB; |
| 3057 | MachineBasicBlock *LastEpi = KernelBB; |
| 3058 | |
| 3059 | // Start from the blocks connected to the kernel and work "out" |
| 3060 | // to the first prolog and the last epilog blocks. |
| 3061 | SmallVector<MachineInstr *, 4> PrevInsts; |
| 3062 | unsigned MaxIter = PrologBBs.size() - 1; |
| 3063 | unsigned LC = UINT_MAX; |
| 3064 | unsigned LCMin = UINT_MAX; |
| 3065 | for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) { |
| 3066 | // Add branches to the prolog that go to the corresponding |
| 3067 | // epilog, and the fall-thru prolog/kernel block. |
| 3068 | MachineBasicBlock *Prolog = PrologBBs[j]; |
| 3069 | MachineBasicBlock *Epilog = EpilogBBs[i]; |
| 3070 | // We've executed one iteration, so decrement the loop count and check for |
| 3071 | // the loop end. |
| 3072 | SmallVector<MachineOperand, 4> Cond; |
| 3073 | // Check if the LOOP0 has already been removed. If so, then there is no need |
| 3074 | // to reduce the trip count. |
| 3075 | if (LC != 0) |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3076 | LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j, |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3077 | MaxIter); |
| 3078 | |
| 3079 | // Record the value of the first trip count, which is used to determine if |
| 3080 | // branches and blocks can be removed for constant trip counts. |
| 3081 | if (LCMin == UINT_MAX) |
| 3082 | LCMin = LC; |
| 3083 | |
| 3084 | unsigned numAdded = 0; |
| 3085 | if (TargetRegisterInfo::isVirtualRegister(LC)) { |
| 3086 | Prolog->addSuccessor(Epilog); |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 3087 | numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc()); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3088 | } else if (j >= LCMin) { |
| 3089 | Prolog->addSuccessor(Epilog); |
| 3090 | Prolog->removeSuccessor(LastPro); |
| 3091 | LastEpi->removeSuccessor(Epilog); |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 3092 | numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc()); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3093 | removePhis(Epilog, LastEpi); |
| 3094 | // Remove the blocks that are no longer referenced. |
| 3095 | if (LastPro != LastEpi) { |
| 3096 | LastEpi->clear(); |
| 3097 | LastEpi->eraseFromParent(); |
| 3098 | } |
| 3099 | LastPro->clear(); |
| 3100 | LastPro->eraseFromParent(); |
| 3101 | } else { |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 3102 | numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc()); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3103 | removePhis(Epilog, Prolog); |
| 3104 | } |
| 3105 | LastPro = Prolog; |
| 3106 | LastEpi = Epilog; |
| 3107 | for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(), |
| 3108 | E = Prolog->instr_rend(); |
| 3109 | I != E && numAdded > 0; ++I, --numAdded) |
| 3110 | updateInstruction(&*I, false, j, 0, Schedule, VRMap); |
| 3111 | } |
| 3112 | } |
| 3113 | |
| 3114 | /// Return true if we can compute the amount the instruction changes |
| 3115 | /// during each iteration. Set Delta to the amount of the change. |
| 3116 | bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) { |
| 3117 | const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); |
| 3118 | unsigned BaseReg; |
| 3119 | int64_t Offset; |
| 3120 | if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI)) |
| 3121 | return false; |
| 3122 | |
| 3123 | MachineRegisterInfo &MRI = MF.getRegInfo(); |
| 3124 | // Check if there is a Phi. If so, get the definition in the loop. |
| 3125 | MachineInstr *BaseDef = MRI.getVRegDef(BaseReg); |
| 3126 | if (BaseDef && BaseDef->isPHI()) { |
| 3127 | BaseReg = getLoopPhiReg(*BaseDef, MI.getParent()); |
| 3128 | BaseDef = MRI.getVRegDef(BaseReg); |
| 3129 | } |
| 3130 | if (!BaseDef) |
| 3131 | return false; |
| 3132 | |
| 3133 | int D = 0; |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3134 | if (!TII->getIncrementValue(*BaseDef, D) && D >= 0) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3135 | return false; |
| 3136 | |
| 3137 | Delta = D; |
| 3138 | return true; |
| 3139 | } |
| 3140 | |
| 3141 | /// Update the memory operand with a new offset when the pipeliner |
Justin Lebar | cf56e92 | 2016-08-12 23:58:19 +0000 | [diff] [blame] | 3142 | /// generates a new copy of the instruction that refers to a |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3143 | /// different memory location. |
| 3144 | void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI, |
| 3145 | MachineInstr &OldMI, unsigned Num) { |
| 3146 | if (Num == 0) |
| 3147 | return; |
| 3148 | // If the instruction has memory operands, then adjust the offset |
| 3149 | // when the instruction appears in different stages. |
| 3150 | unsigned NumRefs = NewMI.memoperands_end() - NewMI.memoperands_begin(); |
| 3151 | if (NumRefs == 0) |
| 3152 | return; |
| 3153 | MachineInstr::mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NumRefs); |
| 3154 | unsigned Refs = 0; |
Justin Lebar | 0a33a7a | 2016-08-23 17:18:07 +0000 | [diff] [blame] | 3155 | for (MachineMemOperand *MMO : NewMI.memoperands()) { |
Justin Lebar | adbf09e | 2016-09-11 01:38:58 +0000 | [diff] [blame] | 3156 | if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) || |
| 3157 | (!MMO->getValue())) { |
Justin Lebar | 0a33a7a | 2016-08-23 17:18:07 +0000 | [diff] [blame] | 3158 | NewMemRefs[Refs++] = MMO; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3159 | continue; |
| 3160 | } |
| 3161 | unsigned Delta; |
Krzysztof Parzyszek | 785b6ce | 2018-03-26 15:45:55 +0000 | [diff] [blame^] | 3162 | if (Num != UINT_MAX && computeDelta(OldMI, Delta)) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3163 | int64_t AdjOffset = Delta * Num; |
| 3164 | NewMemRefs[Refs++] = |
Justin Lebar | 0a33a7a | 2016-08-23 17:18:07 +0000 | [diff] [blame] | 3165 | MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()); |
Krzysztof Parzyszek | 2d79017 | 2018-02-27 22:40:52 +0000 | [diff] [blame] | 3166 | } else { |
| 3167 | NewMI.dropMemRefs(); |
| 3168 | return; |
| 3169 | } |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3170 | } |
| 3171 | NewMI.setMemRefs(NewMemRefs, NewMemRefs + NumRefs); |
| 3172 | } |
| 3173 | |
| 3174 | /// Clone the instruction for the new pipelined loop and update the |
| 3175 | /// memory operands, if needed. |
| 3176 | MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI, |
| 3177 | unsigned CurStageNum, |
| 3178 | unsigned InstStageNum) { |
| 3179 | MachineInstr *NewMI = MF.CloneMachineInstr(OldMI); |
| 3180 | // Check for tied operands in inline asm instructions. This should be handled |
| 3181 | // elsewhere, but I'm not sure of the best solution. |
| 3182 | if (OldMI->isInlineAsm()) |
| 3183 | for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) { |
| 3184 | const auto &MO = OldMI->getOperand(i); |
| 3185 | if (MO.isReg() && MO.isUse()) |
| 3186 | break; |
| 3187 | unsigned UseIdx; |
| 3188 | if (OldMI->isRegTiedToUseOperand(i, &UseIdx)) |
| 3189 | NewMI->tieOperands(i, UseIdx); |
| 3190 | } |
| 3191 | updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum); |
| 3192 | return NewMI; |
| 3193 | } |
| 3194 | |
| 3195 | /// Clone the instruction for the new pipelined loop. If needed, this |
| 3196 | /// function updates the instruction using the values saved in the |
| 3197 | /// InstrChanges structure. |
| 3198 | MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI, |
| 3199 | unsigned CurStageNum, |
| 3200 | unsigned InstStageNum, |
| 3201 | SMSchedule &Schedule) { |
| 3202 | MachineInstr *NewMI = MF.CloneMachineInstr(OldMI); |
| 3203 | DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = |
| 3204 | InstrChanges.find(getSUnit(OldMI)); |
| 3205 | if (It != InstrChanges.end()) { |
| 3206 | std::pair<unsigned, int64_t> RegAndOffset = It->second; |
| 3207 | unsigned BasePos, OffsetPos; |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3208 | if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3209 | return nullptr; |
| 3210 | int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm(); |
| 3211 | MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first); |
| 3212 | if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum) |
| 3213 | NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum); |
| 3214 | NewMI->getOperand(OffsetPos).setImm(NewOffset); |
| 3215 | } |
| 3216 | updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum); |
| 3217 | return NewMI; |
| 3218 | } |
| 3219 | |
| 3220 | /// Update the machine instruction with new virtual registers. This |
| 3221 | /// function may change the defintions and/or uses. |
| 3222 | void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef, |
| 3223 | unsigned CurStageNum, |
| 3224 | unsigned InstrStageNum, |
| 3225 | SMSchedule &Schedule, |
| 3226 | ValueMapTy *VRMap) { |
| 3227 | for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) { |
| 3228 | MachineOperand &MO = NewMI->getOperand(i); |
| 3229 | if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg())) |
| 3230 | continue; |
| 3231 | unsigned reg = MO.getReg(); |
| 3232 | if (MO.isDef()) { |
| 3233 | // Create a new virtual register for the definition. |
| 3234 | const TargetRegisterClass *RC = MRI.getRegClass(reg); |
| 3235 | unsigned NewReg = MRI.createVirtualRegister(RC); |
| 3236 | MO.setReg(NewReg); |
| 3237 | VRMap[CurStageNum][reg] = NewReg; |
| 3238 | if (LastDef) |
| 3239 | replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS); |
| 3240 | } else if (MO.isUse()) { |
| 3241 | MachineInstr *Def = MRI.getVRegDef(reg); |
| 3242 | // Compute the stage that contains the last definition for instruction. |
| 3243 | int DefStageNum = Schedule.stageScheduled(getSUnit(Def)); |
| 3244 | unsigned StageNum = CurStageNum; |
| 3245 | if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) { |
| 3246 | // Compute the difference in stages between the defintion and the use. |
| 3247 | unsigned StageDiff = (InstrStageNum - DefStageNum); |
| 3248 | // Make an adjustment to get the last definition. |
| 3249 | StageNum -= StageDiff; |
| 3250 | } |
| 3251 | if (VRMap[StageNum].count(reg)) |
| 3252 | MO.setReg(VRMap[StageNum][reg]); |
| 3253 | } |
| 3254 | } |
| 3255 | } |
| 3256 | |
| 3257 | /// Return the instruction in the loop that defines the register. |
| 3258 | /// If the definition is a Phi, then follow the Phi operand to |
| 3259 | /// the instruction in the loop. |
| 3260 | MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) { |
| 3261 | SmallPtrSet<MachineInstr *, 8> Visited; |
| 3262 | MachineInstr *Def = MRI.getVRegDef(Reg); |
| 3263 | while (Def->isPHI()) { |
| 3264 | if (!Visited.insert(Def).second) |
| 3265 | break; |
| 3266 | for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) |
| 3267 | if (Def->getOperand(i + 1).getMBB() == BB) { |
| 3268 | Def = MRI.getVRegDef(Def->getOperand(i).getReg()); |
| 3269 | break; |
| 3270 | } |
| 3271 | } |
| 3272 | return Def; |
| 3273 | } |
| 3274 | |
| 3275 | /// Return the new name for the value from the previous stage. |
| 3276 | unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage, |
| 3277 | unsigned LoopVal, unsigned LoopStage, |
| 3278 | ValueMapTy *VRMap, |
| 3279 | MachineBasicBlock *BB) { |
| 3280 | unsigned PrevVal = 0; |
| 3281 | if (StageNum > PhiStage) { |
| 3282 | MachineInstr *LoopInst = MRI.getVRegDef(LoopVal); |
| 3283 | if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal)) |
| 3284 | // The name is defined in the previous stage. |
| 3285 | PrevVal = VRMap[StageNum - 1][LoopVal]; |
| 3286 | else if (VRMap[StageNum].count(LoopVal)) |
| 3287 | // The previous name is defined in the current stage when the instruction |
| 3288 | // order is swapped. |
| 3289 | PrevVal = VRMap[StageNum][LoopVal]; |
Krzysztof Parzyszek | df24da2 | 2016-12-22 18:49:55 +0000 | [diff] [blame] | 3290 | else if (!LoopInst->isPHI() || LoopInst->getParent() != BB) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3291 | // The loop value hasn't yet been scheduled. |
| 3292 | PrevVal = LoopVal; |
| 3293 | else if (StageNum == PhiStage + 1) |
| 3294 | // The loop value is another phi, which has not been scheduled. |
| 3295 | PrevVal = getInitPhiReg(*LoopInst, BB); |
| 3296 | else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB) |
| 3297 | // The loop value is another phi, which has been scheduled. |
| 3298 | PrevVal = |
| 3299 | getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB), |
| 3300 | LoopStage, VRMap, BB); |
| 3301 | } |
| 3302 | return PrevVal; |
| 3303 | } |
| 3304 | |
| 3305 | /// Rewrite the Phi values in the specified block to use the mappings |
| 3306 | /// from the initial operand. Once the Phi is scheduled, we switch |
| 3307 | /// to using the loop value instead of the Phi value, so those names |
| 3308 | /// do not need to be rewritten. |
| 3309 | void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB, |
| 3310 | unsigned StageNum, |
| 3311 | SMSchedule &Schedule, |
| 3312 | ValueMapTy *VRMap, |
| 3313 | InstrMapTy &InstrMap) { |
Bob Wilson | 90ecac0 | 2018-01-04 02:58:15 +0000 | [diff] [blame] | 3314 | for (auto &PHI : BB->phis()) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3315 | unsigned InitVal = 0; |
| 3316 | unsigned LoopVal = 0; |
Bob Wilson | 90ecac0 | 2018-01-04 02:58:15 +0000 | [diff] [blame] | 3317 | getPhiRegs(PHI, BB, InitVal, LoopVal); |
| 3318 | unsigned PhiDef = PHI.getOperand(0).getReg(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3319 | |
| 3320 | unsigned PhiStage = |
| 3321 | (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef))); |
| 3322 | unsigned LoopStage = |
| 3323 | (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal))); |
| 3324 | unsigned NumPhis = Schedule.getStagesForPhi(PhiDef); |
| 3325 | if (NumPhis > StageNum) |
| 3326 | NumPhis = StageNum; |
| 3327 | for (unsigned np = 0; np <= NumPhis; ++np) { |
| 3328 | unsigned NewVal = |
| 3329 | getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB); |
| 3330 | if (!NewVal) |
| 3331 | NewVal = InitVal; |
Bob Wilson | 90ecac0 | 2018-01-04 02:58:15 +0000 | [diff] [blame] | 3332 | rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI, |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3333 | PhiDef, NewVal); |
| 3334 | } |
| 3335 | } |
| 3336 | } |
| 3337 | |
| 3338 | /// Rewrite a previously scheduled instruction to use the register value |
| 3339 | /// from the new instruction. Make sure the instruction occurs in the |
| 3340 | /// basic block, and we don't change the uses in the new instruction. |
| 3341 | void SwingSchedulerDAG::rewriteScheduledInstr( |
| 3342 | MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap, |
| 3343 | unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg, |
| 3344 | unsigned NewReg, unsigned PrevReg) { |
| 3345 | bool InProlog = (CurStageNum < Schedule.getMaxStageCount()); |
| 3346 | int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum; |
| 3347 | // Rewrite uses that have been scheduled already to use the new |
| 3348 | // Phi register. |
| 3349 | for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg), |
| 3350 | EI = MRI.use_end(); |
| 3351 | UI != EI;) { |
| 3352 | MachineOperand &UseOp = *UI; |
| 3353 | MachineInstr *UseMI = UseOp.getParent(); |
| 3354 | ++UI; |
| 3355 | if (UseMI->getParent() != BB) |
| 3356 | continue; |
| 3357 | if (UseMI->isPHI()) { |
| 3358 | if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg) |
| 3359 | continue; |
| 3360 | if (getLoopPhiReg(*UseMI, BB) != OldReg) |
| 3361 | continue; |
| 3362 | } |
| 3363 | InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI); |
| 3364 | assert(OrigInstr != InstrMap.end() && "Instruction not scheduled."); |
| 3365 | SUnit *OrigMISU = getSUnit(OrigInstr->second); |
| 3366 | int StageSched = Schedule.stageScheduled(OrigMISU); |
| 3367 | int CycleSched = Schedule.cycleScheduled(OrigMISU); |
| 3368 | unsigned ReplaceReg = 0; |
| 3369 | // This is the stage for the scheduled instruction. |
| 3370 | if (StagePhi == StageSched && Phi->isPHI()) { |
| 3371 | int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi)); |
| 3372 | if (PrevReg && InProlog) |
| 3373 | ReplaceReg = PrevReg; |
| 3374 | else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) && |
| 3375 | (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI())) |
| 3376 | ReplaceReg = PrevReg; |
| 3377 | else |
| 3378 | ReplaceReg = NewReg; |
| 3379 | } |
| 3380 | // The scheduled instruction occurs before the scheduled Phi, and the |
| 3381 | // Phi is not loop carried. |
| 3382 | if (!InProlog && StagePhi + 1 == StageSched && |
| 3383 | !Schedule.isLoopCarried(this, *Phi)) |
| 3384 | ReplaceReg = NewReg; |
| 3385 | if (StagePhi > StageSched && Phi->isPHI()) |
| 3386 | ReplaceReg = NewReg; |
| 3387 | if (!InProlog && !Phi->isPHI() && StagePhi < StageSched) |
| 3388 | ReplaceReg = NewReg; |
| 3389 | if (ReplaceReg) { |
| 3390 | MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg)); |
| 3391 | UseOp.setReg(ReplaceReg); |
| 3392 | } |
| 3393 | } |
| 3394 | } |
| 3395 | |
| 3396 | /// Check if we can change the instruction to use an offset value from the |
| 3397 | /// previous iteration. If so, return true and set the base and offset values |
| 3398 | /// so that we can rewrite the load, if necessary. |
| 3399 | /// v1 = Phi(v0, v3) |
| 3400 | /// v2 = load v1, 0 |
| 3401 | /// v3 = post_store v1, 4, x |
| 3402 | /// This function enables the load to be rewritten as v2 = load v3, 4. |
| 3403 | bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI, |
| 3404 | unsigned &BasePos, |
| 3405 | unsigned &OffsetPos, |
| 3406 | unsigned &NewBase, |
| 3407 | int64_t &Offset) { |
| 3408 | // Get the load instruction. |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3409 | if (TII->isPostIncrement(*MI)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3410 | return false; |
| 3411 | unsigned BasePosLd, OffsetPosLd; |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3412 | if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3413 | return false; |
| 3414 | unsigned BaseReg = MI->getOperand(BasePosLd).getReg(); |
| 3415 | |
| 3416 | // Look for the Phi instruction. |
Justin Bogner | fdf9bf4 | 2017-10-10 23:50:49 +0000 | [diff] [blame] | 3417 | MachineRegisterInfo &MRI = MI->getMF()->getRegInfo(); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3418 | MachineInstr *Phi = MRI.getVRegDef(BaseReg); |
| 3419 | if (!Phi || !Phi->isPHI()) |
| 3420 | return false; |
| 3421 | // Get the register defined in the loop block. |
| 3422 | unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent()); |
| 3423 | if (!PrevReg) |
| 3424 | return false; |
| 3425 | |
| 3426 | // Check for the post-increment load/store instruction. |
| 3427 | MachineInstr *PrevDef = MRI.getVRegDef(PrevReg); |
| 3428 | if (!PrevDef || PrevDef == MI) |
| 3429 | return false; |
| 3430 | |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3431 | if (!TII->isPostIncrement(*PrevDef)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3432 | return false; |
| 3433 | |
| 3434 | unsigned BasePos1 = 0, OffsetPos1 = 0; |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3435 | if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3436 | return false; |
| 3437 | |
| 3438 | // Make sure offset values are both positive or both negative. |
| 3439 | int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm(); |
| 3440 | int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm(); |
| 3441 | if ((LoadOffset >= 0) != (StoreOffset >= 0)) |
| 3442 | return false; |
| 3443 | |
| 3444 | // Set the return value once we determine that we return true. |
| 3445 | BasePos = BasePosLd; |
| 3446 | OffsetPos = OffsetPosLd; |
| 3447 | NewBase = PrevReg; |
| 3448 | Offset = StoreOffset; |
| 3449 | return true; |
| 3450 | } |
| 3451 | |
| 3452 | /// Apply changes to the instruction if needed. The changes are need |
| 3453 | /// to improve the scheduling and depend up on the final schedule. |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 3454 | void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI, |
| 3455 | SMSchedule &Schedule) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3456 | SUnit *SU = getSUnit(MI); |
| 3457 | DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = |
| 3458 | InstrChanges.find(SU); |
| 3459 | if (It != InstrChanges.end()) { |
| 3460 | std::pair<unsigned, int64_t> RegAndOffset = It->second; |
| 3461 | unsigned BasePos, OffsetPos; |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3462 | if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 3463 | return; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3464 | unsigned BaseReg = MI->getOperand(BasePos).getReg(); |
| 3465 | MachineInstr *LoopDef = findDefInLoop(BaseReg); |
| 3466 | int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef)); |
| 3467 | int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef)); |
| 3468 | int BaseStageNum = Schedule.stageScheduled(SU); |
| 3469 | int BaseCycleNum = Schedule.cycleScheduled(SU); |
| 3470 | if (BaseStageNum < DefStageNum) { |
| 3471 | MachineInstr *NewMI = MF.CloneMachineInstr(MI); |
| 3472 | int OffsetDiff = DefStageNum - BaseStageNum; |
| 3473 | if (DefCycleNum < BaseCycleNum) { |
| 3474 | NewMI->getOperand(BasePos).setReg(RegAndOffset.first); |
| 3475 | if (OffsetDiff > 0) |
| 3476 | --OffsetDiff; |
| 3477 | } |
| 3478 | int64_t NewOffset = |
| 3479 | MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff; |
| 3480 | NewMI->getOperand(OffsetPos).setImm(NewOffset); |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 3481 | SU->setInstr(NewMI); |
| 3482 | MISUnitMap[NewMI] = SU; |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3483 | NewMIs.insert(NewMI); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3484 | } |
| 3485 | } |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3486 | } |
| 3487 | |
| 3488 | /// Return true for an order dependence that is loop carried potentially. |
| 3489 | /// An order dependence is loop carried if the destination defines a value |
| 3490 | /// that may be used by the source in a subsequent iteration. |
| 3491 | bool SwingSchedulerDAG::isLoopCarriedOrder(SUnit *Source, const SDep &Dep, |
| 3492 | bool isSucc) { |
| 3493 | if (!isOrder(Source, Dep) || Dep.isArtificial()) |
| 3494 | return false; |
| 3495 | |
| 3496 | if (!SwpPruneLoopCarried) |
| 3497 | return true; |
| 3498 | |
| 3499 | MachineInstr *SI = Source->getInstr(); |
| 3500 | MachineInstr *DI = Dep.getSUnit()->getInstr(); |
| 3501 | if (!isSucc) |
| 3502 | std::swap(SI, DI); |
| 3503 | assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI."); |
| 3504 | |
| 3505 | // Assume ordered loads and stores may have a loop carried dependence. |
| 3506 | if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() || |
| 3507 | SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef()) |
| 3508 | return true; |
| 3509 | |
| 3510 | // Only chain dependences between a load and store can be loop carried. |
| 3511 | if (!DI->mayStore() || !SI->mayLoad()) |
| 3512 | return false; |
| 3513 | |
| 3514 | unsigned DeltaS, DeltaD; |
| 3515 | if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD)) |
| 3516 | return true; |
| 3517 | |
| 3518 | unsigned BaseRegS, BaseRegD; |
| 3519 | int64_t OffsetS, OffsetD; |
| 3520 | const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); |
| 3521 | if (!TII->getMemOpBaseRegImmOfs(*SI, BaseRegS, OffsetS, TRI) || |
| 3522 | !TII->getMemOpBaseRegImmOfs(*DI, BaseRegD, OffsetD, TRI)) |
| 3523 | return true; |
| 3524 | |
| 3525 | if (BaseRegS != BaseRegD) |
| 3526 | return true; |
| 3527 | |
| 3528 | uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize(); |
| 3529 | uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize(); |
| 3530 | |
| 3531 | // This is the main test, which checks the offset values and the loop |
| 3532 | // increment value to determine if the accesses may be loop carried. |
| 3533 | if (OffsetS >= OffsetD) |
| 3534 | return OffsetS + AccessSizeS > DeltaS; |
Simon Pilgrim | fbfb19b | 2017-03-16 19:52:00 +0000 | [diff] [blame] | 3535 | else |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3536 | return OffsetD + AccessSizeD > DeltaD; |
| 3537 | |
| 3538 | return true; |
| 3539 | } |
| 3540 | |
Krzysztof Parzyszek | 8839124 | 2016-12-22 19:21:20 +0000 | [diff] [blame] | 3541 | void SwingSchedulerDAG::postprocessDAG() { |
| 3542 | for (auto &M : Mutations) |
| 3543 | M->apply(this); |
| 3544 | } |
| 3545 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3546 | /// Try to schedule the node at the specified StartCycle and continue |
| 3547 | /// until the node is schedule or the EndCycle is reached. This function |
| 3548 | /// returns true if the node is scheduled. This routine may search either |
| 3549 | /// forward or backward for a place to insert the instruction based upon |
| 3550 | /// the relative values of StartCycle and EndCycle. |
| 3551 | bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) { |
| 3552 | bool forward = true; |
| 3553 | if (StartCycle > EndCycle) |
| 3554 | forward = false; |
| 3555 | |
| 3556 | // The terminating condition depends on the direction. |
| 3557 | int termCycle = forward ? EndCycle + 1 : EndCycle - 1; |
| 3558 | for (int curCycle = StartCycle; curCycle != termCycle; |
| 3559 | forward ? ++curCycle : --curCycle) { |
| 3560 | |
| 3561 | // Add the already scheduled instructions at the specified cycle to the DFA. |
| 3562 | Resources->clearResources(); |
| 3563 | for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II); |
| 3564 | checkCycle <= LastCycle; checkCycle += II) { |
| 3565 | std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle]; |
| 3566 | |
| 3567 | for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(), |
| 3568 | E = cycleInstrs.end(); |
| 3569 | I != E; ++I) { |
| 3570 | if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode())) |
| 3571 | continue; |
| 3572 | assert(Resources->canReserveResources(*(*I)->getInstr()) && |
| 3573 | "These instructions have already been scheduled."); |
| 3574 | Resources->reserveResources(*(*I)->getInstr()); |
| 3575 | } |
| 3576 | } |
| 3577 | if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) || |
| 3578 | Resources->canReserveResources(*SU->getInstr())) { |
| 3579 | DEBUG({ |
| 3580 | dbgs() << "\tinsert at cycle " << curCycle << " "; |
| 3581 | SU->getInstr()->dump(); |
| 3582 | }); |
| 3583 | |
| 3584 | ScheduledInstrs[curCycle].push_back(SU); |
| 3585 | InstrToCycle.insert(std::make_pair(SU, curCycle)); |
| 3586 | if (curCycle > LastCycle) |
| 3587 | LastCycle = curCycle; |
| 3588 | if (curCycle < FirstCycle) |
| 3589 | FirstCycle = curCycle; |
| 3590 | return true; |
| 3591 | } |
| 3592 | DEBUG({ |
| 3593 | dbgs() << "\tfailed to insert at cycle " << curCycle << " "; |
| 3594 | SU->getInstr()->dump(); |
| 3595 | }); |
| 3596 | } |
| 3597 | return false; |
| 3598 | } |
| 3599 | |
| 3600 | // Return the cycle of the earliest scheduled instruction in the chain. |
| 3601 | int SMSchedule::earliestCycleInChain(const SDep &Dep) { |
| 3602 | SmallPtrSet<SUnit *, 8> Visited; |
| 3603 | SmallVector<SDep, 8> Worklist; |
| 3604 | Worklist.push_back(Dep); |
| 3605 | int EarlyCycle = INT_MAX; |
| 3606 | while (!Worklist.empty()) { |
| 3607 | const SDep &Cur = Worklist.pop_back_val(); |
| 3608 | SUnit *PrevSU = Cur.getSUnit(); |
| 3609 | if (Visited.count(PrevSU)) |
| 3610 | continue; |
| 3611 | std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU); |
| 3612 | if (it == InstrToCycle.end()) |
| 3613 | continue; |
| 3614 | EarlyCycle = std::min(EarlyCycle, it->second); |
| 3615 | for (const auto &PI : PrevSU->Preds) |
| 3616 | if (SwingSchedulerDAG::isOrder(PrevSU, PI)) |
| 3617 | Worklist.push_back(PI); |
| 3618 | Visited.insert(PrevSU); |
| 3619 | } |
| 3620 | return EarlyCycle; |
| 3621 | } |
| 3622 | |
| 3623 | // Return the cycle of the latest scheduled instruction in the chain. |
| 3624 | int SMSchedule::latestCycleInChain(const SDep &Dep) { |
| 3625 | SmallPtrSet<SUnit *, 8> Visited; |
| 3626 | SmallVector<SDep, 8> Worklist; |
| 3627 | Worklist.push_back(Dep); |
| 3628 | int LateCycle = INT_MIN; |
| 3629 | while (!Worklist.empty()) { |
| 3630 | const SDep &Cur = Worklist.pop_back_val(); |
| 3631 | SUnit *SuccSU = Cur.getSUnit(); |
| 3632 | if (Visited.count(SuccSU)) |
| 3633 | continue; |
| 3634 | std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU); |
| 3635 | if (it == InstrToCycle.end()) |
| 3636 | continue; |
| 3637 | LateCycle = std::max(LateCycle, it->second); |
| 3638 | for (const auto &SI : SuccSU->Succs) |
| 3639 | if (SwingSchedulerDAG::isOrder(SuccSU, SI)) |
| 3640 | Worklist.push_back(SI); |
| 3641 | Visited.insert(SuccSU); |
| 3642 | } |
| 3643 | return LateCycle; |
| 3644 | } |
| 3645 | |
| 3646 | /// If an instruction has a use that spans multiple iterations, then |
| 3647 | /// return true. These instructions are characterized by having a back-ege |
| 3648 | /// to a Phi, which contains a reference to another Phi. |
| 3649 | static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) { |
| 3650 | for (auto &P : SU->Preds) |
| 3651 | if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI()) |
| 3652 | for (auto &S : P.getSUnit()->Succs) |
| 3653 | if (S.getKind() == SDep::Order && S.getSUnit()->getInstr()->isPHI()) |
| 3654 | return P.getSUnit(); |
| 3655 | return nullptr; |
| 3656 | } |
| 3657 | |
| 3658 | /// Compute the scheduling start slot for the instruction. The start slot |
| 3659 | /// depends on any predecessor or successor nodes scheduled already. |
| 3660 | void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart, |
| 3661 | int *MinEnd, int *MaxStart, int II, |
| 3662 | SwingSchedulerDAG *DAG) { |
| 3663 | // Iterate over each instruction that has been scheduled already. The start |
| 3664 | // slot computuation depends on whether the previously scheduled instruction |
| 3665 | // is a predecessor or successor of the specified instruction. |
| 3666 | for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) { |
| 3667 | |
| 3668 | // Iterate over each instruction in the current cycle. |
| 3669 | for (SUnit *I : getInstructions(cycle)) { |
| 3670 | // Because we're processing a DAG for the dependences, we recognize |
| 3671 | // the back-edge in recurrences by anti dependences. |
| 3672 | for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) { |
| 3673 | const SDep &Dep = SU->Preds[i]; |
| 3674 | if (Dep.getSUnit() == I) { |
| 3675 | if (!DAG->isBackedge(SU, Dep)) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 3676 | int EarlyStart = cycle + Dep.getLatency() - |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3677 | DAG->getDistance(Dep.getSUnit(), SU, Dep) * II; |
| 3678 | *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart); |
| 3679 | if (DAG->isLoopCarriedOrder(SU, Dep, false)) { |
| 3680 | int End = earliestCycleInChain(Dep) + (II - 1); |
| 3681 | *MinEnd = std::min(*MinEnd, End); |
| 3682 | } |
| 3683 | } else { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 3684 | int LateStart = cycle - Dep.getLatency() + |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3685 | DAG->getDistance(SU, Dep.getSUnit(), Dep) * II; |
| 3686 | *MinLateStart = std::min(*MinLateStart, LateStart); |
| 3687 | } |
| 3688 | } |
| 3689 | // For instruction that requires multiple iterations, make sure that |
| 3690 | // the dependent instruction is not scheduled past the definition. |
| 3691 | SUnit *BE = multipleIterations(I, DAG); |
| 3692 | if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() && |
| 3693 | !SU->isPred(I)) |
| 3694 | *MinLateStart = std::min(*MinLateStart, cycle); |
| 3695 | } |
| 3696 | for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) |
| 3697 | if (SU->Succs[i].getSUnit() == I) { |
| 3698 | const SDep &Dep = SU->Succs[i]; |
| 3699 | if (!DAG->isBackedge(SU, Dep)) { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 3700 | int LateStart = cycle - Dep.getLatency() + |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3701 | DAG->getDistance(SU, Dep.getSUnit(), Dep) * II; |
| 3702 | *MinLateStart = std::min(*MinLateStart, LateStart); |
| 3703 | if (DAG->isLoopCarriedOrder(SU, Dep)) { |
| 3704 | int Start = latestCycleInChain(Dep) + 1 - II; |
| 3705 | *MaxStart = std::max(*MaxStart, Start); |
| 3706 | } |
| 3707 | } else { |
Krzysztof Parzyszek | c715a5d | 2018-03-21 16:39:11 +0000 | [diff] [blame] | 3708 | int EarlyStart = cycle + Dep.getLatency() - |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3709 | DAG->getDistance(Dep.getSUnit(), SU, Dep) * II; |
| 3710 | *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart); |
| 3711 | } |
| 3712 | } |
| 3713 | } |
| 3714 | } |
| 3715 | } |
| 3716 | |
| 3717 | /// Order the instructions within a cycle so that the definitions occur |
| 3718 | /// before the uses. Returns true if the instruction is added to the start |
| 3719 | /// of the list, or false if added to the end. |
| 3720 | bool SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU, |
| 3721 | std::deque<SUnit *> &Insts) { |
| 3722 | MachineInstr *MI = SU->getInstr(); |
| 3723 | bool OrderBeforeUse = false; |
| 3724 | bool OrderAfterDef = false; |
| 3725 | bool OrderBeforeDef = false; |
| 3726 | unsigned MoveDef = 0; |
| 3727 | unsigned MoveUse = 0; |
| 3728 | int StageInst1 = stageScheduled(SU); |
| 3729 | |
| 3730 | unsigned Pos = 0; |
| 3731 | for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E; |
| 3732 | ++I, ++Pos) { |
| 3733 | // Relative order of Phis does not matter. |
| 3734 | if (MI->isPHI() && (*I)->getInstr()->isPHI()) |
| 3735 | continue; |
| 3736 | for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { |
| 3737 | MachineOperand &MO = MI->getOperand(i); |
| 3738 | if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg())) |
| 3739 | continue; |
| 3740 | unsigned Reg = MO.getReg(); |
| 3741 | unsigned BasePos, OffsetPos; |
Krzysztof Parzyszek | 8fb181c | 2016-08-01 17:55:48 +0000 | [diff] [blame] | 3742 | if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3743 | if (MI->getOperand(BasePos).getReg() == Reg) |
| 3744 | if (unsigned NewReg = SSD->getInstrBaseReg(SU)) |
| 3745 | Reg = NewReg; |
| 3746 | bool Reads, Writes; |
| 3747 | std::tie(Reads, Writes) = |
| 3748 | (*I)->getInstr()->readsWritesVirtualRegister(Reg); |
| 3749 | if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) { |
| 3750 | OrderBeforeUse = true; |
| 3751 | MoveUse = Pos; |
| 3752 | } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) { |
| 3753 | // Add the instruction after the scheduled instruction. |
| 3754 | OrderAfterDef = true; |
| 3755 | MoveDef = Pos; |
| 3756 | } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) { |
| 3757 | if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) { |
| 3758 | OrderBeforeUse = true; |
| 3759 | MoveUse = Pos; |
| 3760 | } else { |
| 3761 | OrderAfterDef = true; |
| 3762 | MoveDef = Pos; |
| 3763 | } |
| 3764 | } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) { |
| 3765 | OrderBeforeUse = true; |
| 3766 | MoveUse = Pos; |
| 3767 | if (MoveUse != 0) { |
| 3768 | OrderAfterDef = true; |
| 3769 | MoveDef = Pos - 1; |
| 3770 | } |
| 3771 | } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) { |
| 3772 | // Add the instruction before the scheduled instruction. |
| 3773 | OrderBeforeUse = true; |
| 3774 | MoveUse = Pos; |
| 3775 | } else if (MO.isUse() && stageScheduled(*I) == StageInst1 && |
| 3776 | isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) { |
| 3777 | OrderBeforeDef = true; |
| 3778 | MoveUse = Pos; |
| 3779 | } |
| 3780 | } |
| 3781 | // Check for order dependences between instructions. Make sure the source |
| 3782 | // is ordered before the destination. |
| 3783 | for (auto &S : SU->Succs) |
| 3784 | if (S.getKind() == SDep::Order) { |
| 3785 | if (S.getSUnit() == *I && stageScheduled(*I) == StageInst1) { |
| 3786 | OrderBeforeUse = true; |
| 3787 | MoveUse = Pos; |
| 3788 | } |
| 3789 | } else if (TargetRegisterInfo::isPhysicalRegister(S.getReg())) { |
| 3790 | if (cycleScheduled(SU) != cycleScheduled(S.getSUnit())) { |
| 3791 | if (S.isAssignedRegDep()) { |
| 3792 | OrderAfterDef = true; |
| 3793 | MoveDef = Pos; |
| 3794 | } |
| 3795 | } else { |
| 3796 | OrderBeforeUse = true; |
| 3797 | MoveUse = Pos; |
| 3798 | } |
| 3799 | } |
| 3800 | for (auto &P : SU->Preds) |
| 3801 | if (P.getKind() == SDep::Order) { |
| 3802 | if (P.getSUnit() == *I && stageScheduled(*I) == StageInst1) { |
| 3803 | OrderAfterDef = true; |
| 3804 | MoveDef = Pos; |
| 3805 | } |
| 3806 | } else if (TargetRegisterInfo::isPhysicalRegister(P.getReg())) { |
| 3807 | if (cycleScheduled(SU) != cycleScheduled(P.getSUnit())) { |
| 3808 | if (P.isAssignedRegDep()) { |
| 3809 | OrderBeforeUse = true; |
| 3810 | MoveUse = Pos; |
| 3811 | } |
| 3812 | } else { |
| 3813 | OrderAfterDef = true; |
| 3814 | MoveDef = Pos; |
| 3815 | } |
| 3816 | } |
| 3817 | } |
| 3818 | |
| 3819 | // A circular dependence. |
| 3820 | if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef) |
| 3821 | OrderBeforeUse = false; |
| 3822 | |
| 3823 | // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due |
| 3824 | // to a loop-carried dependence. |
| 3825 | if (OrderBeforeDef) |
| 3826 | OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef); |
| 3827 | |
| 3828 | // The uncommon case when the instruction order needs to be updated because |
| 3829 | // there is both a use and def. |
| 3830 | if (OrderBeforeUse && OrderAfterDef) { |
| 3831 | SUnit *UseSU = Insts.at(MoveUse); |
| 3832 | SUnit *DefSU = Insts.at(MoveDef); |
| 3833 | if (MoveUse > MoveDef) { |
| 3834 | Insts.erase(Insts.begin() + MoveUse); |
| 3835 | Insts.erase(Insts.begin() + MoveDef); |
| 3836 | } else { |
| 3837 | Insts.erase(Insts.begin() + MoveDef); |
| 3838 | Insts.erase(Insts.begin() + MoveUse); |
| 3839 | } |
| 3840 | if (orderDependence(SSD, UseSU, Insts)) { |
| 3841 | Insts.push_front(SU); |
| 3842 | orderDependence(SSD, DefSU, Insts); |
| 3843 | return true; |
| 3844 | } |
| 3845 | Insts.pop_back(); |
| 3846 | Insts.push_back(SU); |
| 3847 | Insts.push_back(UseSU); |
| 3848 | orderDependence(SSD, DefSU, Insts); |
| 3849 | return false; |
| 3850 | } |
| 3851 | // Put the new instruction first if there is a use in the list. Otherwise, |
| 3852 | // put it at the end of the list. |
| 3853 | if (OrderBeforeUse) |
| 3854 | Insts.push_front(SU); |
| 3855 | else |
| 3856 | Insts.push_back(SU); |
| 3857 | return OrderBeforeUse; |
| 3858 | } |
| 3859 | |
| 3860 | /// Return true if the scheduled Phi has a loop carried operand. |
| 3861 | bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) { |
| 3862 | if (!Phi.isPHI()) |
| 3863 | return false; |
| 3864 | assert(Phi.isPHI() && "Expecing a Phi."); |
| 3865 | SUnit *DefSU = SSD->getSUnit(&Phi); |
| 3866 | unsigned DefCycle = cycleScheduled(DefSU); |
| 3867 | int DefStage = stageScheduled(DefSU); |
| 3868 | |
| 3869 | unsigned InitVal = 0; |
| 3870 | unsigned LoopVal = 0; |
| 3871 | getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal); |
| 3872 | SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal)); |
| 3873 | if (!UseSU) |
| 3874 | return true; |
| 3875 | if (UseSU->getInstr()->isPHI()) |
| 3876 | return true; |
| 3877 | unsigned LoopCycle = cycleScheduled(UseSU); |
| 3878 | int LoopStage = stageScheduled(UseSU); |
Simon Pilgrim | 3d8482a | 2016-11-14 10:40:23 +0000 | [diff] [blame] | 3879 | return (LoopCycle > DefCycle) || (LoopStage <= DefStage); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3880 | } |
| 3881 | |
| 3882 | /// Return true if the instruction is a definition that is loop carried |
| 3883 | /// and defines the use on the next iteration. |
| 3884 | /// v1 = phi(v2, v3) |
| 3885 | /// (Def) v3 = op v1 |
| 3886 | /// (MO) = v1 |
| 3887 | /// If MO appears before Def, then then v1 and v3 may get assigned to the same |
| 3888 | /// register. |
| 3889 | bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, |
| 3890 | MachineInstr *Def, MachineOperand &MO) { |
| 3891 | if (!MO.isReg()) |
| 3892 | return false; |
| 3893 | if (Def->isPHI()) |
| 3894 | return false; |
| 3895 | MachineInstr *Phi = MRI.getVRegDef(MO.getReg()); |
| 3896 | if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent()) |
| 3897 | return false; |
| 3898 | if (!isLoopCarried(SSD, *Phi)) |
| 3899 | return false; |
| 3900 | unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent()); |
| 3901 | for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) { |
| 3902 | MachineOperand &DMO = Def->getOperand(i); |
| 3903 | if (!DMO.isReg() || !DMO.isDef()) |
| 3904 | continue; |
| 3905 | if (DMO.getReg() == LoopReg) |
| 3906 | return true; |
| 3907 | } |
| 3908 | return false; |
| 3909 | } |
| 3910 | |
| 3911 | // Check if the generated schedule is valid. This function checks if |
| 3912 | // an instruction that uses a physical register is scheduled in a |
| 3913 | // different stage than the definition. The pipeliner does not handle |
| 3914 | // physical register values that may cross a basic block boundary. |
| 3915 | bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) { |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3916 | for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) { |
| 3917 | SUnit &SU = SSD->SUnits[i]; |
| 3918 | if (!SU.hasPhysRegDefs) |
| 3919 | continue; |
| 3920 | int StageDef = stageScheduled(&SU); |
| 3921 | assert(StageDef != -1 && "Instruction should have been scheduled."); |
| 3922 | for (auto &SI : SU.Succs) |
| 3923 | if (SI.isAssignedRegDep()) |
Simon Pilgrim | b39236b | 2016-07-29 18:57:32 +0000 | [diff] [blame] | 3924 | if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg())) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 3925 | if (stageScheduled(SI.getSUnit()) != StageDef) |
| 3926 | return false; |
| 3927 | } |
| 3928 | return true; |
| 3929 | } |
| 3930 | |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 3931 | /// A property of the node order in swing-modulo-scheduling is |
| 3932 | /// that for nodes outside circuits the following holds: |
| 3933 | /// none of them is scheduled after both a successor and a |
| 3934 | /// predecessor. |
| 3935 | /// The method below checks whether the property is met. |
| 3936 | /// If not, debug information is printed and statistics information updated. |
| 3937 | /// Note that we do not use an assert statement. |
| 3938 | /// The reason is that although an invalid node oder may prevent |
| 3939 | /// the pipeliner from finding a pipelined schedule for arbitrary II, |
| 3940 | /// it does not lead to the generation of incorrect code. |
| 3941 | void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const { |
| 3942 | |
| 3943 | // a sorted vector that maps each SUnit to its index in the NodeOrder |
| 3944 | typedef std::pair<SUnit *, unsigned> UnitIndex; |
| 3945 | std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0)); |
| 3946 | |
| 3947 | for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) |
| 3948 | Indices.push_back(std::make_pair(NodeOrder[i], i)); |
| 3949 | |
| 3950 | auto CompareKey = [](UnitIndex i1, UnitIndex i2) { |
| 3951 | return std::get<0>(i1) < std::get<0>(i2); |
| 3952 | }; |
| 3953 | |
| 3954 | // sort, so that we can perform a binary search |
| 3955 | std::sort(Indices.begin(), Indices.end(), CompareKey); |
| 3956 | |
| 3957 | bool Valid = true; |
David L Kreitzer | febf70a | 2018-03-16 21:21:23 +0000 | [diff] [blame] | 3958 | (void)Valid; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 3959 | // for each SUnit in the NodeOrder, check whether |
| 3960 | // it appears after both a successor and a predecessor |
| 3961 | // of the SUnit. If this is the case, and the SUnit |
| 3962 | // is not part of circuit, then the NodeOrder is not |
| 3963 | // valid. |
| 3964 | for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) { |
| 3965 | SUnit *SU = NodeOrder[i]; |
| 3966 | unsigned Index = i; |
| 3967 | |
| 3968 | bool PredBefore = false; |
| 3969 | bool SuccBefore = false; |
| 3970 | |
| 3971 | SUnit *Succ; |
| 3972 | SUnit *Pred; |
David L Kreitzer | febf70a | 2018-03-16 21:21:23 +0000 | [diff] [blame] | 3973 | (void)Succ; |
| 3974 | (void)Pred; |
Roorda, Jan-Willem | 4b8bcf0 | 2018-03-07 18:53:36 +0000 | [diff] [blame] | 3975 | |
| 3976 | for (SDep &PredEdge : SU->Preds) { |
| 3977 | SUnit *PredSU = PredEdge.getSUnit(); |
| 3978 | unsigned PredIndex = |
| 3979 | std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(), |
| 3980 | std::make_pair(PredSU, 0), CompareKey)); |
| 3981 | if (!PredSU->getInstr()->isPHI() && PredIndex < Index) { |
| 3982 | PredBefore = true; |
| 3983 | Pred = PredSU; |
| 3984 | break; |
| 3985 | } |
| 3986 | } |
| 3987 | |
| 3988 | for (SDep &SuccEdge : SU->Succs) { |
| 3989 | SUnit *SuccSU = SuccEdge.getSUnit(); |
| 3990 | unsigned SuccIndex = |
| 3991 | std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(), |
| 3992 | std::make_pair(SuccSU, 0), CompareKey)); |
| 3993 | if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) { |
| 3994 | SuccBefore = true; |
| 3995 | Succ = SuccSU; |
| 3996 | break; |
| 3997 | } |
| 3998 | } |
| 3999 | |
| 4000 | if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) { |
| 4001 | // instructions in circuits are allowed to be scheduled |
| 4002 | // after both a successor and predecessor. |
| 4003 | bool InCircuit = std::any_of( |
| 4004 | Circuits.begin(), Circuits.end(), |
| 4005 | [SU](const NodeSet &Circuit) { return Circuit.count(SU); }); |
| 4006 | if (InCircuit) |
| 4007 | DEBUG(dbgs() << "In a circuit, predecessor ";); |
| 4008 | else { |
| 4009 | Valid = false; |
| 4010 | NumNodeOrderIssues++; |
| 4011 | DEBUG(dbgs() << "Predecessor ";); |
| 4012 | } |
| 4013 | DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum |
| 4014 | << " are scheduled before node " << SU->NodeNum << "\n";); |
| 4015 | } |
| 4016 | } |
| 4017 | |
| 4018 | DEBUG({ |
| 4019 | if (!Valid) |
| 4020 | dbgs() << "Invalid node order found!\n"; |
| 4021 | }); |
| 4022 | } |
| 4023 | |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 4024 | /// Attempt to fix the degenerate cases when the instruction serialization |
| 4025 | /// causes the register lifetimes to overlap. For example, |
| 4026 | /// p' = store_pi(p, b) |
| 4027 | /// = load p, offset |
| 4028 | /// In this case p and p' overlap, which means that two registers are needed. |
| 4029 | /// Instead, this function changes the load to use p' and updates the offset. |
| 4030 | void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) { |
| 4031 | unsigned OverlapReg = 0; |
| 4032 | unsigned NewBaseReg = 0; |
| 4033 | for (SUnit *SU : Instrs) { |
| 4034 | MachineInstr *MI = SU->getInstr(); |
| 4035 | for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { |
| 4036 | const MachineOperand &MO = MI->getOperand(i); |
| 4037 | // Look for an instruction that uses p. The instruction occurs in the |
| 4038 | // same cycle but occurs later in the serialized order. |
| 4039 | if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) { |
| 4040 | // Check that the instruction appears in the InstrChanges structure, |
| 4041 | // which contains instructions that can have the offset updated. |
| 4042 | DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = |
| 4043 | InstrChanges.find(SU); |
| 4044 | if (It != InstrChanges.end()) { |
| 4045 | unsigned BasePos, OffsetPos; |
| 4046 | // Update the base register and adjust the offset. |
| 4047 | if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) { |
Krzysztof Parzyszek | 12bdcab | 2017-10-11 15:59:51 +0000 | [diff] [blame] | 4048 | MachineInstr *NewMI = MF.CloneMachineInstr(MI); |
| 4049 | NewMI->getOperand(BasePos).setReg(NewBaseReg); |
| 4050 | int64_t NewOffset = |
| 4051 | MI->getOperand(OffsetPos).getImm() - It->second.second; |
| 4052 | NewMI->getOperand(OffsetPos).setImm(NewOffset); |
| 4053 | SU->setInstr(NewMI); |
| 4054 | MISUnitMap[NewMI] = SU; |
| 4055 | NewMIs.insert(NewMI); |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 4056 | } |
| 4057 | } |
| 4058 | OverlapReg = 0; |
| 4059 | NewBaseReg = 0; |
| 4060 | break; |
| 4061 | } |
| 4062 | // Look for an instruction of the form p' = op(p), which uses and defines |
| 4063 | // two virtual registers that get allocated to the same physical register. |
| 4064 | unsigned TiedUseIdx = 0; |
| 4065 | if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) { |
| 4066 | // OverlapReg is p in the example above. |
| 4067 | OverlapReg = MI->getOperand(TiedUseIdx).getReg(); |
| 4068 | // NewBaseReg is p' in the example above. |
| 4069 | NewBaseReg = MI->getOperand(i).getReg(); |
| 4070 | break; |
| 4071 | } |
| 4072 | } |
| 4073 | } |
| 4074 | } |
| 4075 | |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 4076 | /// After the schedule has been formed, call this function to combine |
| 4077 | /// the instructions from the different stages/cycles. That is, this |
| 4078 | /// function creates a schedule that represents a single iteration. |
| 4079 | void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) { |
| 4080 | // Move all instructions to the first stage from later stages. |
| 4081 | for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) { |
| 4082 | for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage; |
| 4083 | ++stage) { |
| 4084 | std::deque<SUnit *> &cycleInstrs = |
| 4085 | ScheduledInstrs[cycle + (stage * InitiationInterval)]; |
| 4086 | for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(), |
| 4087 | E = cycleInstrs.rend(); |
| 4088 | I != E; ++I) |
| 4089 | ScheduledInstrs[cycle].push_front(*I); |
| 4090 | } |
| 4091 | } |
| 4092 | // Iterate over the definitions in each instruction, and compute the |
| 4093 | // stage difference for each use. Keep the maximum value. |
| 4094 | for (auto &I : InstrToCycle) { |
| 4095 | int DefStage = stageScheduled(I.first); |
| 4096 | MachineInstr *MI = I.first->getInstr(); |
| 4097 | for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { |
| 4098 | MachineOperand &Op = MI->getOperand(i); |
| 4099 | if (!Op.isReg() || !Op.isDef()) |
| 4100 | continue; |
| 4101 | |
| 4102 | unsigned Reg = Op.getReg(); |
| 4103 | unsigned MaxDiff = 0; |
| 4104 | bool PhiIsSwapped = false; |
| 4105 | for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg), |
| 4106 | EI = MRI.use_end(); |
| 4107 | UI != EI; ++UI) { |
| 4108 | MachineOperand &UseOp = *UI; |
| 4109 | MachineInstr *UseMI = UseOp.getParent(); |
| 4110 | SUnit *SUnitUse = SSD->getSUnit(UseMI); |
| 4111 | int UseStage = stageScheduled(SUnitUse); |
| 4112 | unsigned Diff = 0; |
| 4113 | if (UseStage != -1 && UseStage >= DefStage) |
| 4114 | Diff = UseStage - DefStage; |
| 4115 | if (MI->isPHI()) { |
| 4116 | if (isLoopCarried(SSD, *MI)) |
| 4117 | ++Diff; |
| 4118 | else |
| 4119 | PhiIsSwapped = true; |
| 4120 | } |
| 4121 | MaxDiff = std::max(Diff, MaxDiff); |
| 4122 | } |
| 4123 | RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped); |
| 4124 | } |
| 4125 | } |
| 4126 | |
| 4127 | // Erase all the elements in the later stages. Only one iteration should |
| 4128 | // remain in the scheduled list, and it contains all the instructions. |
| 4129 | for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle) |
| 4130 | ScheduledInstrs.erase(cycle); |
| 4131 | |
| 4132 | // Change the registers in instruction as specified in the InstrChanges |
| 4133 | // map. We need to use the new registers to create the correct order. |
| 4134 | for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) { |
| 4135 | SUnit *SU = &SSD->SUnits[i]; |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 4136 | SSD->applyInstrChange(SU->getInstr(), *this); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 4137 | } |
| 4138 | |
| 4139 | // Reorder the instructions in each cycle to fix and improve the |
| 4140 | // generated code. |
| 4141 | for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) { |
| 4142 | std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle]; |
| 4143 | std::deque<SUnit *> newOrderZC; |
| 4144 | // Put the zero-cost, pseudo instructions at the start of the cycle. |
| 4145 | for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) { |
| 4146 | SUnit *SU = cycleInstrs[i]; |
| 4147 | if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode())) |
| 4148 | orderDependence(SSD, SU, newOrderZC); |
| 4149 | } |
| 4150 | std::deque<SUnit *> newOrderI; |
| 4151 | // Then, add the regular instructions back. |
| 4152 | for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) { |
| 4153 | SUnit *SU = cycleInstrs[i]; |
| 4154 | if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode())) |
| 4155 | orderDependence(SSD, SU, newOrderI); |
| 4156 | } |
| 4157 | // Replace the old order with the new order. |
| 4158 | cycleInstrs.swap(newOrderZC); |
| 4159 | cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end()); |
Krzysztof Parzyszek | 8f174dd | 2017-10-11 15:51:44 +0000 | [diff] [blame] | 4160 | SSD->fixupRegisterOverlaps(cycleInstrs); |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 4161 | } |
| 4162 | |
| 4163 | DEBUG(dump();); |
| 4164 | } |
| 4165 | |
Aaron Ballman | 615eb47 | 2017-10-15 14:32:27 +0000 | [diff] [blame] | 4166 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Brendon Cahoon | 254f889 | 2016-07-29 16:44:44 +0000 | [diff] [blame] | 4167 | /// Print the schedule information to the given output. |
| 4168 | void SMSchedule::print(raw_ostream &os) const { |
| 4169 | // Iterate over each cycle. |
| 4170 | for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) { |
| 4171 | // Iterate over each instruction in the cycle. |
| 4172 | const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle); |
| 4173 | for (SUnit *CI : cycleInstrs->second) { |
| 4174 | os << "cycle " << cycle << " (" << stageScheduled(CI) << ") "; |
| 4175 | os << "(" << CI->NodeNum << ") "; |
| 4176 | CI->getInstr()->print(os); |
| 4177 | os << "\n"; |
| 4178 | } |
| 4179 | } |
| 4180 | } |
| 4181 | |
| 4182 | /// Utility function used for debugging to print the schedule. |
Matthias Braun | 8c209aa | 2017-01-28 02:02:38 +0000 | [diff] [blame] | 4183 | LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); } |
| 4184 | #endif |