Use uint16_t to store instruction implicit uses and defs. Reduces static data.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGRRList.cpp
1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
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 bottom-up and top-down register pressure reduction list
11 // schedulers, using standard algorithms.  The basic approach uses a priority
12 // queue of available nodes to schedule.  One at a time, nodes are taken from
13 // the priority queue (thus in priority order), checked for legality to
14 // schedule, and emitted if legal.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "ScheduleDAGSDNodes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/CodeGen/SchedulerRegistry.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <climits>
36 using namespace llvm;
37
38 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
39 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
40 STATISTIC(NumDups,       "Number of duplicated nodes");
41 STATISTIC(NumPRCopies,   "Number of physical register copies");
42
43 static RegisterScheduler
44   burrListDAGScheduler("list-burr",
45                        "Bottom-up register reduction list scheduling",
46                        createBURRListDAGScheduler);
47 static RegisterScheduler
48   sourceListDAGScheduler("source",
49                          "Similar to list-burr but schedules in source "
50                          "order when possible",
51                          createSourceListDAGScheduler);
52
53 static RegisterScheduler
54   hybridListDAGScheduler("list-hybrid",
55                          "Bottom-up register pressure aware list scheduling "
56                          "which tries to balance latency and register pressure",
57                          createHybridListDAGScheduler);
58
59 static RegisterScheduler
60   ILPListDAGScheduler("list-ilp",
61                       "Bottom-up register pressure aware list scheduling "
62                       "which tries to balance ILP and register pressure",
63                       createILPListDAGScheduler);
64
65 static cl::opt<bool> DisableSchedCycles(
66   "disable-sched-cycles", cl::Hidden, cl::init(false),
67   cl::desc("Disable cycle-level precision during preRA scheduling"));
68
69 // Temporary sched=list-ilp flags until the heuristics are robust.
70 // Some options are also available under sched=list-hybrid.
71 static cl::opt<bool> DisableSchedRegPressure(
72   "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
73   cl::desc("Disable regpressure priority in sched=list-ilp"));
74 static cl::opt<bool> DisableSchedLiveUses(
75   "disable-sched-live-uses", cl::Hidden, cl::init(true),
76   cl::desc("Disable live use priority in sched=list-ilp"));
77 static cl::opt<bool> DisableSchedVRegCycle(
78   "disable-sched-vrcycle", cl::Hidden, cl::init(false),
79   cl::desc("Disable virtual register cycle interference checks"));
80 static cl::opt<bool> DisableSchedPhysRegJoin(
81   "disable-sched-physreg-join", cl::Hidden, cl::init(false),
82   cl::desc("Disable physreg def-use affinity"));
83 static cl::opt<bool> DisableSchedStalls(
84   "disable-sched-stalls", cl::Hidden, cl::init(true),
85   cl::desc("Disable no-stall priority in sched=list-ilp"));
86 static cl::opt<bool> DisableSchedCriticalPath(
87   "disable-sched-critical-path", cl::Hidden, cl::init(false),
88   cl::desc("Disable critical path priority in sched=list-ilp"));
89 static cl::opt<bool> DisableSchedHeight(
90   "disable-sched-height", cl::Hidden, cl::init(false),
91   cl::desc("Disable scheduled-height priority in sched=list-ilp"));
92 static cl::opt<bool> Disable2AddrHack(
93   "disable-2addr-hack", cl::Hidden, cl::init(true),
94   cl::desc("Disable scheduler's two-address hack"));
95
96 static cl::opt<int> MaxReorderWindow(
97   "max-sched-reorder", cl::Hidden, cl::init(6),
98   cl::desc("Number of instructions to allow ahead of the critical path "
99            "in sched=list-ilp"));
100
101 static cl::opt<unsigned> AvgIPC(
102   "sched-avg-ipc", cl::Hidden, cl::init(1),
103   cl::desc("Average inst/cycle whan no target itinerary exists."));
104
105 namespace {
106 //===----------------------------------------------------------------------===//
107 /// ScheduleDAGRRList - The actual register reduction list scheduler
108 /// implementation.  This supports both top-down and bottom-up scheduling.
109 ///
110 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
111 private:
112   /// NeedLatency - True if the scheduler will make use of latency information.
113   ///
114   bool NeedLatency;
115
116   /// AvailableQueue - The priority queue to use for the available SUnits.
117   SchedulingPriorityQueue *AvailableQueue;
118
119   /// PendingQueue - This contains all of the instructions whose operands have
120   /// been issued, but their results are not ready yet (due to the latency of
121   /// the operation).  Once the operands becomes available, the instruction is
122   /// added to the AvailableQueue.
123   std::vector<SUnit*> PendingQueue;
124
125   /// HazardRec - The hazard recognizer to use.
126   ScheduleHazardRecognizer *HazardRec;
127
128   /// CurCycle - The current scheduler state corresponds to this cycle.
129   unsigned CurCycle;
130
131   /// MinAvailableCycle - Cycle of the soonest available instruction.
132   unsigned MinAvailableCycle;
133
134   /// IssueCount - Count instructions issued in this cycle
135   /// Currently valid only for bottom-up scheduling.
136   unsigned IssueCount;
137
138   /// LiveRegDefs - A set of physical registers and their definition
139   /// that are "live". These nodes must be scheduled before any other nodes that
140   /// modifies the registers can be scheduled.
141   unsigned NumLiveRegs;
142   std::vector<SUnit*> LiveRegDefs;
143   std::vector<SUnit*> LiveRegGens;
144
145   /// Topo - A topological ordering for SUnits which permits fast IsReachable
146   /// and similar queries.
147   ScheduleDAGTopologicalSort Topo;
148
149   // Hack to keep track of the inverse of FindCallSeqStart without more crazy
150   // DAG crawling.
151   DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
152
153 public:
154   ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
155                     SchedulingPriorityQueue *availqueue,
156                     CodeGenOpt::Level OptLevel)
157     : ScheduleDAGSDNodes(mf),
158       NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
159       Topo(SUnits) {
160
161     const TargetMachine &tm = mf.getTarget();
162     if (DisableSchedCycles || !NeedLatency)
163       HazardRec = new ScheduleHazardRecognizer();
164     else
165       HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
166   }
167
168   ~ScheduleDAGRRList() {
169     delete HazardRec;
170     delete AvailableQueue;
171   }
172
173   void Schedule();
174
175   ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
176
177   /// IsReachable - Checks if SU is reachable from TargetSU.
178   bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
179     return Topo.IsReachable(SU, TargetSU);
180   }
181
182   /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
183   /// create a cycle.
184   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
185     return Topo.WillCreateCycle(SU, TargetSU);
186   }
187
188   /// AddPred - adds a predecessor edge to SUnit SU.
189   /// This returns true if this is a new predecessor.
190   /// Updates the topological ordering if required.
191   void AddPred(SUnit *SU, const SDep &D) {
192     Topo.AddPred(SU, D.getSUnit());
193     SU->addPred(D);
194   }
195
196   /// RemovePred - removes a predecessor edge from SUnit SU.
197   /// This returns true if an edge was removed.
198   /// Updates the topological ordering if required.
199   void RemovePred(SUnit *SU, const SDep &D) {
200     Topo.RemovePred(SU, D.getSUnit());
201     SU->removePred(D);
202   }
203
204 private:
205   bool isReady(SUnit *SU) {
206     return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
207       AvailableQueue->isReady(SU);
208   }
209
210   void ReleasePred(SUnit *SU, const SDep *PredEdge);
211   void ReleasePredecessors(SUnit *SU);
212   void ReleasePending();
213   void AdvanceToCycle(unsigned NextCycle);
214   void AdvancePastStalls(SUnit *SU);
215   void EmitNode(SUnit *SU);
216   void ScheduleNodeBottomUp(SUnit*);
217   void CapturePred(SDep *PredEdge);
218   void UnscheduleNodeBottomUp(SUnit*);
219   void RestoreHazardCheckerBottomUp();
220   void BacktrackBottomUp(SUnit*, SUnit*);
221   SUnit *CopyAndMoveSuccessors(SUnit*);
222   void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
223                                 const TargetRegisterClass*,
224                                 const TargetRegisterClass*,
225                                 SmallVector<SUnit*, 2>&);
226   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
227
228   SUnit *PickNodeToScheduleBottomUp();
229   void ListScheduleBottomUp();
230
231   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
232   /// Updates the topological ordering if required.
233   SUnit *CreateNewSUnit(SDNode *N) {
234     unsigned NumSUnits = SUnits.size();
235     SUnit *NewNode = newSUnit(N);
236     // Update the topological ordering.
237     if (NewNode->NodeNum >= NumSUnits)
238       Topo.InitDAGTopologicalSorting();
239     return NewNode;
240   }
241
242   /// CreateClone - Creates a new SUnit from an existing one.
243   /// Updates the topological ordering if required.
244   SUnit *CreateClone(SUnit *N) {
245     unsigned NumSUnits = SUnits.size();
246     SUnit *NewNode = Clone(N);
247     // Update the topological ordering.
248     if (NewNode->NodeNum >= NumSUnits)
249       Topo.InitDAGTopologicalSorting();
250     return NewNode;
251   }
252
253   /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
254   /// need actual latency information but the hybrid scheduler does.
255   bool forceUnitLatencies() const {
256     return !NeedLatency;
257   }
258 };
259 }  // end anonymous namespace
260
261 /// GetCostForDef - Looks up the register class and cost for a given definition.
262 /// Typically this just means looking up the representative register class,
263 /// but for untyped values (MVT::Untyped) it means inspecting the node's
264 /// opcode to determine what register class is being generated.
265 static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
266                           const TargetLowering *TLI,
267                           const TargetInstrInfo *TII,
268                           const TargetRegisterInfo *TRI,
269                           unsigned &RegClass, unsigned &Cost) {
270   EVT VT = RegDefPos.GetValue();
271
272   // Special handling for untyped values.  These values can only come from
273   // the expansion of custom DAG-to-DAG patterns.
274   if (VT == MVT::Untyped) {
275     const SDNode *Node = RegDefPos.GetNode();
276     unsigned Opcode = Node->getMachineOpcode();
277
278     if (Opcode == TargetOpcode::REG_SEQUENCE) {
279       unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
280       const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
281       RegClass = RC->getID();
282       Cost = 1;
283       return;
284     }
285
286     unsigned Idx = RegDefPos.GetIdx();
287     const MCInstrDesc Desc = TII->get(Opcode);
288     const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI);
289     RegClass = RC->getID();
290     // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
291     // better way to determine it.
292     Cost = 1;
293   } else {
294     RegClass = TLI->getRepRegClassFor(VT)->getID();
295     Cost = TLI->getRepRegClassCostFor(VT);
296   }
297 }
298
299 /// Schedule - Schedule the DAG using list scheduling.
300 void ScheduleDAGRRList::Schedule() {
301   DEBUG(dbgs()
302         << "********** List Scheduling BB#" << BB->getNumber()
303         << " '" << BB->getName() << "' **********\n");
304
305   CurCycle = 0;
306   IssueCount = 0;
307   MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
308   NumLiveRegs = 0;
309   // Allocate slots for each physical register, plus one for a special register
310   // to track the virtual resource of a calling sequence.
311   LiveRegDefs.resize(TRI->getNumRegs() + 1, NULL);
312   LiveRegGens.resize(TRI->getNumRegs() + 1, NULL);
313   CallSeqEndForStart.clear();
314
315   // Build the scheduling graph.
316   BuildSchedGraph(NULL);
317
318   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
319           SUnits[su].dumpAll(this));
320   Topo.InitDAGTopologicalSorting();
321
322   AvailableQueue->initNodes(SUnits);
323
324   HazardRec->Reset();
325
326   // Execute the actual scheduling loop.
327   ListScheduleBottomUp();
328
329   AvailableQueue->releaseState();
330
331   DEBUG({
332       dbgs() << "*** Final schedule ***\n";
333       dumpSchedule();
334       dbgs() << '\n';
335     });
336 }
337
338 //===----------------------------------------------------------------------===//
339 //  Bottom-Up Scheduling
340 //===----------------------------------------------------------------------===//
341
342 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
343 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
344 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
345   SUnit *PredSU = PredEdge->getSUnit();
346
347 #ifndef NDEBUG
348   if (PredSU->NumSuccsLeft == 0) {
349     dbgs() << "*** Scheduling failed! ***\n";
350     PredSU->dump(this);
351     dbgs() << " has been released too many times!\n";
352     llvm_unreachable(0);
353   }
354 #endif
355   --PredSU->NumSuccsLeft;
356
357   if (!forceUnitLatencies()) {
358     // Updating predecessor's height. This is now the cycle when the
359     // predecessor can be scheduled without causing a pipeline stall.
360     PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
361   }
362
363   // If all the node's successors are scheduled, this node is ready
364   // to be scheduled. Ignore the special EntrySU node.
365   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
366     PredSU->isAvailable = true;
367
368     unsigned Height = PredSU->getHeight();
369     if (Height < MinAvailableCycle)
370       MinAvailableCycle = Height;
371
372     if (isReady(PredSU)) {
373       AvailableQueue->push(PredSU);
374     }
375     // CapturePred and others may have left the node in the pending queue, avoid
376     // adding it twice.
377     else if (!PredSU->isPending) {
378       PredSU->isPending = true;
379       PendingQueue.push_back(PredSU);
380     }
381   }
382 }
383
384 /// IsChainDependent - Test if Outer is reachable from Inner through
385 /// chain dependencies.
386 static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
387                              unsigned NestLevel,
388                              const TargetInstrInfo *TII) {
389   SDNode *N = Outer;
390   for (;;) {
391     if (N == Inner)
392       return true;
393     // For a TokenFactor, examine each operand. There may be multiple ways
394     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
395     // most nesting in order to ensure that we find the corresponding match.
396     if (N->getOpcode() == ISD::TokenFactor) {
397       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
398         if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
399           return true;
400       return false;
401     }
402     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
403     if (N->isMachineOpcode()) {
404       if (N->getMachineOpcode() ==
405           (unsigned)TII->getCallFrameDestroyOpcode()) {
406         ++NestLevel;
407       } else if (N->getMachineOpcode() ==
408                  (unsigned)TII->getCallFrameSetupOpcode()) {
409         if (NestLevel == 0)
410           return false;
411         --NestLevel;
412       }
413     }
414     // Otherwise, find the chain and continue climbing.
415     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
416       if (N->getOperand(i).getValueType() == MVT::Other) {
417         N = N->getOperand(i).getNode();
418         goto found_chain_operand;
419       }
420     return false;
421   found_chain_operand:;
422     if (N->getOpcode() == ISD::EntryToken)
423       return false;
424   }
425 }
426
427 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
428 /// the corresponding (lowered) CALLSEQ_BEGIN node.
429 ///
430 /// NestLevel and MaxNested are used in recursion to indcate the current level
431 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
432 /// level seen so far.
433 ///
434 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
435 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
436 static SDNode *
437 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
438                  const TargetInstrInfo *TII) {
439   for (;;) {
440     // For a TokenFactor, examine each operand. There may be multiple ways
441     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
442     // most nesting in order to ensure that we find the corresponding match.
443     if (N->getOpcode() == ISD::TokenFactor) {
444       SDNode *Best = 0;
445       unsigned BestMaxNest = MaxNest;
446       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
447         unsigned MyNestLevel = NestLevel;
448         unsigned MyMaxNest = MaxNest;
449         if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
450                                            MyNestLevel, MyMaxNest, TII))
451           if (!Best || (MyMaxNest > BestMaxNest)) {
452             Best = New;
453             BestMaxNest = MyMaxNest;
454           }
455       }
456       assert(Best);
457       MaxNest = BestMaxNest;
458       return Best;
459     }
460     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
461     if (N->isMachineOpcode()) {
462       if (N->getMachineOpcode() ==
463           (unsigned)TII->getCallFrameDestroyOpcode()) {
464         ++NestLevel;
465         MaxNest = std::max(MaxNest, NestLevel);
466       } else if (N->getMachineOpcode() ==
467                  (unsigned)TII->getCallFrameSetupOpcode()) {
468         assert(NestLevel != 0);
469         --NestLevel;
470         if (NestLevel == 0)
471           return N;
472       }
473     }
474     // Otherwise, find the chain and continue climbing.
475     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
476       if (N->getOperand(i).getValueType() == MVT::Other) {
477         N = N->getOperand(i).getNode();
478         goto found_chain_operand;
479       }
480     return 0;
481   found_chain_operand:;
482     if (N->getOpcode() == ISD::EntryToken)
483       return 0;
484   }
485 }
486
487 /// Call ReleasePred for each predecessor, then update register live def/gen.
488 /// Always update LiveRegDefs for a register dependence even if the current SU
489 /// also defines the register. This effectively create one large live range
490 /// across a sequence of two-address node. This is important because the
491 /// entire chain must be scheduled together. Example:
492 ///
493 /// flags = (3) add
494 /// flags = (2) addc flags
495 /// flags = (1) addc flags
496 ///
497 /// results in
498 ///
499 /// LiveRegDefs[flags] = 3
500 /// LiveRegGens[flags] = 1
501 ///
502 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
503 /// interference on flags.
504 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
505   // Bottom up: release predecessors
506   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
507        I != E; ++I) {
508     ReleasePred(SU, &*I);
509     if (I->isAssignedRegDep()) {
510       // This is a physical register dependency and it's impossible or
511       // expensive to copy the register. Make sure nothing that can
512       // clobber the register is scheduled between the predecessor and
513       // this node.
514       SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
515       assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
516              "interference on register dependence");
517       LiveRegDefs[I->getReg()] = I->getSUnit();
518       if (!LiveRegGens[I->getReg()]) {
519         ++NumLiveRegs;
520         LiveRegGens[I->getReg()] = SU;
521       }
522     }
523   }
524
525   // If we're scheduling a lowered CALLSEQ_END, find the corresponding
526   // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
527   // these nodes, to prevent other calls from being interscheduled with them.
528   unsigned CallResource = TRI->getNumRegs();
529   if (!LiveRegDefs[CallResource])
530     for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
531       if (Node->isMachineOpcode() &&
532           Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
533         unsigned NestLevel = 0;
534         unsigned MaxNest = 0;
535         SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
536
537         SUnit *Def = &SUnits[N->getNodeId()];
538         CallSeqEndForStart[Def] = SU;
539
540         ++NumLiveRegs;
541         LiveRegDefs[CallResource] = Def;
542         LiveRegGens[CallResource] = SU;
543         break;
544       }
545 }
546
547 /// Check to see if any of the pending instructions are ready to issue.  If
548 /// so, add them to the available queue.
549 void ScheduleDAGRRList::ReleasePending() {
550   if (DisableSchedCycles) {
551     assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
552     return;
553   }
554
555   // If the available queue is empty, it is safe to reset MinAvailableCycle.
556   if (AvailableQueue->empty())
557     MinAvailableCycle = UINT_MAX;
558
559   // Check to see if any of the pending instructions are ready to issue.  If
560   // so, add them to the available queue.
561   for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
562     unsigned ReadyCycle = PendingQueue[i]->getHeight();
563     if (ReadyCycle < MinAvailableCycle)
564       MinAvailableCycle = ReadyCycle;
565
566     if (PendingQueue[i]->isAvailable) {
567       if (!isReady(PendingQueue[i]))
568           continue;
569       AvailableQueue->push(PendingQueue[i]);
570     }
571     PendingQueue[i]->isPending = false;
572     PendingQueue[i] = PendingQueue.back();
573     PendingQueue.pop_back();
574     --i; --e;
575   }
576 }
577
578 /// Move the scheduler state forward by the specified number of Cycles.
579 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
580   if (NextCycle <= CurCycle)
581     return;
582
583   IssueCount = 0;
584   AvailableQueue->setCurCycle(NextCycle);
585   if (!HazardRec->isEnabled()) {
586     // Bypass lots of virtual calls in case of long latency.
587     CurCycle = NextCycle;
588   }
589   else {
590     for (; CurCycle != NextCycle; ++CurCycle) {
591       HazardRec->RecedeCycle();
592     }
593   }
594   // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
595   // available Q to release pending nodes at least once before popping.
596   ReleasePending();
597 }
598
599 /// Move the scheduler state forward until the specified node's dependents are
600 /// ready and can be scheduled with no resource conflicts.
601 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
602   if (DisableSchedCycles)
603     return;
604
605   // FIXME: Nodes such as CopyFromReg probably should not advance the current
606   // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
607   // has predecessors the cycle will be advanced when they are scheduled.
608   // But given the crude nature of modeling latency though such nodes, we
609   // currently need to treat these nodes like real instructions.
610   // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
611
612   unsigned ReadyCycle = SU->getHeight();
613
614   // Bump CurCycle to account for latency. We assume the latency of other
615   // available instructions may be hidden by the stall (not a full pipe stall).
616   // This updates the hazard recognizer's cycle before reserving resources for
617   // this instruction.
618   AdvanceToCycle(ReadyCycle);
619
620   // Calls are scheduled in their preceding cycle, so don't conflict with
621   // hazards from instructions after the call. EmitNode will reset the
622   // scoreboard state before emitting the call.
623   if (SU->isCall)
624     return;
625
626   // FIXME: For resource conflicts in very long non-pipelined stages, we
627   // should probably skip ahead here to avoid useless scoreboard checks.
628   int Stalls = 0;
629   while (true) {
630     ScheduleHazardRecognizer::HazardType HT =
631       HazardRec->getHazardType(SU, -Stalls);
632
633     if (HT == ScheduleHazardRecognizer::NoHazard)
634       break;
635
636     ++Stalls;
637   }
638   AdvanceToCycle(CurCycle + Stalls);
639 }
640
641 /// Record this SUnit in the HazardRecognizer.
642 /// Does not update CurCycle.
643 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
644   if (!HazardRec->isEnabled())
645     return;
646
647   // Check for phys reg copy.
648   if (!SU->getNode())
649     return;
650
651   switch (SU->getNode()->getOpcode()) {
652   default:
653     assert(SU->getNode()->isMachineOpcode() &&
654            "This target-independent node should not be scheduled.");
655     break;
656   case ISD::MERGE_VALUES:
657   case ISD::TokenFactor:
658   case ISD::CopyToReg:
659   case ISD::CopyFromReg:
660   case ISD::EH_LABEL:
661     // Noops don't affect the scoreboard state. Copies are likely to be
662     // removed.
663     return;
664   case ISD::INLINEASM:
665     // For inline asm, clear the pipeline state.
666     HazardRec->Reset();
667     return;
668   }
669   if (SU->isCall) {
670     // Calls are scheduled with their preceding instructions. For bottom-up
671     // scheduling, clear the pipeline state before emitting.
672     HazardRec->Reset();
673   }
674
675   HazardRec->EmitInstruction(SU);
676 }
677
678 static void resetVRegCycle(SUnit *SU);
679
680 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
681 /// count of its predecessors. If a predecessor pending count is zero, add it to
682 /// the Available queue.
683 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
684   DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
685   DEBUG(SU->dump(this));
686
687 #ifndef NDEBUG
688   if (CurCycle < SU->getHeight())
689     DEBUG(dbgs() << "   Height [" << SU->getHeight()
690           << "] pipeline stall!\n");
691 #endif
692
693   // FIXME: Do not modify node height. It may interfere with
694   // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
695   // node its ready cycle can aid heuristics, and after scheduling it can
696   // indicate the scheduled cycle.
697   SU->setHeightToAtLeast(CurCycle);
698
699   // Reserve resources for the scheduled intruction.
700   EmitNode(SU);
701
702   Sequence.push_back(SU);
703
704   AvailableQueue->scheduledNode(SU);
705
706   // If HazardRec is disabled, and each inst counts as one cycle, then
707   // advance CurCycle before ReleasePredecessors to avoid useless pushes to
708   // PendingQueue for schedulers that implement HasReadyFilter.
709   if (!HazardRec->isEnabled() && AvgIPC < 2)
710     AdvanceToCycle(CurCycle + 1);
711
712   // Update liveness of predecessors before successors to avoid treating a
713   // two-address node as a live range def.
714   ReleasePredecessors(SU);
715
716   // Release all the implicit physical register defs that are live.
717   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
718        I != E; ++I) {
719     // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
720     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
721       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
722       --NumLiveRegs;
723       LiveRegDefs[I->getReg()] = NULL;
724       LiveRegGens[I->getReg()] = NULL;
725     }
726   }
727   // Release the special call resource dependence, if this is the beginning
728   // of a call.
729   unsigned CallResource = TRI->getNumRegs();
730   if (LiveRegDefs[CallResource] == SU)
731     for (const SDNode *SUNode = SU->getNode(); SUNode;
732          SUNode = SUNode->getGluedNode()) {
733       if (SUNode->isMachineOpcode() &&
734           SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
735         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
736         --NumLiveRegs;
737         LiveRegDefs[CallResource] = NULL;
738         LiveRegGens[CallResource] = NULL;
739       }
740     }
741
742   resetVRegCycle(SU);
743
744   SU->isScheduled = true;
745
746   // Conditions under which the scheduler should eagerly advance the cycle:
747   // (1) No available instructions
748   // (2) All pipelines full, so available instructions must have hazards.
749   //
750   // If HazardRec is disabled, the cycle was pre-advanced before calling
751   // ReleasePredecessors. In that case, IssueCount should remain 0.
752   //
753   // Check AvailableQueue after ReleasePredecessors in case of zero latency.
754   if (HazardRec->isEnabled() || AvgIPC > 1) {
755     if (SU->getNode() && SU->getNode()->isMachineOpcode())
756       ++IssueCount;
757     if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
758         || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
759       AdvanceToCycle(CurCycle + 1);
760   }
761 }
762
763 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
764 /// unscheduled, incrcease the succ left count of its predecessors. Remove
765 /// them from AvailableQueue if necessary.
766 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
767   SUnit *PredSU = PredEdge->getSUnit();
768   if (PredSU->isAvailable) {
769     PredSU->isAvailable = false;
770     if (!PredSU->isPending)
771       AvailableQueue->remove(PredSU);
772   }
773
774   assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
775   ++PredSU->NumSuccsLeft;
776 }
777
778 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
779 /// its predecessor states to reflect the change.
780 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
781   DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
782   DEBUG(SU->dump(this));
783
784   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
785        I != E; ++I) {
786     CapturePred(&*I);
787     if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
788       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
789       assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
790              "Physical register dependency violated?");
791       --NumLiveRegs;
792       LiveRegDefs[I->getReg()] = NULL;
793       LiveRegGens[I->getReg()] = NULL;
794     }
795   }
796
797   // Reclaim the special call resource dependence, if this is the beginning
798   // of a call.
799   unsigned CallResource = TRI->getNumRegs();
800   for (const SDNode *SUNode = SU->getNode(); SUNode;
801        SUNode = SUNode->getGluedNode()) {
802     if (SUNode->isMachineOpcode() &&
803         SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
804       ++NumLiveRegs;
805       LiveRegDefs[CallResource] = SU;
806       LiveRegGens[CallResource] = CallSeqEndForStart[SU];
807     }
808   }
809
810   // Release the special call resource dependence, if this is the end
811   // of a call.
812   if (LiveRegGens[CallResource] == SU)
813     for (const SDNode *SUNode = SU->getNode(); SUNode;
814          SUNode = SUNode->getGluedNode()) {
815       if (SUNode->isMachineOpcode() &&
816           SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
817         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
818         --NumLiveRegs;
819         LiveRegDefs[CallResource] = NULL;
820         LiveRegGens[CallResource] = NULL;
821       }
822     }
823
824   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
825        I != E; ++I) {
826     if (I->isAssignedRegDep()) {
827       if (!LiveRegDefs[I->getReg()])
828         ++NumLiveRegs;
829       // This becomes the nearest def. Note that an earlier def may still be
830       // pending if this is a two-address node.
831       LiveRegDefs[I->getReg()] = SU;
832       if (LiveRegGens[I->getReg()] == NULL ||
833           I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
834         LiveRegGens[I->getReg()] = I->getSUnit();
835     }
836   }
837   if (SU->getHeight() < MinAvailableCycle)
838     MinAvailableCycle = SU->getHeight();
839
840   SU->setHeightDirty();
841   SU->isScheduled = false;
842   SU->isAvailable = true;
843   if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
844     // Don't make available until backtracking is complete.
845     SU->isPending = true;
846     PendingQueue.push_back(SU);
847   }
848   else {
849     AvailableQueue->push(SU);
850   }
851   AvailableQueue->unscheduledNode(SU);
852 }
853
854 /// After backtracking, the hazard checker needs to be restored to a state
855 /// corresponding the the current cycle.
856 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
857   HazardRec->Reset();
858
859   unsigned LookAhead = std::min((unsigned)Sequence.size(),
860                                 HazardRec->getMaxLookAhead());
861   if (LookAhead == 0)
862     return;
863
864   std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
865   unsigned HazardCycle = (*I)->getHeight();
866   for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
867     SUnit *SU = *I;
868     for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
869       HazardRec->RecedeCycle();
870     }
871     EmitNode(SU);
872   }
873 }
874
875 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
876 /// BTCycle in order to schedule a specific node.
877 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
878   SUnit *OldSU = Sequence.back();
879   while (true) {
880     Sequence.pop_back();
881     if (SU->isSucc(OldSU))
882       // Don't try to remove SU from AvailableQueue.
883       SU->isAvailable = false;
884     // FIXME: use ready cycle instead of height
885     CurCycle = OldSU->getHeight();
886     UnscheduleNodeBottomUp(OldSU);
887     AvailableQueue->setCurCycle(CurCycle);
888     if (OldSU == BtSU)
889       break;
890     OldSU = Sequence.back();
891   }
892
893   assert(!SU->isSucc(OldSU) && "Something is wrong!");
894
895   RestoreHazardCheckerBottomUp();
896
897   ReleasePending();
898
899   ++NumBacktracks;
900 }
901
902 static bool isOperandOf(const SUnit *SU, SDNode *N) {
903   for (const SDNode *SUNode = SU->getNode(); SUNode;
904        SUNode = SUNode->getGluedNode()) {
905     if (SUNode->isOperandOf(N))
906       return true;
907   }
908   return false;
909 }
910
911 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
912 /// successors to the newly created node.
913 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
914   SDNode *N = SU->getNode();
915   if (!N)
916     return NULL;
917
918   if (SU->getNode()->getGluedNode())
919     return NULL;
920
921   SUnit *NewSU;
922   bool TryUnfold = false;
923   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
924     EVT VT = N->getValueType(i);
925     if (VT == MVT::Glue)
926       return NULL;
927     else if (VT == MVT::Other)
928       TryUnfold = true;
929   }
930   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
931     const SDValue &Op = N->getOperand(i);
932     EVT VT = Op.getNode()->getValueType(Op.getResNo());
933     if (VT == MVT::Glue)
934       return NULL;
935   }
936
937   if (TryUnfold) {
938     SmallVector<SDNode*, 2> NewNodes;
939     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
940       return NULL;
941
942     // unfolding an x86 DEC64m operation results in store, dec, load which
943     // can't be handled here so quit
944     if (NewNodes.size() == 3)
945       return NULL;
946
947     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
948     assert(NewNodes.size() == 2 && "Expected a load folding node!");
949
950     N = NewNodes[1];
951     SDNode *LoadNode = NewNodes[0];
952     unsigned NumVals = N->getNumValues();
953     unsigned OldNumVals = SU->getNode()->getNumValues();
954     for (unsigned i = 0; i != NumVals; ++i)
955       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
956     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
957                                    SDValue(LoadNode, 1));
958
959     // LoadNode may already exist. This can happen when there is another
960     // load from the same location and producing the same type of value
961     // but it has different alignment or volatileness.
962     bool isNewLoad = true;
963     SUnit *LoadSU;
964     if (LoadNode->getNodeId() != -1) {
965       LoadSU = &SUnits[LoadNode->getNodeId()];
966       isNewLoad = false;
967     } else {
968       LoadSU = CreateNewSUnit(LoadNode);
969       LoadNode->setNodeId(LoadSU->NodeNum);
970
971       InitNumRegDefsLeft(LoadSU);
972       computeLatency(LoadSU);
973     }
974
975     SUnit *NewSU = CreateNewSUnit(N);
976     assert(N->getNodeId() == -1 && "Node already inserted!");
977     N->setNodeId(NewSU->NodeNum);
978
979     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
980     for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
981       if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
982         NewSU->isTwoAddress = true;
983         break;
984       }
985     }
986     if (MCID.isCommutable())
987       NewSU->isCommutable = true;
988
989     InitNumRegDefsLeft(NewSU);
990     computeLatency(NewSU);
991
992     // Record all the edges to and from the old SU, by category.
993     SmallVector<SDep, 4> ChainPreds;
994     SmallVector<SDep, 4> ChainSuccs;
995     SmallVector<SDep, 4> LoadPreds;
996     SmallVector<SDep, 4> NodePreds;
997     SmallVector<SDep, 4> NodeSuccs;
998     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
999          I != E; ++I) {
1000       if (I->isCtrl())
1001         ChainPreds.push_back(*I);
1002       else if (isOperandOf(I->getSUnit(), LoadNode))
1003         LoadPreds.push_back(*I);
1004       else
1005         NodePreds.push_back(*I);
1006     }
1007     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1008          I != E; ++I) {
1009       if (I->isCtrl())
1010         ChainSuccs.push_back(*I);
1011       else
1012         NodeSuccs.push_back(*I);
1013     }
1014
1015     // Now assign edges to the newly-created nodes.
1016     for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
1017       const SDep &Pred = ChainPreds[i];
1018       RemovePred(SU, Pred);
1019       if (isNewLoad)
1020         AddPred(LoadSU, Pred);
1021     }
1022     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
1023       const SDep &Pred = LoadPreds[i];
1024       RemovePred(SU, Pred);
1025       if (isNewLoad)
1026         AddPred(LoadSU, Pred);
1027     }
1028     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
1029       const SDep &Pred = NodePreds[i];
1030       RemovePred(SU, Pred);
1031       AddPred(NewSU, Pred);
1032     }
1033     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
1034       SDep D = NodeSuccs[i];
1035       SUnit *SuccDep = D.getSUnit();
1036       D.setSUnit(SU);
1037       RemovePred(SuccDep, D);
1038       D.setSUnit(NewSU);
1039       AddPred(SuccDep, D);
1040       // Balance register pressure.
1041       if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1042           && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1043         --NewSU->NumRegDefsLeft;
1044     }
1045     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
1046       SDep D = ChainSuccs[i];
1047       SUnit *SuccDep = D.getSUnit();
1048       D.setSUnit(SU);
1049       RemovePred(SuccDep, D);
1050       if (isNewLoad) {
1051         D.setSUnit(LoadSU);
1052         AddPred(SuccDep, D);
1053       }
1054     }
1055
1056     // Add a data dependency to reflect that NewSU reads the value defined
1057     // by LoadSU.
1058     AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
1059
1060     if (isNewLoad)
1061       AvailableQueue->addNode(LoadSU);
1062     AvailableQueue->addNode(NewSU);
1063
1064     ++NumUnfolds;
1065
1066     if (NewSU->NumSuccsLeft == 0) {
1067       NewSU->isAvailable = true;
1068       return NewSU;
1069     }
1070     SU = NewSU;
1071   }
1072
1073   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
1074   NewSU = CreateClone(SU);
1075
1076   // New SUnit has the exact same predecessors.
1077   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1078        I != E; ++I)
1079     if (!I->isArtificial())
1080       AddPred(NewSU, *I);
1081
1082   // Only copy scheduled successors. Cut them from old node's successor
1083   // list and move them over.
1084   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1085   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1086        I != E; ++I) {
1087     if (I->isArtificial())
1088       continue;
1089     SUnit *SuccSU = I->getSUnit();
1090     if (SuccSU->isScheduled) {
1091       SDep D = *I;
1092       D.setSUnit(NewSU);
1093       AddPred(SuccSU, D);
1094       D.setSUnit(SU);
1095       DelDeps.push_back(std::make_pair(SuccSU, D));
1096     }
1097   }
1098   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1099     RemovePred(DelDeps[i].first, DelDeps[i].second);
1100
1101   AvailableQueue->updateNode(SU);
1102   AvailableQueue->addNode(NewSU);
1103
1104   ++NumDups;
1105   return NewSU;
1106 }
1107
1108 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
1109 /// scheduled successors of the given SUnit to the last copy.
1110 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1111                                                const TargetRegisterClass *DestRC,
1112                                                const TargetRegisterClass *SrcRC,
1113                                                SmallVector<SUnit*, 2> &Copies) {
1114   SUnit *CopyFromSU = CreateNewSUnit(NULL);
1115   CopyFromSU->CopySrcRC = SrcRC;
1116   CopyFromSU->CopyDstRC = DestRC;
1117
1118   SUnit *CopyToSU = CreateNewSUnit(NULL);
1119   CopyToSU->CopySrcRC = DestRC;
1120   CopyToSU->CopyDstRC = SrcRC;
1121
1122   // Only copy scheduled successors. Cut them from old node's successor
1123   // list and move them over.
1124   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1125   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1126        I != E; ++I) {
1127     if (I->isArtificial())
1128       continue;
1129     SUnit *SuccSU = I->getSUnit();
1130     if (SuccSU->isScheduled) {
1131       SDep D = *I;
1132       D.setSUnit(CopyToSU);
1133       AddPred(SuccSU, D);
1134       DelDeps.push_back(std::make_pair(SuccSU, *I));
1135     }
1136     else {
1137       // Avoid scheduling the def-side copy before other successors. Otherwise
1138       // we could introduce another physreg interference on the copy and
1139       // continue inserting copies indefinitely.
1140       SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
1141              /*Reg=*/0, /*isNormalMemory=*/false,
1142              /*isMustAlias=*/false, /*isArtificial=*/true);
1143       AddPred(SuccSU, D);
1144     }
1145   }
1146   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1147     RemovePred(DelDeps[i].first, DelDeps[i].second);
1148
1149   AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1150   AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
1151
1152   AvailableQueue->updateNode(SU);
1153   AvailableQueue->addNode(CopyFromSU);
1154   AvailableQueue->addNode(CopyToSU);
1155   Copies.push_back(CopyFromSU);
1156   Copies.push_back(CopyToSU);
1157
1158   ++NumPRCopies;
1159 }
1160
1161 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
1162 /// definition of the specified node.
1163 /// FIXME: Move to SelectionDAG?
1164 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
1165                                  const TargetInstrInfo *TII) {
1166   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1167   assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1168   unsigned NumRes = MCID.getNumDefs();
1169   for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
1170     if (Reg == *ImpDef)
1171       break;
1172     ++NumRes;
1173   }
1174   return N->getValueType(NumRes);
1175 }
1176
1177 /// CheckForLiveRegDef - Return true and update live register vector if the
1178 /// specified register def of the specified SUnit clobbers any "live" registers.
1179 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
1180                                std::vector<SUnit*> &LiveRegDefs,
1181                                SmallSet<unsigned, 4> &RegAdded,
1182                                SmallVector<unsigned, 4> &LRegs,
1183                                const TargetRegisterInfo *TRI) {
1184   for (const uint16_t *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
1185
1186     // Check if Ref is live.
1187     if (!LiveRegDefs[*AliasI]) continue;
1188
1189     // Allow multiple uses of the same def.
1190     if (LiveRegDefs[*AliasI] == SU) continue;
1191
1192     // Add Reg to the set of interfering live regs.
1193     if (RegAdded.insert(*AliasI)) {
1194       LRegs.push_back(*AliasI);
1195     }
1196   }
1197 }
1198
1199 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1200 /// by RegMask, and add them to LRegs.
1201 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1202                                      std::vector<SUnit*> &LiveRegDefs,
1203                                      SmallSet<unsigned, 4> &RegAdded,
1204                                      SmallVector<unsigned, 4> &LRegs) {
1205   // Look at all live registers. Skip Reg0 and the special CallResource.
1206   for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1207     if (!LiveRegDefs[i]) continue;
1208     if (LiveRegDefs[i] == SU) continue;
1209     if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1210     if (RegAdded.insert(i))
1211       LRegs.push_back(i);
1212   }
1213 }
1214
1215 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1216 static const uint32_t *getNodeRegMask(const SDNode *N) {
1217   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1218     if (const RegisterMaskSDNode *Op =
1219         dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
1220       return Op->getRegMask();
1221   return NULL;
1222 }
1223
1224 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1225 /// scheduling of the given node to satisfy live physical register dependencies.
1226 /// If the specific node is the last one that's available to schedule, do
1227 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1228 bool ScheduleDAGRRList::
1229 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
1230   if (NumLiveRegs == 0)
1231     return false;
1232
1233   SmallSet<unsigned, 4> RegAdded;
1234   // If this node would clobber any "live" register, then it's not ready.
1235   //
1236   // If SU is the currently live definition of the same register that it uses,
1237   // then we are free to schedule it.
1238   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1239        I != E; ++I) {
1240     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1241       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1242                          RegAdded, LRegs, TRI);
1243   }
1244
1245   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1246     if (Node->getOpcode() == ISD::INLINEASM) {
1247       // Inline asm can clobber physical defs.
1248       unsigned NumOps = Node->getNumOperands();
1249       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1250         --NumOps;  // Ignore the glue operand.
1251
1252       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1253         unsigned Flags =
1254           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1255         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1256
1257         ++i; // Skip the ID value.
1258         if (InlineAsm::isRegDefKind(Flags) ||
1259             InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1260             InlineAsm::isClobberKind(Flags)) {
1261           // Check for def of register or earlyclobber register.
1262           for (; NumVals; --NumVals, ++i) {
1263             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1264             if (TargetRegisterInfo::isPhysicalRegister(Reg))
1265               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1266           }
1267         } else
1268           i += NumVals;
1269       }
1270       continue;
1271     }
1272
1273     if (!Node->isMachineOpcode())
1274       continue;
1275     // If we're in the middle of scheduling a call, don't begin scheduling
1276     // another call. Also, don't allow any physical registers to be live across
1277     // the call.
1278     if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1279       // Check the special calling-sequence resource.
1280       unsigned CallResource = TRI->getNumRegs();
1281       if (LiveRegDefs[CallResource]) {
1282         SDNode *Gen = LiveRegGens[CallResource]->getNode();
1283         while (SDNode *Glued = Gen->getGluedNode())
1284           Gen = Glued;
1285         if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
1286           LRegs.push_back(CallResource);
1287       }
1288     }
1289     if (const uint32_t *RegMask = getNodeRegMask(Node))
1290       CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
1291
1292     const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1293     if (!MCID.ImplicitDefs)
1294       continue;
1295     for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
1296       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1297   }
1298
1299   return !LRegs.empty();
1300 }
1301
1302 /// Return a node that can be scheduled in this cycle. Requirements:
1303 /// (1) Ready: latency has been satisfied
1304 /// (2) No Hazards: resources are available
1305 /// (3) No Interferences: may unschedule to break register interferences.
1306 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1307   SmallVector<SUnit*, 4> Interferences;
1308   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1309
1310   SUnit *CurSU = AvailableQueue->pop();
1311   while (CurSU) {
1312     SmallVector<unsigned, 4> LRegs;
1313     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1314       break;
1315     LRegsMap.insert(std::make_pair(CurSU, LRegs));
1316
1317     CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
1318     Interferences.push_back(CurSU);
1319     CurSU = AvailableQueue->pop();
1320   }
1321   if (CurSU) {
1322     // Add the nodes that aren't ready back onto the available list.
1323     for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1324       Interferences[i]->isPending = false;
1325       assert(Interferences[i]->isAvailable && "must still be available");
1326       AvailableQueue->push(Interferences[i]);
1327     }
1328     return CurSU;
1329   }
1330
1331   // All candidates are delayed due to live physical reg dependencies.
1332   // Try backtracking, code duplication, or inserting cross class copies
1333   // to resolve it.
1334   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1335     SUnit *TrySU = Interferences[i];
1336     SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1337
1338     // Try unscheduling up to the point where it's safe to schedule
1339     // this node.
1340     SUnit *BtSU = NULL;
1341     unsigned LiveCycle = UINT_MAX;
1342     for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1343       unsigned Reg = LRegs[j];
1344       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1345         BtSU = LiveRegGens[Reg];
1346         LiveCycle = BtSU->getHeight();
1347       }
1348     }
1349     if (!WillCreateCycle(TrySU, BtSU))  {
1350       BacktrackBottomUp(TrySU, BtSU);
1351
1352       // Force the current node to be scheduled before the node that
1353       // requires the physical reg dep.
1354       if (BtSU->isAvailable) {
1355         BtSU->isAvailable = false;
1356         if (!BtSU->isPending)
1357           AvailableQueue->remove(BtSU);
1358       }
1359       AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1360                           /*Reg=*/0, /*isNormalMemory=*/false,
1361                           /*isMustAlias=*/false, /*isArtificial=*/true));
1362
1363       // If one or more successors has been unscheduled, then the current
1364       // node is no longer avaialable. Schedule a successor that's now
1365       // available instead.
1366       if (!TrySU->isAvailable) {
1367         CurSU = AvailableQueue->pop();
1368       }
1369       else {
1370         CurSU = TrySU;
1371         TrySU->isPending = false;
1372         Interferences.erase(Interferences.begin()+i);
1373       }
1374       break;
1375     }
1376   }
1377
1378   if (!CurSU) {
1379     // Can't backtrack. If it's too expensive to copy the value, then try
1380     // duplicate the nodes that produces these "too expensive to copy"
1381     // values to break the dependency. In case even that doesn't work,
1382     // insert cross class copies.
1383     // If it's not too expensive, i.e. cost != -1, issue copies.
1384     SUnit *TrySU = Interferences[0];
1385     SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1386     assert(LRegs.size() == 1 && "Can't handle this yet!");
1387     unsigned Reg = LRegs[0];
1388     SUnit *LRDef = LiveRegDefs[Reg];
1389     EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1390     const TargetRegisterClass *RC =
1391       TRI->getMinimalPhysRegClass(Reg, VT);
1392     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1393
1394     // If cross copy register class is the same as RC, then it must be possible
1395     // copy the value directly. Do not try duplicate the def.
1396     // If cross copy register class is not the same as RC, then it's possible to
1397     // copy the value but it require cross register class copies and it is
1398     // expensive.
1399     // If cross copy register class is null, then it's not possible to copy
1400     // the value at all.
1401     SUnit *NewDef = 0;
1402     if (DestRC != RC) {
1403       NewDef = CopyAndMoveSuccessors(LRDef);
1404       if (!DestRC && !NewDef)
1405         report_fatal_error("Can't handle live physical register dependency!");
1406     }
1407     if (!NewDef) {
1408       // Issue copies, these can be expensive cross register class copies.
1409       SmallVector<SUnit*, 2> Copies;
1410       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1411       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
1412             << " to SU #" << Copies.front()->NodeNum << "\n");
1413       AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1414                           /*Reg=*/0, /*isNormalMemory=*/false,
1415                           /*isMustAlias=*/false,
1416                           /*isArtificial=*/true));
1417       NewDef = Copies.back();
1418     }
1419
1420     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
1421           << " to SU #" << TrySU->NodeNum << "\n");
1422     LiveRegDefs[Reg] = NewDef;
1423     AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1424                          /*Reg=*/0, /*isNormalMemory=*/false,
1425                          /*isMustAlias=*/false,
1426                          /*isArtificial=*/true));
1427     TrySU->isAvailable = false;
1428     CurSU = NewDef;
1429   }
1430
1431   assert(CurSU && "Unable to resolve live physical register dependencies!");
1432
1433   // Add the nodes that aren't ready back onto the available list.
1434   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1435     Interferences[i]->isPending = false;
1436     // May no longer be available due to backtracking.
1437     if (Interferences[i]->isAvailable) {
1438       AvailableQueue->push(Interferences[i]);
1439     }
1440   }
1441   return CurSU;
1442 }
1443
1444 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1445 /// schedulers.
1446 void ScheduleDAGRRList::ListScheduleBottomUp() {
1447   // Release any predecessors of the special Exit node.
1448   ReleasePredecessors(&ExitSU);
1449
1450   // Add root to Available queue.
1451   if (!SUnits.empty()) {
1452     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1453     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1454     RootSU->isAvailable = true;
1455     AvailableQueue->push(RootSU);
1456   }
1457
1458   // While Available queue is not empty, grab the node with the highest
1459   // priority. If it is not ready put it back.  Schedule the node.
1460   Sequence.reserve(SUnits.size());
1461   while (!AvailableQueue->empty()) {
1462     DEBUG(dbgs() << "\nExamining Available:\n";
1463           AvailableQueue->dump(this));
1464
1465     // Pick the best node to schedule taking all constraints into
1466     // consideration.
1467     SUnit *SU = PickNodeToScheduleBottomUp();
1468
1469     AdvancePastStalls(SU);
1470
1471     ScheduleNodeBottomUp(SU);
1472
1473     while (AvailableQueue->empty() && !PendingQueue.empty()) {
1474       // Advance the cycle to free resources. Skip ahead to the next ready SU.
1475       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1476       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1477     }
1478   }
1479
1480   // Reverse the order if it is bottom up.
1481   std::reverse(Sequence.begin(), Sequence.end());
1482
1483 #ifndef NDEBUG
1484   VerifyScheduledSequence(/*isBottomUp=*/true);
1485 #endif
1486 }
1487
1488 //===----------------------------------------------------------------------===//
1489 //                RegReductionPriorityQueue Definition
1490 //===----------------------------------------------------------------------===//
1491 //
1492 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1493 // to reduce register pressure.
1494 //
1495 namespace {
1496 class RegReductionPQBase;
1497
1498 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1499   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1500 };
1501
1502 #ifndef NDEBUG
1503 template<class SF>
1504 struct reverse_sort : public queue_sort {
1505   SF &SortFunc;
1506   reverse_sort(SF &sf) : SortFunc(sf) {}
1507   reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1508
1509   bool operator()(SUnit* left, SUnit* right) const {
1510     // reverse left/right rather than simply !SortFunc(left, right)
1511     // to expose different paths in the comparison logic.
1512     return SortFunc(right, left);
1513   }
1514 };
1515 #endif // NDEBUG
1516
1517 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1518 // reduction scheduler.
1519 struct bu_ls_rr_sort : public queue_sort {
1520   enum {
1521     IsBottomUp = true,
1522     HasReadyFilter = false
1523   };
1524
1525   RegReductionPQBase *SPQ;
1526   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1527   bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1528
1529   bool operator()(SUnit* left, SUnit* right) const;
1530 };
1531
1532 // src_ls_rr_sort - Priority function for source order scheduler.
1533 struct src_ls_rr_sort : public queue_sort {
1534   enum {
1535     IsBottomUp = true,
1536     HasReadyFilter = false
1537   };
1538
1539   RegReductionPQBase *SPQ;
1540   src_ls_rr_sort(RegReductionPQBase *spq)
1541     : SPQ(spq) {}
1542   src_ls_rr_sort(const src_ls_rr_sort &RHS)
1543     : SPQ(RHS.SPQ) {}
1544
1545   bool operator()(SUnit* left, SUnit* right) const;
1546 };
1547
1548 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1549 struct hybrid_ls_rr_sort : public queue_sort {
1550   enum {
1551     IsBottomUp = true,
1552     HasReadyFilter = false
1553   };
1554
1555   RegReductionPQBase *SPQ;
1556   hybrid_ls_rr_sort(RegReductionPQBase *spq)
1557     : SPQ(spq) {}
1558   hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1559     : SPQ(RHS.SPQ) {}
1560
1561   bool isReady(SUnit *SU, unsigned CurCycle) const;
1562
1563   bool operator()(SUnit* left, SUnit* right) const;
1564 };
1565
1566 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1567 // scheduler.
1568 struct ilp_ls_rr_sort : public queue_sort {
1569   enum {
1570     IsBottomUp = true,
1571     HasReadyFilter = false
1572   };
1573
1574   RegReductionPQBase *SPQ;
1575   ilp_ls_rr_sort(RegReductionPQBase *spq)
1576     : SPQ(spq) {}
1577   ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1578     : SPQ(RHS.SPQ) {}
1579
1580   bool isReady(SUnit *SU, unsigned CurCycle) const;
1581
1582   bool operator()(SUnit* left, SUnit* right) const;
1583 };
1584
1585 class RegReductionPQBase : public SchedulingPriorityQueue {
1586 protected:
1587   std::vector<SUnit*> Queue;
1588   unsigned CurQueueId;
1589   bool TracksRegPressure;
1590
1591   // SUnits - The SUnits for the current graph.
1592   std::vector<SUnit> *SUnits;
1593
1594   MachineFunction &MF;
1595   const TargetInstrInfo *TII;
1596   const TargetRegisterInfo *TRI;
1597   const TargetLowering *TLI;
1598   ScheduleDAGRRList *scheduleDAG;
1599
1600   // SethiUllmanNumbers - The SethiUllman number for each node.
1601   std::vector<unsigned> SethiUllmanNumbers;
1602
1603   /// RegPressure - Tracking current reg pressure per register class.
1604   ///
1605   std::vector<unsigned> RegPressure;
1606
1607   /// RegLimit - Tracking the number of allocatable registers per register
1608   /// class.
1609   std::vector<unsigned> RegLimit;
1610
1611 public:
1612   RegReductionPQBase(MachineFunction &mf,
1613                      bool hasReadyFilter,
1614                      bool tracksrp,
1615                      const TargetInstrInfo *tii,
1616                      const TargetRegisterInfo *tri,
1617                      const TargetLowering *tli)
1618     : SchedulingPriorityQueue(hasReadyFilter),
1619       CurQueueId(0), TracksRegPressure(tracksrp),
1620       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1621     if (TracksRegPressure) {
1622       unsigned NumRC = TRI->getNumRegClasses();
1623       RegLimit.resize(NumRC);
1624       RegPressure.resize(NumRC);
1625       std::fill(RegLimit.begin(), RegLimit.end(), 0);
1626       std::fill(RegPressure.begin(), RegPressure.end(), 0);
1627       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1628              E = TRI->regclass_end(); I != E; ++I)
1629         RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
1630     }
1631   }
1632
1633   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1634     scheduleDAG = scheduleDag;
1635   }
1636
1637   ScheduleHazardRecognizer* getHazardRec() {
1638     return scheduleDAG->getHazardRec();
1639   }
1640
1641   void initNodes(std::vector<SUnit> &sunits);
1642
1643   void addNode(const SUnit *SU);
1644
1645   void updateNode(const SUnit *SU);
1646
1647   void releaseState() {
1648     SUnits = 0;
1649     SethiUllmanNumbers.clear();
1650     std::fill(RegPressure.begin(), RegPressure.end(), 0);
1651   }
1652
1653   unsigned getNodePriority(const SUnit *SU) const;
1654
1655   unsigned getNodeOrdering(const SUnit *SU) const {
1656     if (!SU->getNode()) return 0;
1657
1658     return scheduleDAG->DAG->GetOrdering(SU->getNode());
1659   }
1660
1661   bool empty() const { return Queue.empty(); }
1662
1663   void push(SUnit *U) {
1664     assert(!U->NodeQueueId && "Node in the queue already");
1665     U->NodeQueueId = ++CurQueueId;
1666     Queue.push_back(U);
1667   }
1668
1669   void remove(SUnit *SU) {
1670     assert(!Queue.empty() && "Queue is empty!");
1671     assert(SU->NodeQueueId != 0 && "Not in queue!");
1672     std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1673                                                  SU);
1674     if (I != prior(Queue.end()))
1675       std::swap(*I, Queue.back());
1676     Queue.pop_back();
1677     SU->NodeQueueId = 0;
1678   }
1679
1680   bool tracksRegPressure() const { return TracksRegPressure; }
1681
1682   void dumpRegPressure() const;
1683
1684   bool HighRegPressure(const SUnit *SU) const;
1685
1686   bool MayReduceRegPressure(SUnit *SU) const;
1687
1688   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1689
1690   void scheduledNode(SUnit *SU);
1691
1692   void unscheduledNode(SUnit *SU);
1693
1694 protected:
1695   bool canClobber(const SUnit *SU, const SUnit *Op);
1696   void AddPseudoTwoAddrDeps();
1697   void PrescheduleNodesWithMultipleUses();
1698   void CalculateSethiUllmanNumbers();
1699 };
1700
1701 template<class SF>
1702 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1703   std::vector<SUnit *>::iterator Best = Q.begin();
1704   for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1705          E = Q.end(); I != E; ++I)
1706     if (Picker(*Best, *I))
1707       Best = I;
1708   SUnit *V = *Best;
1709   if (Best != prior(Q.end()))
1710     std::swap(*Best, Q.back());
1711   Q.pop_back();
1712   return V;
1713 }
1714
1715 template<class SF>
1716 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1717 #ifndef NDEBUG
1718   if (DAG->StressSched) {
1719     reverse_sort<SF> RPicker(Picker);
1720     return popFromQueueImpl(Q, RPicker);
1721   }
1722 #endif
1723   (void)DAG;
1724   return popFromQueueImpl(Q, Picker);
1725 }
1726
1727 template<class SF>
1728 class RegReductionPriorityQueue : public RegReductionPQBase {
1729   SF Picker;
1730
1731 public:
1732   RegReductionPriorityQueue(MachineFunction &mf,
1733                             bool tracksrp,
1734                             const TargetInstrInfo *tii,
1735                             const TargetRegisterInfo *tri,
1736                             const TargetLowering *tli)
1737     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1738       Picker(this) {}
1739
1740   bool isBottomUp() const { return SF::IsBottomUp; }
1741
1742   bool isReady(SUnit *U) const {
1743     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1744   }
1745
1746   SUnit *pop() {
1747     if (Queue.empty()) return NULL;
1748
1749     SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
1750     V->NodeQueueId = 0;
1751     return V;
1752   }
1753
1754   void dump(ScheduleDAG *DAG) const {
1755     // Emulate pop() without clobbering NodeQueueIds.
1756     std::vector<SUnit*> DumpQueue = Queue;
1757     SF DumpPicker = Picker;
1758     while (!DumpQueue.empty()) {
1759       SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1760       dbgs() << "Height " << SU->getHeight() << ": ";
1761       SU->dump(DAG);
1762     }
1763   }
1764 };
1765
1766 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1767 BURegReductionPriorityQueue;
1768
1769 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1770 SrcRegReductionPriorityQueue;
1771
1772 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1773 HybridBURRPriorityQueue;
1774
1775 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1776 ILPBURRPriorityQueue;
1777 } // end anonymous namespace
1778
1779 //===----------------------------------------------------------------------===//
1780 //           Static Node Priority for Register Pressure Reduction
1781 //===----------------------------------------------------------------------===//
1782
1783 // Check for special nodes that bypass scheduling heuristics.
1784 // Currently this pushes TokenFactor nodes down, but may be used for other
1785 // pseudo-ops as well.
1786 //
1787 // Return -1 to schedule right above left, 1 for left above right.
1788 // Return 0 if no bias exists.
1789 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1790   bool LSchedLow = left->isScheduleLow;
1791   bool RSchedLow = right->isScheduleLow;
1792   if (LSchedLow != RSchedLow)
1793     return LSchedLow < RSchedLow ? 1 : -1;
1794   return 0;
1795 }
1796
1797 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1798 /// Smaller number is the higher priority.
1799 static unsigned
1800 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1801   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1802   if (SethiUllmanNumber != 0)
1803     return SethiUllmanNumber;
1804
1805   unsigned Extra = 0;
1806   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1807        I != E; ++I) {
1808     if (I->isCtrl()) continue;  // ignore chain preds
1809     SUnit *PredSU = I->getSUnit();
1810     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1811     if (PredSethiUllman > SethiUllmanNumber) {
1812       SethiUllmanNumber = PredSethiUllman;
1813       Extra = 0;
1814     } else if (PredSethiUllman == SethiUllmanNumber)
1815       ++Extra;
1816   }
1817
1818   SethiUllmanNumber += Extra;
1819
1820   if (SethiUllmanNumber == 0)
1821     SethiUllmanNumber = 1;
1822
1823   return SethiUllmanNumber;
1824 }
1825
1826 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1827 /// scheduling units.
1828 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1829   SethiUllmanNumbers.assign(SUnits->size(), 0);
1830
1831   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1832     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1833 }
1834
1835 void RegReductionPQBase::addNode(const SUnit *SU) {
1836   unsigned SUSize = SethiUllmanNumbers.size();
1837   if (SUnits->size() > SUSize)
1838     SethiUllmanNumbers.resize(SUSize*2, 0);
1839   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1840 }
1841
1842 void RegReductionPQBase::updateNode(const SUnit *SU) {
1843   SethiUllmanNumbers[SU->NodeNum] = 0;
1844   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1845 }
1846
1847 // Lower priority means schedule further down. For bottom-up scheduling, lower
1848 // priority SUs are scheduled before higher priority SUs.
1849 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1850   assert(SU->NodeNum < SethiUllmanNumbers.size());
1851   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1852   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1853     // CopyToReg should be close to its uses to facilitate coalescing and
1854     // avoid spilling.
1855     return 0;
1856   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1857       Opc == TargetOpcode::SUBREG_TO_REG ||
1858       Opc == TargetOpcode::INSERT_SUBREG)
1859     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1860     // close to their uses to facilitate coalescing.
1861     return 0;
1862   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1863     // If SU does not have a register use, i.e. it doesn't produce a value
1864     // that would be consumed (e.g. store), then it terminates a chain of
1865     // computation.  Give it a large SethiUllman number so it will be
1866     // scheduled right before its predecessors that it doesn't lengthen
1867     // their live ranges.
1868     return 0xffff;
1869   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1870     // If SU does not have a register def, schedule it close to its uses
1871     // because it does not lengthen any live ranges.
1872     return 0;
1873 #if 1
1874   return SethiUllmanNumbers[SU->NodeNum];
1875 #else
1876   unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1877   if (SU->isCallOp) {
1878     // FIXME: This assumes all of the defs are used as call operands.
1879     int NP = (int)Priority - SU->getNode()->getNumValues();
1880     return (NP > 0) ? NP : 0;
1881   }
1882   return Priority;
1883 #endif
1884 }
1885
1886 //===----------------------------------------------------------------------===//
1887 //                     Register Pressure Tracking
1888 //===----------------------------------------------------------------------===//
1889
1890 void RegReductionPQBase::dumpRegPressure() const {
1891   for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1892          E = TRI->regclass_end(); I != E; ++I) {
1893     const TargetRegisterClass *RC = *I;
1894     unsigned Id = RC->getID();
1895     unsigned RP = RegPressure[Id];
1896     if (!RP) continue;
1897     DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1898           << '\n');
1899   }
1900 }
1901
1902 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1903   if (!TLI)
1904     return false;
1905
1906   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1907        I != E; ++I) {
1908     if (I->isCtrl())
1909       continue;
1910     SUnit *PredSU = I->getSUnit();
1911     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1912     // to cover the number of registers defined (they are all live).
1913     if (PredSU->NumRegDefsLeft == 0) {
1914       continue;
1915     }
1916     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1917          RegDefPos.IsValid(); RegDefPos.Advance()) {
1918       unsigned RCId, Cost;
1919       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1920
1921       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1922         return true;
1923     }
1924   }
1925   return false;
1926 }
1927
1928 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1929   const SDNode *N = SU->getNode();
1930
1931   if (!N->isMachineOpcode() || !SU->NumSuccs)
1932     return false;
1933
1934   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1935   for (unsigned i = 0; i != NumDefs; ++i) {
1936     EVT VT = N->getValueType(i);
1937     if (!N->hasAnyUseOfValue(i))
1938       continue;
1939     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1940     if (RegPressure[RCId] >= RegLimit[RCId])
1941       return true;
1942   }
1943   return false;
1944 }
1945
1946 // Compute the register pressure contribution by this instruction by count up
1947 // for uses that are not live and down for defs. Only count register classes
1948 // that are already under high pressure. As a side effect, compute the number of
1949 // uses of registers that are already live.
1950 //
1951 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1952 // so could probably be factored.
1953 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1954   LiveUses = 0;
1955   int PDiff = 0;
1956   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1957        I != E; ++I) {
1958     if (I->isCtrl())
1959       continue;
1960     SUnit *PredSU = I->getSUnit();
1961     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1962     // to cover the number of registers defined (they are all live).
1963     if (PredSU->NumRegDefsLeft == 0) {
1964       if (PredSU->getNode()->isMachineOpcode())
1965         ++LiveUses;
1966       continue;
1967     }
1968     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1969          RegDefPos.IsValid(); RegDefPos.Advance()) {
1970       EVT VT = RegDefPos.GetValue();
1971       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1972       if (RegPressure[RCId] >= RegLimit[RCId])
1973         ++PDiff;
1974     }
1975   }
1976   const SDNode *N = SU->getNode();
1977
1978   if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
1979     return PDiff;
1980
1981   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1982   for (unsigned i = 0; i != NumDefs; ++i) {
1983     EVT VT = N->getValueType(i);
1984     if (!N->hasAnyUseOfValue(i))
1985       continue;
1986     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1987     if (RegPressure[RCId] >= RegLimit[RCId])
1988       --PDiff;
1989   }
1990   return PDiff;
1991 }
1992
1993 void RegReductionPQBase::scheduledNode(SUnit *SU) {
1994   if (!TracksRegPressure)
1995     return;
1996
1997   if (!SU->getNode())
1998     return;
1999
2000   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2001        I != E; ++I) {
2002     if (I->isCtrl())
2003       continue;
2004     SUnit *PredSU = I->getSUnit();
2005     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2006     // to cover the number of registers defined (they are all live).
2007     if (PredSU->NumRegDefsLeft == 0) {
2008       continue;
2009     }
2010     // FIXME: The ScheduleDAG currently loses information about which of a
2011     // node's values is consumed by each dependence. Consequently, if the node
2012     // defines multiple register classes, we don't know which to pressurize
2013     // here. Instead the following loop consumes the register defs in an
2014     // arbitrary order. At least it handles the common case of clustered loads
2015     // to the same class. For precise liveness, each SDep needs to indicate the
2016     // result number. But that tightly couples the ScheduleDAG with the
2017     // SelectionDAG making updates tricky. A simpler hack would be to attach a
2018     // value type or register class to SDep.
2019     //
2020     // The most important aspect of register tracking is balancing the increase
2021     // here with the reduction further below. Note that this SU may use multiple
2022     // defs in PredSU. The can't be determined here, but we've already
2023     // compensated by reducing NumRegDefsLeft in PredSU during
2024     // ScheduleDAGSDNodes::AddSchedEdges.
2025     --PredSU->NumRegDefsLeft;
2026     unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2027     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2028          RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2029       if (SkipRegDefs)
2030         continue;
2031
2032       unsigned RCId, Cost;
2033       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
2034       RegPressure[RCId] += Cost;
2035       break;
2036     }
2037   }
2038
2039   // We should have this assert, but there may be dead SDNodes that never
2040   // materialize as SUnits, so they don't appear to generate liveness.
2041   //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2042   int SkipRegDefs = (int)SU->NumRegDefsLeft;
2043   for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2044        RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2045     if (SkipRegDefs > 0)
2046       continue;
2047     unsigned RCId, Cost;
2048     GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
2049     if (RegPressure[RCId] < Cost) {
2050       // Register pressure tracking is imprecise. This can happen. But we try
2051       // hard not to let it happen because it likely results in poor scheduling.
2052       DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") has too many regdefs\n");
2053       RegPressure[RCId] = 0;
2054     }
2055     else {
2056       RegPressure[RCId] -= Cost;
2057     }
2058   }
2059   dumpRegPressure();
2060 }
2061
2062 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2063   if (!TracksRegPressure)
2064     return;
2065
2066   const SDNode *N = SU->getNode();
2067   if (!N) return;
2068
2069   if (!N->isMachineOpcode()) {
2070     if (N->getOpcode() != ISD::CopyToReg)
2071       return;
2072   } else {
2073     unsigned Opc = N->getMachineOpcode();
2074     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2075         Opc == TargetOpcode::INSERT_SUBREG ||
2076         Opc == TargetOpcode::SUBREG_TO_REG ||
2077         Opc == TargetOpcode::REG_SEQUENCE ||
2078         Opc == TargetOpcode::IMPLICIT_DEF)
2079       return;
2080   }
2081
2082   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2083        I != E; ++I) {
2084     if (I->isCtrl())
2085       continue;
2086     SUnit *PredSU = I->getSUnit();
2087     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2088     // counts data deps.
2089     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
2090       continue;
2091     const SDNode *PN = PredSU->getNode();
2092     if (!PN->isMachineOpcode()) {
2093       if (PN->getOpcode() == ISD::CopyFromReg) {
2094         EVT VT = PN->getValueType(0);
2095         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2096         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2097       }
2098       continue;
2099     }
2100     unsigned POpc = PN->getMachineOpcode();
2101     if (POpc == TargetOpcode::IMPLICIT_DEF)
2102       continue;
2103     if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2104         POpc == TargetOpcode::INSERT_SUBREG ||
2105         POpc == TargetOpcode::SUBREG_TO_REG) {
2106       EVT VT = PN->getValueType(0);
2107       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2108       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2109       continue;
2110     }
2111     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2112     for (unsigned i = 0; i != NumDefs; ++i) {
2113       EVT VT = PN->getValueType(i);
2114       if (!PN->hasAnyUseOfValue(i))
2115         continue;
2116       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2117       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2118         // Register pressure tracking is imprecise. This can happen.
2119         RegPressure[RCId] = 0;
2120       else
2121         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2122     }
2123   }
2124
2125   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2126   // may transfer data dependencies to CopyToReg.
2127   if (SU->NumSuccs && N->isMachineOpcode()) {
2128     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2129     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2130       EVT VT = N->getValueType(i);
2131       if (VT == MVT::Glue || VT == MVT::Other)
2132         continue;
2133       if (!N->hasAnyUseOfValue(i))
2134         continue;
2135       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2136       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2137     }
2138   }
2139
2140   dumpRegPressure();
2141 }
2142
2143 //===----------------------------------------------------------------------===//
2144 //           Dynamic Node Priority for Register Pressure Reduction
2145 //===----------------------------------------------------------------------===//
2146
2147 /// closestSucc - Returns the scheduled cycle of the successor which is
2148 /// closest to the current cycle.
2149 static unsigned closestSucc(const SUnit *SU) {
2150   unsigned MaxHeight = 0;
2151   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2152        I != E; ++I) {
2153     if (I->isCtrl()) continue;  // ignore chain succs
2154     unsigned Height = I->getSUnit()->getHeight();
2155     // If there are bunch of CopyToRegs stacked up, they should be considered
2156     // to be at the same position.
2157     if (I->getSUnit()->getNode() &&
2158         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2159       Height = closestSucc(I->getSUnit())+1;
2160     if (Height > MaxHeight)
2161       MaxHeight = Height;
2162   }
2163   return MaxHeight;
2164 }
2165
2166 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
2167 /// for scratch registers, i.e. number of data dependencies.
2168 static unsigned calcMaxScratches(const SUnit *SU) {
2169   unsigned Scratches = 0;
2170   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2171        I != E; ++I) {
2172     if (I->isCtrl()) continue;  // ignore chain preds
2173     Scratches++;
2174   }
2175   return Scratches;
2176 }
2177
2178 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2179 /// CopyFromReg from a virtual register.
2180 static bool hasOnlyLiveInOpers(const SUnit *SU) {
2181   bool RetVal = false;
2182   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2183        I != E; ++I) {
2184     if (I->isCtrl()) continue;
2185     const SUnit *PredSU = I->getSUnit();
2186     if (PredSU->getNode() &&
2187         PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2188       unsigned Reg =
2189         cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2190       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2191         RetVal = true;
2192         continue;
2193       }
2194     }
2195     return false;
2196   }
2197   return RetVal;
2198 }
2199
2200 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
2201 /// CopyToReg to a virtual register. This SU def is probably a liveout and
2202 /// it has no other use. It should be scheduled closer to the terminator.
2203 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2204   bool RetVal = false;
2205   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2206        I != E; ++I) {
2207     if (I->isCtrl()) continue;
2208     const SUnit *SuccSU = I->getSUnit();
2209     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2210       unsigned Reg =
2211         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2212       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2213         RetVal = true;
2214         continue;
2215       }
2216     }
2217     return false;
2218   }
2219   return RetVal;
2220 }
2221
2222 // Set isVRegCycle for a node with only live in opers and live out uses. Also
2223 // set isVRegCycle for its CopyFromReg operands.
2224 //
2225 // This is only relevant for single-block loops, in which case the VRegCycle
2226 // node is likely an induction variable in which the operand and target virtual
2227 // registers should be coalesced (e.g. pre/post increment values). Setting the
2228 // isVRegCycle flag helps the scheduler prioritize other uses of the same
2229 // CopyFromReg so that this node becomes the virtual register "kill". This
2230 // avoids interference between the values live in and out of the block and
2231 // eliminates a copy inside the loop.
2232 static void initVRegCycle(SUnit *SU) {
2233   if (DisableSchedVRegCycle)
2234     return;
2235
2236   if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2237     return;
2238
2239   DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2240
2241   SU->isVRegCycle = true;
2242
2243   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2244        I != E; ++I) {
2245     if (I->isCtrl()) continue;
2246     I->getSUnit()->isVRegCycle = true;
2247   }
2248 }
2249
2250 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2251 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
2252 static void resetVRegCycle(SUnit *SU) {
2253   if (!SU->isVRegCycle)
2254     return;
2255
2256   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2257        I != E; ++I) {
2258     if (I->isCtrl()) continue;  // ignore chain preds
2259     SUnit *PredSU = I->getSUnit();
2260     if (PredSU->isVRegCycle) {
2261       assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2262              "VRegCycle def must be CopyFromReg");
2263       I->getSUnit()->isVRegCycle = 0;
2264     }
2265   }
2266 }
2267
2268 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2269 // means a node that defines the VRegCycle has not been scheduled yet.
2270 static bool hasVRegCycleUse(const SUnit *SU) {
2271   // If this SU also defines the VReg, don't hoist it as a "use".
2272   if (SU->isVRegCycle)
2273     return false;
2274
2275   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2276        I != E; ++I) {
2277     if (I->isCtrl()) continue;  // ignore chain preds
2278     if (I->getSUnit()->isVRegCycle &&
2279         I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2280       DEBUG(dbgs() << "  VReg cycle use: SU (" << SU->NodeNum << ")\n");
2281       return true;
2282     }
2283   }
2284   return false;
2285 }
2286
2287 // Check for either a dependence (latency) or resource (hazard) stall.
2288 //
2289 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2290 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2291   if ((int)SPQ->getCurCycle() < Height) return true;
2292   if (SPQ->getHazardRec()->getHazardType(SU, 0)
2293       != ScheduleHazardRecognizer::NoHazard)
2294     return true;
2295   return false;
2296 }
2297
2298 // Return -1 if left has higher priority, 1 if right has higher priority.
2299 // Return 0 if latency-based priority is equivalent.
2300 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2301                             RegReductionPQBase *SPQ) {
2302   // Scheduling an instruction that uses a VReg whose postincrement has not yet
2303   // been scheduled will induce a copy. Model this as an extra cycle of latency.
2304   int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2305   int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2306   int LHeight = (int)left->getHeight() + LPenalty;
2307   int RHeight = (int)right->getHeight() + RPenalty;
2308
2309   bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
2310     BUHasStall(left, LHeight, SPQ);
2311   bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
2312     BUHasStall(right, RHeight, SPQ);
2313
2314   // If scheduling one of the node will cause a pipeline stall, delay it.
2315   // If scheduling either one of the node will cause a pipeline stall, sort
2316   // them according to their height.
2317   if (LStall) {
2318     if (!RStall)
2319       return 1;
2320     if (LHeight != RHeight)
2321       return LHeight > RHeight ? 1 : -1;
2322   } else if (RStall)
2323     return -1;
2324
2325   // If either node is scheduling for latency, sort them by height/depth
2326   // and latency.
2327   if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2328                      right->SchedulingPref == Sched::ILP)) {
2329     if (DisableSchedCycles) {
2330       if (LHeight != RHeight)
2331         return LHeight > RHeight ? 1 : -1;
2332     }
2333     else {
2334       // If neither instruction stalls (!LStall && !RStall) then
2335       // its height is already covered so only its depth matters. We also reach
2336       // this if both stall but have the same height.
2337       int LDepth = left->getDepth() - LPenalty;
2338       int RDepth = right->getDepth() - RPenalty;
2339       if (LDepth != RDepth) {
2340         DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
2341               << ") depth " << LDepth << " vs SU (" << right->NodeNum
2342               << ") depth " << RDepth << "\n");
2343         return LDepth < RDepth ? 1 : -1;
2344       }
2345     }
2346     if (left->Latency != right->Latency)
2347       return left->Latency > right->Latency ? 1 : -1;
2348   }
2349   return 0;
2350 }
2351
2352 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2353   // Schedule physical register definitions close to their use. This is
2354   // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2355   // long as shortening physreg live ranges is generally good, we can defer
2356   // creating a subtarget hook.
2357   if (!DisableSchedPhysRegJoin) {
2358     bool LHasPhysReg = left->hasPhysRegDefs;
2359     bool RHasPhysReg = right->hasPhysRegDefs;
2360     if (LHasPhysReg != RHasPhysReg) {
2361       #ifndef NDEBUG
2362       const char *PhysRegMsg[] = {" has no physreg", " defines a physreg"};
2363       #endif
2364       DEBUG(dbgs() << "  SU (" << left->NodeNum << ") "
2365             << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2366             << PhysRegMsg[RHasPhysReg] << "\n");
2367       return LHasPhysReg < RHasPhysReg;
2368     }
2369   }
2370
2371   // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
2372   unsigned LPriority = SPQ->getNodePriority(left);
2373   unsigned RPriority = SPQ->getNodePriority(right);
2374
2375   // Be really careful about hoisting call operands above previous calls.
2376   // Only allows it if it would reduce register pressure.
2377   if (left->isCall && right->isCallOp) {
2378     unsigned RNumVals = right->getNode()->getNumValues();
2379     RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2380   }
2381   if (right->isCall && left->isCallOp) {
2382     unsigned LNumVals = left->getNode()->getNumValues();
2383     LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2384   }
2385
2386   if (LPriority != RPriority)
2387     return LPriority > RPriority;
2388
2389   // One or both of the nodes are calls and their sethi-ullman numbers are the
2390   // same, then keep source order.
2391   if (left->isCall || right->isCall) {
2392     unsigned LOrder = SPQ->getNodeOrdering(left);
2393     unsigned ROrder = SPQ->getNodeOrdering(right);
2394
2395     // Prefer an ordering where the lower the non-zero order number, the higher
2396     // the preference.
2397     if ((LOrder || ROrder) && LOrder != ROrder)
2398       return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2399   }
2400
2401   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2402   // e.g.
2403   // t1 = op t2, c1
2404   // t3 = op t4, c2
2405   //
2406   // and the following instructions are both ready.
2407   // t2 = op c3
2408   // t4 = op c4
2409   //
2410   // Then schedule t2 = op first.
2411   // i.e.
2412   // t4 = op c4
2413   // t2 = op c3
2414   // t1 = op t2, c1
2415   // t3 = op t4, c2
2416   //
2417   // This creates more short live intervals.
2418   unsigned LDist = closestSucc(left);
2419   unsigned RDist = closestSucc(right);
2420   if (LDist != RDist)
2421     return LDist < RDist;
2422
2423   // How many registers becomes live when the node is scheduled.
2424   unsigned LScratch = calcMaxScratches(left);
2425   unsigned RScratch = calcMaxScratches(right);
2426   if (LScratch != RScratch)
2427     return LScratch > RScratch;
2428
2429   // Comparing latency against a call makes little sense unless the node
2430   // is register pressure-neutral.
2431   if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2432     return (left->NodeQueueId > right->NodeQueueId);
2433
2434   // Do not compare latencies when one or both of the nodes are calls.
2435   if (!DisableSchedCycles &&
2436       !(left->isCall || right->isCall)) {
2437     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2438     if (result != 0)
2439       return result > 0;
2440   }
2441   else {
2442     if (left->getHeight() != right->getHeight())
2443       return left->getHeight() > right->getHeight();
2444
2445     if (left->getDepth() != right->getDepth())
2446       return left->getDepth() < right->getDepth();
2447   }
2448
2449   assert(left->NodeQueueId && right->NodeQueueId &&
2450          "NodeQueueId cannot be zero");
2451   return (left->NodeQueueId > right->NodeQueueId);
2452 }
2453
2454 // Bottom up
2455 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2456   if (int res = checkSpecialNodes(left, right))
2457     return res > 0;
2458
2459   return BURRSort(left, right, SPQ);
2460 }
2461
2462 // Source order, otherwise bottom up.
2463 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2464   if (int res = checkSpecialNodes(left, right))
2465     return res > 0;
2466
2467   unsigned LOrder = SPQ->getNodeOrdering(left);
2468   unsigned ROrder = SPQ->getNodeOrdering(right);
2469
2470   // Prefer an ordering where the lower the non-zero order number, the higher
2471   // the preference.
2472   if ((LOrder || ROrder) && LOrder != ROrder)
2473     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2474
2475   return BURRSort(left, right, SPQ);
2476 }
2477
2478 // If the time between now and when the instruction will be ready can cover
2479 // the spill code, then avoid adding it to the ready queue. This gives long
2480 // stalls highest priority and allows hoisting across calls. It should also
2481 // speed up processing the available queue.
2482 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2483   static const unsigned ReadyDelay = 3;
2484
2485   if (SPQ->MayReduceRegPressure(SU)) return true;
2486
2487   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2488
2489   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2490       != ScheduleHazardRecognizer::NoHazard)
2491     return false;
2492
2493   return true;
2494 }
2495
2496 // Return true if right should be scheduled with higher priority than left.
2497 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2498   if (int res = checkSpecialNodes(left, right))
2499     return res > 0;
2500
2501   if (left->isCall || right->isCall)
2502     // No way to compute latency of calls.
2503     return BURRSort(left, right, SPQ);
2504
2505   bool LHigh = SPQ->HighRegPressure(left);
2506   bool RHigh = SPQ->HighRegPressure(right);
2507   // Avoid causing spills. If register pressure is high, schedule for
2508   // register pressure reduction.
2509   if (LHigh && !RHigh) {
2510     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
2511           << right->NodeNum << ")\n");
2512     return true;
2513   }
2514   else if (!LHigh && RHigh) {
2515     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
2516           << left->NodeNum << ")\n");
2517     return false;
2518   }
2519   if (!LHigh && !RHigh) {
2520     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2521     if (result != 0)
2522       return result > 0;
2523   }
2524   return BURRSort(left, right, SPQ);
2525 }
2526
2527 // Schedule as many instructions in each cycle as possible. So don't make an
2528 // instruction available unless it is ready in the current cycle.
2529 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2530   if (SU->getHeight() > CurCycle) return false;
2531
2532   if (SPQ->getHazardRec()->getHazardType(SU, 0)
2533       != ScheduleHazardRecognizer::NoHazard)
2534     return false;
2535
2536   return true;
2537 }
2538
2539 static bool canEnableCoalescing(SUnit *SU) {
2540   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2541   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2542     // CopyToReg should be close to its uses to facilitate coalescing and
2543     // avoid spilling.
2544     return true;
2545
2546   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2547       Opc == TargetOpcode::SUBREG_TO_REG ||
2548       Opc == TargetOpcode::INSERT_SUBREG)
2549     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2550     // close to their uses to facilitate coalescing.
2551     return true;
2552
2553   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2554     // If SU does not have a register def, schedule it close to its uses
2555     // because it does not lengthen any live ranges.
2556     return true;
2557
2558   return false;
2559 }
2560
2561 // list-ilp is currently an experimental scheduler that allows various
2562 // heuristics to be enabled prior to the normal register reduction logic.
2563 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2564   if (int res = checkSpecialNodes(left, right))
2565     return res > 0;
2566
2567   if (left->isCall || right->isCall)
2568     // No way to compute latency of calls.
2569     return BURRSort(left, right, SPQ);
2570
2571   unsigned LLiveUses = 0, RLiveUses = 0;
2572   int LPDiff = 0, RPDiff = 0;
2573   if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2574     LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2575     RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2576   }
2577   if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2578     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2579           << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2580     return LPDiff > RPDiff;
2581   }
2582
2583   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2584     bool LReduce = canEnableCoalescing(left);
2585     bool RReduce = canEnableCoalescing(right);
2586     if (LReduce && !RReduce) return false;
2587     if (RReduce && !LReduce) return true;
2588   }
2589
2590   if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2591     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2592           << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2593     return LLiveUses < RLiveUses;
2594   }
2595
2596   if (!DisableSchedStalls) {
2597     bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2598     bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2599     if (LStall != RStall)
2600       return left->getHeight() > right->getHeight();
2601   }
2602
2603   if (!DisableSchedCriticalPath) {
2604     int spread = (int)left->getDepth() - (int)right->getDepth();
2605     if (std::abs(spread) > MaxReorderWindow) {
2606       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2607             << left->getDepth() << " != SU(" << right->NodeNum << "): "
2608             << right->getDepth() << "\n");
2609       return left->getDepth() < right->getDepth();
2610     }
2611   }
2612
2613   if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2614     int spread = (int)left->getHeight() - (int)right->getHeight();
2615     if (std::abs(spread) > MaxReorderWindow)
2616       return left->getHeight() > right->getHeight();
2617   }
2618
2619   return BURRSort(left, right, SPQ);
2620 }
2621
2622 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2623   SUnits = &sunits;
2624   // Add pseudo dependency edges for two-address nodes.
2625   if (!Disable2AddrHack)
2626     AddPseudoTwoAddrDeps();
2627   // Reroute edges to nodes with multiple uses.
2628   if (!TracksRegPressure)
2629     PrescheduleNodesWithMultipleUses();
2630   // Calculate node priorities.
2631   CalculateSethiUllmanNumbers();
2632
2633   // For single block loops, mark nodes that look like canonical IV increments.
2634   if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2635     for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2636       initVRegCycle(&sunits[i]);
2637     }
2638   }
2639 }
2640
2641 //===----------------------------------------------------------------------===//
2642 //                    Preschedule for Register Pressure
2643 //===----------------------------------------------------------------------===//
2644
2645 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2646   if (SU->isTwoAddress) {
2647     unsigned Opc = SU->getNode()->getMachineOpcode();
2648     const MCInstrDesc &MCID = TII->get(Opc);
2649     unsigned NumRes = MCID.getNumDefs();
2650     unsigned NumOps = MCID.getNumOperands() - NumRes;
2651     for (unsigned i = 0; i != NumOps; ++i) {
2652       if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
2653         SDNode *DU = SU->getNode()->getOperand(i).getNode();
2654         if (DU->getNodeId() != -1 &&
2655             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2656           return true;
2657       }
2658     }
2659   }
2660   return false;
2661 }
2662
2663 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2664 /// successor's explicit physregs whose definition can reach DepSU.
2665 /// i.e. DepSU should not be scheduled above SU.
2666 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2667                                          ScheduleDAGRRList *scheduleDAG,
2668                                          const TargetInstrInfo *TII,
2669                                          const TargetRegisterInfo *TRI) {
2670   const uint16_t *ImpDefs
2671     = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
2672   const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2673   if(!ImpDefs && !RegMask)
2674     return false;
2675
2676   for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
2677        SI != SE; ++SI) {
2678     SUnit *SuccSU = SI->getSUnit();
2679     for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
2680            PE = SuccSU->Preds.end(); PI != PE; ++PI) {
2681       if (!PI->isAssignedRegDep())
2682         continue;
2683
2684       if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
2685           scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2686         return true;
2687
2688       if (ImpDefs)
2689         for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
2690           // Return true if SU clobbers this physical register use and the
2691           // definition of the register reaches from DepSU. IsReachable queries
2692           // a topological forward sort of the DAG (following the successors).
2693           if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
2694               scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2695             return true;
2696     }
2697   }
2698   return false;
2699 }
2700
2701 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2702 /// physical register defs.
2703 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2704                                   const TargetInstrInfo *TII,
2705                                   const TargetRegisterInfo *TRI) {
2706   SDNode *N = SuccSU->getNode();
2707   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2708   const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2709   assert(ImpDefs && "Caller should check hasPhysRegDefs");
2710   for (const SDNode *SUNode = SU->getNode(); SUNode;
2711        SUNode = SUNode->getGluedNode()) {
2712     if (!SUNode->isMachineOpcode())
2713       continue;
2714     const uint16_t *SUImpDefs =
2715       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2716     const uint32_t *SURegMask = getNodeRegMask(SUNode);
2717     if (!SUImpDefs && !SURegMask)
2718       continue;
2719     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2720       EVT VT = N->getValueType(i);
2721       if (VT == MVT::Glue || VT == MVT::Other)
2722         continue;
2723       if (!N->hasAnyUseOfValue(i))
2724         continue;
2725       unsigned Reg = ImpDefs[i - NumDefs];
2726       if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2727         return true;
2728       if (!SUImpDefs)
2729         continue;
2730       for (;*SUImpDefs; ++SUImpDefs) {
2731         unsigned SUReg = *SUImpDefs;
2732         if (TRI->regsOverlap(Reg, SUReg))
2733           return true;
2734       }
2735     }
2736   }
2737   return false;
2738 }
2739
2740 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2741 /// are not handled well by the general register pressure reduction
2742 /// heuristics. When presented with code like this:
2743 ///
2744 ///      N
2745 ///    / |
2746 ///   /  |
2747 ///  U  store
2748 ///  |
2749 /// ...
2750 ///
2751 /// the heuristics tend to push the store up, but since the
2752 /// operand of the store has another use (U), this would increase
2753 /// the length of that other use (the U->N edge).
2754 ///
2755 /// This function transforms code like the above to route U's
2756 /// dependence through the store when possible, like this:
2757 ///
2758 ///      N
2759 ///      ||
2760 ///      ||
2761 ///     store
2762 ///       |
2763 ///       U
2764 ///       |
2765 ///      ...
2766 ///
2767 /// This results in the store being scheduled immediately
2768 /// after N, which shortens the U->N live range, reducing
2769 /// register pressure.
2770 ///
2771 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2772   // Visit all the nodes in topological order, working top-down.
2773   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2774     SUnit *SU = &(*SUnits)[i];
2775     // For now, only look at nodes with no data successors, such as stores.
2776     // These are especially important, due to the heuristics in
2777     // getNodePriority for nodes with no data successors.
2778     if (SU->NumSuccs != 0)
2779       continue;
2780     // For now, only look at nodes with exactly one data predecessor.
2781     if (SU->NumPreds != 1)
2782       continue;
2783     // Avoid prescheduling copies to virtual registers, which don't behave
2784     // like other nodes from the perspective of scheduling heuristics.
2785     if (SDNode *N = SU->getNode())
2786       if (N->getOpcode() == ISD::CopyToReg &&
2787           TargetRegisterInfo::isVirtualRegister
2788             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2789         continue;
2790
2791     // Locate the single data predecessor.
2792     SUnit *PredSU = 0;
2793     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2794          EE = SU->Preds.end(); II != EE; ++II)
2795       if (!II->isCtrl()) {
2796         PredSU = II->getSUnit();
2797         break;
2798       }
2799     assert(PredSU);
2800
2801     // Don't rewrite edges that carry physregs, because that requires additional
2802     // support infrastructure.
2803     if (PredSU->hasPhysRegDefs)
2804       continue;
2805     // Short-circuit the case where SU is PredSU's only data successor.
2806     if (PredSU->NumSuccs == 1)
2807       continue;
2808     // Avoid prescheduling to copies from virtual registers, which don't behave
2809     // like other nodes from the perspective of scheduling heuristics.
2810     if (SDNode *N = SU->getNode())
2811       if (N->getOpcode() == ISD::CopyFromReg &&
2812           TargetRegisterInfo::isVirtualRegister
2813             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2814         continue;
2815
2816     // Perform checks on the successors of PredSU.
2817     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2818          EE = PredSU->Succs.end(); II != EE; ++II) {
2819       SUnit *PredSuccSU = II->getSUnit();
2820       if (PredSuccSU == SU) continue;
2821       // If PredSU has another successor with no data successors, for
2822       // now don't attempt to choose either over the other.
2823       if (PredSuccSU->NumSuccs == 0)
2824         goto outer_loop_continue;
2825       // Don't break physical register dependencies.
2826       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2827         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2828           goto outer_loop_continue;
2829       // Don't introduce graph cycles.
2830       if (scheduleDAG->IsReachable(SU, PredSuccSU))
2831         goto outer_loop_continue;
2832     }
2833
2834     // Ok, the transformation is safe and the heuristics suggest it is
2835     // profitable. Update the graph.
2836     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
2837                  << " next to PredSU #" << PredSU->NodeNum
2838                  << " to guide scheduling in the presence of multiple uses\n");
2839     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2840       SDep Edge = PredSU->Succs[i];
2841       assert(!Edge.isAssignedRegDep());
2842       SUnit *SuccSU = Edge.getSUnit();
2843       if (SuccSU != SU) {
2844         Edge.setSUnit(PredSU);
2845         scheduleDAG->RemovePred(SuccSU, Edge);
2846         scheduleDAG->AddPred(SU, Edge);
2847         Edge.setSUnit(SU);
2848         scheduleDAG->AddPred(SuccSU, Edge);
2849         --i;
2850       }
2851     }
2852   outer_loop_continue:;
2853   }
2854 }
2855
2856 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2857 /// it as a def&use operand. Add a pseudo control edge from it to the other
2858 /// node (if it won't create a cycle) so the two-address one will be scheduled
2859 /// first (lower in the schedule). If both nodes are two-address, favor the
2860 /// one that has a CopyToReg use (more likely to be a loop induction update).
2861 /// If both are two-address, but one is commutable while the other is not
2862 /// commutable, favor the one that's not commutable.
2863 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2864   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2865     SUnit *SU = &(*SUnits)[i];
2866     if (!SU->isTwoAddress)
2867       continue;
2868
2869     SDNode *Node = SU->getNode();
2870     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2871       continue;
2872
2873     bool isLiveOut = hasOnlyLiveOutUses(SU);
2874     unsigned Opc = Node->getMachineOpcode();
2875     const MCInstrDesc &MCID = TII->get(Opc);
2876     unsigned NumRes = MCID.getNumDefs();
2877     unsigned NumOps = MCID.getNumOperands() - NumRes;
2878     for (unsigned j = 0; j != NumOps; ++j) {
2879       if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
2880         continue;
2881       SDNode *DU = SU->getNode()->getOperand(j).getNode();
2882       if (DU->getNodeId() == -1)
2883         continue;
2884       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2885       if (!DUSU) continue;
2886       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2887            E = DUSU->Succs.end(); I != E; ++I) {
2888         if (I->isCtrl()) continue;
2889         SUnit *SuccSU = I->getSUnit();
2890         if (SuccSU == SU)
2891           continue;
2892         // Be conservative. Ignore if nodes aren't at roughly the same
2893         // depth and height.
2894         if (SuccSU->getHeight() < SU->getHeight() &&
2895             (SU->getHeight() - SuccSU->getHeight()) > 1)
2896           continue;
2897         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2898         // constrains whatever is using the copy, instead of the copy
2899         // itself. In the case that the copy is coalesced, this
2900         // preserves the intent of the pseudo two-address heurietics.
2901         while (SuccSU->Succs.size() == 1 &&
2902                SuccSU->getNode()->isMachineOpcode() &&
2903                SuccSU->getNode()->getMachineOpcode() ==
2904                  TargetOpcode::COPY_TO_REGCLASS)
2905           SuccSU = SuccSU->Succs.front().getSUnit();
2906         // Don't constrain non-instruction nodes.
2907         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2908           continue;
2909         // Don't constrain nodes with physical register defs if the
2910         // predecessor can clobber them.
2911         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2912           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2913             continue;
2914         }
2915         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2916         // these may be coalesced away. We want them close to their uses.
2917         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2918         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2919             SuccOpc == TargetOpcode::INSERT_SUBREG ||
2920             SuccOpc == TargetOpcode::SUBREG_TO_REG)
2921           continue;
2922         if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
2923             (!canClobber(SuccSU, DUSU) ||
2924              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2925              (!SU->isCommutable && SuccSU->isCommutable)) &&
2926             !scheduleDAG->IsReachable(SuccSU, SU)) {
2927           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
2928                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2929           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2930                                         /*Reg=*/0, /*isNormalMemory=*/false,
2931                                         /*isMustAlias=*/false,
2932                                         /*isArtificial=*/true));
2933         }
2934       }
2935     }
2936   }
2937 }
2938
2939 //===----------------------------------------------------------------------===//
2940 //                         Public Constructor Functions
2941 //===----------------------------------------------------------------------===//
2942
2943 llvm::ScheduleDAGSDNodes *
2944 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2945                                  CodeGenOpt::Level OptLevel) {
2946   const TargetMachine &TM = IS->TM;
2947   const TargetInstrInfo *TII = TM.getInstrInfo();
2948   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2949
2950   BURegReductionPriorityQueue *PQ =
2951     new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2952   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2953   PQ->setScheduleDAG(SD);
2954   return SD;
2955 }
2956
2957 llvm::ScheduleDAGSDNodes *
2958 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2959                                    CodeGenOpt::Level OptLevel) {
2960   const TargetMachine &TM = IS->TM;
2961   const TargetInstrInfo *TII = TM.getInstrInfo();
2962   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2963
2964   SrcRegReductionPriorityQueue *PQ =
2965     new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2966   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2967   PQ->setScheduleDAG(SD);
2968   return SD;
2969 }
2970
2971 llvm::ScheduleDAGSDNodes *
2972 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2973                                    CodeGenOpt::Level OptLevel) {
2974   const TargetMachine &TM = IS->TM;
2975   const TargetInstrInfo *TII = TM.getInstrInfo();
2976   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2977   const TargetLowering *TLI = &IS->getTargetLowering();
2978
2979   HybridBURRPriorityQueue *PQ =
2980     new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2981
2982   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2983   PQ->setScheduleDAG(SD);
2984   return SD;
2985 }
2986
2987 llvm::ScheduleDAGSDNodes *
2988 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2989                                 CodeGenOpt::Level OptLevel) {
2990   const TargetMachine &TM = IS->TM;
2991   const TargetInstrInfo *TII = TM.getInstrInfo();
2992   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2993   const TargetLowering *TLI = &IS->getTargetLowering();
2994
2995   ILPBURRPriorityQueue *PQ =
2996     new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2997   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2998   PQ->setScheduleDAG(SD);
2999   return SD;
3000 }