blob: 65805d12cac6694be8f46c2da6a443be93764434 [file] [log] [blame]
Eugene Zelenko32a40562017-09-11 23:00:48 +00001//===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
Brendon Cahoon254f8892016-07-29 16:44:44 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
11//
Brendon Cahoon254f8892016-07-29 16:44:44 +000012// This SMS implementation is a target-independent back-end pass. When enabled,
13// the pass runs just prior to the register allocation pass, while the machine
14// IR is in SSA form. If software pipelining is successful, then the original
15// loop is replaced by the optimized loop. The optimized loop contains one or
16// more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
17// the instructions cannot be scheduled in a given MII, we increase the MII by
18// one and try again.
19//
20// The SMS implementation is an extension of the ScheduleDAGInstrs class. We
21// represent loop carried dependences in the DAG as order edges to the Phi
22// nodes. We also perform several passes over the DAG to eliminate unnecessary
23// edges that inhibit the ability to pipeline. The implementation uses the
24// DFAPacketizer class to compute the minimum initiation interval and the check
25// where an instruction may be inserted in the pipelined schedule.
26//
27// In order for the SMS pass to work, several target specific hooks need to be
28// implemented to get information about the loop structure and to rewrite
29// instructions.
30//
31//===----------------------------------------------------------------------===//
32
Eugene Zelenkocdc71612016-08-11 17:20:18 +000033#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/BitVector.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000035#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/MapVector.h"
37#include "llvm/ADT/PriorityQueue.h"
38#include "llvm/ADT/SetVector.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/SmallSet.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000041#include "llvm/ADT/SmallVector.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000042#include "llvm/ADT/Statistic.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000043#include "llvm/ADT/iterator_range.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000044#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000045#include "llvm/Analysis/MemoryLocation.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000046#include "llvm/Analysis/ValueTracking.h"
47#include "llvm/CodeGen/DFAPacketizer.h"
Matthias Braunf8422972017-12-13 02:51:04 +000048#include "llvm/CodeGen/LiveIntervals.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000049#include "llvm/CodeGen/MachineBasicBlock.h"
50#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include "llvm/CodeGen/MachineFunction.h"
52#include "llvm/CodeGen/MachineFunctionPass.h"
53#include "llvm/CodeGen/MachineInstr.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000054#include "llvm/CodeGen/MachineInstrBuilder.h"
55#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000056#include "llvm/CodeGen/MachineMemOperand.h"
57#include "llvm/CodeGen/MachineOperand.h"
Lama Saba7d9b3a62018-10-23 07:58:41 +000058#include "llvm/CodeGen/MachinePipeliner.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000059#include "llvm/CodeGen/MachineRegisterInfo.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000060#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000061#include "llvm/CodeGen/ScheduleDAG.h"
Krzysztof Parzyszek88391242016-12-22 19:21:20 +000062#include "llvm/CodeGen/ScheduleDAGMutation.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000063#include "llvm/CodeGen/TargetOpcodes.h"
64#include "llvm/CodeGen/TargetRegisterInfo.h"
65#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000066#include "llvm/Config/llvm-config.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000067#include "llvm/IR/Attributes.h"
68#include "llvm/IR/DebugLoc.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000069#include "llvm/IR/Function.h"
70#include "llvm/MC/LaneBitmask.h"
71#include "llvm/MC/MCInstrDesc.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000072#include "llvm/MC/MCInstrItineraries.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000073#include "llvm/MC/MCRegisterInfo.h"
74#include "llvm/Pass.h"
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +000075#include "llvm/Support/Casting.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000076#include "llvm/Support/CommandLine.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000077#include "llvm/Support/Compiler.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000078#include "llvm/Support/Debug.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000079#include "llvm/Support/MathExtras.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000080#include "llvm/Support/raw_ostream.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000081#include <algorithm>
82#include <cassert>
Brendon Cahoon254f8892016-07-29 16:44:44 +000083#include <climits>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000084#include <cstdint>
Brendon Cahoon254f8892016-07-29 16:44:44 +000085#include <deque>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000086#include <functional>
87#include <iterator>
Brendon Cahoon254f8892016-07-29 16:44:44 +000088#include <map>
Eugene Zelenko32a40562017-09-11 23:00:48 +000089#include <memory>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000090#include <tuple>
91#include <utility>
92#include <vector>
Brendon Cahoon254f8892016-07-29 16:44:44 +000093
94using namespace llvm;
95
96#define DEBUG_TYPE "pipeliner"
97
98STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
99STATISTIC(NumPipelined, "Number of loops software pipelined");
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000100STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000101
102/// A command line option to turn software pipelining on or off.
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000103static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
104 cl::ZeroOrMore,
105 cl::desc("Enable Software Pipelining"));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000106
107/// A command line option to enable SWP at -Os.
108static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
109 cl::desc("Enable SWP at Os."), cl::Hidden,
110 cl::init(false));
111
112/// A command line argument to limit minimum initial interval for pipelining.
113static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000114 cl::desc("Size limit for the MII."),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000115 cl::Hidden, cl::init(27));
116
117/// A command line argument to limit the number of stages in the pipeline.
118static cl::opt<int>
119 SwpMaxStages("pipeliner-max-stages",
120 cl::desc("Maximum stages allowed in the generated scheduled."),
121 cl::Hidden, cl::init(3));
122
123/// A command line option to disable the pruning of chain dependences due to
124/// an unrelated Phi.
125static cl::opt<bool>
126 SwpPruneDeps("pipeliner-prune-deps",
127 cl::desc("Prune dependences between unrelated Phi nodes."),
128 cl::Hidden, cl::init(true));
129
130/// A command line option to disable the pruning of loop carried order
131/// dependences.
132static cl::opt<bool>
133 SwpPruneLoopCarried("pipeliner-prune-loop-carried",
134 cl::desc("Prune loop carried order dependences."),
135 cl::Hidden, cl::init(true));
136
137#ifndef NDEBUG
138static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
139#endif
140
141static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
142 cl::ReallyHidden, cl::init(false),
143 cl::ZeroOrMore, cl::desc("Ignore RecMII"));
144
Lama Saba7d9b3a62018-10-23 07:58:41 +0000145namespace llvm {
146
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000147// A command line option to enable the CopyToPhi DAG mutation.
Lama Saba7d9b3a62018-10-23 07:58:41 +0000148cl::opt<bool> SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
149 cl::init(true), cl::ZeroOrMore,
150 cl::desc("Enable CopyToPhi DAG Mutation"));
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000151
Lama Saba7d9b3a62018-10-23 07:58:41 +0000152} // end namespace llvm
Brendon Cahoon254f8892016-07-29 16:44:44 +0000153
154unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
155char MachinePipeliner::ID = 0;
156#ifndef NDEBUG
157int MachinePipeliner::NumTries = 0;
158#endif
159char &llvm::MachinePipelinerID = MachinePipeliner::ID;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000160
Matthias Braun1527baa2017-05-25 21:26:32 +0000161INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000162 "Modulo Software Pipelining", false, false)
163INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
164INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
165INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
166INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000167INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000168 "Modulo Software Pipelining", false, false)
169
170/// The "main" function for implementing Swing Modulo Scheduling.
171bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000172 if (skipFunction(mf.getFunction()))
Brendon Cahoon254f8892016-07-29 16:44:44 +0000173 return false;
174
175 if (!EnableSWP)
176 return false;
177
Matthias Braunf1caa282017-12-15 22:22:58 +0000178 if (mf.getFunction().getAttributes().hasAttribute(
Reid Klecknerb5180542017-03-21 16:57:19 +0000179 AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +0000180 !EnableSWPOptSize.getPosition())
181 return false;
182
183 MF = &mf;
184 MLI = &getAnalysis<MachineLoopInfo>();
185 MDT = &getAnalysis<MachineDominatorTree>();
186 TII = MF->getSubtarget().getInstrInfo();
187 RegClassInfo.runOnMachineFunction(*MF);
188
189 for (auto &L : *MLI)
190 scheduleLoop(*L);
191
192 return false;
193}
194
195/// Attempt to perform the SMS algorithm on the specified loop. This function is
196/// the main entry point for the algorithm. The function identifies candidate
197/// loops, calculates the minimum initiation interval, and attempts to schedule
198/// the loop.
199bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
200 bool Changed = false;
201 for (auto &InnerLoop : L)
202 Changed |= scheduleLoop(*InnerLoop);
203
204#ifndef NDEBUG
205 // Stop trying after reaching the limit (if any).
206 int Limit = SwpLoopLimit;
207 if (Limit >= 0) {
208 if (NumTries >= SwpLoopLimit)
209 return Changed;
210 NumTries++;
211 }
212#endif
213
214 if (!canPipelineLoop(L))
215 return Changed;
216
217 ++NumTrytoPipeline;
218
219 Changed = swingModuloScheduler(L);
220
221 return Changed;
222}
223
224/// Return true if the loop can be software pipelined. The algorithm is
225/// restricted to loops with a single basic block. Make sure that the
226/// branch in the loop can be analyzed.
227bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
228 if (L.getNumBlocks() != 1)
229 return false;
230
231 // Check if the branch can't be understood because we can't do pipelining
232 // if that's the case.
233 LI.TBB = nullptr;
234 LI.FBB = nullptr;
235 LI.BrCond.clear();
236 if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond))
237 return false;
238
239 LI.LoopInductionVar = nullptr;
240 LI.LoopCompare = nullptr;
241 if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare))
242 return false;
243
244 if (!L.getLoopPreheader())
245 return false;
246
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000247 // Remove any subregisters from inputs to phi nodes.
248 preprocessPhiNodes(*L.getHeader());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000249 return true;
250}
251
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000252void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
253 MachineRegisterInfo &MRI = MF->getRegInfo();
254 SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
255
256 for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
257 MachineOperand &DefOp = PI.getOperand(0);
258 assert(DefOp.getSubReg() == 0);
259 auto *RC = MRI.getRegClass(DefOp.getReg());
260
261 for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
262 MachineOperand &RegOp = PI.getOperand(i);
263 if (RegOp.getSubReg() == 0)
264 continue;
265
266 // If the operand uses a subregister, replace it with a new register
267 // without subregisters, and generate a copy to the new register.
268 unsigned NewReg = MRI.createVirtualRegister(RC);
269 MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
270 MachineBasicBlock::iterator At = PredB.getFirstTerminator();
271 const DebugLoc &DL = PredB.findDebugLoc(At);
272 auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
273 .addReg(RegOp.getReg(), getRegState(RegOp),
274 RegOp.getSubReg());
275 Slots.insertMachineInstrInMaps(*Copy);
276 RegOp.setReg(NewReg);
277 RegOp.setSubReg(0);
278 }
279 }
280}
281
Brendon Cahoon254f8892016-07-29 16:44:44 +0000282/// The SMS algorithm consists of the following main steps:
283/// 1. Computation and analysis of the dependence graph.
284/// 2. Ordering of the nodes (instructions).
285/// 3. Attempt to Schedule the loop.
286bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
287 assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
288
289 SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo);
290
291 MachineBasicBlock *MBB = L.getHeader();
292 // The kernel should not include any terminator instructions. These
293 // will be added back later.
294 SMS.startBlock(MBB);
295
296 // Compute the number of 'real' instructions in the basic block by
297 // ignoring terminators.
298 unsigned size = MBB->size();
299 for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
300 E = MBB->instr_end();
301 I != E; ++I, --size)
302 ;
303
304 SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
305 SMS.schedule();
306 SMS.exitRegion();
307
308 SMS.finishBlock();
309 return SMS.hasNewSchedule();
310}
311
312/// We override the schedule function in ScheduleDAGInstrs to implement the
313/// scheduling part of the Swing Modulo Scheduling algorithm.
314void SwingSchedulerDAG::schedule() {
315 AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
316 buildSchedGraph(AA);
317 addLoopCarriedDependences(AA);
318 updatePhiDependences();
319 Topo.InitDAGTopologicalSorting();
320 changeDependences();
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000321 postprocessDAG();
Matthias Braun726e12c2018-09-19 00:23:35 +0000322 LLVM_DEBUG(dump());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000323
324 NodeSetType NodeSets;
325 findCircuits(NodeSets);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000326 NodeSetType Circuits = NodeSets;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000327
328 // Calculate the MII.
329 unsigned ResMII = calculateResMII();
330 unsigned RecMII = calculateRecMII(NodeSets);
331
332 fuseRecs(NodeSets);
333
334 // This flag is used for testing and can cause correctness problems.
335 if (SwpIgnoreRecMII)
336 RecMII = 0;
337
338 MII = std::max(ResMII, RecMII);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000339 LLVM_DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII
340 << ", res=" << ResMII << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000341
342 // Can't schedule a loop without a valid MII.
343 if (MII == 0)
344 return;
345
346 // Don't pipeline large loops.
347 if (SwpMaxMii != -1 && (int)MII > SwpMaxMii)
348 return;
349
350 computeNodeFunctions(NodeSets);
351
352 registerPressureFilter(NodeSets);
353
354 colocateNodeSets(NodeSets);
355
356 checkNodeSets(NodeSets);
357
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000358 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000359 for (auto &I : NodeSets) {
360 dbgs() << " Rec NodeSet ";
361 I.dump();
362 }
363 });
364
Krzysztof Parzyszek6c2f8682018-04-12 15:11:11 +0000365 std::stable_sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000366
367 groupRemainingNodes(NodeSets);
368
369 removeDuplicateNodes(NodeSets);
370
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000371 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000372 for (auto &I : NodeSets) {
373 dbgs() << " NodeSet ";
374 I.dump();
375 }
376 });
377
378 computeNodeOrder(NodeSets);
379
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000380 // check for node order issues
381 checkValidNodeOrder(Circuits);
382
Brendon Cahoon254f8892016-07-29 16:44:44 +0000383 SMSchedule Schedule(Pass.MF);
384 Scheduled = schedulePipeline(Schedule);
385
386 if (!Scheduled)
387 return;
388
389 unsigned numStages = Schedule.getMaxStageCount();
390 // No need to generate pipeline if there are no overlapped iterations.
391 if (numStages == 0)
392 return;
393
394 // Check that the maximum stage count is less than user-defined limit.
395 if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages)
396 return;
397
398 generatePipelinedLoop(Schedule);
399 ++NumPipelined;
400}
401
402/// Clean up after the software pipeliner runs.
403void SwingSchedulerDAG::finishBlock() {
404 for (MachineInstr *I : NewMIs)
405 MF.DeleteMachineInstr(I);
406 NewMIs.clear();
407
408 // Call the superclass.
409 ScheduleDAGInstrs::finishBlock();
410}
411
412/// Return the register values for the operands of a Phi instruction.
413/// This function assume the instruction is a Phi.
414static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
415 unsigned &InitVal, unsigned &LoopVal) {
416 assert(Phi.isPHI() && "Expecting a Phi.");
417
418 InitVal = 0;
419 LoopVal = 0;
420 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
421 if (Phi.getOperand(i + 1).getMBB() != Loop)
422 InitVal = Phi.getOperand(i).getReg();
Simon Pilgrimfbfb19b2017-03-16 19:52:00 +0000423 else
Brendon Cahoon254f8892016-07-29 16:44:44 +0000424 LoopVal = Phi.getOperand(i).getReg();
425
426 assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
427}
428
429/// Return the Phi register value that comes from the incoming block.
430static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
431 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
432 if (Phi.getOperand(i + 1).getMBB() != LoopBB)
433 return Phi.getOperand(i).getReg();
434 return 0;
435}
436
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000437/// Return the Phi register value that comes the loop block.
Brendon Cahoon254f8892016-07-29 16:44:44 +0000438static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
439 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
440 if (Phi.getOperand(i + 1).getMBB() == LoopBB)
441 return Phi.getOperand(i).getReg();
442 return 0;
443}
444
445/// Return true if SUb can be reached from SUa following the chain edges.
446static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
447 SmallPtrSet<SUnit *, 8> Visited;
448 SmallVector<SUnit *, 8> Worklist;
449 Worklist.push_back(SUa);
450 while (!Worklist.empty()) {
451 const SUnit *SU = Worklist.pop_back_val();
452 for (auto &SI : SU->Succs) {
453 SUnit *SuccSU = SI.getSUnit();
454 if (SI.getKind() == SDep::Order) {
455 if (Visited.count(SuccSU))
456 continue;
457 if (SuccSU == SUb)
458 return true;
459 Worklist.push_back(SuccSU);
460 Visited.insert(SuccSU);
461 }
462 }
463 }
464 return false;
465}
466
467/// Return true if the instruction causes a chain between memory
468/// references before and after it.
469static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
470 return MI.isCall() || MI.hasUnmodeledSideEffects() ||
471 (MI.hasOrderedMemoryRef() &&
Justin Lebard98cf002016-09-10 01:03:20 +0000472 (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000473}
474
475/// Return the underlying objects for the memory references of an instruction.
476/// This function calls the code in ValueTracking, but first checks that the
477/// instruction has a memory operand.
478static void getUnderlyingObjects(MachineInstr *MI,
479 SmallVectorImpl<Value *> &Objs,
480 const DataLayout &DL) {
481 if (!MI->hasOneMemOperand())
482 return;
483 MachineMemOperand *MM = *MI->memoperands_begin();
484 if (!MM->getValue())
485 return;
486 GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL);
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000487 for (Value *V : Objs) {
488 if (!isIdentifiedObject(V)) {
489 Objs.clear();
490 return;
491 }
492 Objs.push_back(V);
493 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000494}
495
496/// Add a chain edge between a load and store if the store can be an
497/// alias of the load on a subsequent iteration, i.e., a loop carried
498/// dependence. This code is very similar to the code in ScheduleDAGInstrs
499/// but that code doesn't create loop carried dependences.
500void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
501 MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads;
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000502 Value *UnknownValue =
503 UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000504 for (auto &SU : SUnits) {
505 MachineInstr &MI = *SU.getInstr();
506 if (isDependenceBarrier(MI, AA))
507 PendingLoads.clear();
508 else if (MI.mayLoad()) {
509 SmallVector<Value *, 4> Objs;
510 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000511 if (Objs.empty())
512 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000513 for (auto V : Objs) {
514 SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
515 SUs.push_back(&SU);
516 }
517 } else if (MI.mayStore()) {
518 SmallVector<Value *, 4> Objs;
519 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000520 if (Objs.empty())
521 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000522 for (auto V : Objs) {
523 MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I =
524 PendingLoads.find(V);
525 if (I == PendingLoads.end())
526 continue;
527 for (auto Load : I->second) {
528 if (isSuccOrder(Load, &SU))
529 continue;
530 MachineInstr &LdMI = *Load->getInstr();
531 // First, perform the cheaper check that compares the base register.
532 // If they are the same and the load offset is less than the store
533 // offset, then mark the dependence as loop carried potentially.
534 unsigned BaseReg1, BaseReg2;
535 int64_t Offset1, Offset2;
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000536 if (TII->getMemOpBaseRegImmOfs(LdMI, BaseReg1, Offset1, TRI) &&
537 TII->getMemOpBaseRegImmOfs(MI, BaseReg2, Offset2, TRI)) {
538 if (BaseReg1 == BaseReg2 && (int)Offset1 < (int)Offset2) {
539 assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
540 "What happened to the chain edge?");
541 SDep Dep(Load, SDep::Barrier);
542 Dep.setLatency(1);
543 SU.addPred(Dep);
544 continue;
545 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000546 }
547 // Second, the more expensive check that uses alias analysis on the
548 // base registers. If they alias, and the load offset is less than
549 // the store offset, the mark the dependence as loop carried.
550 if (!AA) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000551 SDep Dep(Load, SDep::Barrier);
552 Dep.setLatency(1);
553 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000554 continue;
555 }
556 MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
557 MachineMemOperand *MMO2 = *MI.memoperands_begin();
558 if (!MMO1->getValue() || !MMO2->getValue()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000559 SDep Dep(Load, SDep::Barrier);
560 Dep.setLatency(1);
561 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000562 continue;
563 }
564 if (MMO1->getValue() == MMO2->getValue() &&
565 MMO1->getOffset() <= MMO2->getOffset()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000566 SDep Dep(Load, SDep::Barrier);
567 Dep.setLatency(1);
568 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000569 continue;
570 }
571 AliasResult AAResult = AA->alias(
George Burgess IV6ef80022018-10-10 21:28:44 +0000572 MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000573 MMO1->getAAInfo()),
George Burgess IV6ef80022018-10-10 21:28:44 +0000574 MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000575 MMO2->getAAInfo()));
576
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000577 if (AAResult != NoAlias) {
578 SDep Dep(Load, SDep::Barrier);
579 Dep.setLatency(1);
580 SU.addPred(Dep);
581 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000582 }
583 }
584 }
585 }
586}
587
588/// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
589/// processes dependences for PHIs. This function adds true dependences
590/// from a PHI to a use, and a loop carried dependence from the use to the
591/// PHI. The loop carried dependence is represented as an anti dependence
592/// edge. This function also removes chain dependences between unrelated
593/// PHIs.
594void SwingSchedulerDAG::updatePhiDependences() {
595 SmallVector<SDep, 4> RemoveDeps;
596 const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
597
598 // Iterate over each DAG node.
599 for (SUnit &I : SUnits) {
600 RemoveDeps.clear();
601 // Set to true if the instruction has an operand defined by a Phi.
602 unsigned HasPhiUse = 0;
603 unsigned HasPhiDef = 0;
604 MachineInstr *MI = I.getInstr();
605 // Iterate over each operand, and we process the definitions.
606 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
607 MOE = MI->operands_end();
608 MOI != MOE; ++MOI) {
609 if (!MOI->isReg())
610 continue;
611 unsigned Reg = MOI->getReg();
612 if (MOI->isDef()) {
613 // If the register is used by a Phi, then create an anti dependence.
614 for (MachineRegisterInfo::use_instr_iterator
615 UI = MRI.use_instr_begin(Reg),
616 UE = MRI.use_instr_end();
617 UI != UE; ++UI) {
618 MachineInstr *UseMI = &*UI;
619 SUnit *SU = getSUnit(UseMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000620 if (SU != nullptr && UseMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000621 if (!MI->isPHI()) {
622 SDep Dep(SU, SDep::Anti, Reg);
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000623 Dep.setLatency(1);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000624 I.addPred(Dep);
625 } else {
626 HasPhiDef = Reg;
627 // Add a chain edge to a dependent Phi that isn't an existing
628 // predecessor.
629 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
630 I.addPred(SDep(SU, SDep::Barrier));
631 }
632 }
633 }
634 } else if (MOI->isUse()) {
635 // If the register is defined by a Phi, then create a true dependence.
636 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000637 if (DefMI == nullptr)
Brendon Cahoon254f8892016-07-29 16:44:44 +0000638 continue;
639 SUnit *SU = getSUnit(DefMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000640 if (SU != nullptr && DefMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000641 if (!MI->isPHI()) {
642 SDep Dep(SU, SDep::Data, Reg);
643 Dep.setLatency(0);
644 ST.adjustSchedDependency(SU, &I, Dep);
645 I.addPred(Dep);
646 } else {
647 HasPhiUse = Reg;
648 // Add a chain edge to a dependent Phi that isn't an existing
649 // predecessor.
650 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
651 I.addPred(SDep(SU, SDep::Barrier));
652 }
653 }
654 }
655 }
656 // Remove order dependences from an unrelated Phi.
657 if (!SwpPruneDeps)
658 continue;
659 for (auto &PI : I.Preds) {
660 MachineInstr *PMI = PI.getSUnit()->getInstr();
661 if (PMI->isPHI() && PI.getKind() == SDep::Order) {
662 if (I.getInstr()->isPHI()) {
663 if (PMI->getOperand(0).getReg() == HasPhiUse)
664 continue;
665 if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
666 continue;
667 }
668 RemoveDeps.push_back(PI);
669 }
670 }
671 for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
672 I.removePred(RemoveDeps[i]);
673 }
674}
675
676/// Iterate over each DAG node and see if we can change any dependences
677/// in order to reduce the recurrence MII.
678void SwingSchedulerDAG::changeDependences() {
679 // See if an instruction can use a value from the previous iteration.
680 // If so, we update the base and offset of the instruction and change
681 // the dependences.
682 for (SUnit &I : SUnits) {
683 unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
684 int64_t NewOffset = 0;
685 if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
686 NewOffset))
687 continue;
688
689 // Get the MI and SUnit for the instruction that defines the original base.
690 unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
691 MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
692 if (!DefMI)
693 continue;
694 SUnit *DefSU = getSUnit(DefMI);
695 if (!DefSU)
696 continue;
697 // Get the MI and SUnit for the instruction that defins the new base.
698 MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
699 if (!LastMI)
700 continue;
701 SUnit *LastSU = getSUnit(LastMI);
702 if (!LastSU)
703 continue;
704
705 if (Topo.IsReachable(&I, LastSU))
706 continue;
707
708 // Remove the dependence. The value now depends on a prior iteration.
709 SmallVector<SDep, 4> Deps;
710 for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
711 ++P)
712 if (P->getSUnit() == DefSU)
713 Deps.push_back(*P);
714 for (int i = 0, e = Deps.size(); i != e; i++) {
715 Topo.RemovePred(&I, Deps[i].getSUnit());
716 I.removePred(Deps[i]);
717 }
718 // Remove the chain dependence between the instructions.
719 Deps.clear();
720 for (auto &P : LastSU->Preds)
721 if (P.getSUnit() == &I && P.getKind() == SDep::Order)
722 Deps.push_back(P);
723 for (int i = 0, e = Deps.size(); i != e; i++) {
724 Topo.RemovePred(LastSU, Deps[i].getSUnit());
725 LastSU->removePred(Deps[i]);
726 }
727
728 // Add a dependence between the new instruction and the instruction
729 // that defines the new base.
730 SDep Dep(&I, SDep::Anti, NewBase);
Sumanth Gundapaneni8916e432018-10-11 19:42:46 +0000731 Topo.AddPred(LastSU, &I);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000732 LastSU->addPred(Dep);
733
734 // Remember the base and offset information so that we can update the
735 // instruction during code generation.
736 InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
737 }
738}
739
740namespace {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000741
Brendon Cahoon254f8892016-07-29 16:44:44 +0000742// FuncUnitSorter - Comparison operator used to sort instructions by
743// the number of functional unit choices.
744struct FuncUnitSorter {
745 const InstrItineraryData *InstrItins;
746 DenseMap<unsigned, unsigned> Resources;
747
Eugene Zelenko32a40562017-09-11 23:00:48 +0000748 FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {}
749
Brendon Cahoon254f8892016-07-29 16:44:44 +0000750 // Compute the number of functional unit alternatives needed
751 // at each stage, and take the minimum value. We prioritize the
752 // instructions by the least number of choices first.
753 unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
754 unsigned schedClass = Inst->getDesc().getSchedClass();
755 unsigned min = UINT_MAX;
756 for (const InstrStage *IS = InstrItins->beginStage(schedClass),
757 *IE = InstrItins->endStage(schedClass);
758 IS != IE; ++IS) {
759 unsigned funcUnits = IS->getUnits();
760 unsigned numAlternatives = countPopulation(funcUnits);
761 if (numAlternatives < min) {
762 min = numAlternatives;
763 F = funcUnits;
764 }
765 }
766 return min;
767 }
768
769 // Compute the critical resources needed by the instruction. This
770 // function records the functional units needed by instructions that
771 // must use only one functional unit. We use this as a tie breaker
772 // for computing the resource MII. The instrutions that require
773 // the same, highly used, functional unit have high priority.
774 void calcCriticalResources(MachineInstr &MI) {
775 unsigned SchedClass = MI.getDesc().getSchedClass();
776 for (const InstrStage *IS = InstrItins->beginStage(SchedClass),
777 *IE = InstrItins->endStage(SchedClass);
778 IS != IE; ++IS) {
779 unsigned FuncUnits = IS->getUnits();
780 if (countPopulation(FuncUnits) == 1)
781 Resources[FuncUnits]++;
782 }
783 }
784
Brendon Cahoon254f8892016-07-29 16:44:44 +0000785 /// Return true if IS1 has less priority than IS2.
786 bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
787 unsigned F1 = 0, F2 = 0;
788 unsigned MFUs1 = minFuncUnits(IS1, F1);
789 unsigned MFUs2 = minFuncUnits(IS2, F2);
790 if (MFUs1 == 1 && MFUs2 == 1)
791 return Resources.lookup(F1) < Resources.lookup(F2);
792 return MFUs1 > MFUs2;
793 }
794};
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000795
796} // end anonymous namespace
Brendon Cahoon254f8892016-07-29 16:44:44 +0000797
798/// Calculate the resource constrained minimum initiation interval for the
799/// specified loop. We use the DFA to model the resources needed for
800/// each instruction, and we ignore dependences. A different DFA is created
801/// for each cycle that is required. When adding a new instruction, we attempt
802/// to add it to each existing DFA, until a legal space is found. If the
803/// instruction cannot be reserved in an existing DFA, we create a new one.
804unsigned SwingSchedulerDAG::calculateResMII() {
805 SmallVector<DFAPacketizer *, 8> Resources;
806 MachineBasicBlock *MBB = Loop.getHeader();
807 Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget()));
808
809 // Sort the instructions by the number of available choices for scheduling,
810 // least to most. Use the number of critical resources as the tie breaker.
811 FuncUnitSorter FUS =
812 FuncUnitSorter(MF.getSubtarget().getInstrItineraryData());
813 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
814 E = MBB->getFirstTerminator();
815 I != E; ++I)
816 FUS.calcCriticalResources(*I);
817 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
818 FuncUnitOrder(FUS);
819
820 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
821 E = MBB->getFirstTerminator();
822 I != E; ++I)
823 FuncUnitOrder.push(&*I);
824
825 while (!FuncUnitOrder.empty()) {
826 MachineInstr *MI = FuncUnitOrder.top();
827 FuncUnitOrder.pop();
828 if (TII->isZeroCost(MI->getOpcode()))
829 continue;
830 // Attempt to reserve the instruction in an existing DFA. At least one
831 // DFA is needed for each cycle.
832 unsigned NumCycles = getSUnit(MI)->Latency;
833 unsigned ReservedCycles = 0;
834 SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin();
835 SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end();
836 for (unsigned C = 0; C < NumCycles; ++C)
837 while (RI != RE) {
838 if ((*RI++)->canReserveResources(*MI)) {
839 ++ReservedCycles;
840 break;
841 }
842 }
843 // Start reserving resources using existing DFAs.
844 for (unsigned C = 0; C < ReservedCycles; ++C) {
845 --RI;
846 (*RI)->reserveResources(*MI);
847 }
848 // Add new DFAs, if needed, to reserve resources.
849 for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
850 DFAPacketizer *NewResource =
851 TII->CreateTargetScheduleState(MF.getSubtarget());
852 assert(NewResource->canReserveResources(*MI) && "Reserve error.");
853 NewResource->reserveResources(*MI);
854 Resources.push_back(NewResource);
855 }
856 }
857 int Resmii = Resources.size();
858 // Delete the memory for each of the DFAs that were created earlier.
859 for (DFAPacketizer *RI : Resources) {
860 DFAPacketizer *D = RI;
861 delete D;
862 }
863 Resources.clear();
864 return Resmii;
865}
866
867/// Calculate the recurrence-constrainted minimum initiation interval.
868/// Iterate over each circuit. Compute the delay(c) and distance(c)
869/// for each circuit. The II needs to satisfy the inequality
870/// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
Hiroshi Inouec73b6d62018-06-20 05:29:26 +0000871/// II that satisfies the inequality, and the RecMII is the maximum
Brendon Cahoon254f8892016-07-29 16:44:44 +0000872/// of those values.
873unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
874 unsigned RecMII = 0;
875
876 for (NodeSet &Nodes : NodeSets) {
Eugene Zelenko32a40562017-09-11 23:00:48 +0000877 if (Nodes.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +0000878 continue;
879
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +0000880 unsigned Delay = Nodes.getLatency();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000881 unsigned Distance = 1;
882
883 // ii = ceil(delay / distance)
884 unsigned CurMII = (Delay + Distance - 1) / Distance;
885 Nodes.setRecMII(CurMII);
886 if (CurMII > RecMII)
887 RecMII = CurMII;
888 }
889
890 return RecMII;
891}
892
893/// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
894/// but we do this to find the circuits, and then change them back.
895static void swapAntiDependences(std::vector<SUnit> &SUnits) {
896 SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
897 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
898 SUnit *SU = &SUnits[i];
899 for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
900 IP != EP; ++IP) {
901 if (IP->getKind() != SDep::Anti)
902 continue;
903 DepsAdded.push_back(std::make_pair(SU, *IP));
904 }
905 }
906 for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
907 E = DepsAdded.end();
908 I != E; ++I) {
909 // Remove this anti dependency and add one in the reverse direction.
910 SUnit *SU = I->first;
911 SDep &D = I->second;
912 SUnit *TargetSU = D.getSUnit();
913 unsigned Reg = D.getReg();
914 unsigned Lat = D.getLatency();
915 SU->removePred(D);
916 SDep Dep(SU, SDep::Anti, Reg);
917 Dep.setLatency(Lat);
918 TargetSU->addPred(Dep);
919 }
920}
921
922/// Create the adjacency structure of the nodes in the graph.
923void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
924 SwingSchedulerDAG *DAG) {
925 BitVector Added(SUnits.size());
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +0000926 DenseMap<int, int> OutputDeps;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000927 for (int i = 0, e = SUnits.size(); i != e; ++i) {
928 Added.reset();
929 // Add any successor to the adjacency matrix and exclude duplicates.
930 for (auto &SI : SUnits[i].Succs) {
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +0000931 // Only create a back-edge on the first and last nodes of a dependence
932 // chain. This records any chains and adds them later.
933 if (SI.getKind() == SDep::Output) {
934 int N = SI.getSUnit()->NodeNum;
935 int BackEdge = i;
936 auto Dep = OutputDeps.find(BackEdge);
937 if (Dep != OutputDeps.end()) {
938 BackEdge = Dep->second;
939 OutputDeps.erase(Dep);
940 }
941 OutputDeps[N] = BackEdge;
942 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000943 // Do not process a boundary node and a back-edge is processed only
944 // if it goes to a Phi.
945 if (SI.getSUnit()->isBoundaryNode() ||
946 (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
947 continue;
948 int N = SI.getSUnit()->NodeNum;
949 if (!Added.test(N)) {
950 AdjK[i].push_back(N);
951 Added.set(N);
952 }
953 }
954 // A chain edge between a store and a load is treated as a back-edge in the
955 // adjacency matrix.
956 for (auto &PI : SUnits[i].Preds) {
957 if (!SUnits[i].getInstr()->mayStore() ||
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +0000958 !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
Brendon Cahoon254f8892016-07-29 16:44:44 +0000959 continue;
960 if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
961 int N = PI.getSUnit()->NodeNum;
962 if (!Added.test(N)) {
963 AdjK[i].push_back(N);
964 Added.set(N);
965 }
966 }
967 }
968 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +0000969 // Add back-eges in the adjacency matrix for the output dependences.
970 for (auto &OD : OutputDeps)
971 if (!Added.test(OD.second)) {
972 AdjK[OD.first].push_back(OD.second);
973 Added.set(OD.second);
974 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000975}
976
977/// Identify an elementary circuit in the dependence graph starting at the
978/// specified node.
979bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
980 bool HasBackedge) {
981 SUnit *SV = &SUnits[V];
982 bool F = false;
983 Stack.insert(SV);
984 Blocked.set(V);
985
986 for (auto W : AdjK[V]) {
987 if (NumPaths > MaxPaths)
988 break;
989 if (W < S)
990 continue;
991 if (W == S) {
992 if (!HasBackedge)
993 NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
994 F = true;
995 ++NumPaths;
996 break;
997 } else if (!Blocked.test(W)) {
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +0000998 if (circuit(W, S, NodeSets,
999 Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001000 F = true;
1001 }
1002 }
1003
1004 if (F)
1005 unblock(V);
1006 else {
1007 for (auto W : AdjK[V]) {
1008 if (W < S)
1009 continue;
1010 if (B[W].count(SV) == 0)
1011 B[W].insert(SV);
1012 }
1013 }
1014 Stack.pop_back();
1015 return F;
1016}
1017
1018/// Unblock a node in the circuit finding algorithm.
1019void SwingSchedulerDAG::Circuits::unblock(int U) {
1020 Blocked.reset(U);
1021 SmallPtrSet<SUnit *, 4> &BU = B[U];
1022 while (!BU.empty()) {
1023 SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1024 assert(SI != BU.end() && "Invalid B set.");
1025 SUnit *W = *SI;
1026 BU.erase(W);
1027 if (Blocked.test(W->NodeNum))
1028 unblock(W->NodeNum);
1029 }
1030}
1031
1032/// Identify all the elementary circuits in the dependence graph using
1033/// Johnson's circuit algorithm.
1034void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1035 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1036 // but we do this to find the circuits, and then change them back.
1037 swapAntiDependences(SUnits);
1038
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001039 Circuits Cir(SUnits, Topo);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001040 // Create the adjacency structure.
1041 Cir.createAdjacencyStructure(this);
1042 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1043 Cir.reset();
1044 Cir.circuit(i, i, NodeSets);
1045 }
1046
1047 // Change the dependences back so that we've created a DAG again.
1048 swapAntiDependences(SUnits);
1049}
1050
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +00001051// Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1052// is loop-carried to the USE in next iteration. This will help pipeliner avoid
1053// additional copies that are needed across iterations. An artificial dependence
1054// edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1055
1056// PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1057// SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1058// PHI-------True-Dep------> USEOfPhi
1059
1060// The mutation creates
1061// USEOfPHI -------Artificial-Dep---> SRCOfCopy
1062
1063// This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1064// (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1065// late to avoid additional copies across iterations. The possible scheduling
1066// order would be
1067// USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1068
1069void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1070 for (SUnit &SU : DAG->SUnits) {
1071 // Find the COPY/REG_SEQUENCE instruction.
1072 if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1073 continue;
1074
1075 // Record the loop carried PHIs.
1076 SmallVector<SUnit *, 4> PHISUs;
1077 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1078 SmallVector<SUnit *, 4> SrcSUs;
1079
1080 for (auto &Dep : SU.Preds) {
1081 SUnit *TmpSU = Dep.getSUnit();
1082 MachineInstr *TmpMI = TmpSU->getInstr();
1083 SDep::Kind DepKind = Dep.getKind();
1084 // Save the loop carried PHI.
1085 if (DepKind == SDep::Anti && TmpMI->isPHI())
1086 PHISUs.push_back(TmpSU);
1087 // Save the source of COPY/REG_SEQUENCE.
1088 // If the source has no pre-decessors, we will end up creating cycles.
1089 else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1090 SrcSUs.push_back(TmpSU);
1091 }
1092
1093 if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1094 continue;
1095
1096 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1097 // SUnit to the container.
1098 SmallVector<SUnit *, 8> UseSUs;
1099 for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
1100 for (auto &Dep : (*I)->Succs) {
1101 if (Dep.getKind() != SDep::Data)
1102 continue;
1103
1104 SUnit *TmpSU = Dep.getSUnit();
1105 MachineInstr *TmpMI = TmpSU->getInstr();
1106 if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1107 PHISUs.push_back(TmpSU);
1108 continue;
1109 }
1110 UseSUs.push_back(TmpSU);
1111 }
1112 }
1113
1114 if (UseSUs.size() == 0)
1115 continue;
1116
1117 SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1118 // Add the artificial dependencies if it does not form a cycle.
1119 for (auto I : UseSUs) {
1120 for (auto Src : SrcSUs) {
1121 if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1122 Src->addPred(SDep(I, SDep::Artificial));
1123 SDAG->Topo.AddPred(Src, I);
1124 }
1125 }
1126 }
1127 }
1128}
1129
Brendon Cahoon254f8892016-07-29 16:44:44 +00001130/// Return true for DAG nodes that we ignore when computing the cost functions.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001131/// We ignore the back-edge recurrence in order to avoid unbounded recursion
Brendon Cahoon254f8892016-07-29 16:44:44 +00001132/// in the calculation of the ASAP, ALAP, etc functions.
1133static bool ignoreDependence(const SDep &D, bool isPred) {
1134 if (D.isArtificial())
1135 return true;
1136 return D.getKind() == SDep::Anti && isPred;
1137}
1138
1139/// Compute several functions need to order the nodes for scheduling.
1140/// ASAP - Earliest time to schedule a node.
1141/// ALAP - Latest time to schedule a node.
1142/// MOV - Mobility function, difference between ALAP and ASAP.
1143/// D - Depth of each node.
1144/// H - Height of each node.
1145void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001146 ScheduleInfo.resize(SUnits.size());
1147
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001148 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001149 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1150 E = Topo.end();
1151 I != E; ++I) {
Matthias Braun726e12c2018-09-19 00:23:35 +00001152 const SUnit &SU = SUnits[*I];
1153 dumpNode(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001154 }
1155 });
1156
1157 int maxASAP = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001158 // Compute ASAP and ZeroLatencyDepth.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001159 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1160 E = Topo.end();
1161 I != E; ++I) {
1162 int asap = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001163 int zeroLatencyDepth = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001164 SUnit *SU = &SUnits[*I];
1165 for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1166 EP = SU->Preds.end();
1167 IP != EP; ++IP) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001168 SUnit *pred = IP->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001169 if (IP->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001170 zeroLatencyDepth =
1171 std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001172 if (ignoreDependence(*IP, true))
1173 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001174 asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00001175 getDistance(pred, SU, *IP) * MII));
1176 }
1177 maxASAP = std::max(maxASAP, asap);
1178 ScheduleInfo[*I].ASAP = asap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001179 ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001180 }
1181
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001182 // Compute ALAP, ZeroLatencyHeight, and MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001183 for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1184 E = Topo.rend();
1185 I != E; ++I) {
1186 int alap = maxASAP;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001187 int zeroLatencyHeight = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001188 SUnit *SU = &SUnits[*I];
1189 for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1190 ES = SU->Succs.end();
1191 IS != ES; ++IS) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001192 SUnit *succ = IS->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001193 if (IS->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001194 zeroLatencyHeight =
1195 std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001196 if (ignoreDependence(*IS, true))
1197 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001198 alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00001199 getDistance(SU, succ, *IS) * MII));
1200 }
1201
1202 ScheduleInfo[*I].ALAP = alap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001203 ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001204 }
1205
1206 // After computing the node functions, compute the summary for each node set.
1207 for (NodeSet &I : NodeSets)
1208 I.computeNodeSetInfo(this);
1209
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001210 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001211 for (unsigned i = 0; i < SUnits.size(); i++) {
1212 dbgs() << "\tNode " << i << ":\n";
1213 dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
1214 dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
1215 dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
1216 dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
1217 dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001218 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1219 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001220 }
1221 });
1222}
1223
1224/// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1225/// as the predecessors of the elements of NodeOrder that are not also in
1226/// NodeOrder.
1227static bool pred_L(SetVector<SUnit *> &NodeOrder,
1228 SmallSetVector<SUnit *, 8> &Preds,
1229 const NodeSet *S = nullptr) {
1230 Preds.clear();
1231 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1232 I != E; ++I) {
1233 for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1234 PI != PE; ++PI) {
1235 if (S && S->count(PI->getSUnit()) == 0)
1236 continue;
1237 if (ignoreDependence(*PI, true))
1238 continue;
1239 if (NodeOrder.count(PI->getSUnit()) == 0)
1240 Preds.insert(PI->getSUnit());
1241 }
1242 // Back-edges are predecessors with an anti-dependence.
1243 for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1244 ES = (*I)->Succs.end();
1245 IS != ES; ++IS) {
1246 if (IS->getKind() != SDep::Anti)
1247 continue;
1248 if (S && S->count(IS->getSUnit()) == 0)
1249 continue;
1250 if (NodeOrder.count(IS->getSUnit()) == 0)
1251 Preds.insert(IS->getSUnit());
1252 }
1253 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001254 return !Preds.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001255}
1256
1257/// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1258/// as the successors of the elements of NodeOrder that are not also in
1259/// NodeOrder.
1260static bool succ_L(SetVector<SUnit *> &NodeOrder,
1261 SmallSetVector<SUnit *, 8> &Succs,
1262 const NodeSet *S = nullptr) {
1263 Succs.clear();
1264 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1265 I != E; ++I) {
1266 for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1267 SI != SE; ++SI) {
1268 if (S && S->count(SI->getSUnit()) == 0)
1269 continue;
1270 if (ignoreDependence(*SI, false))
1271 continue;
1272 if (NodeOrder.count(SI->getSUnit()) == 0)
1273 Succs.insert(SI->getSUnit());
1274 }
1275 for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1276 PE = (*I)->Preds.end();
1277 PI != PE; ++PI) {
1278 if (PI->getKind() != SDep::Anti)
1279 continue;
1280 if (S && S->count(PI->getSUnit()) == 0)
1281 continue;
1282 if (NodeOrder.count(PI->getSUnit()) == 0)
1283 Succs.insert(PI->getSUnit());
1284 }
1285 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001286 return !Succs.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001287}
1288
1289/// Return true if there is a path from the specified node to any of the nodes
1290/// in DestNodes. Keep track and return the nodes in any path.
1291static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1292 SetVector<SUnit *> &DestNodes,
1293 SetVector<SUnit *> &Exclude,
1294 SmallPtrSet<SUnit *, 8> &Visited) {
1295 if (Cur->isBoundaryNode())
1296 return false;
1297 if (Exclude.count(Cur) != 0)
1298 return false;
1299 if (DestNodes.count(Cur) != 0)
1300 return true;
1301 if (!Visited.insert(Cur).second)
1302 return Path.count(Cur) != 0;
1303 bool FoundPath = false;
1304 for (auto &SI : Cur->Succs)
1305 FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1306 for (auto &PI : Cur->Preds)
1307 if (PI.getKind() == SDep::Anti)
1308 FoundPath |=
1309 computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1310 if (FoundPath)
1311 Path.insert(Cur);
1312 return FoundPath;
1313}
1314
1315/// Return true if Set1 is a subset of Set2.
1316template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1317 for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1318 if (Set2.count(*I) == 0)
1319 return false;
1320 return true;
1321}
1322
1323/// Compute the live-out registers for the instructions in a node-set.
1324/// The live-out registers are those that are defined in the node-set,
1325/// but not used. Except for use operands of Phis.
1326static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1327 NodeSet &NS) {
1328 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1329 MachineRegisterInfo &MRI = MF.getRegInfo();
1330 SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1331 SmallSet<unsigned, 4> Uses;
1332 for (SUnit *SU : NS) {
1333 const MachineInstr *MI = SU->getInstr();
1334 if (MI->isPHI())
1335 continue;
Matthias Braunfc371552016-10-24 21:36:43 +00001336 for (const MachineOperand &MO : MI->operands())
1337 if (MO.isReg() && MO.isUse()) {
1338 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001339 if (TargetRegisterInfo::isVirtualRegister(Reg))
1340 Uses.insert(Reg);
1341 else if (MRI.isAllocatable(Reg))
1342 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1343 Uses.insert(*Units);
1344 }
1345 }
1346 for (SUnit *SU : NS)
Matthias Braunfc371552016-10-24 21:36:43 +00001347 for (const MachineOperand &MO : SU->getInstr()->operands())
1348 if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1349 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001350 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1351 if (!Uses.count(Reg))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001352 LiveOutRegs.push_back(RegisterMaskPair(Reg,
1353 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001354 } else if (MRI.isAllocatable(Reg)) {
1355 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1356 if (!Uses.count(*Units))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001357 LiveOutRegs.push_back(RegisterMaskPair(*Units,
1358 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001359 }
1360 }
1361 RPTracker.addLiveRegs(LiveOutRegs);
1362}
1363
1364/// A heuristic to filter nodes in recurrent node-sets if the register
1365/// pressure of a set is too high.
1366void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1367 for (auto &NS : NodeSets) {
1368 // Skip small node-sets since they won't cause register pressure problems.
1369 if (NS.size() <= 2)
1370 continue;
1371 IntervalPressure RecRegPressure;
1372 RegPressureTracker RecRPTracker(RecRegPressure);
1373 RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1374 computeLiveOuts(MF, RecRPTracker, NS);
1375 RecRPTracker.closeBottom();
1376
1377 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
Fangrui Song0cac7262018-09-27 02:13:45 +00001378 llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001379 return A->NodeNum > B->NodeNum;
1380 });
1381
1382 for (auto &SU : SUnits) {
1383 // Since we're computing the register pressure for a subset of the
1384 // instructions in a block, we need to set the tracker for each
1385 // instruction in the node-set. The tracker is set to the instruction
1386 // just after the one we're interested in.
1387 MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1388 RecRPTracker.setPos(std::next(CurInstI));
1389
1390 RegPressureDelta RPDelta;
1391 ArrayRef<PressureChange> CriticalPSets;
1392 RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1393 CriticalPSets,
1394 RecRegPressure.MaxSetPressure);
1395 if (RPDelta.Excess.isValid()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001396 LLVM_DEBUG(
1397 dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1398 << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1399 << ":" << RPDelta.Excess.getUnitInc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001400 NS.setExceedPressure(SU);
1401 break;
1402 }
1403 RecRPTracker.recede();
1404 }
1405 }
1406}
1407
1408/// A heuristic to colocate node sets that have the same set of
1409/// successors.
1410void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1411 unsigned Colocate = 0;
1412 for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1413 NodeSet &N1 = NodeSets[i];
1414 SmallSetVector<SUnit *, 8> S1;
1415 if (N1.empty() || !succ_L(N1, S1))
1416 continue;
1417 for (int j = i + 1; j < e; ++j) {
1418 NodeSet &N2 = NodeSets[j];
1419 if (N1.compareRecMII(N2) != 0)
1420 continue;
1421 SmallSetVector<SUnit *, 8> S2;
1422 if (N2.empty() || !succ_L(N2, S2))
1423 continue;
1424 if (isSubset(S1, S2) && S1.size() == S2.size()) {
1425 N1.setColocate(++Colocate);
1426 N2.setColocate(Colocate);
1427 break;
1428 }
1429 }
1430 }
1431}
1432
1433/// Check if the existing node-sets are profitable. If not, then ignore the
1434/// recurrent node-sets, and attempt to schedule all nodes together. This is
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001435/// a heuristic. If the MII is large and all the recurrent node-sets are small,
1436/// then it's best to try to schedule all instructions together instead of
1437/// starting with the recurrent node-sets.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001438void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1439 // Look for loops with a large MII.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001440 if (MII < 17)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001441 return;
1442 // Check if the node-set contains only a simple add recurrence.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001443 for (auto &NS : NodeSets) {
1444 if (NS.getRecMII() > 2)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001445 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001446 if (NS.getMaxDepth() > MII)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001447 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001448 }
1449 NodeSets.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001450 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001451 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001452}
1453
1454/// Add the nodes that do not belong to a recurrence set into groups
1455/// based upon connected componenets.
1456void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1457 SetVector<SUnit *> NodesAdded;
1458 SmallPtrSet<SUnit *, 8> Visited;
1459 // Add the nodes that are on a path between the previous node sets and
1460 // the current node set.
1461 for (NodeSet &I : NodeSets) {
1462 SmallSetVector<SUnit *, 8> N;
1463 // Add the nodes from the current node set to the previous node set.
1464 if (succ_L(I, N)) {
1465 SetVector<SUnit *> Path;
1466 for (SUnit *NI : N) {
1467 Visited.clear();
1468 computePath(NI, Path, NodesAdded, I, Visited);
1469 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001470 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001471 I.insert(Path.begin(), Path.end());
1472 }
1473 // Add the nodes from the previous node set to the current node set.
1474 N.clear();
1475 if (succ_L(NodesAdded, N)) {
1476 SetVector<SUnit *> Path;
1477 for (SUnit *NI : N) {
1478 Visited.clear();
1479 computePath(NI, Path, I, NodesAdded, Visited);
1480 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001481 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001482 I.insert(Path.begin(), Path.end());
1483 }
1484 NodesAdded.insert(I.begin(), I.end());
1485 }
1486
1487 // Create a new node set with the connected nodes of any successor of a node
1488 // in a recurrent set.
1489 NodeSet NewSet;
1490 SmallSetVector<SUnit *, 8> N;
1491 if (succ_L(NodesAdded, N))
1492 for (SUnit *I : N)
1493 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001494 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001495 NodeSets.push_back(NewSet);
1496
1497 // Create a new node set with the connected nodes of any predecessor of a node
1498 // in a recurrent set.
1499 NewSet.clear();
1500 if (pred_L(NodesAdded, N))
1501 for (SUnit *I : N)
1502 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001503 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001504 NodeSets.push_back(NewSet);
1505
Hiroshi Inoue372ffa12018-04-13 11:37:06 +00001506 // Create new nodes sets with the connected nodes any remaining node that
Brendon Cahoon254f8892016-07-29 16:44:44 +00001507 // has no predecessor.
1508 for (unsigned i = 0; i < SUnits.size(); ++i) {
1509 SUnit *SU = &SUnits[i];
1510 if (NodesAdded.count(SU) == 0) {
1511 NewSet.clear();
1512 addConnectedNodes(SU, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001513 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001514 NodeSets.push_back(NewSet);
1515 }
1516 }
1517}
1518
1519/// Add the node to the set, and add all is its connected nodes to the set.
1520void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1521 SetVector<SUnit *> &NodesAdded) {
1522 NewSet.insert(SU);
1523 NodesAdded.insert(SU);
1524 for (auto &SI : SU->Succs) {
1525 SUnit *Successor = SI.getSUnit();
1526 if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1527 addConnectedNodes(Successor, NewSet, NodesAdded);
1528 }
1529 for (auto &PI : SU->Preds) {
1530 SUnit *Predecessor = PI.getSUnit();
1531 if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1532 addConnectedNodes(Predecessor, NewSet, NodesAdded);
1533 }
1534}
1535
1536/// Return true if Set1 contains elements in Set2. The elements in common
1537/// are returned in a different container.
1538static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1539 SmallSetVector<SUnit *, 8> &Result) {
1540 Result.clear();
1541 for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1542 SUnit *SU = Set1[i];
1543 if (Set2.count(SU) != 0)
1544 Result.insert(SU);
1545 }
1546 return !Result.empty();
1547}
1548
1549/// Merge the recurrence node sets that have the same initial node.
1550void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1551 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1552 ++I) {
1553 NodeSet &NI = *I;
1554 for (NodeSetType::iterator J = I + 1; J != E;) {
1555 NodeSet &NJ = *J;
1556 if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1557 if (NJ.compareRecMII(NI) > 0)
1558 NI.setRecMII(NJ.getRecMII());
1559 for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1560 ++NII)
1561 I->insert(*NII);
1562 NodeSets.erase(J);
1563 E = NodeSets.end();
1564 } else {
1565 ++J;
1566 }
1567 }
1568 }
1569}
1570
1571/// Remove nodes that have been scheduled in previous NodeSets.
1572void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1573 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1574 ++I)
1575 for (NodeSetType::iterator J = I + 1; J != E;) {
1576 J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1577
Eugene Zelenko32a40562017-09-11 23:00:48 +00001578 if (J->empty()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001579 NodeSets.erase(J);
1580 E = NodeSets.end();
1581 } else {
1582 ++J;
1583 }
1584 }
1585}
1586
Brendon Cahoon254f8892016-07-29 16:44:44 +00001587/// Compute an ordered list of the dependence graph nodes, which
1588/// indicates the order that the nodes will be scheduled. This is a
1589/// two-level algorithm. First, a partial order is created, which
1590/// consists of a list of sets ordered from highest to lowest priority.
1591void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1592 SmallSetVector<SUnit *, 8> R;
1593 NodeOrder.clear();
1594
1595 for (auto &Nodes : NodeSets) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001596 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001597 OrderKind Order;
1598 SmallSetVector<SUnit *, 8> N;
1599 if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1600 R.insert(N.begin(), N.end());
1601 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001602 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001603 } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1604 R.insert(N.begin(), N.end());
1605 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001606 LLVM_DEBUG(dbgs() << " Top down (succs) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001607 } else if (isIntersect(N, Nodes, R)) {
1608 // If some of the successors are in the existing node-set, then use the
1609 // top-down ordering.
1610 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001611 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001612 } else if (NodeSets.size() == 1) {
1613 for (auto &N : Nodes)
1614 if (N->Succs.size() == 0)
1615 R.insert(N);
1616 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001617 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001618 } else {
1619 // Find the node with the highest ASAP.
1620 SUnit *maxASAP = nullptr;
1621 for (SUnit *SU : Nodes) {
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001622 if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1623 (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001624 maxASAP = SU;
1625 }
1626 R.insert(maxASAP);
1627 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001628 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001629 }
1630
1631 while (!R.empty()) {
1632 if (Order == TopDown) {
1633 // Choose the node with the maximum height. If more than one, choose
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001634 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001635 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001636 while (!R.empty()) {
1637 SUnit *maxHeight = nullptr;
1638 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001639 if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001640 maxHeight = I;
1641 else if (getHeight(I) == getHeight(maxHeight) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001642 getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001643 maxHeight = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001644 else if (getHeight(I) == getHeight(maxHeight) &&
1645 getZeroLatencyHeight(I) ==
1646 getZeroLatencyHeight(maxHeight) &&
1647 getMOV(I) < getMOV(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001648 maxHeight = I;
1649 }
1650 NodeOrder.insert(maxHeight);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001651 LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001652 R.remove(maxHeight);
1653 for (const auto &I : maxHeight->Succs) {
1654 if (Nodes.count(I.getSUnit()) == 0)
1655 continue;
1656 if (NodeOrder.count(I.getSUnit()) != 0)
1657 continue;
1658 if (ignoreDependence(I, false))
1659 continue;
1660 R.insert(I.getSUnit());
1661 }
1662 // Back-edges are predecessors with an anti-dependence.
1663 for (const auto &I : maxHeight->Preds) {
1664 if (I.getKind() != SDep::Anti)
1665 continue;
1666 if (Nodes.count(I.getSUnit()) == 0)
1667 continue;
1668 if (NodeOrder.count(I.getSUnit()) != 0)
1669 continue;
1670 R.insert(I.getSUnit());
1671 }
1672 }
1673 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001674 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001675 SmallSetVector<SUnit *, 8> N;
1676 if (pred_L(NodeOrder, N, &Nodes))
1677 R.insert(N.begin(), N.end());
1678 } else {
1679 // Choose the node with the maximum depth. If more than one, choose
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001680 // the node with the maximum ZeroLatencyDepth. If still more than one,
1681 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001682 while (!R.empty()) {
1683 SUnit *maxDepth = nullptr;
1684 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001685 if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001686 maxDepth = I;
1687 else if (getDepth(I) == getDepth(maxDepth) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001688 getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001689 maxDepth = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001690 else if (getDepth(I) == getDepth(maxDepth) &&
1691 getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
1692 getMOV(I) < getMOV(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001693 maxDepth = I;
1694 }
1695 NodeOrder.insert(maxDepth);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001696 LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001697 R.remove(maxDepth);
1698 if (Nodes.isExceedSU(maxDepth)) {
1699 Order = TopDown;
1700 R.clear();
1701 R.insert(Nodes.getNode(0));
1702 break;
1703 }
1704 for (const auto &I : maxDepth->Preds) {
1705 if (Nodes.count(I.getSUnit()) == 0)
1706 continue;
1707 if (NodeOrder.count(I.getSUnit()) != 0)
1708 continue;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001709 R.insert(I.getSUnit());
1710 }
1711 // Back-edges are predecessors with an anti-dependence.
1712 for (const auto &I : maxDepth->Succs) {
1713 if (I.getKind() != SDep::Anti)
1714 continue;
1715 if (Nodes.count(I.getSUnit()) == 0)
1716 continue;
1717 if (NodeOrder.count(I.getSUnit()) != 0)
1718 continue;
1719 R.insert(I.getSUnit());
1720 }
1721 }
1722 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001723 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001724 SmallSetVector<SUnit *, 8> N;
1725 if (succ_L(NodeOrder, N, &Nodes))
1726 R.insert(N.begin(), N.end());
1727 }
1728 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001729 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001730 }
1731
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001732 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001733 dbgs() << "Node order: ";
1734 for (SUnit *I : NodeOrder)
1735 dbgs() << " " << I->NodeNum << " ";
1736 dbgs() << "\n";
1737 });
1738}
1739
1740/// Process the nodes in the computed order and create the pipelined schedule
1741/// of the instructions, if possible. Return true if a schedule is found.
1742bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
Eugene Zelenko32a40562017-09-11 23:00:48 +00001743 if (NodeOrder.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001744 return false;
1745
1746 bool scheduleFound = false;
1747 // Keep increasing II until a valid schedule is found.
1748 for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) {
1749 Schedule.reset();
1750 Schedule.setInitiationInterval(II);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001751 LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001752
1753 SetVector<SUnit *>::iterator NI = NodeOrder.begin();
1754 SetVector<SUnit *>::iterator NE = NodeOrder.end();
1755 do {
1756 SUnit *SU = *NI;
1757
1758 // Compute the schedule time for the instruction, which is based
1759 // upon the scheduled time for any predecessors/successors.
1760 int EarlyStart = INT_MIN;
1761 int LateStart = INT_MAX;
1762 // These values are set when the size of the schedule window is limited
1763 // due to chain dependences.
1764 int SchedEnd = INT_MAX;
1765 int SchedStart = INT_MIN;
1766 Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1767 II, this);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001768 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001769 dbgs() << "Inst (" << SU->NodeNum << ") ";
1770 SU->getInstr()->dump();
1771 dbgs() << "\n";
1772 });
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001773 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001774 dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart
1775 << " me: " << SchedEnd << " ms: " << SchedStart << "\n";
1776 });
1777
1778 if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
1779 SchedStart > LateStart)
1780 scheduleFound = false;
1781 else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
1782 SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
1783 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1784 } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
1785 SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
1786 scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
1787 } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
1788 SchedEnd =
1789 std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
1790 // When scheduling a Phi it is better to start at the late cycle and go
1791 // backwards. The default order may insert the Phi too far away from
1792 // its first dependence.
1793 if (SU->getInstr()->isPHI())
1794 scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
1795 else
1796 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1797 } else {
1798 int FirstCycle = Schedule.getFirstCycle();
1799 scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
1800 FirstCycle + getASAP(SU) + II - 1, II);
1801 }
1802 // Even if we find a schedule, make sure the schedule doesn't exceed the
1803 // allowable number of stages. We keep trying if this happens.
1804 if (scheduleFound)
1805 if (SwpMaxStages > -1 &&
1806 Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
1807 scheduleFound = false;
1808
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001809 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001810 if (!scheduleFound)
1811 dbgs() << "\tCan't schedule\n";
1812 });
1813 } while (++NI != NE && scheduleFound);
1814
1815 // If a schedule is found, check if it is a valid schedule too.
1816 if (scheduleFound)
1817 scheduleFound = Schedule.isValidSchedule(this);
1818 }
1819
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001820 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001821
1822 if (scheduleFound)
1823 Schedule.finalizeSchedule(this);
1824 else
1825 Schedule.reset();
1826
1827 return scheduleFound && Schedule.getMaxStageCount() > 0;
1828}
1829
1830/// Given a schedule for the loop, generate a new version of the loop,
1831/// and replace the old version. This function generates a prolog
1832/// that contains the initial iterations in the pipeline, and kernel
1833/// loop, and the epilogue that contains the code for the final
1834/// iterations.
1835void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
1836 // Create a new basic block for the kernel and add it to the CFG.
1837 MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
1838
1839 unsigned MaxStageCount = Schedule.getMaxStageCount();
1840
1841 // Remember the registers that are used in different stages. The index is
1842 // the iteration, or stage, that the instruction is scheduled in. This is
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001843 // a map between register names in the original block and the names created
Brendon Cahoon254f8892016-07-29 16:44:44 +00001844 // in each stage of the pipelined loop.
1845 ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
1846 InstrMapTy InstrMap;
1847
1848 SmallVector<MachineBasicBlock *, 4> PrologBBs;
1849 // Generate the prolog instructions that set up the pipeline.
1850 generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
1851 MF.insert(BB->getIterator(), KernelBB);
1852
1853 // Rearrange the instructions to generate the new, pipelined loop,
1854 // and update register names as needed.
1855 for (int Cycle = Schedule.getFirstCycle(),
1856 LastCycle = Schedule.getFinalCycle();
1857 Cycle <= LastCycle; ++Cycle) {
1858 std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
1859 // This inner loop schedules each instruction in the cycle.
1860 for (SUnit *CI : CycleInstrs) {
1861 if (CI->getInstr()->isPHI())
1862 continue;
1863 unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
1864 MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
1865 updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
1866 KernelBB->push_back(NewMI);
1867 InstrMap[NewMI] = CI->getInstr();
1868 }
1869 }
1870
1871 // Copy any terminator instructions to the new kernel, and update
1872 // names as needed.
1873 for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
1874 E = BB->instr_end();
1875 I != E; ++I) {
1876 MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
1877 updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
1878 KernelBB->push_back(NewMI);
1879 InstrMap[NewMI] = &*I;
1880 }
1881
1882 KernelBB->transferSuccessors(BB);
1883 KernelBB->replaceSuccessor(BB, KernelBB);
1884
1885 generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
1886 VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
1887 generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
1888 InstrMap, MaxStageCount, MaxStageCount, false);
1889
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001890 LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00001891
1892 SmallVector<MachineBasicBlock *, 4> EpilogBBs;
1893 // Generate the epilog instructions to complete the pipeline.
1894 generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
1895 PrologBBs);
1896
1897 // We need this step because the register allocation doesn't handle some
1898 // situations well, so we insert copies to help out.
1899 splitLifetimes(KernelBB, EpilogBBs, Schedule);
1900
1901 // Remove dead instructions due to loop induction variables.
1902 removeDeadInstructions(KernelBB, EpilogBBs);
1903
1904 // Add branches between prolog and epilog blocks.
1905 addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
1906
1907 // Remove the original loop since it's no longer referenced.
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001908 for (auto &I : *BB)
1909 LIS.RemoveMachineInstrFromMaps(I);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001910 BB->clear();
1911 BB->eraseFromParent();
1912
1913 delete[] VRMap;
1914}
1915
1916/// Generate the pipeline prolog code.
1917void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
1918 MachineBasicBlock *KernelBB,
1919 ValueMapTy *VRMap,
1920 MBBVectorTy &PrologBBs) {
1921 MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
Eugene Zelenko32a40562017-09-11 23:00:48 +00001922 assert(PreheaderBB != nullptr &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00001923 "Need to add code to handle loops w/o preheader");
1924 MachineBasicBlock *PredBB = PreheaderBB;
1925 InstrMapTy InstrMap;
1926
1927 // Generate a basic block for each stage, not including the last stage,
1928 // which will be generated in the kernel. Each basic block may contain
1929 // instructions from multiple stages/iterations.
1930 for (unsigned i = 0; i < LastStage; ++i) {
1931 // Create and insert the prolog basic block prior to the original loop
1932 // basic block. The original loop is removed later.
1933 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
1934 PrologBBs.push_back(NewBB);
1935 MF.insert(BB->getIterator(), NewBB);
1936 NewBB->transferSuccessors(PredBB);
1937 PredBB->addSuccessor(NewBB);
1938 PredBB = NewBB;
1939
1940 // Generate instructions for each appropriate stage. Process instructions
1941 // in original program order.
1942 for (int StageNum = i; StageNum >= 0; --StageNum) {
1943 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
1944 BBE = BB->getFirstTerminator();
1945 BBI != BBE; ++BBI) {
1946 if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
1947 if (BBI->isPHI())
1948 continue;
1949 MachineInstr *NewMI =
1950 cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
1951 updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
1952 VRMap);
1953 NewBB->push_back(NewMI);
1954 InstrMap[NewMI] = &*BBI;
1955 }
1956 }
1957 }
1958 rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001959 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001960 dbgs() << "prolog:\n";
1961 NewBB->dump();
1962 });
1963 }
1964
1965 PredBB->replaceSuccessor(BB, KernelBB);
1966
1967 // Check if we need to remove the branch from the preheader to the original
1968 // loop, and replace it with a branch to the new loop.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001969 unsigned numBranches = TII->removeBranch(*PreheaderBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001970 if (numBranches) {
1971 SmallVector<MachineOperand, 0> Cond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001972 TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001973 }
1974}
1975
1976/// Generate the pipeline epilog code. The epilog code finishes the iterations
1977/// that were started in either the prolog or the kernel. We create a basic
1978/// block for each stage that needs to complete.
1979void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
1980 MachineBasicBlock *KernelBB,
1981 ValueMapTy *VRMap,
1982 MBBVectorTy &EpilogBBs,
1983 MBBVectorTy &PrologBBs) {
1984 // We need to change the branch from the kernel to the first epilog block, so
1985 // this call to analyze branch uses the kernel rather than the original BB.
1986 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1987 SmallVector<MachineOperand, 4> Cond;
1988 bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
1989 assert(!checkBranch && "generateEpilog must be able to analyze the branch");
1990 if (checkBranch)
1991 return;
1992
1993 MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
1994 if (*LoopExitI == KernelBB)
1995 ++LoopExitI;
1996 assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
1997 MachineBasicBlock *LoopExitBB = *LoopExitI;
1998
1999 MachineBasicBlock *PredBB = KernelBB;
2000 MachineBasicBlock *EpilogStart = LoopExitBB;
2001 InstrMapTy InstrMap;
2002
2003 // Generate a basic block for each stage, not including the last stage,
2004 // which was generated for the kernel. Each basic block may contain
2005 // instructions from multiple stages/iterations.
2006 int EpilogStage = LastStage + 1;
2007 for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2008 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2009 EpilogBBs.push_back(NewBB);
2010 MF.insert(BB->getIterator(), NewBB);
2011
2012 PredBB->replaceSuccessor(LoopExitBB, NewBB);
2013 NewBB->addSuccessor(LoopExitBB);
2014
2015 if (EpilogStart == LoopExitBB)
2016 EpilogStart = NewBB;
2017
2018 // Add instructions to the epilog depending on the current block.
2019 // Process instructions in original program order.
2020 for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2021 for (auto &BBI : *BB) {
2022 if (BBI.isPHI())
2023 continue;
2024 MachineInstr *In = &BBI;
2025 if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002026 // Instructions with memoperands in the epilog are updated with
2027 // conservative values.
2028 MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002029 updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2030 NewBB->push_back(NewMI);
2031 InstrMap[NewMI] = In;
2032 }
2033 }
2034 }
2035 generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2036 VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2037 generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2038 InstrMap, LastStage, EpilogStage, i == 1);
2039 PredBB = NewBB;
2040
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002041 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002042 dbgs() << "epilog:\n";
2043 NewBB->dump();
2044 });
2045 }
2046
2047 // Fix any Phi nodes in the loop exit block.
2048 for (MachineInstr &MI : *LoopExitBB) {
2049 if (!MI.isPHI())
2050 break;
2051 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2052 MachineOperand &MO = MI.getOperand(i);
2053 if (MO.getMBB() == BB)
2054 MO.setMBB(PredBB);
2055 }
2056 }
2057
2058 // Create a branch to the new epilog from the kernel.
2059 // Remove the original branch and add a new branch to the epilog.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002060 TII->removeBranch(*KernelBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002061 TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002062 // Add a branch to the loop exit.
2063 if (EpilogBBs.size() > 0) {
2064 MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2065 SmallVector<MachineOperand, 4> Cond1;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002066 TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002067 }
2068}
2069
2070/// Replace all uses of FromReg that appear outside the specified
2071/// basic block with ToReg.
2072static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2073 MachineBasicBlock *MBB,
2074 MachineRegisterInfo &MRI,
2075 LiveIntervals &LIS) {
2076 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2077 E = MRI.use_end();
2078 I != E;) {
2079 MachineOperand &O = *I;
2080 ++I;
2081 if (O.getParent()->getParent() != MBB)
2082 O.setReg(ToReg);
2083 }
2084 if (!LIS.hasInterval(ToReg))
2085 LIS.createEmptyInterval(ToReg);
2086}
2087
2088/// Return true if the register has a use that occurs outside the
2089/// specified loop.
2090static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2091 MachineRegisterInfo &MRI) {
2092 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2093 E = MRI.use_end();
2094 I != E; ++I)
2095 if (I->getParent()->getParent() != BB)
2096 return true;
2097 return false;
2098}
2099
2100/// Generate Phis for the specific block in the generated pipelined code.
2101/// This function looks at the Phis from the original code to guide the
2102/// creation of new Phis.
2103void SwingSchedulerDAG::generateExistingPhis(
2104 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2105 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2106 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2107 bool IsLast) {
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00002108 // Compute the stage number for the initial value of the Phi, which
Brendon Cahoon254f8892016-07-29 16:44:44 +00002109 // comes from the prolog. The prolog to use depends on to which kernel/
2110 // epilog that we're adding the Phi.
2111 unsigned PrologStage = 0;
2112 unsigned PrevStage = 0;
2113 bool InKernel = (LastStageNum == CurStageNum);
2114 if (InKernel) {
2115 PrologStage = LastStageNum - 1;
2116 PrevStage = CurStageNum;
2117 } else {
2118 PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2119 PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2120 }
2121
2122 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2123 BBE = BB->getFirstNonPHI();
2124 BBI != BBE; ++BBI) {
2125 unsigned Def = BBI->getOperand(0).getReg();
2126
2127 unsigned InitVal = 0;
2128 unsigned LoopVal = 0;
2129 getPhiRegs(*BBI, BB, InitVal, LoopVal);
2130
2131 unsigned PhiOp1 = 0;
2132 // The Phi value from the loop body typically is defined in the loop, but
2133 // not always. So, we need to check if the value is defined in the loop.
2134 unsigned PhiOp2 = LoopVal;
2135 if (VRMap[LastStageNum].count(LoopVal))
2136 PhiOp2 = VRMap[LastStageNum][LoopVal];
2137
2138 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2139 int LoopValStage =
2140 Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2141 unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2142 if (NumStages == 0) {
2143 // We don't need to generate a Phi anymore, but we need to rename any uses
2144 // of the Phi value.
2145 unsigned NewReg = VRMap[PrevStage][LoopVal];
2146 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
Krzysztof Parzyszek16e66f52018-03-26 16:41:36 +00002147 Def, InitVal, NewReg);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002148 if (VRMap[CurStageNum].count(LoopVal))
2149 VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2150 }
2151 // Adjust the number of Phis needed depending on the number of prologs left,
Krzysztof Parzyszek3f72a6b2018-03-26 16:37:55 +00002152 // and the distance from where the Phi is first scheduled. The number of
2153 // Phis cannot exceed the number of prolog stages. Each stage can
2154 // potentially define two values.
2155 unsigned MaxPhis = PrologStage + 2;
2156 if (!InKernel && (int)PrologStage <= LoopValStage)
2157 MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
2158 unsigned NumPhis = std::min(NumStages, MaxPhis);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002159
2160 unsigned NewReg = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002161 unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2162 // In the epilog, we may need to look back one stage to get the correct
2163 // Phi name because the epilog and prolog blocks execute the same stage.
2164 // The correct name is from the previous block only when the Phi has
2165 // been completely scheduled prior to the epilog, and Phi value is not
2166 // needed in multiple stages.
2167 int StageDiff = 0;
2168 if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2169 NumPhis == 1)
2170 StageDiff = 1;
2171 // Adjust the computations below when the phi and the loop definition
2172 // are scheduled in different stages.
2173 if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2174 StageDiff = StageScheduled - LoopValStage;
2175 for (unsigned np = 0; np < NumPhis; ++np) {
2176 // If the Phi hasn't been scheduled, then use the initial Phi operand
2177 // value. Otherwise, use the scheduled version of the instruction. This
2178 // is a little complicated when a Phi references another Phi.
2179 if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2180 PhiOp1 = InitVal;
2181 // Check if the Phi has already been scheduled in a prolog stage.
2182 else if (PrologStage >= AccessStage + StageDiff + np &&
2183 VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2184 PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
2185 // Check if the Phi has already been scheduled, but the loop intruction
2186 // is either another Phi, or doesn't occur in the loop.
2187 else if (PrologStage >= AccessStage + StageDiff + np) {
2188 // If the Phi references another Phi, we need to examine the other
2189 // Phi to get the correct value.
2190 PhiOp1 = LoopVal;
2191 MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2192 int Indirects = 1;
2193 while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2194 int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2195 if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2196 PhiOp1 = getInitPhiReg(*InstOp1, BB);
2197 else
2198 PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2199 InstOp1 = MRI.getVRegDef(PhiOp1);
2200 int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2201 int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2202 if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2203 VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2204 PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2205 break;
2206 }
2207 ++Indirects;
2208 }
2209 } else
2210 PhiOp1 = InitVal;
2211 // If this references a generated Phi in the kernel, get the Phi operand
2212 // from the incoming block.
2213 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2214 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2215 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2216
2217 MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2218 bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2219 // In the epilog, a map lookup is needed to get the value from the kernel,
2220 // or previous epilog block. How is does this depends on if the
2221 // instruction is scheduled in the previous block.
2222 if (!InKernel) {
2223 int StageDiffAdj = 0;
2224 if (LoopValStage != -1 && StageScheduled > LoopValStage)
2225 StageDiffAdj = StageScheduled - LoopValStage;
2226 // Use the loop value defined in the kernel, unless the kernel
2227 // contains the last definition of the Phi.
2228 if (np == 0 && PrevStage == LastStageNum &&
2229 (StageScheduled != 0 || LoopValStage != 0) &&
2230 VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2231 PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2232 // Use the value defined by the Phi. We add one because we switch
2233 // from looking at the loop value to the Phi definition.
2234 else if (np > 0 && PrevStage == LastStageNum &&
2235 VRMap[PrevStage - np + 1].count(Def))
2236 PhiOp2 = VRMap[PrevStage - np + 1][Def];
2237 // Use the loop value defined in the kernel.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002238 else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002239 VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2240 PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2241 // Use the value defined by the Phi, unless we're generating the first
2242 // epilog and the Phi refers to a Phi in a different stage.
2243 else if (VRMap[PrevStage - np].count(Def) &&
2244 (!LoopDefIsPhi || PrevStage != LastStageNum))
2245 PhiOp2 = VRMap[PrevStage - np][Def];
2246 }
2247
2248 // Check if we can reuse an existing Phi. This occurs when a Phi
2249 // references another Phi, and the other Phi is scheduled in an
2250 // earlier stage. We can try to reuse an existing Phi up until the last
2251 // stage of the current Phi.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002252 if (LoopDefIsPhi) {
2253 if (static_cast<int>(PrologStage - np) >= StageScheduled) {
2254 int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2255 int StageDiff = (StageScheduled - LoopValStage);
2256 LVNumStages -= StageDiff;
2257 // Make sure the loop value Phi has been processed already.
2258 if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
2259 NewReg = PhiOp2;
2260 unsigned ReuseStage = CurStageNum;
2261 if (Schedule.isLoopCarried(this, *PhiInst))
2262 ReuseStage -= LVNumStages;
2263 // Check if the Phi to reuse has been generated yet. If not, then
2264 // there is nothing to reuse.
2265 if (VRMap[ReuseStage - np].count(LoopVal)) {
2266 NewReg = VRMap[ReuseStage - np][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002267
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002268 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2269 &*BBI, Def, NewReg);
2270 // Update the map with the new Phi name.
2271 VRMap[CurStageNum - np][Def] = NewReg;
2272 PhiOp2 = NewReg;
2273 if (VRMap[LastStageNum - np - 1].count(LoopVal))
2274 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002275
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002276 if (IsLast && np == NumPhis - 1)
2277 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2278 continue;
2279 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002280 }
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002281 }
2282 if (InKernel && StageDiff > 0 &&
2283 VRMap[CurStageNum - StageDiff - np].count(LoopVal))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002284 PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2285 }
2286
2287 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2288 NewReg = MRI.createVirtualRegister(RC);
2289
2290 MachineInstrBuilder NewPhi =
2291 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2292 TII->get(TargetOpcode::PHI), NewReg);
2293 NewPhi.addReg(PhiOp1).addMBB(BB1);
2294 NewPhi.addReg(PhiOp2).addMBB(BB2);
2295 if (np == 0)
2296 InstrMap[NewPhi] = &*BBI;
2297
2298 // We define the Phis after creating the new pipelined code, so
2299 // we need to rename the Phi values in scheduled instructions.
2300
2301 unsigned PrevReg = 0;
2302 if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2303 PrevReg = VRMap[PrevStage - np][LoopVal];
2304 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2305 Def, NewReg, PrevReg);
2306 // If the Phi has been scheduled, use the new name for rewriting.
2307 if (VRMap[CurStageNum - np].count(Def)) {
2308 unsigned R = VRMap[CurStageNum - np][Def];
2309 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2310 R, NewReg);
2311 }
2312
2313 // Check if we need to rename any uses that occurs after the loop. The
2314 // register to replace depends on whether the Phi is scheduled in the
2315 // epilog.
2316 if (IsLast && np == NumPhis - 1)
2317 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2318
2319 // In the kernel, a dependent Phi uses the value from this Phi.
2320 if (InKernel)
2321 PhiOp2 = NewReg;
2322
2323 // Update the map with the new Phi name.
2324 VRMap[CurStageNum - np][Def] = NewReg;
2325 }
2326
2327 while (NumPhis++ < NumStages) {
2328 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2329 &*BBI, Def, NewReg, 0);
2330 }
2331
2332 // Check if we need to rename a Phi that has been eliminated due to
2333 // scheduling.
2334 if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2335 replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2336 }
2337}
2338
2339/// Generate Phis for the specified block in the generated pipelined code.
2340/// These are new Phis needed because the definition is scheduled after the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002341/// use in the pipelined sequence.
Brendon Cahoon254f8892016-07-29 16:44:44 +00002342void SwingSchedulerDAG::generatePhis(
2343 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2344 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2345 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2346 bool IsLast) {
2347 // Compute the stage number that contains the initial Phi value, and
2348 // the Phi from the previous stage.
2349 unsigned PrologStage = 0;
2350 unsigned PrevStage = 0;
2351 unsigned StageDiff = CurStageNum - LastStageNum;
2352 bool InKernel = (StageDiff == 0);
2353 if (InKernel) {
2354 PrologStage = LastStageNum - 1;
2355 PrevStage = CurStageNum;
2356 } else {
2357 PrologStage = LastStageNum - StageDiff;
2358 PrevStage = LastStageNum + StageDiff - 1;
2359 }
2360
2361 for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2362 BBE = BB->instr_end();
2363 BBI != BBE; ++BBI) {
2364 for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2365 MachineOperand &MO = BBI->getOperand(i);
2366 if (!MO.isReg() || !MO.isDef() ||
2367 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2368 continue;
2369
2370 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2371 assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2372 unsigned Def = MO.getReg();
2373 unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2374 // An instruction scheduled in stage 0 and is used after the loop
2375 // requires a phi in the epilog for the last definition from either
2376 // the kernel or prolog.
2377 if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2378 hasUseAfterLoop(Def, BB, MRI))
2379 NumPhis = 1;
2380 if (!InKernel && (unsigned)StageScheduled > PrologStage)
2381 continue;
2382
2383 unsigned PhiOp2 = VRMap[PrevStage][Def];
2384 if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2385 if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2386 PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2387 // The number of Phis can't exceed the number of prolog stages. The
2388 // prolog stage number is zero based.
2389 if (NumPhis > PrologStage + 1 - StageScheduled)
2390 NumPhis = PrologStage + 1 - StageScheduled;
2391 for (unsigned np = 0; np < NumPhis; ++np) {
2392 unsigned PhiOp1 = VRMap[PrologStage][Def];
2393 if (np <= PrologStage)
2394 PhiOp1 = VRMap[PrologStage - np][Def];
2395 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2396 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2397 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2398 if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2399 PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2400 }
2401 if (!InKernel)
2402 PhiOp2 = VRMap[PrevStage - np][Def];
2403
2404 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2405 unsigned NewReg = MRI.createVirtualRegister(RC);
2406
2407 MachineInstrBuilder NewPhi =
2408 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2409 TII->get(TargetOpcode::PHI), NewReg);
2410 NewPhi.addReg(PhiOp1).addMBB(BB1);
2411 NewPhi.addReg(PhiOp2).addMBB(BB2);
2412 if (np == 0)
2413 InstrMap[NewPhi] = &*BBI;
2414
2415 // Rewrite uses and update the map. The actions depend upon whether
2416 // we generating code for the kernel or epilog blocks.
2417 if (InKernel) {
2418 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2419 &*BBI, PhiOp1, NewReg);
2420 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2421 &*BBI, PhiOp2, NewReg);
2422
2423 PhiOp2 = NewReg;
2424 VRMap[PrevStage - np - 1][Def] = NewReg;
2425 } else {
2426 VRMap[CurStageNum - np][Def] = NewReg;
2427 if (np == NumPhis - 1)
2428 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2429 &*BBI, Def, NewReg);
2430 }
2431 if (IsLast && np == NumPhis - 1)
2432 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2433 }
2434 }
2435 }
2436}
2437
2438/// Remove instructions that generate values with no uses.
2439/// Typically, these are induction variable operations that generate values
2440/// used in the loop itself. A dead instruction has a definition with
2441/// no uses, or uses that occur in the original loop only.
2442void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2443 MBBVectorTy &EpilogBBs) {
2444 // For each epilog block, check that the value defined by each instruction
2445 // is used. If not, delete it.
2446 for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2447 MBE = EpilogBBs.rend();
2448 MBB != MBE; ++MBB)
2449 for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2450 ME = (*MBB)->instr_rend();
2451 MI != ME;) {
2452 // From DeadMachineInstructionElem. Don't delete inline assembly.
2453 if (MI->isInlineAsm()) {
2454 ++MI;
2455 continue;
2456 }
2457 bool SawStore = false;
2458 // Check if it's safe to remove the instruction due to side effects.
2459 // We can, and want to, remove Phis here.
2460 if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2461 ++MI;
2462 continue;
2463 }
2464 bool used = true;
2465 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2466 MOE = MI->operands_end();
2467 MOI != MOE; ++MOI) {
2468 if (!MOI->isReg() || !MOI->isDef())
2469 continue;
2470 unsigned reg = MOI->getReg();
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00002471 // Assume physical registers are used, unless they are marked dead.
2472 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
2473 used = !MOI->isDead();
2474 if (used)
2475 break;
2476 continue;
2477 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002478 unsigned realUses = 0;
2479 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2480 EI = MRI.use_end();
2481 UI != EI; ++UI) {
2482 // Check if there are any uses that occur only in the original
2483 // loop. If so, that's not a real use.
2484 if (UI->getParent()->getParent() != BB) {
2485 realUses++;
2486 used = true;
2487 break;
2488 }
2489 }
2490 if (realUses > 0)
2491 break;
2492 used = false;
2493 }
2494 if (!used) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002495 LIS.RemoveMachineInstrFromMaps(*MI);
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002496 MI++->eraseFromParent();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002497 continue;
2498 }
2499 ++MI;
2500 }
2501 // In the kernel block, check if we can remove a Phi that generates a value
2502 // used in an instruction removed in the epilog block.
2503 for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2504 BBE = KernelBB->getFirstNonPHI();
2505 BBI != BBE;) {
2506 MachineInstr *MI = &*BBI;
2507 ++BBI;
2508 unsigned reg = MI->getOperand(0).getReg();
2509 if (MRI.use_begin(reg) == MRI.use_end()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002510 LIS.RemoveMachineInstrFromMaps(*MI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002511 MI->eraseFromParent();
2512 }
2513 }
2514}
2515
2516/// For loop carried definitions, we split the lifetime of a virtual register
2517/// that has uses past the definition in the next iteration. A copy with a new
2518/// virtual register is inserted before the definition, which helps with
2519/// generating a better register assignment.
2520///
2521/// v1 = phi(a, v2) v1 = phi(a, v2)
2522/// v2 = phi(b, v3) v2 = phi(b, v3)
2523/// v3 = .. v4 = copy v1
2524/// .. = V1 v3 = ..
2525/// .. = v4
2526void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
2527 MBBVectorTy &EpilogBBs,
2528 SMSchedule &Schedule) {
2529 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bob Wilson90ecac02018-01-04 02:58:15 +00002530 for (auto &PHI : KernelBB->phis()) {
2531 unsigned Def = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002532 // Check for any Phi definition that used as an operand of another Phi
2533 // in the same block.
2534 for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
2535 E = MRI.use_instr_end();
2536 I != E; ++I) {
2537 if (I->isPHI() && I->getParent() == KernelBB) {
2538 // Get the loop carried definition.
Bob Wilson90ecac02018-01-04 02:58:15 +00002539 unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002540 if (!LCDef)
2541 continue;
2542 MachineInstr *MI = MRI.getVRegDef(LCDef);
2543 if (!MI || MI->getParent() != KernelBB || MI->isPHI())
2544 continue;
2545 // Search through the rest of the block looking for uses of the Phi
2546 // definition. If one occurs, then split the lifetime.
2547 unsigned SplitReg = 0;
2548 for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
2549 KernelBB->instr_end()))
2550 if (BBJ.readsRegister(Def)) {
2551 // We split the lifetime when we find the first use.
2552 if (SplitReg == 0) {
2553 SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
2554 BuildMI(*KernelBB, MI, MI->getDebugLoc(),
2555 TII->get(TargetOpcode::COPY), SplitReg)
2556 .addReg(Def);
2557 }
2558 BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
2559 }
2560 if (!SplitReg)
2561 continue;
2562 // Search through each of the epilog blocks for any uses to be renamed.
2563 for (auto &Epilog : EpilogBBs)
2564 for (auto &I : *Epilog)
2565 if (I.readsRegister(Def))
2566 I.substituteRegister(Def, SplitReg, 0, *TRI);
2567 break;
2568 }
2569 }
2570 }
2571}
2572
2573/// Remove the incoming block from the Phis in a basic block.
2574static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
2575 for (MachineInstr &MI : *BB) {
2576 if (!MI.isPHI())
2577 break;
2578 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
2579 if (MI.getOperand(i + 1).getMBB() == Incoming) {
2580 MI.RemoveOperand(i + 1);
2581 MI.RemoveOperand(i);
2582 break;
2583 }
2584 }
2585}
2586
2587/// Create branches from each prolog basic block to the appropriate epilog
2588/// block. These edges are needed if the loop ends before reaching the
2589/// kernel.
2590void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
2591 MachineBasicBlock *KernelBB,
2592 MBBVectorTy &EpilogBBs,
2593 SMSchedule &Schedule, ValueMapTy *VRMap) {
2594 assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
2595 MachineInstr *IndVar = Pass.LI.LoopInductionVar;
2596 MachineInstr *Cmp = Pass.LI.LoopCompare;
2597 MachineBasicBlock *LastPro = KernelBB;
2598 MachineBasicBlock *LastEpi = KernelBB;
2599
2600 // Start from the blocks connected to the kernel and work "out"
2601 // to the first prolog and the last epilog blocks.
2602 SmallVector<MachineInstr *, 4> PrevInsts;
2603 unsigned MaxIter = PrologBBs.size() - 1;
2604 unsigned LC = UINT_MAX;
2605 unsigned LCMin = UINT_MAX;
2606 for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
2607 // Add branches to the prolog that go to the corresponding
2608 // epilog, and the fall-thru prolog/kernel block.
2609 MachineBasicBlock *Prolog = PrologBBs[j];
2610 MachineBasicBlock *Epilog = EpilogBBs[i];
2611 // We've executed one iteration, so decrement the loop count and check for
2612 // the loop end.
2613 SmallVector<MachineOperand, 4> Cond;
2614 // Check if the LOOP0 has already been removed. If so, then there is no need
2615 // to reduce the trip count.
2616 if (LC != 0)
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002617 LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j,
Brendon Cahoon254f8892016-07-29 16:44:44 +00002618 MaxIter);
2619
2620 // Record the value of the first trip count, which is used to determine if
2621 // branches and blocks can be removed for constant trip counts.
2622 if (LCMin == UINT_MAX)
2623 LCMin = LC;
2624
2625 unsigned numAdded = 0;
2626 if (TargetRegisterInfo::isVirtualRegister(LC)) {
2627 Prolog->addSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002628 numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002629 } else if (j >= LCMin) {
2630 Prolog->addSuccessor(Epilog);
2631 Prolog->removeSuccessor(LastPro);
2632 LastEpi->removeSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002633 numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002634 removePhis(Epilog, LastEpi);
2635 // Remove the blocks that are no longer referenced.
2636 if (LastPro != LastEpi) {
2637 LastEpi->clear();
2638 LastEpi->eraseFromParent();
2639 }
2640 LastPro->clear();
2641 LastPro->eraseFromParent();
2642 } else {
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002643 numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002644 removePhis(Epilog, Prolog);
2645 }
2646 LastPro = Prolog;
2647 LastEpi = Epilog;
2648 for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
2649 E = Prolog->instr_rend();
2650 I != E && numAdded > 0; ++I, --numAdded)
2651 updateInstruction(&*I, false, j, 0, Schedule, VRMap);
2652 }
2653}
2654
2655/// Return true if we can compute the amount the instruction changes
2656/// during each iteration. Set Delta to the amount of the change.
2657bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2658 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2659 unsigned BaseReg;
2660 int64_t Offset;
2661 if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
2662 return false;
2663
2664 MachineRegisterInfo &MRI = MF.getRegInfo();
2665 // Check if there is a Phi. If so, get the definition in the loop.
2666 MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2667 if (BaseDef && BaseDef->isPHI()) {
2668 BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2669 BaseDef = MRI.getVRegDef(BaseReg);
2670 }
2671 if (!BaseDef)
2672 return false;
2673
2674 int D = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002675 if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002676 return false;
2677
2678 Delta = D;
2679 return true;
2680}
2681
2682/// Update the memory operand with a new offset when the pipeliner
Justin Lebarcf56e922016-08-12 23:58:19 +00002683/// generates a new copy of the instruction that refers to a
Brendon Cahoon254f8892016-07-29 16:44:44 +00002684/// different memory location.
2685void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
2686 MachineInstr &OldMI, unsigned Num) {
2687 if (Num == 0)
2688 return;
2689 // If the instruction has memory operands, then adjust the offset
2690 // when the instruction appears in different stages.
Chandler Carruthc73c0302018-08-16 21:30:05 +00002691 if (NewMI.memoperands_empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00002692 return;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002693 SmallVector<MachineMemOperand *, 2> NewMMOs;
Justin Lebar0a33a7a2016-08-23 17:18:07 +00002694 for (MachineMemOperand *MMO : NewMI.memoperands()) {
Justin Lebaradbf09e2016-09-11 01:38:58 +00002695 if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) ||
2696 (!MMO->getValue())) {
Chandler Carruthc73c0302018-08-16 21:30:05 +00002697 NewMMOs.push_back(MMO);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002698 continue;
2699 }
2700 unsigned Delta;
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002701 if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002702 int64_t AdjOffset = Delta * Num;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002703 NewMMOs.push_back(
2704 MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002705 } else {
Krzysztof Parzyszekcc3f6302018-08-20 20:37:57 +00002706 NewMMOs.push_back(
2707 MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002708 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002709 }
Chandler Carruthc73c0302018-08-16 21:30:05 +00002710 NewMI.setMemRefs(MF, NewMMOs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002711}
2712
2713/// Clone the instruction for the new pipelined loop and update the
2714/// memory operands, if needed.
2715MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
2716 unsigned CurStageNum,
2717 unsigned InstStageNum) {
2718 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2719 // Check for tied operands in inline asm instructions. This should be handled
2720 // elsewhere, but I'm not sure of the best solution.
2721 if (OldMI->isInlineAsm())
2722 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
2723 const auto &MO = OldMI->getOperand(i);
2724 if (MO.isReg() && MO.isUse())
2725 break;
2726 unsigned UseIdx;
2727 if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
2728 NewMI->tieOperands(i, UseIdx);
2729 }
2730 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2731 return NewMI;
2732}
2733
2734/// Clone the instruction for the new pipelined loop. If needed, this
2735/// function updates the instruction using the values saved in the
2736/// InstrChanges structure.
2737MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
2738 unsigned CurStageNum,
2739 unsigned InstStageNum,
2740 SMSchedule &Schedule) {
2741 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2742 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2743 InstrChanges.find(getSUnit(OldMI));
2744 if (It != InstrChanges.end()) {
2745 std::pair<unsigned, int64_t> RegAndOffset = It->second;
2746 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002747 if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002748 return nullptr;
2749 int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
2750 MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
2751 if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
2752 NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
2753 NewMI->getOperand(OffsetPos).setImm(NewOffset);
2754 }
2755 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2756 return NewMI;
2757}
2758
2759/// Update the machine instruction with new virtual registers. This
2760/// function may change the defintions and/or uses.
2761void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
2762 unsigned CurStageNum,
2763 unsigned InstrStageNum,
2764 SMSchedule &Schedule,
2765 ValueMapTy *VRMap) {
2766 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
2767 MachineOperand &MO = NewMI->getOperand(i);
2768 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2769 continue;
2770 unsigned reg = MO.getReg();
2771 if (MO.isDef()) {
2772 // Create a new virtual register for the definition.
2773 const TargetRegisterClass *RC = MRI.getRegClass(reg);
2774 unsigned NewReg = MRI.createVirtualRegister(RC);
2775 MO.setReg(NewReg);
2776 VRMap[CurStageNum][reg] = NewReg;
2777 if (LastDef)
2778 replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
2779 } else if (MO.isUse()) {
2780 MachineInstr *Def = MRI.getVRegDef(reg);
2781 // Compute the stage that contains the last definition for instruction.
2782 int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
2783 unsigned StageNum = CurStageNum;
2784 if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
2785 // Compute the difference in stages between the defintion and the use.
2786 unsigned StageDiff = (InstrStageNum - DefStageNum);
2787 // Make an adjustment to get the last definition.
2788 StageNum -= StageDiff;
2789 }
2790 if (VRMap[StageNum].count(reg))
2791 MO.setReg(VRMap[StageNum][reg]);
2792 }
2793 }
2794}
2795
2796/// Return the instruction in the loop that defines the register.
2797/// If the definition is a Phi, then follow the Phi operand to
2798/// the instruction in the loop.
2799MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
2800 SmallPtrSet<MachineInstr *, 8> Visited;
2801 MachineInstr *Def = MRI.getVRegDef(Reg);
2802 while (Def->isPHI()) {
2803 if (!Visited.insert(Def).second)
2804 break;
2805 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2806 if (Def->getOperand(i + 1).getMBB() == BB) {
2807 Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2808 break;
2809 }
2810 }
2811 return Def;
2812}
2813
2814/// Return the new name for the value from the previous stage.
2815unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
2816 unsigned LoopVal, unsigned LoopStage,
2817 ValueMapTy *VRMap,
2818 MachineBasicBlock *BB) {
2819 unsigned PrevVal = 0;
2820 if (StageNum > PhiStage) {
2821 MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
2822 if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
2823 // The name is defined in the previous stage.
2824 PrevVal = VRMap[StageNum - 1][LoopVal];
2825 else if (VRMap[StageNum].count(LoopVal))
2826 // The previous name is defined in the current stage when the instruction
2827 // order is swapped.
2828 PrevVal = VRMap[StageNum][LoopVal];
Krzysztof Parzyszekdf24da22016-12-22 18:49:55 +00002829 else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002830 // The loop value hasn't yet been scheduled.
2831 PrevVal = LoopVal;
2832 else if (StageNum == PhiStage + 1)
2833 // The loop value is another phi, which has not been scheduled.
2834 PrevVal = getInitPhiReg(*LoopInst, BB);
2835 else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
2836 // The loop value is another phi, which has been scheduled.
2837 PrevVal =
2838 getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
2839 LoopStage, VRMap, BB);
2840 }
2841 return PrevVal;
2842}
2843
2844/// Rewrite the Phi values in the specified block to use the mappings
2845/// from the initial operand. Once the Phi is scheduled, we switch
2846/// to using the loop value instead of the Phi value, so those names
2847/// do not need to be rewritten.
2848void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
2849 unsigned StageNum,
2850 SMSchedule &Schedule,
2851 ValueMapTy *VRMap,
2852 InstrMapTy &InstrMap) {
Bob Wilson90ecac02018-01-04 02:58:15 +00002853 for (auto &PHI : BB->phis()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002854 unsigned InitVal = 0;
2855 unsigned LoopVal = 0;
Bob Wilson90ecac02018-01-04 02:58:15 +00002856 getPhiRegs(PHI, BB, InitVal, LoopVal);
2857 unsigned PhiDef = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002858
2859 unsigned PhiStage =
2860 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
2861 unsigned LoopStage =
2862 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2863 unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
2864 if (NumPhis > StageNum)
2865 NumPhis = StageNum;
2866 for (unsigned np = 0; np <= NumPhis; ++np) {
2867 unsigned NewVal =
2868 getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
2869 if (!NewVal)
2870 NewVal = InitVal;
Bob Wilson90ecac02018-01-04 02:58:15 +00002871 rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
Brendon Cahoon254f8892016-07-29 16:44:44 +00002872 PhiDef, NewVal);
2873 }
2874 }
2875}
2876
2877/// Rewrite a previously scheduled instruction to use the register value
2878/// from the new instruction. Make sure the instruction occurs in the
2879/// basic block, and we don't change the uses in the new instruction.
2880void SwingSchedulerDAG::rewriteScheduledInstr(
2881 MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
2882 unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
2883 unsigned NewReg, unsigned PrevReg) {
2884 bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
2885 int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
2886 // Rewrite uses that have been scheduled already to use the new
2887 // Phi register.
2888 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
2889 EI = MRI.use_end();
2890 UI != EI;) {
2891 MachineOperand &UseOp = *UI;
2892 MachineInstr *UseMI = UseOp.getParent();
2893 ++UI;
2894 if (UseMI->getParent() != BB)
2895 continue;
2896 if (UseMI->isPHI()) {
2897 if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
2898 continue;
2899 if (getLoopPhiReg(*UseMI, BB) != OldReg)
2900 continue;
2901 }
2902 InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
2903 assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
2904 SUnit *OrigMISU = getSUnit(OrigInstr->second);
2905 int StageSched = Schedule.stageScheduled(OrigMISU);
2906 int CycleSched = Schedule.cycleScheduled(OrigMISU);
2907 unsigned ReplaceReg = 0;
2908 // This is the stage for the scheduled instruction.
2909 if (StagePhi == StageSched && Phi->isPHI()) {
2910 int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
2911 if (PrevReg && InProlog)
2912 ReplaceReg = PrevReg;
2913 else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
2914 (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
2915 ReplaceReg = PrevReg;
2916 else
2917 ReplaceReg = NewReg;
2918 }
2919 // The scheduled instruction occurs before the scheduled Phi, and the
2920 // Phi is not loop carried.
2921 if (!InProlog && StagePhi + 1 == StageSched &&
2922 !Schedule.isLoopCarried(this, *Phi))
2923 ReplaceReg = NewReg;
2924 if (StagePhi > StageSched && Phi->isPHI())
2925 ReplaceReg = NewReg;
2926 if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
2927 ReplaceReg = NewReg;
2928 if (ReplaceReg) {
2929 MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
2930 UseOp.setReg(ReplaceReg);
2931 }
2932 }
2933}
2934
2935/// Check if we can change the instruction to use an offset value from the
2936/// previous iteration. If so, return true and set the base and offset values
2937/// so that we can rewrite the load, if necessary.
2938/// v1 = Phi(v0, v3)
2939/// v2 = load v1, 0
2940/// v3 = post_store v1, 4, x
2941/// This function enables the load to be rewritten as v2 = load v3, 4.
2942bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2943 unsigned &BasePos,
2944 unsigned &OffsetPos,
2945 unsigned &NewBase,
2946 int64_t &Offset) {
2947 // Get the load instruction.
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002948 if (TII->isPostIncrement(*MI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002949 return false;
2950 unsigned BasePosLd, OffsetPosLd;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002951 if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002952 return false;
2953 unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
2954
2955 // Look for the Phi instruction.
Justin Bognerfdf9bf42017-10-10 23:50:49 +00002956 MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002957 MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2958 if (!Phi || !Phi->isPHI())
2959 return false;
2960 // Get the register defined in the loop block.
2961 unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2962 if (!PrevReg)
2963 return false;
2964
2965 // Check for the post-increment load/store instruction.
2966 MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2967 if (!PrevDef || PrevDef == MI)
2968 return false;
2969
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002970 if (!TII->isPostIncrement(*PrevDef))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002971 return false;
2972
2973 unsigned BasePos1 = 0, OffsetPos1 = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002974 if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002975 return false;
2976
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00002977 // Make sure that the instructions do not access the same memory location in
2978 // the next iteration.
Brendon Cahoon254f8892016-07-29 16:44:44 +00002979 int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2980 int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00002981 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2982 NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
2983 bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
2984 MF.DeleteMachineInstr(NewMI);
2985 if (!Disjoint)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002986 return false;
2987
2988 // Set the return value once we determine that we return true.
2989 BasePos = BasePosLd;
2990 OffsetPos = OffsetPosLd;
2991 NewBase = PrevReg;
2992 Offset = StoreOffset;
2993 return true;
2994}
2995
2996/// Apply changes to the instruction if needed. The changes are need
2997/// to improve the scheduling and depend up on the final schedule.
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002998void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
2999 SMSchedule &Schedule) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003000 SUnit *SU = getSUnit(MI);
3001 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3002 InstrChanges.find(SU);
3003 if (It != InstrChanges.end()) {
3004 std::pair<unsigned, int64_t> RegAndOffset = It->second;
3005 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003006 if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003007 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003008 unsigned BaseReg = MI->getOperand(BasePos).getReg();
3009 MachineInstr *LoopDef = findDefInLoop(BaseReg);
3010 int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3011 int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3012 int BaseStageNum = Schedule.stageScheduled(SU);
3013 int BaseCycleNum = Schedule.cycleScheduled(SU);
3014 if (BaseStageNum < DefStageNum) {
3015 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3016 int OffsetDiff = DefStageNum - BaseStageNum;
3017 if (DefCycleNum < BaseCycleNum) {
3018 NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3019 if (OffsetDiff > 0)
3020 --OffsetDiff;
3021 }
3022 int64_t NewOffset =
3023 MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3024 NewMI->getOperand(OffsetPos).setImm(NewOffset);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003025 SU->setInstr(NewMI);
3026 MISUnitMap[NewMI] = SU;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003027 NewMIs.insert(NewMI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003028 }
3029 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003030}
3031
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003032/// Return true for an order or output dependence that is loop carried
3033/// potentially. A dependence is loop carried if the destination defines a valu
3034/// that may be used or defined by the source in a subsequent iteration.
3035bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
3036 bool isSucc) {
3037 if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
3038 Dep.isArtificial())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003039 return false;
3040
3041 if (!SwpPruneLoopCarried)
3042 return true;
3043
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003044 if (Dep.getKind() == SDep::Output)
3045 return true;
3046
Brendon Cahoon254f8892016-07-29 16:44:44 +00003047 MachineInstr *SI = Source->getInstr();
3048 MachineInstr *DI = Dep.getSUnit()->getInstr();
3049 if (!isSucc)
3050 std::swap(SI, DI);
3051 assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3052
3053 // Assume ordered loads and stores may have a loop carried dependence.
3054 if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
3055 SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3056 return true;
3057
3058 // Only chain dependences between a load and store can be loop carried.
3059 if (!DI->mayStore() || !SI->mayLoad())
3060 return false;
3061
3062 unsigned DeltaS, DeltaD;
3063 if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3064 return true;
3065
3066 unsigned BaseRegS, BaseRegD;
3067 int64_t OffsetS, OffsetD;
3068 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3069 if (!TII->getMemOpBaseRegImmOfs(*SI, BaseRegS, OffsetS, TRI) ||
3070 !TII->getMemOpBaseRegImmOfs(*DI, BaseRegD, OffsetD, TRI))
3071 return true;
3072
3073 if (BaseRegS != BaseRegD)
3074 return true;
3075
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00003076 // Check that the base register is incremented by a constant value for each
3077 // iteration.
3078 MachineInstr *Def = MRI.getVRegDef(BaseRegS);
3079 if (!Def || !Def->isPHI())
3080 return true;
3081 unsigned InitVal = 0;
3082 unsigned LoopVal = 0;
3083 getPhiRegs(*Def, BB, InitVal, LoopVal);
3084 MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
3085 int D = 0;
3086 if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
3087 return true;
3088
Brendon Cahoon254f8892016-07-29 16:44:44 +00003089 uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3090 uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3091
3092 // This is the main test, which checks the offset values and the loop
3093 // increment value to determine if the accesses may be loop carried.
3094 if (OffsetS >= OffsetD)
3095 return OffsetS + AccessSizeS > DeltaS;
Simon Pilgrimfbfb19b2017-03-16 19:52:00 +00003096 else
Brendon Cahoon254f8892016-07-29 16:44:44 +00003097 return OffsetD + AccessSizeD > DeltaD;
3098
3099 return true;
3100}
3101
Krzysztof Parzyszek88391242016-12-22 19:21:20 +00003102void SwingSchedulerDAG::postprocessDAG() {
3103 for (auto &M : Mutations)
3104 M->apply(this);
3105}
3106
Brendon Cahoon254f8892016-07-29 16:44:44 +00003107/// Try to schedule the node at the specified StartCycle and continue
3108/// until the node is schedule or the EndCycle is reached. This function
3109/// returns true if the node is scheduled. This routine may search either
3110/// forward or backward for a place to insert the instruction based upon
3111/// the relative values of StartCycle and EndCycle.
3112bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3113 bool forward = true;
3114 if (StartCycle > EndCycle)
3115 forward = false;
3116
3117 // The terminating condition depends on the direction.
3118 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3119 for (int curCycle = StartCycle; curCycle != termCycle;
3120 forward ? ++curCycle : --curCycle) {
3121
3122 // Add the already scheduled instructions at the specified cycle to the DFA.
3123 Resources->clearResources();
3124 for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3125 checkCycle <= LastCycle; checkCycle += II) {
3126 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3127
3128 for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3129 E = cycleInstrs.end();
3130 I != E; ++I) {
3131 if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3132 continue;
3133 assert(Resources->canReserveResources(*(*I)->getInstr()) &&
3134 "These instructions have already been scheduled.");
3135 Resources->reserveResources(*(*I)->getInstr());
3136 }
3137 }
3138 if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
3139 Resources->canReserveResources(*SU->getInstr())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003140 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003141 dbgs() << "\tinsert at cycle " << curCycle << " ";
3142 SU->getInstr()->dump();
3143 });
3144
3145 ScheduledInstrs[curCycle].push_back(SU);
3146 InstrToCycle.insert(std::make_pair(SU, curCycle));
3147 if (curCycle > LastCycle)
3148 LastCycle = curCycle;
3149 if (curCycle < FirstCycle)
3150 FirstCycle = curCycle;
3151 return true;
3152 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003153 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003154 dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3155 SU->getInstr()->dump();
3156 });
3157 }
3158 return false;
3159}
3160
3161// Return the cycle of the earliest scheduled instruction in the chain.
3162int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3163 SmallPtrSet<SUnit *, 8> Visited;
3164 SmallVector<SDep, 8> Worklist;
3165 Worklist.push_back(Dep);
3166 int EarlyCycle = INT_MAX;
3167 while (!Worklist.empty()) {
3168 const SDep &Cur = Worklist.pop_back_val();
3169 SUnit *PrevSU = Cur.getSUnit();
3170 if (Visited.count(PrevSU))
3171 continue;
3172 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3173 if (it == InstrToCycle.end())
3174 continue;
3175 EarlyCycle = std::min(EarlyCycle, it->second);
3176 for (const auto &PI : PrevSU->Preds)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003177 if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003178 Worklist.push_back(PI);
3179 Visited.insert(PrevSU);
3180 }
3181 return EarlyCycle;
3182}
3183
3184// Return the cycle of the latest scheduled instruction in the chain.
3185int SMSchedule::latestCycleInChain(const SDep &Dep) {
3186 SmallPtrSet<SUnit *, 8> Visited;
3187 SmallVector<SDep, 8> Worklist;
3188 Worklist.push_back(Dep);
3189 int LateCycle = INT_MIN;
3190 while (!Worklist.empty()) {
3191 const SDep &Cur = Worklist.pop_back_val();
3192 SUnit *SuccSU = Cur.getSUnit();
3193 if (Visited.count(SuccSU))
3194 continue;
3195 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3196 if (it == InstrToCycle.end())
3197 continue;
3198 LateCycle = std::max(LateCycle, it->second);
3199 for (const auto &SI : SuccSU->Succs)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003200 if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003201 Worklist.push_back(SI);
3202 Visited.insert(SuccSU);
3203 }
3204 return LateCycle;
3205}
3206
3207/// If an instruction has a use that spans multiple iterations, then
3208/// return true. These instructions are characterized by having a back-ege
3209/// to a Phi, which contains a reference to another Phi.
3210static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3211 for (auto &P : SU->Preds)
3212 if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3213 for (auto &S : P.getSUnit()->Succs)
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00003214 if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003215 return P.getSUnit();
3216 return nullptr;
3217}
3218
3219/// Compute the scheduling start slot for the instruction. The start slot
3220/// depends on any predecessor or successor nodes scheduled already.
3221void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3222 int *MinEnd, int *MaxStart, int II,
3223 SwingSchedulerDAG *DAG) {
3224 // Iterate over each instruction that has been scheduled already. The start
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003225 // slot computation depends on whether the previously scheduled instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00003226 // is a predecessor or successor of the specified instruction.
3227 for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3228
3229 // Iterate over each instruction in the current cycle.
3230 for (SUnit *I : getInstructions(cycle)) {
3231 // Because we're processing a DAG for the dependences, we recognize
3232 // the back-edge in recurrences by anti dependences.
3233 for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3234 const SDep &Dep = SU->Preds[i];
3235 if (Dep.getSUnit() == I) {
3236 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003237 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003238 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3239 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003240 if (DAG->isLoopCarriedDep(SU, Dep, false)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003241 int End = earliestCycleInChain(Dep) + (II - 1);
3242 *MinEnd = std::min(*MinEnd, End);
3243 }
3244 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003245 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003246 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3247 *MinLateStart = std::min(*MinLateStart, LateStart);
3248 }
3249 }
3250 // For instruction that requires multiple iterations, make sure that
3251 // the dependent instruction is not scheduled past the definition.
3252 SUnit *BE = multipleIterations(I, DAG);
3253 if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3254 !SU->isPred(I))
3255 *MinLateStart = std::min(*MinLateStart, cycle);
3256 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003257 for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003258 if (SU->Succs[i].getSUnit() == I) {
3259 const SDep &Dep = SU->Succs[i];
3260 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003261 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003262 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3263 *MinLateStart = std::min(*MinLateStart, LateStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003264 if (DAG->isLoopCarriedDep(SU, Dep)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003265 int Start = latestCycleInChain(Dep) + 1 - II;
3266 *MaxStart = std::max(*MaxStart, Start);
3267 }
3268 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003269 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003270 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3271 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3272 }
3273 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003274 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003275 }
3276 }
3277}
3278
3279/// Order the instructions within a cycle so that the definitions occur
3280/// before the uses. Returns true if the instruction is added to the start
3281/// of the list, or false if added to the end.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003282void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
Brendon Cahoon254f8892016-07-29 16:44:44 +00003283 std::deque<SUnit *> &Insts) {
3284 MachineInstr *MI = SU->getInstr();
3285 bool OrderBeforeUse = false;
3286 bool OrderAfterDef = false;
3287 bool OrderBeforeDef = false;
3288 unsigned MoveDef = 0;
3289 unsigned MoveUse = 0;
3290 int StageInst1 = stageScheduled(SU);
3291
3292 unsigned Pos = 0;
3293 for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3294 ++I, ++Pos) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003295 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3296 MachineOperand &MO = MI->getOperand(i);
3297 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3298 continue;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003299
Brendon Cahoon254f8892016-07-29 16:44:44 +00003300 unsigned Reg = MO.getReg();
3301 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003302 if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003303 if (MI->getOperand(BasePos).getReg() == Reg)
3304 if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3305 Reg = NewReg;
3306 bool Reads, Writes;
3307 std::tie(Reads, Writes) =
3308 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3309 if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3310 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003311 if (MoveUse == 0)
3312 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003313 } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3314 // Add the instruction after the scheduled instruction.
3315 OrderAfterDef = true;
3316 MoveDef = Pos;
3317 } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3318 if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3319 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003320 if (MoveUse == 0)
3321 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003322 } else {
3323 OrderAfterDef = true;
3324 MoveDef = Pos;
3325 }
3326 } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3327 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003328 if (MoveUse == 0)
3329 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003330 if (MoveUse != 0) {
3331 OrderAfterDef = true;
3332 MoveDef = Pos - 1;
3333 }
3334 } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3335 // Add the instruction before the scheduled instruction.
3336 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003337 if (MoveUse == 0)
3338 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003339 } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3340 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003341 if (MoveUse == 0) {
3342 OrderBeforeDef = true;
3343 MoveUse = Pos;
3344 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003345 }
3346 }
3347 // Check for order dependences between instructions. Make sure the source
3348 // is ordered before the destination.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003349 for (auto &S : SU->Succs) {
3350 if (S.getSUnit() != *I)
3351 continue;
3352 if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3353 OrderBeforeUse = true;
3354 if (Pos < MoveUse)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003355 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003356 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003357 }
3358 for (auto &P : SU->Preds) {
3359 if (P.getSUnit() != *I)
3360 continue;
3361 if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3362 OrderAfterDef = true;
3363 MoveDef = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003364 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003365 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003366 }
3367
3368 // A circular dependence.
3369 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3370 OrderBeforeUse = false;
3371
3372 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3373 // to a loop-carried dependence.
3374 if (OrderBeforeDef)
3375 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3376
3377 // The uncommon case when the instruction order needs to be updated because
3378 // there is both a use and def.
3379 if (OrderBeforeUse && OrderAfterDef) {
3380 SUnit *UseSU = Insts.at(MoveUse);
3381 SUnit *DefSU = Insts.at(MoveDef);
3382 if (MoveUse > MoveDef) {
3383 Insts.erase(Insts.begin() + MoveUse);
3384 Insts.erase(Insts.begin() + MoveDef);
3385 } else {
3386 Insts.erase(Insts.begin() + MoveDef);
3387 Insts.erase(Insts.begin() + MoveUse);
3388 }
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003389 orderDependence(SSD, UseSU, Insts);
3390 orderDependence(SSD, SU, Insts);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003391 orderDependence(SSD, DefSU, Insts);
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003392 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003393 }
3394 // Put the new instruction first if there is a use in the list. Otherwise,
3395 // put it at the end of the list.
3396 if (OrderBeforeUse)
3397 Insts.push_front(SU);
3398 else
3399 Insts.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003400}
3401
3402/// Return true if the scheduled Phi has a loop carried operand.
3403bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3404 if (!Phi.isPHI())
3405 return false;
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003406 assert(Phi.isPHI() && "Expecting a Phi.");
Brendon Cahoon254f8892016-07-29 16:44:44 +00003407 SUnit *DefSU = SSD->getSUnit(&Phi);
3408 unsigned DefCycle = cycleScheduled(DefSU);
3409 int DefStage = stageScheduled(DefSU);
3410
3411 unsigned InitVal = 0;
3412 unsigned LoopVal = 0;
3413 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3414 SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3415 if (!UseSU)
3416 return true;
3417 if (UseSU->getInstr()->isPHI())
3418 return true;
3419 unsigned LoopCycle = cycleScheduled(UseSU);
3420 int LoopStage = stageScheduled(UseSU);
Simon Pilgrim3d8482a2016-11-14 10:40:23 +00003421 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003422}
3423
3424/// Return true if the instruction is a definition that is loop carried
3425/// and defines the use on the next iteration.
3426/// v1 = phi(v2, v3)
3427/// (Def) v3 = op v1
3428/// (MO) = v1
3429/// If MO appears before Def, then then v1 and v3 may get assigned to the same
3430/// register.
3431bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3432 MachineInstr *Def, MachineOperand &MO) {
3433 if (!MO.isReg())
3434 return false;
3435 if (Def->isPHI())
3436 return false;
3437 MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3438 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3439 return false;
3440 if (!isLoopCarried(SSD, *Phi))
3441 return false;
3442 unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3443 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3444 MachineOperand &DMO = Def->getOperand(i);
3445 if (!DMO.isReg() || !DMO.isDef())
3446 continue;
3447 if (DMO.getReg() == LoopReg)
3448 return true;
3449 }
3450 return false;
3451}
3452
3453// Check if the generated schedule is valid. This function checks if
3454// an instruction that uses a physical register is scheduled in a
3455// different stage than the definition. The pipeliner does not handle
3456// physical register values that may cross a basic block boundary.
3457bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003458 for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3459 SUnit &SU = SSD->SUnits[i];
3460 if (!SU.hasPhysRegDefs)
3461 continue;
3462 int StageDef = stageScheduled(&SU);
3463 assert(StageDef != -1 && "Instruction should have been scheduled.");
3464 for (auto &SI : SU.Succs)
3465 if (SI.isAssignedRegDep())
Simon Pilgrimb39236b2016-07-29 18:57:32 +00003466 if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003467 if (stageScheduled(SI.getSUnit()) != StageDef)
3468 return false;
3469 }
3470 return true;
3471}
3472
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003473/// A property of the node order in swing-modulo-scheduling is
3474/// that for nodes outside circuits the following holds:
3475/// none of them is scheduled after both a successor and a
3476/// predecessor.
3477/// The method below checks whether the property is met.
3478/// If not, debug information is printed and statistics information updated.
3479/// Note that we do not use an assert statement.
3480/// The reason is that although an invalid node oder may prevent
3481/// the pipeliner from finding a pipelined schedule for arbitrary II,
3482/// it does not lead to the generation of incorrect code.
3483void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3484
3485 // a sorted vector that maps each SUnit to its index in the NodeOrder
3486 typedef std::pair<SUnit *, unsigned> UnitIndex;
3487 std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3488
3489 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3490 Indices.push_back(std::make_pair(NodeOrder[i], i));
3491
3492 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3493 return std::get<0>(i1) < std::get<0>(i2);
3494 };
3495
3496 // sort, so that we can perform a binary search
Fangrui Song0cac7262018-09-27 02:13:45 +00003497 llvm::sort(Indices, CompareKey);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003498
3499 bool Valid = true;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003500 (void)Valid;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003501 // for each SUnit in the NodeOrder, check whether
3502 // it appears after both a successor and a predecessor
3503 // of the SUnit. If this is the case, and the SUnit
3504 // is not part of circuit, then the NodeOrder is not
3505 // valid.
3506 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3507 SUnit *SU = NodeOrder[i];
3508 unsigned Index = i;
3509
3510 bool PredBefore = false;
3511 bool SuccBefore = false;
3512
3513 SUnit *Succ;
3514 SUnit *Pred;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003515 (void)Succ;
3516 (void)Pred;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003517
3518 for (SDep &PredEdge : SU->Preds) {
3519 SUnit *PredSU = PredEdge.getSUnit();
3520 unsigned PredIndex =
3521 std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
3522 std::make_pair(PredSU, 0), CompareKey));
3523 if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3524 PredBefore = true;
3525 Pred = PredSU;
3526 break;
3527 }
3528 }
3529
3530 for (SDep &SuccEdge : SU->Succs) {
3531 SUnit *SuccSU = SuccEdge.getSUnit();
3532 unsigned SuccIndex =
3533 std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
3534 std::make_pair(SuccSU, 0), CompareKey));
3535 if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3536 SuccBefore = true;
3537 Succ = SuccSU;
3538 break;
3539 }
3540 }
3541
3542 if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3543 // instructions in circuits are allowed to be scheduled
3544 // after both a successor and predecessor.
3545 bool InCircuit = std::any_of(
3546 Circuits.begin(), Circuits.end(),
3547 [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
3548 if (InCircuit)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003549 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003550 else {
3551 Valid = false;
3552 NumNodeOrderIssues++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003553 LLVM_DEBUG(dbgs() << "Predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003554 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003555 LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3556 << " are scheduled before node " << SU->NodeNum
3557 << "\n";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003558 }
3559 }
3560
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003561 LLVM_DEBUG({
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003562 if (!Valid)
3563 dbgs() << "Invalid node order found!\n";
3564 });
3565}
3566
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003567/// Attempt to fix the degenerate cases when the instruction serialization
3568/// causes the register lifetimes to overlap. For example,
3569/// p' = store_pi(p, b)
3570/// = load p, offset
3571/// In this case p and p' overlap, which means that two registers are needed.
3572/// Instead, this function changes the load to use p' and updates the offset.
3573void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3574 unsigned OverlapReg = 0;
3575 unsigned NewBaseReg = 0;
3576 for (SUnit *SU : Instrs) {
3577 MachineInstr *MI = SU->getInstr();
3578 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3579 const MachineOperand &MO = MI->getOperand(i);
3580 // Look for an instruction that uses p. The instruction occurs in the
3581 // same cycle but occurs later in the serialized order.
3582 if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3583 // Check that the instruction appears in the InstrChanges structure,
3584 // which contains instructions that can have the offset updated.
3585 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3586 InstrChanges.find(SU);
3587 if (It != InstrChanges.end()) {
3588 unsigned BasePos, OffsetPos;
3589 // Update the base register and adjust the offset.
3590 if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
Krzysztof Parzyszek12bdcab2017-10-11 15:59:51 +00003591 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3592 NewMI->getOperand(BasePos).setReg(NewBaseReg);
3593 int64_t NewOffset =
3594 MI->getOperand(OffsetPos).getImm() - It->second.second;
3595 NewMI->getOperand(OffsetPos).setImm(NewOffset);
3596 SU->setInstr(NewMI);
3597 MISUnitMap[NewMI] = SU;
3598 NewMIs.insert(NewMI);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003599 }
3600 }
3601 OverlapReg = 0;
3602 NewBaseReg = 0;
3603 break;
3604 }
3605 // Look for an instruction of the form p' = op(p), which uses and defines
3606 // two virtual registers that get allocated to the same physical register.
3607 unsigned TiedUseIdx = 0;
3608 if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3609 // OverlapReg is p in the example above.
3610 OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3611 // NewBaseReg is p' in the example above.
3612 NewBaseReg = MI->getOperand(i).getReg();
3613 break;
3614 }
3615 }
3616 }
3617}
3618
Brendon Cahoon254f8892016-07-29 16:44:44 +00003619/// After the schedule has been formed, call this function to combine
3620/// the instructions from the different stages/cycles. That is, this
3621/// function creates a schedule that represents a single iteration.
3622void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3623 // Move all instructions to the first stage from later stages.
3624 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3625 for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3626 ++stage) {
3627 std::deque<SUnit *> &cycleInstrs =
3628 ScheduledInstrs[cycle + (stage * InitiationInterval)];
3629 for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
3630 E = cycleInstrs.rend();
3631 I != E; ++I)
3632 ScheduledInstrs[cycle].push_front(*I);
3633 }
3634 }
3635 // Iterate over the definitions in each instruction, and compute the
3636 // stage difference for each use. Keep the maximum value.
3637 for (auto &I : InstrToCycle) {
3638 int DefStage = stageScheduled(I.first);
3639 MachineInstr *MI = I.first->getInstr();
3640 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3641 MachineOperand &Op = MI->getOperand(i);
3642 if (!Op.isReg() || !Op.isDef())
3643 continue;
3644
3645 unsigned Reg = Op.getReg();
3646 unsigned MaxDiff = 0;
3647 bool PhiIsSwapped = false;
3648 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
3649 EI = MRI.use_end();
3650 UI != EI; ++UI) {
3651 MachineOperand &UseOp = *UI;
3652 MachineInstr *UseMI = UseOp.getParent();
3653 SUnit *SUnitUse = SSD->getSUnit(UseMI);
3654 int UseStage = stageScheduled(SUnitUse);
3655 unsigned Diff = 0;
3656 if (UseStage != -1 && UseStage >= DefStage)
3657 Diff = UseStage - DefStage;
3658 if (MI->isPHI()) {
3659 if (isLoopCarried(SSD, *MI))
3660 ++Diff;
3661 else
3662 PhiIsSwapped = true;
3663 }
3664 MaxDiff = std::max(Diff, MaxDiff);
3665 }
3666 RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
3667 }
3668 }
3669
3670 // Erase all the elements in the later stages. Only one iteration should
3671 // remain in the scheduled list, and it contains all the instructions.
3672 for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3673 ScheduledInstrs.erase(cycle);
3674
3675 // Change the registers in instruction as specified in the InstrChanges
3676 // map. We need to use the new registers to create the correct order.
3677 for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
3678 SUnit *SU = &SSD->SUnits[i];
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003679 SSD->applyInstrChange(SU->getInstr(), *this);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003680 }
3681
3682 // Reorder the instructions in each cycle to fix and improve the
3683 // generated code.
3684 for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3685 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003686 std::deque<SUnit *> newOrderPhi;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003687 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3688 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003689 if (SU->getInstr()->isPHI())
3690 newOrderPhi.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003691 }
3692 std::deque<SUnit *> newOrderI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003693 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3694 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003695 if (!SU->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003696 orderDependence(SSD, SU, newOrderI);
3697 }
3698 // Replace the old order with the new order.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003699 cycleInstrs.swap(newOrderPhi);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003700 cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003701 SSD->fixupRegisterOverlaps(cycleInstrs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003702 }
3703
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003704 LLVM_DEBUG(dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00003705}
3706
Aaron Ballman615eb472017-10-15 14:32:27 +00003707#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003708/// Print the schedule information to the given output.
3709void SMSchedule::print(raw_ostream &os) const {
3710 // Iterate over each cycle.
3711 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3712 // Iterate over each instruction in the cycle.
3713 const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3714 for (SUnit *CI : cycleInstrs->second) {
3715 os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3716 os << "(" << CI->NodeNum << ") ";
3717 CI->getInstr()->print(os);
3718 os << "\n";
3719 }
3720 }
3721}
3722
3723/// Utility function used for debugging to print the schedule.
Matthias Braun8c209aa2017-01-28 02:02:38 +00003724LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
3725#endif