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