LLVM 24.0.0git
Scheduler.cpp
Go to the documentation of this file.
1//===- Scheduler.cpp ------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11
12namespace llvm::sandboxir {
13
14#ifndef NDEBUG
16 switch (Dir) {
18 return "BottomUp";
20 return "TopDown";
21 }
22 llvm_unreachable("Unhandled Dir!");
23}
24#endif // NDEBUG
25
26// TODO: Check if we can cache top/bottom to reduce compile-time.
28 DGNode *TopN = Nodes.front();
29 for (auto *N : drop_begin(Nodes)) {
30 if (N->getInstruction()->comesBefore(TopN->getInstruction()))
31 TopN = N;
32 }
33 return TopN;
34}
35
37 DGNode *BotN = Nodes.front();
38 for (auto *N : drop_begin(Nodes)) {
39 if (BotN->getInstruction()->comesBefore(N->getInstruction()))
40 BotN = N;
41 }
42 return BotN;
43}
44
46 for (auto *N : Nodes) {
47 auto *I = N->getInstruction();
48 if (I->getIterator() == Where)
49 ++Where; // Try to maintain bundle order.
50 I->moveBefore(*Where.getNodeParent(), Where);
51 }
52}
53
54#ifndef NDEBUG
56 for (auto *N : Nodes)
57 OS << *N;
58}
59
60void SchedBundle::dump() const {
61 dump(dbgs());
62 dbgs() << "\n";
63}
64#endif // NDEBUG
65
66#ifndef NDEBUG
68 auto ListCopy = List;
69 while (!ListCopy.empty()) {
70 OS << *ListCopy.top() << "\n";
71 ListCopy.pop();
72 }
73}
74
76 dump(dbgs());
77 dbgs() << "\n";
78}
79
82 OS << "Before begin of BB " << BB->getName();
83 else if (BasicBlock *BB = atEndOrNull())
84 OS << "At end of BB " << BB->getName();
85 else
86 OS << "At instr: " << *atInstrOrNull();
87}
88
90 print(dbgs());
91 dbgs() << "\n";
92}
93#endif // NDEBUG
94
95void Scheduler::scheduleAndUpdateReadyList(SchedBundle &Bndl) {
96 // Find where we should schedule the instructions.
97 assert(ScheduleTopItOpt && "Should have been set by now!");
98 auto Where = Dir == SchedDirection::BottomUp
99 ? ScheduleTopItOpt->getIterator()
100 : ScheduleTopItOpt->getNext().getIterator();
101 // Move all instructions in `Bndl` to `Where`.
102 Bndl.cluster(Where);
103 // Update the last scheduled bundle.
104 ScheduleTopItOpt = Dir == SchedDirection::BottomUp
105 ? Bndl.getTop()->getInstruction()->getIterator()
106 : Bndl.getBot()->getInstruction()->getIterator();
107 // Set nodes as "scheduled" and decrement the UnscheduledSuccs/Preds counter
108 // of all dependency predecessors/successors.
109 for (DGNode *N : Bndl) {
110 switch (Dir) {
112 for (auto *DepN : N->preds(DAG)) {
113 DepN->decrUnscheduledSuccs();
114 if (DepN->readyBottomUp() && !DepN->scheduled())
115 ReadyList.insert(DepN);
116 }
117 break;
118 }
120 for (auto *DepN : N->succs(DAG)) {
121 DepN->decrUnscheduledPreds();
122 if (DepN->readyTopDown() && !DepN->scheduled())
123 ReadyList.insert(DepN);
124 }
125 break;
126 }
127 }
128 N->setScheduled();
129 }
130}
131
132void Scheduler::notifyCreateInstr(Instruction *I) {
133 // The DAG notifier should have run by now.
134 auto *N = DAG.getNode(I);
135 // If there is no DAG node for `I` it means that this is out of scope for the
136 // DAG and as such out of scope for the scheduler too, so nothing to do.
137 if (N == nullptr)
138 return;
139 // If the instruction is inserted below the top-of-schedule then we mark it as
140 // "scheduled".
141 bool IsScheduled = ScheduleTopItOpt &&
142 ScheduleTopItOpt->getIterator() != I->getParent()->end() &&
143 ((Dir == SchedDirection::BottomUp &&
144 (*ScheduleTopItOpt.value()).comesBefore(I)) ||
145 (Dir == SchedDirection::TopDown &&
146 I->comesBefore(&*ScheduleTopItOpt.value())));
147 if (IsScheduled)
148 N->setScheduled();
149 // If the new instruction is above the top of schedule we need to remove its
150 // dependency predecessors from the ready list and increment their
151 // `UnscheduledSuccs` counters.
152 if (!IsScheduled) {
153 if (Dir == SchedDirection::BottomUp) {
154 for (auto *PredN : N->preds(DAG)) {
155 ReadyList.remove(PredN);
156 PredN->incrUnscheduledSuccs();
157 }
158 } else {
159 for (auto *SuccN : N->succs(DAG)) {
160 ReadyList.remove(SuccN);
161 SuccN->incrUnscheduledPreds();
162 }
163 }
164 }
165}
166
167SchedBundle *Scheduler::createBundle(ArrayRef<Instruction *> Instrs) {
169 Nodes.reserve(Instrs.size());
170 for (auto *I : Instrs)
171 Nodes.push_back(DAG.getNode(I));
172 auto BndlPtr = std::make_unique<SchedBundle>(std::move(Nodes));
173 auto *Bndl = BndlPtr.get();
174 Bndls[Bndl] = std::move(BndlPtr);
175 return Bndl;
176}
177
178void Scheduler::eraseBundle(SchedBundle *SB) { Bndls.erase(SB); }
179
180bool Scheduler::tryScheduleUntil(ArrayRef<Instruction *> Instrs) {
181 // Create a bundle for Instrs. If it turns out the schedule is infeasible we
182 // will dismantle it.
183 auto *InstrsSB = createBundle(Instrs);
184 // Keep scheduling ready nodes until we either run out of ready nodes (i.e.,
185 // ReadyList is empty), or all nodes that correspond to `Instrs` (the nodes of
186 // which are collected in DeferredNodes) are all ready to schedule.
188 bool KeepScheduling = true;
189 while (KeepScheduling) {
190 enum class TryScheduleRes {
191 Success, ///> We successfully scheduled the bundle.
192 Failure, ///> We failed to schedule the bundle.
193 Finished, ///> We successfully scheduled the bundle and it is the last
194 /// bundle to be scheduled.
195 };
196 /// TryScheduleNode() attempts to schedule all DAG nodes in the bundle that
197 /// ReadyN is in. If it's not in a bundle it will create a singleton bundle
198 /// and will try to schedule it.
199 auto TryScheduleBndl = [this, InstrsSB](DGNode *ReadyN) -> TryScheduleRes {
200 auto *SB = ReadyN->getSchedBundle();
201 if (SB == nullptr) {
202 // If ReadyN does not belong to a bundle, create a singleton bundle
203 // and schedule it.
204 auto *SingletonSB = createBundle({ReadyN->getInstruction()});
205 scheduleAndUpdateReadyList(*SingletonSB);
206 return TryScheduleRes::Success;
207 }
208 if (SB->ready(Dir)) {
209 // Remove the rest of the bundle from the ready list.
210 // TODO: Perhaps change the Scheduler + ReadyList to operate on
211 // SchedBundles instead of DGNodes.
212 for (auto *N : *SB) {
213 if (N != ReadyN)
214 ReadyList.remove(N);
215 }
216 // If all nodes in the bundle are ready.
217 scheduleAndUpdateReadyList(*SB);
218 if (SB == InstrsSB)
219 // We just scheduled InstrsSB bundle, so we are done scheduling.
220 return TryScheduleRes::Finished;
221 return TryScheduleRes::Success;
222 }
223 return TryScheduleRes::Failure;
224 };
225 while (!ReadyList.empty()) {
226 auto *ReadyN = ReadyList.pop();
227 auto Res = TryScheduleBndl(ReadyN);
228 switch (Res) {
229 case TryScheduleRes::Success:
230 // We successfully scheduled ReadyN, keep scheduling.
231 continue;
232 case TryScheduleRes::Failure:
233 // We failed to schedule ReadyN, defer it to later and keep scheduling
234 // other ready instructions.
235 Retry.push_back(ReadyN);
236 continue;
237 case TryScheduleRes::Finished:
238 // We successfully scheduled the instruction bundle, so we are done.
239 return true;
240 }
241 llvm_unreachable("Unhandled TrySchedule() result");
242 }
243 // Try to schedule nodes from the Retry list.
244 KeepScheduling = false;
245 for (auto *N : make_early_inc_range(Retry)) {
246 auto Res = TryScheduleBndl(N);
247 if (Res == TryScheduleRes::Success) {
248 Retry.erase(find(Retry, N));
249 KeepScheduling = true;
250 }
251 }
252 }
253
254 eraseBundle(InstrsSB);
255 return false;
256}
257
258Scheduler::BndlSchedState
259Scheduler::getBndlSchedState(ArrayRef<Instruction *> Instrs) const {
260 assert(!Instrs.empty() && "Expected non-empty bundle");
261 auto *N0 = DAG.getNode(Instrs[0]);
262 auto *SB0 = N0 != nullptr ? N0->getSchedBundle() : nullptr;
263 bool AllUnscheduled = SB0 == nullptr;
264 bool FullyScheduled = SB0 != nullptr && !SB0->isSingleton();
265 for (auto *I : drop_begin(Instrs)) {
266 auto *N = DAG.getNode(I);
267 auto *SB = N != nullptr ? N->getSchedBundle() : nullptr;
268 if (SB != nullptr) {
269 // We found a scheduled instr, so there is now way all are unscheduled.
270 AllUnscheduled = false;
271 if (SB->isSingleton()) {
272 // We found an instruction in a temporarily scheduled singleton. There
273 // is no way that all instructions are scheduled in the same bundle.
274 FullyScheduled = false;
275 }
276 }
277
278 if (SB != SB0) {
279 // Either one of SB, SB0 is null, or they are in different bundles, so
280 // Instrs are definitely not in the same vector bundle.
281 FullyScheduled = false;
282 // One of SB, SB0 are in a vector bundle and they differ.
283 if ((SB != nullptr && !SB->isSingleton()) ||
284 (SB0 != nullptr && !SB0->isSingleton()))
285 return BndlSchedState::AlreadyScheduled;
286 }
287 }
288 return AllUnscheduled ? BndlSchedState::NoneScheduled
289 : FullyScheduled ? BndlSchedState::FullyScheduled
290 : BndlSchedState::TemporarilyScheduled;
291}
292
293void Scheduler::trimSchedule(ArrayRef<Instruction *> Instrs) {
294 // | Legend: N: DGNode
295 // N <- DAGInterval.top() | B: SchedBundle
296 // N | *: Contains instruction in Instrs
297 // B <- TopI (Top of schedule) +-------------------------------------------
298 // B
299 // B *
300 // B
301 // B * <- LowestI (Lowest in Instrs)
302 // B
303 // N
304 // N
305 // N <- DAGInterval.bottom()
306 //
307 // Note: this figure assumes bottom-up scheduling. In top-down we have the
308 // top-down mirror image.
310 ? &*ScheduleTopItOpt.value()
311 : VecUtils::getHighest(Instrs);
312 Instruction *LowestI = Dir == SchedDirection::BottomUp
313 ? VecUtils::getLowest(Instrs)
314 : &*ScheduleTopItOpt.value();
315 Interval<Instruction> ResetIntvl(TopI, LowestI);
316 // The DAG Nodes contain state like the number of UnscheduledSuccs and the
317 // Scheduled flag. We need to reset their state. We need to do this for all
318 // nodes in ResetIntvl. Also destroy the singleton schedule bundles from
319 // LowestI all the way to the top.
320 for (auto &I : ResetIntvl) {
321 auto *N = DAG.getNode(&I);
322 if (N == nullptr)
323 continue;
324 auto *SB = N->getSchedBundle();
325 if (SB->isSingleton())
326 eraseBundle(SB);
327 N->resetScheduleState();
328 }
329 // Nodes that depend on the nodes in ResetIntvl also need to have their
330 // UnscheduledSuccs/UnscheduledPreds adjusted.
331 for (Instruction &I : ResetIntvl) {
332 auto *N = DAG.getNode(&I);
333 if (Dir == SchedDirection::BottomUp) {
334 // Recompute UnscheduledSuccs for nodes not only in ResetIntvl but even
335 // for nodes above the top of schedule.
336 for (auto *PredN : N->preds(DAG))
337 PredN->incrUnscheduledSuccs();
338 } else {
340 // Recompute UnscheduledPreds for nodes not only in ResetIntvl but even
341 // for nodes below the bottom of schedule.
342 for (auto *SuccN : N->succs(DAG))
343 SuccN->incrUnscheduledPreds();
344 }
345 }
346
347 // Refill the ready list by visiting all the nodes in the unscheduled part of
348 // the DAG. In bottom-up that is from the top of the DAG down to LowestI; in
349 // top-down it is the mirror image, from TopI down to the bottom of the DAG.
350 ReadyList.clear();
351 Interval<Instruction> RefillIntvl =
353 ? Interval<Instruction>(DAG.getInterval().top(), LowestI)
354 : Interval<Instruction>(TopI, DAG.getInterval().bottom());
355 for (Instruction &I : RefillIntvl) {
356 auto *N = DAG.getNode(&I);
357 if (Dir == SchedDirection::BottomUp ? N->readyBottomUp()
358 : N->readyTopDown())
359 ReadyList.insert(N);
360 }
361}
362
364 assert(all_of(drop_begin(Instrs),
365 [Instrs](Instruction *I) {
366 return I->getParent() == (*Instrs.begin())->getParent();
367 }) &&
368 "Instrs not in the same BB, should have been rejected by Legality!");
369 // TODO: For now don't cross BBs.
370 if (!DAG.getInterval().empty()) {
371 auto *BB = DAG.getInterval().top()->getParent();
372 if (any_of(Instrs, [BB](auto *I) { return I->getParent() != BB; }))
373 return false;
374 }
375 if (ScheduledBB == nullptr)
376 ScheduledBB = Instrs[0]->getParent();
377 // We don't support crossing BBs for now.
378 if (any_of(Instrs,
379 [this](Instruction *I) { return I->getParent() != ScheduledBB; }))
380 return false;
381
382 auto GetSchedPoint = [](SchedDirection Dir,
383 const auto &Instrs) -> SchedulingPoint {
384 switch (Dir) {
386 return SchedulingPoint(VecUtils::getLowest(Instrs)->getIterator())
387 .getNext();
389 return SchedulingPoint(VecUtils::getHighest(Instrs)->getIterator())
390 .getPrev();
391 }
392 llvm_unreachable("Unhandled Dir!");
393 };
394 auto SchedState = getBndlSchedState(Instrs);
395 switch (SchedState) {
396 case BndlSchedState::FullyScheduled:
397 // Nothing to do.
398 return true;
399 case BndlSchedState::AlreadyScheduled:
400 // Instructions are part of a different vector schedule, so we can't
401 // schedule \p Instrs in the same bundle (without destroying the existing
402 // schedule).
403 return false;
404 case BndlSchedState::TemporarilyScheduled:
405 // If one or more instrs are already scheduled we need to destroy the
406 // top-most part of the schedule that includes the instrs in the bundle and
407 // re-schedule.
408 DAG.extend(Instrs);
409 trimSchedule(Instrs);
410 ScheduleTopItOpt = GetSchedPoint(Dir, Instrs);
411 return tryScheduleUntil(Instrs);
412 case BndlSchedState::NoneScheduled: {
413 // TODO: Set the window of the DAG that we are interested in.
414 if (!ScheduleTopItOpt)
415 // We start scheduling at the bottom instr of Instrs (top in TopDown).
416 ScheduleTopItOpt = GetSchedPoint(Dir, Instrs);
417 // Extend the DAG to include Instrs.
418 Interval<Instruction> Extension = DAG.extend(Instrs);
419 // Add nodes from the new interval to ready list if they are ready.
420 for (auto &I : Extension) {
421 auto *N = DAG.getNode(&I);
422 if (Dir == SchedDirection::BottomUp ? N->readyBottomUp()
423 : N->readyTopDown())
424 ReadyList.insert(N);
425 }
426 // Try schedule all nodes until we can schedule Instrs back-to-back.
427 return tryScheduleUntil(Instrs);
428 }
429 }
430 llvm_unreachable("Unhandled BndlSchedState enum");
431}
432
433#ifndef NDEBUG
435 OS << "ReadyList:\n";
436 ReadyList.dump(OS);
437 OS << "Dir=" << schedDirectionToStr(Dir) << " "
438 << (Dir == SchedDirection::BottomUp ? "Top" : "Bottom")
439 << " of schedule: ";
440 if (ScheduleTopItOpt)
441 OS << **ScheduleTopItOpt;
442 else
443 OS << "Empty";
444 OS << "\n";
445}
446void Scheduler::dump() const { dump(dbgs()); }
447#endif // NDEBUG
448
449} // namespace llvm::sandboxir
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define I(x, y, z)
Definition MD5.cpp:57
std::pair< uint64_t, uint64_t > Interval
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator begin() const
Definition ArrayRef.h:129
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
void reserve(size_type N)
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:888
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A DependencyGraph Node that points to an Instruction and contains memory dependency edges.
Instruction * getInstruction() const
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition Instruction.h:43
LLVM_ABI BBIterator getIterator() const
\Returns a BasicBlock::iterator for this Instruction.
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:75
The nodes that need to be scheduled back-to-back in a single scheduling cycle form a SchedBundle.
Definition Scheduler.h:117
LLVM_ABI DGNode * getBot() const
\Returns the bundle node that comes after the others in program order.
Definition Scheduler.cpp:36
LLVM_ABI DGNode * getTop() const
\Returns the bundle node that comes before the others in program order.
Definition Scheduler.cpp:27
SmallVector< DGNode *, 4 > ContainerTy
Definition Scheduler.h:119
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:60
LLVM_ABI void cluster(BasicBlock::iterator Where)
Move all bundle instructions to Where back-to-back.
Definition Scheduler.cpp:45
LLVM_DUMP_METHOD void dump() const
LLVM_ABI bool trySchedule(ArrayRef< Instruction * > Instrs)
Tries to build a schedule that includes all of Instrs scheduled at the same scheduling cycle.
The scheduling point in the context of the Scheduler points to the top-of-schedule (i....
Definition Scheduler.h:190
SchedulingPoint getNext() const
Returns the SchedulingPoint pointing after this.
Definition Scheduler.h:253
BasicBlock * atEndOrNull() const
If the SchedulingPoint points after the last instruction in the BB then this returns the correspondin...
Definition Scheduler.h:229
Instruction * atInstrOrNull() const
Returns the instruction pointed to by this SchedulingPoint or null if we are before/after BB.
Definition Scheduler.h:237
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:89
SchedulingPoint getPrev() const
Returns the SchedulingPoint pointing before this.
Definition Scheduler.h:260
BasicBlock * atBeforeBeginOrNull() const
If the SchedulingPoint points to before the beginning of a BB, then this returns that BB,...
Definition Scheduler.h:222
void print(raw_ostream &OS) const
Definition Scheduler.cpp:80
static Instruction * getLowest(ArrayRef< Instruction * > Instrs)
\Returns the instruction in Instrs that is lowest in the BB.
Definition VecUtils.h:141
static Instruction * getHighest(ArrayRef< Instruction * > Instrs)
\Returns the instruction in Instrs that is highest in the BB.
Definition VecUtils.h:151
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
StringLiteral schedDirectionToStr(SchedDirection Dir)
Definition Scheduler.cpp:15
BasicBlock(llvm::BasicBlock *BB, Context &SBCtx)
Definition BasicBlock.h:75
template class LLVM_TEMPLATE_ABI Interval< Instruction >
Definition Interval.cpp:46
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Success
The lock was released successfully.
ArrayRef(const T &OneElt) -> ArrayRef< T >
#define N