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