blob: cc1010f2a0fb2f24ad13cd6f2f50fd0d27b706ba [file] [log] [blame]
David Netoc5fb5242018-07-30 13:28:31 -04001// Copyright 2018 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
15#include <climits>
16#include <map>
17#include <set>
18#include <utility>
19#include <vector>
20
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/UniqueVector.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Module.h"
30#include "llvm/Pass.h"
31#include "llvm/Support/raw_ostream.h"
32
33#include "clspv/Option.h"
David Netoc5fb5242018-07-30 13:28:31 -040034
35#include "ArgKind.h"
alan-bakera71f1932019-04-11 11:04:34 -040036#include "CallGraphOrderedFunctions.h"
Alan Baker202c8c72018-08-13 13:47:44 -040037#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040038#include "Passes.h"
David Netoc5fb5242018-07-30 13:28:31 -040039
40using namespace llvm;
41
42#define DEBUG_TYPE "directresourceaccess"
43
44namespace {
45
46cl::opt<bool> ShowDRA("show-dra", cl::init(false), cl::Hidden,
47 cl::desc("Show direct resource access details"));
48
49using SamplerMapType = llvm::ArrayRef<std::pair<unsigned, std::string>>;
50
51class DirectResourceAccessPass final : public ModulePass {
52public:
53 static char ID;
54 DirectResourceAccessPass() : ModulePass(ID) {}
55 bool runOnModule(Module &M) override;
56
57private:
David Netoc5fb5242018-07-30 13:28:31 -040058 // For each kernel argument that will map to a resource variable (descriptor),
59 // try to rewrite the uses of the argument as a direct access of the resource.
60 // We can only do this if all the callees of the function use the same
61 // resource access value for that argument. Returns true if the module
62 // changed.
63 bool RewriteResourceAccesses(Function *fn);
64
65 // Rewrite uses of this resrouce-based arg if all the callers pass in the
66 // same resource access. Returns true if the module changed.
67 bool RewriteAccessesForArg(Function *fn, int arg_index, Argument &arg);
68};
Diego Novilloa4c44fa2019-04-11 10:56:15 -040069
David Netoc5fb5242018-07-30 13:28:31 -040070} // namespace
71
72char DirectResourceAccessPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -040073INITIALIZE_PASS(DirectResourceAccessPass, "DirectResourceAccessPass",
74 "Direct resource access", false, false)
David Netoc5fb5242018-07-30 13:28:31 -040075
76namespace clspv {
77ModulePass *createDirectResourceAccessPass() {
78 return new DirectResourceAccessPass();
79}
80} // namespace clspv
81
82namespace {
83bool DirectResourceAccessPass::runOnModule(Module &M) {
84 bool Changed = false;
85
86 if (clspv::Option::DirectResourceAccess()) {
alan-bakera71f1932019-04-11 11:04:34 -040087 auto ordered_functions = clspv::CallGraphOrderedFunctions(M);
88 if (ShowDRA) {
89 outs() << "DRA: Ordered functions:\n";
90 for (Function *fun : ordered_functions) {
91 outs() << "DRA: " << fun->getName() << "\n";
92 }
93 }
94
David Netoc5fb5242018-07-30 13:28:31 -040095 for (auto *fn : ordered_functions) {
96 Changed |= RewriteResourceAccesses(fn);
97 }
98 }
99
100 return Changed;
101}
102
David Netoc5fb5242018-07-30 13:28:31 -0400103bool DirectResourceAccessPass::RewriteResourceAccesses(Function *fn) {
104 bool Changed = false;
105 int arg_index = 0;
106 for (Argument &arg : fn->args()) {
107 switch (clspv::GetArgKindForType(arg.getType())) {
108 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -0400109 case clspv::ArgKind::BufferUBO:
David Netoc5fb5242018-07-30 13:28:31 -0400110 case clspv::ArgKind::ReadOnlyImage:
111 case clspv::ArgKind::WriteOnlyImage:
112 case clspv::ArgKind::Sampler:
Alan Baker202c8c72018-08-13 13:47:44 -0400113 case clspv::ArgKind::Local:
David Netoc5fb5242018-07-30 13:28:31 -0400114 Changed |= RewriteAccessesForArg(fn, arg_index, arg);
115 break;
David Neto3a0df832018-08-03 14:35:42 -0400116 default:
117 // Should not happen
118 break;
David Netoc5fb5242018-07-30 13:28:31 -0400119 }
120 arg_index++;
121 }
122 return Changed;
123}
124
125bool DirectResourceAccessPass::RewriteAccessesForArg(Function *fn,
126 int arg_index,
127 Argument &arg) {
128 bool Changed = false;
129 if (fn->use_empty()) {
130 return false;
131 }
132
133 // We can convert a parameter to a direct resource access if it is
134 // either a direct call to a clspv.resource.var.* or if it a GEP of
135 // such a thing (where the GEP can only have zero indices).
136 struct ParamInfo {
Alan Baker202c8c72018-08-13 13:47:44 -0400137 // The base value. It is either a global variable or a resource-access
138 // builtin function. (@clspv.resource.var.* or @clspv.local.var.*)
139 Value *base;
David Netoc5fb5242018-07-30 13:28:31 -0400140 // The descriptor set.
141 uint32_t set;
142 // The binding.
143 uint32_t binding;
144 // If the parameter is a GEP, then this is the number of zero-indices
145 // the GEP used.
146 unsigned num_gep_zeroes;
147 // An example call fitting
148 CallInst *sample_call;
149 };
150 // The common valid parameter info across all the callers seen soo far.
151
152 bool seen_one = false;
153 ParamInfo common;
154 // Tries to merge the given parameter info into |common|. If it is the first
155 // time we've tried, then save it. Returns true if there is no conflict.
156 auto merge_param_info = [&seen_one, &common](const ParamInfo &pi) {
157 if (!seen_one) {
158 common = pi;
159 seen_one = true;
160 return true;
161 }
Alan Baker202c8c72018-08-13 13:47:44 -0400162 return pi.base == common.base && pi.set == common.set &&
David Netoc5fb5242018-07-30 13:28:31 -0400163 pi.binding == common.binding &&
164 pi.num_gep_zeroes == common.num_gep_zeroes;
165 };
166
167 for (auto &use : fn->uses()) {
168 if (auto *caller = dyn_cast<CallInst>(use.getUser())) {
169 Value *value = caller->getArgOperand(arg_index);
170 // We care about two cases:
171 // - a direct call to clspv.resource.var.*
172 // - a GEP with only zero indices, where the base pointer is
173
174 // Unpack GEPs with zeros, if we can. Rewrite |value| as we go along.
175 unsigned num_gep_zeroes = 0;
David Neto2f450002018-08-01 16:13:03 -0400176 bool first_gep = true;
David Netoc5fb5242018-07-30 13:28:31 -0400177 for (auto *gep = dyn_cast<GetElementPtrInst>(value); gep;
178 gep = dyn_cast<GetElementPtrInst>(value)) {
179 if (!gep->hasAllZeroIndices()) {
180 return false;
181 }
David Neto2f450002018-08-01 16:13:03 -0400182 // If not the first GEP, then ignore the "element" index (which I call
183 // "slide") since that will be combined with the last index of the
184 // previous GEP.
185 num_gep_zeroes += gep->getNumIndices() + (first_gep ? 0 : -1);
David Netoc5fb5242018-07-30 13:28:31 -0400186 value = gep->getPointerOperand();
David Neto2f450002018-08-01 16:13:03 -0400187 first_gep = false;
David Netoc5fb5242018-07-30 13:28:31 -0400188 }
189 if (auto *call = dyn_cast<CallInst>(value)) {
190 // If the call is a call to a @clspv.resource.var.* function, then try
191 // to merge it, assuming the given number of GEP zero-indices so far.
192 if (call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -0400193 clspv::ResourceAccessorFunction())) {
David Netoc5fb5242018-07-30 13:28:31 -0400194 const auto set = uint32_t(
195 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
196 const auto binding = uint32_t(
197 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
198 if (!merge_param_info({call->getCalledFunction(), set, binding,
Alan Baker202c8c72018-08-13 13:47:44 -0400199 num_gep_zeroes, call}))
David Netoc5fb5242018-07-30 13:28:31 -0400200 return false;
Alan Baker202c8c72018-08-13 13:47:44 -0400201 } else if (call->getCalledFunction()->getName().startswith(
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400202 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -0400203 const uint32_t spec_id = uint32_t(
204 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
205 if (!merge_param_info({call->getCalledFunction(), spec_id, 0,
206 num_gep_zeroes, call}))
207 return false;
David Netoc5fb5242018-07-30 13:28:31 -0400208 } else {
209 // A call but not to a resource access builtin function.
210 return false;
211 }
Alan Baker202c8c72018-08-13 13:47:44 -0400212 } else if (isa<GlobalValue>(value)) {
213 if (!merge_param_info({value, 0, 0, num_gep_zeroes, nullptr}))
214 return false;
David Netoc5fb5242018-07-30 13:28:31 -0400215 } else {
216 // Not a call.
217 return false;
218 }
219 } else {
220 // There isn't enough commonality. Bail out without changing anything.
221 return false;
222 }
223 }
224 if (ShowDRA) {
225 if (seen_one) {
226 outs() << "DRA: Rewrite " << fn->getName() << " arg " << arg_index << " "
Alan Baker202c8c72018-08-13 13:47:44 -0400227 << arg.getName() << ": " << common.base->getName() << " ("
David Netoc5fb5242018-07-30 13:28:31 -0400228 << common.set << "," << common.binding
Alan Bakerfc6888e2018-08-20 20:54:33 -0400229 << ") zeroes: " << common.num_gep_zeroes << " sample-call ";
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400230 if (common.sample_call)
231 outs() << *common.sample_call << "\n";
232 else
233 outs() << "nullptr\n";
David Netoc5fb5242018-07-30 13:28:31 -0400234 }
235 }
236
237 // Now rewrite the argument, using the info in |common|.
238
239 Changed = true;
240 IRBuilder<> Builder(fn->getParent()->getContext());
241 auto *zero = Builder.getInt32(0);
242 Builder.SetInsertPoint(fn->getEntryBlock().getFirstNonPHI());
243
Alan Baker202c8c72018-08-13 13:47:44 -0400244 Value *replacement = common.base;
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400245 if (Function *function = dyn_cast<Function>(replacement)) {
Alan Baker202c8c72018-08-13 13:47:44 -0400246 // Create the call.
247 SmallVector<Value *, 8> args(common.sample_call->arg_begin(),
248 common.sample_call->arg_end());
249 replacement = Builder.CreateCall(function, args);
250 if (ShowDRA) {
251 outs() << "DRA: Replace: call " << *replacement << "\n";
252 }
David Netoc5fb5242018-07-30 13:28:31 -0400253 }
254 if (common.num_gep_zeroes) {
255 SmallVector<Value *, 3> zeroes;
256 for (unsigned i = 0; i < common.num_gep_zeroes; i++) {
257 zeroes.push_back(zero);
258 }
Alan Baker202c8c72018-08-13 13:47:44 -0400259 // Builder.CreateGEP is not used to avoid creating a GEPConstantExpr in the
260 // case of global variables.
261 replacement = GetElementPtrInst::Create(nullptr, replacement, zeroes);
262 Builder.Insert(cast<Instruction>(replacement));
David Netoc5fb5242018-07-30 13:28:31 -0400263 if (ShowDRA) {
264 outs() << "DRA: Replace: gep " << *replacement << "\n";
265 }
266 }
267 arg.replaceAllUsesWith(replacement);
268
269 return Changed;
270}
271
272} // namespace