ScheduleDAGInstrs.cpp revision b12a77199245a72c24dadbc039ed263d68d8e91a
1//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
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 the ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16#include "llvm/CodeGen/ScheduleDAGInstrs.h"
17#include "llvm/ADT/MapVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/CodeGen/LiveIntervalAnalysis.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineMemOperand.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/PseudoSourceValue.h"
27#include "llvm/CodeGen/RegisterPressure.h"
28#include "llvm/CodeGen/ScheduleDFS.h"
29#include "llvm/IR/Operator.h"
30#include "llvm/MC/MCInstrItineraries.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/Format.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegisterInfo.h"
38#include "llvm/Target/TargetSubtargetInfo.h"
39using namespace llvm;
40
41static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
42    cl::ZeroOrMore, cl::init(false),
43    cl::desc("Enable use of AA during MI GAD construction"));
44
45ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
46                                     const MachineLoopInfo &mli,
47                                     const MachineDominatorTree &mdt,
48                                     bool IsPostRAFlag,
49                                     LiveIntervals *lis)
50  : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
51    IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
52  assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
53  DbgValues.clear();
54  assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
55         "Virtual registers must be removed prior to PostRA scheduling");
56
57  const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
58  SchedModel.init(*ST.getSchedModel(), &ST, TII);
59}
60
61/// getUnderlyingObjectFromInt - This is the function that does the work of
62/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
63static const Value *getUnderlyingObjectFromInt(const Value *V) {
64  do {
65    if (const Operator *U = dyn_cast<Operator>(V)) {
66      // If we find a ptrtoint, we can transfer control back to the
67      // regular getUnderlyingObjectFromInt.
68      if (U->getOpcode() == Instruction::PtrToInt)
69        return U->getOperand(0);
70      // If we find an add of a constant, a multiplied value, or a phi, it's
71      // likely that the other operand will lead us to the base
72      // object. We don't have to worry about the case where the
73      // object address is somehow being computed by the multiply,
74      // because our callers only care when the result is an
75      // identifiable object.
76      if (U->getOpcode() != Instruction::Add ||
77          (!isa<ConstantInt>(U->getOperand(1)) &&
78           Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
79           !isa<PHINode>(U->getOperand(1))))
80        return V;
81      V = U->getOperand(0);
82    } else {
83      return V;
84    }
85    assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
86  } while (1);
87}
88
89/// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
90/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
91static void getUnderlyingObjects(const Value *V,
92                                 SmallVectorImpl<Value *> &Objects) {
93  SmallPtrSet<const Value*, 16> Visited;
94  SmallVector<const Value *, 4> Working(1, V);
95  do {
96    V = Working.pop_back_val();
97
98    SmallVector<Value *, 4> Objs;
99    GetUnderlyingObjects(const_cast<Value *>(V), Objs);
100
101    for (SmallVector<Value *, 4>::iterator I = Objs.begin(), IE = Objs.end();
102         I != IE; ++I) {
103      V = *I;
104      if (!Visited.insert(V))
105        continue;
106      if (Operator::getOpcode(V) == Instruction::IntToPtr) {
107        const Value *O =
108          getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
109        if (O->getType()->isPointerTy()) {
110          Working.push_back(O);
111          continue;
112        }
113      }
114      Objects.push_back(const_cast<Value *>(V));
115    }
116  } while (!Working.empty());
117}
118
119/// getUnderlyingObjectsForInstr - If this machine instr has memory reference
120/// information and it can be tracked to a normal reference to a known
121/// object, return the Value for that object.
122static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
123              const MachineFrameInfo *MFI,
124              SmallVectorImpl<std::pair<const Value *, bool> > &Objects) {
125  if (!MI->hasOneMemOperand() ||
126      !(*MI->memoperands_begin())->getValue() ||
127      (*MI->memoperands_begin())->isVolatile())
128    return;
129
130  const Value *V = (*MI->memoperands_begin())->getValue();
131  if (!V)
132    return;
133
134  SmallVector<Value *, 4> Objs;
135  getUnderlyingObjects(V, Objs);
136
137  for (SmallVector<Value *, 4>::iterator I = Objs.begin(), IE = Objs.end();
138       I != IE; ++I) {
139    bool MayAlias = true;
140    V = *I;
141
142    if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
143      // For now, ignore PseudoSourceValues which may alias LLVM IR values
144      // because the code that uses this function has no way to cope with
145      // such aliases.
146
147      if (PSV->isAliased(MFI)) {
148        Objects.clear();
149        return;
150      }
151
152      MayAlias = PSV->mayAlias(MFI);
153    } else if (!isIdentifiedObject(V)) {
154      Objects.clear();
155      return;
156    }
157
158    Objects.push_back(std::make_pair(V, MayAlias));
159  }
160}
161
162void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
163  BB = bb;
164}
165
166void ScheduleDAGInstrs::finishBlock() {
167  // Subclasses should no longer refer to the old block.
168  BB = 0;
169}
170
171/// Initialize the DAG and common scheduler state for the current scheduling
172/// region. This does not actually create the DAG, only clears it. The
173/// scheduling driver may call BuildSchedGraph multiple times per scheduling
174/// region.
175void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
176                                    MachineBasicBlock::iterator begin,
177                                    MachineBasicBlock::iterator end,
178                                    unsigned endcount) {
179  assert(bb == BB && "startBlock should set BB");
180  RegionBegin = begin;
181  RegionEnd = end;
182  EndIndex = endcount;
183  MISUnitMap.clear();
184
185  ScheduleDAG::clearDAG();
186}
187
188/// Close the current scheduling region. Don't clear any state in case the
189/// driver wants to refer to the previous scheduling region.
190void ScheduleDAGInstrs::exitRegion() {
191  // Nothing to do.
192}
193
194/// addSchedBarrierDeps - Add dependencies from instructions in the current
195/// list of instructions being scheduled to scheduling barrier by adding
196/// the exit SU to the register defs and use list. This is because we want to
197/// make sure instructions which define registers that are either used by
198/// the terminator or are live-out are properly scheduled. This is
199/// especially important when the definition latency of the return value(s)
200/// are too high to be hidden by the branch or when the liveout registers
201/// used by instructions in the fallthrough block.
202void ScheduleDAGInstrs::addSchedBarrierDeps() {
203  MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
204  ExitSU.setInstr(ExitMI);
205  bool AllDepKnown = ExitMI &&
206    (ExitMI->isCall() || ExitMI->isBarrier());
207  if (ExitMI && AllDepKnown) {
208    // If it's a call or a barrier, add dependencies on the defs and uses of
209    // instruction.
210    for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
211      const MachineOperand &MO = ExitMI->getOperand(i);
212      if (!MO.isReg() || MO.isDef()) continue;
213      unsigned Reg = MO.getReg();
214      if (Reg == 0) continue;
215
216      if (TRI->isPhysicalRegister(Reg))
217        Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
218      else {
219        assert(!IsPostRA && "Virtual register encountered after regalloc.");
220        if (MO.readsReg()) // ignore undef operands
221          addVRegUseDeps(&ExitSU, i);
222      }
223    }
224  } else {
225    // For others, e.g. fallthrough, conditional branch, assume the exit
226    // uses all the registers that are livein to the successor blocks.
227    assert(Uses.empty() && "Uses in set before adding deps?");
228    for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
229           SE = BB->succ_end(); SI != SE; ++SI)
230      for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
231             E = (*SI)->livein_end(); I != E; ++I) {
232        unsigned Reg = *I;
233        if (!Uses.contains(Reg))
234          Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
235      }
236  }
237}
238
239/// MO is an operand of SU's instruction that defines a physical register. Add
240/// data dependencies from SU to any uses of the physical register.
241void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
242  const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
243  assert(MO.isDef() && "expect physreg def");
244
245  // Ask the target if address-backscheduling is desirable, and if so how much.
246  const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
247
248  for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
249       Alias.isValid(); ++Alias) {
250    if (!Uses.contains(*Alias))
251      continue;
252    for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
253      SUnit *UseSU = I->SU;
254      if (UseSU == SU)
255        continue;
256
257      // Adjust the dependence latency using operand def/use information,
258      // then allow the target to perform its own adjustments.
259      int UseOp = I->OpIdx;
260      MachineInstr *RegUse = 0;
261      SDep Dep;
262      if (UseOp < 0)
263        Dep = SDep(SU, SDep::Artificial);
264      else {
265        Dep = SDep(SU, SDep::Data, *Alias);
266        RegUse = UseSU->getInstr();
267        Dep.setMinLatency(
268          SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
269                                           RegUse, UseOp, /*FindMin=*/true));
270      }
271      Dep.setLatency(
272        SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
273                                         RegUse, UseOp, /*FindMin=*/false));
274
275      ST.adjustSchedDependency(SU, UseSU, Dep);
276      UseSU->addPred(Dep);
277    }
278  }
279}
280
281/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
282/// this SUnit to following instructions in the same scheduling region that
283/// depend the physical register referenced at OperIdx.
284void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
285  const MachineInstr *MI = SU->getInstr();
286  const MachineOperand &MO = MI->getOperand(OperIdx);
287
288  // Optionally add output and anti dependencies. For anti
289  // dependencies we use a latency of 0 because for a multi-issue
290  // target we want to allow the defining instruction to issue
291  // in the same cycle as the using instruction.
292  // TODO: Using a latency of 1 here for output dependencies assumes
293  //       there's no cost for reusing registers.
294  SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
295  for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
296       Alias.isValid(); ++Alias) {
297    if (!Defs.contains(*Alias))
298      continue;
299    for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
300      SUnit *DefSU = I->SU;
301      if (DefSU == &ExitSU)
302        continue;
303      if (DefSU != SU &&
304          (Kind != SDep::Output || !MO.isDead() ||
305           !DefSU->getInstr()->registerDefIsDead(*Alias))) {
306        if (Kind == SDep::Anti)
307          DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
308        else {
309          SDep Dep(SU, Kind, /*Reg=*/*Alias);
310          unsigned OutLatency =
311            SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
312          Dep.setMinLatency(OutLatency);
313          Dep.setLatency(OutLatency);
314          DefSU->addPred(Dep);
315        }
316      }
317    }
318  }
319
320  if (!MO.isDef()) {
321    // Either insert a new Reg2SUnits entry with an empty SUnits list, or
322    // retrieve the existing SUnits list for this register's uses.
323    // Push this SUnit on the use list.
324    Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
325  }
326  else {
327    addPhysRegDataDeps(SU, OperIdx);
328    unsigned Reg = MO.getReg();
329
330    // clear this register's use list
331    if (Uses.contains(Reg))
332      Uses.eraseAll(Reg);
333
334    if (!MO.isDead()) {
335      Defs.eraseAll(Reg);
336    } else if (SU->isCall) {
337      // Calls will not be reordered because of chain dependencies (see
338      // below). Since call operands are dead, calls may continue to be added
339      // to the DefList making dependence checking quadratic in the size of
340      // the block. Instead, we leave only one call at the back of the
341      // DefList.
342      Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
343      Reg2SUnitsMap::iterator B = P.first;
344      Reg2SUnitsMap::iterator I = P.second;
345      for (bool isBegin = I == B; !isBegin; /* empty */) {
346        isBegin = (--I) == B;
347        if (!I->SU->isCall)
348          break;
349        I = Defs.erase(I);
350      }
351    }
352
353    // Defs are pushed in the order they are visited and never reordered.
354    Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
355  }
356}
357
358/// addVRegDefDeps - Add register output and data dependencies from this SUnit
359/// to instructions that occur later in the same scheduling region if they read
360/// from or write to the virtual register defined at OperIdx.
361///
362/// TODO: Hoist loop induction variable increments. This has to be
363/// reevaluated. Generally, IV scheduling should be done before coalescing.
364void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
365  const MachineInstr *MI = SU->getInstr();
366  unsigned Reg = MI->getOperand(OperIdx).getReg();
367
368  // Singly defined vregs do not have output/anti dependencies.
369  // The current operand is a def, so we have at least one.
370  // Check here if there are any others...
371  if (MRI.hasOneDef(Reg))
372    return;
373
374  // Add output dependence to the next nearest def of this vreg.
375  //
376  // Unless this definition is dead, the output dependence should be
377  // transitively redundant with antidependencies from this definition's
378  // uses. We're conservative for now until we have a way to guarantee the uses
379  // are not eliminated sometime during scheduling. The output dependence edge
380  // is also useful if output latency exceeds def-use latency.
381  VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
382  if (DefI == VRegDefs.end())
383    VRegDefs.insert(VReg2SUnit(Reg, SU));
384  else {
385    SUnit *DefSU = DefI->SU;
386    if (DefSU != SU && DefSU != &ExitSU) {
387      SDep Dep(SU, SDep::Output, Reg);
388      unsigned OutLatency =
389        SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
390      Dep.setMinLatency(OutLatency);
391      Dep.setLatency(OutLatency);
392      DefSU->addPred(Dep);
393    }
394    DefI->SU = SU;
395  }
396}
397
398/// addVRegUseDeps - Add a register data dependency if the instruction that
399/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
400/// register antidependency from this SUnit to instructions that occur later in
401/// the same scheduling region if they write the virtual register.
402///
403/// TODO: Handle ExitSU "uses" properly.
404void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
405  MachineInstr *MI = SU->getInstr();
406  unsigned Reg = MI->getOperand(OperIdx).getReg();
407
408  // Lookup this operand's reaching definition.
409  assert(LIS && "vreg dependencies requires LiveIntervals");
410  LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
411  VNInfo *VNI = LRQ.valueIn();
412
413  // VNI will be valid because MachineOperand::readsReg() is checked by caller.
414  assert(VNI && "No value to read by operand");
415  MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
416  // Phis and other noninstructions (after coalescing) have a NULL Def.
417  if (Def) {
418    SUnit *DefSU = getSUnit(Def);
419    if (DefSU) {
420      // The reaching Def lives within this scheduling region.
421      // Create a data dependence.
422      SDep dep(DefSU, SDep::Data, Reg);
423      // Adjust the dependence latency using operand def/use information, then
424      // allow the target to perform its own adjustments.
425      int DefOp = Def->findRegisterDefOperandIdx(Reg);
426      dep.setLatency(
427        SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false));
428      dep.setMinLatency(
429        SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true));
430
431      const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
432      ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
433      SU->addPred(dep);
434    }
435  }
436
437  // Add antidependence to the following def of the vreg it uses.
438  VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
439  if (DefI != VRegDefs.end() && DefI->SU != SU)
440    DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
441}
442
443/// Return true if MI is an instruction we are unable to reason about
444/// (like a call or something with unmodeled side effects).
445static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
446  if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
447      (MI->hasOrderedMemoryRef() &&
448       (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
449    return true;
450  return false;
451}
452
453// This MI might have either incomplete info, or known to be unsafe
454// to deal with (i.e. volatile object).
455static inline bool isUnsafeMemoryObject(MachineInstr *MI,
456                                        const MachineFrameInfo *MFI) {
457  if (!MI || MI->memoperands_empty())
458    return true;
459  // We purposefully do no check for hasOneMemOperand() here
460  // in hope to trigger an assert downstream in order to
461  // finish implementation.
462  if ((*MI->memoperands_begin())->isVolatile() ||
463       MI->hasUnmodeledSideEffects())
464    return true;
465  const Value *V = (*MI->memoperands_begin())->getValue();
466  if (!V)
467    return true;
468
469  SmallVector<Value *, 4> Objs;
470  getUnderlyingObjects(V, Objs);
471  for (SmallVector<Value *, 4>::iterator I = Objs.begin(),
472       IE = Objs.end(); I != IE; ++I) {
473    V = *I;
474
475    if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
476      // Similarly to getUnderlyingObjectForInstr:
477      // For now, ignore PseudoSourceValues which may alias LLVM IR values
478      // because the code that uses this function has no way to cope with
479      // such aliases.
480      if (PSV->isAliased(MFI))
481        return true;
482    }
483
484    // Does this pointer refer to a distinct and identifiable object?
485    if (!isIdentifiedObject(V))
486      return true;
487  }
488
489  return false;
490}
491
492/// This returns true if the two MIs need a chain edge betwee them.
493/// If these are not even memory operations, we still may need
494/// chain deps between them. The question really is - could
495/// these two MIs be reordered during scheduling from memory dependency
496/// point of view.
497static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
498                             MachineInstr *MIa,
499                             MachineInstr *MIb) {
500  // Cover a trivial case - no edge is need to itself.
501  if (MIa == MIb)
502    return false;
503
504  if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
505    return true;
506
507  // If we are dealing with two "normal" loads, we do not need an edge
508  // between them - they could be reordered.
509  if (!MIa->mayStore() && !MIb->mayStore())
510    return false;
511
512  // To this point analysis is generic. From here on we do need AA.
513  if (!AA)
514    return true;
515
516  MachineMemOperand *MMOa = *MIa->memoperands_begin();
517  MachineMemOperand *MMOb = *MIb->memoperands_begin();
518
519  // FIXME: Need to handle multiple memory operands to support all targets.
520  if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
521    llvm_unreachable("Multiple memory operands.");
522
523  // The following interface to AA is fashioned after DAGCombiner::isAlias
524  // and operates with MachineMemOperand offset with some important
525  // assumptions:
526  //   - LLVM fundamentally assumes flat address spaces.
527  //   - MachineOperand offset can *only* result from legalization and
528  //     cannot affect queries other than the trivial case of overlap
529  //     checking.
530  //   - These offsets never wrap and never step outside
531  //     of allocated objects.
532  //   - There should never be any negative offsets here.
533  //
534  // FIXME: Modify API to hide this math from "user"
535  // FIXME: Even before we go to AA we can reason locally about some
536  // memory objects. It can save compile time, and possibly catch some
537  // corner cases not currently covered.
538
539  assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
540  assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
541
542  int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
543  int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
544  int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
545
546  AliasAnalysis::AliasResult AAResult = AA->alias(
547  AliasAnalysis::Location(MMOa->getValue(), Overlapa,
548                          MMOa->getTBAAInfo()),
549  AliasAnalysis::Location(MMOb->getValue(), Overlapb,
550                          MMOb->getTBAAInfo()));
551
552  return (AAResult != AliasAnalysis::NoAlias);
553}
554
555/// This recursive function iterates over chain deps of SUb looking for
556/// "latest" node that needs a chain edge to SUa.
557static unsigned
558iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
559                 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
560                 SmallPtrSet<const SUnit*, 16> &Visited) {
561  if (!SUa || !SUb || SUb == ExitSU)
562    return *Depth;
563
564  // Remember visited nodes.
565  if (!Visited.insert(SUb))
566      return *Depth;
567  // If there is _some_ dependency already in place, do not
568  // descend any further.
569  // TODO: Need to make sure that if that dependency got eliminated or ignored
570  // for any reason in the future, we would not violate DAG topology.
571  // Currently it does not happen, but makes an implicit assumption about
572  // future implementation.
573  //
574  // Independently, if we encounter node that is some sort of global
575  // object (like a call) we already have full set of dependencies to it
576  // and we can stop descending.
577  if (SUa->isSucc(SUb) ||
578      isGlobalMemoryObject(AA, SUb->getInstr()))
579    return *Depth;
580
581  // If we do need an edge, or we have exceeded depth budget,
582  // add that edge to the predecessors chain of SUb,
583  // and stop descending.
584  if (*Depth > 200 ||
585      MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
586    SUb->addPred(SDep(SUa, SDep::MayAliasMem));
587    return *Depth;
588  }
589  // Track current depth.
590  (*Depth)++;
591  // Iterate over chain dependencies only.
592  for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
593       I != E; ++I)
594    if (I->isCtrl())
595      iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
596  return *Depth;
597}
598
599/// This function assumes that "downward" from SU there exist
600/// tail/leaf of already constructed DAG. It iterates downward and
601/// checks whether SU can be aliasing any node dominated
602/// by it.
603static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
604                            SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
605                            unsigned LatencyToLoad) {
606  if (!SU)
607    return;
608
609  SmallPtrSet<const SUnit*, 16> Visited;
610  unsigned Depth = 0;
611
612  for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
613       I != IE; ++I) {
614    if (SU == *I)
615      continue;
616    if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
617      SDep Dep(SU, SDep::MayAliasMem);
618      Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
619      (*I)->addPred(Dep);
620    }
621    // Now go through all the chain successors and iterate from them.
622    // Keep track of visited nodes.
623    for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
624         JE = (*I)->Succs.end(); J != JE; ++J)
625      if (J->isCtrl())
626        iterateChainSucc (AA, MFI, SU, J->getSUnit(),
627                          ExitSU, &Depth, Visited);
628  }
629}
630
631/// Check whether two objects need a chain edge, if so, add it
632/// otherwise remember the rejected SU.
633static inline
634void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
635                         SUnit *SUa, SUnit *SUb,
636                         std::set<SUnit *> &RejectList,
637                         unsigned TrueMemOrderLatency = 0,
638                         bool isNormalMemory = false) {
639  // If this is a false dependency,
640  // do not add the edge, but rememeber the rejected node.
641  if (!EnableAASchedMI ||
642      MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
643    SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
644    Dep.setLatency(TrueMemOrderLatency);
645    SUb->addPred(Dep);
646  }
647  else {
648    // Duplicate entries should be ignored.
649    RejectList.insert(SUb);
650    DEBUG(dbgs() << "\tReject chain dep between SU("
651          << SUa->NodeNum << ") and SU("
652          << SUb->NodeNum << ")\n");
653  }
654}
655
656/// Create an SUnit for each real instruction, numbered in top-down toplological
657/// order. The instruction order A < B, implies that no edge exists from B to A.
658///
659/// Map each real instruction to its SUnit.
660///
661/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
662/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
663/// instead of pointers.
664///
665/// MachineScheduler relies on initSUnits numbering the nodes by their order in
666/// the original instruction list.
667void ScheduleDAGInstrs::initSUnits() {
668  // We'll be allocating one SUnit for each real instruction in the region,
669  // which is contained within a basic block.
670  SUnits.reserve(BB->size());
671
672  for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
673    MachineInstr *MI = I;
674    if (MI->isDebugValue())
675      continue;
676
677    SUnit *SU = newSUnit(MI);
678    MISUnitMap[MI] = SU;
679
680    SU->isCall = MI->isCall();
681    SU->isCommutable = MI->isCommutable();
682
683    // Assign the Latency field of SU using target-provided information.
684    SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
685  }
686}
687
688/// If RegPressure is non null, compute register pressure as a side effect. The
689/// DAG builder is an efficient place to do it because it already visits
690/// operands.
691void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
692                                        RegPressureTracker *RPTracker) {
693  // Create an SUnit for each real instruction.
694  initSUnits();
695
696  // We build scheduling units by walking a block's instruction list from bottom
697  // to top.
698
699  // Remember where a generic side-effecting instruction is as we procede.
700  SUnit *BarrierChain = 0, *AliasChain = 0;
701
702  // Memory references to specific known memory locations are tracked
703  // so that they can be given more precise dependencies. We track
704  // separately the known memory locations that may alias and those
705  // that are known not to alias
706  MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
707  MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
708  std::set<SUnit*> RejectMemNodes;
709
710  // Remove any stale debug info; sometimes BuildSchedGraph is called again
711  // without emitting the info from the previous call.
712  DbgValues.clear();
713  FirstDbgValue = NULL;
714
715  assert(Defs.empty() && Uses.empty() &&
716         "Only BuildGraph should update Defs/Uses");
717  Defs.setUniverse(TRI->getNumRegs());
718  Uses.setUniverse(TRI->getNumRegs());
719
720  assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
721  // FIXME: Allow SparseSet to reserve space for the creation of virtual
722  // registers during scheduling. Don't artificially inflate the Universe
723  // because we want to assert that vregs are not created during DAG building.
724  VRegDefs.setUniverse(MRI.getNumVirtRegs());
725
726  // Model data dependencies between instructions being scheduled and the
727  // ExitSU.
728  addSchedBarrierDeps();
729
730  // Walk the list of instructions, from bottom moving up.
731  MachineInstr *DbgMI = NULL;
732  for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
733       MII != MIE; --MII) {
734    MachineInstr *MI = prior(MII);
735    if (MI && DbgMI) {
736      DbgValues.push_back(std::make_pair(DbgMI, MI));
737      DbgMI = NULL;
738    }
739
740    if (MI->isDebugValue()) {
741      DbgMI = MI;
742      continue;
743    }
744    if (RPTracker) {
745      RPTracker->recede();
746      assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
747    }
748
749    assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
750           "Cannot schedule terminators or labels!");
751
752    SUnit *SU = MISUnitMap[MI];
753    assert(SU && "No SUnit mapped to this MI");
754
755    // Add register-based dependencies (data, anti, and output).
756    bool HasVRegDef = false;
757    for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
758      const MachineOperand &MO = MI->getOperand(j);
759      if (!MO.isReg()) continue;
760      unsigned Reg = MO.getReg();
761      if (Reg == 0) continue;
762
763      if (TRI->isPhysicalRegister(Reg))
764        addPhysRegDeps(SU, j);
765      else {
766        assert(!IsPostRA && "Virtual register encountered!");
767        if (MO.isDef()) {
768          HasVRegDef = true;
769          addVRegDefDeps(SU, j);
770        }
771        else if (MO.readsReg()) // ignore undef operands
772          addVRegUseDeps(SU, j);
773      }
774    }
775    // If we haven't seen any uses in this scheduling region, create a
776    // dependence edge to ExitSU to model the live-out latency. This is required
777    // for vreg defs with no in-region use, and prefetches with no vreg def.
778    //
779    // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
780    // check currently relies on being called before adding chain deps.
781    if (SU->NumSuccs == 0 && SU->Latency > 1
782        && (HasVRegDef || MI->mayLoad())) {
783      SDep Dep(SU, SDep::Artificial);
784      Dep.setLatency(SU->Latency - 1);
785      ExitSU.addPred(Dep);
786    }
787
788    // Add chain dependencies.
789    // Chain dependencies used to enforce memory order should have
790    // latency of 0 (except for true dependency of Store followed by
791    // aliased Load... we estimate that with a single cycle of latency
792    // assuming the hardware will bypass)
793    // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
794    // after stack slots are lowered to actual addresses.
795    // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
796    // produce more precise dependence information.
797    unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
798    if (isGlobalMemoryObject(AA, MI)) {
799      // Be conservative with these and add dependencies on all memory
800      // references, even those that are known to not alias.
801      for (MapVector<const Value *, SUnit *>::iterator I =
802             NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
803        I->second->addPred(SDep(SU, SDep::Barrier));
804      }
805      for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
806             NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
807        for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
808          SDep Dep(SU, SDep::Barrier);
809          Dep.setLatency(TrueMemOrderLatency);
810          I->second[i]->addPred(Dep);
811        }
812      }
813      // Add SU to the barrier chain.
814      if (BarrierChain)
815        BarrierChain->addPred(SDep(SU, SDep::Barrier));
816      BarrierChain = SU;
817      // This is a barrier event that acts as a pivotal node in the DAG,
818      // so it is safe to clear list of exposed nodes.
819      adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
820                      TrueMemOrderLatency);
821      RejectMemNodes.clear();
822      NonAliasMemDefs.clear();
823      NonAliasMemUses.clear();
824
825      // fall-through
826    new_alias_chain:
827      // Chain all possibly aliasing memory references though SU.
828      if (AliasChain) {
829        unsigned ChainLatency = 0;
830        if (AliasChain->getInstr()->mayLoad())
831          ChainLatency = TrueMemOrderLatency;
832        addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
833                           ChainLatency);
834      }
835      AliasChain = SU;
836      for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
837        addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
838                           TrueMemOrderLatency);
839      for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
840           E = AliasMemDefs.end(); I != E; ++I)
841        addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
842      for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
843           AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
844        for (unsigned i = 0, e = I->second.size(); i != e; ++i)
845          addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
846                             TrueMemOrderLatency);
847      }
848      adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
849                      TrueMemOrderLatency);
850      PendingLoads.clear();
851      AliasMemDefs.clear();
852      AliasMemUses.clear();
853    } else if (MI->mayStore()) {
854      SmallVector<std::pair<const Value *, bool>, 4> Objs;
855      getUnderlyingObjectsForInstr(MI, MFI, Objs);
856
857      if (Objs.empty()) {
858        // Treat all other stores conservatively.
859        goto new_alias_chain;
860      }
861
862      bool MayAlias = false;
863      for (SmallVector<std::pair<const Value *, bool>, 4>::iterator
864           K = Objs.begin(), KE = Objs.end(); K != KE; ++K) {
865        const Value *V = K->first;
866        bool ThisMayAlias = K->second;
867        if (ThisMayAlias)
868          MayAlias = true;
869
870        // A store to a specific PseudoSourceValue. Add precise dependencies.
871        // Record the def in MemDefs, first adding a dep if there is
872        // an existing def.
873        MapVector<const Value *, SUnit *>::iterator I =
874          ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
875        MapVector<const Value *, SUnit *>::iterator IE =
876          ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
877        if (I != IE) {
878          addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
879          I->second = SU;
880        } else {
881          if (ThisMayAlias)
882            AliasMemDefs[V] = SU;
883          else
884            NonAliasMemDefs[V] = SU;
885        }
886        // Handle the uses in MemUses, if there are any.
887        MapVector<const Value *, std::vector<SUnit *> >::iterator J =
888          ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
889        MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
890          ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
891        if (J != JE) {
892          for (unsigned i = 0, e = J->second.size(); i != e; ++i)
893            addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
894                               TrueMemOrderLatency, true);
895          J->second.clear();
896        }
897      }
898      if (MayAlias) {
899        // Add dependencies from all the PendingLoads, i.e. loads
900        // with no underlying object.
901        for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
902          addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
903                             TrueMemOrderLatency);
904        // Add dependence on alias chain, if needed.
905        if (AliasChain)
906          addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
907        // But we also should check dependent instructions for the
908        // SU in question.
909        adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
910                        TrueMemOrderLatency);
911      }
912      // Add dependence on barrier chain, if needed.
913      // There is no point to check aliasing on barrier event. Even if
914      // SU and barrier _could_ be reordered, they should not. In addition,
915      // we have lost all RejectMemNodes below barrier.
916      if (BarrierChain)
917        BarrierChain->addPred(SDep(SU, SDep::Barrier));
918
919      if (!ExitSU.isPred(SU))
920        // Push store's up a bit to avoid them getting in between cmp
921        // and branches.
922        ExitSU.addPred(SDep(SU, SDep::Artificial));
923    } else if (MI->mayLoad()) {
924      bool MayAlias = true;
925      if (MI->isInvariantLoad(AA)) {
926        // Invariant load, no chain dependencies needed!
927      } else {
928        SmallVector<std::pair<const Value *, bool>, 4> Objs;
929        getUnderlyingObjectsForInstr(MI, MFI, Objs);
930
931        if (Objs.empty()) {
932          // A load with no underlying object. Depend on all
933          // potentially aliasing stores.
934          for (MapVector<const Value *, SUnit *>::iterator I =
935                 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
936            addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
937
938          PendingLoads.push_back(SU);
939          MayAlias = true;
940        } else {
941          MayAlias = false;
942        }
943
944        for (SmallVector<std::pair<const Value *, bool>, 4>::iterator
945             J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
946          const Value *V = J->first;
947          bool ThisMayAlias = J->second;
948
949          if (ThisMayAlias)
950            MayAlias = true;
951
952          // A load from a specific PseudoSourceValue. Add precise dependencies.
953          MapVector<const Value *, SUnit *>::iterator I =
954            ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
955          MapVector<const Value *, SUnit *>::iterator IE =
956            ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
957          if (I != IE)
958            addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
959          if (ThisMayAlias)
960            AliasMemUses[V].push_back(SU);
961          else
962            NonAliasMemUses[V].push_back(SU);
963        }
964        if (MayAlias)
965          adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
966        // Add dependencies on alias and barrier chains, if needed.
967        if (MayAlias && AliasChain)
968          addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
969        if (BarrierChain)
970          BarrierChain->addPred(SDep(SU, SDep::Barrier));
971      }
972    }
973  }
974  if (DbgMI)
975    FirstDbgValue = DbgMI;
976
977  Defs.clear();
978  Uses.clear();
979  VRegDefs.clear();
980  PendingLoads.clear();
981}
982
983void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
984#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
985  SU->getInstr()->dump();
986#endif
987}
988
989std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
990  std::string s;
991  raw_string_ostream oss(s);
992  if (SU == &EntrySU)
993    oss << "<entry>";
994  else if (SU == &ExitSU)
995    oss << "<exit>";
996  else
997    SU->getInstr()->print(oss);
998  return oss.str();
999}
1000
1001/// Return the basic block label. It is not necessarilly unique because a block
1002/// contains multiple scheduling regions. But it is fine for visualization.
1003std::string ScheduleDAGInstrs::getDAGName() const {
1004  return "dag." + BB->getFullName();
1005}
1006
1007//===----------------------------------------------------------------------===//
1008// SchedDFSResult Implementation
1009//===----------------------------------------------------------------------===//
1010
1011namespace llvm {
1012/// \brief Internal state used to compute SchedDFSResult.
1013class SchedDFSImpl {
1014  SchedDFSResult &R;
1015
1016  /// Join DAG nodes into equivalence classes by their subtree.
1017  IntEqClasses SubtreeClasses;
1018  /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1019  std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1020
1021public:
1022  SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSData.size()) {}
1023
1024  /// SubtreID is initialized to zero, set to itself to flag the root of a
1025  /// subtree, set to the parent to indicate an interior node,
1026  /// then set to a representative subtree ID during finalization.
1027  bool isVisited(const SUnit *SU) const {
1028    return R.DFSData[SU->NodeNum].SubtreeID;
1029  }
1030
1031  /// Initialize this node's instruction count. We don't need to flag the node
1032  /// visited until visitPostorder because the DAG cannot have cycles.
1033  void visitPreorder(const SUnit *SU) {
1034    R.DFSData[SU->NodeNum].InstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1035  }
1036
1037  /// Mark this node as either the root of a subtree or an interior
1038  /// node. Increment the parent node's instruction count.
1039  void visitPostorder(const SUnit *SU, const SDep *PredDep, const SUnit *Parent) {
1040    R.DFSData[SU->NodeNum].SubtreeID = SU->NodeNum;
1041
1042    if (!Parent)
1043      return;
1044    assert(PredDep && "PredDep required for non-root node");
1045
1046    joinPredSubtree(*PredDep, Parent);
1047  }
1048
1049  /// Determine whether the DFS cross edge should be considered a subtree edge
1050  /// or a connection between subtrees.
1051  void visitCross(const SDep &PredDep, const SUnit *Succ) {
1052    joinPredSubtree(PredDep, Succ);
1053    ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1054  }
1055
1056  /// Set each node's subtree ID to the representative ID and record connections
1057  /// between trees.
1058  void finalize() {
1059    SubtreeClasses.compress();
1060    R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1061    R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1062    DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1063    for (unsigned Idx = 0, End = R.DFSData.size(); Idx != End; ++Idx) {
1064      R.DFSData[Idx].SubtreeID = SubtreeClasses[Idx];
1065      DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1066            << R.DFSData[Idx].SubtreeID << '\n');
1067    }
1068    for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1069           I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1070         I != E; ++I) {
1071      unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1072      unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1073      if (PredTree == SuccTree)
1074        continue;
1075      unsigned Depth = I->first->getDepth();
1076      addConnection(PredTree, SuccTree, Depth);
1077      addConnection(SuccTree, PredTree, Depth);
1078    }
1079  }
1080
1081protected:
1082  void joinPredSubtree(const SDep &PredDep, const SUnit *Succ) {
1083    // Join the child to its parent if they are connected via data dependence.
1084    if (PredDep.getKind() != SDep::Data)
1085      return;
1086
1087    // Four is the magic number of successors before a node is considered a
1088    // pinch point.
1089    unsigned NumDataSucs = 0;
1090    const SUnit *PredSU = PredDep.getSUnit();
1091    for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1092           SE = PredSU->Succs.end(); SI != SE; ++SI) {
1093      if (SI->getKind() == SDep::Data) {
1094        if (++NumDataSucs >= 4)
1095          return;
1096      }
1097    }
1098    // If this is a cross edge to a root, join the subtrees. This happens when
1099    // the root was first reached by a non-data dependence.
1100    unsigned NodeNum = PredSU->NodeNum;
1101    unsigned PredCnt = R.DFSData[NodeNum].InstrCount;
1102    if (R.DFSData[NodeNum].SubtreeID == NodeNum && PredCnt < R.SubtreeLimit) {
1103      R.DFSData[NodeNum].SubtreeID = Succ->NodeNum;
1104      R.DFSData[Succ->NodeNum].InstrCount += PredCnt;
1105      SubtreeClasses.join(Succ->NodeNum, NodeNum);
1106      return;
1107    }
1108  }
1109
1110  /// Called by finalize() to record a connection between trees.
1111  void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1112    if (!Depth)
1113      return;
1114
1115    SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1116      R.SubtreeConnections[FromTree];
1117    for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1118           I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1119      if (I->TreeID == ToTree) {
1120        I->Level = std::max(I->Level, Depth);
1121        return;
1122      }
1123    }
1124    Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1125  }
1126};
1127} // namespace llvm
1128
1129namespace {
1130/// \brief Manage the stack used by a reverse depth-first search over the DAG.
1131class SchedDAGReverseDFS {
1132  std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1133public:
1134  bool isComplete() const { return DFSStack.empty(); }
1135
1136  void follow(const SUnit *SU) {
1137    DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1138  }
1139  void advance() { ++DFSStack.back().second; }
1140
1141  const SDep *backtrack() {
1142    DFSStack.pop_back();
1143    return DFSStack.empty() ? 0 : llvm::prior(DFSStack.back().second);
1144  }
1145
1146  const SUnit *getCurr() const { return DFSStack.back().first; }
1147
1148  SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1149
1150  SUnit::const_pred_iterator getPredEnd() const {
1151    return getCurr()->Preds.end();
1152  }
1153};
1154} // anonymous
1155
1156/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1157/// search from this root.
1158void SchedDFSResult::compute(ArrayRef<SUnit *> Roots) {
1159  if (!IsBottomUp)
1160    llvm_unreachable("Top-down ILP metric is unimplemnted");
1161
1162  SchedDFSImpl Impl(*this);
1163  for (ArrayRef<const SUnit*>::const_iterator
1164         RootI = Roots.begin(), RootE = Roots.end(); RootI != RootE; ++RootI) {
1165    SchedDAGReverseDFS DFS;
1166    Impl.visitPreorder(*RootI);
1167    DFS.follow(*RootI);
1168    for (;;) {
1169      // Traverse the leftmost path as far as possible.
1170      while (DFS.getPred() != DFS.getPredEnd()) {
1171        const SDep &PredDep = *DFS.getPred();
1172        DFS.advance();
1173        // If the pred is already valid, skip it. We may preorder visit a node
1174        // with InstrCount==0 more than once, but it won't affect heuristics
1175        // because we don't care about cross edges to leaf copies.
1176        if (Impl.isVisited(PredDep.getSUnit())) {
1177          Impl.visitCross(PredDep, DFS.getCurr());
1178          continue;
1179        }
1180        Impl.visitPreorder(PredDep.getSUnit());
1181        DFS.follow(PredDep.getSUnit());
1182      }
1183      // Visit the top of the stack in postorder and backtrack.
1184      const SUnit *Child = DFS.getCurr();
1185      const SDep *PredDep = DFS.backtrack();
1186      Impl.visitPostorder(Child, PredDep, PredDep ? DFS.getCurr() : 0);
1187      if (DFS.isComplete())
1188        break;
1189    }
1190  }
1191  Impl.finalize();
1192}
1193
1194/// The root of the given SubtreeID was just scheduled. For all subtrees
1195/// connected to this tree, record the depth of the connection so that the
1196/// nearest connected subtrees can be prioritized.
1197void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1198  for (SmallVectorImpl<Connection>::const_iterator
1199         I = SubtreeConnections[SubtreeID].begin(),
1200         E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1201    SubtreeConnectLevels[I->TreeID] =
1202      std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1203    DEBUG(dbgs() << "  Tree: " << I->TreeID
1204          << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
1205  }
1206}
1207
1208#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1209void ILPValue::print(raw_ostream &OS) const {
1210  OS << InstrCount << " / " << Length << " = ";
1211  if (!Length)
1212    OS << "BADILP";
1213  else
1214    OS << format("%g", ((double)InstrCount / Length));
1215}
1216
1217void ILPValue::dump() const {
1218  dbgs() << *this << '\n';
1219}
1220
1221namespace llvm {
1222
1223raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1224  Val.print(OS);
1225  return OS;
1226}
1227
1228} // namespace llvm
1229#endif // !NDEBUG || LLVM_ENABLE_DUMP
1230