blob: dd0a4c21bae306f9506b1d6cb7f9ecb899e1936c [file] [log] [blame]
David Netodd992212017-06-23 17:47:55 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
David Neto156783e2017-07-05 15:39:41 -040015// Cluster POD kernel arguments.
16//
17// Collect plain-old-data kernel arguments and place them into a single
18// struct argument, at the end. Other arguments are pointers, and retain
19// their relative order.
20//
21// We will create a kernel function as the new entry point, and change
22// the original kernel function into a regular SPIR function. Key
23// kernel metadata is moved from the old function to the wrapper.
24// We also attach a "kernel_arg_map" metadata node to the function to
25// encode the mapping from old kernel argument to new kernel argument.
26
David Netodd992212017-06-23 17:47:55 -040027#include <cassert>
28
29#include <llvm/IR/Constants.h>
30#include <llvm/IR/DerivedTypes.h>
31#include <llvm/IR/Function.h>
32#include <llvm/IR/Instructions.h>
33#include <llvm/IR/IRBuilder.h>
David Neto156783e2017-07-05 15:39:41 -040034#include <llvm/IR/Metadata.h>
David Netodd992212017-06-23 17:47:55 -040035#include <llvm/IR/Module.h>
36#include <llvm/Pass.h>
37#include <llvm/Support/raw_ostream.h>
38
David Neto4feb7a42017-10-06 17:29:42 -040039#include "ArgKind.h"
David Netodd992212017-06-23 17:47:55 -040040
41using namespace llvm;
42
43#define DEBUG_TYPE "clusterpodkernelargs"
44
45namespace {
46struct ClusterPodKernelArgumentsPass : public ModulePass {
47 static char ID;
48 ClusterPodKernelArgumentsPass() : ModulePass(ID) {}
49
50 bool runOnModule(Module &M) override;
51};
David Neto48f56a42017-10-06 16:44:25 -040052
David Netodd992212017-06-23 17:47:55 -040053} // namespace
54
55char ClusterPodKernelArgumentsPass::ID = 0;
56static RegisterPass<ClusterPodKernelArgumentsPass>
57 X("ClusterPodKernelArgumentsPass",
58 "Cluster POD Kernel Arguments Pass");
59
60namespace clspv {
61llvm::ModulePass *createClusterPodKernelArgumentsPass() {
62 return new ClusterPodKernelArgumentsPass();
63}
64} // namespace clspv
65
66bool ClusterPodKernelArgumentsPass::runOnModule(Module &M) {
67 bool Changed = false;
68 LLVMContext &Context = M.getContext();
69
70 SmallVector<Function *, 8> WorkList;
71
72 for (Function &F : M) {
73 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
74 continue;
75 }
76 for (Argument &Arg : F.args()) {
77 if (!isa<PointerType>(Arg.getType())) {
78 WorkList.push_back(&F);
79 break;
80 }
81 }
82 }
83
David Netodd992212017-06-23 17:47:55 -040084 for (Function* F : WorkList) {
85 Changed = true;
86
David Neto156783e2017-07-05 15:39:41 -040087 // An ArgMapping describes how a kernel argument is remapped.
88 struct ArgMapping {
89 std::string name;
90 // 0-based argument index in the old kernel function.
91 unsigned old_index;
92 // 0-based argument index in the new kernel function.
93 unsigned new_index;
94 // Offset of the argument value within the new kernel argument.
95 // This is always zero for non-POD arguments. For a POD argument,
96 // this is the byte offset within the POD arguments struct.
97 unsigned offset;
David Neto48f56a42017-10-06 16:44:25 -040098 // Argument type. Same range of values as the result of
David Neto4feb7a42017-10-06 17:29:42 -040099 // clspv::GetArgKindForType.
100 const char* arg_kind;
David Neto156783e2017-07-05 15:39:41 -0400101 };
102
David Netodd992212017-06-23 17:47:55 -0400103 // In OpenCL, kernel arguments are either pointers or POD. A composite with
104 // an element or memeber that is a pointer is not allowed. So we'll use POD
105 // as a shorthand for non-pointer.
106
107 SmallVector<Type *, 8> PtrArgTys;
108 SmallVector<Type *, 8> PodArgTys;
David Neto156783e2017-07-05 15:39:41 -0400109 SmallVector<ArgMapping, 8> RemapInfo;
110 unsigned arg_index = 0;
David Netodd992212017-06-23 17:47:55 -0400111 for (Argument &Arg : F->args()) {
112 Type *ArgTy = Arg.getType();
113 if (isa<PointerType>(ArgTy)) {
114 PtrArgTys.push_back(ArgTy);
David Neto156783e2017-07-05 15:39:41 -0400115 RemapInfo.push_back({std::string(Arg.getName()), arg_index,
David Neto48f56a42017-10-06 16:44:25 -0400116 unsigned(RemapInfo.size()), 0u,
David Neto4feb7a42017-10-06 17:29:42 -0400117 clspv::GetArgKindForType(ArgTy)});
David Netodd992212017-06-23 17:47:55 -0400118 } else {
119 PodArgTys.push_back(ArgTy);
120 }
David Neto156783e2017-07-05 15:39:41 -0400121 arg_index++;
David Netodd992212017-06-23 17:47:55 -0400122 }
123
David Netodd992212017-06-23 17:47:55 -0400124 // Put the pointer arguments first, and then POD arguments struct last.
125 auto PodArgsStructTy =
126 StructType::create(PodArgTys, F->getName().str() + ".podargs");
127 SmallVector<Type *, 8> NewFuncParamTys(PtrArgTys);
128 NewFuncParamTys.push_back(PodArgsStructTy);
129
David Neto156783e2017-07-05 15:39:41 -0400130 // We've recorded the remapping for pointer arguments. Now record the
131 // remapping for POD arguments.
132 {
133 const auto StructLayout =
134 M.getDataLayout().getStructLayout(PodArgsStructTy);
135 arg_index = 0;
136 int pod_index = 0;
137 const unsigned num_pointer_args = unsigned(RemapInfo.size());
138 for (Argument &Arg : F->args()) {
139 Type *ArgTy = Arg.getType();
140 if (!isa<PointerType>(ArgTy)) {
141 RemapInfo.push_back(
142 {std::string(Arg.getName()), arg_index, num_pointer_args,
David Neto48f56a42017-10-06 16:44:25 -0400143 unsigned(StructLayout->getElementOffset(pod_index++)),
David Neto4feb7a42017-10-06 17:29:42 -0400144 clspv::GetArgKindForType(ArgTy)});
David Neto156783e2017-07-05 15:39:41 -0400145 }
146 arg_index++;
147 }
148 }
149
David Netodd992212017-06-23 17:47:55 -0400150 FunctionType *NewFuncTy =
151 FunctionType::get(F->getReturnType(), NewFuncParamTys, false);
152
153 // Create the new function and set key properties.
154 auto NewFunc = Function::Create(NewFuncTy, F->getLinkage());
155 // The new function adopts the real name so that linkage to the outside
156 // world remains the same.
157 NewFunc->setName(F->getName());
158 F->setName(NewFunc->getName().str() + ".inner");
159
160 NewFunc->setCallingConv(F->getCallingConv());
161 F->setCallingConv(CallingConv::SPIR_FUNC);
162
163 NewFunc->setAttributes(F->getAttributes());
164 // Move OpenCL kernel named attributes.
165 // TODO(dneto): Attributes starting with kernel_arg_* should be rewritten
166 // to reflect change in the argument shape.
167 std::vector<const char *> Metadatas{
168 "reqd_work_group_size", "kernel_arg_addr_space",
169 "kernel_arg_access_qual", "kernel_arg_type",
170 "kernel_arg_base_type", "kernel_arg_type_qual"};
171 for (auto name : Metadatas) {
172 NewFunc->setMetadata(name, F->getMetadata(name));
173 F->setMetadata(name, nullptr);
174 }
175
David Neto156783e2017-07-05 15:39:41 -0400176 IRBuilder<> Builder(BasicBlock::Create(Context, "entry", NewFunc));
177
178 // Set kernel argument mapping metadata.
179 {
180 // Attach a metadata node named "kernel_arg_map" to the new kernel
181 // function. It is a tuple of nodes, each of which is a tuple for
182 // each argument, with members:
183 // - Argument name
184 // - Ordinal index in the original kernel function
185 // - Ordinal index in the new kernel function
186 // - Byte offset within the argument. This is always 0 for pointer
187 // arguments. For POD arguments this is the offest within the POD
188 // argument struct.
David Neto48f56a42017-10-06 16:44:25 -0400189 // - Argument type
David Neto156783e2017-07-05 15:39:41 -0400190 LLVMContext& Context = M.getContext();
191 SmallVector<Metadata*, 8> mappings;
192 for (auto &arg_mapping : RemapInfo) {
193 auto *name_md = MDString::get(Context, arg_mapping.name);
194 auto *old_index_md =
195 ConstantAsMetadata::get(Builder.getInt32(arg_mapping.old_index));
196 auto *new_index_md =
197 ConstantAsMetadata::get(Builder.getInt32(arg_mapping.new_index));
198 auto *offset =
199 ConstantAsMetadata::get(Builder.getInt32(arg_mapping.offset));
David Neto4feb7a42017-10-06 17:29:42 -0400200 auto *argtype_md = MDString::get(Context, arg_mapping.arg_kind);
David Neto48f56a42017-10-06 16:44:25 -0400201 auto *arg_md = MDNode::get(
202 Context, {name_md, old_index_md, new_index_md, offset, argtype_md});
David Neto156783e2017-07-05 15:39:41 -0400203 mappings.push_back(arg_md);
204 }
205
206 NewFunc->setMetadata("kernel_arg_map", MDNode::get(Context, mappings));
207 }
208
David Netodd992212017-06-23 17:47:55 -0400209 // Insert the function after the original, to preserve ordering
210 // in the module as much as possible.
211 auto &FunctionList = M.getFunctionList();
212 for (auto Iter = FunctionList.begin(), IterEnd = FunctionList.end();
213 Iter != IterEnd; ++Iter) {
214 if (&*Iter == F) {
215 FunctionList.insertAfter(Iter, NewFunc);
216 break;
217 }
218 }
219
220 // The body of the wrapper is essentially a call to the original function,
221 // but we have to unwrap the non-pointer arguments from the struct.
David Netodd992212017-06-23 17:47:55 -0400222
223 // Map the wrapper's arguments to the callee's arguments.
224 SmallVector<Argument *, 8> CallerArgs;
225 for (Argument &Arg : NewFunc->args()) {
226 CallerArgs.push_back(&Arg);
227 }
228 Argument *PodArg = CallerArgs.back();
229 PodArg->setName("podargs");
230
231 SmallVector<Value *, 8> CalleeArgs;
232 unsigned podIndex = 0;
233 unsigned ptrIndex = 0;
234 for (const Argument &Arg : F->args()) {
235 if (isa<PointerType>(Arg.getType())) {
236 CalleeArgs.push_back(CallerArgs[ptrIndex++]);
237 } else {
238 CalleeArgs.push_back(Builder.CreateExtractValue(PodArg, {podIndex++}));
239 }
240 CalleeArgs.back()->setName(Arg.getName());
241 }
242 assert(ptrIndex + podIndex == F->arg_size());
243 assert(ptrIndex = PtrArgTys.size());
244 assert(podIndex = PodArgTys.size());
245
246 auto Call = Builder.CreateCall(F, CalleeArgs);
247 Call->setCallingConv(F->getCallingConv());
248
249 Builder.CreateRetVoid();
250 }
251
252 return Changed;
253}