Remove the TargetMachine forwards for TargetSubtargetInfo based
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGVLIW.cpp
1 //===- ScheduleDAGVLIW.cpp - SelectionDAG list scheduler for VLIW -*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // order), checked for legality to schedule, and emitted if legal.
14 //
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/CodeGen/SchedulerRegistry.h"
22 #include "ScheduleDAGSDNodes.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/LatencyPriorityQueue.h"
25 #include "llvm/CodeGen/ResourcePriorityQueue.h"
26 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include <climits>
36 using namespace llvm;
37
38 #define DEBUG_TYPE "pre-RA-sched"
39
40 STATISTIC(NumNoops , "Number of noops inserted");
41 STATISTIC(NumStalls, "Number of pipeline stalls");
42
43 static RegisterScheduler
44   VLIWScheduler("vliw-td", "VLIW scheduler",
45                 createVLIWDAGScheduler);
46
47 namespace {
48 //===----------------------------------------------------------------------===//
49 /// ScheduleDAGVLIW - The actual DFA list scheduler implementation.  This
50 /// supports / top-down scheduling.
51 ///
52 class ScheduleDAGVLIW : public ScheduleDAGSDNodes {
53 private:
54   /// AvailableQueue - The priority queue to use for the available SUnits.
55   ///
56   SchedulingPriorityQueue *AvailableQueue;
57
58   /// PendingQueue - This contains all of the instructions whose operands have
59   /// been issued, but their results are not ready yet (due to the latency of
60   /// the operation).  Once the operands become available, the instruction is
61   /// added to the AvailableQueue.
62   std::vector<SUnit*> PendingQueue;
63
64   /// HazardRec - The hazard recognizer to use.
65   ScheduleHazardRecognizer *HazardRec;
66
67   /// AA - AliasAnalysis for making memory reference queries.
68   AliasAnalysis *AA;
69
70 public:
71   ScheduleDAGVLIW(MachineFunction &mf,
72                   AliasAnalysis *aa,
73                   SchedulingPriorityQueue *availqueue)
74     : ScheduleDAGSDNodes(mf), AvailableQueue(availqueue), AA(aa) {
75
76     const TargetMachine &tm = mf.getTarget();
77     HazardRec =
78         tm.getSubtargetImpl()->getInstrInfo()->CreateTargetHazardRecognizer(
79             tm.getSubtargetImpl(), this);
80   }
81
82   ~ScheduleDAGVLIW() {
83     delete HazardRec;
84     delete AvailableQueue;
85   }
86
87   void Schedule() override;
88
89 private:
90   void releaseSucc(SUnit *SU, const SDep &D);
91   void releaseSuccessors(SUnit *SU);
92   void scheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
93   void listScheduleTopDown();
94 };
95 }  // end anonymous namespace
96
97 /// Schedule - Schedule the DAG using list scheduling.
98 void ScheduleDAGVLIW::Schedule() {
99   DEBUG(dbgs()
100         << "********** List Scheduling BB#" << BB->getNumber()
101         << " '" << BB->getName() << "' **********\n");
102
103   // Build the scheduling graph.
104   BuildSchedGraph(AA);
105
106   AvailableQueue->initNodes(SUnits);
107
108   listScheduleTopDown();
109
110   AvailableQueue->releaseState();
111 }
112
113 //===----------------------------------------------------------------------===//
114 //  Top-Down Scheduling
115 //===----------------------------------------------------------------------===//
116
117 /// releaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
118 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
119 void ScheduleDAGVLIW::releaseSucc(SUnit *SU, const SDep &D) {
120   SUnit *SuccSU = D.getSUnit();
121
122 #ifndef NDEBUG
123   if (SuccSU->NumPredsLeft == 0) {
124     dbgs() << "*** Scheduling failed! ***\n";
125     SuccSU->dump(this);
126     dbgs() << " has been released too many times!\n";
127     llvm_unreachable(nullptr);
128   }
129 #endif
130   assert(!D.isWeak() && "unexpected artificial DAG edge");
131
132   --SuccSU->NumPredsLeft;
133
134   SuccSU->setDepthToAtLeast(SU->getDepth() + D.getLatency());
135
136   // If all the node's predecessors are scheduled, this node is ready
137   // to be scheduled. Ignore the special ExitSU node.
138   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
139     PendingQueue.push_back(SuccSU);
140   }
141 }
142
143 void ScheduleDAGVLIW::releaseSuccessors(SUnit *SU) {
144   // Top down: release successors.
145   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
146        I != E; ++I) {
147     assert(!I->isAssignedRegDep() &&
148            "The list-td scheduler doesn't yet support physreg dependencies!");
149
150     releaseSucc(SU, *I);
151   }
152 }
153
154 /// scheduleNodeTopDown - Add the node to the schedule. Decrement the pending
155 /// count of its successors. If a successor pending count is zero, add it to
156 /// the Available queue.
157 void ScheduleDAGVLIW::scheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
158   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
159   DEBUG(SU->dump(this));
160
161   Sequence.push_back(SU);
162   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
163   SU->setDepthToAtLeast(CurCycle);
164
165   releaseSuccessors(SU);
166   SU->isScheduled = true;
167   AvailableQueue->scheduledNode(SU);
168 }
169
170 /// listScheduleTopDown - The main loop of list scheduling for top-down
171 /// schedulers.
172 void ScheduleDAGVLIW::listScheduleTopDown() {
173   unsigned CurCycle = 0;
174
175   // Release any successors of the special Entry node.
176   releaseSuccessors(&EntrySU);
177
178   // All leaves to AvailableQueue.
179   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
180     // It is available if it has no predecessors.
181     if (SUnits[i].Preds.empty()) {
182       AvailableQueue->push(&SUnits[i]);
183       SUnits[i].isAvailable = true;
184     }
185   }
186
187   // While AvailableQueue is not empty, grab the node with the highest
188   // priority. If it is not ready put it back.  Schedule the node.
189   std::vector<SUnit*> NotReady;
190   Sequence.reserve(SUnits.size());
191   while (!AvailableQueue->empty() || !PendingQueue.empty()) {
192     // Check to see if any of the pending instructions are ready to issue.  If
193     // so, add them to the available queue.
194     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
195       if (PendingQueue[i]->getDepth() == CurCycle) {
196         AvailableQueue->push(PendingQueue[i]);
197         PendingQueue[i]->isAvailable = true;
198         PendingQueue[i] = PendingQueue.back();
199         PendingQueue.pop_back();
200         --i; --e;
201       }
202       else {
203         assert(PendingQueue[i]->getDepth() > CurCycle && "Negative latency?");
204       }
205     }
206
207     // If there are no instructions available, don't try to issue anything, and
208     // don't advance the hazard recognizer.
209     if (AvailableQueue->empty()) {
210       // Reset DFA state.
211       AvailableQueue->scheduledNode(nullptr);
212       ++CurCycle;
213       continue;
214     }
215
216     SUnit *FoundSUnit = nullptr;
217
218     bool HasNoopHazards = false;
219     while (!AvailableQueue->empty()) {
220       SUnit *CurSUnit = AvailableQueue->pop();
221
222       ScheduleHazardRecognizer::HazardType HT =
223         HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
224       if (HT == ScheduleHazardRecognizer::NoHazard) {
225         FoundSUnit = CurSUnit;
226         break;
227       }
228
229       // Remember if this is a noop hazard.
230       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
231
232       NotReady.push_back(CurSUnit);
233     }
234
235     // Add the nodes that aren't ready back onto the available list.
236     if (!NotReady.empty()) {
237       AvailableQueue->push_all(NotReady);
238       NotReady.clear();
239     }
240
241     // If we found a node to schedule, do it now.
242     if (FoundSUnit) {
243       scheduleNodeTopDown(FoundSUnit, CurCycle);
244       HazardRec->EmitInstruction(FoundSUnit);
245
246       // If this is a pseudo-op node, we don't want to increment the current
247       // cycle.
248       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
249         ++CurCycle;
250     } else if (!HasNoopHazards) {
251       // Otherwise, we have a pipeline stall, but no other problem, just advance
252       // the current cycle and try again.
253       DEBUG(dbgs() << "*** Advancing cycle, no work to do\n");
254       HazardRec->AdvanceCycle();
255       ++NumStalls;
256       ++CurCycle;
257     } else {
258       // Otherwise, we have no instructions to issue and we have instructions
259       // that will fault if we don't do this right.  This is the case for
260       // processors without pipeline interlocks and other cases.
261       DEBUG(dbgs() << "*** Emitting noop\n");
262       HazardRec->EmitNoop();
263       Sequence.push_back(nullptr);   // NULL here means noop
264       ++NumNoops;
265       ++CurCycle;
266     }
267   }
268
269 #ifndef NDEBUG
270   VerifyScheduledSequence(/*isBottomUp=*/false);
271 #endif
272 }
273
274 //===----------------------------------------------------------------------===//
275 //                         Public Constructor Functions
276 //===----------------------------------------------------------------------===//
277
278 /// createVLIWDAGScheduler - This creates a top-down list scheduler.
279 ScheduleDAGSDNodes *
280 llvm::createVLIWDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
281   return new ScheduleDAGVLIW(*IS->MF, IS->AA, new ResourcePriorityQueue(IS));
282 }