LLVM 24.0.0git
SPIRVMergeRegionExitTargets.cpp
Go to the documentation of this file.
1//===-- SPIRVMergeRegionExitTargets.cpp ----------------------*- C++ -*-===//
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// Merge the multiple exit targets of a convergence region into a single block.
10// Each exit target will be assigned a constant value, and a phi node + switch
11// will allow the new exit target to re-route to the correct basic block.
12//
13//===----------------------------------------------------------------------===//
14
16#include "SPIRV.h"
17#include "SPIRVSubtarget.h"
18#include "SPIRVUtils.h"
19#include "llvm/ADT/DenseMap.h"
22#include "llvm/IR/Dominators.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/Intrinsics.h"
29
30using namespace llvm;
31
32namespace {
33
34// Run the pass on the given convergence region, ignoring the sub-regions.
35// Returns true if the CFG changed, false otherwise.
36static bool runOnConvergenceRegionNoRecurse(LoopInfo &LI,
38 // Gather all the exit targets for this region.
40 for (BasicBlock *Exit : CR->Exits) {
41 for (BasicBlock *Target : successors(Exit)) {
42 if (CR->Blocks.count(Target) == 0)
43 ExitTargets.insert(Target);
44 }
45 }
46
47 // If we have zero or one exit target, nothing do to.
48 if (ExitTargets.size() <= 1)
49 return false;
50
51 // Create the new single exit target.
52 auto F = CR->Entry->getParent();
53 auto NewExitTarget = BasicBlock::Create(F->getContext(), "new.exit", F);
54 IRBuilder<> Builder(NewExitTarget);
55
56 AllocaInst *Variable = createVariable(*F, Builder.getInt32Ty());
57
58 // CodeGen output needs to be stable. Using the set as-is would order
59 // the targets differently depending on the allocation pattern.
60 // Sorting per basic-block ordering in the function.
61 std::vector<BasicBlock *> SortedExitTargets;
62 std::vector<BasicBlock *> SortedExits;
63 for (BasicBlock &BB : *F) {
64 if (ExitTargets.count(&BB) != 0)
65 SortedExitTargets.push_back(&BB);
66 if (CR->Exits.count(&BB) != 0)
67 SortedExits.push_back(&BB);
68 }
69
70 // Creating one constant per distinct exit target. This will be route to the
71 // correct target.
73 for (BasicBlock *Target : SortedExitTargets)
74 TargetToValue.insert(
75 std::make_pair(Target, Builder.getInt32(TargetToValue.size())));
76
77 // Creating one variable per exit node, set to the constant matching the
78 // targeted external block.
79 std::vector<std::pair<BasicBlock *, Value *>> ExitToVariable;
80 for (auto Exit : SortedExits) {
81 llvm::Value *Value = createExitVariable(Exit, TargetToValue);
82 IRBuilder<> B2(Exit);
83 B2.SetInsertPoint(Exit->getFirstInsertionPt());
84 B2.CreateStore(Value, Variable);
85 ExitToVariable.emplace_back(std::make_pair(Exit, Value));
86 }
87
88 llvm::Value *Load = Builder.CreateLoad(Builder.getInt32Ty(), Variable);
89
90 // Creating the switch to jump to the correct exit target.
91 llvm::SwitchInst *Sw = Builder.CreateSwitch(Load, SortedExitTargets[0],
92 SortedExitTargets.size() - 1);
93 for (size_t i = 1; i < SortedExitTargets.size(); i++) {
94 BasicBlock *BB = SortedExitTargets[i];
95 Sw->addCase(TargetToValue[BB], BB);
96 }
97
98 // Fix exit branches to redirect to the new exit.
99 for (auto Exit : CR->Exits) {
100 Instruction *T = Exit->getTerminator();
101 for (auto I = succ_begin(T), E = succ_end(T); I != E; ++I)
102 if (ExitTargets.contains(*I))
103 I.getUse()->set(NewExitTarget);
104 }
105
106 CR = CR->Parent;
107 while (CR) {
108 CR->Blocks.insert(NewExitTarget);
109 CR = CR->Parent;
110 }
111
112 return true;
113}
114
115/// Run the pass on the given convergence region and sub-regions (DFS).
116/// Returns true if a region/sub-region was modified, false otherwise.
117/// This returns as soon as one region/sub-region has been modified.
118static bool runOnConvergenceRegion(LoopInfo &LI, SPIRV::ConvergenceRegion *CR) {
119 for (auto *Child : CR->Children)
120 if (runOnConvergenceRegion(LI, Child))
121 return true;
122
123 return runOnConvergenceRegionNoRecurse(LI, CR);
124}
125
126#if !NDEBUG
127/// Validates each edge exiting the region has the same destination basic
128/// block.
129static void validateRegionExits(const SPIRV::ConvergenceRegion *CR) {
130 for (auto *Child : CR->Children)
131 validateRegionExits(Child);
132
134 for (auto *Exit : CR->Exits) {
135 for (auto *BB : successors(Exit)) {
136 if (CR->Blocks.count(BB) == 0)
137 ExitTargets.insert(BB);
138 }
139 }
140
141 assert(ExitTargets.size() <= 1);
142}
143#endif
144
145static bool runImpl(Function &F, LoopInfo &LI,
147 auto *TopLevelRegion = RegionInfo.getWritableTopLevelRegion();
148
149 // FIXME: very inefficient method: each time a region is modified, we bubble
150 // back up, and recompute the whole convergence region tree. Once the
151 // algorithm is completed and test coverage good enough, rewrite this pass
152 // to be efficient instead of simple.
153 bool Modified = false;
154 while (runOnConvergenceRegion(LI, TopLevelRegion)) {
155 Modified = true;
156 }
157
158#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
159 validateRegionExits(TopLevelRegion);
160#endif
161 return Modified;
162}
163
164class SPIRVMergeRegionExitTargetsLegacy : public FunctionPass {
165public:
166 static char ID;
167
168 SPIRVMergeRegionExitTargetsLegacy() : FunctionPass(ID) {}
169
170 bool runOnFunction(Function &F) override {
171 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
172 auto &RegionInfo = getAnalysis<SPIRVConvergenceRegionAnalysisWrapperPass>()
173 .getRegionInfo();
174 return runImpl(F, LI, RegionInfo);
175 }
176
177 void getAnalysisUsage(AnalysisUsage &AU) const override {
178 AU.addRequired<LoopInfoWrapperPass>();
179 AU.addRequired<SPIRVConvergenceRegionAnalysisWrapperPass>();
180
181 AU.addPreserved<SPIRVConvergenceRegionAnalysisWrapperPass>();
182 FunctionPass::getAnalysisUsage(AU);
183 }
184};
185} // namespace
186
194
195char SPIRVMergeRegionExitTargetsLegacy::ID = 0;
196
197INITIALIZE_PASS_BEGIN(SPIRVMergeRegionExitTargetsLegacy,
198 "split-region-exit-blocks",
199 "SPIRV split region exit blocks", false, false)
200INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
203
204INITIALIZE_PASS_END(SPIRVMergeRegionExitTargetsLegacy,
205 "split-region-exit-blocks",
206 "SPIRV split region exit blocks", false, false)
207
209 return new SPIRVMergeRegionExitTargetsLegacy();
210}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool runImpl(MachineFunction &MF)
Definition CFIFixup.cpp:304
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallPtrSet class.
an instruction to allocate memory on the stack
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
unsigned size() const
Definition DenseMap.h:172
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
SmallVector< ConvergenceRegion * > Children
size_type size() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Multiway switch.
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
Target - Wrapper for Target specific information.
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
AllocaInst * createVariable(Function &F, Type *Type)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
Value * createExitVariable(BasicBlock *BB, const DenseMap< BasicBlock *, ConstantInt * > &TargetToValue)
FunctionPass * createSPIRVMergeRegionExitTargetsPass()
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.