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 assert(!contains(N) && "Node already exists in ready list!");
70#endif
71 List.push(N);
72 }
74 auto *Back = List.top();
75 List.pop();
76 return Back;
77 }
78 bool empty() const { return List.empty(); }
79 void clear() { List = {}; }
80 bool contains(DGNode *N) const {
81 // TODO: We should update the data structure to make this O(1).
82 auto ListCopy = List;
83 while (!ListCopy.empty()) {
84 DGNode *Top = ListCopy.top();
85 if (Top == N)
86 return true;
87 ListCopy.pop();
88 }
89 return false;
90 }
91 /// \Removes \p N if found in the ready list.
92 void remove(DGNode *N) {
93 // TODO: Use a more efficient data-structure for the ready list because the
94 // priority queue does not support fast removals.
96 Keep.reserve(List.size());
97 while (!List.empty()) {
98 auto *Top = List.top();
99 List.pop();
100 if (Top == N)
101 break;
102 Keep.push_back(Top);
103 }
104 for (auto *KeepN : Keep)
105 List.push(KeepN);
106 }
107#ifndef NDEBUG
108 void dump(raw_ostream &OS) const;
109 LLVM_DUMP_METHOD void dump() const;
110#endif // NDEBUG
111};
112
113/// The nodes that need to be scheduled back-to-back in a single scheduling
114/// cycle form a SchedBundle.
116public:
118
119private:
120 ContainerTy Nodes;
121
122 /// Called by the DGNode destructor to avoid accessing freed memory.
123 void eraseFromBundle(DGNode *N) { llvm::erase(Nodes, N); }
124 friend void DGNode::setSchedBundle(SchedBundle &); // For eraseFromBunde().
125 friend DGNode::~DGNode(); // For eraseFromBundle().
126
127public:
128 SchedBundle() = default;
129 SchedBundle(ContainerTy &&Nodes) : Nodes(std::move(Nodes)) {
130 for (auto *N : this->Nodes)
131 N->setSchedBundle(*this);
132 }
133 /// Copy CTOR (unimplemented).
134 SchedBundle(const SchedBundle &Other) = delete;
135 /// Copy Assignment (unimplemented).
138 for (auto *N : this->Nodes)
139 N->clearSchedBundle();
140 }
141 bool empty() const { return Nodes.empty(); }
142 /// Singleton bundles are created when scheduling instructions temporarily to
143 /// fill in the schedule until we schedule the vector bundle. These are
144 /// non-vector bundles containing just a single instruction.
145 bool isSingleton() const { return Nodes.size() == 1u; }
146 DGNode *back() const { return Nodes.back(); }
149 iterator begin() { return Nodes.begin(); }
150 iterator end() { return Nodes.end(); }
151 const_iterator begin() const { return Nodes.begin(); }
152 const_iterator end() const { return Nodes.end(); }
153 /// \Returns the bundle node that comes before the others in program order.
154 LLVM_ABI DGNode *getTop() const;
155 /// \Returns the bundle node that comes after the others in program order.
156 LLVM_ABI DGNode *getBot() const;
157 /// Move all bundle instructions to \p Where back-to-back.
159 /// \Returns true if all nodes in the bundle are ready.
160 bool ready(SchedDirection Dir) const {
161 return all_of(Nodes, [Dir](const auto *N) {
162 return Dir == SchedDirection::BottomUp ? N->readyBottomUp()
163 : N->readyTopDown();
164 });
165 }
166#ifndef NDEBUG
167 void dump(raw_ostream &OS) const;
168 LLVM_DUMP_METHOD void dump() const;
169#endif
170};
171
172/// The scheduling point in the context of the Scheduler points to the
173/// top-of-schedule (i.e., the top-most instruction of the top bundle) during
174/// bottom-up scheduling or the bottom of the schedule (i.e., the bottom-most
175/// instruction of the bottom bundle) during top-down.
176///
177/// This class can be thought of as an extended BB::iterator, one that can
178/// not only point to after the last instruction in a BB (i.e., BB.end()), but
179/// also before the first instruction (i.e., something equivalent to
180/// prev(BB.begin()), which is not a legal BasicBlock::iterator).
181///
182/// This is needed for symmetric implementations of top-down and bottom-up
183/// scheduling. More specifically, if this is the first scheduling attempt we
184/// need the scheduling front to still point to a hypothetical last scheduling
185/// point. In bottom-up this can be at BB.end() but in top-down this can be
186/// before BB.begin(). This is why a BasicBlock::iterator is not suitable for
187/// this.
188class SchedulingPoint {
189 /// If Where contains a Block, then we are pointing before BB.begin(),
190 /// otherwise if it contains an iterator then we point to anywhere in the BB
191 /// or at BB.end().
192 std::variant<BasicBlock::iterator, BasicBlock *> Where;
193
194 /// Creates a scheduling point pointing before the beginning of BB.
195 SchedulingPoint(BasicBlock &BB) : Where(&BB) {}
196
197public:
198 /// Creates a scheduling point pointing at \p It, meaning any instruction in a
199 /// BB or BB.end().
201 /// Returns a SchedulingPoint that points to \p It.
202 static SchedulingPoint createAt(BasicBlock::iterator It) {
203 return SchedulingPoint(It);
204 }
205 /// Returns a SchedulingPoint that points to one element before \p It.
206 static SchedulingPoint createBefore(BasicBlock::iterator It) {
207 BasicBlock &BB = *It.getNodeParent();
208 if (It == BB.begin())
209 return SchedulingPoint(BB);
210 return SchedulingPoint(std::prev(It));
211 }
212 /// Returns a SchedulingPoint that points to one element after \p It.
213 static SchedulingPoint createAfter(BasicBlock::iterator It) {
214 assert(It != It.getNodeParent()->end() && "Already at end!");
215 return SchedulingPoint(std::next(It));
216 }
217
218 /// If the SchedulingPoint points to before the beginning of a BB, then this
219 /// returns that BB, else returns nullptr.
221 if (std::holds_alternative<BasicBlock::iterator>(Where))
222 return nullptr;
223 return std::get<BasicBlock *>(Where);
224 }
225 /// If the SchedulingPoint points after the last instruction in the BB then
226 /// this returns the corresponding BasicBlock, nullptr otherwise.
228 if (std::holds_alternative<BasicBlock *>(Where))
229 return nullptr;
230 auto It = std::get<BasicBlock::iterator>(Where);
231 return It == It.getNodeParent()->end() ? It.getNodeParent() : nullptr;
232 }
233 /// Returns the instruction pointed to by this SchedulingPoint or null if we
234 /// are before/after BB.
237 return nullptr;
238 return &*std::get<BasicBlock::iterator>(Where);
239 }
240 /// Cast to Instruction *. Asserts that we are pointing to an instruction and
241 /// not before/after the beginning/end of a BB.
242 operator Instruction *() const { return atInstrOrNull(); }
243 /// Returns the corresponding BB::iterator. Asserts that we are not pointing
244 /// before BB begin.
246 assert(!atBeforeBeginOrNull() && "Expected in/after BB!");
247 return std::get<BasicBlock::iterator>(Where);
248 }
249 operator BasicBlock::iterator() const { return getIterator(); }
250 /// Returns the SchedulingPoint pointing after this.
251 SchedulingPoint getNext() const {
252 assert(!atEndOrNull() && "Expected before/in BB!");
254 return BB->begin();
255 return std::next(getIterator());
256 }
257 /// Returns the SchedulingPoint pointing before this.
258 SchedulingPoint getPrev() const {
259 assert(!atBeforeBeginOrNull() && "Expected in/after BB!");
260 auto It = getIterator();
261 auto *BB = It.getNodeParent();
262 if (It == BB->begin())
263 return *BB;
264 return std::prev(It);
265 }
266 bool operator==(const SchedulingPoint &Other) const {
267 return Where == Other.Where;
268 }
269#ifndef NDEBUG
270 void print(raw_ostream &OS) const;
271 LLVM_DUMP_METHOD void dump() const;
272#endif
273};
274
275/// The list scheduler.
276class Scheduler {
277 /// This is a list-scheduler and this is the list containing the instructions
278 /// that are ready, meaning that all their dependency successors have already
279 /// been scheduled.
280 ReadyListContainer ReadyList;
281 /// The dependency graph is used by the scheduler to determine the legal
282 /// ordering of instructions.
283 DependencyGraph DAG;
284 friend class SchedulerInternalsAttorney; // For DAG.
285 Context &Ctx;
286 /// This is the top of the schedule during bottom-up scheduling and the bottom
287 /// of the schedule during top-down. It points to the position of the last
288 /// top-most/bottom-most instruction scheduled. It may get updated after every
289 /// trySchedule() attempt, regardless of whether scheduling succeeded or not.
290 /// It is nullopt if we have not scheduled before.
291 std::optional<SchedulingPoint> ScheduleTopItOpt;
292 // TODO: This is wasting memory in exchange for fast removal using a raw ptr.
294 /// The BB that we are currently scheduling.
295 BasicBlock *ScheduledBB = nullptr;
296 /// The ID of the callback we register with Sandbox IR.
297 std::optional<Context::CallbackID> CreateInstrCB;
298 /// Called by Sandbox IR's callback system, after \p I has been created.
299 /// NOTE: This should run after DAG's callback has run.
300 // TODO: Perhaps call DAG's notify function from within this one?
301 LLVM_ABI void notifyCreateInstr(Instruction *I);
302
303 /// \Returns a scheduling bundle containing \p Instrs.
304 SchedBundle *createBundle(ArrayRef<Instruction *> Instrs);
305 void eraseBundle(SchedBundle *SB);
306 /// Schedule nodes until we can schedule \p Instrs back-to-back.
307 bool tryScheduleUntil(ArrayRef<Instruction *> Instrs);
308 /// Schedules all nodes in \p Bndl, marks them as scheduled, updates the
309 /// UnscheduledSuccs counter of all dependency predecessors, and adds any of
310 /// them that become ready to the ready list.
311 void scheduleAndUpdateReadyList(SchedBundle &Bndl);
312 /// The scheduling state of the instructions in the bundle.
313 enum class BndlSchedState {
314 NoneScheduled, ///> No instruction in the bundle was previously scheduled.
315 AlreadyScheduled, ///> At least one instruction in the bundle belongs to a
316 /// different non-singleton scheduling bundle.
317 TemporarilyScheduled, ///> Instructions were temporarily scheduled as
318 /// singleton bundles or some of them were not
319 /// scheduled at all. None of them were in a vector
320 ///(non-singleton) bundle.
321 FullyScheduled, ///> All instrs in the bundle were previously scheduled and
322 /// were in the same SchedBundle.
323 };
324 /// \Returns whether none/some/all of \p Instrs have been scheduled.
325 LLVM_ABI BndlSchedState
326 getBndlSchedState(ArrayRef<Instruction *> Instrs) const;
327 /// Destroy the top-most part of the schedule that includes \p Instrs.
328 void trimSchedule(ArrayRef<Instruction *> Instrs);
329 /// Disable copies.
330 Scheduler(const Scheduler &) = delete;
331 Scheduler &operator=(const Scheduler &) = delete;
332
333private:
335
336public:
338 : DAG(Dir, AA, Ctx), Ctx(Ctx), Dir(Dir) {
339 // NOTE: The scheduler's callback depends on the DAG's callback running
340 // before it and updating the DAG accordingly.
341 CreateInstrCB = Ctx.registerCreateInstrCallback(
342 [this](Instruction *I) { notifyCreateInstr(I); });
343 }
345 if (CreateInstrCB)
346 Ctx.unregisterCreateInstrCallback(*CreateInstrCB);
347 }
348 /// Tries to build a schedule that includes all of \p Instrs scheduled at the
349 /// same scheduling cycle. This essentially checks that there are no
350 /// dependencies among \p Instrs. This function may involve scheduling
351 /// intermediate instructions or canceling and re-scheduling if needed.
352 /// \Returns true on success, false otherwise.
354 /// Clear the scheduler's state, including the DAG.
355 void clear() {
356 Bndls.clear();
357 // TODO: clear view once it lands.
358 DAG.clear();
359 ReadyList.clear();
360 ScheduleTopItOpt = std::nullopt;
361 ScheduledBB = nullptr;
362 assert(Bndls.empty() && DAG.empty() && ReadyList.empty() &&
363 !ScheduleTopItOpt && ScheduledBB == nullptr &&
364 "Expected empty state!");
365 }
366
367#ifndef NDEBUG
368 void dump(raw_ostream &OS) const;
369 LLVM_DUMP_METHOD void dump() const;
370#endif
371};
372
373/// A client-attorney class for accessing the Scheduler's internals (used for
374/// unit tests).
376public:
377 static DependencyGraph &getDAG(Scheduler &Sched) { return Sched.DAG; }
378 using BndlSchedState = Scheduler::BndlSchedState;
381 return Sched.getBndlSchedState(Instrs);
382 }
383};
384
385} // namespace llvm::sandboxir
386
387#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:678
#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:446
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.
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:63
void remove(DGNode *N)
\Removes N if found in the ready list.
Definition Scheduler.h:92
bool contains(DGNode *N) const
Definition Scheduler.h:80
The nodes that need to be scheduled back-to-back in a single scheduling cycle form a SchedBundle.
Definition Scheduler.h:115
LLVM_ABI DGNode * getBot() const
\Returns the bundle node that comes after the others in program order.
Definition Scheduler.cpp:24
SchedBundle(ContainerTy &&Nodes)
Definition Scheduler.h:129
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:15
bool isSingleton() const
Singleton bundles are created when scheduling instructions temporarily to fill in the schedule until ...
Definition Scheduler.h:145
SmallVector< DGNode *, 4 > ContainerTy
Definition Scheduler.h:117
const_iterator begin() const
Definition Scheduler.h:151
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:48
SchedBundle(const SchedBundle &Other)=delete
Copy CTOR (unimplemented).
ContainerTy::iterator iterator
Definition Scheduler.h:147
const_iterator end() const
Definition Scheduler.h:152
ContainerTy::const_iterator const_iterator
Definition Scheduler.h:148
LLVM_ABI void cluster(BasicBlock::iterator Where)
Move all bundle instructions to Where back-to-back.
Definition Scheduler.cpp:33
bool ready(SchedDirection Dir) const
\Returns true if all nodes in the bundle are ready.
Definition Scheduler.h:160
A client-attorney class for accessing the Scheduler's internals (used for unit tests).
Definition Scheduler.h:375
static BndlSchedState getBndlSchedState(const Scheduler &Sched, ArrayRef< Instruction * > Instrs)
Definition Scheduler.h:379
Scheduler::BndlSchedState BndlSchedState
Definition Scheduler.h:378
static DependencyGraph & getDAG(Scheduler &Sched)
Definition Scheduler.h:377
The list scheduler.
Definition Scheduler.h:276
friend class SchedulerInternalsAttorney
Definition Scheduler.h:284
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:355
Scheduler(AAResults &AA, Context &Ctx, SchedDirection Dir)
Definition Scheduler.h:337
SchedulingPoint getNext() const
Returns the SchedulingPoint pointing after this.
Definition Scheduler.h:251
BasicBlock * atEndOrNull() const
If the SchedulingPoint points after the last instruction in the BB then this returns the correspondin...
Definition Scheduler.h:227
Instruction * atInstrOrNull() const
Returns the instruction pointed to by this SchedulingPoint or null if we are before/after BB.
Definition Scheduler.h:235
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:77
SchedulingPoint getPrev() const
Returns the SchedulingPoint pointing before this.
Definition Scheduler.h:258
BasicBlock::iterator getIterator() const
Returns the corresponding BB::iterator.
Definition Scheduler.h:245
BasicBlock * atBeforeBeginOrNull() const
If the SchedulingPoint points to before the beginning of a BB, then this returns that BB,...
Definition Scheduler.h:220
static SchedulingPoint createAt(BasicBlock::iterator It)
Returns a SchedulingPoint that points to It.
Definition Scheduler.h:202
static SchedulingPoint createBefore(BasicBlock::iterator It)
Returns a SchedulingPoint that points to one element before It.
Definition Scheduler.h:206
SchedulingPoint(BasicBlock::iterator It)
Creates a scheduling point pointing at It, meaning any instruction in a BB or BB.end().
Definition Scheduler.h:200
bool operator==(const SchedulingPoint &Other) const
Definition Scheduler.h:266
void print(raw_ostream &OS) const
Definition Scheduler.cpp:68
static SchedulingPoint createAfter(BasicBlock::iterator It)
Returns a SchedulingPoint that points to one element after It.
Definition Scheduler.h:213
Abstract Attribute helper functions.
Definition Attributor.h:165
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:229
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N