blob: 2e8e8ebc629b55ec3582b0fbc8db2ebe86af048e [file] [log] [blame]
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001//===-- SIMachineScheduler.cpp - SI Scheduler Interface -------------------===//
Nicolai Haehnle02c32912016-01-13 16:10:10 +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/// \file
11/// \brief SI Machine Scheduler interface
12//
13//===----------------------------------------------------------------------===//
14
Matt Arsenault43e92fe2016-06-24 06:30:11 +000015#include "AMDGPU.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000016#include "SIInstrInfo.h"
Nicolai Haehnle02c32912016-01-13 16:10:10 +000017#include "SIMachineScheduler.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000018#include "SIRegisterInfo.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
Nicolai Haehnle02c32912016-01-13 16:10:10 +000021#include "llvm/CodeGen/LiveInterval.h"
22#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000023#include "llvm/CodeGen/MachineInstr.h"
Nicolai Haehnle02c32912016-01-13 16:10:10 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/MachineScheduler.h"
26#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000027#include "llvm/CodeGen/SlotIndexes.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Target/TargetRegisterInfo.h"
32#include <algorithm>
33#include <cassert>
34#include <map>
35#include <set>
36#include <utility>
37#include <vector>
Nicolai Haehnle02c32912016-01-13 16:10:10 +000038
39using namespace llvm;
40
41#define DEBUG_TYPE "misched"
42
43// This scheduler implements a different scheduling algorithm than
44// GenericScheduler.
45//
46// There are several specific architecture behaviours that can't be modelled
47// for GenericScheduler:
48// . When accessing the result of an SGPR load instruction, you have to wait
49// for all the SGPR load instructions before your current instruction to
50// have finished.
51// . When accessing the result of an VGPR load instruction, you have to wait
52// for all the VGPR load instructions previous to the VGPR load instruction
53// you are interested in to finish.
54// . The less the register pressure, the best load latencies are hidden
55//
56// Moreover some specifities (like the fact a lot of instructions in the shader
57// have few dependencies) makes the generic scheduler have some unpredictable
58// behaviours. For example when register pressure becomes high, it can either
59// manage to prevent register pressure from going too high, or it can
60// increase register pressure even more than if it hadn't taken register
61// pressure into account.
62//
63// Also some other bad behaviours are generated, like loading at the beginning
64// of the shader a constant in VGPR you won't need until the end of the shader.
65//
66// The scheduling problem for SI can distinguish three main parts:
67// . Hiding high latencies (texture sampling, etc)
68// . Hiding low latencies (SGPR constant loading, etc)
69// . Keeping register usage low for better latency hiding and general
70// performance
71//
72// Some other things can also affect performance, but are hard to predict
73// (cache usage, the fact the HW can issue several instructions from different
74// wavefronts if different types, etc)
75//
76// This scheduler tries to solve the scheduling problem by dividing it into
77// simpler sub-problems. It divides the instructions into blocks, schedules
78// locally inside the blocks where it takes care of low latencies, and then
79// chooses the order of the blocks by taking care of high latencies.
80// Dividing the instructions into blocks helps control keeping register
81// usage low.
82//
83// First the instructions are put into blocks.
84// We want the blocks help control register usage and hide high latencies
85// later. To help control register usage, we typically want all local
86// computations, when for example you create a result that can be comsummed
87// right away, to be contained in a block. Block inputs and outputs would
88// typically be important results that are needed in several locations of
89// the shader. Since we do want blocks to help hide high latencies, we want
90// the instructions inside the block to have a minimal set of dependencies
91// on high latencies. It will make it easy to pick blocks to hide specific
92// high latencies.
93// The block creation algorithm is divided into several steps, and several
94// variants can be tried during the scheduling process.
95//
Simon Pilgrime995a8082016-11-18 11:04:02 +000096// Second the order of the instructions inside the blocks is chosen.
Nicolai Haehnle02c32912016-01-13 16:10:10 +000097// At that step we do take into account only register usage and hiding
98// low latency instructions
99//
Simon Pilgrime995a8082016-11-18 11:04:02 +0000100// Third the block order is chosen, there we try to hide high latencies
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000101// and keep register usage low.
102//
103// After the third step, a pass is done to improve the hiding of low
104// latencies.
105//
106// Actually when talking about 'low latency' or 'high latency' it includes
107// both the latency to get the cache (or global mem) data go to the register,
Simon Pilgrime995a8082016-11-18 11:04:02 +0000108// and the bandwidth limitations.
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000109// Increasing the number of active wavefronts helps hide the former, but it
110// doesn't solve the latter, thus why even if wavefront count is high, we have
111// to try have as many instructions hiding high latencies as possible.
112// The OpenCL doc says for example latency of 400 cycles for a global mem access,
113// which is hidden by 10 instructions if the wavefront count is 10.
114
115// Some figures taken from AMD docs:
116// Both texture and constant L1 caches are 4-way associative with 64 bytes
117// lines.
118// Constant cache is shared with 4 CUs.
119// For texture sampling, the address generation unit receives 4 texture
120// addresses per cycle, thus we could expect texture sampling latency to be
121// equivalent to 4 instructions in the very best case (a VGPR is 64 work items,
122// instructions in a wavefront group are executed every 4 cycles),
123// or 16 instructions if the other wavefronts associated to the 3 other VALUs
124// of the CU do texture sampling too. (Don't take these figures too seriously,
125// as I'm not 100% sure of the computation)
126// Data exports should get similar latency.
127// For constant loading, the cache is shader with 4 CUs.
128// The doc says "a throughput of 16B/cycle for each of the 4 Compute Unit"
129// I guess if the other CU don't read the cache, it can go up to 64B/cycle.
130// It means a simple s_buffer_load should take one instruction to hide, as
131// well as a s_buffer_loadx2 and potentially a s_buffer_loadx8 if on the same
132// cache line.
133//
134// As of today the driver doesn't preload the constants in cache, thus the
135// first loads get extra latency. The doc says global memory access can be
136// 300-600 cycles. We do not specially take that into account when scheduling
137// As we expect the driver to be able to preload the constants soon.
138
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000139// common code //
140
141#ifndef NDEBUG
142
143static const char *getReasonStr(SIScheduleCandReason Reason) {
144 switch (Reason) {
145 case NoCand: return "NOCAND";
146 case RegUsage: return "REGUSAGE";
147 case Latency: return "LATENCY";
148 case Successor: return "SUCCESSOR";
149 case Depth: return "DEPTH";
150 case NodeOrder: return "ORDER";
151 }
152 llvm_unreachable("Unknown reason!");
153}
154
155#endif
156
157static bool tryLess(int TryVal, int CandVal,
158 SISchedulerCandidate &TryCand,
159 SISchedulerCandidate &Cand,
160 SIScheduleCandReason Reason) {
161 if (TryVal < CandVal) {
162 TryCand.Reason = Reason;
163 return true;
164 }
165 if (TryVal > CandVal) {
166 if (Cand.Reason > Reason)
167 Cand.Reason = Reason;
168 return true;
169 }
170 Cand.setRepeat(Reason);
171 return false;
172}
173
174static bool tryGreater(int TryVal, int CandVal,
175 SISchedulerCandidate &TryCand,
176 SISchedulerCandidate &Cand,
177 SIScheduleCandReason Reason) {
178 if (TryVal > CandVal) {
179 TryCand.Reason = Reason;
180 return true;
181 }
182 if (TryVal < CandVal) {
183 if (Cand.Reason > Reason)
184 Cand.Reason = Reason;
185 return true;
186 }
187 Cand.setRepeat(Reason);
188 return false;
189}
190
191// SIScheduleBlock //
192
193void SIScheduleBlock::addUnit(SUnit *SU) {
194 NodeNum2Index[SU->NodeNum] = SUnits.size();
195 SUnits.push_back(SU);
196}
197
198#ifndef NDEBUG
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000199void SIScheduleBlock::traceCandidate(const SISchedCandidate &Cand) {
200
201 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
202 dbgs() << '\n';
203}
204#endif
205
206void SIScheduleBlock::tryCandidateTopDown(SISchedCandidate &Cand,
207 SISchedCandidate &TryCand) {
208 // Initialize the candidate if needed.
209 if (!Cand.isValid()) {
210 TryCand.Reason = NodeOrder;
211 return;
212 }
213
214 if (Cand.SGPRUsage > 60 &&
215 tryLess(TryCand.SGPRUsage, Cand.SGPRUsage, TryCand, Cand, RegUsage))
216 return;
217
218 // Schedule low latency instructions as top as possible.
219 // Order of priority is:
220 // . Low latency instructions which do not depend on other low latency
221 // instructions we haven't waited for
222 // . Other instructions which do not depend on low latency instructions
223 // we haven't waited for
224 // . Low latencies
225 // . All other instructions
Simon Pilgrime995a8082016-11-18 11:04:02 +0000226 // Goal is to get: low latency instructions - independent instructions
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000227 // - (eventually some more low latency instructions)
228 // - instructions that depend on the first low latency instructions.
229 // If in the block there is a lot of constant loads, the SGPR usage
230 // could go quite high, thus above the arbitrary limit of 60 will encourage
231 // use the already loaded constants (in order to release some SGPRs) before
232 // loading more.
233 if (tryLess(TryCand.HasLowLatencyNonWaitedParent,
234 Cand.HasLowLatencyNonWaitedParent,
235 TryCand, Cand, SIScheduleCandReason::Depth))
236 return;
237
238 if (tryGreater(TryCand.IsLowLatency, Cand.IsLowLatency,
239 TryCand, Cand, SIScheduleCandReason::Depth))
240 return;
241
242 if (TryCand.IsLowLatency &&
243 tryLess(TryCand.LowLatencyOffset, Cand.LowLatencyOffset,
244 TryCand, Cand, SIScheduleCandReason::Depth))
245 return;
246
247 if (tryLess(TryCand.VGPRUsage, Cand.VGPRUsage, TryCand, Cand, RegUsage))
248 return;
249
250 // Fall through to original instruction order.
251 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) {
252 TryCand.Reason = NodeOrder;
253 }
254}
255
256SUnit* SIScheduleBlock::pickNode() {
257 SISchedCandidate TopCand;
258
259 for (SUnit* SU : TopReadySUs) {
260 SISchedCandidate TryCand;
261 std::vector<unsigned> pressure;
262 std::vector<unsigned> MaxPressure;
263 // Predict register usage after this instruction.
264 TryCand.SU = SU;
265 TopRPTracker.getDownwardPressure(SU->getInstr(), pressure, MaxPressure);
266 TryCand.SGPRUsage = pressure[DAG->getSGPRSetID()];
267 TryCand.VGPRUsage = pressure[DAG->getVGPRSetID()];
268 TryCand.IsLowLatency = DAG->IsLowLatencySU[SU->NodeNum];
269 TryCand.LowLatencyOffset = DAG->LowLatencyOffset[SU->NodeNum];
270 TryCand.HasLowLatencyNonWaitedParent =
271 HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]];
272 tryCandidateTopDown(TopCand, TryCand);
273 if (TryCand.Reason != NoCand)
274 TopCand.setBest(TryCand);
275 }
276
277 return TopCand.SU;
278}
279
280
281// Schedule something valid.
282void SIScheduleBlock::fastSchedule() {
283 TopReadySUs.clear();
284 if (Scheduled)
285 undoSchedule();
286
287 for (SUnit* SU : SUnits) {
288 if (!SU->NumPredsLeft)
289 TopReadySUs.push_back(SU);
290 }
291
292 while (!TopReadySUs.empty()) {
293 SUnit *SU = TopReadySUs[0];
294 ScheduledSUnits.push_back(SU);
295 nodeScheduled(SU);
296 }
297
298 Scheduled = true;
299}
300
301// Returns if the register was set between first and last.
302static bool isDefBetween(unsigned Reg,
303 SlotIndex First, SlotIndex Last,
304 const MachineRegisterInfo *MRI,
305 const LiveIntervals *LIS) {
306 for (MachineRegisterInfo::def_instr_iterator
307 UI = MRI->def_instr_begin(Reg),
308 UE = MRI->def_instr_end(); UI != UE; ++UI) {
309 const MachineInstr* MI = &*UI;
310 if (MI->isDebugValue())
311 continue;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000312 SlotIndex InstSlot = LIS->getInstructionIndex(*MI).getRegSlot();
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000313 if (InstSlot >= First && InstSlot <= Last)
314 return true;
315 }
316 return false;
317}
318
319void SIScheduleBlock::initRegPressure(MachineBasicBlock::iterator BeginBlock,
320 MachineBasicBlock::iterator EndBlock) {
321 IntervalPressure Pressure, BotPressure;
322 RegPressureTracker RPTracker(Pressure), BotRPTracker(BotPressure);
323 LiveIntervals *LIS = DAG->getLIS();
324 MachineRegisterInfo *MRI = DAG->getMRI();
325 DAG->initRPTracker(TopRPTracker);
326 DAG->initRPTracker(BotRPTracker);
327 DAG->initRPTracker(RPTracker);
328
329 // Goes though all SU. RPTracker captures what had to be alive for the SUs
330 // to execute, and what is still alive at the end.
331 for (SUnit* SU : ScheduledSUnits) {
332 RPTracker.setPos(SU->getInstr());
333 RPTracker.advance();
334 }
335
336 // Close the RPTracker to finalize live ins/outs.
337 RPTracker.closeRegion();
338
339 // Initialize the live ins and live outs.
340 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
341 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
342
343 // Do not Track Physical Registers, because it messes up.
Matthias Braun5d458612016-01-20 00:23:26 +0000344 for (const auto &RegMaskPair : RPTracker.getPressure().LiveInRegs) {
345 if (TargetRegisterInfo::isVirtualRegister(RegMaskPair.RegUnit))
346 LiveInRegs.insert(RegMaskPair.RegUnit);
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000347 }
348 LiveOutRegs.clear();
349 // There is several possibilities to distinguish:
350 // 1) Reg is not input to any instruction in the block, but is output of one
351 // 2) 1) + read in the block and not needed after it
352 // 3) 1) + read in the block but needed in another block
353 // 4) Reg is input of an instruction but another block will read it too
354 // 5) Reg is input of an instruction and then rewritten in the block.
355 // result is not read in the block (implies used in another block)
356 // 6) Reg is input of an instruction and then rewritten in the block.
357 // result is read in the block and not needed in another block
358 // 7) Reg is input of an instruction and then rewritten in the block.
359 // result is read in the block but also needed in another block
360 // LiveInRegs will contains all the regs in situation 4, 5, 6, 7
361 // We want LiveOutRegs to contain only Regs whose content will be read after
362 // in another block, and whose content was written in the current block,
363 // that is we want it to get 1, 3, 5, 7
364 // Since we made the MIs of a block to be packed all together before
365 // scheduling, then the LiveIntervals were correct, and the RPTracker was
366 // able to correctly handle 5 vs 6, 2 vs 3.
367 // (Note: This is not sufficient for RPTracker to not do mistakes for case 4)
368 // The RPTracker's LiveOutRegs has 1, 3, (some correct or incorrect)4, 5, 7
369 // Comparing to LiveInRegs is not sufficient to differenciate 4 vs 5, 7
370 // The use of findDefBetween removes the case 4.
Matthias Braun5d458612016-01-20 00:23:26 +0000371 for (const auto &RegMaskPair : RPTracker.getPressure().LiveOutRegs) {
372 unsigned Reg = RegMaskPair.RegUnit;
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000373 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000374 isDefBetween(Reg, LIS->getInstructionIndex(*BeginBlock).getRegSlot(),
375 LIS->getInstructionIndex(*EndBlock).getRegSlot(), MRI,
376 LIS)) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000377 LiveOutRegs.insert(Reg);
378 }
379 }
380
381 // Pressure = sum_alive_registers register size
382 // Internally llvm will represent some registers as big 128 bits registers
383 // for example, but they actually correspond to 4 actual 32 bits registers.
384 // Thus Pressure is not equal to num_alive_registers * constant.
385 LiveInPressure = TopPressure.MaxSetPressure;
386 LiveOutPressure = BotPressure.MaxSetPressure;
387
388 // Prepares TopRPTracker for top down scheduling.
389 TopRPTracker.closeTop();
390}
391
392void SIScheduleBlock::schedule(MachineBasicBlock::iterator BeginBlock,
393 MachineBasicBlock::iterator EndBlock) {
394 if (!Scheduled)
395 fastSchedule();
396
397 // PreScheduling phase to set LiveIn and LiveOut.
398 initRegPressure(BeginBlock, EndBlock);
399 undoSchedule();
400
401 // Schedule for real now.
402
403 TopReadySUs.clear();
404
405 for (SUnit* SU : SUnits) {
406 if (!SU->NumPredsLeft)
407 TopReadySUs.push_back(SU);
408 }
409
410 while (!TopReadySUs.empty()) {
411 SUnit *SU = pickNode();
412 ScheduledSUnits.push_back(SU);
413 TopRPTracker.setPos(SU->getInstr());
414 TopRPTracker.advance();
415 nodeScheduled(SU);
416 }
417
418 // TODO: compute InternalAdditionnalPressure.
419 InternalAdditionnalPressure.resize(TopPressure.MaxSetPressure.size());
420
421 // Check everything is right.
422#ifndef NDEBUG
423 assert(SUnits.size() == ScheduledSUnits.size() &&
424 TopReadySUs.empty());
425 for (SUnit* SU : SUnits) {
426 assert(SU->isScheduled &&
427 SU->NumPredsLeft == 0);
428 }
429#endif
430
431 Scheduled = true;
432}
433
434void SIScheduleBlock::undoSchedule() {
435 for (SUnit* SU : SUnits) {
436 SU->isScheduled = false;
437 for (SDep& Succ : SU->Succs) {
438 if (BC->isSUInBlock(Succ.getSUnit(), ID))
439 undoReleaseSucc(SU, &Succ);
440 }
441 }
442 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
443 ScheduledSUnits.clear();
444 Scheduled = false;
445}
446
447void SIScheduleBlock::undoReleaseSucc(SUnit *SU, SDep *SuccEdge) {
448 SUnit *SuccSU = SuccEdge->getSUnit();
449
450 if (SuccEdge->isWeak()) {
451 ++SuccSU->WeakPredsLeft;
452 return;
453 }
454 ++SuccSU->NumPredsLeft;
455}
456
457void SIScheduleBlock::releaseSucc(SUnit *SU, SDep *SuccEdge) {
458 SUnit *SuccSU = SuccEdge->getSUnit();
459
460 if (SuccEdge->isWeak()) {
461 --SuccSU->WeakPredsLeft;
462 return;
463 }
464#ifndef NDEBUG
465 if (SuccSU->NumPredsLeft == 0) {
466 dbgs() << "*** Scheduling failed! ***\n";
467 SuccSU->dump(DAG);
468 dbgs() << " has been released too many times!\n";
469 llvm_unreachable(nullptr);
470 }
471#endif
472
473 --SuccSU->NumPredsLeft;
474}
475
476/// Release Successors of the SU that are in the block or not.
477void SIScheduleBlock::releaseSuccessors(SUnit *SU, bool InOrOutBlock) {
478 for (SDep& Succ : SU->Succs) {
479 SUnit *SuccSU = Succ.getSUnit();
480
Matt Arsenaultfe358062016-07-19 00:35:22 +0000481 if (SuccSU->NodeNum >= DAG->SUnits.size())
482 continue;
483
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000484 if (BC->isSUInBlock(SuccSU, ID) != InOrOutBlock)
485 continue;
486
487 releaseSucc(SU, &Succ);
488 if (SuccSU->NumPredsLeft == 0 && InOrOutBlock)
489 TopReadySUs.push_back(SuccSU);
490 }
491}
492
493void SIScheduleBlock::nodeScheduled(SUnit *SU) {
494 // Is in TopReadySUs
495 assert (!SU->NumPredsLeft);
Eugene Zelenko6a9226d2016-12-12 22:23:53 +0000496 std::vector<SUnit *>::iterator I = llvm::find(TopReadySUs, SU);
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000497 if (I == TopReadySUs.end()) {
498 dbgs() << "Data Structure Bug in SI Scheduler\n";
499 llvm_unreachable(nullptr);
500 }
501 TopReadySUs.erase(I);
502
503 releaseSuccessors(SU, true);
504 // Scheduling this node will trigger a wait,
505 // thus propagate to other instructions that they do not need to wait either.
506 if (HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]])
507 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
508
509 if (DAG->IsLowLatencySU[SU->NodeNum]) {
510 for (SDep& Succ : SU->Succs) {
511 std::map<unsigned, unsigned>::iterator I =
512 NodeNum2Index.find(Succ.getSUnit()->NodeNum);
513 if (I != NodeNum2Index.end())
514 HasLowLatencyNonWaitedParent[I->second] = 1;
515 }
516 }
517 SU->isScheduled = true;
518}
519
520void SIScheduleBlock::finalizeUnits() {
521 // We remove links from outside blocks to enable scheduling inside the block.
522 for (SUnit* SU : SUnits) {
523 releaseSuccessors(SU, false);
524 if (DAG->IsHighLatencySU[SU->NodeNum])
525 HighLatencyBlock = true;
526 }
527 HasLowLatencyNonWaitedParent.resize(SUnits.size(), 0);
528}
529
530// we maintain ascending order of IDs
531void SIScheduleBlock::addPred(SIScheduleBlock *Pred) {
532 unsigned PredID = Pred->getID();
533
534 // Check if not already predecessor.
535 for (SIScheduleBlock* P : Preds) {
536 if (PredID == P->getID())
537 return;
538 }
539 Preds.push_back(Pred);
540
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000541 assert(none_of(Succs,
542 [=](SIScheduleBlock *S) { return PredID == S->getID(); }) &&
543 "Loop in the Block Graph!");
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000544}
545
546void SIScheduleBlock::addSucc(SIScheduleBlock *Succ) {
547 unsigned SuccID = Succ->getID();
548
549 // Check if not already predecessor.
550 for (SIScheduleBlock* S : Succs) {
551 if (SuccID == S->getID())
552 return;
553 }
554 if (Succ->isHighLatencyBlock())
555 ++NumHighLatencySuccessors;
556 Succs.push_back(Succ);
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000557 assert(none_of(Preds,
558 [=](SIScheduleBlock *P) { return SuccID == P->getID(); }) &&
559 "Loop in the Block Graph!");
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000560}
561
562#ifndef NDEBUG
563void SIScheduleBlock::printDebug(bool full) {
564 dbgs() << "Block (" << ID << ")\n";
565 if (!full)
566 return;
567
568 dbgs() << "\nContains High Latency Instruction: "
569 << HighLatencyBlock << '\n';
570 dbgs() << "\nDepends On:\n";
571 for (SIScheduleBlock* P : Preds) {
572 P->printDebug(false);
573 }
574
575 dbgs() << "\nSuccessors:\n";
576 for (SIScheduleBlock* S : Succs) {
577 S->printDebug(false);
578 }
579
580 if (Scheduled) {
581 dbgs() << "LiveInPressure " << LiveInPressure[DAG->getSGPRSetID()] << ' '
582 << LiveInPressure[DAG->getVGPRSetID()] << '\n';
583 dbgs() << "LiveOutPressure " << LiveOutPressure[DAG->getSGPRSetID()] << ' '
584 << LiveOutPressure[DAG->getVGPRSetID()] << "\n\n";
585 dbgs() << "LiveIns:\n";
586 for (unsigned Reg : LiveInRegs)
587 dbgs() << PrintVRegOrUnit(Reg, DAG->getTRI()) << ' ';
588
589 dbgs() << "\nLiveOuts:\n";
590 for (unsigned Reg : LiveOutRegs)
591 dbgs() << PrintVRegOrUnit(Reg, DAG->getTRI()) << ' ';
592 }
593
594 dbgs() << "\nInstructions:\n";
595 if (!Scheduled) {
596 for (SUnit* SU : SUnits) {
597 SU->dump(DAG);
598 }
599 } else {
600 for (SUnit* SU : SUnits) {
601 SU->dump(DAG);
602 }
603 }
604
Eugene Zelenko6a9226d2016-12-12 22:23:53 +0000605 dbgs() << "///////////////////////\n";
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000606}
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000607#endif
608
609// SIScheduleBlockCreator //
610
611SIScheduleBlockCreator::SIScheduleBlockCreator(SIScheduleDAGMI *DAG) :
612DAG(DAG) {
613}
614
Eugene Zelenko6a9226d2016-12-12 22:23:53 +0000615SIScheduleBlockCreator::~SIScheduleBlockCreator() = default;
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000616
617SIScheduleBlocks
618SIScheduleBlockCreator::getBlocks(SISchedulerBlockCreatorVariant BlockVariant) {
619 std::map<SISchedulerBlockCreatorVariant, SIScheduleBlocks>::iterator B =
620 Blocks.find(BlockVariant);
621 if (B == Blocks.end()) {
622 SIScheduleBlocks Res;
623 createBlocksForVariant(BlockVariant);
624 topologicalSort();
625 scheduleInsideBlocks();
626 fillStats();
627 Res.Blocks = CurrentBlocks;
628 Res.TopDownIndex2Block = TopDownIndex2Block;
629 Res.TopDownBlock2Index = TopDownBlock2Index;
630 Blocks[BlockVariant] = Res;
631 return Res;
632 } else {
633 return B->second;
634 }
635}
636
637bool SIScheduleBlockCreator::isSUInBlock(SUnit *SU, unsigned ID) {
638 if (SU->NodeNum >= DAG->SUnits.size())
639 return false;
640 return CurrentBlocks[Node2CurrentBlock[SU->NodeNum]]->getID() == ID;
641}
642
643void SIScheduleBlockCreator::colorHighLatenciesAlone() {
644 unsigned DAGSize = DAG->SUnits.size();
645
646 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
647 SUnit *SU = &DAG->SUnits[i];
648 if (DAG->IsHighLatencySU[SU->NodeNum]) {
649 CurrentColoring[SU->NodeNum] = NextReservedID++;
650 }
651 }
652}
653
654void SIScheduleBlockCreator::colorHighLatenciesGroups() {
655 unsigned DAGSize = DAG->SUnits.size();
656 unsigned NumHighLatencies = 0;
657 unsigned GroupSize;
658 unsigned Color = NextReservedID;
659 unsigned Count = 0;
660 std::set<unsigned> FormingGroup;
661
662 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
663 SUnit *SU = &DAG->SUnits[i];
664 if (DAG->IsHighLatencySU[SU->NodeNum])
665 ++NumHighLatencies;
666 }
667
668 if (NumHighLatencies == 0)
669 return;
670
671 if (NumHighLatencies <= 6)
672 GroupSize = 2;
673 else if (NumHighLatencies <= 12)
674 GroupSize = 3;
675 else
676 GroupSize = 4;
677
678 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
679 SUnit *SU = &DAG->SUnits[i];
680 if (DAG->IsHighLatencySU[SU->NodeNum]) {
681 unsigned CompatibleGroup = true;
682 unsigned ProposedColor = Color;
683 for (unsigned j : FormingGroup) {
684 // TODO: Currently CompatibleGroup will always be false,
685 // because the graph enforces the load order. This
686 // can be fixed, but as keeping the load order is often
687 // good for performance that causes a performance hit (both
688 // the default scheduler and this scheduler).
689 // When this scheduler determines a good load order,
690 // this can be fixed.
691 if (!DAG->canAddEdge(SU, &DAG->SUnits[j]) ||
692 !DAG->canAddEdge(&DAG->SUnits[j], SU))
693 CompatibleGroup = false;
694 }
695 if (!CompatibleGroup || ++Count == GroupSize) {
696 FormingGroup.clear();
697 Color = ++NextReservedID;
698 if (!CompatibleGroup) {
699 ProposedColor = Color;
700 FormingGroup.insert(SU->NodeNum);
701 }
702 Count = 0;
703 } else {
704 FormingGroup.insert(SU->NodeNum);
705 }
706 CurrentColoring[SU->NodeNum] = ProposedColor;
707 }
708 }
709}
710
711void SIScheduleBlockCreator::colorComputeReservedDependencies() {
712 unsigned DAGSize = DAG->SUnits.size();
713 std::map<std::set<unsigned>, unsigned> ColorCombinations;
714
715 CurrentTopDownReservedDependencyColoring.clear();
716 CurrentBottomUpReservedDependencyColoring.clear();
717
718 CurrentTopDownReservedDependencyColoring.resize(DAGSize, 0);
719 CurrentBottomUpReservedDependencyColoring.resize(DAGSize, 0);
720
721 // Traverse TopDown, and give different colors to SUs depending
722 // on which combination of High Latencies they depend on.
723
Tom Stellard4a304b32016-05-03 16:30:56 +0000724 for (unsigned SUNum : DAG->TopDownIndex2SU) {
725 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000726 std::set<unsigned> SUColors;
727
728 // Already given.
729 if (CurrentColoring[SU->NodeNum]) {
730 CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
731 CurrentColoring[SU->NodeNum];
732 continue;
733 }
734
735 for (SDep& PredDep : SU->Preds) {
736 SUnit *Pred = PredDep.getSUnit();
737 if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
738 continue;
739 if (CurrentTopDownReservedDependencyColoring[Pred->NodeNum] > 0)
740 SUColors.insert(CurrentTopDownReservedDependencyColoring[Pred->NodeNum]);
741 }
742 // Color 0 by default.
743 if (SUColors.empty())
744 continue;
745 // Same color than parents.
746 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
747 CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
748 *SUColors.begin();
749 else {
750 std::map<std::set<unsigned>, unsigned>::iterator Pos =
751 ColorCombinations.find(SUColors);
752 if (Pos != ColorCombinations.end()) {
753 CurrentTopDownReservedDependencyColoring[SU->NodeNum] = Pos->second;
754 } else {
755 CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
756 NextNonReservedID;
757 ColorCombinations[SUColors] = NextNonReservedID++;
758 }
759 }
760 }
761
762 ColorCombinations.clear();
763
764 // Same as before, but BottomUp.
765
Tom Stellard4a304b32016-05-03 16:30:56 +0000766 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
767 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000768 std::set<unsigned> SUColors;
769
770 // Already given.
771 if (CurrentColoring[SU->NodeNum]) {
772 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
773 CurrentColoring[SU->NodeNum];
774 continue;
775 }
776
777 for (SDep& SuccDep : SU->Succs) {
778 SUnit *Succ = SuccDep.getSUnit();
779 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
780 continue;
781 if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0)
782 SUColors.insert(CurrentBottomUpReservedDependencyColoring[Succ->NodeNum]);
783 }
784 // Keep color 0.
785 if (SUColors.empty())
786 continue;
787 // Same color than parents.
788 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
789 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
790 *SUColors.begin();
791 else {
792 std::map<std::set<unsigned>, unsigned>::iterator Pos =
793 ColorCombinations.find(SUColors);
794 if (Pos != ColorCombinations.end()) {
795 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = Pos->second;
796 } else {
797 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
798 NextNonReservedID;
799 ColorCombinations[SUColors] = NextNonReservedID++;
800 }
801 }
802 }
803}
804
805void SIScheduleBlockCreator::colorAccordingToReservedDependencies() {
806 unsigned DAGSize = DAG->SUnits.size();
807 std::map<std::pair<unsigned, unsigned>, unsigned> ColorCombinations;
808
809 // Every combination of colors given by the top down
810 // and bottom up Reserved node dependency
811
812 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
813 SUnit *SU = &DAG->SUnits[i];
814 std::pair<unsigned, unsigned> SUColors;
815
816 // High latency instructions: already given.
817 if (CurrentColoring[SU->NodeNum])
818 continue;
819
820 SUColors.first = CurrentTopDownReservedDependencyColoring[SU->NodeNum];
821 SUColors.second = CurrentBottomUpReservedDependencyColoring[SU->NodeNum];
822
823 std::map<std::pair<unsigned, unsigned>, unsigned>::iterator Pos =
824 ColorCombinations.find(SUColors);
825 if (Pos != ColorCombinations.end()) {
826 CurrentColoring[SU->NodeNum] = Pos->second;
827 } else {
828 CurrentColoring[SU->NodeNum] = NextNonReservedID;
829 ColorCombinations[SUColors] = NextNonReservedID++;
830 }
831 }
832}
833
834void SIScheduleBlockCreator::colorEndsAccordingToDependencies() {
835 unsigned DAGSize = DAG->SUnits.size();
836 std::vector<int> PendingColoring = CurrentColoring;
837
Tom Stellard4a304b32016-05-03 16:30:56 +0000838 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
839 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000840 std::set<unsigned> SUColors;
841 std::set<unsigned> SUColorsPending;
842
843 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
844 continue;
845
846 if (CurrentBottomUpReservedDependencyColoring[SU->NodeNum] > 0 ||
847 CurrentTopDownReservedDependencyColoring[SU->NodeNum] > 0)
848 continue;
849
850 for (SDep& SuccDep : SU->Succs) {
851 SUnit *Succ = SuccDep.getSUnit();
852 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
853 continue;
854 if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0 ||
855 CurrentTopDownReservedDependencyColoring[Succ->NodeNum] > 0)
856 SUColors.insert(CurrentColoring[Succ->NodeNum]);
857 SUColorsPending.insert(PendingColoring[Succ->NodeNum]);
858 }
859 if (SUColors.size() == 1 && SUColorsPending.size() == 1)
860 PendingColoring[SU->NodeNum] = *SUColors.begin();
861 else // TODO: Attribute new colors depending on color
862 // combination of children.
863 PendingColoring[SU->NodeNum] = NextNonReservedID++;
864 }
865 CurrentColoring = PendingColoring;
866}
867
868
869void SIScheduleBlockCreator::colorForceConsecutiveOrderInGroup() {
870 unsigned DAGSize = DAG->SUnits.size();
871 unsigned PreviousColor;
872 std::set<unsigned> SeenColors;
873
874 if (DAGSize <= 1)
875 return;
876
877 PreviousColor = CurrentColoring[0];
878
879 for (unsigned i = 1, e = DAGSize; i != e; ++i) {
880 SUnit *SU = &DAG->SUnits[i];
881 unsigned CurrentColor = CurrentColoring[i];
882 unsigned PreviousColorSave = PreviousColor;
883 assert(i == SU->NodeNum);
884
885 if (CurrentColor != PreviousColor)
886 SeenColors.insert(PreviousColor);
887 PreviousColor = CurrentColor;
888
889 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
890 continue;
891
892 if (SeenColors.find(CurrentColor) == SeenColors.end())
893 continue;
894
895 if (PreviousColorSave != CurrentColor)
896 CurrentColoring[i] = NextNonReservedID++;
897 else
898 CurrentColoring[i] = CurrentColoring[i-1];
899 }
900}
901
902void SIScheduleBlockCreator::colorMergeConstantLoadsNextGroup() {
903 unsigned DAGSize = DAG->SUnits.size();
904
Tom Stellard4a304b32016-05-03 16:30:56 +0000905 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
906 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000907 std::set<unsigned> SUColors;
908
909 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
910 continue;
911
912 // No predecessor: Vgpr constant loading.
913 // Low latency instructions usually have a predecessor (the address)
914 if (SU->Preds.size() > 0 && !DAG->IsLowLatencySU[SU->NodeNum])
915 continue;
916
917 for (SDep& SuccDep : SU->Succs) {
918 SUnit *Succ = SuccDep.getSUnit();
919 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
920 continue;
921 SUColors.insert(CurrentColoring[Succ->NodeNum]);
922 }
923 if (SUColors.size() == 1)
924 CurrentColoring[SU->NodeNum] = *SUColors.begin();
925 }
926}
927
928void SIScheduleBlockCreator::colorMergeIfPossibleNextGroup() {
929 unsigned DAGSize = DAG->SUnits.size();
930
Tom Stellard4a304b32016-05-03 16:30:56 +0000931 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
932 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000933 std::set<unsigned> SUColors;
934
935 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
936 continue;
937
938 for (SDep& SuccDep : SU->Succs) {
939 SUnit *Succ = SuccDep.getSUnit();
940 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
941 continue;
942 SUColors.insert(CurrentColoring[Succ->NodeNum]);
943 }
944 if (SUColors.size() == 1)
945 CurrentColoring[SU->NodeNum] = *SUColors.begin();
946 }
947}
948
949void SIScheduleBlockCreator::colorMergeIfPossibleNextGroupOnlyForReserved() {
950 unsigned DAGSize = DAG->SUnits.size();
951
Tom Stellard4a304b32016-05-03 16:30:56 +0000952 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
953 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000954 std::set<unsigned> SUColors;
955
956 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
957 continue;
958
959 for (SDep& SuccDep : SU->Succs) {
960 SUnit *Succ = SuccDep.getSUnit();
961 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
962 continue;
963 SUColors.insert(CurrentColoring[Succ->NodeNum]);
964 }
965 if (SUColors.size() == 1 && *SUColors.begin() <= DAGSize)
966 CurrentColoring[SU->NodeNum] = *SUColors.begin();
967 }
968}
969
970void SIScheduleBlockCreator::colorMergeIfPossibleSmallGroupsToNextGroup() {
971 unsigned DAGSize = DAG->SUnits.size();
972 std::map<unsigned, unsigned> ColorCount;
973
Tom Stellard4a304b32016-05-03 16:30:56 +0000974 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
975 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000976 unsigned color = CurrentColoring[SU->NodeNum];
Valery Pykhtine2419dc2017-03-24 17:49:05 +0000977 ++ColorCount[color];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000978 }
979
Tom Stellard4a304b32016-05-03 16:30:56 +0000980 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
981 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000982 unsigned color = CurrentColoring[SU->NodeNum];
983 std::set<unsigned> SUColors;
984
985 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
986 continue;
987
988 if (ColorCount[color] > 1)
989 continue;
990
991 for (SDep& SuccDep : SU->Succs) {
992 SUnit *Succ = SuccDep.getSUnit();
993 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
994 continue;
995 SUColors.insert(CurrentColoring[Succ->NodeNum]);
996 }
997 if (SUColors.size() == 1 && *SUColors.begin() != color) {
998 --ColorCount[color];
999 CurrentColoring[SU->NodeNum] = *SUColors.begin();
1000 ++ColorCount[*SUColors.begin()];
1001 }
1002 }
1003}
1004
1005void SIScheduleBlockCreator::cutHugeBlocks() {
1006 // TODO
1007}
1008
1009void SIScheduleBlockCreator::regroupNoUserInstructions() {
1010 unsigned DAGSize = DAG->SUnits.size();
1011 int GroupID = NextNonReservedID++;
1012
Tom Stellard4a304b32016-05-03 16:30:56 +00001013 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1014 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001015 bool hasSuccessor = false;
1016
1017 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1018 continue;
1019
1020 for (SDep& SuccDep : SU->Succs) {
1021 SUnit *Succ = SuccDep.getSUnit();
1022 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1023 continue;
1024 hasSuccessor = true;
1025 }
1026 if (!hasSuccessor)
1027 CurrentColoring[SU->NodeNum] = GroupID;
1028 }
1029}
1030
1031void SIScheduleBlockCreator::createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant) {
1032 unsigned DAGSize = DAG->SUnits.size();
1033 std::map<unsigned,unsigned> RealID;
1034
1035 CurrentBlocks.clear();
1036 CurrentColoring.clear();
1037 CurrentColoring.resize(DAGSize, 0);
1038 Node2CurrentBlock.clear();
1039
1040 // Restore links previous scheduling variant has overridden.
1041 DAG->restoreSULinksLeft();
1042
1043 NextReservedID = 1;
1044 NextNonReservedID = DAGSize + 1;
1045
1046 DEBUG(dbgs() << "Coloring the graph\n");
1047
1048 if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesGrouped)
1049 colorHighLatenciesGroups();
1050 else
1051 colorHighLatenciesAlone();
1052 colorComputeReservedDependencies();
1053 colorAccordingToReservedDependencies();
1054 colorEndsAccordingToDependencies();
1055 if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesAlonePlusConsecutive)
1056 colorForceConsecutiveOrderInGroup();
1057 regroupNoUserInstructions();
1058 colorMergeConstantLoadsNextGroup();
1059 colorMergeIfPossibleNextGroupOnlyForReserved();
1060
1061 // Put SUs of same color into same block
1062 Node2CurrentBlock.resize(DAGSize, -1);
1063 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1064 SUnit *SU = &DAG->SUnits[i];
1065 unsigned Color = CurrentColoring[SU->NodeNum];
1066 if (RealID.find(Color) == RealID.end()) {
1067 int ID = CurrentBlocks.size();
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001068 BlockPtrs.push_back(llvm::make_unique<SIScheduleBlock>(DAG, this, ID));
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001069 CurrentBlocks.push_back(BlockPtrs.rbegin()->get());
1070 RealID[Color] = ID;
1071 }
1072 CurrentBlocks[RealID[Color]]->addUnit(SU);
1073 Node2CurrentBlock[SU->NodeNum] = RealID[Color];
1074 }
1075
1076 // Build dependencies between blocks.
1077 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1078 SUnit *SU = &DAG->SUnits[i];
1079 int SUID = Node2CurrentBlock[i];
1080 for (SDep& SuccDep : SU->Succs) {
1081 SUnit *Succ = SuccDep.getSUnit();
1082 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1083 continue;
1084 if (Node2CurrentBlock[Succ->NodeNum] != SUID)
1085 CurrentBlocks[SUID]->addSucc(CurrentBlocks[Node2CurrentBlock[Succ->NodeNum]]);
1086 }
1087 for (SDep& PredDep : SU->Preds) {
1088 SUnit *Pred = PredDep.getSUnit();
1089 if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
1090 continue;
1091 if (Node2CurrentBlock[Pred->NodeNum] != SUID)
1092 CurrentBlocks[SUID]->addPred(CurrentBlocks[Node2CurrentBlock[Pred->NodeNum]]);
1093 }
1094 }
1095
1096 // Free root and leafs of all blocks to enable scheduling inside them.
1097 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1098 SIScheduleBlock *Block = CurrentBlocks[i];
1099 Block->finalizeUnits();
1100 }
1101 DEBUG(
1102 dbgs() << "Blocks created:\n\n";
1103 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1104 SIScheduleBlock *Block = CurrentBlocks[i];
1105 Block->printDebug(true);
1106 }
1107 );
1108}
1109
1110// Two functions taken from Codegen/MachineScheduler.cpp
1111
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001112/// Non-const version.
1113static MachineBasicBlock::iterator
1114nextIfDebug(MachineBasicBlock::iterator I,
1115 MachineBasicBlock::const_iterator End) {
Matt Arsenaultfef7beb2016-12-22 16:06:32 +00001116 for (; I != End; ++I) {
1117 if (!I->isDebugValue())
1118 break;
1119 }
1120 return I;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001121}
1122
1123void SIScheduleBlockCreator::topologicalSort() {
1124 unsigned DAGSize = CurrentBlocks.size();
1125 std::vector<int> WorkList;
1126
1127 DEBUG(dbgs() << "Topological Sort\n");
1128
1129 WorkList.reserve(DAGSize);
1130 TopDownIndex2Block.resize(DAGSize);
1131 TopDownBlock2Index.resize(DAGSize);
1132 BottomUpIndex2Block.resize(DAGSize);
1133
1134 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1135 SIScheduleBlock *Block = CurrentBlocks[i];
1136 unsigned Degree = Block->getSuccs().size();
1137 TopDownBlock2Index[i] = Degree;
1138 if (Degree == 0) {
1139 WorkList.push_back(i);
1140 }
1141 }
1142
1143 int Id = DAGSize;
1144 while (!WorkList.empty()) {
1145 int i = WorkList.back();
1146 SIScheduleBlock *Block = CurrentBlocks[i];
1147 WorkList.pop_back();
1148 TopDownBlock2Index[i] = --Id;
1149 TopDownIndex2Block[Id] = i;
1150 for (SIScheduleBlock* Pred : Block->getPreds()) {
1151 if (!--TopDownBlock2Index[Pred->getID()])
1152 WorkList.push_back(Pred->getID());
1153 }
1154 }
1155
1156#ifndef NDEBUG
1157 // Check correctness of the ordering.
1158 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1159 SIScheduleBlock *Block = CurrentBlocks[i];
1160 for (SIScheduleBlock* Pred : Block->getPreds()) {
1161 assert(TopDownBlock2Index[i] > TopDownBlock2Index[Pred->getID()] &&
1162 "Wrong Top Down topological sorting");
1163 }
1164 }
1165#endif
1166
1167 BottomUpIndex2Block = std::vector<int>(TopDownIndex2Block.rbegin(),
1168 TopDownIndex2Block.rend());
1169}
1170
1171void SIScheduleBlockCreator::scheduleInsideBlocks() {
1172 unsigned DAGSize = CurrentBlocks.size();
1173
1174 DEBUG(dbgs() << "\nScheduling Blocks\n\n");
1175
1176 // We do schedule a valid scheduling such that a Block corresponds
1177 // to a range of instructions.
1178 DEBUG(dbgs() << "First phase: Fast scheduling for Reg Liveness\n");
1179 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1180 SIScheduleBlock *Block = CurrentBlocks[i];
1181 Block->fastSchedule();
1182 }
1183
1184 // Note: the following code, and the part restoring previous position
1185 // is by far the most expensive operation of the Scheduler.
1186
1187 // Do not update CurrentTop.
1188 MachineBasicBlock::iterator CurrentTopFastSched = DAG->getCurrentTop();
1189 std::vector<MachineBasicBlock::iterator> PosOld;
1190 std::vector<MachineBasicBlock::iterator> PosNew;
1191 PosOld.reserve(DAG->SUnits.size());
1192 PosNew.reserve(DAG->SUnits.size());
1193
1194 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1195 int BlockIndice = TopDownIndex2Block[i];
1196 SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1197 std::vector<SUnit*> SUs = Block->getScheduledUnits();
1198
1199 for (SUnit* SU : SUs) {
1200 MachineInstr *MI = SU->getInstr();
1201 MachineBasicBlock::iterator Pos = MI;
1202 PosOld.push_back(Pos);
1203 if (&*CurrentTopFastSched == MI) {
1204 PosNew.push_back(Pos);
1205 CurrentTopFastSched = nextIfDebug(++CurrentTopFastSched,
1206 DAG->getCurrentBottom());
1207 } else {
1208 // Update the instruction stream.
1209 DAG->getBB()->splice(CurrentTopFastSched, DAG->getBB(), MI);
1210
1211 // Update LiveIntervals.
Simon Pilgrime995a8082016-11-18 11:04:02 +00001212 // Note: Moving all instructions and calling handleMove every time
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001213 // is the most cpu intensive operation of the scheduler.
1214 // It would gain a lot if there was a way to recompute the
1215 // LiveIntervals for the entire scheduling region.
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +00001216 DAG->getLIS()->handleMove(*MI, /*UpdateFlags=*/true);
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001217 PosNew.push_back(CurrentTopFastSched);
1218 }
1219 }
1220 }
1221
1222 // Now we have Block of SUs == Block of MI.
1223 // We do the final schedule for the instructions inside the block.
1224 // The property that all the SUs of the Block are grouped together as MI
1225 // is used for correct reg usage tracking.
1226 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1227 SIScheduleBlock *Block = CurrentBlocks[i];
1228 std::vector<SUnit*> SUs = Block->getScheduledUnits();
1229 Block->schedule((*SUs.begin())->getInstr(), (*SUs.rbegin())->getInstr());
1230 }
1231
1232 DEBUG(dbgs() << "Restoring MI Pos\n");
1233 // Restore old ordering (which prevents a LIS->handleMove bug).
1234 for (unsigned i = PosOld.size(), e = 0; i != e; --i) {
1235 MachineBasicBlock::iterator POld = PosOld[i-1];
1236 MachineBasicBlock::iterator PNew = PosNew[i-1];
1237 if (PNew != POld) {
1238 // Update the instruction stream.
1239 DAG->getBB()->splice(POld, DAG->getBB(), PNew);
1240
1241 // Update LiveIntervals.
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +00001242 DAG->getLIS()->handleMove(*POld, /*UpdateFlags=*/true);
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001243 }
1244 }
1245
1246 DEBUG(
1247 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1248 SIScheduleBlock *Block = CurrentBlocks[i];
1249 Block->printDebug(true);
1250 }
1251 );
1252}
1253
1254void SIScheduleBlockCreator::fillStats() {
1255 unsigned DAGSize = CurrentBlocks.size();
1256
1257 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1258 int BlockIndice = TopDownIndex2Block[i];
1259 SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001260 if (Block->getPreds().empty())
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001261 Block->Depth = 0;
1262 else {
1263 unsigned Depth = 0;
1264 for (SIScheduleBlock *Pred : Block->getPreds()) {
1265 if (Depth < Pred->Depth + 1)
1266 Depth = Pred->Depth + 1;
1267 }
1268 Block->Depth = Depth;
1269 }
1270 }
1271
1272 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1273 int BlockIndice = BottomUpIndex2Block[i];
1274 SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001275 if (Block->getSuccs().empty())
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001276 Block->Height = 0;
1277 else {
1278 unsigned Height = 0;
1279 for (SIScheduleBlock *Succ : Block->getSuccs()) {
1280 if (Height < Succ->Height + 1)
1281 Height = Succ->Height + 1;
1282 }
1283 Block->Height = Height;
1284 }
1285 }
1286}
1287
1288// SIScheduleBlockScheduler //
1289
1290SIScheduleBlockScheduler::SIScheduleBlockScheduler(SIScheduleDAGMI *DAG,
1291 SISchedulerBlockSchedulerVariant Variant,
1292 SIScheduleBlocks BlocksStruct) :
1293 DAG(DAG), Variant(Variant), Blocks(BlocksStruct.Blocks),
1294 LastPosWaitedHighLatency(0), NumBlockScheduled(0), VregCurrentUsage(0),
1295 SregCurrentUsage(0), maxVregUsage(0), maxSregUsage(0) {
1296
1297 // Fill the usage of every output
1298 // Warning: while by construction we always have a link between two blocks
1299 // when one needs a result from the other, the number of users of an output
1300 // is not the sum of child blocks having as input the same virtual register.
1301 // Here is an example. A produces x and y. B eats x and produces x'.
1302 // C eats x' and y. The register coalescer may have attributed the same
1303 // virtual register to x and x'.
1304 // To count accurately, we do a topological sort. In case the register is
1305 // found for several parents, we increment the usage of the one with the
1306 // highest topological index.
1307 LiveOutRegsNumUsages.resize(Blocks.size());
1308 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1309 SIScheduleBlock *Block = Blocks[i];
1310 for (unsigned Reg : Block->getInRegs()) {
1311 bool Found = false;
1312 int topoInd = -1;
1313 for (SIScheduleBlock* Pred: Block->getPreds()) {
1314 std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1315 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1316
1317 if (RegPos != PredOutRegs.end()) {
1318 Found = true;
1319 if (topoInd < BlocksStruct.TopDownBlock2Index[Pred->getID()]) {
1320 topoInd = BlocksStruct.TopDownBlock2Index[Pred->getID()];
1321 }
1322 }
1323 }
1324
1325 if (!Found)
1326 continue;
1327
1328 int PredID = BlocksStruct.TopDownIndex2Block[topoInd];
Valery Pykhtine2419dc2017-03-24 17:49:05 +00001329 ++LiveOutRegsNumUsages[PredID][Reg];
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001330 }
1331 }
1332
1333 LastPosHighLatencyParentScheduled.resize(Blocks.size(), 0);
1334 BlockNumPredsLeft.resize(Blocks.size());
1335 BlockNumSuccsLeft.resize(Blocks.size());
1336
1337 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1338 SIScheduleBlock *Block = Blocks[i];
1339 BlockNumPredsLeft[i] = Block->getPreds().size();
1340 BlockNumSuccsLeft[i] = Block->getSuccs().size();
1341 }
1342
1343#ifndef NDEBUG
1344 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1345 SIScheduleBlock *Block = Blocks[i];
1346 assert(Block->getID() == i);
1347 }
1348#endif
1349
1350 std::set<unsigned> InRegs = DAG->getInRegs();
1351 addLiveRegs(InRegs);
1352
Valery Pykhtinf70f6832017-03-27 17:06:36 +00001353 // Increase LiveOutRegsNumUsages for blocks
1354 // producing registers consumed in another
1355 // scheduling region.
1356 for (unsigned Reg : DAG->getOutRegs()) {
1357 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1358 // Do reverse traversal
1359 int ID = BlocksStruct.TopDownIndex2Block[Blocks.size()-1-i];
1360 SIScheduleBlock *Block = Blocks[ID];
1361 const std::set<unsigned> &OutRegs = Block->getOutRegs();
1362
1363 if (OutRegs.find(Reg) == OutRegs.end())
1364 continue;
1365
1366 ++LiveOutRegsNumUsages[ID][Reg];
1367 break;
1368 }
1369 }
1370
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001371 // Fill LiveRegsConsumers for regs that were already
1372 // defined before scheduling.
1373 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1374 SIScheduleBlock *Block = Blocks[i];
1375 for (unsigned Reg : Block->getInRegs()) {
1376 bool Found = false;
1377 for (SIScheduleBlock* Pred: Block->getPreds()) {
1378 std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1379 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1380
1381 if (RegPos != PredOutRegs.end()) {
1382 Found = true;
1383 break;
1384 }
1385 }
1386
Valery Pykhtine2419dc2017-03-24 17:49:05 +00001387 if (!Found)
1388 ++LiveRegsConsumers[Reg];
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001389 }
1390 }
1391
1392 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1393 SIScheduleBlock *Block = Blocks[i];
1394 if (BlockNumPredsLeft[i] == 0) {
1395 ReadyBlocks.push_back(Block);
1396 }
1397 }
1398
1399 while (SIScheduleBlock *Block = pickBlock()) {
1400 BlocksScheduled.push_back(Block);
1401 blockScheduled(Block);
1402 }
1403
1404 DEBUG(
1405 dbgs() << "Block Order:";
1406 for (SIScheduleBlock* Block : BlocksScheduled) {
1407 dbgs() << ' ' << Block->getID();
1408 }
Valery Pykhtin57ab6992017-03-24 16:37:48 +00001409 dbgs() << '\n';
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001410 );
1411}
1412
1413bool SIScheduleBlockScheduler::tryCandidateLatency(SIBlockSchedCandidate &Cand,
1414 SIBlockSchedCandidate &TryCand) {
1415 if (!Cand.isValid()) {
1416 TryCand.Reason = NodeOrder;
1417 return true;
1418 }
1419
1420 // Try to hide high latencies.
1421 if (tryLess(TryCand.LastPosHighLatParentScheduled,
1422 Cand.LastPosHighLatParentScheduled, TryCand, Cand, Latency))
1423 return true;
1424 // Schedule high latencies early so you can hide them better.
1425 if (tryGreater(TryCand.IsHighLatency, Cand.IsHighLatency,
1426 TryCand, Cand, Latency))
1427 return true;
1428 if (TryCand.IsHighLatency && tryGreater(TryCand.Height, Cand.Height,
1429 TryCand, Cand, Depth))
1430 return true;
1431 if (tryGreater(TryCand.NumHighLatencySuccessors,
1432 Cand.NumHighLatencySuccessors,
1433 TryCand, Cand, Successor))
1434 return true;
1435 return false;
1436}
1437
1438bool SIScheduleBlockScheduler::tryCandidateRegUsage(SIBlockSchedCandidate &Cand,
1439 SIBlockSchedCandidate &TryCand) {
1440 if (!Cand.isValid()) {
1441 TryCand.Reason = NodeOrder;
1442 return true;
1443 }
1444
1445 if (tryLess(TryCand.VGPRUsageDiff > 0, Cand.VGPRUsageDiff > 0,
1446 TryCand, Cand, RegUsage))
1447 return true;
1448 if (tryGreater(TryCand.NumSuccessors > 0,
1449 Cand.NumSuccessors > 0,
1450 TryCand, Cand, Successor))
1451 return true;
1452 if (tryGreater(TryCand.Height, Cand.Height, TryCand, Cand, Depth))
1453 return true;
1454 if (tryLess(TryCand.VGPRUsageDiff, Cand.VGPRUsageDiff,
1455 TryCand, Cand, RegUsage))
1456 return true;
1457 return false;
1458}
1459
1460SIScheduleBlock *SIScheduleBlockScheduler::pickBlock() {
1461 SIBlockSchedCandidate Cand;
1462 std::vector<SIScheduleBlock*>::iterator Best;
1463 SIScheduleBlock *Block;
1464 if (ReadyBlocks.empty())
1465 return nullptr;
1466
1467 DAG->fillVgprSgprCost(LiveRegs.begin(), LiveRegs.end(),
1468 VregCurrentUsage, SregCurrentUsage);
1469 if (VregCurrentUsage > maxVregUsage)
1470 maxVregUsage = VregCurrentUsage;
Valery Pykhtinf7d10232017-03-24 16:45:50 +00001471 if (SregCurrentUsage > maxSregUsage)
1472 maxSregUsage = SregCurrentUsage;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001473 DEBUG(
1474 dbgs() << "Picking New Blocks\n";
1475 dbgs() << "Available: ";
1476 for (SIScheduleBlock* Block : ReadyBlocks)
1477 dbgs() << Block->getID() << ' ';
1478 dbgs() << "\nCurrent Live:\n";
1479 for (unsigned Reg : LiveRegs)
1480 dbgs() << PrintVRegOrUnit(Reg, DAG->getTRI()) << ' ';
1481 dbgs() << '\n';
1482 dbgs() << "Current VGPRs: " << VregCurrentUsage << '\n';
1483 dbgs() << "Current SGPRs: " << SregCurrentUsage << '\n';
1484 );
1485
1486 Cand.Block = nullptr;
1487 for (std::vector<SIScheduleBlock*>::iterator I = ReadyBlocks.begin(),
1488 E = ReadyBlocks.end(); I != E; ++I) {
1489 SIBlockSchedCandidate TryCand;
1490 TryCand.Block = *I;
1491 TryCand.IsHighLatency = TryCand.Block->isHighLatencyBlock();
1492 TryCand.VGPRUsageDiff =
1493 checkRegUsageImpact(TryCand.Block->getInRegs(),
1494 TryCand.Block->getOutRegs())[DAG->getVGPRSetID()];
1495 TryCand.NumSuccessors = TryCand.Block->getSuccs().size();
1496 TryCand.NumHighLatencySuccessors =
1497 TryCand.Block->getNumHighLatencySuccessors();
1498 TryCand.LastPosHighLatParentScheduled =
1499 (unsigned int) std::max<int> (0,
1500 LastPosHighLatencyParentScheduled[TryCand.Block->getID()] -
1501 LastPosWaitedHighLatency);
1502 TryCand.Height = TryCand.Block->Height;
1503 // Try not to increase VGPR usage too much, else we may spill.
1504 if (VregCurrentUsage > 120 ||
1505 Variant != SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage) {
1506 if (!tryCandidateRegUsage(Cand, TryCand) &&
1507 Variant != SISchedulerBlockSchedulerVariant::BlockRegUsage)
1508 tryCandidateLatency(Cand, TryCand);
1509 } else {
1510 if (!tryCandidateLatency(Cand, TryCand))
1511 tryCandidateRegUsage(Cand, TryCand);
1512 }
1513 if (TryCand.Reason != NoCand) {
1514 Cand.setBest(TryCand);
1515 Best = I;
1516 DEBUG(dbgs() << "Best Current Choice: " << Cand.Block->getID() << ' '
1517 << getReasonStr(Cand.Reason) << '\n');
1518 }
1519 }
1520
1521 DEBUG(
1522 dbgs() << "Picking: " << Cand.Block->getID() << '\n';
1523 dbgs() << "Is a block with high latency instruction: "
1524 << (Cand.IsHighLatency ? "yes\n" : "no\n");
1525 dbgs() << "Position of last high latency dependency: "
1526 << Cand.LastPosHighLatParentScheduled << '\n';
1527 dbgs() << "VGPRUsageDiff: " << Cand.VGPRUsageDiff << '\n';
1528 dbgs() << '\n';
1529 );
1530
1531 Block = Cand.Block;
1532 ReadyBlocks.erase(Best);
1533 return Block;
1534}
1535
1536// Tracking of currently alive registers to determine VGPR Usage.
1537
1538void SIScheduleBlockScheduler::addLiveRegs(std::set<unsigned> &Regs) {
1539 for (unsigned Reg : Regs) {
1540 // For now only track virtual registers.
1541 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1542 continue;
1543 // If not already in the live set, then add it.
1544 (void) LiveRegs.insert(Reg);
1545 }
1546}
1547
1548void SIScheduleBlockScheduler::decreaseLiveRegs(SIScheduleBlock *Block,
1549 std::set<unsigned> &Regs) {
1550 for (unsigned Reg : Regs) {
1551 // For now only track virtual registers.
1552 std::set<unsigned>::iterator Pos = LiveRegs.find(Reg);
1553 assert (Pos != LiveRegs.end() && // Reg must be live.
1554 LiveRegsConsumers.find(Reg) != LiveRegsConsumers.end() &&
1555 LiveRegsConsumers[Reg] >= 1);
1556 --LiveRegsConsumers[Reg];
1557 if (LiveRegsConsumers[Reg] == 0)
1558 LiveRegs.erase(Pos);
1559 }
1560}
1561
1562void SIScheduleBlockScheduler::releaseBlockSuccs(SIScheduleBlock *Parent) {
1563 for (SIScheduleBlock* Block : Parent->getSuccs()) {
1564 --BlockNumPredsLeft[Block->getID()];
1565 if (BlockNumPredsLeft[Block->getID()] == 0) {
1566 ReadyBlocks.push_back(Block);
1567 }
1568 // TODO: Improve check. When the dependency between the high latency
1569 // instructions and the instructions of the other blocks are WAR or WAW
1570 // there will be no wait triggered. We would like these cases to not
1571 // update LastPosHighLatencyParentScheduled.
1572 if (Parent->isHighLatencyBlock())
1573 LastPosHighLatencyParentScheduled[Block->getID()] = NumBlockScheduled;
1574 }
1575}
1576
1577void SIScheduleBlockScheduler::blockScheduled(SIScheduleBlock *Block) {
1578 decreaseLiveRegs(Block, Block->getInRegs());
1579 addLiveRegs(Block->getOutRegs());
1580 releaseBlockSuccs(Block);
1581 for (std::map<unsigned, unsigned>::iterator RegI =
1582 LiveOutRegsNumUsages[Block->getID()].begin(),
1583 E = LiveOutRegsNumUsages[Block->getID()].end(); RegI != E; ++RegI) {
1584 std::pair<unsigned, unsigned> RegP = *RegI;
Valery Pykhtine2419dc2017-03-24 17:49:05 +00001585 // We produce this register, thus it must not be previously alive.
1586 assert(LiveRegsConsumers.find(RegP.first) == LiveRegsConsumers.end() ||
1587 LiveRegsConsumers[RegP.first] == 0);
1588 LiveRegsConsumers[RegP.first] += RegP.second;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001589 }
1590 if (LastPosHighLatencyParentScheduled[Block->getID()] >
1591 (unsigned)LastPosWaitedHighLatency)
1592 LastPosWaitedHighLatency =
1593 LastPosHighLatencyParentScheduled[Block->getID()];
1594 ++NumBlockScheduled;
1595}
1596
1597std::vector<int>
1598SIScheduleBlockScheduler::checkRegUsageImpact(std::set<unsigned> &InRegs,
1599 std::set<unsigned> &OutRegs) {
1600 std::vector<int> DiffSetPressure;
1601 DiffSetPressure.assign(DAG->getTRI()->getNumRegPressureSets(), 0);
1602
1603 for (unsigned Reg : InRegs) {
1604 // For now only track virtual registers.
1605 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1606 continue;
1607 if (LiveRegsConsumers[Reg] > 1)
1608 continue;
1609 PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1610 for (; PSetI.isValid(); ++PSetI) {
1611 DiffSetPressure[*PSetI] -= PSetI.getWeight();
1612 }
1613 }
1614
1615 for (unsigned Reg : OutRegs) {
1616 // For now only track virtual registers.
1617 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1618 continue;
1619 PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1620 for (; PSetI.isValid(); ++PSetI) {
1621 DiffSetPressure[*PSetI] += PSetI.getWeight();
1622 }
1623 }
1624
1625 return DiffSetPressure;
1626}
1627
1628// SIScheduler //
1629
1630struct SIScheduleBlockResult
1631SIScheduler::scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant,
1632 SISchedulerBlockSchedulerVariant ScheduleVariant) {
1633 SIScheduleBlocks Blocks = BlockCreator.getBlocks(BlockVariant);
1634 SIScheduleBlockScheduler Scheduler(DAG, ScheduleVariant, Blocks);
1635 std::vector<SIScheduleBlock*> ScheduledBlocks;
1636 struct SIScheduleBlockResult Res;
1637
1638 ScheduledBlocks = Scheduler.getBlocks();
1639
1640 for (unsigned b = 0; b < ScheduledBlocks.size(); ++b) {
1641 SIScheduleBlock *Block = ScheduledBlocks[b];
1642 std::vector<SUnit*> SUs = Block->getScheduledUnits();
1643
1644 for (SUnit* SU : SUs)
1645 Res.SUs.push_back(SU->NodeNum);
1646 }
1647
1648 Res.MaxSGPRUsage = Scheduler.getSGPRUsage();
1649 Res.MaxVGPRUsage = Scheduler.getVGPRUsage();
1650 return Res;
1651}
1652
1653// SIScheduleDAGMI //
1654
1655SIScheduleDAGMI::SIScheduleDAGMI(MachineSchedContext *C) :
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001656 ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C)) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001657 SITII = static_cast<const SIInstrInfo*>(TII);
1658 SITRI = static_cast<const SIRegisterInfo*>(TRI);
1659
Tom Stellard7c463c92016-08-26 21:16:37 +00001660 VGPRSetID = SITRI->getVGPRPressureSet();
1661 SGPRSetID = SITRI->getSGPRPressureSet();
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001662}
1663
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001664SIScheduleDAGMI::~SIScheduleDAGMI() = default;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001665
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001666// Code adapted from scheduleDAG.cpp
1667// Does a topological sort over the SUs.
1668// Both TopDown and BottomUp
1669void SIScheduleDAGMI::topologicalSort() {
Tom Stellard1d3940e2016-06-09 23:48:02 +00001670 Topo.InitDAGTopologicalSorting();
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001671
Tom Stellard1d3940e2016-06-09 23:48:02 +00001672 TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());
1673 BottomUpIndex2SU = std::vector<int>(Topo.rbegin(), Topo.rend());
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001674}
1675
1676// Move low latencies further from their user without
1677// increasing SGPR usage (in general)
1678// This is to be replaced by a better pass that would
1679// take into account SGPR usage (based on VGPR Usage
1680// and the corresponding wavefront count), that would
1681// try to merge groups of loads if it make sense, etc
1682void SIScheduleDAGMI::moveLowLatencies() {
1683 unsigned DAGSize = SUnits.size();
1684 int LastLowLatencyUser = -1;
1685 int LastLowLatencyPos = -1;
1686
1687 for (unsigned i = 0, e = ScheduledSUnits.size(); i != e; ++i) {
1688 SUnit *SU = &SUnits[ScheduledSUnits[i]];
1689 bool IsLowLatencyUser = false;
1690 unsigned MinPos = 0;
1691
1692 for (SDep& PredDep : SU->Preds) {
1693 SUnit *Pred = PredDep.getSUnit();
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001694 if (SITII->isLowLatencyInstruction(*Pred->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001695 IsLowLatencyUser = true;
1696 }
1697 if (Pred->NodeNum >= DAGSize)
1698 continue;
1699 unsigned PredPos = ScheduledSUnitsInv[Pred->NodeNum];
1700 if (PredPos >= MinPos)
1701 MinPos = PredPos + 1;
1702 }
1703
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001704 if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001705 unsigned BestPos = LastLowLatencyUser + 1;
1706 if ((int)BestPos <= LastLowLatencyPos)
1707 BestPos = LastLowLatencyPos + 1;
1708 if (BestPos < MinPos)
1709 BestPos = MinPos;
1710 if (BestPos < i) {
1711 for (unsigned u = i; u > BestPos; --u) {
1712 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1713 ScheduledSUnits[u] = ScheduledSUnits[u-1];
1714 }
1715 ScheduledSUnits[BestPos] = SU->NodeNum;
1716 ScheduledSUnitsInv[SU->NodeNum] = BestPos;
1717 }
1718 LastLowLatencyPos = BestPos;
1719 if (IsLowLatencyUser)
1720 LastLowLatencyUser = BestPos;
1721 } else if (IsLowLatencyUser) {
1722 LastLowLatencyUser = i;
1723 // Moves COPY instructions on which depends
1724 // the low latency instructions too.
1725 } else if (SU->getInstr()->getOpcode() == AMDGPU::COPY) {
1726 bool CopyForLowLat = false;
1727 for (SDep& SuccDep : SU->Succs) {
1728 SUnit *Succ = SuccDep.getSUnit();
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001729 if (SITII->isLowLatencyInstruction(*Succ->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001730 CopyForLowLat = true;
1731 }
1732 }
1733 if (!CopyForLowLat)
1734 continue;
1735 if (MinPos < i) {
1736 for (unsigned u = i; u > MinPos; --u) {
1737 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1738 ScheduledSUnits[u] = ScheduledSUnits[u-1];
1739 }
1740 ScheduledSUnits[MinPos] = SU->NodeNum;
1741 ScheduledSUnitsInv[SU->NodeNum] = MinPos;
1742 }
1743 }
1744 }
1745}
1746
1747void SIScheduleDAGMI::restoreSULinksLeft() {
1748 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1749 SUnits[i].isScheduled = false;
1750 SUnits[i].WeakPredsLeft = SUnitsLinksBackup[i].WeakPredsLeft;
1751 SUnits[i].NumPredsLeft = SUnitsLinksBackup[i].NumPredsLeft;
1752 SUnits[i].WeakSuccsLeft = SUnitsLinksBackup[i].WeakSuccsLeft;
1753 SUnits[i].NumSuccsLeft = SUnitsLinksBackup[i].NumSuccsLeft;
1754 }
1755}
1756
1757// Return the Vgpr and Sgpr usage corresponding to some virtual registers.
1758template<typename _Iterator> void
1759SIScheduleDAGMI::fillVgprSgprCost(_Iterator First, _Iterator End,
1760 unsigned &VgprUsage, unsigned &SgprUsage) {
1761 VgprUsage = 0;
1762 SgprUsage = 0;
1763 for (_Iterator RegI = First; RegI != End; ++RegI) {
1764 unsigned Reg = *RegI;
1765 // For now only track virtual registers
1766 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1767 continue;
1768 PSetIterator PSetI = MRI.getPressureSets(Reg);
1769 for (; PSetI.isValid(); ++PSetI) {
1770 if (*PSetI == VGPRSetID)
1771 VgprUsage += PSetI.getWeight();
1772 else if (*PSetI == SGPRSetID)
1773 SgprUsage += PSetI.getWeight();
1774 }
1775 }
1776}
1777
1778void SIScheduleDAGMI::schedule()
1779{
1780 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1781 SIScheduleBlockResult Best, Temp;
1782 DEBUG(dbgs() << "Preparing Scheduling\n");
1783
1784 buildDAGWithRegPressure();
1785 DEBUG(
1786 for(SUnit& SU : SUnits)
1787 SU.dumpAll(this)
1788 );
1789
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001790 topologicalSort();
1791 findRootsAndBiasEdges(TopRoots, BotRoots);
1792 // We reuse several ScheduleDAGMI and ScheduleDAGMILive
1793 // functions, but to make them happy we must initialize
1794 // the default Scheduler implementation (even if we do not
1795 // run it)
1796 SchedImpl->initialize(this);
1797 initQueues(TopRoots, BotRoots);
1798
1799 // Fill some stats to help scheduling.
1800
1801 SUnitsLinksBackup = SUnits;
1802 IsLowLatencySU.clear();
1803 LowLatencyOffset.clear();
1804 IsHighLatencySU.clear();
1805
1806 IsLowLatencySU.resize(SUnits.size(), 0);
1807 LowLatencyOffset.resize(SUnits.size(), 0);
1808 IsHighLatencySU.resize(SUnits.size(), 0);
1809
1810 for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
1811 SUnit *SU = &SUnits[i];
Chad Rosierc27a18f2016-03-09 16:00:35 +00001812 unsigned BaseLatReg;
1813 int64_t OffLatReg;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001814 if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001815 IsLowLatencySU[i] = 1;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001816 if (SITII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseLatReg, OffLatReg,
1817 TRI))
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001818 LowLatencyOffset[i] = OffLatReg;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001819 } else if (SITII->isHighLatencyInstruction(*SU->getInstr()))
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001820 IsHighLatencySU[i] = 1;
1821 }
1822
1823 SIScheduler Scheduler(this);
1824 Best = Scheduler.scheduleVariant(SISchedulerBlockCreatorVariant::LatenciesAlone,
1825 SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage);
Matt Arsenault105c2a22016-07-01 18:03:46 +00001826
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001827 // if VGPR usage is extremely high, try other good performing variants
1828 // which could lead to lower VGPR usage
1829 if (Best.MaxVGPRUsage > 180) {
Benjamin Kramer80e3d5b2017-03-24 17:53:06 +00001830 static const std::pair<SISchedulerBlockCreatorVariant,
1831 SISchedulerBlockSchedulerVariant>
Benjamin Kramerc06d6722017-03-24 14:11:47 +00001832 Variants[] = {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001833 { LatenciesAlone, BlockRegUsageLatency },
1834// { LatenciesAlone, BlockRegUsage },
1835 { LatenciesGrouped, BlockLatencyRegUsage },
1836// { LatenciesGrouped, BlockRegUsageLatency },
1837// { LatenciesGrouped, BlockRegUsage },
1838 { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1839// { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1840// { LatenciesAlonePlusConsecutive, BlockRegUsage }
1841 };
1842 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1843 Temp = Scheduler.scheduleVariant(v.first, v.second);
1844 if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
1845 Best = Temp;
1846 }
1847 }
1848 // if VGPR usage is still extremely high, we may spill. Try other variants
1849 // which are less performing, but that could lead to lower VGPR usage.
1850 if (Best.MaxVGPRUsage > 200) {
Benjamin Kramer80e3d5b2017-03-24 17:53:06 +00001851 static const std::pair<SISchedulerBlockCreatorVariant,
1852 SISchedulerBlockSchedulerVariant>
Benjamin Kramerc06d6722017-03-24 14:11:47 +00001853 Variants[] = {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001854// { LatenciesAlone, BlockRegUsageLatency },
1855 { LatenciesAlone, BlockRegUsage },
1856// { LatenciesGrouped, BlockLatencyRegUsage },
1857 { LatenciesGrouped, BlockRegUsageLatency },
1858 { LatenciesGrouped, BlockRegUsage },
1859// { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1860 { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1861 { LatenciesAlonePlusConsecutive, BlockRegUsage }
1862 };
1863 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1864 Temp = Scheduler.scheduleVariant(v.first, v.second);
1865 if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
1866 Best = Temp;
1867 }
1868 }
Matt Arsenault105c2a22016-07-01 18:03:46 +00001869
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001870 ScheduledSUnits = Best.SUs;
1871 ScheduledSUnitsInv.resize(SUnits.size());
1872
1873 for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
1874 ScheduledSUnitsInv[ScheduledSUnits[i]] = i;
1875 }
1876
1877 moveLowLatencies();
1878
1879 // Tell the outside world about the result of the scheduling.
1880
1881 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1882 TopRPTracker.setPos(CurrentTop);
1883
1884 for (std::vector<unsigned>::iterator I = ScheduledSUnits.begin(),
1885 E = ScheduledSUnits.end(); I != E; ++I) {
1886 SUnit *SU = &SUnits[*I];
1887
1888 scheduleMI(SU, true);
1889
1890 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
1891 << *SU->getInstr());
1892 }
1893
1894 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1895
1896 placeDebugValues();
1897
1898 DEBUG({
1899 unsigned BBNum = begin()->getParent()->getNumber();
1900 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1901 dumpSchedule();
1902 dbgs() << '\n';
1903 });
1904}