LLVM 24.0.0git
WindowScheduler.h
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 concept of the window algorithm was first unveiled in Steven Muchnick's
12// book, "Advanced Compiler Design And Implementation", and later elaborated
13// upon in Venkatraman Govindaraju's report, "Implementation of Software
14// Pipelining Using Window Scheduling".
15//
16// The window algorithm can be perceived as a modulo scheduling algorithm with a
17// stage count of 2. It boasts a higher scheduling success rate in targets with
18// severe resource conflicts when compared to the classic Swing Modulo
19// Scheduling (SMS) algorithm. To align with the LLVM scheduling framework, we
20// have enhanced the original window algorithm. The primary steps are as
21// follows:
22//
23// 1. Instead of duplicating the original MBB twice as mentioned in the
24// literature, we copy it three times, generating TripleMBB and the
25// corresponding TripleDAG.
26//
27// 2. We establish a scheduling window on TripleMBB and execute list scheduling
28// within it.
29//
30// 3. After multiple list scheduling, we select the best outcome and expand it
31// into the final scheduling result.
32//
33// To cater to the needs of various targets, we have developed the window
34// scheduler in a form that is easily derivable. We recommend employing this
35// algorithm in targets with severe resource conflicts, and it can be utilized
36// either before or after the Register Allocator (RA).
37//
38// The default implementation provided here is before RA. If it is to be used
39// after RA, certain critical algorithm functions will need to be derived.
40//
41//===----------------------------------------------------------------------===//
42#ifndef LLVM_CODEGEN_WINDOWSCHEDULER_H
43#define LLVM_CODEGEN_WINDOWSCHEDULER_H
44
45#include "llvm/ADT/DenseSet.h"
51
52namespace llvm {
53
54struct CodeGenOptions;
56
57// On comes first as the zero value is the -window-sched default.
59 On, /// Use window algorithm after SMS algorithm fails.
60 Off, /// Turn off window algorithm.
61 Force /// Use window algorithm instead of SMS algorithm.
62};
63
64/// TriCloneInfo describes an MI clone in TripleMBB: the original MI it was
65/// cloned from and the index of the copy (0, 1, or 2) it belongs to.
67 MachineInstr *Ori = nullptr;
68 unsigned Copy = 0;
69};
70
71/// The main class in the implementation of the target independent window
72/// scheduler.
74protected:
75 const CodeGenOptions &Opts;
77 MachineFunction *MF = nullptr;
81 const TargetInstrInfo *TII = nullptr;
82 const TargetRegisterInfo *TRI = nullptr;
85
86 /// To innovatively identify the dependencies between MIs across two trips, we
87 /// construct a DAG for a new MBB, which is created by copying the original
88 /// MBB three times. We refer to this new MBB as 'TripleMBB' and the
89 /// corresponding DAG as 'TripleDAG'.
90 /// If the dependencies are more than two trips, we avoid applying window
91 /// algorithm by identifying successive phis in the old MBB.
92 std::unique_ptr<ScheduleDAGInstrs> TripleDAG;
93 /// OriMIs keeps the MIs removed from the original MBB.
95 /// TriMIs keeps the MIs of TripleMBB, which is used to restore TripleMBB.
97 /// TriToOri keeps the mappings between the MI clones in TripleMBB and the
98 /// information about their original MI and copy index.
100 /// OriToCycle keeps the mappings between the original MI and its issue cycle.
102 /// LoopCarriedMemDeps keeps ordered pairs (Pred, Succ) of original memory MIs
103 /// such that the iteration-N access Pred must be ordered before the
104 /// iteration-(N+1) access Succ.
106 /// MemDepEdgeFailed is set when enforcing a loop-carried memory dependence as
107 /// an artificial DAG edge would have created a cycle, so the edge could not
108 /// be added. In that case the current window must be abandoned, as its
109 /// schedule would not honor the dependence.
110 bool MemDepEdgeFailed = false;
111 /// SchedResult keeps the result of each list scheduling, and the format of
112 /// the tuple is <MI pointer, Cycle, Stage, Order ID>.
114 /// SchedPhiNum records the number of phi in the original MBB, and the
115 /// scheduling starts with MI after phis.
116 unsigned SchedPhiNum = 0;
117 /// SchedInstrNum records the MIs involved in scheduling in the original MBB,
118 /// excluding debug instructions.
119 unsigned SchedInstrNum = 0;
120 /// BestII and BestOffset record the characteristics of the best scheduling
121 /// result and are used together with SchedResult as the final window
122 /// scheduling result.
123 unsigned BestII = UINT_MAX;
124 unsigned BestOffset = 0;
125 /// BaseII is the II obtained when the window offset is SchedPhiNum. This
126 /// offset is the initial position of the sliding window.
127 unsigned BaseII = 0;
128
129public:
131 MachineDominatorTree *MDT = nullptr);
132 virtual ~WindowScheduler() = default;
133
134 bool run();
135
136protected:
137 /// Two types of ScheduleDAGs are needed, one for creating dependency graphs
138 /// only, and the other for list scheduling as determined by the target.
139 virtual ScheduleDAGInstrs *
140 createMachineScheduler(bool OnlyBuildGraph = false);
141 /// Initializes the algorithm and determines if it can be executed.
142 virtual bool initialize();
143 /// Add some related processing before running window scheduling.
144 virtual void preProcess();
145 /// Detect loop-carried memory dependences in the original MBB that must be
146 /// preserved across loop iterations. This must run on the live MBB before
147 /// backupMBB(), as it analyzes the induction recurrence of memory accesses.
148 /// The hazardous pairs of original MIs are recorded in LoopCarriedMemDeps.
150 /// Add some related processing after running window scheduling.
151 virtual void postProcess();
152 /// Back up the MIs in the original MBB and remove them from MBB.
153 void backupMBB();
154 /// Erase the MIs in current MBB and restore the original MIs.
155 void restoreMBB();
156 /// Make three copies of the original MBB to generate a new TripleMBB.
157 virtual void generateTripleMBB();
158 /// Restore the order of MIs in TripleMBB after each list scheduling.
159 virtual void restoreTripleMBB();
160 /// Give the folding position in the window algorithm, where different
161 /// heuristics can be used. It determines the performance and compilation time
162 /// of the algorithm.
163 virtual SmallVector<unsigned> getSearchIndexes(unsigned SearchNum,
164 unsigned SearchRatio);
165 /// Calculate MIs execution cycle after list scheduling.
166 virtual int calculateMaxCycle(ScheduleDAGInstrs &DAG, unsigned Offset);
167 /// Calculate the stall cycle between two trips after list scheduling.
168 virtual int calculateStallCycle(unsigned Offset, int MaxCycle);
169 /// Analyzes the II value after each list scheduling.
170 virtual unsigned analyseII(ScheduleDAGInstrs &DAG, unsigned Offset);
171 /// Phis are scheduled separately after each list scheduling.
172 virtual void schedulePhi(int Offset, unsigned &II);
173 /// Get the final issue order of all scheduled MIs including phis.
175 /// Update the scheduling result after each list scheduling.
176 virtual void updateScheduleResult(unsigned Offset, unsigned II);
177 /// Check whether the final result of window scheduling is valid.
178 virtual bool isScheduleValid() { return BestOffset != SchedPhiNum; }
179 /// Using the scheduling infrastructure to expand the results of window
180 /// scheduling. It is usually necessary to add prologue and epilogue MBBs.
181 virtual void expand();
182 /// Update the live intervals for all registers used within MBB.
183 virtual void updateLiveIntervals();
184 /// Estimate a II value at which all MIs will be scheduled successfully.
185 int getEstimatedII(ScheduleDAGInstrs &DAG);
186 /// Gets the iterator range of MIs in the scheduling window.
187 iterator_range<MachineBasicBlock::iterator> getScheduleRange(unsigned Offset,
188 unsigned Num);
189 /// Get the issue cycle of the new MI based on the cycle of the original MI.
190 int getOriCycle(MachineInstr *NewMI);
191 /// Get the original MI from which the new MI is cloned.
192 MachineInstr *getOriMI(MachineInstr *NewMI);
193 /// Get the scheduling stage, where the stage of the new MI is identical to
194 /// the original MI.
195 unsigned getOriStage(MachineInstr *OriMI, unsigned Offset);
196 /// Gets the register in phi which is generated from the current MBB.
197 Register getAntiRegister(MachineInstr *Phi);
198};
199} // namespace llvm
200#endif
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseSet and SmallDenseSet classes.
static Expected< BitVector > expand(StringRef S, StringRef Original)
uint64_t IntrinsicInst * II
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
A ScheduleDAG for scheduling lists of MachineInstr.
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.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual ScheduleDAGInstrs * createMachineScheduler(bool OnlyBuildGraph=false)
Two types of ScheduleDAGs are needed, one for creating dependency graphs only, and the other for list...
virtual ~WindowScheduler()=default
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.
DenseMap< MachineInstr *, int > getIssueOrder(unsigned Offset, unsigned II)
Get the final issue order of all scheduled MIs including phis.
const TargetRegisterInfo * TRI
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.
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.
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.
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.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
WindowSchedulingFlag
@ Force
Turn off window algorithm.
@ Off
Use window algorithm after SMS algorithm fails.
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
TriCloneInfo describes an MI clone in TripleMBB: the original MI it was cloned from and the index of ...
MachineInstr * Ori