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