Proteus
Programmable JIT compilation and optimization for C/C++ using LLVM
Loading...
Searching...
No Matches
CoreLLVMDevice.h
Go to the documentation of this file.
1#ifndef PROTEUS_CORE_LLVM_DEVICE_H
2#define PROTEUS_CORE_LLVM_DEVICE_H
3
4#if PROTEUS_ENABLE_HIP
6#endif
7
8#if PROTEUS_ENABLE_CUDA
10#endif
11
12#if defined(PROTEUS_ENABLE_HIP) || defined(PROTEUS_ENABLE_CUDA)
13
20
21#include <llvm/Analysis/CallGraph.h>
22#include <llvm/Bitcode/BitcodeReader.h>
23#include <llvm/Bitcode/BitcodeWriter.h>
24#include <llvm/IR/Attributes.h>
25#include <llvm/IR/ConstantRange.h>
26#include <llvm/IR/ReplaceConstant.h>
27#include <llvm/IR/Verifier.h>
28#include <llvm/Object/ELFObjectFile.h>
29#include <llvm/Transforms/Utils/Cloning.h>
30
31namespace proteus {
32
33inline void setKernelDims(Module &M, dim3 &GridDim, dim3 &BlockDim) {
34 auto ReplaceIntrinsicDim = [&](ArrayRef<StringRef> IntrinsicNames,
35 uint32_t DimValue) {
36 auto CollectCallUsers = [](Function &F) {
37 SmallVector<CallInst *> CallUsers;
38 for (auto *User : F.users()) {
39 auto *Call = dyn_cast<CallInst>(User);
40 if (!Call)
41 continue;
42 CallUsers.push_back(Call);
43 }
44
45 return CallUsers;
46 };
47
48 for (auto IntrinsicName : IntrinsicNames) {
49
50 Function *IntrinsicFunction = M.getFunction(IntrinsicName);
51 if (!IntrinsicFunction)
52 continue;
53
54 auto TraceOut = [](Function *F, Value *C) {
55 SmallString<128> S;
56 raw_svector_ostream OS(S);
57 OS << "[DimSpec] Replace call to " << F->getName() << " with constant "
58 << *C << "\n";
59
60 return S;
61 };
62
63 for (auto *Call : CollectCallUsers(*IntrinsicFunction)) {
64 Value *ConstantValue =
65 ConstantInt::get(Type::getInt32Ty(M.getContext()), DimValue);
66 Call->replaceAllUsesWith(ConstantValue);
67 if (Config::get().traceSpecializations())
68 Logger::trace(TraceOut(IntrinsicFunction, ConstantValue));
69 Call->eraseFromParent();
70 }
71 }
72 };
73
74 ReplaceIntrinsicDim(detail::gridDimXFnName(), GridDim.x);
75 ReplaceIntrinsicDim(detail::gridDimYFnName(), GridDim.y);
76 ReplaceIntrinsicDim(detail::gridDimZFnName(), GridDim.z);
77
78 ReplaceIntrinsicDim(detail::blockDimXFnName(), BlockDim.x);
79 ReplaceIntrinsicDim(detail::blockDimYFnName(), BlockDim.y);
80 ReplaceIntrinsicDim(detail::blockDimZFnName(), BlockDim.z);
81}
82
83inline void setKernelDimsRange(Module &M, dim3 &GridDim, dim3 &BlockDim) {
84 auto AttachRange = [&](ArrayRef<StringRef> IntrinsicNames,
85 uint32_t DimValue) {
86 if (DimValue == 0) {
87 reportFatalError("Dimension value cannot be zero");
88 }
89
90 for (auto IntrinsicName : IntrinsicNames) {
91 Function *IntrinsicFunction = M.getFunction(IntrinsicName);
92 if (!IntrinsicFunction || IntrinsicFunction->use_empty())
93 continue;
94
95 auto TraceOut = [](Function *IntrinsicF, uint32_t DimValue) {
96 SmallString<128> S;
97 raw_svector_ostream OS(S);
98 OS << "[DimSpec] Range " << IntrinsicF->getName() << " [0," << DimValue
99 << ")\n";
100 return S;
101 };
102
103 for (auto *U : IntrinsicFunction->users()) {
104 auto *Call = dyn_cast<CallInst>(U);
105 if (!Call)
106 continue;
107
108 auto *RetTy = dyn_cast<IntegerType>(Call->getType());
109 if (!RetTy)
110 continue;
111
112 unsigned BitWidth = RetTy->getBitWidth();
113 ConstantRange Range(APInt(BitWidth, 0), APInt(BitWidth, DimValue));
114
115#if LLVM_VERSION_MAJOR >= 19
116 AttrBuilder Builder{M.getContext()};
117 Builder.addRangeAttr(Range);
118 Call->removeRetAttr(Attribute::Range);
119 Call->setAttributes(
120 Call->getAttributes().addRetAttributes(M.getContext(), Builder));
121#else
122 // LLVM 18 (ROCm 6.2.x) does not expose the Range attribute; use range
123 // metadata instead.
124 LLVMContext &Ctx = M.getContext();
125 Metadata *RangeMD[] = {
126 ConstantAsMetadata::get(ConstantInt::get(RetTy, 0)),
127 ConstantAsMetadata::get(ConstantInt::get(RetTy, DimValue))};
128 MDNode *RangeNode = MDNode::get(Ctx, RangeMD);
129 Call->setMetadata(LLVMContext::MD_range, RangeNode);
130#endif
131
132 if (Config::get().traceSpecializations())
133 Logger::trace(TraceOut(IntrinsicFunction, DimValue));
134 }
135 }
136 };
137
138 AttachRange(detail::threadIdxXFnName(), BlockDim.x);
139 AttachRange(detail::threadIdxYFnName(), BlockDim.y);
140 AttachRange(detail::threadIdxZFnName(), BlockDim.z);
141
142 AttachRange(detail::blockIdxXFnName(), GridDim.x);
143 AttachRange(detail::blockIdxYFnName(), GridDim.y);
144 AttachRange(detail::blockIdxZFnName(), GridDim.z);
145}
146
147inline void replaceGlobalVariablesWithPointers(
148 Module &M,
149 const std::unordered_map<std::string, GlobalVarInfo> &VarNameToGlobalInfo) {
150 // Re-link globals to fixed addresses provided by registered
151 // variables.
152 for (auto RegisterVar : VarNameToGlobalInfo) {
153 auto &VarName = RegisterVar.first;
154 auto *GV = M.getNamedGlobal(VarName);
155 // Skip linking if the GV does not exist in the module.
156 if (!GV)
157 continue;
158
159 // This will convert constant users of GV to instructions so that we can
160 // replace with the GV ptr.
161 convertUsersOfConstantsToInstructions({GV});
162
163 Constant *Addr =
164 ConstantInt::get(Type::getInt64Ty(M.getContext()), 0xDEADBEEFDEADBEEF);
165 auto *CE = ConstantExpr::getIntToPtr(
166 Addr, PointerType::get(GV->getType(), GV->getAddressSpace()));
167 auto *GVarPtr = new GlobalVariable(
168 M, PointerType::get(GV->getType(), GV->getAddressSpace()), false,
169 GlobalValue::ExternalLinkage, CE, GV->getName() + "$ptr", nullptr,
170 GV->getThreadLocalMode(), GV->getAddressSpace(), true);
171
172 // Find all Constant users that refer to the global variable.
173 SmallPtrSet<Value *, 16> ValuesToReplace;
174 SmallVector<Value *> Worklist;
175 // Seed with the global variable.
176 Worklist.push_back(GV);
177 ValuesToReplace.insert(GV);
178 while (!Worklist.empty()) {
179 Value *V = Worklist.pop_back_val();
180 for (auto *User : V->users()) {
181 if (auto *C = dyn_cast<Constant>(User)) {
182 if (ValuesToReplace.insert(C).second)
183 Worklist.push_back(C);
184
185 continue;
186 }
187
188 // Skip instructions to be handled when replacing.
189 if (isa<Instruction>(User))
190 continue;
191
192 reportFatalError("Expected Instruction or Constant user for Value: " +
193 toString(*V) + " , User: " + toString(*User));
194 }
195 }
196
197 for (Value *V : ValuesToReplace) {
198 SmallPtrSet<Instruction *, 16> Insts;
199 // Find instruction users to replace value.
200 for (User *U : V->users()) {
201 if (auto *I = dyn_cast<Instruction>(U)) {
202 Insts.insert(I);
203 }
204 }
205
206 // Replace value in instructions.
207 for (auto *I : Insts) {
208 IRBuilder Builder{I};
209 auto *Load = Builder.CreateLoad(GV->getType(), GVarPtr);
210 Value *Replacement = Load;
211 Type *ExpectedTy = V->getType();
212 if (Load->getType() != ExpectedTy)
213 Replacement =
214 Builder.CreatePointerBitCastOrAddrSpaceCast(Load, ExpectedTy);
215
216 I->replaceUsesOfWith(V, Replacement);
217 }
218 }
219 }
220
221 if (Config::get().ProteusDebugOutput) {
222 if (verifyModule(M, &errs()))
223 reportFatalError("Broken module found, JIT compilation aborted!");
224 }
225}
226
227inline void relinkGlobalsObject(
228 MemoryBufferRef Object,
229 const std::unordered_map<std::string, GlobalVarInfo> &VarNameToGlobalInfo) {
230 Expected<object::ELF64LEObjectFile> DeviceElfOrErr =
231 object::ELF64LEObjectFile::create(Object);
232 if (auto E = DeviceElfOrErr.takeError())
233 reportFatalError("Cannot create the device elf: " + toString(std::move(E)));
234 auto &DeviceElf = *DeviceElfOrErr;
235
236 for (auto &[GlobalName, GVI] : VarNameToGlobalInfo) {
237 for (auto &Symbol : DeviceElf.symbols()) {
238 auto SymbolNameOrErr = Symbol.getName();
239 if (!SymbolNameOrErr)
240 continue;
241 auto SymbolName = *SymbolNameOrErr;
242
243 if (!(SymbolName == (GlobalName + "$ptr")))
244 continue;
245
246 Expected<uint64_t> ValueOrErr = Symbol.getValue();
247 if (!ValueOrErr)
248 reportFatalError("Expected symbol value");
249 uint64_t SymbolValue = *ValueOrErr;
250
251 // Get the section containing the symbol
252 auto SectionOrErr = Symbol.getSection();
253 if (!SectionOrErr)
254 reportFatalError("Cannot retrieve section");
255 const auto &Section = *SectionOrErr;
256 if (Section == DeviceElf.section_end())
257 reportFatalError("Expected sybmol in section");
258
259 // Get the section's address and data
260 Expected<StringRef> SectionDataOrErr = Section->getContents();
261 if (!SectionDataOrErr)
262 reportFatalError("Error retrieving section data");
263 StringRef SectionData = *SectionDataOrErr;
264
265 // Calculate offset within the section
266 uint64_t SectionAddr = Section->getAddress();
267 uint64_t Offset = SymbolValue - SectionAddr;
268 if (Offset >= SectionData.size())
269 reportFatalError("Expected offset within section size");
270
271 uint64_t *Data = (uint64_t *)(SectionData.data() + Offset);
272 if (!GVI.DevAddr)
273 reportFatalError("Cannot set global Var " + GlobalName +
274 " without a concrete device address");
275
276 *Data = reinterpret_cast<uint64_t>(GVI.DevAddr);
277 break;
278 }
279 }
280}
281
282inline void specializeIR(
283 Module &M, StringRef FnName, StringRef Suffix, dim3 &BlockDim,
284 dim3 &GridDim, ArrayRef<RuntimeConstant> RCArray,
285 const SmallVector<std::pair<std::string, StringRef>> LambdaCalleeInfo,
286 bool SpecializeArgs, bool SpecializeDims, bool SpecializeDimsRange,
287 bool SpecializeLaunchBounds, int MinBlocksPerSM) {
288 Timer T;
289 Function *F = M.getFunction(FnName);
290
291 assert(F && "Expected non-null function!");
292 // Replace argument uses with runtime constants.
293 if (SpecializeArgs)
295
296 auto &LR = LambdaRegistry::instance();
297 for (auto &[FnName, LambdaType] : LambdaCalleeInfo) {
298 const SmallVector<RuntimeConstant> &RCVec = LR.getJitVariables(LambdaType);
299 Function *F = M.getFunction(FnName);
300 if (!F)
301 reportFatalError("Expected non-null Function");
303 }
304
305 // Run the shared array transform after any value specialization (arguments,
306 // captures) to propagate any constants.
308
309 // Replace uses of blockDim.* and gridDim.* with constants.
310 if (SpecializeDims)
311 setKernelDims(M, GridDim, BlockDim);
312 if (SpecializeDimsRange)
313 setKernelDimsRange(M, GridDim, BlockDim);
314 F->setName(FnName + Suffix);
315
316 if (SpecializeLaunchBounds) {
317 int BlockSize = BlockDim.x * BlockDim.y * BlockDim.z;
318 auto TraceOut = [](int BlockSize, int MinBlocksPerSM) {
319 SmallString<128> S;
320 raw_svector_ostream OS(S);
321 OS << "[LaunchBoundSpec] MaxThreads " << BlockSize << " MinBlocksPerSM "
322 << MinBlocksPerSM << "\n";
323
324 return S;
325 };
326 if (Config::get().traceSpecializations())
327 Logger::trace(TraceOut(BlockSize, MinBlocksPerSM));
328 setLaunchBoundsForKernel(*F, BlockSize, MinBlocksPerSM);
329 }
330
332
334 << "specializeIR " << T.elapsed() << " ms\n");
335}
336
337} // namespace proteus
338
339#endif
340
341#endif
const void const char * VarName
Definition CompilerInterfaceDevice.cpp:24
#define PROTEUS_TIMER_OUTPUT(x)
Definition TimeTracing.h:54
static Config & get()
Definition Config.h:334
static LambdaRegistry & instance()
Definition LambdaRegistry.h:21
static llvm::raw_ostream & outs(const std::string &Name)
Definition Logger.h:25
static void trace(llvm::StringRef Msg)
Definition Logger.h:30
static void transform(Module &M, Function &F, ArrayRef< RuntimeConstant > RCArray)
Definition TransformArgumentSpecialization.h:88
static void transform(Module &M, Function &F, const SmallVector< RuntimeConstant > &RCVec)
Definition TransformLambdaSpecialization.h:126
static void transform(Module &M)
Definition TransformSharedArray.h:30
const SmallVector< StringRef > & threadIdxXFnName()
Definition CoreLLVMCUDA.h:70
const SmallVector< StringRef > & gridDimYFnName()
Definition CoreLLVMCUDA.h:30
const SmallVector< StringRef > & threadIdxZFnName()
Definition CoreLLVMCUDA.h:80
const SmallVector< StringRef > & blockIdxZFnName()
Definition CoreLLVMCUDA.h:65
const SmallVector< StringRef > & gridDimZFnName()
Definition CoreLLVMCUDA.h:35
const SmallVector< StringRef > & gridDimXFnName()
Definition CoreLLVMCUDA.h:25
const SmallVector< StringRef > & blockIdxXFnName()
Definition CoreLLVMCUDA.h:55
const SmallVector< StringRef > & threadIdxYFnName()
Definition CoreLLVMCUDA.h:75
const SmallVector< StringRef > & blockIdxYFnName()
Definition CoreLLVMCUDA.h:60
const SmallVector< StringRef > & blockDimYFnName()
Definition CoreLLVMCUDA.h:45
const SmallVector< StringRef > & blockDimZFnName()
Definition CoreLLVMCUDA.h:50
const SmallVector< StringRef > & blockDimXFnName()
Definition CoreLLVMCUDA.h:40
Definition MemoryCache.h:26
void setLaunchBoundsForKernel(Function &F, int MaxThreadsPerSM, int MinBlocksPerSM=0)
Definition CoreLLVMCUDA.h:87
void reportFatalError(const llvm::Twine &Reason, const char *FILE, unsigned Line)
Definition Error.cpp:14
static int int Offset
Definition JitInterface.h:102
std::string toString(CodegenOption Option)
Definition Config.h:28
void runCleanupPassPipeline(Module &M)
Definition CoreLLVM.h:230