blob: 6f77d0b3e37045711b262684a7deb50127f4542b [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -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 Neto62653202017-10-16 19:05:18 -040015#include <math.h>
16#include <string>
17#include <tuple>
18
Kévin Petit9d1a9d12019-03-25 15:23:46 +000019#include "llvm/ADT/StringSwitch.h"
David Neto118188e2018-08-24 11:27:54 -040020#include "llvm/IR/Constants.h"
David Neto118188e2018-08-24 11:27:54 -040021#include "llvm/IR/IRBuilder.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040022#include "llvm/IR/Instructions.h"
David Neto118188e2018-08-24 11:27:54 -040023#include "llvm/IR/Module.h"
Kévin Petitf5b78a22018-10-25 14:32:17 +000024#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040025#include "llvm/Pass.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040029
David Neto118188e2018-08-24 11:27:54 -040030#include "spirv/1.0/spirv.hpp"
David Neto22f144c2017-06-12 14:26:21 -040031
alan-baker931d18a2019-12-12 08:21:32 -050032#include "clspv/AddressSpace.h"
James Pricec05f6052020-01-14 13:37:20 -050033#include "clspv/DescriptorMap.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040034#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070035
alan-baker931d18a2019-12-12 08:21:32 -050036#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040037#include "Passes.h"
38#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050039#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040040
David Neto22f144c2017-06-12 14:26:21 -040041using namespace llvm;
42
43#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
44
45namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000046
47struct ArgTypeInfo {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040048 enum class SignedNess { None, Unsigned, Signed };
Kévin Petit8a560882019-03-21 15:24:34 +000049 SignedNess signedness;
50};
51
52struct FunctionInfo {
Kévin Petit9d1a9d12019-03-25 15:23:46 +000053 StringRef name;
Kévin Petit8a560882019-03-21 15:24:34 +000054 std::vector<ArgTypeInfo> argTypeInfos;
Kévin Petit8a560882019-03-21 15:24:34 +000055
Kévin Petit91bc72e2019-04-08 15:17:46 +010056 bool isArgSigned(size_t arg) const {
57 assert(argTypeInfos.size() > arg);
58 return argTypeInfos[arg].signedness == ArgTypeInfo::SignedNess::Signed;
Kévin Petit8a560882019-03-21 15:24:34 +000059 }
60
Kévin Petit91bc72e2019-04-08 15:17:46 +010061 static FunctionInfo getFromMangledName(StringRef name) {
62 FunctionInfo fi;
63 if (!getFromMangledNameCheck(name, &fi)) {
64 llvm_unreachable("Can't parse mangled function name!");
Kévin Petit8a560882019-03-21 15:24:34 +000065 }
Kévin Petit91bc72e2019-04-08 15:17:46 +010066 return fi;
67 }
Kévin Petit8a560882019-03-21 15:24:34 +000068
Kévin Petit91bc72e2019-04-08 15:17:46 +010069 static bool getFromMangledNameCheck(StringRef name, FunctionInfo *finfo) {
70 if (!name.consume_front("_Z")) {
71 return false;
72 }
73 size_t nameLen;
74 if (name.consumeInteger(10, nameLen)) {
Kévin Petit8a560882019-03-21 15:24:34 +000075 return false;
76 }
77
Kévin Petit91bc72e2019-04-08 15:17:46 +010078 finfo->name = name.take_front(nameLen);
79 name = name.drop_front(nameLen);
Kévin Petit8a560882019-03-21 15:24:34 +000080
Kévin Petit91bc72e2019-04-08 15:17:46 +010081 ArgTypeInfo prev_ti;
Kévin Petit8a560882019-03-21 15:24:34 +000082
Kévin Petit91bc72e2019-04-08 15:17:46 +010083 while (name.size() != 0) {
84
85 ArgTypeInfo ti;
86
87 // Try parsing a vector prefix
88 if (name.consume_front("Dv")) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040089 int numElems;
90 if (name.consumeInteger(10, numElems)) {
91 return false;
92 }
Kévin Petit91bc72e2019-04-08 15:17:46 +010093
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040094 if (!name.consume_front("_")) {
95 return false;
96 }
Kévin Petit91bc72e2019-04-08 15:17:46 +010097 }
98
99 // Parse the base type
alan-baker4092cc52020-01-15 16:42:57 -0500100 if (name.consume_front("Dh")) {
Kévin Petit91bc72e2019-04-08 15:17:46 +0100101 ti.signedness = ArgTypeInfo::SignedNess::None;
alan-baker4092cc52020-01-15 16:42:57 -0500102 } else {
103 char typeCode = name.front();
104 name = name.drop_front(1);
105 switch (typeCode) {
106 case 'c': // char
107 case 'a': // signed char
108 case 's': // short
109 case 'i': // int
110 case 'l': // long
111 ti.signedness = ArgTypeInfo::SignedNess::Signed;
112 break;
113 case 'h': // unsigned char
114 case 't': // unsigned short
115 case 'j': // unsigned int
116 case 'm': // unsigned long
117 ti.signedness = ArgTypeInfo::SignedNess::Unsigned;
118 break;
119 case 'f':
120 ti.signedness = ArgTypeInfo::SignedNess::None;
121 break;
122 case 'S':
123 ti = prev_ti;
124 if (!name.consume_front("_")) {
125 return false;
126 }
127 break;
128 default:
Kévin Petit91bc72e2019-04-08 15:17:46 +0100129 return false;
130 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100131 }
132
133 finfo->argTypeInfos.push_back(ti);
134
135 prev_ti = ti;
136 }
137
138 return true;
139 };
Kévin Petit8a560882019-03-21 15:24:34 +0000140};
141
David Neto22f144c2017-06-12 14:26:21 -0400142uint32_t clz(uint32_t v) {
143 uint32_t r;
144 uint32_t shift;
145
146 r = (v > 0xFFFF) << 4;
147 v >>= r;
148 shift = (v > 0xFF) << 3;
149 v >>= shift;
150 r |= shift;
151 shift = (v > 0xF) << 2;
152 v >>= shift;
153 r |= shift;
154 shift = (v > 0x3) << 1;
155 v >>= shift;
156 r |= shift;
157 r |= (v >> 1);
158
159 return r;
160}
161
162Type *getBoolOrBoolVectorTy(LLVMContext &C, unsigned elements) {
163 if (1 == elements) {
164 return Type::getInt1Ty(C);
165 } else {
166 return VectorType::get(Type::getInt1Ty(C), elements);
167 }
168}
169
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100170Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
171 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
172 if (Ty->isVectorTy()) {
173 IntTy = VectorType::get(IntTy, Ty->getVectorNumElements());
174 }
175 return IntTy;
176}
177
David Neto22f144c2017-06-12 14:26:21 -0400178struct ReplaceOpenCLBuiltinPass final : public ModulePass {
179 static char ID;
180 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
181
182 bool runOnModule(Module &M) override;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000183 bool replaceAbs(Module &M);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100184 bool replaceAbsDiff(Module &M);
Kévin Petit8c1be282019-04-02 19:34:25 +0100185 bool replaceCopysign(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400186 bool replaceRecip(Module &M);
187 bool replaceDivide(Module &M);
Kévin Petit1329a002019-06-15 05:54:05 +0100188 bool replaceDot(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400189 bool replaceExp10(Module &M);
Kévin Petit0644a9c2019-06-20 21:08:46 +0100190 bool replaceFmod(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400191 bool replaceLog10(Module &M);
192 bool replaceBarrier(Module &M);
193 bool replaceMemFence(Module &M);
194 bool replaceRelational(Module &M);
195 bool replaceIsInfAndIsNan(Module &M);
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100196 bool replaceIsFinite(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400197 bool replaceAllAndAny(Module &M);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000198 bool replaceUpsample(Module &M);
Kévin Petitd44eef52019-03-08 13:22:14 +0000199 bool replaceRotate(Module &M);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000200 bool replaceConvert(Module &M);
Kévin Petit8a560882019-03-21 15:24:34 +0000201 bool replaceMulHiMadHi(Module &M);
Kévin Petitf5b78a22018-10-25 14:32:17 +0000202 bool replaceSelect(Module &M);
Kévin Petite7d0cce2018-10-31 12:38:56 +0000203 bool replaceBitSelect(Module &M);
Kévin Petit6b0a9532018-10-30 20:00:39 +0000204 bool replaceStepSmoothStep(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400205 bool replaceSignbit(Module &M);
206 bool replaceMadandMad24andMul24(Module &M);
207 bool replaceVloadHalf(Module &M);
208 bool replaceVloadHalf2(Module &M);
209 bool replaceVloadHalf4(Module &M);
David Neto6ad93232018-06-07 15:42:58 -0700210 bool replaceClspvVloadaHalf2(Module &M);
211 bool replaceClspvVloadaHalf4(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400212 bool replaceVstoreHalf(Module &M);
213 bool replaceVstoreHalf2(Module &M);
214 bool replaceVstoreHalf4(Module &M);
alan-bakerf7e17cb2020-01-02 07:29:59 -0500215 bool replaceHalfReadImage(Module &M);
216 bool replaceHalfWriteImage(Module &M);
alan-baker931d18a2019-12-12 08:21:32 -0500217 bool replaceUnsampledReadImage(Module &M);
Kévin Petit06517a12019-12-09 19:40:31 +0000218 bool replaceSampledReadImageWithIntCoords(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400219 bool replaceAtomics(Module &M);
220 bool replaceCross(Module &M);
David Neto62653202017-10-16 19:05:18 -0400221 bool replaceFract(Module &M);
Derek Chowcfd368b2017-10-19 20:58:45 -0700222 bool replaceVload(Module &M);
223 bool replaceVstore(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400224};
Kévin Petit91bc72e2019-04-08 15:17:46 +0100225} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400226
227char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400228INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
229 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400230
231namespace clspv {
232ModulePass *createReplaceOpenCLBuiltinPass() {
233 return new ReplaceOpenCLBuiltinPass();
234}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400235} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400236
237bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
238 bool Changed = false;
239
Kévin Petit2444e9b2018-11-09 14:14:37 +0000240 Changed |= replaceAbs(M);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100241 Changed |= replaceAbsDiff(M);
Kévin Petit8c1be282019-04-02 19:34:25 +0100242 Changed |= replaceCopysign(M);
David Neto22f144c2017-06-12 14:26:21 -0400243 Changed |= replaceRecip(M);
244 Changed |= replaceDivide(M);
Kévin Petit1329a002019-06-15 05:54:05 +0100245 Changed |= replaceDot(M);
David Neto22f144c2017-06-12 14:26:21 -0400246 Changed |= replaceExp10(M);
Kévin Petit0644a9c2019-06-20 21:08:46 +0100247 Changed |= replaceFmod(M);
David Neto22f144c2017-06-12 14:26:21 -0400248 Changed |= replaceLog10(M);
249 Changed |= replaceBarrier(M);
250 Changed |= replaceMemFence(M);
251 Changed |= replaceRelational(M);
252 Changed |= replaceIsInfAndIsNan(M);
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100253 Changed |= replaceIsFinite(M);
David Neto22f144c2017-06-12 14:26:21 -0400254 Changed |= replaceAllAndAny(M);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000255 Changed |= replaceUpsample(M);
Kévin Petitd44eef52019-03-08 13:22:14 +0000256 Changed |= replaceRotate(M);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000257 Changed |= replaceConvert(M);
Kévin Petit8a560882019-03-21 15:24:34 +0000258 Changed |= replaceMulHiMadHi(M);
Kévin Petitf5b78a22018-10-25 14:32:17 +0000259 Changed |= replaceSelect(M);
Kévin Petite7d0cce2018-10-31 12:38:56 +0000260 Changed |= replaceBitSelect(M);
Kévin Petit6b0a9532018-10-30 20:00:39 +0000261 Changed |= replaceStepSmoothStep(M);
David Neto22f144c2017-06-12 14:26:21 -0400262 Changed |= replaceSignbit(M);
263 Changed |= replaceMadandMad24andMul24(M);
264 Changed |= replaceVloadHalf(M);
265 Changed |= replaceVloadHalf2(M);
266 Changed |= replaceVloadHalf4(M);
David Neto6ad93232018-06-07 15:42:58 -0700267 Changed |= replaceClspvVloadaHalf2(M);
268 Changed |= replaceClspvVloadaHalf4(M);
David Neto22f144c2017-06-12 14:26:21 -0400269 Changed |= replaceVstoreHalf(M);
270 Changed |= replaceVstoreHalf2(M);
271 Changed |= replaceVstoreHalf4(M);
alan-bakerf7e17cb2020-01-02 07:29:59 -0500272 // Replace the half image builtins before handling other image builtins.
273 Changed |= replaceHalfReadImage(M);
274 Changed |= replaceHalfWriteImage(M);
Kévin Petit06517a12019-12-09 19:40:31 +0000275 Changed |= replaceSampledReadImageWithIntCoords(M);
David Neto22f144c2017-06-12 14:26:21 -0400276 Changed |= replaceAtomics(M);
277 Changed |= replaceCross(M);
David Neto62653202017-10-16 19:05:18 -0400278 Changed |= replaceFract(M);
Derek Chowcfd368b2017-10-19 20:58:45 -0700279 Changed |= replaceVload(M);
280 Changed |= replaceVstore(M);
David Neto22f144c2017-06-12 14:26:21 -0400281
282 return Changed;
283}
284
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400285bool replaceCallsWithValue(Module &M, std::vector<const char *> Names,
286 std::function<Value *(CallInst *)> Replacer) {
Kévin Petit2444e9b2018-11-09 14:14:37 +0000287
Kévin Petite8edce32019-04-10 14:23:32 +0100288 bool Changed = false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000289
290 for (auto Name : Names) {
291 // If we find a function with the matching name.
292 if (auto F = M.getFunction(Name)) {
293 SmallVector<Instruction *, 4> ToRemoves;
294
295 // Walk the users of the function.
296 for (auto &U : F->uses()) {
297 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
Kévin Petit2444e9b2018-11-09 14:14:37 +0000298
Kévin Petite8edce32019-04-10 14:23:32 +0100299 auto NewValue = Replacer(CI);
300
301 if (NewValue != nullptr) {
302 CI->replaceAllUsesWith(NewValue);
303 }
Kévin Petit2444e9b2018-11-09 14:14:37 +0000304
305 // Lastly, remember to remove the user.
306 ToRemoves.push_back(CI);
307 }
308 }
309
310 Changed = !ToRemoves.empty();
311
312 // And cleanup the calls we don't use anymore.
313 for (auto V : ToRemoves) {
314 V->eraseFromParent();
315 }
316
317 // And remove the function we don't need either too.
318 F->eraseFromParent();
319 }
320 }
321
322 return Changed;
323}
324
Kévin Petite8edce32019-04-10 14:23:32 +0100325bool ReplaceOpenCLBuiltinPass::replaceAbs(Module &M) {
Kévin Petit91bc72e2019-04-08 15:17:46 +0100326
Kévin Petite8edce32019-04-10 14:23:32 +0100327 std::vector<const char *> Names = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400328 "_Z3absh", "_Z3absDv2_h", "_Z3absDv3_h", "_Z3absDv4_h",
329 "_Z3abst", "_Z3absDv2_t", "_Z3absDv3_t", "_Z3absDv4_t",
330 "_Z3absj", "_Z3absDv2_j", "_Z3absDv3_j", "_Z3absDv4_j",
331 "_Z3absm", "_Z3absDv2_m", "_Z3absDv3_m", "_Z3absDv4_m",
Kévin Petite8edce32019-04-10 14:23:32 +0100332 };
333
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400334 return replaceCallsWithValue(M, Names,
335 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100336}
337
338bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Module &M) {
339
340 std::vector<const char *> Names = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400341 "_Z8abs_diffcc", "_Z8abs_diffDv2_cS_", "_Z8abs_diffDv3_cS_",
342 "_Z8abs_diffDv4_cS_", "_Z8abs_diffhh", "_Z8abs_diffDv2_hS_",
343 "_Z8abs_diffDv3_hS_", "_Z8abs_diffDv4_hS_", "_Z8abs_diffss",
344 "_Z8abs_diffDv2_sS_", "_Z8abs_diffDv3_sS_", "_Z8abs_diffDv4_sS_",
345 "_Z8abs_difftt", "_Z8abs_diffDv2_tS_", "_Z8abs_diffDv3_tS_",
346 "_Z8abs_diffDv4_tS_", "_Z8abs_diffii", "_Z8abs_diffDv2_iS_",
347 "_Z8abs_diffDv3_iS_", "_Z8abs_diffDv4_iS_", "_Z8abs_diffjj",
348 "_Z8abs_diffDv2_jS_", "_Z8abs_diffDv3_jS_", "_Z8abs_diffDv4_jS_",
349 "_Z8abs_diffll", "_Z8abs_diffDv2_lS_", "_Z8abs_diffDv3_lS_",
350 "_Z8abs_diffDv4_lS_", "_Z8abs_diffmm", "_Z8abs_diffDv2_mS_",
351 "_Z8abs_diffDv3_mS_", "_Z8abs_diffDv4_mS_",
Kévin Petit91bc72e2019-04-08 15:17:46 +0100352 };
353
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400354 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100355 auto XValue = CI->getOperand(0);
356 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100357
Kévin Petite8edce32019-04-10 14:23:32 +0100358 IRBuilder<> Builder(CI);
359 auto XmY = Builder.CreateSub(XValue, YValue);
360 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100361
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400362 Value *Cmp;
Kévin Petite8edce32019-04-10 14:23:32 +0100363 auto F = CI->getCalledFunction();
364 auto finfo = FunctionInfo::getFromMangledName(F->getName());
365 if (finfo.isArgSigned(0)) {
366 Cmp = Builder.CreateICmpSGT(YValue, XValue);
367 } else {
368 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100369 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100370
Kévin Petite8edce32019-04-10 14:23:32 +0100371 return Builder.CreateSelect(Cmp, YmX, XmY);
372 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100373}
374
Kévin Petit8c1be282019-04-02 19:34:25 +0100375bool ReplaceOpenCLBuiltinPass::replaceCopysign(Module &M) {
Kévin Petit8c1be282019-04-02 19:34:25 +0100376
Kévin Petite8edce32019-04-10 14:23:32 +0100377 std::vector<const char *> Names = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400378 "_Z8copysignff",
379 "_Z8copysignDv2_fS_",
380 "_Z8copysignDv3_fS_",
381 "_Z8copysignDv4_fS_",
Kévin Petit8c1be282019-04-02 19:34:25 +0100382 };
383
Kévin Petite8edce32019-04-10 14:23:32 +0100384 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
385 auto XValue = CI->getOperand(0);
386 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100387
Kévin Petite8edce32019-04-10 14:23:32 +0100388 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100389
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400390 Type *IntTy = Type::getIntNTy(M.getContext(), Ty->getScalarSizeInBits());
Kévin Petite8edce32019-04-10 14:23:32 +0100391 if (Ty->isVectorTy()) {
392 IntTy = VectorType::get(IntTy, Ty->getVectorNumElements());
Kévin Petit8c1be282019-04-02 19:34:25 +0100393 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100394
Kévin Petite8edce32019-04-10 14:23:32 +0100395 // Return X with the sign of Y
396
397 // Sign bit masks
398 auto SignBit = IntTy->getScalarSizeInBits() - 1;
399 auto SignBitMask = 1 << SignBit;
400 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
401 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
402
403 IRBuilder<> Builder(CI);
404
405 // Extract sign of Y
406 auto YInt = Builder.CreateBitCast(YValue, IntTy);
407 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
408
409 // Clear sign bit in X
410 auto XInt = Builder.CreateBitCast(XValue, IntTy);
411 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
412
413 // Insert sign bit of Y into X
414 auto NewXInt = Builder.CreateOr(XInt, YSign);
415
416 // And cast back to floating-point
417 return Builder.CreateBitCast(NewXInt, Ty);
418 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100419}
420
David Neto22f144c2017-06-12 14:26:21 -0400421bool ReplaceOpenCLBuiltinPass::replaceRecip(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -0400422
Kévin Petite8edce32019-04-10 14:23:32 +0100423 std::vector<const char *> Names = {
David Neto22f144c2017-06-12 14:26:21 -0400424 "_Z10half_recipf", "_Z12native_recipf", "_Z10half_recipDv2_f",
425 "_Z12native_recipDv2_f", "_Z10half_recipDv3_f", "_Z12native_recipDv3_f",
426 "_Z10half_recipDv4_f", "_Z12native_recipDv4_f",
427 };
428
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400429 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100430 // Recip has one arg.
431 auto Arg = CI->getOperand(0);
432 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
433 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
434 });
David Neto22f144c2017-06-12 14:26:21 -0400435}
436
437bool ReplaceOpenCLBuiltinPass::replaceDivide(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -0400438
Kévin Petite8edce32019-04-10 14:23:32 +0100439 std::vector<const char *> Names = {
David Neto22f144c2017-06-12 14:26:21 -0400440 "_Z11half_divideff", "_Z13native_divideff",
441 "_Z11half_divideDv2_fS_", "_Z13native_divideDv2_fS_",
442 "_Z11half_divideDv3_fS_", "_Z13native_divideDv3_fS_",
443 "_Z11half_divideDv4_fS_", "_Z13native_divideDv4_fS_",
444 };
445
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400446 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100447 auto Op0 = CI->getOperand(0);
448 auto Op1 = CI->getOperand(1);
449 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
450 });
David Neto22f144c2017-06-12 14:26:21 -0400451}
452
Kévin Petit1329a002019-06-15 05:54:05 +0100453bool ReplaceOpenCLBuiltinPass::replaceDot(Module &M) {
454
455 std::vector<const char *> Names = {
James Price71403812020-03-16 08:18:47 -0400456 "_Z3dotff", "_Z3dotDv2_fS_", "_Z3dotDv3_fS_", "_Z3dotDv4_fS_",
457 "_Z3dotDhDh", "_Z3dotDv2_DhS_", "_Z3dotDv3_DhS_", "_Z3dotDv4_DhS_",
Kévin Petit1329a002019-06-15 05:54:05 +0100458 };
459
460 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
461 auto Op0 = CI->getOperand(0);
462 auto Op1 = CI->getOperand(1);
463
464 Value *V;
465 if (Op0->getType()->isVectorTy()) {
466 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
467 CI->getType(), {Op0, Op1});
468 } else {
469 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
470 }
471
472 return V;
473 });
474}
475
David Neto22f144c2017-06-12 14:26:21 -0400476bool ReplaceOpenCLBuiltinPass::replaceExp10(Module &M) {
477 bool Changed = false;
478
479 const std::map<const char *, const char *> Map = {
480 {"_Z5exp10f", "_Z3expf"},
481 {"_Z10half_exp10f", "_Z8half_expf"},
482 {"_Z12native_exp10f", "_Z10native_expf"},
483 {"_Z5exp10Dv2_f", "_Z3expDv2_f"},
484 {"_Z10half_exp10Dv2_f", "_Z8half_expDv2_f"},
485 {"_Z12native_exp10Dv2_f", "_Z10native_expDv2_f"},
486 {"_Z5exp10Dv3_f", "_Z3expDv3_f"},
487 {"_Z10half_exp10Dv3_f", "_Z8half_expDv3_f"},
488 {"_Z12native_exp10Dv3_f", "_Z10native_expDv3_f"},
489 {"_Z5exp10Dv4_f", "_Z3expDv4_f"},
490 {"_Z10half_exp10Dv4_f", "_Z8half_expDv4_f"},
491 {"_Z12native_exp10Dv4_f", "_Z10native_expDv4_f"}};
492
493 for (auto Pair : Map) {
494 // If we find a function with the matching name.
495 if (auto F = M.getFunction(Pair.first)) {
496 SmallVector<Instruction *, 4> ToRemoves;
497
498 // Walk the users of the function.
499 for (auto &U : F->uses()) {
500 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
501 auto NewF = M.getOrInsertFunction(Pair.second, F->getFunctionType());
502
503 auto Arg = CI->getOperand(0);
504
505 // Constant of the natural log of 10 (ln(10)).
506 const double Ln10 =
507 2.302585092994045684017991454684364207601101488628772976033;
508
509 auto Mul = BinaryOperator::Create(
510 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "",
511 CI);
512
513 auto NewCI = CallInst::Create(NewF, Mul, "", CI);
514
515 CI->replaceAllUsesWith(NewCI);
516
517 // Lastly, remember to remove the user.
518 ToRemoves.push_back(CI);
519 }
520 }
521
522 Changed = !ToRemoves.empty();
523
524 // And cleanup the calls we don't use anymore.
525 for (auto V : ToRemoves) {
526 V->eraseFromParent();
527 }
528
529 // And remove the function we don't need either too.
530 F->eraseFromParent();
531 }
532 }
533
534 return Changed;
535}
536
Kévin Petit0644a9c2019-06-20 21:08:46 +0100537bool ReplaceOpenCLBuiltinPass::replaceFmod(Module &M) {
538
539 std::vector<const char *> Names = {
540 "_Z4fmodff",
541 "_Z4fmodDv2_fS_",
542 "_Z4fmodDv3_fS_",
543 "_Z4fmodDv4_fS_",
544 };
545
546 // OpenCL fmod(x,y) is x - y * trunc(x/y)
547 // The sign for a non-zero result is taken from x.
548 // (Try an example.)
549 // So translate to FRem
550 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
551 auto Op0 = CI->getOperand(0);
552 auto Op1 = CI->getOperand(1);
553 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
554 });
555}
556
David Neto22f144c2017-06-12 14:26:21 -0400557bool ReplaceOpenCLBuiltinPass::replaceLog10(Module &M) {
558 bool Changed = false;
559
560 const std::map<const char *, const char *> Map = {
561 {"_Z5log10f", "_Z3logf"},
562 {"_Z10half_log10f", "_Z8half_logf"},
563 {"_Z12native_log10f", "_Z10native_logf"},
564 {"_Z5log10Dv2_f", "_Z3logDv2_f"},
565 {"_Z10half_log10Dv2_f", "_Z8half_logDv2_f"},
566 {"_Z12native_log10Dv2_f", "_Z10native_logDv2_f"},
567 {"_Z5log10Dv3_f", "_Z3logDv3_f"},
568 {"_Z10half_log10Dv3_f", "_Z8half_logDv3_f"},
569 {"_Z12native_log10Dv3_f", "_Z10native_logDv3_f"},
570 {"_Z5log10Dv4_f", "_Z3logDv4_f"},
571 {"_Z10half_log10Dv4_f", "_Z8half_logDv4_f"},
572 {"_Z12native_log10Dv4_f", "_Z10native_logDv4_f"}};
573
574 for (auto Pair : Map) {
575 // If we find a function with the matching name.
576 if (auto F = M.getFunction(Pair.first)) {
577 SmallVector<Instruction *, 4> ToRemoves;
578
579 // Walk the users of the function.
580 for (auto &U : F->uses()) {
581 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
582 auto NewF = M.getOrInsertFunction(Pair.second, F->getFunctionType());
583
584 auto Arg = CI->getOperand(0);
585
586 // Constant of the reciprocal of the natural log of 10 (ln(10)).
587 const double Ln10 =
588 0.434294481903251827651128918916605082294397005803666566114;
589
590 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
591
592 auto Mul = BinaryOperator::Create(
593 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), NewCI,
594 "", CI);
595
596 CI->replaceAllUsesWith(Mul);
597
598 // Lastly, remember to remove the user.
599 ToRemoves.push_back(CI);
600 }
601 }
602
603 Changed = !ToRemoves.empty();
604
605 // And cleanup the calls we don't use anymore.
606 for (auto V : ToRemoves) {
607 V->eraseFromParent();
608 }
609
610 // And remove the function we don't need either too.
611 F->eraseFromParent();
612 }
613 }
614
615 return Changed;
616}
617
618bool ReplaceOpenCLBuiltinPass::replaceBarrier(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -0400619
620 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
621
alan-bakerb60b1fc2019-12-13 19:09:38 -0500622 const std::vector<const char *> Names = {"_Z7barrierj",
623 // OpenCL 2.0 alias for barrier.
624 "_Z18work_group_barrierj"};
David Neto22f144c2017-06-12 14:26:21 -0400625
Kévin Petitc4643922019-06-17 19:32:05 +0100626 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
627 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400628
Kévin Petitc4643922019-06-17 19:32:05 +0100629 // We need to map the OpenCL constants to the SPIR-V equivalents.
630 const auto LocalMemFence =
631 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
632 const auto GlobalMemFence =
633 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
634 const auto ConstantSequentiallyConsistent = ConstantInt::get(
635 Arg->getType(), spv::MemorySemanticsSequentiallyConsistentMask);
636 const auto ConstantScopeDevice =
637 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
638 const auto ConstantScopeWorkgroup =
639 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400640
Kévin Petitc4643922019-06-17 19:32:05 +0100641 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
642 const auto LocalMemFenceMask =
643 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
644 const auto WorkgroupShiftAmount =
645 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
646 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
647 Instruction::Shl, LocalMemFenceMask,
648 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400649
Kévin Petitc4643922019-06-17 19:32:05 +0100650 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
651 const auto GlobalMemFenceMask =
652 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
653 const auto UniformShiftAmount =
654 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
655 const auto MemorySemanticsUniform = BinaryOperator::Create(
656 Instruction::Shl, GlobalMemFenceMask,
657 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400658
Kévin Petitc4643922019-06-17 19:32:05 +0100659 // And combine the above together, also adding in
660 // MemorySemanticsSequentiallyConsistentMask.
661 auto MemorySemantics =
662 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
663 ConstantSequentiallyConsistent, "", CI);
664 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
665 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400666
Kévin Petitc4643922019-06-17 19:32:05 +0100667 // For Memory Scope if we used CLK_GLOBAL_MEM_FENCE, we need to use
668 // Device Scope, otherwise Workgroup Scope.
669 const auto Cmp =
670 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, GlobalMemFenceMask,
671 GlobalMemFence, "", CI);
672 const auto MemoryScope = SelectInst::Create(Cmp, ConstantScopeDevice,
673 ConstantScopeWorkgroup, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400674
Kévin Petitc4643922019-06-17 19:32:05 +0100675 // Lastly, the Execution Scope is always Workgroup Scope.
676 const auto ExecutionScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400677
Kévin Petitc4643922019-06-17 19:32:05 +0100678 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
679 {Attribute::NoDuplicate}, CI->getType(),
680 {ExecutionScope, MemoryScope, MemorySemantics});
681 });
David Neto22f144c2017-06-12 14:26:21 -0400682}
683
684bool ReplaceOpenCLBuiltinPass::replaceMemFence(Module &M) {
685 bool Changed = false;
686
687 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
688
Kévin Petitc4643922019-06-17 19:32:05 +0100689 using Tuple = std::tuple<spv::Op, unsigned>;
Neil Henning39672102017-09-29 14:33:13 +0100690 const std::map<const char *, Tuple> Map = {
Kévin Petitc4643922019-06-17 19:32:05 +0100691 {"_Z9mem_fencej", Tuple(spv::OpMemoryBarrier,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400692 spv::MemorySemanticsSequentiallyConsistentMask)},
Neil Henning39672102017-09-29 14:33:13 +0100693 {"_Z14read_mem_fencej",
Kévin Petitc4643922019-06-17 19:32:05 +0100694 Tuple(spv::OpMemoryBarrier, spv::MemorySemanticsAcquireMask)},
Neil Henning39672102017-09-29 14:33:13 +0100695 {"_Z15write_mem_fencej",
Kévin Petitc4643922019-06-17 19:32:05 +0100696 Tuple(spv::OpMemoryBarrier, spv::MemorySemanticsReleaseMask)}};
David Neto22f144c2017-06-12 14:26:21 -0400697
698 for (auto Pair : Map) {
699 // If we find a function with the matching name.
700 if (auto F = M.getFunction(Pair.first)) {
701 SmallVector<Instruction *, 4> ToRemoves;
702
703 // Walk the users of the function.
704 for (auto &U : F->uses()) {
705 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
David Neto22f144c2017-06-12 14:26:21 -0400706
707 auto Arg = CI->getOperand(0);
708
709 // We need to map the OpenCL constants to the SPIR-V equivalents.
710 const auto LocalMemFence =
711 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
712 const auto GlobalMemFence =
713 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
714 const auto ConstantMemorySemantics =
Neil Henning39672102017-09-29 14:33:13 +0100715 ConstantInt::get(Arg->getType(), std::get<1>(Pair.second));
David Neto22f144c2017-06-12 14:26:21 -0400716 const auto ConstantScopeDevice =
717 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
718
719 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
720 const auto LocalMemFenceMask = BinaryOperator::Create(
721 Instruction::And, LocalMemFence, Arg, "", CI);
722 const auto WorkgroupShiftAmount =
723 clz(spv::MemorySemanticsWorkgroupMemoryMask) -
724 clz(CLK_LOCAL_MEM_FENCE);
725 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
726 Instruction::Shl, LocalMemFenceMask,
727 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
728
729 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
730 const auto GlobalMemFenceMask = BinaryOperator::Create(
731 Instruction::And, GlobalMemFence, Arg, "", CI);
732 const auto UniformShiftAmount =
733 clz(spv::MemorySemanticsUniformMemoryMask) -
734 clz(CLK_GLOBAL_MEM_FENCE);
735 const auto MemorySemanticsUniform = BinaryOperator::Create(
736 Instruction::Shl, GlobalMemFenceMask,
737 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
738
739 // And combine the above together, also adding in
740 // MemorySemanticsSequentiallyConsistentMask.
741 auto MemorySemantics =
742 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
743 ConstantMemorySemantics, "", CI);
744 MemorySemantics = BinaryOperator::Create(
745 Instruction::Or, MemorySemantics, MemorySemanticsUniform, "", CI);
746
747 // Memory Scope is always device.
748 const auto MemoryScope = ConstantScopeDevice;
749
Kévin Petitc4643922019-06-17 19:32:05 +0100750 const auto SPIRVOp = std::get<0>(Pair.second);
751 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {}, CI->getType(),
752 {MemoryScope, MemorySemantics});
David Neto22f144c2017-06-12 14:26:21 -0400753
754 CI->replaceAllUsesWith(NewCI);
755
756 // Lastly, remember to remove the user.
757 ToRemoves.push_back(CI);
758 }
759 }
760
761 Changed = !ToRemoves.empty();
762
763 // And cleanup the calls we don't use anymore.
764 for (auto V : ToRemoves) {
765 V->eraseFromParent();
766 }
767
768 // And remove the function we don't need either too.
769 F->eraseFromParent();
770 }
771 }
772
773 return Changed;
774}
775
776bool ReplaceOpenCLBuiltinPass::replaceRelational(Module &M) {
777 bool Changed = false;
778
779 const std::map<const char *, std::pair<CmpInst::Predicate, int32_t>> Map = {
780 {"_Z7isequalff", {CmpInst::FCMP_OEQ, 1}},
781 {"_Z7isequalDv2_fS_", {CmpInst::FCMP_OEQ, -1}},
782 {"_Z7isequalDv3_fS_", {CmpInst::FCMP_OEQ, -1}},
783 {"_Z7isequalDv4_fS_", {CmpInst::FCMP_OEQ, -1}},
784 {"_Z9isgreaterff", {CmpInst::FCMP_OGT, 1}},
785 {"_Z9isgreaterDv2_fS_", {CmpInst::FCMP_OGT, -1}},
786 {"_Z9isgreaterDv3_fS_", {CmpInst::FCMP_OGT, -1}},
787 {"_Z9isgreaterDv4_fS_", {CmpInst::FCMP_OGT, -1}},
788 {"_Z14isgreaterequalff", {CmpInst::FCMP_OGE, 1}},
789 {"_Z14isgreaterequalDv2_fS_", {CmpInst::FCMP_OGE, -1}},
790 {"_Z14isgreaterequalDv3_fS_", {CmpInst::FCMP_OGE, -1}},
791 {"_Z14isgreaterequalDv4_fS_", {CmpInst::FCMP_OGE, -1}},
792 {"_Z6islessff", {CmpInst::FCMP_OLT, 1}},
793 {"_Z6islessDv2_fS_", {CmpInst::FCMP_OLT, -1}},
794 {"_Z6islessDv3_fS_", {CmpInst::FCMP_OLT, -1}},
795 {"_Z6islessDv4_fS_", {CmpInst::FCMP_OLT, -1}},
796 {"_Z11islessequalff", {CmpInst::FCMP_OLE, 1}},
797 {"_Z11islessequalDv2_fS_", {CmpInst::FCMP_OLE, -1}},
798 {"_Z11islessequalDv3_fS_", {CmpInst::FCMP_OLE, -1}},
799 {"_Z11islessequalDv4_fS_", {CmpInst::FCMP_OLE, -1}},
800 {"_Z10isnotequalff", {CmpInst::FCMP_ONE, 1}},
801 {"_Z10isnotequalDv2_fS_", {CmpInst::FCMP_ONE, -1}},
802 {"_Z10isnotequalDv3_fS_", {CmpInst::FCMP_ONE, -1}},
803 {"_Z10isnotequalDv4_fS_", {CmpInst::FCMP_ONE, -1}},
804 };
805
806 for (auto Pair : Map) {
807 // If we find a function with the matching name.
808 if (auto F = M.getFunction(Pair.first)) {
809 SmallVector<Instruction *, 4> ToRemoves;
810
811 // Walk the users of the function.
812 for (auto &U : F->uses()) {
813 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
814 // The predicate to use in the CmpInst.
815 auto Predicate = Pair.second.first;
816
817 // The value to return for true.
818 auto TrueValue =
819 ConstantInt::getSigned(CI->getType(), Pair.second.second);
820
821 // The value to return for false.
822 auto FalseValue = Constant::getNullValue(CI->getType());
823
824 auto Arg1 = CI->getOperand(0);
825 auto Arg2 = CI->getOperand(1);
826
827 const auto Cmp =
828 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
829
830 const auto Select =
831 SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
832
833 CI->replaceAllUsesWith(Select);
834
835 // Lastly, remember to remove the user.
836 ToRemoves.push_back(CI);
837 }
838 }
839
840 Changed = !ToRemoves.empty();
841
842 // And cleanup the calls we don't use anymore.
843 for (auto V : ToRemoves) {
844 V->eraseFromParent();
845 }
846
847 // And remove the function we don't need either too.
848 F->eraseFromParent();
849 }
850 }
851
852 return Changed;
853}
854
855bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Module &M) {
856 bool Changed = false;
857
Kévin Petitff03aee2019-06-12 19:39:03 +0100858 const std::map<const char *, std::pair<spv::Op, int32_t>> Map = {
859 {"_Z5isinff", {spv::OpIsInf, 1}},
860 {"_Z5isinfDv2_f", {spv::OpIsInf, -1}},
861 {"_Z5isinfDv3_f", {spv::OpIsInf, -1}},
862 {"_Z5isinfDv4_f", {spv::OpIsInf, -1}},
863 {"_Z5isnanf", {spv::OpIsNan, 1}},
864 {"_Z5isnanDv2_f", {spv::OpIsNan, -1}},
865 {"_Z5isnanDv3_f", {spv::OpIsNan, -1}},
866 {"_Z5isnanDv4_f", {spv::OpIsNan, -1}},
David Neto22f144c2017-06-12 14:26:21 -0400867 };
868
869 for (auto Pair : Map) {
870 // If we find a function with the matching name.
871 if (auto F = M.getFunction(Pair.first)) {
872 SmallVector<Instruction *, 4> ToRemoves;
873
874 // Walk the users of the function.
875 for (auto &U : F->uses()) {
876 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
877 const auto CITy = CI->getType();
878
Kévin Petitff03aee2019-06-12 19:39:03 +0100879 auto SPIRVOp = Pair.second.first;
David Neto22f144c2017-06-12 14:26:21 -0400880
881 // The value to return for true.
882 auto TrueValue = ConstantInt::getSigned(CITy, Pair.second.second);
883
884 // The value to return for false.
885 auto FalseValue = Constant::getNullValue(CITy);
886
887 const auto CorrespondingBoolTy = getBoolOrBoolVectorTy(
888 M.getContext(),
889 CITy->isVectorTy() ? CITy->getVectorNumElements() : 1);
890
Kévin Petitff03aee2019-06-12 19:39:03 +0100891 auto NewCI =
892 clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
893 CorrespondingBoolTy, {CI->getOperand(0)});
David Neto22f144c2017-06-12 14:26:21 -0400894
895 const auto Select =
896 SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
897
898 CI->replaceAllUsesWith(Select);
899
900 // Lastly, remember to remove the user.
901 ToRemoves.push_back(CI);
902 }
903 }
904
905 Changed = !ToRemoves.empty();
906
907 // And cleanup the calls we don't use anymore.
908 for (auto V : ToRemoves) {
909 V->eraseFromParent();
910 }
911
912 // And remove the function we don't need either too.
913 F->eraseFromParent();
914 }
915 }
916
917 return Changed;
918}
919
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100920bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Module &M) {
921 std::vector<const char *> Names = {
922 "_Z8isfiniteh", "_Z8isfiniteDv2_h", "_Z8isfiniteDv3_h",
923 "_Z8isfiniteDv4_h", "_Z8isfinitef", "_Z8isfiniteDv2_f",
924 "_Z8isfiniteDv3_f", "_Z8isfiniteDv4_f", "_Z8isfinited",
925 "_Z8isfiniteDv2_d", "_Z8isfiniteDv3_d", "_Z8isfiniteDv4_d",
926 };
927
928 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
929 auto &C = M.getContext();
930 auto Val = CI->getOperand(0);
931 auto ValTy = Val->getType();
932 auto RetTy = CI->getType();
933
934 // Get a suitable integer type to represent the number
935 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
936
937 // Create Mask
938 auto ScalarSize = ValTy->getScalarSizeInBits();
939 Value *InfMask;
940 switch (ScalarSize) {
941 case 16:
942 InfMask = ConstantInt::get(IntTy, 0x7C00U);
943 break;
944 case 32:
945 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
946 break;
947 case 64:
948 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
949 break;
950 default:
951 llvm_unreachable("Unsupported floating-point type");
952 }
953
954 IRBuilder<> Builder(CI);
955
956 // Bitcast to int
957 auto ValInt = Builder.CreateBitCast(Val, IntTy);
958
959 // Mask and compare
960 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
961 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
962
963 auto RetFalse = ConstantInt::get(RetTy, 0);
964 Value *RetTrue;
965 if (ValTy->isVectorTy()) {
966 RetTrue = ConstantInt::getSigned(RetTy, -1);
967 } else {
968 RetTrue = ConstantInt::get(RetTy, 1);
969 }
970 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
971 });
972}
973
David Neto22f144c2017-06-12 14:26:21 -0400974bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Module &M) {
975 bool Changed = false;
976
Kévin Petitff03aee2019-06-12 19:39:03 +0100977 const std::map<const char *, spv::Op> Map = {
Kévin Petitfd27cca2018-10-31 13:00:17 +0000978 // all
Kévin Petitff03aee2019-06-12 19:39:03 +0100979 {"_Z3allc", spv::OpNop},
980 {"_Z3allDv2_c", spv::OpAll},
981 {"_Z3allDv3_c", spv::OpAll},
982 {"_Z3allDv4_c", spv::OpAll},
983 {"_Z3alls", spv::OpNop},
984 {"_Z3allDv2_s", spv::OpAll},
985 {"_Z3allDv3_s", spv::OpAll},
986 {"_Z3allDv4_s", spv::OpAll},
987 {"_Z3alli", spv::OpNop},
988 {"_Z3allDv2_i", spv::OpAll},
989 {"_Z3allDv3_i", spv::OpAll},
990 {"_Z3allDv4_i", spv::OpAll},
991 {"_Z3alll", spv::OpNop},
992 {"_Z3allDv2_l", spv::OpAll},
993 {"_Z3allDv3_l", spv::OpAll},
994 {"_Z3allDv4_l", spv::OpAll},
Kévin Petitfd27cca2018-10-31 13:00:17 +0000995
996 // any
Kévin Petitff03aee2019-06-12 19:39:03 +0100997 {"_Z3anyc", spv::OpNop},
998 {"_Z3anyDv2_c", spv::OpAny},
999 {"_Z3anyDv3_c", spv::OpAny},
1000 {"_Z3anyDv4_c", spv::OpAny},
1001 {"_Z3anys", spv::OpNop},
1002 {"_Z3anyDv2_s", spv::OpAny},
1003 {"_Z3anyDv3_s", spv::OpAny},
1004 {"_Z3anyDv4_s", spv::OpAny},
1005 {"_Z3anyi", spv::OpNop},
1006 {"_Z3anyDv2_i", spv::OpAny},
1007 {"_Z3anyDv3_i", spv::OpAny},
1008 {"_Z3anyDv4_i", spv::OpAny},
1009 {"_Z3anyl", spv::OpNop},
1010 {"_Z3anyDv2_l", spv::OpAny},
1011 {"_Z3anyDv3_l", spv::OpAny},
1012 {"_Z3anyDv4_l", spv::OpAny},
David Neto22f144c2017-06-12 14:26:21 -04001013 };
1014
1015 for (auto Pair : Map) {
1016 // If we find a function with the matching name.
1017 if (auto F = M.getFunction(Pair.first)) {
1018 SmallVector<Instruction *, 4> ToRemoves;
1019
1020 // Walk the users of the function.
1021 for (auto &U : F->uses()) {
1022 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
David Neto22f144c2017-06-12 14:26:21 -04001023
1024 auto Arg = CI->getOperand(0);
1025
1026 Value *V;
1027
Kévin Petitfd27cca2018-10-31 13:00:17 +00001028 // If the argument is a 32-bit int, just use a shift
1029 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1030 V = BinaryOperator::Create(Instruction::LShr, Arg,
1031 ConstantInt::get(Arg->getType(), 31), "",
1032 CI);
1033 } else {
David Neto22f144c2017-06-12 14:26:21 -04001034 // The value for zero to compare against.
1035 const auto ZeroValue = Constant::getNullValue(Arg->getType());
1036
David Neto22f144c2017-06-12 14:26:21 -04001037 // The value to return for true.
1038 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
1039
1040 // The value to return for false.
1041 const auto FalseValue = Constant::getNullValue(CI->getType());
1042
Kévin Petitfd27cca2018-10-31 13:00:17 +00001043 const auto Cmp = CmpInst::Create(
1044 Instruction::ICmp, CmpInst::ICMP_SLT, Arg, ZeroValue, "", CI);
1045
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001046 Value *SelectSource;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001047
1048 // If we have a function to call, call it!
Kévin Petitff03aee2019-06-12 19:39:03 +01001049 const auto SPIRVOp = Pair.second;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001050
Kévin Petitff03aee2019-06-12 19:39:03 +01001051 if (SPIRVOp != spv::OpNop) {
Kévin Petitfd27cca2018-10-31 13:00:17 +00001052
Kévin Petitff03aee2019-06-12 19:39:03 +01001053 const auto BoolTy = Type::getInt1Ty(M.getContext());
Kévin Petitfd27cca2018-10-31 13:00:17 +00001054
Kévin Petitff03aee2019-06-12 19:39:03 +01001055 const auto NewCI = clspv::InsertSPIRVOp(
1056 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
Kévin Petitfd27cca2018-10-31 13:00:17 +00001057 SelectSource = NewCI;
1058
1059 } else {
1060 SelectSource = Cmp;
1061 }
1062
1063 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001064 }
1065
1066 CI->replaceAllUsesWith(V);
1067
1068 // Lastly, remember to remove the user.
1069 ToRemoves.push_back(CI);
1070 }
1071 }
1072
1073 Changed = !ToRemoves.empty();
1074
1075 // And cleanup the calls we don't use anymore.
1076 for (auto V : ToRemoves) {
1077 V->eraseFromParent();
1078 }
1079
1080 // And remove the function we don't need either too.
1081 F->eraseFromParent();
1082 }
1083 }
1084
1085 return Changed;
1086}
1087
Kévin Petitbf0036c2019-03-06 13:57:10 +00001088bool ReplaceOpenCLBuiltinPass::replaceUpsample(Module &M) {
1089 bool Changed = false;
1090
1091 for (auto const &SymVal : M.getValueSymbolTable()) {
1092 // Skip symbols whose name doesn't match
1093 if (!SymVal.getKey().startswith("_Z8upsample")) {
1094 continue;
1095 }
1096 // Is there a function going by that name?
1097 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
1098
1099 SmallVector<Instruction *, 4> ToRemoves;
1100
1101 // Walk the users of the function.
1102 for (auto &U : F->uses()) {
1103 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1104
1105 // Get arguments
1106 auto HiValue = CI->getOperand(0);
1107 auto LoValue = CI->getOperand(1);
1108
1109 // Don't touch overloads that aren't in OpenCL C
1110 auto HiType = HiValue->getType();
1111 auto LoType = LoValue->getType();
1112
1113 if (HiType != LoType) {
1114 continue;
1115 }
1116
1117 if (!HiType->isIntOrIntVectorTy()) {
1118 continue;
1119 }
1120
1121 if (HiType->getScalarSizeInBits() * 2 !=
1122 CI->getType()->getScalarSizeInBits()) {
1123 continue;
1124 }
1125
1126 if ((HiType->getScalarSizeInBits() != 8) &&
1127 (HiType->getScalarSizeInBits() != 16) &&
1128 (HiType->getScalarSizeInBits() != 32)) {
1129 continue;
1130 }
1131
1132 if (HiType->isVectorTy()) {
1133 if ((HiType->getVectorNumElements() != 2) &&
1134 (HiType->getVectorNumElements() != 3) &&
1135 (HiType->getVectorNumElements() != 4) &&
1136 (HiType->getVectorNumElements() != 8) &&
1137 (HiType->getVectorNumElements() != 16)) {
1138 continue;
1139 }
1140 }
1141
1142 // Convert both operands to the result type
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001143 auto HiCast =
1144 CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1145 auto LoCast =
1146 CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001147
1148 // Shift high operand
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001149 auto ShiftAmount =
1150 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
Kévin Petitbf0036c2019-03-06 13:57:10 +00001151 auto HiShifted = BinaryOperator::Create(Instruction::Shl, HiCast,
1152 ShiftAmount, "", CI);
1153
1154 // OR both results
1155 Value *V = BinaryOperator::Create(Instruction::Or, HiShifted, LoCast,
1156 "", CI);
1157
1158 // Replace call with the expression
1159 CI->replaceAllUsesWith(V);
1160
1161 // Lastly, remember to remove the user.
1162 ToRemoves.push_back(CI);
1163 }
1164 }
1165
1166 Changed = !ToRemoves.empty();
1167
1168 // And cleanup the calls we don't use anymore.
1169 for (auto V : ToRemoves) {
1170 V->eraseFromParent();
1171 }
1172
1173 // And remove the function we don't need either too.
1174 F->eraseFromParent();
1175 }
1176 }
1177
1178 return Changed;
1179}
1180
Kévin Petitd44eef52019-03-08 13:22:14 +00001181bool ReplaceOpenCLBuiltinPass::replaceRotate(Module &M) {
1182 bool Changed = false;
1183
1184 for (auto const &SymVal : M.getValueSymbolTable()) {
1185 // Skip symbols whose name doesn't match
1186 if (!SymVal.getKey().startswith("_Z6rotate")) {
1187 continue;
1188 }
1189 // Is there a function going by that name?
1190 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
1191
1192 SmallVector<Instruction *, 4> ToRemoves;
1193
1194 // Walk the users of the function.
1195 for (auto &U : F->uses()) {
1196 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1197
1198 // Get arguments
1199 auto SrcValue = CI->getOperand(0);
1200 auto RotAmount = CI->getOperand(1);
1201
1202 // Don't touch overloads that aren't in OpenCL C
1203 auto SrcType = SrcValue->getType();
1204 auto RotType = RotAmount->getType();
1205
1206 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1207 continue;
1208 }
1209
1210 if (!SrcType->isIntOrIntVectorTy()) {
1211 continue;
1212 }
1213
1214 if ((SrcType->getScalarSizeInBits() != 8) &&
1215 (SrcType->getScalarSizeInBits() != 16) &&
1216 (SrcType->getScalarSizeInBits() != 32) &&
1217 (SrcType->getScalarSizeInBits() != 64)) {
1218 continue;
1219 }
1220
1221 if (SrcType->isVectorTy()) {
1222 if ((SrcType->getVectorNumElements() != 2) &&
1223 (SrcType->getVectorNumElements() != 3) &&
1224 (SrcType->getVectorNumElements() != 4) &&
1225 (SrcType->getVectorNumElements() != 8) &&
1226 (SrcType->getVectorNumElements() != 16)) {
1227 continue;
1228 }
1229 }
1230
1231 // The approach used is to shift the top bits down, the bottom bits up
1232 // and OR the two shifted values.
1233
1234 // The rotation amount is to be treated modulo the element size.
1235 // Since SPIR-V shift ops don't support this, let's apply the
1236 // modulo ahead of shifting. The element size is always a power of
1237 // two so we can just AND with a mask.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001238 auto ModMask =
1239 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001240 RotAmount = BinaryOperator::Create(Instruction::And, RotAmount,
1241 ModMask, "", CI);
1242
1243 // Let's calc the amount by which to shift top bits down
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001244 auto ScalarSize =
1245 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
Kévin Petitd44eef52019-03-08 13:22:14 +00001246 auto DownAmount = BinaryOperator::Create(Instruction::Sub, ScalarSize,
1247 RotAmount, "", CI);
1248
1249 // Now shift the bottom bits up and the top bits down
1250 auto LoRotated = BinaryOperator::Create(Instruction::Shl, SrcValue,
1251 RotAmount, "", CI);
1252 auto HiRotated = BinaryOperator::Create(Instruction::LShr, SrcValue,
1253 DownAmount, "", CI);
1254
1255 // Finally OR the two shifted values
1256 Value *V = BinaryOperator::Create(Instruction::Or, LoRotated,
1257 HiRotated, "", CI);
1258
1259 // Replace call with the expression
1260 CI->replaceAllUsesWith(V);
1261
1262 // Lastly, remember to remove the user.
1263 ToRemoves.push_back(CI);
1264 }
1265 }
1266
1267 Changed = !ToRemoves.empty();
1268
1269 // And cleanup the calls we don't use anymore.
1270 for (auto V : ToRemoves) {
1271 V->eraseFromParent();
1272 }
1273
1274 // And remove the function we don't need either too.
1275 F->eraseFromParent();
1276 }
1277 }
1278
1279 return Changed;
1280}
1281
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001282bool ReplaceOpenCLBuiltinPass::replaceConvert(Module &M) {
1283 bool Changed = false;
1284
1285 for (auto const &SymVal : M.getValueSymbolTable()) {
1286
1287 // Skip symbols whose name obviously doesn't match
1288 if (!SymVal.getKey().contains("convert_")) {
1289 continue;
1290 }
1291
1292 // Is there a function going by that name?
1293 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
1294
1295 // Get info from the mangled name
1296 FunctionInfo finfo;
Kévin Petit91bc72e2019-04-08 15:17:46 +01001297 bool parsed = FunctionInfo::getFromMangledNameCheck(F->getName(), &finfo);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001298
1299 // All functions of interest are handled by our mangled name parser
1300 if (!parsed) {
1301 continue;
1302 }
1303
1304 // Move on if this isn't a call to convert_
1305 if (!finfo.name.startswith("convert_")) {
1306 continue;
1307 }
1308
1309 // Extract the destination type from the function name
1310 StringRef DstTypeName = finfo.name;
1311 DstTypeName.consume_front("convert_");
1312
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001313 auto DstSignedNess =
1314 StringSwitch<ArgTypeInfo::SignedNess>(DstTypeName)
1315 .StartsWith("char", ArgTypeInfo::SignedNess::Signed)
1316 .StartsWith("short", ArgTypeInfo::SignedNess::Signed)
1317 .StartsWith("int", ArgTypeInfo::SignedNess::Signed)
1318 .StartsWith("long", ArgTypeInfo::SignedNess::Signed)
1319 .StartsWith("uchar", ArgTypeInfo::SignedNess::Unsigned)
1320 .StartsWith("ushort", ArgTypeInfo::SignedNess::Unsigned)
1321 .StartsWith("uint", ArgTypeInfo::SignedNess::Unsigned)
1322 .StartsWith("ulong", ArgTypeInfo::SignedNess::Unsigned)
1323 .Default(ArgTypeInfo::SignedNess::None);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001324
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001325 bool DstIsSigned = DstSignedNess == ArgTypeInfo::SignedNess::Signed;
Kévin Petit91bc72e2019-04-08 15:17:46 +01001326 bool SrcIsSigned = finfo.isArgSigned(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001327
1328 SmallVector<Instruction *, 4> ToRemoves;
1329
1330 // Walk the users of the function.
1331 for (auto &U : F->uses()) {
1332 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1333
1334 // Get arguments
1335 auto SrcValue = CI->getOperand(0);
1336
1337 // Don't touch overloads that aren't in OpenCL C
1338 auto SrcType = SrcValue->getType();
1339 auto DstType = CI->getType();
1340
1341 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1342 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1343 continue;
1344 }
1345
1346 if (SrcType->isVectorTy()) {
1347
1348 if (SrcType->getVectorNumElements() !=
1349 DstType->getVectorNumElements()) {
1350 continue;
1351 }
1352
1353 if ((SrcType->getVectorNumElements() != 2) &&
1354 (SrcType->getVectorNumElements() != 3) &&
1355 (SrcType->getVectorNumElements() != 4) &&
1356 (SrcType->getVectorNumElements() != 8) &&
1357 (SrcType->getVectorNumElements() != 16)) {
1358 continue;
1359 }
1360 }
1361
1362 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1363 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1364
1365 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1366 bool DstIsInt = DstType->isIntOrIntVectorTy();
1367
1368 Value *V;
alan-baker4092cc52020-01-15 16:42:57 -05001369 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1370 // Unnecessary cast operation.
1371 V = SrcValue;
1372 } else if (SrcIsFloat && DstIsFloat) {
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001373 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1374 } else if (SrcIsFloat && DstIsInt) {
1375 if (DstIsSigned) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001376 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "",
1377 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001378 } else {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001379 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "",
1380 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001381 }
1382 } else if (SrcIsInt && DstIsFloat) {
1383 if (SrcIsSigned) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001384 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "",
1385 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001386 } else {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001387 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "",
1388 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001389 }
1390 } else if (SrcIsInt && DstIsInt) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001391 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "",
1392 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001393 } else {
1394 // Not something we're supposed to handle, just move on
1395 continue;
1396 }
1397
1398 // Replace call with the expression
1399 CI->replaceAllUsesWith(V);
1400
1401 // Lastly, remember to remove the user.
1402 ToRemoves.push_back(CI);
1403 }
1404 }
1405
1406 Changed = !ToRemoves.empty();
1407
1408 // And cleanup the calls we don't use anymore.
1409 for (auto V : ToRemoves) {
1410 V->eraseFromParent();
1411 }
1412
1413 // And remove the function we don't need either too.
1414 F->eraseFromParent();
1415 }
1416 }
1417
1418 return Changed;
1419}
1420
Kévin Petit8a560882019-03-21 15:24:34 +00001421bool ReplaceOpenCLBuiltinPass::replaceMulHiMadHi(Module &M) {
1422 bool Changed = false;
1423
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001424 SmallVector<Function *, 4> FnWorklist;
Kévin Petit8a560882019-03-21 15:24:34 +00001425
Kévin Petit617a76d2019-04-04 13:54:16 +01001426 for (auto const &SymVal : M.getValueSymbolTable()) {
Kévin Petit8a560882019-03-21 15:24:34 +00001427 bool isMad = SymVal.getKey().startswith("_Z6mad_hi");
1428 bool isMul = SymVal.getKey().startswith("_Z6mul_hi");
1429
1430 // Skip symbols whose name doesn't match
1431 if (!isMad && !isMul) {
1432 continue;
1433 }
1434
1435 // Is there a function going by that name?
1436 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
Kévin Petit617a76d2019-04-04 13:54:16 +01001437 FnWorklist.push_back(F);
Kévin Petit8a560882019-03-21 15:24:34 +00001438 }
1439 }
1440
Kévin Petit617a76d2019-04-04 13:54:16 +01001441 for (auto F : FnWorklist) {
1442 SmallVector<Instruction *, 4> ToRemoves;
1443
1444 bool isMad = F->getName().startswith("_Z6mad_hi");
1445 // Walk the users of the function.
1446 for (auto &U : F->uses()) {
1447 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1448
1449 // Get arguments
1450 auto AValue = CI->getOperand(0);
1451 auto BValue = CI->getOperand(1);
1452 auto CValue = CI->getOperand(2);
1453
1454 // Don't touch overloads that aren't in OpenCL C
1455 auto AType = AValue->getType();
1456 auto BType = BValue->getType();
1457 auto CType = CValue->getType();
1458
1459 if ((AType != BType) || (CI->getType() != AType) ||
1460 (isMad && (AType != CType))) {
1461 continue;
1462 }
1463
1464 if (!AType->isIntOrIntVectorTy()) {
1465 continue;
1466 }
1467
1468 if ((AType->getScalarSizeInBits() != 8) &&
1469 (AType->getScalarSizeInBits() != 16) &&
1470 (AType->getScalarSizeInBits() != 32) &&
1471 (AType->getScalarSizeInBits() != 64)) {
1472 continue;
1473 }
1474
1475 if (AType->isVectorTy()) {
1476 if ((AType->getVectorNumElements() != 2) &&
1477 (AType->getVectorNumElements() != 3) &&
1478 (AType->getVectorNumElements() != 4) &&
1479 (AType->getVectorNumElements() != 8) &&
1480 (AType->getVectorNumElements() != 16)) {
1481 continue;
1482 }
1483 }
1484
1485 // Get infos from the mangled OpenCL built-in function name
Kévin Petit91bc72e2019-04-08 15:17:46 +01001486 auto finfo = FunctionInfo::getFromMangledName(F->getName());
Kévin Petit617a76d2019-04-04 13:54:16 +01001487
1488 // Select the appropriate signed/unsigned SPIR-V op
1489 spv::Op opcode;
Kévin Petit91bc72e2019-04-08 15:17:46 +01001490 if (finfo.isArgSigned(0)) {
Kévin Petit617a76d2019-04-04 13:54:16 +01001491 opcode = spv::OpSMulExtended;
1492 } else {
1493 opcode = spv::OpUMulExtended;
1494 }
1495
1496 // Our SPIR-V op returns a struct, create a type for it
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001497 SmallVector<Type *, 2> TwoValueType = {AType, AType};
Kévin Petit617a76d2019-04-04 13:54:16 +01001498 auto ExMulRetType = StructType::create(TwoValueType);
1499
1500 // Call the SPIR-V op
1501 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1502 ExMulRetType, {AValue, BValue});
1503
1504 // Get the high part of the result
1505 unsigned Idxs[] = {1};
1506 Value *V = ExtractValueInst::Create(Call, Idxs, "", CI);
1507
1508 // If we're handling a mad_hi, add the third argument to the result
1509 if (isMad) {
1510 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
1511 }
1512
1513 // Replace call with the expression
1514 CI->replaceAllUsesWith(V);
1515
1516 // Lastly, remember to remove the user.
1517 ToRemoves.push_back(CI);
1518 }
1519 }
1520
1521 Changed = !ToRemoves.empty();
1522
1523 // And cleanup the calls we don't use anymore.
1524 for (auto V : ToRemoves) {
1525 V->eraseFromParent();
1526 }
1527
1528 // And remove the function we don't need either too.
1529 F->eraseFromParent();
1530 }
1531
Kévin Petit8a560882019-03-21 15:24:34 +00001532 return Changed;
1533}
1534
Kévin Petitf5b78a22018-10-25 14:32:17 +00001535bool ReplaceOpenCLBuiltinPass::replaceSelect(Module &M) {
1536 bool Changed = false;
1537
1538 for (auto const &SymVal : M.getValueSymbolTable()) {
1539 // Skip symbols whose name doesn't match
1540 if (!SymVal.getKey().startswith("_Z6select")) {
1541 continue;
1542 }
1543 // Is there a function going by that name?
1544 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
1545
1546 SmallVector<Instruction *, 4> ToRemoves;
1547
1548 // Walk the users of the function.
1549 for (auto &U : F->uses()) {
1550 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1551
1552 // Get arguments
1553 auto FalseValue = CI->getOperand(0);
1554 auto TrueValue = CI->getOperand(1);
1555 auto PredicateValue = CI->getOperand(2);
1556
1557 // Don't touch overloads that aren't in OpenCL C
1558 auto FalseType = FalseValue->getType();
1559 auto TrueType = TrueValue->getType();
1560 auto PredicateType = PredicateValue->getType();
1561
1562 if (FalseType != TrueType) {
1563 continue;
1564 }
1565
1566 if (!PredicateType->isIntOrIntVectorTy()) {
1567 continue;
1568 }
1569
1570 if (!FalseType->isIntOrIntVectorTy() &&
1571 !FalseType->getScalarType()->isFloatingPointTy()) {
1572 continue;
1573 }
1574
1575 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1576 continue;
1577 }
1578
1579 if (FalseType->getScalarSizeInBits() !=
1580 PredicateType->getScalarSizeInBits()) {
1581 continue;
1582 }
1583
1584 if (FalseType->isVectorTy()) {
1585 if (FalseType->getVectorNumElements() !=
1586 PredicateType->getVectorNumElements()) {
1587 continue;
1588 }
1589
1590 if ((FalseType->getVectorNumElements() != 2) &&
1591 (FalseType->getVectorNumElements() != 3) &&
1592 (FalseType->getVectorNumElements() != 4) &&
1593 (FalseType->getVectorNumElements() != 8) &&
1594 (FalseType->getVectorNumElements() != 16)) {
1595 continue;
1596 }
1597 }
1598
1599 // Create constant
1600 const auto ZeroValue = Constant::getNullValue(PredicateType);
1601
1602 // Scalar and vector are to be treated differently
1603 CmpInst::Predicate Pred;
1604 if (PredicateType->isVectorTy()) {
1605 Pred = CmpInst::ICMP_SLT;
1606 } else {
1607 Pred = CmpInst::ICMP_NE;
1608 }
1609
1610 // Create comparison instruction
1611 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1612 ZeroValue, "", CI);
1613
1614 // Create select
1615 Value *V = SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1616
1617 // Replace call with the selection
1618 CI->replaceAllUsesWith(V);
1619
1620 // Lastly, remember to remove the user.
1621 ToRemoves.push_back(CI);
1622 }
1623 }
1624
1625 Changed = !ToRemoves.empty();
1626
1627 // And cleanup the calls we don't use anymore.
1628 for (auto V : ToRemoves) {
1629 V->eraseFromParent();
1630 }
1631
1632 // And remove the function we don't need either too.
1633 F->eraseFromParent();
1634 }
1635 }
1636
1637 return Changed;
1638}
1639
Kévin Petite7d0cce2018-10-31 12:38:56 +00001640bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Module &M) {
1641 bool Changed = false;
1642
1643 for (auto const &SymVal : M.getValueSymbolTable()) {
1644 // Skip symbols whose name doesn't match
1645 if (!SymVal.getKey().startswith("_Z9bitselect")) {
1646 continue;
1647 }
1648 // Is there a function going by that name?
1649 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
1650
1651 SmallVector<Instruction *, 4> ToRemoves;
1652
1653 // Walk the users of the function.
1654 for (auto &U : F->uses()) {
1655 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1656
1657 if (CI->getNumOperands() != 4) {
1658 continue;
1659 }
1660
1661 // Get arguments
1662 auto FalseValue = CI->getOperand(0);
1663 auto TrueValue = CI->getOperand(1);
1664 auto PredicateValue = CI->getOperand(2);
1665
1666 // Don't touch overloads that aren't in OpenCL C
1667 auto FalseType = FalseValue->getType();
1668 auto TrueType = TrueValue->getType();
1669 auto PredicateType = PredicateValue->getType();
1670
1671 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1672 continue;
1673 }
1674
1675 if (TrueType->isVectorTy()) {
1676 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1677 !TrueType->getScalarType()->isIntegerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001678 continue;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001679 }
1680 if ((TrueType->getVectorNumElements() != 2) &&
1681 (TrueType->getVectorNumElements() != 3) &&
1682 (TrueType->getVectorNumElements() != 4) &&
1683 (TrueType->getVectorNumElements() != 8) &&
1684 (TrueType->getVectorNumElements() != 16)) {
1685 continue;
1686 }
1687 }
1688
1689 // Remember the type of the operands
1690 auto OpType = TrueType;
1691
1692 // The actual bit selection will always be done on an integer type,
1693 // declare it here
1694 Type *BitType;
1695
1696 // If the operands are float, then bitcast them to int
1697 if (OpType->getScalarType()->isFloatingPointTy()) {
1698
1699 // First create the new type
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001700 BitType = getIntOrIntVectorTyForCast(M.getContext(), OpType);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001701
1702 // Then bitcast all operands
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001703 PredicateValue =
1704 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1705 FalseValue =
1706 CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1707 TrueValue =
1708 CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001709
1710 } else {
1711 // The operands have an integer type, use it directly
1712 BitType = OpType;
1713 }
1714
1715 // All the operands are now always integers
1716 // implement as (c & b) | (~c & a)
1717
1718 // Create our negated predicate value
1719 auto AllOnes = Constant::getAllOnesValue(BitType);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001720 auto NotPredicateValue = BinaryOperator::Create(
1721 Instruction::Xor, PredicateValue, AllOnes, "", CI);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001722
1723 // Then put everything together
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001724 auto BitsFalse = BinaryOperator::Create(
1725 Instruction::And, NotPredicateValue, FalseValue, "", CI);
1726 auto BitsTrue = BinaryOperator::Create(
1727 Instruction::And, PredicateValue, TrueValue, "", CI);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001728
1729 Value *V = BinaryOperator::Create(Instruction::Or, BitsFalse,
1730 BitsTrue, "", CI);
1731
1732 // If we were dealing with a floating point type, we must bitcast
1733 // the result back to that
1734 if (OpType->getScalarType()->isFloatingPointTy()) {
1735 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1736 }
1737
1738 // Replace call with our new code
1739 CI->replaceAllUsesWith(V);
1740
1741 // Lastly, remember to remove the user.
1742 ToRemoves.push_back(CI);
1743 }
1744 }
1745
1746 Changed = !ToRemoves.empty();
1747
1748 // And cleanup the calls we don't use anymore.
1749 for (auto V : ToRemoves) {
1750 V->eraseFromParent();
1751 }
1752
1753 // And remove the function we don't need either too.
1754 F->eraseFromParent();
1755 }
1756 }
1757
1758 return Changed;
1759}
1760
Kévin Petit6b0a9532018-10-30 20:00:39 +00001761bool ReplaceOpenCLBuiltinPass::replaceStepSmoothStep(Module &M) {
1762 bool Changed = false;
1763
1764 const std::map<const char *, const char *> Map = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001765 {"_Z4stepfDv2_f", "_Z4stepDv2_fS_"},
1766 {"_Z4stepfDv3_f", "_Z4stepDv3_fS_"},
1767 {"_Z4stepfDv4_f", "_Z4stepDv4_fS_"},
1768 {"_Z10smoothstepffDv2_f", "_Z10smoothstepDv2_fS_S_"},
1769 {"_Z10smoothstepffDv3_f", "_Z10smoothstepDv3_fS_S_"},
1770 {"_Z10smoothstepffDv4_f", "_Z10smoothstepDv4_fS_S_"},
Kévin Petit6b0a9532018-10-30 20:00:39 +00001771 };
1772
1773 for (auto Pair : Map) {
1774 // If we find a function with the matching name.
1775 if (auto F = M.getFunction(Pair.first)) {
1776 SmallVector<Instruction *, 4> ToRemoves;
1777
1778 // Walk the users of the function.
1779 for (auto &U : F->uses()) {
1780 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1781
1782 auto ReplacementFn = Pair.second;
1783
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001784 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
Kévin Petit6b0a9532018-10-30 20:00:39 +00001785 Value *VectorArg;
1786
1787 // First figure out which function we're dealing with
1788 if (F->getName().startswith("_Z10smoothstep")) {
1789 ArgsToSplat.push_back(CI->getOperand(1));
1790 VectorArg = CI->getOperand(2);
1791 } else {
1792 VectorArg = CI->getOperand(1);
1793 }
1794
1795 // Splat arguments that need to be
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001796 SmallVector<Value *, 2> SplatArgs;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001797 auto VecType = VectorArg->getType();
1798
1799 for (auto arg : ArgsToSplat) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001800 Value *NewVectorArg = UndefValue::get(VecType);
Kévin Petit6b0a9532018-10-30 20:00:39 +00001801 for (auto i = 0; i < VecType->getVectorNumElements(); i++) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001802 auto index =
1803 ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1804 NewVectorArg =
1805 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
Kévin Petit6b0a9532018-10-30 20:00:39 +00001806 }
1807 SplatArgs.push_back(NewVectorArg);
1808 }
1809
1810 // Replace the call with the vector/vector flavour
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001811 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1812 const auto NewFType =
1813 FunctionType::get(CI->getType(), NewArgTypes, false);
Kévin Petit6b0a9532018-10-30 20:00:39 +00001814
1815 const auto NewF = M.getOrInsertFunction(ReplacementFn, NewFType);
1816
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001817 SmallVector<Value *, 3> NewArgs;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001818 for (auto arg : SplatArgs) {
1819 NewArgs.push_back(arg);
1820 }
1821 NewArgs.push_back(VectorArg);
1822
1823 const auto NewCI = CallInst::Create(NewF, NewArgs, "", CI);
1824
1825 CI->replaceAllUsesWith(NewCI);
1826
1827 // Lastly, remember to remove the user.
1828 ToRemoves.push_back(CI);
1829 }
1830 }
1831
1832 Changed = !ToRemoves.empty();
1833
1834 // And cleanup the calls we don't use anymore.
1835 for (auto V : ToRemoves) {
1836 V->eraseFromParent();
1837 }
1838
1839 // And remove the function we don't need either too.
1840 F->eraseFromParent();
1841 }
1842 }
1843
1844 return Changed;
1845}
1846
David Neto22f144c2017-06-12 14:26:21 -04001847bool ReplaceOpenCLBuiltinPass::replaceSignbit(Module &M) {
1848 bool Changed = false;
1849
1850 const std::map<const char *, Instruction::BinaryOps> Map = {
1851 {"_Z7signbitf", Instruction::LShr},
1852 {"_Z7signbitDv2_f", Instruction::AShr},
1853 {"_Z7signbitDv3_f", Instruction::AShr},
1854 {"_Z7signbitDv4_f", Instruction::AShr},
1855 };
1856
1857 for (auto Pair : Map) {
1858 // If we find a function with the matching name.
1859 if (auto F = M.getFunction(Pair.first)) {
1860 SmallVector<Instruction *, 4> ToRemoves;
1861
1862 // Walk the users of the function.
1863 for (auto &U : F->uses()) {
1864 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1865 auto Arg = CI->getOperand(0);
1866
1867 auto Bitcast =
1868 CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
1869
1870 auto Shr = BinaryOperator::Create(Pair.second, Bitcast,
1871 ConstantInt::get(CI->getType(), 31),
1872 "", CI);
1873
1874 CI->replaceAllUsesWith(Shr);
1875
1876 // Lastly, remember to remove the user.
1877 ToRemoves.push_back(CI);
1878 }
1879 }
1880
1881 Changed = !ToRemoves.empty();
1882
1883 // And cleanup the calls we don't use anymore.
1884 for (auto V : ToRemoves) {
1885 V->eraseFromParent();
1886 }
1887
1888 // And remove the function we don't need either too.
1889 F->eraseFromParent();
1890 }
1891 }
1892
1893 return Changed;
1894}
1895
1896bool ReplaceOpenCLBuiltinPass::replaceMadandMad24andMul24(Module &M) {
1897 bool Changed = false;
1898
1899 const std::map<const char *,
1900 std::pair<Instruction::BinaryOps, Instruction::BinaryOps>>
1901 Map = {
1902 {"_Z3madfff", {Instruction::FMul, Instruction::FAdd}},
1903 {"_Z3madDv2_fS_S_", {Instruction::FMul, Instruction::FAdd}},
1904 {"_Z3madDv3_fS_S_", {Instruction::FMul, Instruction::FAdd}},
1905 {"_Z3madDv4_fS_S_", {Instruction::FMul, Instruction::FAdd}},
alan-bakerc21a65e2020-01-15 14:19:39 -05001906 {"_Z3madDhDhDh", {Instruction::FMul, Instruction::FAdd}},
1907 {"_Z3madDv2_DhS_S_", {Instruction::FMul, Instruction::FAdd}},
1908 {"_Z3madDv3_DhS_S_", {Instruction::FMul, Instruction::FAdd}},
1909 {"_Z3madDv4_DhS_S_", {Instruction::FMul, Instruction::FAdd}},
David Neto22f144c2017-06-12 14:26:21 -04001910 {"_Z5mad24iii", {Instruction::Mul, Instruction::Add}},
1911 {"_Z5mad24Dv2_iS_S_", {Instruction::Mul, Instruction::Add}},
1912 {"_Z5mad24Dv3_iS_S_", {Instruction::Mul, Instruction::Add}},
1913 {"_Z5mad24Dv4_iS_S_", {Instruction::Mul, Instruction::Add}},
1914 {"_Z5mad24jjj", {Instruction::Mul, Instruction::Add}},
1915 {"_Z5mad24Dv2_jS_S_", {Instruction::Mul, Instruction::Add}},
1916 {"_Z5mad24Dv3_jS_S_", {Instruction::Mul, Instruction::Add}},
1917 {"_Z5mad24Dv4_jS_S_", {Instruction::Mul, Instruction::Add}},
1918 {"_Z5mul24ii", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1919 {"_Z5mul24Dv2_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1920 {"_Z5mul24Dv3_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1921 {"_Z5mul24Dv4_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1922 {"_Z5mul24jj", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1923 {"_Z5mul24Dv2_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1924 {"_Z5mul24Dv3_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1925 {"_Z5mul24Dv4_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1926 };
1927
1928 for (auto Pair : Map) {
1929 // If we find a function with the matching name.
1930 if (auto F = M.getFunction(Pair.first)) {
1931 SmallVector<Instruction *, 4> ToRemoves;
1932
1933 // Walk the users of the function.
1934 for (auto &U : F->uses()) {
1935 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1936 // The multiply instruction to use.
1937 auto MulInst = Pair.second.first;
1938
1939 // The add instruction to use.
1940 auto AddInst = Pair.second.second;
1941
1942 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
1943
1944 auto I = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1945 CI->getArgOperand(1), "", CI);
1946
1947 if (Instruction::BinaryOpsEnd != AddInst) {
1948 I = BinaryOperator::Create(AddInst, I, CI->getArgOperand(2), "",
1949 CI);
1950 }
1951
1952 CI->replaceAllUsesWith(I);
1953
1954 // Lastly, remember to remove the user.
1955 ToRemoves.push_back(CI);
1956 }
1957 }
1958
1959 Changed = !ToRemoves.empty();
1960
1961 // And cleanup the calls we don't use anymore.
1962 for (auto V : ToRemoves) {
1963 V->eraseFromParent();
1964 }
1965
1966 // And remove the function we don't need either too.
1967 F->eraseFromParent();
1968 }
1969 }
1970
1971 return Changed;
1972}
1973
Derek Chowcfd368b2017-10-19 20:58:45 -07001974bool ReplaceOpenCLBuiltinPass::replaceVstore(Module &M) {
1975 bool Changed = false;
1976
alan-bakerf795f392019-06-11 18:24:34 -04001977 for (auto const &SymVal : M.getValueSymbolTable()) {
1978 if (!SymVal.getKey().contains("vstore"))
1979 continue;
1980 if (SymVal.getKey().contains("vstore_"))
1981 continue;
1982 if (SymVal.getKey().contains("vstorea"))
1983 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07001984
alan-bakerf795f392019-06-11 18:24:34 -04001985 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
Derek Chowcfd368b2017-10-19 20:58:45 -07001986 SmallVector<Instruction *, 4> ToRemoves;
1987
alan-bakerf795f392019-06-11 18:24:34 -04001988 auto fname = F->getName();
1989 if (!fname.consume_front("_Z"))
1990 continue;
1991 size_t name_len;
1992 if (fname.consumeInteger(10, name_len))
1993 continue;
alan-baker21574d32020-01-29 16:00:31 -05001994 std::string name = fname.take_front(name_len).str();
alan-bakerf795f392019-06-11 18:24:34 -04001995
1996 bool ok = StringSwitch<bool>(name)
1997 .Case("vstore2", true)
1998 .Case("vstore3", true)
1999 .Case("vstore4", true)
2000 .Case("vstore8", true)
2001 .Case("vstore16", true)
2002 .Default(false);
2003 if (!ok)
2004 continue;
2005
Derek Chowcfd368b2017-10-19 20:58:45 -07002006 for (auto &U : F->uses()) {
2007 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
alan-bakerf795f392019-06-11 18:24:34 -04002008 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07002009
alan-bakerf795f392019-06-11 18:24:34 -04002010 auto data_type = data->getType();
2011 if (!data_type->isVectorTy())
2012 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002013
alan-bakerf795f392019-06-11 18:24:34 -04002014 auto elems = data_type->getVectorNumElements();
2015 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 &&
2016 elems != 16)
2017 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002018
alan-bakerf795f392019-06-11 18:24:34 -04002019 auto offset = CI->getOperand(1);
2020 auto ptr = CI->getOperand(2);
2021 auto ptr_type = ptr->getType();
2022 auto pointee_type = ptr_type->getPointerElementType();
2023 if (pointee_type != data_type->getVectorElementType())
2024 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002025
alan-bakerf795f392019-06-11 18:24:34 -04002026 // Avoid pointer casts. Instead generate the correct number of stores
2027 // and rely on drivers to coalesce appropriately.
2028 IRBuilder<> builder(CI);
2029 auto elems_const = builder.getInt32(elems);
2030 auto adjust = builder.CreateMul(offset, elems_const);
2031 for (auto i = 0; i < elems; ++i) {
2032 auto idx = builder.getInt32(i);
2033 auto add = builder.CreateAdd(adjust, idx);
2034 auto gep = builder.CreateGEP(ptr, add);
2035 auto extract = builder.CreateExtractElement(data, i);
2036 auto store = builder.CreateStore(extract, gep);
2037 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002038
Derek Chowcfd368b2017-10-19 20:58:45 -07002039 ToRemoves.push_back(CI);
2040 }
2041 }
2042
2043 Changed = !ToRemoves.empty();
Derek Chowcfd368b2017-10-19 20:58:45 -07002044 for (auto V : ToRemoves) {
2045 V->eraseFromParent();
2046 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002047 F->eraseFromParent();
2048 }
2049 }
2050
2051 return Changed;
2052}
2053
2054bool ReplaceOpenCLBuiltinPass::replaceVload(Module &M) {
2055 bool Changed = false;
2056
alan-bakerf795f392019-06-11 18:24:34 -04002057 for (auto const &SymVal : M.getValueSymbolTable()) {
2058 if (!SymVal.getKey().contains("vload"))
2059 continue;
2060 if (SymVal.getKey().contains("vload_"))
2061 continue;
2062 if (SymVal.getKey().contains("vloada"))
2063 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002064
alan-bakerf795f392019-06-11 18:24:34 -04002065 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
Derek Chowcfd368b2017-10-19 20:58:45 -07002066 SmallVector<Instruction *, 4> ToRemoves;
2067
alan-bakerf795f392019-06-11 18:24:34 -04002068 auto fname = F->getName();
2069 if (!fname.consume_front("_Z"))
2070 continue;
2071 size_t name_len;
2072 if (fname.consumeInteger(10, name_len))
2073 continue;
alan-baker21574d32020-01-29 16:00:31 -05002074 std::string name = fname.take_front(name_len).str();
alan-bakerf795f392019-06-11 18:24:34 -04002075
2076 bool ok = StringSwitch<bool>(name)
2077 .Case("vload2", true)
2078 .Case("vload3", true)
2079 .Case("vload4", true)
2080 .Case("vload8", true)
2081 .Case("vload16", true)
2082 .Default(false);
2083 if (!ok)
2084 continue;
2085
Derek Chowcfd368b2017-10-19 20:58:45 -07002086 for (auto &U : F->uses()) {
2087 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
alan-bakerf795f392019-06-11 18:24:34 -04002088 auto ret_type = F->getReturnType();
2089 if (!ret_type->isVectorTy())
2090 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002091
alan-bakerf795f392019-06-11 18:24:34 -04002092 auto elems = ret_type->getVectorNumElements();
2093 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 &&
2094 elems != 16)
2095 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002096
alan-bakerf795f392019-06-11 18:24:34 -04002097 auto offset = CI->getOperand(0);
2098 auto ptr = CI->getOperand(1);
2099 auto ptr_type = ptr->getType();
2100 auto pointee_type = ptr_type->getPointerElementType();
2101 if (pointee_type != ret_type->getVectorElementType())
2102 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002103
alan-bakerf795f392019-06-11 18:24:34 -04002104 // Avoid pointer casts. Instead generate the correct number of loads
2105 // and rely on drivers to coalesce appropriately.
2106 IRBuilder<> builder(CI);
2107 auto elems_const = builder.getInt32(elems);
2108 Value *insert = UndefValue::get(ret_type);
2109 auto adjust = builder.CreateMul(offset, elems_const);
2110 for (auto i = 0; i < elems; ++i) {
2111 auto idx = builder.getInt32(i);
2112 auto add = builder.CreateAdd(adjust, idx);
2113 auto gep = builder.CreateGEP(ptr, add);
2114 auto load = builder.CreateLoad(gep);
2115 insert = builder.CreateInsertElement(insert, load, i);
2116 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002117
alan-bakerf795f392019-06-11 18:24:34 -04002118 CI->replaceAllUsesWith(insert);
Derek Chowcfd368b2017-10-19 20:58:45 -07002119 ToRemoves.push_back(CI);
2120 }
2121 }
2122
2123 Changed = !ToRemoves.empty();
Derek Chowcfd368b2017-10-19 20:58:45 -07002124 for (auto V : ToRemoves) {
2125 V->eraseFromParent();
2126 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002127 F->eraseFromParent();
Derek Chowcfd368b2017-10-19 20:58:45 -07002128 }
2129 }
2130
2131 return Changed;
2132}
2133
David Neto22f144c2017-06-12 14:26:21 -04002134bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Module &M) {
2135 bool Changed = false;
2136
2137 const std::vector<const char *> Map = {"_Z10vload_halfjPU3AS1KDh",
2138 "_Z10vload_halfjPU3AS2KDh"};
2139
2140 for (auto Name : Map) {
2141 // If we find a function with the matching name.
2142 if (auto F = M.getFunction(Name)) {
2143 SmallVector<Instruction *, 4> ToRemoves;
2144
2145 // Walk the users of the function.
2146 for (auto &U : F->uses()) {
2147 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2148 // The index argument from vload_half.
2149 auto Arg0 = CI->getOperand(0);
2150
2151 // The pointer argument from vload_half.
2152 auto Arg1 = CI->getOperand(1);
2153
David Neto22f144c2017-06-12 14:26:21 -04002154 auto IntTy = Type::getInt32Ty(M.getContext());
2155 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
David Neto22f144c2017-06-12 14:26:21 -04002156 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
2157
David Neto22f144c2017-06-12 14:26:21 -04002158 // Our intrinsic to unpack a float2 from an int.
2159 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
2160
2161 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
2162
David Neto482550a2018-03-24 05:21:07 -07002163 if (clspv::Option::F16BitStorage()) {
David Netoac825b82017-05-30 12:49:01 -04002164 auto ShortTy = Type::getInt16Ty(M.getContext());
2165 auto ShortPointerTy = PointerType::get(
2166 ShortTy, Arg1->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002167
David Netoac825b82017-05-30 12:49:01 -04002168 // Cast the half* pointer to short*.
2169 auto Cast =
2170 CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002171
David Netoac825b82017-05-30 12:49:01 -04002172 // Index into the correct address of the casted pointer.
2173 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
2174
2175 // Load from the short* we casted to.
2176 auto Load = new LoadInst(Index, "", CI);
2177
2178 // ZExt the short -> int.
2179 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
2180
2181 // Get our float2.
2182 auto Call = CallInst::Create(NewF, ZExt, "", CI);
2183
2184 // Extract out the bottom element which is our float result.
2185 auto Extract = ExtractElementInst::Create(
2186 Call, ConstantInt::get(IntTy, 0), "", CI);
2187
2188 CI->replaceAllUsesWith(Extract);
2189 } else {
2190 // Assume the pointer argument points to storage aligned to 32bits
2191 // or more.
2192 // TODO(dneto): Do more analysis to make sure this is true?
2193 //
2194 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
2195 // with:
2196 //
2197 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
2198 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
2199 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
2200 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
2201 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
2202 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
2203 // x float> %converted, %index_is_odd32
2204
2205 auto IntPointerTy = PointerType::get(
2206 IntTy, Arg1->getType()->getPointerAddressSpace());
2207
David Neto973e6a82017-05-30 13:48:18 -04002208 // Cast the base pointer to int*.
David Netoac825b82017-05-30 12:49:01 -04002209 // In a valid call (according to assumptions), this should get
David Neto973e6a82017-05-30 13:48:18 -04002210 // optimized away in the simplify GEP pass.
David Netoac825b82017-05-30 12:49:01 -04002211 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
2212
2213 auto One = ConstantInt::get(IntTy, 1);
2214 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
2215 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
2216
2217 // Index into the correct address of the casted pointer.
2218 auto Ptr =
2219 GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
2220
2221 // Load from the int* we casted to.
2222 auto Load = new LoadInst(Ptr, "", CI);
2223
2224 // Get our float2.
2225 auto Call = CallInst::Create(NewF, Load, "", CI);
2226
2227 // Extract out the float result, where the element number is
2228 // determined by whether the original index was even or odd.
2229 auto Extract = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
2230
2231 CI->replaceAllUsesWith(Extract);
2232 }
David Neto22f144c2017-06-12 14:26:21 -04002233
2234 // Lastly, remember to remove the user.
2235 ToRemoves.push_back(CI);
2236 }
2237 }
2238
2239 Changed = !ToRemoves.empty();
2240
2241 // And cleanup the calls we don't use anymore.
2242 for (auto V : ToRemoves) {
2243 V->eraseFromParent();
2244 }
2245
2246 // And remove the function we don't need either too.
2247 F->eraseFromParent();
2248 }
2249 }
2250
2251 return Changed;
2252}
2253
2254bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002255
Kévin Petite8edce32019-04-10 14:23:32 +01002256 const std::vector<const char *> Names = {
David Neto556c7e62018-06-08 13:45:55 -07002257 "_Z11vload_half2jPU3AS1KDh",
2258 "_Z12vloada_half2jPU3AS1KDh", // vloada_half2 global
2259 "_Z11vload_half2jPU3AS2KDh",
2260 "_Z12vloada_half2jPU3AS2KDh", // vloada_half2 constant
2261 };
David Neto22f144c2017-06-12 14:26:21 -04002262
Kévin Petite8edce32019-04-10 14:23:32 +01002263 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2264 // The index argument from vload_half.
2265 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002266
Kévin Petite8edce32019-04-10 14:23:32 +01002267 // The pointer argument from vload_half.
2268 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002269
Kévin Petite8edce32019-04-10 14:23:32 +01002270 auto IntTy = Type::getInt32Ty(M.getContext());
2271 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002272 auto NewPointerTy =
2273 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002274 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04002275
Kévin Petite8edce32019-04-10 14:23:32 +01002276 // Cast the half* pointer to int*.
2277 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002278
Kévin Petite8edce32019-04-10 14:23:32 +01002279 // Index into the correct address of the casted pointer.
2280 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002281
Kévin Petite8edce32019-04-10 14:23:32 +01002282 // Load from the int* we casted to.
2283 auto Load = new LoadInst(Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002284
Kévin Petite8edce32019-04-10 14:23:32 +01002285 // Our intrinsic to unpack a float2 from an int.
2286 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002287
Kévin Petite8edce32019-04-10 14:23:32 +01002288 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002289
Kévin Petite8edce32019-04-10 14:23:32 +01002290 // Get our float2.
2291 return CallInst::Create(NewF, Load, "", CI);
2292 });
David Neto22f144c2017-06-12 14:26:21 -04002293}
2294
2295bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002296
Kévin Petite8edce32019-04-10 14:23:32 +01002297 const std::vector<const char *> Names = {
David Neto556c7e62018-06-08 13:45:55 -07002298 "_Z11vload_half4jPU3AS1KDh",
2299 "_Z12vloada_half4jPU3AS1KDh",
2300 "_Z11vload_half4jPU3AS2KDh",
2301 "_Z12vloada_half4jPU3AS2KDh",
2302 };
David Neto22f144c2017-06-12 14:26:21 -04002303
Kévin Petite8edce32019-04-10 14:23:32 +01002304 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2305 // The index argument from vload_half.
2306 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002307
Kévin Petite8edce32019-04-10 14:23:32 +01002308 // The pointer argument from vload_half.
2309 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002310
Kévin Petite8edce32019-04-10 14:23:32 +01002311 auto IntTy = Type::getInt32Ty(M.getContext());
2312 auto Int2Ty = VectorType::get(IntTy, 2);
2313 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002314 auto NewPointerTy =
2315 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002316 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04002317
Kévin Petite8edce32019-04-10 14:23:32 +01002318 // Cast the half* pointer to int2*.
2319 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002320
Kévin Petite8edce32019-04-10 14:23:32 +01002321 // Index into the correct address of the casted pointer.
2322 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002323
Kévin Petite8edce32019-04-10 14:23:32 +01002324 // Load from the int2* we casted to.
2325 auto Load = new LoadInst(Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002326
Kévin Petite8edce32019-04-10 14:23:32 +01002327 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002328 auto X =
2329 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
2330 auto Y =
2331 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002332
Kévin Petite8edce32019-04-10 14:23:32 +01002333 // Our intrinsic to unpack a float2 from an int.
2334 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002335
Kévin Petite8edce32019-04-10 14:23:32 +01002336 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002337
Kévin Petite8edce32019-04-10 14:23:32 +01002338 // Get the lower (x & y) components of our final float4.
2339 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002340
Kévin Petite8edce32019-04-10 14:23:32 +01002341 // Get the higher (z & w) components of our final float4.
2342 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002343
Kévin Petite8edce32019-04-10 14:23:32 +01002344 Constant *ShuffleMask[4] = {
2345 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2346 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002347
Kévin Petite8edce32019-04-10 14:23:32 +01002348 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002349 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
2350 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002351 });
David Neto22f144c2017-06-12 14:26:21 -04002352}
2353
David Neto6ad93232018-06-07 15:42:58 -07002354bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Module &M) {
David Neto6ad93232018-06-07 15:42:58 -07002355
2356 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
2357 //
2358 // %u = load i32 %ptr
2359 // %fxy = call <2 x float> Unpack2xHalf(u)
2360 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
Kévin Petite8edce32019-04-10 14:23:32 +01002361 const std::vector<const char *> Names = {
David Neto6ad93232018-06-07 15:42:58 -07002362 "_Z20__clspv_vloada_half2jPU3AS1Kj", // global
2363 "_Z20__clspv_vloada_half2jPU3AS3Kj", // local
2364 "_Z20__clspv_vloada_half2jPKj", // private
2365 };
2366
Kévin Petite8edce32019-04-10 14:23:32 +01002367 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2368 auto Index = CI->getOperand(0);
2369 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07002370
Kévin Petite8edce32019-04-10 14:23:32 +01002371 auto IntTy = Type::getInt32Ty(M.getContext());
2372 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
2373 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07002374
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002375 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002376 auto Load = new LoadInst(IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002377
Kévin Petite8edce32019-04-10 14:23:32 +01002378 // Our intrinsic to unpack a float2 from an int.
2379 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07002380
Kévin Petite8edce32019-04-10 14:23:32 +01002381 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07002382
Kévin Petite8edce32019-04-10 14:23:32 +01002383 // Get our final float2.
2384 return CallInst::Create(NewF, Load, "", CI);
2385 });
David Neto6ad93232018-06-07 15:42:58 -07002386}
2387
2388bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Module &M) {
David Neto6ad93232018-06-07 15:42:58 -07002389
2390 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
2391 //
2392 // %u2 = load <2 x i32> %ptr
2393 // %u2xy = extractelement %u2, 0
2394 // %u2zw = extractelement %u2, 1
2395 // %fxy = call <2 x float> Unpack2xHalf(uint)
2396 // %fzw = call <2 x float> Unpack2xHalf(uint)
2397 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
Kévin Petite8edce32019-04-10 14:23:32 +01002398 const std::vector<const char *> Names = {
David Neto6ad93232018-06-07 15:42:58 -07002399 "_Z20__clspv_vloada_half4jPU3AS1KDv2_j", // global
2400 "_Z20__clspv_vloada_half4jPU3AS3KDv2_j", // local
2401 "_Z20__clspv_vloada_half4jPKDv2_j", // private
2402 };
2403
Kévin Petite8edce32019-04-10 14:23:32 +01002404 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2405 auto Index = CI->getOperand(0);
2406 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07002407
Kévin Petite8edce32019-04-10 14:23:32 +01002408 auto IntTy = Type::getInt32Ty(M.getContext());
2409 auto Int2Ty = VectorType::get(IntTy, 2);
2410 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
2411 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07002412
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002413 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002414 auto Load = new LoadInst(IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002415
Kévin Petite8edce32019-04-10 14:23:32 +01002416 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002417 auto X =
2418 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
2419 auto Y =
2420 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002421
Kévin Petite8edce32019-04-10 14:23:32 +01002422 // Our intrinsic to unpack a float2 from an int.
2423 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07002424
Kévin Petite8edce32019-04-10 14:23:32 +01002425 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07002426
Kévin Petite8edce32019-04-10 14:23:32 +01002427 // Get the lower (x & y) components of our final float4.
2428 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002429
Kévin Petite8edce32019-04-10 14:23:32 +01002430 // Get the higher (z & w) components of our final float4.
2431 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002432
Kévin Petite8edce32019-04-10 14:23:32 +01002433 Constant *ShuffleMask[4] = {
2434 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2435 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07002436
Kévin Petite8edce32019-04-10 14:23:32 +01002437 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002438 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
2439 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002440 });
David Neto6ad93232018-06-07 15:42:58 -07002441}
2442
David Neto22f144c2017-06-12 14:26:21 -04002443bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002444
Kévin Petite8edce32019-04-10 14:23:32 +01002445 const std::vector<const char *> Names = {"_Z11vstore_halffjPU3AS1Dh",
2446 "_Z15vstore_half_rtefjPU3AS1Dh",
2447 "_Z15vstore_half_rtzfjPU3AS1Dh"};
David Neto22f144c2017-06-12 14:26:21 -04002448
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002449 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002450 // The value to store.
2451 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002452
Kévin Petite8edce32019-04-10 14:23:32 +01002453 // The index argument from vstore_half.
2454 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002455
Kévin Petite8edce32019-04-10 14:23:32 +01002456 // The pointer argument from vstore_half.
2457 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002458
Kévin Petite8edce32019-04-10 14:23:32 +01002459 auto IntTy = Type::getInt32Ty(M.getContext());
2460 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
2461 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
2462 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04002463
Kévin Petite8edce32019-04-10 14:23:32 +01002464 // Our intrinsic to pack a float2 to an int.
2465 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002466
Kévin Petite8edce32019-04-10 14:23:32 +01002467 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002468
Kévin Petite8edce32019-04-10 14:23:32 +01002469 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002470 auto TempVec = InsertElementInst::Create(
2471 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002472
Kévin Petite8edce32019-04-10 14:23:32 +01002473 // Pack the float2 -> half2 (in an int).
2474 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002475
Kévin Petite8edce32019-04-10 14:23:32 +01002476 Value *Ret;
2477 if (clspv::Option::F16BitStorage()) {
2478 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002479 auto ShortPointerTy =
2480 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002481
Kévin Petite8edce32019-04-10 14:23:32 +01002482 // Truncate our i32 to an i16.
2483 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002484
Kévin Petite8edce32019-04-10 14:23:32 +01002485 // Cast the half* pointer to short*.
2486 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002487
Kévin Petite8edce32019-04-10 14:23:32 +01002488 // Index into the correct address of the casted pointer.
2489 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002490
Kévin Petite8edce32019-04-10 14:23:32 +01002491 // Store to the int* we casted to.
2492 Ret = new StoreInst(Trunc, Index, CI);
2493 } else {
2494 // We can only write to 32-bit aligned words.
2495 //
2496 // Assuming base is aligned to 32-bits, replace the equivalent of
2497 // vstore_half(value, index, base)
2498 // with:
2499 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2500 // uint32_t write_to_upper_half = index & 1u;
2501 // uint32_t shift = write_to_upper_half << 4;
2502 //
2503 // // Pack the float value as a half number in bottom 16 bits
2504 // // of an i32.
2505 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2506 //
2507 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2508 // ^ ((packed & 0xffff) << shift)
2509 // // We only need relaxed consistency, but OpenCL 1.2 only has
2510 // // sequentially consistent atomics.
2511 // // TODO(dneto): Use relaxed consistency.
2512 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002513 auto IntPointerTy =
2514 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002515
Kévin Petite8edce32019-04-10 14:23:32 +01002516 auto Four = ConstantInt::get(IntTy, 4);
2517 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002518
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002519 auto IndexIsOdd =
2520 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002521 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002522 auto IndexIntoI32 =
2523 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2524 auto BaseI32Ptr =
2525 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2526 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2527 "base_i32_ptr", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002528 auto CurrentValue = new LoadInst(OutPtr, "current_value", CI);
2529 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002530 auto MaskBitsToWrite =
2531 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2532 auto MaskedCurrent = BinaryOperator::CreateAnd(
2533 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002534
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002535 auto XLowerBits =
2536 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2537 auto NewBitsToWrite =
2538 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2539 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2540 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002541
Kévin Petite8edce32019-04-10 14:23:32 +01002542 // Generate the call to atomi_xor.
2543 SmallVector<Type *, 5> ParamTypes;
2544 // The pointer type.
2545 ParamTypes.push_back(IntPointerTy);
2546 // The Types for memory scope, semantics, and value.
2547 ParamTypes.push_back(IntTy);
2548 ParamTypes.push_back(IntTy);
2549 ParamTypes.push_back(IntTy);
2550 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2551 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002552
Kévin Petite8edce32019-04-10 14:23:32 +01002553 const auto ConstantScopeDevice =
2554 ConstantInt::get(IntTy, spv::ScopeDevice);
2555 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2556 // (SPIR-V Workgroup).
2557 const auto AddrSpaceSemanticsBits =
2558 IntPointerTy->getPointerAddressSpace() == 1
2559 ? spv::MemorySemanticsUniformMemoryMask
2560 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002561
Kévin Petite8edce32019-04-10 14:23:32 +01002562 // We're using relaxed consistency here.
2563 const auto ConstantMemorySemantics =
2564 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2565 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002566
Kévin Petite8edce32019-04-10 14:23:32 +01002567 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2568 ConstantMemorySemantics, ValueToXor};
2569 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
2570 Ret = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04002571 }
David Neto22f144c2017-06-12 14:26:21 -04002572
Kévin Petite8edce32019-04-10 14:23:32 +01002573 return Ret;
2574 });
David Neto22f144c2017-06-12 14:26:21 -04002575}
2576
2577bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002578
Kévin Petite8edce32019-04-10 14:23:32 +01002579 const std::vector<const char *> Names = {
David Netoe2871522018-06-08 11:09:54 -07002580 "_Z12vstore_half2Dv2_fjPU3AS1Dh",
2581 "_Z13vstorea_half2Dv2_fjPU3AS1Dh", // vstorea global
2582 "_Z13vstorea_half2Dv2_fjPU3AS3Dh", // vstorea local
2583 "_Z13vstorea_half2Dv2_fjPDh", // vstorea private
2584 "_Z16vstore_half2_rteDv2_fjPU3AS1Dh",
2585 "_Z17vstorea_half2_rteDv2_fjPU3AS1Dh", // vstorea global
2586 "_Z17vstorea_half2_rteDv2_fjPU3AS3Dh", // vstorea local
2587 "_Z17vstorea_half2_rteDv2_fjPDh", // vstorea private
2588 "_Z16vstore_half2_rtzDv2_fjPU3AS1Dh",
2589 "_Z17vstorea_half2_rtzDv2_fjPU3AS1Dh", // vstorea global
2590 "_Z17vstorea_half2_rtzDv2_fjPU3AS3Dh", // vstorea local
2591 "_Z17vstorea_half2_rtzDv2_fjPDh", // vstorea private
2592 };
David Neto22f144c2017-06-12 14:26:21 -04002593
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002594 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002595 // The value to store.
2596 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002597
Kévin Petite8edce32019-04-10 14:23:32 +01002598 // The index argument from vstore_half.
2599 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002600
Kévin Petite8edce32019-04-10 14:23:32 +01002601 // The pointer argument from vstore_half.
2602 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002603
Kévin Petite8edce32019-04-10 14:23:32 +01002604 auto IntTy = Type::getInt32Ty(M.getContext());
2605 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002606 auto NewPointerTy =
2607 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002608 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002609
Kévin Petite8edce32019-04-10 14:23:32 +01002610 // Our intrinsic to pack a float2 to an int.
2611 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002612
Kévin Petite8edce32019-04-10 14:23:32 +01002613 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002614
Kévin Petite8edce32019-04-10 14:23:32 +01002615 // Turn the packed x & y into the final packing.
2616 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002617
Kévin Petite8edce32019-04-10 14:23:32 +01002618 // Cast the half* pointer to int*.
2619 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002620
Kévin Petite8edce32019-04-10 14:23:32 +01002621 // Index into the correct address of the casted pointer.
2622 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002623
Kévin Petite8edce32019-04-10 14:23:32 +01002624 // Store to the int* we casted to.
2625 return new StoreInst(X, Index, CI);
2626 });
David Neto22f144c2017-06-12 14:26:21 -04002627}
2628
2629bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002630
Kévin Petite8edce32019-04-10 14:23:32 +01002631 const std::vector<const char *> Names = {
David Netoe2871522018-06-08 11:09:54 -07002632 "_Z12vstore_half4Dv4_fjPU3AS1Dh",
2633 "_Z13vstorea_half4Dv4_fjPU3AS1Dh", // global
2634 "_Z13vstorea_half4Dv4_fjPU3AS3Dh", // local
2635 "_Z13vstorea_half4Dv4_fjPDh", // private
2636 "_Z16vstore_half4_rteDv4_fjPU3AS1Dh",
2637 "_Z17vstorea_half4_rteDv4_fjPU3AS1Dh", // global
2638 "_Z17vstorea_half4_rteDv4_fjPU3AS3Dh", // local
2639 "_Z17vstorea_half4_rteDv4_fjPDh", // private
2640 "_Z16vstore_half4_rtzDv4_fjPU3AS1Dh",
2641 "_Z17vstorea_half4_rtzDv4_fjPU3AS1Dh", // global
2642 "_Z17vstorea_half4_rtzDv4_fjPU3AS3Dh", // local
2643 "_Z17vstorea_half4_rtzDv4_fjPDh", // private
2644 };
David Neto22f144c2017-06-12 14:26:21 -04002645
Kévin Petite8edce32019-04-10 14:23:32 +01002646 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2647 // The value to store.
2648 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002649
Kévin Petite8edce32019-04-10 14:23:32 +01002650 // The index argument from vstore_half.
2651 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002652
Kévin Petite8edce32019-04-10 14:23:32 +01002653 // The pointer argument from vstore_half.
2654 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002655
Kévin Petite8edce32019-04-10 14:23:32 +01002656 auto IntTy = Type::getInt32Ty(M.getContext());
2657 auto Int2Ty = VectorType::get(IntTy, 2);
2658 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002659 auto NewPointerTy =
2660 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002661 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002662
Kévin Petite8edce32019-04-10 14:23:32 +01002663 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2664 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002665
Kévin Petite8edce32019-04-10 14:23:32 +01002666 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002667 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2668 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002669
Kévin Petite8edce32019-04-10 14:23:32 +01002670 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2671 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002672
Kévin Petite8edce32019-04-10 14:23:32 +01002673 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002674 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2675 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002676
Kévin Petite8edce32019-04-10 14:23:32 +01002677 // Our intrinsic to pack a float2 to an int.
2678 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002679
Kévin Petite8edce32019-04-10 14:23:32 +01002680 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002681
Kévin Petite8edce32019-04-10 14:23:32 +01002682 // Turn the packed x & y into the final component of our int2.
2683 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002684
Kévin Petite8edce32019-04-10 14:23:32 +01002685 // Turn the packed z & w into the final component of our int2.
2686 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002687
Kévin Petite8edce32019-04-10 14:23:32 +01002688 auto Combine = InsertElementInst::Create(
2689 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002690 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2691 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002692
Kévin Petite8edce32019-04-10 14:23:32 +01002693 // Cast the half* pointer to int2*.
2694 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002695
Kévin Petite8edce32019-04-10 14:23:32 +01002696 // Index into the correct address of the casted pointer.
2697 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002698
Kévin Petite8edce32019-04-10 14:23:32 +01002699 // Store to the int2* we casted to.
2700 return new StoreInst(Combine, Index, CI);
2701 });
David Neto22f144c2017-06-12 14:26:21 -04002702}
2703
alan-bakerf7e17cb2020-01-02 07:29:59 -05002704bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Module &M) {
2705 bool Changed = false;
2706 const std::map<const char *, const char *> Map = {
2707 // 1D
2708 {"_Z11read_imageh14ocl_image1d_roi", "_Z11read_imagef14ocl_image1d_roi"},
2709 {"_Z11read_imageh14ocl_image1d_ro11ocl_sampleri",
2710 "_Z11read_imagef14ocl_image1d_ro11ocl_sampleri"},
2711 {"_Z11read_imageh14ocl_image1d_ro11ocl_samplerf",
2712 "_Z11read_imagef14ocl_image1d_ro11ocl_samplerf"},
alan-baker7150a1d2020-02-25 08:31:06 -05002713 // 1D array
2714 {"_Z11read_imageh20ocl_image1d_array_roDv2_i",
2715 "_Z11read_imagef20ocl_image1d_array_roDv2_i"},
2716 {"_Z11read_imageh20ocl_image1d_array_ro11ocl_samplerDv2_i",
2717 "_Z11read_imagef20ocl_image1d_array_ro11ocl_samplerDv2_i"},
2718 {"_Z11read_imageh20ocl_image1d_array_ro11ocl_samplerDv2_f",
2719 "_Z11read_imagef20ocl_image1d_array_ro11ocl_samplerDv2_f"},
alan-bakerf7e17cb2020-01-02 07:29:59 -05002720 // 2D
2721 {"_Z11read_imageh14ocl_image2d_roDv2_i",
2722 "_Z11read_imagef14ocl_image2d_roDv2_i"},
2723 {"_Z11read_imageh14ocl_image2d_ro11ocl_samplerDv2_i",
2724 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_i"},
2725 {"_Z11read_imageh14ocl_image2d_ro11ocl_samplerDv2_f",
2726 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f"},
alan-baker7150a1d2020-02-25 08:31:06 -05002727 // 2D array
2728 {"_Z11read_imageh20ocl_image2d_array_roDv4_i",
2729 "_Z11read_imagef20ocl_image2d_array_roDv4_i"},
2730 {"_Z11read_imageh20ocl_image2d_array_ro11ocl_samplerDv4_i",
2731 "_Z11read_imagef20ocl_image2d_array_ro11ocl_samplerDv4_i"},
2732 {"_Z11read_imageh20ocl_image2d_array_ro11ocl_samplerDv4_f",
2733 "_Z11read_imagef20ocl_image2d_array_ro11ocl_samplerDv4_f"},
alan-bakerf7e17cb2020-01-02 07:29:59 -05002734 // 3D
2735 {"_Z11read_imageh14ocl_image3d_roDv4_i",
2736 "_Z11read_imagef14ocl_image3d_roDv4_i"},
2737 {"_Z11read_imageh14ocl_image3d_ro11ocl_samplerDv4_i",
2738 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_i"},
2739 {"_Z11read_imageh14ocl_image3d_ro11ocl_samplerDv4_f",
2740 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f"}};
2741
2742 for (auto Pair : Map) {
2743 // If we find a function with the matching name.
2744 if (auto F = M.getFunction(Pair.first)) {
2745 SmallVector<Instruction *, 4> ToRemoves;
2746
2747 // Walk the users of the function.
2748 for (auto &U : F->uses()) {
2749 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2750 SmallVector<Type *, 3> types;
2751 SmallVector<Value *, 3> args;
2752 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2753 types.push_back(CI->getArgOperand(i)->getType());
2754 args.push_back(CI->getArgOperand(i));
2755 }
2756
2757 auto NewFType = FunctionType::get(
2758 VectorType::get(Type::getFloatTy(M.getContext()),
2759 CI->getType()->getVectorNumElements()),
2760 types, false);
2761
2762 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
2763
2764 auto NewCI = CallInst::Create(NewF, args, "", CI);
2765
2766 // Convert to the half type.
2767 auto Cast = CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2768
2769 CI->replaceAllUsesWith(Cast);
2770
2771 // Lastly, remember to remove the user.
2772 ToRemoves.push_back(CI);
2773 }
2774 }
2775
2776 Changed = !ToRemoves.empty();
2777
2778 // And cleanup the calls we don't use anymore.
2779 for (auto V : ToRemoves) {
2780 V->eraseFromParent();
2781 }
2782
2783 // And remove the function we don't need either too.
2784 F->eraseFromParent();
2785 }
2786 }
2787
2788 return Changed;
2789}
2790
2791bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Module &M) {
2792 bool Changed = false;
2793 const std::map<const char *, const char *> Map = {
2794 // 1D
2795 {"_Z12write_imageh14ocl_image1d_woiDv4_Dh",
2796 "_Z12write_imagef14ocl_image1d_woiDv4_f"},
alan-baker7150a1d2020-02-25 08:31:06 -05002797 // 1D array
2798 {"_Z12write_imageh20ocl_image1d_array_woDv2_iDv4_Dh",
2799 "_Z12write_imagef20ocl_image1d_array_woDv2_iDv4_f"},
alan-bakerf7e17cb2020-01-02 07:29:59 -05002800 // 2D
2801 {"_Z12write_imageh14ocl_image2d_woDv2_iDv4_Dh",
2802 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f"},
alan-baker7150a1d2020-02-25 08:31:06 -05002803 // 2D array
2804 {"_Z12write_imageh20ocl_image2d_array_woDv4_iDv4_Dh",
2805 "_Z12write_imagef20ocl_image2d_array_woDv4_iDv4_f"},
alan-bakerf7e17cb2020-01-02 07:29:59 -05002806 // 3D
2807 {"_Z12write_imageh14ocl_image3d_woDv4_iDv4_Dh",
2808 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f"}};
2809
2810 for (auto Pair : Map) {
2811 // If we find a function with the matching name.
2812 if (auto F = M.getFunction(Pair.first)) {
2813 SmallVector<Instruction *, 4> ToRemoves;
2814
2815 // Walk the users of the function.
2816 for (auto &U : F->uses()) {
2817 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2818 SmallVector<Type *, 3> types(3);
2819 SmallVector<Value *, 3> args(3);
2820
2821 // Image
2822 types[0] = CI->getArgOperand(0)->getType();
2823 args[0] = CI->getArgOperand(0);
2824
2825 // Coord
2826 types[1] = CI->getArgOperand(1)->getType();
2827 args[1] = CI->getArgOperand(1);
2828
2829 // Data
2830 types[2] = VectorType::get(
2831 Type::getFloatTy(M.getContext()),
2832 CI->getArgOperand(2)->getType()->getVectorNumElements());
2833
2834 auto NewFType =
2835 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
2836
2837 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
2838
2839 // Convert data to the float type.
2840 auto Cast =
2841 CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2842 args[2] = Cast;
2843
2844 auto NewCI = CallInst::Create(NewF, args, "", CI);
2845
2846 // Lastly, remember to remove the user.
2847 ToRemoves.push_back(CI);
2848 }
2849 }
2850
2851 Changed = !ToRemoves.empty();
2852
2853 // And cleanup the calls we don't use anymore.
2854 for (auto V : ToRemoves) {
2855 V->eraseFromParent();
2856 }
2857
2858 // And remove the function we don't need either too.
2859 F->eraseFromParent();
2860 }
2861 }
2862
2863 return Changed;
2864}
2865
Kévin Petit06517a12019-12-09 19:40:31 +00002866bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002867 bool Changed = false;
2868
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002869 const std::map<const char *, const char *> Map = {
alan-bakerf906d2b2019-12-10 11:26:23 -05002870 // 1D
2871 {"_Z11read_imagei14ocl_image1d_ro11ocl_sampleri",
2872 "_Z11read_imagei14ocl_image1d_ro11ocl_samplerf"},
2873 {"_Z12read_imageui14ocl_image1d_ro11ocl_sampleri",
2874 "_Z12read_imageui14ocl_image1d_ro11ocl_samplerf"},
2875 {"_Z11read_imagef14ocl_image1d_ro11ocl_sampleri",
2876 "_Z11read_imagef14ocl_image1d_ro11ocl_samplerf"},
alan-baker7150a1d2020-02-25 08:31:06 -05002877 // 1D array
2878 {"_Z11read_imagei20ocl_image1d_array_ro11ocl_samplerDv2_i",
2879 "_Z11read_imagei20ocl_image1d_array_ro11ocl_samplerDv2_f"},
2880 {"_Z12read_imageui20ocl_image1d_array_ro11ocl_samplerDv2_i",
2881 "_Z12read_imageui20ocl_image1d_array_ro11ocl_samplerDv2_f"},
2882 {"_Z11read_imagef20ocl_image1d_array_ro11ocl_samplerDv2_i",
2883 "_Z11read_imagef20ocl_image1d_array_ro11ocl_samplerDv2_f"},
Kévin Petit06517a12019-12-09 19:40:31 +00002884 // 2D
2885 {"_Z11read_imagei14ocl_image2d_ro11ocl_samplerDv2_i",
2886 "_Z11read_imagei14ocl_image2d_ro11ocl_samplerDv2_f"},
2887 {"_Z12read_imageui14ocl_image2d_ro11ocl_samplerDv2_i",
2888 "_Z12read_imageui14ocl_image2d_ro11ocl_samplerDv2_f"},
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002889 {"_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_i",
2890 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f"},
alan-baker7150a1d2020-02-25 08:31:06 -05002891 // 2D array
2892 {"_Z11read_imagei20ocl_image2d_array_ro11ocl_samplerDv4_i",
2893 "_Z11read_imagei20ocl_image2d_array_ro11ocl_samplerDv4_f"},
2894 {"_Z12read_imageui20ocl_image2d_array_ro11ocl_samplerDv4_i",
2895 "_Z12read_imageui20ocl_image2d_array_ro11ocl_samplerDv4_f"},
2896 {"_Z11read_imagef20ocl_image2d_array_ro11ocl_samplerDv4_i",
2897 "_Z11read_imagef20ocl_image2d_array_ro11ocl_samplerDv4_f"},
Kévin Petit06517a12019-12-09 19:40:31 +00002898 // 3D
2899 {"_Z11read_imagei14ocl_image3d_ro11ocl_samplerDv4_i",
2900 "_Z11read_imagei14ocl_image3d_ro11ocl_samplerDv4_f"},
2901 {"_Z12read_imageui14ocl_image3d_ro11ocl_samplerDv4_i",
2902 "_Z12read_imageui14ocl_image3d_ro11ocl_samplerDv4_f"},
2903 {"_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_i",
2904 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f"}};
David Neto22f144c2017-06-12 14:26:21 -04002905
2906 for (auto Pair : Map) {
2907 // If we find a function with the matching name.
2908 if (auto F = M.getFunction(Pair.first)) {
2909 SmallVector<Instruction *, 4> ToRemoves;
2910
2911 // Walk the users of the function.
2912 for (auto &U : F->uses()) {
2913 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2914 // The image.
2915 auto Arg0 = CI->getOperand(0);
2916
2917 // The sampler.
2918 auto Arg1 = CI->getOperand(1);
2919
2920 // The coordinate (integer type that we can't handle).
2921 auto Arg2 = CI->getOperand(2);
2922
alan-bakerf906d2b2019-12-10 11:26:23 -05002923 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
alan-baker7150a1d2020-02-25 08:31:06 -05002924 uint32_t components =
2925 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
alan-bakerf906d2b2019-12-10 11:26:23 -05002926 Type *float_ty = nullptr;
2927 if (components == 1) {
2928 float_ty = Type::getFloatTy(M.getContext());
2929 } else {
2930 float_ty = VectorType::get(Type::getFloatTy(M.getContext()),
2931 Arg2->getType()->getVectorNumElements());
2932 }
David Neto22f144c2017-06-12 14:26:21 -04002933
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002934 auto NewFType = FunctionType::get(
alan-bakerf906d2b2019-12-10 11:26:23 -05002935 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty},
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002936 false);
David Neto22f144c2017-06-12 14:26:21 -04002937
2938 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
2939
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002940 auto Cast =
alan-bakerf906d2b2019-12-10 11:26:23 -05002941 CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002942
2943 auto NewCI = CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2944
2945 CI->replaceAllUsesWith(NewCI);
2946
2947 // Lastly, remember to remove the user.
2948 ToRemoves.push_back(CI);
2949 }
2950 }
2951
2952 Changed = !ToRemoves.empty();
2953
2954 // And cleanup the calls we don't use anymore.
2955 for (auto V : ToRemoves) {
2956 V->eraseFromParent();
2957 }
2958
2959 // And remove the function we don't need either too.
2960 F->eraseFromParent();
2961 }
2962 }
2963
2964 return Changed;
2965}
2966
2967bool ReplaceOpenCLBuiltinPass::replaceAtomics(Module &M) {
2968 bool Changed = false;
2969
Kévin Petit9b340262019-06-19 18:31:11 +01002970 const std::map<const char *, spv::Op> Map = {
2971 {"_Z8atom_incPU3AS1Vi", spv::OpAtomicIIncrement},
2972 {"_Z8atom_incPU3AS3Vi", spv::OpAtomicIIncrement},
2973 {"_Z8atom_incPU3AS1Vj", spv::OpAtomicIIncrement},
2974 {"_Z8atom_incPU3AS3Vj", spv::OpAtomicIIncrement},
2975 {"_Z8atom_decPU3AS1Vi", spv::OpAtomicIDecrement},
2976 {"_Z8atom_decPU3AS3Vi", spv::OpAtomicIDecrement},
2977 {"_Z8atom_decPU3AS1Vj", spv::OpAtomicIDecrement},
2978 {"_Z8atom_decPU3AS3Vj", spv::OpAtomicIDecrement},
2979 {"_Z12atom_cmpxchgPU3AS1Viii", spv::OpAtomicCompareExchange},
2980 {"_Z12atom_cmpxchgPU3AS3Viii", spv::OpAtomicCompareExchange},
2981 {"_Z12atom_cmpxchgPU3AS1Vjjj", spv::OpAtomicCompareExchange},
2982 {"_Z12atom_cmpxchgPU3AS3Vjjj", spv::OpAtomicCompareExchange},
2983 {"_Z10atomic_incPU3AS1Vi", spv::OpAtomicIIncrement},
2984 {"_Z10atomic_incPU3AS3Vi", spv::OpAtomicIIncrement},
2985 {"_Z10atomic_incPU3AS1Vj", spv::OpAtomicIIncrement},
2986 {"_Z10atomic_incPU3AS3Vj", spv::OpAtomicIIncrement},
2987 {"_Z10atomic_decPU3AS1Vi", spv::OpAtomicIDecrement},
2988 {"_Z10atomic_decPU3AS3Vi", spv::OpAtomicIDecrement},
2989 {"_Z10atomic_decPU3AS1Vj", spv::OpAtomicIDecrement},
2990 {"_Z10atomic_decPU3AS3Vj", spv::OpAtomicIDecrement},
2991 {"_Z14atomic_cmpxchgPU3AS1Viii", spv::OpAtomicCompareExchange},
2992 {"_Z14atomic_cmpxchgPU3AS3Viii", spv::OpAtomicCompareExchange},
2993 {"_Z14atomic_cmpxchgPU3AS1Vjjj", spv::OpAtomicCompareExchange},
2994 {"_Z14atomic_cmpxchgPU3AS3Vjjj", spv::OpAtomicCompareExchange}};
David Neto22f144c2017-06-12 14:26:21 -04002995
2996 for (auto Pair : Map) {
2997 // If we find a function with the matching name.
2998 if (auto F = M.getFunction(Pair.first)) {
2999 SmallVector<Instruction *, 4> ToRemoves;
3000
3001 // Walk the users of the function.
3002 for (auto &U : F->uses()) {
3003 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
David Neto22f144c2017-06-12 14:26:21 -04003004
3005 auto IntTy = Type::getInt32Ty(M.getContext());
3006
David Neto22f144c2017-06-12 14:26:21 -04003007 // We need to map the OpenCL constants to the SPIR-V equivalents.
3008 const auto ConstantScopeDevice =
3009 ConstantInt::get(IntTy, spv::ScopeDevice);
3010 const auto ConstantMemorySemantics = ConstantInt::get(
3011 IntTy, spv::MemorySemanticsUniformMemoryMask |
3012 spv::MemorySemanticsSequentiallyConsistentMask);
3013
3014 SmallVector<Value *, 5> Params;
3015
3016 // The pointer.
3017 Params.push_back(CI->getArgOperand(0));
3018
3019 // The memory scope.
3020 Params.push_back(ConstantScopeDevice);
3021
3022 // The memory semantics.
3023 Params.push_back(ConstantMemorySemantics);
3024
3025 if (2 < CI->getNumArgOperands()) {
3026 // The unequal memory semantics.
3027 Params.push_back(ConstantMemorySemantics);
3028
3029 // The value.
3030 Params.push_back(CI->getArgOperand(2));
3031
3032 // The comparator.
3033 Params.push_back(CI->getArgOperand(1));
3034 } else if (1 < CI->getNumArgOperands()) {
3035 // The value.
3036 Params.push_back(CI->getArgOperand(1));
3037 }
3038
Kévin Petit9b340262019-06-19 18:31:11 +01003039 auto NewCI =
3040 clspv::InsertSPIRVOp(CI, Pair.second, {}, CI->getType(), Params);
David Neto22f144c2017-06-12 14:26:21 -04003041
3042 CI->replaceAllUsesWith(NewCI);
3043
3044 // Lastly, remember to remove the user.
3045 ToRemoves.push_back(CI);
3046 }
3047 }
3048
3049 Changed = !ToRemoves.empty();
3050
3051 // And cleanup the calls we don't use anymore.
3052 for (auto V : ToRemoves) {
3053 V->eraseFromParent();
3054 }
3055
3056 // And remove the function we don't need either too.
3057 F->eraseFromParent();
3058 }
3059 }
3060
Neil Henning39672102017-09-29 14:33:13 +01003061 const std::map<const char *, llvm::AtomicRMWInst::BinOp> Map2 = {
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003062 {"_Z8atom_addPU3AS1Vii", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003063 {"_Z8atom_addPU3AS3Vii", llvm::AtomicRMWInst::Add},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003064 {"_Z8atom_addPU3AS1Vjj", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003065 {"_Z8atom_addPU3AS3Vjj", llvm::AtomicRMWInst::Add},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003066 {"_Z8atom_subPU3AS1Vii", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003067 {"_Z8atom_subPU3AS3Vii", llvm::AtomicRMWInst::Sub},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003068 {"_Z8atom_subPU3AS1Vjj", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003069 {"_Z8atom_subPU3AS3Vjj", llvm::AtomicRMWInst::Sub},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003070 {"_Z9atom_xchgPU3AS1Vii", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003071 {"_Z9atom_xchgPU3AS3Vii", llvm::AtomicRMWInst::Xchg},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003072 {"_Z9atom_xchgPU3AS1Vjj", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003073 {"_Z9atom_xchgPU3AS3Vjj", llvm::AtomicRMWInst::Xchg},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003074 {"_Z8atom_minPU3AS1Vii", llvm::AtomicRMWInst::Min},
Kévin Petita303dc62019-03-26 21:40:35 +00003075 {"_Z8atom_minPU3AS3Vii", llvm::AtomicRMWInst::Min},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003076 {"_Z8atom_minPU3AS1Vjj", llvm::AtomicRMWInst::UMin},
Kévin Petita303dc62019-03-26 21:40:35 +00003077 {"_Z8atom_minPU3AS3Vjj", llvm::AtomicRMWInst::UMin},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003078 {"_Z8atom_maxPU3AS1Vii", llvm::AtomicRMWInst::Max},
Kévin Petita303dc62019-03-26 21:40:35 +00003079 {"_Z8atom_maxPU3AS3Vii", llvm::AtomicRMWInst::Max},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003080 {"_Z8atom_maxPU3AS1Vjj", llvm::AtomicRMWInst::UMax},
Kévin Petita303dc62019-03-26 21:40:35 +00003081 {"_Z8atom_maxPU3AS3Vjj", llvm::AtomicRMWInst::UMax},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003082 {"_Z8atom_andPU3AS1Vii", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003083 {"_Z8atom_andPU3AS3Vii", llvm::AtomicRMWInst::And},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003084 {"_Z8atom_andPU3AS1Vjj", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003085 {"_Z8atom_andPU3AS3Vjj", llvm::AtomicRMWInst::And},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003086 {"_Z7atom_orPU3AS1Vii", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003087 {"_Z7atom_orPU3AS3Vii", llvm::AtomicRMWInst::Or},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003088 {"_Z7atom_orPU3AS1Vjj", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003089 {"_Z7atom_orPU3AS3Vjj", llvm::AtomicRMWInst::Or},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003090 {"_Z8atom_xorPU3AS1Vii", llvm::AtomicRMWInst::Xor},
Kévin Petita303dc62019-03-26 21:40:35 +00003091 {"_Z8atom_xorPU3AS3Vii", llvm::AtomicRMWInst::Xor},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003092 {"_Z8atom_xorPU3AS1Vjj", llvm::AtomicRMWInst::Xor},
Kévin Petita303dc62019-03-26 21:40:35 +00003093 {"_Z8atom_xorPU3AS3Vjj", llvm::AtomicRMWInst::Xor},
Neil Henning39672102017-09-29 14:33:13 +01003094 {"_Z10atomic_addPU3AS1Vii", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003095 {"_Z10atomic_addPU3AS3Vii", llvm::AtomicRMWInst::Add},
Neil Henning39672102017-09-29 14:33:13 +01003096 {"_Z10atomic_addPU3AS1Vjj", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003097 {"_Z10atomic_addPU3AS3Vjj", llvm::AtomicRMWInst::Add},
Neil Henning39672102017-09-29 14:33:13 +01003098 {"_Z10atomic_subPU3AS1Vii", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003099 {"_Z10atomic_subPU3AS3Vii", llvm::AtomicRMWInst::Sub},
Neil Henning39672102017-09-29 14:33:13 +01003100 {"_Z10atomic_subPU3AS1Vjj", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003101 {"_Z10atomic_subPU3AS3Vjj", llvm::AtomicRMWInst::Sub},
Neil Henning39672102017-09-29 14:33:13 +01003102 {"_Z11atomic_xchgPU3AS1Vii", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003103 {"_Z11atomic_xchgPU3AS3Vii", llvm::AtomicRMWInst::Xchg},
Neil Henning39672102017-09-29 14:33:13 +01003104 {"_Z11atomic_xchgPU3AS1Vjj", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003105 {"_Z11atomic_xchgPU3AS3Vjj", llvm::AtomicRMWInst::Xchg},
Neil Henning39672102017-09-29 14:33:13 +01003106 {"_Z10atomic_minPU3AS1Vii", llvm::AtomicRMWInst::Min},
Kévin Petita303dc62019-03-26 21:40:35 +00003107 {"_Z10atomic_minPU3AS3Vii", llvm::AtomicRMWInst::Min},
Neil Henning39672102017-09-29 14:33:13 +01003108 {"_Z10atomic_minPU3AS1Vjj", llvm::AtomicRMWInst::UMin},
Kévin Petita303dc62019-03-26 21:40:35 +00003109 {"_Z10atomic_minPU3AS3Vjj", llvm::AtomicRMWInst::UMin},
Neil Henning39672102017-09-29 14:33:13 +01003110 {"_Z10atomic_maxPU3AS1Vii", llvm::AtomicRMWInst::Max},
Kévin Petita303dc62019-03-26 21:40:35 +00003111 {"_Z10atomic_maxPU3AS3Vii", llvm::AtomicRMWInst::Max},
Neil Henning39672102017-09-29 14:33:13 +01003112 {"_Z10atomic_maxPU3AS1Vjj", llvm::AtomicRMWInst::UMax},
Kévin Petita303dc62019-03-26 21:40:35 +00003113 {"_Z10atomic_maxPU3AS3Vjj", llvm::AtomicRMWInst::UMax},
Neil Henning39672102017-09-29 14:33:13 +01003114 {"_Z10atomic_andPU3AS1Vii", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003115 {"_Z10atomic_andPU3AS3Vii", llvm::AtomicRMWInst::And},
Neil Henning39672102017-09-29 14:33:13 +01003116 {"_Z10atomic_andPU3AS1Vjj", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003117 {"_Z10atomic_andPU3AS3Vjj", llvm::AtomicRMWInst::And},
Neil Henning39672102017-09-29 14:33:13 +01003118 {"_Z9atomic_orPU3AS1Vii", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003119 {"_Z9atomic_orPU3AS3Vii", llvm::AtomicRMWInst::Or},
Neil Henning39672102017-09-29 14:33:13 +01003120 {"_Z9atomic_orPU3AS1Vjj", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003121 {"_Z9atomic_orPU3AS3Vjj", llvm::AtomicRMWInst::Or},
Neil Henning39672102017-09-29 14:33:13 +01003122 {"_Z10atomic_xorPU3AS1Vii", llvm::AtomicRMWInst::Xor},
Kévin Petita303dc62019-03-26 21:40:35 +00003123 {"_Z10atomic_xorPU3AS3Vii", llvm::AtomicRMWInst::Xor},
3124 {"_Z10atomic_xorPU3AS1Vjj", llvm::AtomicRMWInst::Xor},
3125 {"_Z10atomic_xorPU3AS3Vjj", llvm::AtomicRMWInst::Xor}};
Neil Henning39672102017-09-29 14:33:13 +01003126
3127 for (auto Pair : Map2) {
3128 // If we find a function with the matching name.
3129 if (auto F = M.getFunction(Pair.first)) {
3130 SmallVector<Instruction *, 4> ToRemoves;
3131
3132 // Walk the users of the function.
3133 for (auto &U : F->uses()) {
3134 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
3135 auto AtomicOp = new AtomicRMWInst(
3136 Pair.second, CI->getArgOperand(0), CI->getArgOperand(1),
3137 AtomicOrdering::SequentiallyConsistent, SyncScope::System, CI);
3138
3139 CI->replaceAllUsesWith(AtomicOp);
3140
3141 // Lastly, remember to remove the user.
3142 ToRemoves.push_back(CI);
3143 }
3144 }
3145
3146 Changed = !ToRemoves.empty();
3147
3148 // And cleanup the calls we don't use anymore.
3149 for (auto V : ToRemoves) {
3150 V->eraseFromParent();
3151 }
3152
3153 // And remove the function we don't need either too.
3154 F->eraseFromParent();
3155 }
3156 }
3157
David Neto22f144c2017-06-12 14:26:21 -04003158 return Changed;
3159}
3160
3161bool ReplaceOpenCLBuiltinPass::replaceCross(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04003162
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003163 std::vector<const char *> Names = {
3164 "_Z5crossDv4_fS_",
Kévin Petite8edce32019-04-10 14:23:32 +01003165 };
3166
3167 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04003168 auto IntTy = Type::getInt32Ty(M.getContext());
3169 auto FloatTy = Type::getFloatTy(M.getContext());
3170
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003171 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
3172 ConstantInt::get(IntTy, 1),
3173 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04003174
3175 Constant *UpShuffleMask[4] = {
3176 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
3177 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
3178
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003179 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
3180 UndefValue::get(FloatTy),
3181 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04003182
Kévin Petite8edce32019-04-10 14:23:32 +01003183 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003184 auto Arg0 =
3185 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
3186 ConstantVector::get(DownShuffleMask), "", CI);
3187 auto Arg1 =
3188 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
3189 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01003190 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04003191
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003192 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
David Neto22f144c2017-06-12 14:26:21 -04003193
Kévin Petite8edce32019-04-10 14:23:32 +01003194 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04003195
Kévin Petite8edce32019-04-10 14:23:32 +01003196 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04003197
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003198 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
3199 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01003200 });
David Neto22f144c2017-06-12 14:26:21 -04003201}
David Neto62653202017-10-16 19:05:18 -04003202
3203bool ReplaceOpenCLBuiltinPass::replaceFract(Module &M) {
3204 bool Changed = false;
3205
3206 // OpenCL's float result = fract(float x, float* ptr)
3207 //
3208 // In the LLVM domain:
3209 //
3210 // %floor_result = call spir_func float @floor(float %x)
3211 // store float %floor_result, float * %ptr
3212 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
3213 // %result = call spir_func float
3214 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
3215 //
3216 // Becomes in the SPIR-V domain, where translations of floor, fmin,
3217 // and clspv.fract occur in the SPIR-V generator pass:
3218 //
3219 // %glsl_ext = OpExtInstImport "GLSL.std.450"
3220 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
3221 // ...
3222 // %floor_result = OpExtInst %float %glsl_ext Floor %x
3223 // OpStore %ptr %floor_result
3224 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
3225 // %fract_result = OpExtInst %float
3226 // %glsl_ext Fmin %fract_intermediate %just_under_1
3227
David Neto62653202017-10-16 19:05:18 -04003228 using std::string;
3229
3230 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
3231 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003232 using QuadType =
3233 std::tuple<const char *, const char *, const char *, const char *>;
David Neto62653202017-10-16 19:05:18 -04003234 auto make_quad = [](const char *a, const char *b, const char *c,
3235 const char *d) {
3236 return std::tuple<const char *, const char *, const char *, const char *>(
3237 a, b, c, d);
3238 };
3239 const std::vector<QuadType> Functions = {
3240 make_quad("_Z5fractfPf", "_Z5floorff", "_Z4fminff", "clspv.fract.f"),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003241 make_quad("_Z5fractDv2_fPS_", "_Z5floorDv2_f", "_Z4fminDv2_ff",
3242 "clspv.fract.v2f"),
3243 make_quad("_Z5fractDv3_fPS_", "_Z5floorDv3_f", "_Z4fminDv3_ff",
3244 "clspv.fract.v3f"),
3245 make_quad("_Z5fractDv4_fPS_", "_Z5floorDv4_f", "_Z4fminDv4_ff",
3246 "clspv.fract.v4f"),
David Neto62653202017-10-16 19:05:18 -04003247 };
3248
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003249 for (auto &quad : Functions) {
David Neto62653202017-10-16 19:05:18 -04003250 const StringRef fract_name(std::get<0>(quad));
3251
3252 // If we find a function with the matching name.
3253 if (auto F = M.getFunction(fract_name)) {
3254 if (F->use_begin() == F->use_end())
3255 continue;
3256
3257 // We have some uses.
3258 Changed = true;
3259
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003260 auto &Context = M.getContext();
David Neto62653202017-10-16 19:05:18 -04003261
3262 const StringRef floor_name(std::get<1>(quad));
3263 const StringRef fmin_name(std::get<2>(quad));
3264 const StringRef clspv_fract_name(std::get<3>(quad));
3265
3266 // This is either float or a float vector. All the float-like
3267 // types are this type.
3268 auto result_ty = F->getReturnType();
3269
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003270 Function *fmin_fn = M.getFunction(fmin_name);
David Neto62653202017-10-16 19:05:18 -04003271 if (!fmin_fn) {
3272 // Make the fmin function.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003273 FunctionType *fn_ty =
3274 FunctionType::get(result_ty, {result_ty, result_ty}, false);
alan-bakerbccf62c2019-03-29 10:32:41 -04003275 fmin_fn =
3276 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
David Neto62653202017-10-16 19:05:18 -04003277 fmin_fn->addFnAttr(Attribute::ReadNone);
3278 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
3279 }
3280
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003281 Function *floor_fn = M.getFunction(floor_name);
David Neto62653202017-10-16 19:05:18 -04003282 if (!floor_fn) {
3283 // Make the floor function.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003284 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
alan-bakerbccf62c2019-03-29 10:32:41 -04003285 floor_fn = cast<Function>(
3286 M.getOrInsertFunction(floor_name, fn_ty).getCallee());
David Neto62653202017-10-16 19:05:18 -04003287 floor_fn->addFnAttr(Attribute::ReadNone);
3288 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
3289 }
3290
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003291 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
David Neto62653202017-10-16 19:05:18 -04003292 if (!clspv_fract_fn) {
3293 // Make the clspv_fract function.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003294 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
alan-bakerbccf62c2019-03-29 10:32:41 -04003295 clspv_fract_fn = cast<Function>(
3296 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
David Neto62653202017-10-16 19:05:18 -04003297 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
3298 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
3299 }
3300
3301 // Number of significant significand bits, whether represented or not.
3302 unsigned num_significand_bits;
3303 switch (result_ty->getScalarType()->getTypeID()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003304 case Type::HalfTyID:
3305 num_significand_bits = 11;
3306 break;
3307 case Type::FloatTyID:
3308 num_significand_bits = 24;
3309 break;
3310 case Type::DoubleTyID:
3311 num_significand_bits = 53;
3312 break;
3313 default:
3314 assert(false && "Unhandled float type when processing fract builtin");
3315 break;
David Neto62653202017-10-16 19:05:18 -04003316 }
3317 // Beware that the disassembler displays this value as
3318 // OpConstant %float 1
3319 // which is not quite right.
3320 const double kJustUnderOneScalar =
3321 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
3322
3323 Constant *just_under_one =
3324 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
3325 if (result_ty->isVectorTy()) {
3326 just_under_one = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04003327 {result_ty->getVectorNumElements(), false}, just_under_one);
David Neto62653202017-10-16 19:05:18 -04003328 }
3329
3330 IRBuilder<> Builder(Context);
3331
3332 SmallVector<Instruction *, 4> ToRemoves;
3333
3334 // Walk the users of the function.
3335 for (auto &U : F->uses()) {
3336 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
3337
3338 Builder.SetInsertPoint(CI);
3339 auto arg = CI->getArgOperand(0);
3340 auto ptr = CI->getArgOperand(1);
3341
3342 // Compute floor result and store it.
3343 auto floor = Builder.CreateCall(floor_fn, {arg});
3344 Builder.CreateStore(floor, ptr);
3345
3346 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003347 auto fract_result =
3348 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
David Neto62653202017-10-16 19:05:18 -04003349
3350 CI->replaceAllUsesWith(fract_result);
3351
3352 // Lastly, remember to remove the user.
3353 ToRemoves.push_back(CI);
3354 }
3355 }
3356
3357 // And cleanup the calls we don't use anymore.
3358 for (auto V : ToRemoves) {
3359 V->eraseFromParent();
3360 }
3361
3362 // And remove the function we don't need either too.
3363 F->eraseFromParent();
3364 }
3365 }
3366
3367 return Changed;
3368}