2858904fde3cbddc86147c31db999b363857d466
[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 "ScheduleDAGInstrs.h"
17 #include "llvm/Operator.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineMemOperand.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/MC/MCInstrItineraries.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/SmallSet.h"
33 using namespace llvm;
34
35 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
36                                      const MachineLoopInfo &mli,
37                                      const MachineDominatorTree &mdt,
38                                      bool IsPostRAFlag,
39                                      LiveIntervals *lis)
40   : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()),
41     InstrItins(mf.getTarget().getInstrItineraryData()), IsPostRA(IsPostRAFlag),
42     LIS(lis), UnitLatencies(false), LoopRegs(MLI, MDT), FirstDbgValue(0) {
43   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
44   DbgValues.clear();
45   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
46          "Virtual registers must be removed prior to PostRA scheduling");
47 }
48
49 /// Run - perform scheduling.
50 ///
51 void ScheduleDAGInstrs::Run(MachineBasicBlock *bb,
52                             MachineBasicBlock::iterator begin,
53                             MachineBasicBlock::iterator end,
54                             unsigned endcount) {
55   BB = bb;
56   Begin = begin;
57   InsertPosIndex = endcount;
58
59   // Check to see if the scheduler cares about latencies.
60   UnitLatencies = ForceUnitLatencies();
61
62   ScheduleDAG::Run(bb, end);
63 }
64
65 /// getUnderlyingObjectFromInt - This is the function that does the work of
66 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
67 static const Value *getUnderlyingObjectFromInt(const Value *V) {
68   do {
69     if (const Operator *U = dyn_cast<Operator>(V)) {
70       // If we find a ptrtoint, we can transfer control back to the
71       // regular getUnderlyingObjectFromInt.
72       if (U->getOpcode() == Instruction::PtrToInt)
73         return U->getOperand(0);
74       // If we find an add of a constant or a multiplied value, it's
75       // likely that the other operand will lead us to the base
76       // object. We don't have to worry about the case where the
77       // object address is somehow being computed by the multiply,
78       // because our callers only care when the result is an
79       // identifibale object.
80       if (U->getOpcode() != Instruction::Add ||
81           (!isa<ConstantInt>(U->getOperand(1)) &&
82            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
83         return V;
84       V = U->getOperand(0);
85     } else {
86       return V;
87     }
88     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
89   } while (1);
90 }
91
92 /// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
93 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
94 static const Value *getUnderlyingObject(const Value *V) {
95   // First just call Value::getUnderlyingObject to let it do what it does.
96   do {
97     V = GetUnderlyingObject(V);
98     // If it found an inttoptr, use special code to continue climing.
99     if (Operator::getOpcode(V) != Instruction::IntToPtr)
100       break;
101     const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
102     // If that succeeded in finding a pointer, continue the search.
103     if (!O->getType()->isPointerTy())
104       break;
105     V = O;
106   } while (1);
107   return V;
108 }
109
110 /// getUnderlyingObjectForInstr - If this machine instr has memory reference
111 /// information and it can be tracked to a normal reference to a known
112 /// object, return the Value for that object. Otherwise return null.
113 static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
114                                                 const MachineFrameInfo *MFI,
115                                                 bool &MayAlias) {
116   MayAlias = true;
117   if (!MI->hasOneMemOperand() ||
118       !(*MI->memoperands_begin())->getValue() ||
119       (*MI->memoperands_begin())->isVolatile())
120     return 0;
121
122   const Value *V = (*MI->memoperands_begin())->getValue();
123   if (!V)
124     return 0;
125
126   V = getUnderlyingObject(V);
127   if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
128     // For now, ignore PseudoSourceValues which may alias LLVM IR values
129     // because the code that uses this function has no way to cope with
130     // such aliases.
131     if (PSV->isAliased(MFI))
132       return 0;
133
134     MayAlias = PSV->mayAlias(MFI);
135     return V;
136   }
137
138   if (isIdentifiedObject(V))
139     return V;
140
141   return 0;
142 }
143
144 void ScheduleDAGInstrs::StartBlock(MachineBasicBlock *BB) {
145   LoopRegs.Deps.clear();
146   if (MachineLoop *ML = MLI.getLoopFor(BB))
147     if (BB == ML->getLoopLatch())
148       LoopRegs.VisitLoop(ML);
149 }
150
151 /// AddSchedBarrierDeps - Add dependencies from instructions in the current
152 /// list of instructions being scheduled to scheduling barrier by adding
153 /// the exit SU to the register defs and use list. This is because we want to
154 /// make sure instructions which define registers that are either used by
155 /// the terminator or are live-out are properly scheduled. This is
156 /// especially important when the definition latency of the return value(s)
157 /// are too high to be hidden by the branch or when the liveout registers
158 /// used by instructions in the fallthrough block.
159 void ScheduleDAGInstrs::AddSchedBarrierDeps() {
160   MachineInstr *ExitMI = InsertPos != BB->end() ? &*InsertPos : 0;
161   ExitSU.setInstr(ExitMI);
162   bool AllDepKnown = ExitMI &&
163     (ExitMI->isCall() || ExitMI->isBarrier());
164   if (ExitMI && AllDepKnown) {
165     // If it's a call or a barrier, add dependencies on the defs and uses of
166     // instruction.
167     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
168       const MachineOperand &MO = ExitMI->getOperand(i);
169       if (!MO.isReg() || MO.isDef()) continue;
170       unsigned Reg = MO.getReg();
171       if (Reg == 0) continue;
172
173       if (TRI->isPhysicalRegister(Reg))
174         Uses[Reg].SUnits.push_back(&ExitSU);
175       else
176         assert(!IsPostRA && "Virtual register encountered after regalloc.");
177     }
178   } else {
179     // For others, e.g. fallthrough, conditional branch, assume the exit
180     // uses all the registers that are livein to the successor blocks.
181     SmallSet<unsigned, 8> Seen;
182     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
183            SE = BB->succ_end(); SI != SE; ++SI)
184       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
185              E = (*SI)->livein_end(); I != E; ++I) {
186         unsigned Reg = *I;
187         if (Seen.insert(Reg))
188           Uses[Reg].SUnits.push_back(&ExitSU);
189       }
190   }
191 }
192
193 /// MO is an operand of SU's instruction that defines a physical register. Add
194 /// data dependencies from SU to any uses of the physical register.
195 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU,
196                                            const MachineOperand &MO) {
197   assert(MO.isDef() && "expect physreg def");
198
199   // Ask the target if address-backscheduling is desirable, and if so how much.
200   const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
201   unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
202   unsigned DataLatency = SU->Latency;
203
204   for (const unsigned *Alias = TRI->getOverlaps(MO.getReg()); *Alias; ++Alias) {
205     Reg2SUnitsMap::iterator UsesI = Uses.find(*Alias);
206     if (UsesI == Uses.end())
207       continue;
208     std::vector<SUnit*> &UseList = UsesI->SUnits;
209     for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
210       SUnit *UseSU = UseList[i];
211       if (UseSU == SU)
212         continue;
213       unsigned LDataLatency = DataLatency;
214       // Optionally add in a special extra latency for nodes that
215       // feed addresses.
216       // TODO: Perhaps we should get rid of
217       // SpecialAddressLatency and just move this into
218       // adjustSchedDependency for the targets that care about it.
219       if (SpecialAddressLatency != 0 && !UnitLatencies &&
220           UseSU != &ExitSU) {
221         MachineInstr *UseMI = UseSU->getInstr();
222         const MCInstrDesc &UseMCID = UseMI->getDesc();
223         int RegUseIndex = UseMI->findRegisterUseOperandIdx(*Alias);
224         assert(RegUseIndex >= 0 && "UseMI doesn't use register!");
225         if (RegUseIndex >= 0 &&
226             (UseMI->mayLoad() || UseMI->mayStore()) &&
227             (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
228             UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
229           LDataLatency += SpecialAddressLatency;
230       }
231       // Adjust the dependence latency using operand def/use
232       // information (if any), and then allow the target to
233       // perform its own adjustments.
234       const SDep& dep = SDep(SU, SDep::Data, LDataLatency, *Alias);
235       if (!UnitLatencies) {
236         ComputeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
237         ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
238       }
239       UseSU->addPred(dep);
240     }
241   }
242 }
243
244 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
245 /// this SUnit to following instructions in the same scheduling region that
246 /// depend the physical register referenced at OperIdx.
247 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
248   const MachineInstr *MI = SU->getInstr();
249   const MachineOperand &MO = MI->getOperand(OperIdx);
250
251   // Optionally add output and anti dependencies. For anti
252   // dependencies we use a latency of 0 because for a multi-issue
253   // target we want to allow the defining instruction to issue
254   // in the same cycle as the using instruction.
255   // TODO: Using a latency of 1 here for output dependencies assumes
256   //       there's no cost for reusing registers.
257   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
258   for (const unsigned *Alias = TRI->getOverlaps(MO.getReg()); *Alias; ++Alias) {
259     Reg2SUnitsMap::iterator DefI = Defs.find(*Alias);
260     if (DefI == Defs.end())
261       continue;
262     std::vector<SUnit *> &DefList = DefI->SUnits;
263     for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
264       SUnit *DefSU = DefList[i];
265       if (DefSU == &ExitSU)
266         continue;
267       if (DefSU != SU &&
268           (Kind != SDep::Output || !MO.isDead() ||
269            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
270         if (Kind == SDep::Anti)
271           DefSU->addPred(SDep(SU, Kind, 0, /*Reg=*/*Alias));
272         else {
273           unsigned AOLat = TII->getOutputLatency(InstrItins, MI, OperIdx,
274                                                  DefSU->getInstr());
275           DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=*/*Alias));
276         }
277       }
278     }
279   }
280
281   if (!MO.isDef()) {
282     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
283     // retrieve the existing SUnits list for this register's uses.
284     // Push this SUnit on the use list.
285     Uses[MO.getReg()].SUnits.push_back(SU);
286   }
287   else {
288     addPhysRegDataDeps(SU, MO);
289
290     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
291     // retrieve the existing SUnits list for this register's defs.
292     std::vector<SUnit *> &DefList = Defs[MO.getReg()].SUnits;
293
294     // If a def is going to wrap back around to the top of the loop,
295     // backschedule it.
296     if (!UnitLatencies && DefList.empty()) {
297       LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(MO.getReg());
298       if (I != LoopRegs.Deps.end()) {
299         const MachineOperand *UseMO = I->second.first;
300         unsigned Count = I->second.second;
301         const MachineInstr *UseMI = UseMO->getParent();
302         unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
303         const MCInstrDesc &UseMCID = UseMI->getDesc();
304         const TargetSubtargetInfo &ST =
305           TM.getSubtarget<TargetSubtargetInfo>();
306         unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
307         // TODO: If we knew the total depth of the region here, we could
308         // handle the case where the whole loop is inside the region but
309         // is large enough that the isScheduleHigh trick isn't needed.
310         if (UseMOIdx < UseMCID.getNumOperands()) {
311           // Currently, we only support scheduling regions consisting of
312           // single basic blocks. Check to see if the instruction is in
313           // the same region by checking to see if it has the same parent.
314           if (UseMI->getParent() != MI->getParent()) {
315             unsigned Latency = SU->Latency;
316             if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
317               Latency += SpecialAddressLatency;
318             // This is a wild guess as to the portion of the latency which
319             // will be overlapped by work done outside the current
320             // scheduling region.
321             Latency -= std::min(Latency, Count);
322             // Add the artificial edge.
323             ExitSU.addPred(SDep(SU, SDep::Order, Latency,
324                                 /*Reg=*/0, /*isNormalMemory=*/false,
325                                 /*isMustAlias=*/false,
326                                 /*isArtificial=*/true));
327           } else if (SpecialAddressLatency > 0 &&
328                      UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
329             // The entire loop body is within the current scheduling region
330             // and the latency of this operation is assumed to be greater
331             // than the latency of the loop.
332             // TODO: Recursively mark data-edge predecessors as
333             //       isScheduleHigh too.
334             SU->isScheduleHigh = true;
335           }
336         }
337         LoopRegs.Deps.erase(I);
338       }
339     }
340
341     // clear this register's use list
342     Reg2SUnitsMap::iterator UsesI = Uses.find(MO.getReg());
343     if (UsesI != Uses.end())
344       UsesI->SUnits.clear();
345
346     if (!MO.isDead())
347       DefList.clear();
348
349     // Calls will not be reordered because of chain dependencies (see
350     // below). Since call operands are dead, calls may continue to be added
351     // to the DefList making dependence checking quadratic in the size of
352     // the block. Instead, we leave only one call at the back of the
353     // DefList.
354     if (SU->isCall) {
355       while (!DefList.empty() && DefList.back()->isCall)
356         DefList.pop_back();
357     }
358     // Defs are pushed in the order they are visited and never reordered.
359     DefList.push_back(SU);
360   }
361 }
362
363 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
364 /// to instructions that occur later in the same scheduling region if they read
365 /// from or write to the virtual register defined at OperIdx.
366 ///
367 /// TODO: Hoist loop induction variable increments. This has to be
368 /// reevaluated. Generally, IV scheduling should be done before coalescing.
369 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
370   const MachineInstr *MI = SU->getInstr();
371   unsigned Reg = MI->getOperand(OperIdx).getReg();
372
373   // SSA defs do not have output/anti dependencies.
374   // The current operand is a def, so we have at least one.
375   if (llvm::next(MRI.def_begin(Reg)) == MRI.def_end())
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 = findVRegDef(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       unsigned OutLatency = TII->getOutputLatency(InstrItins, MI, OperIdx,
392                                                   DefSU->getInstr());
393       DefSU->addPred(SDep(SU, SDep::Output, OutLatency, Reg));
394     }
395     DefI->SU = SU;
396   }
397 }
398
399 /// addVRegUseDeps - Add a register data dependency if the instruction that
400 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
401 /// register antidependency from this SUnit to instructions that occur later in
402 /// the same scheduling region if they write the virtual register.
403 ///
404 /// TODO: Handle ExitSU "uses" properly.
405 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
406   MachineInstr *MI = SU->getInstr();
407   unsigned Reg = MI->getOperand(OperIdx).getReg();
408
409   // Lookup this operand's reaching definition.
410   assert(LIS && "vreg dependencies requires LiveIntervals");
411   SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot();
412   LiveInterval *LI = &LIS->getInterval(Reg);
413   VNInfo *VNI = LI->getVNInfoBefore(UseIdx);
414   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
415   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
416   // Phis and other noninstructions (after coalescing) have a NULL Def.
417   if (Def) {
418     SUnit *DefSU = getSUnit(Def);
419     if (DefSU) {
420       // The reaching Def lives within this scheduling region.
421       // Create a data dependence.
422       //
423       // TODO: Handle "special" address latencies cleanly.
424       const SDep &dep = SDep(DefSU, SDep::Data, DefSU->Latency, Reg);
425       if (!UnitLatencies) {
426         // Adjust the dependence latency using operand def/use information, then
427         // allow the target to perform its own adjustments.
428         ComputeOperandLatency(DefSU, SU, const_cast<SDep &>(dep));
429         const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
430         ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
431       }
432       SU->addPred(dep);
433     }
434   }
435
436   // Add antidependence to the following def of the vreg it uses.
437   VReg2SUnitMap::iterator DefI = findVRegDef(Reg);
438   if (DefI != VRegDefs.end() && DefI->SU != SU)
439     DefI->SU->addPred(SDep(SU, SDep::Anti, 0, Reg));
440 }
441
442 /// Create an SUnit for each real instruction, numbered in top-down toplological
443 /// order. The instruction order A < B, implies that no edge exists from B to A.
444 ///
445 /// Map each real instruction to its SUnit.
446 ///
447 /// After initSUnits, the SUnits vector is cannot be resized and the scheduler
448 /// may hang onto SUnit pointers. We may relax this in the future by using SUnit
449 /// IDs instead of pointers.
450 void ScheduleDAGInstrs::initSUnits() {
451   // We'll be allocating one SUnit for each real instruction in the region,
452   // which is contained within a basic block.
453   SUnits.reserve(BB->size());
454
455   for (MachineBasicBlock::iterator I = Begin; I != InsertPos; ++I) {
456     MachineInstr *MI = I;
457     if (MI->isDebugValue())
458       continue;
459
460     SUnit *SU = NewSUnit(MI);
461     MISUnitMap[MI] = SU;
462
463     SU->isCall = MI->isCall();
464     SU->isCommutable = MI->isCommutable();
465
466     // Assign the Latency field of SU using target-provided information.
467     if (UnitLatencies)
468       SU->Latency = 1;
469     else
470       ComputeLatency(SU);
471   }
472 }
473
474 void ScheduleDAGInstrs::BuildSchedGraph(AliasAnalysis *AA) {
475   // Create an SUnit for each real instruction.
476   initSUnits();
477
478   // We build scheduling units by walking a block's instruction list from bottom
479   // to top.
480
481   // Remember where a generic side-effecting instruction is as we procede.
482   SUnit *BarrierChain = 0, *AliasChain = 0;
483
484   // Memory references to specific known memory locations are tracked
485   // so that they can be given more precise dependencies. We track
486   // separately the known memory locations that may alias and those
487   // that are known not to alias
488   std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
489   std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
490
491   // Remove any stale debug info; sometimes BuildSchedGraph is called again
492   // without emitting the info from the previous call.
493   DbgValues.clear();
494   FirstDbgValue = NULL;
495
496   assert(Defs.empty() && Uses.empty() &&
497          "Only BuildGraph should update Defs/Uses");
498   Defs.setUniverse(TRI->getNumRegs());
499   Uses.setUniverse(TRI->getNumRegs());
500
501   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
502   // FIXME: Allow SparseSet to reserve space for the creation of virtual
503   // registers during scheduling. Don't artificially inflate the Universe
504   // because we want to assert that vregs are not created during DAG building.
505   VRegDefs.setUniverse(MRI.getNumVirtRegs());
506
507   // Model data dependencies between instructions being scheduled and the
508   // ExitSU.
509   AddSchedBarrierDeps();
510
511   // Walk the list of instructions, from bottom moving up.
512   MachineInstr *PrevMI = NULL;
513   for (MachineBasicBlock::iterator MII = InsertPos, MIE = Begin;
514        MII != MIE; --MII) {
515     MachineInstr *MI = prior(MII);
516     if (MI && PrevMI) {
517       DbgValues.push_back(std::make_pair(PrevMI, MI));
518       PrevMI = NULL;
519     }
520
521     if (MI->isDebugValue()) {
522       PrevMI = MI;
523       continue;
524     }
525
526     assert(!MI->isTerminator() && !MI->isLabel() &&
527            "Cannot schedule terminators or labels!");
528
529     SUnit *SU = MISUnitMap[MI];
530     assert(SU && "No SUnit mapped to this MI");
531
532     // Add register-based dependencies (data, anti, and output).
533     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
534       const MachineOperand &MO = MI->getOperand(j);
535       if (!MO.isReg()) continue;
536       unsigned Reg = MO.getReg();
537       if (Reg == 0) continue;
538
539       if (TRI->isPhysicalRegister(Reg))
540         addPhysRegDeps(SU, j);
541       else {
542         assert(!IsPostRA && "Virtual register encountered!");
543         if (MO.isDef())
544           addVRegDefDeps(SU, j);
545         else if (MO.readsReg()) // ignore undef operands
546           addVRegUseDeps(SU, j);
547       }
548     }
549
550     // Add chain dependencies.
551     // Chain dependencies used to enforce memory order should have
552     // latency of 0 (except for true dependency of Store followed by
553     // aliased Load... we estimate that with a single cycle of latency
554     // assuming the hardware will bypass)
555     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
556     // after stack slots are lowered to actual addresses.
557     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
558     // produce more precise dependence information.
559 #define STORE_LOAD_LATENCY 1
560     unsigned TrueMemOrderLatency = 0;
561     if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
562         (MI->hasVolatileMemoryRef() &&
563          (!MI->mayLoad() || !MI->isInvariantLoad(AA)))) {
564       // Be conservative with these and add dependencies on all memory
565       // references, even those that are known to not alias.
566       for (std::map<const Value *, SUnit *>::iterator I =
567              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
568         I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
569       }
570       for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
571              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
572         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
573           I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
574       }
575       NonAliasMemDefs.clear();
576       NonAliasMemUses.clear();
577       // Add SU to the barrier chain.
578       if (BarrierChain)
579         BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
580       BarrierChain = SU;
581
582       // fall-through
583     new_alias_chain:
584       // Chain all possibly aliasing memory references though SU.
585       if (AliasChain)
586         AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
587       AliasChain = SU;
588       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
589         PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
590       for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
591            E = AliasMemDefs.end(); I != E; ++I) {
592         I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
593       }
594       for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
595            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
596         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
597           I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
598       }
599       PendingLoads.clear();
600       AliasMemDefs.clear();
601       AliasMemUses.clear();
602     } else if (MI->mayStore()) {
603       bool MayAlias = true;
604       TrueMemOrderLatency = STORE_LOAD_LATENCY;
605       if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
606         // A store to a specific PseudoSourceValue. Add precise dependencies.
607         // Record the def in MemDefs, first adding a dep if there is
608         // an existing def.
609         std::map<const Value *, SUnit *>::iterator I =
610           ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
611         std::map<const Value *, SUnit *>::iterator IE =
612           ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
613         if (I != IE) {
614           I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
615                                   /*isNormalMemory=*/true));
616           I->second = SU;
617         } else {
618           if (MayAlias)
619             AliasMemDefs[V] = SU;
620           else
621             NonAliasMemDefs[V] = SU;
622         }
623         // Handle the uses in MemUses, if there are any.
624         std::map<const Value *, std::vector<SUnit *> >::iterator J =
625           ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
626         std::map<const Value *, std::vector<SUnit *> >::iterator JE =
627           ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
628         if (J != JE) {
629           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
630             J->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency,
631                                        /*Reg=*/0, /*isNormalMemory=*/true));
632           J->second.clear();
633         }
634         if (MayAlias) {
635           // Add dependencies from all the PendingLoads, i.e. loads
636           // with no underlying object.
637           for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
638             PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
639           // Add dependence on alias chain, if needed.
640           if (AliasChain)
641             AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
642         }
643         // Add dependence on barrier chain, if needed.
644         if (BarrierChain)
645           BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
646       } else {
647         // Treat all other stores conservatively.
648         goto new_alias_chain;
649       }
650
651       if (!ExitSU.isPred(SU))
652         // Push store's up a bit to avoid them getting in between cmp
653         // and branches.
654         ExitSU.addPred(SDep(SU, SDep::Order, 0,
655                             /*Reg=*/0, /*isNormalMemory=*/false,
656                             /*isMustAlias=*/false,
657                             /*isArtificial=*/true));
658     } else if (MI->mayLoad()) {
659       bool MayAlias = true;
660       TrueMemOrderLatency = 0;
661       if (MI->isInvariantLoad(AA)) {
662         // Invariant load, no chain dependencies needed!
663       } else {
664         if (const Value *V =
665             getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
666           // A load from a specific PseudoSourceValue. Add precise dependencies.
667           std::map<const Value *, SUnit *>::iterator I =
668             ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
669           std::map<const Value *, SUnit *>::iterator IE =
670             ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
671           if (I != IE)
672             I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
673                                     /*isNormalMemory=*/true));
674           if (MayAlias)
675             AliasMemUses[V].push_back(SU);
676           else
677             NonAliasMemUses[V].push_back(SU);
678         } else {
679           // A load with no underlying object. Depend on all
680           // potentially aliasing stores.
681           for (std::map<const Value *, SUnit *>::iterator I =
682                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
683             I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
684
685           PendingLoads.push_back(SU);
686           MayAlias = true;
687         }
688
689         // Add dependencies on alias and barrier chains, if needed.
690         if (MayAlias && AliasChain)
691           AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
692         if (BarrierChain)
693           BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
694       }
695     }
696   }
697   if (PrevMI)
698     FirstDbgValue = PrevMI;
699
700   Defs.clear();
701   Uses.clear();
702   VRegDefs.clear();
703   PendingLoads.clear();
704   MISUnitMap.clear();
705 }
706
707 void ScheduleDAGInstrs::FinishBlock() {
708   // Nothing to do.
709 }
710
711 void ScheduleDAGInstrs::ComputeLatency(SUnit *SU) {
712   // Compute the latency for the node.
713   if (!InstrItins || InstrItins->isEmpty()) {
714     SU->Latency = 1;
715
716     // Simplistic target-independent heuristic: assume that loads take
717     // extra time.
718     if (SU->getInstr()->mayLoad())
719       SU->Latency += 2;
720   } else {
721     SU->Latency = TII->getInstrLatency(InstrItins, SU->getInstr());
722   }
723 }
724
725 void ScheduleDAGInstrs::ComputeOperandLatency(SUnit *Def, SUnit *Use,
726                                               SDep& dep) const {
727   if (!InstrItins || InstrItins->isEmpty())
728     return;
729
730   // For a data dependency with a known register...
731   if ((dep.getKind() != SDep::Data) || (dep.getReg() == 0))
732     return;
733
734   const unsigned Reg = dep.getReg();
735
736   // ... find the definition of the register in the defining
737   // instruction
738   MachineInstr *DefMI = Def->getInstr();
739   int DefIdx = DefMI->findRegisterDefOperandIdx(Reg);
740   if (DefIdx != -1) {
741     const MachineOperand &MO = DefMI->getOperand(DefIdx);
742     if (MO.isReg() && MO.isImplicit() &&
743         DefIdx >= (int)DefMI->getDesc().getNumOperands()) {
744       // This is an implicit def, getOperandLatency() won't return the correct
745       // latency. e.g.
746       //   %D6<def>, %D7<def> = VLD1q16 %R2<kill>, 0, ..., %Q3<imp-def>
747       //   %Q1<def> = VMULv8i16 %Q1<kill>, %Q3<kill>, ...
748       // What we want is to compute latency between def of %D6/%D7 and use of
749       // %Q3 instead.
750       unsigned Op2 = DefMI->findRegisterDefOperandIdx(Reg, false, true, TRI);
751       if (DefMI->getOperand(Op2).isReg())
752         DefIdx = Op2;
753     }
754     MachineInstr *UseMI = Use->getInstr();
755     // For all uses of the register, calculate the maxmimum latency
756     int Latency = -1;
757     if (UseMI) {
758       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
759         const MachineOperand &MO = UseMI->getOperand(i);
760         if (!MO.isReg() || !MO.isUse())
761           continue;
762         unsigned MOReg = MO.getReg();
763         if (MOReg != Reg)
764           continue;
765
766         int UseCycle = TII->getOperandLatency(InstrItins, DefMI, DefIdx,
767                                               UseMI, i);
768         Latency = std::max(Latency, UseCycle);
769       }
770     } else {
771       // UseMI is null, then it must be a scheduling barrier.
772       if (!InstrItins || InstrItins->isEmpty())
773         return;
774       unsigned DefClass = DefMI->getDesc().getSchedClass();
775       Latency = InstrItins->getOperandCycle(DefClass, DefIdx);
776     }
777
778     // If we found a latency, then replace the existing dependence latency.
779     if (Latency >= 0)
780       dep.setLatency(Latency);
781   }
782 }
783
784 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
785   SU->getInstr()->dump();
786 }
787
788 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
789   std::string s;
790   raw_string_ostream oss(s);
791   if (SU == &EntrySU)
792     oss << "<entry>";
793   else if (SU == &ExitSU)
794     oss << "<exit>";
795   else
796     SU->getInstr()->print(oss);
797   return oss.str();
798 }
799
800 // EmitSchedule - Emit the machine code in scheduled order.
801 MachineBasicBlock *ScheduleDAGInstrs::EmitSchedule() {
802   Begin = InsertPos;
803
804   // If first instruction was a DBG_VALUE then put it back.
805   if (FirstDbgValue)
806     BB->splice(InsertPos, BB, FirstDbgValue);
807
808   // Then re-insert them according to the given schedule.
809   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
810     if (SUnit *SU = Sequence[i])
811       BB->splice(InsertPos, BB, SU->getInstr());
812     else
813       // Null SUnit* is a noop.
814       EmitNoop();
815
816     // Update the Begin iterator, as the first instruction in the block
817     // may have been scheduled later.
818     if (i == 0)
819       Begin = prior(InsertPos);
820   }
821
822   // Reinsert any remaining debug_values.
823   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
824          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
825     std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
826     MachineInstr *DbgValue = P.first;
827     MachineBasicBlock::iterator OrigPrivMI = P.second;
828     BB->splice(++OrigPrivMI, BB, DbgValue);
829   }
830   DbgValues.clear();
831   FirstDbgValue = NULL;
832   return BB;
833 }