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