1d88c1a5aSDimitry Andric //===-- SIMachineScheduler.cpp - SI Scheduler Interface -------------------===//
2444ed5c5SDimitry Andric //
3444ed5c5SDimitry Andric //                     The LLVM Compiler Infrastructure
4444ed5c5SDimitry Andric //
5444ed5c5SDimitry Andric // This file is distributed under the University of Illinois Open Source
6444ed5c5SDimitry Andric // License. See LICENSE.TXT for details.
7444ed5c5SDimitry Andric //
8444ed5c5SDimitry Andric //===----------------------------------------------------------------------===//
9444ed5c5SDimitry Andric //
10444ed5c5SDimitry Andric /// \file
114ba319b5SDimitry Andric /// SI Machine Scheduler interface
12444ed5c5SDimitry Andric //
13444ed5c5SDimitry Andric //===----------------------------------------------------------------------===//
14444ed5c5SDimitry Andric 
15db17bf38SDimitry Andric #include "SIMachineScheduler.h"
163ca95b02SDimitry Andric #include "AMDGPU.h"
17d88c1a5aSDimitry Andric #include "SIInstrInfo.h"
18d88c1a5aSDimitry Andric #include "SIRegisterInfo.h"
194ba319b5SDimitry Andric #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20d88c1a5aSDimitry Andric #include "llvm/ADT/STLExtras.h"
21d88c1a5aSDimitry Andric #include "llvm/ADT/SmallVector.h"
22444ed5c5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
232cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
24d88c1a5aSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
25444ed5c5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
26444ed5c5SDimitry Andric #include "llvm/CodeGen/MachineScheduler.h"
27444ed5c5SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
28d88c1a5aSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
292cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
30d88c1a5aSDimitry Andric #include "llvm/Support/Debug.h"
31d88c1a5aSDimitry Andric #include "llvm/Support/ErrorHandling.h"
32d88c1a5aSDimitry Andric #include "llvm/Support/raw_ostream.h"
33d88c1a5aSDimitry Andric #include <algorithm>
34d88c1a5aSDimitry Andric #include <cassert>
35d88c1a5aSDimitry Andric #include <map>
36d88c1a5aSDimitry Andric #include <set>
37d88c1a5aSDimitry Andric #include <utility>
38d88c1a5aSDimitry Andric #include <vector>
39444ed5c5SDimitry Andric 
40444ed5c5SDimitry Andric using namespace llvm;
41444ed5c5SDimitry Andric 
42c4394386SDimitry Andric #define DEBUG_TYPE "machine-scheduler"
43444ed5c5SDimitry Andric 
44444ed5c5SDimitry Andric // This scheduler implements a different scheduling algorithm than
45444ed5c5SDimitry Andric // GenericScheduler.
46444ed5c5SDimitry Andric //
47444ed5c5SDimitry Andric // There are several specific architecture behaviours that can't be modelled
48444ed5c5SDimitry Andric // for GenericScheduler:
49444ed5c5SDimitry Andric // . When accessing the result of an SGPR load instruction, you have to wait
50444ed5c5SDimitry Andric // for all the SGPR load instructions before your current instruction to
51444ed5c5SDimitry Andric // have finished.
52444ed5c5SDimitry Andric // . When accessing the result of an VGPR load instruction, you have to wait
53444ed5c5SDimitry Andric // for all the VGPR load instructions previous to the VGPR load instruction
54444ed5c5SDimitry Andric // you are interested in to finish.
55444ed5c5SDimitry Andric // . The less the register pressure, the best load latencies are hidden
56444ed5c5SDimitry Andric //
57444ed5c5SDimitry Andric // Moreover some specifities (like the fact a lot of instructions in the shader
58444ed5c5SDimitry Andric // have few dependencies) makes the generic scheduler have some unpredictable
59444ed5c5SDimitry Andric // behaviours. For example when register pressure becomes high, it can either
60444ed5c5SDimitry Andric // manage to prevent register pressure from going too high, or it can
61444ed5c5SDimitry Andric // increase register pressure even more than if it hadn't taken register
62444ed5c5SDimitry Andric // pressure into account.
63444ed5c5SDimitry Andric //
64444ed5c5SDimitry Andric // Also some other bad behaviours are generated, like loading at the beginning
65444ed5c5SDimitry Andric // of the shader a constant in VGPR you won't need until the end of the shader.
66444ed5c5SDimitry Andric //
67444ed5c5SDimitry Andric // The scheduling problem for SI can distinguish three main parts:
68444ed5c5SDimitry Andric // . Hiding high latencies (texture sampling, etc)
69444ed5c5SDimitry Andric // . Hiding low latencies (SGPR constant loading, etc)
70444ed5c5SDimitry Andric // . Keeping register usage low for better latency hiding and general
71444ed5c5SDimitry Andric //   performance
72444ed5c5SDimitry Andric //
73444ed5c5SDimitry Andric // Some other things can also affect performance, but are hard to predict
74444ed5c5SDimitry Andric // (cache usage, the fact the HW can issue several instructions from different
75444ed5c5SDimitry Andric // wavefronts if different types, etc)
76444ed5c5SDimitry Andric //
77444ed5c5SDimitry Andric // This scheduler tries to solve the scheduling problem by dividing it into
78444ed5c5SDimitry Andric // simpler sub-problems. It divides the instructions into blocks, schedules
79444ed5c5SDimitry Andric // locally inside the blocks where it takes care of low latencies, and then
80444ed5c5SDimitry Andric // chooses the order of the blocks by taking care of high latencies.
81444ed5c5SDimitry Andric // Dividing the instructions into blocks helps control keeping register
82444ed5c5SDimitry Andric // usage low.
83444ed5c5SDimitry Andric //
84444ed5c5SDimitry Andric // First the instructions are put into blocks.
85444ed5c5SDimitry Andric //   We want the blocks help control register usage and hide high latencies
86444ed5c5SDimitry Andric //   later. To help control register usage, we typically want all local
87444ed5c5SDimitry Andric //   computations, when for example you create a result that can be comsummed
88444ed5c5SDimitry Andric //   right away, to be contained in a block. Block inputs and outputs would
89444ed5c5SDimitry Andric //   typically be important results that are needed in several locations of
90444ed5c5SDimitry Andric //   the shader. Since we do want blocks to help hide high latencies, we want
91444ed5c5SDimitry Andric //   the instructions inside the block to have a minimal set of dependencies
92444ed5c5SDimitry Andric //   on high latencies. It will make it easy to pick blocks to hide specific
93444ed5c5SDimitry Andric //   high latencies.
94444ed5c5SDimitry Andric //   The block creation algorithm is divided into several steps, and several
95444ed5c5SDimitry Andric //   variants can be tried during the scheduling process.
96444ed5c5SDimitry Andric //
97d88c1a5aSDimitry Andric // Second the order of the instructions inside the blocks is chosen.
98444ed5c5SDimitry Andric //   At that step we do take into account only register usage and hiding
99444ed5c5SDimitry Andric //   low latency instructions
100444ed5c5SDimitry Andric //
101d88c1a5aSDimitry Andric // Third the block order is chosen, there we try to hide high latencies
102444ed5c5SDimitry Andric // and keep register usage low.
103444ed5c5SDimitry Andric //
104444ed5c5SDimitry Andric // After the third step, a pass is done to improve the hiding of low
105444ed5c5SDimitry Andric // latencies.
106444ed5c5SDimitry Andric //
107444ed5c5SDimitry Andric // Actually when talking about 'low latency' or 'high latency' it includes
108444ed5c5SDimitry Andric // both the latency to get the cache (or global mem) data go to the register,
109d88c1a5aSDimitry Andric // and the bandwidth limitations.
110444ed5c5SDimitry Andric // Increasing the number of active wavefronts helps hide the former, but it
111444ed5c5SDimitry Andric // doesn't solve the latter, thus why even if wavefront count is high, we have
112444ed5c5SDimitry Andric // to try have as many instructions hiding high latencies as possible.
113444ed5c5SDimitry Andric // The OpenCL doc says for example latency of 400 cycles for a global mem access,
114444ed5c5SDimitry Andric // which is hidden by 10 instructions if the wavefront count is 10.
115444ed5c5SDimitry Andric 
116444ed5c5SDimitry Andric // Some figures taken from AMD docs:
117444ed5c5SDimitry Andric // Both texture and constant L1 caches are 4-way associative with 64 bytes
118444ed5c5SDimitry Andric // lines.
119444ed5c5SDimitry Andric // Constant cache is shared with 4 CUs.
120444ed5c5SDimitry Andric // For texture sampling, the address generation unit receives 4 texture
121444ed5c5SDimitry Andric // addresses per cycle, thus we could expect texture sampling latency to be
122444ed5c5SDimitry Andric // equivalent to 4 instructions in the very best case (a VGPR is 64 work items,
123444ed5c5SDimitry Andric // instructions in a wavefront group are executed every 4 cycles),
124444ed5c5SDimitry Andric // or 16 instructions if the other wavefronts associated to the 3 other VALUs
125444ed5c5SDimitry Andric // of the CU do texture sampling too. (Don't take these figures too seriously,
126444ed5c5SDimitry Andric // as I'm not 100% sure of the computation)
127444ed5c5SDimitry Andric // Data exports should get similar latency.
128444ed5c5SDimitry Andric // For constant loading, the cache is shader with 4 CUs.
129444ed5c5SDimitry Andric // The doc says "a throughput of 16B/cycle for each of the 4 Compute Unit"
130444ed5c5SDimitry Andric // I guess if the other CU don't read the cache, it can go up to 64B/cycle.
131444ed5c5SDimitry Andric // It means a simple s_buffer_load should take one instruction to hide, as
132444ed5c5SDimitry Andric // well as a s_buffer_loadx2 and potentially a s_buffer_loadx8 if on the same
133444ed5c5SDimitry Andric // cache line.
134444ed5c5SDimitry Andric //
135444ed5c5SDimitry Andric // As of today the driver doesn't preload the constants in cache, thus the
136444ed5c5SDimitry Andric // first loads get extra latency. The doc says global memory access can be
137444ed5c5SDimitry Andric // 300-600 cycles. We do not specially take that into account when scheduling
138444ed5c5SDimitry Andric // As we expect the driver to be able to preload the constants soon.
139444ed5c5SDimitry Andric 
140444ed5c5SDimitry Andric // common code //
141444ed5c5SDimitry Andric 
142444ed5c5SDimitry Andric #ifndef NDEBUG
143444ed5c5SDimitry Andric 
getReasonStr(SIScheduleCandReason Reason)144444ed5c5SDimitry Andric static const char *getReasonStr(SIScheduleCandReason Reason) {
145444ed5c5SDimitry Andric   switch (Reason) {
146444ed5c5SDimitry Andric   case NoCand:         return "NOCAND";
147444ed5c5SDimitry Andric   case RegUsage:       return "REGUSAGE";
148444ed5c5SDimitry Andric   case Latency:        return "LATENCY";
149444ed5c5SDimitry Andric   case Successor:      return "SUCCESSOR";
150444ed5c5SDimitry Andric   case Depth:          return "DEPTH";
151444ed5c5SDimitry Andric   case NodeOrder:      return "ORDER";
152444ed5c5SDimitry Andric   }
153444ed5c5SDimitry Andric   llvm_unreachable("Unknown reason!");
154444ed5c5SDimitry Andric }
155444ed5c5SDimitry Andric 
156444ed5c5SDimitry Andric #endif
157444ed5c5SDimitry Andric 
1584ba319b5SDimitry Andric namespace llvm {
1594ba319b5SDimitry Andric namespace SISched {
tryLess(int TryVal,int CandVal,SISchedulerCandidate & TryCand,SISchedulerCandidate & Cand,SIScheduleCandReason Reason)160444ed5c5SDimitry Andric static bool tryLess(int TryVal, int CandVal,
161444ed5c5SDimitry Andric                     SISchedulerCandidate &TryCand,
162444ed5c5SDimitry Andric                     SISchedulerCandidate &Cand,
163444ed5c5SDimitry Andric                     SIScheduleCandReason Reason) {
164444ed5c5SDimitry Andric   if (TryVal < CandVal) {
165444ed5c5SDimitry Andric     TryCand.Reason = Reason;
166444ed5c5SDimitry Andric     return true;
167444ed5c5SDimitry Andric   }
168444ed5c5SDimitry Andric   if (TryVal > CandVal) {
169444ed5c5SDimitry Andric     if (Cand.Reason > Reason)
170444ed5c5SDimitry Andric       Cand.Reason = Reason;
171444ed5c5SDimitry Andric     return true;
172444ed5c5SDimitry Andric   }
173444ed5c5SDimitry Andric   Cand.setRepeat(Reason);
174444ed5c5SDimitry Andric   return false;
175444ed5c5SDimitry Andric }
176444ed5c5SDimitry Andric 
tryGreater(int TryVal,int CandVal,SISchedulerCandidate & TryCand,SISchedulerCandidate & Cand,SIScheduleCandReason Reason)177444ed5c5SDimitry Andric static bool tryGreater(int TryVal, int CandVal,
178444ed5c5SDimitry Andric                        SISchedulerCandidate &TryCand,
179444ed5c5SDimitry Andric                        SISchedulerCandidate &Cand,
180444ed5c5SDimitry Andric                        SIScheduleCandReason Reason) {
181444ed5c5SDimitry Andric   if (TryVal > CandVal) {
182444ed5c5SDimitry Andric     TryCand.Reason = Reason;
183444ed5c5SDimitry Andric     return true;
184444ed5c5SDimitry Andric   }
185444ed5c5SDimitry Andric   if (TryVal < CandVal) {
186444ed5c5SDimitry Andric     if (Cand.Reason > Reason)
187444ed5c5SDimitry Andric       Cand.Reason = Reason;
188444ed5c5SDimitry Andric     return true;
189444ed5c5SDimitry Andric   }
190444ed5c5SDimitry Andric   Cand.setRepeat(Reason);
191444ed5c5SDimitry Andric   return false;
192444ed5c5SDimitry Andric }
1934ba319b5SDimitry Andric } // end namespace SISched
1944ba319b5SDimitry Andric } // end namespace llvm
195444ed5c5SDimitry Andric 
196444ed5c5SDimitry Andric // SIScheduleBlock //
197444ed5c5SDimitry Andric 
addUnit(SUnit * SU)198444ed5c5SDimitry Andric void SIScheduleBlock::addUnit(SUnit *SU) {
199444ed5c5SDimitry Andric   NodeNum2Index[SU->NodeNum] = SUnits.size();
200444ed5c5SDimitry Andric   SUnits.push_back(SU);
201444ed5c5SDimitry Andric }
202444ed5c5SDimitry Andric 
203444ed5c5SDimitry Andric #ifndef NDEBUG
traceCandidate(const SISchedCandidate & Cand)204444ed5c5SDimitry Andric void SIScheduleBlock::traceCandidate(const SISchedCandidate &Cand) {
205444ed5c5SDimitry Andric 
206444ed5c5SDimitry Andric   dbgs() << "  SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
207444ed5c5SDimitry Andric   dbgs() << '\n';
208444ed5c5SDimitry Andric }
209444ed5c5SDimitry Andric #endif
210444ed5c5SDimitry Andric 
tryCandidateTopDown(SISchedCandidate & Cand,SISchedCandidate & TryCand)211444ed5c5SDimitry Andric void SIScheduleBlock::tryCandidateTopDown(SISchedCandidate &Cand,
212444ed5c5SDimitry Andric                                           SISchedCandidate &TryCand) {
213444ed5c5SDimitry Andric   // Initialize the candidate if needed.
214444ed5c5SDimitry Andric   if (!Cand.isValid()) {
215444ed5c5SDimitry Andric     TryCand.Reason = NodeOrder;
216444ed5c5SDimitry Andric     return;
217444ed5c5SDimitry Andric   }
218444ed5c5SDimitry Andric 
219444ed5c5SDimitry Andric   if (Cand.SGPRUsage > 60 &&
2204ba319b5SDimitry Andric       SISched::tryLess(TryCand.SGPRUsage, Cand.SGPRUsage,
2214ba319b5SDimitry Andric                        TryCand, Cand, RegUsage))
222444ed5c5SDimitry Andric     return;
223444ed5c5SDimitry Andric 
224444ed5c5SDimitry Andric   // Schedule low latency instructions as top as possible.
225444ed5c5SDimitry Andric   // Order of priority is:
226444ed5c5SDimitry Andric   // . Low latency instructions which do not depend on other low latency
227444ed5c5SDimitry Andric   //   instructions we haven't waited for
228444ed5c5SDimitry Andric   // . Other instructions which do not depend on low latency instructions
229444ed5c5SDimitry Andric   //   we haven't waited for
230444ed5c5SDimitry Andric   // . Low latencies
231444ed5c5SDimitry Andric   // . All other instructions
232d88c1a5aSDimitry Andric   // Goal is to get: low latency instructions - independent instructions
233444ed5c5SDimitry Andric   //     - (eventually some more low latency instructions)
234444ed5c5SDimitry Andric   //     - instructions that depend on the first low latency instructions.
235444ed5c5SDimitry Andric   // If in the block there is a lot of constant loads, the SGPR usage
236444ed5c5SDimitry Andric   // could go quite high, thus above the arbitrary limit of 60 will encourage
237444ed5c5SDimitry Andric   // use the already loaded constants (in order to release some SGPRs) before
238444ed5c5SDimitry Andric   // loading more.
2394ba319b5SDimitry Andric   if (SISched::tryLess(TryCand.HasLowLatencyNonWaitedParent,
240444ed5c5SDimitry Andric                        Cand.HasLowLatencyNonWaitedParent,
241444ed5c5SDimitry Andric                        TryCand, Cand, SIScheduleCandReason::Depth))
242444ed5c5SDimitry Andric     return;
243444ed5c5SDimitry Andric 
2444ba319b5SDimitry Andric   if (SISched::tryGreater(TryCand.IsLowLatency, Cand.IsLowLatency,
245444ed5c5SDimitry Andric                           TryCand, Cand, SIScheduleCandReason::Depth))
246444ed5c5SDimitry Andric     return;
247444ed5c5SDimitry Andric 
248444ed5c5SDimitry Andric   if (TryCand.IsLowLatency &&
2494ba319b5SDimitry Andric       SISched::tryLess(TryCand.LowLatencyOffset, Cand.LowLatencyOffset,
250444ed5c5SDimitry Andric                        TryCand, Cand, SIScheduleCandReason::Depth))
251444ed5c5SDimitry Andric     return;
252444ed5c5SDimitry Andric 
2534ba319b5SDimitry Andric   if (SISched::tryLess(TryCand.VGPRUsage, Cand.VGPRUsage,
2544ba319b5SDimitry Andric                        TryCand, Cand, RegUsage))
255444ed5c5SDimitry Andric     return;
256444ed5c5SDimitry Andric 
257444ed5c5SDimitry Andric   // Fall through to original instruction order.
258444ed5c5SDimitry Andric   if (TryCand.SU->NodeNum < Cand.SU->NodeNum) {
259444ed5c5SDimitry Andric     TryCand.Reason = NodeOrder;
260444ed5c5SDimitry Andric   }
261444ed5c5SDimitry Andric }
262444ed5c5SDimitry Andric 
pickNode()263444ed5c5SDimitry Andric SUnit* SIScheduleBlock::pickNode() {
264444ed5c5SDimitry Andric   SISchedCandidate TopCand;
265444ed5c5SDimitry Andric 
266444ed5c5SDimitry Andric   for (SUnit* SU : TopReadySUs) {
267444ed5c5SDimitry Andric     SISchedCandidate TryCand;
268444ed5c5SDimitry Andric     std::vector<unsigned> pressure;
269444ed5c5SDimitry Andric     std::vector<unsigned> MaxPressure;
270444ed5c5SDimitry Andric     // Predict register usage after this instruction.
271444ed5c5SDimitry Andric     TryCand.SU = SU;
272444ed5c5SDimitry Andric     TopRPTracker.getDownwardPressure(SU->getInstr(), pressure, MaxPressure);
273444ed5c5SDimitry Andric     TryCand.SGPRUsage = pressure[DAG->getSGPRSetID()];
274444ed5c5SDimitry Andric     TryCand.VGPRUsage = pressure[DAG->getVGPRSetID()];
275444ed5c5SDimitry Andric     TryCand.IsLowLatency = DAG->IsLowLatencySU[SU->NodeNum];
276444ed5c5SDimitry Andric     TryCand.LowLatencyOffset = DAG->LowLatencyOffset[SU->NodeNum];
277444ed5c5SDimitry Andric     TryCand.HasLowLatencyNonWaitedParent =
278444ed5c5SDimitry Andric       HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]];
279444ed5c5SDimitry Andric     tryCandidateTopDown(TopCand, TryCand);
280444ed5c5SDimitry Andric     if (TryCand.Reason != NoCand)
281444ed5c5SDimitry Andric       TopCand.setBest(TryCand);
282444ed5c5SDimitry Andric   }
283444ed5c5SDimitry Andric 
284444ed5c5SDimitry Andric   return TopCand.SU;
285444ed5c5SDimitry Andric }
286444ed5c5SDimitry Andric 
287444ed5c5SDimitry Andric 
288444ed5c5SDimitry Andric // Schedule something valid.
fastSchedule()289444ed5c5SDimitry Andric void SIScheduleBlock::fastSchedule() {
290444ed5c5SDimitry Andric   TopReadySUs.clear();
291444ed5c5SDimitry Andric   if (Scheduled)
292444ed5c5SDimitry Andric     undoSchedule();
293444ed5c5SDimitry Andric 
294444ed5c5SDimitry Andric   for (SUnit* SU : SUnits) {
295444ed5c5SDimitry Andric     if (!SU->NumPredsLeft)
296444ed5c5SDimitry Andric       TopReadySUs.push_back(SU);
297444ed5c5SDimitry Andric   }
298444ed5c5SDimitry Andric 
299444ed5c5SDimitry Andric   while (!TopReadySUs.empty()) {
300444ed5c5SDimitry Andric     SUnit *SU = TopReadySUs[0];
301444ed5c5SDimitry Andric     ScheduledSUnits.push_back(SU);
302444ed5c5SDimitry Andric     nodeScheduled(SU);
303444ed5c5SDimitry Andric   }
304444ed5c5SDimitry Andric 
305444ed5c5SDimitry Andric   Scheduled = true;
306444ed5c5SDimitry Andric }
307444ed5c5SDimitry Andric 
308444ed5c5SDimitry Andric // Returns if the register was set between first and last.
isDefBetween(unsigned Reg,SlotIndex First,SlotIndex Last,const MachineRegisterInfo * MRI,const LiveIntervals * LIS)309444ed5c5SDimitry Andric static bool isDefBetween(unsigned Reg,
310444ed5c5SDimitry Andric                            SlotIndex First, SlotIndex Last,
311444ed5c5SDimitry Andric                            const MachineRegisterInfo *MRI,
312444ed5c5SDimitry Andric                            const LiveIntervals *LIS) {
313444ed5c5SDimitry Andric   for (MachineRegisterInfo::def_instr_iterator
314444ed5c5SDimitry Andric        UI = MRI->def_instr_begin(Reg),
315444ed5c5SDimitry Andric        UE = MRI->def_instr_end(); UI != UE; ++UI) {
316444ed5c5SDimitry Andric     const MachineInstr* MI = &*UI;
317444ed5c5SDimitry Andric     if (MI->isDebugValue())
318444ed5c5SDimitry Andric       continue;
3193ca95b02SDimitry Andric     SlotIndex InstSlot = LIS->getInstructionIndex(*MI).getRegSlot();
320444ed5c5SDimitry Andric     if (InstSlot >= First && InstSlot <= Last)
321444ed5c5SDimitry Andric       return true;
322444ed5c5SDimitry Andric   }
323444ed5c5SDimitry Andric   return false;
324444ed5c5SDimitry Andric }
325444ed5c5SDimitry Andric 
initRegPressure(MachineBasicBlock::iterator BeginBlock,MachineBasicBlock::iterator EndBlock)326444ed5c5SDimitry Andric void SIScheduleBlock::initRegPressure(MachineBasicBlock::iterator BeginBlock,
327444ed5c5SDimitry Andric                                       MachineBasicBlock::iterator EndBlock) {
328444ed5c5SDimitry Andric   IntervalPressure Pressure, BotPressure;
329444ed5c5SDimitry Andric   RegPressureTracker RPTracker(Pressure), BotRPTracker(BotPressure);
330444ed5c5SDimitry Andric   LiveIntervals *LIS = DAG->getLIS();
331444ed5c5SDimitry Andric   MachineRegisterInfo *MRI = DAG->getMRI();
332444ed5c5SDimitry Andric   DAG->initRPTracker(TopRPTracker);
333444ed5c5SDimitry Andric   DAG->initRPTracker(BotRPTracker);
334444ed5c5SDimitry Andric   DAG->initRPTracker(RPTracker);
335444ed5c5SDimitry Andric 
336444ed5c5SDimitry Andric   // Goes though all SU. RPTracker captures what had to be alive for the SUs
337444ed5c5SDimitry Andric   // to execute, and what is still alive at the end.
338444ed5c5SDimitry Andric   for (SUnit* SU : ScheduledSUnits) {
339444ed5c5SDimitry Andric     RPTracker.setPos(SU->getInstr());
340444ed5c5SDimitry Andric     RPTracker.advance();
341444ed5c5SDimitry Andric   }
342444ed5c5SDimitry Andric 
343444ed5c5SDimitry Andric   // Close the RPTracker to finalize live ins/outs.
344444ed5c5SDimitry Andric   RPTracker.closeRegion();
345444ed5c5SDimitry Andric 
346444ed5c5SDimitry Andric   // Initialize the live ins and live outs.
347444ed5c5SDimitry Andric   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
348444ed5c5SDimitry Andric   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
349444ed5c5SDimitry Andric 
350444ed5c5SDimitry Andric   // Do not Track Physical Registers, because it messes up.
3513ca95b02SDimitry Andric   for (const auto &RegMaskPair : RPTracker.getPressure().LiveInRegs) {
3523ca95b02SDimitry Andric     if (TargetRegisterInfo::isVirtualRegister(RegMaskPair.RegUnit))
3533ca95b02SDimitry Andric       LiveInRegs.insert(RegMaskPair.RegUnit);
354444ed5c5SDimitry Andric   }
355444ed5c5SDimitry Andric   LiveOutRegs.clear();
356444ed5c5SDimitry Andric   // There is several possibilities to distinguish:
357444ed5c5SDimitry Andric   // 1) Reg is not input to any instruction in the block, but is output of one
358444ed5c5SDimitry Andric   // 2) 1) + read in the block and not needed after it
359444ed5c5SDimitry Andric   // 3) 1) + read in the block but needed in another block
360444ed5c5SDimitry Andric   // 4) Reg is input of an instruction but another block will read it too
361444ed5c5SDimitry Andric   // 5) Reg is input of an instruction and then rewritten in the block.
362444ed5c5SDimitry Andric   //    result is not read in the block (implies used in another block)
363444ed5c5SDimitry Andric   // 6) Reg is input of an instruction and then rewritten in the block.
364444ed5c5SDimitry Andric   //    result is read in the block and not needed in another block
365444ed5c5SDimitry Andric   // 7) Reg is input of an instruction and then rewritten in the block.
366444ed5c5SDimitry Andric   //    result is read in the block but also needed in another block
367444ed5c5SDimitry Andric   // LiveInRegs will contains all the regs in situation 4, 5, 6, 7
368444ed5c5SDimitry Andric   // We want LiveOutRegs to contain only Regs whose content will be read after
369444ed5c5SDimitry Andric   // in another block, and whose content was written in the current block,
370444ed5c5SDimitry Andric   // that is we want it to get 1, 3, 5, 7
371444ed5c5SDimitry Andric   // Since we made the MIs of a block to be packed all together before
372444ed5c5SDimitry Andric   // scheduling, then the LiveIntervals were correct, and the RPTracker was
373444ed5c5SDimitry Andric   // able to correctly handle 5 vs 6, 2 vs 3.
374444ed5c5SDimitry Andric   // (Note: This is not sufficient for RPTracker to not do mistakes for case 4)
375444ed5c5SDimitry Andric   // The RPTracker's LiveOutRegs has 1, 3, (some correct or incorrect)4, 5, 7
376444ed5c5SDimitry Andric   // Comparing to LiveInRegs is not sufficient to differenciate 4 vs 5, 7
377444ed5c5SDimitry Andric   // The use of findDefBetween removes the case 4.
3783ca95b02SDimitry Andric   for (const auto &RegMaskPair : RPTracker.getPressure().LiveOutRegs) {
3793ca95b02SDimitry Andric     unsigned Reg = RegMaskPair.RegUnit;
380444ed5c5SDimitry Andric     if (TargetRegisterInfo::isVirtualRegister(Reg) &&
3813ca95b02SDimitry Andric         isDefBetween(Reg, LIS->getInstructionIndex(*BeginBlock).getRegSlot(),
3823ca95b02SDimitry Andric                      LIS->getInstructionIndex(*EndBlock).getRegSlot(), MRI,
3833ca95b02SDimitry Andric                      LIS)) {
384444ed5c5SDimitry Andric       LiveOutRegs.insert(Reg);
385444ed5c5SDimitry Andric     }
386444ed5c5SDimitry Andric   }
387444ed5c5SDimitry Andric 
388444ed5c5SDimitry Andric   // Pressure = sum_alive_registers register size
389444ed5c5SDimitry Andric   // Internally llvm will represent some registers as big 128 bits registers
390444ed5c5SDimitry Andric   // for example, but they actually correspond to 4 actual 32 bits registers.
391444ed5c5SDimitry Andric   // Thus Pressure is not equal to num_alive_registers * constant.
392444ed5c5SDimitry Andric   LiveInPressure = TopPressure.MaxSetPressure;
393444ed5c5SDimitry Andric   LiveOutPressure = BotPressure.MaxSetPressure;
394444ed5c5SDimitry Andric 
395444ed5c5SDimitry Andric   // Prepares TopRPTracker for top down scheduling.
396444ed5c5SDimitry Andric   TopRPTracker.closeTop();
397444ed5c5SDimitry Andric }
398444ed5c5SDimitry Andric 
schedule(MachineBasicBlock::iterator BeginBlock,MachineBasicBlock::iterator EndBlock)399444ed5c5SDimitry Andric void SIScheduleBlock::schedule(MachineBasicBlock::iterator BeginBlock,
400444ed5c5SDimitry Andric                                MachineBasicBlock::iterator EndBlock) {
401444ed5c5SDimitry Andric   if (!Scheduled)
402444ed5c5SDimitry Andric     fastSchedule();
403444ed5c5SDimitry Andric 
404444ed5c5SDimitry Andric   // PreScheduling phase to set LiveIn and LiveOut.
405444ed5c5SDimitry Andric   initRegPressure(BeginBlock, EndBlock);
406444ed5c5SDimitry Andric   undoSchedule();
407444ed5c5SDimitry Andric 
408444ed5c5SDimitry Andric   // Schedule for real now.
409444ed5c5SDimitry Andric 
410444ed5c5SDimitry Andric   TopReadySUs.clear();
411444ed5c5SDimitry Andric 
412444ed5c5SDimitry Andric   for (SUnit* SU : SUnits) {
413444ed5c5SDimitry Andric     if (!SU->NumPredsLeft)
414444ed5c5SDimitry Andric       TopReadySUs.push_back(SU);
415444ed5c5SDimitry Andric   }
416444ed5c5SDimitry Andric 
417444ed5c5SDimitry Andric   while (!TopReadySUs.empty()) {
418444ed5c5SDimitry Andric     SUnit *SU = pickNode();
419444ed5c5SDimitry Andric     ScheduledSUnits.push_back(SU);
420444ed5c5SDimitry Andric     TopRPTracker.setPos(SU->getInstr());
421444ed5c5SDimitry Andric     TopRPTracker.advance();
422444ed5c5SDimitry Andric     nodeScheduled(SU);
423444ed5c5SDimitry Andric   }
424444ed5c5SDimitry Andric 
425444ed5c5SDimitry Andric   // TODO: compute InternalAdditionnalPressure.
426444ed5c5SDimitry Andric   InternalAdditionnalPressure.resize(TopPressure.MaxSetPressure.size());
427444ed5c5SDimitry Andric 
428444ed5c5SDimitry Andric   // Check everything is right.
429444ed5c5SDimitry Andric #ifndef NDEBUG
430444ed5c5SDimitry Andric   assert(SUnits.size() == ScheduledSUnits.size() &&
431444ed5c5SDimitry Andric             TopReadySUs.empty());
432444ed5c5SDimitry Andric   for (SUnit* SU : SUnits) {
433444ed5c5SDimitry Andric     assert(SU->isScheduled &&
434444ed5c5SDimitry Andric               SU->NumPredsLeft == 0);
435444ed5c5SDimitry Andric   }
436444ed5c5SDimitry Andric #endif
437444ed5c5SDimitry Andric 
438444ed5c5SDimitry Andric   Scheduled = true;
439444ed5c5SDimitry Andric }
440444ed5c5SDimitry Andric 
undoSchedule()441444ed5c5SDimitry Andric void SIScheduleBlock::undoSchedule() {
442444ed5c5SDimitry Andric   for (SUnit* SU : SUnits) {
443444ed5c5SDimitry Andric     SU->isScheduled = false;
444444ed5c5SDimitry Andric     for (SDep& Succ : SU->Succs) {
445444ed5c5SDimitry Andric       if (BC->isSUInBlock(Succ.getSUnit(), ID))
446444ed5c5SDimitry Andric         undoReleaseSucc(SU, &Succ);
447444ed5c5SDimitry Andric     }
448444ed5c5SDimitry Andric   }
449444ed5c5SDimitry Andric   HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
450444ed5c5SDimitry Andric   ScheduledSUnits.clear();
451444ed5c5SDimitry Andric   Scheduled = false;
452444ed5c5SDimitry Andric }
453444ed5c5SDimitry Andric 
undoReleaseSucc(SUnit * SU,SDep * SuccEdge)454444ed5c5SDimitry Andric void SIScheduleBlock::undoReleaseSucc(SUnit *SU, SDep *SuccEdge) {
455444ed5c5SDimitry Andric   SUnit *SuccSU = SuccEdge->getSUnit();
456444ed5c5SDimitry Andric 
457444ed5c5SDimitry Andric   if (SuccEdge->isWeak()) {
458444ed5c5SDimitry Andric     ++SuccSU->WeakPredsLeft;
459444ed5c5SDimitry Andric     return;
460444ed5c5SDimitry Andric   }
461444ed5c5SDimitry Andric   ++SuccSU->NumPredsLeft;
462444ed5c5SDimitry Andric }
463444ed5c5SDimitry Andric 
releaseSucc(SUnit * SU,SDep * SuccEdge)464444ed5c5SDimitry Andric void SIScheduleBlock::releaseSucc(SUnit *SU, SDep *SuccEdge) {
465444ed5c5SDimitry Andric   SUnit *SuccSU = SuccEdge->getSUnit();
466444ed5c5SDimitry Andric 
467444ed5c5SDimitry Andric   if (SuccEdge->isWeak()) {
468444ed5c5SDimitry Andric     --SuccSU->WeakPredsLeft;
469444ed5c5SDimitry Andric     return;
470444ed5c5SDimitry Andric   }
471444ed5c5SDimitry Andric #ifndef NDEBUG
472444ed5c5SDimitry Andric   if (SuccSU->NumPredsLeft == 0) {
473444ed5c5SDimitry Andric     dbgs() << "*** Scheduling failed! ***\n";
474*b5893f02SDimitry Andric     DAG->dumpNode(*SuccSU);
475444ed5c5SDimitry Andric     dbgs() << " has been released too many times!\n";
476444ed5c5SDimitry Andric     llvm_unreachable(nullptr);
477444ed5c5SDimitry Andric   }
478444ed5c5SDimitry Andric #endif
479444ed5c5SDimitry Andric 
480444ed5c5SDimitry Andric   --SuccSU->NumPredsLeft;
481444ed5c5SDimitry Andric }
482444ed5c5SDimitry Andric 
483444ed5c5SDimitry Andric /// Release Successors of the SU that are in the block or not.
releaseSuccessors(SUnit * SU,bool InOrOutBlock)484444ed5c5SDimitry Andric void SIScheduleBlock::releaseSuccessors(SUnit *SU, bool InOrOutBlock) {
485444ed5c5SDimitry Andric   for (SDep& Succ : SU->Succs) {
486444ed5c5SDimitry Andric     SUnit *SuccSU = Succ.getSUnit();
487444ed5c5SDimitry Andric 
4883ca95b02SDimitry Andric     if (SuccSU->NodeNum >= DAG->SUnits.size())
4893ca95b02SDimitry Andric         continue;
4903ca95b02SDimitry Andric 
491444ed5c5SDimitry Andric     if (BC->isSUInBlock(SuccSU, ID) != InOrOutBlock)
492444ed5c5SDimitry Andric       continue;
493444ed5c5SDimitry Andric 
494444ed5c5SDimitry Andric     releaseSucc(SU, &Succ);
495444ed5c5SDimitry Andric     if (SuccSU->NumPredsLeft == 0 && InOrOutBlock)
496444ed5c5SDimitry Andric       TopReadySUs.push_back(SuccSU);
497444ed5c5SDimitry Andric   }
498444ed5c5SDimitry Andric }
499444ed5c5SDimitry Andric 
nodeScheduled(SUnit * SU)500444ed5c5SDimitry Andric void SIScheduleBlock::nodeScheduled(SUnit *SU) {
501444ed5c5SDimitry Andric   // Is in TopReadySUs
502444ed5c5SDimitry Andric   assert (!SU->NumPredsLeft);
503d88c1a5aSDimitry Andric   std::vector<SUnit *>::iterator I = llvm::find(TopReadySUs, SU);
504444ed5c5SDimitry Andric   if (I == TopReadySUs.end()) {
505444ed5c5SDimitry Andric     dbgs() << "Data Structure Bug in SI Scheduler\n";
506444ed5c5SDimitry Andric     llvm_unreachable(nullptr);
507444ed5c5SDimitry Andric   }
508444ed5c5SDimitry Andric   TopReadySUs.erase(I);
509444ed5c5SDimitry Andric 
510444ed5c5SDimitry Andric   releaseSuccessors(SU, true);
511444ed5c5SDimitry Andric   // Scheduling this node will trigger a wait,
512444ed5c5SDimitry Andric   // thus propagate to other instructions that they do not need to wait either.
513444ed5c5SDimitry Andric   if (HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]])
514444ed5c5SDimitry Andric     HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
515444ed5c5SDimitry Andric 
516444ed5c5SDimitry Andric   if (DAG->IsLowLatencySU[SU->NodeNum]) {
517444ed5c5SDimitry Andric      for (SDep& Succ : SU->Succs) {
518444ed5c5SDimitry Andric       std::map<unsigned, unsigned>::iterator I =
519444ed5c5SDimitry Andric         NodeNum2Index.find(Succ.getSUnit()->NodeNum);
520444ed5c5SDimitry Andric       if (I != NodeNum2Index.end())
521444ed5c5SDimitry Andric         HasLowLatencyNonWaitedParent[I->second] = 1;
522444ed5c5SDimitry Andric     }
523444ed5c5SDimitry Andric   }
524444ed5c5SDimitry Andric   SU->isScheduled = true;
525444ed5c5SDimitry Andric }
526444ed5c5SDimitry Andric 
finalizeUnits()527444ed5c5SDimitry Andric void SIScheduleBlock::finalizeUnits() {
528444ed5c5SDimitry Andric   // We remove links from outside blocks to enable scheduling inside the block.
529444ed5c5SDimitry Andric   for (SUnit* SU : SUnits) {
530444ed5c5SDimitry Andric     releaseSuccessors(SU, false);
531444ed5c5SDimitry Andric     if (DAG->IsHighLatencySU[SU->NodeNum])
532444ed5c5SDimitry Andric       HighLatencyBlock = true;
533444ed5c5SDimitry Andric   }
534444ed5c5SDimitry Andric   HasLowLatencyNonWaitedParent.resize(SUnits.size(), 0);
535444ed5c5SDimitry Andric }
536444ed5c5SDimitry Andric 
537444ed5c5SDimitry Andric // we maintain ascending order of IDs
addPred(SIScheduleBlock * Pred)538444ed5c5SDimitry Andric void SIScheduleBlock::addPred(SIScheduleBlock *Pred) {
539444ed5c5SDimitry Andric   unsigned PredID = Pred->getID();
540444ed5c5SDimitry Andric 
541444ed5c5SDimitry Andric   // Check if not already predecessor.
542444ed5c5SDimitry Andric   for (SIScheduleBlock* P : Preds) {
543444ed5c5SDimitry Andric     if (PredID == P->getID())
544444ed5c5SDimitry Andric       return;
545444ed5c5SDimitry Andric   }
546444ed5c5SDimitry Andric   Preds.push_back(Pred);
547444ed5c5SDimitry Andric 
5483ca95b02SDimitry Andric   assert(none_of(Succs,
5497a7e6055SDimitry Andric                  [=](std::pair<SIScheduleBlock*,
5507a7e6055SDimitry Andric                      SIScheduleBlockLinkKind> S) {
5517a7e6055SDimitry Andric                    return PredID == S.first->getID();
5527a7e6055SDimitry Andric                     }) &&
5533ca95b02SDimitry Andric          "Loop in the Block Graph!");
554444ed5c5SDimitry Andric }
555444ed5c5SDimitry Andric 
addSucc(SIScheduleBlock * Succ,SIScheduleBlockLinkKind Kind)5567a7e6055SDimitry Andric void SIScheduleBlock::addSucc(SIScheduleBlock *Succ,
5577a7e6055SDimitry Andric                               SIScheduleBlockLinkKind Kind) {
558444ed5c5SDimitry Andric   unsigned SuccID = Succ->getID();
559444ed5c5SDimitry Andric 
560444ed5c5SDimitry Andric   // Check if not already predecessor.
5617a7e6055SDimitry Andric   for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> &S : Succs) {
5627a7e6055SDimitry Andric     if (SuccID == S.first->getID()) {
5637a7e6055SDimitry Andric       if (S.second == SIScheduleBlockLinkKind::NoData &&
5647a7e6055SDimitry Andric           Kind == SIScheduleBlockLinkKind::Data)
5657a7e6055SDimitry Andric         S.second = Kind;
566444ed5c5SDimitry Andric       return;
567444ed5c5SDimitry Andric     }
5687a7e6055SDimitry Andric   }
569444ed5c5SDimitry Andric   if (Succ->isHighLatencyBlock())
570444ed5c5SDimitry Andric     ++NumHighLatencySuccessors;
5717a7e6055SDimitry Andric   Succs.push_back(std::make_pair(Succ, Kind));
5727a7e6055SDimitry Andric 
5733ca95b02SDimitry Andric   assert(none_of(Preds,
5743ca95b02SDimitry Andric                  [=](SIScheduleBlock *P) { return SuccID == P->getID(); }) &&
5753ca95b02SDimitry Andric          "Loop in the Block Graph!");
576444ed5c5SDimitry Andric }
577444ed5c5SDimitry Andric 
578444ed5c5SDimitry Andric #ifndef NDEBUG
printDebug(bool full)579444ed5c5SDimitry Andric void SIScheduleBlock::printDebug(bool full) {
580444ed5c5SDimitry Andric   dbgs() << "Block (" << ID << ")\n";
581444ed5c5SDimitry Andric   if (!full)
582444ed5c5SDimitry Andric     return;
583444ed5c5SDimitry Andric 
584444ed5c5SDimitry Andric   dbgs() << "\nContains High Latency Instruction: "
585444ed5c5SDimitry Andric          << HighLatencyBlock << '\n';
586444ed5c5SDimitry Andric   dbgs() << "\nDepends On:\n";
587444ed5c5SDimitry Andric   for (SIScheduleBlock* P : Preds) {
588444ed5c5SDimitry Andric     P->printDebug(false);
589444ed5c5SDimitry Andric   }
590444ed5c5SDimitry Andric 
591444ed5c5SDimitry Andric   dbgs() << "\nSuccessors:\n";
5927a7e6055SDimitry Andric   for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> S : Succs) {
5937a7e6055SDimitry Andric     if (S.second == SIScheduleBlockLinkKind::Data)
5947a7e6055SDimitry Andric       dbgs() << "(Data Dep) ";
5957a7e6055SDimitry Andric     S.first->printDebug(false);
596444ed5c5SDimitry Andric   }
597444ed5c5SDimitry Andric 
598444ed5c5SDimitry Andric   if (Scheduled) {
599444ed5c5SDimitry Andric     dbgs() << "LiveInPressure " << LiveInPressure[DAG->getSGPRSetID()] << ' '
600444ed5c5SDimitry Andric            << LiveInPressure[DAG->getVGPRSetID()] << '\n';
601444ed5c5SDimitry Andric     dbgs() << "LiveOutPressure " << LiveOutPressure[DAG->getSGPRSetID()] << ' '
602444ed5c5SDimitry Andric            << LiveOutPressure[DAG->getVGPRSetID()] << "\n\n";
603444ed5c5SDimitry Andric     dbgs() << "LiveIns:\n";
604444ed5c5SDimitry Andric     for (unsigned Reg : LiveInRegs)
6052cab237bSDimitry Andric       dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
606444ed5c5SDimitry Andric 
607444ed5c5SDimitry Andric     dbgs() << "\nLiveOuts:\n";
608444ed5c5SDimitry Andric     for (unsigned Reg : LiveOutRegs)
6092cab237bSDimitry Andric       dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
610444ed5c5SDimitry Andric   }
611444ed5c5SDimitry Andric 
612444ed5c5SDimitry Andric   dbgs() << "\nInstructions:\n";
613444ed5c5SDimitry Andric   if (!Scheduled) {
614*b5893f02SDimitry Andric     for (const SUnit* SU : SUnits)
615*b5893f02SDimitry Andric       DAG->dumpNode(*SU);
616444ed5c5SDimitry Andric   } else {
617*b5893f02SDimitry Andric     for (const SUnit* SU : SUnits)
618*b5893f02SDimitry Andric       DAG->dumpNode(*SU);
619444ed5c5SDimitry Andric   }
620444ed5c5SDimitry Andric 
621444ed5c5SDimitry Andric   dbgs() << "///////////////////////\n";
622444ed5c5SDimitry Andric }
623444ed5c5SDimitry Andric #endif
624444ed5c5SDimitry Andric 
625444ed5c5SDimitry Andric // SIScheduleBlockCreator //
626444ed5c5SDimitry Andric 
SIScheduleBlockCreator(SIScheduleDAGMI * DAG)627444ed5c5SDimitry Andric SIScheduleBlockCreator::SIScheduleBlockCreator(SIScheduleDAGMI *DAG) :
628444ed5c5SDimitry Andric DAG(DAG) {
629444ed5c5SDimitry Andric }
630444ed5c5SDimitry Andric 
631d88c1a5aSDimitry Andric SIScheduleBlockCreator::~SIScheduleBlockCreator() = default;
632444ed5c5SDimitry Andric 
633444ed5c5SDimitry Andric SIScheduleBlocks
getBlocks(SISchedulerBlockCreatorVariant BlockVariant)634444ed5c5SDimitry Andric SIScheduleBlockCreator::getBlocks(SISchedulerBlockCreatorVariant BlockVariant) {
635444ed5c5SDimitry Andric   std::map<SISchedulerBlockCreatorVariant, SIScheduleBlocks>::iterator B =
636444ed5c5SDimitry Andric     Blocks.find(BlockVariant);
637444ed5c5SDimitry Andric   if (B == Blocks.end()) {
638444ed5c5SDimitry Andric     SIScheduleBlocks Res;
639444ed5c5SDimitry Andric     createBlocksForVariant(BlockVariant);
640444ed5c5SDimitry Andric     topologicalSort();
641444ed5c5SDimitry Andric     scheduleInsideBlocks();
642444ed5c5SDimitry Andric     fillStats();
643444ed5c5SDimitry Andric     Res.Blocks = CurrentBlocks;
644444ed5c5SDimitry Andric     Res.TopDownIndex2Block = TopDownIndex2Block;
645444ed5c5SDimitry Andric     Res.TopDownBlock2Index = TopDownBlock2Index;
646444ed5c5SDimitry Andric     Blocks[BlockVariant] = Res;
647444ed5c5SDimitry Andric     return Res;
648444ed5c5SDimitry Andric   } else {
649444ed5c5SDimitry Andric     return B->second;
650444ed5c5SDimitry Andric   }
651444ed5c5SDimitry Andric }
652444ed5c5SDimitry Andric 
isSUInBlock(SUnit * SU,unsigned ID)653444ed5c5SDimitry Andric bool SIScheduleBlockCreator::isSUInBlock(SUnit *SU, unsigned ID) {
654444ed5c5SDimitry Andric   if (SU->NodeNum >= DAG->SUnits.size())
655444ed5c5SDimitry Andric     return false;
656444ed5c5SDimitry Andric   return CurrentBlocks[Node2CurrentBlock[SU->NodeNum]]->getID() == ID;
657444ed5c5SDimitry Andric }
658444ed5c5SDimitry Andric 
colorHighLatenciesAlone()659444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorHighLatenciesAlone() {
660444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
661444ed5c5SDimitry Andric 
662444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
663444ed5c5SDimitry Andric     SUnit *SU = &DAG->SUnits[i];
664444ed5c5SDimitry Andric     if (DAG->IsHighLatencySU[SU->NodeNum]) {
665444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = NextReservedID++;
666444ed5c5SDimitry Andric     }
667444ed5c5SDimitry Andric   }
668444ed5c5SDimitry Andric }
669444ed5c5SDimitry Andric 
6707a7e6055SDimitry Andric static bool
hasDataDependencyPred(const SUnit & SU,const SUnit & FromSU)6717a7e6055SDimitry Andric hasDataDependencyPred(const SUnit &SU, const SUnit &FromSU) {
6727a7e6055SDimitry Andric   for (const auto &PredDep : SU.Preds) {
6737a7e6055SDimitry Andric     if (PredDep.getSUnit() == &FromSU &&
6747a7e6055SDimitry Andric         PredDep.getKind() == llvm::SDep::Data)
6757a7e6055SDimitry Andric       return true;
6767a7e6055SDimitry Andric   }
6777a7e6055SDimitry Andric   return false;
6787a7e6055SDimitry Andric }
6797a7e6055SDimitry Andric 
colorHighLatenciesGroups()680444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorHighLatenciesGroups() {
681444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
682444ed5c5SDimitry Andric   unsigned NumHighLatencies = 0;
683444ed5c5SDimitry Andric   unsigned GroupSize;
6847a7e6055SDimitry Andric   int Color = NextReservedID;
685444ed5c5SDimitry Andric   unsigned Count = 0;
686444ed5c5SDimitry Andric   std::set<unsigned> FormingGroup;
687444ed5c5SDimitry Andric 
688444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
689444ed5c5SDimitry Andric     SUnit *SU = &DAG->SUnits[i];
690444ed5c5SDimitry Andric     if (DAG->IsHighLatencySU[SU->NodeNum])
691444ed5c5SDimitry Andric       ++NumHighLatencies;
692444ed5c5SDimitry Andric   }
693444ed5c5SDimitry Andric 
694444ed5c5SDimitry Andric   if (NumHighLatencies == 0)
695444ed5c5SDimitry Andric     return;
696444ed5c5SDimitry Andric 
697444ed5c5SDimitry Andric   if (NumHighLatencies <= 6)
698444ed5c5SDimitry Andric     GroupSize = 2;
699444ed5c5SDimitry Andric   else if (NumHighLatencies <= 12)
700444ed5c5SDimitry Andric     GroupSize = 3;
701444ed5c5SDimitry Andric   else
702444ed5c5SDimitry Andric     GroupSize = 4;
703444ed5c5SDimitry Andric 
7047a7e6055SDimitry Andric   for (unsigned SUNum : DAG->TopDownIndex2SU) {
7057a7e6055SDimitry Andric     const SUnit &SU = DAG->SUnits[SUNum];
7067a7e6055SDimitry Andric     if (DAG->IsHighLatencySU[SU.NodeNum]) {
707444ed5c5SDimitry Andric       unsigned CompatibleGroup = true;
7087a7e6055SDimitry Andric       int ProposedColor = Color;
7097a7e6055SDimitry Andric       std::vector<int> AdditionalElements;
7107a7e6055SDimitry Andric 
7117a7e6055SDimitry Andric       // We don't want to put in the same block
7127a7e6055SDimitry Andric       // two high latency instructions that depend
7137a7e6055SDimitry Andric       // on each other.
7147a7e6055SDimitry Andric       // One way would be to check canAddEdge
7157a7e6055SDimitry Andric       // in both directions, but that currently is not
7167a7e6055SDimitry Andric       // enough because there the high latency order is
7177a7e6055SDimitry Andric       // enforced (via links).
7187a7e6055SDimitry Andric       // Instead, look at the dependencies between the
7197a7e6055SDimitry Andric       // high latency instructions and deduce if it is
7207a7e6055SDimitry Andric       // a data dependency or not.
721444ed5c5SDimitry Andric       for (unsigned j : FormingGroup) {
7227a7e6055SDimitry Andric         bool HasSubGraph;
7237a7e6055SDimitry Andric         std::vector<int> SubGraph;
7247a7e6055SDimitry Andric         // By construction (topological order), if SU and
7257a7e6055SDimitry Andric         // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary
7267a7e6055SDimitry Andric         // in the parent graph of SU.
7277a7e6055SDimitry Andric #ifndef NDEBUG
7287a7e6055SDimitry Andric         SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j],
7297a7e6055SDimitry Andric                                                HasSubGraph);
7307a7e6055SDimitry Andric         assert(!HasSubGraph);
7317a7e6055SDimitry Andric #endif
7327a7e6055SDimitry Andric         SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU,
7337a7e6055SDimitry Andric                                                HasSubGraph);
7347a7e6055SDimitry Andric         if (!HasSubGraph)
7357a7e6055SDimitry Andric           continue; // No dependencies between each other
7367a7e6055SDimitry Andric         else if (SubGraph.size() > 5) {
7377a7e6055SDimitry Andric           // Too many elements would be required to be added to the block.
738444ed5c5SDimitry Andric           CompatibleGroup = false;
7397a7e6055SDimitry Andric           break;
740444ed5c5SDimitry Andric         }
7417a7e6055SDimitry Andric         else {
7427a7e6055SDimitry Andric           // Check the type of dependency
7437a7e6055SDimitry Andric           for (unsigned k : SubGraph) {
7447a7e6055SDimitry Andric             // If in the path to join the two instructions,
7457a7e6055SDimitry Andric             // there is another high latency instruction,
7467a7e6055SDimitry Andric             // or instructions colored for another block
7477a7e6055SDimitry Andric             // abort the merge.
7487a7e6055SDimitry Andric             if (DAG->IsHighLatencySU[k] ||
7497a7e6055SDimitry Andric                 (CurrentColoring[k] != ProposedColor &&
7507a7e6055SDimitry Andric                  CurrentColoring[k] != 0)) {
7517a7e6055SDimitry Andric               CompatibleGroup = false;
7527a7e6055SDimitry Andric               break;
7537a7e6055SDimitry Andric             }
7547a7e6055SDimitry Andric             // If one of the SU in the subgraph depends on the result of SU j,
7557a7e6055SDimitry Andric             // there'll be a data dependency.
7567a7e6055SDimitry Andric             if (hasDataDependencyPred(DAG->SUnits[k], DAG->SUnits[j])) {
7577a7e6055SDimitry Andric               CompatibleGroup = false;
7587a7e6055SDimitry Andric               break;
7597a7e6055SDimitry Andric             }
7607a7e6055SDimitry Andric           }
7617a7e6055SDimitry Andric           if (!CompatibleGroup)
7627a7e6055SDimitry Andric             break;
7637a7e6055SDimitry Andric           // Same check for the SU
7647a7e6055SDimitry Andric           if (hasDataDependencyPred(SU, DAG->SUnits[j])) {
7657a7e6055SDimitry Andric             CompatibleGroup = false;
7667a7e6055SDimitry Andric             break;
7677a7e6055SDimitry Andric           }
7687a7e6055SDimitry Andric           // Add all the required instructions to the block
7697a7e6055SDimitry Andric           // These cannot live in another block (because they
7707a7e6055SDimitry Andric           // depend (order dependency) on one of the
7717a7e6055SDimitry Andric           // instruction in the block, and are required for the
7727a7e6055SDimitry Andric           // high latency instruction we add.
7737a7e6055SDimitry Andric           AdditionalElements.insert(AdditionalElements.end(),
7747a7e6055SDimitry Andric                                     SubGraph.begin(), SubGraph.end());
7757a7e6055SDimitry Andric         }
7767a7e6055SDimitry Andric       }
7777a7e6055SDimitry Andric       if (CompatibleGroup) {
7787a7e6055SDimitry Andric         FormingGroup.insert(SU.NodeNum);
7797a7e6055SDimitry Andric         for (unsigned j : AdditionalElements)
7807a7e6055SDimitry Andric           CurrentColoring[j] = ProposedColor;
7817a7e6055SDimitry Andric         CurrentColoring[SU.NodeNum] = ProposedColor;
7827a7e6055SDimitry Andric         ++Count;
7837a7e6055SDimitry Andric       }
7847a7e6055SDimitry Andric       // Found one incompatible instruction,
7857a7e6055SDimitry Andric       // or has filled a big enough group.
7867a7e6055SDimitry Andric       // -> start a new one.
7877a7e6055SDimitry Andric       if (!CompatibleGroup) {
788444ed5c5SDimitry Andric         FormingGroup.clear();
789444ed5c5SDimitry Andric         Color = ++NextReservedID;
790444ed5c5SDimitry Andric         ProposedColor = Color;
7917a7e6055SDimitry Andric         FormingGroup.insert(SU.NodeNum);
7927a7e6055SDimitry Andric         CurrentColoring[SU.NodeNum] = ProposedColor;
793444ed5c5SDimitry Andric         Count = 0;
7947a7e6055SDimitry Andric       } else if (Count == GroupSize) {
7957a7e6055SDimitry Andric         FormingGroup.clear();
7967a7e6055SDimitry Andric         Color = ++NextReservedID;
7977a7e6055SDimitry Andric         ProposedColor = Color;
7987a7e6055SDimitry Andric         Count = 0;
799444ed5c5SDimitry Andric       }
800444ed5c5SDimitry Andric     }
801444ed5c5SDimitry Andric   }
802444ed5c5SDimitry Andric }
803444ed5c5SDimitry Andric 
colorComputeReservedDependencies()804444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorComputeReservedDependencies() {
805444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
806444ed5c5SDimitry Andric   std::map<std::set<unsigned>, unsigned> ColorCombinations;
807444ed5c5SDimitry Andric 
808444ed5c5SDimitry Andric   CurrentTopDownReservedDependencyColoring.clear();
809444ed5c5SDimitry Andric   CurrentBottomUpReservedDependencyColoring.clear();
810444ed5c5SDimitry Andric 
811444ed5c5SDimitry Andric   CurrentTopDownReservedDependencyColoring.resize(DAGSize, 0);
812444ed5c5SDimitry Andric   CurrentBottomUpReservedDependencyColoring.resize(DAGSize, 0);
813444ed5c5SDimitry Andric 
814444ed5c5SDimitry Andric   // Traverse TopDown, and give different colors to SUs depending
815444ed5c5SDimitry Andric   // on which combination of High Latencies they depend on.
816444ed5c5SDimitry Andric 
8173ca95b02SDimitry Andric   for (unsigned SUNum : DAG->TopDownIndex2SU) {
8183ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
819444ed5c5SDimitry Andric     std::set<unsigned> SUColors;
820444ed5c5SDimitry Andric 
821444ed5c5SDimitry Andric     // Already given.
822444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum]) {
823444ed5c5SDimitry Andric       CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
824444ed5c5SDimitry Andric         CurrentColoring[SU->NodeNum];
825444ed5c5SDimitry Andric       continue;
826444ed5c5SDimitry Andric     }
827444ed5c5SDimitry Andric 
828444ed5c5SDimitry Andric    for (SDep& PredDep : SU->Preds) {
829444ed5c5SDimitry Andric       SUnit *Pred = PredDep.getSUnit();
830444ed5c5SDimitry Andric       if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
831444ed5c5SDimitry Andric         continue;
832444ed5c5SDimitry Andric       if (CurrentTopDownReservedDependencyColoring[Pred->NodeNum] > 0)
833444ed5c5SDimitry Andric         SUColors.insert(CurrentTopDownReservedDependencyColoring[Pred->NodeNum]);
834444ed5c5SDimitry Andric     }
835444ed5c5SDimitry Andric     // Color 0 by default.
836444ed5c5SDimitry Andric     if (SUColors.empty())
837444ed5c5SDimitry Andric       continue;
838444ed5c5SDimitry Andric     // Same color than parents.
839444ed5c5SDimitry Andric     if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
840444ed5c5SDimitry Andric       CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
841444ed5c5SDimitry Andric         *SUColors.begin();
842444ed5c5SDimitry Andric     else {
843444ed5c5SDimitry Andric       std::map<std::set<unsigned>, unsigned>::iterator Pos =
844444ed5c5SDimitry Andric         ColorCombinations.find(SUColors);
845444ed5c5SDimitry Andric       if (Pos != ColorCombinations.end()) {
846444ed5c5SDimitry Andric           CurrentTopDownReservedDependencyColoring[SU->NodeNum] = Pos->second;
847444ed5c5SDimitry Andric       } else {
848444ed5c5SDimitry Andric         CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
849444ed5c5SDimitry Andric           NextNonReservedID;
850444ed5c5SDimitry Andric         ColorCombinations[SUColors] = NextNonReservedID++;
851444ed5c5SDimitry Andric       }
852444ed5c5SDimitry Andric     }
853444ed5c5SDimitry Andric   }
854444ed5c5SDimitry Andric 
855444ed5c5SDimitry Andric   ColorCombinations.clear();
856444ed5c5SDimitry Andric 
857444ed5c5SDimitry Andric   // Same as before, but BottomUp.
858444ed5c5SDimitry Andric 
8593ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
8603ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
861444ed5c5SDimitry Andric     std::set<unsigned> SUColors;
862444ed5c5SDimitry Andric 
863444ed5c5SDimitry Andric     // Already given.
864444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum]) {
865444ed5c5SDimitry Andric       CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
866444ed5c5SDimitry Andric         CurrentColoring[SU->NodeNum];
867444ed5c5SDimitry Andric       continue;
868444ed5c5SDimitry Andric     }
869444ed5c5SDimitry Andric 
870444ed5c5SDimitry Andric     for (SDep& SuccDep : SU->Succs) {
871444ed5c5SDimitry Andric       SUnit *Succ = SuccDep.getSUnit();
872444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
873444ed5c5SDimitry Andric         continue;
874444ed5c5SDimitry Andric       if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0)
875444ed5c5SDimitry Andric         SUColors.insert(CurrentBottomUpReservedDependencyColoring[Succ->NodeNum]);
876444ed5c5SDimitry Andric     }
877444ed5c5SDimitry Andric     // Keep color 0.
878444ed5c5SDimitry Andric     if (SUColors.empty())
879444ed5c5SDimitry Andric       continue;
880444ed5c5SDimitry Andric     // Same color than parents.
881444ed5c5SDimitry Andric     if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
882444ed5c5SDimitry Andric       CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
883444ed5c5SDimitry Andric         *SUColors.begin();
884444ed5c5SDimitry Andric     else {
885444ed5c5SDimitry Andric       std::map<std::set<unsigned>, unsigned>::iterator Pos =
886444ed5c5SDimitry Andric         ColorCombinations.find(SUColors);
887444ed5c5SDimitry Andric       if (Pos != ColorCombinations.end()) {
888444ed5c5SDimitry Andric         CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = Pos->second;
889444ed5c5SDimitry Andric       } else {
890444ed5c5SDimitry Andric         CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
891444ed5c5SDimitry Andric           NextNonReservedID;
892444ed5c5SDimitry Andric         ColorCombinations[SUColors] = NextNonReservedID++;
893444ed5c5SDimitry Andric       }
894444ed5c5SDimitry Andric     }
895444ed5c5SDimitry Andric   }
896444ed5c5SDimitry Andric }
897444ed5c5SDimitry Andric 
colorAccordingToReservedDependencies()898444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorAccordingToReservedDependencies() {
899444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
900444ed5c5SDimitry Andric   std::map<std::pair<unsigned, unsigned>, unsigned> ColorCombinations;
901444ed5c5SDimitry Andric 
902444ed5c5SDimitry Andric   // Every combination of colors given by the top down
903444ed5c5SDimitry Andric   // and bottom up Reserved node dependency
904444ed5c5SDimitry Andric 
905444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
906444ed5c5SDimitry Andric     SUnit *SU = &DAG->SUnits[i];
907444ed5c5SDimitry Andric     std::pair<unsigned, unsigned> SUColors;
908444ed5c5SDimitry Andric 
909444ed5c5SDimitry Andric     // High latency instructions: already given.
910444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum])
911444ed5c5SDimitry Andric       continue;
912444ed5c5SDimitry Andric 
913444ed5c5SDimitry Andric     SUColors.first = CurrentTopDownReservedDependencyColoring[SU->NodeNum];
914444ed5c5SDimitry Andric     SUColors.second = CurrentBottomUpReservedDependencyColoring[SU->NodeNum];
915444ed5c5SDimitry Andric 
916444ed5c5SDimitry Andric     std::map<std::pair<unsigned, unsigned>, unsigned>::iterator Pos =
917444ed5c5SDimitry Andric       ColorCombinations.find(SUColors);
918444ed5c5SDimitry Andric     if (Pos != ColorCombinations.end()) {
919444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = Pos->second;
920444ed5c5SDimitry Andric     } else {
921444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = NextNonReservedID;
922444ed5c5SDimitry Andric       ColorCombinations[SUColors] = NextNonReservedID++;
923444ed5c5SDimitry Andric     }
924444ed5c5SDimitry Andric   }
925444ed5c5SDimitry Andric }
926444ed5c5SDimitry Andric 
colorEndsAccordingToDependencies()927444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorEndsAccordingToDependencies() {
928444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
929444ed5c5SDimitry Andric   std::vector<int> PendingColoring = CurrentColoring;
930444ed5c5SDimitry Andric 
9317a7e6055SDimitry Andric   assert(DAGSize >= 1 &&
9327a7e6055SDimitry Andric          CurrentBottomUpReservedDependencyColoring.size() == DAGSize &&
9337a7e6055SDimitry Andric          CurrentTopDownReservedDependencyColoring.size() == DAGSize);
9347a7e6055SDimitry Andric   // If there is no reserved block at all, do nothing. We don't want
9357a7e6055SDimitry Andric   // everything in one block.
9367a7e6055SDimitry Andric   if (*std::max_element(CurrentBottomUpReservedDependencyColoring.begin(),
9377a7e6055SDimitry Andric                         CurrentBottomUpReservedDependencyColoring.end()) == 0 &&
9387a7e6055SDimitry Andric       *std::max_element(CurrentTopDownReservedDependencyColoring.begin(),
9397a7e6055SDimitry Andric                         CurrentTopDownReservedDependencyColoring.end()) == 0)
9407a7e6055SDimitry Andric     return;
9417a7e6055SDimitry Andric 
9423ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
9433ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
944444ed5c5SDimitry Andric     std::set<unsigned> SUColors;
945444ed5c5SDimitry Andric     std::set<unsigned> SUColorsPending;
946444ed5c5SDimitry Andric 
947444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
948444ed5c5SDimitry Andric       continue;
949444ed5c5SDimitry Andric 
950444ed5c5SDimitry Andric     if (CurrentBottomUpReservedDependencyColoring[SU->NodeNum] > 0 ||
951444ed5c5SDimitry Andric         CurrentTopDownReservedDependencyColoring[SU->NodeNum] > 0)
952444ed5c5SDimitry Andric       continue;
953444ed5c5SDimitry Andric 
954444ed5c5SDimitry Andric     for (SDep& SuccDep : SU->Succs) {
955444ed5c5SDimitry Andric       SUnit *Succ = SuccDep.getSUnit();
956444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
957444ed5c5SDimitry Andric         continue;
958444ed5c5SDimitry Andric       if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0 ||
959444ed5c5SDimitry Andric           CurrentTopDownReservedDependencyColoring[Succ->NodeNum] > 0)
960444ed5c5SDimitry Andric         SUColors.insert(CurrentColoring[Succ->NodeNum]);
961444ed5c5SDimitry Andric       SUColorsPending.insert(PendingColoring[Succ->NodeNum]);
962444ed5c5SDimitry Andric     }
9637a7e6055SDimitry Andric     // If there is only one child/parent block, and that block
9647a7e6055SDimitry Andric     // is not among the ones we are removing in this path, then
9657a7e6055SDimitry Andric     // merge the instruction to that block
966444ed5c5SDimitry Andric     if (SUColors.size() == 1 && SUColorsPending.size() == 1)
967444ed5c5SDimitry Andric       PendingColoring[SU->NodeNum] = *SUColors.begin();
968444ed5c5SDimitry Andric     else // TODO: Attribute new colors depending on color
969444ed5c5SDimitry Andric          // combination of children.
970444ed5c5SDimitry Andric       PendingColoring[SU->NodeNum] = NextNonReservedID++;
971444ed5c5SDimitry Andric   }
972444ed5c5SDimitry Andric   CurrentColoring = PendingColoring;
973444ed5c5SDimitry Andric }
974444ed5c5SDimitry Andric 
975444ed5c5SDimitry Andric 
colorForceConsecutiveOrderInGroup()976444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorForceConsecutiveOrderInGroup() {
977444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
978444ed5c5SDimitry Andric   unsigned PreviousColor;
979444ed5c5SDimitry Andric   std::set<unsigned> SeenColors;
980444ed5c5SDimitry Andric 
981444ed5c5SDimitry Andric   if (DAGSize <= 1)
982444ed5c5SDimitry Andric     return;
983444ed5c5SDimitry Andric 
984444ed5c5SDimitry Andric   PreviousColor = CurrentColoring[0];
985444ed5c5SDimitry Andric 
986444ed5c5SDimitry Andric   for (unsigned i = 1, e = DAGSize; i != e; ++i) {
987444ed5c5SDimitry Andric     SUnit *SU = &DAG->SUnits[i];
988444ed5c5SDimitry Andric     unsigned CurrentColor = CurrentColoring[i];
989444ed5c5SDimitry Andric     unsigned PreviousColorSave = PreviousColor;
990444ed5c5SDimitry Andric     assert(i == SU->NodeNum);
991444ed5c5SDimitry Andric 
992444ed5c5SDimitry Andric     if (CurrentColor != PreviousColor)
993444ed5c5SDimitry Andric       SeenColors.insert(PreviousColor);
994444ed5c5SDimitry Andric     PreviousColor = CurrentColor;
995444ed5c5SDimitry Andric 
996444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
997444ed5c5SDimitry Andric       continue;
998444ed5c5SDimitry Andric 
999444ed5c5SDimitry Andric     if (SeenColors.find(CurrentColor) == SeenColors.end())
1000444ed5c5SDimitry Andric       continue;
1001444ed5c5SDimitry Andric 
1002444ed5c5SDimitry Andric     if (PreviousColorSave != CurrentColor)
1003444ed5c5SDimitry Andric       CurrentColoring[i] = NextNonReservedID++;
1004444ed5c5SDimitry Andric     else
1005444ed5c5SDimitry Andric       CurrentColoring[i] = CurrentColoring[i-1];
1006444ed5c5SDimitry Andric   }
1007444ed5c5SDimitry Andric }
1008444ed5c5SDimitry Andric 
colorMergeConstantLoadsNextGroup()1009444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorMergeConstantLoadsNextGroup() {
1010444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
1011444ed5c5SDimitry Andric 
10123ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
10133ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
1014444ed5c5SDimitry Andric     std::set<unsigned> SUColors;
1015444ed5c5SDimitry Andric 
1016444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1017444ed5c5SDimitry Andric       continue;
1018444ed5c5SDimitry Andric 
1019444ed5c5SDimitry Andric     // No predecessor: Vgpr constant loading.
1020444ed5c5SDimitry Andric     // Low latency instructions usually have a predecessor (the address)
1021444ed5c5SDimitry Andric     if (SU->Preds.size() > 0 && !DAG->IsLowLatencySU[SU->NodeNum])
1022444ed5c5SDimitry Andric       continue;
1023444ed5c5SDimitry Andric 
1024444ed5c5SDimitry Andric     for (SDep& SuccDep : SU->Succs) {
1025444ed5c5SDimitry Andric       SUnit *Succ = SuccDep.getSUnit();
1026444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1027444ed5c5SDimitry Andric         continue;
1028444ed5c5SDimitry Andric       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1029444ed5c5SDimitry Andric     }
1030444ed5c5SDimitry Andric     if (SUColors.size() == 1)
1031444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1032444ed5c5SDimitry Andric   }
1033444ed5c5SDimitry Andric }
1034444ed5c5SDimitry Andric 
colorMergeIfPossibleNextGroup()1035444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorMergeIfPossibleNextGroup() {
1036444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
1037444ed5c5SDimitry Andric 
10383ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
10393ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
1040444ed5c5SDimitry Andric     std::set<unsigned> SUColors;
1041444ed5c5SDimitry Andric 
1042444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1043444ed5c5SDimitry Andric       continue;
1044444ed5c5SDimitry Andric 
1045444ed5c5SDimitry Andric     for (SDep& SuccDep : SU->Succs) {
1046444ed5c5SDimitry Andric        SUnit *Succ = SuccDep.getSUnit();
1047444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1048444ed5c5SDimitry Andric         continue;
1049444ed5c5SDimitry Andric       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1050444ed5c5SDimitry Andric     }
1051444ed5c5SDimitry Andric     if (SUColors.size() == 1)
1052444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1053444ed5c5SDimitry Andric   }
1054444ed5c5SDimitry Andric }
1055444ed5c5SDimitry Andric 
colorMergeIfPossibleNextGroupOnlyForReserved()1056444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorMergeIfPossibleNextGroupOnlyForReserved() {
1057444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
1058444ed5c5SDimitry Andric 
10593ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
10603ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
1061444ed5c5SDimitry Andric     std::set<unsigned> SUColors;
1062444ed5c5SDimitry Andric 
1063444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1064444ed5c5SDimitry Andric       continue;
1065444ed5c5SDimitry Andric 
1066444ed5c5SDimitry Andric     for (SDep& SuccDep : SU->Succs) {
1067444ed5c5SDimitry Andric        SUnit *Succ = SuccDep.getSUnit();
1068444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1069444ed5c5SDimitry Andric         continue;
1070444ed5c5SDimitry Andric       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1071444ed5c5SDimitry Andric     }
1072444ed5c5SDimitry Andric     if (SUColors.size() == 1 && *SUColors.begin() <= DAGSize)
1073444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1074444ed5c5SDimitry Andric   }
1075444ed5c5SDimitry Andric }
1076444ed5c5SDimitry Andric 
colorMergeIfPossibleSmallGroupsToNextGroup()1077444ed5c5SDimitry Andric void SIScheduleBlockCreator::colorMergeIfPossibleSmallGroupsToNextGroup() {
1078444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
1079444ed5c5SDimitry Andric   std::map<unsigned, unsigned> ColorCount;
1080444ed5c5SDimitry Andric 
10813ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
10823ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
1083444ed5c5SDimitry Andric     unsigned color = CurrentColoring[SU->NodeNum];
1084444ed5c5SDimitry Andric      ++ColorCount[color];
1085444ed5c5SDimitry Andric   }
1086444ed5c5SDimitry Andric 
10873ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
10883ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
1089444ed5c5SDimitry Andric     unsigned color = CurrentColoring[SU->NodeNum];
1090444ed5c5SDimitry Andric     std::set<unsigned> SUColors;
1091444ed5c5SDimitry Andric 
1092444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1093444ed5c5SDimitry Andric       continue;
1094444ed5c5SDimitry Andric 
1095444ed5c5SDimitry Andric     if (ColorCount[color] > 1)
1096444ed5c5SDimitry Andric       continue;
1097444ed5c5SDimitry Andric 
1098444ed5c5SDimitry Andric     for (SDep& SuccDep : SU->Succs) {
1099444ed5c5SDimitry Andric        SUnit *Succ = SuccDep.getSUnit();
1100444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1101444ed5c5SDimitry Andric         continue;
1102444ed5c5SDimitry Andric       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1103444ed5c5SDimitry Andric     }
1104444ed5c5SDimitry Andric     if (SUColors.size() == 1 && *SUColors.begin() != color) {
1105444ed5c5SDimitry Andric       --ColorCount[color];
1106444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1107444ed5c5SDimitry Andric       ++ColorCount[*SUColors.begin()];
1108444ed5c5SDimitry Andric     }
1109444ed5c5SDimitry Andric   }
1110444ed5c5SDimitry Andric }
1111444ed5c5SDimitry Andric 
cutHugeBlocks()1112444ed5c5SDimitry Andric void SIScheduleBlockCreator::cutHugeBlocks() {
1113444ed5c5SDimitry Andric   // TODO
1114444ed5c5SDimitry Andric }
1115444ed5c5SDimitry Andric 
regroupNoUserInstructions()1116444ed5c5SDimitry Andric void SIScheduleBlockCreator::regroupNoUserInstructions() {
1117444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
1118444ed5c5SDimitry Andric   int GroupID = NextNonReservedID++;
1119444ed5c5SDimitry Andric 
11203ca95b02SDimitry Andric   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
11213ca95b02SDimitry Andric     SUnit *SU = &DAG->SUnits[SUNum];
1122444ed5c5SDimitry Andric     bool hasSuccessor = false;
1123444ed5c5SDimitry Andric 
1124444ed5c5SDimitry Andric     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1125444ed5c5SDimitry Andric       continue;
1126444ed5c5SDimitry Andric 
1127444ed5c5SDimitry Andric     for (SDep& SuccDep : SU->Succs) {
1128444ed5c5SDimitry Andric        SUnit *Succ = SuccDep.getSUnit();
1129444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1130444ed5c5SDimitry Andric         continue;
1131444ed5c5SDimitry Andric       hasSuccessor = true;
1132444ed5c5SDimitry Andric     }
1133444ed5c5SDimitry Andric     if (!hasSuccessor)
1134444ed5c5SDimitry Andric       CurrentColoring[SU->NodeNum] = GroupID;
1135444ed5c5SDimitry Andric   }
1136444ed5c5SDimitry Andric }
1137444ed5c5SDimitry Andric 
colorExports()11382cab237bSDimitry Andric void SIScheduleBlockCreator::colorExports() {
11392cab237bSDimitry Andric   unsigned ExportColor = NextNonReservedID++;
11402cab237bSDimitry Andric   SmallVector<unsigned, 8> ExpGroup;
11412cab237bSDimitry Andric 
11422cab237bSDimitry Andric   // Put all exports together in a block.
11432cab237bSDimitry Andric   // The block will naturally end up being scheduled last,
11442cab237bSDimitry Andric   // thus putting exports at the end of the schedule, which
11452cab237bSDimitry Andric   // is better for performance.
11462cab237bSDimitry Andric   // However we must ensure, for safety, the exports can be put
11472cab237bSDimitry Andric   // together in the same block without any other instruction.
11482cab237bSDimitry Andric   // This could happen, for example, when scheduling after regalloc
11492cab237bSDimitry Andric   // if reloading a spilled register from memory using the same
11502cab237bSDimitry Andric   // register than used in a previous export.
11512cab237bSDimitry Andric   // If that happens, do not regroup the exports.
11522cab237bSDimitry Andric   for (unsigned SUNum : DAG->TopDownIndex2SU) {
11532cab237bSDimitry Andric     const SUnit &SU = DAG->SUnits[SUNum];
11542cab237bSDimitry Andric     if (SIInstrInfo::isEXP(*SU.getInstr())) {
11552cab237bSDimitry Andric       // Check the EXP can be added to the group safely,
11562cab237bSDimitry Andric       // ie without needing any other instruction.
11572cab237bSDimitry Andric       // The EXP is allowed to depend on other EXP
11582cab237bSDimitry Andric       // (they will be in the same group).
11592cab237bSDimitry Andric       for (unsigned j : ExpGroup) {
11602cab237bSDimitry Andric         bool HasSubGraph;
11612cab237bSDimitry Andric         std::vector<int> SubGraph;
11622cab237bSDimitry Andric         // By construction (topological order), if SU and
11632cab237bSDimitry Andric         // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary
11642cab237bSDimitry Andric         // in the parent graph of SU.
11652cab237bSDimitry Andric #ifndef NDEBUG
11662cab237bSDimitry Andric         SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j],
11672cab237bSDimitry Andric                                                HasSubGraph);
11682cab237bSDimitry Andric         assert(!HasSubGraph);
11692cab237bSDimitry Andric #endif
11702cab237bSDimitry Andric         SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU,
11712cab237bSDimitry Andric                                                HasSubGraph);
11722cab237bSDimitry Andric         if (!HasSubGraph)
11732cab237bSDimitry Andric           continue; // No dependencies between each other
11742cab237bSDimitry Andric 
11752cab237bSDimitry Andric         // SubGraph contains all the instructions required
11762cab237bSDimitry Andric         // between EXP SUnits[j] and EXP SU.
11772cab237bSDimitry Andric         for (unsigned k : SubGraph) {
11782cab237bSDimitry Andric           if (!SIInstrInfo::isEXP(*DAG->SUnits[k].getInstr()))
11792cab237bSDimitry Andric             // Other instructions than EXP would be required in the group.
11802cab237bSDimitry Andric             // Abort the groupping.
11812cab237bSDimitry Andric             return;
11822cab237bSDimitry Andric         }
11832cab237bSDimitry Andric       }
11842cab237bSDimitry Andric 
11852cab237bSDimitry Andric       ExpGroup.push_back(SUNum);
11862cab237bSDimitry Andric     }
11872cab237bSDimitry Andric   }
11882cab237bSDimitry Andric 
11892cab237bSDimitry Andric   // The group can be formed. Give the color.
11902cab237bSDimitry Andric   for (unsigned j : ExpGroup)
11912cab237bSDimitry Andric     CurrentColoring[j] = ExportColor;
11922cab237bSDimitry Andric }
11932cab237bSDimitry Andric 
createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant)1194444ed5c5SDimitry Andric void SIScheduleBlockCreator::createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant) {
1195444ed5c5SDimitry Andric   unsigned DAGSize = DAG->SUnits.size();
1196444ed5c5SDimitry Andric   std::map<unsigned,unsigned> RealID;
1197444ed5c5SDimitry Andric 
1198444ed5c5SDimitry Andric   CurrentBlocks.clear();
1199444ed5c5SDimitry Andric   CurrentColoring.clear();
1200444ed5c5SDimitry Andric   CurrentColoring.resize(DAGSize, 0);
1201444ed5c5SDimitry Andric   Node2CurrentBlock.clear();
1202444ed5c5SDimitry Andric 
1203444ed5c5SDimitry Andric   // Restore links previous scheduling variant has overridden.
1204444ed5c5SDimitry Andric   DAG->restoreSULinksLeft();
1205444ed5c5SDimitry Andric 
1206444ed5c5SDimitry Andric   NextReservedID = 1;
1207444ed5c5SDimitry Andric   NextNonReservedID = DAGSize + 1;
1208444ed5c5SDimitry Andric 
12094ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Coloring the graph\n");
1210444ed5c5SDimitry Andric 
1211444ed5c5SDimitry Andric   if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesGrouped)
1212444ed5c5SDimitry Andric     colorHighLatenciesGroups();
1213444ed5c5SDimitry Andric   else
1214444ed5c5SDimitry Andric     colorHighLatenciesAlone();
1215444ed5c5SDimitry Andric   colorComputeReservedDependencies();
1216444ed5c5SDimitry Andric   colorAccordingToReservedDependencies();
1217444ed5c5SDimitry Andric   colorEndsAccordingToDependencies();
1218444ed5c5SDimitry Andric   if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesAlonePlusConsecutive)
1219444ed5c5SDimitry Andric     colorForceConsecutiveOrderInGroup();
1220444ed5c5SDimitry Andric   regroupNoUserInstructions();
1221444ed5c5SDimitry Andric   colorMergeConstantLoadsNextGroup();
1222444ed5c5SDimitry Andric   colorMergeIfPossibleNextGroupOnlyForReserved();
12232cab237bSDimitry Andric   colorExports();
1224444ed5c5SDimitry Andric 
1225444ed5c5SDimitry Andric   // Put SUs of same color into same block
1226444ed5c5SDimitry Andric   Node2CurrentBlock.resize(DAGSize, -1);
1227444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1228444ed5c5SDimitry Andric     SUnit *SU = &DAG->SUnits[i];
1229444ed5c5SDimitry Andric     unsigned Color = CurrentColoring[SU->NodeNum];
1230444ed5c5SDimitry Andric     if (RealID.find(Color) == RealID.end()) {
1231444ed5c5SDimitry Andric       int ID = CurrentBlocks.size();
1232d88c1a5aSDimitry Andric       BlockPtrs.push_back(llvm::make_unique<SIScheduleBlock>(DAG, this, ID));
1233444ed5c5SDimitry Andric       CurrentBlocks.push_back(BlockPtrs.rbegin()->get());
1234444ed5c5SDimitry Andric       RealID[Color] = ID;
1235444ed5c5SDimitry Andric     }
1236444ed5c5SDimitry Andric     CurrentBlocks[RealID[Color]]->addUnit(SU);
1237444ed5c5SDimitry Andric     Node2CurrentBlock[SU->NodeNum] = RealID[Color];
1238444ed5c5SDimitry Andric   }
1239444ed5c5SDimitry Andric 
1240444ed5c5SDimitry Andric   // Build dependencies between blocks.
1241444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1242444ed5c5SDimitry Andric     SUnit *SU = &DAG->SUnits[i];
1243444ed5c5SDimitry Andric     int SUID = Node2CurrentBlock[i];
1244444ed5c5SDimitry Andric      for (SDep& SuccDep : SU->Succs) {
1245444ed5c5SDimitry Andric        SUnit *Succ = SuccDep.getSUnit();
1246444ed5c5SDimitry Andric       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1247444ed5c5SDimitry Andric         continue;
1248444ed5c5SDimitry Andric       if (Node2CurrentBlock[Succ->NodeNum] != SUID)
12497a7e6055SDimitry Andric         CurrentBlocks[SUID]->addSucc(CurrentBlocks[Node2CurrentBlock[Succ->NodeNum]],
12507a7e6055SDimitry Andric                                      SuccDep.isCtrl() ? NoData : Data);
1251444ed5c5SDimitry Andric     }
1252444ed5c5SDimitry Andric     for (SDep& PredDep : SU->Preds) {
1253444ed5c5SDimitry Andric       SUnit *Pred = PredDep.getSUnit();
1254444ed5c5SDimitry Andric       if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
1255444ed5c5SDimitry Andric         continue;
1256444ed5c5SDimitry Andric       if (Node2CurrentBlock[Pred->NodeNum] != SUID)
1257444ed5c5SDimitry Andric         CurrentBlocks[SUID]->addPred(CurrentBlocks[Node2CurrentBlock[Pred->NodeNum]]);
1258444ed5c5SDimitry Andric     }
1259444ed5c5SDimitry Andric   }
1260444ed5c5SDimitry Andric 
1261444ed5c5SDimitry Andric   // Free root and leafs of all blocks to enable scheduling inside them.
1262444ed5c5SDimitry Andric   for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1263444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[i];
1264444ed5c5SDimitry Andric     Block->finalizeUnits();
1265444ed5c5SDimitry Andric   }
12664ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Blocks created:\n\n";
1267444ed5c5SDimitry Andric              for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1268444ed5c5SDimitry Andric                SIScheduleBlock *Block = CurrentBlocks[i];
1269444ed5c5SDimitry Andric                Block->printDebug(true);
12704ba319b5SDimitry Andric              });
1271444ed5c5SDimitry Andric }
1272444ed5c5SDimitry Andric 
1273444ed5c5SDimitry Andric // Two functions taken from Codegen/MachineScheduler.cpp
1274444ed5c5SDimitry Andric 
1275d88c1a5aSDimitry Andric /// Non-const version.
1276d88c1a5aSDimitry Andric static MachineBasicBlock::iterator
nextIfDebug(MachineBasicBlock::iterator I,MachineBasicBlock::const_iterator End)1277d88c1a5aSDimitry Andric nextIfDebug(MachineBasicBlock::iterator I,
1278444ed5c5SDimitry Andric             MachineBasicBlock::const_iterator End) {
1279444ed5c5SDimitry Andric   for (; I != End; ++I) {
12804ba319b5SDimitry Andric     if (!I->isDebugInstr())
1281444ed5c5SDimitry Andric       break;
1282444ed5c5SDimitry Andric   }
1283444ed5c5SDimitry Andric   return I;
1284444ed5c5SDimitry Andric }
1285444ed5c5SDimitry Andric 
topologicalSort()1286444ed5c5SDimitry Andric void SIScheduleBlockCreator::topologicalSort() {
1287444ed5c5SDimitry Andric   unsigned DAGSize = CurrentBlocks.size();
1288444ed5c5SDimitry Andric   std::vector<int> WorkList;
1289444ed5c5SDimitry Andric 
12904ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Topological Sort\n");
1291444ed5c5SDimitry Andric 
1292444ed5c5SDimitry Andric   WorkList.reserve(DAGSize);
1293444ed5c5SDimitry Andric   TopDownIndex2Block.resize(DAGSize);
1294444ed5c5SDimitry Andric   TopDownBlock2Index.resize(DAGSize);
1295444ed5c5SDimitry Andric   BottomUpIndex2Block.resize(DAGSize);
1296444ed5c5SDimitry Andric 
1297444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1298444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[i];
1299444ed5c5SDimitry Andric     unsigned Degree = Block->getSuccs().size();
1300444ed5c5SDimitry Andric     TopDownBlock2Index[i] = Degree;
1301444ed5c5SDimitry Andric     if (Degree == 0) {
1302444ed5c5SDimitry Andric       WorkList.push_back(i);
1303444ed5c5SDimitry Andric     }
1304444ed5c5SDimitry Andric   }
1305444ed5c5SDimitry Andric 
1306444ed5c5SDimitry Andric   int Id = DAGSize;
1307444ed5c5SDimitry Andric   while (!WorkList.empty()) {
1308444ed5c5SDimitry Andric     int i = WorkList.back();
1309444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[i];
1310444ed5c5SDimitry Andric     WorkList.pop_back();
1311444ed5c5SDimitry Andric     TopDownBlock2Index[i] = --Id;
1312444ed5c5SDimitry Andric     TopDownIndex2Block[Id] = i;
1313444ed5c5SDimitry Andric     for (SIScheduleBlock* Pred : Block->getPreds()) {
1314444ed5c5SDimitry Andric       if (!--TopDownBlock2Index[Pred->getID()])
1315444ed5c5SDimitry Andric         WorkList.push_back(Pred->getID());
1316444ed5c5SDimitry Andric     }
1317444ed5c5SDimitry Andric   }
1318444ed5c5SDimitry Andric 
1319444ed5c5SDimitry Andric #ifndef NDEBUG
1320444ed5c5SDimitry Andric   // Check correctness of the ordering.
1321444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1322444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[i];
1323444ed5c5SDimitry Andric     for (SIScheduleBlock* Pred : Block->getPreds()) {
1324444ed5c5SDimitry Andric       assert(TopDownBlock2Index[i] > TopDownBlock2Index[Pred->getID()] &&
1325444ed5c5SDimitry Andric       "Wrong Top Down topological sorting");
1326444ed5c5SDimitry Andric     }
1327444ed5c5SDimitry Andric   }
1328444ed5c5SDimitry Andric #endif
1329444ed5c5SDimitry Andric 
1330444ed5c5SDimitry Andric   BottomUpIndex2Block = std::vector<int>(TopDownIndex2Block.rbegin(),
1331444ed5c5SDimitry Andric                                          TopDownIndex2Block.rend());
1332444ed5c5SDimitry Andric }
1333444ed5c5SDimitry Andric 
scheduleInsideBlocks()1334444ed5c5SDimitry Andric void SIScheduleBlockCreator::scheduleInsideBlocks() {
1335444ed5c5SDimitry Andric   unsigned DAGSize = CurrentBlocks.size();
1336444ed5c5SDimitry Andric 
13374ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nScheduling Blocks\n\n");
1338444ed5c5SDimitry Andric 
1339444ed5c5SDimitry Andric   // We do schedule a valid scheduling such that a Block corresponds
1340444ed5c5SDimitry Andric   // to a range of instructions.
13414ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "First phase: Fast scheduling for Reg Liveness\n");
1342444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1343444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[i];
1344444ed5c5SDimitry Andric     Block->fastSchedule();
1345444ed5c5SDimitry Andric   }
1346444ed5c5SDimitry Andric 
1347444ed5c5SDimitry Andric   // Note: the following code, and the part restoring previous position
1348444ed5c5SDimitry Andric   // is by far the most expensive operation of the Scheduler.
1349444ed5c5SDimitry Andric 
1350444ed5c5SDimitry Andric   // Do not update CurrentTop.
1351444ed5c5SDimitry Andric   MachineBasicBlock::iterator CurrentTopFastSched = DAG->getCurrentTop();
1352444ed5c5SDimitry Andric   std::vector<MachineBasicBlock::iterator> PosOld;
1353444ed5c5SDimitry Andric   std::vector<MachineBasicBlock::iterator> PosNew;
1354444ed5c5SDimitry Andric   PosOld.reserve(DAG->SUnits.size());
1355444ed5c5SDimitry Andric   PosNew.reserve(DAG->SUnits.size());
1356444ed5c5SDimitry Andric 
1357444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1358444ed5c5SDimitry Andric     int BlockIndice = TopDownIndex2Block[i];
1359444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1360444ed5c5SDimitry Andric     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1361444ed5c5SDimitry Andric 
1362444ed5c5SDimitry Andric     for (SUnit* SU : SUs) {
1363444ed5c5SDimitry Andric       MachineInstr *MI = SU->getInstr();
1364444ed5c5SDimitry Andric       MachineBasicBlock::iterator Pos = MI;
1365444ed5c5SDimitry Andric       PosOld.push_back(Pos);
1366444ed5c5SDimitry Andric       if (&*CurrentTopFastSched == MI) {
1367444ed5c5SDimitry Andric         PosNew.push_back(Pos);
1368444ed5c5SDimitry Andric         CurrentTopFastSched = nextIfDebug(++CurrentTopFastSched,
1369444ed5c5SDimitry Andric                                           DAG->getCurrentBottom());
1370444ed5c5SDimitry Andric       } else {
1371444ed5c5SDimitry Andric         // Update the instruction stream.
1372444ed5c5SDimitry Andric         DAG->getBB()->splice(CurrentTopFastSched, DAG->getBB(), MI);
1373444ed5c5SDimitry Andric 
1374444ed5c5SDimitry Andric         // Update LiveIntervals.
1375444ed5c5SDimitry Andric         // Note: Moving all instructions and calling handleMove every time
1376444ed5c5SDimitry Andric         // is the most cpu intensive operation of the scheduler.
1377444ed5c5SDimitry Andric         // It would gain a lot if there was a way to recompute the
1378444ed5c5SDimitry Andric         // LiveIntervals for the entire scheduling region.
13793ca95b02SDimitry Andric         DAG->getLIS()->handleMove(*MI, /*UpdateFlags=*/true);
1380444ed5c5SDimitry Andric         PosNew.push_back(CurrentTopFastSched);
1381444ed5c5SDimitry Andric       }
1382444ed5c5SDimitry Andric     }
1383444ed5c5SDimitry Andric   }
1384444ed5c5SDimitry Andric 
1385444ed5c5SDimitry Andric   // Now we have Block of SUs == Block of MI.
1386444ed5c5SDimitry Andric   // We do the final schedule for the instructions inside the block.
1387444ed5c5SDimitry Andric   // The property that all the SUs of the Block are grouped together as MI
1388444ed5c5SDimitry Andric   // is used for correct reg usage tracking.
1389444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1390444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[i];
1391444ed5c5SDimitry Andric     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1392444ed5c5SDimitry Andric     Block->schedule((*SUs.begin())->getInstr(), (*SUs.rbegin())->getInstr());
1393444ed5c5SDimitry Andric   }
1394444ed5c5SDimitry Andric 
13954ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Restoring MI Pos\n");
1396444ed5c5SDimitry Andric   // Restore old ordering (which prevents a LIS->handleMove bug).
1397444ed5c5SDimitry Andric   for (unsigned i = PosOld.size(), e = 0; i != e; --i) {
1398444ed5c5SDimitry Andric     MachineBasicBlock::iterator POld = PosOld[i-1];
1399444ed5c5SDimitry Andric     MachineBasicBlock::iterator PNew = PosNew[i-1];
1400444ed5c5SDimitry Andric     if (PNew != POld) {
1401444ed5c5SDimitry Andric       // Update the instruction stream.
1402444ed5c5SDimitry Andric       DAG->getBB()->splice(POld, DAG->getBB(), PNew);
1403444ed5c5SDimitry Andric 
1404444ed5c5SDimitry Andric       // Update LiveIntervals.
14053ca95b02SDimitry Andric       DAG->getLIS()->handleMove(*POld, /*UpdateFlags=*/true);
1406444ed5c5SDimitry Andric     }
1407444ed5c5SDimitry Andric   }
1408444ed5c5SDimitry Andric 
14094ba319b5SDimitry Andric   LLVM_DEBUG(for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1410444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[i];
1411444ed5c5SDimitry Andric     Block->printDebug(true);
14124ba319b5SDimitry Andric   });
1413444ed5c5SDimitry Andric }
1414444ed5c5SDimitry Andric 
fillStats()1415444ed5c5SDimitry Andric void SIScheduleBlockCreator::fillStats() {
1416444ed5c5SDimitry Andric   unsigned DAGSize = CurrentBlocks.size();
1417444ed5c5SDimitry Andric 
1418444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1419444ed5c5SDimitry Andric     int BlockIndice = TopDownIndex2Block[i];
1420444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1421d88c1a5aSDimitry Andric     if (Block->getPreds().empty())
1422444ed5c5SDimitry Andric       Block->Depth = 0;
1423444ed5c5SDimitry Andric     else {
1424444ed5c5SDimitry Andric       unsigned Depth = 0;
1425444ed5c5SDimitry Andric       for (SIScheduleBlock *Pred : Block->getPreds()) {
14262cab237bSDimitry Andric         if (Depth < Pred->Depth + Pred->getCost())
14272cab237bSDimitry Andric           Depth = Pred->Depth + Pred->getCost();
1428444ed5c5SDimitry Andric       }
1429444ed5c5SDimitry Andric       Block->Depth = Depth;
1430444ed5c5SDimitry Andric     }
1431444ed5c5SDimitry Andric   }
1432444ed5c5SDimitry Andric 
1433444ed5c5SDimitry Andric   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1434444ed5c5SDimitry Andric     int BlockIndice = BottomUpIndex2Block[i];
1435444ed5c5SDimitry Andric     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1436d88c1a5aSDimitry Andric     if (Block->getSuccs().empty())
1437444ed5c5SDimitry Andric       Block->Height = 0;
1438444ed5c5SDimitry Andric     else {
1439444ed5c5SDimitry Andric       unsigned Height = 0;
14407a7e6055SDimitry Andric       for (const auto &Succ : Block->getSuccs())
14412cab237bSDimitry Andric         Height = std::max(Height, Succ.first->Height + Succ.first->getCost());
1442444ed5c5SDimitry Andric       Block->Height = Height;
1443444ed5c5SDimitry Andric     }
1444444ed5c5SDimitry Andric   }
1445444ed5c5SDimitry Andric }
1446444ed5c5SDimitry Andric 
1447444ed5c5SDimitry Andric // SIScheduleBlockScheduler //
1448444ed5c5SDimitry Andric 
SIScheduleBlockScheduler(SIScheduleDAGMI * DAG,SISchedulerBlockSchedulerVariant Variant,SIScheduleBlocks BlocksStruct)1449444ed5c5SDimitry Andric SIScheduleBlockScheduler::SIScheduleBlockScheduler(SIScheduleDAGMI *DAG,
1450444ed5c5SDimitry Andric                                                    SISchedulerBlockSchedulerVariant Variant,
1451444ed5c5SDimitry Andric                                                    SIScheduleBlocks  BlocksStruct) :
1452444ed5c5SDimitry Andric   DAG(DAG), Variant(Variant), Blocks(BlocksStruct.Blocks),
1453444ed5c5SDimitry Andric   LastPosWaitedHighLatency(0), NumBlockScheduled(0), VregCurrentUsage(0),
1454444ed5c5SDimitry Andric   SregCurrentUsage(0), maxVregUsage(0), maxSregUsage(0) {
1455444ed5c5SDimitry Andric 
1456444ed5c5SDimitry Andric   // Fill the usage of every output
1457444ed5c5SDimitry Andric   // Warning: while by construction we always have a link between two blocks
1458444ed5c5SDimitry Andric   // when one needs a result from the other, the number of users of an output
1459444ed5c5SDimitry Andric   // is not the sum of child blocks having as input the same virtual register.
1460444ed5c5SDimitry Andric   // Here is an example. A produces x and y. B eats x and produces x'.
1461444ed5c5SDimitry Andric   // C eats x' and y. The register coalescer may have attributed the same
1462444ed5c5SDimitry Andric   // virtual register to x and x'.
1463444ed5c5SDimitry Andric   // To count accurately, we do a topological sort. In case the register is
1464444ed5c5SDimitry Andric   // found for several parents, we increment the usage of the one with the
1465444ed5c5SDimitry Andric   // highest topological index.
1466444ed5c5SDimitry Andric   LiveOutRegsNumUsages.resize(Blocks.size());
1467444ed5c5SDimitry Andric   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1468444ed5c5SDimitry Andric     SIScheduleBlock *Block = Blocks[i];
1469444ed5c5SDimitry Andric     for (unsigned Reg : Block->getInRegs()) {
1470444ed5c5SDimitry Andric       bool Found = false;
1471444ed5c5SDimitry Andric       int topoInd = -1;
1472444ed5c5SDimitry Andric       for (SIScheduleBlock* Pred: Block->getPreds()) {
1473444ed5c5SDimitry Andric         std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1474444ed5c5SDimitry Andric         std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1475444ed5c5SDimitry Andric 
1476444ed5c5SDimitry Andric         if (RegPos != PredOutRegs.end()) {
1477444ed5c5SDimitry Andric           Found = true;
1478444ed5c5SDimitry Andric           if (topoInd < BlocksStruct.TopDownBlock2Index[Pred->getID()]) {
1479444ed5c5SDimitry Andric             topoInd = BlocksStruct.TopDownBlock2Index[Pred->getID()];
1480444ed5c5SDimitry Andric           }
1481444ed5c5SDimitry Andric         }
1482444ed5c5SDimitry Andric       }
1483444ed5c5SDimitry Andric 
1484444ed5c5SDimitry Andric       if (!Found)
1485444ed5c5SDimitry Andric         continue;
1486444ed5c5SDimitry Andric 
1487444ed5c5SDimitry Andric       int PredID = BlocksStruct.TopDownIndex2Block[topoInd];
1488444ed5c5SDimitry Andric       ++LiveOutRegsNumUsages[PredID][Reg];
1489444ed5c5SDimitry Andric     }
1490444ed5c5SDimitry Andric   }
1491444ed5c5SDimitry Andric 
1492444ed5c5SDimitry Andric   LastPosHighLatencyParentScheduled.resize(Blocks.size(), 0);
1493444ed5c5SDimitry Andric   BlockNumPredsLeft.resize(Blocks.size());
1494444ed5c5SDimitry Andric   BlockNumSuccsLeft.resize(Blocks.size());
1495444ed5c5SDimitry Andric 
1496444ed5c5SDimitry Andric   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1497444ed5c5SDimitry Andric     SIScheduleBlock *Block = Blocks[i];
1498444ed5c5SDimitry Andric     BlockNumPredsLeft[i] = Block->getPreds().size();
1499444ed5c5SDimitry Andric     BlockNumSuccsLeft[i] = Block->getSuccs().size();
1500444ed5c5SDimitry Andric   }
1501444ed5c5SDimitry Andric 
1502444ed5c5SDimitry Andric #ifndef NDEBUG
1503444ed5c5SDimitry Andric   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1504444ed5c5SDimitry Andric     SIScheduleBlock *Block = Blocks[i];
1505444ed5c5SDimitry Andric     assert(Block->getID() == i);
1506444ed5c5SDimitry Andric   }
1507444ed5c5SDimitry Andric #endif
1508444ed5c5SDimitry Andric 
1509444ed5c5SDimitry Andric   std::set<unsigned> InRegs = DAG->getInRegs();
1510444ed5c5SDimitry Andric   addLiveRegs(InRegs);
1511444ed5c5SDimitry Andric 
15127a7e6055SDimitry Andric   // Increase LiveOutRegsNumUsages for blocks
15137a7e6055SDimitry Andric   // producing registers consumed in another
15147a7e6055SDimitry Andric   // scheduling region.
15157a7e6055SDimitry Andric   for (unsigned Reg : DAG->getOutRegs()) {
15167a7e6055SDimitry Andric     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
15177a7e6055SDimitry Andric       // Do reverse traversal
15187a7e6055SDimitry Andric       int ID = BlocksStruct.TopDownIndex2Block[Blocks.size()-1-i];
15197a7e6055SDimitry Andric       SIScheduleBlock *Block = Blocks[ID];
15207a7e6055SDimitry Andric       const std::set<unsigned> &OutRegs = Block->getOutRegs();
15217a7e6055SDimitry Andric 
15227a7e6055SDimitry Andric       if (OutRegs.find(Reg) == OutRegs.end())
15237a7e6055SDimitry Andric         continue;
15247a7e6055SDimitry Andric 
15257a7e6055SDimitry Andric       ++LiveOutRegsNumUsages[ID][Reg];
15267a7e6055SDimitry Andric       break;
15277a7e6055SDimitry Andric     }
15287a7e6055SDimitry Andric   }
15297a7e6055SDimitry Andric 
1530444ed5c5SDimitry Andric   // Fill LiveRegsConsumers for regs that were already
1531444ed5c5SDimitry Andric   // defined before scheduling.
1532444ed5c5SDimitry Andric   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1533444ed5c5SDimitry Andric     SIScheduleBlock *Block = Blocks[i];
1534444ed5c5SDimitry Andric     for (unsigned Reg : Block->getInRegs()) {
1535444ed5c5SDimitry Andric       bool Found = false;
1536444ed5c5SDimitry Andric       for (SIScheduleBlock* Pred: Block->getPreds()) {
1537444ed5c5SDimitry Andric         std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1538444ed5c5SDimitry Andric         std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1539444ed5c5SDimitry Andric 
1540444ed5c5SDimitry Andric         if (RegPos != PredOutRegs.end()) {
1541444ed5c5SDimitry Andric           Found = true;
1542444ed5c5SDimitry Andric           break;
1543444ed5c5SDimitry Andric         }
1544444ed5c5SDimitry Andric       }
1545444ed5c5SDimitry Andric 
15467a7e6055SDimitry Andric       if (!Found)
1547444ed5c5SDimitry Andric         ++LiveRegsConsumers[Reg];
1548444ed5c5SDimitry Andric     }
1549444ed5c5SDimitry Andric   }
1550444ed5c5SDimitry Andric 
1551444ed5c5SDimitry Andric   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1552444ed5c5SDimitry Andric     SIScheduleBlock *Block = Blocks[i];
1553444ed5c5SDimitry Andric     if (BlockNumPredsLeft[i] == 0) {
1554444ed5c5SDimitry Andric       ReadyBlocks.push_back(Block);
1555444ed5c5SDimitry Andric     }
1556444ed5c5SDimitry Andric   }
1557444ed5c5SDimitry Andric 
1558444ed5c5SDimitry Andric   while (SIScheduleBlock *Block = pickBlock()) {
1559444ed5c5SDimitry Andric     BlocksScheduled.push_back(Block);
1560444ed5c5SDimitry Andric     blockScheduled(Block);
1561444ed5c5SDimitry Andric   }
1562444ed5c5SDimitry Andric 
15634ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Block Order:"; for (SIScheduleBlock *Block
15644ba319b5SDimitry Andric                                             : BlocksScheduled) {
1565444ed5c5SDimitry Andric     dbgs() << ' ' << Block->getID();
15664ba319b5SDimitry Andric   } dbgs() << '\n';);
1567444ed5c5SDimitry Andric }
1568444ed5c5SDimitry Andric 
tryCandidateLatency(SIBlockSchedCandidate & Cand,SIBlockSchedCandidate & TryCand)1569444ed5c5SDimitry Andric bool SIScheduleBlockScheduler::tryCandidateLatency(SIBlockSchedCandidate &Cand,
1570444ed5c5SDimitry Andric                                                    SIBlockSchedCandidate &TryCand) {
1571444ed5c5SDimitry Andric   if (!Cand.isValid()) {
1572444ed5c5SDimitry Andric     TryCand.Reason = NodeOrder;
1573444ed5c5SDimitry Andric     return true;
1574444ed5c5SDimitry Andric   }
1575444ed5c5SDimitry Andric 
1576444ed5c5SDimitry Andric   // Try to hide high latencies.
15774ba319b5SDimitry Andric   if (SISched::tryLess(TryCand.LastPosHighLatParentScheduled,
1578444ed5c5SDimitry Andric                  Cand.LastPosHighLatParentScheduled, TryCand, Cand, Latency))
1579444ed5c5SDimitry Andric     return true;
1580444ed5c5SDimitry Andric   // Schedule high latencies early so you can hide them better.
15814ba319b5SDimitry Andric   if (SISched::tryGreater(TryCand.IsHighLatency, Cand.IsHighLatency,
1582444ed5c5SDimitry Andric                           TryCand, Cand, Latency))
1583444ed5c5SDimitry Andric     return true;
15844ba319b5SDimitry Andric   if (TryCand.IsHighLatency && SISched::tryGreater(TryCand.Height, Cand.Height,
1585444ed5c5SDimitry Andric                                                    TryCand, Cand, Depth))
1586444ed5c5SDimitry Andric     return true;
15874ba319b5SDimitry Andric   if (SISched::tryGreater(TryCand.NumHighLatencySuccessors,
1588444ed5c5SDimitry Andric                           Cand.NumHighLatencySuccessors,
1589444ed5c5SDimitry Andric                           TryCand, Cand, Successor))
1590444ed5c5SDimitry Andric     return true;
1591444ed5c5SDimitry Andric   return false;
1592444ed5c5SDimitry Andric }
1593444ed5c5SDimitry Andric 
tryCandidateRegUsage(SIBlockSchedCandidate & Cand,SIBlockSchedCandidate & TryCand)1594444ed5c5SDimitry Andric bool SIScheduleBlockScheduler::tryCandidateRegUsage(SIBlockSchedCandidate &Cand,
1595444ed5c5SDimitry Andric                                                     SIBlockSchedCandidate &TryCand) {
1596444ed5c5SDimitry Andric   if (!Cand.isValid()) {
1597444ed5c5SDimitry Andric     TryCand.Reason = NodeOrder;
1598444ed5c5SDimitry Andric     return true;
1599444ed5c5SDimitry Andric   }
1600444ed5c5SDimitry Andric 
16014ba319b5SDimitry Andric   if (SISched::tryLess(TryCand.VGPRUsageDiff > 0, Cand.VGPRUsageDiff > 0,
1602444ed5c5SDimitry Andric                        TryCand, Cand, RegUsage))
1603444ed5c5SDimitry Andric     return true;
16044ba319b5SDimitry Andric   if (SISched::tryGreater(TryCand.NumSuccessors > 0,
1605444ed5c5SDimitry Andric                           Cand.NumSuccessors > 0,
1606444ed5c5SDimitry Andric                           TryCand, Cand, Successor))
1607444ed5c5SDimitry Andric     return true;
16084ba319b5SDimitry Andric   if (SISched::tryGreater(TryCand.Height, Cand.Height, TryCand, Cand, Depth))
1609444ed5c5SDimitry Andric     return true;
16104ba319b5SDimitry Andric   if (SISched::tryLess(TryCand.VGPRUsageDiff, Cand.VGPRUsageDiff,
1611444ed5c5SDimitry Andric                        TryCand, Cand, RegUsage))
1612444ed5c5SDimitry Andric     return true;
1613444ed5c5SDimitry Andric   return false;
1614444ed5c5SDimitry Andric }
1615444ed5c5SDimitry Andric 
pickBlock()1616444ed5c5SDimitry Andric SIScheduleBlock *SIScheduleBlockScheduler::pickBlock() {
1617444ed5c5SDimitry Andric   SIBlockSchedCandidate Cand;
1618444ed5c5SDimitry Andric   std::vector<SIScheduleBlock*>::iterator Best;
1619444ed5c5SDimitry Andric   SIScheduleBlock *Block;
1620444ed5c5SDimitry Andric   if (ReadyBlocks.empty())
1621444ed5c5SDimitry Andric     return nullptr;
1622444ed5c5SDimitry Andric 
1623444ed5c5SDimitry Andric   DAG->fillVgprSgprCost(LiveRegs.begin(), LiveRegs.end(),
1624444ed5c5SDimitry Andric                         VregCurrentUsage, SregCurrentUsage);
1625444ed5c5SDimitry Andric   if (VregCurrentUsage > maxVregUsage)
1626444ed5c5SDimitry Andric     maxVregUsage = VregCurrentUsage;
16277a7e6055SDimitry Andric   if (SregCurrentUsage > maxSregUsage)
16287a7e6055SDimitry Andric     maxSregUsage = SregCurrentUsage;
16294ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Picking New Blocks\n"; dbgs() << "Available: ";
16304ba319b5SDimitry Andric              for (SIScheduleBlock *Block
16314ba319b5SDimitry Andric                   : ReadyBlocks) dbgs()
16324ba319b5SDimitry Andric              << Block->getID() << ' ';
1633444ed5c5SDimitry Andric              dbgs() << "\nCurrent Live:\n";
16344ba319b5SDimitry Andric              for (unsigned Reg
16354ba319b5SDimitry Andric                   : LiveRegs) dbgs()
16364ba319b5SDimitry Andric              << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
1637444ed5c5SDimitry Andric              dbgs() << '\n';
1638444ed5c5SDimitry Andric              dbgs() << "Current VGPRs: " << VregCurrentUsage << '\n';
16394ba319b5SDimitry Andric              dbgs() << "Current SGPRs: " << SregCurrentUsage << '\n';);
1640444ed5c5SDimitry Andric 
1641444ed5c5SDimitry Andric   Cand.Block = nullptr;
1642444ed5c5SDimitry Andric   for (std::vector<SIScheduleBlock*>::iterator I = ReadyBlocks.begin(),
1643444ed5c5SDimitry Andric        E = ReadyBlocks.end(); I != E; ++I) {
1644444ed5c5SDimitry Andric     SIBlockSchedCandidate TryCand;
1645444ed5c5SDimitry Andric     TryCand.Block = *I;
1646444ed5c5SDimitry Andric     TryCand.IsHighLatency = TryCand.Block->isHighLatencyBlock();
1647444ed5c5SDimitry Andric     TryCand.VGPRUsageDiff =
1648444ed5c5SDimitry Andric       checkRegUsageImpact(TryCand.Block->getInRegs(),
1649444ed5c5SDimitry Andric                           TryCand.Block->getOutRegs())[DAG->getVGPRSetID()];
1650444ed5c5SDimitry Andric     TryCand.NumSuccessors = TryCand.Block->getSuccs().size();
1651444ed5c5SDimitry Andric     TryCand.NumHighLatencySuccessors =
1652444ed5c5SDimitry Andric       TryCand.Block->getNumHighLatencySuccessors();
1653444ed5c5SDimitry Andric     TryCand.LastPosHighLatParentScheduled =
1654444ed5c5SDimitry Andric       (unsigned int) std::max<int> (0,
1655444ed5c5SDimitry Andric          LastPosHighLatencyParentScheduled[TryCand.Block->getID()] -
1656444ed5c5SDimitry Andric            LastPosWaitedHighLatency);
1657444ed5c5SDimitry Andric     TryCand.Height = TryCand.Block->Height;
1658444ed5c5SDimitry Andric     // Try not to increase VGPR usage too much, else we may spill.
1659444ed5c5SDimitry Andric     if (VregCurrentUsage > 120 ||
1660444ed5c5SDimitry Andric         Variant != SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage) {
1661444ed5c5SDimitry Andric       if (!tryCandidateRegUsage(Cand, TryCand) &&
1662444ed5c5SDimitry Andric           Variant != SISchedulerBlockSchedulerVariant::BlockRegUsage)
1663444ed5c5SDimitry Andric         tryCandidateLatency(Cand, TryCand);
1664444ed5c5SDimitry Andric     } else {
1665444ed5c5SDimitry Andric       if (!tryCandidateLatency(Cand, TryCand))
1666444ed5c5SDimitry Andric         tryCandidateRegUsage(Cand, TryCand);
1667444ed5c5SDimitry Andric     }
1668444ed5c5SDimitry Andric     if (TryCand.Reason != NoCand) {
1669444ed5c5SDimitry Andric       Cand.setBest(TryCand);
1670444ed5c5SDimitry Andric       Best = I;
16714ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Best Current Choice: " << Cand.Block->getID() << ' '
1672444ed5c5SDimitry Andric                         << getReasonStr(Cand.Reason) << '\n');
1673444ed5c5SDimitry Andric     }
1674444ed5c5SDimitry Andric   }
1675444ed5c5SDimitry Andric 
16764ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Picking: " << Cand.Block->getID() << '\n';
1677444ed5c5SDimitry Andric              dbgs() << "Is a block with high latency instruction: "
1678444ed5c5SDimitry Andric                     << (Cand.IsHighLatency ? "yes\n" : "no\n");
1679444ed5c5SDimitry Andric              dbgs() << "Position of last high latency dependency: "
1680444ed5c5SDimitry Andric                     << Cand.LastPosHighLatParentScheduled << '\n';
1681444ed5c5SDimitry Andric              dbgs() << "VGPRUsageDiff: " << Cand.VGPRUsageDiff << '\n';
16824ba319b5SDimitry Andric              dbgs() << '\n';);
1683444ed5c5SDimitry Andric 
1684444ed5c5SDimitry Andric   Block = Cand.Block;
1685444ed5c5SDimitry Andric   ReadyBlocks.erase(Best);
1686444ed5c5SDimitry Andric   return Block;
1687444ed5c5SDimitry Andric }
1688444ed5c5SDimitry Andric 
1689444ed5c5SDimitry Andric // Tracking of currently alive registers to determine VGPR Usage.
1690444ed5c5SDimitry Andric 
addLiveRegs(std::set<unsigned> & Regs)1691444ed5c5SDimitry Andric void SIScheduleBlockScheduler::addLiveRegs(std::set<unsigned> &Regs) {
1692444ed5c5SDimitry Andric   for (unsigned Reg : Regs) {
1693444ed5c5SDimitry Andric     // For now only track virtual registers.
1694444ed5c5SDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1695444ed5c5SDimitry Andric       continue;
1696444ed5c5SDimitry Andric     // If not already in the live set, then add it.
1697444ed5c5SDimitry Andric     (void) LiveRegs.insert(Reg);
1698444ed5c5SDimitry Andric   }
1699444ed5c5SDimitry Andric }
1700444ed5c5SDimitry Andric 
decreaseLiveRegs(SIScheduleBlock * Block,std::set<unsigned> & Regs)1701444ed5c5SDimitry Andric void SIScheduleBlockScheduler::decreaseLiveRegs(SIScheduleBlock *Block,
1702444ed5c5SDimitry Andric                                        std::set<unsigned> &Regs) {
1703444ed5c5SDimitry Andric   for (unsigned Reg : Regs) {
1704444ed5c5SDimitry Andric     // For now only track virtual registers.
1705444ed5c5SDimitry Andric     std::set<unsigned>::iterator Pos = LiveRegs.find(Reg);
1706444ed5c5SDimitry Andric     assert (Pos != LiveRegs.end() && // Reg must be live.
1707444ed5c5SDimitry Andric                LiveRegsConsumers.find(Reg) != LiveRegsConsumers.end() &&
1708444ed5c5SDimitry Andric                LiveRegsConsumers[Reg] >= 1);
1709444ed5c5SDimitry Andric     --LiveRegsConsumers[Reg];
1710444ed5c5SDimitry Andric     if (LiveRegsConsumers[Reg] == 0)
1711444ed5c5SDimitry Andric       LiveRegs.erase(Pos);
1712444ed5c5SDimitry Andric   }
1713444ed5c5SDimitry Andric }
1714444ed5c5SDimitry Andric 
releaseBlockSuccs(SIScheduleBlock * Parent)1715444ed5c5SDimitry Andric void SIScheduleBlockScheduler::releaseBlockSuccs(SIScheduleBlock *Parent) {
17167a7e6055SDimitry Andric   for (const auto &Block : Parent->getSuccs()) {
17177a7e6055SDimitry Andric     if (--BlockNumPredsLeft[Block.first->getID()] == 0)
17187a7e6055SDimitry Andric       ReadyBlocks.push_back(Block.first);
17197a7e6055SDimitry Andric 
17207a7e6055SDimitry Andric     if (Parent->isHighLatencyBlock() &&
17217a7e6055SDimitry Andric         Block.second == SIScheduleBlockLinkKind::Data)
17227a7e6055SDimitry Andric       LastPosHighLatencyParentScheduled[Block.first->getID()] = NumBlockScheduled;
1723444ed5c5SDimitry Andric   }
1724444ed5c5SDimitry Andric }
1725444ed5c5SDimitry Andric 
blockScheduled(SIScheduleBlock * Block)1726444ed5c5SDimitry Andric void SIScheduleBlockScheduler::blockScheduled(SIScheduleBlock *Block) {
1727444ed5c5SDimitry Andric   decreaseLiveRegs(Block, Block->getInRegs());
1728444ed5c5SDimitry Andric   addLiveRegs(Block->getOutRegs());
1729444ed5c5SDimitry Andric   releaseBlockSuccs(Block);
1730444ed5c5SDimitry Andric   for (std::map<unsigned, unsigned>::iterator RegI =
1731444ed5c5SDimitry Andric        LiveOutRegsNumUsages[Block->getID()].begin(),
1732444ed5c5SDimitry Andric        E = LiveOutRegsNumUsages[Block->getID()].end(); RegI != E; ++RegI) {
1733444ed5c5SDimitry Andric     std::pair<unsigned, unsigned> RegP = *RegI;
17347a7e6055SDimitry Andric     // We produce this register, thus it must not be previously alive.
17357a7e6055SDimitry Andric     assert(LiveRegsConsumers.find(RegP.first) == LiveRegsConsumers.end() ||
17367a7e6055SDimitry Andric            LiveRegsConsumers[RegP.first] == 0);
1737444ed5c5SDimitry Andric     LiveRegsConsumers[RegP.first] += RegP.second;
1738444ed5c5SDimitry Andric   }
1739444ed5c5SDimitry Andric   if (LastPosHighLatencyParentScheduled[Block->getID()] >
1740444ed5c5SDimitry Andric         (unsigned)LastPosWaitedHighLatency)
1741444ed5c5SDimitry Andric     LastPosWaitedHighLatency =
1742444ed5c5SDimitry Andric       LastPosHighLatencyParentScheduled[Block->getID()];
1743444ed5c5SDimitry Andric   ++NumBlockScheduled;
1744444ed5c5SDimitry Andric }
1745444ed5c5SDimitry Andric 
1746444ed5c5SDimitry Andric std::vector<int>
checkRegUsageImpact(std::set<unsigned> & InRegs,std::set<unsigned> & OutRegs)1747444ed5c5SDimitry Andric SIScheduleBlockScheduler::checkRegUsageImpact(std::set<unsigned> &InRegs,
1748444ed5c5SDimitry Andric                                      std::set<unsigned> &OutRegs) {
1749444ed5c5SDimitry Andric   std::vector<int> DiffSetPressure;
1750444ed5c5SDimitry Andric   DiffSetPressure.assign(DAG->getTRI()->getNumRegPressureSets(), 0);
1751444ed5c5SDimitry Andric 
1752444ed5c5SDimitry Andric   for (unsigned Reg : InRegs) {
1753444ed5c5SDimitry Andric     // For now only track virtual registers.
1754444ed5c5SDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1755444ed5c5SDimitry Andric       continue;
1756444ed5c5SDimitry Andric     if (LiveRegsConsumers[Reg] > 1)
1757444ed5c5SDimitry Andric       continue;
1758444ed5c5SDimitry Andric     PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1759444ed5c5SDimitry Andric     for (; PSetI.isValid(); ++PSetI) {
1760444ed5c5SDimitry Andric       DiffSetPressure[*PSetI] -= PSetI.getWeight();
1761444ed5c5SDimitry Andric     }
1762444ed5c5SDimitry Andric   }
1763444ed5c5SDimitry Andric 
1764444ed5c5SDimitry Andric   for (unsigned Reg : OutRegs) {
1765444ed5c5SDimitry Andric     // For now only track virtual registers.
1766444ed5c5SDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1767444ed5c5SDimitry Andric       continue;
1768444ed5c5SDimitry Andric     PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1769444ed5c5SDimitry Andric     for (; PSetI.isValid(); ++PSetI) {
1770444ed5c5SDimitry Andric       DiffSetPressure[*PSetI] += PSetI.getWeight();
1771444ed5c5SDimitry Andric     }
1772444ed5c5SDimitry Andric   }
1773444ed5c5SDimitry Andric 
1774444ed5c5SDimitry Andric   return DiffSetPressure;
1775444ed5c5SDimitry Andric }
1776444ed5c5SDimitry Andric 
1777444ed5c5SDimitry Andric // SIScheduler //
1778444ed5c5SDimitry Andric 
1779444ed5c5SDimitry Andric struct SIScheduleBlockResult
scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant,SISchedulerBlockSchedulerVariant ScheduleVariant)1780444ed5c5SDimitry Andric SIScheduler::scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant,
1781444ed5c5SDimitry Andric                              SISchedulerBlockSchedulerVariant ScheduleVariant) {
1782444ed5c5SDimitry Andric   SIScheduleBlocks Blocks = BlockCreator.getBlocks(BlockVariant);
1783444ed5c5SDimitry Andric   SIScheduleBlockScheduler Scheduler(DAG, ScheduleVariant, Blocks);
1784444ed5c5SDimitry Andric   std::vector<SIScheduleBlock*> ScheduledBlocks;
1785444ed5c5SDimitry Andric   struct SIScheduleBlockResult Res;
1786444ed5c5SDimitry Andric 
1787444ed5c5SDimitry Andric   ScheduledBlocks = Scheduler.getBlocks();
1788444ed5c5SDimitry Andric 
1789444ed5c5SDimitry Andric   for (unsigned b = 0; b < ScheduledBlocks.size(); ++b) {
1790444ed5c5SDimitry Andric     SIScheduleBlock *Block = ScheduledBlocks[b];
1791444ed5c5SDimitry Andric     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1792444ed5c5SDimitry Andric 
1793444ed5c5SDimitry Andric     for (SUnit* SU : SUs)
1794444ed5c5SDimitry Andric       Res.SUs.push_back(SU->NodeNum);
1795444ed5c5SDimitry Andric   }
1796444ed5c5SDimitry Andric 
1797444ed5c5SDimitry Andric   Res.MaxSGPRUsage = Scheduler.getSGPRUsage();
1798444ed5c5SDimitry Andric   Res.MaxVGPRUsage = Scheduler.getVGPRUsage();
1799444ed5c5SDimitry Andric   return Res;
1800444ed5c5SDimitry Andric }
1801444ed5c5SDimitry Andric 
1802444ed5c5SDimitry Andric // SIScheduleDAGMI //
1803444ed5c5SDimitry Andric 
SIScheduleDAGMI(MachineSchedContext * C)1804444ed5c5SDimitry Andric SIScheduleDAGMI::SIScheduleDAGMI(MachineSchedContext *C) :
1805d88c1a5aSDimitry Andric   ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C)) {
1806444ed5c5SDimitry Andric   SITII = static_cast<const SIInstrInfo*>(TII);
1807444ed5c5SDimitry Andric   SITRI = static_cast<const SIRegisterInfo*>(TRI);
1808444ed5c5SDimitry Andric 
1809d88c1a5aSDimitry Andric   VGPRSetID = SITRI->getVGPRPressureSet();
1810d88c1a5aSDimitry Andric   SGPRSetID = SITRI->getSGPRPressureSet();
1811444ed5c5SDimitry Andric }
1812444ed5c5SDimitry Andric 
1813d88c1a5aSDimitry Andric SIScheduleDAGMI::~SIScheduleDAGMI() = default;
1814444ed5c5SDimitry Andric 
1815444ed5c5SDimitry Andric // Code adapted from scheduleDAG.cpp
1816444ed5c5SDimitry Andric // Does a topological sort over the SUs.
1817444ed5c5SDimitry Andric // Both TopDown and BottomUp
topologicalSort()1818444ed5c5SDimitry Andric void SIScheduleDAGMI::topologicalSort() {
18193ca95b02SDimitry Andric   Topo.InitDAGTopologicalSorting();
1820444ed5c5SDimitry Andric 
18213ca95b02SDimitry Andric   TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());
18223ca95b02SDimitry Andric   BottomUpIndex2SU = std::vector<int>(Topo.rbegin(), Topo.rend());
1823444ed5c5SDimitry Andric }
1824444ed5c5SDimitry Andric 
1825444ed5c5SDimitry Andric // Move low latencies further from their user without
1826444ed5c5SDimitry Andric // increasing SGPR usage (in general)
1827444ed5c5SDimitry Andric // This is to be replaced by a better pass that would
1828444ed5c5SDimitry Andric // take into account SGPR usage (based on VGPR Usage
1829444ed5c5SDimitry Andric // and the corresponding wavefront count), that would
1830444ed5c5SDimitry Andric // try to merge groups of loads if it make sense, etc
moveLowLatencies()1831444ed5c5SDimitry Andric void SIScheduleDAGMI::moveLowLatencies() {
1832444ed5c5SDimitry Andric    unsigned DAGSize = SUnits.size();
1833444ed5c5SDimitry Andric    int LastLowLatencyUser = -1;
1834444ed5c5SDimitry Andric    int LastLowLatencyPos = -1;
1835444ed5c5SDimitry Andric 
1836444ed5c5SDimitry Andric    for (unsigned i = 0, e = ScheduledSUnits.size(); i != e; ++i) {
1837444ed5c5SDimitry Andric     SUnit *SU = &SUnits[ScheduledSUnits[i]];
1838444ed5c5SDimitry Andric     bool IsLowLatencyUser = false;
1839444ed5c5SDimitry Andric     unsigned MinPos = 0;
1840444ed5c5SDimitry Andric 
1841444ed5c5SDimitry Andric     for (SDep& PredDep : SU->Preds) {
1842444ed5c5SDimitry Andric       SUnit *Pred = PredDep.getSUnit();
18433ca95b02SDimitry Andric       if (SITII->isLowLatencyInstruction(*Pred->getInstr())) {
1844444ed5c5SDimitry Andric         IsLowLatencyUser = true;
1845444ed5c5SDimitry Andric       }
1846444ed5c5SDimitry Andric       if (Pred->NodeNum >= DAGSize)
1847444ed5c5SDimitry Andric         continue;
1848444ed5c5SDimitry Andric       unsigned PredPos = ScheduledSUnitsInv[Pred->NodeNum];
1849444ed5c5SDimitry Andric       if (PredPos >= MinPos)
1850444ed5c5SDimitry Andric         MinPos = PredPos + 1;
1851444ed5c5SDimitry Andric     }
1852444ed5c5SDimitry Andric 
18533ca95b02SDimitry Andric     if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
1854444ed5c5SDimitry Andric       unsigned BestPos = LastLowLatencyUser + 1;
1855444ed5c5SDimitry Andric       if ((int)BestPos <= LastLowLatencyPos)
1856444ed5c5SDimitry Andric         BestPos = LastLowLatencyPos + 1;
1857444ed5c5SDimitry Andric       if (BestPos < MinPos)
1858444ed5c5SDimitry Andric         BestPos = MinPos;
1859444ed5c5SDimitry Andric       if (BestPos < i) {
1860444ed5c5SDimitry Andric         for (unsigned u = i; u > BestPos; --u) {
1861444ed5c5SDimitry Andric           ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1862444ed5c5SDimitry Andric           ScheduledSUnits[u] = ScheduledSUnits[u-1];
1863444ed5c5SDimitry Andric         }
1864444ed5c5SDimitry Andric         ScheduledSUnits[BestPos] = SU->NodeNum;
1865444ed5c5SDimitry Andric         ScheduledSUnitsInv[SU->NodeNum] = BestPos;
1866444ed5c5SDimitry Andric       }
1867444ed5c5SDimitry Andric       LastLowLatencyPos = BestPos;
1868444ed5c5SDimitry Andric       if (IsLowLatencyUser)
1869444ed5c5SDimitry Andric         LastLowLatencyUser = BestPos;
1870444ed5c5SDimitry Andric     } else if (IsLowLatencyUser) {
1871444ed5c5SDimitry Andric       LastLowLatencyUser = i;
1872444ed5c5SDimitry Andric     // Moves COPY instructions on which depends
1873444ed5c5SDimitry Andric     // the low latency instructions too.
1874444ed5c5SDimitry Andric     } else if (SU->getInstr()->getOpcode() == AMDGPU::COPY) {
1875444ed5c5SDimitry Andric       bool CopyForLowLat = false;
1876444ed5c5SDimitry Andric       for (SDep& SuccDep : SU->Succs) {
1877444ed5c5SDimitry Andric         SUnit *Succ = SuccDep.getSUnit();
18783ca95b02SDimitry Andric         if (SITII->isLowLatencyInstruction(*Succ->getInstr())) {
1879444ed5c5SDimitry Andric           CopyForLowLat = true;
1880444ed5c5SDimitry Andric         }
1881444ed5c5SDimitry Andric       }
1882444ed5c5SDimitry Andric       if (!CopyForLowLat)
1883444ed5c5SDimitry Andric         continue;
1884444ed5c5SDimitry Andric       if (MinPos < i) {
1885444ed5c5SDimitry Andric         for (unsigned u = i; u > MinPos; --u) {
1886444ed5c5SDimitry Andric           ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1887444ed5c5SDimitry Andric           ScheduledSUnits[u] = ScheduledSUnits[u-1];
1888444ed5c5SDimitry Andric         }
1889444ed5c5SDimitry Andric         ScheduledSUnits[MinPos] = SU->NodeNum;
1890444ed5c5SDimitry Andric         ScheduledSUnitsInv[SU->NodeNum] = MinPos;
1891444ed5c5SDimitry Andric       }
1892444ed5c5SDimitry Andric     }
1893444ed5c5SDimitry Andric   }
1894444ed5c5SDimitry Andric }
1895444ed5c5SDimitry Andric 
restoreSULinksLeft()1896444ed5c5SDimitry Andric void SIScheduleDAGMI::restoreSULinksLeft() {
1897444ed5c5SDimitry Andric   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1898444ed5c5SDimitry Andric     SUnits[i].isScheduled = false;
1899444ed5c5SDimitry Andric     SUnits[i].WeakPredsLeft = SUnitsLinksBackup[i].WeakPredsLeft;
1900444ed5c5SDimitry Andric     SUnits[i].NumPredsLeft = SUnitsLinksBackup[i].NumPredsLeft;
1901444ed5c5SDimitry Andric     SUnits[i].WeakSuccsLeft = SUnitsLinksBackup[i].WeakSuccsLeft;
1902444ed5c5SDimitry Andric     SUnits[i].NumSuccsLeft = SUnitsLinksBackup[i].NumSuccsLeft;
1903444ed5c5SDimitry Andric   }
1904444ed5c5SDimitry Andric }
1905444ed5c5SDimitry Andric 
1906444ed5c5SDimitry Andric // Return the Vgpr and Sgpr usage corresponding to some virtual registers.
1907444ed5c5SDimitry Andric template<typename _Iterator> void
fillVgprSgprCost(_Iterator First,_Iterator End,unsigned & VgprUsage,unsigned & SgprUsage)1908444ed5c5SDimitry Andric SIScheduleDAGMI::fillVgprSgprCost(_Iterator First, _Iterator End,
1909444ed5c5SDimitry Andric                                   unsigned &VgprUsage, unsigned &SgprUsage) {
1910444ed5c5SDimitry Andric   VgprUsage = 0;
1911444ed5c5SDimitry Andric   SgprUsage = 0;
1912444ed5c5SDimitry Andric   for (_Iterator RegI = First; RegI != End; ++RegI) {
1913444ed5c5SDimitry Andric     unsigned Reg = *RegI;
1914444ed5c5SDimitry Andric     // For now only track virtual registers
1915444ed5c5SDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1916444ed5c5SDimitry Andric       continue;
1917444ed5c5SDimitry Andric     PSetIterator PSetI = MRI.getPressureSets(Reg);
1918444ed5c5SDimitry Andric     for (; PSetI.isValid(); ++PSetI) {
1919444ed5c5SDimitry Andric       if (*PSetI == VGPRSetID)
1920444ed5c5SDimitry Andric         VgprUsage += PSetI.getWeight();
1921444ed5c5SDimitry Andric       else if (*PSetI == SGPRSetID)
1922444ed5c5SDimitry Andric         SgprUsage += PSetI.getWeight();
1923444ed5c5SDimitry Andric     }
1924444ed5c5SDimitry Andric   }
1925444ed5c5SDimitry Andric }
1926444ed5c5SDimitry Andric 
schedule()1927444ed5c5SDimitry Andric void SIScheduleDAGMI::schedule()
1928444ed5c5SDimitry Andric {
1929444ed5c5SDimitry Andric   SmallVector<SUnit*, 8> TopRoots, BotRoots;
1930444ed5c5SDimitry Andric   SIScheduleBlockResult Best, Temp;
19314ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Preparing Scheduling\n");
1932444ed5c5SDimitry Andric 
1933444ed5c5SDimitry Andric   buildDAGWithRegPressure();
1934*b5893f02SDimitry Andric   LLVM_DEBUG(dump());
1935444ed5c5SDimitry Andric 
1936444ed5c5SDimitry Andric   topologicalSort();
1937444ed5c5SDimitry Andric   findRootsAndBiasEdges(TopRoots, BotRoots);
1938444ed5c5SDimitry Andric   // We reuse several ScheduleDAGMI and ScheduleDAGMILive
1939444ed5c5SDimitry Andric   // functions, but to make them happy we must initialize
1940444ed5c5SDimitry Andric   // the default Scheduler implementation (even if we do not
1941444ed5c5SDimitry Andric   // run it)
1942444ed5c5SDimitry Andric   SchedImpl->initialize(this);
1943444ed5c5SDimitry Andric   initQueues(TopRoots, BotRoots);
1944444ed5c5SDimitry Andric 
1945444ed5c5SDimitry Andric   // Fill some stats to help scheduling.
1946444ed5c5SDimitry Andric 
1947444ed5c5SDimitry Andric   SUnitsLinksBackup = SUnits;
1948444ed5c5SDimitry Andric   IsLowLatencySU.clear();
1949444ed5c5SDimitry Andric   LowLatencyOffset.clear();
1950444ed5c5SDimitry Andric   IsHighLatencySU.clear();
1951444ed5c5SDimitry Andric 
1952444ed5c5SDimitry Andric   IsLowLatencySU.resize(SUnits.size(), 0);
1953444ed5c5SDimitry Andric   LowLatencyOffset.resize(SUnits.size(), 0);
1954444ed5c5SDimitry Andric   IsHighLatencySU.resize(SUnits.size(), 0);
1955444ed5c5SDimitry Andric 
1956444ed5c5SDimitry Andric   for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
1957444ed5c5SDimitry Andric     SUnit *SU = &SUnits[i];
1958*b5893f02SDimitry Andric     MachineOperand *BaseLatOp;
19593ca95b02SDimitry Andric     int64_t OffLatReg;
19603ca95b02SDimitry Andric     if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
1961444ed5c5SDimitry Andric       IsLowLatencySU[i] = 1;
1962*b5893f02SDimitry Andric       if (SITII->getMemOperandWithOffset(*SU->getInstr(), BaseLatOp, OffLatReg,
19633ca95b02SDimitry Andric                                          TRI))
1964444ed5c5SDimitry Andric         LowLatencyOffset[i] = OffLatReg;
19653ca95b02SDimitry Andric     } else if (SITII->isHighLatencyInstruction(*SU->getInstr()))
1966444ed5c5SDimitry Andric       IsHighLatencySU[i] = 1;
1967444ed5c5SDimitry Andric   }
1968444ed5c5SDimitry Andric 
1969444ed5c5SDimitry Andric   SIScheduler Scheduler(this);
1970444ed5c5SDimitry Andric   Best = Scheduler.scheduleVariant(SISchedulerBlockCreatorVariant::LatenciesAlone,
1971444ed5c5SDimitry Andric                                    SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage);
19723ca95b02SDimitry Andric 
1973444ed5c5SDimitry Andric   // if VGPR usage is extremely high, try other good performing variants
1974444ed5c5SDimitry Andric   // which could lead to lower VGPR usage
1975444ed5c5SDimitry Andric   if (Best.MaxVGPRUsage > 180) {
19767a7e6055SDimitry Andric     static const std::pair<SISchedulerBlockCreatorVariant,
19777a7e6055SDimitry Andric                            SISchedulerBlockSchedulerVariant>
19787a7e6055SDimitry Andric         Variants[] = {
1979444ed5c5SDimitry Andric       { LatenciesAlone, BlockRegUsageLatency },
1980444ed5c5SDimitry Andric //      { LatenciesAlone, BlockRegUsage },
1981444ed5c5SDimitry Andric       { LatenciesGrouped, BlockLatencyRegUsage },
1982444ed5c5SDimitry Andric //      { LatenciesGrouped, BlockRegUsageLatency },
1983444ed5c5SDimitry Andric //      { LatenciesGrouped, BlockRegUsage },
1984444ed5c5SDimitry Andric       { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1985444ed5c5SDimitry Andric //      { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1986444ed5c5SDimitry Andric //      { LatenciesAlonePlusConsecutive, BlockRegUsage }
1987444ed5c5SDimitry Andric     };
1988444ed5c5SDimitry Andric     for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1989444ed5c5SDimitry Andric       Temp = Scheduler.scheduleVariant(v.first, v.second);
1990444ed5c5SDimitry Andric       if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
1991444ed5c5SDimitry Andric         Best = Temp;
1992444ed5c5SDimitry Andric     }
1993444ed5c5SDimitry Andric   }
1994444ed5c5SDimitry Andric   // if VGPR usage is still extremely high, we may spill. Try other variants
1995444ed5c5SDimitry Andric   // which are less performing, but that could lead to lower VGPR usage.
1996444ed5c5SDimitry Andric   if (Best.MaxVGPRUsage > 200) {
19977a7e6055SDimitry Andric     static const std::pair<SISchedulerBlockCreatorVariant,
19987a7e6055SDimitry Andric                            SISchedulerBlockSchedulerVariant>
19997a7e6055SDimitry Andric         Variants[] = {
2000444ed5c5SDimitry Andric //      { LatenciesAlone, BlockRegUsageLatency },
2001444ed5c5SDimitry Andric       { LatenciesAlone, BlockRegUsage },
2002444ed5c5SDimitry Andric //      { LatenciesGrouped, BlockLatencyRegUsage },
2003444ed5c5SDimitry Andric       { LatenciesGrouped, BlockRegUsageLatency },
2004444ed5c5SDimitry Andric       { LatenciesGrouped, BlockRegUsage },
2005444ed5c5SDimitry Andric //      { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
2006444ed5c5SDimitry Andric       { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
2007444ed5c5SDimitry Andric       { LatenciesAlonePlusConsecutive, BlockRegUsage }
2008444ed5c5SDimitry Andric     };
2009444ed5c5SDimitry Andric     for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
2010444ed5c5SDimitry Andric       Temp = Scheduler.scheduleVariant(v.first, v.second);
2011444ed5c5SDimitry Andric       if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
2012444ed5c5SDimitry Andric         Best = Temp;
2013444ed5c5SDimitry Andric     }
2014444ed5c5SDimitry Andric   }
20153ca95b02SDimitry Andric 
2016444ed5c5SDimitry Andric   ScheduledSUnits = Best.SUs;
2017444ed5c5SDimitry Andric   ScheduledSUnitsInv.resize(SUnits.size());
2018444ed5c5SDimitry Andric 
2019444ed5c5SDimitry Andric   for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
2020444ed5c5SDimitry Andric     ScheduledSUnitsInv[ScheduledSUnits[i]] = i;
2021444ed5c5SDimitry Andric   }
2022444ed5c5SDimitry Andric 
2023444ed5c5SDimitry Andric   moveLowLatencies();
2024444ed5c5SDimitry Andric 
2025444ed5c5SDimitry Andric   // Tell the outside world about the result of the scheduling.
2026444ed5c5SDimitry Andric 
2027444ed5c5SDimitry Andric   assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
2028444ed5c5SDimitry Andric   TopRPTracker.setPos(CurrentTop);
2029444ed5c5SDimitry Andric 
2030444ed5c5SDimitry Andric   for (std::vector<unsigned>::iterator I = ScheduledSUnits.begin(),
2031444ed5c5SDimitry Andric        E = ScheduledSUnits.end(); I != E; ++I) {
2032444ed5c5SDimitry Andric     SUnit *SU = &SUnits[*I];
2033444ed5c5SDimitry Andric 
2034444ed5c5SDimitry Andric     scheduleMI(SU, true);
2035444ed5c5SDimitry Andric 
20364ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
2037444ed5c5SDimitry Andric                       << *SU->getInstr());
2038444ed5c5SDimitry Andric   }
2039444ed5c5SDimitry Andric 
2040444ed5c5SDimitry Andric   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
2041444ed5c5SDimitry Andric 
2042444ed5c5SDimitry Andric   placeDebugValues();
2043444ed5c5SDimitry Andric 
20444ba319b5SDimitry Andric   LLVM_DEBUG({
20452cab237bSDimitry Andric     dbgs() << "*** Final schedule for "
20462cab237bSDimitry Andric            << printMBBReference(*begin()->getParent()) << " ***\n";
2047444ed5c5SDimitry Andric     dumpSchedule();
2048444ed5c5SDimitry Andric     dbgs() << '\n';
2049444ed5c5SDimitry Andric   });
2050444ed5c5SDimitry Andric }
2051