Movatterモバイル変換


[0]ホーム

URL:


LLVM 20.0.0git
NVVMReflect.cpp
Go to the documentation of this file.
1//===- NVVMReflect.cpp - NVVM Emulate conditional compilation -------------===//
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// This pass replaces occurrences of __nvvm_reflect("foo") and llvm.nvvm.reflect
10// with an integer.
11//
12// We choose the value we use by looking at metadata in the module itself. Note
13// that we intentionally only have one way to choose these values, because other
14// parts of LLVM (particularly, InstCombineCall) rely on being able to predict
15// the values chosen by this pass.
16//
17// If we see an unknown string, we replace its call with 0.
18//
19//===----------------------------------------------------------------------===//
20
21#include "NVPTX.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/Analysis/ConstantFolding.h"
24#include "llvm/CodeGen/CommandFlags.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InstIterator.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/IntrinsicsNVPTX.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/PassManager.h"
34#include "llvm/IR/Type.h"
35#include "llvm/Pass.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Transforms/Scalar.h"
40#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Transforms/Utils/Local.h"
42#include <algorithm>
43#define NVVM_REFLECT_FUNCTION "__nvvm_reflect"
44#define NVVM_REFLECT_OCL_FUNCTION "__nvvm_reflect_ocl"
45
46using namespacellvm;
47
48#define DEBUG_TYPE "nvptx-reflect"
49
50namespacellvm {
51voidinitializeNVVMReflectPass(PassRegistry &);
52}
53
54namespace{
55classNVVMReflect :publicFunctionPass {
56public:
57staticcharID;
58unsignedintSmVersion;
59 NVVMReflect() : NVVMReflect(0) {}
60explicit NVVMReflect(unsignedint Sm) :FunctionPass(ID),SmVersion(Sm) {
61initializeNVVMReflectPass(*PassRegistry::getPassRegistry());
62 }
63
64boolrunOnFunction(Function &)override;
65};
66}// namespace
67
68FunctionPass *llvm::createNVVMReflectPass(unsignedintSmVersion) {
69returnnew NVVMReflect(SmVersion);
70}
71
72staticcl::opt<bool>
73NVVMReflectEnabled("nvvm-reflect-enable",cl::init(true),cl::Hidden,
74cl::desc("NVVM reflection, enabled by default"));
75
76char NVVMReflect::ID = 0;
77INITIALIZE_PASS(NVVMReflect,"nvvm-reflect",
78"Replace occurrences of __nvvm_reflect() calls with 0/1",false,
79false)
80
81staticbool runNVVMReflect(Function &F,unsignedSmVersion) {
82if (!NVVMReflectEnabled)
83returnfalse;
84
85if (F.getName() ==NVVM_REFLECT_FUNCTION ||
86F.getName() ==NVVM_REFLECT_OCL_FUNCTION) {
87assert(F.isDeclaration() &&"_reflect function should not have a body");
88assert(F.getReturnType()->isIntegerTy() &&
89"_reflect's return type should be integer");
90returnfalse;
91 }
92
93SmallVector<Instruction *, 4>ToRemove;
94SmallVector<Instruction *, 4>ToSimplify;
95
96// Go through the calls in this function. Each call to __nvvm_reflect or
97// llvm.nvvm.reflect should be a CallInst with a ConstantArray argument.
98// First validate that. If the c-string corresponding to the ConstantArray can
99// be found successfully, see if it can be found in VarMap. If so, replace the
100// uses of CallInst with the value found in VarMap. If not, replace the use
101// with value 0.
102
103// The IR for __nvvm_reflect calls differs between CUDA versions.
104//
105// CUDA 6.5 and earlier uses this sequence:
106// %ptr = tail call i8* @llvm.nvvm.ptr.constant.to.gen.p0i8.p4i8
107// (i8 addrspace(4)* getelementptr inbounds
108// ([8 x i8], [8 x i8] addrspace(4)* @str, i32 0, i32 0))
109// %reflect = tail call i32 @__nvvm_reflect(i8* %ptr)
110//
111// The value returned by Sym->getOperand(0) is a Constant with a
112// ConstantDataSequential operand which can be converted to string and used
113// for lookup.
114//
115// CUDA 7.0 does it slightly differently:
116// %reflect = call i32 @__nvvm_reflect(i8* addrspacecast
117// (i8 addrspace(1)* getelementptr inbounds
118// ([8 x i8], [8 x i8] addrspace(1)* @str, i32 0, i32 0) to i8*))
119//
120// In this case, we get a Constant with a GlobalVariable operand and we need
121// to dig deeper to find its initializer with the string we'll use for lookup.
122for (Instruction &I :instructions(F)) {
123CallInst *Call = dyn_cast<CallInst>(&I);
124if (!Call)
125continue;
126Function *Callee = Call->getCalledFunction();
127if (!Callee || (Callee->getName() !=NVVM_REFLECT_FUNCTION &&
128 Callee->getName() !=NVVM_REFLECT_OCL_FUNCTION &&
129 Callee->getIntrinsicID() != Intrinsic::nvvm_reflect))
130continue;
131
132// FIXME: Improve error handling here and elsewhere in this pass.
133assert(Call->getNumOperands() == 2 &&
134"Wrong number of operands to __nvvm_reflect function");
135
136// In cuda 6.5 and earlier, we will have an extra constant-to-generic
137// conversion of the string.
138constValue *Str = Call->getArgOperand(0);
139if (constCallInst *ConvCall = dyn_cast<CallInst>(Str)) {
140// FIXME: Add assertions about ConvCall.
141 Str = ConvCall->getArgOperand(0);
142 }
143// Pre opaque pointers we have a constant expression wrapping the constant
144// string.
145 Str = Str->stripPointerCasts();
146assert(isa<Constant>(Str) &&
147"Format of __nvvm_reflect function not recognized");
148
149constValue *Operand = cast<Constant>(Str)->getOperand(0);
150if (constGlobalVariable *GV = dyn_cast<GlobalVariable>(Operand)) {
151// For CUDA-7.0 style __nvvm_reflect calls, we need to find the operand's
152// initializer.
153assert(GV->hasInitializer() &&
154"Format of _reflect function not recognized");
155constConstant *Initializer = GV->getInitializer();
156 Operand = Initializer;
157 }
158
159assert(isa<ConstantDataSequential>(Operand) &&
160"Format of _reflect function not recognized");
161assert(cast<ConstantDataSequential>(Operand)->isCString() &&
162"Format of _reflect function not recognized");
163
164StringRef ReflectArg = cast<ConstantDataSequential>(Operand)->getAsString();
165 ReflectArg = ReflectArg.substr(0, ReflectArg.size() - 1);
166LLVM_DEBUG(dbgs() <<"Arg of _reflect : " << ReflectArg <<"\n");
167
168int ReflectVal = 0;// The default value is 0
169if (ReflectArg =="__CUDA_FTZ") {
170// Try to pull __CUDA_FTZ from the nvvm-reflect-ftz module flag. Our
171// choice here must be kept in sync with AutoUpgrade, which uses the same
172// technique to detect whether ftz is enabled.
173if (auto *Flag = mdconst::extract_or_null<ConstantInt>(
174F.getParent()->getModuleFlag("nvvm-reflect-ftz")))
175 ReflectVal = Flag->getSExtValue();
176 }elseif (ReflectArg =="__CUDA_ARCH") {
177 ReflectVal =SmVersion * 10;
178 }
179
180// If the immediate user is a simple comparison we want to simplify it.
181for (User *U : Call->users())
182if (Instruction *I = dyn_cast<Instruction>(U))
183ToSimplify.push_back(I);
184
185 Call->replaceAllUsesWith(ConstantInt::get(Call->getType(), ReflectVal));
186ToRemove.push_back(Call);
187 }
188
189// The code guarded by __nvvm_reflect may be invalid for the target machine.
190// Traverse the use-def chain, continually simplifying constant expressions
191// until we find a terminator that we can then remove.
192while (!ToSimplify.empty()) {
193Instruction *I =ToSimplify.pop_back_val();
194if (Constant *C =ConstantFoldInstruction(I,F.getDataLayout())) {
195for (User *U :I->users())
196if (Instruction *I = dyn_cast<Instruction>(U))
197ToSimplify.push_back(I);
198
199I->replaceAllUsesWith(C);
200if (isInstructionTriviallyDead(I)) {
201ToRemove.push_back(I);
202 }
203 }elseif (I->isTerminator()) {
204ConstantFoldTerminator(I->getParent());
205 }
206 }
207
208// Removing via isInstructionTriviallyDead may add duplicates to the ToRemove
209// array. Filter out the duplicates before starting to erase from parent.
210 std::sort(ToRemove.begin(),ToRemove.end());
211autoNewLastIter =llvm::unique(ToRemove);
212ToRemove.erase(NewLastIter,ToRemove.end());
213
214for (Instruction *I :ToRemove)
215I->eraseFromParent();
216
217returnToRemove.size() > 0;
218}
219
220bool NVVMReflect::runOnFunction(Function &F) {
221return runNVVMReflect(F,SmVersion);
222}
223
224NVVMReflectPass::NVVMReflectPass() :NVVMReflectPass(0) {}
225
226PreservedAnalysesNVVMReflectPass::run(Function &F,
227FunctionAnalysisManager &AM) {
228return runNVVMReflect(F,SmVersion) ?PreservedAnalyses::none()
229 :PreservedAnalyses::all();
230}
instructions
Expand Atomic instructions
Definition:AtomicExpandPass.cpp:172
BasicBlockUtils.h
CommandFlags.h
CommandLine.h
ConstantFolding.h
Constants.h
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Debug.h
LLVM_DEBUG
#define LLVM_DEBUG(...)
Definition:Debug.h:106
DerivedTypes.h
Function.h
Module.h
Module.h This file contains the declarations for the Module class.
PassManager.h
This header defines various interfaces for pass management in LLVM.
Type.h
InstIterator.h
Instructions.h
Intrinsics.h
F
#define F(x, y, z)
Definition:MD5.cpp:55
I
#define I(x, y, z)
Definition:MD5.cpp:58
NVPTX.h
NewLastIter
auto NewLastIter
Definition:NVVMReflect.cpp:211
NVVM_REFLECT_OCL_FUNCTION
#define NVVM_REFLECT_OCL_FUNCTION
Definition:NVVMReflect.cpp:44
ToSimplify
SmallVector< Instruction *, 4 > ToSimplify
Definition:NVVMReflect.cpp:94
NVVM_REFLECT_FUNCTION
#define NVVM_REFLECT_FUNCTION
Definition:NVVMReflect.cpp:43
SmVersion
unsigned SmVersion
Definition:NVVMReflect.cpp:81
NVVMReflectEnabled
static cl::opt< bool > NVVMReflectEnabled("nvvm-reflect-enable", cl::init(true), cl::Hidden, cl::desc("NVVM reflection, enabled by default"))
ToRemove
SmallVector< Instruction *, 4 > ToRemove
Definition:NVVMReflect.cpp:93
INITIALIZE_PASS
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition:PassSupport.h:38
Pass.h
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Scalar.h
SmallVector.h
This file defines the SmallVector class.
Local.h
llvm::AnalysisManager
A container for analyses that lazily runs them and caches their results.
Definition:PassManager.h:253
llvm::CallInst
This class represents a function call, abstracting a target machine's calling convention.
Definition:Instructions.h:1479
llvm::Constant
This is an important base class in LLVM.
Definition:Constant.h:42
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition:Pass.h:310
llvm::FunctionPass::runOnFunction
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
llvm::Function
Definition:Function.h:63
llvm::GlobalVariable
Definition:GlobalVariable.h:39
llvm::Instruction
Definition:Instruction.h:68
llvm::PassRegistry
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition:PassRegistry.h:37
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition:PassRegistry.cpp:24
llvm::PreservedAnalyses
A set of analyses that are preserved following a run of a transformation pass.
Definition:Analysis.h:111
llvm::PreservedAnalyses::none
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition:Analysis.h:114
llvm::PreservedAnalyses::all
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition:Analysis.h:117
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition:SmallVector.h:1196
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition:StringRef.h:51
llvm::StringRef::substr
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition:StringRef.h:571
llvm::StringRef::size
constexpr size_t size() const
size - Get the string size.
Definition:StringRef.h:150
llvm::User
Definition:User.h:44
llvm::Value
LLVM Value Representation.
Definition:Value.h:74
llvm::cl::opt
Definition:CommandLine.h:1423
unsigned
llvm::CallingConv::C
@ C
The default llvm calling convention, compatible with C.
Definition:CallingConv.h:34
llvm::CallingConv::ID
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition:CallingConv.h:24
llvm::cl::Hidden
@ Hidden
Definition:CommandLine.h:137
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition:CommandLine.h:443
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition:AddressRanges.h:18
llvm::ConstantFoldTerminator
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition:Local.cpp:136
llvm::createNVVMReflectPass
FunctionPass * createNVVMReflectPass(unsigned int SmVersion)
Definition:NVVMReflect.cpp:68
llvm::unique
auto unique(Range &&R, Predicate P)
Definition:STLExtras.h:2055
llvm::initializeNVVMReflectPass
void initializeNVVMReflectPass(PassRegistry &)
llvm::isInstructionTriviallyDead
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition:Local.cpp:406
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition:Debug.cpp:163
llvm::ConstantFoldInstruction
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
Definition:ConstantFolding.cpp:1123
raw_ostream.h
llvm::NVVMReflectPass
Definition:NVPTX.h:60
llvm::NVVMReflectPass::NVVMReflectPass
NVVMReflectPass()
Definition:NVVMReflect.cpp:224
llvm::NVVMReflectPass::run
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition:NVVMReflect.cpp:226
llvm::cl::desc
Definition:CommandLine.h:409

Generated on Thu Jul 17 2025 15:17:46 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp