LLVM 24.0.0git
Scheduler.cpp
Go to the documentation of this file.
1//===--------------------- Scheduler.cpp ------------------------*- 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// A scheduler for processor resource units and processor resource groups.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/Support/Debug.h"
16
17namespace llvm {
18namespace mca {
19
20#define DEBUG_TYPE "llvm-mca"
21
22void Scheduler::initializeStrategy(std::unique_ptr<SchedulerStrategy> S) {
23 // Ensure we have a valid (non-null) strategy object.
24 Strategy = S ? std::move(S) : std::make_unique<DefaultSchedulerStrategy>();
25}
26
27// Anchor the vtable of SchedulerStrategy and DefaultSchedulerStrategy.
30
31#ifndef NDEBUG
32void Scheduler::dump() const {
33 dbgs() << "[SCHEDULER]: WaitSet size is: " << WaitSet.size() << '\n';
34 dbgs() << "[SCHEDULER]: ReadySet size is: " << ReadySet.size() << '\n';
35 dbgs() << "[SCHEDULER]: IssuedSet size is: " << IssuedSet.size() << '\n';
36 Resources->dump();
37}
38#endif
39
42 Resources->canBeDispatched(IR.getInstruction()->getUsedBuffers());
43 HadTokenStall = RSE != RS_BUFFER_AVAILABLE;
44
45 switch (RSE) {
51 break;
52 }
53
54 // Instructions that must issue at dispatch also need their pipelines to be
55 // available, even if a previous instruction has already released its buffers.
57 Resources->checkAvailability(IR.getInstruction()->getDesc())) {
58 HadTokenStall = true;
60 }
61
62 // Give lower priority to LSUnit stall events.
63 LSUnit::Status LSS = LSU.isAvailable(IR);
64 HadTokenStall = LSS != LSUnit::LSU_AVAILABLE;
65
66 switch (LSS) {
73 }
74
75 llvm_unreachable("Don't know how to process this LSU state result!");
76}
77
78void Scheduler::issueInstructionImpl(
79 InstRef &IR,
80 SmallVectorImpl<std::pair<ResourceRef, ReleaseAtCycles>> &UsedResources) {
81 Instruction *IS = IR.getInstruction();
82 const InstrDesc &D = IS->getDesc();
83
84 // Issue the instruction and collect all the consumed resources
85 // into a vector. That vector is then used to notify the listener.
86 Resources->issueInstruction(D, UsedResources);
87
88 // Notify the instruction that it started executing.
89 // This updates the internal state of each write.
90 IS->execute(IR.getSourceIndex());
91
92 IS->computeCriticalRegDep();
93
94 if (IS->isMemOp()) {
96 const CriticalDependency &MemDep =
97 LSU.getCriticalPredecessor(IS->getLSUTokenID());
98 IS->setCriticalMemDep(MemDep);
99 }
100
101 if (IS->isExecuting())
102 IssuedSet.emplace_back(IR);
103 else if (IS->isExecuted())
105}
106
107// Release the buffered resources and issue the instruction.
109 InstRef &IR,
110 SmallVectorImpl<std::pair<ResourceRef, ReleaseAtCycles>> &UsedResources,
111 SmallVectorImpl<InstRef> &PendingInstructions,
112 SmallVectorImpl<InstRef> &ReadyInstructions) {
113 const Instruction &Inst = *IR.getInstruction();
114 bool HasDependentUsers = Inst.hasDependentUsers();
115 HasDependentUsers |= Inst.isMemOp() && LSU.hasDependentUsers(IR);
116
117 Resources->releaseBuffers(Inst.getUsedBuffers());
118 issueInstructionImpl(IR, UsedResources);
119 // Instructions that have been issued during this cycle might have unblocked
120 // other dependent instructions. Dependent instructions may be issued during
121 // this same cycle if operands have ReadAdvance entries. Promote those
122 // instructions to the ReadySet and notify the caller that those are ready.
123 if (HasDependentUsers)
124 if (promoteToPendingSet(PendingInstructions))
125 promoteToReadySet(ReadyInstructions);
126}
127
128bool Scheduler::promoteToReadySet(SmallVectorImpl<InstRef> &Ready) {
129 // Scan the set of waiting instructions and promote them to the
130 // ready set if operands are all ready.
131 unsigned PromotedElements = 0;
132 for (auto I = PendingSet.begin(), E = PendingSet.end(); I != E;) {
133 InstRef &IR = *I;
134 if (!IR)
135 break;
136
137 // Check if there are unsolved register dependencies.
138 Instruction &IS = *IR.getInstruction();
139 if (!IS.isReady() && !IS.updatePending()) {
140 ++I;
141 continue;
142 }
143 // Check if there are unsolved memory dependencies.
144 if (IS.isMemOp() && !LSU.isReady(IR)) {
145 ++I;
146 continue;
147 }
148
149 LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction #" << IR
150 << " promoted to the READY set.\n");
151
152 Ready.emplace_back(IR);
153 ReadySet.emplace_back(IR);
154
155 IR.invalidate();
156 ++PromotedElements;
157 std::iter_swap(I, E - PromotedElements);
158 }
159
160 PendingSet.resize(PendingSet.size() - PromotedElements);
161 return PromotedElements;
162}
163
164bool Scheduler::promoteToPendingSet(SmallVectorImpl<InstRef> &Pending) {
165 // Scan the set of waiting instructions and promote them to the
166 // pending set if operands are all ready.
167 unsigned RemovedElements = 0;
168 for (auto I = WaitSet.begin(), E = WaitSet.end(); I != E;) {
169 InstRef &IR = *I;
170 if (!IR)
171 break;
172
173 // Check if this instruction is now ready. In case, force
174 // a transition in state using method 'updateDispatched()'.
175 Instruction &IS = *IR.getInstruction();
176 if (IS.isDispatched() && !IS.updateDispatched()) {
177 ++I;
178 continue;
179 }
180
181 if (IS.isMemOp() && LSU.isWaiting(IR)) {
182 ++I;
183 continue;
184 }
185
186 LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction #" << IR
187 << " promoted to the PENDING set.\n");
188
189 Pending.emplace_back(IR);
190 PendingSet.emplace_back(IR);
191
192 IR.invalidate();
193 ++RemovedElements;
194 std::iter_swap(I, E - RemovedElements);
195 }
196
197 WaitSet.resize(WaitSet.size() - RemovedElements);
198 return RemovedElements;
199}
200
202 unsigned QueueIndex = ReadySet.size();
203 for (unsigned I = 0, E = ReadySet.size(); I != E; ++I) {
204 InstRef &IR = ReadySet[I];
205 if (QueueIndex == ReadySet.size() ||
206 Strategy->compare(IR, ReadySet[QueueIndex])) {
207 Instruction &IS = *IR.getInstruction();
208 uint64_t BusyResourceMask = Resources->checkAvailability(IS.getDesc());
209 if (BusyResourceMask)
210 IS.setCriticalResourceMask(BusyResourceMask);
211 BusyResourceUnits |= BusyResourceMask;
212 if (!BusyResourceMask)
213 QueueIndex = I;
214 }
215 }
216
217 if (QueueIndex == ReadySet.size())
218 return InstRef();
219
220 // We found an instruction to issue.
221 InstRef IR = ReadySet[QueueIndex];
222 std::swap(ReadySet[QueueIndex], ReadySet[ReadySet.size() - 1]);
223 ReadySet.pop_back();
224 return IR;
225}
226
227void Scheduler::updateIssuedSet(SmallVectorImpl<InstRef> &Executed) {
228 unsigned RemovedElements = 0;
229 for (auto I = IssuedSet.begin(), E = IssuedSet.end(); I != E;) {
230 InstRef &IR = *I;
231 if (!IR)
232 break;
233 Instruction &IS = *IR.getInstruction();
234 if (!IS.isExecuted()) {
235 LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction #" << IR
236 << " is still executing.\n");
237 ++I;
238 continue;
239 }
240
241 // Instruction IR has completed execution.
243 Executed.emplace_back(IR);
244 ++RemovedElements;
245 IR.invalidate();
246 std::iter_swap(I, E - RemovedElements);
247 }
248
249 IssuedSet.resize(IssuedSet.size() - RemovedElements);
250}
251
253 llvm::append_range(Insts, ReadySet);
254 return BusyResourceUnits;
255}
256
258 SmallVectorImpl<InstRef> &MemDeps) {
259 const auto EndIt = PendingSet.end() - NumDispatchedToThePendingSet;
260 for (const InstRef &IR : make_range(PendingSet.begin(), EndIt)) {
261 const Instruction &IS = *IR.getInstruction();
262 if (Resources->checkAvailability(IS.getDesc()))
263 continue;
264
265 if (IS.isMemOp() && LSU.isPending(IR))
266 MemDeps.emplace_back(IR);
267
268 if (IS.isPending())
269 RegDeps.emplace_back(IR);
270 }
271}
272
274 SmallVectorImpl<InstRef> &Executed,
277 LSU.cycleEvent();
278
279 // Release consumed resources.
280 Resources->cycleEvent(Freed);
281
282 for (InstRef &IR : IssuedSet)
283 IR.getInstruction()->cycleEvent();
284 updateIssuedSet(Executed);
285
286 for (InstRef &IR : PendingSet)
287 IR.getInstruction()->cycleEvent();
288
289 for (InstRef &IR : WaitSet)
290 IR.getInstruction()->cycleEvent();
291
292 promoteToPendingSet(Pending);
293 promoteToReadySet(Ready);
294
295 NumDispatchedToThePendingSet = 0;
296 BusyResourceUnits = 0;
297}
298
300 const InstrDesc &Desc = IR.getInstruction()->getDesc();
301 if (Desc.isZeroLatency())
302 return true;
303 // Instructions that use an in-order dispatch/issue processor resource must be
304 // issued immediately to the pipeline(s). Any other in-order buffered
305 // resources (i.e. BufferSize=1) is consumed.
306 return Desc.MustIssueImmediately;
307}
308
310 Instruction &IS = *IR.getInstruction();
311 Resources->reserveBuffers(IS.getUsedBuffers());
312
313 // If necessary, reserve queue entries in the load-store unit (LSU).
314 if (IS.isMemOp())
315 IS.setLSUTokenID(LSU.dispatch(IR));
316
317 if (IS.isDispatched() || (IS.isMemOp() && LSU.isWaiting(IR))) {
318 LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding #" << IR << " to the WaitSet\n");
319 WaitSet.push_back(IR);
320 return false;
321 }
322
323 if (IS.isPending() || (IS.isMemOp() && LSU.isPending(IR))) {
324 LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding #" << IR
325 << " to the PendingSet\n");
326 PendingSet.push_back(IR);
327 ++NumDispatchedToThePendingSet;
328 return false;
329 }
330
331 assert(IS.isReady() && (!IS.isMemOp() || LSU.isReady(IR)) &&
332 "Unexpected internal state found!");
333 // Don't add a zero-latency instruction to the Ready queue.
334 // A zero-latency instruction doesn't consume any scheduler resources. That is
335 // because it doesn't need to be executed, and it is often removed at register
336 // renaming stage. For example, register-register moves are often optimized at
337 // register renaming stage by simply updating register aliases. On some
338 // targets, zero-idiom instructions (for example: a xor that clears the value
339 // of a register) are treated specially, and are often eliminated at register
340 // renaming stage.
341 if (!mustIssueImmediately(IR)) {
342 LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding #" << IR << " to the ReadySet\n");
343 ReadySet.push_back(IR);
344 }
345
346 return true;
347}
348
349} // namespace mca
350} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DXIL Remove Unused Resources
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
A scheduler for Processor Resource Units and Processor Resource Groups.
#define I(x, y, z)
Definition MD5.cpp:57
#define LLVM_DEBUG(...)
Definition Debug.h:119
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
An InstRef contains both a SourceMgr index and Instruction pair.
An instruction propagated through the simulated instruction pipeline.
uint64_t getUsedBuffers() const
virtual bool isReady(const InstRef &IR) const =0
Check if a peviously dispatched instruction IR is now ready for execution.
virtual void onInstructionExecuted(const InstRef &IR)=0
virtual const CriticalDependency getCriticalPredecessor(unsigned GroupId)=0
virtual void onInstructionIssued(const InstRef &IR)=0
LLVM_ABI InstRef select()
Select the next instruction to issue from the ReadySet.
LLVM_ABI void issueInstruction(InstRef &IR, SmallVectorImpl< std::pair< ResourceRef, ReleaseAtCycles > > &Used, SmallVectorImpl< InstRef > &Pending, SmallVectorImpl< InstRef > &Ready)
Issue an instruction and populates a vector of used pipeline resources, and a vector of instructions ...
LLVM_ABI Status isAvailable(const InstRef &IR)
Check if the instruction in 'IR' can be dispatched during this cycle.
Definition Scheduler.cpp:40
LLVM_ABI void analyzeDataDependencies(SmallVectorImpl< InstRef > &RegDeps, SmallVectorImpl< InstRef > &MemDeps)
This method is called by the ExecuteStage at the end of each cycle to identify bottlenecks caused by ...
LLVM_ABI bool dispatch(InstRef &IR)
Reserves buffer and LSUnit queue resources that are necessary to issue this instruction.
LLVM_ABI void cycleEvent(SmallVectorImpl< ResourceRef > &Freed, SmallVectorImpl< InstRef > &Executed, SmallVectorImpl< InstRef > &Pending, SmallVectorImpl< InstRef > &Ready)
This routine notifies the Scheduler that a new cycle just started.
LLVM_ABI bool mustIssueImmediately(const InstRef &IR) const
Returns true if IR has to be issued immediately, or if IR is a zero latency instruction.
LLVM_ABI uint64_t analyzeResourcePressure(SmallVectorImpl< InstRef > &Insts)
Returns a mask of busy resources, and populates vector Insts with instructions that could not be issu...
void dump() const
Definition Scheduler.cpp:32
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ResourceStateEvent
Used to notify the internal state of a processor resource.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
Op::Description Desc
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
A critical data dependency descriptor.
An instruction descriptor.