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