e4da6a41eead6376706fc33609dfcd016065840a
[oota-llvm.git] / lib / CodeGen / ScheduleDAGInstrs.cpp
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"
39 using namespace llvm;
40
41 static 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
45 ScheduleDAGInstrs::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.
63 static 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.
91 static 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.
122 static 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
162 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
163   BB = bb;
164 }
165
166 void 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.
175 void 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.
190 void 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.
202 void 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.
241 void 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         // Set the hasPhysRegDefs only for physreg defs that have a use within
266         // the scheduling region.
267         SU->hasPhysRegDefs = true;
268         Dep = SDep(SU, SDep::Data, *Alias);
269         RegUse = UseSU->getInstr();
270         Dep.setMinLatency(
271           SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
272                                            RegUse, UseOp, /*FindMin=*/true));
273       }
274       Dep.setLatency(
275         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
276                                          RegUse, UseOp, /*FindMin=*/false));
277
278       ST.adjustSchedDependency(SU, UseSU, Dep);
279       UseSU->addPred(Dep);
280     }
281   }
282 }
283
284 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
285 /// this SUnit to following instructions in the same scheduling region that
286 /// depend the physical register referenced at OperIdx.
287 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
288   const MachineInstr *MI = SU->getInstr();
289   const MachineOperand &MO = MI->getOperand(OperIdx);
290
291   // Optionally add output and anti dependencies. For anti
292   // dependencies we use a latency of 0 because for a multi-issue
293   // target we want to allow the defining instruction to issue
294   // in the same cycle as the using instruction.
295   // TODO: Using a latency of 1 here for output dependencies assumes
296   //       there's no cost for reusing registers.
297   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
298   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
299        Alias.isValid(); ++Alias) {
300     if (!Defs.contains(*Alias))
301       continue;
302     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
303       SUnit *DefSU = I->SU;
304       if (DefSU == &ExitSU)
305         continue;
306       if (DefSU != SU &&
307           (Kind != SDep::Output || !MO.isDead() ||
308            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
309         if (Kind == SDep::Anti)
310           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
311         else {
312           SDep Dep(SU, Kind, /*Reg=*/*Alias);
313           unsigned OutLatency =
314             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
315           Dep.setMinLatency(OutLatency);
316           Dep.setLatency(OutLatency);
317           DefSU->addPred(Dep);
318         }
319       }
320     }
321   }
322
323   if (!MO.isDef()) {
324     SU->hasPhysRegUses = true;
325     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
326     // retrieve the existing SUnits list for this register's uses.
327     // Push this SUnit on the use list.
328     Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
329   }
330   else {
331     addPhysRegDataDeps(SU, OperIdx);
332     unsigned Reg = MO.getReg();
333
334     // clear this register's use list
335     if (Uses.contains(Reg))
336       Uses.eraseAll(Reg);
337
338     if (!MO.isDead()) {
339       Defs.eraseAll(Reg);
340     } else if (SU->isCall) {
341       // Calls will not be reordered because of chain dependencies (see
342       // below). Since call operands are dead, calls may continue to be added
343       // to the DefList making dependence checking quadratic in the size of
344       // the block. Instead, we leave only one call at the back of the
345       // DefList.
346       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
347       Reg2SUnitsMap::iterator B = P.first;
348       Reg2SUnitsMap::iterator I = P.second;
349       for (bool isBegin = I == B; !isBegin; /* empty */) {
350         isBegin = (--I) == B;
351         if (!I->SU->isCall)
352           break;
353         I = Defs.erase(I);
354       }
355     }
356
357     // Defs are pushed in the order they are visited and never reordered.
358     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
359   }
360 }
361
362 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
363 /// to instructions that occur later in the same scheduling region if they read
364 /// from or write to the virtual register defined at OperIdx.
365 ///
366 /// TODO: Hoist loop induction variable increments. This has to be
367 /// reevaluated. Generally, IV scheduling should be done before coalescing.
368 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
369   const MachineInstr *MI = SU->getInstr();
370   unsigned Reg = MI->getOperand(OperIdx).getReg();
371
372   // Singly defined vregs do not have output/anti dependencies.
373   // The current operand is a def, so we have at least one.
374   // Check here if there are any others...
375   if (MRI.hasOneDef(Reg))
376     return;
377
378   // Add output dependence to the next nearest def of this vreg.
379   //
380   // Unless this definition is dead, the output dependence should be
381   // transitively redundant with antidependencies from this definition's
382   // uses. We're conservative for now until we have a way to guarantee the uses
383   // are not eliminated sometime during scheduling. The output dependence edge
384   // is also useful if output latency exceeds def-use latency.
385   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
386   if (DefI == VRegDefs.end())
387     VRegDefs.insert(VReg2SUnit(Reg, SU));
388   else {
389     SUnit *DefSU = DefI->SU;
390     if (DefSU != SU && DefSU != &ExitSU) {
391       SDep Dep(SU, SDep::Output, Reg);
392       unsigned OutLatency =
393         SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
394       Dep.setMinLatency(OutLatency);
395       Dep.setLatency(OutLatency);
396       DefSU->addPred(Dep);
397     }
398     DefI->SU = SU;
399   }
400 }
401
402 /// addVRegUseDeps - Add a register data dependency if the instruction that
403 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
404 /// register antidependency from this SUnit to instructions that occur later in
405 /// the same scheduling region if they write the virtual register.
406 ///
407 /// TODO: Handle ExitSU "uses" properly.
408 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
409   MachineInstr *MI = SU->getInstr();
410   unsigned Reg = MI->getOperand(OperIdx).getReg();
411
412   // Lookup this operand's reaching definition.
413   assert(LIS && "vreg dependencies requires LiveIntervals");
414   LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
415   VNInfo *VNI = LRQ.valueIn();
416
417   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
418   assert(VNI && "No value to read by operand");
419   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
420   // Phis and other noninstructions (after coalescing) have a NULL Def.
421   if (Def) {
422     SUnit *DefSU = getSUnit(Def);
423     if (DefSU) {
424       // The reaching Def lives within this scheduling region.
425       // Create a data dependence.
426       SDep dep(DefSU, SDep::Data, Reg);
427       // Adjust the dependence latency using operand def/use information, then
428       // allow the target to perform its own adjustments.
429       int DefOp = Def->findRegisterDefOperandIdx(Reg);
430       dep.setLatency(
431         SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false));
432       dep.setMinLatency(
433         SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true));
434
435       const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
436       ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
437       SU->addPred(dep);
438     }
439   }
440
441   // Add antidependence to the following def of the vreg it uses.
442   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
443   if (DefI != VRegDefs.end() && DefI->SU != SU)
444     DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
445 }
446
447 /// Return true if MI is an instruction we are unable to reason about
448 /// (like a call or something with unmodeled side effects).
449 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
450   if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
451       (MI->hasOrderedMemoryRef() &&
452        (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
453     return true;
454   return false;
455 }
456
457 // This MI might have either incomplete info, or known to be unsafe
458 // to deal with (i.e. volatile object).
459 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
460                                         const MachineFrameInfo *MFI) {
461   if (!MI || MI->memoperands_empty())
462     return true;
463   // We purposefully do no check for hasOneMemOperand() here
464   // in hope to trigger an assert downstream in order to
465   // finish implementation.
466   if ((*MI->memoperands_begin())->isVolatile() ||
467        MI->hasUnmodeledSideEffects())
468     return true;
469   const Value *V = (*MI->memoperands_begin())->getValue();
470   if (!V)
471     return true;
472
473   SmallVector<Value *, 4> Objs;
474   getUnderlyingObjects(V, Objs);
475   for (SmallVector<Value *, 4>::iterator I = Objs.begin(),
476        IE = Objs.end(); I != IE; ++I) {
477     V = *I;
478
479     if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
480       // Similarly to getUnderlyingObjectForInstr:
481       // For now, ignore PseudoSourceValues which may alias LLVM IR values
482       // because the code that uses this function has no way to cope with
483       // such aliases.
484       if (PSV->isAliased(MFI))
485         return true;
486     }
487
488     // Does this pointer refer to a distinct and identifiable object?
489     if (!isIdentifiedObject(V))
490       return true;
491   }
492
493   return false;
494 }
495
496 /// This returns true if the two MIs need a chain edge betwee them.
497 /// If these are not even memory operations, we still may need
498 /// chain deps between them. The question really is - could
499 /// these two MIs be reordered during scheduling from memory dependency
500 /// point of view.
501 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
502                              MachineInstr *MIa,
503                              MachineInstr *MIb) {
504   // Cover a trivial case - no edge is need to itself.
505   if (MIa == MIb)
506     return false;
507
508   if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
509     return true;
510
511   // If we are dealing with two "normal" loads, we do not need an edge
512   // between them - they could be reordered.
513   if (!MIa->mayStore() && !MIb->mayStore())
514     return false;
515
516   // To this point analysis is generic. From here on we do need AA.
517   if (!AA)
518     return true;
519
520   MachineMemOperand *MMOa = *MIa->memoperands_begin();
521   MachineMemOperand *MMOb = *MIb->memoperands_begin();
522
523   // FIXME: Need to handle multiple memory operands to support all targets.
524   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
525     llvm_unreachable("Multiple memory operands.");
526
527   // The following interface to AA is fashioned after DAGCombiner::isAlias
528   // and operates with MachineMemOperand offset with some important
529   // assumptions:
530   //   - LLVM fundamentally assumes flat address spaces.
531   //   - MachineOperand offset can *only* result from legalization and
532   //     cannot affect queries other than the trivial case of overlap
533   //     checking.
534   //   - These offsets never wrap and never step outside
535   //     of allocated objects.
536   //   - There should never be any negative offsets here.
537   //
538   // FIXME: Modify API to hide this math from "user"
539   // FIXME: Even before we go to AA we can reason locally about some
540   // memory objects. It can save compile time, and possibly catch some
541   // corner cases not currently covered.
542
543   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
544   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
545
546   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
547   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
548   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
549
550   AliasAnalysis::AliasResult AAResult = AA->alias(
551   AliasAnalysis::Location(MMOa->getValue(), Overlapa,
552                           MMOa->getTBAAInfo()),
553   AliasAnalysis::Location(MMOb->getValue(), Overlapb,
554                           MMOb->getTBAAInfo()));
555
556   return (AAResult != AliasAnalysis::NoAlias);
557 }
558
559 /// This recursive function iterates over chain deps of SUb looking for
560 /// "latest" node that needs a chain edge to SUa.
561 static unsigned
562 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
563                  SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
564                  SmallPtrSet<const SUnit*, 16> &Visited) {
565   if (!SUa || !SUb || SUb == ExitSU)
566     return *Depth;
567
568   // Remember visited nodes.
569   if (!Visited.insert(SUb))
570       return *Depth;
571   // If there is _some_ dependency already in place, do not
572   // descend any further.
573   // TODO: Need to make sure that if that dependency got eliminated or ignored
574   // for any reason in the future, we would not violate DAG topology.
575   // Currently it does not happen, but makes an implicit assumption about
576   // future implementation.
577   //
578   // Independently, if we encounter node that is some sort of global
579   // object (like a call) we already have full set of dependencies to it
580   // and we can stop descending.
581   if (SUa->isSucc(SUb) ||
582       isGlobalMemoryObject(AA, SUb->getInstr()))
583     return *Depth;
584
585   // If we do need an edge, or we have exceeded depth budget,
586   // add that edge to the predecessors chain of SUb,
587   // and stop descending.
588   if (*Depth > 200 ||
589       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
590     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
591     return *Depth;
592   }
593   // Track current depth.
594   (*Depth)++;
595   // Iterate over chain dependencies only.
596   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
597        I != E; ++I)
598     if (I->isCtrl())
599       iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
600   return *Depth;
601 }
602
603 /// This function assumes that "downward" from SU there exist
604 /// tail/leaf of already constructed DAG. It iterates downward and
605 /// checks whether SU can be aliasing any node dominated
606 /// by it.
607 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
608                             SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
609                             unsigned LatencyToLoad) {
610   if (!SU)
611     return;
612
613   SmallPtrSet<const SUnit*, 16> Visited;
614   unsigned Depth = 0;
615
616   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
617        I != IE; ++I) {
618     if (SU == *I)
619       continue;
620     if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
621       SDep Dep(SU, SDep::MayAliasMem);
622       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
623       (*I)->addPred(Dep);
624     }
625     // Now go through all the chain successors and iterate from them.
626     // Keep track of visited nodes.
627     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
628          JE = (*I)->Succs.end(); J != JE; ++J)
629       if (J->isCtrl())
630         iterateChainSucc (AA, MFI, SU, J->getSUnit(),
631                           ExitSU, &Depth, Visited);
632   }
633 }
634
635 /// Check whether two objects need a chain edge, if so, add it
636 /// otherwise remember the rejected SU.
637 static inline
638 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
639                          SUnit *SUa, SUnit *SUb,
640                          std::set<SUnit *> &RejectList,
641                          unsigned TrueMemOrderLatency = 0,
642                          bool isNormalMemory = false) {
643   // If this is a false dependency,
644   // do not add the edge, but rememeber the rejected node.
645   if (!EnableAASchedMI ||
646       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
647     SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
648     Dep.setLatency(TrueMemOrderLatency);
649     SUb->addPred(Dep);
650   }
651   else {
652     // Duplicate entries should be ignored.
653     RejectList.insert(SUb);
654     DEBUG(dbgs() << "\tReject chain dep between SU("
655           << SUa->NodeNum << ") and SU("
656           << SUb->NodeNum << ")\n");
657   }
658 }
659
660 /// Create an SUnit for each real instruction, numbered in top-down toplological
661 /// order. The instruction order A < B, implies that no edge exists from B to A.
662 ///
663 /// Map each real instruction to its SUnit.
664 ///
665 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
666 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
667 /// instead of pointers.
668 ///
669 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
670 /// the original instruction list.
671 void ScheduleDAGInstrs::initSUnits() {
672   // We'll be allocating one SUnit for each real instruction in the region,
673   // which is contained within a basic block.
674   SUnits.reserve(BB->size());
675
676   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
677     MachineInstr *MI = I;
678     if (MI->isDebugValue())
679       continue;
680
681     SUnit *SU = newSUnit(MI);
682     MISUnitMap[MI] = SU;
683
684     SU->isCall = MI->isCall();
685     SU->isCommutable = MI->isCommutable();
686
687     // Assign the Latency field of SU using target-provided information.
688     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
689   }
690 }
691
692 /// If RegPressure is non null, compute register pressure as a side effect. The
693 /// DAG builder is an efficient place to do it because it already visits
694 /// operands.
695 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
696                                         RegPressureTracker *RPTracker) {
697   // Create an SUnit for each real instruction.
698   initSUnits();
699
700   // We build scheduling units by walking a block's instruction list from bottom
701   // to top.
702
703   // Remember where a generic side-effecting instruction is as we procede.
704   SUnit *BarrierChain = 0, *AliasChain = 0;
705
706   // Memory references to specific known memory locations are tracked
707   // so that they can be given more precise dependencies. We track
708   // separately the known memory locations that may alias and those
709   // that are known not to alias
710   MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
711   MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
712   std::set<SUnit*> RejectMemNodes;
713
714   // Remove any stale debug info; sometimes BuildSchedGraph is called again
715   // without emitting the info from the previous call.
716   DbgValues.clear();
717   FirstDbgValue = NULL;
718
719   assert(Defs.empty() && Uses.empty() &&
720          "Only BuildGraph should update Defs/Uses");
721   Defs.setUniverse(TRI->getNumRegs());
722   Uses.setUniverse(TRI->getNumRegs());
723
724   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
725   // FIXME: Allow SparseSet to reserve space for the creation of virtual
726   // registers during scheduling. Don't artificially inflate the Universe
727   // because we want to assert that vregs are not created during DAG building.
728   VRegDefs.setUniverse(MRI.getNumVirtRegs());
729
730   // Model data dependencies between instructions being scheduled and the
731   // ExitSU.
732   addSchedBarrierDeps();
733
734   // Walk the list of instructions, from bottom moving up.
735   MachineInstr *DbgMI = NULL;
736   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
737        MII != MIE; --MII) {
738     MachineInstr *MI = prior(MII);
739     if (MI && DbgMI) {
740       DbgValues.push_back(std::make_pair(DbgMI, MI));
741       DbgMI = NULL;
742     }
743
744     if (MI->isDebugValue()) {
745       DbgMI = MI;
746       continue;
747     }
748     if (RPTracker) {
749       RPTracker->recede();
750       assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
751     }
752
753     assert((CanHandleTerminators || (!MI->isTerminator() && !MI->isLabel())) &&
754            "Cannot schedule terminators or labels!");
755
756     SUnit *SU = MISUnitMap[MI];
757     assert(SU && "No SUnit mapped to this MI");
758
759     // Add register-based dependencies (data, anti, and output).
760     bool HasVRegDef = false;
761     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
762       const MachineOperand &MO = MI->getOperand(j);
763       if (!MO.isReg()) continue;
764       unsigned Reg = MO.getReg();
765       if (Reg == 0) continue;
766
767       if (TRI->isPhysicalRegister(Reg))
768         addPhysRegDeps(SU, j);
769       else {
770         assert(!IsPostRA && "Virtual register encountered!");
771         if (MO.isDef()) {
772           HasVRegDef = true;
773           addVRegDefDeps(SU, j);
774         }
775         else if (MO.readsReg()) // ignore undef operands
776           addVRegUseDeps(SU, j);
777       }
778     }
779     // If we haven't seen any uses in this scheduling region, create a
780     // dependence edge to ExitSU to model the live-out latency. This is required
781     // for vreg defs with no in-region use, and prefetches with no vreg def.
782     //
783     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
784     // check currently relies on being called before adding chain deps.
785     if (SU->NumSuccs == 0 && SU->Latency > 1
786         && (HasVRegDef || MI->mayLoad())) {
787       SDep Dep(SU, SDep::Artificial);
788       Dep.setLatency(SU->Latency - 1);
789       ExitSU.addPred(Dep);
790     }
791
792     // Add chain dependencies.
793     // Chain dependencies used to enforce memory order should have
794     // latency of 0 (except for true dependency of Store followed by
795     // aliased Load... we estimate that with a single cycle of latency
796     // assuming the hardware will bypass)
797     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
798     // after stack slots are lowered to actual addresses.
799     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
800     // produce more precise dependence information.
801     unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
802     if (isGlobalMemoryObject(AA, MI)) {
803       // Be conservative with these and add dependencies on all memory
804       // references, even those that are known to not alias.
805       for (MapVector<const Value *, SUnit *>::iterator I =
806              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
807         I->second->addPred(SDep(SU, SDep::Barrier));
808       }
809       for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
810              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
811         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
812           SDep Dep(SU, SDep::Barrier);
813           Dep.setLatency(TrueMemOrderLatency);
814           I->second[i]->addPred(Dep);
815         }
816       }
817       // Add SU to the barrier chain.
818       if (BarrierChain)
819         BarrierChain->addPred(SDep(SU, SDep::Barrier));
820       BarrierChain = SU;
821       // This is a barrier event that acts as a pivotal node in the DAG,
822       // so it is safe to clear list of exposed nodes.
823       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
824                       TrueMemOrderLatency);
825       RejectMemNodes.clear();
826       NonAliasMemDefs.clear();
827       NonAliasMemUses.clear();
828
829       // fall-through
830     new_alias_chain:
831       // Chain all possibly aliasing memory references though SU.
832       if (AliasChain) {
833         unsigned ChainLatency = 0;
834         if (AliasChain->getInstr()->mayLoad())
835           ChainLatency = TrueMemOrderLatency;
836         addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
837                            ChainLatency);
838       }
839       AliasChain = SU;
840       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
841         addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
842                            TrueMemOrderLatency);
843       for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
844            E = AliasMemDefs.end(); I != E; ++I)
845         addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
846       for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
847            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
848         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
849           addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
850                              TrueMemOrderLatency);
851       }
852       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
853                       TrueMemOrderLatency);
854       PendingLoads.clear();
855       AliasMemDefs.clear();
856       AliasMemUses.clear();
857     } else if (MI->mayStore()) {
858       SmallVector<std::pair<const Value *, bool>, 4> Objs;
859       getUnderlyingObjectsForInstr(MI, MFI, Objs);
860
861       if (Objs.empty()) {
862         // Treat all other stores conservatively.
863         goto new_alias_chain;
864       }
865
866       bool MayAlias = false;
867       for (SmallVector<std::pair<const Value *, bool>, 4>::iterator
868            K = Objs.begin(), KE = Objs.end(); K != KE; ++K) {
869         const Value *V = K->first;
870         bool ThisMayAlias = K->second;
871         if (ThisMayAlias)
872           MayAlias = true;
873
874         // A store to a specific PseudoSourceValue. Add precise dependencies.
875         // Record the def in MemDefs, first adding a dep if there is
876         // an existing def.
877         MapVector<const Value *, SUnit *>::iterator I =
878           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
879         MapVector<const Value *, SUnit *>::iterator IE =
880           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
881         if (I != IE) {
882           addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
883           I->second = SU;
884         } else {
885           if (ThisMayAlias)
886             AliasMemDefs[V] = SU;
887           else
888             NonAliasMemDefs[V] = SU;
889         }
890         // Handle the uses in MemUses, if there are any.
891         MapVector<const Value *, std::vector<SUnit *> >::iterator J =
892           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
893         MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
894           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
895         if (J != JE) {
896           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
897             addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
898                                TrueMemOrderLatency, true);
899           J->second.clear();
900         }
901       }
902       if (MayAlias) {
903         // Add dependencies from all the PendingLoads, i.e. loads
904         // with no underlying object.
905         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
906           addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
907                              TrueMemOrderLatency);
908         // Add dependence on alias chain, if needed.
909         if (AliasChain)
910           addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
911         // But we also should check dependent instructions for the
912         // SU in question.
913         adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
914                         TrueMemOrderLatency);
915       }
916       // Add dependence on barrier chain, if needed.
917       // There is no point to check aliasing on barrier event. Even if
918       // SU and barrier _could_ be reordered, they should not. In addition,
919       // we have lost all RejectMemNodes below barrier.
920       if (BarrierChain)
921         BarrierChain->addPred(SDep(SU, SDep::Barrier));
922
923       if (!ExitSU.isPred(SU))
924         // Push store's up a bit to avoid them getting in between cmp
925         // and branches.
926         ExitSU.addPred(SDep(SU, SDep::Artificial));
927     } else if (MI->mayLoad()) {
928       bool MayAlias = true;
929       if (MI->isInvariantLoad(AA)) {
930         // Invariant load, no chain dependencies needed!
931       } else {
932         SmallVector<std::pair<const Value *, bool>, 4> Objs;
933         getUnderlyingObjectsForInstr(MI, MFI, Objs);
934
935         if (Objs.empty()) {
936           // A load with no underlying object. Depend on all
937           // potentially aliasing stores.
938           for (MapVector<const Value *, SUnit *>::iterator I =
939                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
940             addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
941
942           PendingLoads.push_back(SU);
943           MayAlias = true;
944         } else {
945           MayAlias = false;
946         }
947
948         for (SmallVector<std::pair<const Value *, bool>, 4>::iterator
949              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
950           const Value *V = J->first;
951           bool ThisMayAlias = J->second;
952
953           if (ThisMayAlias)
954             MayAlias = true;
955
956           // A load from a specific PseudoSourceValue. Add precise dependencies.
957           MapVector<const Value *, SUnit *>::iterator I =
958             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
959           MapVector<const Value *, SUnit *>::iterator IE =
960             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
961           if (I != IE)
962             addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
963           if (ThisMayAlias)
964             AliasMemUses[V].push_back(SU);
965           else
966             NonAliasMemUses[V].push_back(SU);
967         }
968         if (MayAlias)
969           adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
970         // Add dependencies on alias and barrier chains, if needed.
971         if (MayAlias && AliasChain)
972           addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
973         if (BarrierChain)
974           BarrierChain->addPred(SDep(SU, SDep::Barrier));
975       }
976     }
977   }
978   if (DbgMI)
979     FirstDbgValue = DbgMI;
980
981   Defs.clear();
982   Uses.clear();
983   VRegDefs.clear();
984   PendingLoads.clear();
985 }
986
987 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
988 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
989   SU->getInstr()->dump();
990 #endif
991 }
992
993 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
994   std::string s;
995   raw_string_ostream oss(s);
996   if (SU == &EntrySU)
997     oss << "<entry>";
998   else if (SU == &ExitSU)
999     oss << "<exit>";
1000   else
1001     SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
1002   return oss.str();
1003 }
1004
1005 /// Return the basic block label. It is not necessarilly unique because a block
1006 /// contains multiple scheduling regions. But it is fine for visualization.
1007 std::string ScheduleDAGInstrs::getDAGName() const {
1008   return "dag." + BB->getFullName();
1009 }
1010
1011 //===----------------------------------------------------------------------===//
1012 // SchedDFSResult Implementation
1013 //===----------------------------------------------------------------------===//
1014
1015 namespace llvm {
1016 /// \brief Internal state used to compute SchedDFSResult.
1017 class SchedDFSImpl {
1018   SchedDFSResult &R;
1019
1020   /// Join DAG nodes into equivalence classes by their subtree.
1021   IntEqClasses SubtreeClasses;
1022   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1023   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1024
1025   struct RootData {
1026     unsigned NodeID;
1027     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
1028     unsigned SubInstrCount; // Instr count in this tree only, not children.
1029
1030     RootData(unsigned id): NodeID(id),
1031                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1032                            SubInstrCount(0) {}
1033
1034     unsigned getSparseSetIndex() const { return NodeID; }
1035   };
1036
1037   SparseSet<RootData> RootSet;
1038
1039 public:
1040   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1041     RootSet.setUniverse(R.DFSNodeData.size());
1042   }
1043
1044   /// Return true if this node been visited by the DFS traversal.
1045   ///
1046   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1047   /// ID. Later, SubtreeID is updated but remains valid.
1048   bool isVisited(const SUnit *SU) const {
1049     return R.DFSNodeData[SU->NodeNum].SubtreeID
1050       != SchedDFSResult::InvalidSubtreeID;
1051   }
1052
1053   /// Initialize this node's instruction count. We don't need to flag the node
1054   /// visited until visitPostorder because the DAG cannot have cycles.
1055   void visitPreorder(const SUnit *SU) {
1056     R.DFSNodeData[SU->NodeNum].InstrCount =
1057       SU->getInstr()->isTransient() ? 0 : 1;
1058   }
1059
1060   /// Called once for each node after all predecessors are visited. Revisit this
1061   /// node's predecessors and potentially join them now that we know the ILP of
1062   /// the other predecessors.
1063   void visitPostorderNode(const SUnit *SU) {
1064     // Mark this node as the root of a subtree. It may be joined with its
1065     // successors later.
1066     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1067     RootData RData(SU->NodeNum);
1068     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1069
1070     // If any predecessors are still in their own subtree, they either cannot be
1071     // joined or are large enough to remain separate. If this parent node's
1072     // total instruction count is not greater than a child subtree by at least
1073     // the subtree limit, then try to join it now since splitting subtrees is
1074     // only useful if multiple high-pressure paths are possible.
1075     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1076     for (SUnit::const_pred_iterator
1077            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1078       if (PI->getKind() != SDep::Data)
1079         continue;
1080       unsigned PredNum = PI->getSUnit()->NodeNum;
1081       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1082         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
1083
1084       // Either link or merge the TreeData entry from the child to the parent.
1085       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1086         // If the predecessor's parent is invalid, this is a tree edge and the
1087         // current node is the parent.
1088         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1089           RootSet[PredNum].ParentNodeID = SU->NodeNum;
1090       }
1091       else if (RootSet.count(PredNum)) {
1092         // The predecessor is not a root, but is still in the root set. This
1093         // must be the new parent that it was just joined to. Note that
1094         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1095         // set to the original parent.
1096         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1097         RootSet.erase(PredNum);
1098       }
1099     }
1100     RootSet[SU->NodeNum] = RData;
1101   }
1102
1103   /// Called once for each tree edge after calling visitPostOrderNode on the
1104   /// predecessor. Increment the parent node's instruction count and
1105   /// preemptively join this subtree to its parent's if it is small enough.
1106   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1107     R.DFSNodeData[Succ->NodeNum].InstrCount
1108       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1109     joinPredSubtree(PredDep, Succ);
1110   }
1111
1112   /// Add a connection for cross edges.
1113   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1114     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1115   }
1116
1117   /// Set each node's subtree ID to the representative ID and record connections
1118   /// between trees.
1119   void finalize() {
1120     SubtreeClasses.compress();
1121     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1122     assert(SubtreeClasses.getNumClasses() == RootSet.size()
1123            && "number of roots should match trees");
1124     for (SparseSet<RootData>::const_iterator
1125            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1126       unsigned TreeID = SubtreeClasses[RI->NodeID];
1127       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1128         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1129       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
1130       // Note that SubInstrCount may be greater than InstrCount if we joined
1131       // subtrees across a cross edge. InstrCount will be attributed to the
1132       // original parent, while SubInstrCount will be attributed to the joined
1133       // parent.
1134     }
1135     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1136     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1137     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1138     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1139       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1140       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1141             << R.DFSNodeData[Idx].SubtreeID << '\n');
1142     }
1143     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1144            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1145          I != E; ++I) {
1146       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1147       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1148       if (PredTree == SuccTree)
1149         continue;
1150       unsigned Depth = I->first->getDepth();
1151       addConnection(PredTree, SuccTree, Depth);
1152       addConnection(SuccTree, PredTree, Depth);
1153     }
1154   }
1155
1156 protected:
1157   /// Join the predecessor subtree with the successor that is its DFS
1158   /// parent. Apply some heuristics before joining.
1159   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1160                        bool CheckLimit = true) {
1161     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1162
1163     // Check if the predecessor is already joined.
1164     const SUnit *PredSU = PredDep.getSUnit();
1165     unsigned PredNum = PredSU->NodeNum;
1166     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1167       return false;
1168
1169     // Four is the magic number of successors before a node is considered a
1170     // pinch point.
1171     unsigned NumDataSucs = 0;
1172     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1173            SE = PredSU->Succs.end(); SI != SE; ++SI) {
1174       if (SI->getKind() == SDep::Data) {
1175         if (++NumDataSucs >= 4)
1176           return false;
1177       }
1178     }
1179     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1180       return false;
1181     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1182     SubtreeClasses.join(Succ->NodeNum, PredNum);
1183     return true;
1184   }
1185
1186   /// Called by finalize() to record a connection between trees.
1187   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1188     if (!Depth)
1189       return;
1190
1191     do {
1192       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1193         R.SubtreeConnections[FromTree];
1194       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1195              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1196         if (I->TreeID == ToTree) {
1197           I->Level = std::max(I->Level, Depth);
1198           return;
1199         }
1200       }
1201       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1202       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1203     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1204   }
1205 };
1206 } // namespace llvm
1207
1208 namespace {
1209 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
1210 class SchedDAGReverseDFS {
1211   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1212 public:
1213   bool isComplete() const { return DFSStack.empty(); }
1214
1215   void follow(const SUnit *SU) {
1216     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1217   }
1218   void advance() { ++DFSStack.back().second; }
1219
1220   const SDep *backtrack() {
1221     DFSStack.pop_back();
1222     return DFSStack.empty() ? 0 : llvm::prior(DFSStack.back().second);
1223   }
1224
1225   const SUnit *getCurr() const { return DFSStack.back().first; }
1226
1227   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1228
1229   SUnit::const_pred_iterator getPredEnd() const {
1230     return getCurr()->Preds.end();
1231   }
1232 };
1233 } // anonymous
1234
1235 static bool hasDataSucc(const SUnit *SU) {
1236   for (SUnit::const_succ_iterator
1237          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
1238     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
1239       return true;
1240   }
1241   return false;
1242 }
1243
1244 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1245 /// search from this root.
1246 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1247   if (!IsBottomUp)
1248     llvm_unreachable("Top-down ILP metric is unimplemnted");
1249
1250   SchedDFSImpl Impl(*this);
1251   for (ArrayRef<SUnit>::const_iterator
1252          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1253     const SUnit *SU = &*SI;
1254     if (Impl.isVisited(SU) || hasDataSucc(SU))
1255       continue;
1256
1257     SchedDAGReverseDFS DFS;
1258     Impl.visitPreorder(SU);
1259     DFS.follow(SU);
1260     for (;;) {
1261       // Traverse the leftmost path as far as possible.
1262       while (DFS.getPred() != DFS.getPredEnd()) {
1263         const SDep &PredDep = *DFS.getPred();
1264         DFS.advance();
1265         // Ignore non-data edges.
1266         if (PredDep.getKind() != SDep::Data
1267             || PredDep.getSUnit()->isBoundaryNode()) {
1268           continue;
1269         }
1270         // An already visited edge is a cross edge, assuming an acyclic DAG.
1271         if (Impl.isVisited(PredDep.getSUnit())) {
1272           Impl.visitCrossEdge(PredDep, DFS.getCurr());
1273           continue;
1274         }
1275         Impl.visitPreorder(PredDep.getSUnit());
1276         DFS.follow(PredDep.getSUnit());
1277       }
1278       // Visit the top of the stack in postorder and backtrack.
1279       const SUnit *Child = DFS.getCurr();
1280       const SDep *PredDep = DFS.backtrack();
1281       Impl.visitPostorderNode(Child);
1282       if (PredDep)
1283         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1284       if (DFS.isComplete())
1285         break;
1286     }
1287   }
1288   Impl.finalize();
1289 }
1290
1291 /// The root of the given SubtreeID was just scheduled. For all subtrees
1292 /// connected to this tree, record the depth of the connection so that the
1293 /// nearest connected subtrees can be prioritized.
1294 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1295   for (SmallVectorImpl<Connection>::const_iterator
1296          I = SubtreeConnections[SubtreeID].begin(),
1297          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1298     SubtreeConnectLevels[I->TreeID] =
1299       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1300     DEBUG(dbgs() << "  Tree: " << I->TreeID
1301           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
1302   }
1303 }
1304
1305 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1306 void ILPValue::print(raw_ostream &OS) const {
1307   OS << InstrCount << " / " << Length << " = ";
1308   if (!Length)
1309     OS << "BADILP";
1310   else
1311     OS << format("%g", ((double)InstrCount / Length));
1312 }
1313
1314 void ILPValue::dump() const {
1315   dbgs() << *this << '\n';
1316 }
1317
1318 namespace llvm {
1319
1320 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1321   Val.print(OS);
1322   return OS;
1323 }
1324
1325 } // namespace llvm
1326 #endif // !NDEBUG || LLVM_ENABLE_DUMP