1de4b88d9SYaxun Liu //===- AMDGPUOpenCLEnqueuedBlockLowering.cpp - Lower enqueued block -------===//
2de4b88d9SYaxun Liu //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6de4b88d9SYaxun Liu //
7de4b88d9SYaxun Liu //===----------------------------------------------------------------------===//
8de4b88d9SYaxun Liu //
9de4b88d9SYaxun Liu // \file
105f8f34e4SAdrian Prantl // This post-linking pass replaces the function pointer of enqueued
11de4b88d9SYaxun Liu // block kernel with a global variable (runtime handle) and adds
12de4b88d9SYaxun Liu // "runtime-handle" attribute to the enqueued block kernel.
13de4b88d9SYaxun Liu //
14de4b88d9SYaxun Liu // In LLVM CodeGen the runtime-handle metadata will be translated to
15de4b88d9SYaxun Liu // RuntimeHandle metadata in code object. Runtime allocates a global buffer
16d1f45ed5SNeubauer, Sebastian // for each kernel with RuntimeHandle metadata and saves the kernel address
17de4b88d9SYaxun Liu // required for the AQL packet into the buffer. __enqueue_kernel function
18de4b88d9SYaxun Liu // in device library knows that the invoke function pointer in the block
19de4b88d9SYaxun Liu // literal is actually runtime handle and loads the kernel address from it
20de4b88d9SYaxun Liu // and put it into AQL packet for dispatching.
21de4b88d9SYaxun Liu //
22de4b88d9SYaxun Liu // This cannot be done in FE since FE cannot create a unique global variable
23de4b88d9SYaxun Liu // with external linkage across LLVM modules. The global variable with internal
24de4b88d9SYaxun Liu // linkage does not work since optimization passes will try to replace loads
25de4b88d9SYaxun Liu // of the global variable with its initialization value.
26de4b88d9SYaxun Liu //
27c928f2a6SYaxun Liu // It also identifies the kernels directly or indirectly enqueues kernels
28c928f2a6SYaxun Liu // and adds "calls-enqueue-kernel" function attribute to them, which will
29c928f2a6SYaxun Liu // be used to determine whether to emit runtime metadata for the kernel
30c928f2a6SYaxun Liu // enqueue related hidden kernel arguments.
31c928f2a6SYaxun Liu //
32de4b88d9SYaxun Liu //===----------------------------------------------------------------------===//
33de4b88d9SYaxun Liu 
34de4b88d9SYaxun Liu #include "AMDGPU.h"
35c928f2a6SYaxun Liu #include "llvm/ADT/DenseSet.h"
36465dca79SReid Kleckner #include "llvm/ADT/SmallString.h"
37*a5bbc6efSBill Wendling #include "llvm/IR/Constants.h"
38c928f2a6SYaxun Liu #include "llvm/IR/Instructions.h"
39a99e7d8eSYaxun Liu #include "llvm/IR/Mangler.h"
40de4b88d9SYaxun Liu #include "llvm/IR/Module.h"
41de4b88d9SYaxun Liu #include "llvm/Pass.h"
42de4b88d9SYaxun Liu #include "llvm/Support/Debug.h"
43de4b88d9SYaxun Liu 
44de4b88d9SYaxun Liu #define DEBUG_TYPE "amdgpu-lower-enqueued-block"
45de4b88d9SYaxun Liu 
46de4b88d9SYaxun Liu using namespace llvm;
47de4b88d9SYaxun Liu 
48de4b88d9SYaxun Liu namespace {
49de4b88d9SYaxun Liu 
505f8f34e4SAdrian Prantl /// Lower enqueued blocks.
51de4b88d9SYaxun Liu class AMDGPUOpenCLEnqueuedBlockLowering : public ModulePass {
52de4b88d9SYaxun Liu public:
53de4b88d9SYaxun Liu   static char ID;
54de4b88d9SYaxun Liu 
AMDGPUOpenCLEnqueuedBlockLowering()55de4b88d9SYaxun Liu   explicit AMDGPUOpenCLEnqueuedBlockLowering() : ModulePass(ID) {}
56de4b88d9SYaxun Liu 
57de4b88d9SYaxun Liu private:
58de4b88d9SYaxun Liu   bool runOnModule(Module &M) override;
59de4b88d9SYaxun Liu };
60de4b88d9SYaxun Liu 
61de4b88d9SYaxun Liu } // end anonymous namespace
62de4b88d9SYaxun Liu 
63de4b88d9SYaxun Liu char AMDGPUOpenCLEnqueuedBlockLowering::ID = 0;
64de4b88d9SYaxun Liu 
65de4b88d9SYaxun Liu char &llvm::AMDGPUOpenCLEnqueuedBlockLoweringID =
66de4b88d9SYaxun Liu     AMDGPUOpenCLEnqueuedBlockLowering::ID;
67de4b88d9SYaxun Liu 
68de4b88d9SYaxun Liu INITIALIZE_PASS(AMDGPUOpenCLEnqueuedBlockLowering, DEBUG_TYPE,
69de4b88d9SYaxun Liu                 "Lower OpenCL enqueued blocks", false, false)
70de4b88d9SYaxun Liu 
createAMDGPUOpenCLEnqueuedBlockLoweringPass()71de4b88d9SYaxun Liu ModulePass* llvm::createAMDGPUOpenCLEnqueuedBlockLoweringPass() {
72de4b88d9SYaxun Liu   return new AMDGPUOpenCLEnqueuedBlockLowering();
73de4b88d9SYaxun Liu }
74de4b88d9SYaxun Liu 
756527b2a4SSebastian Neubauer /// Collect direct or indirect callers of \p F and save them
76c928f2a6SYaxun Liu /// to \p Callers.
collectCallers(Function * F,DenseSet<Function * > & Callers)77c928f2a6SYaxun Liu static void collectCallers(Function *F, DenseSet<Function *> &Callers) {
78c928f2a6SYaxun Liu   for (auto U : F->users()) {
79c928f2a6SYaxun Liu     if (auto *CI = dyn_cast<CallInst>(&*U)) {
80c928f2a6SYaxun Liu       auto *Caller = CI->getParent()->getParent();
819381ae97SYaxun Liu       if (Callers.insert(Caller).second)
82c928f2a6SYaxun Liu         collectCallers(Caller, Callers);
83c928f2a6SYaxun Liu     }
84c928f2a6SYaxun Liu   }
85c928f2a6SYaxun Liu }
86c928f2a6SYaxun Liu 
879381ae97SYaxun Liu /// If \p U is instruction or constant, collect functions which directly or
889381ae97SYaxun Liu /// indirectly use it.
collectFunctionUsers(User * U,DenseSet<Function * > & Funcs)899381ae97SYaxun Liu static void collectFunctionUsers(User *U, DenseSet<Function *> &Funcs) {
909381ae97SYaxun Liu   if (auto *I = dyn_cast<Instruction>(U)) {
919381ae97SYaxun Liu     auto *F = I->getParent()->getParent();
929381ae97SYaxun Liu     if (Funcs.insert(F).second)
939381ae97SYaxun Liu       collectCallers(F, Funcs);
949381ae97SYaxun Liu     return;
959381ae97SYaxun Liu   }
969381ae97SYaxun Liu   if (!isa<Constant>(U))
979381ae97SYaxun Liu     return;
989381ae97SYaxun Liu   for (auto UU : U->users())
999381ae97SYaxun Liu     collectFunctionUsers(&*UU, Funcs);
1009381ae97SYaxun Liu }
1019381ae97SYaxun Liu 
runOnModule(Module & M)102de4b88d9SYaxun Liu bool AMDGPUOpenCLEnqueuedBlockLowering::runOnModule(Module &M) {
103c928f2a6SYaxun Liu   DenseSet<Function *> Callers;
104de4b88d9SYaxun Liu   auto &C = M.getContext();
105de4b88d9SYaxun Liu   bool Changed = false;
106de4b88d9SYaxun Liu   for (auto &F : M.functions()) {
107de4b88d9SYaxun Liu     if (F.hasFnAttribute("enqueued-block")) {
108a99e7d8eSYaxun Liu       if (!F.hasName()) {
109a99e7d8eSYaxun Liu         SmallString<64> Name;
110a99e7d8eSYaxun Liu         Mangler::getNameWithPrefix(Name, "__amdgpu_enqueued_kernel",
111a99e7d8eSYaxun Liu                                    M.getDataLayout());
112a99e7d8eSYaxun Liu         F.setName(Name);
113a99e7d8eSYaxun Liu       }
114d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "found enqueued kernel: " << F.getName() << '\n');
115a99e7d8eSYaxun Liu       auto RuntimeHandle = (F.getName() + ".runtime_handle").str();
116fb17bf60SYaxun Liu       auto T = ArrayType::get(Type::getInt64Ty(C), 2);
117de4b88d9SYaxun Liu       auto *GV = new GlobalVariable(
1189381ae97SYaxun Liu           M, T,
11949a3ad21SRui Ueyama           /*isConstant=*/false, GlobalValue::ExternalLinkage,
1209381ae97SYaxun Liu           /*Initializer=*/Constant::getNullValue(T), RuntimeHandle,
1219381ae97SYaxun Liu           /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
1229381ae97SYaxun Liu           AMDGPUAS::GLOBAL_ADDRESS,
12349a3ad21SRui Ueyama           /*isExternallyInitialized=*/false);
124d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "runtime handle created: " << *GV << '\n');
125a99e7d8eSYaxun Liu 
126a99e7d8eSYaxun Liu       for (auto U : F.users()) {
1279381ae97SYaxun Liu         auto *UU = &*U;
1289381ae97SYaxun Liu         if (!isa<ConstantExpr>(UU))
129a99e7d8eSYaxun Liu           continue;
1309381ae97SYaxun Liu         collectFunctionUsers(UU, Callers);
1319381ae97SYaxun Liu         auto *BitCast = cast<ConstantExpr>(UU);
13246439e8dSYaxun Liu         auto *NewPtr = ConstantExpr::getPointerCast(GV, BitCast->getType());
13346439e8dSYaxun Liu         BitCast->replaceAllUsesWith(NewPtr);
134de4b88d9SYaxun Liu         F.addFnAttr("runtime-handle", RuntimeHandle);
135de4b88d9SYaxun Liu         F.setLinkage(GlobalValue::ExternalLinkage);
136de4b88d9SYaxun Liu         Changed = true;
137de4b88d9SYaxun Liu       }
138de4b88d9SYaxun Liu     }
13946439e8dSYaxun Liu   }
140c928f2a6SYaxun Liu 
141c928f2a6SYaxun Liu   for (auto F : Callers) {
142c928f2a6SYaxun Liu     if (F->getCallingConv() != CallingConv::AMDGPU_KERNEL)
143c928f2a6SYaxun Liu       continue;
144c928f2a6SYaxun Liu     F->addFnAttr("calls-enqueue-kernel");
145d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "mark enqueue_kernel caller:" << F->getName() << '\n');
146c928f2a6SYaxun Liu   }
147de4b88d9SYaxun Liu   return Changed;
148de4b88d9SYaxun Liu }
149