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