David Neto | c5fb524 | 2018-07-30 13:28:31 -0400 | [diff] [blame] | 1 | // 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" |
| 34 | #include "clspv/Passes.h" |
| 35 | |
| 36 | #include "ArgKind.h" |
| 37 | |
| 38 | using namespace llvm; |
| 39 | |
| 40 | #define DEBUG_TYPE "directresourceaccess" |
| 41 | |
| 42 | namespace { |
| 43 | |
| 44 | cl::opt<bool> ShowDRA("show-dra", cl::init(false), cl::Hidden, |
| 45 | cl::desc("Show direct resource access details")); |
| 46 | |
| 47 | using SamplerMapType = llvm::ArrayRef<std::pair<unsigned, std::string>>; |
| 48 | |
| 49 | class DirectResourceAccessPass final : public ModulePass { |
| 50 | public: |
| 51 | static char ID; |
| 52 | DirectResourceAccessPass() : ModulePass(ID) {} |
| 53 | bool runOnModule(Module &M) override; |
| 54 | |
| 55 | private: |
| 56 | // Return the functions reachable from entry point functions, where |
| 57 | // callers appear before callees. OpenCL C does not permit recursion |
| 58 | // or function or pointers, so this is always well defined. The ordering |
| 59 | // should be reproducible from one run to the next. |
| 60 | UniqueVector<Function *> CallGraphOrderedFunctions(Module &); |
| 61 | |
| 62 | // For each kernel argument that will map to a resource variable (descriptor), |
| 63 | // try to rewrite the uses of the argument as a direct access of the resource. |
| 64 | // We can only do this if all the callees of the function use the same |
| 65 | // resource access value for that argument. Returns true if the module |
| 66 | // changed. |
| 67 | bool RewriteResourceAccesses(Function *fn); |
| 68 | |
| 69 | // Rewrite uses of this resrouce-based arg if all the callers pass in the |
| 70 | // same resource access. Returns true if the module changed. |
| 71 | bool RewriteAccessesForArg(Function *fn, int arg_index, Argument &arg); |
| 72 | }; |
| 73 | } // namespace |
| 74 | |
| 75 | char DirectResourceAccessPass::ID = 0; |
| 76 | static RegisterPass<DirectResourceAccessPass> X("DirectResourceAccessPass", |
| 77 | "Direct resource access"); |
| 78 | |
| 79 | namespace clspv { |
| 80 | ModulePass *createDirectResourceAccessPass() { |
| 81 | return new DirectResourceAccessPass(); |
| 82 | } |
| 83 | } // namespace clspv |
| 84 | |
| 85 | namespace { |
| 86 | bool DirectResourceAccessPass::runOnModule(Module &M) { |
| 87 | bool Changed = false; |
| 88 | |
| 89 | if (clspv::Option::DirectResourceAccess()) { |
| 90 | auto ordered_functions = CallGraphOrderedFunctions(M); |
| 91 | for (auto *fn : ordered_functions) { |
| 92 | Changed |= RewriteResourceAccesses(fn); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | return Changed; |
| 97 | } |
| 98 | |
| 99 | UniqueVector<Function *> |
| 100 | DirectResourceAccessPass::CallGraphOrderedFunctions(Module &M) { |
| 101 | // Use a topological sort. |
| 102 | |
| 103 | // Make an ordered list of all functions having bodies, with kernel entry |
| 104 | // points listed first. |
| 105 | UniqueVector<Function *> functions; |
| 106 | SmallVector<Function *, 10> entry_points; |
| 107 | for (Function &F : M) { |
| 108 | if (F.isDeclaration()) { |
| 109 | continue; |
| 110 | } |
| 111 | if (F.getCallingConv() == CallingConv::SPIR_KERNEL) { |
| 112 | functions.insert(&F); |
| 113 | entry_points.push_back(&F); |
| 114 | } |
| 115 | } |
| 116 | // Add the remaining functions. |
| 117 | for (Function &F : M) { |
| 118 | if (F.isDeclaration()) { |
| 119 | continue; |
| 120 | } |
| 121 | if (F.getCallingConv() != CallingConv::SPIR_KERNEL) { |
| 122 | functions.insert(&F); |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | // This will be a complete set of reveresed edges, i.e. with all pairs |
| 127 | // of (callee, caller). |
| 128 | using Edge = std::pair<unsigned, unsigned>; |
| 129 | auto make_edge = [&functions](Function *callee, Function *caller) { |
| 130 | return std::pair<unsigned, unsigned>{functions.idFor(callee), |
| 131 | functions.idFor(caller)}; |
| 132 | }; |
| 133 | std::set<Edge> reverse_edges; |
| 134 | // Map each function to the functions it calls, and populate |reverse_edges|. |
| 135 | std::map<Function *, SmallVector<Function *, 3>> calls_functions; |
| 136 | for (Function *callee : functions) { |
| 137 | for (auto &use : callee->uses()) { |
| 138 | if (auto *call = dyn_cast<CallInst>(use.getUser())) { |
| 139 | Function *caller = call->getParent()->getParent(); |
| 140 | calls_functions[caller].push_back(callee); |
| 141 | reverse_edges.insert(make_edge(callee, caller)); |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | // Sort the callees in module-order. This helps us produce a deterministic |
| 146 | // result. |
| 147 | for (auto &pair : calls_functions) { |
| 148 | auto &callees = pair.second; |
| 149 | std::sort(callees.begin(), callees.end(), |
| 150 | [&functions](Function *lhs, Function *rhs) { |
| 151 | return functions.idFor(lhs) < functions.idFor(rhs); |
| 152 | }); |
| 153 | } |
| 154 | |
| 155 | // Use Kahn's algorithm for topoological sort. |
| 156 | UniqueVector<Function *> result; |
| 157 | SmallVector<Function *, 10> work_list(entry_points.begin(), |
| 158 | entry_points.end()); |
| 159 | while (!work_list.empty()) { |
| 160 | Function *caller = work_list.back(); |
| 161 | work_list.pop_back(); |
| 162 | result.insert(caller); |
| 163 | auto &callees = calls_functions[caller]; |
| 164 | for (auto *callee : callees) { |
| 165 | reverse_edges.erase(make_edge(callee, caller)); |
| 166 | auto lower_bound = reverse_edges.lower_bound(make_edge(callee, nullptr)); |
| 167 | if (lower_bound == reverse_edges.end() || |
| 168 | lower_bound->first != functions.idFor(callee)) { |
| 169 | // Callee has no other unvisited callers. |
| 170 | work_list.push_back(callee); |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | // If reverse_edges is not empty then there was a cycle. But we don't care |
| 175 | // about that erroneous case. |
| 176 | |
| 177 | if (ShowDRA) { |
| 178 | outs() << "DRA: Ordered functions:\n"; |
| 179 | for (Function *fun : result) { |
| 180 | outs() << "DRA: " << fun->getName() << "\n"; |
| 181 | } |
| 182 | } |
| 183 | return result; |
| 184 | } |
| 185 | |
| 186 | bool DirectResourceAccessPass::RewriteResourceAccesses(Function *fn) { |
| 187 | bool Changed = false; |
| 188 | int arg_index = 0; |
| 189 | for (Argument &arg : fn->args()) { |
| 190 | switch (clspv::GetArgKindForType(arg.getType())) { |
| 191 | case clspv::ArgKind::Buffer: |
| 192 | case clspv::ArgKind::ReadOnlyImage: |
| 193 | case clspv::ArgKind::WriteOnlyImage: |
| 194 | case clspv::ArgKind::Sampler: |
| 195 | Changed |= RewriteAccessesForArg(fn, arg_index, arg); |
| 196 | break; |
| 197 | } |
| 198 | arg_index++; |
| 199 | } |
| 200 | return Changed; |
| 201 | } |
| 202 | |
| 203 | bool DirectResourceAccessPass::RewriteAccessesForArg(Function *fn, |
| 204 | int arg_index, |
| 205 | Argument &arg) { |
| 206 | bool Changed = false; |
| 207 | if (fn->use_empty()) { |
| 208 | return false; |
| 209 | } |
| 210 | |
| 211 | // We can convert a parameter to a direct resource access if it is |
| 212 | // either a direct call to a clspv.resource.var.* or if it a GEP of |
| 213 | // such a thing (where the GEP can only have zero indices). |
| 214 | struct ParamInfo { |
| 215 | // The resource-access builtin function. (@clspv.resource.var.*) |
| 216 | Function *var_fn; |
| 217 | // The descriptor set. |
| 218 | uint32_t set; |
| 219 | // The binding. |
| 220 | uint32_t binding; |
| 221 | // If the parameter is a GEP, then this is the number of zero-indices |
| 222 | // the GEP used. |
| 223 | unsigned num_gep_zeroes; |
| 224 | // An example call fitting |
| 225 | CallInst *sample_call; |
| 226 | }; |
| 227 | // The common valid parameter info across all the callers seen soo far. |
| 228 | |
| 229 | bool seen_one = false; |
| 230 | ParamInfo common; |
| 231 | // Tries to merge the given parameter info into |common|. If it is the first |
| 232 | // time we've tried, then save it. Returns true if there is no conflict. |
| 233 | auto merge_param_info = [&seen_one, &common](const ParamInfo &pi) { |
| 234 | if (!seen_one) { |
| 235 | common = pi; |
| 236 | seen_one = true; |
| 237 | return true; |
| 238 | } |
| 239 | return pi.var_fn == common.var_fn && pi.set == common.set && |
| 240 | pi.binding == common.binding && |
| 241 | pi.num_gep_zeroes == common.num_gep_zeroes; |
| 242 | }; |
| 243 | |
| 244 | for (auto &use : fn->uses()) { |
| 245 | if (auto *caller = dyn_cast<CallInst>(use.getUser())) { |
| 246 | Value *value = caller->getArgOperand(arg_index); |
| 247 | // We care about two cases: |
| 248 | // - a direct call to clspv.resource.var.* |
| 249 | // - a GEP with only zero indices, where the base pointer is |
| 250 | |
| 251 | // Unpack GEPs with zeros, if we can. Rewrite |value| as we go along. |
| 252 | unsigned num_gep_zeroes = 0; |
| 253 | for (auto *gep = dyn_cast<GetElementPtrInst>(value); gep; |
| 254 | gep = dyn_cast<GetElementPtrInst>(value)) { |
| 255 | if (!gep->hasAllZeroIndices()) { |
| 256 | return false; |
| 257 | } |
| 258 | num_gep_zeroes += gep->getNumIndices(); |
| 259 | value = gep->getPointerOperand(); |
| 260 | } |
| 261 | if (auto *call = dyn_cast<CallInst>(value)) { |
| 262 | // If the call is a call to a @clspv.resource.var.* function, then try |
| 263 | // to merge it, assuming the given number of GEP zero-indices so far. |
| 264 | if (call->getCalledFunction()->getName().startswith( |
| 265 | "clspv.resource.var.")) { |
| 266 | const auto set = uint32_t( |
| 267 | dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue()); |
| 268 | const auto binding = uint32_t( |
| 269 | dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue()); |
| 270 | if (!merge_param_info({call->getCalledFunction(), set, binding, |
| 271 | num_gep_zeroes, call})) { |
| 272 | return false; |
| 273 | } |
| 274 | } else { |
| 275 | // A call but not to a resource access builtin function. |
| 276 | return false; |
| 277 | } |
| 278 | } else { |
| 279 | // Not a call. |
| 280 | return false; |
| 281 | } |
| 282 | } else { |
| 283 | // There isn't enough commonality. Bail out without changing anything. |
| 284 | return false; |
| 285 | } |
| 286 | } |
| 287 | if (ShowDRA) { |
| 288 | if (seen_one) { |
| 289 | outs() << "DRA: Rewrite " << fn->getName() << " arg " << arg_index << " " |
| 290 | << arg.getName() << ": " << common.var_fn->getName() << " (" |
| 291 | << common.set << "," << common.binding |
| 292 | << ") zeroes: " << common.num_gep_zeroes << "\n"; |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | // Now rewrite the argument, using the info in |common|. |
| 297 | |
| 298 | Changed = true; |
| 299 | IRBuilder<> Builder(fn->getParent()->getContext()); |
| 300 | auto *zero = Builder.getInt32(0); |
| 301 | Builder.SetInsertPoint(fn->getEntryBlock().getFirstNonPHI()); |
| 302 | |
| 303 | // Create the call. |
| 304 | SmallVector<Value *, 8> args(common.sample_call->arg_begin(), |
| 305 | common.sample_call->arg_end()); |
| 306 | Value *replacement = Builder.CreateCall(common.var_fn, args); |
| 307 | if (ShowDRA) { |
| 308 | outs() << "DRA: Replace: call " << *replacement << "\n"; |
| 309 | } |
| 310 | if (common.num_gep_zeroes) { |
| 311 | SmallVector<Value *, 3> zeroes; |
| 312 | for (unsigned i = 0; i < common.num_gep_zeroes; i++) { |
| 313 | zeroes.push_back(zero); |
| 314 | } |
| 315 | replacement = Builder.CreateGEP(replacement, zeroes); |
| 316 | if (ShowDRA) { |
| 317 | outs() << "DRA: Replace: gep " << *replacement << "\n"; |
| 318 | } |
| 319 | } |
| 320 | arg.replaceAllUsesWith(replacement); |
| 321 | |
| 322 | return Changed; |
| 323 | } |
| 324 | |
| 325 | } // namespace |