LLVM 24.0.0git
Scheduler.h
Go to the documentation of this file.
1//===- Scheduler.h ----------------------------------------------*- C++ -*-===//
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//
9// This is the bottom-up list scheduler used by the vectorizer. It is used for
10// checking the legality of vectorization and for scheduling instructions in
11// such a way that makes vectorization possible, if legal.
12//
13// The legality check is performed by `trySchedule(Instrs)`, which will try to
14// schedule the IR until all instructions in `Instrs` can be scheduled together
15// back-to-back. If this fails then it is illegal to vectorize `Instrs`.
16//
17// Internally the scheduler uses the vectorizer-specific DependencyGraph class.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_SCHEDULER_H
22#define LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_SCHEDULER_H
23
27#include <queue>
28#include <variant>
29
30namespace llvm::sandboxir {
31
33public:
34 bool operator()(const DGNode *N1, const DGNode *N2) {
35 // Given that the DAG does not model dependencies such that PHIs are always
36 // at the top, or terminators always at the bottom, we need to force the
37 // priority here in the comparator of the ready list container.
38 auto *I1 = N1->getInstruction();
39 auto *I2 = N2->getInstruction();
40 bool IsTerm1 = I1->isTerminator();
41 bool IsTerm2 = I2->isTerminator();
42 if (IsTerm1 != IsTerm2)
43 // Terminators have the lowest priority.
44 return IsTerm1 > IsTerm2;
45 bool IsPHI1 = isa<PHINode>(I1);
46 bool IsPHI2 = isa<PHINode>(I2);
47 if (IsPHI1 != IsPHI2)
48 // PHIs have the highest priority.
49 return IsPHI1 < IsPHI2;
50 // Otherwise rely on the instruction order.
51 return I2->comesBefore(I1);
52 }
53};
54
55/// The list holding nodes that are ready to schedule. Used by the scheduler.
57 PriorityCmp Cmp;
58 /// Control/Other dependencies are not modeled by the DAG to save memory.
59 /// These have to be modeled in the ready list for correctness.
60 /// This means that the list will hold back nodes that need to meet such
61 /// unmodeled dependencies.
62 std::priority_queue<DGNode *, std::vector<DGNode *>, PriorityCmp> List;
63
64public:
65 ReadyListContainer() : List(Cmp) {}
66 void insert(DGNode *N) {
67#ifndef NDEBUG
68 assert(!N->scheduled() && "Don't insert a scheduled node!");
69 auto ListCopy = List;
70 while (!ListCopy.empty()) {
71 DGNode *Top = ListCopy.top();
72 ListCopy.pop();
73 assert(Top != N && "Node already exists in ready list!");
74 }
75#endif
76 List.push(N);
77 }
79 auto *Back = List.top();
80 List.pop();
81 return Back;
82 }
83 bool empty() const { return List.empty(); }
84 void clear() { List = {}; }
85 /// \Removes \p N if found in the ready list.
86 void remove(DGNode *N) {
87 // TODO: Use a more efficient data-structure for the ready list because the
88 // priority queue does not support fast removals.
90 Keep.reserve(List.size());
91 while (!List.empty()) {
92 auto *Top = List.top();
93 List.pop();
94 if (Top == N)
95 break;
96 Keep.push_back(Top);
97 }
98 for (auto *KeepN : Keep)
99 List.push(KeepN);
100 }
101#ifndef NDEBUG
102 void dump(raw_ostream &OS) const;
103 LLVM_DUMP_METHOD void dump() const;
104#endif // NDEBUG
105};
106
111#ifndef NDEBUG
112StringLiteral schedDirectionToStr(SchedDirection Dir);
113#endif
114
115/// The nodes that need to be scheduled back-to-back in a single scheduling
116/// cycle form a SchedBundle.
118public:
120
121private:
122 ContainerTy Nodes;
123
124 /// Called by the DGNode destructor to avoid accessing freed memory.
125 void eraseFromBundle(DGNode *N) { llvm::erase(Nodes, N); }
126 friend void DGNode::setSchedBundle(SchedBundle &); // For eraseFromBunde().
127 friend DGNode::~DGNode(); // For eraseFromBundle().
128
129public:
130 SchedBundle() = default;
131 SchedBundle(ContainerTy &&Nodes) : Nodes(std::move(Nodes)) {
132 for (auto *N : this->Nodes)
133 N->setSchedBundle(*this);
134 }
135 /// Copy CTOR (unimplemented).
136 SchedBundle(const SchedBundle &Other) = delete;
137 /// Copy Assignment (unimplemented).
140 for (auto *N : this->Nodes)
141 N->clearSchedBundle();
142 }
143 bool empty() const { return Nodes.empty(); }
144 /// Singleton bundles are created when scheduling instructions temporarily to
145 /// fill in the schedule until we schedule the vector bundle. These are
146 /// non-vector bundles containing just a single instruction.
147 bool isSingleton() const { return Nodes.size() == 1u; }
148 DGNode *back() const { return Nodes.back(); }
151 iterator begin() { return Nodes.begin(); }
152 iterator end() { return Nodes.end(); }
153 const_iterator begin() const { return Nodes.begin(); }
154 const_iterator end() const { return Nodes.end(); }
155 /// \Returns the bundle node that comes before the others in program order.
156 LLVM_ABI DGNode *getTop() const;
157 /// \Returns the bundle node that comes after the others in program order.
158 LLVM_ABI DGNode *getBot() const;
159 /// Move all bundle instructions to \p Where back-to-back.
161 /// \Returns true if all nodes in the bundle are ready.
162 bool ready(SchedDirection Dir) const {
163 return all_of(Nodes, [Dir](const auto *N) {
164 return Dir == SchedDirection::BottomUp ? N->readyBottomUp()
165 : N->readyTopDown();
166 });
167 }
168#ifndef NDEBUG
169 void dump(raw_ostream &OS) const;
170 LLVM_DUMP_METHOD void dump() const;
171#endif
172};
173
174/// The scheduling point in the context of the Scheduler points to the
175/// top-of-schedule (i.e., the top-most instruction of the top bundle) during
176/// bottom-up scheduling or the bottom of the schedule (i.e., the bottom-most
177/// instruction of the bottom bundle) during top-down.
178///
179/// This class can be thought of as an extended BB::iterator, one that can
180/// not only point to after the last instruction in a BB (i.e., BB.end()), but
181/// also before the first instruction (i.e., something equivalent to
182/// prev(BB.begin()), which is not a legal BasicBlock::iterator).
183///
184/// This is needed for symmetric implementations of top-down and bottom-up
185/// scheduling. More specifically, if this is the first scheduling attempt we
186/// need the scheduling front to still point to a hypothetical last scheduling
187/// point. In bottom-up this can be at BB.end() but in top-down this can be
188/// before BB.begin(). This is why a BasicBlock::iterator is not suitable for
189/// this.
190class SchedulingPoint {
191 /// If Where contains a Block, then we are pointing before BB.begin(),
192 /// otherwise if it contains an iterator then we point to anywhere in the BB
193 /// or at BB.end().
194 std::variant<BasicBlock::iterator, BasicBlock *> Where;
195
196 /// Creates a scheduling point pointing before the beginning of BB.
197 SchedulingPoint(BasicBlock &BB) : Where(&BB) {}
198
199public:
200 /// Creates a scheduling point pointing at \p It, meaning any instruction in a
201 /// BB or BB.end().
203 /// Returns a SchedulingPoint that points to \p It.
204 static SchedulingPoint createAt(BasicBlock::iterator It) {
205 return SchedulingPoint(It);
206 }
207 /// Returns a SchedulingPoint that points to one element before \p It.
208 static SchedulingPoint createBefore(BasicBlock::iterator It) {
209 BasicBlock &BB = *It.getNodeParent();
210 if (It == BB.begin())
211 return SchedulingPoint(BB);
212 return SchedulingPoint(std::prev(It));
213 }
214 /// Returns a SchedulingPoint that points to one element after \p It.
215 static SchedulingPoint createAfter(BasicBlock::iterator It) {
216 assert(It != It.getNodeParent()->end() && "Already at end!");
217 return SchedulingPoint(std::next(It));
218 }
219
220 /// If the SchedulingPoint points to before the beginning of a BB, then this
221 /// returns that BB, else returns nullptr.
223 if (std::holds_alternative<BasicBlock::iterator>(Where))
224 return nullptr;
225 return std::get<BasicBlock *>(Where);
226 }
227 /// If the SchedulingPoint points after the last instruction in the BB then
228 /// this returns the corresponding BasicBlock, nullptr otherwise.
230 if (std::holds_alternative<BasicBlock *>(Where))
231 return nullptr;
232 auto It = std::get<BasicBlock::iterator>(Where);
233 return It == It.getNodeParent()->end() ? It.getNodeParent() : nullptr;
234 }
235 /// Returns the instruction pointed to by this SchedulingPoint or null if we
236 /// are before/after BB.
239 return nullptr;
240 return &*std::get<BasicBlock::iterator>(Where);
241 }
242 /// Cast to Instruction *. Asserts that we are pointing to an instruction and
243 /// not before/after the beginning/end of a BB.
244 operator Instruction *() const { return atInstrOrNull(); }
245 /// Returns the corresponding BB::iterator. Asserts that we are not pointing
246 /// before BB begin.
248 assert(!atBeforeBeginOrNull() && "Expected in/after BB!");
249 return std::get<BasicBlock::iterator>(Where);
250 }
251 operator BasicBlock::iterator() const { return getIterator(); }
252 /// Returns the SchedulingPoint pointing after this.
253 SchedulingPoint getNext() const {
254 assert(!atEndOrNull() && "Expected before/in BB!");
256 return BB->begin();
257 return std::next(getIterator());
258 }
259 /// Returns the SchedulingPoint pointing before this.
260 SchedulingPoint getPrev() const {
261 assert(!atBeforeBeginOrNull() && "Expected in/after BB!");
262 auto It = getIterator();
263 auto *BB = It.getNodeParent();
264 if (It == BB->begin())
265 return *BB;
266 return std::prev(It);
267 }
268 bool operator==(const SchedulingPoint &Other) const {
269 return Where == Other.Where;
270 }
271#ifndef NDEBUG
272 void print(raw_ostream &OS) const;
273 LLVM_DUMP_METHOD void dump() const;
274#endif
275};
276
277/// The list scheduler.
278class Scheduler {
279 /// This is a list-scheduler and this is the list containing the instructions
280 /// that are ready, meaning that all their dependency successors have already
281 /// been scheduled.
282 ReadyListContainer ReadyList;
283 /// The dependency graph is used by the scheduler to determine the legal
284 /// ordering of instructions.
285 DependencyGraph DAG;
286 friend class SchedulerInternalsAttorney; // For DAG.
287 Context &Ctx;
288 /// This is the top of the schedule during bottom-up scheduling and the bottom
289 /// of the schedule during top-down. It points to the position of the last
290 /// top-most/bottom-most instruction scheduled. It may get updated after every
291 /// trySchedule() attempt, regardless of whether scheduling succeeded or not.
292 /// It is nullopt if we have not scheduled before.
293 std::optional<SchedulingPoint> ScheduleTopItOpt;
294 // TODO: This is wasting memory in exchange for fast removal using a raw ptr.
296 /// The BB that we are currently scheduling.
297 BasicBlock *ScheduledBB = nullptr;
298 /// The ID of the callback we register with Sandbox IR.
299 std::optional<Context::CallbackID> CreateInstrCB;
300 /// Called by Sandbox IR's callback system, after \p I has been created.
301 /// NOTE: This should run after DAG's callback has run.
302 // TODO: Perhaps call DAG's notify function from within this one?
303 LLVM_ABI void notifyCreateInstr(Instruction *I);
304
305 /// \Returns a scheduling bundle containing \p Instrs.
306 SchedBundle *createBundle(ArrayRef<Instruction *> Instrs);
307 void eraseBundle(SchedBundle *SB);
308 /// Schedule nodes until we can schedule \p Instrs back-to-back.
309 bool tryScheduleUntil(ArrayRef<Instruction *> Instrs);
310 /// Schedules all nodes in \p Bndl, marks them as scheduled, updates the
311 /// UnscheduledSuccs counter of all dependency predecessors, and adds any of
312 /// them that become ready to the ready list.
313 void scheduleAndUpdateReadyList(SchedBundle &Bndl);
314 /// The scheduling state of the instructions in the bundle.
315 enum class BndlSchedState {
316 NoneScheduled, ///> No instruction in the bundle was previously scheduled.
317 AlreadyScheduled, ///> At least one instruction in the bundle belongs to a
318 /// different non-singleton scheduling bundle.
319 TemporarilyScheduled, ///> Instructions were temporarily scheduled as
320 /// singleton bundles or some of them were not
321 /// scheduled at all. None of them were in a vector
322 ///(non-singleton) bundle.
323 FullyScheduled, ///> All instrs in the bundle were previously scheduled and
324 /// were in the same SchedBundle.
325 };
326 /// \Returns whether none/some/all of \p Instrs have been scheduled.
327 LLVM_ABI BndlSchedState
328 getBndlSchedState(ArrayRef<Instruction *> Instrs) const;
329 /// Destroy the top-most part of the schedule that includes \p Instrs.
330 void trimSchedule(ArrayRef<Instruction *> Instrs);
331 /// Disable copies.
332 Scheduler(const Scheduler &) = delete;
333 Scheduler &operator=(const Scheduler &) = delete;
334
335private:
337
338public:
340 : DAG(AA, Ctx), Ctx(Ctx), Dir(Dir) {
341 // NOTE: The scheduler's callback depends on the DAG's callback running
342 // before it and updating the DAG accordingly.
343 CreateInstrCB = Ctx.registerCreateInstrCallback(
344 [this](Instruction *I) { notifyCreateInstr(I); });
345 }
347 if (CreateInstrCB)
348 Ctx.unregisterCreateInstrCallback(*CreateInstrCB);
349 }
350 /// Tries to build a schedule that includes all of \p Instrs scheduled at the
351 /// same scheduling cycle. This essentially checks that there are no
352 /// dependencies among \p Instrs. This function may involve scheduling
353 /// intermediate instructions or canceling and re-scheduling if needed.
354 /// \Returns true on success, false otherwise.
356 /// Clear the scheduler's state, including the DAG.
357 void clear() {
358 Bndls.clear();
359 // TODO: clear view once it lands.
360 DAG.clear();
361 ReadyList.clear();
362 ScheduleTopItOpt = std::nullopt;
363 ScheduledBB = nullptr;
364 assert(Bndls.empty() && DAG.empty() && ReadyList.empty() &&
365 !ScheduleTopItOpt && ScheduledBB == nullptr &&
366 "Expected empty state!");
367 }
368
369#ifndef NDEBUG
370 void dump(raw_ostream &OS) const;
371 LLVM_DUMP_METHOD void dump() const;
372#endif
373};
374
375/// A client-attorney class for accessing the Scheduler's internals (used for
376/// unit tests).
378public:
379 static DependencyGraph &getDAG(Scheduler &Sched) { return Sched.DAG; }
380 using BndlSchedState = Scheduler::BndlSchedState;
383 return Sched.getBndlSchedState(Instrs);
384 }
385};
386
387} // namespace llvm::sandboxir
388
389#endif // LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_SCHEDULER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:672
#define I(x, y, z)
Definition MD5.cpp:57
PostRA Machine Instruction Scheduler
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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.
void setSchedBundle(SchedBundle &SB)
Instruction * getInstruction() const
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition Instruction.h:43
bool operator()(const DGNode *N1, const DGNode *N2)
Definition Scheduler.h:34
The list holding nodes that are ready to schedule. Used by the scheduler.
Definition Scheduler.h:56
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:75
void remove(DGNode *N)
\Removes N if found in the ready list.
Definition Scheduler.h:86
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
SchedBundle(ContainerTy &&Nodes)
Definition Scheduler.h:131
SchedBundle & operator=(const SchedBundle &Other)=delete
Copy Assignment (unimplemented).
LLVM_ABI DGNode * getTop() const
\Returns the bundle node that comes before the others in program order.
Definition Scheduler.cpp:27
bool isSingleton() const
Singleton bundles are created when scheduling instructions temporarily to fill in the schedule until ...
Definition Scheduler.h:147
SmallVector< DGNode *, 4 > ContainerTy
Definition Scheduler.h:119
const_iterator begin() const
Definition Scheduler.h:153
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:60
SchedBundle(const SchedBundle &Other)=delete
Copy CTOR (unimplemented).
ContainerTy::iterator iterator
Definition Scheduler.h:149
const_iterator end() const
Definition Scheduler.h:154
ContainerTy::const_iterator const_iterator
Definition Scheduler.h:150
LLVM_ABI void cluster(BasicBlock::iterator Where)
Move all bundle instructions to Where back-to-back.
Definition Scheduler.cpp:45
bool ready(SchedDirection Dir) const
\Returns true if all nodes in the bundle are ready.
Definition Scheduler.h:162
A client-attorney class for accessing the Scheduler's internals (used for unit tests).
Definition Scheduler.h:377
static BndlSchedState getBndlSchedState(const Scheduler &Sched, ArrayRef< Instruction * > Instrs)
Definition Scheduler.h:381
Scheduler::BndlSchedState BndlSchedState
Definition Scheduler.h:380
static DependencyGraph & getDAG(Scheduler &Sched)
Definition Scheduler.h:379
The list scheduler.
Definition Scheduler.h:278
friend class SchedulerInternalsAttorney
Definition Scheduler.h:286
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.
void clear()
Clear the scheduler's state, including the DAG.
Definition Scheduler.h:357
Scheduler(AAResults &AA, Context &Ctx, SchedDirection Dir)
Definition Scheduler.h:339
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::iterator getIterator() const
Returns the corresponding BB::iterator.
Definition Scheduler.h:247
BasicBlock * atBeforeBeginOrNull() const
If the SchedulingPoint points to before the beginning of a BB, then this returns that BB,...
Definition Scheduler.h:222
static SchedulingPoint createAt(BasicBlock::iterator It)
Returns a SchedulingPoint that points to It.
Definition Scheduler.h:204
static SchedulingPoint createBefore(BasicBlock::iterator It)
Returns a SchedulingPoint that points to one element before It.
Definition Scheduler.h:208
SchedulingPoint(BasicBlock::iterator It)
Creates a scheduling point pointing at It, meaning any instruction in a BB or BB.end().
Definition Scheduler.h:202
bool operator==(const SchedulingPoint &Other) const
Definition Scheduler.h:268
void print(raw_ostream &OS) const
Definition Scheduler.cpp:80
static SchedulingPoint createAfter(BasicBlock::iterator It)
Returns a SchedulingPoint that points to one element after It.
Definition Scheduler.h:215
Abstract Attribute helper functions.
Definition Attributor.h:165
StringLiteral schedDirectionToStr(SchedDirection Dir)
Definition Scheduler.cpp:15
BasicBlock(llvm::BasicBlock *BB, Context &SBCtx)
Definition BasicBlock.h:75
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
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
@ Keep
No function return thunk.
Definition CodeGen.h:162
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N