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 
13 #include "llvm/MCA/HardwareUnits/Scheduler.h"
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/raw_ostream.h"
16 
17 namespace llvm {
18 namespace mca {
19 
20 #define DEBUG_TYPE "llvm-mca"
21 
22 void Scheduler::initializeStrategy(std::unique_ptr<SchedulerStrategy> S) {
23   // Ensure we have a valid (non-null) strategy object.
24   Strategy = S ? std::move(S) : llvm::make_unique<DefaultSchedulerStrategy>();
25 }
26 
27 // Anchor the vtable of SchedulerStrategy and DefaultSchedulerStrategy.
28 SchedulerStrategy::~SchedulerStrategy() = default;
29 DefaultSchedulerStrategy::~DefaultSchedulerStrategy() = default;
30 
31 #ifndef NDEBUG
32 void 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 
40 Scheduler::Status Scheduler::isAvailable(const InstRef &IR) {
41   const InstrDesc &Desc = IR.getInstruction()->getDesc();
42 
43   ResourceStateEvent RSE = Resources->canBeDispatched(Desc.Buffers);
44   HadTokenStall = RSE != RS_BUFFER_AVAILABLE;
45 
46   switch (RSE) {
47   case ResourceStateEvent::RS_BUFFER_UNAVAILABLE:
48     return Scheduler::SC_BUFFERS_FULL;
49   case ResourceStateEvent::RS_RESERVED:
50     return Scheduler::SC_DISPATCH_GROUP_STALL;
51   case ResourceStateEvent::RS_BUFFER_AVAILABLE:
52     break;
53   }
54 
55   // Give lower priority to LSUnit stall events.
56   LSUnit::Status LSS = LSU.isAvailable(IR);
57   HadTokenStall = LSS != LSUnit::LSU_AVAILABLE;
58 
59   switch (LSS) {
60   case LSUnit::LSU_LQUEUE_FULL:
61     return Scheduler::SC_LOAD_QUEUE_FULL;
62   case LSUnit::LSU_SQUEUE_FULL:
63     return Scheduler::SC_STORE_QUEUE_FULL;
64   case LSUnit::LSU_AVAILABLE:
65     return Scheduler::SC_AVAILABLE;
66   }
67 
68   llvm_unreachable("Don't know how to process this LSU state result!");
69 }
70 
71 void Scheduler::issueInstructionImpl(
72     InstRef &IR,
73     SmallVectorImpl<std::pair<ResourceRef, ResourceCycles>> &UsedResources) {
74   Instruction *IS = IR.getInstruction();
75   const InstrDesc &D = IS->getDesc();
76 
77   // Issue the instruction and collect all the consumed resources
78   // into a vector. That vector is then used to notify the listener.
79   Resources->issueInstruction(D, UsedResources);
80 
81   // Notify the instruction that it started executing.
82   // This updates the internal state of each write.
83   IS->execute(IR.getSourceIndex());
84 
85   IS->computeCriticalRegDep();
86 
87   if (IS->isMemOp()) {
88     LSU.onInstructionIssued(IR);
89     const MemoryGroup &Group = LSU.getGroup(IS->getLSUTokenID());
90     IS->setCriticalMemDep(Group.getCriticalPredecessor());
91   }
92 
93   if (IS->isExecuting())
94     IssuedSet.emplace_back(IR);
95   else if (IS->isExecuted())
96     LSU.onInstructionExecuted(IR);
97 }
98 
99 // Release the buffered resources and issue the instruction.
100 void Scheduler::issueInstruction(
101     InstRef &IR,
102     SmallVectorImpl<std::pair<ResourceRef, ResourceCycles>> &UsedResources,
103     SmallVectorImpl<InstRef> &PendingInstructions,
104     SmallVectorImpl<InstRef> &ReadyInstructions) {
105   const Instruction &Inst = *IR.getInstruction();
106   bool HasDependentUsers = Inst.hasDependentUsers();
107 
108   Resources->releaseBuffers(Inst.getDesc().Buffers);
109   issueInstructionImpl(IR, UsedResources);
110   // Instructions that have been issued during this cycle might have unblocked
111   // other dependent instructions. Dependent instructions may be issued during
112   // this same cycle if operands have ReadAdvance entries.  Promote those
113   // instructions to the ReadySet and notify the caller that those are ready.
114   // If IR is a memory operation, then always call method `promoteToReadySet()`
115   // to notify any dependent memory operations that IR started execution.
116   bool ShouldPromoteInstructions = Inst.isMemOp();
117   if (HasDependentUsers)
118     ShouldPromoteInstructions |= promoteToPendingSet(PendingInstructions);
119 
120   if (ShouldPromoteInstructions)
121     promoteToReadySet(ReadyInstructions);
122 }
123 
124 bool Scheduler::promoteToReadySet(SmallVectorImpl<InstRef> &Ready) {
125   // Scan the set of waiting instructions and promote them to the
126   // ready set if operands are all ready.
127   unsigned PromotedElements = 0;
128   for (auto I = PendingSet.begin(), E = PendingSet.end(); I != E;) {
129     InstRef &IR = *I;
130     if (!IR)
131       break;
132 
133     // Check if there are unsolved memory dependencies.
134     Instruction &IS = *IR.getInstruction();
135     if (IS.isMemOp() && !LSU.isReady(IR)) {
136       ++I;
137       continue;
138     }
139 
140     // Check if there are unsolved register dependencies.
141     if (!IS.isReady() && !IS.updatePending()) {
142       ++I;
143       continue;
144     }
145     LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction #" << IR
146                       << " promoted to the READY set.\n");
147 
148     Ready.emplace_back(IR);
149     ReadySet.emplace_back(IR);
150 
151     IR.invalidate();
152     ++PromotedElements;
153     std::iter_swap(I, E - PromotedElements);
154   }
155 
156   PendingSet.resize(PendingSet.size() - PromotedElements);
157   return PromotedElements;
158 }
159 
160 bool Scheduler::promoteToPendingSet(SmallVectorImpl<InstRef> &Pending) {
161   // Scan the set of waiting instructions and promote them to the
162   // pending set if operands are all ready.
163   unsigned RemovedElements = 0;
164   for (auto I = WaitSet.begin(), E = WaitSet.end(); I != E;) {
165     InstRef &IR = *I;
166     if (!IR)
167       break;
168 
169     // Check if this instruction is now ready. In case, force
170     // a transition in state using method 'updateDispatched()'.
171     Instruction &IS = *IR.getInstruction();
172     if (IS.isDispatched() && !IS.updateDispatched()) {
173       ++I;
174       continue;
175     }
176     LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction #" << IR
177                       << " promoted to the PENDING set.\n");
178 
179     Pending.emplace_back(IR);
180     PendingSet.emplace_back(IR);
181 
182     IR.invalidate();
183     ++RemovedElements;
184     std::iter_swap(I, E - RemovedElements);
185   }
186 
187   WaitSet.resize(WaitSet.size() - RemovedElements);
188   return RemovedElements;
189 }
190 
191 InstRef Scheduler::select() {
192   unsigned QueueIndex = ReadySet.size();
193   for (unsigned I = 0, E = ReadySet.size(); I != E; ++I) {
194     InstRef &IR = ReadySet[I];
195     if (QueueIndex == ReadySet.size() ||
196         Strategy->compare(IR, ReadySet[QueueIndex])) {
197       Instruction &IS = *IR.getInstruction();
198       uint64_t BusyResourceMask = Resources->checkAvailability(IS.getDesc());
199       IS.setCriticalResourceMask(BusyResourceMask);
200       BusyResourceUnits |= BusyResourceMask;
201       if (!BusyResourceMask)
202         QueueIndex = I;
203     }
204   }
205 
206   if (QueueIndex == ReadySet.size())
207     return InstRef();
208 
209   // We found an instruction to issue.
210   InstRef IR = ReadySet[QueueIndex];
211   std::swap(ReadySet[QueueIndex], ReadySet[ReadySet.size() - 1]);
212   ReadySet.pop_back();
213   return IR;
214 }
215 
216 void Scheduler::updateIssuedSet(SmallVectorImpl<InstRef> &Executed) {
217   unsigned RemovedElements = 0;
218   for (auto I = IssuedSet.begin(), E = IssuedSet.end(); I != E;) {
219     InstRef &IR = *I;
220     if (!IR)
221       break;
222     Instruction &IS = *IR.getInstruction();
223     if (!IS.isExecuted()) {
224       LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction #" << IR
225                         << " is still executing.\n");
226       ++I;
227       continue;
228     }
229 
230     // Instruction IR has completed execution.
231     LSU.onInstructionExecuted(IR);
232     Executed.emplace_back(IR);
233     ++RemovedElements;
234     IR.invalidate();
235     std::iter_swap(I, E - RemovedElements);
236   }
237 
238   IssuedSet.resize(IssuedSet.size() - RemovedElements);
239 }
240 
241 uint64_t Scheduler::analyzeResourcePressure(SmallVectorImpl<InstRef> &Insts) {
242   Insts.insert(Insts.end(), ReadySet.begin(), ReadySet.end());
243   return BusyResourceUnits;
244 }
245 
246 void Scheduler::analyzeDataDependencies(SmallVectorImpl<InstRef> &RegDeps,
247                                         SmallVectorImpl<InstRef> &MemDeps) {
248   const auto EndIt = PendingSet.end() - NumDispatchedToThePendingSet;
249   for (const InstRef &IR : make_range(PendingSet.begin(), EndIt)) {
250     const Instruction &IS = *IR.getInstruction();
251     if (Resources->checkAvailability(IS.getDesc()))
252       continue;
253 
254     if (IS.isMemOp()) {
255       const MemoryGroup &Group = LSU.getGroup(IS.getLSUTokenID());
256       if (Group.isWaiting())
257         continue;
258       if (Group.isPending())
259         MemDeps.emplace_back(IR);
260     }
261 
262     if (IS.isPending())
263       RegDeps.emplace_back(IR);
264   }
265 }
266 
267 void Scheduler::cycleEvent(SmallVectorImpl<ResourceRef> &Freed,
268                            SmallVectorImpl<InstRef> &Executed,
269                            SmallVectorImpl<InstRef> &Pending,
270                            SmallVectorImpl<InstRef> &Ready) {
271   LSU.cycleEvent();
272 
273   // Release consumed resources.
274   Resources->cycleEvent(Freed);
275 
276   for (InstRef &IR : IssuedSet)
277     IR.getInstruction()->cycleEvent();
278   updateIssuedSet(Executed);
279 
280   for (InstRef &IR : PendingSet)
281     IR.getInstruction()->cycleEvent();
282 
283   for (InstRef &IR : WaitSet)
284     IR.getInstruction()->cycleEvent();
285 
286   promoteToPendingSet(Pending);
287   promoteToReadySet(Ready);
288 
289   NumDispatchedToThePendingSet = 0;
290   BusyResourceUnits = 0;
291 }
292 
293 bool Scheduler::mustIssueImmediately(const InstRef &IR) const {
294   const InstrDesc &Desc = IR.getInstruction()->getDesc();
295   if (Desc.isZeroLatency())
296     return true;
297   // Instructions that use an in-order dispatch/issue processor resource must be
298   // issued immediately to the pipeline(s). Any other in-order buffered
299   // resources (i.e. BufferSize=1) is consumed.
300   return Desc.MustIssueImmediately;
301 }
302 
303 bool Scheduler::dispatch(InstRef &IR) {
304   Instruction &IS = *IR.getInstruction();
305   const InstrDesc &Desc = IS.getDesc();
306   Resources->reserveBuffers(Desc.Buffers);
307 
308   // If necessary, reserve queue entries in the load-store unit (LSU).
309   if (IS.isMemOp())
310     IS.setLSUTokenID(LSU.dispatch(IR));
311 
312   if (IS.isPending()) {
313     LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding #" << IR
314                       << " to the PendingSet\n");
315     PendingSet.push_back(IR);
316     ++NumDispatchedToThePendingSet;
317     return false;
318   }
319 
320   // Memory operations that still have unsolved memory dependencies are
321   // initially dispatched to the WaitSet.
322   if (!IS.isReady() || (IS.isMemOp() && !LSU.isReady(IR))) {
323     LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding #" << IR << " to the WaitSet\n");
324     WaitSet.push_back(IR);
325     return false;
326   }
327 
328   // Don't add a zero-latency instruction to the Ready queue.
329   // A zero-latency instruction doesn't consume any scheduler resources. That is
330   // because it doesn't need to be executed, and it is often removed at register
331   // renaming stage. For example, register-register moves are often optimized at
332   // register renaming stage by simply updating register aliases. On some
333   // targets, zero-idiom instructions (for example: a xor that clears the value
334   // of a register) are treated specially, and are often eliminated at register
335   // renaming stage.
336   if (!mustIssueImmediately(IR)) {
337     LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding #" << IR << " to the ReadySet\n");
338     ReadySet.push_back(IR);
339   }
340 
341   return true;
342 }
343 
344 } // namespace mca
345 } // namespace llvm
346