LLVM 24.0.0git
WindowScheduler.cpp
Go to the documentation of this file.
1//======----------- WindowScheduler.cpp - window scheduler -------------======//
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// An implementation of the Window Scheduling software pipelining algorithm.
10//
11// The fundamental concept of the window scheduling algorithm involves folding
12// the original MBB at a specific position, followed by list scheduling on the
13// folded MIs. The optimal scheduling result is then chosen from various folding
14// positions as the final scheduling outcome.
15//
16// The primary challenge in this algorithm lies in generating the folded MIs and
17// establishing their dependencies. We have innovatively employed a new MBB,
18// created by copying the original MBB three times, known as TripleMBB. This
19// TripleMBB enables the convenient implementation of MI folding and dependency
20// establishment. To facilitate the algorithm's implementation, we have also
21// devised data structures such as OriMIs, TriMIs, TriToOri, and OriToCycle.
22//
23// Another challenge in the algorithm is the scheduling of phis. Semantically,
24// it is difficult to place the phis in the window and perform list scheduling.
25// Therefore, we schedule these phis separately after each list scheduling.
26//
27// The provided implementation is designed for use before the Register Allocator
28// (RA). If the target requires implementation after RA, it is recommended to
29// reimplement analyseII(), schedulePhi(), and expand(). Additionally,
30// target-specific logic can be added in initialize(), preProcess(), and
31// postProcess().
32//
33// Lastly, it is worth mentioning that getSearchIndexes() is an important
34// function. We have experimented with more complex heuristics on downstream
35// target and achieved favorable results.
36//
37//===----------------------------------------------------------------------===//
39#include "CodeGenOptions.h"
40#include "llvm/ADT/Statistic.h"
50#include "llvm/Support/Debug.h"
53
54using namespace llvm;
55
56#define DEBUG_TYPE "pipeliner"
57
58namespace {
59STATISTIC(NumTryWindowSchedule,
60 "Number of loops that we attempt to use window scheduling");
61STATISTIC(NumTryWindowSearch,
62 "Number of times that we run list schedule in the window scheduling");
63STATISTIC(NumWindowSchedule,
64 "Number of loops that we successfully use window scheduling");
65STATISTIC(NumFailAnalyseII,
66 "Window scheduling abort due to the failure of the II analysis");
67} // namespace
68
69/// Collect the underlying objects and alias metadata for the single memory
70/// operand of MI. Returns false when MI does not have exactly one memory
71/// operand with a known IR value.
72static bool getMemInfo(const MachineInstr *MI, const Value *&MemOpValue,
73 int64_t &MemOpOffset,
74 SmallVectorImpl<const Value *> &UnderlyingObjs,
75 AAMDNodes &AATags, bool &IsAllIdentified) {
76 if (!MI->hasOneMemOperand())
77 return false;
78 MachineMemOperand *MM = *MI->memoperands_begin();
79 if (!MM->getValue())
80 return false;
81 MemOpValue = MM->getValue();
82 MemOpOffset = MM->getOffset();
83 getUnderlyingObjects(MemOpValue, UnderlyingObjs);
84 AATags = MM->getAAInfo();
85 IsAllIdentified = llvm::all_of(UnderlyingObjs, isIdentifiedObject);
86 return true;
87}
88
89/// Return true if there is a loop-carried order dependency from memory access
90/// SrcMI to DstMI in loop LoopBB.
91static bool hasLoopCarriedMemDep(const MachineInstr *SrcMI,
92 const MachineInstr *DstMI, BatchAAResults &BAA,
93 const MachineBasicBlock *LoopBB,
95 const TargetInstrInfo *TII) {
96 const Value *SrcVal = nullptr, *DstVal = nullptr;
97 int64_t SrcOffset = 0, DstOffset = 0;
98 SmallVector<const Value *, 4> SrcObjs, DstObjs;
99 AAMDNodes SrcAATags, DstAATags;
100 bool SrcAllIdentified = false, DstAllIdentified = false;
101 bool SrcKnown = getMemInfo(SrcMI, SrcVal, SrcOffset, SrcObjs, SrcAATags,
102 SrcAllIdentified);
103 bool DstKnown = getMemInfo(DstMI, DstVal, DstOffset, DstObjs, DstAATags,
104 DstAllIdentified);
105
106 // If all underlying objects are identified and disjoint, the accesses cannot
107 // alias.
108 if (SrcKnown && DstKnown && SrcAllIdentified && DstAllIdentified &&
109 llvm::none_of(SrcObjs, [&](const Value *Obj) {
110 return llvm::is_contained(DstObjs, Obj);
111 }))
112 return false;
113
114 // The overlap helper inspects only the first memory operand. Multi-MMO
115 // instructions could carry an overlap through a later operand, so be
116 // conservative and keep the dependency for them.
117 if (!SrcMI->hasOneMemOperand() || !DstMI->hasOneMemOperand())
118 return true;
119
120 if (!mayOverlapInLaterIter(SrcMI, DstMI, LoopBB, MRI, *TII))
121 return false;
122
123 // The more expensive check that uses alias analysis on the base values.
124 if (!SrcKnown || !DstKnown)
125 return true;
126 if (SrcVal == DstVal && SrcOffset <= DstOffset)
127 return true;
128
129 if (BAA.isNoAlias(MemoryLocation::getBeforeOrAfter(SrcVal, SrcAATags),
130 MemoryLocation::getBeforeOrAfter(DstVal, DstAATags)))
131 return false;
132
133 // AliasAnalysis sometimes gives up on following the underlying object. In
134 // such a case, separate checks for underlying objects may prove that there
135 // are no aliases between two accesses.
136 for (const Value *SrcObj : SrcObjs)
137 for (const Value *DstObj : DstObjs)
138 if (!BAA.isNoAlias(MemoryLocation::getBeforeOrAfter(SrcObj, SrcAATags),
139 MemoryLocation::getBeforeOrAfter(DstObj, DstAATags)))
140 return true;
141
142 return false;
143}
144
145namespace {
146/// A DAG mutation that enforces the loop-carried memory dependences discovered
147/// on the original loop while list scheduling each window of TripleMBB.
148///
149/// For each recorded hazard pair (Pred, Succ) we add an artificial order edge
150/// between the clone of Pred and the clone of Succ belonging to a later copy,
151/// so that the iteration-N Pred is kept before the iteration-(N+1) Succ.
152class WindowMemDepMutation : public ScheduleDAGMutation {
153 const DenseSet<std::pair<MachineInstr *, MachineInstr *>> &LoopCarriedMemDeps;
154 const DenseMap<MachineInstr *, TriCloneInfo> &TriToOri;
155 bool &EdgeFailed;
156
157public:
158 WindowMemDepMutation(
159 const DenseSet<std::pair<MachineInstr *, MachineInstr *>> &Deps,
160 const DenseMap<MachineInstr *, TriCloneInfo> &TriToOri, bool &EdgeFailed)
161 : LoopCarriedMemDeps(Deps), TriToOri(TriToOri), EdgeFailed(EdgeFailed) {}
162
163 void apply(ScheduleDAGInstrs *DAG) override {
164 if (LoopCarriedMemDeps.empty())
165 return;
166 for (SUnit &PredSU : DAG->SUnits) {
167 MachineInstr *PredMI = PredSU.getInstr();
168 if (!PredMI || !PredMI->mayLoadOrStore())
169 continue;
170 auto PredIt = TriToOri.find(PredMI);
171 if (PredIt == TriToOri.end())
172 continue;
173 for (SUnit &SuccSU : DAG->SUnits) {
174 MachineInstr *SuccMI = SuccSU.getInstr();
175 if (&PredSU == &SuccSU || !SuccMI || !SuccMI->mayLoadOrStore())
176 continue;
177 auto SuccIt = TriToOri.find(SuccMI);
178 if (SuccIt == TriToOri.end())
179 continue;
180 // Only order a Pred from an earlier copy before a Succ from a later
181 // copy, which models the iteration-N to iteration-(N+1) dependence.
182 if (PredIt->second.Copy >= SuccIt->second.Copy)
183 continue;
184 if (!LoopCarriedMemDeps.contains(
185 {PredIt->second.Ori, SuccIt->second.Ori}))
186 continue;
187 // If the edge would create a cycle, addEdge() returns false and does
188 // not insert it. The required dependence then cannot be enforced in
189 // this window, so mark it to make the caller abandon this window's
190 // schedule.
191 if (!DAG->addEdge(&SuccSU, SDep(&PredSU, SDep::Barrier)))
192 EdgeFailed = true;
193 }
194 }
195 }
196};
197} // end anonymous namespace
198
201 : Opts(getCodeGenOptions(*C->MF)), Context(C), MF(C->MF),
202 MBB(ML.getHeader()), Loop(ML), Subtarget(&MF->getSubtarget()),
203 TII(Subtarget->getInstrInfo()), TRI(Subtarget->getRegisterInfo()),
204 MRI(&MF->getRegInfo()), MDT(MDT) {
205 TripleDAG = std::unique_ptr<ScheduleDAGInstrs>(
206 createMachineScheduler(/*OnlyBuildGraph=*/true));
207}
208
210 if (!initialize()) {
211 LLVM_DEBUG(dbgs() << "The WindowScheduler failed to initialize!\n");
212 return false;
213 }
214 // The window algorithm is time-consuming, and its compilation time should be
215 // taken into consideration.
216 TimeTraceScope Scope("WindowSearch");
217 ++NumTryWindowSchedule;
218 // Performing the relevant processing before window scheduling.
219 preProcess();
220 // The main window scheduling begins.
221 std::unique_ptr<ScheduleDAGInstrs> SchedDAG(createMachineScheduler());
222 // A target may decline to provide a scheduler, in which case fall back to the
223 // generic live scheduler so that window scheduling still has one to drive.
224 if (!SchedDAG)
225 SchedDAG.reset(createSchedLive(Context));
226 // Attach the mutation that enforces the loop-carried memory dependences.
227 // This requires the scheduler to support DAG mutations, i.e. to be a
228 // ScheduleDAGMI. Every in-tree target's pre-RA machine scheduler is a
229 // ScheduleDAGMI (or ScheduleDAGMILive), and the generic fallback
230 // createSchedLive() above returns one as well, so the cast below is safe.
231 // The assert documents and guards this invariant.
232 assert(SchedDAG && "Expected a scheduler for window scheduling");
233 auto *SchedDAGMI = static_cast<ScheduleDAGMI *>(SchedDAG.get());
234 SchedDAGMI->addMutation(std::make_unique<WindowMemDepMutation>(
236 auto SearchIndexes =
237 getSearchIndexes(Opts.window_search_num, Opts.window_search_ratio);
238 for (unsigned Idx : SearchIndexes) {
239 OriToCycle.clear();
240 ++NumTryWindowSearch;
241 // The scheduling starts with non-phi instruction, so SchedPhiNum needs to
242 // be added to Idx.
243 unsigned Offset = Idx + SchedPhiNum;
245 MemDepEdgeFailed = false;
246 SchedDAG->startBlock(MBB);
247 SchedDAG->enterRegion(MBB, Range.begin(), Range.end(), SchedInstrNum);
248 SchedDAG->schedule();
249 LLVM_DEBUG(SchedDAG->dump());
250 if (MemDepEdgeFailed) {
252 LLVM_DEBUG(dbgs() << "Can't enforce a loop-carried memory dependence. "
253 "Keep searching...\n");
254 continue;
255 }
256 unsigned II = analyseII(*SchedDAG, Offset);
257 if (II == Opts.window_ii_limit) {
259 LLVM_DEBUG(dbgs() << "Can't find a valid II. Keep searching...\n");
260 ++NumFailAnalyseII;
261 continue;
262 }
266 LLVM_DEBUG(dbgs() << "Current window Offset is " << Offset << " and II is "
267 << II << ".\n");
268 }
269 // Performing the relevant processing after window scheduling.
270 postProcess();
271 // Check whether the scheduling result is valid.
272 if (!isScheduleValid()) {
273 LLVM_DEBUG(dbgs() << "Window scheduling is not needed!\n");
274 return false;
275 }
276 LLVM_DEBUG(dbgs() << "\nBest window offset is " << BestOffset
277 << " and Best II is " << BestII << ".\n");
278 // Expand the scheduling result to prologue, kernel, and epilogue.
279 expand();
280 ++NumWindowSchedule;
281 return true;
282}
283
286 return OnlyBuildGraph
287 ? new ScheduleDAGMI(
288 Context, std::make_unique<PostGenericScheduler>(Context),
289 true)
290 : Context->TM->createMachineScheduler(Context);
291}
292
294 if (!Subtarget->enableWindowScheduler()) {
295 LLVM_DEBUG(dbgs() << "Target disables the window scheduling!\n");
296 return false;
297 }
298 // Initialized the member variables used by window algorithm.
299 OriMIs.clear();
300 TriMIs.clear();
301 TriToOri.clear();
302 OriToCycle.clear();
303 SchedResult.clear();
304 SchedPhiNum = 0;
305 SchedInstrNum = 0;
306 BestII = UINT_MAX;
307 BestOffset = 0;
308 BaseII = 0;
309 // List scheduling used in the window algorithm depends on LiveIntervals.
310 if (!Context->LIS) {
311 LLVM_DEBUG(dbgs() << "There is no LiveIntervals information!\n");
312 return false;
313 }
314 // Check each MI in MBB.
315 SmallSet<Register, 8> PrevDefs;
316 SmallSet<Register, 8> PrevUses;
317 auto IsLoopCarried = [&](MachineInstr &Phi) {
318 // Two cases are checked here: (1)The virtual register defined by the
319 // preceding phi is used by the succeeding phi;(2)The preceding phi uses the
320 // virtual register defined by the succeeding phi.
321 if (PrevUses.count(Phi.getOperand(0).getReg()))
322 return true;
323 PrevDefs.insert(Phi.getOperand(0).getReg());
324 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
325 if (PrevDefs.count(Phi.getOperand(I).getReg()))
326 return true;
327 PrevUses.insert(Phi.getOperand(I).getReg());
328 }
329 return false;
330 };
331 auto PLI = TII->analyzeLoopForPipelining(MBB);
332 for (auto &MI : *MBB) {
333 if (MI.isDebugOrPseudoInstr() || MI.isTerminator())
334 continue;
335 if (MI.isPHI()) {
336 if (IsLoopCarried(MI)) {
337 LLVM_DEBUG(dbgs() << "Loop carried phis are not supported yet!\n");
338 return false;
339 }
340 ++SchedPhiNum;
341 ++BestOffset;
342 } else
344 if (TII->isSchedulingBoundary(MI, MBB, *MF)) {
346 dbgs() << "Boundary MI is not allowed in window scheduling!\n");
347 return false;
348 }
349 if (PLI->shouldIgnoreForPipelining(&MI)) {
350 LLVM_DEBUG(dbgs() << "Special MI defined by target is not allowed in "
351 "window scheduling!\n");
352 return false;
353 }
354 for (auto &Def : MI.all_defs())
355 if (Def.isReg() && Def.getReg().isPhysical()) {
356 LLVM_DEBUG(dbgs() << "Physical registers are not supported in "
357 "window scheduling!\n");
358 return false;
359 }
360 }
361 if (SchedInstrNum <= Opts.window_region_limit) {
362 LLVM_DEBUG(dbgs() << "There are too few MIs in the window region!\n");
363 return false;
364 }
365 return true;
366}
367
369 // Prior to window scheduling, it's necessary to backup the original MBB,
370 // generate a new TripleMBB, and build a TripleDAG based on the TripleMBB.
371 // Collect loop-carried memory dependences first, while the original MBB is
372 // still live (see collectLoopCarriedMemDeps() and run()).
374 backupMBB();
376 TripleDAG->startBlock(MBB);
377 TripleDAG->enterRegion(
378 MBB, MBB->begin(), MBB->getFirstTerminator(),
379 std::distance(MBB->begin(), MBB->getFirstTerminator()));
380 TripleDAG->buildSchedGraph(Context->AA);
381}
382
384 LoopCarriedMemDeps.clear();
385 MachineBasicBlock *LoopBB = MBB;
386
387 // Collect the memory instructions of the original loop in program order.
389 for (MachineInstr &MI : *LoopBB)
390 if (MI.mayLoadOrStore() && !MI.isDebugInstr())
391 MemMIs.push_back(&MI);
392
393 // Nothing to do unless there is at least one store to order against.
394 if (llvm::none_of(MemMIs,
395 [](const MachineInstr *MI) { return MI->mayStore(); }))
396 return;
397
398 BatchAAResults BAA(*Context->AA);
400
401 for (MachineInstr *SrcMI : MemMIs) {
402 for (MachineInstr *DstMI : MemMIs) {
403 if (SrcMI == DstMI)
404 continue;
405 // A loop-carried order edge is only required when at least one of the
406 // accesses stores.
407 if (!SrcMI->mayStore() && !DstMI->mayStore())
408 continue;
409 if (hasLoopCarriedMemDep(SrcMI, DstMI, BAA, LoopBB, *MRI, TII))
410 LoopCarriedMemDeps.insert({SrcMI, DstMI});
411 }
412 }
413}
414
416 // After window scheduling, it's necessary to clear the TripleDAG and restore
417 // to the original MBB.
418 TripleDAG->exitRegion();
419 TripleDAG->finishBlock();
420 restoreMBB();
421}
422
424 for (auto &MI : MBB->instrs())
425 OriMIs.push_back(&MI);
426 // Remove MIs and the corresponding live intervals.
427 for (auto &MI : make_early_inc_range(*MBB)) {
428 Context->LIS->getSlotIndexes()->removeMachineInstrFromMaps(MI, true);
429 MBB->remove(&MI);
430 }
431}
432
434 // Erase MIs and the corresponding live intervals.
435 for (auto &MI : make_early_inc_range(*MBB)) {
436 Context->LIS->getSlotIndexes()->removeMachineInstrFromMaps(MI, true);
437 MI.eraseFromParent();
438 }
439 // Restore MBB to the state before window scheduling.
442}
443
445 const unsigned DuplicateNum = 3;
446 TriMIs.clear();
447 TriToOri.clear();
448 assert(OriMIs.size() > 0 && "The Original MIs were not backed up!");
449 // Step 1: Performing the first copy of MBB instructions, excluding
450 // terminators. At the same time, we back up the anti-register of phis.
451 // DefPairs hold the old and new define register pairs.
453 for (auto *MI : OriMIs) {
454 if (MI->isDebugOrPseudoInstr() || MI->isTerminator())
455 continue;
456 if (MI->isPHI())
457 if (Register AntiReg = getAntiRegister(MI))
458 DefPairs[MI->getOperand(0).getReg()] = AntiReg;
459 auto *NewMI = MF->CloneMachineInstr(MI);
460 MBB->push_back(NewMI);
461 TriMIs.push_back(NewMI);
462 TriToOri[NewMI] = {MI, 0};
463 }
464 // Step 2: Performing the remaining two copies of MBB instructions excluding
465 // phis, and the last one contains terminators. At the same time, registers
466 // are updated accordingly.
467 for (size_t Cnt = 1; Cnt < DuplicateNum; ++Cnt) {
468 for (auto *MI : OriMIs) {
469 if (MI->isPHI() || MI->isDebugOrPseudoInstr() ||
470 (MI->isTerminator() && Cnt < DuplicateNum - 1))
471 continue;
472 auto *NewMI = MF->CloneMachineInstr(MI);
474 // New defines are updated.
475 for (auto MO : NewMI->all_defs())
476 if (MO.isReg() && MO.getReg().isVirtual()) {
477 Register NewDef =
478 MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));
479 NewMI->substituteRegister(MO.getReg(), NewDef, 0, *TRI);
480 NewDefs[MO.getReg()] = NewDef;
481 }
482 // New uses are updated.
483 for (auto DefRegPair : DefPairs)
484 if (NewMI->readsRegister(DefRegPair.first, TRI)) {
485 Register NewUse = DefRegPair.second;
486 // Note the update process for '%1 -> %9' in '%10 = sub i32 %9, %3':
487 //
488 // BB.3: DefPairs
489 // ==================================
490 // %1 = phi i32 [%2, %BB.1], [%7, %BB.3] (%1,%7)
491 // ...
492 // ==================================
493 // ...
494 // %4 = sub i32 %1, %3
495 // ...
496 // %7 = add i32 %5, %6
497 // ...
498 // ----------------------------------
499 // ...
500 // %8 = sub i32 %7, %3 (%1,%7),(%4,%8)
501 // ...
502 // %9 = add i32 %5, %6 (%1,%7),(%4,%8),(%7,%9)
503 // ...
504 // ----------------------------------
505 // ...
506 // %10 = sub i32 %9, %3 (%1,%7),(%4,%10),(%7,%9)
507 // ... ^
508 // %11 = add i32 %5, %6 (%1,%7),(%4,%10),(%7,%11)
509 // ...
510 // ==================================
511 // < Terminators >
512 // ==================================
513 if (auto It = DefPairs.find(NewUse); It != DefPairs.end())
514 NewUse = It->second;
515 NewMI->substituteRegister(DefRegPair.first, NewUse, 0, *TRI);
516 }
517 // DefPairs is updated at last.
518 for (auto &NewDef : NewDefs)
519 DefPairs[NewDef.first] = NewDef.second;
520 MBB->push_back(NewMI);
521 TriMIs.push_back(NewMI);
522 TriToOri[NewMI] = {MI, static_cast<unsigned>(Cnt)};
523 }
524 }
525 // Step 3: The registers used by phis are updated, and they are generated in
526 // the third copy of MBB.
527 // In the privious example, the old phi is:
528 // %1 = phi i32 [%2, %BB.1], [%7, %BB.3]
529 // The new phi is:
530 // %1 = phi i32 [%2, %BB.1], [%11, %BB.3]
531 for (auto &Phi : MBB->phis()) {
532 for (auto DefRegPair : DefPairs)
533 if (Phi.readsRegister(DefRegPair.first, TRI))
534 Phi.substituteRegister(DefRegPair.first, DefRegPair.second, 0, *TRI);
535 }
537}
538
540 // After list scheduling, the MBB is restored in one traversal.
541 for (size_t I = 0; I < TriMIs.size(); ++I) {
542 auto *MI = TriMIs[I];
543 auto OldPos = MBB->begin();
544 std::advance(OldPos, I);
545 auto CurPos = MI->getIterator();
546 if (CurPos != OldPos) {
547 MBB->splice(OldPos, MBB, CurPos);
548 Context->LIS->handleMove(*MI, /*UpdateFlags=*/false);
549 }
550 }
551}
552
554 unsigned SearchRatio) {
555 // We use SearchRatio to get the index range, and then evenly get the indexes
556 // according to the SearchNum. This is a simple huristic. Depending on the
557 // characteristics of the target, more complex algorithms can be used for both
558 // performance and compilation time.
559 assert(SearchRatio <= 100 && "SearchRatio should be equal or less than 100!");
560 unsigned MaxIdx = SchedInstrNum * SearchRatio / 100;
561 unsigned Step = SearchNum > 0 && SearchNum <= MaxIdx ? MaxIdx / SearchNum : 1;
562 SmallVector<unsigned> SearchIndexes;
563 for (unsigned Idx = 0; Idx < MaxIdx; Idx += Step)
564 SearchIndexes.push_back(Idx);
565 return SearchIndexes;
566}
567
569 // Sometimes MaxDepth is 0, so it should be limited to the minimum of 1.
570 unsigned MaxDepth = 1;
571 for (auto &SU : DAG.SUnits)
572 MaxDepth = std::max(SU.getDepth() + SU.Latency, MaxDepth);
573 return MaxDepth * Opts.window_ii_coeff;
574}
575
577 unsigned Offset) {
578 int InitII = getEstimatedII(DAG);
579 ResourceManager RM(Subtarget, &DAG);
580 RM.init(InitII);
581 // ResourceManager and DAG are used to calculate the maximum cycle for the
582 // scheduled MIs. Since MIs in the Region have already been scheduled, the
583 // emit cycles can be estimated in order here.
584 int CurCycle = 0;
586 for (auto &MI : Range) {
587 auto *SU = DAG.getSUnit(&MI);
588 int ExpectCycle = CurCycle;
589 // The predecessors of current MI determine its earliest issue cycle.
590 for (auto &Pred : SU->Preds) {
591 if (Pred.isWeak())
592 continue;
593 auto *PredMI = Pred.getSUnit()->getInstr();
594 int PredCycle = getOriCycle(PredMI);
595 ExpectCycle = std::max(ExpectCycle, PredCycle + (int)Pred.getLatency());
596 }
597 // Zero cost instructions do not need to check resource.
598 if (!TII->isZeroCost(MI.getOpcode())) {
599 // ResourceManager can be used to detect resource conflicts between the
600 // current MI and the previously inserted MIs.
601 while (!RM.canReserveResources(*SU, CurCycle) || CurCycle < ExpectCycle) {
602 ++CurCycle;
603 if (CurCycle == (int)Opts.window_ii_limit)
604 return CurCycle;
605 }
606 RM.reserveResources(*SU, CurCycle);
607 }
608 OriToCycle[getOriMI(&MI)] = CurCycle;
609 LLVM_DEBUG(dbgs() << "\tCycle " << CurCycle << " [S."
610 << getOriStage(getOriMI(&MI), Offset) << "]: " << MI);
611 }
612 LLVM_DEBUG(dbgs() << "MaxCycle is " << CurCycle << ".\n");
613 return CurCycle;
614}
615
616// By utilizing TripleDAG, we can easily establish dependencies between A and B.
617// Based on the MaxCycle and the issue cycle of A and B, we can determine
618// whether it is necessary to add a stall cycle. This is because, without
619// inserting the stall cycle, the latency constraint between A and B cannot be
620// satisfied. The details are as follows:
621//
622// New MBB:
623// ========================================
624// < Phis >
625// ======================================== (sliding direction)
626// MBB copy 1 |
627// V
628//
629// ~~~~~~~~~~~~~~~~~~~|~~~~~~~~~~~~~~~~~~~~ ----schedule window-----
630// | |
631// ===================V==================== |
632// MBB copy 2 < MI B > |
633// |
634// < MI A > V
635// ~~~~~~~~~~~~~~~~~~~:~~~~~~~~~~~~~~~~~~~~ ------------------------
636// :
637// ===================V====================
638// MBB copy 3 < MI B'>
639//
640//
641//
642//
643// ========================================
644// < Terminators >
645// ========================================
646int WindowScheduler::calculateStallCycle(unsigned Offset, int MaxCycle) {
647 int MaxStallCycle = 0;
648 int CurrentII = MaxCycle + 1;
650 for (auto &MI : Range) {
651 auto *SU = TripleDAG->getSUnit(&MI);
652 int DefCycle = getOriCycle(&MI);
653 for (auto &Succ : SU->Succs) {
654 if (Succ.isWeak() || Succ.getSUnit() == &TripleDAG->ExitSU)
655 continue;
656 // If the expected cycle does not exceed CurrentII, no check is needed.
657 if (DefCycle + (int)Succ.getLatency() <= CurrentII)
658 continue;
659 // If the cycle of the scheduled MI A is less than that of the scheduled
660 // MI B, the scheduling will fail because the lifetime of the
661 // corresponding register exceeds II.
662 auto *SuccMI = Succ.getSUnit()->getInstr();
663 int UseCycle = getOriCycle(SuccMI);
664 if (DefCycle < UseCycle)
665 return Opts.window_ii_limit;
666 // Get the stall cycle introduced by the register between two trips.
667 int StallCycle = DefCycle + (int)Succ.getLatency() - CurrentII - UseCycle;
668 MaxStallCycle = std::max(MaxStallCycle, StallCycle);
669 }
670 }
671 LLVM_DEBUG(dbgs() << "MaxStallCycle is " << MaxStallCycle << ".\n");
672 return MaxStallCycle;
673}
674
676 LLVM_DEBUG(dbgs() << "Start analyzing II:\n");
677 int MaxCycle = calculateMaxCycle(DAG, Offset);
678 if (MaxCycle == (int)Opts.window_ii_limit)
679 return MaxCycle;
680 int StallCycle = calculateStallCycle(Offset, MaxCycle);
681 if (StallCycle == (int)Opts.window_ii_limit)
682 return StallCycle;
683 // The value of II is equal to the maximum execution cycle plus 1.
684 return MaxCycle + StallCycle + 1;
685}
686
688 LLVM_DEBUG(dbgs() << "Start scheduling Phis:\n");
689 for (auto &Phi : MBB->phis()) {
690 int LateCycle = INT_MAX;
691 auto *SU = TripleDAG->getSUnit(&Phi);
692 for (auto &Succ : SU->Succs) {
693 // Phi doesn't have any Anti successors.
694 if (Succ.getKind() != SDep::Data)
695 continue;
696 // Phi is scheduled before the successor of stage 0. The issue cycle of
697 // phi is the latest cycle in this interval.
698 auto *SuccMI = Succ.getSUnit()->getInstr();
699 int Cycle = getOriCycle(SuccMI);
700 if (getOriStage(getOriMI(SuccMI), Offset) == 0)
701 LateCycle = std::min(LateCycle, Cycle);
702 }
703 // The anti-dependency of phi need to be handled separately in the same way.
704 if (Register AntiReg = getAntiRegister(&Phi)) {
705 auto *AntiMI = MRI->getVRegDef(AntiReg);
706 // AntiReg may be defined outside the kernel MBB.
707 if (AntiMI->getParent() == MBB) {
708 auto AntiCycle = getOriCycle(AntiMI);
709 if (getOriStage(getOriMI(AntiMI), Offset) == 0)
710 LateCycle = std::min(LateCycle, AntiCycle);
711 }
712 }
713 // If there is no limit to the late cycle, a default value is given.
714 if (LateCycle == INT_MAX)
715 LateCycle = (int)(II - 1);
716 LLVM_DEBUG(dbgs() << "\tCycle range [0, " << LateCycle << "] " << Phi);
717 // The issue cycle of phi is set to the latest cycle in the interval.
718 auto *OriPhi = getOriMI(&Phi);
719 OriToCycle[OriPhi] = LateCycle;
720 }
721}
722
724 unsigned II) {
725 // At each issue cycle, phi is placed before MIs in stage 0. So the simplest
726 // way is to put phi at the beginning of the current cycle.
729 for (auto &Phi : MBB->phis())
730 CycleToMIs[getOriCycle(&Phi)].push_back(getOriMI(&Phi));
731 for (auto &MI : Range)
732 CycleToMIs[getOriCycle(&MI)].push_back(getOriMI(&MI));
733 // Each MI is assigned a separate ordered Id, which is used as a sort marker
734 // in the following expand process.
736 int Id = 0;
737 for (int Cycle = 0; Cycle < (int)II; ++Cycle) {
738 auto It = CycleToMIs.find(Cycle);
739 if (It == CycleToMIs.end())
740 continue;
741 for (auto *MI : It->second)
742 IssueOrder[MI] = Id++;
743 }
744 return IssueOrder;
745}
746
748 // At the first update, Offset is equal to SchedPhiNum. At this time, only
749 // BestII, BestOffset, and BaseII need to be updated.
750 if (Offset == SchedPhiNum) {
751 BestII = II;
753 BaseII = II;
754 return;
755 }
756 // The update will only continue if the II is smaller than BestII and the II
757 // is sufficiently small.
758 if ((II >= BestII) || (II + Opts.window_diff_limit > BaseII))
759 return;
760 BestII = II;
762 // Record the result of the current list scheduling, noting that each MI is
763 // stored unordered in SchedResult.
764 SchedResult.clear();
765 auto IssueOrder = getIssueOrder(Offset, II);
766 for (auto &Pair : OriToCycle) {
767 assert(IssueOrder.count(Pair.first) && "Cannot find original MI!");
768 SchedResult.push_back(std::make_tuple(Pair.first, Pair.second,
769 getOriStage(Pair.first, Offset),
770 IssueOrder[Pair.first]));
771 }
772}
773
775 // The MIs in the SchedResult are sorted by the issue order ID.
777 [](const std::tuple<MachineInstr *, int, int, int> &A,
778 const std::tuple<MachineInstr *, int, int, int> &B) {
779 return std::get<3>(A) < std::get<3>(B);
780 });
781 // Use the scheduling infrastructure for expansion, noting that InstrChanges
782 // is not supported here.
783 DenseMap<MachineInstr *, int> Cycles, Stages;
784 std::vector<MachineInstr *> OrderedInsts;
785 for (auto &Info : SchedResult) {
786 auto *MI = std::get<0>(Info);
787 OrderedInsts.push_back(MI);
788 Cycles[MI] = std::get<1>(Info);
789 Stages[MI] = std::get<2>(Info);
790 LLVM_DEBUG(dbgs() << "\tCycle " << Cycles[MI] << " [S." << Stages[MI]
791 << "]: " << *MI);
792 }
793 ModuloSchedule MS(*MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
794 std::move(Stages));
795 ModuloScheduleExpander MSE(*MF, MS, *Context->LIS,
797 MSE.expand();
798 MSE.cleanup();
799}
800
803 for (MachineInstr &MI : *MBB)
804 for (const MachineOperand &MO : MI.operands()) {
805 if (!MO.isReg() || MO.getReg() == 0)
806 continue;
807 Register Reg = MO.getReg();
808 if (!is_contained(UsedRegs, Reg))
809 UsedRegs.push_back(Reg);
810 }
811 Context->LIS->repairIntervalsInRange(MBB, MBB->begin(), MBB->end(), UsedRegs);
812}
813
816 auto RegionBegin = MBB->begin();
817 std::advance(RegionBegin, Offset);
818 auto RegionEnd = RegionBegin;
819 std::advance(RegionEnd, Num);
820 return make_range(RegionBegin, RegionEnd);
821}
822
824 assert(TriToOri.count(NewMI) && "Cannot find original MI!");
825 auto *OriMI = TriToOri[NewMI].Ori;
826 assert(OriToCycle.count(OriMI) && "Cannot find schedule cycle!");
827 return OriToCycle[OriMI];
828}
829
831 assert(TriToOri.count(NewMI) && "Cannot find original MI!");
832 return TriToOri[NewMI].Ori;
833}
834
836 assert(llvm::is_contained(OriMIs, OriMI) && "Cannot find OriMI in OriMIs!");
837 // If there is no instruction fold, all MI stages are 0.
838 if (Offset == SchedPhiNum)
839 return 0;
840 // For those MIs with an ID less than the Offset, their stages are set to 0,
841 // while the rest are set to 1.
842 unsigned Id = 0;
843 for (auto *MI : OriMIs) {
844 if (MI->isDebugOrPseudoInstr())
845 continue;
846 if (MI == OriMI)
847 break;
848 ++Id;
849 }
850 return Id >= (size_t)Offset ? 1 : 0;
851}
852
854 assert(Phi->isPHI() && "Expecting PHI!");
855 Register AntiReg;
856 for (auto MO : Phi->uses()) {
857 if (MO.isReg())
858 AntiReg = MO.getReg();
859 else if (MO.isMBB() && MO.getMBB() == MBB)
860 return AntiReg;
861 }
862 return 0;
863}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
static bool hasLoopCarriedMemDep(const SUnitWithMemInfo &Src, const SUnitWithMemInfo &Dst, BatchAAResults &BAA, const TargetInstrInfo *TII)
Returns true if there is a loop-carried order dependency from Src to Dst.
This file provides utility analysis objects describing memory locations.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
MachineRegisterInfo & MRI
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
static bool getMemInfo(const MachineInstr *MI, const Value *&MemOpValue, int64_t &MemOpOffset, SmallVectorImpl< const Value * > &UnderlyingObjs, AAMDNodes &AATags, bool &IsAllIdentified)
Collect the underlying objects and alias metadata for the single memory operand of MI.
static bool hasLoopCarriedMemDep(const MachineInstr *SrcMI, const MachineInstr *DstMI, BatchAAResults &BAA, const MachineBasicBlock *LoopBB, const MachineRegisterInfo &MRI, const TargetInstrInfo *TII)
Return true if there is a loop-carried order dependency from memory access SrcMI to DstMI in loop Loo...
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
void enableCrossIterationMode()
Assume that values may come from different cycle iterations.
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Representation of each machine instruction.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
A description of a memory reference used in the backend.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
const Value * getValue() const
Return the base address of the memory access.
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
The ModuloScheduleExpander takes a ModuloSchedule and expands it in-place, rewriting the old loop and...
LLVM_ABI void cleanup()
Performs final cleanup after expansion.
LLVM_ABI void expand()
Performs the actual expansion.
DenseMap< MachineInstr *, std::pair< Register, int64_t > > InstrChangesTy
Represents a schedule for a single-block loop.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
@ Barrier
An unknown scheduling barrier.
Definition ScheduleDAG.h:74
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
A ScheduleDAG for scheduling lists of MachineInstr.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
Mutate the DAG as a postpass after normal DAG building.
std::vector< SUnit > SUnits
The scheduling units.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
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.
TargetInstrInfo - Interface to description of machine instruction set.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
LLVM Value Representation.
Definition Value.h:75
MachineInstr * getOriMI(MachineInstr *NewMI)
Get the original MI from which the new MI is cloned.
virtual ScheduleDAGInstrs * createMachineScheduler(bool OnlyBuildGraph=false)
Two types of ScheduleDAGs are needed, one for creating dependency graphs only, and the other for list...
unsigned SchedPhiNum
SchedPhiNum records the number of phi in the original MBB, and the scheduling starts with MI after ph...
virtual void preProcess()
Add some related processing before running window scheduling.
void collectLoopCarriedMemDeps()
Detect loop-carried memory dependences in the original MBB that must be preserved across loop iterati...
MachineSchedContext * Context
virtual void restoreTripleMBB()
Restore the order of MIs in TripleMBB after each list scheduling.
WindowScheduler(MachineSchedContext *C, MachineLoop &ML, MachineDominatorTree *MDT=nullptr)
virtual void postProcess()
Add some related processing after running window scheduling.
DenseMap< MachineInstr *, int > OriToCycle
OriToCycle keeps the mappings between the original MI and its issue cycle.
virtual int calculateMaxCycle(ScheduleDAGInstrs &DAG, unsigned Offset)
Calculate MIs execution cycle after list scheduling.
MachineRegisterInfo * MRI
MachineDominatorTree * MDT
MachineBasicBlock * MBB
unsigned BestII
BestII and BestOffset record the characteristics of the best scheduling result and are used together ...
void backupMBB()
Back up the MIs in the original MBB and remove them from MBB.
int getEstimatedII(ScheduleDAGInstrs &DAG)
Estimate a II value at which all MIs will be scheduled successfully.
virtual void expand()
Using the scheduling infrastructure to expand the results of window scheduling.
DenseMap< MachineInstr *, int > getIssueOrder(unsigned Offset, unsigned II)
Get the final issue order of all scheduled MIs including phis.
Register getAntiRegister(MachineInstr *Phi)
Gets the register in phi which is generated from the current MBB.
unsigned getOriStage(MachineInstr *OriMI, unsigned Offset)
Get the scheduling stage, where the stage of the new MI is identical to the original MI.
const TargetRegisterInfo * TRI
virtual void updateLiveIntervals()
Update the live intervals for all registers used within MBB.
const TargetSubtargetInfo * Subtarget
bool MemDepEdgeFailed
MemDepEdgeFailed is set when enforcing a loop-carried memory dependence as an artificial DAG edge wou...
std::unique_ptr< ScheduleDAGInstrs > TripleDAG
To innovatively identify the dependencies between MIs across two trips, we construct a DAG for a new ...
unsigned BaseII
BaseII is the II obtained when the window offset is SchedPhiNum.
DenseSet< std::pair< MachineInstr *, MachineInstr * > > LoopCarriedMemDeps
LoopCarriedMemDeps keeps ordered pairs (Pred, Succ) of original memory MIs such that the iteration-N ...
virtual void schedulePhi(int Offset, unsigned &II)
Phis are scheduled separately after each list scheduling.
MachineFunction * MF
DenseMap< MachineInstr *, TriCloneInfo > TriToOri
TriToOri keeps the mappings between the MI clones in TripleMBB and the information about their origin...
virtual unsigned analyseII(ScheduleDAGInstrs &DAG, unsigned Offset)
Analyzes the II value after each list scheduling.
int getOriCycle(MachineInstr *NewMI)
Get the issue cycle of the new MI based on the cycle of the original MI.
unsigned SchedInstrNum
SchedInstrNum records the MIs involved in scheduling in the original MBB, excluding debug instruction...
const TargetInstrInfo * TII
virtual void generateTripleMBB()
Make three copies of the original MBB to generate a new TripleMBB.
iterator_range< MachineBasicBlock::iterator > getScheduleRange(unsigned Offset, unsigned Num)
Gets the iterator range of MIs in the scheduling window.
virtual bool isScheduleValid()
Check whether the final result of window scheduling is valid.
virtual int calculateStallCycle(unsigned Offset, int MaxCycle)
Calculate the stall cycle between two trips after list scheduling.
virtual void updateScheduleResult(unsigned Offset, unsigned II)
Update the scheduling result after each list scheduling.
SmallVector< MachineInstr * > OriMIs
OriMIs keeps the MIs removed from the original MBB.
virtual bool initialize()
Initializes the algorithm and determines if it can be executed.
SmallVector< std::tuple< MachineInstr *, int, int, int >, 256 > SchedResult
SchedResult keeps the result of each list scheduling, and the format of the tuple is <MI pointer,...
virtual SmallVector< unsigned > getSearchIndexes(unsigned SearchNum, unsigned SearchRatio)
Give the folding position in the window algorithm, where different heuristics can be used.
void restoreMBB()
Erase the MIs in current MBB and restore the original MIs.
SmallVector< MachineInstr * > TriMIs
TriMIs keeps the MIs of TripleMBB, which is used to restore TripleMBB.
const CodeGenOptions & Opts
A range adaptor for a pair of iterators.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
This is an optimization pass for GlobalISel generic memory operations.
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI bool mayOverlapInLaterIter(const MachineInstr *BaseMI, const MachineInstr *OtherMI, const MachineBasicBlock *LoopBB, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
Return true if BaseMI and OtherMI may access overlapping memory in a later iteration of the loop Loop...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...