blob: ab17141596020b9ca81abc81118641b5ae9cf658 [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
100 char typeCode = name.front();
101 name = name.drop_front(1);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400102 switch (typeCode) {
Kévin Petit91bc72e2019-04-08 15:17:46 +0100103 case 'c': // char
104 case 'a': // signed char
105 case 's': // short
106 case 'i': // int
107 case 'l': // long
108 ti.signedness = ArgTypeInfo::SignedNess::Signed;
109 break;
110 case 'h': // unsigned char
111 case 't': // unsigned short
112 case 'j': // unsigned int
113 case 'm': // unsigned long
114 ti.signedness = ArgTypeInfo::SignedNess::Unsigned;
115 break;
116 case 'f':
117 ti.signedness = ArgTypeInfo::SignedNess::None;
118 break;
119 case 'S':
120 ti = prev_ti;
121 if (!name.consume_front("_")) {
122 return false;
123 }
124 break;
125 default:
126 return false;
127 }
128
129 finfo->argTypeInfos.push_back(ti);
130
131 prev_ti = ti;
132 }
133
134 return true;
135 };
Kévin Petit8a560882019-03-21 15:24:34 +0000136};
137
David Neto22f144c2017-06-12 14:26:21 -0400138uint32_t clz(uint32_t v) {
139 uint32_t r;
140 uint32_t shift;
141
142 r = (v > 0xFFFF) << 4;
143 v >>= r;
144 shift = (v > 0xFF) << 3;
145 v >>= shift;
146 r |= shift;
147 shift = (v > 0xF) << 2;
148 v >>= shift;
149 r |= shift;
150 shift = (v > 0x3) << 1;
151 v >>= shift;
152 r |= shift;
153 r |= (v >> 1);
154
155 return r;
156}
157
158Type *getBoolOrBoolVectorTy(LLVMContext &C, unsigned elements) {
159 if (1 == elements) {
160 return Type::getInt1Ty(C);
161 } else {
162 return VectorType::get(Type::getInt1Ty(C), elements);
163 }
164}
165
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100166Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
167 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
168 if (Ty->isVectorTy()) {
169 IntTy = VectorType::get(IntTy, Ty->getVectorNumElements());
170 }
171 return IntTy;
172}
173
David Neto22f144c2017-06-12 14:26:21 -0400174struct ReplaceOpenCLBuiltinPass final : public ModulePass {
175 static char ID;
176 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
177
178 bool runOnModule(Module &M) override;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000179 bool replaceAbs(Module &M);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100180 bool replaceAbsDiff(Module &M);
Kévin Petit8c1be282019-04-02 19:34:25 +0100181 bool replaceCopysign(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400182 bool replaceRecip(Module &M);
183 bool replaceDivide(Module &M);
Kévin Petit1329a002019-06-15 05:54:05 +0100184 bool replaceDot(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400185 bool replaceExp10(Module &M);
Kévin Petit0644a9c2019-06-20 21:08:46 +0100186 bool replaceFmod(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400187 bool replaceLog10(Module &M);
188 bool replaceBarrier(Module &M);
189 bool replaceMemFence(Module &M);
190 bool replaceRelational(Module &M);
191 bool replaceIsInfAndIsNan(Module &M);
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100192 bool replaceIsFinite(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400193 bool replaceAllAndAny(Module &M);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000194 bool replaceUpsample(Module &M);
Kévin Petitd44eef52019-03-08 13:22:14 +0000195 bool replaceRotate(Module &M);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000196 bool replaceConvert(Module &M);
Kévin Petit8a560882019-03-21 15:24:34 +0000197 bool replaceMulHiMadHi(Module &M);
Kévin Petitf5b78a22018-10-25 14:32:17 +0000198 bool replaceSelect(Module &M);
Kévin Petite7d0cce2018-10-31 12:38:56 +0000199 bool replaceBitSelect(Module &M);
Kévin Petit6b0a9532018-10-30 20:00:39 +0000200 bool replaceStepSmoothStep(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400201 bool replaceSignbit(Module &M);
202 bool replaceMadandMad24andMul24(Module &M);
203 bool replaceVloadHalf(Module &M);
204 bool replaceVloadHalf2(Module &M);
205 bool replaceVloadHalf4(Module &M);
David Neto6ad93232018-06-07 15:42:58 -0700206 bool replaceClspvVloadaHalf2(Module &M);
207 bool replaceClspvVloadaHalf4(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400208 bool replaceVstoreHalf(Module &M);
209 bool replaceVstoreHalf2(Module &M);
210 bool replaceVstoreHalf4(Module &M);
alan-bakerf7e17cb2020-01-02 07:29:59 -0500211 bool replaceHalfReadImage(Module &M);
212 bool replaceHalfWriteImage(Module &M);
alan-baker931d18a2019-12-12 08:21:32 -0500213 bool replaceUnsampledReadImage(Module &M);
Kévin Petit06517a12019-12-09 19:40:31 +0000214 bool replaceSampledReadImageWithIntCoords(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400215 bool replaceAtomics(Module &M);
216 bool replaceCross(Module &M);
David Neto62653202017-10-16 19:05:18 -0400217 bool replaceFract(Module &M);
Derek Chowcfd368b2017-10-19 20:58:45 -0700218 bool replaceVload(Module &M);
219 bool replaceVstore(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400220};
Kévin Petit91bc72e2019-04-08 15:17:46 +0100221} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400222
223char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400224INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
225 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400226
227namespace clspv {
228ModulePass *createReplaceOpenCLBuiltinPass() {
229 return new ReplaceOpenCLBuiltinPass();
230}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400231} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400232
233bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
234 bool Changed = false;
235
Kévin Petit2444e9b2018-11-09 14:14:37 +0000236 Changed |= replaceAbs(M);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100237 Changed |= replaceAbsDiff(M);
Kévin Petit8c1be282019-04-02 19:34:25 +0100238 Changed |= replaceCopysign(M);
David Neto22f144c2017-06-12 14:26:21 -0400239 Changed |= replaceRecip(M);
240 Changed |= replaceDivide(M);
Kévin Petit1329a002019-06-15 05:54:05 +0100241 Changed |= replaceDot(M);
David Neto22f144c2017-06-12 14:26:21 -0400242 Changed |= replaceExp10(M);
Kévin Petit0644a9c2019-06-20 21:08:46 +0100243 Changed |= replaceFmod(M);
David Neto22f144c2017-06-12 14:26:21 -0400244 Changed |= replaceLog10(M);
245 Changed |= replaceBarrier(M);
246 Changed |= replaceMemFence(M);
247 Changed |= replaceRelational(M);
248 Changed |= replaceIsInfAndIsNan(M);
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100249 Changed |= replaceIsFinite(M);
David Neto22f144c2017-06-12 14:26:21 -0400250 Changed |= replaceAllAndAny(M);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000251 Changed |= replaceUpsample(M);
Kévin Petitd44eef52019-03-08 13:22:14 +0000252 Changed |= replaceRotate(M);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000253 Changed |= replaceConvert(M);
Kévin Petit8a560882019-03-21 15:24:34 +0000254 Changed |= replaceMulHiMadHi(M);
Kévin Petitf5b78a22018-10-25 14:32:17 +0000255 Changed |= replaceSelect(M);
Kévin Petite7d0cce2018-10-31 12:38:56 +0000256 Changed |= replaceBitSelect(M);
Kévin Petit6b0a9532018-10-30 20:00:39 +0000257 Changed |= replaceStepSmoothStep(M);
David Neto22f144c2017-06-12 14:26:21 -0400258 Changed |= replaceSignbit(M);
259 Changed |= replaceMadandMad24andMul24(M);
260 Changed |= replaceVloadHalf(M);
261 Changed |= replaceVloadHalf2(M);
262 Changed |= replaceVloadHalf4(M);
David Neto6ad93232018-06-07 15:42:58 -0700263 Changed |= replaceClspvVloadaHalf2(M);
264 Changed |= replaceClspvVloadaHalf4(M);
David Neto22f144c2017-06-12 14:26:21 -0400265 Changed |= replaceVstoreHalf(M);
266 Changed |= replaceVstoreHalf2(M);
267 Changed |= replaceVstoreHalf4(M);
alan-bakerf7e17cb2020-01-02 07:29:59 -0500268 // Replace the half image builtins before handling other image builtins.
269 Changed |= replaceHalfReadImage(M);
270 Changed |= replaceHalfWriteImage(M);
alan-baker931d18a2019-12-12 08:21:32 -0500271 // Replace unsampled reads before converting sampled read coordinates.
272 Changed |= replaceUnsampledReadImage(M);
Kévin Petit06517a12019-12-09 19:40:31 +0000273 Changed |= replaceSampledReadImageWithIntCoords(M);
David Neto22f144c2017-06-12 14:26:21 -0400274 Changed |= replaceAtomics(M);
275 Changed |= replaceCross(M);
David Neto62653202017-10-16 19:05:18 -0400276 Changed |= replaceFract(M);
Derek Chowcfd368b2017-10-19 20:58:45 -0700277 Changed |= replaceVload(M);
278 Changed |= replaceVstore(M);
David Neto22f144c2017-06-12 14:26:21 -0400279
280 return Changed;
281}
282
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400283bool replaceCallsWithValue(Module &M, std::vector<const char *> Names,
284 std::function<Value *(CallInst *)> Replacer) {
Kévin Petit2444e9b2018-11-09 14:14:37 +0000285
Kévin Petite8edce32019-04-10 14:23:32 +0100286 bool Changed = false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000287
288 for (auto Name : Names) {
289 // If we find a function with the matching name.
290 if (auto F = M.getFunction(Name)) {
291 SmallVector<Instruction *, 4> ToRemoves;
292
293 // Walk the users of the function.
294 for (auto &U : F->uses()) {
295 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
Kévin Petit2444e9b2018-11-09 14:14:37 +0000296
Kévin Petite8edce32019-04-10 14:23:32 +0100297 auto NewValue = Replacer(CI);
298
299 if (NewValue != nullptr) {
300 CI->replaceAllUsesWith(NewValue);
301 }
Kévin Petit2444e9b2018-11-09 14:14:37 +0000302
303 // Lastly, remember to remove the user.
304 ToRemoves.push_back(CI);
305 }
306 }
307
308 Changed = !ToRemoves.empty();
309
310 // And cleanup the calls we don't use anymore.
311 for (auto V : ToRemoves) {
312 V->eraseFromParent();
313 }
314
315 // And remove the function we don't need either too.
316 F->eraseFromParent();
317 }
318 }
319
320 return Changed;
321}
322
Kévin Petite8edce32019-04-10 14:23:32 +0100323bool ReplaceOpenCLBuiltinPass::replaceAbs(Module &M) {
Kévin Petit91bc72e2019-04-08 15:17:46 +0100324
Kévin Petite8edce32019-04-10 14:23:32 +0100325 std::vector<const char *> Names = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400326 "_Z3absh", "_Z3absDv2_h", "_Z3absDv3_h", "_Z3absDv4_h",
327 "_Z3abst", "_Z3absDv2_t", "_Z3absDv3_t", "_Z3absDv4_t",
328 "_Z3absj", "_Z3absDv2_j", "_Z3absDv3_j", "_Z3absDv4_j",
329 "_Z3absm", "_Z3absDv2_m", "_Z3absDv3_m", "_Z3absDv4_m",
Kévin Petite8edce32019-04-10 14:23:32 +0100330 };
331
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400332 return replaceCallsWithValue(M, Names,
333 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100334}
335
336bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Module &M) {
337
338 std::vector<const char *> Names = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400339 "_Z8abs_diffcc", "_Z8abs_diffDv2_cS_", "_Z8abs_diffDv3_cS_",
340 "_Z8abs_diffDv4_cS_", "_Z8abs_diffhh", "_Z8abs_diffDv2_hS_",
341 "_Z8abs_diffDv3_hS_", "_Z8abs_diffDv4_hS_", "_Z8abs_diffss",
342 "_Z8abs_diffDv2_sS_", "_Z8abs_diffDv3_sS_", "_Z8abs_diffDv4_sS_",
343 "_Z8abs_difftt", "_Z8abs_diffDv2_tS_", "_Z8abs_diffDv3_tS_",
344 "_Z8abs_diffDv4_tS_", "_Z8abs_diffii", "_Z8abs_diffDv2_iS_",
345 "_Z8abs_diffDv3_iS_", "_Z8abs_diffDv4_iS_", "_Z8abs_diffjj",
346 "_Z8abs_diffDv2_jS_", "_Z8abs_diffDv3_jS_", "_Z8abs_diffDv4_jS_",
347 "_Z8abs_diffll", "_Z8abs_diffDv2_lS_", "_Z8abs_diffDv3_lS_",
348 "_Z8abs_diffDv4_lS_", "_Z8abs_diffmm", "_Z8abs_diffDv2_mS_",
349 "_Z8abs_diffDv3_mS_", "_Z8abs_diffDv4_mS_",
Kévin Petit91bc72e2019-04-08 15:17:46 +0100350 };
351
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400352 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100353 auto XValue = CI->getOperand(0);
354 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100355
Kévin Petite8edce32019-04-10 14:23:32 +0100356 IRBuilder<> Builder(CI);
357 auto XmY = Builder.CreateSub(XValue, YValue);
358 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100359
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400360 Value *Cmp;
Kévin Petite8edce32019-04-10 14:23:32 +0100361 auto F = CI->getCalledFunction();
362 auto finfo = FunctionInfo::getFromMangledName(F->getName());
363 if (finfo.isArgSigned(0)) {
364 Cmp = Builder.CreateICmpSGT(YValue, XValue);
365 } else {
366 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100367 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100368
Kévin Petite8edce32019-04-10 14:23:32 +0100369 return Builder.CreateSelect(Cmp, YmX, XmY);
370 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100371}
372
Kévin Petit8c1be282019-04-02 19:34:25 +0100373bool ReplaceOpenCLBuiltinPass::replaceCopysign(Module &M) {
Kévin Petit8c1be282019-04-02 19:34:25 +0100374
Kévin Petite8edce32019-04-10 14:23:32 +0100375 std::vector<const char *> Names = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400376 "_Z8copysignff",
377 "_Z8copysignDv2_fS_",
378 "_Z8copysignDv3_fS_",
379 "_Z8copysignDv4_fS_",
Kévin Petit8c1be282019-04-02 19:34:25 +0100380 };
381
Kévin Petite8edce32019-04-10 14:23:32 +0100382 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
383 auto XValue = CI->getOperand(0);
384 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100385
Kévin Petite8edce32019-04-10 14:23:32 +0100386 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100387
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400388 Type *IntTy = Type::getIntNTy(M.getContext(), Ty->getScalarSizeInBits());
Kévin Petite8edce32019-04-10 14:23:32 +0100389 if (Ty->isVectorTy()) {
390 IntTy = VectorType::get(IntTy, Ty->getVectorNumElements());
Kévin Petit8c1be282019-04-02 19:34:25 +0100391 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100392
Kévin Petite8edce32019-04-10 14:23:32 +0100393 // Return X with the sign of Y
394
395 // Sign bit masks
396 auto SignBit = IntTy->getScalarSizeInBits() - 1;
397 auto SignBitMask = 1 << SignBit;
398 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
399 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
400
401 IRBuilder<> Builder(CI);
402
403 // Extract sign of Y
404 auto YInt = Builder.CreateBitCast(YValue, IntTy);
405 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
406
407 // Clear sign bit in X
408 auto XInt = Builder.CreateBitCast(XValue, IntTy);
409 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
410
411 // Insert sign bit of Y into X
412 auto NewXInt = Builder.CreateOr(XInt, YSign);
413
414 // And cast back to floating-point
415 return Builder.CreateBitCast(NewXInt, Ty);
416 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100417}
418
David Neto22f144c2017-06-12 14:26:21 -0400419bool ReplaceOpenCLBuiltinPass::replaceRecip(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -0400420
Kévin Petite8edce32019-04-10 14:23:32 +0100421 std::vector<const char *> Names = {
David Neto22f144c2017-06-12 14:26:21 -0400422 "_Z10half_recipf", "_Z12native_recipf", "_Z10half_recipDv2_f",
423 "_Z12native_recipDv2_f", "_Z10half_recipDv3_f", "_Z12native_recipDv3_f",
424 "_Z10half_recipDv4_f", "_Z12native_recipDv4_f",
425 };
426
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400427 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100428 // Recip has one arg.
429 auto Arg = CI->getOperand(0);
430 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
431 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
432 });
David Neto22f144c2017-06-12 14:26:21 -0400433}
434
435bool ReplaceOpenCLBuiltinPass::replaceDivide(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -0400436
Kévin Petite8edce32019-04-10 14:23:32 +0100437 std::vector<const char *> Names = {
David Neto22f144c2017-06-12 14:26:21 -0400438 "_Z11half_divideff", "_Z13native_divideff",
439 "_Z11half_divideDv2_fS_", "_Z13native_divideDv2_fS_",
440 "_Z11half_divideDv3_fS_", "_Z13native_divideDv3_fS_",
441 "_Z11half_divideDv4_fS_", "_Z13native_divideDv4_fS_",
442 };
443
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400444 return replaceCallsWithValue(M, Names, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100445 auto Op0 = CI->getOperand(0);
446 auto Op1 = CI->getOperand(1);
447 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
448 });
David Neto22f144c2017-06-12 14:26:21 -0400449}
450
Kévin Petit1329a002019-06-15 05:54:05 +0100451bool ReplaceOpenCLBuiltinPass::replaceDot(Module &M) {
452
453 std::vector<const char *> Names = {
454 "_Z3dotff",
455 "_Z3dotDv2_fS_",
456 "_Z3dotDv3_fS_",
457 "_Z3dotDv4_fS_",
458 };
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;
1369 if (SrcIsFloat && DstIsFloat) {
1370 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1371 } else if (SrcIsFloat && DstIsInt) {
1372 if (DstIsSigned) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001373 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "",
1374 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001375 } else {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001376 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "",
1377 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001378 }
1379 } else if (SrcIsInt && DstIsFloat) {
1380 if (SrcIsSigned) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001381 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "",
1382 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001383 } else {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001384 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "",
1385 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001386 }
1387 } else if (SrcIsInt && DstIsInt) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001388 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "",
1389 CI);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001390 } else {
1391 // Not something we're supposed to handle, just move on
1392 continue;
1393 }
1394
1395 // Replace call with the expression
1396 CI->replaceAllUsesWith(V);
1397
1398 // Lastly, remember to remove the user.
1399 ToRemoves.push_back(CI);
1400 }
1401 }
1402
1403 Changed = !ToRemoves.empty();
1404
1405 // And cleanup the calls we don't use anymore.
1406 for (auto V : ToRemoves) {
1407 V->eraseFromParent();
1408 }
1409
1410 // And remove the function we don't need either too.
1411 F->eraseFromParent();
1412 }
1413 }
1414
1415 return Changed;
1416}
1417
Kévin Petit8a560882019-03-21 15:24:34 +00001418bool ReplaceOpenCLBuiltinPass::replaceMulHiMadHi(Module &M) {
1419 bool Changed = false;
1420
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001421 SmallVector<Function *, 4> FnWorklist;
Kévin Petit8a560882019-03-21 15:24:34 +00001422
Kévin Petit617a76d2019-04-04 13:54:16 +01001423 for (auto const &SymVal : M.getValueSymbolTable()) {
Kévin Petit8a560882019-03-21 15:24:34 +00001424 bool isMad = SymVal.getKey().startswith("_Z6mad_hi");
1425 bool isMul = SymVal.getKey().startswith("_Z6mul_hi");
1426
1427 // Skip symbols whose name doesn't match
1428 if (!isMad && !isMul) {
1429 continue;
1430 }
1431
1432 // Is there a function going by that name?
1433 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
Kévin Petit617a76d2019-04-04 13:54:16 +01001434 FnWorklist.push_back(F);
Kévin Petit8a560882019-03-21 15:24:34 +00001435 }
1436 }
1437
Kévin Petit617a76d2019-04-04 13:54:16 +01001438 for (auto F : FnWorklist) {
1439 SmallVector<Instruction *, 4> ToRemoves;
1440
1441 bool isMad = F->getName().startswith("_Z6mad_hi");
1442 // Walk the users of the function.
1443 for (auto &U : F->uses()) {
1444 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1445
1446 // Get arguments
1447 auto AValue = CI->getOperand(0);
1448 auto BValue = CI->getOperand(1);
1449 auto CValue = CI->getOperand(2);
1450
1451 // Don't touch overloads that aren't in OpenCL C
1452 auto AType = AValue->getType();
1453 auto BType = BValue->getType();
1454 auto CType = CValue->getType();
1455
1456 if ((AType != BType) || (CI->getType() != AType) ||
1457 (isMad && (AType != CType))) {
1458 continue;
1459 }
1460
1461 if (!AType->isIntOrIntVectorTy()) {
1462 continue;
1463 }
1464
1465 if ((AType->getScalarSizeInBits() != 8) &&
1466 (AType->getScalarSizeInBits() != 16) &&
1467 (AType->getScalarSizeInBits() != 32) &&
1468 (AType->getScalarSizeInBits() != 64)) {
1469 continue;
1470 }
1471
1472 if (AType->isVectorTy()) {
1473 if ((AType->getVectorNumElements() != 2) &&
1474 (AType->getVectorNumElements() != 3) &&
1475 (AType->getVectorNumElements() != 4) &&
1476 (AType->getVectorNumElements() != 8) &&
1477 (AType->getVectorNumElements() != 16)) {
1478 continue;
1479 }
1480 }
1481
1482 // Get infos from the mangled OpenCL built-in function name
Kévin Petit91bc72e2019-04-08 15:17:46 +01001483 auto finfo = FunctionInfo::getFromMangledName(F->getName());
Kévin Petit617a76d2019-04-04 13:54:16 +01001484
1485 // Select the appropriate signed/unsigned SPIR-V op
1486 spv::Op opcode;
Kévin Petit91bc72e2019-04-08 15:17:46 +01001487 if (finfo.isArgSigned(0)) {
Kévin Petit617a76d2019-04-04 13:54:16 +01001488 opcode = spv::OpSMulExtended;
1489 } else {
1490 opcode = spv::OpUMulExtended;
1491 }
1492
1493 // Our SPIR-V op returns a struct, create a type for it
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001494 SmallVector<Type *, 2> TwoValueType = {AType, AType};
Kévin Petit617a76d2019-04-04 13:54:16 +01001495 auto ExMulRetType = StructType::create(TwoValueType);
1496
1497 // Call the SPIR-V op
1498 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1499 ExMulRetType, {AValue, BValue});
1500
1501 // Get the high part of the result
1502 unsigned Idxs[] = {1};
1503 Value *V = ExtractValueInst::Create(Call, Idxs, "", CI);
1504
1505 // If we're handling a mad_hi, add the third argument to the result
1506 if (isMad) {
1507 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
1508 }
1509
1510 // Replace call with the expression
1511 CI->replaceAllUsesWith(V);
1512
1513 // Lastly, remember to remove the user.
1514 ToRemoves.push_back(CI);
1515 }
1516 }
1517
1518 Changed = !ToRemoves.empty();
1519
1520 // And cleanup the calls we don't use anymore.
1521 for (auto V : ToRemoves) {
1522 V->eraseFromParent();
1523 }
1524
1525 // And remove the function we don't need either too.
1526 F->eraseFromParent();
1527 }
1528
Kévin Petit8a560882019-03-21 15:24:34 +00001529 return Changed;
1530}
1531
Kévin Petitf5b78a22018-10-25 14:32:17 +00001532bool ReplaceOpenCLBuiltinPass::replaceSelect(Module &M) {
1533 bool Changed = false;
1534
1535 for (auto const &SymVal : M.getValueSymbolTable()) {
1536 // Skip symbols whose name doesn't match
1537 if (!SymVal.getKey().startswith("_Z6select")) {
1538 continue;
1539 }
1540 // Is there a function going by that name?
1541 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
1542
1543 SmallVector<Instruction *, 4> ToRemoves;
1544
1545 // Walk the users of the function.
1546 for (auto &U : F->uses()) {
1547 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1548
1549 // Get arguments
1550 auto FalseValue = CI->getOperand(0);
1551 auto TrueValue = CI->getOperand(1);
1552 auto PredicateValue = CI->getOperand(2);
1553
1554 // Don't touch overloads that aren't in OpenCL C
1555 auto FalseType = FalseValue->getType();
1556 auto TrueType = TrueValue->getType();
1557 auto PredicateType = PredicateValue->getType();
1558
1559 if (FalseType != TrueType) {
1560 continue;
1561 }
1562
1563 if (!PredicateType->isIntOrIntVectorTy()) {
1564 continue;
1565 }
1566
1567 if (!FalseType->isIntOrIntVectorTy() &&
1568 !FalseType->getScalarType()->isFloatingPointTy()) {
1569 continue;
1570 }
1571
1572 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1573 continue;
1574 }
1575
1576 if (FalseType->getScalarSizeInBits() !=
1577 PredicateType->getScalarSizeInBits()) {
1578 continue;
1579 }
1580
1581 if (FalseType->isVectorTy()) {
1582 if (FalseType->getVectorNumElements() !=
1583 PredicateType->getVectorNumElements()) {
1584 continue;
1585 }
1586
1587 if ((FalseType->getVectorNumElements() != 2) &&
1588 (FalseType->getVectorNumElements() != 3) &&
1589 (FalseType->getVectorNumElements() != 4) &&
1590 (FalseType->getVectorNumElements() != 8) &&
1591 (FalseType->getVectorNumElements() != 16)) {
1592 continue;
1593 }
1594 }
1595
1596 // Create constant
1597 const auto ZeroValue = Constant::getNullValue(PredicateType);
1598
1599 // Scalar and vector are to be treated differently
1600 CmpInst::Predicate Pred;
1601 if (PredicateType->isVectorTy()) {
1602 Pred = CmpInst::ICMP_SLT;
1603 } else {
1604 Pred = CmpInst::ICMP_NE;
1605 }
1606
1607 // Create comparison instruction
1608 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1609 ZeroValue, "", CI);
1610
1611 // Create select
1612 Value *V = SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1613
1614 // Replace call with the selection
1615 CI->replaceAllUsesWith(V);
1616
1617 // Lastly, remember to remove the user.
1618 ToRemoves.push_back(CI);
1619 }
1620 }
1621
1622 Changed = !ToRemoves.empty();
1623
1624 // And cleanup the calls we don't use anymore.
1625 for (auto V : ToRemoves) {
1626 V->eraseFromParent();
1627 }
1628
1629 // And remove the function we don't need either too.
1630 F->eraseFromParent();
1631 }
1632 }
1633
1634 return Changed;
1635}
1636
Kévin Petite7d0cce2018-10-31 12:38:56 +00001637bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Module &M) {
1638 bool Changed = false;
1639
1640 for (auto const &SymVal : M.getValueSymbolTable()) {
1641 // Skip symbols whose name doesn't match
1642 if (!SymVal.getKey().startswith("_Z9bitselect")) {
1643 continue;
1644 }
1645 // Is there a function going by that name?
1646 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
1647
1648 SmallVector<Instruction *, 4> ToRemoves;
1649
1650 // Walk the users of the function.
1651 for (auto &U : F->uses()) {
1652 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1653
1654 if (CI->getNumOperands() != 4) {
1655 continue;
1656 }
1657
1658 // Get arguments
1659 auto FalseValue = CI->getOperand(0);
1660 auto TrueValue = CI->getOperand(1);
1661 auto PredicateValue = CI->getOperand(2);
1662
1663 // Don't touch overloads that aren't in OpenCL C
1664 auto FalseType = FalseValue->getType();
1665 auto TrueType = TrueValue->getType();
1666 auto PredicateType = PredicateValue->getType();
1667
1668 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1669 continue;
1670 }
1671
1672 if (TrueType->isVectorTy()) {
1673 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1674 !TrueType->getScalarType()->isIntegerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001675 continue;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001676 }
1677 if ((TrueType->getVectorNumElements() != 2) &&
1678 (TrueType->getVectorNumElements() != 3) &&
1679 (TrueType->getVectorNumElements() != 4) &&
1680 (TrueType->getVectorNumElements() != 8) &&
1681 (TrueType->getVectorNumElements() != 16)) {
1682 continue;
1683 }
1684 }
1685
1686 // Remember the type of the operands
1687 auto OpType = TrueType;
1688
1689 // The actual bit selection will always be done on an integer type,
1690 // declare it here
1691 Type *BitType;
1692
1693 // If the operands are float, then bitcast them to int
1694 if (OpType->getScalarType()->isFloatingPointTy()) {
1695
1696 // First create the new type
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001697 BitType = getIntOrIntVectorTyForCast(M.getContext(), OpType);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001698
1699 // Then bitcast all operands
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001700 PredicateValue =
1701 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1702 FalseValue =
1703 CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1704 TrueValue =
1705 CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001706
1707 } else {
1708 // The operands have an integer type, use it directly
1709 BitType = OpType;
1710 }
1711
1712 // All the operands are now always integers
1713 // implement as (c & b) | (~c & a)
1714
1715 // Create our negated predicate value
1716 auto AllOnes = Constant::getAllOnesValue(BitType);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001717 auto NotPredicateValue = BinaryOperator::Create(
1718 Instruction::Xor, PredicateValue, AllOnes, "", CI);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001719
1720 // Then put everything together
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001721 auto BitsFalse = BinaryOperator::Create(
1722 Instruction::And, NotPredicateValue, FalseValue, "", CI);
1723 auto BitsTrue = BinaryOperator::Create(
1724 Instruction::And, PredicateValue, TrueValue, "", CI);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001725
1726 Value *V = BinaryOperator::Create(Instruction::Or, BitsFalse,
1727 BitsTrue, "", CI);
1728
1729 // If we were dealing with a floating point type, we must bitcast
1730 // the result back to that
1731 if (OpType->getScalarType()->isFloatingPointTy()) {
1732 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1733 }
1734
1735 // Replace call with our new code
1736 CI->replaceAllUsesWith(V);
1737
1738 // Lastly, remember to remove the user.
1739 ToRemoves.push_back(CI);
1740 }
1741 }
1742
1743 Changed = !ToRemoves.empty();
1744
1745 // And cleanup the calls we don't use anymore.
1746 for (auto V : ToRemoves) {
1747 V->eraseFromParent();
1748 }
1749
1750 // And remove the function we don't need either too.
1751 F->eraseFromParent();
1752 }
1753 }
1754
1755 return Changed;
1756}
1757
Kévin Petit6b0a9532018-10-30 20:00:39 +00001758bool ReplaceOpenCLBuiltinPass::replaceStepSmoothStep(Module &M) {
1759 bool Changed = false;
1760
1761 const std::map<const char *, const char *> Map = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001762 {"_Z4stepfDv2_f", "_Z4stepDv2_fS_"},
1763 {"_Z4stepfDv3_f", "_Z4stepDv3_fS_"},
1764 {"_Z4stepfDv4_f", "_Z4stepDv4_fS_"},
1765 {"_Z10smoothstepffDv2_f", "_Z10smoothstepDv2_fS_S_"},
1766 {"_Z10smoothstepffDv3_f", "_Z10smoothstepDv3_fS_S_"},
1767 {"_Z10smoothstepffDv4_f", "_Z10smoothstepDv4_fS_S_"},
Kévin Petit6b0a9532018-10-30 20:00:39 +00001768 };
1769
1770 for (auto Pair : Map) {
1771 // If we find a function with the matching name.
1772 if (auto F = M.getFunction(Pair.first)) {
1773 SmallVector<Instruction *, 4> ToRemoves;
1774
1775 // Walk the users of the function.
1776 for (auto &U : F->uses()) {
1777 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1778
1779 auto ReplacementFn = Pair.second;
1780
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001781 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
Kévin Petit6b0a9532018-10-30 20:00:39 +00001782 Value *VectorArg;
1783
1784 // First figure out which function we're dealing with
1785 if (F->getName().startswith("_Z10smoothstep")) {
1786 ArgsToSplat.push_back(CI->getOperand(1));
1787 VectorArg = CI->getOperand(2);
1788 } else {
1789 VectorArg = CI->getOperand(1);
1790 }
1791
1792 // Splat arguments that need to be
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001793 SmallVector<Value *, 2> SplatArgs;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001794 auto VecType = VectorArg->getType();
1795
1796 for (auto arg : ArgsToSplat) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001797 Value *NewVectorArg = UndefValue::get(VecType);
Kévin Petit6b0a9532018-10-30 20:00:39 +00001798 for (auto i = 0; i < VecType->getVectorNumElements(); i++) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001799 auto index =
1800 ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1801 NewVectorArg =
1802 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
Kévin Petit6b0a9532018-10-30 20:00:39 +00001803 }
1804 SplatArgs.push_back(NewVectorArg);
1805 }
1806
1807 // Replace the call with the vector/vector flavour
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001808 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1809 const auto NewFType =
1810 FunctionType::get(CI->getType(), NewArgTypes, false);
Kévin Petit6b0a9532018-10-30 20:00:39 +00001811
1812 const auto NewF = M.getOrInsertFunction(ReplacementFn, NewFType);
1813
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001814 SmallVector<Value *, 3> NewArgs;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001815 for (auto arg : SplatArgs) {
1816 NewArgs.push_back(arg);
1817 }
1818 NewArgs.push_back(VectorArg);
1819
1820 const auto NewCI = CallInst::Create(NewF, NewArgs, "", CI);
1821
1822 CI->replaceAllUsesWith(NewCI);
1823
1824 // Lastly, remember to remove the user.
1825 ToRemoves.push_back(CI);
1826 }
1827 }
1828
1829 Changed = !ToRemoves.empty();
1830
1831 // And cleanup the calls we don't use anymore.
1832 for (auto V : ToRemoves) {
1833 V->eraseFromParent();
1834 }
1835
1836 // And remove the function we don't need either too.
1837 F->eraseFromParent();
1838 }
1839 }
1840
1841 return Changed;
1842}
1843
David Neto22f144c2017-06-12 14:26:21 -04001844bool ReplaceOpenCLBuiltinPass::replaceSignbit(Module &M) {
1845 bool Changed = false;
1846
1847 const std::map<const char *, Instruction::BinaryOps> Map = {
1848 {"_Z7signbitf", Instruction::LShr},
1849 {"_Z7signbitDv2_f", Instruction::AShr},
1850 {"_Z7signbitDv3_f", Instruction::AShr},
1851 {"_Z7signbitDv4_f", Instruction::AShr},
1852 };
1853
1854 for (auto Pair : Map) {
1855 // If we find a function with the matching name.
1856 if (auto F = M.getFunction(Pair.first)) {
1857 SmallVector<Instruction *, 4> ToRemoves;
1858
1859 // Walk the users of the function.
1860 for (auto &U : F->uses()) {
1861 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1862 auto Arg = CI->getOperand(0);
1863
1864 auto Bitcast =
1865 CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
1866
1867 auto Shr = BinaryOperator::Create(Pair.second, Bitcast,
1868 ConstantInt::get(CI->getType(), 31),
1869 "", CI);
1870
1871 CI->replaceAllUsesWith(Shr);
1872
1873 // Lastly, remember to remove the user.
1874 ToRemoves.push_back(CI);
1875 }
1876 }
1877
1878 Changed = !ToRemoves.empty();
1879
1880 // And cleanup the calls we don't use anymore.
1881 for (auto V : ToRemoves) {
1882 V->eraseFromParent();
1883 }
1884
1885 // And remove the function we don't need either too.
1886 F->eraseFromParent();
1887 }
1888 }
1889
1890 return Changed;
1891}
1892
1893bool ReplaceOpenCLBuiltinPass::replaceMadandMad24andMul24(Module &M) {
1894 bool Changed = false;
1895
1896 const std::map<const char *,
1897 std::pair<Instruction::BinaryOps, Instruction::BinaryOps>>
1898 Map = {
1899 {"_Z3madfff", {Instruction::FMul, Instruction::FAdd}},
1900 {"_Z3madDv2_fS_S_", {Instruction::FMul, Instruction::FAdd}},
1901 {"_Z3madDv3_fS_S_", {Instruction::FMul, Instruction::FAdd}},
1902 {"_Z3madDv4_fS_S_", {Instruction::FMul, Instruction::FAdd}},
1903 {"_Z5mad24iii", {Instruction::Mul, Instruction::Add}},
1904 {"_Z5mad24Dv2_iS_S_", {Instruction::Mul, Instruction::Add}},
1905 {"_Z5mad24Dv3_iS_S_", {Instruction::Mul, Instruction::Add}},
1906 {"_Z5mad24Dv4_iS_S_", {Instruction::Mul, Instruction::Add}},
1907 {"_Z5mad24jjj", {Instruction::Mul, Instruction::Add}},
1908 {"_Z5mad24Dv2_jS_S_", {Instruction::Mul, Instruction::Add}},
1909 {"_Z5mad24Dv3_jS_S_", {Instruction::Mul, Instruction::Add}},
1910 {"_Z5mad24Dv4_jS_S_", {Instruction::Mul, Instruction::Add}},
1911 {"_Z5mul24ii", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1912 {"_Z5mul24Dv2_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1913 {"_Z5mul24Dv3_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1914 {"_Z5mul24Dv4_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1915 {"_Z5mul24jj", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1916 {"_Z5mul24Dv2_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1917 {"_Z5mul24Dv3_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1918 {"_Z5mul24Dv4_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
1919 };
1920
1921 for (auto Pair : Map) {
1922 // If we find a function with the matching name.
1923 if (auto F = M.getFunction(Pair.first)) {
1924 SmallVector<Instruction *, 4> ToRemoves;
1925
1926 // Walk the users of the function.
1927 for (auto &U : F->uses()) {
1928 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1929 // The multiply instruction to use.
1930 auto MulInst = Pair.second.first;
1931
1932 // The add instruction to use.
1933 auto AddInst = Pair.second.second;
1934
1935 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
1936
1937 auto I = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1938 CI->getArgOperand(1), "", CI);
1939
1940 if (Instruction::BinaryOpsEnd != AddInst) {
1941 I = BinaryOperator::Create(AddInst, I, CI->getArgOperand(2), "",
1942 CI);
1943 }
1944
1945 CI->replaceAllUsesWith(I);
1946
1947 // Lastly, remember to remove the user.
1948 ToRemoves.push_back(CI);
1949 }
1950 }
1951
1952 Changed = !ToRemoves.empty();
1953
1954 // And cleanup the calls we don't use anymore.
1955 for (auto V : ToRemoves) {
1956 V->eraseFromParent();
1957 }
1958
1959 // And remove the function we don't need either too.
1960 F->eraseFromParent();
1961 }
1962 }
1963
1964 return Changed;
1965}
1966
Derek Chowcfd368b2017-10-19 20:58:45 -07001967bool ReplaceOpenCLBuiltinPass::replaceVstore(Module &M) {
1968 bool Changed = false;
1969
alan-bakerf795f392019-06-11 18:24:34 -04001970 for (auto const &SymVal : M.getValueSymbolTable()) {
1971 if (!SymVal.getKey().contains("vstore"))
1972 continue;
1973 if (SymVal.getKey().contains("vstore_"))
1974 continue;
1975 if (SymVal.getKey().contains("vstorea"))
1976 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07001977
alan-bakerf795f392019-06-11 18:24:34 -04001978 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
Derek Chowcfd368b2017-10-19 20:58:45 -07001979 SmallVector<Instruction *, 4> ToRemoves;
1980
alan-bakerf795f392019-06-11 18:24:34 -04001981 auto fname = F->getName();
1982 if (!fname.consume_front("_Z"))
1983 continue;
1984 size_t name_len;
1985 if (fname.consumeInteger(10, name_len))
1986 continue;
1987 std::string name = fname.take_front(name_len);
1988
1989 bool ok = StringSwitch<bool>(name)
1990 .Case("vstore2", true)
1991 .Case("vstore3", true)
1992 .Case("vstore4", true)
1993 .Case("vstore8", true)
1994 .Case("vstore16", true)
1995 .Default(false);
1996 if (!ok)
1997 continue;
1998
Derek Chowcfd368b2017-10-19 20:58:45 -07001999 for (auto &U : F->uses()) {
2000 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
alan-bakerf795f392019-06-11 18:24:34 -04002001 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07002002
alan-bakerf795f392019-06-11 18:24:34 -04002003 auto data_type = data->getType();
2004 if (!data_type->isVectorTy())
2005 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002006
alan-bakerf795f392019-06-11 18:24:34 -04002007 auto elems = data_type->getVectorNumElements();
2008 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 &&
2009 elems != 16)
2010 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002011
alan-bakerf795f392019-06-11 18:24:34 -04002012 auto offset = CI->getOperand(1);
2013 auto ptr = CI->getOperand(2);
2014 auto ptr_type = ptr->getType();
2015 auto pointee_type = ptr_type->getPointerElementType();
2016 if (pointee_type != data_type->getVectorElementType())
2017 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002018
alan-bakerf795f392019-06-11 18:24:34 -04002019 // Avoid pointer casts. Instead generate the correct number of stores
2020 // and rely on drivers to coalesce appropriately.
2021 IRBuilder<> builder(CI);
2022 auto elems_const = builder.getInt32(elems);
2023 auto adjust = builder.CreateMul(offset, elems_const);
2024 for (auto i = 0; i < elems; ++i) {
2025 auto idx = builder.getInt32(i);
2026 auto add = builder.CreateAdd(adjust, idx);
2027 auto gep = builder.CreateGEP(ptr, add);
2028 auto extract = builder.CreateExtractElement(data, i);
2029 auto store = builder.CreateStore(extract, gep);
2030 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002031
Derek Chowcfd368b2017-10-19 20:58:45 -07002032 ToRemoves.push_back(CI);
2033 }
2034 }
2035
2036 Changed = !ToRemoves.empty();
Derek Chowcfd368b2017-10-19 20:58:45 -07002037 for (auto V : ToRemoves) {
2038 V->eraseFromParent();
2039 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002040 F->eraseFromParent();
2041 }
2042 }
2043
2044 return Changed;
2045}
2046
2047bool ReplaceOpenCLBuiltinPass::replaceVload(Module &M) {
2048 bool Changed = false;
2049
alan-bakerf795f392019-06-11 18:24:34 -04002050 for (auto const &SymVal : M.getValueSymbolTable()) {
2051 if (!SymVal.getKey().contains("vload"))
2052 continue;
2053 if (SymVal.getKey().contains("vload_"))
2054 continue;
2055 if (SymVal.getKey().contains("vloada"))
2056 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002057
alan-bakerf795f392019-06-11 18:24:34 -04002058 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
Derek Chowcfd368b2017-10-19 20:58:45 -07002059 SmallVector<Instruction *, 4> ToRemoves;
2060
alan-bakerf795f392019-06-11 18:24:34 -04002061 auto fname = F->getName();
2062 if (!fname.consume_front("_Z"))
2063 continue;
2064 size_t name_len;
2065 if (fname.consumeInteger(10, name_len))
2066 continue;
2067 std::string name = fname.take_front(name_len);
2068
2069 bool ok = StringSwitch<bool>(name)
2070 .Case("vload2", true)
2071 .Case("vload3", true)
2072 .Case("vload4", true)
2073 .Case("vload8", true)
2074 .Case("vload16", true)
2075 .Default(false);
2076 if (!ok)
2077 continue;
2078
Derek Chowcfd368b2017-10-19 20:58:45 -07002079 for (auto &U : F->uses()) {
2080 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
alan-bakerf795f392019-06-11 18:24:34 -04002081 auto ret_type = F->getReturnType();
2082 if (!ret_type->isVectorTy())
2083 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002084
alan-bakerf795f392019-06-11 18:24:34 -04002085 auto elems = ret_type->getVectorNumElements();
2086 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 &&
2087 elems != 16)
2088 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002089
alan-bakerf795f392019-06-11 18:24:34 -04002090 auto offset = CI->getOperand(0);
2091 auto ptr = CI->getOperand(1);
2092 auto ptr_type = ptr->getType();
2093 auto pointee_type = ptr_type->getPointerElementType();
2094 if (pointee_type != ret_type->getVectorElementType())
2095 continue;
Derek Chowcfd368b2017-10-19 20:58:45 -07002096
alan-bakerf795f392019-06-11 18:24:34 -04002097 // Avoid pointer casts. Instead generate the correct number of loads
2098 // and rely on drivers to coalesce appropriately.
2099 IRBuilder<> builder(CI);
2100 auto elems_const = builder.getInt32(elems);
2101 Value *insert = UndefValue::get(ret_type);
2102 auto adjust = builder.CreateMul(offset, elems_const);
2103 for (auto i = 0; i < elems; ++i) {
2104 auto idx = builder.getInt32(i);
2105 auto add = builder.CreateAdd(adjust, idx);
2106 auto gep = builder.CreateGEP(ptr, add);
2107 auto load = builder.CreateLoad(gep);
2108 insert = builder.CreateInsertElement(insert, load, i);
2109 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002110
alan-bakerf795f392019-06-11 18:24:34 -04002111 CI->replaceAllUsesWith(insert);
Derek Chowcfd368b2017-10-19 20:58:45 -07002112 ToRemoves.push_back(CI);
2113 }
2114 }
2115
2116 Changed = !ToRemoves.empty();
Derek Chowcfd368b2017-10-19 20:58:45 -07002117 for (auto V : ToRemoves) {
2118 V->eraseFromParent();
2119 }
Derek Chowcfd368b2017-10-19 20:58:45 -07002120 F->eraseFromParent();
Derek Chowcfd368b2017-10-19 20:58:45 -07002121 }
2122 }
2123
2124 return Changed;
2125}
2126
David Neto22f144c2017-06-12 14:26:21 -04002127bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Module &M) {
2128 bool Changed = false;
2129
2130 const std::vector<const char *> Map = {"_Z10vload_halfjPU3AS1KDh",
2131 "_Z10vload_halfjPU3AS2KDh"};
2132
2133 for (auto Name : Map) {
2134 // If we find a function with the matching name.
2135 if (auto F = M.getFunction(Name)) {
2136 SmallVector<Instruction *, 4> ToRemoves;
2137
2138 // Walk the users of the function.
2139 for (auto &U : F->uses()) {
2140 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2141 // The index argument from vload_half.
2142 auto Arg0 = CI->getOperand(0);
2143
2144 // The pointer argument from vload_half.
2145 auto Arg1 = CI->getOperand(1);
2146
David Neto22f144c2017-06-12 14:26:21 -04002147 auto IntTy = Type::getInt32Ty(M.getContext());
2148 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
David Neto22f144c2017-06-12 14:26:21 -04002149 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
2150
David Neto22f144c2017-06-12 14:26:21 -04002151 // Our intrinsic to unpack a float2 from an int.
2152 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
2153
2154 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
2155
David Neto482550a2018-03-24 05:21:07 -07002156 if (clspv::Option::F16BitStorage()) {
David Netoac825b82017-05-30 12:49:01 -04002157 auto ShortTy = Type::getInt16Ty(M.getContext());
2158 auto ShortPointerTy = PointerType::get(
2159 ShortTy, Arg1->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002160
David Netoac825b82017-05-30 12:49:01 -04002161 // Cast the half* pointer to short*.
2162 auto Cast =
2163 CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002164
David Netoac825b82017-05-30 12:49:01 -04002165 // Index into the correct address of the casted pointer.
2166 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
2167
2168 // Load from the short* we casted to.
2169 auto Load = new LoadInst(Index, "", CI);
2170
2171 // ZExt the short -> int.
2172 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
2173
2174 // Get our float2.
2175 auto Call = CallInst::Create(NewF, ZExt, "", CI);
2176
2177 // Extract out the bottom element which is our float result.
2178 auto Extract = ExtractElementInst::Create(
2179 Call, ConstantInt::get(IntTy, 0), "", CI);
2180
2181 CI->replaceAllUsesWith(Extract);
2182 } else {
2183 // Assume the pointer argument points to storage aligned to 32bits
2184 // or more.
2185 // TODO(dneto): Do more analysis to make sure this is true?
2186 //
2187 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
2188 // with:
2189 //
2190 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
2191 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
2192 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
2193 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
2194 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
2195 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
2196 // x float> %converted, %index_is_odd32
2197
2198 auto IntPointerTy = PointerType::get(
2199 IntTy, Arg1->getType()->getPointerAddressSpace());
2200
David Neto973e6a82017-05-30 13:48:18 -04002201 // Cast the base pointer to int*.
David Netoac825b82017-05-30 12:49:01 -04002202 // In a valid call (according to assumptions), this should get
David Neto973e6a82017-05-30 13:48:18 -04002203 // optimized away in the simplify GEP pass.
David Netoac825b82017-05-30 12:49:01 -04002204 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
2205
2206 auto One = ConstantInt::get(IntTy, 1);
2207 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
2208 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
2209
2210 // Index into the correct address of the casted pointer.
2211 auto Ptr =
2212 GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
2213
2214 // Load from the int* we casted to.
2215 auto Load = new LoadInst(Ptr, "", CI);
2216
2217 // Get our float2.
2218 auto Call = CallInst::Create(NewF, Load, "", CI);
2219
2220 // Extract out the float result, where the element number is
2221 // determined by whether the original index was even or odd.
2222 auto Extract = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
2223
2224 CI->replaceAllUsesWith(Extract);
2225 }
David Neto22f144c2017-06-12 14:26:21 -04002226
2227 // Lastly, remember to remove the user.
2228 ToRemoves.push_back(CI);
2229 }
2230 }
2231
2232 Changed = !ToRemoves.empty();
2233
2234 // And cleanup the calls we don't use anymore.
2235 for (auto V : ToRemoves) {
2236 V->eraseFromParent();
2237 }
2238
2239 // And remove the function we don't need either too.
2240 F->eraseFromParent();
2241 }
2242 }
2243
2244 return Changed;
2245}
2246
2247bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002248
Kévin Petite8edce32019-04-10 14:23:32 +01002249 const std::vector<const char *> Names = {
David Neto556c7e62018-06-08 13:45:55 -07002250 "_Z11vload_half2jPU3AS1KDh",
2251 "_Z12vloada_half2jPU3AS1KDh", // vloada_half2 global
2252 "_Z11vload_half2jPU3AS2KDh",
2253 "_Z12vloada_half2jPU3AS2KDh", // vloada_half2 constant
2254 };
David Neto22f144c2017-06-12 14:26:21 -04002255
Kévin Petite8edce32019-04-10 14:23:32 +01002256 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2257 // The index argument from vload_half.
2258 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002259
Kévin Petite8edce32019-04-10 14:23:32 +01002260 // The pointer argument from vload_half.
2261 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002262
Kévin Petite8edce32019-04-10 14:23:32 +01002263 auto IntTy = Type::getInt32Ty(M.getContext());
2264 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002265 auto NewPointerTy =
2266 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002267 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04002268
Kévin Petite8edce32019-04-10 14:23:32 +01002269 // Cast the half* pointer to int*.
2270 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002271
Kévin Petite8edce32019-04-10 14:23:32 +01002272 // Index into the correct address of the casted pointer.
2273 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002274
Kévin Petite8edce32019-04-10 14:23:32 +01002275 // Load from the int* we casted to.
2276 auto Load = new LoadInst(Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002277
Kévin Petite8edce32019-04-10 14:23:32 +01002278 // Our intrinsic to unpack a float2 from an int.
2279 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002280
Kévin Petite8edce32019-04-10 14:23:32 +01002281 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002282
Kévin Petite8edce32019-04-10 14:23:32 +01002283 // Get our float2.
2284 return CallInst::Create(NewF, Load, "", CI);
2285 });
David Neto22f144c2017-06-12 14:26:21 -04002286}
2287
2288bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002289
Kévin Petite8edce32019-04-10 14:23:32 +01002290 const std::vector<const char *> Names = {
David Neto556c7e62018-06-08 13:45:55 -07002291 "_Z11vload_half4jPU3AS1KDh",
2292 "_Z12vloada_half4jPU3AS1KDh",
2293 "_Z11vload_half4jPU3AS2KDh",
2294 "_Z12vloada_half4jPU3AS2KDh",
2295 };
David Neto22f144c2017-06-12 14:26:21 -04002296
Kévin Petite8edce32019-04-10 14:23:32 +01002297 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2298 // The index argument from vload_half.
2299 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002300
Kévin Petite8edce32019-04-10 14:23:32 +01002301 // The pointer argument from vload_half.
2302 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002303
Kévin Petite8edce32019-04-10 14:23:32 +01002304 auto IntTy = Type::getInt32Ty(M.getContext());
2305 auto Int2Ty = VectorType::get(IntTy, 2);
2306 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002307 auto NewPointerTy =
2308 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002309 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04002310
Kévin Petite8edce32019-04-10 14:23:32 +01002311 // Cast the half* pointer to int2*.
2312 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002313
Kévin Petite8edce32019-04-10 14:23:32 +01002314 // Index into the correct address of the casted pointer.
2315 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002316
Kévin Petite8edce32019-04-10 14:23:32 +01002317 // Load from the int2* we casted to.
2318 auto Load = new LoadInst(Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002319
Kévin Petite8edce32019-04-10 14:23:32 +01002320 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002321 auto X =
2322 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
2323 auto Y =
2324 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002325
Kévin Petite8edce32019-04-10 14:23:32 +01002326 // Our intrinsic to unpack a float2 from an int.
2327 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002328
Kévin Petite8edce32019-04-10 14:23:32 +01002329 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002330
Kévin Petite8edce32019-04-10 14:23:32 +01002331 // Get the lower (x & y) components of our final float4.
2332 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002333
Kévin Petite8edce32019-04-10 14:23:32 +01002334 // Get the higher (z & w) components of our final float4.
2335 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002336
Kévin Petite8edce32019-04-10 14:23:32 +01002337 Constant *ShuffleMask[4] = {
2338 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2339 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002340
Kévin Petite8edce32019-04-10 14:23:32 +01002341 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002342 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
2343 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002344 });
David Neto22f144c2017-06-12 14:26:21 -04002345}
2346
David Neto6ad93232018-06-07 15:42:58 -07002347bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Module &M) {
David Neto6ad93232018-06-07 15:42:58 -07002348
2349 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
2350 //
2351 // %u = load i32 %ptr
2352 // %fxy = call <2 x float> Unpack2xHalf(u)
2353 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
Kévin Petite8edce32019-04-10 14:23:32 +01002354 const std::vector<const char *> Names = {
David Neto6ad93232018-06-07 15:42:58 -07002355 "_Z20__clspv_vloada_half2jPU3AS1Kj", // global
2356 "_Z20__clspv_vloada_half2jPU3AS3Kj", // local
2357 "_Z20__clspv_vloada_half2jPKj", // private
2358 };
2359
Kévin Petite8edce32019-04-10 14:23:32 +01002360 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2361 auto Index = CI->getOperand(0);
2362 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07002363
Kévin Petite8edce32019-04-10 14:23:32 +01002364 auto IntTy = Type::getInt32Ty(M.getContext());
2365 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
2366 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07002367
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002368 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002369 auto Load = new LoadInst(IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002370
Kévin Petite8edce32019-04-10 14:23:32 +01002371 // Our intrinsic to unpack a float2 from an int.
2372 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07002373
Kévin Petite8edce32019-04-10 14:23:32 +01002374 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07002375
Kévin Petite8edce32019-04-10 14:23:32 +01002376 // Get our final float2.
2377 return CallInst::Create(NewF, Load, "", CI);
2378 });
David Neto6ad93232018-06-07 15:42:58 -07002379}
2380
2381bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Module &M) {
David Neto6ad93232018-06-07 15:42:58 -07002382
2383 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
2384 //
2385 // %u2 = load <2 x i32> %ptr
2386 // %u2xy = extractelement %u2, 0
2387 // %u2zw = extractelement %u2, 1
2388 // %fxy = call <2 x float> Unpack2xHalf(uint)
2389 // %fzw = call <2 x float> Unpack2xHalf(uint)
2390 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
Kévin Petite8edce32019-04-10 14:23:32 +01002391 const std::vector<const char *> Names = {
David Neto6ad93232018-06-07 15:42:58 -07002392 "_Z20__clspv_vloada_half4jPU3AS1KDv2_j", // global
2393 "_Z20__clspv_vloada_half4jPU3AS3KDv2_j", // local
2394 "_Z20__clspv_vloada_half4jPKDv2_j", // private
2395 };
2396
Kévin Petite8edce32019-04-10 14:23:32 +01002397 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2398 auto Index = CI->getOperand(0);
2399 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07002400
Kévin Petite8edce32019-04-10 14:23:32 +01002401 auto IntTy = Type::getInt32Ty(M.getContext());
2402 auto Int2Ty = VectorType::get(IntTy, 2);
2403 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
2404 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07002405
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002406 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002407 auto Load = new LoadInst(IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002408
Kévin Petite8edce32019-04-10 14:23:32 +01002409 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002410 auto X =
2411 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
2412 auto Y =
2413 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002414
Kévin Petite8edce32019-04-10 14:23:32 +01002415 // Our intrinsic to unpack a float2 from an int.
2416 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07002417
Kévin Petite8edce32019-04-10 14:23:32 +01002418 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07002419
Kévin Petite8edce32019-04-10 14:23:32 +01002420 // Get the lower (x & y) components of our final float4.
2421 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002422
Kévin Petite8edce32019-04-10 14:23:32 +01002423 // Get the higher (z & w) components of our final float4.
2424 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07002425
Kévin Petite8edce32019-04-10 14:23:32 +01002426 Constant *ShuffleMask[4] = {
2427 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2428 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07002429
Kévin Petite8edce32019-04-10 14:23:32 +01002430 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002431 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
2432 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002433 });
David Neto6ad93232018-06-07 15:42:58 -07002434}
2435
David Neto22f144c2017-06-12 14:26:21 -04002436bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002437
Kévin Petite8edce32019-04-10 14:23:32 +01002438 const std::vector<const char *> Names = {"_Z11vstore_halffjPU3AS1Dh",
2439 "_Z15vstore_half_rtefjPU3AS1Dh",
2440 "_Z15vstore_half_rtzfjPU3AS1Dh"};
David Neto22f144c2017-06-12 14:26:21 -04002441
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002442 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002443 // The value to store.
2444 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002445
Kévin Petite8edce32019-04-10 14:23:32 +01002446 // The index argument from vstore_half.
2447 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002448
Kévin Petite8edce32019-04-10 14:23:32 +01002449 // The pointer argument from vstore_half.
2450 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002451
Kévin Petite8edce32019-04-10 14:23:32 +01002452 auto IntTy = Type::getInt32Ty(M.getContext());
2453 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
2454 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
2455 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04002456
Kévin Petite8edce32019-04-10 14:23:32 +01002457 // Our intrinsic to pack a float2 to an int.
2458 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002459
Kévin Petite8edce32019-04-10 14:23:32 +01002460 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002461
Kévin Petite8edce32019-04-10 14:23:32 +01002462 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002463 auto TempVec = InsertElementInst::Create(
2464 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002465
Kévin Petite8edce32019-04-10 14:23:32 +01002466 // Pack the float2 -> half2 (in an int).
2467 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002468
Kévin Petite8edce32019-04-10 14:23:32 +01002469 Value *Ret;
2470 if (clspv::Option::F16BitStorage()) {
2471 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002472 auto ShortPointerTy =
2473 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002474
Kévin Petite8edce32019-04-10 14:23:32 +01002475 // Truncate our i32 to an i16.
2476 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002477
Kévin Petite8edce32019-04-10 14:23:32 +01002478 // Cast the half* pointer to short*.
2479 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002480
Kévin Petite8edce32019-04-10 14:23:32 +01002481 // Index into the correct address of the casted pointer.
2482 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002483
Kévin Petite8edce32019-04-10 14:23:32 +01002484 // Store to the int* we casted to.
2485 Ret = new StoreInst(Trunc, Index, CI);
2486 } else {
2487 // We can only write to 32-bit aligned words.
2488 //
2489 // Assuming base is aligned to 32-bits, replace the equivalent of
2490 // vstore_half(value, index, base)
2491 // with:
2492 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2493 // uint32_t write_to_upper_half = index & 1u;
2494 // uint32_t shift = write_to_upper_half << 4;
2495 //
2496 // // Pack the float value as a half number in bottom 16 bits
2497 // // of an i32.
2498 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2499 //
2500 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2501 // ^ ((packed & 0xffff) << shift)
2502 // // We only need relaxed consistency, but OpenCL 1.2 only has
2503 // // sequentially consistent atomics.
2504 // // TODO(dneto): Use relaxed consistency.
2505 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002506 auto IntPointerTy =
2507 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002508
Kévin Petite8edce32019-04-10 14:23:32 +01002509 auto Four = ConstantInt::get(IntTy, 4);
2510 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002511
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002512 auto IndexIsOdd =
2513 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002514 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002515 auto IndexIntoI32 =
2516 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2517 auto BaseI32Ptr =
2518 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2519 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2520 "base_i32_ptr", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002521 auto CurrentValue = new LoadInst(OutPtr, "current_value", CI);
2522 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002523 auto MaskBitsToWrite =
2524 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2525 auto MaskedCurrent = BinaryOperator::CreateAnd(
2526 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002527
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002528 auto XLowerBits =
2529 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2530 auto NewBitsToWrite =
2531 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2532 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2533 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002534
Kévin Petite8edce32019-04-10 14:23:32 +01002535 // Generate the call to atomi_xor.
2536 SmallVector<Type *, 5> ParamTypes;
2537 // The pointer type.
2538 ParamTypes.push_back(IntPointerTy);
2539 // The Types for memory scope, semantics, and value.
2540 ParamTypes.push_back(IntTy);
2541 ParamTypes.push_back(IntTy);
2542 ParamTypes.push_back(IntTy);
2543 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2544 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002545
Kévin Petite8edce32019-04-10 14:23:32 +01002546 const auto ConstantScopeDevice =
2547 ConstantInt::get(IntTy, spv::ScopeDevice);
2548 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2549 // (SPIR-V Workgroup).
2550 const auto AddrSpaceSemanticsBits =
2551 IntPointerTy->getPointerAddressSpace() == 1
2552 ? spv::MemorySemanticsUniformMemoryMask
2553 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002554
Kévin Petite8edce32019-04-10 14:23:32 +01002555 // We're using relaxed consistency here.
2556 const auto ConstantMemorySemantics =
2557 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2558 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002559
Kévin Petite8edce32019-04-10 14:23:32 +01002560 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2561 ConstantMemorySemantics, ValueToXor};
2562 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
2563 Ret = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04002564 }
David Neto22f144c2017-06-12 14:26:21 -04002565
Kévin Petite8edce32019-04-10 14:23:32 +01002566 return Ret;
2567 });
David Neto22f144c2017-06-12 14:26:21 -04002568}
2569
2570bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002571
Kévin Petite8edce32019-04-10 14:23:32 +01002572 const std::vector<const char *> Names = {
David Netoe2871522018-06-08 11:09:54 -07002573 "_Z12vstore_half2Dv2_fjPU3AS1Dh",
2574 "_Z13vstorea_half2Dv2_fjPU3AS1Dh", // vstorea global
2575 "_Z13vstorea_half2Dv2_fjPU3AS3Dh", // vstorea local
2576 "_Z13vstorea_half2Dv2_fjPDh", // vstorea private
2577 "_Z16vstore_half2_rteDv2_fjPU3AS1Dh",
2578 "_Z17vstorea_half2_rteDv2_fjPU3AS1Dh", // vstorea global
2579 "_Z17vstorea_half2_rteDv2_fjPU3AS3Dh", // vstorea local
2580 "_Z17vstorea_half2_rteDv2_fjPDh", // vstorea private
2581 "_Z16vstore_half2_rtzDv2_fjPU3AS1Dh",
2582 "_Z17vstorea_half2_rtzDv2_fjPU3AS1Dh", // vstorea global
2583 "_Z17vstorea_half2_rtzDv2_fjPU3AS3Dh", // vstorea local
2584 "_Z17vstorea_half2_rtzDv2_fjPDh", // vstorea private
2585 };
David Neto22f144c2017-06-12 14:26:21 -04002586
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002587 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002588 // The value to store.
2589 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002590
Kévin Petite8edce32019-04-10 14:23:32 +01002591 // The index argument from vstore_half.
2592 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002593
Kévin Petite8edce32019-04-10 14:23:32 +01002594 // The pointer argument from vstore_half.
2595 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002596
Kévin Petite8edce32019-04-10 14:23:32 +01002597 auto IntTy = Type::getInt32Ty(M.getContext());
2598 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002599 auto NewPointerTy =
2600 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002601 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002602
Kévin Petite8edce32019-04-10 14:23:32 +01002603 // Our intrinsic to pack a float2 to an int.
2604 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002605
Kévin Petite8edce32019-04-10 14:23:32 +01002606 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002607
Kévin Petite8edce32019-04-10 14:23:32 +01002608 // Turn the packed x & y into the final packing.
2609 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002610
Kévin Petite8edce32019-04-10 14:23:32 +01002611 // Cast the half* pointer to int*.
2612 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002613
Kévin Petite8edce32019-04-10 14:23:32 +01002614 // Index into the correct address of the casted pointer.
2615 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002616
Kévin Petite8edce32019-04-10 14:23:32 +01002617 // Store to the int* we casted to.
2618 return new StoreInst(X, Index, CI);
2619 });
David Neto22f144c2017-06-12 14:26:21 -04002620}
2621
2622bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002623
Kévin Petite8edce32019-04-10 14:23:32 +01002624 const std::vector<const char *> Names = {
David Netoe2871522018-06-08 11:09:54 -07002625 "_Z12vstore_half4Dv4_fjPU3AS1Dh",
2626 "_Z13vstorea_half4Dv4_fjPU3AS1Dh", // global
2627 "_Z13vstorea_half4Dv4_fjPU3AS3Dh", // local
2628 "_Z13vstorea_half4Dv4_fjPDh", // private
2629 "_Z16vstore_half4_rteDv4_fjPU3AS1Dh",
2630 "_Z17vstorea_half4_rteDv4_fjPU3AS1Dh", // global
2631 "_Z17vstorea_half4_rteDv4_fjPU3AS3Dh", // local
2632 "_Z17vstorea_half4_rteDv4_fjPDh", // private
2633 "_Z16vstore_half4_rtzDv4_fjPU3AS1Dh",
2634 "_Z17vstorea_half4_rtzDv4_fjPU3AS1Dh", // global
2635 "_Z17vstorea_half4_rtzDv4_fjPU3AS3Dh", // local
2636 "_Z17vstorea_half4_rtzDv4_fjPDh", // private
2637 };
David Neto22f144c2017-06-12 14:26:21 -04002638
Kévin Petite8edce32019-04-10 14:23:32 +01002639 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
2640 // The value to store.
2641 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002642
Kévin Petite8edce32019-04-10 14:23:32 +01002643 // The index argument from vstore_half.
2644 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002645
Kévin Petite8edce32019-04-10 14:23:32 +01002646 // The pointer argument from vstore_half.
2647 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002648
Kévin Petite8edce32019-04-10 14:23:32 +01002649 auto IntTy = Type::getInt32Ty(M.getContext());
2650 auto Int2Ty = VectorType::get(IntTy, 2);
2651 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002652 auto NewPointerTy =
2653 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002654 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002655
Kévin Petite8edce32019-04-10 14:23:32 +01002656 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2657 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002658
Kévin Petite8edce32019-04-10 14:23:32 +01002659 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002660 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2661 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002662
Kévin Petite8edce32019-04-10 14:23:32 +01002663 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2664 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002665
Kévin Petite8edce32019-04-10 14:23:32 +01002666 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002667 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2668 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002669
Kévin Petite8edce32019-04-10 14:23:32 +01002670 // Our intrinsic to pack a float2 to an int.
2671 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04002672
Kévin Petite8edce32019-04-10 14:23:32 +01002673 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002674
Kévin Petite8edce32019-04-10 14:23:32 +01002675 // Turn the packed x & y into the final component of our int2.
2676 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002677
Kévin Petite8edce32019-04-10 14:23:32 +01002678 // Turn the packed z & w into the final component of our int2.
2679 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002680
Kévin Petite8edce32019-04-10 14:23:32 +01002681 auto Combine = InsertElementInst::Create(
2682 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002683 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2684 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002685
Kévin Petite8edce32019-04-10 14:23:32 +01002686 // Cast the half* pointer to int2*.
2687 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002688
Kévin Petite8edce32019-04-10 14:23:32 +01002689 // Index into the correct address of the casted pointer.
2690 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002691
Kévin Petite8edce32019-04-10 14:23:32 +01002692 // Store to the int2* we casted to.
2693 return new StoreInst(Combine, Index, CI);
2694 });
David Neto22f144c2017-06-12 14:26:21 -04002695}
2696
alan-bakerf7e17cb2020-01-02 07:29:59 -05002697bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Module &M) {
2698 bool Changed = false;
2699 const std::map<const char *, const char *> Map = {
2700 // 1D
2701 {"_Z11read_imageh14ocl_image1d_roi", "_Z11read_imagef14ocl_image1d_roi"},
2702 {"_Z11read_imageh14ocl_image1d_ro11ocl_sampleri",
2703 "_Z11read_imagef14ocl_image1d_ro11ocl_sampleri"},
2704 {"_Z11read_imageh14ocl_image1d_ro11ocl_samplerf",
2705 "_Z11read_imagef14ocl_image1d_ro11ocl_samplerf"},
2706 // TODO 1D array
2707 // 2D
2708 {"_Z11read_imageh14ocl_image2d_roDv2_i",
2709 "_Z11read_imagef14ocl_image2d_roDv2_i"},
2710 {"_Z11read_imageh14ocl_image2d_ro11ocl_samplerDv2_i",
2711 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_i"},
2712 {"_Z11read_imageh14ocl_image2d_ro11ocl_samplerDv2_f",
2713 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f"},
2714 // TODO 2D array
2715 // 3D
2716 {"_Z11read_imageh14ocl_image3d_roDv4_i",
2717 "_Z11read_imagef14ocl_image3d_roDv4_i"},
2718 {"_Z11read_imageh14ocl_image3d_ro11ocl_samplerDv4_i",
2719 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_i"},
2720 {"_Z11read_imageh14ocl_image3d_ro11ocl_samplerDv4_f",
2721 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f"}};
2722
2723 for (auto Pair : Map) {
2724 // If we find a function with the matching name.
2725 if (auto F = M.getFunction(Pair.first)) {
2726 SmallVector<Instruction *, 4> ToRemoves;
2727
2728 // Walk the users of the function.
2729 for (auto &U : F->uses()) {
2730 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2731 SmallVector<Type *, 3> types;
2732 SmallVector<Value *, 3> args;
2733 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2734 types.push_back(CI->getArgOperand(i)->getType());
2735 args.push_back(CI->getArgOperand(i));
2736 }
2737
2738 auto NewFType = FunctionType::get(
2739 VectorType::get(Type::getFloatTy(M.getContext()),
2740 CI->getType()->getVectorNumElements()),
2741 types, false);
2742
2743 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
2744
2745 auto NewCI = CallInst::Create(NewF, args, "", CI);
2746
2747 // Convert to the half type.
2748 auto Cast = CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2749
2750 CI->replaceAllUsesWith(Cast);
2751
2752 // Lastly, remember to remove the user.
2753 ToRemoves.push_back(CI);
2754 }
2755 }
2756
2757 Changed = !ToRemoves.empty();
2758
2759 // And cleanup the calls we don't use anymore.
2760 for (auto V : ToRemoves) {
2761 V->eraseFromParent();
2762 }
2763
2764 // And remove the function we don't need either too.
2765 F->eraseFromParent();
2766 }
2767 }
2768
2769 return Changed;
2770}
2771
2772bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Module &M) {
2773 bool Changed = false;
2774 const std::map<const char *, const char *> Map = {
2775 // 1D
2776 {"_Z12write_imageh14ocl_image1d_woiDv4_Dh",
2777 "_Z12write_imagef14ocl_image1d_woiDv4_f"},
2778 // TODO 1D array
2779 // 2D
2780 {"_Z12write_imageh14ocl_image2d_woDv2_iDv4_Dh",
2781 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f"},
2782 // TODO 2D array
2783 // 3D
2784 {"_Z12write_imageh14ocl_image3d_woDv4_iDv4_Dh",
2785 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f"}};
2786
2787 for (auto Pair : Map) {
2788 // If we find a function with the matching name.
2789 if (auto F = M.getFunction(Pair.first)) {
2790 SmallVector<Instruction *, 4> ToRemoves;
2791
2792 // Walk the users of the function.
2793 for (auto &U : F->uses()) {
2794 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2795 SmallVector<Type *, 3> types(3);
2796 SmallVector<Value *, 3> args(3);
2797
2798 // Image
2799 types[0] = CI->getArgOperand(0)->getType();
2800 args[0] = CI->getArgOperand(0);
2801
2802 // Coord
2803 types[1] = CI->getArgOperand(1)->getType();
2804 args[1] = CI->getArgOperand(1);
2805
2806 // Data
2807 types[2] = VectorType::get(
2808 Type::getFloatTy(M.getContext()),
2809 CI->getArgOperand(2)->getType()->getVectorNumElements());
2810
2811 auto NewFType =
2812 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
2813
2814 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
2815
2816 // Convert data to the float type.
2817 auto Cast =
2818 CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2819 args[2] = Cast;
2820
2821 auto NewCI = CallInst::Create(NewF, args, "", CI);
2822
2823 // Lastly, remember to remove the user.
2824 ToRemoves.push_back(CI);
2825 }
2826 }
2827
2828 Changed = !ToRemoves.empty();
2829
2830 // And cleanup the calls we don't use anymore.
2831 for (auto V : ToRemoves) {
2832 V->eraseFromParent();
2833 }
2834
2835 // And remove the function we don't need either too.
2836 F->eraseFromParent();
2837 }
2838 }
2839
2840 return Changed;
2841}
2842
alan-baker931d18a2019-12-12 08:21:32 -05002843bool ReplaceOpenCLBuiltinPass::replaceUnsampledReadImage(Module &M) {
2844 bool Changed = false;
2845 const std::map<const char *, const char *> Map = {
2846 // 1D
2847 {"_Z11read_imagef14ocl_image1d_roi",
2848 "_Z11read_imagef14ocl_image1d_ro11ocl_sampleri"},
2849 {"_Z11read_imagei14ocl_image1d_roi",
2850 "_Z11read_imagei14ocl_image1d_ro11ocl_sampleri"},
2851 {"_Z12read_imageui14ocl_image1d_roi",
2852 "_Z12read_imageui14ocl_image1d_ro11ocl_sampleri"},
2853 // TODO 1D array
2854 // 2D
2855 {"_Z11read_imagef14ocl_image2d_roDv2_i",
2856 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_i"},
2857 {"_Z11read_imagei14ocl_image2d_roDv2_i",
2858 "_Z11read_imagei14ocl_image2d_ro11ocl_samplerDv2_i"},
2859 {"_Z12read_imageui14ocl_image2d_roDv2_i",
2860 "_Z12read_imageui14ocl_image2d_ro11ocl_samplerDv2_i"},
2861 // TODO 2D array
2862 // 3D
2863 {"_Z11read_imagef14ocl_image3d_roDv4_i",
2864 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_i"},
2865 {"_Z11read_imagei14ocl_image3d_roDv4_i",
2866 "_Z11read_imagei14ocl_image3d_ro11ocl_samplerDv4_i"},
2867 {"_Z12read_imageui14ocl_image3d_roDv4_i",
2868 "_Z12read_imageui14ocl_image3d_ro11ocl_samplerDv4_i"}};
2869
2870 Function *translate_sampler =
2871 M.getFunction(clspv::TranslateSamplerInitializerFunction());
2872 Type *sampler_type = M.getTypeByName("opencl.sampler_t");
alan-bakerf7e17cb2020-01-02 07:29:59 -05002873 if (sampler_type) {
2874 sampler_type = sampler_type->getPointerTo(clspv::AddressSpace::Constant);
2875 }
alan-baker931d18a2019-12-12 08:21:32 -05002876 for (auto Pair : Map) {
2877 // If we find a function with the matching name.
2878 if (auto F = M.getFunction(Pair.first)) {
2879 SmallVector<Instruction *, 4> ToRemoves;
2880
2881 // Walk the users of the function.
2882 for (auto &U : F->uses()) {
2883 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2884 // The image.
2885 auto Image = CI->getOperand(0);
2886
2887 // The coordinate.
2888 auto Coord = CI->getOperand(1);
2889
2890 // Create the sampler translation function if necessary.
2891 if (!translate_sampler) {
2892 // Create the sampler type if necessary.
2893 if (!sampler_type) {
2894 sampler_type =
2895 StructType::create(M.getContext(), "opencl.sampler_t");
2896 sampler_type =
2897 sampler_type->getPointerTo(clspv::AddressSpace::Constant);
2898 }
2899 auto fn_type = FunctionType::get(
2900 sampler_type, {Type::getInt32Ty(M.getContext())}, false);
2901 auto callee = M.getOrInsertFunction(
2902 clspv::TranslateSamplerInitializerFunction(), fn_type);
2903 translate_sampler = cast<Function>(callee.getCallee());
2904 }
2905
2906 auto NewFType = FunctionType::get(
2907 CI->getType(), {Image->getType(), sampler_type, Coord->getType()},
2908 false);
2909
2910 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
2911
James Pricec05f6052020-01-14 13:37:20 -05002912 const uint64_t data_mask =
2913 clspv::version0::CLK_ADDRESS_NONE |
2914 clspv::version0::CLK_FILTER_NEAREST |
2915 clspv::version0::CLK_NORMALIZED_COORDS_FALSE;
alan-baker931d18a2019-12-12 08:21:32 -05002916 auto NewSamplerCI = CallInst::Create(
2917 translate_sampler,
2918 {ConstantInt::get(Type::getInt32Ty(M.getContext()), data_mask)},
2919 "", CI);
2920 auto NewCI =
2921 CallInst::Create(NewF, {Image, NewSamplerCI, Coord}, "", CI);
2922
2923 CI->replaceAllUsesWith(NewCI);
2924
2925 // Lastly, remember to remove the user.
2926 ToRemoves.push_back(CI);
2927 }
2928 }
2929
2930 Changed = !ToRemoves.empty();
2931
2932 // And cleanup the calls we don't use anymore.
2933 for (auto V : ToRemoves) {
2934 V->eraseFromParent();
2935 }
2936
2937 // And remove the function we don't need either too.
2938 F->eraseFromParent();
2939 }
2940 }
2941
2942 return Changed;
2943}
2944
Kévin Petit06517a12019-12-09 19:40:31 +00002945bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04002946 bool Changed = false;
2947
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002948 const std::map<const char *, const char *> Map = {
alan-bakerf906d2b2019-12-10 11:26:23 -05002949 // 1D
2950 {"_Z11read_imagei14ocl_image1d_ro11ocl_sampleri",
2951 "_Z11read_imagei14ocl_image1d_ro11ocl_samplerf"},
2952 {"_Z12read_imageui14ocl_image1d_ro11ocl_sampleri",
2953 "_Z12read_imageui14ocl_image1d_ro11ocl_samplerf"},
2954 {"_Z11read_imagef14ocl_image1d_ro11ocl_sampleri",
2955 "_Z11read_imagef14ocl_image1d_ro11ocl_samplerf"},
2956 // TODO 1Darray
Kévin Petit06517a12019-12-09 19:40:31 +00002957 // 2D
2958 {"_Z11read_imagei14ocl_image2d_ro11ocl_samplerDv2_i",
2959 "_Z11read_imagei14ocl_image2d_ro11ocl_samplerDv2_f"},
2960 {"_Z12read_imageui14ocl_image2d_ro11ocl_samplerDv2_i",
2961 "_Z12read_imageui14ocl_image2d_ro11ocl_samplerDv2_f"},
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002962 {"_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_i",
2963 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f"},
Kévin Petit06517a12019-12-09 19:40:31 +00002964 // TODO 2D array
2965 // 3D
2966 {"_Z11read_imagei14ocl_image3d_ro11ocl_samplerDv4_i",
2967 "_Z11read_imagei14ocl_image3d_ro11ocl_samplerDv4_f"},
2968 {"_Z12read_imageui14ocl_image3d_ro11ocl_samplerDv4_i",
2969 "_Z12read_imageui14ocl_image3d_ro11ocl_samplerDv4_f"},
2970 {"_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_i",
2971 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f"}};
David Neto22f144c2017-06-12 14:26:21 -04002972
2973 for (auto Pair : Map) {
2974 // If we find a function with the matching name.
2975 if (auto F = M.getFunction(Pair.first)) {
2976 SmallVector<Instruction *, 4> ToRemoves;
2977
2978 // Walk the users of the function.
2979 for (auto &U : F->uses()) {
2980 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2981 // The image.
2982 auto Arg0 = CI->getOperand(0);
2983
2984 // The sampler.
2985 auto Arg1 = CI->getOperand(1);
2986
2987 // The coordinate (integer type that we can't handle).
2988 auto Arg2 = CI->getOperand(2);
2989
alan-bakerf906d2b2019-12-10 11:26:23 -05002990 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2991 // TODO(alan-baker): when arrayed images are supported fix component
2992 // calculation.
2993 uint32_t components = dim;
2994 Type *float_ty = nullptr;
2995 if (components == 1) {
2996 float_ty = Type::getFloatTy(M.getContext());
2997 } else {
2998 float_ty = VectorType::get(Type::getFloatTy(M.getContext()),
2999 Arg2->getType()->getVectorNumElements());
3000 }
David Neto22f144c2017-06-12 14:26:21 -04003001
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003002 auto NewFType = FunctionType::get(
alan-bakerf906d2b2019-12-10 11:26:23 -05003003 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty},
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003004 false);
David Neto22f144c2017-06-12 14:26:21 -04003005
3006 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
3007
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003008 auto Cast =
alan-bakerf906d2b2019-12-10 11:26:23 -05003009 CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04003010
3011 auto NewCI = CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
3012
3013 CI->replaceAllUsesWith(NewCI);
3014
3015 // Lastly, remember to remove the user.
3016 ToRemoves.push_back(CI);
3017 }
3018 }
3019
3020 Changed = !ToRemoves.empty();
3021
3022 // And cleanup the calls we don't use anymore.
3023 for (auto V : ToRemoves) {
3024 V->eraseFromParent();
3025 }
3026
3027 // And remove the function we don't need either too.
3028 F->eraseFromParent();
3029 }
3030 }
3031
3032 return Changed;
3033}
3034
3035bool ReplaceOpenCLBuiltinPass::replaceAtomics(Module &M) {
3036 bool Changed = false;
3037
Kévin Petit9b340262019-06-19 18:31:11 +01003038 const std::map<const char *, spv::Op> Map = {
3039 {"_Z8atom_incPU3AS1Vi", spv::OpAtomicIIncrement},
3040 {"_Z8atom_incPU3AS3Vi", spv::OpAtomicIIncrement},
3041 {"_Z8atom_incPU3AS1Vj", spv::OpAtomicIIncrement},
3042 {"_Z8atom_incPU3AS3Vj", spv::OpAtomicIIncrement},
3043 {"_Z8atom_decPU3AS1Vi", spv::OpAtomicIDecrement},
3044 {"_Z8atom_decPU3AS3Vi", spv::OpAtomicIDecrement},
3045 {"_Z8atom_decPU3AS1Vj", spv::OpAtomicIDecrement},
3046 {"_Z8atom_decPU3AS3Vj", spv::OpAtomicIDecrement},
3047 {"_Z12atom_cmpxchgPU3AS1Viii", spv::OpAtomicCompareExchange},
3048 {"_Z12atom_cmpxchgPU3AS3Viii", spv::OpAtomicCompareExchange},
3049 {"_Z12atom_cmpxchgPU3AS1Vjjj", spv::OpAtomicCompareExchange},
3050 {"_Z12atom_cmpxchgPU3AS3Vjjj", spv::OpAtomicCompareExchange},
3051 {"_Z10atomic_incPU3AS1Vi", spv::OpAtomicIIncrement},
3052 {"_Z10atomic_incPU3AS3Vi", spv::OpAtomicIIncrement},
3053 {"_Z10atomic_incPU3AS1Vj", spv::OpAtomicIIncrement},
3054 {"_Z10atomic_incPU3AS3Vj", spv::OpAtomicIIncrement},
3055 {"_Z10atomic_decPU3AS1Vi", spv::OpAtomicIDecrement},
3056 {"_Z10atomic_decPU3AS3Vi", spv::OpAtomicIDecrement},
3057 {"_Z10atomic_decPU3AS1Vj", spv::OpAtomicIDecrement},
3058 {"_Z10atomic_decPU3AS3Vj", spv::OpAtomicIDecrement},
3059 {"_Z14atomic_cmpxchgPU3AS1Viii", spv::OpAtomicCompareExchange},
3060 {"_Z14atomic_cmpxchgPU3AS3Viii", spv::OpAtomicCompareExchange},
3061 {"_Z14atomic_cmpxchgPU3AS1Vjjj", spv::OpAtomicCompareExchange},
3062 {"_Z14atomic_cmpxchgPU3AS3Vjjj", spv::OpAtomicCompareExchange}};
David Neto22f144c2017-06-12 14:26:21 -04003063
3064 for (auto Pair : Map) {
3065 // If we find a function with the matching name.
3066 if (auto F = M.getFunction(Pair.first)) {
3067 SmallVector<Instruction *, 4> ToRemoves;
3068
3069 // Walk the users of the function.
3070 for (auto &U : F->uses()) {
3071 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
David Neto22f144c2017-06-12 14:26:21 -04003072
3073 auto IntTy = Type::getInt32Ty(M.getContext());
3074
David Neto22f144c2017-06-12 14:26:21 -04003075 // We need to map the OpenCL constants to the SPIR-V equivalents.
3076 const auto ConstantScopeDevice =
3077 ConstantInt::get(IntTy, spv::ScopeDevice);
3078 const auto ConstantMemorySemantics = ConstantInt::get(
3079 IntTy, spv::MemorySemanticsUniformMemoryMask |
3080 spv::MemorySemanticsSequentiallyConsistentMask);
3081
3082 SmallVector<Value *, 5> Params;
3083
3084 // The pointer.
3085 Params.push_back(CI->getArgOperand(0));
3086
3087 // The memory scope.
3088 Params.push_back(ConstantScopeDevice);
3089
3090 // The memory semantics.
3091 Params.push_back(ConstantMemorySemantics);
3092
3093 if (2 < CI->getNumArgOperands()) {
3094 // The unequal memory semantics.
3095 Params.push_back(ConstantMemorySemantics);
3096
3097 // The value.
3098 Params.push_back(CI->getArgOperand(2));
3099
3100 // The comparator.
3101 Params.push_back(CI->getArgOperand(1));
3102 } else if (1 < CI->getNumArgOperands()) {
3103 // The value.
3104 Params.push_back(CI->getArgOperand(1));
3105 }
3106
Kévin Petit9b340262019-06-19 18:31:11 +01003107 auto NewCI =
3108 clspv::InsertSPIRVOp(CI, Pair.second, {}, CI->getType(), Params);
David Neto22f144c2017-06-12 14:26:21 -04003109
3110 CI->replaceAllUsesWith(NewCI);
3111
3112 // Lastly, remember to remove the user.
3113 ToRemoves.push_back(CI);
3114 }
3115 }
3116
3117 Changed = !ToRemoves.empty();
3118
3119 // And cleanup the calls we don't use anymore.
3120 for (auto V : ToRemoves) {
3121 V->eraseFromParent();
3122 }
3123
3124 // And remove the function we don't need either too.
3125 F->eraseFromParent();
3126 }
3127 }
3128
Neil Henning39672102017-09-29 14:33:13 +01003129 const std::map<const char *, llvm::AtomicRMWInst::BinOp> Map2 = {
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003130 {"_Z8atom_addPU3AS1Vii", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003131 {"_Z8atom_addPU3AS3Vii", llvm::AtomicRMWInst::Add},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003132 {"_Z8atom_addPU3AS1Vjj", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003133 {"_Z8atom_addPU3AS3Vjj", llvm::AtomicRMWInst::Add},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003134 {"_Z8atom_subPU3AS1Vii", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003135 {"_Z8atom_subPU3AS3Vii", llvm::AtomicRMWInst::Sub},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003136 {"_Z8atom_subPU3AS1Vjj", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003137 {"_Z8atom_subPU3AS3Vjj", llvm::AtomicRMWInst::Sub},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003138 {"_Z9atom_xchgPU3AS1Vii", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003139 {"_Z9atom_xchgPU3AS3Vii", llvm::AtomicRMWInst::Xchg},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003140 {"_Z9atom_xchgPU3AS1Vjj", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003141 {"_Z9atom_xchgPU3AS3Vjj", llvm::AtomicRMWInst::Xchg},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003142 {"_Z8atom_minPU3AS1Vii", llvm::AtomicRMWInst::Min},
Kévin Petita303dc62019-03-26 21:40:35 +00003143 {"_Z8atom_minPU3AS3Vii", llvm::AtomicRMWInst::Min},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003144 {"_Z8atom_minPU3AS1Vjj", llvm::AtomicRMWInst::UMin},
Kévin Petita303dc62019-03-26 21:40:35 +00003145 {"_Z8atom_minPU3AS3Vjj", llvm::AtomicRMWInst::UMin},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003146 {"_Z8atom_maxPU3AS1Vii", llvm::AtomicRMWInst::Max},
Kévin Petita303dc62019-03-26 21:40:35 +00003147 {"_Z8atom_maxPU3AS3Vii", llvm::AtomicRMWInst::Max},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003148 {"_Z8atom_maxPU3AS1Vjj", llvm::AtomicRMWInst::UMax},
Kévin Petita303dc62019-03-26 21:40:35 +00003149 {"_Z8atom_maxPU3AS3Vjj", llvm::AtomicRMWInst::UMax},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003150 {"_Z8atom_andPU3AS1Vii", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003151 {"_Z8atom_andPU3AS3Vii", llvm::AtomicRMWInst::And},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003152 {"_Z8atom_andPU3AS1Vjj", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003153 {"_Z8atom_andPU3AS3Vjj", llvm::AtomicRMWInst::And},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003154 {"_Z7atom_orPU3AS1Vii", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003155 {"_Z7atom_orPU3AS3Vii", llvm::AtomicRMWInst::Or},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003156 {"_Z7atom_orPU3AS1Vjj", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003157 {"_Z7atom_orPU3AS3Vjj", llvm::AtomicRMWInst::Or},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003158 {"_Z8atom_xorPU3AS1Vii", llvm::AtomicRMWInst::Xor},
Kévin Petita303dc62019-03-26 21:40:35 +00003159 {"_Z8atom_xorPU3AS3Vii", llvm::AtomicRMWInst::Xor},
Kévin Petit4f6c6b02018-10-25 18:56:55 +00003160 {"_Z8atom_xorPU3AS1Vjj", llvm::AtomicRMWInst::Xor},
Kévin Petita303dc62019-03-26 21:40:35 +00003161 {"_Z8atom_xorPU3AS3Vjj", llvm::AtomicRMWInst::Xor},
Neil Henning39672102017-09-29 14:33:13 +01003162 {"_Z10atomic_addPU3AS1Vii", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003163 {"_Z10atomic_addPU3AS3Vii", llvm::AtomicRMWInst::Add},
Neil Henning39672102017-09-29 14:33:13 +01003164 {"_Z10atomic_addPU3AS1Vjj", llvm::AtomicRMWInst::Add},
Kévin Petita303dc62019-03-26 21:40:35 +00003165 {"_Z10atomic_addPU3AS3Vjj", llvm::AtomicRMWInst::Add},
Neil Henning39672102017-09-29 14:33:13 +01003166 {"_Z10atomic_subPU3AS1Vii", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003167 {"_Z10atomic_subPU3AS3Vii", llvm::AtomicRMWInst::Sub},
Neil Henning39672102017-09-29 14:33:13 +01003168 {"_Z10atomic_subPU3AS1Vjj", llvm::AtomicRMWInst::Sub},
Kévin Petita303dc62019-03-26 21:40:35 +00003169 {"_Z10atomic_subPU3AS3Vjj", llvm::AtomicRMWInst::Sub},
Neil Henning39672102017-09-29 14:33:13 +01003170 {"_Z11atomic_xchgPU3AS1Vii", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003171 {"_Z11atomic_xchgPU3AS3Vii", llvm::AtomicRMWInst::Xchg},
Neil Henning39672102017-09-29 14:33:13 +01003172 {"_Z11atomic_xchgPU3AS1Vjj", llvm::AtomicRMWInst::Xchg},
Kévin Petita303dc62019-03-26 21:40:35 +00003173 {"_Z11atomic_xchgPU3AS3Vjj", llvm::AtomicRMWInst::Xchg},
Neil Henning39672102017-09-29 14:33:13 +01003174 {"_Z10atomic_minPU3AS1Vii", llvm::AtomicRMWInst::Min},
Kévin Petita303dc62019-03-26 21:40:35 +00003175 {"_Z10atomic_minPU3AS3Vii", llvm::AtomicRMWInst::Min},
Neil Henning39672102017-09-29 14:33:13 +01003176 {"_Z10atomic_minPU3AS1Vjj", llvm::AtomicRMWInst::UMin},
Kévin Petita303dc62019-03-26 21:40:35 +00003177 {"_Z10atomic_minPU3AS3Vjj", llvm::AtomicRMWInst::UMin},
Neil Henning39672102017-09-29 14:33:13 +01003178 {"_Z10atomic_maxPU3AS1Vii", llvm::AtomicRMWInst::Max},
Kévin Petita303dc62019-03-26 21:40:35 +00003179 {"_Z10atomic_maxPU3AS3Vii", llvm::AtomicRMWInst::Max},
Neil Henning39672102017-09-29 14:33:13 +01003180 {"_Z10atomic_maxPU3AS1Vjj", llvm::AtomicRMWInst::UMax},
Kévin Petita303dc62019-03-26 21:40:35 +00003181 {"_Z10atomic_maxPU3AS3Vjj", llvm::AtomicRMWInst::UMax},
Neil Henning39672102017-09-29 14:33:13 +01003182 {"_Z10atomic_andPU3AS1Vii", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003183 {"_Z10atomic_andPU3AS3Vii", llvm::AtomicRMWInst::And},
Neil Henning39672102017-09-29 14:33:13 +01003184 {"_Z10atomic_andPU3AS1Vjj", llvm::AtomicRMWInst::And},
Kévin Petita303dc62019-03-26 21:40:35 +00003185 {"_Z10atomic_andPU3AS3Vjj", llvm::AtomicRMWInst::And},
Neil Henning39672102017-09-29 14:33:13 +01003186 {"_Z9atomic_orPU3AS1Vii", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003187 {"_Z9atomic_orPU3AS3Vii", llvm::AtomicRMWInst::Or},
Neil Henning39672102017-09-29 14:33:13 +01003188 {"_Z9atomic_orPU3AS1Vjj", llvm::AtomicRMWInst::Or},
Kévin Petita303dc62019-03-26 21:40:35 +00003189 {"_Z9atomic_orPU3AS3Vjj", llvm::AtomicRMWInst::Or},
Neil Henning39672102017-09-29 14:33:13 +01003190 {"_Z10atomic_xorPU3AS1Vii", llvm::AtomicRMWInst::Xor},
Kévin Petita303dc62019-03-26 21:40:35 +00003191 {"_Z10atomic_xorPU3AS3Vii", llvm::AtomicRMWInst::Xor},
3192 {"_Z10atomic_xorPU3AS1Vjj", llvm::AtomicRMWInst::Xor},
3193 {"_Z10atomic_xorPU3AS3Vjj", llvm::AtomicRMWInst::Xor}};
Neil Henning39672102017-09-29 14:33:13 +01003194
3195 for (auto Pair : Map2) {
3196 // If we find a function with the matching name.
3197 if (auto F = M.getFunction(Pair.first)) {
3198 SmallVector<Instruction *, 4> ToRemoves;
3199
3200 // Walk the users of the function.
3201 for (auto &U : F->uses()) {
3202 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
3203 auto AtomicOp = new AtomicRMWInst(
3204 Pair.second, CI->getArgOperand(0), CI->getArgOperand(1),
3205 AtomicOrdering::SequentiallyConsistent, SyncScope::System, CI);
3206
3207 CI->replaceAllUsesWith(AtomicOp);
3208
3209 // Lastly, remember to remove the user.
3210 ToRemoves.push_back(CI);
3211 }
3212 }
3213
3214 Changed = !ToRemoves.empty();
3215
3216 // And cleanup the calls we don't use anymore.
3217 for (auto V : ToRemoves) {
3218 V->eraseFromParent();
3219 }
3220
3221 // And remove the function we don't need either too.
3222 F->eraseFromParent();
3223 }
3224 }
3225
David Neto22f144c2017-06-12 14:26:21 -04003226 return Changed;
3227}
3228
3229bool ReplaceOpenCLBuiltinPass::replaceCross(Module &M) {
David Neto22f144c2017-06-12 14:26:21 -04003230
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003231 std::vector<const char *> Names = {
3232 "_Z5crossDv4_fS_",
Kévin Petite8edce32019-04-10 14:23:32 +01003233 };
3234
3235 return replaceCallsWithValue(M, Names, [&M](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04003236 auto IntTy = Type::getInt32Ty(M.getContext());
3237 auto FloatTy = Type::getFloatTy(M.getContext());
3238
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003239 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
3240 ConstantInt::get(IntTy, 1),
3241 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04003242
3243 Constant *UpShuffleMask[4] = {
3244 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
3245 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
3246
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003247 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
3248 UndefValue::get(FloatTy),
3249 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04003250
Kévin Petite8edce32019-04-10 14:23:32 +01003251 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003252 auto Arg0 =
3253 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
3254 ConstantVector::get(DownShuffleMask), "", CI);
3255 auto Arg1 =
3256 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
3257 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01003258 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04003259
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003260 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
David Neto22f144c2017-06-12 14:26:21 -04003261
Kévin Petite8edce32019-04-10 14:23:32 +01003262 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04003263
Kévin Petite8edce32019-04-10 14:23:32 +01003264 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04003265
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003266 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
3267 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01003268 });
David Neto22f144c2017-06-12 14:26:21 -04003269}
David Neto62653202017-10-16 19:05:18 -04003270
3271bool ReplaceOpenCLBuiltinPass::replaceFract(Module &M) {
3272 bool Changed = false;
3273
3274 // OpenCL's float result = fract(float x, float* ptr)
3275 //
3276 // In the LLVM domain:
3277 //
3278 // %floor_result = call spir_func float @floor(float %x)
3279 // store float %floor_result, float * %ptr
3280 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
3281 // %result = call spir_func float
3282 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
3283 //
3284 // Becomes in the SPIR-V domain, where translations of floor, fmin,
3285 // and clspv.fract occur in the SPIR-V generator pass:
3286 //
3287 // %glsl_ext = OpExtInstImport "GLSL.std.450"
3288 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
3289 // ...
3290 // %floor_result = OpExtInst %float %glsl_ext Floor %x
3291 // OpStore %ptr %floor_result
3292 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
3293 // %fract_result = OpExtInst %float
3294 // %glsl_ext Fmin %fract_intermediate %just_under_1
3295
David Neto62653202017-10-16 19:05:18 -04003296 using std::string;
3297
3298 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
3299 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003300 using QuadType =
3301 std::tuple<const char *, const char *, const char *, const char *>;
David Neto62653202017-10-16 19:05:18 -04003302 auto make_quad = [](const char *a, const char *b, const char *c,
3303 const char *d) {
3304 return std::tuple<const char *, const char *, const char *, const char *>(
3305 a, b, c, d);
3306 };
3307 const std::vector<QuadType> Functions = {
3308 make_quad("_Z5fractfPf", "_Z5floorff", "_Z4fminff", "clspv.fract.f"),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003309 make_quad("_Z5fractDv2_fPS_", "_Z5floorDv2_f", "_Z4fminDv2_ff",
3310 "clspv.fract.v2f"),
3311 make_quad("_Z5fractDv3_fPS_", "_Z5floorDv3_f", "_Z4fminDv3_ff",
3312 "clspv.fract.v3f"),
3313 make_quad("_Z5fractDv4_fPS_", "_Z5floorDv4_f", "_Z4fminDv4_ff",
3314 "clspv.fract.v4f"),
David Neto62653202017-10-16 19:05:18 -04003315 };
3316
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003317 for (auto &quad : Functions) {
David Neto62653202017-10-16 19:05:18 -04003318 const StringRef fract_name(std::get<0>(quad));
3319
3320 // If we find a function with the matching name.
3321 if (auto F = M.getFunction(fract_name)) {
3322 if (F->use_begin() == F->use_end())
3323 continue;
3324
3325 // We have some uses.
3326 Changed = true;
3327
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003328 auto &Context = M.getContext();
David Neto62653202017-10-16 19:05:18 -04003329
3330 const StringRef floor_name(std::get<1>(quad));
3331 const StringRef fmin_name(std::get<2>(quad));
3332 const StringRef clspv_fract_name(std::get<3>(quad));
3333
3334 // This is either float or a float vector. All the float-like
3335 // types are this type.
3336 auto result_ty = F->getReturnType();
3337
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003338 Function *fmin_fn = M.getFunction(fmin_name);
David Neto62653202017-10-16 19:05:18 -04003339 if (!fmin_fn) {
3340 // Make the fmin function.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003341 FunctionType *fn_ty =
3342 FunctionType::get(result_ty, {result_ty, result_ty}, false);
alan-bakerbccf62c2019-03-29 10:32:41 -04003343 fmin_fn =
3344 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
David Neto62653202017-10-16 19:05:18 -04003345 fmin_fn->addFnAttr(Attribute::ReadNone);
3346 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
3347 }
3348
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003349 Function *floor_fn = M.getFunction(floor_name);
David Neto62653202017-10-16 19:05:18 -04003350 if (!floor_fn) {
3351 // Make the floor function.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003352 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
alan-bakerbccf62c2019-03-29 10:32:41 -04003353 floor_fn = cast<Function>(
3354 M.getOrInsertFunction(floor_name, fn_ty).getCallee());
David Neto62653202017-10-16 19:05:18 -04003355 floor_fn->addFnAttr(Attribute::ReadNone);
3356 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
3357 }
3358
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003359 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
David Neto62653202017-10-16 19:05:18 -04003360 if (!clspv_fract_fn) {
3361 // Make the clspv_fract function.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003362 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
alan-bakerbccf62c2019-03-29 10:32:41 -04003363 clspv_fract_fn = cast<Function>(
3364 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
David Neto62653202017-10-16 19:05:18 -04003365 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
3366 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
3367 }
3368
3369 // Number of significant significand bits, whether represented or not.
3370 unsigned num_significand_bits;
3371 switch (result_ty->getScalarType()->getTypeID()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003372 case Type::HalfTyID:
3373 num_significand_bits = 11;
3374 break;
3375 case Type::FloatTyID:
3376 num_significand_bits = 24;
3377 break;
3378 case Type::DoubleTyID:
3379 num_significand_bits = 53;
3380 break;
3381 default:
3382 assert(false && "Unhandled float type when processing fract builtin");
3383 break;
David Neto62653202017-10-16 19:05:18 -04003384 }
3385 // Beware that the disassembler displays this value as
3386 // OpConstant %float 1
3387 // which is not quite right.
3388 const double kJustUnderOneScalar =
3389 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
3390
3391 Constant *just_under_one =
3392 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
3393 if (result_ty->isVectorTy()) {
3394 just_under_one = ConstantVector::getSplat(
3395 result_ty->getVectorNumElements(), just_under_one);
3396 }
3397
3398 IRBuilder<> Builder(Context);
3399
3400 SmallVector<Instruction *, 4> ToRemoves;
3401
3402 // Walk the users of the function.
3403 for (auto &U : F->uses()) {
3404 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
3405
3406 Builder.SetInsertPoint(CI);
3407 auto arg = CI->getArgOperand(0);
3408 auto ptr = CI->getArgOperand(1);
3409
3410 // Compute floor result and store it.
3411 auto floor = Builder.CreateCall(floor_fn, {arg});
3412 Builder.CreateStore(floor, ptr);
3413
3414 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003415 auto fract_result =
3416 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
David Neto62653202017-10-16 19:05:18 -04003417
3418 CI->replaceAllUsesWith(fract_result);
3419
3420 // Lastly, remember to remove the user.
3421 ToRemoves.push_back(CI);
3422 }
3423 }
3424
3425 // And cleanup the calls we don't use anymore.
3426 for (auto V : ToRemoves) {
3427 V->eraseFromParent();
3428 }
3429
3430 // And remove the function we don't need either too.
3431 F->eraseFromParent();
3432 }
3433 }
3434
3435 return Changed;
3436}