blob: 4f0a74bfee68279c2fab3e15410c18687f349b28 [file] [log] [blame]
Evan Chenga9c20912006-01-21 02:32:06 +00001//===-- ScheduleDAGSimple.cpp - Implement a trivial DAG scheduler ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by James M. Laskey and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements a simple two pass scheduler. The first pass attempts to push
11// backward any lengthy instructions and critical paths. The second pass packs
12// instructions into semi-optimal time slots.
13//
14//===----------------------------------------------------------------------===//
15
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000016#define DEBUG_TYPE "pre-RA-sched"
Jim Laskeyf4923912006-08-03 20:51:06 +000017#include "llvm/CodeGen/MachineFunction.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000019#include "llvm/CodeGen/SchedulerRegistry.h"
Evan Chenga9c20912006-01-21 02:32:06 +000020#include "llvm/CodeGen/SelectionDAG.h"
Jim Laskeyf4923912006-08-03 20:51:06 +000021#include "llvm/CodeGen/SSARegMap.h"
Owen Anderson07000c62006-05-12 06:33:49 +000022#include "llvm/Target/TargetData.h"
Evan Chenga9c20912006-01-21 02:32:06 +000023#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
Evan Chenga9c20912006-01-21 02:32:06 +000025#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000026#include "llvm/Support/Compiler.h"
Jeff Cohen2aa750a2006-01-24 04:43:17 +000027#include <algorithm>
Evan Chenga9c20912006-01-21 02:32:06 +000028using namespace llvm;
29
30namespace {
Jim Laskey13ec7022006-08-01 14:21:23 +000031
32static RegisterScheduler
33 bfsDAGScheduler("none", " No scheduling: breadth first sequencing",
34 createBFS_DAGScheduler);
35static RegisterScheduler
36 simpleDAGScheduler("simple",
37 " Simple two pass scheduling: minimize critical path "
38 "and maximize processor utilization",
39 createSimpleDAGScheduler);
40static RegisterScheduler
41 noitinDAGScheduler("simple-noitin",
42 " Simple two pass scheduling: Same as simple "
43 "except using generic latency",
44 createNoItinsDAGScheduler);
45
Chris Lattnera34b6f82006-03-10 07:51:18 +000046class NodeInfo;
47typedef NodeInfo *NodeInfoPtr;
48typedef std::vector<NodeInfoPtr> NIVector;
49typedef std::vector<NodeInfoPtr>::iterator NIIterator;
50
51//===--------------------------------------------------------------------===//
52///
53/// Node group - This struct is used to manage flagged node groups.
54///
55class NodeGroup {
56public:
57 NodeGroup *Next;
58private:
59 NIVector Members; // Group member nodes
60 NodeInfo *Dominator; // Node with highest latency
61 unsigned Latency; // Total latency of the group
62 int Pending; // Number of visits pending before
63 // adding to order
64
65public:
66 // Ctor.
67 NodeGroup() : Next(NULL), Dominator(NULL), Pending(0) {}
68
69 // Accessors
70 inline void setDominator(NodeInfo *D) { Dominator = D; }
71 inline NodeInfo *getTop() { return Members.front(); }
72 inline NodeInfo *getBottom() { return Members.back(); }
73 inline NodeInfo *getDominator() { return Dominator; }
74 inline void setLatency(unsigned L) { Latency = L; }
75 inline unsigned getLatency() { return Latency; }
76 inline int getPending() const { return Pending; }
77 inline void setPending(int P) { Pending = P; }
78 inline int addPending(int I) { return Pending += I; }
79
80 // Pass thru
81 inline bool group_empty() { return Members.empty(); }
82 inline NIIterator group_begin() { return Members.begin(); }
83 inline NIIterator group_end() { return Members.end(); }
84 inline void group_push_back(const NodeInfoPtr &NI) {
85 Members.push_back(NI);
86 }
87 inline NIIterator group_insert(NIIterator Pos, const NodeInfoPtr &NI) {
88 return Members.insert(Pos, NI);
89 }
90 inline void group_insert(NIIterator Pos, NIIterator First,
91 NIIterator Last) {
92 Members.insert(Pos, First, Last);
93 }
94
95 static void Add(NodeInfo *D, NodeInfo *U);
96};
97
98//===--------------------------------------------------------------------===//
99///
100/// NodeInfo - This struct tracks information used to schedule the a node.
101///
102class NodeInfo {
103private:
104 int Pending; // Number of visits pending before
105 // adding to order
106public:
107 SDNode *Node; // DAG node
108 InstrStage *StageBegin; // First stage in itinerary
109 InstrStage *StageEnd; // Last+1 stage in itinerary
110 unsigned Latency; // Total cycles to complete instr
111 bool IsCall : 1; // Is function call
112 bool IsLoad : 1; // Is memory load
113 bool IsStore : 1; // Is memory store
114 unsigned Slot; // Node's time slot
115 NodeGroup *Group; // Grouping information
116#ifndef NDEBUG
117 unsigned Preorder; // Index before scheduling
118#endif
119
120 // Ctor.
121 NodeInfo(SDNode *N = NULL)
122 : Pending(0)
123 , Node(N)
124 , StageBegin(NULL)
125 , StageEnd(NULL)
126 , Latency(0)
127 , IsCall(false)
Chris Lattnerb690a002007-09-22 07:02:12 +0000128 , IsLoad(false)
129 , IsStore(false)
Chris Lattnera34b6f82006-03-10 07:51:18 +0000130 , Slot(0)
131 , Group(NULL)
132#ifndef NDEBUG
133 , Preorder(0)
134#endif
135 {}
136
137 // Accessors
138 inline bool isInGroup() const {
139 assert(!Group || !Group->group_empty() && "Group with no members");
140 return Group != NULL;
141 }
142 inline bool isGroupDominator() const {
143 return isInGroup() && Group->getDominator() == this;
144 }
145 inline int getPending() const {
146 return Group ? Group->getPending() : Pending;
147 }
148 inline void setPending(int P) {
149 if (Group) Group->setPending(P);
150 else Pending = P;
151 }
152 inline int addPending(int I) {
153 if (Group) return Group->addPending(I);
154 else return Pending += I;
155 }
156};
157
158//===--------------------------------------------------------------------===//
159///
160/// NodeGroupIterator - Iterates over all the nodes indicated by the node
161/// info. If the node is in a group then iterate over the members of the
162/// group, otherwise just the node info.
163///
164class NodeGroupIterator {
165private:
166 NodeInfo *NI; // Node info
167 NIIterator NGI; // Node group iterator
168 NIIterator NGE; // Node group iterator end
David Greenefd273b62007-08-17 15:13:55 +0000169 bool iter_valid;
Chris Lattnera34b6f82006-03-10 07:51:18 +0000170
171public:
172 // Ctor.
David Greenefd273b62007-08-17 15:13:55 +0000173 NodeGroupIterator(NodeInfo *N) : NI(N), iter_valid(false) {
Chris Lattnera34b6f82006-03-10 07:51:18 +0000174 // If the node is in a group then set up the group iterator. Otherwise
175 // the group iterators will trip first time out.
David Greenefd273b62007-08-17 15:13:55 +0000176 assert(N && "Bad node info");
Chris Lattnera34b6f82006-03-10 07:51:18 +0000177 if (N->isInGroup()) {
178 // get Group
179 NodeGroup *Group = NI->Group;
180 NGI = Group->group_begin();
181 NGE = Group->group_end();
182 // Prevent this node from being used (will be in members list
183 NI = NULL;
David Greenefd273b62007-08-17 15:13:55 +0000184 iter_valid = true;
Chris Lattnera34b6f82006-03-10 07:51:18 +0000185 }
186 }
187
188 /// next - Return the next node info, otherwise NULL.
189 ///
190 NodeInfo *next() {
David Greenefd273b62007-08-17 15:13:55 +0000191 if (iter_valid) {
192 // If members list
193 if (NGI != NGE) return *NGI++;
194 }
Chris Lattnera34b6f82006-03-10 07:51:18 +0000195 // Use node as the result (may be NULL)
196 NodeInfo *Result = NI;
197 // Only use once
198 NI = NULL;
199 // Return node or NULL
200 return Result;
201 }
202};
203//===--------------------------------------------------------------------===//
204
205
206//===--------------------------------------------------------------------===//
207///
208/// NodeGroupOpIterator - Iterates over all the operands of a node. If the
209/// node is a member of a group, this iterates over all the operands of all
210/// the members of the group.
211///
212class NodeGroupOpIterator {
213private:
214 NodeInfo *NI; // Node containing operands
215 NodeGroupIterator GI; // Node group iterator
216 SDNode::op_iterator OI; // Operand iterator
217 SDNode::op_iterator OE; // Operand iterator end
218
219 /// CheckNode - Test if node has more operands. If not get the next node
220 /// skipping over nodes that have no operands.
221 void CheckNode() {
222 // Only if operands are exhausted first
223 while (OI == OE) {
224 // Get next node info
225 NodeInfo *NI = GI.next();
226 // Exit if nodes are exhausted
227 if (!NI) return;
228 // Get node itself
229 SDNode *Node = NI->Node;
230 // Set up the operand iterators
231 OI = Node->op_begin();
232 OE = Node->op_end();
233 }
234 }
235
236public:
237 // Ctor.
238 NodeGroupOpIterator(NodeInfo *N)
239 : NI(N), GI(N), OI(SDNode::op_iterator()), OE(SDNode::op_iterator()) {}
240
241 /// isEnd - Returns true when not more operands are available.
242 ///
243 inline bool isEnd() { CheckNode(); return OI == OE; }
244
245 /// next - Returns the next available operand.
246 ///
247 inline SDOperand next() {
248 assert(OI != OE &&
249 "Not checking for end of NodeGroupOpIterator correctly");
250 return *OI++;
251 }
252};
253
254
Evan Chenga9c20912006-01-21 02:32:06 +0000255//===----------------------------------------------------------------------===//
256///
257/// BitsIterator - Provides iteration through individual bits in a bit vector.
258///
259template<class T>
260class BitsIterator {
261private:
262 T Bits; // Bits left to iterate through
263
264public:
265 /// Ctor.
266 BitsIterator(T Initial) : Bits(Initial) {}
267
268 /// Next - Returns the next bit set or zero if exhausted.
269 inline T Next() {
270 // Get the rightmost bit set
271 T Result = Bits & -Bits;
272 // Remove from rest
273 Bits &= ~Result;
274 // Return single bit or zero
275 return Result;
276 }
277};
278
279//===----------------------------------------------------------------------===//
280
281
282//===----------------------------------------------------------------------===//
283///
284/// ResourceTally - Manages the use of resources over time intervals. Each
285/// item (slot) in the tally vector represents the resources used at a given
286/// moment. A bit set to 1 indicates that a resource is in use, otherwise
Chris Lattnerfea997a2007-02-01 04:55:59 +0000287/// available. An assumption is made that the tally is large enough to schedule
Evan Chenga9c20912006-01-21 02:32:06 +0000288/// all current instructions (asserts otherwise.)
289///
290template<class T>
291class ResourceTally {
292private:
293 std::vector<T> Tally; // Resources used per slot
294 typedef typename std::vector<T>::iterator Iter;
295 // Tally iterator
296
297 /// SlotsAvailable - Returns true if all units are available.
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000298 ///
Evan Chenga9c20912006-01-21 02:32:06 +0000299 bool SlotsAvailable(Iter Begin, unsigned N, unsigned ResourceSet,
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000300 unsigned &Resource) {
Evan Chenga9c20912006-01-21 02:32:06 +0000301 assert(N && "Must check availability with N != 0");
302 // Determine end of interval
303 Iter End = Begin + N;
304 assert(End <= Tally.end() && "Tally is not large enough for schedule");
305
306 // Iterate thru each resource
307 BitsIterator<T> Resources(ResourceSet & ~*Begin);
308 while (unsigned Res = Resources.Next()) {
309 // Check if resource is available for next N slots
310 Iter Interval = End;
311 do {
312 Interval--;
313 if (*Interval & Res) break;
314 } while (Interval != Begin);
315
316 // If available for N
317 if (Interval == Begin) {
318 // Success
319 Resource = Res;
320 return true;
321 }
322 }
323
324 // No luck
325 Resource = 0;
326 return false;
327 }
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000328
329 /// RetrySlot - Finds a good candidate slot to retry search.
Evan Chenga9c20912006-01-21 02:32:06 +0000330 Iter RetrySlot(Iter Begin, unsigned N, unsigned ResourceSet) {
331 assert(N && "Must check availability with N != 0");
332 // Determine end of interval
333 Iter End = Begin + N;
334 assert(End <= Tally.end() && "Tally is not large enough for schedule");
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000335
336 while (Begin != End--) {
337 // Clear units in use
338 ResourceSet &= ~*End;
339 // If no units left then we should go no further
340 if (!ResourceSet) return End + 1;
341 }
342 // Made it all the way through
343 return Begin;
344 }
Evan Chenga9c20912006-01-21 02:32:06 +0000345
346 /// FindAndReserveStages - Return true if the stages can be completed. If
347 /// so mark as busy.
348 bool FindAndReserveStages(Iter Begin,
349 InstrStage *Stage, InstrStage *StageEnd) {
350 // If at last stage then we're done
351 if (Stage == StageEnd) return true;
352 // Get number of cycles for current stage
353 unsigned N = Stage->Cycles;
354 // Check to see if N slots are available, if not fail
355 unsigned Resource;
356 if (!SlotsAvailable(Begin, N, Stage->Units, Resource)) return false;
357 // Check to see if remaining stages are available, if not fail
358 if (!FindAndReserveStages(Begin + N, Stage + 1, StageEnd)) return false;
359 // Reserve resource
360 Reserve(Begin, N, Resource);
361 // Success
362 return true;
363 }
364
365 /// Reserve - Mark busy (set) the specified N slots.
366 void Reserve(Iter Begin, unsigned N, unsigned Resource) {
367 // Determine end of interval
368 Iter End = Begin + N;
369 assert(End <= Tally.end() && "Tally is not large enough for schedule");
370
371 // Set resource bit in each slot
372 for (; Begin < End; Begin++)
373 *Begin |= Resource;
374 }
375
376 /// FindSlots - Starting from Begin, locate consecutive slots where all stages
377 /// can be completed. Returns the address of first slot.
378 Iter FindSlots(Iter Begin, InstrStage *StageBegin, InstrStage *StageEnd) {
379 // Track position
380 Iter Cursor = Begin;
381
382 // Try all possible slots forward
383 while (true) {
384 // Try at cursor, if successful return position.
385 if (FindAndReserveStages(Cursor, StageBegin, StageEnd)) return Cursor;
386 // Locate a better position
Chris Lattnerfea997a2007-02-01 04:55:59 +0000387 Cursor = RetrySlot(Cursor + 1, StageBegin->Cycles, StageBegin->Units);
Evan Chenga9c20912006-01-21 02:32:06 +0000388 }
389 }
390
391public:
392 /// Initialize - Resize and zero the tally to the specified number of time
393 /// slots.
394 inline void Initialize(unsigned N) {
395 Tally.assign(N, 0); // Initialize tally to all zeros.
396 }
397
398 // FindAndReserve - Locate an ideal slot for the specified stages and mark
399 // as busy.
400 unsigned FindAndReserve(unsigned Slot, InstrStage *StageBegin,
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000401 InstrStage *StageEnd) {
402 // Where to begin
403 Iter Begin = Tally.begin() + Slot;
404 // Find a free slot
405 Iter Where = FindSlots(Begin, StageBegin, StageEnd);
406 // Distance is slot number
407 unsigned Final = Where - Tally.begin();
Evan Chenga9c20912006-01-21 02:32:06 +0000408 return Final;
409 }
410
411};
412
413//===----------------------------------------------------------------------===//
414///
415/// ScheduleDAGSimple - Simple two pass scheduler.
416///
Chris Lattnerf8c68f62006-06-28 22:17:39 +0000417class VISIBILITY_HIDDEN ScheduleDAGSimple : public ScheduleDAG {
Evan Chenga9c20912006-01-21 02:32:06 +0000418private:
Chris Lattner20a49212006-03-10 07:49:12 +0000419 bool NoSched; // Just do a BFS schedule, nothing fancy
420 bool NoItins; // Don't use itineraries?
Evan Chenga9c20912006-01-21 02:32:06 +0000421 ResourceTally<unsigned> Tally; // Resource usage tally
422 unsigned NSlots; // Total latency
423 static const unsigned NotFound = ~0U; // Search marker
Chris Lattner2f5806c2006-03-10 07:42:02 +0000424
425 unsigned NodeCount; // Number of nodes in DAG
426 std::map<SDNode *, NodeInfo *> Map; // Map nodes to info
427 bool HasGroups; // True if there are any groups
428 NodeInfo *Info; // Info for nodes being scheduled
429 NIVector Ordering; // Emit ordering of nodes
430 NodeGroup *HeadNG, *TailNG; // Keep track of allocated NodeGroups
Evan Chenga9c20912006-01-21 02:32:06 +0000431
432public:
433
434 // Ctor.
Chris Lattner20a49212006-03-10 07:49:12 +0000435 ScheduleDAGSimple(bool noSched, bool noItins, SelectionDAG &dag,
Evan Cheng4ef10862006-01-23 07:01:07 +0000436 MachineBasicBlock *bb, const TargetMachine &tm)
Chris Lattner20a49212006-03-10 07:49:12 +0000437 : ScheduleDAG(dag, bb, tm), NoSched(noSched), NoItins(noItins), NSlots(0),
Chris Lattner2f5806c2006-03-10 07:42:02 +0000438 NodeCount(0), HasGroups(false), Info(NULL), HeadNG(NULL), TailNG(NULL) {
Evan Chenga9c20912006-01-21 02:32:06 +0000439 assert(&TII && "Target doesn't provide instr info?");
440 assert(&MRI && "Target doesn't provide register info?");
441 }
442
Chris Lattner2f5806c2006-03-10 07:42:02 +0000443 virtual ~ScheduleDAGSimple() {
444 if (Info)
445 delete[] Info;
446
447 NodeGroup *NG = HeadNG;
448 while (NG) {
449 NodeGroup *NextSU = NG->Next;
450 delete NG;
451 NG = NextSU;
452 }
453 }
Evan Chenga9c20912006-01-21 02:32:06 +0000454
Evan Cheng41484292006-01-23 08:25:34 +0000455 void Schedule();
456
Chris Lattner2f5806c2006-03-10 07:42:02 +0000457 /// getNI - Returns the node info for the specified node.
458 ///
459 NodeInfo *getNI(SDNode *Node) { return Map[Node]; }
460
Evan Chenga9c20912006-01-21 02:32:06 +0000461private:
Evan Chenga9c20912006-01-21 02:32:06 +0000462 static bool isDefiner(NodeInfo *A, NodeInfo *B);
Evan Chenga9c20912006-01-21 02:32:06 +0000463 void IncludeNode(NodeInfo *NI);
464 void VisitAll();
Evan Chenga9c20912006-01-21 02:32:06 +0000465 void GatherSchedulingInfo();
466 void FakeGroupDominators();
Evan Chenga9c20912006-01-21 02:32:06 +0000467 bool isStrongDependency(NodeInfo *A, NodeInfo *B);
468 bool isWeakDependency(NodeInfo *A, NodeInfo *B);
469 void ScheduleBackward();
470 void ScheduleForward();
Chris Lattnere76074a2006-03-10 07:35:21 +0000471
472 void AddToGroup(NodeInfo *D, NodeInfo *U);
473 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
474 ///
475 void PrepareNodeInfo();
476
477 /// IdentifyGroups - Put flagged nodes into groups.
478 ///
479 void IdentifyGroups();
480
481 /// print - Print ordering to specified output stream.
482 ///
Bill Wendling5c7e3262006-12-17 05:15:13 +0000483 void print(std::ostream &O) const;
484 void print(std::ostream *O) const { if (O) print(*O); }
Chris Lattnere76074a2006-03-10 07:35:21 +0000485
486 void dump(const char *tag) const;
487
488 virtual void dump() const;
489
490 /// EmitAll - Emit all nodes in schedule sorted order.
491 ///
492 void EmitAll();
493
494 /// printNI - Print node info.
495 ///
Bill Wendling5c7e3262006-12-17 05:15:13 +0000496 void printNI(std::ostream &O, NodeInfo *NI) const;
Bill Wendlingf2174da2006-12-17 11:15:53 +0000497 void printNI(std::ostream *O, NodeInfo *NI) const { if (O) printNI(*O, NI); }
Chris Lattnere76074a2006-03-10 07:35:21 +0000498
499 /// printChanges - Hilight changes in order caused by scheduling.
500 ///
501 void printChanges(unsigned Index) const;
Evan Chenga9c20912006-01-21 02:32:06 +0000502};
503
Evan Chenga9c20912006-01-21 02:32:06 +0000504//===----------------------------------------------------------------------===//
505/// Special case itineraries.
506///
507enum {
508 CallLatency = 40, // To push calls back in time
509
510 RSInteger = 0xC0000000, // Two integer units
511 RSFloat = 0x30000000, // Two float units
512 RSLoadStore = 0x0C000000, // Two load store units
513 RSBranch = 0x02000000 // One branch unit
514};
Evan Chenga9c20912006-01-21 02:32:06 +0000515static InstrStage LoadStage = { 5, RSLoadStore };
516static InstrStage StoreStage = { 2, RSLoadStore };
517static InstrStage IntStage = { 2, RSInteger };
518static InstrStage FloatStage = { 3, RSFloat };
519//===----------------------------------------------------------------------===//
520
Evan Chenga9c20912006-01-21 02:32:06 +0000521} // namespace
522
523//===----------------------------------------------------------------------===//
524
Chris Lattnere76074a2006-03-10 07:35:21 +0000525/// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
526///
527void ScheduleDAGSimple::PrepareNodeInfo() {
528 // Allocate node information
529 Info = new NodeInfo[NodeCount];
530
531 unsigned i = 0;
532 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
533 E = DAG.allnodes_end(); I != E; ++I, ++i) {
534 // Fast reference to node schedule info
535 NodeInfo* NI = &Info[i];
536 // Set up map
537 Map[I] = NI;
538 // Set node
539 NI->Node = I;
540 // Set pending visit count
541 NI->setPending(I->use_size());
542 }
543}
544
545/// IdentifyGroups - Put flagged nodes into groups.
546///
547void ScheduleDAGSimple::IdentifyGroups() {
548 for (unsigned i = 0, N = NodeCount; i < N; i++) {
549 NodeInfo* NI = &Info[i];
550 SDNode *Node = NI->Node;
551
552 // For each operand (in reverse to only look at flags)
553 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
554 // Get operand
555 SDOperand Op = Node->getOperand(N);
556 // No more flags to walk
557 if (Op.getValueType() != MVT::Flag) break;
558 // Add to node group
559 AddToGroup(getNI(Op.Val), NI);
560 // Let everyone else know
561 HasGroups = true;
562 }
563 }
564}
565
566/// CountInternalUses - Returns the number of edges between the two nodes.
567///
568static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
569 unsigned N = 0;
570 for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
571 SDOperand Op = U->Node->getOperand(M);
572 if (Op.Val == D->Node) N++;
573 }
574
575 return N;
576}
577
578//===----------------------------------------------------------------------===//
579/// Add - Adds a definer and user pair to a node group.
580///
581void ScheduleDAGSimple::AddToGroup(NodeInfo *D, NodeInfo *U) {
582 // Get current groups
583 NodeGroup *DGroup = D->Group;
584 NodeGroup *UGroup = U->Group;
585 // If both are members of groups
586 if (DGroup && UGroup) {
587 // There may have been another edge connecting
588 if (DGroup == UGroup) return;
589 // Add the pending users count
590 DGroup->addPending(UGroup->getPending());
591 // For each member of the users group
592 NodeGroupIterator UNGI(U);
593 while (NodeInfo *UNI = UNGI.next() ) {
594 // Change the group
595 UNI->Group = DGroup;
596 // For each member of the definers group
597 NodeGroupIterator DNGI(D);
598 while (NodeInfo *DNI = DNGI.next() ) {
599 // Remove internal edges
600 DGroup->addPending(-CountInternalUses(DNI, UNI));
601 }
602 }
603 // Merge the two lists
604 DGroup->group_insert(DGroup->group_end(),
605 UGroup->group_begin(), UGroup->group_end());
606 } else if (DGroup) {
607 // Make user member of definers group
608 U->Group = DGroup;
609 // Add users uses to definers group pending
610 DGroup->addPending(U->Node->use_size());
611 // For each member of the definers group
612 NodeGroupIterator DNGI(D);
613 while (NodeInfo *DNI = DNGI.next() ) {
614 // Remove internal edges
615 DGroup->addPending(-CountInternalUses(DNI, U));
616 }
617 DGroup->group_push_back(U);
618 } else if (UGroup) {
619 // Make definer member of users group
620 D->Group = UGroup;
621 // Add definers uses to users group pending
622 UGroup->addPending(D->Node->use_size());
623 // For each member of the users group
624 NodeGroupIterator UNGI(U);
625 while (NodeInfo *UNI = UNGI.next() ) {
626 // Remove internal edges
627 UGroup->addPending(-CountInternalUses(D, UNI));
628 }
629 UGroup->group_insert(UGroup->group_begin(), D);
630 } else {
631 D->Group = U->Group = DGroup = new NodeGroup();
632 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
633 CountInternalUses(D, U));
634 DGroup->group_push_back(D);
635 DGroup->group_push_back(U);
636
637 if (HeadNG == NULL)
638 HeadNG = DGroup;
639 if (TailNG != NULL)
640 TailNG->Next = DGroup;
641 TailNG = DGroup;
642 }
643}
644
645
646/// print - Print ordering to specified output stream.
647///
Bill Wendling5c7e3262006-12-17 05:15:13 +0000648void ScheduleDAGSimple::print(std::ostream &O) const {
Chris Lattnere76074a2006-03-10 07:35:21 +0000649#ifndef NDEBUG
650 O << "Ordering\n";
651 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
652 NodeInfo *NI = Ordering[i];
653 printNI(O, NI);
654 O << "\n";
655 if (NI->isGroupDominator()) {
656 NodeGroup *Group = NI->Group;
657 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
658 NII != E; NII++) {
659 O << " ";
660 printNI(O, *NII);
661 O << "\n";
662 }
663 }
664 }
665#endif
666}
667
668void ScheduleDAGSimple::dump(const char *tag) const {
Bill Wendling832171c2006-12-07 20:04:42 +0000669 cerr << tag; dump();
Chris Lattnere76074a2006-03-10 07:35:21 +0000670}
671
672void ScheduleDAGSimple::dump() const {
Bill Wendling832171c2006-12-07 20:04:42 +0000673 print(cerr);
Chris Lattnere76074a2006-03-10 07:35:21 +0000674}
675
676
677/// EmitAll - Emit all nodes in schedule sorted order.
678///
679void ScheduleDAGSimple::EmitAll() {
Jim Laskeyf4923912006-08-03 20:51:06 +0000680 // If this is the first basic block in the function, and if it has live ins
681 // that need to be copied into vregs, emit the copies into the top of the
682 // block before emitting the code for the block.
683 MachineFunction &MF = DAG.getMachineFunction();
684 if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
685 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
686 E = MF.livein_end(); LI != E; ++LI)
Evan Cheng9efce632007-09-26 06:25:56 +0000687 if (LI->second) {
688 const TargetRegisterClass *RC = RegMap->getRegClass(LI->second);
Jim Laskeyf4923912006-08-03 20:51:06 +0000689 MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
Evan Cheng9efce632007-09-26 06:25:56 +0000690 LI->first, RC, RC);
691 }
Jim Laskeyf4923912006-08-03 20:51:06 +0000692 }
693
Evan Chengaf825c82007-07-10 07:08:32 +0000694 DenseMap<SDOperand, unsigned> VRBaseMap;
Chris Lattnere76074a2006-03-10 07:35:21 +0000695
696 // For each node in the ordering
697 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
698 // Get the scheduling info
699 NodeInfo *NI = Ordering[i];
700 if (NI->isInGroup()) {
701 NodeGroupIterator NGI(Ordering[i]);
Evan Chenga6fb1b62007-09-25 01:54:36 +0000702 while (NodeInfo *NI = NGI.next()) EmitNode(NI->Node, 0, VRBaseMap);
Chris Lattnere76074a2006-03-10 07:35:21 +0000703 } else {
Evan Chenga6fb1b62007-09-25 01:54:36 +0000704 EmitNode(NI->Node, 0, VRBaseMap);
Chris Lattnere76074a2006-03-10 07:35:21 +0000705 }
706 }
707}
708
709/// isFlagDefiner - Returns true if the node defines a flag result.
710static bool isFlagDefiner(SDNode *A) {
711 unsigned N = A->getNumValues();
712 return N && A->getValueType(N - 1) == MVT::Flag;
713}
714
715/// isFlagUser - Returns true if the node uses a flag result.
716///
717static bool isFlagUser(SDNode *A) {
718 unsigned N = A->getNumOperands();
719 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
720}
721
722/// printNI - Print node info.
723///
Bill Wendling5c7e3262006-12-17 05:15:13 +0000724void ScheduleDAGSimple::printNI(std::ostream &O, NodeInfo *NI) const {
Chris Lattnere76074a2006-03-10 07:35:21 +0000725#ifndef NDEBUG
726 SDNode *Node = NI->Node;
Bill Wendling5c7e3262006-12-17 05:15:13 +0000727 O << " "
728 << std::hex << Node << std::dec
729 << ", Lat=" << NI->Latency
730 << ", Slot=" << NI->Slot
731 << ", ARITY=(" << Node->getNumOperands() << ","
732 << Node->getNumValues() << ")"
733 << " " << Node->getOperationName(&DAG);
Chris Lattnere76074a2006-03-10 07:35:21 +0000734 if (isFlagDefiner(Node)) O << "<#";
735 if (isFlagUser(Node)) O << ">#";
736#endif
737}
738
739/// printChanges - Hilight changes in order caused by scheduling.
740///
741void ScheduleDAGSimple::printChanges(unsigned Index) const {
742#ifndef NDEBUG
743 // Get the ordered node count
744 unsigned N = Ordering.size();
745 // Determine if any changes
746 unsigned i = 0;
747 for (; i < N; i++) {
748 NodeInfo *NI = Ordering[i];
749 if (NI->Preorder != i) break;
750 }
751
752 if (i < N) {
Bill Wendling832171c2006-12-07 20:04:42 +0000753 cerr << Index << ". New Ordering\n";
Chris Lattnere76074a2006-03-10 07:35:21 +0000754
755 for (i = 0; i < N; i++) {
756 NodeInfo *NI = Ordering[i];
Bill Wendling832171c2006-12-07 20:04:42 +0000757 cerr << " " << NI->Preorder << ". ";
758 printNI(cerr, NI);
759 cerr << "\n";
Chris Lattnere76074a2006-03-10 07:35:21 +0000760 if (NI->isGroupDominator()) {
761 NodeGroup *Group = NI->Group;
762 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
763 NII != E; NII++) {
Bill Wendling832171c2006-12-07 20:04:42 +0000764 cerr << " ";
765 printNI(cerr, *NII);
766 cerr << "\n";
Chris Lattnere76074a2006-03-10 07:35:21 +0000767 }
768 }
769 }
770 } else {
Bill Wendling832171c2006-12-07 20:04:42 +0000771 cerr << Index << ". No Changes\n";
Chris Lattnere76074a2006-03-10 07:35:21 +0000772 }
773#endif
774}
Evan Chenga9c20912006-01-21 02:32:06 +0000775
776//===----------------------------------------------------------------------===//
Evan Chenga9c20912006-01-21 02:32:06 +0000777/// isDefiner - Return true if node A is a definer for B.
778///
779bool ScheduleDAGSimple::isDefiner(NodeInfo *A, NodeInfo *B) {
780 // While there are A nodes
781 NodeGroupIterator NII(A);
782 while (NodeInfo *NI = NII.next()) {
783 // Extract node
784 SDNode *Node = NI->Node;
785 // While there operands in nodes of B
786 NodeGroupOpIterator NGOI(B);
787 while (!NGOI.isEnd()) {
788 SDOperand Op = NGOI.next();
789 // If node from A defines a node in B
790 if (Node == Op.Val) return true;
791 }
792 }
793 return false;
794}
795
Evan Chenga9c20912006-01-21 02:32:06 +0000796/// IncludeNode - Add node to NodeInfo vector.
797///
798void ScheduleDAGSimple::IncludeNode(NodeInfo *NI) {
799 // Get node
800 SDNode *Node = NI->Node;
801 // Ignore entry node
802 if (Node->getOpcode() == ISD::EntryToken) return;
803 // Check current count for node
804 int Count = NI->getPending();
805 // If the node is already in list
806 if (Count < 0) return;
807 // Decrement count to indicate a visit
808 Count--;
809 // If count has gone to zero then add node to list
810 if (!Count) {
811 // Add node
812 if (NI->isInGroup()) {
813 Ordering.push_back(NI->Group->getDominator());
814 } else {
815 Ordering.push_back(NI);
816 }
817 // indicate node has been added
818 Count--;
819 }
820 // Mark as visited with new count
821 NI->setPending(Count);
822}
823
Evan Chenga9c20912006-01-21 02:32:06 +0000824/// GatherSchedulingInfo - Get latency and resource information about each node.
825///
826void ScheduleDAGSimple::GatherSchedulingInfo() {
827 // Get instruction itineraries for the target
Chris Lattnere70f6712006-03-09 07:13:00 +0000828 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
Evan Chenga9c20912006-01-21 02:32:06 +0000829
830 // For each node
831 for (unsigned i = 0, N = NodeCount; i < N; i++) {
832 // Get node info
833 NodeInfo* NI = &Info[i];
834 SDNode *Node = NI->Node;
835
836 // If there are itineraries and it is a machine instruction
Chris Lattner20a49212006-03-10 07:49:12 +0000837 if (InstrItins.isEmpty() || NoItins) {
Evan Chenga9c20912006-01-21 02:32:06 +0000838 // If machine opcode
839 if (Node->isTargetOpcode()) {
840 // Get return type to guess which processing unit
841 MVT::ValueType VT = Node->getValueType(0);
842 // Get machine opcode
843 MachineOpCode TOpc = Node->getTargetOpcode();
844 NI->IsCall = TII->isCall(TOpc);
845 NI->IsLoad = TII->isLoad(TOpc);
846 NI->IsStore = TII->isStore(TOpc);
847
848 if (TII->isLoad(TOpc)) NI->StageBegin = &LoadStage;
849 else if (TII->isStore(TOpc)) NI->StageBegin = &StoreStage;
850 else if (MVT::isInteger(VT)) NI->StageBegin = &IntStage;
851 else if (MVT::isFloatingPoint(VT)) NI->StageBegin = &FloatStage;
852 if (NI->StageBegin) NI->StageEnd = NI->StageBegin + 1;
853 }
854 } else if (Node->isTargetOpcode()) {
855 // get machine opcode
856 MachineOpCode TOpc = Node->getTargetOpcode();
857 // Check to see if it is a call
858 NI->IsCall = TII->isCall(TOpc);
859 // Get itinerary stages for instruction
860 unsigned II = TII->getSchedClass(TOpc);
861 NI->StageBegin = InstrItins.begin(II);
862 NI->StageEnd = InstrItins.end(II);
863 }
864
865 // One slot for the instruction itself
866 NI->Latency = 1;
867
868 // Add long latency for a call to push it back in time
869 if (NI->IsCall) NI->Latency += CallLatency;
870
871 // Sum up all the latencies
872 for (InstrStage *Stage = NI->StageBegin, *E = NI->StageEnd;
873 Stage != E; Stage++) {
874 NI->Latency += Stage->Cycles;
875 }
876
877 // Sum up all the latencies for max tally size
878 NSlots += NI->Latency;
879 }
880
881 // Unify metrics if in a group
882 if (HasGroups) {
883 for (unsigned i = 0, N = NodeCount; i < N; i++) {
884 NodeInfo* NI = &Info[i];
885
886 if (NI->isInGroup()) {
887 NodeGroup *Group = NI->Group;
888
889 if (!Group->getDominator()) {
890 NIIterator NGI = Group->group_begin(), NGE = Group->group_end();
891 NodeInfo *Dominator = *NGI;
892 unsigned Latency = 0;
893
894 for (NGI++; NGI != NGE; NGI++) {
895 NodeInfo* NGNI = *NGI;
896 Latency += NGNI->Latency;
897 if (Dominator->Latency < NGNI->Latency) Dominator = NGNI;
898 }
899
900 Dominator->Latency = Latency;
901 Group->setDominator(Dominator);
902 }
903 }
904 }
905 }
906}
907
Evan Cheng4ef10862006-01-23 07:01:07 +0000908/// VisitAll - Visit each node breadth-wise to produce an initial ordering.
909/// Note that the ordering in the Nodes vector is reversed.
910void ScheduleDAGSimple::VisitAll() {
911 // Add first element to list
912 NodeInfo *NI = getNI(DAG.getRoot().Val);
913 if (NI->isInGroup()) {
914 Ordering.push_back(NI->Group->getDominator());
915 } else {
916 Ordering.push_back(NI);
917 }
918
919 // Iterate through all nodes that have been added
920 for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
921 // Visit all operands
922 NodeGroupOpIterator NGI(Ordering[i]);
923 while (!NGI.isEnd()) {
924 // Get next operand
925 SDOperand Op = NGI.next();
926 // Get node
927 SDNode *Node = Op.Val;
928 // Ignore passive nodes
929 if (isPassiveNode(Node)) continue;
930 // Check out node
931 IncludeNode(getNI(Node));
932 }
933 }
934
935 // Add entry node last (IncludeNode filters entry nodes)
936 if (DAG.getEntryNode().Val != DAG.getRoot().Val)
937 Ordering.push_back(getNI(DAG.getEntryNode().Val));
938
939 // Reverse the order
940 std::reverse(Ordering.begin(), Ordering.end());
941}
942
Evan Chenga9c20912006-01-21 02:32:06 +0000943/// FakeGroupDominators - Set dominators for non-scheduling.
944///
945void ScheduleDAGSimple::FakeGroupDominators() {
946 for (unsigned i = 0, N = NodeCount; i < N; i++) {
947 NodeInfo* NI = &Info[i];
948
949 if (NI->isInGroup()) {
950 NodeGroup *Group = NI->Group;
951
952 if (!Group->getDominator()) {
953 Group->setDominator(NI);
954 }
955 }
956 }
957}
958
Evan Chenga9c20912006-01-21 02:32:06 +0000959/// isStrongDependency - Return true if node A has results used by node B.
960/// I.E., B must wait for latency of A.
961bool ScheduleDAGSimple::isStrongDependency(NodeInfo *A, NodeInfo *B) {
962 // If A defines for B then it's a strong dependency or
963 // if a load follows a store (may be dependent but why take a chance.)
964 return isDefiner(A, B) || (A->IsStore && B->IsLoad);
965}
966
967/// isWeakDependency Return true if node A produces a result that will
968/// conflict with operands of B. It is assumed that we have called
969/// isStrongDependency prior.
970bool ScheduleDAGSimple::isWeakDependency(NodeInfo *A, NodeInfo *B) {
971 // TODO check for conflicting real registers and aliases
972#if 0 // FIXME - Since we are in SSA form and not checking register aliasing
973 return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
974#else
975 return A->Node->getOpcode() == ISD::EntryToken;
976#endif
977}
978
979/// ScheduleBackward - Schedule instructions so that any long latency
980/// instructions and the critical path get pushed back in time. Time is run in
981/// reverse to allow code reuse of the Tally and eliminate the overhead of
982/// biasing every slot indices against NSlots.
983void ScheduleDAGSimple::ScheduleBackward() {
984 // Size and clear the resource tally
985 Tally.Initialize(NSlots);
986 // Get number of nodes to schedule
987 unsigned N = Ordering.size();
988
989 // For each node being scheduled
990 for (unsigned i = N; 0 < i--;) {
991 NodeInfo *NI = Ordering[i];
992 // Track insertion
993 unsigned Slot = NotFound;
994
995 // Compare against those previously scheduled nodes
996 unsigned j = i + 1;
997 for (; j < N; j++) {
998 // Get following instruction
999 NodeInfo *Other = Ordering[j];
1000
1001 // Check dependency against previously inserted nodes
1002 if (isStrongDependency(NI, Other)) {
1003 Slot = Other->Slot + Other->Latency;
1004 break;
1005 } else if (isWeakDependency(NI, Other)) {
1006 Slot = Other->Slot;
1007 break;
1008 }
1009 }
1010
1011 // If independent of others (or first entry)
1012 if (Slot == NotFound) Slot = 0;
1013
1014#if 0 // FIXME - measure later
1015 // Find a slot where the needed resources are available
1016 if (NI->StageBegin != NI->StageEnd)
1017 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
1018#endif
1019
1020 // Set node slot
1021 NI->Slot = Slot;
1022
1023 // Insert sort based on slot
1024 j = i + 1;
1025 for (; j < N; j++) {
1026 // Get following instruction
1027 NodeInfo *Other = Ordering[j];
1028 // Should we look further (remember slots are in reverse time)
1029 if (Slot >= Other->Slot) break;
1030 // Shuffle other into ordering
1031 Ordering[j - 1] = Other;
1032 }
1033 // Insert node in proper slot
1034 if (j != i + 1) Ordering[j - 1] = NI;
1035 }
1036}
1037
1038/// ScheduleForward - Schedule instructions to maximize packing.
1039///
1040void ScheduleDAGSimple::ScheduleForward() {
1041 // Size and clear the resource tally
1042 Tally.Initialize(NSlots);
1043 // Get number of nodes to schedule
1044 unsigned N = Ordering.size();
1045
1046 // For each node being scheduled
1047 for (unsigned i = 0; i < N; i++) {
1048 NodeInfo *NI = Ordering[i];
1049 // Track insertion
1050 unsigned Slot = NotFound;
1051
1052 // Compare against those previously scheduled nodes
1053 unsigned j = i;
1054 for (; 0 < j--;) {
1055 // Get following instruction
1056 NodeInfo *Other = Ordering[j];
1057
1058 // Check dependency against previously inserted nodes
1059 if (isStrongDependency(Other, NI)) {
1060 Slot = Other->Slot + Other->Latency;
1061 break;
1062 } else if (Other->IsCall || isWeakDependency(Other, NI)) {
1063 Slot = Other->Slot;
1064 break;
1065 }
1066 }
1067
1068 // If independent of others (or first entry)
1069 if (Slot == NotFound) Slot = 0;
1070
1071 // Find a slot where the needed resources are available
1072 if (NI->StageBegin != NI->StageEnd)
1073 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
1074
1075 // Set node slot
1076 NI->Slot = Slot;
1077
1078 // Insert sort based on slot
1079 j = i;
1080 for (; 0 < j--;) {
1081 // Get prior instruction
1082 NodeInfo *Other = Ordering[j];
1083 // Should we look further
1084 if (Slot >= Other->Slot) break;
1085 // Shuffle other into ordering
1086 Ordering[j + 1] = Other;
1087 }
1088 // Insert node in proper slot
1089 if (j != i) Ordering[j + 1] = NI;
1090 }
1091}
1092
Evan Chenga9c20912006-01-21 02:32:06 +00001093/// Schedule - Order nodes according to selected style.
1094///
1095void ScheduleDAGSimple::Schedule() {
Chris Lattner2f5806c2006-03-10 07:42:02 +00001096 // Number the nodes
1097 NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
1098
Chris Lattnerbe24e592006-03-10 06:34:51 +00001099 // Set up minimum info for scheduling
1100 PrepareNodeInfo();
1101 // Construct node groups for flagged nodes
1102 IdentifyGroups();
1103
Evan Chenga9c20912006-01-21 02:32:06 +00001104 // Test to see if scheduling should occur
Chris Lattner20a49212006-03-10 07:49:12 +00001105 bool ShouldSchedule = NodeCount > 3 && !NoSched;
Evan Chenga9c20912006-01-21 02:32:06 +00001106 // Don't waste time if is only entry and return
1107 if (ShouldSchedule) {
1108 // Get latency and resource requirements
1109 GatherSchedulingInfo();
1110 } else if (HasGroups) {
1111 // Make sure all the groups have dominators
1112 FakeGroupDominators();
1113 }
1114
1115 // Breadth first walk of DAG
1116 VisitAll();
1117
1118#ifndef NDEBUG
1119 static unsigned Count = 0;
1120 Count++;
1121 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
1122 NodeInfo *NI = Ordering[i];
1123 NI->Preorder = i;
1124 }
1125#endif
1126
1127 // Don't waste time if is only entry and return
1128 if (ShouldSchedule) {
1129 // Push back long instructions and critical path
1130 ScheduleBackward();
1131
1132 // Pack instructions to maximize resource utilization
1133 ScheduleForward();
1134 }
1135
1136 DEBUG(printChanges(Count));
1137
1138 // Emit in scheduled order
1139 EmitAll();
1140}
1141
Evan Chenga9c20912006-01-21 02:32:06 +00001142
1143/// createSimpleDAGScheduler - This creates a simple two pass instruction
Jim Laskey13ec7022006-08-01 14:21:23 +00001144/// scheduler using instruction itinerary.
Jim Laskey9ff542f2006-08-01 18:29:48 +00001145llvm::ScheduleDAG* llvm::createSimpleDAGScheduler(SelectionDAGISel *IS,
1146 SelectionDAG *DAG,
Evan Chenga9c20912006-01-21 02:32:06 +00001147 MachineBasicBlock *BB) {
Jim Laskey13ec7022006-08-01 14:21:23 +00001148 return new ScheduleDAGSimple(false, false, *DAG, BB, DAG->getTarget());
Chris Lattner20a49212006-03-10 07:49:12 +00001149}
1150
Jim Laskey13ec7022006-08-01 14:21:23 +00001151/// createNoItinsDAGScheduler - This creates a simple two pass instruction
1152/// scheduler without using instruction itinerary.
Jim Laskey9ff542f2006-08-01 18:29:48 +00001153llvm::ScheduleDAG* llvm::createNoItinsDAGScheduler(SelectionDAGISel *IS,
1154 SelectionDAG *DAG,
Jim Laskey13ec7022006-08-01 14:21:23 +00001155 MachineBasicBlock *BB) {
1156 return new ScheduleDAGSimple(false, true, *DAG, BB, DAG->getTarget());
1157}
1158
1159/// createBFS_DAGScheduler - This creates a simple breadth first instruction
1160/// scheduler.
Jim Laskey9ff542f2006-08-01 18:29:48 +00001161llvm::ScheduleDAG* llvm::createBFS_DAGScheduler(SelectionDAGISel *IS,
1162 SelectionDAG *DAG,
Chris Lattner20a49212006-03-10 07:49:12 +00001163 MachineBasicBlock *BB) {
Jim Laskey13ec7022006-08-01 14:21:23 +00001164 return new ScheduleDAGSimple(true, false, *DAG, BB, DAG->getTarget());
Evan Chenga9c20912006-01-21 02:32:06 +00001165}