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 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
16 #include "llvm/ADT/IntEqClasses.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineMemOperand.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/CodeGen/RegisterPressure.h"
29 #include "llvm/CodeGen/ScheduleDFS.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "misched"
45 
46 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
47     cl::ZeroOrMore, cl::init(false),
48     cl::desc("Enable use of AA during MI DAG construction"));
49 
50 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
51     cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
52 
53 // Note: the two options below might be used in tuning compile time vs
54 // output quality. Setting HugeRegion so large that it will never be
55 // reached means best-effort, but may be slow.
56 
57 // When Stores and Loads maps (or NonAliasStores and NonAliasLoads)
58 // together hold this many SUs, a reduction of maps will be done.
59 static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
60     cl::init(1000), cl::desc("The limit to use while constructing the DAG "
61                              "prior to scheduling, at which point a trade-off "
62                              "is made to avoid excessive compile time."));
63 
64 static cl::opt<unsigned> ReductionSize(
65     "dag-maps-reduction-size", cl::Hidden,
66     cl::desc("A huge scheduling region will have maps reduced by this many "
67              "nodes at a time. Defaults to HugeRegion / 2."));
68 
69 static unsigned getReductionSize() {
70   // Always reduce a huge region with half of the elements, except
71   // when user sets this number explicitly.
72   if (ReductionSize.getNumOccurrences() == 0)
73     return HugeRegion / 2;
74   return ReductionSize;
75 }
76 
77 static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
78 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
79   dbgs() << "{ ";
80   for (const SUnit *su : L) {
81     dbgs() << "SU(" << su->NodeNum << ")";
82     if (su != L.back())
83       dbgs() << ", ";
84   }
85   dbgs() << "}\n";
86 #endif
87 }
88 
89 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
90                                      const MachineLoopInfo *mli,
91                                      bool RemoveKillFlags)
92     : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
93       RemoveKillFlags(RemoveKillFlags), CanHandleTerminators(false),
94       TrackLaneMasks(false), AAForDep(nullptr), BarrierChain(nullptr),
95       UnknownValue(UndefValue::get(
96                      Type::getVoidTy(mf.getFunction()->getContext()))),
97       FirstDbgValue(nullptr) {
98   DbgValues.clear();
99 
100   const TargetSubtargetInfo &ST = mf.getSubtarget();
101   SchedModel.init(ST.getSchedModel(), &ST, TII);
102 }
103 
104 /// getUnderlyingObjectFromInt - This is the function that does the work of
105 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
106 static const Value *getUnderlyingObjectFromInt(const Value *V) {
107   do {
108     if (const Operator *U = dyn_cast<Operator>(V)) {
109       // If we find a ptrtoint, we can transfer control back to the
110       // regular getUnderlyingObjectFromInt.
111       if (U->getOpcode() == Instruction::PtrToInt)
112         return U->getOperand(0);
113       // If we find an add of a constant, a multiplied value, or a phi, it's
114       // likely that the other operand will lead us to the base
115       // object. We don't have to worry about the case where the
116       // object address is somehow being computed by the multiply,
117       // because our callers only care when the result is an
118       // identifiable object.
119       if (U->getOpcode() != Instruction::Add ||
120           (!isa<ConstantInt>(U->getOperand(1)) &&
121            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
122            !isa<PHINode>(U->getOperand(1))))
123         return V;
124       V = U->getOperand(0);
125     } else {
126       return V;
127     }
128     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
129   } while (1);
130 }
131 
132 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
133 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
134 static void getUnderlyingObjects(const Value *V,
135                                  SmallVectorImpl<Value *> &Objects,
136                                  const DataLayout &DL) {
137   SmallPtrSet<const Value *, 16> Visited;
138   SmallVector<const Value *, 4> Working(1, V);
139   do {
140     V = Working.pop_back_val();
141 
142     SmallVector<Value *, 4> Objs;
143     GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
144 
145     for (Value *V : Objs) {
146       if (!Visited.insert(V).second)
147         continue;
148       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
149         const Value *O =
150           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
151         if (O->getType()->isPointerTy()) {
152           Working.push_back(O);
153           continue;
154         }
155       }
156       Objects.push_back(const_cast<Value *>(V));
157     }
158   } while (!Working.empty());
159 }
160 
161 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
162 /// information and it can be tracked to a normal reference to a known
163 /// object, return the Value for that object.
164 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
165                                          const MachineFrameInfo &MFI,
166                                          UnderlyingObjectsVector &Objects,
167                                          const DataLayout &DL) {
168   auto allMMOsOkay = [&]() {
169     for (const MachineMemOperand *MMO : MI->memoperands()) {
170       if (MMO->isVolatile())
171         return false;
172 
173       if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
174         // Function that contain tail calls don't have unique PseudoSourceValue
175         // objects. Two PseudoSourceValues might refer to the same or
176         // overlapping locations. The client code calling this function assumes
177         // this is not the case. So return a conservative answer of no known
178         // object.
179         if (MFI.hasTailCall())
180           return false;
181 
182         // For now, ignore PseudoSourceValues which may alias LLVM IR values
183         // because the code that uses this function has no way to cope with
184         // such aliases.
185         if (PSV->isAliased(&MFI))
186           return false;
187 
188         bool MayAlias = PSV->mayAlias(&MFI);
189         Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
190       } else if (const Value *V = MMO->getValue()) {
191         SmallVector<Value *, 4> Objs;
192         getUnderlyingObjects(V, Objs, DL);
193 
194         for (Value *V : Objs) {
195           if (!isIdentifiedObject(V))
196             return false;
197 
198           Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
199         }
200       } else
201         return false;
202     }
203     return true;
204   };
205 
206   if (!allMMOsOkay())
207     Objects.clear();
208 }
209 
210 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
211   BB = bb;
212 }
213 
214 void ScheduleDAGInstrs::finishBlock() {
215   // Subclasses should no longer refer to the old block.
216   BB = nullptr;
217 }
218 
219 /// Initialize the DAG and common scheduler state for the current scheduling
220 /// region. This does not actually create the DAG, only clears it. The
221 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
222 /// region.
223 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
224                                     MachineBasicBlock::iterator begin,
225                                     MachineBasicBlock::iterator end,
226                                     unsigned regioninstrs) {
227   assert(bb == BB && "startBlock should set BB");
228   RegionBegin = begin;
229   RegionEnd = end;
230   NumRegionInstrs = regioninstrs;
231 }
232 
233 /// Close the current scheduling region. Don't clear any state in case the
234 /// driver wants to refer to the previous scheduling region.
235 void ScheduleDAGInstrs::exitRegion() {
236   // Nothing to do.
237 }
238 
239 /// addSchedBarrierDeps - Add dependencies from instructions in the current
240 /// list of instructions being scheduled to scheduling barrier by adding
241 /// the exit SU to the register defs and use list. This is because we want to
242 /// make sure instructions which define registers that are either used by
243 /// the terminator or are live-out are properly scheduled. This is
244 /// especially important when the definition latency of the return value(s)
245 /// are too high to be hidden by the branch or when the liveout registers
246 /// used by instructions in the fallthrough block.
247 void ScheduleDAGInstrs::addSchedBarrierDeps() {
248   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
249   ExitSU.setInstr(ExitMI);
250   // Add dependencies on the defs and uses of the instruction.
251   if (ExitMI) {
252     for (const MachineOperand &MO : ExitMI->operands()) {
253       if (!MO.isReg() || MO.isDef()) continue;
254       unsigned Reg = MO.getReg();
255       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
256         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
257       } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
258         addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
259       }
260     }
261   }
262   if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
263     // For others, e.g. fallthrough, conditional branch, assume the exit
264     // uses all the registers that are livein to the successor blocks.
265     for (const MachineBasicBlock *Succ : BB->successors()) {
266       for (const auto &LI : Succ->liveins()) {
267         if (!Uses.contains(LI.PhysReg))
268           Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
269       }
270     }
271   }
272 }
273 
274 /// MO is an operand of SU's instruction that defines a physical register. Add
275 /// data dependencies from SU to any uses of the physical register.
276 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
277   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
278   assert(MO.isDef() && "expect physreg def");
279 
280   // Ask the target if address-backscheduling is desirable, and if so how much.
281   const TargetSubtargetInfo &ST = MF.getSubtarget();
282 
283   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
284        Alias.isValid(); ++Alias) {
285     if (!Uses.contains(*Alias))
286       continue;
287     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
288       SUnit *UseSU = I->SU;
289       if (UseSU == SU)
290         continue;
291 
292       // Adjust the dependence latency using operand def/use information,
293       // then allow the target to perform its own adjustments.
294       int UseOp = I->OpIdx;
295       MachineInstr *RegUse = nullptr;
296       SDep Dep;
297       if (UseOp < 0)
298         Dep = SDep(SU, SDep::Artificial);
299       else {
300         // Set the hasPhysRegDefs only for physreg defs that have a use within
301         // the scheduling region.
302         SU->hasPhysRegDefs = true;
303         Dep = SDep(SU, SDep::Data, *Alias);
304         RegUse = UseSU->getInstr();
305       }
306       Dep.setLatency(
307         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
308                                          UseOp));
309 
310       ST.adjustSchedDependency(SU, UseSU, Dep);
311       UseSU->addPred(Dep);
312     }
313   }
314 }
315 
316 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
317 /// this SUnit to following instructions in the same scheduling region that
318 /// depend the physical register referenced at OperIdx.
319 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
320   MachineInstr *MI = SU->getInstr();
321   MachineOperand &MO = MI->getOperand(OperIdx);
322   unsigned Reg = MO.getReg();
323   // We do not need to track any dependencies for constant registers.
324   if (MRI.isConstantPhysReg(Reg))
325     return;
326 
327   // Optionally add output and anti dependencies. For anti
328   // dependencies we use a latency of 0 because for a multi-issue
329   // target we want to allow the defining instruction to issue
330   // in the same cycle as the using instruction.
331   // TODO: Using a latency of 1 here for output dependencies assumes
332   //       there's no cost for reusing registers.
333   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
334   for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
335     if (!Defs.contains(*Alias))
336       continue;
337     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
338       SUnit *DefSU = I->SU;
339       if (DefSU == &ExitSU)
340         continue;
341       if (DefSU != SU &&
342           (Kind != SDep::Output || !MO.isDead() ||
343            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
344         if (Kind == SDep::Anti)
345           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
346         else {
347           SDep Dep(SU, Kind, /*Reg=*/*Alias);
348           Dep.setLatency(
349             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
350           DefSU->addPred(Dep);
351         }
352       }
353     }
354   }
355 
356   if (!MO.isDef()) {
357     SU->hasPhysRegUses = true;
358     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
359     // retrieve the existing SUnits list for this register's uses.
360     // Push this SUnit on the use list.
361     Uses.insert(PhysRegSUOper(SU, OperIdx, Reg));
362     if (RemoveKillFlags)
363       MO.setIsKill(false);
364   } else {
365     addPhysRegDataDeps(SU, OperIdx);
366 
367     // clear this register's use list
368     if (Uses.contains(Reg))
369       Uses.eraseAll(Reg);
370 
371     if (!MO.isDead()) {
372       Defs.eraseAll(Reg);
373     } else if (SU->isCall) {
374       // Calls will not be reordered because of chain dependencies (see
375       // below). Since call operands are dead, calls may continue to be added
376       // to the DefList making dependence checking quadratic in the size of
377       // the block. Instead, we leave only one call at the back of the
378       // DefList.
379       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
380       Reg2SUnitsMap::iterator B = P.first;
381       Reg2SUnitsMap::iterator I = P.second;
382       for (bool isBegin = I == B; !isBegin; /* empty */) {
383         isBegin = (--I) == B;
384         if (!I->SU->isCall)
385           break;
386         I = Defs.erase(I);
387       }
388     }
389 
390     // Defs are pushed in the order they are visited and never reordered.
391     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
392   }
393 }
394 
395 LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
396 {
397   unsigned Reg = MO.getReg();
398   // No point in tracking lanemasks if we don't have interesting subregisters.
399   const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
400   if (!RC.HasDisjunctSubRegs)
401     return ~0u;
402 
403   unsigned SubReg = MO.getSubReg();
404   if (SubReg == 0)
405     return RC.getLaneMask();
406   return TRI->getSubRegIndexLaneMask(SubReg);
407 }
408 
409 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
410 /// to instructions that occur later in the same scheduling region if they read
411 /// from or write to the virtual register defined at OperIdx.
412 ///
413 /// TODO: Hoist loop induction variable increments. This has to be
414 /// reevaluated. Generally, IV scheduling should be done before coalescing.
415 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
416   MachineInstr *MI = SU->getInstr();
417   MachineOperand &MO = MI->getOperand(OperIdx);
418   unsigned Reg = MO.getReg();
419 
420   LaneBitmask DefLaneMask;
421   LaneBitmask KillLaneMask;
422   if (TrackLaneMasks) {
423     bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
424     DefLaneMask = getLaneMaskForMO(MO);
425     // If we have a <read-undef> flag, none of the lane values comes from an
426     // earlier instruction.
427     KillLaneMask = IsKill ? ~0u : DefLaneMask;
428 
429     // Clear undef flag, we'll re-add it later once we know which subregister
430     // Def is first.
431     MO.setIsUndef(false);
432   } else {
433     DefLaneMask = ~0u;
434     KillLaneMask = ~0u;
435   }
436 
437   if (MO.isDead()) {
438     assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
439            "Dead defs should have no uses");
440   } else {
441     // Add data dependence to all uses we found so far.
442     const TargetSubtargetInfo &ST = MF.getSubtarget();
443     for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
444          E = CurrentVRegUses.end(); I != E; /*empty*/) {
445       LaneBitmask LaneMask = I->LaneMask;
446       // Ignore uses of other lanes.
447       if ((LaneMask & KillLaneMask) == 0) {
448         ++I;
449         continue;
450       }
451 
452       if ((LaneMask & DefLaneMask) != 0) {
453         SUnit *UseSU = I->SU;
454         MachineInstr *Use = UseSU->getInstr();
455         SDep Dep(SU, SDep::Data, Reg);
456         Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
457                                                         I->OperandIndex));
458         ST.adjustSchedDependency(SU, UseSU, Dep);
459         UseSU->addPred(Dep);
460       }
461 
462       LaneMask &= ~KillLaneMask;
463       // If we found a Def for all lanes of this use, remove it from the list.
464       if (LaneMask != 0) {
465         I->LaneMask = LaneMask;
466         ++I;
467       } else
468         I = CurrentVRegUses.erase(I);
469     }
470   }
471 
472   // Shortcut: Singly defined vregs do not have output/anti dependencies.
473   if (MRI.hasOneDef(Reg))
474     return;
475 
476   // Add output dependence to the next nearest defs of this vreg.
477   //
478   // Unless this definition is dead, the output dependence should be
479   // transitively redundant with antidependencies from this definition's
480   // uses. We're conservative for now until we have a way to guarantee the uses
481   // are not eliminated sometime during scheduling. The output dependence edge
482   // is also useful if output latency exceeds def-use latency.
483   LaneBitmask LaneMask = DefLaneMask;
484   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
485                                      CurrentVRegDefs.end())) {
486     // Ignore defs for other lanes.
487     if ((V2SU.LaneMask & LaneMask) == 0)
488       continue;
489     // Add an output dependence.
490     SUnit *DefSU = V2SU.SU;
491     // Ignore additional defs of the same lanes in one instruction. This can
492     // happen because lanemasks are shared for targets with too many
493     // subregisters. We also use some representration tricks/hacks where we
494     // add super-register defs/uses, to imply that although we only access parts
495     // of the reg we care about the full one.
496     if (DefSU == SU)
497       continue;
498     SDep Dep(SU, SDep::Output, Reg);
499     Dep.setLatency(
500       SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
501     DefSU->addPred(Dep);
502 
503     // Update current definition. This can get tricky if the def was about a
504     // bigger lanemask before. We then have to shrink it and create a new
505     // VReg2SUnit for the non-overlapping part.
506     LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
507     LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
508     V2SU.SU = SU;
509     V2SU.LaneMask = OverlapMask;
510     if (NonOverlapMask != 0)
511       CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
512   }
513   // If there was no CurrentVRegDefs entry for some lanes yet, create one.
514   if (LaneMask != 0)
515     CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
516 }
517 
518 /// addVRegUseDeps - Add a register data dependency if the instruction that
519 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
520 /// register antidependency from this SUnit to instructions that occur later in
521 /// the same scheduling region if they write the virtual register.
522 ///
523 /// TODO: Handle ExitSU "uses" properly.
524 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
525   const MachineInstr *MI = SU->getInstr();
526   const MachineOperand &MO = MI->getOperand(OperIdx);
527   unsigned Reg = MO.getReg();
528 
529   // Remember the use. Data dependencies will be added when we find the def.
530   LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO) : ~0u;
531   CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
532 
533   // Add antidependences to the following defs of the vreg.
534   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
535                                      CurrentVRegDefs.end())) {
536     // Ignore defs for unrelated lanes.
537     LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
538     if ((PrevDefLaneMask & LaneMask) == 0)
539       continue;
540     if (V2SU.SU == SU)
541       continue;
542 
543     V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
544   }
545 }
546 
547 /// Return true if MI is an instruction we are unable to reason about
548 /// (like a call or something with unmodeled side effects).
549 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
550   return MI->isCall() || MI->hasUnmodeledSideEffects() ||
551          (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
552 }
553 
554 /// This returns true if the two MIs need a chain edge between them.
555 /// This is called on normal stores and loads.
556 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
557                              const DataLayout &DL, MachineInstr *MIa,
558                              MachineInstr *MIb) {
559   const MachineFunction *MF = MIa->getParent()->getParent();
560   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
561 
562   assert ((MIa->mayStore() || MIb->mayStore()) &&
563           "Dependency checked between two loads");
564 
565   // Let the target decide if memory accesses cannot possibly overlap.
566   if (TII->areMemAccessesTriviallyDisjoint(*MIa, *MIb, AA))
567     return false;
568 
569   // To this point analysis is generic. From here on we do need AA.
570   if (!AA)
571     return true;
572 
573   // FIXME: Need to handle multiple memory operands to support all targets.
574   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
575     return true;
576 
577   MachineMemOperand *MMOa = *MIa->memoperands_begin();
578   MachineMemOperand *MMOb = *MIb->memoperands_begin();
579 
580   if (!MMOa->getValue() || !MMOb->getValue())
581     return true;
582 
583   // The following interface to AA is fashioned after DAGCombiner::isAlias
584   // and operates with MachineMemOperand offset with some important
585   // assumptions:
586   //   - LLVM fundamentally assumes flat address spaces.
587   //   - MachineOperand offset can *only* result from legalization and
588   //     cannot affect queries other than the trivial case of overlap
589   //     checking.
590   //   - These offsets never wrap and never step outside
591   //     of allocated objects.
592   //   - There should never be any negative offsets here.
593   //
594   // FIXME: Modify API to hide this math from "user"
595   // FIXME: Even before we go to AA we can reason locally about some
596   // memory objects. It can save compile time, and possibly catch some
597   // corner cases not currently covered.
598 
599   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
600   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
601 
602   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
603   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
604   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
605 
606   AliasResult AAResult =
607       AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
608                                UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
609                 MemoryLocation(MMOb->getValue(), Overlapb,
610                                UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
611 
612   return (AAResult != NoAlias);
613 }
614 
615 /// Check whether two objects need a chain edge and add it if needed.
616 void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
617                                             unsigned Latency) {
618   if (MIsNeedChainEdge(AAForDep, &MFI, MF.getDataLayout(), SUa->getInstr(),
619                        SUb->getInstr())) {
620     SDep Dep(SUa, SDep::MayAliasMem);
621     Dep.setLatency(Latency);
622     SUb->addPred(Dep);
623   }
624 }
625 
626 /// Create an SUnit for each real instruction, numbered in top-down topological
627 /// order. The instruction order A < B, implies that no edge exists from B to A.
628 ///
629 /// Map each real instruction to its SUnit.
630 ///
631 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
632 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
633 /// instead of pointers.
634 ///
635 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
636 /// the original instruction list.
637 void ScheduleDAGInstrs::initSUnits() {
638   // We'll be allocating one SUnit for each real instruction in the region,
639   // which is contained within a basic block.
640   SUnits.reserve(NumRegionInstrs);
641 
642   for (MachineInstr &MI : llvm::make_range(RegionBegin, RegionEnd)) {
643     if (MI.isDebugValue())
644       continue;
645 
646     SUnit *SU = newSUnit(&MI);
647     MISUnitMap[&MI] = SU;
648 
649     SU->isCall = MI.isCall();
650     SU->isCommutable = MI.isCommutable();
651 
652     // Assign the Latency field of SU using target-provided information.
653     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
654 
655     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
656     //
657     // Reserved resources block an instruction from issuing and stall the
658     // entire pipeline. These are identified by BufferSize=0.
659     //
660     // Unbuffered resources prevent execution of subsequent instructions that
661     // require the same resources. This is used for in-order execution pipelines
662     // within an out-of-order core. These are identified by BufferSize=1.
663     if (SchedModel.hasInstrSchedModel()) {
664       const MCSchedClassDesc *SC = getSchedClass(SU);
665       for (const MCWriteProcResEntry &PRE :
666            make_range(SchedModel.getWriteProcResBegin(SC),
667                       SchedModel.getWriteProcResEnd(SC))) {
668         switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
669         case 0:
670           SU->hasReservedResource = true;
671           break;
672         case 1:
673           SU->isUnbuffered = true;
674           break;
675         default:
676           break;
677         }
678       }
679     }
680   }
681 }
682 
683 class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
684 
685   /// Current total number of SUs in map.
686   unsigned NumNodes;
687 
688   /// 1 for loads, 0 for stores. (see comment in SUList)
689   unsigned TrueMemOrderLatency;
690 public:
691 
692   Value2SUsMap(unsigned lat = 0) : NumNodes(0), TrueMemOrderLatency(lat) {}
693 
694   /// To keep NumNodes up to date, insert() is used instead of
695   /// this operator w/ push_back().
696   ValueType &operator[](const SUList &Key) {
697     llvm_unreachable("Don't use. Use insert() instead."); };
698 
699   /// Add SU to the SUList of V. If Map grows huge, reduce its size
700   /// by calling reduce().
701   void inline insert(SUnit *SU, ValueType V) {
702     MapVector::operator[](V).push_back(SU);
703     NumNodes++;
704   }
705 
706   /// Clears the list of SUs mapped to V.
707   void inline clearList(ValueType V) {
708     iterator Itr = find(V);
709     if (Itr != end()) {
710       assert (NumNodes >= Itr->second.size());
711       NumNodes -= Itr->second.size();
712 
713       Itr->second.clear();
714     }
715   }
716 
717   /// Clears map from all contents.
718   void clear() {
719     MapVector<ValueType, SUList>::clear();
720     NumNodes = 0;
721   }
722 
723   unsigned inline size() const { return NumNodes; }
724 
725   /// Count the number of SUs in this map after a reduction.
726   void reComputeSize(void) {
727     NumNodes = 0;
728     for (auto &I : *this)
729       NumNodes += I.second.size();
730   }
731 
732   unsigned inline getTrueMemOrderLatency() const {
733     return TrueMemOrderLatency;
734   }
735 
736   void dump();
737 };
738 
739 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
740                                              Value2SUsMap &Val2SUsMap) {
741   for (auto &I : Val2SUsMap)
742     addChainDependencies(SU, I.second,
743                          Val2SUsMap.getTrueMemOrderLatency());
744 }
745 
746 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
747                                              Value2SUsMap &Val2SUsMap,
748                                              ValueType V) {
749   Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
750   if (Itr != Val2SUsMap.end())
751     addChainDependencies(SU, Itr->second,
752                          Val2SUsMap.getTrueMemOrderLatency());
753 }
754 
755 void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
756   assert (BarrierChain != nullptr);
757 
758   for (auto &I : map) {
759     SUList &sus = I.second;
760     for (auto *SU : sus)
761       SU->addPredBarrier(BarrierChain);
762   }
763   map.clear();
764 }
765 
766 void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
767   assert (BarrierChain != nullptr);
768 
769   // Go through all lists of SUs.
770   for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
771     Value2SUsMap::iterator CurrItr = I++;
772     SUList &sus = CurrItr->second;
773     SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
774     for (; SUItr != SUEE; ++SUItr) {
775       // Stop on BarrierChain or any instruction above it.
776       if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
777         break;
778 
779       (*SUItr)->addPredBarrier(BarrierChain);
780     }
781 
782     // Remove also the BarrierChain from list if present.
783     if (SUItr != SUEE && *SUItr == BarrierChain)
784       SUItr++;
785 
786     // Remove all SUs that are now successors of BarrierChain.
787     if (SUItr != sus.begin())
788       sus.erase(sus.begin(), SUItr);
789   }
790 
791   // Remove all entries with empty su lists.
792   map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
793       return (mapEntry.second.empty()); });
794 
795   // Recompute the size of the map (NumNodes).
796   map.reComputeSize();
797 }
798 
799 /// If RegPressure is non-null, compute register pressure as a side effect. The
800 /// DAG builder is an efficient place to do it because it already visits
801 /// operands.
802 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
803                                         RegPressureTracker *RPTracker,
804                                         PressureDiffs *PDiffs,
805                                         LiveIntervals *LIS,
806                                         bool TrackLaneMasks) {
807   const TargetSubtargetInfo &ST = MF.getSubtarget();
808   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
809                                                        : ST.useAA();
810   AAForDep = UseAA ? AA : nullptr;
811 
812   BarrierChain = nullptr;
813 
814   this->TrackLaneMasks = TrackLaneMasks;
815   MISUnitMap.clear();
816   ScheduleDAG::clearDAG();
817 
818   // Create an SUnit for each real instruction.
819   initSUnits();
820 
821   if (PDiffs)
822     PDiffs->init(SUnits.size());
823 
824   // We build scheduling units by walking a block's instruction list
825   // from bottom to top.
826 
827   // Each MIs' memory operand(s) is analyzed to a list of underlying
828   // objects. The SU is then inserted in the SUList(s) mapped from the
829   // Value(s). Each Value thus gets mapped to lists of SUs depending
830   // on it, stores and loads kept separately. Two SUs are trivially
831   // non-aliasing if they both depend on only identified Values and do
832   // not share any common Value.
833   Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
834 
835   // Certain memory accesses are known to not alias any SU in Stores
836   // or Loads, and have therefore their own 'NonAlias'
837   // domain. E.g. spill / reload instructions never alias LLVM I/R
838   // Values. It would be nice to assume that this type of memory
839   // accesses always have a proper memory operand modelling, and are
840   // therefore never unanalyzable, but this is conservatively not
841   // done.
842   Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
843 
844   // Remove any stale debug info; sometimes BuildSchedGraph is called again
845   // without emitting the info from the previous call.
846   DbgValues.clear();
847   FirstDbgValue = nullptr;
848 
849   assert(Defs.empty() && Uses.empty() &&
850          "Only BuildGraph should update Defs/Uses");
851   Defs.setUniverse(TRI->getNumRegs());
852   Uses.setUniverse(TRI->getNumRegs());
853 
854   assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
855   assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
856   unsigned NumVirtRegs = MRI.getNumVirtRegs();
857   CurrentVRegDefs.setUniverse(NumVirtRegs);
858   CurrentVRegUses.setUniverse(NumVirtRegs);
859 
860   // Model data dependencies between instructions being scheduled and the
861   // ExitSU.
862   addSchedBarrierDeps();
863 
864   // Walk the list of instructions, from bottom moving up.
865   MachineInstr *DbgMI = nullptr;
866   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
867        MII != MIE; --MII) {
868     MachineInstr &MI = *std::prev(MII);
869     if (DbgMI) {
870       DbgValues.push_back(std::make_pair(DbgMI, &MI));
871       DbgMI = nullptr;
872     }
873 
874     if (MI.isDebugValue()) {
875       DbgMI = &MI;
876       continue;
877     }
878     SUnit *SU = MISUnitMap[&MI];
879     assert(SU && "No SUnit mapped to this MI");
880 
881     if (RPTracker) {
882       RegisterOperands RegOpers;
883       RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
884       if (TrackLaneMasks) {
885         SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
886         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
887       }
888       if (PDiffs != nullptr)
889         PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
890 
891       RPTracker->recedeSkipDebugValues();
892       assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
893       RPTracker->recede(RegOpers);
894     }
895 
896     assert(
897         (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
898         "Cannot schedule terminators or labels!");
899 
900     // Add register-based dependencies (data, anti, and output).
901     // For some instructions (calls, returns, inline-asm, etc.) there can
902     // be explicit uses and implicit defs, in which case the use will appear
903     // on the operand list before the def. Do two passes over the operand
904     // list to make sure that defs are processed before any uses.
905     bool HasVRegDef = false;
906     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
907       const MachineOperand &MO = MI.getOperand(j);
908       if (!MO.isReg() || !MO.isDef())
909         continue;
910       unsigned Reg = MO.getReg();
911       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
912         addPhysRegDeps(SU, j);
913       } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
914         HasVRegDef = true;
915         addVRegDefDeps(SU, j);
916       }
917     }
918     // Now process all uses.
919     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
920       const MachineOperand &MO = MI.getOperand(j);
921       // Only look at use operands.
922       // We do not need to check for MO.readsReg() here because subsequent
923       // subregister defs will get output dependence edges and need no
924       // additional use dependencies.
925       if (!MO.isReg() || !MO.isUse())
926         continue;
927       unsigned Reg = MO.getReg();
928       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
929         addPhysRegDeps(SU, j);
930       } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
931         addVRegUseDeps(SU, j);
932       }
933     }
934 
935     // If we haven't seen any uses in this scheduling region, create a
936     // dependence edge to ExitSU to model the live-out latency. This is required
937     // for vreg defs with no in-region use, and prefetches with no vreg def.
938     //
939     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
940     // check currently relies on being called before adding chain deps.
941     if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
942       SDep Dep(SU, SDep::Artificial);
943       Dep.setLatency(SU->Latency - 1);
944       ExitSU.addPred(Dep);
945     }
946 
947     // Add memory dependencies (Note: isStoreToStackSlot and
948     // isLoadFromStackSLot are not usable after stack slots are lowered to
949     // actual addresses).
950 
951     // This is a barrier event that acts as a pivotal node in the DAG.
952     if (isGlobalMemoryObject(AA, &MI)) {
953 
954       // Become the barrier chain.
955       if (BarrierChain)
956         BarrierChain->addPredBarrier(SU);
957       BarrierChain = SU;
958 
959       DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
960             << BarrierChain->NodeNum << ").\n";);
961 
962       // Add dependencies against everything below it and clear maps.
963       addBarrierChain(Stores);
964       addBarrierChain(Loads);
965       addBarrierChain(NonAliasStores);
966       addBarrierChain(NonAliasLoads);
967 
968       continue;
969     }
970 
971     // If it's not a store or a variant load, we're done.
972     if (!MI.mayStore() &&
973         !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
974       continue;
975 
976     // Always add dependecy edge to BarrierChain if present.
977     if (BarrierChain)
978       BarrierChain->addPredBarrier(SU);
979 
980     // Find the underlying objects for MI. The Objs vector is either
981     // empty, or filled with the Values of memory locations which this
982     // SU depends on. An empty vector means the memory location is
983     // unknown, and may alias anything.
984     UnderlyingObjectsVector Objs;
985     getUnderlyingObjectsForInstr(&MI, MFI, Objs, MF.getDataLayout());
986 
987     if (MI.mayStore()) {
988       if (Objs.empty()) {
989         // An unknown store depends on all stores and loads.
990         addChainDependencies(SU, Stores);
991         addChainDependencies(SU, NonAliasStores);
992         addChainDependencies(SU, Loads);
993         addChainDependencies(SU, NonAliasLoads);
994 
995         // Map this store to 'UnknownValue'.
996         Stores.insert(SU, UnknownValue);
997       } else {
998         // Add precise dependencies against all previously seen memory
999         // accesses mapped to the same Value(s).
1000         for (const UnderlyingObject &UnderlObj : Objs) {
1001           ValueType V = UnderlObj.getValue();
1002           bool ThisMayAlias = UnderlObj.mayAlias();
1003 
1004           // Add dependencies to previous stores and loads mapped to V.
1005           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
1006           addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
1007         }
1008         // Update the store map after all chains have been added to avoid adding
1009         // self-loop edge if multiple underlying objects are present.
1010         for (const UnderlyingObject &UnderlObj : Objs) {
1011           ValueType V = UnderlObj.getValue();
1012           bool ThisMayAlias = UnderlObj.mayAlias();
1013 
1014           // Map this store to V.
1015           (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
1016         }
1017         // The store may have dependencies to unanalyzable loads and
1018         // stores.
1019         addChainDependencies(SU, Loads, UnknownValue);
1020         addChainDependencies(SU, Stores, UnknownValue);
1021       }
1022     } else { // SU is a load.
1023       if (Objs.empty()) {
1024         // An unknown load depends on all stores.
1025         addChainDependencies(SU, Stores);
1026         addChainDependencies(SU, NonAliasStores);
1027 
1028         Loads.insert(SU, UnknownValue);
1029       } else {
1030         for (const UnderlyingObject &UnderlObj : Objs) {
1031           ValueType V = UnderlObj.getValue();
1032           bool ThisMayAlias = UnderlObj.mayAlias();
1033 
1034           // Add precise dependencies against all previously seen stores
1035           // mapping to the same Value(s).
1036           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
1037 
1038           // Map this load to V.
1039           (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
1040         }
1041         // The load may have dependencies to unanalyzable stores.
1042         addChainDependencies(SU, Stores, UnknownValue);
1043       }
1044     }
1045 
1046     // Reduce maps if they grow huge.
1047     if (Stores.size() + Loads.size() >= HugeRegion) {
1048       DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
1049       reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
1050     }
1051     if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
1052       DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
1053       reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
1054     }
1055   }
1056 
1057   if (DbgMI)
1058     FirstDbgValue = DbgMI;
1059 
1060   Defs.clear();
1061   Uses.clear();
1062   CurrentVRegDefs.clear();
1063   CurrentVRegUses.clear();
1064 }
1065 
1066 raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
1067   PSV->printCustom(OS);
1068   return OS;
1069 }
1070 
1071 void ScheduleDAGInstrs::Value2SUsMap::dump() {
1072   for (auto &Itr : *this) {
1073     if (Itr.first.is<const Value*>()) {
1074       const Value *V = Itr.first.get<const Value*>();
1075       if (isa<UndefValue>(V))
1076         dbgs() << "Unknown";
1077       else
1078         V->printAsOperand(dbgs());
1079     }
1080     else if (Itr.first.is<const PseudoSourceValue*>())
1081       dbgs() <<  Itr.first.get<const PseudoSourceValue*>();
1082     else
1083       llvm_unreachable("Unknown Value type.");
1084 
1085     dbgs() << " : ";
1086     dumpSUList(Itr.second);
1087   }
1088 }
1089 
1090 /// Reduce maps in FIFO order, by N SUs. This is better than turning
1091 /// every Nth memory SU into BarrierChain in buildSchedGraph(), since
1092 /// it avoids unnecessary edges between seen SUs above the new
1093 /// BarrierChain, and those below it.
1094 void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
1095                                               Value2SUsMap &loads, unsigned N) {
1096   DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n";
1097         stores.dump();
1098         dbgs() << "Loading SUnits:\n";
1099         loads.dump());
1100 
1101   // Insert all SU's NodeNums into a vector and sort it.
1102   std::vector<unsigned> NodeNums;
1103   NodeNums.reserve(stores.size() + loads.size());
1104   for (auto &I : stores)
1105     for (auto *SU : I.second)
1106       NodeNums.push_back(SU->NodeNum);
1107   for (auto &I : loads)
1108     for (auto *SU : I.second)
1109       NodeNums.push_back(SU->NodeNum);
1110   std::sort(NodeNums.begin(), NodeNums.end());
1111 
1112   // The N last elements in NodeNums will be removed, and the SU with
1113   // the lowest NodeNum of them will become the new BarrierChain to
1114   // let the not yet seen SUs have a dependency to the removed SUs.
1115   assert (N <= NodeNums.size());
1116   SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1117   if (BarrierChain) {
1118     // The aliasing and non-aliasing maps reduce independently of each
1119     // other, but share a common BarrierChain. Check if the
1120     // newBarrierChain is above the former one. If it is not, it may
1121     // introduce a loop to use newBarrierChain, so keep the old one.
1122     if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1123       BarrierChain->addPredBarrier(newBarrierChain);
1124       BarrierChain = newBarrierChain;
1125       DEBUG(dbgs() << "Inserting new barrier chain: SU("
1126             << BarrierChain->NodeNum << ").\n";);
1127     }
1128     else
1129       DEBUG(dbgs() << "Keeping old barrier chain: SU("
1130             << BarrierChain->NodeNum << ").\n";);
1131   }
1132   else
1133     BarrierChain = newBarrierChain;
1134 
1135   insertBarrierChain(stores);
1136   insertBarrierChain(loads);
1137 
1138   DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n";
1139         stores.dump();
1140         dbgs() << "Loading SUnits:\n";
1141         loads.dump());
1142 }
1143 
1144 /// \brief Initialize register live-range state for updating kills.
1145 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1146   // Start with no live registers.
1147   LiveRegs.reset();
1148 
1149   // Examine the live-in regs of all successors.
1150   for (const MachineBasicBlock *Succ : BB->successors()) {
1151     for (const auto &LI : Succ->liveins()) {
1152       // Repeat, for reg and all subregs.
1153       for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
1154            SubRegs.isValid(); ++SubRegs)
1155         LiveRegs.set(*SubRegs);
1156     }
1157   }
1158 }
1159 
1160 /// \brief If we change a kill flag on the bundle instruction implicit register
1161 /// operands, then we also need to propagate that to any instructions inside
1162 /// the bundle which had the same kill state.
1163 static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
1164                                  bool NewKillState,
1165                                  const TargetRegisterInfo *TRI) {
1166   if (MI->getOpcode() != TargetOpcode::BUNDLE)
1167     return;
1168 
1169   // Walk backwards from the last instruction in the bundle to the first.
1170   // Once we set a kill flag on an instruction, we bail out, as otherwise we
1171   // might set it on too many operands.  We will clear as many flags as we
1172   // can though.
1173   MachineBasicBlock::instr_iterator Begin = MI->getIterator();
1174   MachineBasicBlock::instr_iterator End = getBundleEnd(Begin);
1175   while (Begin != End) {
1176     if (NewKillState) {
1177       if ((--End)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
1178          return;
1179     } else
1180         (--End)->clearRegisterKills(Reg, TRI);
1181   }
1182 }
1183 
1184 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1185   // Setting kill flag...
1186   if (!MO.isKill()) {
1187     MO.setIsKill(true);
1188     toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
1189     return false;
1190   }
1191 
1192   // If MO itself is live, clear the kill flag...
1193   if (LiveRegs.test(MO.getReg())) {
1194     MO.setIsKill(false);
1195     toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
1196     return false;
1197   }
1198 
1199   // If any subreg of MO is live, then create an imp-def for that
1200   // subreg and keep MO marked as killed.
1201   MO.setIsKill(false);
1202   toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
1203   bool AllDead = true;
1204   const unsigned SuperReg = MO.getReg();
1205   MachineInstrBuilder MIB(MF, MI);
1206   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1207     if (LiveRegs.test(*SubRegs)) {
1208       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1209       AllDead = false;
1210     }
1211   }
1212 
1213   if(AllDead) {
1214     MO.setIsKill(true);
1215     toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
1216   }
1217   return false;
1218 }
1219 
1220 // FIXME: Reuse the LivePhysRegs utility for this.
1221 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1222   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1223 
1224   LiveRegs.resize(TRI->getNumRegs());
1225   BitVector killedRegs(TRI->getNumRegs());
1226 
1227   startBlockForKills(MBB);
1228 
1229   // Examine block from end to start...
1230   unsigned Count = MBB->size();
1231   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1232        I != E; --Count) {
1233     MachineInstr &MI = *--I;
1234     if (MI.isDebugValue())
1235       continue;
1236 
1237     // Update liveness.  Registers that are defed but not used in this
1238     // instruction are now dead. Mark register and all subregs as they
1239     // are completely defined.
1240     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1241       MachineOperand &MO = MI.getOperand(i);
1242       if (MO.isRegMask())
1243         LiveRegs.clearBitsNotInMask(MO.getRegMask());
1244       if (!MO.isReg()) continue;
1245       unsigned Reg = MO.getReg();
1246       if (Reg == 0) continue;
1247       if (!MO.isDef()) continue;
1248       // Ignore two-addr defs.
1249       if (MI.isRegTiedToUseOperand(i)) continue;
1250 
1251       // Repeat for reg and all subregs.
1252       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1253            SubRegs.isValid(); ++SubRegs)
1254         LiveRegs.reset(*SubRegs);
1255     }
1256 
1257     // Examine all used registers and set/clear kill flag. When a
1258     // register is used multiple times we only set the kill flag on
1259     // the first use. Don't set kill flags on undef operands.
1260     killedRegs.reset();
1261 
1262     // toggleKillFlag can append new operands (implicit defs), so using
1263     // a range-based loop is not safe. The new operands will be appended
1264     // at the end of the operand list and they don't need to be visited,
1265     // so iterating until the currently last operand is ok.
1266     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1267       MachineOperand &MO = MI.getOperand(i);
1268       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1269       unsigned Reg = MO.getReg();
1270       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1271 
1272       bool kill = false;
1273       if (!killedRegs.test(Reg)) {
1274         kill = true;
1275         // A register is not killed if any subregs are live...
1276         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1277           if (LiveRegs.test(*SubRegs)) {
1278             kill = false;
1279             break;
1280           }
1281         }
1282 
1283         // If subreg is not live, then register is killed if it became
1284         // live in this instruction
1285         if (kill)
1286           kill = !LiveRegs.test(Reg);
1287       }
1288 
1289       if (MO.isKill() != kill) {
1290         DEBUG(dbgs() << "Fixing " << MO << " in ");
1291         toggleKillFlag(&MI, MO);
1292         DEBUG(MI.dump());
1293         DEBUG({
1294           if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1295             MachineBasicBlock::instr_iterator Begin = MI.getIterator();
1296             MachineBasicBlock::instr_iterator End = getBundleEnd(Begin);
1297             while (++Begin != End)
1298               DEBUG(Begin->dump());
1299           }
1300         });
1301       }
1302 
1303       killedRegs.set(Reg);
1304     }
1305 
1306     // Mark any used register (that is not using undef) and subregs as
1307     // now live...
1308     for (const MachineOperand &MO : MI.operands()) {
1309       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1310       unsigned Reg = MO.getReg();
1311       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1312 
1313       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1314            SubRegs.isValid(); ++SubRegs)
1315         LiveRegs.set(*SubRegs);
1316     }
1317   }
1318 }
1319 
1320 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1322   SU->getInstr()->dump();
1323 #endif
1324 }
1325 
1326 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1327   std::string s;
1328   raw_string_ostream oss(s);
1329   if (SU == &EntrySU)
1330     oss << "<entry>";
1331   else if (SU == &ExitSU)
1332     oss << "<exit>";
1333   else
1334     SU->getInstr()->print(oss, /*SkipOpers=*/true);
1335   return oss.str();
1336 }
1337 
1338 /// Return the basic block label. It is not necessarilly unique because a block
1339 /// contains multiple scheduling regions. But it is fine for visualization.
1340 std::string ScheduleDAGInstrs::getDAGName() const {
1341   return "dag." + BB->getFullName();
1342 }
1343 
1344 //===----------------------------------------------------------------------===//
1345 // SchedDFSResult Implementation
1346 //===----------------------------------------------------------------------===//
1347 
1348 namespace llvm {
1349 /// \brief Internal state used to compute SchedDFSResult.
1350 class SchedDFSImpl {
1351   SchedDFSResult &R;
1352 
1353   /// Join DAG nodes into equivalence classes by their subtree.
1354   IntEqClasses SubtreeClasses;
1355   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1356   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1357 
1358   struct RootData {
1359     unsigned NodeID;
1360     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
1361     unsigned SubInstrCount; // Instr count in this tree only, not children.
1362 
1363     RootData(unsigned id): NodeID(id),
1364                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1365                            SubInstrCount(0) {}
1366 
1367     unsigned getSparseSetIndex() const { return NodeID; }
1368   };
1369 
1370   SparseSet<RootData> RootSet;
1371 
1372 public:
1373   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1374     RootSet.setUniverse(R.DFSNodeData.size());
1375   }
1376 
1377   /// Return true if this node been visited by the DFS traversal.
1378   ///
1379   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1380   /// ID. Later, SubtreeID is updated but remains valid.
1381   bool isVisited(const SUnit *SU) const {
1382     return R.DFSNodeData[SU->NodeNum].SubtreeID
1383       != SchedDFSResult::InvalidSubtreeID;
1384   }
1385 
1386   /// Initialize this node's instruction count. We don't need to flag the node
1387   /// visited until visitPostorder because the DAG cannot have cycles.
1388   void visitPreorder(const SUnit *SU) {
1389     R.DFSNodeData[SU->NodeNum].InstrCount =
1390       SU->getInstr()->isTransient() ? 0 : 1;
1391   }
1392 
1393   /// Called once for each node after all predecessors are visited. Revisit this
1394   /// node's predecessors and potentially join them now that we know the ILP of
1395   /// the other predecessors.
1396   void visitPostorderNode(const SUnit *SU) {
1397     // Mark this node as the root of a subtree. It may be joined with its
1398     // successors later.
1399     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1400     RootData RData(SU->NodeNum);
1401     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1402 
1403     // If any predecessors are still in their own subtree, they either cannot be
1404     // joined or are large enough to remain separate. If this parent node's
1405     // total instruction count is not greater than a child subtree by at least
1406     // the subtree limit, then try to join it now since splitting subtrees is
1407     // only useful if multiple high-pressure paths are possible.
1408     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1409     for (const SDep &PredDep : SU->Preds) {
1410       if (PredDep.getKind() != SDep::Data)
1411         continue;
1412       unsigned PredNum = PredDep.getSUnit()->NodeNum;
1413       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1414         joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
1415 
1416       // Either link or merge the TreeData entry from the child to the parent.
1417       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1418         // If the predecessor's parent is invalid, this is a tree edge and the
1419         // current node is the parent.
1420         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1421           RootSet[PredNum].ParentNodeID = SU->NodeNum;
1422       }
1423       else if (RootSet.count(PredNum)) {
1424         // The predecessor is not a root, but is still in the root set. This
1425         // must be the new parent that it was just joined to. Note that
1426         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1427         // set to the original parent.
1428         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1429         RootSet.erase(PredNum);
1430       }
1431     }
1432     RootSet[SU->NodeNum] = RData;
1433   }
1434 
1435   /// Called once for each tree edge after calling visitPostOrderNode on the
1436   /// predecessor. Increment the parent node's instruction count and
1437   /// preemptively join this subtree to its parent's if it is small enough.
1438   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1439     R.DFSNodeData[Succ->NodeNum].InstrCount
1440       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1441     joinPredSubtree(PredDep, Succ);
1442   }
1443 
1444   /// Add a connection for cross edges.
1445   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1446     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1447   }
1448 
1449   /// Set each node's subtree ID to the representative ID and record connections
1450   /// between trees.
1451   void finalize() {
1452     SubtreeClasses.compress();
1453     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1454     assert(SubtreeClasses.getNumClasses() == RootSet.size()
1455            && "number of roots should match trees");
1456     for (const RootData &Root : RootSet) {
1457       unsigned TreeID = SubtreeClasses[Root.NodeID];
1458       if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1459         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1460       R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1461       // Note that SubInstrCount may be greater than InstrCount if we joined
1462       // subtrees across a cross edge. InstrCount will be attributed to the
1463       // original parent, while SubInstrCount will be attributed to the joined
1464       // parent.
1465     }
1466     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1467     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1468     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1469     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1470       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1471       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1472             << R.DFSNodeData[Idx].SubtreeID << '\n');
1473     }
1474     for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
1475       unsigned PredTree = SubtreeClasses[P.first->NodeNum];
1476       unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
1477       if (PredTree == SuccTree)
1478         continue;
1479       unsigned Depth = P.first->getDepth();
1480       addConnection(PredTree, SuccTree, Depth);
1481       addConnection(SuccTree, PredTree, Depth);
1482     }
1483   }
1484 
1485 protected:
1486   /// Join the predecessor subtree with the successor that is its DFS
1487   /// parent. Apply some heuristics before joining.
1488   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1489                        bool CheckLimit = true) {
1490     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1491 
1492     // Check if the predecessor is already joined.
1493     const SUnit *PredSU = PredDep.getSUnit();
1494     unsigned PredNum = PredSU->NodeNum;
1495     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1496       return false;
1497 
1498     // Four is the magic number of successors before a node is considered a
1499     // pinch point.
1500     unsigned NumDataSucs = 0;
1501     for (const SDep &SuccDep : PredSU->Succs) {
1502       if (SuccDep.getKind() == SDep::Data) {
1503         if (++NumDataSucs >= 4)
1504           return false;
1505       }
1506     }
1507     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1508       return false;
1509     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1510     SubtreeClasses.join(Succ->NodeNum, PredNum);
1511     return true;
1512   }
1513 
1514   /// Called by finalize() to record a connection between trees.
1515   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1516     if (!Depth)
1517       return;
1518 
1519     do {
1520       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1521         R.SubtreeConnections[FromTree];
1522       for (SchedDFSResult::Connection &C : Connections) {
1523         if (C.TreeID == ToTree) {
1524           C.Level = std::max(C.Level, Depth);
1525           return;
1526         }
1527       }
1528       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1529       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1530     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1531   }
1532 };
1533 } // namespace llvm
1534 
1535 namespace {
1536 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
1537 class SchedDAGReverseDFS {
1538   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1539 public:
1540   bool isComplete() const { return DFSStack.empty(); }
1541 
1542   void follow(const SUnit *SU) {
1543     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1544   }
1545   void advance() { ++DFSStack.back().second; }
1546 
1547   const SDep *backtrack() {
1548     DFSStack.pop_back();
1549     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1550   }
1551 
1552   const SUnit *getCurr() const { return DFSStack.back().first; }
1553 
1554   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1555 
1556   SUnit::const_pred_iterator getPredEnd() const {
1557     return getCurr()->Preds.end();
1558   }
1559 };
1560 } // anonymous
1561 
1562 static bool hasDataSucc(const SUnit *SU) {
1563   for (const SDep &SuccDep : SU->Succs) {
1564     if (SuccDep.getKind() == SDep::Data &&
1565         !SuccDep.getSUnit()->isBoundaryNode())
1566       return true;
1567   }
1568   return false;
1569 }
1570 
1571 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1572 /// search from this root.
1573 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1574   if (!IsBottomUp)
1575     llvm_unreachable("Top-down ILP metric is unimplemnted");
1576 
1577   SchedDFSImpl Impl(*this);
1578   for (const SUnit &SU : SUnits) {
1579     if (Impl.isVisited(&SU) || hasDataSucc(&SU))
1580       continue;
1581 
1582     SchedDAGReverseDFS DFS;
1583     Impl.visitPreorder(&SU);
1584     DFS.follow(&SU);
1585     for (;;) {
1586       // Traverse the leftmost path as far as possible.
1587       while (DFS.getPred() != DFS.getPredEnd()) {
1588         const SDep &PredDep = *DFS.getPred();
1589         DFS.advance();
1590         // Ignore non-data edges.
1591         if (PredDep.getKind() != SDep::Data
1592             || PredDep.getSUnit()->isBoundaryNode()) {
1593           continue;
1594         }
1595         // An already visited edge is a cross edge, assuming an acyclic DAG.
1596         if (Impl.isVisited(PredDep.getSUnit())) {
1597           Impl.visitCrossEdge(PredDep, DFS.getCurr());
1598           continue;
1599         }
1600         Impl.visitPreorder(PredDep.getSUnit());
1601         DFS.follow(PredDep.getSUnit());
1602       }
1603       // Visit the top of the stack in postorder and backtrack.
1604       const SUnit *Child = DFS.getCurr();
1605       const SDep *PredDep = DFS.backtrack();
1606       Impl.visitPostorderNode(Child);
1607       if (PredDep)
1608         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1609       if (DFS.isComplete())
1610         break;
1611     }
1612   }
1613   Impl.finalize();
1614 }
1615 
1616 /// The root of the given SubtreeID was just scheduled. For all subtrees
1617 /// connected to this tree, record the depth of the connection so that the
1618 /// nearest connected subtrees can be prioritized.
1619 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1620   for (const Connection &C : SubtreeConnections[SubtreeID]) {
1621     SubtreeConnectLevels[C.TreeID] =
1622       std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1623     DEBUG(dbgs() << "  Tree: " << C.TreeID
1624           << " @" << SubtreeConnectLevels[C.TreeID] << '\n');
1625   }
1626 }
1627 
1628 LLVM_DUMP_METHOD
1629 void ILPValue::print(raw_ostream &OS) const {
1630   OS << InstrCount << " / " << Length << " = ";
1631   if (!Length)
1632     OS << "BADILP";
1633   else
1634     OS << format("%g", ((double)InstrCount / Length));
1635 }
1636 
1637 LLVM_DUMP_METHOD
1638 void ILPValue::dump() const {
1639   dbgs() << *this << '\n';
1640 }
1641 
1642 namespace llvm {
1643 
1644 LLVM_DUMP_METHOD
1645 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1646   Val.print(OS);
1647   return OS;
1648 }
1649 
1650 } // namespace llvm
1651