This repository was archived by the owner on Sep 15, 2025. It is now read-only.
forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathAMDGPUConditionalDiscard.cpp
More file actions
258 lines (213 loc) · 8.21 KB
/
Copy pathAMDGPUConditionalDiscard.cpp
File metadata and controls
258 lines (213 loc) · 8.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//===-- AMDGPUConditionalDiscard.cpp
//-----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// Modifications Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved.
// Notified per clause 4(b) of the license.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass transforms conditional discard of the form:
///
/// if (condition)
/// discard (false);
///
/// into:
///
/// discard (!condition);
///
///
/// More specifically,
///
/// ...
/// block:
/// %cond = icmp eq i32 %a, %b
/// br i1 %cond, label %kill_block, label %cont_block
///
/// kill_block:
/// call void @llvm.amdgcn.kill(i1 false)
/// br label %other
/// ...
///
/// gets transformed into:
///
/// ...
/// block:
/// %cond = icmp eq i32 %a, %b
/// %nonkill = not i1 %cond
/// call void @llvm.amdgcn.kill(i1 %nonkill)
/// br i1 %cond, %other, %cont_block
/// ...
///
/// The transformation is useful, because removing basic blocks simplifies CFG
/// and limits the number of phi nodes used.
/// The pass should ideally be placed after code sinking, because some sinking
/// opportunities get lost after the transformation due to the basic block
/// removal.
///
/// Additionally this pass can be used to transform kill intrinsics optimized
/// as above to demote operations.
/// This provides a workaround for applications which perform a non-uniform
/// "kill" and later compute (implicit) derivatives.
/// Note that in Vulkan, such applications should be fixed to use demote
/// (OpDemoteToHelperInvocationEXT) instead of kill (OpKill).
///
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
#include "llvm/InitializePasses.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#define DEBUG_TYPE "amdgpu-conditional-discard"
using namespace llvm;
using namespace llvm::AMDGPU;
// Enable conditional discard transformations
static cl::opt<bool> EnableConditionalDiscardTransformations(
"amdgpu-conditional-discard-transformations",
cl::desc("Enable conditional discard transformations"),
cl::init(false),
cl::Hidden);
// Enable conditional discard to demote transformations
static cl::opt<bool> EnableTransformDiscardToDemote(
"amdgpu-transform-discard-to-demote",
cl::desc("Enable transformation of optimized discards to demotes"),
cl::init(false),
cl::Hidden);
namespace {
class AMDGPUConditionalDiscard : public FunctionPass {
private:
SmallVector<BasicBlock *, 4> KillBlocksToRemove;
const LoopInfo *LI;
public:
static char ID;
AMDGPUConditionalDiscard() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredTransitive<LoopInfoWrapperPass>();
}
StringRef getPassName() const override { return "AMDGPUConditionalDiscard"; }
void optimizeBlock(BasicBlock &BB, bool ConvertToDemote);
};
} // namespace
char AMDGPUConditionalDiscard::ID = 0;
char &llvm::AMDGPUConditionalDiscardID = AMDGPUConditionalDiscard::ID;
// Look for a basic block that has only a single predecessor and its
// first instruction is a call to amdgcn_kill, with "false" as argument.
// Transform the branch condition of the block's predecessor and mark
// the block for removal. Clone the call to amdgcn_kill to the predecessor.
void AMDGPUConditionalDiscard::optimizeBlock(BasicBlock &BB, bool ConvertToDemote) {
if (auto *KillCand = dyn_cast<CallInst>(&BB.front())) {
auto *Callee = KillCand->getCalledFunction();
if (!Callee || Callee->getIntrinsicID() != Intrinsic::amdgcn_kill) {
return;
}
ConstantInt *Val = dyn_cast<ConstantInt>(KillCand->getOperand(0));
if (!Val || !Val->isZero())
return;
// Skip if the terminator is not a branch, e.g. an "unreachable".
if (!isa<BranchInst>(BB.getTerminator()))
return;
auto *PredBlock = BB.getSinglePredecessor();
if (!PredBlock)
return;
// Skip if the kill is in a loop.
if (LI->getLoopFor(PredBlock)) {
LLVM_DEBUG(dbgs() << "Cannot optimize " << BB.getName() << " due to loop\n");
return;
}
auto *PredTerminator = PredBlock->getTerminator();
auto *PredBranchInst = dyn_cast<BranchInst>(PredTerminator);
if (!PredBranchInst || !PredBranchInst->isConditional())
return;
BasicBlock *LiveBlock = nullptr;
auto *Cond = PredBranchInst->getCondition();
if (PredBranchInst->getSuccessor(0) == &BB) {
// The old kill block could only be reached if
// the condition was true - negate the condition.
Cond = BinaryOperator::CreateNot(Cond, "", PredTerminator);
LiveBlock = PredBranchInst->getSuccessor(1);
} else {
LiveBlock = PredBranchInst->getSuccessor(0);
}
auto *NewKill = cast<CallInst>(KillCand->clone());
NewKill->setArgOperand(0, Cond);
NewKill->insertBefore(PredTerminator);
if (ConvertToDemote) {
NewKill->setCalledFunction(Intrinsic::getDeclaration(
KillCand->getModule(), Intrinsic::amdgcn_wqm_demote));
KillBlocksToRemove.push_back(&BB);
// Change the branch to an unconditional one, targeting the live block.
auto *NewBranchInst = BranchInst::Create(LiveBlock, PredBranchInst);
NewBranchInst->copyMetadata(*PredBranchInst);
PredBranchInst->eraseFromParent();
} else {
KillCand->eraseFromParent();
// Try removing the old kill block.
if (BB.sizeWithoutDebug() == 1) {
auto *OldKillBlockBranchInst = dyn_cast<BranchInst>(BB.getTerminator());
if (!OldKillBlockBranchInst->isConditional()) {
auto *OldKillBlockSucc = OldKillBlockBranchInst->getSuccessor(0);
// Change the branch to point to the old kill block successor instead
// of old kill block. This is necessary to remove the old kill block.
if (PredBranchInst->getSuccessor(0) == &BB)
PredBranchInst->setSuccessor(0, OldKillBlockSucc);
else
PredBranchInst->setSuccessor(1, OldKillBlockSucc);
// For OldKillBlockSucc's PHINode, the incoming block should be
// updated from BB to PredBlock, and the incoming value may also need
// to be updated if PredBlock is OldKillBlockSucc's predecessor. This
// could avoid leaving the PHINode with different incoming values for
// the PredBlock.
for (PHINode &PN : OldKillBlockSucc->phis()) {
if (PN.getBasicBlockIndex(PredBlock) >= 0) {
auto *PredIncoming = PN.getIncomingValueForBlock(PredBlock);
PN.setIncomingValue(PN.getBasicBlockIndex(&BB), PredIncoming);
}
PN.replaceIncomingBlockWith(&BB, PredBlock);
}
KillBlocksToRemove.push_back(&BB);
}
}
}
}
}
bool AMDGPUConditionalDiscard::runOnFunction(Function &F) {
if (F.getCallingConv() != CallingConv::AMDGPU_PS)
return false;
if (skipFunction(F))
return false;
if (!(EnableConditionalDiscardTransformations ||
F.hasFnAttribute("amdgpu-conditional-discard-transformations")))
return false;
bool ConvertToDemote =
(EnableTransformDiscardToDemote ||
F.hasFnAttribute("amdgpu-transform-discard-to-demote"));
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
for (auto &BB : F)
optimizeBlock(BB, ConvertToDemote);
for (auto *BB : KillBlocksToRemove) {
for (auto *Succ : successors(BB)) {
for (PHINode &PN : Succ->phis()) {
if (PN.getBasicBlockIndex(BB) >= 0)
PN.removeIncomingValue(BB);
}
}
BB->eraseFromParent();
}
bool Ret = !KillBlocksToRemove.empty();
KillBlocksToRemove.clear();
return Ret;
}
INITIALIZE_PASS_BEGIN(AMDGPUConditionalDiscard, DEBUG_TYPE,
"AMDGPUConditionalDiscard", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(AMDGPUConditionalDiscard, DEBUG_TYPE,
"AMDGPUConditionalDiscard", false, false)
FunctionPass *llvm::createAMDGPUConditionalDiscardPass() {
return new AMDGPUConditionalDiscard();
}