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