blob: 570ed4aadab7114dd007114f10356f0b3f6464c1 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Brendon Cahoon254f8892016-07-29 16:44:44 +00006//
7//===----------------------------------------------------------------------===//
8//
9// An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10//
Brendon Cahoon254f8892016-07-29 16:44:44 +000011// This SMS implementation is a target-independent back-end pass. When enabled,
12// the pass runs just prior to the register allocation pass, while the machine
13// IR is in SSA form. If software pipelining is successful, then the original
14// loop is replaced by the optimized loop. The optimized loop contains one or
15// more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16// the instructions cannot be scheduled in a given MII, we increase the MII by
17// one and try again.
18//
19// The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20// represent loop carried dependences in the DAG as order edges to the Phi
21// nodes. We also perform several passes over the DAG to eliminate unnecessary
22// edges that inhibit the ability to pipeline. The implementation uses the
23// DFAPacketizer class to compute the minimum initiation interval and the check
24// where an instruction may be inserted in the pipelined schedule.
25//
26// In order for the SMS pass to work, several target specific hooks need to be
27// implemented to get information about the loop structure and to rewrite
28// instructions.
29//
30//===----------------------------------------------------------------------===//
31
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/BitVector.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000034#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/PriorityQueue.h"
37#include "llvm/ADT/SetVector.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallSet.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000040#include "llvm/ADT/SmallVector.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000041#include "llvm/ADT/Statistic.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include "llvm/ADT/iterator_range.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000043#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000044#include "llvm/Analysis/MemoryLocation.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000045#include "llvm/Analysis/ValueTracking.h"
46#include "llvm/CodeGen/DFAPacketizer.h"
Matthias Braunf8422972017-12-13 02:51:04 +000047#include "llvm/CodeGen/LiveIntervals.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000048#include "llvm/CodeGen/MachineBasicBlock.h"
49#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/CodeGen/MachineFunction.h"
51#include "llvm/CodeGen/MachineFunctionPass.h"
52#include "llvm/CodeGen/MachineInstr.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000053#include "llvm/CodeGen/MachineInstrBuilder.h"
54#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000055#include "llvm/CodeGen/MachineMemOperand.h"
56#include "llvm/CodeGen/MachineOperand.h"
Adrian Prantlfa2e3582019-01-14 17:24:11 +000057#include "llvm/CodeGen/MachinePipeliner.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000058#include "llvm/CodeGen/MachineRegisterInfo.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000059#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000060#include "llvm/CodeGen/ScheduleDAG.h"
Krzysztof Parzyszek88391242016-12-22 19:21:20 +000061#include "llvm/CodeGen/ScheduleDAGMutation.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000062#include "llvm/CodeGen/TargetOpcodes.h"
63#include "llvm/CodeGen/TargetRegisterInfo.h"
64#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000065#include "llvm/Config/llvm-config.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000066#include "llvm/IR/Attributes.h"
67#include "llvm/IR/DebugLoc.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000068#include "llvm/IR/Function.h"
69#include "llvm/MC/LaneBitmask.h"
70#include "llvm/MC/MCInstrDesc.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000071#include "llvm/MC/MCInstrItineraries.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000072#include "llvm/MC/MCRegisterInfo.h"
73#include "llvm/Pass.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000074#include "llvm/Support/CommandLine.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000075#include "llvm/Support/Compiler.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000076#include "llvm/Support/Debug.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000077#include "llvm/Support/MathExtras.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000078#include "llvm/Support/raw_ostream.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000079#include <algorithm>
80#include <cassert>
Brendon Cahoon254f8892016-07-29 16:44:44 +000081#include <climits>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000082#include <cstdint>
Brendon Cahoon254f8892016-07-29 16:44:44 +000083#include <deque>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000084#include <functional>
85#include <iterator>
Brendon Cahoon254f8892016-07-29 16:44:44 +000086#include <map>
Eugene Zelenko32a40562017-09-11 23:00:48 +000087#include <memory>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000088#include <tuple>
89#include <utility>
90#include <vector>
Brendon Cahoon254f8892016-07-29 16:44:44 +000091
92using namespace llvm;
93
94#define DEBUG_TYPE "pipeliner"
95
96STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
97STATISTIC(NumPipelined, "Number of loops software pipelined");
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +000098STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
Jinsong Ji18e7bf52019-05-31 15:35:19 +000099STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
100STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
101STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
102STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
103STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
104STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
105STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
106STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000107
108/// A command line option to turn software pipelining on or off.
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000109static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
110 cl::ZeroOrMore,
111 cl::desc("Enable Software Pipelining"));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000112
113/// A command line option to enable SWP at -Os.
114static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
115 cl::desc("Enable SWP at Os."), cl::Hidden,
116 cl::init(false));
117
118/// A command line argument to limit minimum initial interval for pipelining.
119static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000120 cl::desc("Size limit for the MII."),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000121 cl::Hidden, cl::init(27));
122
123/// A command line argument to limit the number of stages in the pipeline.
124static cl::opt<int>
125 SwpMaxStages("pipeliner-max-stages",
126 cl::desc("Maximum stages allowed in the generated scheduled."),
127 cl::Hidden, cl::init(3));
128
129/// A command line option to disable the pruning of chain dependences due to
130/// an unrelated Phi.
131static cl::opt<bool>
132 SwpPruneDeps("pipeliner-prune-deps",
133 cl::desc("Prune dependences between unrelated Phi nodes."),
134 cl::Hidden, cl::init(true));
135
136/// A command line option to disable the pruning of loop carried order
137/// dependences.
138static cl::opt<bool>
139 SwpPruneLoopCarried("pipeliner-prune-loop-carried",
140 cl::desc("Prune loop carried order dependences."),
141 cl::Hidden, cl::init(true));
142
143#ifndef NDEBUG
144static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
145#endif
146
147static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
148 cl::ReallyHidden, cl::init(false),
149 cl::ZeroOrMore, cl::desc("Ignore RecMII"));
150
Jinsong Jiba438402019-06-18 20:24:49 +0000151static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
152 cl::init(false));
153static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
154 cl::init(false));
155
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000156namespace llvm {
157
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000158// A command line option to enable the CopyToPhi DAG mutation.
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000159cl::opt<bool>
Aleksandr Urakov00d4c382018-10-23 14:27:45 +0000160 SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
161 cl::init(true), cl::ZeroOrMore,
162 cl::desc("Enable CopyToPhi DAG Mutation"));
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000163
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000164} // end namespace llvm
Brendon Cahoon254f8892016-07-29 16:44:44 +0000165
166unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
167char MachinePipeliner::ID = 0;
168#ifndef NDEBUG
169int MachinePipeliner::NumTries = 0;
170#endif
171char &llvm::MachinePipelinerID = MachinePipeliner::ID;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000172
Matthias Braun1527baa2017-05-25 21:26:32 +0000173INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000174 "Modulo Software Pipelining", false, false)
175INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
176INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
177INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
178INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000179INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000180 "Modulo Software Pipelining", false, false)
181
182/// The "main" function for implementing Swing Modulo Scheduling.
183bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000184 if (skipFunction(mf.getFunction()))
Brendon Cahoon254f8892016-07-29 16:44:44 +0000185 return false;
186
187 if (!EnableSWP)
188 return false;
189
Matthias Braunf1caa282017-12-15 22:22:58 +0000190 if (mf.getFunction().getAttributes().hasAttribute(
Reid Klecknerb5180542017-03-21 16:57:19 +0000191 AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +0000192 !EnableSWPOptSize.getPosition())
193 return false;
194
Jinsong Jief2d6d92019-06-11 17:40:39 +0000195 if (!mf.getSubtarget().enableMachinePipeliner())
196 return false;
197
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000198 // Cannot pipeline loops without instruction itineraries if we are using
199 // DFA for the pipeliner.
200 if (mf.getSubtarget().useDFAforSMS() &&
201 (!mf.getSubtarget().getInstrItineraryData() ||
202 mf.getSubtarget().getInstrItineraryData()->isEmpty()))
203 return false;
204
Brendon Cahoon254f8892016-07-29 16:44:44 +0000205 MF = &mf;
206 MLI = &getAnalysis<MachineLoopInfo>();
207 MDT = &getAnalysis<MachineDominatorTree>();
208 TII = MF->getSubtarget().getInstrInfo();
209 RegClassInfo.runOnMachineFunction(*MF);
210
211 for (auto &L : *MLI)
212 scheduleLoop(*L);
213
214 return false;
215}
216
217/// Attempt to perform the SMS algorithm on the specified loop. This function is
218/// the main entry point for the algorithm. The function identifies candidate
219/// loops, calculates the minimum initiation interval, and attempts to schedule
220/// the loop.
221bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
222 bool Changed = false;
223 for (auto &InnerLoop : L)
224 Changed |= scheduleLoop(*InnerLoop);
225
226#ifndef NDEBUG
227 // Stop trying after reaching the limit (if any).
228 int Limit = SwpLoopLimit;
229 if (Limit >= 0) {
230 if (NumTries >= SwpLoopLimit)
231 return Changed;
232 NumTries++;
233 }
234#endif
235
Brendon Cahoon59d99732019-01-23 03:26:10 +0000236 setPragmaPipelineOptions(L);
237 if (!canPipelineLoop(L)) {
238 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000239 return Changed;
Brendon Cahoon59d99732019-01-23 03:26:10 +0000240 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000241
242 ++NumTrytoPipeline;
243
244 Changed = swingModuloScheduler(L);
245
246 return Changed;
247}
248
Brendon Cahoon59d99732019-01-23 03:26:10 +0000249void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
250 MachineBasicBlock *LBLK = L.getTopBlock();
251
252 if (LBLK == nullptr)
253 return;
254
255 const BasicBlock *BBLK = LBLK->getBasicBlock();
256 if (BBLK == nullptr)
257 return;
258
259 const Instruction *TI = BBLK->getTerminator();
260 if (TI == nullptr)
261 return;
262
263 MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
264 if (LoopID == nullptr)
265 return;
266
267 assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
268 assert(LoopID->getOperand(0) == LoopID && "invalid loop");
269
270 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
271 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
272
273 if (MD == nullptr)
274 continue;
275
276 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
277
278 if (S == nullptr)
279 continue;
280
281 if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
282 assert(MD->getNumOperands() == 2 &&
283 "Pipeline initiation interval hint metadata should have two operands.");
284 II_setByPragma =
285 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
286 assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
287 } else if (S->getString() == "llvm.loop.pipeline.disable") {
288 disabledByPragma = true;
289 }
290 }
291}
292
Brendon Cahoon254f8892016-07-29 16:44:44 +0000293/// Return true if the loop can be software pipelined. The algorithm is
294/// restricted to loops with a single basic block. Make sure that the
295/// branch in the loop can be analyzed.
296bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
297 if (L.getNumBlocks() != 1)
298 return false;
299
Brendon Cahoon59d99732019-01-23 03:26:10 +0000300 if (disabledByPragma)
301 return false;
302
Brendon Cahoon254f8892016-07-29 16:44:44 +0000303 // Check if the branch can't be understood because we can't do pipelining
304 // if that's the case.
305 LI.TBB = nullptr;
306 LI.FBB = nullptr;
307 LI.BrCond.clear();
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000308 if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
309 LLVM_DEBUG(
310 dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
311 NumFailBranch++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000312 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000313 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000314
315 LI.LoopInductionVar = nullptr;
316 LI.LoopCompare = nullptr;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000317 if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) {
318 LLVM_DEBUG(
319 dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
320 NumFailLoop++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000321 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000322 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000323
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000324 if (!L.getLoopPreheader()) {
325 LLVM_DEBUG(
326 dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
327 NumFailPreheader++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000328 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000329 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000330
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000331 // Remove any subregisters from inputs to phi nodes.
332 preprocessPhiNodes(*L.getHeader());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000333 return true;
334}
335
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000336void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
337 MachineRegisterInfo &MRI = MF->getRegInfo();
338 SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
339
340 for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
341 MachineOperand &DefOp = PI.getOperand(0);
342 assert(DefOp.getSubReg() == 0);
343 auto *RC = MRI.getRegClass(DefOp.getReg());
344
345 for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
346 MachineOperand &RegOp = PI.getOperand(i);
347 if (RegOp.getSubReg() == 0)
348 continue;
349
350 // If the operand uses a subregister, replace it with a new register
351 // without subregisters, and generate a copy to the new register.
352 unsigned NewReg = MRI.createVirtualRegister(RC);
353 MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
354 MachineBasicBlock::iterator At = PredB.getFirstTerminator();
355 const DebugLoc &DL = PredB.findDebugLoc(At);
356 auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
357 .addReg(RegOp.getReg(), getRegState(RegOp),
358 RegOp.getSubReg());
359 Slots.insertMachineInstrInMaps(*Copy);
360 RegOp.setReg(NewReg);
361 RegOp.setSubReg(0);
362 }
363 }
364}
365
Brendon Cahoon254f8892016-07-29 16:44:44 +0000366/// The SMS algorithm consists of the following main steps:
367/// 1. Computation and analysis of the dependence graph.
368/// 2. Ordering of the nodes (instructions).
369/// 3. Attempt to Schedule the loop.
370bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
371 assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
372
Brendon Cahoon59d99732019-01-23 03:26:10 +0000373 SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
374 II_setByPragma);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000375
376 MachineBasicBlock *MBB = L.getHeader();
377 // The kernel should not include any terminator instructions. These
378 // will be added back later.
379 SMS.startBlock(MBB);
380
381 // Compute the number of 'real' instructions in the basic block by
382 // ignoring terminators.
383 unsigned size = MBB->size();
384 for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
385 E = MBB->instr_end();
386 I != E; ++I, --size)
387 ;
388
389 SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
390 SMS.schedule();
391 SMS.exitRegion();
392
393 SMS.finishBlock();
394 return SMS.hasNewSchedule();
395}
396
Brendon Cahoon59d99732019-01-23 03:26:10 +0000397void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
398 if (II_setByPragma > 0)
399 MII = II_setByPragma;
400 else
401 MII = std::max(ResMII, RecMII);
402}
403
404void SwingSchedulerDAG::setMAX_II() {
405 if (II_setByPragma > 0)
406 MAX_II = II_setByPragma;
407 else
408 MAX_II = MII + 10;
409}
410
Brendon Cahoon254f8892016-07-29 16:44:44 +0000411/// We override the schedule function in ScheduleDAGInstrs to implement the
412/// scheduling part of the Swing Modulo Scheduling algorithm.
413void SwingSchedulerDAG::schedule() {
414 AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
415 buildSchedGraph(AA);
416 addLoopCarriedDependences(AA);
417 updatePhiDependences();
418 Topo.InitDAGTopologicalSorting();
419 changeDependences();
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000420 postprocessDAG();
Matthias Braun726e12c2018-09-19 00:23:35 +0000421 LLVM_DEBUG(dump());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000422
423 NodeSetType NodeSets;
424 findCircuits(NodeSets);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000425 NodeSetType Circuits = NodeSets;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000426
427 // Calculate the MII.
428 unsigned ResMII = calculateResMII();
429 unsigned RecMII = calculateRecMII(NodeSets);
430
431 fuseRecs(NodeSets);
432
433 // This flag is used for testing and can cause correctness problems.
434 if (SwpIgnoreRecMII)
435 RecMII = 0;
436
Brendon Cahoon59d99732019-01-23 03:26:10 +0000437 setMII(ResMII, RecMII);
438 setMAX_II();
439
440 LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
441 << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000442
443 // Can't schedule a loop without a valid MII.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000444 if (MII == 0) {
445 LLVM_DEBUG(
446 dbgs()
447 << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
448 NumFailZeroMII++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000449 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000450 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000451
452 // Don't pipeline large loops.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000453 if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
454 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
455 << ", we don't pipleline large loops\n");
456 NumFailLargeMaxMII++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000457 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000458 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000459
460 computeNodeFunctions(NodeSets);
461
462 registerPressureFilter(NodeSets);
463
464 colocateNodeSets(NodeSets);
465
466 checkNodeSets(NodeSets);
467
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000469 for (auto &I : NodeSets) {
470 dbgs() << " Rec NodeSet ";
471 I.dump();
472 }
473 });
474
Fangrui Songefd94c52019-04-23 14:51:27 +0000475 llvm::stable_sort(NodeSets, std::greater<NodeSet>());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000476
477 groupRemainingNodes(NodeSets);
478
479 removeDuplicateNodes(NodeSets);
480
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000481 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000482 for (auto &I : NodeSets) {
483 dbgs() << " NodeSet ";
484 I.dump();
485 }
486 });
487
488 computeNodeOrder(NodeSets);
489
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000490 // check for node order issues
491 checkValidNodeOrder(Circuits);
492
Brendon Cahoon254f8892016-07-29 16:44:44 +0000493 SMSchedule Schedule(Pass.MF);
494 Scheduled = schedulePipeline(Schedule);
495
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000496 if (!Scheduled){
497 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
498 NumFailNoSchedule++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000499 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000500 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000501
502 unsigned numStages = Schedule.getMaxStageCount();
503 // No need to generate pipeline if there are no overlapped iterations.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000504 if (numStages == 0) {
505 LLVM_DEBUG(
506 dbgs() << "No overlapped iterations, no need to generate pipeline\n");
507 NumFailZeroStage++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000508 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000509 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000510 // Check that the maximum stage count is less than user-defined limit.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000511 if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
512 LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
513 << " : too many stages, abort\n");
514 NumFailLargeMaxStage++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000515 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000516 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000517
518 generatePipelinedLoop(Schedule);
519 ++NumPipelined;
520}
521
522/// Clean up after the software pipeliner runs.
523void SwingSchedulerDAG::finishBlock() {
524 for (MachineInstr *I : NewMIs)
525 MF.DeleteMachineInstr(I);
526 NewMIs.clear();
527
528 // Call the superclass.
529 ScheduleDAGInstrs::finishBlock();
530}
531
532/// Return the register values for the operands of a Phi instruction.
533/// This function assume the instruction is a Phi.
534static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
535 unsigned &InitVal, unsigned &LoopVal) {
536 assert(Phi.isPHI() && "Expecting a Phi.");
537
538 InitVal = 0;
539 LoopVal = 0;
540 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
541 if (Phi.getOperand(i + 1).getMBB() != Loop)
542 InitVal = Phi.getOperand(i).getReg();
Simon Pilgrimfbfb19b2017-03-16 19:52:00 +0000543 else
Brendon Cahoon254f8892016-07-29 16:44:44 +0000544 LoopVal = Phi.getOperand(i).getReg();
545
546 assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
547}
548
549/// Return the Phi register value that comes from the incoming block.
550static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
551 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
552 if (Phi.getOperand(i + 1).getMBB() != LoopBB)
553 return Phi.getOperand(i).getReg();
554 return 0;
555}
556
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000557/// Return the Phi register value that comes the loop block.
Brendon Cahoon254f8892016-07-29 16:44:44 +0000558static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
559 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
560 if (Phi.getOperand(i + 1).getMBB() == LoopBB)
561 return Phi.getOperand(i).getReg();
562 return 0;
563}
564
565/// Return true if SUb can be reached from SUa following the chain edges.
566static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
567 SmallPtrSet<SUnit *, 8> Visited;
568 SmallVector<SUnit *, 8> Worklist;
569 Worklist.push_back(SUa);
570 while (!Worklist.empty()) {
571 const SUnit *SU = Worklist.pop_back_val();
572 for (auto &SI : SU->Succs) {
573 SUnit *SuccSU = SI.getSUnit();
574 if (SI.getKind() == SDep::Order) {
575 if (Visited.count(SuccSU))
576 continue;
577 if (SuccSU == SUb)
578 return true;
579 Worklist.push_back(SuccSU);
580 Visited.insert(SuccSU);
581 }
582 }
583 }
584 return false;
585}
586
587/// Return true if the instruction causes a chain between memory
588/// references before and after it.
589static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +0000590 return MI.isCall() || MI.mayRaiseFPException() ||
591 MI.hasUnmodeledSideEffects() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +0000592 (MI.hasOrderedMemoryRef() &&
Justin Lebard98cf002016-09-10 01:03:20 +0000593 (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000594}
595
596/// Return the underlying objects for the memory references of an instruction.
597/// This function calls the code in ValueTracking, but first checks that the
598/// instruction has a memory operand.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000599static void getUnderlyingObjects(const MachineInstr *MI,
600 SmallVectorImpl<const Value *> &Objs,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000601 const DataLayout &DL) {
602 if (!MI->hasOneMemOperand())
603 return;
604 MachineMemOperand *MM = *MI->memoperands_begin();
605 if (!MM->getValue())
606 return;
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000607 GetUnderlyingObjects(MM->getValue(), Objs, DL);
608 for (const Value *V : Objs) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000609 if (!isIdentifiedObject(V)) {
610 Objs.clear();
611 return;
612 }
613 Objs.push_back(V);
614 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000615}
616
617/// Add a chain edge between a load and store if the store can be an
618/// alias of the load on a subsequent iteration, i.e., a loop carried
619/// dependence. This code is very similar to the code in ScheduleDAGInstrs
620/// but that code doesn't create loop carried dependences.
621void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000622 MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000623 Value *UnknownValue =
624 UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000625 for (auto &SU : SUnits) {
626 MachineInstr &MI = *SU.getInstr();
627 if (isDependenceBarrier(MI, AA))
628 PendingLoads.clear();
629 else if (MI.mayLoad()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000630 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000631 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000632 if (Objs.empty())
633 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000634 for (auto V : Objs) {
635 SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
636 SUs.push_back(&SU);
637 }
638 } else if (MI.mayStore()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000639 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000640 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000641 if (Objs.empty())
642 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000643 for (auto V : Objs) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000644 MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
Brendon Cahoon254f8892016-07-29 16:44:44 +0000645 PendingLoads.find(V);
646 if (I == PendingLoads.end())
647 continue;
648 for (auto Load : I->second) {
649 if (isSuccOrder(Load, &SU))
650 continue;
651 MachineInstr &LdMI = *Load->getInstr();
652 // First, perform the cheaper check that compares the base register.
653 // If they are the same and the load offset is less than the store
654 // offset, then mark the dependence as loop carried potentially.
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000655 const MachineOperand *BaseOp1, *BaseOp2;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000656 int64_t Offset1, Offset2;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +0000657 if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) &&
658 TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) {
659 if (BaseOp1->isIdenticalTo(*BaseOp2) &&
660 (int)Offset1 < (int)Offset2) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000661 assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
662 "What happened to the chain edge?");
663 SDep Dep(Load, SDep::Barrier);
664 Dep.setLatency(1);
665 SU.addPred(Dep);
666 continue;
667 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000668 }
669 // Second, the more expensive check that uses alias analysis on the
670 // base registers. If they alias, and the load offset is less than
671 // the store offset, the mark the dependence as loop carried.
672 if (!AA) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000673 SDep Dep(Load, SDep::Barrier);
674 Dep.setLatency(1);
675 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000676 continue;
677 }
678 MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
679 MachineMemOperand *MMO2 = *MI.memoperands_begin();
680 if (!MMO1->getValue() || !MMO2->getValue()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000681 SDep Dep(Load, SDep::Barrier);
682 Dep.setLatency(1);
683 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000684 continue;
685 }
686 if (MMO1->getValue() == MMO2->getValue() &&
687 MMO1->getOffset() <= MMO2->getOffset()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000688 SDep Dep(Load, SDep::Barrier);
689 Dep.setLatency(1);
690 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000691 continue;
692 }
693 AliasResult AAResult = AA->alias(
George Burgess IV6ef80022018-10-10 21:28:44 +0000694 MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000695 MMO1->getAAInfo()),
George Burgess IV6ef80022018-10-10 21:28:44 +0000696 MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000697 MMO2->getAAInfo()));
698
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000699 if (AAResult != NoAlias) {
700 SDep Dep(Load, SDep::Barrier);
701 Dep.setLatency(1);
702 SU.addPred(Dep);
703 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000704 }
705 }
706 }
707 }
708}
709
710/// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
711/// processes dependences for PHIs. This function adds true dependences
712/// from a PHI to a use, and a loop carried dependence from the use to the
713/// PHI. The loop carried dependence is represented as an anti dependence
714/// edge. This function also removes chain dependences between unrelated
715/// PHIs.
716void SwingSchedulerDAG::updatePhiDependences() {
717 SmallVector<SDep, 4> RemoveDeps;
718 const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
719
720 // Iterate over each DAG node.
721 for (SUnit &I : SUnits) {
722 RemoveDeps.clear();
723 // Set to true if the instruction has an operand defined by a Phi.
724 unsigned HasPhiUse = 0;
725 unsigned HasPhiDef = 0;
726 MachineInstr *MI = I.getInstr();
727 // Iterate over each operand, and we process the definitions.
728 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
729 MOE = MI->operands_end();
730 MOI != MOE; ++MOI) {
731 if (!MOI->isReg())
732 continue;
733 unsigned Reg = MOI->getReg();
734 if (MOI->isDef()) {
735 // If the register is used by a Phi, then create an anti dependence.
736 for (MachineRegisterInfo::use_instr_iterator
737 UI = MRI.use_instr_begin(Reg),
738 UE = MRI.use_instr_end();
739 UI != UE; ++UI) {
740 MachineInstr *UseMI = &*UI;
741 SUnit *SU = getSUnit(UseMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000742 if (SU != nullptr && UseMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000743 if (!MI->isPHI()) {
744 SDep Dep(SU, SDep::Anti, Reg);
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000745 Dep.setLatency(1);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000746 I.addPred(Dep);
747 } else {
748 HasPhiDef = Reg;
749 // Add a chain edge to a dependent Phi that isn't an existing
750 // predecessor.
751 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
752 I.addPred(SDep(SU, SDep::Barrier));
753 }
754 }
755 }
756 } else if (MOI->isUse()) {
757 // If the register is defined by a Phi, then create a true dependence.
758 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000759 if (DefMI == nullptr)
Brendon Cahoon254f8892016-07-29 16:44:44 +0000760 continue;
761 SUnit *SU = getSUnit(DefMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000762 if (SU != nullptr && DefMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000763 if (!MI->isPHI()) {
764 SDep Dep(SU, SDep::Data, Reg);
765 Dep.setLatency(0);
766 ST.adjustSchedDependency(SU, &I, Dep);
767 I.addPred(Dep);
768 } else {
769 HasPhiUse = Reg;
770 // Add a chain edge to a dependent Phi that isn't an existing
771 // predecessor.
772 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
773 I.addPred(SDep(SU, SDep::Barrier));
774 }
775 }
776 }
777 }
778 // Remove order dependences from an unrelated Phi.
779 if (!SwpPruneDeps)
780 continue;
781 for (auto &PI : I.Preds) {
782 MachineInstr *PMI = PI.getSUnit()->getInstr();
783 if (PMI->isPHI() && PI.getKind() == SDep::Order) {
784 if (I.getInstr()->isPHI()) {
785 if (PMI->getOperand(0).getReg() == HasPhiUse)
786 continue;
787 if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
788 continue;
789 }
790 RemoveDeps.push_back(PI);
791 }
792 }
793 for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
794 I.removePred(RemoveDeps[i]);
795 }
796}
797
798/// Iterate over each DAG node and see if we can change any dependences
799/// in order to reduce the recurrence MII.
800void SwingSchedulerDAG::changeDependences() {
801 // See if an instruction can use a value from the previous iteration.
802 // If so, we update the base and offset of the instruction and change
803 // the dependences.
804 for (SUnit &I : SUnits) {
805 unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
806 int64_t NewOffset = 0;
807 if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
808 NewOffset))
809 continue;
810
811 // Get the MI and SUnit for the instruction that defines the original base.
812 unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
813 MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
814 if (!DefMI)
815 continue;
816 SUnit *DefSU = getSUnit(DefMI);
817 if (!DefSU)
818 continue;
819 // Get the MI and SUnit for the instruction that defins the new base.
820 MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
821 if (!LastMI)
822 continue;
823 SUnit *LastSU = getSUnit(LastMI);
824 if (!LastSU)
825 continue;
826
827 if (Topo.IsReachable(&I, LastSU))
828 continue;
829
830 // Remove the dependence. The value now depends on a prior iteration.
831 SmallVector<SDep, 4> Deps;
832 for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
833 ++P)
834 if (P->getSUnit() == DefSU)
835 Deps.push_back(*P);
836 for (int i = 0, e = Deps.size(); i != e; i++) {
837 Topo.RemovePred(&I, Deps[i].getSUnit());
838 I.removePred(Deps[i]);
839 }
840 // Remove the chain dependence between the instructions.
841 Deps.clear();
842 for (auto &P : LastSU->Preds)
843 if (P.getSUnit() == &I && P.getKind() == SDep::Order)
844 Deps.push_back(P);
845 for (int i = 0, e = Deps.size(); i != e; i++) {
846 Topo.RemovePred(LastSU, Deps[i].getSUnit());
847 LastSU->removePred(Deps[i]);
848 }
849
850 // Add a dependence between the new instruction and the instruction
851 // that defines the new base.
852 SDep Dep(&I, SDep::Anti, NewBase);
Sumanth Gundapaneni8916e432018-10-11 19:42:46 +0000853 Topo.AddPred(LastSU, &I);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000854 LastSU->addPred(Dep);
855
856 // Remember the base and offset information so that we can update the
857 // instruction during code generation.
858 InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
859 }
860}
861
862namespace {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000863
Brendon Cahoon254f8892016-07-29 16:44:44 +0000864// FuncUnitSorter - Comparison operator used to sort instructions by
865// the number of functional unit choices.
866struct FuncUnitSorter {
867 const InstrItineraryData *InstrItins;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000868 const MCSubtargetInfo *STI;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000869 DenseMap<unsigned, unsigned> Resources;
870
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000871 FuncUnitSorter(const TargetSubtargetInfo &TSI)
872 : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
Eugene Zelenko32a40562017-09-11 23:00:48 +0000873
Brendon Cahoon254f8892016-07-29 16:44:44 +0000874 // Compute the number of functional unit alternatives needed
875 // at each stage, and take the minimum value. We prioritize the
876 // instructions by the least number of choices first.
877 unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000878 unsigned SchedClass = Inst->getDesc().getSchedClass();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000879 unsigned min = UINT_MAX;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000880 if (InstrItins && !InstrItins->isEmpty()) {
881 for (const InstrStage &IS :
882 make_range(InstrItins->beginStage(SchedClass),
883 InstrItins->endStage(SchedClass))) {
884 unsigned funcUnits = IS.getUnits();
885 unsigned numAlternatives = countPopulation(funcUnits);
886 if (numAlternatives < min) {
887 min = numAlternatives;
888 F = funcUnits;
889 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000890 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000891 return min;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000892 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000893 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
894 const MCSchedClassDesc *SCDesc =
895 STI->getSchedModel().getSchedClassDesc(SchedClass);
896 if (!SCDesc->isValid())
897 // No valid Schedule Class Desc for schedClass, should be
898 // Pseudo/PostRAPseudo
899 return min;
900
901 for (const MCWriteProcResEntry &PRE :
902 make_range(STI->getWriteProcResBegin(SCDesc),
903 STI->getWriteProcResEnd(SCDesc))) {
904 if (!PRE.Cycles)
905 continue;
906 const MCProcResourceDesc *ProcResource =
907 STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
908 unsigned NumUnits = ProcResource->NumUnits;
909 if (NumUnits < min) {
910 min = NumUnits;
911 F = PRE.ProcResourceIdx;
912 }
913 }
914 return min;
915 }
916 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000917 }
918
919 // Compute the critical resources needed by the instruction. This
920 // function records the functional units needed by instructions that
921 // must use only one functional unit. We use this as a tie breaker
922 // for computing the resource MII. The instrutions that require
923 // the same, highly used, functional unit have high priority.
924 void calcCriticalResources(MachineInstr &MI) {
925 unsigned SchedClass = MI.getDesc().getSchedClass();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000926 if (InstrItins && !InstrItins->isEmpty()) {
927 for (const InstrStage &IS :
928 make_range(InstrItins->beginStage(SchedClass),
929 InstrItins->endStage(SchedClass))) {
930 unsigned FuncUnits = IS.getUnits();
931 if (countPopulation(FuncUnits) == 1)
932 Resources[FuncUnits]++;
933 }
934 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000935 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000936 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
937 const MCSchedClassDesc *SCDesc =
938 STI->getSchedModel().getSchedClassDesc(SchedClass);
939 if (!SCDesc->isValid())
940 // No valid Schedule Class Desc for schedClass, should be
941 // Pseudo/PostRAPseudo
942 return;
943
944 for (const MCWriteProcResEntry &PRE :
945 make_range(STI->getWriteProcResBegin(SCDesc),
946 STI->getWriteProcResEnd(SCDesc))) {
947 if (!PRE.Cycles)
948 continue;
949 Resources[PRE.ProcResourceIdx]++;
950 }
951 return;
952 }
953 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000954 }
955
Brendon Cahoon254f8892016-07-29 16:44:44 +0000956 /// Return true if IS1 has less priority than IS2.
957 bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
958 unsigned F1 = 0, F2 = 0;
959 unsigned MFUs1 = minFuncUnits(IS1, F1);
960 unsigned MFUs2 = minFuncUnits(IS2, F2);
961 if (MFUs1 == 1 && MFUs2 == 1)
962 return Resources.lookup(F1) < Resources.lookup(F2);
963 return MFUs1 > MFUs2;
964 }
965};
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000966
967} // end anonymous namespace
Brendon Cahoon254f8892016-07-29 16:44:44 +0000968
969/// Calculate the resource constrained minimum initiation interval for the
970/// specified loop. We use the DFA to model the resources needed for
971/// each instruction, and we ignore dependences. A different DFA is created
972/// for each cycle that is required. When adding a new instruction, we attempt
973/// to add it to each existing DFA, until a legal space is found. If the
974/// instruction cannot be reserved in an existing DFA, we create a new one.
975unsigned SwingSchedulerDAG::calculateResMII() {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000976
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000977 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000978 SmallVector<ResourceManager*, 8> Resources;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000979 MachineBasicBlock *MBB = Loop.getHeader();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000980 Resources.push_back(new ResourceManager(&MF.getSubtarget()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000981
982 // Sort the instructions by the number of available choices for scheduling,
983 // least to most. Use the number of critical resources as the tie breaker.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000984 FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000985 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
986 E = MBB->getFirstTerminator();
987 I != E; ++I)
988 FUS.calcCriticalResources(*I);
989 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
990 FuncUnitOrder(FUS);
991
992 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
993 E = MBB->getFirstTerminator();
994 I != E; ++I)
995 FuncUnitOrder.push(&*I);
996
997 while (!FuncUnitOrder.empty()) {
998 MachineInstr *MI = FuncUnitOrder.top();
999 FuncUnitOrder.pop();
1000 if (TII->isZeroCost(MI->getOpcode()))
1001 continue;
1002 // Attempt to reserve the instruction in an existing DFA. At least one
1003 // DFA is needed for each cycle.
1004 unsigned NumCycles = getSUnit(MI)->Latency;
1005 unsigned ReservedCycles = 0;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001006 SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
1007 SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001008 LLVM_DEBUG({
1009 dbgs() << "Trying to reserve resource for " << NumCycles
1010 << " cycles for \n";
1011 MI->dump();
1012 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00001013 for (unsigned C = 0; C < NumCycles; ++C)
1014 while (RI != RE) {
1015 if ((*RI++)->canReserveResources(*MI)) {
1016 ++ReservedCycles;
1017 break;
1018 }
1019 }
1020 // Start reserving resources using existing DFAs.
1021 for (unsigned C = 0; C < ReservedCycles; ++C) {
1022 --RI;
1023 (*RI)->reserveResources(*MI);
1024 }
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001025
1026 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1027 << ", NumCycles:" << NumCycles << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001028 // Add new DFAs, if needed, to reserve resources.
1029 for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
Jinsong Jiba438402019-06-18 20:24:49 +00001030 LLVM_DEBUG(if (SwpDebugResource) dbgs()
1031 << "NewResource created to reserve resources"
1032 << "\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001033 ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001034 assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1035 NewResource->reserveResources(*MI);
1036 Resources.push_back(NewResource);
1037 }
1038 }
1039 int Resmii = Resources.size();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001040 LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001041 // Delete the memory for each of the DFAs that were created earlier.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001042 for (ResourceManager *RI : Resources) {
1043 ResourceManager *D = RI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001044 delete D;
1045 }
1046 Resources.clear();
1047 return Resmii;
1048}
1049
1050/// Calculate the recurrence-constrainted minimum initiation interval.
1051/// Iterate over each circuit. Compute the delay(c) and distance(c)
1052/// for each circuit. The II needs to satisfy the inequality
1053/// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001054/// II that satisfies the inequality, and the RecMII is the maximum
Brendon Cahoon254f8892016-07-29 16:44:44 +00001055/// of those values.
1056unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1057 unsigned RecMII = 0;
1058
1059 for (NodeSet &Nodes : NodeSets) {
Eugene Zelenko32a40562017-09-11 23:00:48 +00001060 if (Nodes.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001061 continue;
1062
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001063 unsigned Delay = Nodes.getLatency();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001064 unsigned Distance = 1;
1065
1066 // ii = ceil(delay / distance)
1067 unsigned CurMII = (Delay + Distance - 1) / Distance;
1068 Nodes.setRecMII(CurMII);
1069 if (CurMII > RecMII)
1070 RecMII = CurMII;
1071 }
1072
1073 return RecMII;
1074}
1075
1076/// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1077/// but we do this to find the circuits, and then change them back.
1078static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1079 SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1080 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1081 SUnit *SU = &SUnits[i];
1082 for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1083 IP != EP; ++IP) {
1084 if (IP->getKind() != SDep::Anti)
1085 continue;
1086 DepsAdded.push_back(std::make_pair(SU, *IP));
1087 }
1088 }
1089 for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1090 E = DepsAdded.end();
1091 I != E; ++I) {
1092 // Remove this anti dependency and add one in the reverse direction.
1093 SUnit *SU = I->first;
1094 SDep &D = I->second;
1095 SUnit *TargetSU = D.getSUnit();
1096 unsigned Reg = D.getReg();
1097 unsigned Lat = D.getLatency();
1098 SU->removePred(D);
1099 SDep Dep(SU, SDep::Anti, Reg);
1100 Dep.setLatency(Lat);
1101 TargetSU->addPred(Dep);
1102 }
1103}
1104
1105/// Create the adjacency structure of the nodes in the graph.
1106void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1107 SwingSchedulerDAG *DAG) {
1108 BitVector Added(SUnits.size());
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001109 DenseMap<int, int> OutputDeps;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001110 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1111 Added.reset();
1112 // Add any successor to the adjacency matrix and exclude duplicates.
1113 for (auto &SI : SUnits[i].Succs) {
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001114 // Only create a back-edge on the first and last nodes of a dependence
1115 // chain. This records any chains and adds them later.
1116 if (SI.getKind() == SDep::Output) {
1117 int N = SI.getSUnit()->NodeNum;
1118 int BackEdge = i;
1119 auto Dep = OutputDeps.find(BackEdge);
1120 if (Dep != OutputDeps.end()) {
1121 BackEdge = Dep->second;
1122 OutputDeps.erase(Dep);
1123 }
1124 OutputDeps[N] = BackEdge;
1125 }
Sumanth Gundapaneniada0f512018-10-25 21:27:08 +00001126 // Do not process a boundary node, an artificial node.
1127 // A back-edge is processed only if it goes to a Phi.
1128 if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00001129 (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1130 continue;
1131 int N = SI.getSUnit()->NodeNum;
1132 if (!Added.test(N)) {
1133 AdjK[i].push_back(N);
1134 Added.set(N);
1135 }
1136 }
1137 // A chain edge between a store and a load is treated as a back-edge in the
1138 // adjacency matrix.
1139 for (auto &PI : SUnits[i].Preds) {
1140 if (!SUnits[i].getInstr()->mayStore() ||
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001141 !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001142 continue;
1143 if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1144 int N = PI.getSUnit()->NodeNum;
1145 if (!Added.test(N)) {
1146 AdjK[i].push_back(N);
1147 Added.set(N);
1148 }
1149 }
1150 }
1151 }
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00001152 // Add back-edges in the adjacency matrix for the output dependences.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001153 for (auto &OD : OutputDeps)
1154 if (!Added.test(OD.second)) {
1155 AdjK[OD.first].push_back(OD.second);
1156 Added.set(OD.second);
1157 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001158}
1159
1160/// Identify an elementary circuit in the dependence graph starting at the
1161/// specified node.
1162bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1163 bool HasBackedge) {
1164 SUnit *SV = &SUnits[V];
1165 bool F = false;
1166 Stack.insert(SV);
1167 Blocked.set(V);
1168
1169 for (auto W : AdjK[V]) {
1170 if (NumPaths > MaxPaths)
1171 break;
1172 if (W < S)
1173 continue;
1174 if (W == S) {
1175 if (!HasBackedge)
1176 NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1177 F = true;
1178 ++NumPaths;
1179 break;
1180 } else if (!Blocked.test(W)) {
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001181 if (circuit(W, S, NodeSets,
1182 Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001183 F = true;
1184 }
1185 }
1186
1187 if (F)
1188 unblock(V);
1189 else {
1190 for (auto W : AdjK[V]) {
1191 if (W < S)
1192 continue;
1193 if (B[W].count(SV) == 0)
1194 B[W].insert(SV);
1195 }
1196 }
1197 Stack.pop_back();
1198 return F;
1199}
1200
1201/// Unblock a node in the circuit finding algorithm.
1202void SwingSchedulerDAG::Circuits::unblock(int U) {
1203 Blocked.reset(U);
1204 SmallPtrSet<SUnit *, 4> &BU = B[U];
1205 while (!BU.empty()) {
1206 SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1207 assert(SI != BU.end() && "Invalid B set.");
1208 SUnit *W = *SI;
1209 BU.erase(W);
1210 if (Blocked.test(W->NodeNum))
1211 unblock(W->NodeNum);
1212 }
1213}
1214
1215/// Identify all the elementary circuits in the dependence graph using
1216/// Johnson's circuit algorithm.
1217void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1218 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1219 // but we do this to find the circuits, and then change them back.
1220 swapAntiDependences(SUnits);
1221
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001222 Circuits Cir(SUnits, Topo);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001223 // Create the adjacency structure.
1224 Cir.createAdjacencyStructure(this);
1225 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1226 Cir.reset();
1227 Cir.circuit(i, i, NodeSets);
1228 }
1229
1230 // Change the dependences back so that we've created a DAG again.
1231 swapAntiDependences(SUnits);
1232}
1233
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +00001234// Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1235// is loop-carried to the USE in next iteration. This will help pipeliner avoid
1236// additional copies that are needed across iterations. An artificial dependence
1237// edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1238
1239// PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1240// SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1241// PHI-------True-Dep------> USEOfPhi
1242
1243// The mutation creates
1244// USEOfPHI -------Artificial-Dep---> SRCOfCopy
1245
1246// This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1247// (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1248// late to avoid additional copies across iterations. The possible scheduling
1249// order would be
1250// USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1251
1252void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1253 for (SUnit &SU : DAG->SUnits) {
1254 // Find the COPY/REG_SEQUENCE instruction.
1255 if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1256 continue;
1257
1258 // Record the loop carried PHIs.
1259 SmallVector<SUnit *, 4> PHISUs;
1260 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1261 SmallVector<SUnit *, 4> SrcSUs;
1262
1263 for (auto &Dep : SU.Preds) {
1264 SUnit *TmpSU = Dep.getSUnit();
1265 MachineInstr *TmpMI = TmpSU->getInstr();
1266 SDep::Kind DepKind = Dep.getKind();
1267 // Save the loop carried PHI.
1268 if (DepKind == SDep::Anti && TmpMI->isPHI())
1269 PHISUs.push_back(TmpSU);
1270 // Save the source of COPY/REG_SEQUENCE.
1271 // If the source has no pre-decessors, we will end up creating cycles.
1272 else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1273 SrcSUs.push_back(TmpSU);
1274 }
1275
1276 if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1277 continue;
1278
1279 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1280 // SUnit to the container.
1281 SmallVector<SUnit *, 8> UseSUs;
1282 for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
1283 for (auto &Dep : (*I)->Succs) {
1284 if (Dep.getKind() != SDep::Data)
1285 continue;
1286
1287 SUnit *TmpSU = Dep.getSUnit();
1288 MachineInstr *TmpMI = TmpSU->getInstr();
1289 if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1290 PHISUs.push_back(TmpSU);
1291 continue;
1292 }
1293 UseSUs.push_back(TmpSU);
1294 }
1295 }
1296
1297 if (UseSUs.size() == 0)
1298 continue;
1299
1300 SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1301 // Add the artificial dependencies if it does not form a cycle.
1302 for (auto I : UseSUs) {
1303 for (auto Src : SrcSUs) {
1304 if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1305 Src->addPred(SDep(I, SDep::Artificial));
1306 SDAG->Topo.AddPred(Src, I);
1307 }
1308 }
1309 }
1310 }
1311}
1312
Brendon Cahoon254f8892016-07-29 16:44:44 +00001313/// Return true for DAG nodes that we ignore when computing the cost functions.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001314/// We ignore the back-edge recurrence in order to avoid unbounded recursion
Brendon Cahoon254f8892016-07-29 16:44:44 +00001315/// in the calculation of the ASAP, ALAP, etc functions.
1316static bool ignoreDependence(const SDep &D, bool isPred) {
1317 if (D.isArtificial())
1318 return true;
1319 return D.getKind() == SDep::Anti && isPred;
1320}
1321
1322/// Compute several functions need to order the nodes for scheduling.
1323/// ASAP - Earliest time to schedule a node.
1324/// ALAP - Latest time to schedule a node.
1325/// MOV - Mobility function, difference between ALAP and ASAP.
1326/// D - Depth of each node.
1327/// H - Height of each node.
1328void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001329 ScheduleInfo.resize(SUnits.size());
1330
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001331 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001332 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1333 E = Topo.end();
1334 I != E; ++I) {
Matthias Braun726e12c2018-09-19 00:23:35 +00001335 const SUnit &SU = SUnits[*I];
1336 dumpNode(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001337 }
1338 });
1339
1340 int maxASAP = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001341 // Compute ASAP and ZeroLatencyDepth.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001342 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1343 E = Topo.end();
1344 I != E; ++I) {
1345 int asap = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001346 int zeroLatencyDepth = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001347 SUnit *SU = &SUnits[*I];
1348 for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1349 EP = SU->Preds.end();
1350 IP != EP; ++IP) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001351 SUnit *pred = IP->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001352 if (IP->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001353 zeroLatencyDepth =
1354 std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001355 if (ignoreDependence(*IP, true))
1356 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001357 asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00001358 getDistance(pred, SU, *IP) * MII));
1359 }
1360 maxASAP = std::max(maxASAP, asap);
1361 ScheduleInfo[*I].ASAP = asap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001362 ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001363 }
1364
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001365 // Compute ALAP, ZeroLatencyHeight, and MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001366 for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1367 E = Topo.rend();
1368 I != E; ++I) {
1369 int alap = maxASAP;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001370 int zeroLatencyHeight = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001371 SUnit *SU = &SUnits[*I];
1372 for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1373 ES = SU->Succs.end();
1374 IS != ES; ++IS) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001375 SUnit *succ = IS->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001376 if (IS->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001377 zeroLatencyHeight =
1378 std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001379 if (ignoreDependence(*IS, true))
1380 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001381 alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00001382 getDistance(SU, succ, *IS) * MII));
1383 }
1384
1385 ScheduleInfo[*I].ALAP = alap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001386 ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001387 }
1388
1389 // After computing the node functions, compute the summary for each node set.
1390 for (NodeSet &I : NodeSets)
1391 I.computeNodeSetInfo(this);
1392
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001393 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001394 for (unsigned i = 0; i < SUnits.size(); i++) {
1395 dbgs() << "\tNode " << i << ":\n";
1396 dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
1397 dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
1398 dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
1399 dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
1400 dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001401 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1402 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001403 }
1404 });
1405}
1406
1407/// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1408/// as the predecessors of the elements of NodeOrder that are not also in
1409/// NodeOrder.
1410static bool pred_L(SetVector<SUnit *> &NodeOrder,
1411 SmallSetVector<SUnit *, 8> &Preds,
1412 const NodeSet *S = nullptr) {
1413 Preds.clear();
1414 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1415 I != E; ++I) {
1416 for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1417 PI != PE; ++PI) {
1418 if (S && S->count(PI->getSUnit()) == 0)
1419 continue;
1420 if (ignoreDependence(*PI, true))
1421 continue;
1422 if (NodeOrder.count(PI->getSUnit()) == 0)
1423 Preds.insert(PI->getSUnit());
1424 }
1425 // Back-edges are predecessors with an anti-dependence.
1426 for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1427 ES = (*I)->Succs.end();
1428 IS != ES; ++IS) {
1429 if (IS->getKind() != SDep::Anti)
1430 continue;
1431 if (S && S->count(IS->getSUnit()) == 0)
1432 continue;
1433 if (NodeOrder.count(IS->getSUnit()) == 0)
1434 Preds.insert(IS->getSUnit());
1435 }
1436 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001437 return !Preds.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001438}
1439
1440/// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1441/// as the successors of the elements of NodeOrder that are not also in
1442/// NodeOrder.
1443static bool succ_L(SetVector<SUnit *> &NodeOrder,
1444 SmallSetVector<SUnit *, 8> &Succs,
1445 const NodeSet *S = nullptr) {
1446 Succs.clear();
1447 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1448 I != E; ++I) {
1449 for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1450 SI != SE; ++SI) {
1451 if (S && S->count(SI->getSUnit()) == 0)
1452 continue;
1453 if (ignoreDependence(*SI, false))
1454 continue;
1455 if (NodeOrder.count(SI->getSUnit()) == 0)
1456 Succs.insert(SI->getSUnit());
1457 }
1458 for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1459 PE = (*I)->Preds.end();
1460 PI != PE; ++PI) {
1461 if (PI->getKind() != SDep::Anti)
1462 continue;
1463 if (S && S->count(PI->getSUnit()) == 0)
1464 continue;
1465 if (NodeOrder.count(PI->getSUnit()) == 0)
1466 Succs.insert(PI->getSUnit());
1467 }
1468 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001469 return !Succs.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001470}
1471
1472/// Return true if there is a path from the specified node to any of the nodes
1473/// in DestNodes. Keep track and return the nodes in any path.
1474static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1475 SetVector<SUnit *> &DestNodes,
1476 SetVector<SUnit *> &Exclude,
1477 SmallPtrSet<SUnit *, 8> &Visited) {
1478 if (Cur->isBoundaryNode())
1479 return false;
1480 if (Exclude.count(Cur) != 0)
1481 return false;
1482 if (DestNodes.count(Cur) != 0)
1483 return true;
1484 if (!Visited.insert(Cur).second)
1485 return Path.count(Cur) != 0;
1486 bool FoundPath = false;
1487 for (auto &SI : Cur->Succs)
1488 FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1489 for (auto &PI : Cur->Preds)
1490 if (PI.getKind() == SDep::Anti)
1491 FoundPath |=
1492 computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1493 if (FoundPath)
1494 Path.insert(Cur);
1495 return FoundPath;
1496}
1497
1498/// Return true if Set1 is a subset of Set2.
1499template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1500 for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1501 if (Set2.count(*I) == 0)
1502 return false;
1503 return true;
1504}
1505
1506/// Compute the live-out registers for the instructions in a node-set.
1507/// The live-out registers are those that are defined in the node-set,
1508/// but not used. Except for use operands of Phis.
1509static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1510 NodeSet &NS) {
1511 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1512 MachineRegisterInfo &MRI = MF.getRegInfo();
1513 SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1514 SmallSet<unsigned, 4> Uses;
1515 for (SUnit *SU : NS) {
1516 const MachineInstr *MI = SU->getInstr();
1517 if (MI->isPHI())
1518 continue;
Matthias Braunfc371552016-10-24 21:36:43 +00001519 for (const MachineOperand &MO : MI->operands())
1520 if (MO.isReg() && MO.isUse()) {
1521 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001522 if (TargetRegisterInfo::isVirtualRegister(Reg))
1523 Uses.insert(Reg);
1524 else if (MRI.isAllocatable(Reg))
1525 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1526 Uses.insert(*Units);
1527 }
1528 }
1529 for (SUnit *SU : NS)
Matthias Braunfc371552016-10-24 21:36:43 +00001530 for (const MachineOperand &MO : SU->getInstr()->operands())
1531 if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1532 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001533 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1534 if (!Uses.count(Reg))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001535 LiveOutRegs.push_back(RegisterMaskPair(Reg,
1536 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001537 } else if (MRI.isAllocatable(Reg)) {
1538 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1539 if (!Uses.count(*Units))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001540 LiveOutRegs.push_back(RegisterMaskPair(*Units,
1541 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001542 }
1543 }
1544 RPTracker.addLiveRegs(LiveOutRegs);
1545}
1546
1547/// A heuristic to filter nodes in recurrent node-sets if the register
1548/// pressure of a set is too high.
1549void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1550 for (auto &NS : NodeSets) {
1551 // Skip small node-sets since they won't cause register pressure problems.
1552 if (NS.size() <= 2)
1553 continue;
1554 IntervalPressure RecRegPressure;
1555 RegPressureTracker RecRPTracker(RecRegPressure);
1556 RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1557 computeLiveOuts(MF, RecRPTracker, NS);
1558 RecRPTracker.closeBottom();
1559
1560 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
Fangrui Song0cac7262018-09-27 02:13:45 +00001561 llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001562 return A->NodeNum > B->NodeNum;
1563 });
1564
1565 for (auto &SU : SUnits) {
1566 // Since we're computing the register pressure for a subset of the
1567 // instructions in a block, we need to set the tracker for each
1568 // instruction in the node-set. The tracker is set to the instruction
1569 // just after the one we're interested in.
1570 MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1571 RecRPTracker.setPos(std::next(CurInstI));
1572
1573 RegPressureDelta RPDelta;
1574 ArrayRef<PressureChange> CriticalPSets;
1575 RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1576 CriticalPSets,
1577 RecRegPressure.MaxSetPressure);
1578 if (RPDelta.Excess.isValid()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001579 LLVM_DEBUG(
1580 dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1581 << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1582 << ":" << RPDelta.Excess.getUnitInc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001583 NS.setExceedPressure(SU);
1584 break;
1585 }
1586 RecRPTracker.recede();
1587 }
1588 }
1589}
1590
1591/// A heuristic to colocate node sets that have the same set of
1592/// successors.
1593void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1594 unsigned Colocate = 0;
1595 for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1596 NodeSet &N1 = NodeSets[i];
1597 SmallSetVector<SUnit *, 8> S1;
1598 if (N1.empty() || !succ_L(N1, S1))
1599 continue;
1600 for (int j = i + 1; j < e; ++j) {
1601 NodeSet &N2 = NodeSets[j];
1602 if (N1.compareRecMII(N2) != 0)
1603 continue;
1604 SmallSetVector<SUnit *, 8> S2;
1605 if (N2.empty() || !succ_L(N2, S2))
1606 continue;
1607 if (isSubset(S1, S2) && S1.size() == S2.size()) {
1608 N1.setColocate(++Colocate);
1609 N2.setColocate(Colocate);
1610 break;
1611 }
1612 }
1613 }
1614}
1615
1616/// Check if the existing node-sets are profitable. If not, then ignore the
1617/// recurrent node-sets, and attempt to schedule all nodes together. This is
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001618/// a heuristic. If the MII is large and all the recurrent node-sets are small,
1619/// then it's best to try to schedule all instructions together instead of
1620/// starting with the recurrent node-sets.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001621void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1622 // Look for loops with a large MII.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001623 if (MII < 17)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001624 return;
1625 // Check if the node-set contains only a simple add recurrence.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001626 for (auto &NS : NodeSets) {
1627 if (NS.getRecMII() > 2)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001628 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001629 if (NS.getMaxDepth() > MII)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001630 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001631 }
1632 NodeSets.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001633 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001634 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001635}
1636
1637/// Add the nodes that do not belong to a recurrence set into groups
1638/// based upon connected componenets.
1639void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1640 SetVector<SUnit *> NodesAdded;
1641 SmallPtrSet<SUnit *, 8> Visited;
1642 // Add the nodes that are on a path between the previous node sets and
1643 // the current node set.
1644 for (NodeSet &I : NodeSets) {
1645 SmallSetVector<SUnit *, 8> N;
1646 // Add the nodes from the current node set to the previous node set.
1647 if (succ_L(I, N)) {
1648 SetVector<SUnit *> Path;
1649 for (SUnit *NI : N) {
1650 Visited.clear();
1651 computePath(NI, Path, NodesAdded, I, Visited);
1652 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001653 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001654 I.insert(Path.begin(), Path.end());
1655 }
1656 // Add the nodes from the previous node set to the current node set.
1657 N.clear();
1658 if (succ_L(NodesAdded, N)) {
1659 SetVector<SUnit *> Path;
1660 for (SUnit *NI : N) {
1661 Visited.clear();
1662 computePath(NI, Path, I, NodesAdded, Visited);
1663 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001664 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001665 I.insert(Path.begin(), Path.end());
1666 }
1667 NodesAdded.insert(I.begin(), I.end());
1668 }
1669
1670 // Create a new node set with the connected nodes of any successor of a node
1671 // in a recurrent set.
1672 NodeSet NewSet;
1673 SmallSetVector<SUnit *, 8> N;
1674 if (succ_L(NodesAdded, N))
1675 for (SUnit *I : N)
1676 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001677 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001678 NodeSets.push_back(NewSet);
1679
1680 // Create a new node set with the connected nodes of any predecessor of a node
1681 // in a recurrent set.
1682 NewSet.clear();
1683 if (pred_L(NodesAdded, N))
1684 for (SUnit *I : N)
1685 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001686 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001687 NodeSets.push_back(NewSet);
1688
Hiroshi Inoue372ffa12018-04-13 11:37:06 +00001689 // Create new nodes sets with the connected nodes any remaining node that
Brendon Cahoon254f8892016-07-29 16:44:44 +00001690 // has no predecessor.
1691 for (unsigned i = 0; i < SUnits.size(); ++i) {
1692 SUnit *SU = &SUnits[i];
1693 if (NodesAdded.count(SU) == 0) {
1694 NewSet.clear();
1695 addConnectedNodes(SU, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001696 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001697 NodeSets.push_back(NewSet);
1698 }
1699 }
1700}
1701
Alexey Lapshin31f47b82019-01-25 21:59:53 +00001702/// Add the node to the set, and add all of its connected nodes to the set.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001703void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1704 SetVector<SUnit *> &NodesAdded) {
1705 NewSet.insert(SU);
1706 NodesAdded.insert(SU);
1707 for (auto &SI : SU->Succs) {
1708 SUnit *Successor = SI.getSUnit();
1709 if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1710 addConnectedNodes(Successor, NewSet, NodesAdded);
1711 }
1712 for (auto &PI : SU->Preds) {
1713 SUnit *Predecessor = PI.getSUnit();
1714 if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1715 addConnectedNodes(Predecessor, NewSet, NodesAdded);
1716 }
1717}
1718
1719/// Return true if Set1 contains elements in Set2. The elements in common
1720/// are returned in a different container.
1721static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1722 SmallSetVector<SUnit *, 8> &Result) {
1723 Result.clear();
1724 for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1725 SUnit *SU = Set1[i];
1726 if (Set2.count(SU) != 0)
1727 Result.insert(SU);
1728 }
1729 return !Result.empty();
1730}
1731
1732/// Merge the recurrence node sets that have the same initial node.
1733void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1734 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1735 ++I) {
1736 NodeSet &NI = *I;
1737 for (NodeSetType::iterator J = I + 1; J != E;) {
1738 NodeSet &NJ = *J;
1739 if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1740 if (NJ.compareRecMII(NI) > 0)
1741 NI.setRecMII(NJ.getRecMII());
1742 for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1743 ++NII)
1744 I->insert(*NII);
1745 NodeSets.erase(J);
1746 E = NodeSets.end();
1747 } else {
1748 ++J;
1749 }
1750 }
1751 }
1752}
1753
1754/// Remove nodes that have been scheduled in previous NodeSets.
1755void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1756 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1757 ++I)
1758 for (NodeSetType::iterator J = I + 1; J != E;) {
1759 J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1760
Eugene Zelenko32a40562017-09-11 23:00:48 +00001761 if (J->empty()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001762 NodeSets.erase(J);
1763 E = NodeSets.end();
1764 } else {
1765 ++J;
1766 }
1767 }
1768}
1769
Brendon Cahoon254f8892016-07-29 16:44:44 +00001770/// Compute an ordered list of the dependence graph nodes, which
1771/// indicates the order that the nodes will be scheduled. This is a
1772/// two-level algorithm. First, a partial order is created, which
1773/// consists of a list of sets ordered from highest to lowest priority.
1774void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1775 SmallSetVector<SUnit *, 8> R;
1776 NodeOrder.clear();
1777
1778 for (auto &Nodes : NodeSets) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001779 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001780 OrderKind Order;
1781 SmallSetVector<SUnit *, 8> N;
1782 if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1783 R.insert(N.begin(), N.end());
1784 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001785 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001786 } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1787 R.insert(N.begin(), N.end());
1788 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001789 LLVM_DEBUG(dbgs() << " Top down (succs) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001790 } else if (isIntersect(N, Nodes, R)) {
1791 // If some of the successors are in the existing node-set, then use the
1792 // top-down ordering.
1793 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001794 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001795 } else if (NodeSets.size() == 1) {
1796 for (auto &N : Nodes)
1797 if (N->Succs.size() == 0)
1798 R.insert(N);
1799 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001800 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001801 } else {
1802 // Find the node with the highest ASAP.
1803 SUnit *maxASAP = nullptr;
1804 for (SUnit *SU : Nodes) {
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001805 if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1806 (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001807 maxASAP = SU;
1808 }
1809 R.insert(maxASAP);
1810 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001811 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001812 }
1813
1814 while (!R.empty()) {
1815 if (Order == TopDown) {
1816 // Choose the node with the maximum height. If more than one, choose
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001817 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001818 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001819 while (!R.empty()) {
1820 SUnit *maxHeight = nullptr;
1821 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001822 if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001823 maxHeight = I;
1824 else if (getHeight(I) == getHeight(maxHeight) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001825 getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001826 maxHeight = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001827 else if (getHeight(I) == getHeight(maxHeight) &&
1828 getZeroLatencyHeight(I) ==
1829 getZeroLatencyHeight(maxHeight) &&
1830 getMOV(I) < getMOV(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001831 maxHeight = I;
1832 }
1833 NodeOrder.insert(maxHeight);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001834 LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001835 R.remove(maxHeight);
1836 for (const auto &I : maxHeight->Succs) {
1837 if (Nodes.count(I.getSUnit()) == 0)
1838 continue;
1839 if (NodeOrder.count(I.getSUnit()) != 0)
1840 continue;
1841 if (ignoreDependence(I, false))
1842 continue;
1843 R.insert(I.getSUnit());
1844 }
1845 // Back-edges are predecessors with an anti-dependence.
1846 for (const auto &I : maxHeight->Preds) {
1847 if (I.getKind() != SDep::Anti)
1848 continue;
1849 if (Nodes.count(I.getSUnit()) == 0)
1850 continue;
1851 if (NodeOrder.count(I.getSUnit()) != 0)
1852 continue;
1853 R.insert(I.getSUnit());
1854 }
1855 }
1856 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001857 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001858 SmallSetVector<SUnit *, 8> N;
1859 if (pred_L(NodeOrder, N, &Nodes))
1860 R.insert(N.begin(), N.end());
1861 } else {
1862 // Choose the node with the maximum depth. If more than one, choose
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001863 // the node with the maximum ZeroLatencyDepth. If still more than one,
1864 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001865 while (!R.empty()) {
1866 SUnit *maxDepth = nullptr;
1867 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001868 if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001869 maxDepth = I;
1870 else if (getDepth(I) == getDepth(maxDepth) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001871 getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001872 maxDepth = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001873 else if (getDepth(I) == getDepth(maxDepth) &&
1874 getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
1875 getMOV(I) < getMOV(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001876 maxDepth = I;
1877 }
1878 NodeOrder.insert(maxDepth);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001879 LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001880 R.remove(maxDepth);
1881 if (Nodes.isExceedSU(maxDepth)) {
1882 Order = TopDown;
1883 R.clear();
1884 R.insert(Nodes.getNode(0));
1885 break;
1886 }
1887 for (const auto &I : maxDepth->Preds) {
1888 if (Nodes.count(I.getSUnit()) == 0)
1889 continue;
1890 if (NodeOrder.count(I.getSUnit()) != 0)
1891 continue;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001892 R.insert(I.getSUnit());
1893 }
1894 // Back-edges are predecessors with an anti-dependence.
1895 for (const auto &I : maxDepth->Succs) {
1896 if (I.getKind() != SDep::Anti)
1897 continue;
1898 if (Nodes.count(I.getSUnit()) == 0)
1899 continue;
1900 if (NodeOrder.count(I.getSUnit()) != 0)
1901 continue;
1902 R.insert(I.getSUnit());
1903 }
1904 }
1905 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001906 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001907 SmallSetVector<SUnit *, 8> N;
1908 if (succ_L(NodeOrder, N, &Nodes))
1909 R.insert(N.begin(), N.end());
1910 }
1911 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001912 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001913 }
1914
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001915 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001916 dbgs() << "Node order: ";
1917 for (SUnit *I : NodeOrder)
1918 dbgs() << " " << I->NodeNum << " ";
1919 dbgs() << "\n";
1920 });
1921}
1922
1923/// Process the nodes in the computed order and create the pipelined schedule
1924/// of the instructions, if possible. Return true if a schedule is found.
1925bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001926
1927 if (NodeOrder.empty()){
1928 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
Brendon Cahoon254f8892016-07-29 16:44:44 +00001929 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001930 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001931
1932 bool scheduleFound = false;
Brendon Cahoon59d99732019-01-23 03:26:10 +00001933 unsigned II = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001934 // Keep increasing II until a valid schedule is found.
Brendon Cahoon59d99732019-01-23 03:26:10 +00001935 for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001936 Schedule.reset();
1937 Schedule.setInitiationInterval(II);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001938 LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001939
1940 SetVector<SUnit *>::iterator NI = NodeOrder.begin();
1941 SetVector<SUnit *>::iterator NE = NodeOrder.end();
1942 do {
1943 SUnit *SU = *NI;
1944
1945 // Compute the schedule time for the instruction, which is based
1946 // upon the scheduled time for any predecessors/successors.
1947 int EarlyStart = INT_MIN;
1948 int LateStart = INT_MAX;
1949 // These values are set when the size of the schedule window is limited
1950 // due to chain dependences.
1951 int SchedEnd = INT_MAX;
1952 int SchedStart = INT_MIN;
1953 Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1954 II, this);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001955 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001956 dbgs() << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001957 dbgs() << "Inst (" << SU->NodeNum << ") ";
1958 SU->getInstr()->dump();
1959 dbgs() << "\n";
1960 });
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001961 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001962 dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
1963 LateStart, SchedEnd, SchedStart);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001964 });
1965
1966 if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
1967 SchedStart > LateStart)
1968 scheduleFound = false;
1969 else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
1970 SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
1971 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1972 } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
1973 SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
1974 scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
1975 } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
1976 SchedEnd =
1977 std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
1978 // When scheduling a Phi it is better to start at the late cycle and go
1979 // backwards. The default order may insert the Phi too far away from
1980 // its first dependence.
1981 if (SU->getInstr()->isPHI())
1982 scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
1983 else
1984 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1985 } else {
1986 int FirstCycle = Schedule.getFirstCycle();
1987 scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
1988 FirstCycle + getASAP(SU) + II - 1, II);
1989 }
1990 // Even if we find a schedule, make sure the schedule doesn't exceed the
1991 // allowable number of stages. We keep trying if this happens.
1992 if (scheduleFound)
1993 if (SwpMaxStages > -1 &&
1994 Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
1995 scheduleFound = false;
1996
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001997 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001998 if (!scheduleFound)
1999 dbgs() << "\tCan't schedule\n";
2000 });
2001 } while (++NI != NE && scheduleFound);
2002
2003 // If a schedule is found, check if it is a valid schedule too.
2004 if (scheduleFound)
2005 scheduleFound = Schedule.isValidSchedule(this);
2006 }
2007
Brendon Cahoon59d99732019-01-23 03:26:10 +00002008 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
2009 << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00002010
2011 if (scheduleFound)
2012 Schedule.finalizeSchedule(this);
2013 else
2014 Schedule.reset();
2015
2016 return scheduleFound && Schedule.getMaxStageCount() > 0;
2017}
2018
2019/// Given a schedule for the loop, generate a new version of the loop,
2020/// and replace the old version. This function generates a prolog
2021/// that contains the initial iterations in the pipeline, and kernel
2022/// loop, and the epilogue that contains the code for the final
2023/// iterations.
2024void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2025 // Create a new basic block for the kernel and add it to the CFG.
2026 MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2027
2028 unsigned MaxStageCount = Schedule.getMaxStageCount();
2029
2030 // Remember the registers that are used in different stages. The index is
2031 // the iteration, or stage, that the instruction is scheduled in. This is
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002032 // a map between register names in the original block and the names created
Brendon Cahoon254f8892016-07-29 16:44:44 +00002033 // in each stage of the pipelined loop.
2034 ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
2035 InstrMapTy InstrMap;
2036
2037 SmallVector<MachineBasicBlock *, 4> PrologBBs;
Jinsong Jief2d6d92019-06-11 17:40:39 +00002038
2039 MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
2040 assert(PreheaderBB != nullptr &&
2041 "Need to add code to handle loops w/o preheader");
Brendon Cahoon254f8892016-07-29 16:44:44 +00002042 // Generate the prolog instructions that set up the pipeline.
2043 generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2044 MF.insert(BB->getIterator(), KernelBB);
2045
2046 // Rearrange the instructions to generate the new, pipelined loop,
2047 // and update register names as needed.
2048 for (int Cycle = Schedule.getFirstCycle(),
2049 LastCycle = Schedule.getFinalCycle();
2050 Cycle <= LastCycle; ++Cycle) {
2051 std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2052 // This inner loop schedules each instruction in the cycle.
2053 for (SUnit *CI : CycleInstrs) {
2054 if (CI->getInstr()->isPHI())
2055 continue;
2056 unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2057 MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2058 updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
2059 KernelBB->push_back(NewMI);
2060 InstrMap[NewMI] = CI->getInstr();
2061 }
2062 }
2063
2064 // Copy any terminator instructions to the new kernel, and update
2065 // names as needed.
2066 for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
2067 E = BB->instr_end();
2068 I != E; ++I) {
2069 MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
2070 updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
2071 KernelBB->push_back(NewMI);
2072 InstrMap[NewMI] = &*I;
2073 }
2074
2075 KernelBB->transferSuccessors(BB);
2076 KernelBB->replaceSuccessor(BB, KernelBB);
2077
2078 generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
2079 VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
2080 generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
2081 InstrMap, MaxStageCount, MaxStageCount, false);
2082
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002083 LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00002084
2085 SmallVector<MachineBasicBlock *, 4> EpilogBBs;
2086 // Generate the epilog instructions to complete the pipeline.
2087 generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2088 PrologBBs);
2089
2090 // We need this step because the register allocation doesn't handle some
2091 // situations well, so we insert copies to help out.
2092 splitLifetimes(KernelBB, EpilogBBs, Schedule);
2093
2094 // Remove dead instructions due to loop induction variables.
2095 removeDeadInstructions(KernelBB, EpilogBBs);
2096
2097 // Add branches between prolog and epilog blocks.
Jinsong Jief2d6d92019-06-11 17:40:39 +00002098 addBranches(*PreheaderBB, PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002099
2100 // Remove the original loop since it's no longer referenced.
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002101 for (auto &I : *BB)
2102 LIS.RemoveMachineInstrFromMaps(I);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002103 BB->clear();
2104 BB->eraseFromParent();
2105
2106 delete[] VRMap;
2107}
2108
2109/// Generate the pipeline prolog code.
2110void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
2111 MachineBasicBlock *KernelBB,
2112 ValueMapTy *VRMap,
2113 MBBVectorTy &PrologBBs) {
2114 MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
Eugene Zelenko32a40562017-09-11 23:00:48 +00002115 assert(PreheaderBB != nullptr &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002116 "Need to add code to handle loops w/o preheader");
2117 MachineBasicBlock *PredBB = PreheaderBB;
2118 InstrMapTy InstrMap;
2119
2120 // Generate a basic block for each stage, not including the last stage,
2121 // which will be generated in the kernel. Each basic block may contain
2122 // instructions from multiple stages/iterations.
2123 for (unsigned i = 0; i < LastStage; ++i) {
2124 // Create and insert the prolog basic block prior to the original loop
2125 // basic block. The original loop is removed later.
2126 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2127 PrologBBs.push_back(NewBB);
2128 MF.insert(BB->getIterator(), NewBB);
2129 NewBB->transferSuccessors(PredBB);
2130 PredBB->addSuccessor(NewBB);
2131 PredBB = NewBB;
2132
2133 // Generate instructions for each appropriate stage. Process instructions
2134 // in original program order.
2135 for (int StageNum = i; StageNum >= 0; --StageNum) {
2136 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2137 BBE = BB->getFirstTerminator();
2138 BBI != BBE; ++BBI) {
2139 if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
2140 if (BBI->isPHI())
2141 continue;
2142 MachineInstr *NewMI =
2143 cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
2144 updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
2145 VRMap);
2146 NewBB->push_back(NewMI);
2147 InstrMap[NewMI] = &*BBI;
2148 }
2149 }
2150 }
2151 rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002152 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002153 dbgs() << "prolog:\n";
2154 NewBB->dump();
2155 });
2156 }
2157
2158 PredBB->replaceSuccessor(BB, KernelBB);
2159
2160 // Check if we need to remove the branch from the preheader to the original
2161 // loop, and replace it with a branch to the new loop.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002162 unsigned numBranches = TII->removeBranch(*PreheaderBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002163 if (numBranches) {
2164 SmallVector<MachineOperand, 0> Cond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002165 TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002166 }
2167}
2168
2169/// Generate the pipeline epilog code. The epilog code finishes the iterations
2170/// that were started in either the prolog or the kernel. We create a basic
2171/// block for each stage that needs to complete.
2172void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
2173 MachineBasicBlock *KernelBB,
2174 ValueMapTy *VRMap,
2175 MBBVectorTy &EpilogBBs,
2176 MBBVectorTy &PrologBBs) {
2177 // We need to change the branch from the kernel to the first epilog block, so
2178 // this call to analyze branch uses the kernel rather than the original BB.
2179 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2180 SmallVector<MachineOperand, 4> Cond;
2181 bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2182 assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2183 if (checkBranch)
2184 return;
2185
2186 MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2187 if (*LoopExitI == KernelBB)
2188 ++LoopExitI;
2189 assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2190 MachineBasicBlock *LoopExitBB = *LoopExitI;
2191
2192 MachineBasicBlock *PredBB = KernelBB;
2193 MachineBasicBlock *EpilogStart = LoopExitBB;
2194 InstrMapTy InstrMap;
2195
2196 // Generate a basic block for each stage, not including the last stage,
2197 // which was generated for the kernel. Each basic block may contain
2198 // instructions from multiple stages/iterations.
2199 int EpilogStage = LastStage + 1;
2200 for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2201 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2202 EpilogBBs.push_back(NewBB);
2203 MF.insert(BB->getIterator(), NewBB);
2204
2205 PredBB->replaceSuccessor(LoopExitBB, NewBB);
2206 NewBB->addSuccessor(LoopExitBB);
2207
2208 if (EpilogStart == LoopExitBB)
2209 EpilogStart = NewBB;
2210
2211 // Add instructions to the epilog depending on the current block.
2212 // Process instructions in original program order.
2213 for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2214 for (auto &BBI : *BB) {
2215 if (BBI.isPHI())
2216 continue;
2217 MachineInstr *In = &BBI;
2218 if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002219 // Instructions with memoperands in the epilog are updated with
2220 // conservative values.
2221 MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002222 updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2223 NewBB->push_back(NewMI);
2224 InstrMap[NewMI] = In;
2225 }
2226 }
2227 }
2228 generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2229 VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2230 generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2231 InstrMap, LastStage, EpilogStage, i == 1);
2232 PredBB = NewBB;
2233
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002234 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002235 dbgs() << "epilog:\n";
2236 NewBB->dump();
2237 });
2238 }
2239
2240 // Fix any Phi nodes in the loop exit block.
2241 for (MachineInstr &MI : *LoopExitBB) {
2242 if (!MI.isPHI())
2243 break;
2244 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2245 MachineOperand &MO = MI.getOperand(i);
2246 if (MO.getMBB() == BB)
2247 MO.setMBB(PredBB);
2248 }
2249 }
2250
2251 // Create a branch to the new epilog from the kernel.
2252 // Remove the original branch and add a new branch to the epilog.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002253 TII->removeBranch(*KernelBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002254 TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002255 // Add a branch to the loop exit.
2256 if (EpilogBBs.size() > 0) {
2257 MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2258 SmallVector<MachineOperand, 4> Cond1;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002259 TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002260 }
2261}
2262
2263/// Replace all uses of FromReg that appear outside the specified
2264/// basic block with ToReg.
2265static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2266 MachineBasicBlock *MBB,
2267 MachineRegisterInfo &MRI,
2268 LiveIntervals &LIS) {
2269 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2270 E = MRI.use_end();
2271 I != E;) {
2272 MachineOperand &O = *I;
2273 ++I;
2274 if (O.getParent()->getParent() != MBB)
2275 O.setReg(ToReg);
2276 }
2277 if (!LIS.hasInterval(ToReg))
2278 LIS.createEmptyInterval(ToReg);
2279}
2280
2281/// Return true if the register has a use that occurs outside the
2282/// specified loop.
2283static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2284 MachineRegisterInfo &MRI) {
2285 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2286 E = MRI.use_end();
2287 I != E; ++I)
2288 if (I->getParent()->getParent() != BB)
2289 return true;
2290 return false;
2291}
2292
2293/// Generate Phis for the specific block in the generated pipelined code.
2294/// This function looks at the Phis from the original code to guide the
2295/// creation of new Phis.
2296void SwingSchedulerDAG::generateExistingPhis(
2297 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2298 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2299 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2300 bool IsLast) {
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00002301 // Compute the stage number for the initial value of the Phi, which
Brendon Cahoon254f8892016-07-29 16:44:44 +00002302 // comes from the prolog. The prolog to use depends on to which kernel/
2303 // epilog that we're adding the Phi.
2304 unsigned PrologStage = 0;
2305 unsigned PrevStage = 0;
2306 bool InKernel = (LastStageNum == CurStageNum);
2307 if (InKernel) {
2308 PrologStage = LastStageNum - 1;
2309 PrevStage = CurStageNum;
2310 } else {
2311 PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2312 PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2313 }
2314
2315 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2316 BBE = BB->getFirstNonPHI();
2317 BBI != BBE; ++BBI) {
2318 unsigned Def = BBI->getOperand(0).getReg();
2319
2320 unsigned InitVal = 0;
2321 unsigned LoopVal = 0;
2322 getPhiRegs(*BBI, BB, InitVal, LoopVal);
2323
2324 unsigned PhiOp1 = 0;
2325 // The Phi value from the loop body typically is defined in the loop, but
2326 // not always. So, we need to check if the value is defined in the loop.
2327 unsigned PhiOp2 = LoopVal;
2328 if (VRMap[LastStageNum].count(LoopVal))
2329 PhiOp2 = VRMap[LastStageNum][LoopVal];
2330
2331 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2332 int LoopValStage =
2333 Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2334 unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2335 if (NumStages == 0) {
2336 // We don't need to generate a Phi anymore, but we need to rename any uses
2337 // of the Phi value.
2338 unsigned NewReg = VRMap[PrevStage][LoopVal];
2339 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
Krzysztof Parzyszek16e66f52018-03-26 16:41:36 +00002340 Def, InitVal, NewReg);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002341 if (VRMap[CurStageNum].count(LoopVal))
2342 VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2343 }
2344 // Adjust the number of Phis needed depending on the number of prologs left,
Krzysztof Parzyszek3f72a6b2018-03-26 16:37:55 +00002345 // and the distance from where the Phi is first scheduled. The number of
2346 // Phis cannot exceed the number of prolog stages. Each stage can
2347 // potentially define two values.
2348 unsigned MaxPhis = PrologStage + 2;
2349 if (!InKernel && (int)PrologStage <= LoopValStage)
2350 MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
2351 unsigned NumPhis = std::min(NumStages, MaxPhis);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002352
2353 unsigned NewReg = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002354 unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2355 // In the epilog, we may need to look back one stage to get the correct
2356 // Phi name because the epilog and prolog blocks execute the same stage.
2357 // The correct name is from the previous block only when the Phi has
2358 // been completely scheduled prior to the epilog, and Phi value is not
2359 // needed in multiple stages.
2360 int StageDiff = 0;
2361 if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2362 NumPhis == 1)
2363 StageDiff = 1;
2364 // Adjust the computations below when the phi and the loop definition
2365 // are scheduled in different stages.
2366 if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2367 StageDiff = StageScheduled - LoopValStage;
2368 for (unsigned np = 0; np < NumPhis; ++np) {
2369 // If the Phi hasn't been scheduled, then use the initial Phi operand
2370 // value. Otherwise, use the scheduled version of the instruction. This
2371 // is a little complicated when a Phi references another Phi.
2372 if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2373 PhiOp1 = InitVal;
2374 // Check if the Phi has already been scheduled in a prolog stage.
2375 else if (PrologStage >= AccessStage + StageDiff + np &&
2376 VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2377 PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00002378 // Check if the Phi has already been scheduled, but the loop instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00002379 // is either another Phi, or doesn't occur in the loop.
2380 else if (PrologStage >= AccessStage + StageDiff + np) {
2381 // If the Phi references another Phi, we need to examine the other
2382 // Phi to get the correct value.
2383 PhiOp1 = LoopVal;
2384 MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2385 int Indirects = 1;
2386 while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2387 int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2388 if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2389 PhiOp1 = getInitPhiReg(*InstOp1, BB);
2390 else
2391 PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2392 InstOp1 = MRI.getVRegDef(PhiOp1);
2393 int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2394 int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2395 if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2396 VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2397 PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2398 break;
2399 }
2400 ++Indirects;
2401 }
2402 } else
2403 PhiOp1 = InitVal;
2404 // If this references a generated Phi in the kernel, get the Phi operand
2405 // from the incoming block.
2406 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2407 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2408 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2409
2410 MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2411 bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2412 // In the epilog, a map lookup is needed to get the value from the kernel,
2413 // or previous epilog block. How is does this depends on if the
2414 // instruction is scheduled in the previous block.
2415 if (!InKernel) {
2416 int StageDiffAdj = 0;
2417 if (LoopValStage != -1 && StageScheduled > LoopValStage)
2418 StageDiffAdj = StageScheduled - LoopValStage;
2419 // Use the loop value defined in the kernel, unless the kernel
2420 // contains the last definition of the Phi.
2421 if (np == 0 && PrevStage == LastStageNum &&
2422 (StageScheduled != 0 || LoopValStage != 0) &&
2423 VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2424 PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2425 // Use the value defined by the Phi. We add one because we switch
2426 // from looking at the loop value to the Phi definition.
2427 else if (np > 0 && PrevStage == LastStageNum &&
2428 VRMap[PrevStage - np + 1].count(Def))
2429 PhiOp2 = VRMap[PrevStage - np + 1][Def];
2430 // Use the loop value defined in the kernel.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002431 else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002432 VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2433 PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2434 // Use the value defined by the Phi, unless we're generating the first
2435 // epilog and the Phi refers to a Phi in a different stage.
2436 else if (VRMap[PrevStage - np].count(Def) &&
2437 (!LoopDefIsPhi || PrevStage != LastStageNum))
2438 PhiOp2 = VRMap[PrevStage - np][Def];
2439 }
2440
2441 // Check if we can reuse an existing Phi. This occurs when a Phi
2442 // references another Phi, and the other Phi is scheduled in an
2443 // earlier stage. We can try to reuse an existing Phi up until the last
2444 // stage of the current Phi.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002445 if (LoopDefIsPhi) {
2446 if (static_cast<int>(PrologStage - np) >= StageScheduled) {
2447 int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2448 int StageDiff = (StageScheduled - LoopValStage);
2449 LVNumStages -= StageDiff;
2450 // Make sure the loop value Phi has been processed already.
2451 if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
2452 NewReg = PhiOp2;
2453 unsigned ReuseStage = CurStageNum;
2454 if (Schedule.isLoopCarried(this, *PhiInst))
2455 ReuseStage -= LVNumStages;
2456 // Check if the Phi to reuse has been generated yet. If not, then
2457 // there is nothing to reuse.
2458 if (VRMap[ReuseStage - np].count(LoopVal)) {
2459 NewReg = VRMap[ReuseStage - np][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002460
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002461 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2462 &*BBI, Def, NewReg);
2463 // Update the map with the new Phi name.
2464 VRMap[CurStageNum - np][Def] = NewReg;
2465 PhiOp2 = NewReg;
2466 if (VRMap[LastStageNum - np - 1].count(LoopVal))
2467 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002468
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002469 if (IsLast && np == NumPhis - 1)
2470 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2471 continue;
2472 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002473 }
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002474 }
2475 if (InKernel && StageDiff > 0 &&
2476 VRMap[CurStageNum - StageDiff - np].count(LoopVal))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002477 PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2478 }
2479
2480 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2481 NewReg = MRI.createVirtualRegister(RC);
2482
2483 MachineInstrBuilder NewPhi =
2484 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2485 TII->get(TargetOpcode::PHI), NewReg);
2486 NewPhi.addReg(PhiOp1).addMBB(BB1);
2487 NewPhi.addReg(PhiOp2).addMBB(BB2);
2488 if (np == 0)
2489 InstrMap[NewPhi] = &*BBI;
2490
2491 // We define the Phis after creating the new pipelined code, so
2492 // we need to rename the Phi values in scheduled instructions.
2493
2494 unsigned PrevReg = 0;
2495 if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2496 PrevReg = VRMap[PrevStage - np][LoopVal];
2497 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2498 Def, NewReg, PrevReg);
2499 // If the Phi has been scheduled, use the new name for rewriting.
2500 if (VRMap[CurStageNum - np].count(Def)) {
2501 unsigned R = VRMap[CurStageNum - np][Def];
2502 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2503 R, NewReg);
2504 }
2505
2506 // Check if we need to rename any uses that occurs after the loop. The
2507 // register to replace depends on whether the Phi is scheduled in the
2508 // epilog.
2509 if (IsLast && np == NumPhis - 1)
2510 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2511
2512 // In the kernel, a dependent Phi uses the value from this Phi.
2513 if (InKernel)
2514 PhiOp2 = NewReg;
2515
2516 // Update the map with the new Phi name.
2517 VRMap[CurStageNum - np][Def] = NewReg;
2518 }
2519
2520 while (NumPhis++ < NumStages) {
2521 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2522 &*BBI, Def, NewReg, 0);
2523 }
2524
2525 // Check if we need to rename a Phi that has been eliminated due to
2526 // scheduling.
2527 if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2528 replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2529 }
2530}
2531
2532/// Generate Phis for the specified block in the generated pipelined code.
2533/// These are new Phis needed because the definition is scheduled after the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002534/// use in the pipelined sequence.
Brendon Cahoon254f8892016-07-29 16:44:44 +00002535void SwingSchedulerDAG::generatePhis(
2536 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2537 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2538 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2539 bool IsLast) {
2540 // Compute the stage number that contains the initial Phi value, and
2541 // the Phi from the previous stage.
2542 unsigned PrologStage = 0;
2543 unsigned PrevStage = 0;
2544 unsigned StageDiff = CurStageNum - LastStageNum;
2545 bool InKernel = (StageDiff == 0);
2546 if (InKernel) {
2547 PrologStage = LastStageNum - 1;
2548 PrevStage = CurStageNum;
2549 } else {
2550 PrologStage = LastStageNum - StageDiff;
2551 PrevStage = LastStageNum + StageDiff - 1;
2552 }
2553
2554 for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2555 BBE = BB->instr_end();
2556 BBI != BBE; ++BBI) {
2557 for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2558 MachineOperand &MO = BBI->getOperand(i);
2559 if (!MO.isReg() || !MO.isDef() ||
2560 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2561 continue;
2562
2563 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2564 assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2565 unsigned Def = MO.getReg();
2566 unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2567 // An instruction scheduled in stage 0 and is used after the loop
2568 // requires a phi in the epilog for the last definition from either
2569 // the kernel or prolog.
2570 if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2571 hasUseAfterLoop(Def, BB, MRI))
2572 NumPhis = 1;
2573 if (!InKernel && (unsigned)StageScheduled > PrologStage)
2574 continue;
2575
2576 unsigned PhiOp2 = VRMap[PrevStage][Def];
2577 if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2578 if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2579 PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2580 // The number of Phis can't exceed the number of prolog stages. The
2581 // prolog stage number is zero based.
2582 if (NumPhis > PrologStage + 1 - StageScheduled)
2583 NumPhis = PrologStage + 1 - StageScheduled;
2584 for (unsigned np = 0; np < NumPhis; ++np) {
2585 unsigned PhiOp1 = VRMap[PrologStage][Def];
2586 if (np <= PrologStage)
2587 PhiOp1 = VRMap[PrologStage - np][Def];
2588 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2589 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2590 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2591 if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2592 PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2593 }
2594 if (!InKernel)
2595 PhiOp2 = VRMap[PrevStage - np][Def];
2596
2597 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2598 unsigned NewReg = MRI.createVirtualRegister(RC);
2599
2600 MachineInstrBuilder NewPhi =
2601 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2602 TII->get(TargetOpcode::PHI), NewReg);
2603 NewPhi.addReg(PhiOp1).addMBB(BB1);
2604 NewPhi.addReg(PhiOp2).addMBB(BB2);
2605 if (np == 0)
2606 InstrMap[NewPhi] = &*BBI;
2607
2608 // Rewrite uses and update the map. The actions depend upon whether
2609 // we generating code for the kernel or epilog blocks.
2610 if (InKernel) {
2611 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2612 &*BBI, PhiOp1, NewReg);
2613 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2614 &*BBI, PhiOp2, NewReg);
2615
2616 PhiOp2 = NewReg;
2617 VRMap[PrevStage - np - 1][Def] = NewReg;
2618 } else {
2619 VRMap[CurStageNum - np][Def] = NewReg;
2620 if (np == NumPhis - 1)
2621 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2622 &*BBI, Def, NewReg);
2623 }
2624 if (IsLast && np == NumPhis - 1)
2625 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2626 }
2627 }
2628 }
2629}
2630
2631/// Remove instructions that generate values with no uses.
2632/// Typically, these are induction variable operations that generate values
2633/// used in the loop itself. A dead instruction has a definition with
2634/// no uses, or uses that occur in the original loop only.
2635void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2636 MBBVectorTy &EpilogBBs) {
2637 // For each epilog block, check that the value defined by each instruction
2638 // is used. If not, delete it.
2639 for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2640 MBE = EpilogBBs.rend();
2641 MBB != MBE; ++MBB)
2642 for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2643 ME = (*MBB)->instr_rend();
2644 MI != ME;) {
2645 // From DeadMachineInstructionElem. Don't delete inline assembly.
2646 if (MI->isInlineAsm()) {
2647 ++MI;
2648 continue;
2649 }
2650 bool SawStore = false;
2651 // Check if it's safe to remove the instruction due to side effects.
2652 // We can, and want to, remove Phis here.
2653 if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2654 ++MI;
2655 continue;
2656 }
2657 bool used = true;
2658 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2659 MOE = MI->operands_end();
2660 MOI != MOE; ++MOI) {
2661 if (!MOI->isReg() || !MOI->isDef())
2662 continue;
2663 unsigned reg = MOI->getReg();
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00002664 // Assume physical registers are used, unless they are marked dead.
2665 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
2666 used = !MOI->isDead();
2667 if (used)
2668 break;
2669 continue;
2670 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002671 unsigned realUses = 0;
2672 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2673 EI = MRI.use_end();
2674 UI != EI; ++UI) {
2675 // Check if there are any uses that occur only in the original
2676 // loop. If so, that's not a real use.
2677 if (UI->getParent()->getParent() != BB) {
2678 realUses++;
2679 used = true;
2680 break;
2681 }
2682 }
2683 if (realUses > 0)
2684 break;
2685 used = false;
2686 }
2687 if (!used) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002688 LIS.RemoveMachineInstrFromMaps(*MI);
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002689 MI++->eraseFromParent();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002690 continue;
2691 }
2692 ++MI;
2693 }
2694 // In the kernel block, check if we can remove a Phi that generates a value
2695 // used in an instruction removed in the epilog block.
2696 for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2697 BBE = KernelBB->getFirstNonPHI();
2698 BBI != BBE;) {
2699 MachineInstr *MI = &*BBI;
2700 ++BBI;
2701 unsigned reg = MI->getOperand(0).getReg();
2702 if (MRI.use_begin(reg) == MRI.use_end()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002703 LIS.RemoveMachineInstrFromMaps(*MI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002704 MI->eraseFromParent();
2705 }
2706 }
2707}
2708
2709/// For loop carried definitions, we split the lifetime of a virtual register
2710/// that has uses past the definition in the next iteration. A copy with a new
2711/// virtual register is inserted before the definition, which helps with
2712/// generating a better register assignment.
2713///
2714/// v1 = phi(a, v2) v1 = phi(a, v2)
2715/// v2 = phi(b, v3) v2 = phi(b, v3)
2716/// v3 = .. v4 = copy v1
2717/// .. = V1 v3 = ..
2718/// .. = v4
2719void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
2720 MBBVectorTy &EpilogBBs,
2721 SMSchedule &Schedule) {
2722 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bob Wilson90ecac02018-01-04 02:58:15 +00002723 for (auto &PHI : KernelBB->phis()) {
2724 unsigned Def = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002725 // Check for any Phi definition that used as an operand of another Phi
2726 // in the same block.
2727 for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
2728 E = MRI.use_instr_end();
2729 I != E; ++I) {
2730 if (I->isPHI() && I->getParent() == KernelBB) {
2731 // Get the loop carried definition.
Bob Wilson90ecac02018-01-04 02:58:15 +00002732 unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002733 if (!LCDef)
2734 continue;
2735 MachineInstr *MI = MRI.getVRegDef(LCDef);
2736 if (!MI || MI->getParent() != KernelBB || MI->isPHI())
2737 continue;
2738 // Search through the rest of the block looking for uses of the Phi
2739 // definition. If one occurs, then split the lifetime.
2740 unsigned SplitReg = 0;
2741 for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
2742 KernelBB->instr_end()))
2743 if (BBJ.readsRegister(Def)) {
2744 // We split the lifetime when we find the first use.
2745 if (SplitReg == 0) {
2746 SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
2747 BuildMI(*KernelBB, MI, MI->getDebugLoc(),
2748 TII->get(TargetOpcode::COPY), SplitReg)
2749 .addReg(Def);
2750 }
2751 BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
2752 }
2753 if (!SplitReg)
2754 continue;
2755 // Search through each of the epilog blocks for any uses to be renamed.
2756 for (auto &Epilog : EpilogBBs)
2757 for (auto &I : *Epilog)
2758 if (I.readsRegister(Def))
2759 I.substituteRegister(Def, SplitReg, 0, *TRI);
2760 break;
2761 }
2762 }
2763 }
2764}
2765
2766/// Remove the incoming block from the Phis in a basic block.
2767static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
2768 for (MachineInstr &MI : *BB) {
2769 if (!MI.isPHI())
2770 break;
2771 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
2772 if (MI.getOperand(i + 1).getMBB() == Incoming) {
2773 MI.RemoveOperand(i + 1);
2774 MI.RemoveOperand(i);
2775 break;
2776 }
2777 }
2778}
2779
2780/// Create branches from each prolog basic block to the appropriate epilog
2781/// block. These edges are needed if the loop ends before reaching the
2782/// kernel.
Jinsong Jief2d6d92019-06-11 17:40:39 +00002783void SwingSchedulerDAG::addBranches(MachineBasicBlock &PreheaderBB,
2784 MBBVectorTy &PrologBBs,
Brendon Cahoon254f8892016-07-29 16:44:44 +00002785 MachineBasicBlock *KernelBB,
2786 MBBVectorTy &EpilogBBs,
2787 SMSchedule &Schedule, ValueMapTy *VRMap) {
2788 assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
2789 MachineInstr *IndVar = Pass.LI.LoopInductionVar;
2790 MachineInstr *Cmp = Pass.LI.LoopCompare;
2791 MachineBasicBlock *LastPro = KernelBB;
2792 MachineBasicBlock *LastEpi = KernelBB;
2793
2794 // Start from the blocks connected to the kernel and work "out"
2795 // to the first prolog and the last epilog blocks.
2796 SmallVector<MachineInstr *, 4> PrevInsts;
2797 unsigned MaxIter = PrologBBs.size() - 1;
2798 unsigned LC = UINT_MAX;
2799 unsigned LCMin = UINT_MAX;
2800 for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
2801 // Add branches to the prolog that go to the corresponding
2802 // epilog, and the fall-thru prolog/kernel block.
2803 MachineBasicBlock *Prolog = PrologBBs[j];
2804 MachineBasicBlock *Epilog = EpilogBBs[i];
2805 // We've executed one iteration, so decrement the loop count and check for
2806 // the loop end.
2807 SmallVector<MachineOperand, 4> Cond;
2808 // Check if the LOOP0 has already been removed. If so, then there is no need
2809 // to reduce the trip count.
2810 if (LC != 0)
Jinsong Jief2d6d92019-06-11 17:40:39 +00002811 LC = TII->reduceLoopCount(*Prolog, PreheaderBB, IndVar, *Cmp, Cond,
2812 PrevInsts, j, MaxIter);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002813
2814 // Record the value of the first trip count, which is used to determine if
2815 // branches and blocks can be removed for constant trip counts.
2816 if (LCMin == UINT_MAX)
2817 LCMin = LC;
2818
2819 unsigned numAdded = 0;
2820 if (TargetRegisterInfo::isVirtualRegister(LC)) {
2821 Prolog->addSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002822 numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002823 } else if (j >= LCMin) {
2824 Prolog->addSuccessor(Epilog);
2825 Prolog->removeSuccessor(LastPro);
2826 LastEpi->removeSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002827 numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002828 removePhis(Epilog, LastEpi);
2829 // Remove the blocks that are no longer referenced.
2830 if (LastPro != LastEpi) {
2831 LastEpi->clear();
2832 LastEpi->eraseFromParent();
2833 }
2834 LastPro->clear();
2835 LastPro->eraseFromParent();
2836 } else {
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002837 numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002838 removePhis(Epilog, Prolog);
2839 }
2840 LastPro = Prolog;
2841 LastEpi = Epilog;
2842 for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
2843 E = Prolog->instr_rend();
2844 I != E && numAdded > 0; ++I, --numAdded)
2845 updateInstruction(&*I, false, j, 0, Schedule, VRMap);
2846 }
2847}
2848
2849/// Return true if we can compute the amount the instruction changes
2850/// during each iteration. Set Delta to the amount of the change.
2851bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2852 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00002853 const MachineOperand *BaseOp;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002854 int64_t Offset;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002855 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002856 return false;
2857
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002858 if (!BaseOp->isReg())
2859 return false;
2860
2861 unsigned BaseReg = BaseOp->getReg();
2862
Brendon Cahoon254f8892016-07-29 16:44:44 +00002863 MachineRegisterInfo &MRI = MF.getRegInfo();
2864 // Check if there is a Phi. If so, get the definition in the loop.
2865 MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2866 if (BaseDef && BaseDef->isPHI()) {
2867 BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2868 BaseDef = MRI.getVRegDef(BaseReg);
2869 }
2870 if (!BaseDef)
2871 return false;
2872
2873 int D = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002874 if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002875 return false;
2876
2877 Delta = D;
2878 return true;
2879}
2880
2881/// Update the memory operand with a new offset when the pipeliner
Justin Lebarcf56e922016-08-12 23:58:19 +00002882/// generates a new copy of the instruction that refers to a
Brendon Cahoon254f8892016-07-29 16:44:44 +00002883/// different memory location.
2884void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
2885 MachineInstr &OldMI, unsigned Num) {
2886 if (Num == 0)
2887 return;
2888 // If the instruction has memory operands, then adjust the offset
2889 // when the instruction appears in different stages.
Chandler Carruthc73c0302018-08-16 21:30:05 +00002890 if (NewMI.memoperands_empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00002891 return;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002892 SmallVector<MachineMemOperand *, 2> NewMMOs;
Justin Lebar0a33a7a2016-08-23 17:18:07 +00002893 for (MachineMemOperand *MMO : NewMI.memoperands()) {
Philip Reames00056ed2019-02-01 22:58:52 +00002894 // TODO: Figure out whether isAtomic is really necessary (see D57601).
2895 if (MMO->isVolatile() || MMO->isAtomic() ||
2896 (MMO->isInvariant() && MMO->isDereferenceable()) ||
Justin Lebaradbf09e2016-09-11 01:38:58 +00002897 (!MMO->getValue())) {
Chandler Carruthc73c0302018-08-16 21:30:05 +00002898 NewMMOs.push_back(MMO);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002899 continue;
2900 }
2901 unsigned Delta;
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002902 if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002903 int64_t AdjOffset = Delta * Num;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002904 NewMMOs.push_back(
2905 MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002906 } else {
Krzysztof Parzyszekcc3f6302018-08-20 20:37:57 +00002907 NewMMOs.push_back(
2908 MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002909 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002910 }
Chandler Carruthc73c0302018-08-16 21:30:05 +00002911 NewMI.setMemRefs(MF, NewMMOs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002912}
2913
2914/// Clone the instruction for the new pipelined loop and update the
2915/// memory operands, if needed.
2916MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
2917 unsigned CurStageNum,
2918 unsigned InstStageNum) {
2919 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2920 // Check for tied operands in inline asm instructions. This should be handled
2921 // elsewhere, but I'm not sure of the best solution.
2922 if (OldMI->isInlineAsm())
2923 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
2924 const auto &MO = OldMI->getOperand(i);
2925 if (MO.isReg() && MO.isUse())
2926 break;
2927 unsigned UseIdx;
2928 if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
2929 NewMI->tieOperands(i, UseIdx);
2930 }
2931 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2932 return NewMI;
2933}
2934
2935/// Clone the instruction for the new pipelined loop. If needed, this
2936/// function updates the instruction using the values saved in the
2937/// InstrChanges structure.
2938MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
2939 unsigned CurStageNum,
2940 unsigned InstStageNum,
2941 SMSchedule &Schedule) {
2942 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2943 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2944 InstrChanges.find(getSUnit(OldMI));
2945 if (It != InstrChanges.end()) {
2946 std::pair<unsigned, int64_t> RegAndOffset = It->second;
2947 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002948 if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002949 return nullptr;
2950 int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
2951 MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
2952 if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
2953 NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
2954 NewMI->getOperand(OffsetPos).setImm(NewOffset);
2955 }
2956 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2957 return NewMI;
2958}
2959
2960/// Update the machine instruction with new virtual registers. This
2961/// function may change the defintions and/or uses.
2962void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
2963 unsigned CurStageNum,
2964 unsigned InstrStageNum,
2965 SMSchedule &Schedule,
2966 ValueMapTy *VRMap) {
2967 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
2968 MachineOperand &MO = NewMI->getOperand(i);
2969 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2970 continue;
2971 unsigned reg = MO.getReg();
2972 if (MO.isDef()) {
2973 // Create a new virtual register for the definition.
2974 const TargetRegisterClass *RC = MRI.getRegClass(reg);
2975 unsigned NewReg = MRI.createVirtualRegister(RC);
2976 MO.setReg(NewReg);
2977 VRMap[CurStageNum][reg] = NewReg;
2978 if (LastDef)
2979 replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
2980 } else if (MO.isUse()) {
2981 MachineInstr *Def = MRI.getVRegDef(reg);
2982 // Compute the stage that contains the last definition for instruction.
2983 int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
2984 unsigned StageNum = CurStageNum;
2985 if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
2986 // Compute the difference in stages between the defintion and the use.
2987 unsigned StageDiff = (InstrStageNum - DefStageNum);
2988 // Make an adjustment to get the last definition.
2989 StageNum -= StageDiff;
2990 }
2991 if (VRMap[StageNum].count(reg))
2992 MO.setReg(VRMap[StageNum][reg]);
2993 }
2994 }
2995}
2996
2997/// Return the instruction in the loop that defines the register.
2998/// If the definition is a Phi, then follow the Phi operand to
2999/// the instruction in the loop.
3000MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
3001 SmallPtrSet<MachineInstr *, 8> Visited;
3002 MachineInstr *Def = MRI.getVRegDef(Reg);
3003 while (Def->isPHI()) {
3004 if (!Visited.insert(Def).second)
3005 break;
3006 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3007 if (Def->getOperand(i + 1).getMBB() == BB) {
3008 Def = MRI.getVRegDef(Def->getOperand(i).getReg());
3009 break;
3010 }
3011 }
3012 return Def;
3013}
3014
3015/// Return the new name for the value from the previous stage.
3016unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
3017 unsigned LoopVal, unsigned LoopStage,
3018 ValueMapTy *VRMap,
3019 MachineBasicBlock *BB) {
3020 unsigned PrevVal = 0;
3021 if (StageNum > PhiStage) {
3022 MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
3023 if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
3024 // The name is defined in the previous stage.
3025 PrevVal = VRMap[StageNum - 1][LoopVal];
3026 else if (VRMap[StageNum].count(LoopVal))
3027 // The previous name is defined in the current stage when the instruction
3028 // order is swapped.
3029 PrevVal = VRMap[StageNum][LoopVal];
Krzysztof Parzyszekdf24da22016-12-22 18:49:55 +00003030 else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003031 // The loop value hasn't yet been scheduled.
3032 PrevVal = LoopVal;
3033 else if (StageNum == PhiStage + 1)
3034 // The loop value is another phi, which has not been scheduled.
3035 PrevVal = getInitPhiReg(*LoopInst, BB);
3036 else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
3037 // The loop value is another phi, which has been scheduled.
3038 PrevVal =
3039 getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
3040 LoopStage, VRMap, BB);
3041 }
3042 return PrevVal;
3043}
3044
3045/// Rewrite the Phi values in the specified block to use the mappings
3046/// from the initial operand. Once the Phi is scheduled, we switch
3047/// to using the loop value instead of the Phi value, so those names
3048/// do not need to be rewritten.
3049void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
3050 unsigned StageNum,
3051 SMSchedule &Schedule,
3052 ValueMapTy *VRMap,
3053 InstrMapTy &InstrMap) {
Bob Wilson90ecac02018-01-04 02:58:15 +00003054 for (auto &PHI : BB->phis()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003055 unsigned InitVal = 0;
3056 unsigned LoopVal = 0;
Bob Wilson90ecac02018-01-04 02:58:15 +00003057 getPhiRegs(PHI, BB, InitVal, LoopVal);
3058 unsigned PhiDef = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003059
3060 unsigned PhiStage =
3061 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
3062 unsigned LoopStage =
3063 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
3064 unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3065 if (NumPhis > StageNum)
3066 NumPhis = StageNum;
3067 for (unsigned np = 0; np <= NumPhis; ++np) {
3068 unsigned NewVal =
3069 getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3070 if (!NewVal)
3071 NewVal = InitVal;
Bob Wilson90ecac02018-01-04 02:58:15 +00003072 rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
Brendon Cahoon254f8892016-07-29 16:44:44 +00003073 PhiDef, NewVal);
3074 }
3075 }
3076}
3077
3078/// Rewrite a previously scheduled instruction to use the register value
3079/// from the new instruction. Make sure the instruction occurs in the
3080/// basic block, and we don't change the uses in the new instruction.
3081void SwingSchedulerDAG::rewriteScheduledInstr(
3082 MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
3083 unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
3084 unsigned NewReg, unsigned PrevReg) {
3085 bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3086 int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3087 // Rewrite uses that have been scheduled already to use the new
3088 // Phi register.
3089 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
3090 EI = MRI.use_end();
3091 UI != EI;) {
3092 MachineOperand &UseOp = *UI;
3093 MachineInstr *UseMI = UseOp.getParent();
3094 ++UI;
3095 if (UseMI->getParent() != BB)
3096 continue;
3097 if (UseMI->isPHI()) {
3098 if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
3099 continue;
3100 if (getLoopPhiReg(*UseMI, BB) != OldReg)
3101 continue;
3102 }
3103 InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3104 assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
3105 SUnit *OrigMISU = getSUnit(OrigInstr->second);
3106 int StageSched = Schedule.stageScheduled(OrigMISU);
3107 int CycleSched = Schedule.cycleScheduled(OrigMISU);
3108 unsigned ReplaceReg = 0;
3109 // This is the stage for the scheduled instruction.
3110 if (StagePhi == StageSched && Phi->isPHI()) {
3111 int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3112 if (PrevReg && InProlog)
3113 ReplaceReg = PrevReg;
3114 else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
3115 (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3116 ReplaceReg = PrevReg;
3117 else
3118 ReplaceReg = NewReg;
3119 }
3120 // The scheduled instruction occurs before the scheduled Phi, and the
3121 // Phi is not loop carried.
3122 if (!InProlog && StagePhi + 1 == StageSched &&
3123 !Schedule.isLoopCarried(this, *Phi))
3124 ReplaceReg = NewReg;
3125 if (StagePhi > StageSched && Phi->isPHI())
3126 ReplaceReg = NewReg;
3127 if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
3128 ReplaceReg = NewReg;
3129 if (ReplaceReg) {
3130 MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
3131 UseOp.setReg(ReplaceReg);
3132 }
3133 }
3134}
3135
3136/// Check if we can change the instruction to use an offset value from the
3137/// previous iteration. If so, return true and set the base and offset values
3138/// so that we can rewrite the load, if necessary.
3139/// v1 = Phi(v0, v3)
3140/// v2 = load v1, 0
3141/// v3 = post_store v1, 4, x
3142/// This function enables the load to be rewritten as v2 = load v3, 4.
3143bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3144 unsigned &BasePos,
3145 unsigned &OffsetPos,
3146 unsigned &NewBase,
3147 int64_t &Offset) {
3148 // Get the load instruction.
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003149 if (TII->isPostIncrement(*MI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003150 return false;
3151 unsigned BasePosLd, OffsetPosLd;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003152 if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003153 return false;
3154 unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
3155
3156 // Look for the Phi instruction.
Justin Bognerfdf9bf42017-10-10 23:50:49 +00003157 MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003158 MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3159 if (!Phi || !Phi->isPHI())
3160 return false;
3161 // Get the register defined in the loop block.
3162 unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3163 if (!PrevReg)
3164 return false;
3165
3166 // Check for the post-increment load/store instruction.
3167 MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3168 if (!PrevDef || PrevDef == MI)
3169 return false;
3170
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003171 if (!TII->isPostIncrement(*PrevDef))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003172 return false;
3173
3174 unsigned BasePos1 = 0, OffsetPos1 = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003175 if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003176 return false;
3177
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00003178 // Make sure that the instructions do not access the same memory location in
3179 // the next iteration.
Brendon Cahoon254f8892016-07-29 16:44:44 +00003180 int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3181 int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00003182 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3183 NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
3184 bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
3185 MF.DeleteMachineInstr(NewMI);
3186 if (!Disjoint)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003187 return false;
3188
3189 // Set the return value once we determine that we return true.
3190 BasePos = BasePosLd;
3191 OffsetPos = OffsetPosLd;
3192 NewBase = PrevReg;
3193 Offset = StoreOffset;
3194 return true;
3195}
3196
3197/// Apply changes to the instruction if needed. The changes are need
3198/// to improve the scheduling and depend up on the final schedule.
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003199void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
3200 SMSchedule &Schedule) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003201 SUnit *SU = getSUnit(MI);
3202 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3203 InstrChanges.find(SU);
3204 if (It != InstrChanges.end()) {
3205 std::pair<unsigned, int64_t> RegAndOffset = It->second;
3206 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003207 if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003208 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003209 unsigned BaseReg = MI->getOperand(BasePos).getReg();
3210 MachineInstr *LoopDef = findDefInLoop(BaseReg);
3211 int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3212 int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3213 int BaseStageNum = Schedule.stageScheduled(SU);
3214 int BaseCycleNum = Schedule.cycleScheduled(SU);
3215 if (BaseStageNum < DefStageNum) {
3216 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3217 int OffsetDiff = DefStageNum - BaseStageNum;
3218 if (DefCycleNum < BaseCycleNum) {
3219 NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3220 if (OffsetDiff > 0)
3221 --OffsetDiff;
3222 }
3223 int64_t NewOffset =
3224 MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3225 NewMI->getOperand(OffsetPos).setImm(NewOffset);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003226 SU->setInstr(NewMI);
3227 MISUnitMap[NewMI] = SU;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003228 NewMIs.insert(NewMI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003229 }
3230 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003231}
3232
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003233/// Return true for an order or output dependence that is loop carried
3234/// potentially. A dependence is loop carried if the destination defines a valu
3235/// that may be used or defined by the source in a subsequent iteration.
3236bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
3237 bool isSucc) {
3238 if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
3239 Dep.isArtificial())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003240 return false;
3241
3242 if (!SwpPruneLoopCarried)
3243 return true;
3244
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003245 if (Dep.getKind() == SDep::Output)
3246 return true;
3247
Brendon Cahoon254f8892016-07-29 16:44:44 +00003248 MachineInstr *SI = Source->getInstr();
3249 MachineInstr *DI = Dep.getSUnit()->getInstr();
3250 if (!isSucc)
3251 std::swap(SI, DI);
3252 assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3253
3254 // Assume ordered loads and stores may have a loop carried dependence.
3255 if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +00003256 SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00003257 SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3258 return true;
3259
3260 // Only chain dependences between a load and store can be loop carried.
3261 if (!DI->mayStore() || !SI->mayLoad())
3262 return false;
3263
3264 unsigned DeltaS, DeltaD;
3265 if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3266 return true;
3267
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00003268 const MachineOperand *BaseOpS, *BaseOpD;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003269 int64_t OffsetS, OffsetD;
3270 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003271 if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
3272 !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003273 return true;
3274
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003275 if (!BaseOpS->isIdenticalTo(*BaseOpD))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003276 return true;
3277
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00003278 // Check that the base register is incremented by a constant value for each
3279 // iteration.
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003280 MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00003281 if (!Def || !Def->isPHI())
3282 return true;
3283 unsigned InitVal = 0;
3284 unsigned LoopVal = 0;
3285 getPhiRegs(*Def, BB, InitVal, LoopVal);
3286 MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
3287 int D = 0;
3288 if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
3289 return true;
3290
Brendon Cahoon254f8892016-07-29 16:44:44 +00003291 uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3292 uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3293
3294 // This is the main test, which checks the offset values and the loop
3295 // increment value to determine if the accesses may be loop carried.
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00003296 if (AccessSizeS == MemoryLocation::UnknownSize ||
3297 AccessSizeD == MemoryLocation::UnknownSize)
3298 return true;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003299
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00003300 if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
3301 return true;
3302
3303 return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003304}
3305
Krzysztof Parzyszek88391242016-12-22 19:21:20 +00003306void SwingSchedulerDAG::postprocessDAG() {
3307 for (auto &M : Mutations)
3308 M->apply(this);
3309}
3310
Brendon Cahoon254f8892016-07-29 16:44:44 +00003311/// Try to schedule the node at the specified StartCycle and continue
3312/// until the node is schedule or the EndCycle is reached. This function
3313/// returns true if the node is scheduled. This routine may search either
3314/// forward or backward for a place to insert the instruction based upon
3315/// the relative values of StartCycle and EndCycle.
3316bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3317 bool forward = true;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00003318 LLVM_DEBUG({
3319 dbgs() << "Trying to insert node between " << StartCycle << " and "
3320 << EndCycle << " II: " << II << "\n";
3321 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00003322 if (StartCycle > EndCycle)
3323 forward = false;
3324
3325 // The terminating condition depends on the direction.
3326 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3327 for (int curCycle = StartCycle; curCycle != termCycle;
3328 forward ? ++curCycle : --curCycle) {
3329
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003330 // Add the already scheduled instructions at the specified cycle to the
3331 // DFA.
3332 ProcItinResources.clearResources();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003333 for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3334 checkCycle <= LastCycle; checkCycle += II) {
3335 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3336
3337 for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3338 E = cycleInstrs.end();
3339 I != E; ++I) {
3340 if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3341 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003342 assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00003343 "These instructions have already been scheduled.");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003344 ProcItinResources.reserveResources(*(*I)->getInstr());
Brendon Cahoon254f8892016-07-29 16:44:44 +00003345 }
3346 }
3347 if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003348 ProcItinResources.canReserveResources(*SU->getInstr())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003349 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003350 dbgs() << "\tinsert at cycle " << curCycle << " ";
3351 SU->getInstr()->dump();
3352 });
3353
3354 ScheduledInstrs[curCycle].push_back(SU);
3355 InstrToCycle.insert(std::make_pair(SU, curCycle));
3356 if (curCycle > LastCycle)
3357 LastCycle = curCycle;
3358 if (curCycle < FirstCycle)
3359 FirstCycle = curCycle;
3360 return true;
3361 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003362 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003363 dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3364 SU->getInstr()->dump();
3365 });
3366 }
3367 return false;
3368}
3369
3370// Return the cycle of the earliest scheduled instruction in the chain.
3371int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3372 SmallPtrSet<SUnit *, 8> Visited;
3373 SmallVector<SDep, 8> Worklist;
3374 Worklist.push_back(Dep);
3375 int EarlyCycle = INT_MAX;
3376 while (!Worklist.empty()) {
3377 const SDep &Cur = Worklist.pop_back_val();
3378 SUnit *PrevSU = Cur.getSUnit();
3379 if (Visited.count(PrevSU))
3380 continue;
3381 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3382 if (it == InstrToCycle.end())
3383 continue;
3384 EarlyCycle = std::min(EarlyCycle, it->second);
3385 for (const auto &PI : PrevSU->Preds)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003386 if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003387 Worklist.push_back(PI);
3388 Visited.insert(PrevSU);
3389 }
3390 return EarlyCycle;
3391}
3392
3393// Return the cycle of the latest scheduled instruction in the chain.
3394int SMSchedule::latestCycleInChain(const SDep &Dep) {
3395 SmallPtrSet<SUnit *, 8> Visited;
3396 SmallVector<SDep, 8> Worklist;
3397 Worklist.push_back(Dep);
3398 int LateCycle = INT_MIN;
3399 while (!Worklist.empty()) {
3400 const SDep &Cur = Worklist.pop_back_val();
3401 SUnit *SuccSU = Cur.getSUnit();
3402 if (Visited.count(SuccSU))
3403 continue;
3404 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3405 if (it == InstrToCycle.end())
3406 continue;
3407 LateCycle = std::max(LateCycle, it->second);
3408 for (const auto &SI : SuccSU->Succs)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003409 if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003410 Worklist.push_back(SI);
3411 Visited.insert(SuccSU);
3412 }
3413 return LateCycle;
3414}
3415
3416/// If an instruction has a use that spans multiple iterations, then
3417/// return true. These instructions are characterized by having a back-ege
3418/// to a Phi, which contains a reference to another Phi.
3419static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3420 for (auto &P : SU->Preds)
3421 if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3422 for (auto &S : P.getSUnit()->Succs)
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00003423 if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003424 return P.getSUnit();
3425 return nullptr;
3426}
3427
3428/// Compute the scheduling start slot for the instruction. The start slot
3429/// depends on any predecessor or successor nodes scheduled already.
3430void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3431 int *MinEnd, int *MaxStart, int II,
3432 SwingSchedulerDAG *DAG) {
3433 // Iterate over each instruction that has been scheduled already. The start
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003434 // slot computation depends on whether the previously scheduled instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00003435 // is a predecessor or successor of the specified instruction.
3436 for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3437
3438 // Iterate over each instruction in the current cycle.
3439 for (SUnit *I : getInstructions(cycle)) {
3440 // Because we're processing a DAG for the dependences, we recognize
3441 // the back-edge in recurrences by anti dependences.
3442 for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3443 const SDep &Dep = SU->Preds[i];
3444 if (Dep.getSUnit() == I) {
3445 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003446 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003447 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3448 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003449 if (DAG->isLoopCarriedDep(SU, Dep, false)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003450 int End = earliestCycleInChain(Dep) + (II - 1);
3451 *MinEnd = std::min(*MinEnd, End);
3452 }
3453 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003454 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003455 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3456 *MinLateStart = std::min(*MinLateStart, LateStart);
3457 }
3458 }
3459 // For instruction that requires multiple iterations, make sure that
3460 // the dependent instruction is not scheduled past the definition.
3461 SUnit *BE = multipleIterations(I, DAG);
3462 if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3463 !SU->isPred(I))
3464 *MinLateStart = std::min(*MinLateStart, cycle);
3465 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003466 for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003467 if (SU->Succs[i].getSUnit() == I) {
3468 const SDep &Dep = SU->Succs[i];
3469 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003470 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003471 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3472 *MinLateStart = std::min(*MinLateStart, LateStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003473 if (DAG->isLoopCarriedDep(SU, Dep)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003474 int Start = latestCycleInChain(Dep) + 1 - II;
3475 *MaxStart = std::max(*MaxStart, Start);
3476 }
3477 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003478 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003479 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3480 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3481 }
3482 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003483 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003484 }
3485 }
3486}
3487
3488/// Order the instructions within a cycle so that the definitions occur
3489/// before the uses. Returns true if the instruction is added to the start
3490/// of the list, or false if added to the end.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003491void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
Brendon Cahoon254f8892016-07-29 16:44:44 +00003492 std::deque<SUnit *> &Insts) {
3493 MachineInstr *MI = SU->getInstr();
3494 bool OrderBeforeUse = false;
3495 bool OrderAfterDef = false;
3496 bool OrderBeforeDef = false;
3497 unsigned MoveDef = 0;
3498 unsigned MoveUse = 0;
3499 int StageInst1 = stageScheduled(SU);
3500
3501 unsigned Pos = 0;
3502 for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3503 ++I, ++Pos) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003504 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3505 MachineOperand &MO = MI->getOperand(i);
3506 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3507 continue;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003508
Brendon Cahoon254f8892016-07-29 16:44:44 +00003509 unsigned Reg = MO.getReg();
3510 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003511 if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003512 if (MI->getOperand(BasePos).getReg() == Reg)
3513 if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3514 Reg = NewReg;
3515 bool Reads, Writes;
3516 std::tie(Reads, Writes) =
3517 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3518 if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3519 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003520 if (MoveUse == 0)
3521 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003522 } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3523 // Add the instruction after the scheduled instruction.
3524 OrderAfterDef = true;
3525 MoveDef = Pos;
3526 } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3527 if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3528 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003529 if (MoveUse == 0)
3530 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003531 } else {
3532 OrderAfterDef = true;
3533 MoveDef = Pos;
3534 }
3535 } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3536 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003537 if (MoveUse == 0)
3538 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003539 if (MoveUse != 0) {
3540 OrderAfterDef = true;
3541 MoveDef = Pos - 1;
3542 }
3543 } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3544 // Add the instruction before the scheduled instruction.
3545 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003546 if (MoveUse == 0)
3547 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003548 } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3549 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003550 if (MoveUse == 0) {
3551 OrderBeforeDef = true;
3552 MoveUse = Pos;
3553 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003554 }
3555 }
3556 // Check for order dependences between instructions. Make sure the source
3557 // is ordered before the destination.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003558 for (auto &S : SU->Succs) {
3559 if (S.getSUnit() != *I)
3560 continue;
3561 if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3562 OrderBeforeUse = true;
3563 if (Pos < MoveUse)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003564 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003565 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003566 }
3567 for (auto &P : SU->Preds) {
3568 if (P.getSUnit() != *I)
3569 continue;
3570 if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3571 OrderAfterDef = true;
3572 MoveDef = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003573 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003574 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003575 }
3576
3577 // A circular dependence.
3578 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3579 OrderBeforeUse = false;
3580
3581 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3582 // to a loop-carried dependence.
3583 if (OrderBeforeDef)
3584 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3585
3586 // The uncommon case when the instruction order needs to be updated because
3587 // there is both a use and def.
3588 if (OrderBeforeUse && OrderAfterDef) {
3589 SUnit *UseSU = Insts.at(MoveUse);
3590 SUnit *DefSU = Insts.at(MoveDef);
3591 if (MoveUse > MoveDef) {
3592 Insts.erase(Insts.begin() + MoveUse);
3593 Insts.erase(Insts.begin() + MoveDef);
3594 } else {
3595 Insts.erase(Insts.begin() + MoveDef);
3596 Insts.erase(Insts.begin() + MoveUse);
3597 }
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003598 orderDependence(SSD, UseSU, Insts);
3599 orderDependence(SSD, SU, Insts);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003600 orderDependence(SSD, DefSU, Insts);
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003601 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003602 }
3603 // Put the new instruction first if there is a use in the list. Otherwise,
3604 // put it at the end of the list.
3605 if (OrderBeforeUse)
3606 Insts.push_front(SU);
3607 else
3608 Insts.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003609}
3610
3611/// Return true if the scheduled Phi has a loop carried operand.
3612bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3613 if (!Phi.isPHI())
3614 return false;
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003615 assert(Phi.isPHI() && "Expecting a Phi.");
Brendon Cahoon254f8892016-07-29 16:44:44 +00003616 SUnit *DefSU = SSD->getSUnit(&Phi);
3617 unsigned DefCycle = cycleScheduled(DefSU);
3618 int DefStage = stageScheduled(DefSU);
3619
3620 unsigned InitVal = 0;
3621 unsigned LoopVal = 0;
3622 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3623 SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3624 if (!UseSU)
3625 return true;
3626 if (UseSU->getInstr()->isPHI())
3627 return true;
3628 unsigned LoopCycle = cycleScheduled(UseSU);
3629 int LoopStage = stageScheduled(UseSU);
Simon Pilgrim3d8482a2016-11-14 10:40:23 +00003630 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003631}
3632
3633/// Return true if the instruction is a definition that is loop carried
3634/// and defines the use on the next iteration.
3635/// v1 = phi(v2, v3)
3636/// (Def) v3 = op v1
3637/// (MO) = v1
3638/// If MO appears before Def, then then v1 and v3 may get assigned to the same
3639/// register.
3640bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3641 MachineInstr *Def, MachineOperand &MO) {
3642 if (!MO.isReg())
3643 return false;
3644 if (Def->isPHI())
3645 return false;
3646 MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3647 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3648 return false;
3649 if (!isLoopCarried(SSD, *Phi))
3650 return false;
3651 unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3652 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3653 MachineOperand &DMO = Def->getOperand(i);
3654 if (!DMO.isReg() || !DMO.isDef())
3655 continue;
3656 if (DMO.getReg() == LoopReg)
3657 return true;
3658 }
3659 return false;
3660}
3661
3662// Check if the generated schedule is valid. This function checks if
3663// an instruction that uses a physical register is scheduled in a
3664// different stage than the definition. The pipeliner does not handle
3665// physical register values that may cross a basic block boundary.
3666bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003667 for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3668 SUnit &SU = SSD->SUnits[i];
3669 if (!SU.hasPhysRegDefs)
3670 continue;
3671 int StageDef = stageScheduled(&SU);
3672 assert(StageDef != -1 && "Instruction should have been scheduled.");
3673 for (auto &SI : SU.Succs)
3674 if (SI.isAssignedRegDep())
Simon Pilgrimb39236b2016-07-29 18:57:32 +00003675 if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003676 if (stageScheduled(SI.getSUnit()) != StageDef)
3677 return false;
3678 }
3679 return true;
3680}
3681
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003682/// A property of the node order in swing-modulo-scheduling is
3683/// that for nodes outside circuits the following holds:
3684/// none of them is scheduled after both a successor and a
3685/// predecessor.
3686/// The method below checks whether the property is met.
3687/// If not, debug information is printed and statistics information updated.
3688/// Note that we do not use an assert statement.
3689/// The reason is that although an invalid node oder may prevent
3690/// the pipeliner from finding a pipelined schedule for arbitrary II,
3691/// it does not lead to the generation of incorrect code.
3692void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3693
3694 // a sorted vector that maps each SUnit to its index in the NodeOrder
3695 typedef std::pair<SUnit *, unsigned> UnitIndex;
3696 std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3697
3698 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3699 Indices.push_back(std::make_pair(NodeOrder[i], i));
3700
3701 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3702 return std::get<0>(i1) < std::get<0>(i2);
3703 };
3704
3705 // sort, so that we can perform a binary search
Fangrui Song0cac7262018-09-27 02:13:45 +00003706 llvm::sort(Indices, CompareKey);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003707
3708 bool Valid = true;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003709 (void)Valid;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003710 // for each SUnit in the NodeOrder, check whether
3711 // it appears after both a successor and a predecessor
3712 // of the SUnit. If this is the case, and the SUnit
3713 // is not part of circuit, then the NodeOrder is not
3714 // valid.
3715 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3716 SUnit *SU = NodeOrder[i];
3717 unsigned Index = i;
3718
3719 bool PredBefore = false;
3720 bool SuccBefore = false;
3721
3722 SUnit *Succ;
3723 SUnit *Pred;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003724 (void)Succ;
3725 (void)Pred;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003726
3727 for (SDep &PredEdge : SU->Preds) {
3728 SUnit *PredSU = PredEdge.getSUnit();
Fangrui Songdc8de602019-06-21 05:40:31 +00003729 unsigned PredIndex = std::get<1>(
3730 *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003731 if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3732 PredBefore = true;
3733 Pred = PredSU;
3734 break;
3735 }
3736 }
3737
3738 for (SDep &SuccEdge : SU->Succs) {
3739 SUnit *SuccSU = SuccEdge.getSUnit();
Jinsong Ji1c884452019-06-13 21:51:12 +00003740 // Do not process a boundary node, it was not included in NodeOrder,
3741 // hence not in Indices either, call to std::lower_bound() below will
3742 // return Indices.end().
3743 if (SuccSU->isBoundaryNode())
3744 continue;
Fangrui Songdc8de602019-06-21 05:40:31 +00003745 unsigned SuccIndex = std::get<1>(
3746 *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003747 if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3748 SuccBefore = true;
3749 Succ = SuccSU;
3750 break;
3751 }
3752 }
3753
3754 if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3755 // instructions in circuits are allowed to be scheduled
3756 // after both a successor and predecessor.
Fangrui Songdc8de602019-06-21 05:40:31 +00003757 bool InCircuit = llvm::any_of(
3758 Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003759 if (InCircuit)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003760 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003761 else {
3762 Valid = false;
3763 NumNodeOrderIssues++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003764 LLVM_DEBUG(dbgs() << "Predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003765 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003766 LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3767 << " are scheduled before node " << SU->NodeNum
3768 << "\n";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003769 }
3770 }
3771
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003772 LLVM_DEBUG({
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003773 if (!Valid)
3774 dbgs() << "Invalid node order found!\n";
3775 });
3776}
3777
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003778/// Attempt to fix the degenerate cases when the instruction serialization
3779/// causes the register lifetimes to overlap. For example,
3780/// p' = store_pi(p, b)
3781/// = load p, offset
3782/// In this case p and p' overlap, which means that two registers are needed.
3783/// Instead, this function changes the load to use p' and updates the offset.
3784void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3785 unsigned OverlapReg = 0;
3786 unsigned NewBaseReg = 0;
3787 for (SUnit *SU : Instrs) {
3788 MachineInstr *MI = SU->getInstr();
3789 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3790 const MachineOperand &MO = MI->getOperand(i);
3791 // Look for an instruction that uses p. The instruction occurs in the
3792 // same cycle but occurs later in the serialized order.
3793 if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3794 // Check that the instruction appears in the InstrChanges structure,
3795 // which contains instructions that can have the offset updated.
3796 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3797 InstrChanges.find(SU);
3798 if (It != InstrChanges.end()) {
3799 unsigned BasePos, OffsetPos;
3800 // Update the base register and adjust the offset.
3801 if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
Krzysztof Parzyszek12bdcab2017-10-11 15:59:51 +00003802 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3803 NewMI->getOperand(BasePos).setReg(NewBaseReg);
3804 int64_t NewOffset =
3805 MI->getOperand(OffsetPos).getImm() - It->second.second;
3806 NewMI->getOperand(OffsetPos).setImm(NewOffset);
3807 SU->setInstr(NewMI);
3808 MISUnitMap[NewMI] = SU;
3809 NewMIs.insert(NewMI);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003810 }
3811 }
3812 OverlapReg = 0;
3813 NewBaseReg = 0;
3814 break;
3815 }
3816 // Look for an instruction of the form p' = op(p), which uses and defines
3817 // two virtual registers that get allocated to the same physical register.
3818 unsigned TiedUseIdx = 0;
3819 if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3820 // OverlapReg is p in the example above.
3821 OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3822 // NewBaseReg is p' in the example above.
3823 NewBaseReg = MI->getOperand(i).getReg();
3824 break;
3825 }
3826 }
3827 }
3828}
3829
Brendon Cahoon254f8892016-07-29 16:44:44 +00003830/// After the schedule has been formed, call this function to combine
3831/// the instructions from the different stages/cycles. That is, this
3832/// function creates a schedule that represents a single iteration.
3833void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3834 // Move all instructions to the first stage from later stages.
3835 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3836 for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3837 ++stage) {
3838 std::deque<SUnit *> &cycleInstrs =
3839 ScheduledInstrs[cycle + (stage * InitiationInterval)];
3840 for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
3841 E = cycleInstrs.rend();
3842 I != E; ++I)
3843 ScheduledInstrs[cycle].push_front(*I);
3844 }
3845 }
3846 // Iterate over the definitions in each instruction, and compute the
3847 // stage difference for each use. Keep the maximum value.
3848 for (auto &I : InstrToCycle) {
3849 int DefStage = stageScheduled(I.first);
3850 MachineInstr *MI = I.first->getInstr();
3851 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3852 MachineOperand &Op = MI->getOperand(i);
3853 if (!Op.isReg() || !Op.isDef())
3854 continue;
3855
3856 unsigned Reg = Op.getReg();
3857 unsigned MaxDiff = 0;
3858 bool PhiIsSwapped = false;
3859 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
3860 EI = MRI.use_end();
3861 UI != EI; ++UI) {
3862 MachineOperand &UseOp = *UI;
3863 MachineInstr *UseMI = UseOp.getParent();
3864 SUnit *SUnitUse = SSD->getSUnit(UseMI);
3865 int UseStage = stageScheduled(SUnitUse);
3866 unsigned Diff = 0;
3867 if (UseStage != -1 && UseStage >= DefStage)
3868 Diff = UseStage - DefStage;
3869 if (MI->isPHI()) {
3870 if (isLoopCarried(SSD, *MI))
3871 ++Diff;
3872 else
3873 PhiIsSwapped = true;
3874 }
3875 MaxDiff = std::max(Diff, MaxDiff);
3876 }
3877 RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
3878 }
3879 }
3880
3881 // Erase all the elements in the later stages. Only one iteration should
3882 // remain in the scheduled list, and it contains all the instructions.
3883 for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3884 ScheduledInstrs.erase(cycle);
3885
3886 // Change the registers in instruction as specified in the InstrChanges
3887 // map. We need to use the new registers to create the correct order.
3888 for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
3889 SUnit *SU = &SSD->SUnits[i];
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003890 SSD->applyInstrChange(SU->getInstr(), *this);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003891 }
3892
3893 // Reorder the instructions in each cycle to fix and improve the
3894 // generated code.
3895 for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3896 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003897 std::deque<SUnit *> newOrderPhi;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003898 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3899 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003900 if (SU->getInstr()->isPHI())
3901 newOrderPhi.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003902 }
3903 std::deque<SUnit *> newOrderI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003904 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3905 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003906 if (!SU->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003907 orderDependence(SSD, SU, newOrderI);
3908 }
3909 // Replace the old order with the new order.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003910 cycleInstrs.swap(newOrderPhi);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003911 cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003912 SSD->fixupRegisterOverlaps(cycleInstrs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003913 }
3914
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003915 LLVM_DEBUG(dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00003916}
3917
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003918void NodeSet::print(raw_ostream &os) const {
3919 os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3920 << " depth " << MaxDepth << " col " << Colocate << "\n";
3921 for (const auto &I : Nodes)
3922 os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
3923 os << "\n";
3924}
3925
Aaron Ballman615eb472017-10-15 14:32:27 +00003926#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003927/// Print the schedule information to the given output.
3928void SMSchedule::print(raw_ostream &os) const {
3929 // Iterate over each cycle.
3930 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3931 // Iterate over each instruction in the cycle.
3932 const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3933 for (SUnit *CI : cycleInstrs->second) {
3934 os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3935 os << "(" << CI->NodeNum << ") ";
3936 CI->getInstr()->print(os);
3937 os << "\n";
3938 }
3939 }
3940}
3941
3942/// Utility function used for debugging to print the schedule.
Matthias Braun8c209aa2017-01-28 02:02:38 +00003943LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003944LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3945
Matthias Braun8c209aa2017-01-28 02:02:38 +00003946#endif
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003947
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003948void ResourceManager::initProcResourceVectors(
3949 const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3950 unsigned ProcResourceID = 0;
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003951
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003952 // We currently limit the resource kinds to 64 and below so that we can use
3953 // uint64_t for Masks
3954 assert(SM.getNumProcResourceKinds() < 64 &&
3955 "Too many kinds of resources, unsupported");
3956 // Create a unique bitmask for every processor resource unit.
3957 // Skip resource at index 0, since it always references 'InvalidUnit'.
3958 Masks.resize(SM.getNumProcResourceKinds());
3959 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3960 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3961 if (Desc.SubUnitsIdxBegin)
3962 continue;
3963 Masks[I] = 1ULL << ProcResourceID;
3964 ProcResourceID++;
3965 }
3966 // Create a unique bitmask for every processor resource group.
3967 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3968 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3969 if (!Desc.SubUnitsIdxBegin)
3970 continue;
3971 Masks[I] = 1ULL << ProcResourceID;
3972 for (unsigned U = 0; U < Desc.NumUnits; ++U)
3973 Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3974 ProcResourceID++;
3975 }
3976 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00003977 if (SwpShowResMask) {
3978 dbgs() << "ProcResourceDesc:\n";
3979 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3980 const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3981 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3982 ProcResource->Name, I, Masks[I],
3983 ProcResource->NumUnits);
3984 }
3985 dbgs() << " -----------------\n";
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003986 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003987 });
3988}
3989
3990bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
3991
Jinsong Jiba438402019-06-18 20:24:49 +00003992 LLVM_DEBUG({
3993 if (SwpDebugResource)
3994 dbgs() << "canReserveResources:\n";
3995 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003996 if (UseDFA)
3997 return DFAResources->canReserveResources(MID);
3998
3999 unsigned InsnClass = MID->getSchedClass();
4000 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
4001 if (!SCDesc->isValid()) {
4002 LLVM_DEBUG({
4003 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4004 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
4005 });
4006 return true;
4007 }
4008
4009 const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
4010 const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
4011 for (; I != E; ++I) {
4012 if (!I->Cycles)
4013 continue;
4014 const MCProcResourceDesc *ProcResource =
4015 SM.getProcResource(I->ProcResourceIdx);
4016 unsigned NumUnits = ProcResource->NumUnits;
4017 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00004018 if (SwpDebugResource)
4019 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
4020 ProcResource->Name, I->ProcResourceIdx,
4021 ProcResourceCount[I->ProcResourceIdx], NumUnits,
4022 I->Cycles);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004023 });
4024 if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
4025 return false;
4026 }
Jinsong Jiba438402019-06-18 20:24:49 +00004027 LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004028 return true;
4029}
4030
4031void ResourceManager::reserveResources(const MCInstrDesc *MID) {
Jinsong Jiba438402019-06-18 20:24:49 +00004032 LLVM_DEBUG({
4033 if (SwpDebugResource)
4034 dbgs() << "reserveResources:\n";
4035 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004036 if (UseDFA)
4037 return DFAResources->reserveResources(MID);
4038
4039 unsigned InsnClass = MID->getSchedClass();
4040 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
4041 if (!SCDesc->isValid()) {
4042 LLVM_DEBUG({
4043 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4044 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
4045 });
4046 return;
4047 }
4048 for (const MCWriteProcResEntry &PRE :
4049 make_range(STI->getWriteProcResBegin(SCDesc),
4050 STI->getWriteProcResEnd(SCDesc))) {
4051 if (!PRE.Cycles)
4052 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004053 ++ProcResourceCount[PRE.ProcResourceIdx];
4054 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00004055 if (SwpDebugResource) {
4056 const MCProcResourceDesc *ProcResource =
4057 SM.getProcResource(PRE.ProcResourceIdx);
4058 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
4059 ProcResource->Name, PRE.ProcResourceIdx,
4060 ProcResourceCount[PRE.ProcResourceIdx],
4061 ProcResource->NumUnits, PRE.Cycles);
4062 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004063 });
4064 }
Jinsong Jiba438402019-06-18 20:24:49 +00004065 LLVM_DEBUG({
4066 if (SwpDebugResource)
4067 dbgs() << "reserveResources: done!\n\n";
4068 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004069}
4070
4071bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
4072 return canReserveResources(&MI.getDesc());
4073}
4074
4075void ResourceManager::reserveResources(const MachineInstr &MI) {
4076 return reserveResources(&MI.getDesc());
4077}
4078
4079void ResourceManager::clearResources() {
4080 if (UseDFA)
4081 return DFAResources->clearResources();
4082 std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
4083}
Adrian Prantlfa2e3582019-01-14 17:24:11 +00004084