blob: 639d124804c96b18301c385a7050dce5834d6e98 [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
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000151namespace llvm {
152
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000153// A command line option to enable the CopyToPhi DAG mutation.
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000154cl::opt<bool>
Aleksandr Urakov00d4c382018-10-23 14:27:45 +0000155 SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
156 cl::init(true), cl::ZeroOrMore,
157 cl::desc("Enable CopyToPhi DAG Mutation"));
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000158
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000159} // end namespace llvm
Brendon Cahoon254f8892016-07-29 16:44:44 +0000160
161unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
162char MachinePipeliner::ID = 0;
163#ifndef NDEBUG
164int MachinePipeliner::NumTries = 0;
165#endif
166char &llvm::MachinePipelinerID = MachinePipeliner::ID;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000167
Matthias Braun1527baa2017-05-25 21:26:32 +0000168INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000169 "Modulo Software Pipelining", false, false)
170INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
171INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
172INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
173INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000174INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000175 "Modulo Software Pipelining", false, false)
176
177/// The "main" function for implementing Swing Modulo Scheduling.
178bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000179 if (skipFunction(mf.getFunction()))
Brendon Cahoon254f8892016-07-29 16:44:44 +0000180 return false;
181
182 if (!EnableSWP)
183 return false;
184
Matthias Braunf1caa282017-12-15 22:22:58 +0000185 if (mf.getFunction().getAttributes().hasAttribute(
Reid Klecknerb5180542017-03-21 16:57:19 +0000186 AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +0000187 !EnableSWPOptSize.getPosition())
188 return false;
189
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000190 // Cannot pipeline loops without instruction itineraries if we are using
191 // DFA for the pipeliner.
192 if (mf.getSubtarget().useDFAforSMS() &&
193 (!mf.getSubtarget().getInstrItineraryData() ||
194 mf.getSubtarget().getInstrItineraryData()->isEmpty()))
195 return false;
196
Brendon Cahoon254f8892016-07-29 16:44:44 +0000197 MF = &mf;
198 MLI = &getAnalysis<MachineLoopInfo>();
199 MDT = &getAnalysis<MachineDominatorTree>();
200 TII = MF->getSubtarget().getInstrInfo();
201 RegClassInfo.runOnMachineFunction(*MF);
202
203 for (auto &L : *MLI)
204 scheduleLoop(*L);
205
206 return false;
207}
208
209/// Attempt to perform the SMS algorithm on the specified loop. This function is
210/// the main entry point for the algorithm. The function identifies candidate
211/// loops, calculates the minimum initiation interval, and attempts to schedule
212/// the loop.
213bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
214 bool Changed = false;
215 for (auto &InnerLoop : L)
216 Changed |= scheduleLoop(*InnerLoop);
217
218#ifndef NDEBUG
219 // Stop trying after reaching the limit (if any).
220 int Limit = SwpLoopLimit;
221 if (Limit >= 0) {
222 if (NumTries >= SwpLoopLimit)
223 return Changed;
224 NumTries++;
225 }
226#endif
227
Brendon Cahoon59d99732019-01-23 03:26:10 +0000228 setPragmaPipelineOptions(L);
229 if (!canPipelineLoop(L)) {
230 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000231 return Changed;
Brendon Cahoon59d99732019-01-23 03:26:10 +0000232 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000233
234 ++NumTrytoPipeline;
235
236 Changed = swingModuloScheduler(L);
237
238 return Changed;
239}
240
Brendon Cahoon59d99732019-01-23 03:26:10 +0000241void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
242 MachineBasicBlock *LBLK = L.getTopBlock();
243
244 if (LBLK == nullptr)
245 return;
246
247 const BasicBlock *BBLK = LBLK->getBasicBlock();
248 if (BBLK == nullptr)
249 return;
250
251 const Instruction *TI = BBLK->getTerminator();
252 if (TI == nullptr)
253 return;
254
255 MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
256 if (LoopID == nullptr)
257 return;
258
259 assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
260 assert(LoopID->getOperand(0) == LoopID && "invalid loop");
261
262 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
263 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
264
265 if (MD == nullptr)
266 continue;
267
268 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
269
270 if (S == nullptr)
271 continue;
272
273 if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
274 assert(MD->getNumOperands() == 2 &&
275 "Pipeline initiation interval hint metadata should have two operands.");
276 II_setByPragma =
277 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
278 assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
279 } else if (S->getString() == "llvm.loop.pipeline.disable") {
280 disabledByPragma = true;
281 }
282 }
283}
284
Brendon Cahoon254f8892016-07-29 16:44:44 +0000285/// Return true if the loop can be software pipelined. The algorithm is
286/// restricted to loops with a single basic block. Make sure that the
287/// branch in the loop can be analyzed.
288bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
289 if (L.getNumBlocks() != 1)
290 return false;
291
Brendon Cahoon59d99732019-01-23 03:26:10 +0000292 if (disabledByPragma)
293 return false;
294
Brendon Cahoon254f8892016-07-29 16:44:44 +0000295 // Check if the branch can't be understood because we can't do pipelining
296 // if that's the case.
297 LI.TBB = nullptr;
298 LI.FBB = nullptr;
299 LI.BrCond.clear();
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000300 if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
301 LLVM_DEBUG(
302 dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
303 NumFailBranch++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000304 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000305 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000306
307 LI.LoopInductionVar = nullptr;
308 LI.LoopCompare = nullptr;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000309 if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) {
310 LLVM_DEBUG(
311 dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
312 NumFailLoop++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000313 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000314 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000315
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000316 if (!L.getLoopPreheader()) {
317 LLVM_DEBUG(
318 dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
319 NumFailPreheader++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000320 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000321 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000322
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000323 // Remove any subregisters from inputs to phi nodes.
324 preprocessPhiNodes(*L.getHeader());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000325 return true;
326}
327
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000328void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
329 MachineRegisterInfo &MRI = MF->getRegInfo();
330 SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
331
332 for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
333 MachineOperand &DefOp = PI.getOperand(0);
334 assert(DefOp.getSubReg() == 0);
335 auto *RC = MRI.getRegClass(DefOp.getReg());
336
337 for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
338 MachineOperand &RegOp = PI.getOperand(i);
339 if (RegOp.getSubReg() == 0)
340 continue;
341
342 // If the operand uses a subregister, replace it with a new register
343 // without subregisters, and generate a copy to the new register.
344 unsigned NewReg = MRI.createVirtualRegister(RC);
345 MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
346 MachineBasicBlock::iterator At = PredB.getFirstTerminator();
347 const DebugLoc &DL = PredB.findDebugLoc(At);
348 auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
349 .addReg(RegOp.getReg(), getRegState(RegOp),
350 RegOp.getSubReg());
351 Slots.insertMachineInstrInMaps(*Copy);
352 RegOp.setReg(NewReg);
353 RegOp.setSubReg(0);
354 }
355 }
356}
357
Brendon Cahoon254f8892016-07-29 16:44:44 +0000358/// The SMS algorithm consists of the following main steps:
359/// 1. Computation and analysis of the dependence graph.
360/// 2. Ordering of the nodes (instructions).
361/// 3. Attempt to Schedule the loop.
362bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
363 assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
364
Brendon Cahoon59d99732019-01-23 03:26:10 +0000365 SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
366 II_setByPragma);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000367
368 MachineBasicBlock *MBB = L.getHeader();
369 // The kernel should not include any terminator instructions. These
370 // will be added back later.
371 SMS.startBlock(MBB);
372
373 // Compute the number of 'real' instructions in the basic block by
374 // ignoring terminators.
375 unsigned size = MBB->size();
376 for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
377 E = MBB->instr_end();
378 I != E; ++I, --size)
379 ;
380
381 SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
382 SMS.schedule();
383 SMS.exitRegion();
384
385 SMS.finishBlock();
386 return SMS.hasNewSchedule();
387}
388
Brendon Cahoon59d99732019-01-23 03:26:10 +0000389void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
390 if (II_setByPragma > 0)
391 MII = II_setByPragma;
392 else
393 MII = std::max(ResMII, RecMII);
394}
395
396void SwingSchedulerDAG::setMAX_II() {
397 if (II_setByPragma > 0)
398 MAX_II = II_setByPragma;
399 else
400 MAX_II = MII + 10;
401}
402
Brendon Cahoon254f8892016-07-29 16:44:44 +0000403/// We override the schedule function in ScheduleDAGInstrs to implement the
404/// scheduling part of the Swing Modulo Scheduling algorithm.
405void SwingSchedulerDAG::schedule() {
406 AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
407 buildSchedGraph(AA);
408 addLoopCarriedDependences(AA);
409 updatePhiDependences();
410 Topo.InitDAGTopologicalSorting();
411 changeDependences();
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000412 postprocessDAG();
Matthias Braun726e12c2018-09-19 00:23:35 +0000413 LLVM_DEBUG(dump());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000414
415 NodeSetType NodeSets;
416 findCircuits(NodeSets);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000417 NodeSetType Circuits = NodeSets;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000418
419 // Calculate the MII.
420 unsigned ResMII = calculateResMII();
421 unsigned RecMII = calculateRecMII(NodeSets);
422
423 fuseRecs(NodeSets);
424
425 // This flag is used for testing and can cause correctness problems.
426 if (SwpIgnoreRecMII)
427 RecMII = 0;
428
Brendon Cahoon59d99732019-01-23 03:26:10 +0000429 setMII(ResMII, RecMII);
430 setMAX_II();
431
432 LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
433 << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000434
435 // Can't schedule a loop without a valid MII.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000436 if (MII == 0) {
437 LLVM_DEBUG(
438 dbgs()
439 << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
440 NumFailZeroMII++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000441 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000442 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000443
444 // Don't pipeline large loops.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000445 if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
446 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
447 << ", we don't pipleline large loops\n");
448 NumFailLargeMaxMII++;
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 computeNodeFunctions(NodeSets);
453
454 registerPressureFilter(NodeSets);
455
456 colocateNodeSets(NodeSets);
457
458 checkNodeSets(NodeSets);
459
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000460 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000461 for (auto &I : NodeSets) {
462 dbgs() << " Rec NodeSet ";
463 I.dump();
464 }
465 });
466
Fangrui Songefd94c52019-04-23 14:51:27 +0000467 llvm::stable_sort(NodeSets, std::greater<NodeSet>());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000468
469 groupRemainingNodes(NodeSets);
470
471 removeDuplicateNodes(NodeSets);
472
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000473 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000474 for (auto &I : NodeSets) {
475 dbgs() << " NodeSet ";
476 I.dump();
477 }
478 });
479
480 computeNodeOrder(NodeSets);
481
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000482 // check for node order issues
483 checkValidNodeOrder(Circuits);
484
Brendon Cahoon254f8892016-07-29 16:44:44 +0000485 SMSchedule Schedule(Pass.MF);
486 Scheduled = schedulePipeline(Schedule);
487
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000488 if (!Scheduled){
489 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
490 NumFailNoSchedule++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000491 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000492 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000493
494 unsigned numStages = Schedule.getMaxStageCount();
495 // No need to generate pipeline if there are no overlapped iterations.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000496 if (numStages == 0) {
497 LLVM_DEBUG(
498 dbgs() << "No overlapped iterations, no need to generate pipeline\n");
499 NumFailZeroStage++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000500 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000501 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000502 // Check that the maximum stage count is less than user-defined limit.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000503 if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
504 LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
505 << " : too many stages, abort\n");
506 NumFailLargeMaxStage++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000507 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000508 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000509
510 generatePipelinedLoop(Schedule);
511 ++NumPipelined;
512}
513
514/// Clean up after the software pipeliner runs.
515void SwingSchedulerDAG::finishBlock() {
516 for (MachineInstr *I : NewMIs)
517 MF.DeleteMachineInstr(I);
518 NewMIs.clear();
519
520 // Call the superclass.
521 ScheduleDAGInstrs::finishBlock();
522}
523
524/// Return the register values for the operands of a Phi instruction.
525/// This function assume the instruction is a Phi.
526static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
527 unsigned &InitVal, unsigned &LoopVal) {
528 assert(Phi.isPHI() && "Expecting a Phi.");
529
530 InitVal = 0;
531 LoopVal = 0;
532 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
533 if (Phi.getOperand(i + 1).getMBB() != Loop)
534 InitVal = Phi.getOperand(i).getReg();
Simon Pilgrimfbfb19b2017-03-16 19:52:00 +0000535 else
Brendon Cahoon254f8892016-07-29 16:44:44 +0000536 LoopVal = Phi.getOperand(i).getReg();
537
538 assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
539}
540
541/// Return the Phi register value that comes from the incoming block.
542static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
543 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
544 if (Phi.getOperand(i + 1).getMBB() != LoopBB)
545 return Phi.getOperand(i).getReg();
546 return 0;
547}
548
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000549/// Return the Phi register value that comes the loop block.
Brendon Cahoon254f8892016-07-29 16:44:44 +0000550static unsigned getLoopPhiReg(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
557/// Return true if SUb can be reached from SUa following the chain edges.
558static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
559 SmallPtrSet<SUnit *, 8> Visited;
560 SmallVector<SUnit *, 8> Worklist;
561 Worklist.push_back(SUa);
562 while (!Worklist.empty()) {
563 const SUnit *SU = Worklist.pop_back_val();
564 for (auto &SI : SU->Succs) {
565 SUnit *SuccSU = SI.getSUnit();
566 if (SI.getKind() == SDep::Order) {
567 if (Visited.count(SuccSU))
568 continue;
569 if (SuccSU == SUb)
570 return true;
571 Worklist.push_back(SuccSU);
572 Visited.insert(SuccSU);
573 }
574 }
575 }
576 return false;
577}
578
579/// Return true if the instruction causes a chain between memory
580/// references before and after it.
581static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +0000582 return MI.isCall() || MI.mayRaiseFPException() ||
583 MI.hasUnmodeledSideEffects() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +0000584 (MI.hasOrderedMemoryRef() &&
Justin Lebard98cf002016-09-10 01:03:20 +0000585 (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000586}
587
588/// Return the underlying objects for the memory references of an instruction.
589/// This function calls the code in ValueTracking, but first checks that the
590/// instruction has a memory operand.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000591static void getUnderlyingObjects(const MachineInstr *MI,
592 SmallVectorImpl<const Value *> &Objs,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000593 const DataLayout &DL) {
594 if (!MI->hasOneMemOperand())
595 return;
596 MachineMemOperand *MM = *MI->memoperands_begin();
597 if (!MM->getValue())
598 return;
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000599 GetUnderlyingObjects(MM->getValue(), Objs, DL);
600 for (const Value *V : Objs) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000601 if (!isIdentifiedObject(V)) {
602 Objs.clear();
603 return;
604 }
605 Objs.push_back(V);
606 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000607}
608
609/// Add a chain edge between a load and store if the store can be an
610/// alias of the load on a subsequent iteration, i.e., a loop carried
611/// dependence. This code is very similar to the code in ScheduleDAGInstrs
612/// but that code doesn't create loop carried dependences.
613void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000614 MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000615 Value *UnknownValue =
616 UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000617 for (auto &SU : SUnits) {
618 MachineInstr &MI = *SU.getInstr();
619 if (isDependenceBarrier(MI, AA))
620 PendingLoads.clear();
621 else if (MI.mayLoad()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000622 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000623 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000624 if (Objs.empty())
625 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000626 for (auto V : Objs) {
627 SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
628 SUs.push_back(&SU);
629 }
630 } else if (MI.mayStore()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000631 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000632 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000633 if (Objs.empty())
634 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000635 for (auto V : Objs) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000636 MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
Brendon Cahoon254f8892016-07-29 16:44:44 +0000637 PendingLoads.find(V);
638 if (I == PendingLoads.end())
639 continue;
640 for (auto Load : I->second) {
641 if (isSuccOrder(Load, &SU))
642 continue;
643 MachineInstr &LdMI = *Load->getInstr();
644 // First, perform the cheaper check that compares the base register.
645 // If they are the same and the load offset is less than the store
646 // offset, then mark the dependence as loop carried potentially.
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000647 const MachineOperand *BaseOp1, *BaseOp2;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000648 int64_t Offset1, Offset2;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +0000649 if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) &&
650 TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) {
651 if (BaseOp1->isIdenticalTo(*BaseOp2) &&
652 (int)Offset1 < (int)Offset2) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000653 assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
654 "What happened to the chain edge?");
655 SDep Dep(Load, SDep::Barrier);
656 Dep.setLatency(1);
657 SU.addPred(Dep);
658 continue;
659 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000660 }
661 // Second, the more expensive check that uses alias analysis on the
662 // base registers. If they alias, and the load offset is less than
663 // the store offset, the mark the dependence as loop carried.
664 if (!AA) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000665 SDep Dep(Load, SDep::Barrier);
666 Dep.setLatency(1);
667 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000668 continue;
669 }
670 MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
671 MachineMemOperand *MMO2 = *MI.memoperands_begin();
672 if (!MMO1->getValue() || !MMO2->getValue()) {
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 if (MMO1->getValue() == MMO2->getValue() &&
679 MMO1->getOffset() <= MMO2->getOffset()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000680 SDep Dep(Load, SDep::Barrier);
681 Dep.setLatency(1);
682 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000683 continue;
684 }
685 AliasResult AAResult = AA->alias(
George Burgess IV6ef80022018-10-10 21:28:44 +0000686 MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000687 MMO1->getAAInfo()),
George Burgess IV6ef80022018-10-10 21:28:44 +0000688 MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000689 MMO2->getAAInfo()));
690
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000691 if (AAResult != NoAlias) {
692 SDep Dep(Load, SDep::Barrier);
693 Dep.setLatency(1);
694 SU.addPred(Dep);
695 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000696 }
697 }
698 }
699 }
700}
701
702/// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
703/// processes dependences for PHIs. This function adds true dependences
704/// from a PHI to a use, and a loop carried dependence from the use to the
705/// PHI. The loop carried dependence is represented as an anti dependence
706/// edge. This function also removes chain dependences between unrelated
707/// PHIs.
708void SwingSchedulerDAG::updatePhiDependences() {
709 SmallVector<SDep, 4> RemoveDeps;
710 const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
711
712 // Iterate over each DAG node.
713 for (SUnit &I : SUnits) {
714 RemoveDeps.clear();
715 // Set to true if the instruction has an operand defined by a Phi.
716 unsigned HasPhiUse = 0;
717 unsigned HasPhiDef = 0;
718 MachineInstr *MI = I.getInstr();
719 // Iterate over each operand, and we process the definitions.
720 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
721 MOE = MI->operands_end();
722 MOI != MOE; ++MOI) {
723 if (!MOI->isReg())
724 continue;
725 unsigned Reg = MOI->getReg();
726 if (MOI->isDef()) {
727 // If the register is used by a Phi, then create an anti dependence.
728 for (MachineRegisterInfo::use_instr_iterator
729 UI = MRI.use_instr_begin(Reg),
730 UE = MRI.use_instr_end();
731 UI != UE; ++UI) {
732 MachineInstr *UseMI = &*UI;
733 SUnit *SU = getSUnit(UseMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000734 if (SU != nullptr && UseMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000735 if (!MI->isPHI()) {
736 SDep Dep(SU, SDep::Anti, Reg);
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000737 Dep.setLatency(1);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000738 I.addPred(Dep);
739 } else {
740 HasPhiDef = Reg;
741 // Add a chain edge to a dependent Phi that isn't an existing
742 // predecessor.
743 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
744 I.addPred(SDep(SU, SDep::Barrier));
745 }
746 }
747 }
748 } else if (MOI->isUse()) {
749 // If the register is defined by a Phi, then create a true dependence.
750 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000751 if (DefMI == nullptr)
Brendon Cahoon254f8892016-07-29 16:44:44 +0000752 continue;
753 SUnit *SU = getSUnit(DefMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000754 if (SU != nullptr && DefMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000755 if (!MI->isPHI()) {
756 SDep Dep(SU, SDep::Data, Reg);
757 Dep.setLatency(0);
758 ST.adjustSchedDependency(SU, &I, Dep);
759 I.addPred(Dep);
760 } else {
761 HasPhiUse = Reg;
762 // Add a chain edge to a dependent Phi that isn't an existing
763 // predecessor.
764 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
765 I.addPred(SDep(SU, SDep::Barrier));
766 }
767 }
768 }
769 }
770 // Remove order dependences from an unrelated Phi.
771 if (!SwpPruneDeps)
772 continue;
773 for (auto &PI : I.Preds) {
774 MachineInstr *PMI = PI.getSUnit()->getInstr();
775 if (PMI->isPHI() && PI.getKind() == SDep::Order) {
776 if (I.getInstr()->isPHI()) {
777 if (PMI->getOperand(0).getReg() == HasPhiUse)
778 continue;
779 if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
780 continue;
781 }
782 RemoveDeps.push_back(PI);
783 }
784 }
785 for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
786 I.removePred(RemoveDeps[i]);
787 }
788}
789
790/// Iterate over each DAG node and see if we can change any dependences
791/// in order to reduce the recurrence MII.
792void SwingSchedulerDAG::changeDependences() {
793 // See if an instruction can use a value from the previous iteration.
794 // If so, we update the base and offset of the instruction and change
795 // the dependences.
796 for (SUnit &I : SUnits) {
797 unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
798 int64_t NewOffset = 0;
799 if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
800 NewOffset))
801 continue;
802
803 // Get the MI and SUnit for the instruction that defines the original base.
804 unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
805 MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
806 if (!DefMI)
807 continue;
808 SUnit *DefSU = getSUnit(DefMI);
809 if (!DefSU)
810 continue;
811 // Get the MI and SUnit for the instruction that defins the new base.
812 MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
813 if (!LastMI)
814 continue;
815 SUnit *LastSU = getSUnit(LastMI);
816 if (!LastSU)
817 continue;
818
819 if (Topo.IsReachable(&I, LastSU))
820 continue;
821
822 // Remove the dependence. The value now depends on a prior iteration.
823 SmallVector<SDep, 4> Deps;
824 for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
825 ++P)
826 if (P->getSUnit() == DefSU)
827 Deps.push_back(*P);
828 for (int i = 0, e = Deps.size(); i != e; i++) {
829 Topo.RemovePred(&I, Deps[i].getSUnit());
830 I.removePred(Deps[i]);
831 }
832 // Remove the chain dependence between the instructions.
833 Deps.clear();
834 for (auto &P : LastSU->Preds)
835 if (P.getSUnit() == &I && P.getKind() == SDep::Order)
836 Deps.push_back(P);
837 for (int i = 0, e = Deps.size(); i != e; i++) {
838 Topo.RemovePred(LastSU, Deps[i].getSUnit());
839 LastSU->removePred(Deps[i]);
840 }
841
842 // Add a dependence between the new instruction and the instruction
843 // that defines the new base.
844 SDep Dep(&I, SDep::Anti, NewBase);
Sumanth Gundapaneni8916e432018-10-11 19:42:46 +0000845 Topo.AddPred(LastSU, &I);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000846 LastSU->addPred(Dep);
847
848 // Remember the base and offset information so that we can update the
849 // instruction during code generation.
850 InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
851 }
852}
853
854namespace {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000855
Brendon Cahoon254f8892016-07-29 16:44:44 +0000856// FuncUnitSorter - Comparison operator used to sort instructions by
857// the number of functional unit choices.
858struct FuncUnitSorter {
859 const InstrItineraryData *InstrItins;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000860 const MCSubtargetInfo *STI;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000861 DenseMap<unsigned, unsigned> Resources;
862
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000863 FuncUnitSorter(const TargetSubtargetInfo &TSI)
864 : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
Eugene Zelenko32a40562017-09-11 23:00:48 +0000865
Brendon Cahoon254f8892016-07-29 16:44:44 +0000866 // Compute the number of functional unit alternatives needed
867 // at each stage, and take the minimum value. We prioritize the
868 // instructions by the least number of choices first.
869 unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000870 unsigned SchedClass = Inst->getDesc().getSchedClass();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000871 unsigned min = UINT_MAX;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000872 if (InstrItins && !InstrItins->isEmpty()) {
873 for (const InstrStage &IS :
874 make_range(InstrItins->beginStage(SchedClass),
875 InstrItins->endStage(SchedClass))) {
876 unsigned funcUnits = IS.getUnits();
877 unsigned numAlternatives = countPopulation(funcUnits);
878 if (numAlternatives < min) {
879 min = numAlternatives;
880 F = funcUnits;
881 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000882 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000883 return min;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000884 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000885 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
886 const MCSchedClassDesc *SCDesc =
887 STI->getSchedModel().getSchedClassDesc(SchedClass);
888 if (!SCDesc->isValid())
889 // No valid Schedule Class Desc for schedClass, should be
890 // Pseudo/PostRAPseudo
891 return min;
892
893 for (const MCWriteProcResEntry &PRE :
894 make_range(STI->getWriteProcResBegin(SCDesc),
895 STI->getWriteProcResEnd(SCDesc))) {
896 if (!PRE.Cycles)
897 continue;
898 const MCProcResourceDesc *ProcResource =
899 STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
900 unsigned NumUnits = ProcResource->NumUnits;
901 if (NumUnits < min) {
902 min = NumUnits;
903 F = PRE.ProcResourceIdx;
904 }
905 }
906 return min;
907 }
908 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000909 }
910
911 // Compute the critical resources needed by the instruction. This
912 // function records the functional units needed by instructions that
913 // must use only one functional unit. We use this as a tie breaker
914 // for computing the resource MII. The instrutions that require
915 // the same, highly used, functional unit have high priority.
916 void calcCriticalResources(MachineInstr &MI) {
917 unsigned SchedClass = MI.getDesc().getSchedClass();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000918 if (InstrItins && !InstrItins->isEmpty()) {
919 for (const InstrStage &IS :
920 make_range(InstrItins->beginStage(SchedClass),
921 InstrItins->endStage(SchedClass))) {
922 unsigned FuncUnits = IS.getUnits();
923 if (countPopulation(FuncUnits) == 1)
924 Resources[FuncUnits]++;
925 }
926 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000927 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000928 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
929 const MCSchedClassDesc *SCDesc =
930 STI->getSchedModel().getSchedClassDesc(SchedClass);
931 if (!SCDesc->isValid())
932 // No valid Schedule Class Desc for schedClass, should be
933 // Pseudo/PostRAPseudo
934 return;
935
936 for (const MCWriteProcResEntry &PRE :
937 make_range(STI->getWriteProcResBegin(SCDesc),
938 STI->getWriteProcResEnd(SCDesc))) {
939 if (!PRE.Cycles)
940 continue;
941 Resources[PRE.ProcResourceIdx]++;
942 }
943 return;
944 }
945 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000946 }
947
Brendon Cahoon254f8892016-07-29 16:44:44 +0000948 /// Return true if IS1 has less priority than IS2.
949 bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
950 unsigned F1 = 0, F2 = 0;
951 unsigned MFUs1 = minFuncUnits(IS1, F1);
952 unsigned MFUs2 = minFuncUnits(IS2, F2);
953 if (MFUs1 == 1 && MFUs2 == 1)
954 return Resources.lookup(F1) < Resources.lookup(F2);
955 return MFUs1 > MFUs2;
956 }
957};
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000958
959} // end anonymous namespace
Brendon Cahoon254f8892016-07-29 16:44:44 +0000960
961/// Calculate the resource constrained minimum initiation interval for the
962/// specified loop. We use the DFA to model the resources needed for
963/// each instruction, and we ignore dependences. A different DFA is created
964/// for each cycle that is required. When adding a new instruction, we attempt
965/// to add it to each existing DFA, until a legal space is found. If the
966/// instruction cannot be reserved in an existing DFA, we create a new one.
967unsigned SwingSchedulerDAG::calculateResMII() {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000968
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000969 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000970 SmallVector<ResourceManager*, 8> Resources;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000971 MachineBasicBlock *MBB = Loop.getHeader();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000972 Resources.push_back(new ResourceManager(&MF.getSubtarget()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000973
974 // Sort the instructions by the number of available choices for scheduling,
975 // least to most. Use the number of critical resources as the tie breaker.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000976 FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000977 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
978 E = MBB->getFirstTerminator();
979 I != E; ++I)
980 FUS.calcCriticalResources(*I);
981 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
982 FuncUnitOrder(FUS);
983
984 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
985 E = MBB->getFirstTerminator();
986 I != E; ++I)
987 FuncUnitOrder.push(&*I);
988
989 while (!FuncUnitOrder.empty()) {
990 MachineInstr *MI = FuncUnitOrder.top();
991 FuncUnitOrder.pop();
992 if (TII->isZeroCost(MI->getOpcode()))
993 continue;
994 // Attempt to reserve the instruction in an existing DFA. At least one
995 // DFA is needed for each cycle.
996 unsigned NumCycles = getSUnit(MI)->Latency;
997 unsigned ReservedCycles = 0;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000998 SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
999 SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001000 LLVM_DEBUG({
1001 dbgs() << "Trying to reserve resource for " << NumCycles
1002 << " cycles for \n";
1003 MI->dump();
1004 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00001005 for (unsigned C = 0; C < NumCycles; ++C)
1006 while (RI != RE) {
1007 if ((*RI++)->canReserveResources(*MI)) {
1008 ++ReservedCycles;
1009 break;
1010 }
1011 }
1012 // Start reserving resources using existing DFAs.
1013 for (unsigned C = 0; C < ReservedCycles; ++C) {
1014 --RI;
1015 (*RI)->reserveResources(*MI);
1016 }
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001017
1018 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1019 << ", NumCycles:" << NumCycles << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001020 // Add new DFAs, if needed, to reserve resources.
1021 for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001022 LLVM_DEBUG(dbgs() << "NewResource created to reserve resources"
1023 << "\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001024 ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001025 assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1026 NewResource->reserveResources(*MI);
1027 Resources.push_back(NewResource);
1028 }
1029 }
1030 int Resmii = Resources.size();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001031 LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001032 // Delete the memory for each of the DFAs that were created earlier.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001033 for (ResourceManager *RI : Resources) {
1034 ResourceManager *D = RI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001035 delete D;
1036 }
1037 Resources.clear();
1038 return Resmii;
1039}
1040
1041/// Calculate the recurrence-constrainted minimum initiation interval.
1042/// Iterate over each circuit. Compute the delay(c) and distance(c)
1043/// for each circuit. The II needs to satisfy the inequality
1044/// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001045/// II that satisfies the inequality, and the RecMII is the maximum
Brendon Cahoon254f8892016-07-29 16:44:44 +00001046/// of those values.
1047unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1048 unsigned RecMII = 0;
1049
1050 for (NodeSet &Nodes : NodeSets) {
Eugene Zelenko32a40562017-09-11 23:00:48 +00001051 if (Nodes.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001052 continue;
1053
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001054 unsigned Delay = Nodes.getLatency();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001055 unsigned Distance = 1;
1056
1057 // ii = ceil(delay / distance)
1058 unsigned CurMII = (Delay + Distance - 1) / Distance;
1059 Nodes.setRecMII(CurMII);
1060 if (CurMII > RecMII)
1061 RecMII = CurMII;
1062 }
1063
1064 return RecMII;
1065}
1066
1067/// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1068/// but we do this to find the circuits, and then change them back.
1069static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1070 SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1071 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1072 SUnit *SU = &SUnits[i];
1073 for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1074 IP != EP; ++IP) {
1075 if (IP->getKind() != SDep::Anti)
1076 continue;
1077 DepsAdded.push_back(std::make_pair(SU, *IP));
1078 }
1079 }
1080 for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1081 E = DepsAdded.end();
1082 I != E; ++I) {
1083 // Remove this anti dependency and add one in the reverse direction.
1084 SUnit *SU = I->first;
1085 SDep &D = I->second;
1086 SUnit *TargetSU = D.getSUnit();
1087 unsigned Reg = D.getReg();
1088 unsigned Lat = D.getLatency();
1089 SU->removePred(D);
1090 SDep Dep(SU, SDep::Anti, Reg);
1091 Dep.setLatency(Lat);
1092 TargetSU->addPred(Dep);
1093 }
1094}
1095
1096/// Create the adjacency structure of the nodes in the graph.
1097void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1098 SwingSchedulerDAG *DAG) {
1099 BitVector Added(SUnits.size());
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001100 DenseMap<int, int> OutputDeps;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001101 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1102 Added.reset();
1103 // Add any successor to the adjacency matrix and exclude duplicates.
1104 for (auto &SI : SUnits[i].Succs) {
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001105 // Only create a back-edge on the first and last nodes of a dependence
1106 // chain. This records any chains and adds them later.
1107 if (SI.getKind() == SDep::Output) {
1108 int N = SI.getSUnit()->NodeNum;
1109 int BackEdge = i;
1110 auto Dep = OutputDeps.find(BackEdge);
1111 if (Dep != OutputDeps.end()) {
1112 BackEdge = Dep->second;
1113 OutputDeps.erase(Dep);
1114 }
1115 OutputDeps[N] = BackEdge;
1116 }
Sumanth Gundapaneniada0f512018-10-25 21:27:08 +00001117 // Do not process a boundary node, an artificial node.
1118 // A back-edge is processed only if it goes to a Phi.
1119 if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00001120 (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1121 continue;
1122 int N = SI.getSUnit()->NodeNum;
1123 if (!Added.test(N)) {
1124 AdjK[i].push_back(N);
1125 Added.set(N);
1126 }
1127 }
1128 // A chain edge between a store and a load is treated as a back-edge in the
1129 // adjacency matrix.
1130 for (auto &PI : SUnits[i].Preds) {
1131 if (!SUnits[i].getInstr()->mayStore() ||
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001132 !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001133 continue;
1134 if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1135 int N = PI.getSUnit()->NodeNum;
1136 if (!Added.test(N)) {
1137 AdjK[i].push_back(N);
1138 Added.set(N);
1139 }
1140 }
1141 }
1142 }
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00001143 // Add back-edges in the adjacency matrix for the output dependences.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001144 for (auto &OD : OutputDeps)
1145 if (!Added.test(OD.second)) {
1146 AdjK[OD.first].push_back(OD.second);
1147 Added.set(OD.second);
1148 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001149}
1150
1151/// Identify an elementary circuit in the dependence graph starting at the
1152/// specified node.
1153bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1154 bool HasBackedge) {
1155 SUnit *SV = &SUnits[V];
1156 bool F = false;
1157 Stack.insert(SV);
1158 Blocked.set(V);
1159
1160 for (auto W : AdjK[V]) {
1161 if (NumPaths > MaxPaths)
1162 break;
1163 if (W < S)
1164 continue;
1165 if (W == S) {
1166 if (!HasBackedge)
1167 NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1168 F = true;
1169 ++NumPaths;
1170 break;
1171 } else if (!Blocked.test(W)) {
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001172 if (circuit(W, S, NodeSets,
1173 Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001174 F = true;
1175 }
1176 }
1177
1178 if (F)
1179 unblock(V);
1180 else {
1181 for (auto W : AdjK[V]) {
1182 if (W < S)
1183 continue;
1184 if (B[W].count(SV) == 0)
1185 B[W].insert(SV);
1186 }
1187 }
1188 Stack.pop_back();
1189 return F;
1190}
1191
1192/// Unblock a node in the circuit finding algorithm.
1193void SwingSchedulerDAG::Circuits::unblock(int U) {
1194 Blocked.reset(U);
1195 SmallPtrSet<SUnit *, 4> &BU = B[U];
1196 while (!BU.empty()) {
1197 SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1198 assert(SI != BU.end() && "Invalid B set.");
1199 SUnit *W = *SI;
1200 BU.erase(W);
1201 if (Blocked.test(W->NodeNum))
1202 unblock(W->NodeNum);
1203 }
1204}
1205
1206/// Identify all the elementary circuits in the dependence graph using
1207/// Johnson's circuit algorithm.
1208void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1209 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1210 // but we do this to find the circuits, and then change them back.
1211 swapAntiDependences(SUnits);
1212
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001213 Circuits Cir(SUnits, Topo);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001214 // Create the adjacency structure.
1215 Cir.createAdjacencyStructure(this);
1216 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1217 Cir.reset();
1218 Cir.circuit(i, i, NodeSets);
1219 }
1220
1221 // Change the dependences back so that we've created a DAG again.
1222 swapAntiDependences(SUnits);
1223}
1224
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +00001225// Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1226// is loop-carried to the USE in next iteration. This will help pipeliner avoid
1227// additional copies that are needed across iterations. An artificial dependence
1228// edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1229
1230// PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1231// SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1232// PHI-------True-Dep------> USEOfPhi
1233
1234// The mutation creates
1235// USEOfPHI -------Artificial-Dep---> SRCOfCopy
1236
1237// This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1238// (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1239// late to avoid additional copies across iterations. The possible scheduling
1240// order would be
1241// USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1242
1243void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1244 for (SUnit &SU : DAG->SUnits) {
1245 // Find the COPY/REG_SEQUENCE instruction.
1246 if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1247 continue;
1248
1249 // Record the loop carried PHIs.
1250 SmallVector<SUnit *, 4> PHISUs;
1251 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1252 SmallVector<SUnit *, 4> SrcSUs;
1253
1254 for (auto &Dep : SU.Preds) {
1255 SUnit *TmpSU = Dep.getSUnit();
1256 MachineInstr *TmpMI = TmpSU->getInstr();
1257 SDep::Kind DepKind = Dep.getKind();
1258 // Save the loop carried PHI.
1259 if (DepKind == SDep::Anti && TmpMI->isPHI())
1260 PHISUs.push_back(TmpSU);
1261 // Save the source of COPY/REG_SEQUENCE.
1262 // If the source has no pre-decessors, we will end up creating cycles.
1263 else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1264 SrcSUs.push_back(TmpSU);
1265 }
1266
1267 if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1268 continue;
1269
1270 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1271 // SUnit to the container.
1272 SmallVector<SUnit *, 8> UseSUs;
1273 for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
1274 for (auto &Dep : (*I)->Succs) {
1275 if (Dep.getKind() != SDep::Data)
1276 continue;
1277
1278 SUnit *TmpSU = Dep.getSUnit();
1279 MachineInstr *TmpMI = TmpSU->getInstr();
1280 if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1281 PHISUs.push_back(TmpSU);
1282 continue;
1283 }
1284 UseSUs.push_back(TmpSU);
1285 }
1286 }
1287
1288 if (UseSUs.size() == 0)
1289 continue;
1290
1291 SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1292 // Add the artificial dependencies if it does not form a cycle.
1293 for (auto I : UseSUs) {
1294 for (auto Src : SrcSUs) {
1295 if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1296 Src->addPred(SDep(I, SDep::Artificial));
1297 SDAG->Topo.AddPred(Src, I);
1298 }
1299 }
1300 }
1301 }
1302}
1303
Brendon Cahoon254f8892016-07-29 16:44:44 +00001304/// Return true for DAG nodes that we ignore when computing the cost functions.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001305/// We ignore the back-edge recurrence in order to avoid unbounded recursion
Brendon Cahoon254f8892016-07-29 16:44:44 +00001306/// in the calculation of the ASAP, ALAP, etc functions.
1307static bool ignoreDependence(const SDep &D, bool isPred) {
1308 if (D.isArtificial())
1309 return true;
1310 return D.getKind() == SDep::Anti && isPred;
1311}
1312
1313/// Compute several functions need to order the nodes for scheduling.
1314/// ASAP - Earliest time to schedule a node.
1315/// ALAP - Latest time to schedule a node.
1316/// MOV - Mobility function, difference between ALAP and ASAP.
1317/// D - Depth of each node.
1318/// H - Height of each node.
1319void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001320 ScheduleInfo.resize(SUnits.size());
1321
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001322 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001323 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1324 E = Topo.end();
1325 I != E; ++I) {
Matthias Braun726e12c2018-09-19 00:23:35 +00001326 const SUnit &SU = SUnits[*I];
1327 dumpNode(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001328 }
1329 });
1330
1331 int maxASAP = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001332 // Compute ASAP and ZeroLatencyDepth.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001333 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1334 E = Topo.end();
1335 I != E; ++I) {
1336 int asap = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001337 int zeroLatencyDepth = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001338 SUnit *SU = &SUnits[*I];
1339 for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1340 EP = SU->Preds.end();
1341 IP != EP; ++IP) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001342 SUnit *pred = IP->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001343 if (IP->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001344 zeroLatencyDepth =
1345 std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001346 if (ignoreDependence(*IP, true))
1347 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001348 asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00001349 getDistance(pred, SU, *IP) * MII));
1350 }
1351 maxASAP = std::max(maxASAP, asap);
1352 ScheduleInfo[*I].ASAP = asap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001353 ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001354 }
1355
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001356 // Compute ALAP, ZeroLatencyHeight, and MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001357 for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1358 E = Topo.rend();
1359 I != E; ++I) {
1360 int alap = maxASAP;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001361 int zeroLatencyHeight = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001362 SUnit *SU = &SUnits[*I];
1363 for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1364 ES = SU->Succs.end();
1365 IS != ES; ++IS) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001366 SUnit *succ = IS->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001367 if (IS->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001368 zeroLatencyHeight =
1369 std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001370 if (ignoreDependence(*IS, true))
1371 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001372 alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00001373 getDistance(SU, succ, *IS) * MII));
1374 }
1375
1376 ScheduleInfo[*I].ALAP = alap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001377 ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001378 }
1379
1380 // After computing the node functions, compute the summary for each node set.
1381 for (NodeSet &I : NodeSets)
1382 I.computeNodeSetInfo(this);
1383
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001384 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001385 for (unsigned i = 0; i < SUnits.size(); i++) {
1386 dbgs() << "\tNode " << i << ":\n";
1387 dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
1388 dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
1389 dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
1390 dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
1391 dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001392 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1393 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001394 }
1395 });
1396}
1397
1398/// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1399/// as the predecessors of the elements of NodeOrder that are not also in
1400/// NodeOrder.
1401static bool pred_L(SetVector<SUnit *> &NodeOrder,
1402 SmallSetVector<SUnit *, 8> &Preds,
1403 const NodeSet *S = nullptr) {
1404 Preds.clear();
1405 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1406 I != E; ++I) {
1407 for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1408 PI != PE; ++PI) {
1409 if (S && S->count(PI->getSUnit()) == 0)
1410 continue;
1411 if (ignoreDependence(*PI, true))
1412 continue;
1413 if (NodeOrder.count(PI->getSUnit()) == 0)
1414 Preds.insert(PI->getSUnit());
1415 }
1416 // Back-edges are predecessors with an anti-dependence.
1417 for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1418 ES = (*I)->Succs.end();
1419 IS != ES; ++IS) {
1420 if (IS->getKind() != SDep::Anti)
1421 continue;
1422 if (S && S->count(IS->getSUnit()) == 0)
1423 continue;
1424 if (NodeOrder.count(IS->getSUnit()) == 0)
1425 Preds.insert(IS->getSUnit());
1426 }
1427 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001428 return !Preds.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001429}
1430
1431/// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1432/// as the successors of the elements of NodeOrder that are not also in
1433/// NodeOrder.
1434static bool succ_L(SetVector<SUnit *> &NodeOrder,
1435 SmallSetVector<SUnit *, 8> &Succs,
1436 const NodeSet *S = nullptr) {
1437 Succs.clear();
1438 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1439 I != E; ++I) {
1440 for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1441 SI != SE; ++SI) {
1442 if (S && S->count(SI->getSUnit()) == 0)
1443 continue;
1444 if (ignoreDependence(*SI, false))
1445 continue;
1446 if (NodeOrder.count(SI->getSUnit()) == 0)
1447 Succs.insert(SI->getSUnit());
1448 }
1449 for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1450 PE = (*I)->Preds.end();
1451 PI != PE; ++PI) {
1452 if (PI->getKind() != SDep::Anti)
1453 continue;
1454 if (S && S->count(PI->getSUnit()) == 0)
1455 continue;
1456 if (NodeOrder.count(PI->getSUnit()) == 0)
1457 Succs.insert(PI->getSUnit());
1458 }
1459 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001460 return !Succs.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001461}
1462
1463/// Return true if there is a path from the specified node to any of the nodes
1464/// in DestNodes. Keep track and return the nodes in any path.
1465static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1466 SetVector<SUnit *> &DestNodes,
1467 SetVector<SUnit *> &Exclude,
1468 SmallPtrSet<SUnit *, 8> &Visited) {
1469 if (Cur->isBoundaryNode())
1470 return false;
1471 if (Exclude.count(Cur) != 0)
1472 return false;
1473 if (DestNodes.count(Cur) != 0)
1474 return true;
1475 if (!Visited.insert(Cur).second)
1476 return Path.count(Cur) != 0;
1477 bool FoundPath = false;
1478 for (auto &SI : Cur->Succs)
1479 FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1480 for (auto &PI : Cur->Preds)
1481 if (PI.getKind() == SDep::Anti)
1482 FoundPath |=
1483 computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1484 if (FoundPath)
1485 Path.insert(Cur);
1486 return FoundPath;
1487}
1488
1489/// Return true if Set1 is a subset of Set2.
1490template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1491 for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1492 if (Set2.count(*I) == 0)
1493 return false;
1494 return true;
1495}
1496
1497/// Compute the live-out registers for the instructions in a node-set.
1498/// The live-out registers are those that are defined in the node-set,
1499/// but not used. Except for use operands of Phis.
1500static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1501 NodeSet &NS) {
1502 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1503 MachineRegisterInfo &MRI = MF.getRegInfo();
1504 SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1505 SmallSet<unsigned, 4> Uses;
1506 for (SUnit *SU : NS) {
1507 const MachineInstr *MI = SU->getInstr();
1508 if (MI->isPHI())
1509 continue;
Matthias Braunfc371552016-10-24 21:36:43 +00001510 for (const MachineOperand &MO : MI->operands())
1511 if (MO.isReg() && MO.isUse()) {
1512 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001513 if (TargetRegisterInfo::isVirtualRegister(Reg))
1514 Uses.insert(Reg);
1515 else if (MRI.isAllocatable(Reg))
1516 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1517 Uses.insert(*Units);
1518 }
1519 }
1520 for (SUnit *SU : NS)
Matthias Braunfc371552016-10-24 21:36:43 +00001521 for (const MachineOperand &MO : SU->getInstr()->operands())
1522 if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1523 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001524 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1525 if (!Uses.count(Reg))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001526 LiveOutRegs.push_back(RegisterMaskPair(Reg,
1527 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001528 } else if (MRI.isAllocatable(Reg)) {
1529 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1530 if (!Uses.count(*Units))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001531 LiveOutRegs.push_back(RegisterMaskPair(*Units,
1532 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001533 }
1534 }
1535 RPTracker.addLiveRegs(LiveOutRegs);
1536}
1537
1538/// A heuristic to filter nodes in recurrent node-sets if the register
1539/// pressure of a set is too high.
1540void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1541 for (auto &NS : NodeSets) {
1542 // Skip small node-sets since they won't cause register pressure problems.
1543 if (NS.size() <= 2)
1544 continue;
1545 IntervalPressure RecRegPressure;
1546 RegPressureTracker RecRPTracker(RecRegPressure);
1547 RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1548 computeLiveOuts(MF, RecRPTracker, NS);
1549 RecRPTracker.closeBottom();
1550
1551 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
Fangrui Song0cac7262018-09-27 02:13:45 +00001552 llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001553 return A->NodeNum > B->NodeNum;
1554 });
1555
1556 for (auto &SU : SUnits) {
1557 // Since we're computing the register pressure for a subset of the
1558 // instructions in a block, we need to set the tracker for each
1559 // instruction in the node-set. The tracker is set to the instruction
1560 // just after the one we're interested in.
1561 MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1562 RecRPTracker.setPos(std::next(CurInstI));
1563
1564 RegPressureDelta RPDelta;
1565 ArrayRef<PressureChange> CriticalPSets;
1566 RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1567 CriticalPSets,
1568 RecRegPressure.MaxSetPressure);
1569 if (RPDelta.Excess.isValid()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001570 LLVM_DEBUG(
1571 dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1572 << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1573 << ":" << RPDelta.Excess.getUnitInc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001574 NS.setExceedPressure(SU);
1575 break;
1576 }
1577 RecRPTracker.recede();
1578 }
1579 }
1580}
1581
1582/// A heuristic to colocate node sets that have the same set of
1583/// successors.
1584void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1585 unsigned Colocate = 0;
1586 for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1587 NodeSet &N1 = NodeSets[i];
1588 SmallSetVector<SUnit *, 8> S1;
1589 if (N1.empty() || !succ_L(N1, S1))
1590 continue;
1591 for (int j = i + 1; j < e; ++j) {
1592 NodeSet &N2 = NodeSets[j];
1593 if (N1.compareRecMII(N2) != 0)
1594 continue;
1595 SmallSetVector<SUnit *, 8> S2;
1596 if (N2.empty() || !succ_L(N2, S2))
1597 continue;
1598 if (isSubset(S1, S2) && S1.size() == S2.size()) {
1599 N1.setColocate(++Colocate);
1600 N2.setColocate(Colocate);
1601 break;
1602 }
1603 }
1604 }
1605}
1606
1607/// Check if the existing node-sets are profitable. If not, then ignore the
1608/// recurrent node-sets, and attempt to schedule all nodes together. This is
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001609/// a heuristic. If the MII is large and all the recurrent node-sets are small,
1610/// then it's best to try to schedule all instructions together instead of
1611/// starting with the recurrent node-sets.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001612void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1613 // Look for loops with a large MII.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001614 if (MII < 17)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001615 return;
1616 // Check if the node-set contains only a simple add recurrence.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001617 for (auto &NS : NodeSets) {
1618 if (NS.getRecMII() > 2)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001619 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001620 if (NS.getMaxDepth() > MII)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001621 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001622 }
1623 NodeSets.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001624 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001625 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001626}
1627
1628/// Add the nodes that do not belong to a recurrence set into groups
1629/// based upon connected componenets.
1630void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1631 SetVector<SUnit *> NodesAdded;
1632 SmallPtrSet<SUnit *, 8> Visited;
1633 // Add the nodes that are on a path between the previous node sets and
1634 // the current node set.
1635 for (NodeSet &I : NodeSets) {
1636 SmallSetVector<SUnit *, 8> N;
1637 // Add the nodes from the current node set to the previous node set.
1638 if (succ_L(I, N)) {
1639 SetVector<SUnit *> Path;
1640 for (SUnit *NI : N) {
1641 Visited.clear();
1642 computePath(NI, Path, NodesAdded, I, Visited);
1643 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001644 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001645 I.insert(Path.begin(), Path.end());
1646 }
1647 // Add the nodes from the previous node set to the current node set.
1648 N.clear();
1649 if (succ_L(NodesAdded, N)) {
1650 SetVector<SUnit *> Path;
1651 for (SUnit *NI : N) {
1652 Visited.clear();
1653 computePath(NI, Path, I, NodesAdded, Visited);
1654 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001655 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001656 I.insert(Path.begin(), Path.end());
1657 }
1658 NodesAdded.insert(I.begin(), I.end());
1659 }
1660
1661 // Create a new node set with the connected nodes of any successor of a node
1662 // in a recurrent set.
1663 NodeSet NewSet;
1664 SmallSetVector<SUnit *, 8> N;
1665 if (succ_L(NodesAdded, N))
1666 for (SUnit *I : N)
1667 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001668 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001669 NodeSets.push_back(NewSet);
1670
1671 // Create a new node set with the connected nodes of any predecessor of a node
1672 // in a recurrent set.
1673 NewSet.clear();
1674 if (pred_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
Hiroshi Inoue372ffa12018-04-13 11:37:06 +00001680 // Create new nodes sets with the connected nodes any remaining node that
Brendon Cahoon254f8892016-07-29 16:44:44 +00001681 // has no predecessor.
1682 for (unsigned i = 0; i < SUnits.size(); ++i) {
1683 SUnit *SU = &SUnits[i];
1684 if (NodesAdded.count(SU) == 0) {
1685 NewSet.clear();
1686 addConnectedNodes(SU, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001687 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001688 NodeSets.push_back(NewSet);
1689 }
1690 }
1691}
1692
Alexey Lapshin31f47b82019-01-25 21:59:53 +00001693/// Add the node to the set, and add all of its connected nodes to the set.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001694void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1695 SetVector<SUnit *> &NodesAdded) {
1696 NewSet.insert(SU);
1697 NodesAdded.insert(SU);
1698 for (auto &SI : SU->Succs) {
1699 SUnit *Successor = SI.getSUnit();
1700 if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1701 addConnectedNodes(Successor, NewSet, NodesAdded);
1702 }
1703 for (auto &PI : SU->Preds) {
1704 SUnit *Predecessor = PI.getSUnit();
1705 if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1706 addConnectedNodes(Predecessor, NewSet, NodesAdded);
1707 }
1708}
1709
1710/// Return true if Set1 contains elements in Set2. The elements in common
1711/// are returned in a different container.
1712static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1713 SmallSetVector<SUnit *, 8> &Result) {
1714 Result.clear();
1715 for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1716 SUnit *SU = Set1[i];
1717 if (Set2.count(SU) != 0)
1718 Result.insert(SU);
1719 }
1720 return !Result.empty();
1721}
1722
1723/// Merge the recurrence node sets that have the same initial node.
1724void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1725 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1726 ++I) {
1727 NodeSet &NI = *I;
1728 for (NodeSetType::iterator J = I + 1; J != E;) {
1729 NodeSet &NJ = *J;
1730 if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1731 if (NJ.compareRecMII(NI) > 0)
1732 NI.setRecMII(NJ.getRecMII());
1733 for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1734 ++NII)
1735 I->insert(*NII);
1736 NodeSets.erase(J);
1737 E = NodeSets.end();
1738 } else {
1739 ++J;
1740 }
1741 }
1742 }
1743}
1744
1745/// Remove nodes that have been scheduled in previous NodeSets.
1746void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1747 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1748 ++I)
1749 for (NodeSetType::iterator J = I + 1; J != E;) {
1750 J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1751
Eugene Zelenko32a40562017-09-11 23:00:48 +00001752 if (J->empty()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001753 NodeSets.erase(J);
1754 E = NodeSets.end();
1755 } else {
1756 ++J;
1757 }
1758 }
1759}
1760
Brendon Cahoon254f8892016-07-29 16:44:44 +00001761/// Compute an ordered list of the dependence graph nodes, which
1762/// indicates the order that the nodes will be scheduled. This is a
1763/// two-level algorithm. First, a partial order is created, which
1764/// consists of a list of sets ordered from highest to lowest priority.
1765void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1766 SmallSetVector<SUnit *, 8> R;
1767 NodeOrder.clear();
1768
1769 for (auto &Nodes : NodeSets) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001770 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001771 OrderKind Order;
1772 SmallSetVector<SUnit *, 8> N;
1773 if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1774 R.insert(N.begin(), N.end());
1775 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001776 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001777 } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1778 R.insert(N.begin(), N.end());
1779 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001780 LLVM_DEBUG(dbgs() << " Top down (succs) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001781 } else if (isIntersect(N, Nodes, R)) {
1782 // If some of the successors are in the existing node-set, then use the
1783 // top-down ordering.
1784 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001785 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001786 } else if (NodeSets.size() == 1) {
1787 for (auto &N : Nodes)
1788 if (N->Succs.size() == 0)
1789 R.insert(N);
1790 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001791 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001792 } else {
1793 // Find the node with the highest ASAP.
1794 SUnit *maxASAP = nullptr;
1795 for (SUnit *SU : Nodes) {
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001796 if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1797 (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001798 maxASAP = SU;
1799 }
1800 R.insert(maxASAP);
1801 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001802 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001803 }
1804
1805 while (!R.empty()) {
1806 if (Order == TopDown) {
1807 // Choose the node with the maximum height. If more than one, choose
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001808 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001809 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001810 while (!R.empty()) {
1811 SUnit *maxHeight = nullptr;
1812 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001813 if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001814 maxHeight = I;
1815 else if (getHeight(I) == getHeight(maxHeight) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001816 getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001817 maxHeight = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001818 else if (getHeight(I) == getHeight(maxHeight) &&
1819 getZeroLatencyHeight(I) ==
1820 getZeroLatencyHeight(maxHeight) &&
1821 getMOV(I) < getMOV(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001822 maxHeight = I;
1823 }
1824 NodeOrder.insert(maxHeight);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001825 LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001826 R.remove(maxHeight);
1827 for (const auto &I : maxHeight->Succs) {
1828 if (Nodes.count(I.getSUnit()) == 0)
1829 continue;
1830 if (NodeOrder.count(I.getSUnit()) != 0)
1831 continue;
1832 if (ignoreDependence(I, false))
1833 continue;
1834 R.insert(I.getSUnit());
1835 }
1836 // Back-edges are predecessors with an anti-dependence.
1837 for (const auto &I : maxHeight->Preds) {
1838 if (I.getKind() != SDep::Anti)
1839 continue;
1840 if (Nodes.count(I.getSUnit()) == 0)
1841 continue;
1842 if (NodeOrder.count(I.getSUnit()) != 0)
1843 continue;
1844 R.insert(I.getSUnit());
1845 }
1846 }
1847 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001848 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001849 SmallSetVector<SUnit *, 8> N;
1850 if (pred_L(NodeOrder, N, &Nodes))
1851 R.insert(N.begin(), N.end());
1852 } else {
1853 // Choose the node with the maximum depth. If more than one, choose
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001854 // the node with the maximum ZeroLatencyDepth. If still more than one,
1855 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001856 while (!R.empty()) {
1857 SUnit *maxDepth = nullptr;
1858 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001859 if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001860 maxDepth = I;
1861 else if (getDepth(I) == getDepth(maxDepth) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001862 getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001863 maxDepth = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001864 else if (getDepth(I) == getDepth(maxDepth) &&
1865 getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
1866 getMOV(I) < getMOV(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001867 maxDepth = I;
1868 }
1869 NodeOrder.insert(maxDepth);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001870 LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001871 R.remove(maxDepth);
1872 if (Nodes.isExceedSU(maxDepth)) {
1873 Order = TopDown;
1874 R.clear();
1875 R.insert(Nodes.getNode(0));
1876 break;
1877 }
1878 for (const auto &I : maxDepth->Preds) {
1879 if (Nodes.count(I.getSUnit()) == 0)
1880 continue;
1881 if (NodeOrder.count(I.getSUnit()) != 0)
1882 continue;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001883 R.insert(I.getSUnit());
1884 }
1885 // Back-edges are predecessors with an anti-dependence.
1886 for (const auto &I : maxDepth->Succs) {
1887 if (I.getKind() != SDep::Anti)
1888 continue;
1889 if (Nodes.count(I.getSUnit()) == 0)
1890 continue;
1891 if (NodeOrder.count(I.getSUnit()) != 0)
1892 continue;
1893 R.insert(I.getSUnit());
1894 }
1895 }
1896 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001897 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001898 SmallSetVector<SUnit *, 8> N;
1899 if (succ_L(NodeOrder, N, &Nodes))
1900 R.insert(N.begin(), N.end());
1901 }
1902 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001903 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001904 }
1905
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001906 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001907 dbgs() << "Node order: ";
1908 for (SUnit *I : NodeOrder)
1909 dbgs() << " " << I->NodeNum << " ";
1910 dbgs() << "\n";
1911 });
1912}
1913
1914/// Process the nodes in the computed order and create the pipelined schedule
1915/// of the instructions, if possible. Return true if a schedule is found.
1916bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001917
1918 if (NodeOrder.empty()){
1919 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
Brendon Cahoon254f8892016-07-29 16:44:44 +00001920 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001921 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001922
1923 bool scheduleFound = false;
Brendon Cahoon59d99732019-01-23 03:26:10 +00001924 unsigned II = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001925 // Keep increasing II until a valid schedule is found.
Brendon Cahoon59d99732019-01-23 03:26:10 +00001926 for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001927 Schedule.reset();
1928 Schedule.setInitiationInterval(II);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001929 LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001930
1931 SetVector<SUnit *>::iterator NI = NodeOrder.begin();
1932 SetVector<SUnit *>::iterator NE = NodeOrder.end();
1933 do {
1934 SUnit *SU = *NI;
1935
1936 // Compute the schedule time for the instruction, which is based
1937 // upon the scheduled time for any predecessors/successors.
1938 int EarlyStart = INT_MIN;
1939 int LateStart = INT_MAX;
1940 // These values are set when the size of the schedule window is limited
1941 // due to chain dependences.
1942 int SchedEnd = INT_MAX;
1943 int SchedStart = INT_MIN;
1944 Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1945 II, this);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001946 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001947 dbgs() << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001948 dbgs() << "Inst (" << SU->NodeNum << ") ";
1949 SU->getInstr()->dump();
1950 dbgs() << "\n";
1951 });
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001952 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001953 dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
1954 LateStart, SchedEnd, SchedStart);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001955 });
1956
1957 if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
1958 SchedStart > LateStart)
1959 scheduleFound = false;
1960 else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
1961 SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
1962 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1963 } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
1964 SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
1965 scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
1966 } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
1967 SchedEnd =
1968 std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
1969 // When scheduling a Phi it is better to start at the late cycle and go
1970 // backwards. The default order may insert the Phi too far away from
1971 // its first dependence.
1972 if (SU->getInstr()->isPHI())
1973 scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
1974 else
1975 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1976 } else {
1977 int FirstCycle = Schedule.getFirstCycle();
1978 scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
1979 FirstCycle + getASAP(SU) + II - 1, II);
1980 }
1981 // Even if we find a schedule, make sure the schedule doesn't exceed the
1982 // allowable number of stages. We keep trying if this happens.
1983 if (scheduleFound)
1984 if (SwpMaxStages > -1 &&
1985 Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
1986 scheduleFound = false;
1987
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001988 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001989 if (!scheduleFound)
1990 dbgs() << "\tCan't schedule\n";
1991 });
1992 } while (++NI != NE && scheduleFound);
1993
1994 // If a schedule is found, check if it is a valid schedule too.
1995 if (scheduleFound)
1996 scheduleFound = Schedule.isValidSchedule(this);
1997 }
1998
Brendon Cahoon59d99732019-01-23 03:26:10 +00001999 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
2000 << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00002001
2002 if (scheduleFound)
2003 Schedule.finalizeSchedule(this);
2004 else
2005 Schedule.reset();
2006
2007 return scheduleFound && Schedule.getMaxStageCount() > 0;
2008}
2009
2010/// Given a schedule for the loop, generate a new version of the loop,
2011/// and replace the old version. This function generates a prolog
2012/// that contains the initial iterations in the pipeline, and kernel
2013/// loop, and the epilogue that contains the code for the final
2014/// iterations.
2015void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2016 // Create a new basic block for the kernel and add it to the CFG.
2017 MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2018
2019 unsigned MaxStageCount = Schedule.getMaxStageCount();
2020
2021 // Remember the registers that are used in different stages. The index is
2022 // the iteration, or stage, that the instruction is scheduled in. This is
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002023 // a map between register names in the original block and the names created
Brendon Cahoon254f8892016-07-29 16:44:44 +00002024 // in each stage of the pipelined loop.
2025 ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
2026 InstrMapTy InstrMap;
2027
2028 SmallVector<MachineBasicBlock *, 4> PrologBBs;
2029 // Generate the prolog instructions that set up the pipeline.
2030 generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2031 MF.insert(BB->getIterator(), KernelBB);
2032
2033 // Rearrange the instructions to generate the new, pipelined loop,
2034 // and update register names as needed.
2035 for (int Cycle = Schedule.getFirstCycle(),
2036 LastCycle = Schedule.getFinalCycle();
2037 Cycle <= LastCycle; ++Cycle) {
2038 std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2039 // This inner loop schedules each instruction in the cycle.
2040 for (SUnit *CI : CycleInstrs) {
2041 if (CI->getInstr()->isPHI())
2042 continue;
2043 unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2044 MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2045 updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
2046 KernelBB->push_back(NewMI);
2047 InstrMap[NewMI] = CI->getInstr();
2048 }
2049 }
2050
2051 // Copy any terminator instructions to the new kernel, and update
2052 // names as needed.
2053 for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
2054 E = BB->instr_end();
2055 I != E; ++I) {
2056 MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
2057 updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
2058 KernelBB->push_back(NewMI);
2059 InstrMap[NewMI] = &*I;
2060 }
2061
2062 KernelBB->transferSuccessors(BB);
2063 KernelBB->replaceSuccessor(BB, KernelBB);
2064
2065 generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
2066 VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
2067 generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
2068 InstrMap, MaxStageCount, MaxStageCount, false);
2069
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002070 LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00002071
2072 SmallVector<MachineBasicBlock *, 4> EpilogBBs;
2073 // Generate the epilog instructions to complete the pipeline.
2074 generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2075 PrologBBs);
2076
2077 // We need this step because the register allocation doesn't handle some
2078 // situations well, so we insert copies to help out.
2079 splitLifetimes(KernelBB, EpilogBBs, Schedule);
2080
2081 // Remove dead instructions due to loop induction variables.
2082 removeDeadInstructions(KernelBB, EpilogBBs);
2083
2084 // Add branches between prolog and epilog blocks.
2085 addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
2086
2087 // Remove the original loop since it's no longer referenced.
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002088 for (auto &I : *BB)
2089 LIS.RemoveMachineInstrFromMaps(I);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002090 BB->clear();
2091 BB->eraseFromParent();
2092
2093 delete[] VRMap;
2094}
2095
2096/// Generate the pipeline prolog code.
2097void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
2098 MachineBasicBlock *KernelBB,
2099 ValueMapTy *VRMap,
2100 MBBVectorTy &PrologBBs) {
2101 MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
Eugene Zelenko32a40562017-09-11 23:00:48 +00002102 assert(PreheaderBB != nullptr &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002103 "Need to add code to handle loops w/o preheader");
2104 MachineBasicBlock *PredBB = PreheaderBB;
2105 InstrMapTy InstrMap;
2106
2107 // Generate a basic block for each stage, not including the last stage,
2108 // which will be generated in the kernel. Each basic block may contain
2109 // instructions from multiple stages/iterations.
2110 for (unsigned i = 0; i < LastStage; ++i) {
2111 // Create and insert the prolog basic block prior to the original loop
2112 // basic block. The original loop is removed later.
2113 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2114 PrologBBs.push_back(NewBB);
2115 MF.insert(BB->getIterator(), NewBB);
2116 NewBB->transferSuccessors(PredBB);
2117 PredBB->addSuccessor(NewBB);
2118 PredBB = NewBB;
2119
2120 // Generate instructions for each appropriate stage. Process instructions
2121 // in original program order.
2122 for (int StageNum = i; StageNum >= 0; --StageNum) {
2123 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2124 BBE = BB->getFirstTerminator();
2125 BBI != BBE; ++BBI) {
2126 if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
2127 if (BBI->isPHI())
2128 continue;
2129 MachineInstr *NewMI =
2130 cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
2131 updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
2132 VRMap);
2133 NewBB->push_back(NewMI);
2134 InstrMap[NewMI] = &*BBI;
2135 }
2136 }
2137 }
2138 rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002139 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002140 dbgs() << "prolog:\n";
2141 NewBB->dump();
2142 });
2143 }
2144
2145 PredBB->replaceSuccessor(BB, KernelBB);
2146
2147 // Check if we need to remove the branch from the preheader to the original
2148 // loop, and replace it with a branch to the new loop.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002149 unsigned numBranches = TII->removeBranch(*PreheaderBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002150 if (numBranches) {
2151 SmallVector<MachineOperand, 0> Cond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002152 TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002153 }
2154}
2155
2156/// Generate the pipeline epilog code. The epilog code finishes the iterations
2157/// that were started in either the prolog or the kernel. We create a basic
2158/// block for each stage that needs to complete.
2159void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
2160 MachineBasicBlock *KernelBB,
2161 ValueMapTy *VRMap,
2162 MBBVectorTy &EpilogBBs,
2163 MBBVectorTy &PrologBBs) {
2164 // We need to change the branch from the kernel to the first epilog block, so
2165 // this call to analyze branch uses the kernel rather than the original BB.
2166 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2167 SmallVector<MachineOperand, 4> Cond;
2168 bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2169 assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2170 if (checkBranch)
2171 return;
2172
2173 MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2174 if (*LoopExitI == KernelBB)
2175 ++LoopExitI;
2176 assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2177 MachineBasicBlock *LoopExitBB = *LoopExitI;
2178
2179 MachineBasicBlock *PredBB = KernelBB;
2180 MachineBasicBlock *EpilogStart = LoopExitBB;
2181 InstrMapTy InstrMap;
2182
2183 // Generate a basic block for each stage, not including the last stage,
2184 // which was generated for the kernel. Each basic block may contain
2185 // instructions from multiple stages/iterations.
2186 int EpilogStage = LastStage + 1;
2187 for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2188 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2189 EpilogBBs.push_back(NewBB);
2190 MF.insert(BB->getIterator(), NewBB);
2191
2192 PredBB->replaceSuccessor(LoopExitBB, NewBB);
2193 NewBB->addSuccessor(LoopExitBB);
2194
2195 if (EpilogStart == LoopExitBB)
2196 EpilogStart = NewBB;
2197
2198 // Add instructions to the epilog depending on the current block.
2199 // Process instructions in original program order.
2200 for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2201 for (auto &BBI : *BB) {
2202 if (BBI.isPHI())
2203 continue;
2204 MachineInstr *In = &BBI;
2205 if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002206 // Instructions with memoperands in the epilog are updated with
2207 // conservative values.
2208 MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002209 updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2210 NewBB->push_back(NewMI);
2211 InstrMap[NewMI] = In;
2212 }
2213 }
2214 }
2215 generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2216 VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2217 generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2218 InstrMap, LastStage, EpilogStage, i == 1);
2219 PredBB = NewBB;
2220
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002221 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002222 dbgs() << "epilog:\n";
2223 NewBB->dump();
2224 });
2225 }
2226
2227 // Fix any Phi nodes in the loop exit block.
2228 for (MachineInstr &MI : *LoopExitBB) {
2229 if (!MI.isPHI())
2230 break;
2231 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2232 MachineOperand &MO = MI.getOperand(i);
2233 if (MO.getMBB() == BB)
2234 MO.setMBB(PredBB);
2235 }
2236 }
2237
2238 // Create a branch to the new epilog from the kernel.
2239 // Remove the original branch and add a new branch to the epilog.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002240 TII->removeBranch(*KernelBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002241 TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002242 // Add a branch to the loop exit.
2243 if (EpilogBBs.size() > 0) {
2244 MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2245 SmallVector<MachineOperand, 4> Cond1;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002246 TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002247 }
2248}
2249
2250/// Replace all uses of FromReg that appear outside the specified
2251/// basic block with ToReg.
2252static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2253 MachineBasicBlock *MBB,
2254 MachineRegisterInfo &MRI,
2255 LiveIntervals &LIS) {
2256 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2257 E = MRI.use_end();
2258 I != E;) {
2259 MachineOperand &O = *I;
2260 ++I;
2261 if (O.getParent()->getParent() != MBB)
2262 O.setReg(ToReg);
2263 }
2264 if (!LIS.hasInterval(ToReg))
2265 LIS.createEmptyInterval(ToReg);
2266}
2267
2268/// Return true if the register has a use that occurs outside the
2269/// specified loop.
2270static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2271 MachineRegisterInfo &MRI) {
2272 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2273 E = MRI.use_end();
2274 I != E; ++I)
2275 if (I->getParent()->getParent() != BB)
2276 return true;
2277 return false;
2278}
2279
2280/// Generate Phis for the specific block in the generated pipelined code.
2281/// This function looks at the Phis from the original code to guide the
2282/// creation of new Phis.
2283void SwingSchedulerDAG::generateExistingPhis(
2284 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2285 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2286 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2287 bool IsLast) {
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00002288 // Compute the stage number for the initial value of the Phi, which
Brendon Cahoon254f8892016-07-29 16:44:44 +00002289 // comes from the prolog. The prolog to use depends on to which kernel/
2290 // epilog that we're adding the Phi.
2291 unsigned PrologStage = 0;
2292 unsigned PrevStage = 0;
2293 bool InKernel = (LastStageNum == CurStageNum);
2294 if (InKernel) {
2295 PrologStage = LastStageNum - 1;
2296 PrevStage = CurStageNum;
2297 } else {
2298 PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2299 PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2300 }
2301
2302 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2303 BBE = BB->getFirstNonPHI();
2304 BBI != BBE; ++BBI) {
2305 unsigned Def = BBI->getOperand(0).getReg();
2306
2307 unsigned InitVal = 0;
2308 unsigned LoopVal = 0;
2309 getPhiRegs(*BBI, BB, InitVal, LoopVal);
2310
2311 unsigned PhiOp1 = 0;
2312 // The Phi value from the loop body typically is defined in the loop, but
2313 // not always. So, we need to check if the value is defined in the loop.
2314 unsigned PhiOp2 = LoopVal;
2315 if (VRMap[LastStageNum].count(LoopVal))
2316 PhiOp2 = VRMap[LastStageNum][LoopVal];
2317
2318 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2319 int LoopValStage =
2320 Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2321 unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2322 if (NumStages == 0) {
2323 // We don't need to generate a Phi anymore, but we need to rename any uses
2324 // of the Phi value.
2325 unsigned NewReg = VRMap[PrevStage][LoopVal];
2326 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
Krzysztof Parzyszek16e66f52018-03-26 16:41:36 +00002327 Def, InitVal, NewReg);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002328 if (VRMap[CurStageNum].count(LoopVal))
2329 VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2330 }
2331 // Adjust the number of Phis needed depending on the number of prologs left,
Krzysztof Parzyszek3f72a6b2018-03-26 16:37:55 +00002332 // and the distance from where the Phi is first scheduled. The number of
2333 // Phis cannot exceed the number of prolog stages. Each stage can
2334 // potentially define two values.
2335 unsigned MaxPhis = PrologStage + 2;
2336 if (!InKernel && (int)PrologStage <= LoopValStage)
2337 MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
2338 unsigned NumPhis = std::min(NumStages, MaxPhis);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002339
2340 unsigned NewReg = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002341 unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2342 // In the epilog, we may need to look back one stage to get the correct
2343 // Phi name because the epilog and prolog blocks execute the same stage.
2344 // The correct name is from the previous block only when the Phi has
2345 // been completely scheduled prior to the epilog, and Phi value is not
2346 // needed in multiple stages.
2347 int StageDiff = 0;
2348 if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2349 NumPhis == 1)
2350 StageDiff = 1;
2351 // Adjust the computations below when the phi and the loop definition
2352 // are scheduled in different stages.
2353 if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2354 StageDiff = StageScheduled - LoopValStage;
2355 for (unsigned np = 0; np < NumPhis; ++np) {
2356 // If the Phi hasn't been scheduled, then use the initial Phi operand
2357 // value. Otherwise, use the scheduled version of the instruction. This
2358 // is a little complicated when a Phi references another Phi.
2359 if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2360 PhiOp1 = InitVal;
2361 // Check if the Phi has already been scheduled in a prolog stage.
2362 else if (PrologStage >= AccessStage + StageDiff + np &&
2363 VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2364 PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00002365 // Check if the Phi has already been scheduled, but the loop instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00002366 // is either another Phi, or doesn't occur in the loop.
2367 else if (PrologStage >= AccessStage + StageDiff + np) {
2368 // If the Phi references another Phi, we need to examine the other
2369 // Phi to get the correct value.
2370 PhiOp1 = LoopVal;
2371 MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2372 int Indirects = 1;
2373 while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2374 int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2375 if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2376 PhiOp1 = getInitPhiReg(*InstOp1, BB);
2377 else
2378 PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2379 InstOp1 = MRI.getVRegDef(PhiOp1);
2380 int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2381 int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2382 if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2383 VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2384 PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2385 break;
2386 }
2387 ++Indirects;
2388 }
2389 } else
2390 PhiOp1 = InitVal;
2391 // If this references a generated Phi in the kernel, get the Phi operand
2392 // from the incoming block.
2393 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2394 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2395 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2396
2397 MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2398 bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2399 // In the epilog, a map lookup is needed to get the value from the kernel,
2400 // or previous epilog block. How is does this depends on if the
2401 // instruction is scheduled in the previous block.
2402 if (!InKernel) {
2403 int StageDiffAdj = 0;
2404 if (LoopValStage != -1 && StageScheduled > LoopValStage)
2405 StageDiffAdj = StageScheduled - LoopValStage;
2406 // Use the loop value defined in the kernel, unless the kernel
2407 // contains the last definition of the Phi.
2408 if (np == 0 && PrevStage == LastStageNum &&
2409 (StageScheduled != 0 || LoopValStage != 0) &&
2410 VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2411 PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2412 // Use the value defined by the Phi. We add one because we switch
2413 // from looking at the loop value to the Phi definition.
2414 else if (np > 0 && PrevStage == LastStageNum &&
2415 VRMap[PrevStage - np + 1].count(Def))
2416 PhiOp2 = VRMap[PrevStage - np + 1][Def];
2417 // Use the loop value defined in the kernel.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002418 else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002419 VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2420 PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2421 // Use the value defined by the Phi, unless we're generating the first
2422 // epilog and the Phi refers to a Phi in a different stage.
2423 else if (VRMap[PrevStage - np].count(Def) &&
2424 (!LoopDefIsPhi || PrevStage != LastStageNum))
2425 PhiOp2 = VRMap[PrevStage - np][Def];
2426 }
2427
2428 // Check if we can reuse an existing Phi. This occurs when a Phi
2429 // references another Phi, and the other Phi is scheduled in an
2430 // earlier stage. We can try to reuse an existing Phi up until the last
2431 // stage of the current Phi.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002432 if (LoopDefIsPhi) {
2433 if (static_cast<int>(PrologStage - np) >= StageScheduled) {
2434 int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2435 int StageDiff = (StageScheduled - LoopValStage);
2436 LVNumStages -= StageDiff;
2437 // Make sure the loop value Phi has been processed already.
2438 if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
2439 NewReg = PhiOp2;
2440 unsigned ReuseStage = CurStageNum;
2441 if (Schedule.isLoopCarried(this, *PhiInst))
2442 ReuseStage -= LVNumStages;
2443 // Check if the Phi to reuse has been generated yet. If not, then
2444 // there is nothing to reuse.
2445 if (VRMap[ReuseStage - np].count(LoopVal)) {
2446 NewReg = VRMap[ReuseStage - np][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002447
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002448 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2449 &*BBI, Def, NewReg);
2450 // Update the map with the new Phi name.
2451 VRMap[CurStageNum - np][Def] = NewReg;
2452 PhiOp2 = NewReg;
2453 if (VRMap[LastStageNum - np - 1].count(LoopVal))
2454 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002455
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002456 if (IsLast && np == NumPhis - 1)
2457 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2458 continue;
2459 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002460 }
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002461 }
2462 if (InKernel && StageDiff > 0 &&
2463 VRMap[CurStageNum - StageDiff - np].count(LoopVal))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002464 PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2465 }
2466
2467 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2468 NewReg = MRI.createVirtualRegister(RC);
2469
2470 MachineInstrBuilder NewPhi =
2471 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2472 TII->get(TargetOpcode::PHI), NewReg);
2473 NewPhi.addReg(PhiOp1).addMBB(BB1);
2474 NewPhi.addReg(PhiOp2).addMBB(BB2);
2475 if (np == 0)
2476 InstrMap[NewPhi] = &*BBI;
2477
2478 // We define the Phis after creating the new pipelined code, so
2479 // we need to rename the Phi values in scheduled instructions.
2480
2481 unsigned PrevReg = 0;
2482 if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2483 PrevReg = VRMap[PrevStage - np][LoopVal];
2484 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2485 Def, NewReg, PrevReg);
2486 // If the Phi has been scheduled, use the new name for rewriting.
2487 if (VRMap[CurStageNum - np].count(Def)) {
2488 unsigned R = VRMap[CurStageNum - np][Def];
2489 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2490 R, NewReg);
2491 }
2492
2493 // Check if we need to rename any uses that occurs after the loop. The
2494 // register to replace depends on whether the Phi is scheduled in the
2495 // epilog.
2496 if (IsLast && np == NumPhis - 1)
2497 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2498
2499 // In the kernel, a dependent Phi uses the value from this Phi.
2500 if (InKernel)
2501 PhiOp2 = NewReg;
2502
2503 // Update the map with the new Phi name.
2504 VRMap[CurStageNum - np][Def] = NewReg;
2505 }
2506
2507 while (NumPhis++ < NumStages) {
2508 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2509 &*BBI, Def, NewReg, 0);
2510 }
2511
2512 // Check if we need to rename a Phi that has been eliminated due to
2513 // scheduling.
2514 if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2515 replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2516 }
2517}
2518
2519/// Generate Phis for the specified block in the generated pipelined code.
2520/// These are new Phis needed because the definition is scheduled after the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002521/// use in the pipelined sequence.
Brendon Cahoon254f8892016-07-29 16:44:44 +00002522void SwingSchedulerDAG::generatePhis(
2523 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2524 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2525 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2526 bool IsLast) {
2527 // Compute the stage number that contains the initial Phi value, and
2528 // the Phi from the previous stage.
2529 unsigned PrologStage = 0;
2530 unsigned PrevStage = 0;
2531 unsigned StageDiff = CurStageNum - LastStageNum;
2532 bool InKernel = (StageDiff == 0);
2533 if (InKernel) {
2534 PrologStage = LastStageNum - 1;
2535 PrevStage = CurStageNum;
2536 } else {
2537 PrologStage = LastStageNum - StageDiff;
2538 PrevStage = LastStageNum + StageDiff - 1;
2539 }
2540
2541 for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2542 BBE = BB->instr_end();
2543 BBI != BBE; ++BBI) {
2544 for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2545 MachineOperand &MO = BBI->getOperand(i);
2546 if (!MO.isReg() || !MO.isDef() ||
2547 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2548 continue;
2549
2550 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2551 assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2552 unsigned Def = MO.getReg();
2553 unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2554 // An instruction scheduled in stage 0 and is used after the loop
2555 // requires a phi in the epilog for the last definition from either
2556 // the kernel or prolog.
2557 if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2558 hasUseAfterLoop(Def, BB, MRI))
2559 NumPhis = 1;
2560 if (!InKernel && (unsigned)StageScheduled > PrologStage)
2561 continue;
2562
2563 unsigned PhiOp2 = VRMap[PrevStage][Def];
2564 if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2565 if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2566 PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2567 // The number of Phis can't exceed the number of prolog stages. The
2568 // prolog stage number is zero based.
2569 if (NumPhis > PrologStage + 1 - StageScheduled)
2570 NumPhis = PrologStage + 1 - StageScheduled;
2571 for (unsigned np = 0; np < NumPhis; ++np) {
2572 unsigned PhiOp1 = VRMap[PrologStage][Def];
2573 if (np <= PrologStage)
2574 PhiOp1 = VRMap[PrologStage - np][Def];
2575 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2576 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2577 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2578 if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2579 PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2580 }
2581 if (!InKernel)
2582 PhiOp2 = VRMap[PrevStage - np][Def];
2583
2584 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2585 unsigned NewReg = MRI.createVirtualRegister(RC);
2586
2587 MachineInstrBuilder NewPhi =
2588 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2589 TII->get(TargetOpcode::PHI), NewReg);
2590 NewPhi.addReg(PhiOp1).addMBB(BB1);
2591 NewPhi.addReg(PhiOp2).addMBB(BB2);
2592 if (np == 0)
2593 InstrMap[NewPhi] = &*BBI;
2594
2595 // Rewrite uses and update the map. The actions depend upon whether
2596 // we generating code for the kernel or epilog blocks.
2597 if (InKernel) {
2598 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2599 &*BBI, PhiOp1, NewReg);
2600 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2601 &*BBI, PhiOp2, NewReg);
2602
2603 PhiOp2 = NewReg;
2604 VRMap[PrevStage - np - 1][Def] = NewReg;
2605 } else {
2606 VRMap[CurStageNum - np][Def] = NewReg;
2607 if (np == NumPhis - 1)
2608 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2609 &*BBI, Def, NewReg);
2610 }
2611 if (IsLast && np == NumPhis - 1)
2612 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2613 }
2614 }
2615 }
2616}
2617
2618/// Remove instructions that generate values with no uses.
2619/// Typically, these are induction variable operations that generate values
2620/// used in the loop itself. A dead instruction has a definition with
2621/// no uses, or uses that occur in the original loop only.
2622void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2623 MBBVectorTy &EpilogBBs) {
2624 // For each epilog block, check that the value defined by each instruction
2625 // is used. If not, delete it.
2626 for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2627 MBE = EpilogBBs.rend();
2628 MBB != MBE; ++MBB)
2629 for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2630 ME = (*MBB)->instr_rend();
2631 MI != ME;) {
2632 // From DeadMachineInstructionElem. Don't delete inline assembly.
2633 if (MI->isInlineAsm()) {
2634 ++MI;
2635 continue;
2636 }
2637 bool SawStore = false;
2638 // Check if it's safe to remove the instruction due to side effects.
2639 // We can, and want to, remove Phis here.
2640 if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2641 ++MI;
2642 continue;
2643 }
2644 bool used = true;
2645 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2646 MOE = MI->operands_end();
2647 MOI != MOE; ++MOI) {
2648 if (!MOI->isReg() || !MOI->isDef())
2649 continue;
2650 unsigned reg = MOI->getReg();
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00002651 // Assume physical registers are used, unless they are marked dead.
2652 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
2653 used = !MOI->isDead();
2654 if (used)
2655 break;
2656 continue;
2657 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002658 unsigned realUses = 0;
2659 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2660 EI = MRI.use_end();
2661 UI != EI; ++UI) {
2662 // Check if there are any uses that occur only in the original
2663 // loop. If so, that's not a real use.
2664 if (UI->getParent()->getParent() != BB) {
2665 realUses++;
2666 used = true;
2667 break;
2668 }
2669 }
2670 if (realUses > 0)
2671 break;
2672 used = false;
2673 }
2674 if (!used) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002675 LIS.RemoveMachineInstrFromMaps(*MI);
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002676 MI++->eraseFromParent();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002677 continue;
2678 }
2679 ++MI;
2680 }
2681 // In the kernel block, check if we can remove a Phi that generates a value
2682 // used in an instruction removed in the epilog block.
2683 for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2684 BBE = KernelBB->getFirstNonPHI();
2685 BBI != BBE;) {
2686 MachineInstr *MI = &*BBI;
2687 ++BBI;
2688 unsigned reg = MI->getOperand(0).getReg();
2689 if (MRI.use_begin(reg) == MRI.use_end()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002690 LIS.RemoveMachineInstrFromMaps(*MI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002691 MI->eraseFromParent();
2692 }
2693 }
2694}
2695
2696/// For loop carried definitions, we split the lifetime of a virtual register
2697/// that has uses past the definition in the next iteration. A copy with a new
2698/// virtual register is inserted before the definition, which helps with
2699/// generating a better register assignment.
2700///
2701/// v1 = phi(a, v2) v1 = phi(a, v2)
2702/// v2 = phi(b, v3) v2 = phi(b, v3)
2703/// v3 = .. v4 = copy v1
2704/// .. = V1 v3 = ..
2705/// .. = v4
2706void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
2707 MBBVectorTy &EpilogBBs,
2708 SMSchedule &Schedule) {
2709 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bob Wilson90ecac02018-01-04 02:58:15 +00002710 for (auto &PHI : KernelBB->phis()) {
2711 unsigned Def = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002712 // Check for any Phi definition that used as an operand of another Phi
2713 // in the same block.
2714 for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
2715 E = MRI.use_instr_end();
2716 I != E; ++I) {
2717 if (I->isPHI() && I->getParent() == KernelBB) {
2718 // Get the loop carried definition.
Bob Wilson90ecac02018-01-04 02:58:15 +00002719 unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002720 if (!LCDef)
2721 continue;
2722 MachineInstr *MI = MRI.getVRegDef(LCDef);
2723 if (!MI || MI->getParent() != KernelBB || MI->isPHI())
2724 continue;
2725 // Search through the rest of the block looking for uses of the Phi
2726 // definition. If one occurs, then split the lifetime.
2727 unsigned SplitReg = 0;
2728 for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
2729 KernelBB->instr_end()))
2730 if (BBJ.readsRegister(Def)) {
2731 // We split the lifetime when we find the first use.
2732 if (SplitReg == 0) {
2733 SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
2734 BuildMI(*KernelBB, MI, MI->getDebugLoc(),
2735 TII->get(TargetOpcode::COPY), SplitReg)
2736 .addReg(Def);
2737 }
2738 BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
2739 }
2740 if (!SplitReg)
2741 continue;
2742 // Search through each of the epilog blocks for any uses to be renamed.
2743 for (auto &Epilog : EpilogBBs)
2744 for (auto &I : *Epilog)
2745 if (I.readsRegister(Def))
2746 I.substituteRegister(Def, SplitReg, 0, *TRI);
2747 break;
2748 }
2749 }
2750 }
2751}
2752
2753/// Remove the incoming block from the Phis in a basic block.
2754static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
2755 for (MachineInstr &MI : *BB) {
2756 if (!MI.isPHI())
2757 break;
2758 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
2759 if (MI.getOperand(i + 1).getMBB() == Incoming) {
2760 MI.RemoveOperand(i + 1);
2761 MI.RemoveOperand(i);
2762 break;
2763 }
2764 }
2765}
2766
2767/// Create branches from each prolog basic block to the appropriate epilog
2768/// block. These edges are needed if the loop ends before reaching the
2769/// kernel.
2770void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
2771 MachineBasicBlock *KernelBB,
2772 MBBVectorTy &EpilogBBs,
2773 SMSchedule &Schedule, ValueMapTy *VRMap) {
2774 assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
2775 MachineInstr *IndVar = Pass.LI.LoopInductionVar;
2776 MachineInstr *Cmp = Pass.LI.LoopCompare;
2777 MachineBasicBlock *LastPro = KernelBB;
2778 MachineBasicBlock *LastEpi = KernelBB;
2779
2780 // Start from the blocks connected to the kernel and work "out"
2781 // to the first prolog and the last epilog blocks.
2782 SmallVector<MachineInstr *, 4> PrevInsts;
2783 unsigned MaxIter = PrologBBs.size() - 1;
2784 unsigned LC = UINT_MAX;
2785 unsigned LCMin = UINT_MAX;
2786 for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
2787 // Add branches to the prolog that go to the corresponding
2788 // epilog, and the fall-thru prolog/kernel block.
2789 MachineBasicBlock *Prolog = PrologBBs[j];
2790 MachineBasicBlock *Epilog = EpilogBBs[i];
2791 // We've executed one iteration, so decrement the loop count and check for
2792 // the loop end.
2793 SmallVector<MachineOperand, 4> Cond;
2794 // Check if the LOOP0 has already been removed. If so, then there is no need
2795 // to reduce the trip count.
2796 if (LC != 0)
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002797 LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j,
Brendon Cahoon254f8892016-07-29 16:44:44 +00002798 MaxIter);
2799
2800 // Record the value of the first trip count, which is used to determine if
2801 // branches and blocks can be removed for constant trip counts.
2802 if (LCMin == UINT_MAX)
2803 LCMin = LC;
2804
2805 unsigned numAdded = 0;
2806 if (TargetRegisterInfo::isVirtualRegister(LC)) {
2807 Prolog->addSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002808 numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002809 } else if (j >= LCMin) {
2810 Prolog->addSuccessor(Epilog);
2811 Prolog->removeSuccessor(LastPro);
2812 LastEpi->removeSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002813 numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002814 removePhis(Epilog, LastEpi);
2815 // Remove the blocks that are no longer referenced.
2816 if (LastPro != LastEpi) {
2817 LastEpi->clear();
2818 LastEpi->eraseFromParent();
2819 }
2820 LastPro->clear();
2821 LastPro->eraseFromParent();
2822 } else {
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002823 numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002824 removePhis(Epilog, Prolog);
2825 }
2826 LastPro = Prolog;
2827 LastEpi = Epilog;
2828 for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
2829 E = Prolog->instr_rend();
2830 I != E && numAdded > 0; ++I, --numAdded)
2831 updateInstruction(&*I, false, j, 0, Schedule, VRMap);
2832 }
2833}
2834
2835/// Return true if we can compute the amount the instruction changes
2836/// during each iteration. Set Delta to the amount of the change.
2837bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2838 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00002839 const MachineOperand *BaseOp;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002840 int64_t Offset;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002841 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002842 return false;
2843
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002844 if (!BaseOp->isReg())
2845 return false;
2846
2847 unsigned BaseReg = BaseOp->getReg();
2848
Brendon Cahoon254f8892016-07-29 16:44:44 +00002849 MachineRegisterInfo &MRI = MF.getRegInfo();
2850 // Check if there is a Phi. If so, get the definition in the loop.
2851 MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2852 if (BaseDef && BaseDef->isPHI()) {
2853 BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2854 BaseDef = MRI.getVRegDef(BaseReg);
2855 }
2856 if (!BaseDef)
2857 return false;
2858
2859 int D = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002860 if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002861 return false;
2862
2863 Delta = D;
2864 return true;
2865}
2866
2867/// Update the memory operand with a new offset when the pipeliner
Justin Lebarcf56e922016-08-12 23:58:19 +00002868/// generates a new copy of the instruction that refers to a
Brendon Cahoon254f8892016-07-29 16:44:44 +00002869/// different memory location.
2870void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
2871 MachineInstr &OldMI, unsigned Num) {
2872 if (Num == 0)
2873 return;
2874 // If the instruction has memory operands, then adjust the offset
2875 // when the instruction appears in different stages.
Chandler Carruthc73c0302018-08-16 21:30:05 +00002876 if (NewMI.memoperands_empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00002877 return;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002878 SmallVector<MachineMemOperand *, 2> NewMMOs;
Justin Lebar0a33a7a2016-08-23 17:18:07 +00002879 for (MachineMemOperand *MMO : NewMI.memoperands()) {
Philip Reames00056ed2019-02-01 22:58:52 +00002880 // TODO: Figure out whether isAtomic is really necessary (see D57601).
2881 if (MMO->isVolatile() || MMO->isAtomic() ||
2882 (MMO->isInvariant() && MMO->isDereferenceable()) ||
Justin Lebaradbf09e2016-09-11 01:38:58 +00002883 (!MMO->getValue())) {
Chandler Carruthc73c0302018-08-16 21:30:05 +00002884 NewMMOs.push_back(MMO);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002885 continue;
2886 }
2887 unsigned Delta;
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002888 if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002889 int64_t AdjOffset = Delta * Num;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002890 NewMMOs.push_back(
2891 MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002892 } else {
Krzysztof Parzyszekcc3f6302018-08-20 20:37:57 +00002893 NewMMOs.push_back(
2894 MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002895 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002896 }
Chandler Carruthc73c0302018-08-16 21:30:05 +00002897 NewMI.setMemRefs(MF, NewMMOs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002898}
2899
2900/// Clone the instruction for the new pipelined loop and update the
2901/// memory operands, if needed.
2902MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
2903 unsigned CurStageNum,
2904 unsigned InstStageNum) {
2905 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2906 // Check for tied operands in inline asm instructions. This should be handled
2907 // elsewhere, but I'm not sure of the best solution.
2908 if (OldMI->isInlineAsm())
2909 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
2910 const auto &MO = OldMI->getOperand(i);
2911 if (MO.isReg() && MO.isUse())
2912 break;
2913 unsigned UseIdx;
2914 if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
2915 NewMI->tieOperands(i, UseIdx);
2916 }
2917 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2918 return NewMI;
2919}
2920
2921/// Clone the instruction for the new pipelined loop. If needed, this
2922/// function updates the instruction using the values saved in the
2923/// InstrChanges structure.
2924MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
2925 unsigned CurStageNum,
2926 unsigned InstStageNum,
2927 SMSchedule &Schedule) {
2928 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2929 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2930 InstrChanges.find(getSUnit(OldMI));
2931 if (It != InstrChanges.end()) {
2932 std::pair<unsigned, int64_t> RegAndOffset = It->second;
2933 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002934 if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002935 return nullptr;
2936 int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
2937 MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
2938 if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
2939 NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
2940 NewMI->getOperand(OffsetPos).setImm(NewOffset);
2941 }
2942 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2943 return NewMI;
2944}
2945
2946/// Update the machine instruction with new virtual registers. This
2947/// function may change the defintions and/or uses.
2948void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
2949 unsigned CurStageNum,
2950 unsigned InstrStageNum,
2951 SMSchedule &Schedule,
2952 ValueMapTy *VRMap) {
2953 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
2954 MachineOperand &MO = NewMI->getOperand(i);
2955 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2956 continue;
2957 unsigned reg = MO.getReg();
2958 if (MO.isDef()) {
2959 // Create a new virtual register for the definition.
2960 const TargetRegisterClass *RC = MRI.getRegClass(reg);
2961 unsigned NewReg = MRI.createVirtualRegister(RC);
2962 MO.setReg(NewReg);
2963 VRMap[CurStageNum][reg] = NewReg;
2964 if (LastDef)
2965 replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
2966 } else if (MO.isUse()) {
2967 MachineInstr *Def = MRI.getVRegDef(reg);
2968 // Compute the stage that contains the last definition for instruction.
2969 int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
2970 unsigned StageNum = CurStageNum;
2971 if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
2972 // Compute the difference in stages between the defintion and the use.
2973 unsigned StageDiff = (InstrStageNum - DefStageNum);
2974 // Make an adjustment to get the last definition.
2975 StageNum -= StageDiff;
2976 }
2977 if (VRMap[StageNum].count(reg))
2978 MO.setReg(VRMap[StageNum][reg]);
2979 }
2980 }
2981}
2982
2983/// Return the instruction in the loop that defines the register.
2984/// If the definition is a Phi, then follow the Phi operand to
2985/// the instruction in the loop.
2986MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
2987 SmallPtrSet<MachineInstr *, 8> Visited;
2988 MachineInstr *Def = MRI.getVRegDef(Reg);
2989 while (Def->isPHI()) {
2990 if (!Visited.insert(Def).second)
2991 break;
2992 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2993 if (Def->getOperand(i + 1).getMBB() == BB) {
2994 Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2995 break;
2996 }
2997 }
2998 return Def;
2999}
3000
3001/// Return the new name for the value from the previous stage.
3002unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
3003 unsigned LoopVal, unsigned LoopStage,
3004 ValueMapTy *VRMap,
3005 MachineBasicBlock *BB) {
3006 unsigned PrevVal = 0;
3007 if (StageNum > PhiStage) {
3008 MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
3009 if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
3010 // The name is defined in the previous stage.
3011 PrevVal = VRMap[StageNum - 1][LoopVal];
3012 else if (VRMap[StageNum].count(LoopVal))
3013 // The previous name is defined in the current stage when the instruction
3014 // order is swapped.
3015 PrevVal = VRMap[StageNum][LoopVal];
Krzysztof Parzyszekdf24da22016-12-22 18:49:55 +00003016 else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003017 // The loop value hasn't yet been scheduled.
3018 PrevVal = LoopVal;
3019 else if (StageNum == PhiStage + 1)
3020 // The loop value is another phi, which has not been scheduled.
3021 PrevVal = getInitPhiReg(*LoopInst, BB);
3022 else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
3023 // The loop value is another phi, which has been scheduled.
3024 PrevVal =
3025 getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
3026 LoopStage, VRMap, BB);
3027 }
3028 return PrevVal;
3029}
3030
3031/// Rewrite the Phi values in the specified block to use the mappings
3032/// from the initial operand. Once the Phi is scheduled, we switch
3033/// to using the loop value instead of the Phi value, so those names
3034/// do not need to be rewritten.
3035void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
3036 unsigned StageNum,
3037 SMSchedule &Schedule,
3038 ValueMapTy *VRMap,
3039 InstrMapTy &InstrMap) {
Bob Wilson90ecac02018-01-04 02:58:15 +00003040 for (auto &PHI : BB->phis()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003041 unsigned InitVal = 0;
3042 unsigned LoopVal = 0;
Bob Wilson90ecac02018-01-04 02:58:15 +00003043 getPhiRegs(PHI, BB, InitVal, LoopVal);
3044 unsigned PhiDef = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003045
3046 unsigned PhiStage =
3047 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
3048 unsigned LoopStage =
3049 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
3050 unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3051 if (NumPhis > StageNum)
3052 NumPhis = StageNum;
3053 for (unsigned np = 0; np <= NumPhis; ++np) {
3054 unsigned NewVal =
3055 getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3056 if (!NewVal)
3057 NewVal = InitVal;
Bob Wilson90ecac02018-01-04 02:58:15 +00003058 rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
Brendon Cahoon254f8892016-07-29 16:44:44 +00003059 PhiDef, NewVal);
3060 }
3061 }
3062}
3063
3064/// Rewrite a previously scheduled instruction to use the register value
3065/// from the new instruction. Make sure the instruction occurs in the
3066/// basic block, and we don't change the uses in the new instruction.
3067void SwingSchedulerDAG::rewriteScheduledInstr(
3068 MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
3069 unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
3070 unsigned NewReg, unsigned PrevReg) {
3071 bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3072 int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3073 // Rewrite uses that have been scheduled already to use the new
3074 // Phi register.
3075 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
3076 EI = MRI.use_end();
3077 UI != EI;) {
3078 MachineOperand &UseOp = *UI;
3079 MachineInstr *UseMI = UseOp.getParent();
3080 ++UI;
3081 if (UseMI->getParent() != BB)
3082 continue;
3083 if (UseMI->isPHI()) {
3084 if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
3085 continue;
3086 if (getLoopPhiReg(*UseMI, BB) != OldReg)
3087 continue;
3088 }
3089 InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3090 assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
3091 SUnit *OrigMISU = getSUnit(OrigInstr->second);
3092 int StageSched = Schedule.stageScheduled(OrigMISU);
3093 int CycleSched = Schedule.cycleScheduled(OrigMISU);
3094 unsigned ReplaceReg = 0;
3095 // This is the stage for the scheduled instruction.
3096 if (StagePhi == StageSched && Phi->isPHI()) {
3097 int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3098 if (PrevReg && InProlog)
3099 ReplaceReg = PrevReg;
3100 else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
3101 (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3102 ReplaceReg = PrevReg;
3103 else
3104 ReplaceReg = NewReg;
3105 }
3106 // The scheduled instruction occurs before the scheduled Phi, and the
3107 // Phi is not loop carried.
3108 if (!InProlog && StagePhi + 1 == StageSched &&
3109 !Schedule.isLoopCarried(this, *Phi))
3110 ReplaceReg = NewReg;
3111 if (StagePhi > StageSched && Phi->isPHI())
3112 ReplaceReg = NewReg;
3113 if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
3114 ReplaceReg = NewReg;
3115 if (ReplaceReg) {
3116 MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
3117 UseOp.setReg(ReplaceReg);
3118 }
3119 }
3120}
3121
3122/// Check if we can change the instruction to use an offset value from the
3123/// previous iteration. If so, return true and set the base and offset values
3124/// so that we can rewrite the load, if necessary.
3125/// v1 = Phi(v0, v3)
3126/// v2 = load v1, 0
3127/// v3 = post_store v1, 4, x
3128/// This function enables the load to be rewritten as v2 = load v3, 4.
3129bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3130 unsigned &BasePos,
3131 unsigned &OffsetPos,
3132 unsigned &NewBase,
3133 int64_t &Offset) {
3134 // Get the load instruction.
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003135 if (TII->isPostIncrement(*MI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003136 return false;
3137 unsigned BasePosLd, OffsetPosLd;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003138 if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003139 return false;
3140 unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
3141
3142 // Look for the Phi instruction.
Justin Bognerfdf9bf42017-10-10 23:50:49 +00003143 MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003144 MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3145 if (!Phi || !Phi->isPHI())
3146 return false;
3147 // Get the register defined in the loop block.
3148 unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3149 if (!PrevReg)
3150 return false;
3151
3152 // Check for the post-increment load/store instruction.
3153 MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3154 if (!PrevDef || PrevDef == MI)
3155 return false;
3156
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003157 if (!TII->isPostIncrement(*PrevDef))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003158 return false;
3159
3160 unsigned BasePos1 = 0, OffsetPos1 = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003161 if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003162 return false;
3163
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00003164 // Make sure that the instructions do not access the same memory location in
3165 // the next iteration.
Brendon Cahoon254f8892016-07-29 16:44:44 +00003166 int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3167 int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00003168 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3169 NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
3170 bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
3171 MF.DeleteMachineInstr(NewMI);
3172 if (!Disjoint)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003173 return false;
3174
3175 // Set the return value once we determine that we return true.
3176 BasePos = BasePosLd;
3177 OffsetPos = OffsetPosLd;
3178 NewBase = PrevReg;
3179 Offset = StoreOffset;
3180 return true;
3181}
3182
3183/// Apply changes to the instruction if needed. The changes are need
3184/// to improve the scheduling and depend up on the final schedule.
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003185void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
3186 SMSchedule &Schedule) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003187 SUnit *SU = getSUnit(MI);
3188 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3189 InstrChanges.find(SU);
3190 if (It != InstrChanges.end()) {
3191 std::pair<unsigned, int64_t> RegAndOffset = It->second;
3192 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003193 if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003194 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003195 unsigned BaseReg = MI->getOperand(BasePos).getReg();
3196 MachineInstr *LoopDef = findDefInLoop(BaseReg);
3197 int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3198 int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3199 int BaseStageNum = Schedule.stageScheduled(SU);
3200 int BaseCycleNum = Schedule.cycleScheduled(SU);
3201 if (BaseStageNum < DefStageNum) {
3202 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3203 int OffsetDiff = DefStageNum - BaseStageNum;
3204 if (DefCycleNum < BaseCycleNum) {
3205 NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3206 if (OffsetDiff > 0)
3207 --OffsetDiff;
3208 }
3209 int64_t NewOffset =
3210 MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3211 NewMI->getOperand(OffsetPos).setImm(NewOffset);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003212 SU->setInstr(NewMI);
3213 MISUnitMap[NewMI] = SU;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003214 NewMIs.insert(NewMI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003215 }
3216 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003217}
3218
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003219/// Return true for an order or output dependence that is loop carried
3220/// potentially. A dependence is loop carried if the destination defines a valu
3221/// that may be used or defined by the source in a subsequent iteration.
3222bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
3223 bool isSucc) {
3224 if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
3225 Dep.isArtificial())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003226 return false;
3227
3228 if (!SwpPruneLoopCarried)
3229 return true;
3230
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003231 if (Dep.getKind() == SDep::Output)
3232 return true;
3233
Brendon Cahoon254f8892016-07-29 16:44:44 +00003234 MachineInstr *SI = Source->getInstr();
3235 MachineInstr *DI = Dep.getSUnit()->getInstr();
3236 if (!isSucc)
3237 std::swap(SI, DI);
3238 assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3239
3240 // Assume ordered loads and stores may have a loop carried dependence.
3241 if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +00003242 SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00003243 SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3244 return true;
3245
3246 // Only chain dependences between a load and store can be loop carried.
3247 if (!DI->mayStore() || !SI->mayLoad())
3248 return false;
3249
3250 unsigned DeltaS, DeltaD;
3251 if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3252 return true;
3253
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00003254 const MachineOperand *BaseOpS, *BaseOpD;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003255 int64_t OffsetS, OffsetD;
3256 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003257 if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
3258 !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003259 return true;
3260
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003261 if (!BaseOpS->isIdenticalTo(*BaseOpD))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003262 return true;
3263
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00003264 // Check that the base register is incremented by a constant value for each
3265 // iteration.
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003266 MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00003267 if (!Def || !Def->isPHI())
3268 return true;
3269 unsigned InitVal = 0;
3270 unsigned LoopVal = 0;
3271 getPhiRegs(*Def, BB, InitVal, LoopVal);
3272 MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
3273 int D = 0;
3274 if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
3275 return true;
3276
Brendon Cahoon254f8892016-07-29 16:44:44 +00003277 uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3278 uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3279
3280 // This is the main test, which checks the offset values and the loop
3281 // increment value to determine if the accesses may be loop carried.
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00003282 if (AccessSizeS == MemoryLocation::UnknownSize ||
3283 AccessSizeD == MemoryLocation::UnknownSize)
3284 return true;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003285
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00003286 if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
3287 return true;
3288
3289 return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003290}
3291
Krzysztof Parzyszek88391242016-12-22 19:21:20 +00003292void SwingSchedulerDAG::postprocessDAG() {
3293 for (auto &M : Mutations)
3294 M->apply(this);
3295}
3296
Brendon Cahoon254f8892016-07-29 16:44:44 +00003297/// Try to schedule the node at the specified StartCycle and continue
3298/// until the node is schedule or the EndCycle is reached. This function
3299/// returns true if the node is scheduled. This routine may search either
3300/// forward or backward for a place to insert the instruction based upon
3301/// the relative values of StartCycle and EndCycle.
3302bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3303 bool forward = true;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00003304 LLVM_DEBUG({
3305 dbgs() << "Trying to insert node between " << StartCycle << " and "
3306 << EndCycle << " II: " << II << "\n";
3307 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00003308 if (StartCycle > EndCycle)
3309 forward = false;
3310
3311 // The terminating condition depends on the direction.
3312 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3313 for (int curCycle = StartCycle; curCycle != termCycle;
3314 forward ? ++curCycle : --curCycle) {
3315
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003316 // Add the already scheduled instructions at the specified cycle to the
3317 // DFA.
3318 ProcItinResources.clearResources();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003319 for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3320 checkCycle <= LastCycle; checkCycle += II) {
3321 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3322
3323 for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3324 E = cycleInstrs.end();
3325 I != E; ++I) {
3326 if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3327 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003328 assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00003329 "These instructions have already been scheduled.");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003330 ProcItinResources.reserveResources(*(*I)->getInstr());
Brendon Cahoon254f8892016-07-29 16:44:44 +00003331 }
3332 }
3333 if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003334 ProcItinResources.canReserveResources(*SU->getInstr())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003335 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003336 dbgs() << "\tinsert at cycle " << curCycle << " ";
3337 SU->getInstr()->dump();
3338 });
3339
3340 ScheduledInstrs[curCycle].push_back(SU);
3341 InstrToCycle.insert(std::make_pair(SU, curCycle));
3342 if (curCycle > LastCycle)
3343 LastCycle = curCycle;
3344 if (curCycle < FirstCycle)
3345 FirstCycle = curCycle;
3346 return true;
3347 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003348 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003349 dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3350 SU->getInstr()->dump();
3351 });
3352 }
3353 return false;
3354}
3355
3356// Return the cycle of the earliest scheduled instruction in the chain.
3357int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3358 SmallPtrSet<SUnit *, 8> Visited;
3359 SmallVector<SDep, 8> Worklist;
3360 Worklist.push_back(Dep);
3361 int EarlyCycle = INT_MAX;
3362 while (!Worklist.empty()) {
3363 const SDep &Cur = Worklist.pop_back_val();
3364 SUnit *PrevSU = Cur.getSUnit();
3365 if (Visited.count(PrevSU))
3366 continue;
3367 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3368 if (it == InstrToCycle.end())
3369 continue;
3370 EarlyCycle = std::min(EarlyCycle, it->second);
3371 for (const auto &PI : PrevSU->Preds)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003372 if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003373 Worklist.push_back(PI);
3374 Visited.insert(PrevSU);
3375 }
3376 return EarlyCycle;
3377}
3378
3379// Return the cycle of the latest scheduled instruction in the chain.
3380int SMSchedule::latestCycleInChain(const SDep &Dep) {
3381 SmallPtrSet<SUnit *, 8> Visited;
3382 SmallVector<SDep, 8> Worklist;
3383 Worklist.push_back(Dep);
3384 int LateCycle = INT_MIN;
3385 while (!Worklist.empty()) {
3386 const SDep &Cur = Worklist.pop_back_val();
3387 SUnit *SuccSU = Cur.getSUnit();
3388 if (Visited.count(SuccSU))
3389 continue;
3390 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3391 if (it == InstrToCycle.end())
3392 continue;
3393 LateCycle = std::max(LateCycle, it->second);
3394 for (const auto &SI : SuccSU->Succs)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003395 if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003396 Worklist.push_back(SI);
3397 Visited.insert(SuccSU);
3398 }
3399 return LateCycle;
3400}
3401
3402/// If an instruction has a use that spans multiple iterations, then
3403/// return true. These instructions are characterized by having a back-ege
3404/// to a Phi, which contains a reference to another Phi.
3405static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3406 for (auto &P : SU->Preds)
3407 if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3408 for (auto &S : P.getSUnit()->Succs)
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00003409 if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003410 return P.getSUnit();
3411 return nullptr;
3412}
3413
3414/// Compute the scheduling start slot for the instruction. The start slot
3415/// depends on any predecessor or successor nodes scheduled already.
3416void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3417 int *MinEnd, int *MaxStart, int II,
3418 SwingSchedulerDAG *DAG) {
3419 // Iterate over each instruction that has been scheduled already. The start
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003420 // slot computation depends on whether the previously scheduled instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00003421 // is a predecessor or successor of the specified instruction.
3422 for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3423
3424 // Iterate over each instruction in the current cycle.
3425 for (SUnit *I : getInstructions(cycle)) {
3426 // Because we're processing a DAG for the dependences, we recognize
3427 // the back-edge in recurrences by anti dependences.
3428 for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3429 const SDep &Dep = SU->Preds[i];
3430 if (Dep.getSUnit() == I) {
3431 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003432 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003433 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3434 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003435 if (DAG->isLoopCarriedDep(SU, Dep, false)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003436 int End = earliestCycleInChain(Dep) + (II - 1);
3437 *MinEnd = std::min(*MinEnd, End);
3438 }
3439 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003440 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003441 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3442 *MinLateStart = std::min(*MinLateStart, LateStart);
3443 }
3444 }
3445 // For instruction that requires multiple iterations, make sure that
3446 // the dependent instruction is not scheduled past the definition.
3447 SUnit *BE = multipleIterations(I, DAG);
3448 if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3449 !SU->isPred(I))
3450 *MinLateStart = std::min(*MinLateStart, cycle);
3451 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003452 for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003453 if (SU->Succs[i].getSUnit() == I) {
3454 const SDep &Dep = SU->Succs[i];
3455 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003456 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003457 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3458 *MinLateStart = std::min(*MinLateStart, LateStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003459 if (DAG->isLoopCarriedDep(SU, Dep)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003460 int Start = latestCycleInChain(Dep) + 1 - II;
3461 *MaxStart = std::max(*MaxStart, Start);
3462 }
3463 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003464 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003465 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3466 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3467 }
3468 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003469 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003470 }
3471 }
3472}
3473
3474/// Order the instructions within a cycle so that the definitions occur
3475/// before the uses. Returns true if the instruction is added to the start
3476/// of the list, or false if added to the end.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003477void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
Brendon Cahoon254f8892016-07-29 16:44:44 +00003478 std::deque<SUnit *> &Insts) {
3479 MachineInstr *MI = SU->getInstr();
3480 bool OrderBeforeUse = false;
3481 bool OrderAfterDef = false;
3482 bool OrderBeforeDef = false;
3483 unsigned MoveDef = 0;
3484 unsigned MoveUse = 0;
3485 int StageInst1 = stageScheduled(SU);
3486
3487 unsigned Pos = 0;
3488 for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3489 ++I, ++Pos) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003490 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3491 MachineOperand &MO = MI->getOperand(i);
3492 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3493 continue;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003494
Brendon Cahoon254f8892016-07-29 16:44:44 +00003495 unsigned Reg = MO.getReg();
3496 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003497 if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003498 if (MI->getOperand(BasePos).getReg() == Reg)
3499 if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3500 Reg = NewReg;
3501 bool Reads, Writes;
3502 std::tie(Reads, Writes) =
3503 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3504 if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3505 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003506 if (MoveUse == 0)
3507 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003508 } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3509 // Add the instruction after the scheduled instruction.
3510 OrderAfterDef = true;
3511 MoveDef = Pos;
3512 } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3513 if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3514 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003515 if (MoveUse == 0)
3516 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003517 } else {
3518 OrderAfterDef = true;
3519 MoveDef = Pos;
3520 }
3521 } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3522 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003523 if (MoveUse == 0)
3524 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003525 if (MoveUse != 0) {
3526 OrderAfterDef = true;
3527 MoveDef = Pos - 1;
3528 }
3529 } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3530 // Add the instruction before the scheduled instruction.
3531 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003532 if (MoveUse == 0)
3533 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003534 } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3535 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003536 if (MoveUse == 0) {
3537 OrderBeforeDef = true;
3538 MoveUse = Pos;
3539 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003540 }
3541 }
3542 // Check for order dependences between instructions. Make sure the source
3543 // is ordered before the destination.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003544 for (auto &S : SU->Succs) {
3545 if (S.getSUnit() != *I)
3546 continue;
3547 if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3548 OrderBeforeUse = true;
3549 if (Pos < MoveUse)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003550 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003551 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003552 }
3553 for (auto &P : SU->Preds) {
3554 if (P.getSUnit() != *I)
3555 continue;
3556 if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3557 OrderAfterDef = true;
3558 MoveDef = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003559 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003560 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003561 }
3562
3563 // A circular dependence.
3564 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3565 OrderBeforeUse = false;
3566
3567 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3568 // to a loop-carried dependence.
3569 if (OrderBeforeDef)
3570 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3571
3572 // The uncommon case when the instruction order needs to be updated because
3573 // there is both a use and def.
3574 if (OrderBeforeUse && OrderAfterDef) {
3575 SUnit *UseSU = Insts.at(MoveUse);
3576 SUnit *DefSU = Insts.at(MoveDef);
3577 if (MoveUse > MoveDef) {
3578 Insts.erase(Insts.begin() + MoveUse);
3579 Insts.erase(Insts.begin() + MoveDef);
3580 } else {
3581 Insts.erase(Insts.begin() + MoveDef);
3582 Insts.erase(Insts.begin() + MoveUse);
3583 }
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003584 orderDependence(SSD, UseSU, Insts);
3585 orderDependence(SSD, SU, Insts);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003586 orderDependence(SSD, DefSU, Insts);
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003587 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003588 }
3589 // Put the new instruction first if there is a use in the list. Otherwise,
3590 // put it at the end of the list.
3591 if (OrderBeforeUse)
3592 Insts.push_front(SU);
3593 else
3594 Insts.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003595}
3596
3597/// Return true if the scheduled Phi has a loop carried operand.
3598bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3599 if (!Phi.isPHI())
3600 return false;
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003601 assert(Phi.isPHI() && "Expecting a Phi.");
Brendon Cahoon254f8892016-07-29 16:44:44 +00003602 SUnit *DefSU = SSD->getSUnit(&Phi);
3603 unsigned DefCycle = cycleScheduled(DefSU);
3604 int DefStage = stageScheduled(DefSU);
3605
3606 unsigned InitVal = 0;
3607 unsigned LoopVal = 0;
3608 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3609 SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3610 if (!UseSU)
3611 return true;
3612 if (UseSU->getInstr()->isPHI())
3613 return true;
3614 unsigned LoopCycle = cycleScheduled(UseSU);
3615 int LoopStage = stageScheduled(UseSU);
Simon Pilgrim3d8482a2016-11-14 10:40:23 +00003616 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003617}
3618
3619/// Return true if the instruction is a definition that is loop carried
3620/// and defines the use on the next iteration.
3621/// v1 = phi(v2, v3)
3622/// (Def) v3 = op v1
3623/// (MO) = v1
3624/// If MO appears before Def, then then v1 and v3 may get assigned to the same
3625/// register.
3626bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3627 MachineInstr *Def, MachineOperand &MO) {
3628 if (!MO.isReg())
3629 return false;
3630 if (Def->isPHI())
3631 return false;
3632 MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3633 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3634 return false;
3635 if (!isLoopCarried(SSD, *Phi))
3636 return false;
3637 unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3638 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3639 MachineOperand &DMO = Def->getOperand(i);
3640 if (!DMO.isReg() || !DMO.isDef())
3641 continue;
3642 if (DMO.getReg() == LoopReg)
3643 return true;
3644 }
3645 return false;
3646}
3647
3648// Check if the generated schedule is valid. This function checks if
3649// an instruction that uses a physical register is scheduled in a
3650// different stage than the definition. The pipeliner does not handle
3651// physical register values that may cross a basic block boundary.
3652bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003653 for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3654 SUnit &SU = SSD->SUnits[i];
3655 if (!SU.hasPhysRegDefs)
3656 continue;
3657 int StageDef = stageScheduled(&SU);
3658 assert(StageDef != -1 && "Instruction should have been scheduled.");
3659 for (auto &SI : SU.Succs)
3660 if (SI.isAssignedRegDep())
Simon Pilgrimb39236b2016-07-29 18:57:32 +00003661 if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003662 if (stageScheduled(SI.getSUnit()) != StageDef)
3663 return false;
3664 }
3665 return true;
3666}
3667
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003668/// A property of the node order in swing-modulo-scheduling is
3669/// that for nodes outside circuits the following holds:
3670/// none of them is scheduled after both a successor and a
3671/// predecessor.
3672/// The method below checks whether the property is met.
3673/// If not, debug information is printed and statistics information updated.
3674/// Note that we do not use an assert statement.
3675/// The reason is that although an invalid node oder may prevent
3676/// the pipeliner from finding a pipelined schedule for arbitrary II,
3677/// it does not lead to the generation of incorrect code.
3678void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3679
3680 // a sorted vector that maps each SUnit to its index in the NodeOrder
3681 typedef std::pair<SUnit *, unsigned> UnitIndex;
3682 std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3683
3684 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3685 Indices.push_back(std::make_pair(NodeOrder[i], i));
3686
3687 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3688 return std::get<0>(i1) < std::get<0>(i2);
3689 };
3690
3691 // sort, so that we can perform a binary search
Fangrui Song0cac7262018-09-27 02:13:45 +00003692 llvm::sort(Indices, CompareKey);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003693
3694 bool Valid = true;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003695 (void)Valid;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003696 // for each SUnit in the NodeOrder, check whether
3697 // it appears after both a successor and a predecessor
3698 // of the SUnit. If this is the case, and the SUnit
3699 // is not part of circuit, then the NodeOrder is not
3700 // valid.
3701 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3702 SUnit *SU = NodeOrder[i];
3703 unsigned Index = i;
3704
3705 bool PredBefore = false;
3706 bool SuccBefore = false;
3707
3708 SUnit *Succ;
3709 SUnit *Pred;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003710 (void)Succ;
3711 (void)Pred;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003712
3713 for (SDep &PredEdge : SU->Preds) {
3714 SUnit *PredSU = PredEdge.getSUnit();
3715 unsigned PredIndex =
3716 std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
3717 std::make_pair(PredSU, 0), CompareKey));
3718 if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3719 PredBefore = true;
3720 Pred = PredSU;
3721 break;
3722 }
3723 }
3724
3725 for (SDep &SuccEdge : SU->Succs) {
3726 SUnit *SuccSU = SuccEdge.getSUnit();
3727 unsigned SuccIndex =
3728 std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
3729 std::make_pair(SuccSU, 0), CompareKey));
3730 if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3731 SuccBefore = true;
3732 Succ = SuccSU;
3733 break;
3734 }
3735 }
3736
3737 if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3738 // instructions in circuits are allowed to be scheduled
3739 // after both a successor and predecessor.
3740 bool InCircuit = std::any_of(
3741 Circuits.begin(), Circuits.end(),
3742 [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
3743 if (InCircuit)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003744 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003745 else {
3746 Valid = false;
3747 NumNodeOrderIssues++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003748 LLVM_DEBUG(dbgs() << "Predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003749 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003750 LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3751 << " are scheduled before node " << SU->NodeNum
3752 << "\n";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003753 }
3754 }
3755
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003756 LLVM_DEBUG({
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003757 if (!Valid)
3758 dbgs() << "Invalid node order found!\n";
3759 });
3760}
3761
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003762/// Attempt to fix the degenerate cases when the instruction serialization
3763/// causes the register lifetimes to overlap. For example,
3764/// p' = store_pi(p, b)
3765/// = load p, offset
3766/// In this case p and p' overlap, which means that two registers are needed.
3767/// Instead, this function changes the load to use p' and updates the offset.
3768void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3769 unsigned OverlapReg = 0;
3770 unsigned NewBaseReg = 0;
3771 for (SUnit *SU : Instrs) {
3772 MachineInstr *MI = SU->getInstr();
3773 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3774 const MachineOperand &MO = MI->getOperand(i);
3775 // Look for an instruction that uses p. The instruction occurs in the
3776 // same cycle but occurs later in the serialized order.
3777 if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3778 // Check that the instruction appears in the InstrChanges structure,
3779 // which contains instructions that can have the offset updated.
3780 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3781 InstrChanges.find(SU);
3782 if (It != InstrChanges.end()) {
3783 unsigned BasePos, OffsetPos;
3784 // Update the base register and adjust the offset.
3785 if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
Krzysztof Parzyszek12bdcab2017-10-11 15:59:51 +00003786 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3787 NewMI->getOperand(BasePos).setReg(NewBaseReg);
3788 int64_t NewOffset =
3789 MI->getOperand(OffsetPos).getImm() - It->second.second;
3790 NewMI->getOperand(OffsetPos).setImm(NewOffset);
3791 SU->setInstr(NewMI);
3792 MISUnitMap[NewMI] = SU;
3793 NewMIs.insert(NewMI);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003794 }
3795 }
3796 OverlapReg = 0;
3797 NewBaseReg = 0;
3798 break;
3799 }
3800 // Look for an instruction of the form p' = op(p), which uses and defines
3801 // two virtual registers that get allocated to the same physical register.
3802 unsigned TiedUseIdx = 0;
3803 if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3804 // OverlapReg is p in the example above.
3805 OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3806 // NewBaseReg is p' in the example above.
3807 NewBaseReg = MI->getOperand(i).getReg();
3808 break;
3809 }
3810 }
3811 }
3812}
3813
Brendon Cahoon254f8892016-07-29 16:44:44 +00003814/// After the schedule has been formed, call this function to combine
3815/// the instructions from the different stages/cycles. That is, this
3816/// function creates a schedule that represents a single iteration.
3817void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3818 // Move all instructions to the first stage from later stages.
3819 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3820 for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3821 ++stage) {
3822 std::deque<SUnit *> &cycleInstrs =
3823 ScheduledInstrs[cycle + (stage * InitiationInterval)];
3824 for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
3825 E = cycleInstrs.rend();
3826 I != E; ++I)
3827 ScheduledInstrs[cycle].push_front(*I);
3828 }
3829 }
3830 // Iterate over the definitions in each instruction, and compute the
3831 // stage difference for each use. Keep the maximum value.
3832 for (auto &I : InstrToCycle) {
3833 int DefStage = stageScheduled(I.first);
3834 MachineInstr *MI = I.first->getInstr();
3835 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3836 MachineOperand &Op = MI->getOperand(i);
3837 if (!Op.isReg() || !Op.isDef())
3838 continue;
3839
3840 unsigned Reg = Op.getReg();
3841 unsigned MaxDiff = 0;
3842 bool PhiIsSwapped = false;
3843 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
3844 EI = MRI.use_end();
3845 UI != EI; ++UI) {
3846 MachineOperand &UseOp = *UI;
3847 MachineInstr *UseMI = UseOp.getParent();
3848 SUnit *SUnitUse = SSD->getSUnit(UseMI);
3849 int UseStage = stageScheduled(SUnitUse);
3850 unsigned Diff = 0;
3851 if (UseStage != -1 && UseStage >= DefStage)
3852 Diff = UseStage - DefStage;
3853 if (MI->isPHI()) {
3854 if (isLoopCarried(SSD, *MI))
3855 ++Diff;
3856 else
3857 PhiIsSwapped = true;
3858 }
3859 MaxDiff = std::max(Diff, MaxDiff);
3860 }
3861 RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
3862 }
3863 }
3864
3865 // Erase all the elements in the later stages. Only one iteration should
3866 // remain in the scheduled list, and it contains all the instructions.
3867 for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3868 ScheduledInstrs.erase(cycle);
3869
3870 // Change the registers in instruction as specified in the InstrChanges
3871 // map. We need to use the new registers to create the correct order.
3872 for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
3873 SUnit *SU = &SSD->SUnits[i];
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003874 SSD->applyInstrChange(SU->getInstr(), *this);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003875 }
3876
3877 // Reorder the instructions in each cycle to fix and improve the
3878 // generated code.
3879 for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3880 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003881 std::deque<SUnit *> newOrderPhi;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003882 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3883 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003884 if (SU->getInstr()->isPHI())
3885 newOrderPhi.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003886 }
3887 std::deque<SUnit *> newOrderI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003888 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3889 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003890 if (!SU->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003891 orderDependence(SSD, SU, newOrderI);
3892 }
3893 // Replace the old order with the new order.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003894 cycleInstrs.swap(newOrderPhi);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003895 cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003896 SSD->fixupRegisterOverlaps(cycleInstrs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003897 }
3898
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003899 LLVM_DEBUG(dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00003900}
3901
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003902void NodeSet::print(raw_ostream &os) const {
3903 os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3904 << " depth " << MaxDepth << " col " << Colocate << "\n";
3905 for (const auto &I : Nodes)
3906 os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
3907 os << "\n";
3908}
3909
Aaron Ballman615eb472017-10-15 14:32:27 +00003910#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003911/// Print the schedule information to the given output.
3912void SMSchedule::print(raw_ostream &os) const {
3913 // Iterate over each cycle.
3914 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3915 // Iterate over each instruction in the cycle.
3916 const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3917 for (SUnit *CI : cycleInstrs->second) {
3918 os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3919 os << "(" << CI->NodeNum << ") ";
3920 CI->getInstr()->print(os);
3921 os << "\n";
3922 }
3923 }
3924}
3925
3926/// Utility function used for debugging to print the schedule.
Matthias Braun8c209aa2017-01-28 02:02:38 +00003927LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003928LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3929
Matthias Braun8c209aa2017-01-28 02:02:38 +00003930#endif
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003931
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003932void ResourceManager::initProcResourceVectors(
3933 const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3934 unsigned ProcResourceID = 0;
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003935
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003936 // We currently limit the resource kinds to 64 and below so that we can use
3937 // uint64_t for Masks
3938 assert(SM.getNumProcResourceKinds() < 64 &&
3939 "Too many kinds of resources, unsupported");
3940 // Create a unique bitmask for every processor resource unit.
3941 // Skip resource at index 0, since it always references 'InvalidUnit'.
3942 Masks.resize(SM.getNumProcResourceKinds());
3943 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3944 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3945 if (Desc.SubUnitsIdxBegin)
3946 continue;
3947 Masks[I] = 1ULL << ProcResourceID;
3948 ProcResourceID++;
3949 }
3950 // Create a unique bitmask for every processor resource group.
3951 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3952 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3953 if (!Desc.SubUnitsIdxBegin)
3954 continue;
3955 Masks[I] = 1ULL << ProcResourceID;
3956 for (unsigned U = 0; U < Desc.NumUnits; ++U)
3957 Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3958 ProcResourceID++;
3959 }
3960 LLVM_DEBUG({
3961 dbgs() << "ProcResourceDesc:\n";
3962 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3963 const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3964 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3965 ProcResource->Name, I, Masks[I], ProcResource->NumUnits);
3966 }
3967 dbgs() << " -----------------\n";
3968 });
3969}
3970
3971bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
3972
3973 LLVM_DEBUG({ dbgs() << "canReserveResources:\n"; });
3974 if (UseDFA)
3975 return DFAResources->canReserveResources(MID);
3976
3977 unsigned InsnClass = MID->getSchedClass();
3978 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
3979 if (!SCDesc->isValid()) {
3980 LLVM_DEBUG({
3981 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3982 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
3983 });
3984 return true;
3985 }
3986
3987 const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
3988 const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
3989 for (; I != E; ++I) {
3990 if (!I->Cycles)
3991 continue;
3992 const MCProcResourceDesc *ProcResource =
3993 SM.getProcResource(I->ProcResourceIdx);
3994 unsigned NumUnits = ProcResource->NumUnits;
3995 LLVM_DEBUG({
3996 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3997 ProcResource->Name, I->ProcResourceIdx,
3998 ProcResourceCount[I->ProcResourceIdx], NumUnits,
3999 I->Cycles);
4000 });
4001 if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
4002 return false;
4003 }
4004 LLVM_DEBUG(dbgs() << "return true\n\n";);
4005 return true;
4006}
4007
4008void ResourceManager::reserveResources(const MCInstrDesc *MID) {
4009 LLVM_DEBUG({ dbgs() << "reserveResources:\n"; });
4010 if (UseDFA)
4011 return DFAResources->reserveResources(MID);
4012
4013 unsigned InsnClass = MID->getSchedClass();
4014 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
4015 if (!SCDesc->isValid()) {
4016 LLVM_DEBUG({
4017 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4018 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
4019 });
4020 return;
4021 }
4022 for (const MCWriteProcResEntry &PRE :
4023 make_range(STI->getWriteProcResBegin(SCDesc),
4024 STI->getWriteProcResEnd(SCDesc))) {
4025 if (!PRE.Cycles)
4026 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004027 ++ProcResourceCount[PRE.ProcResourceIdx];
4028 LLVM_DEBUG({
Richard Trieuc77aff72019-05-29 04:09:32 +00004029 const MCProcResourceDesc *ProcResource =
4030 SM.getProcResource(PRE.ProcResourceIdx);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004031 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
4032 ProcResource->Name, PRE.ProcResourceIdx,
Richard Trieue8698ea2019-05-29 03:43:01 +00004033 ProcResourceCount[PRE.ProcResourceIdx],
4034 ProcResource->NumUnits, PRE.Cycles);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004035 });
4036 }
4037 LLVM_DEBUG({ dbgs() << "reserveResources: done!\n\n"; });
4038}
4039
4040bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
4041 return canReserveResources(&MI.getDesc());
4042}
4043
4044void ResourceManager::reserveResources(const MachineInstr &MI) {
4045 return reserveResources(&MI.getDesc());
4046}
4047
4048void ResourceManager::clearResources() {
4049 if (UseDFA)
4050 return DFAResources->clearResources();
4051 std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
4052}
Adrian Prantlfa2e3582019-01-14 17:24:11 +00004053