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