blob: 05c134d2b746259a341aeb953da5732e51dffc86 [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
alan-bakere0902602020-03-23 08:43:40 -040030#include "spirv/unified1/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
SJW2c317da2020-03-23 07:39:13 -050036#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050037#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040038#include "Passes.h"
39#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050040#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040041
SJW2c317da2020-03-23 07:39:13 -050042using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040043using namespace llvm;
44
45#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
46
47namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000048
David Neto22f144c2017-06-12 14:26:21 -040049uint32_t clz(uint32_t v) {
50 uint32_t r;
51 uint32_t shift;
52
53 r = (v > 0xFFFF) << 4;
54 v >>= r;
55 shift = (v > 0xFF) << 3;
56 v >>= shift;
57 r |= shift;
58 shift = (v > 0xF) << 2;
59 v >>= shift;
60 r |= shift;
61 shift = (v > 0x3) << 1;
62 v >>= shift;
63 r |= shift;
64 r |= (v >> 1);
65
66 return r;
67}
68
Kévin Petitfdfa92e2019-09-25 14:20:58 +010069Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
70 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040071 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
72 IntTy = VectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petitfdfa92e2019-09-25 14:20:58 +010073 }
74 return IntTy;
75}
76
SJW2c317da2020-03-23 07:39:13 -050077bool replaceCallsWithValue(Function &F,
78 std::function<Value *(CallInst *)> Replacer) {
79
80 bool Changed = false;
81
82 SmallVector<Instruction *, 4> ToRemoves;
83
84 // Walk the users of the function.
85 for (auto &U : F.uses()) {
86 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
87
88 auto NewValue = Replacer(CI);
89
90 if (NewValue != nullptr) {
91 CI->replaceAllUsesWith(NewValue);
92
93 // Lastly, remember to remove the user.
94 ToRemoves.push_back(CI);
95 }
96 }
97 }
98
99 Changed = !ToRemoves.empty();
100
101 // And cleanup the calls we don't use anymore.
102 for (auto V : ToRemoves) {
103 V->eraseFromParent();
104 }
105
106 return Changed;
107}
108
David Neto22f144c2017-06-12 14:26:21 -0400109struct ReplaceOpenCLBuiltinPass final : public ModulePass {
110 static char ID;
111 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
112
113 bool runOnModule(Module &M) override;
SJW2c317da2020-03-23 07:39:13 -0500114 bool runOnFunction(Function &F);
115 bool replaceAbs(Function &F);
116 bool replaceAbsDiff(Function &F, bool is_signed);
117 bool replaceCopysign(Function &F);
118 bool replaceRecip(Function &F);
119 bool replaceDivide(Function &F);
120 bool replaceDot(Function &F);
121 bool replaceFmod(Function &F);
122 bool replaceExp10(Function &F, const std::string &basename, int vec_size,
123 int byte_len);
124 bool replaceLog10(Function &F, const std::string &basename, int vec_size,
125 int byte_len);
126 bool replaceBarrier(Function &F);
127 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100128 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500129 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
130 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
131 bool replaceIsFinite(Function &F);
132 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
133 bool replaceUpsample(Function &F);
134 bool replaceRotate(Function &F);
135 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
136 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
137 bool replaceSelect(Function &F);
138 bool replaceBitSelect(Function &F);
139 bool replaceStep(Function &F, bool is_smooth, int vec_size);
140 bool replaceSignbit(Function &F, bool is_vec);
141 bool replaceMul(Function &F, bool is_float, bool is_mad);
142 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
143 bool replaceVloadHalf(Function &F);
144 bool replaceVloadHalf2(Function &F);
145 bool replaceVloadHalf4(Function &F);
146 bool replaceClspvVloadaHalf2(Function &F);
147 bool replaceClspvVloadaHalf4(Function &F);
148 bool replaceVstoreHalf(Function &F, int vec_size);
149 bool replaceVstoreHalf(Function &F);
150 bool replaceVstoreHalf2(Function &F);
151 bool replaceVstoreHalf4(Function &F);
152 bool replaceHalfReadImage(Function &F);
153 bool replaceHalfWriteImage(Function &F);
154 bool replaceSampledReadImageWithIntCoords(Function &F);
155 bool replaceAtomics(Function &F, spv::Op Op);
156 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
157 bool replaceCross(Function &F);
158 bool replaceFract(Function &F, int vec_size);
159 bool replaceVload(Function &F);
160 bool replaceVstore(Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400161};
SJW2c317da2020-03-23 07:39:13 -0500162
Kévin Petit91bc72e2019-04-08 15:17:46 +0100163} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400164
165char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400166INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
167 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400168
169namespace clspv {
170ModulePass *createReplaceOpenCLBuiltinPass() {
171 return new ReplaceOpenCLBuiltinPass();
172}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400173} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400174
175bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500176 std::list<Function *> func_list;
177 for (auto &F : M.getFunctionList()) {
178 // process only function declarations
179 if (F.isDeclaration() && runOnFunction(F)) {
180 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000181 }
182 }
SJW2c317da2020-03-23 07:39:13 -0500183 if (func_list.size() != 0) {
184 // recursively convert functions, but first remove dead
185 for (auto *F : func_list) {
186 if (F->use_empty()) {
187 F->eraseFromParent();
188 }
189 }
190 runOnModule(M);
191 return true;
192 }
193 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000194}
195
SJW2c317da2020-03-23 07:39:13 -0500196bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
197 auto &FI = Builtins::Lookup(&F);
198 switch (FI.getType()) {
199 case Builtins::kAbs:
200 if (!FI.getParameter(0).is_signed) {
201 return replaceAbs(F);
202 }
203 break;
204 case Builtins::kAbsDiff:
205 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
206 case Builtins::kCopysign:
207 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100208
SJW2c317da2020-03-23 07:39:13 -0500209 case Builtins::kHalfRecip:
210 case Builtins::kNativeRecip:
211 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100212
SJW2c317da2020-03-23 07:39:13 -0500213 case Builtins::kHalfDivide:
214 case Builtins::kNativeDivide:
215 return replaceDivide(F);
216
217 case Builtins::kDot:
218 return replaceDot(F);
219
220 case Builtins::kExp10:
221 case Builtins::kHalfExp10:
222 case Builtins::kNativeExp10: {
223 auto &P0 = FI.getParameter(0);
224 return replaceExp10(F, FI.getName(), P0.vector_size, P0.byte_len);
225 }
226
227 case Builtins::kLog10:
228 case Builtins::kHalfLog10:
229 case Builtins::kNativeLog10: {
230 auto &P0 = FI.getParameter(0);
231 return replaceLog10(F, FI.getName(), P0.vector_size, P0.byte_len);
232 }
233
234 case Builtins::kFmod:
235 return replaceFmod(F);
236
237 case Builtins::kBarrier:
238 case Builtins::kWorkGroupBarrier:
239 return replaceBarrier(F);
240
241 case Builtins::kMemFence:
242 return replaceMemFence(F, spv::MemorySemanticsSequentiallyConsistentMask);
243 case Builtins::kReadMemFence:
244 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
245 case Builtins::kWriteMemFence:
246 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
247
248 // Relational
249 case Builtins::kIsequal:
250 return replaceRelational(F, CmpInst::FCMP_OEQ,
251 FI.getParameter(0).vector_size ? -1 : 1);
252 case Builtins::kIsgreater:
253 return replaceRelational(F, CmpInst::FCMP_OGT,
254 FI.getParameter(0).vector_size ? -1 : 1);
255 case Builtins::kIsgreaterequal:
256 return replaceRelational(F, CmpInst::FCMP_OGE,
257 FI.getParameter(0).vector_size ? -1 : 1);
258 case Builtins::kIsless:
259 return replaceRelational(F, CmpInst::FCMP_OLT,
260 FI.getParameter(0).vector_size ? -1 : 1);
261 case Builtins::kIslessequal:
262 return replaceRelational(F, CmpInst::FCMP_OLE,
263 FI.getParameter(0).vector_size ? -1 : 1);
264 case Builtins::kIsnotequal:
265 return replaceRelational(F, CmpInst::FCMP_ONE,
266 FI.getParameter(0).vector_size ? -1 : 1);
267
268 case Builtins::kIsinf: {
269 bool is_vec = FI.getParameter(0).vector_size != 0;
270 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
271 }
272 case Builtins::kIsnan: {
273 bool is_vec = FI.getParameter(0).vector_size != 0;
274 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
275 }
276
277 case Builtins::kIsfinite:
278 return replaceIsFinite(F);
279
280 case Builtins::kAll: {
281 bool is_vec = FI.getParameter(0).vector_size != 0;
282 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
283 }
284 case Builtins::kAny: {
285 bool is_vec = FI.getParameter(0).vector_size != 0;
286 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
287 }
288
289 case Builtins::kUpsample:
290 return replaceUpsample(F);
291
292 case Builtins::kRotate:
293 return replaceRotate(F);
294
295 case Builtins::kConvert:
296 return replaceConvert(F, FI.getParameter(0).is_signed,
297 FI.getReturnType().is_signed);
298
299 case Builtins::kAtomicInc:
300 return replaceAtomics(F, spv::OpAtomicIIncrement);
301 case Builtins::kAtomicDec:
302 return replaceAtomics(F, spv::OpAtomicIDecrement);
303 case Builtins::kAtomicCmpxchg:
304 return replaceAtomics(F, spv::OpAtomicCompareExchange);
305 case Builtins::kAtomicAdd:
306 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
307 case Builtins::kAtomicSub:
308 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
309 case Builtins::kAtomicXchg:
310 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
311 case Builtins::kAtomicMin:
312 return replaceAtomics(F, FI.getParameter(0).is_signed
313 ? llvm::AtomicRMWInst::Min
314 : llvm::AtomicRMWInst::UMin);
315 case Builtins::kAtomicMax:
316 return replaceAtomics(F, FI.getParameter(0).is_signed
317 ? llvm::AtomicRMWInst::Max
318 : llvm::AtomicRMWInst::UMax);
319 case Builtins::kAtomicAnd:
320 return replaceAtomics(F, llvm::AtomicRMWInst::And);
321 case Builtins::kAtomicOr:
322 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
323 case Builtins::kAtomicXor:
324 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
325
326 case Builtins::kCross:
327 if (FI.getParameter(0).vector_size == 4) {
328 return replaceCross(F);
329 }
330 break;
331
332 case Builtins::kFract:
333 if (FI.getParameterCount()) {
334 return replaceFract(F, FI.getParameter(0).vector_size);
335 }
336 break;
337
338 case Builtins::kMadHi:
339 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
340 case Builtins::kMulHi:
341 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
342
343 case Builtins::kMad:
344 case Builtins::kMad24:
345 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
346 true);
347 case Builtins::kMul24:
348 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
349 false);
350
351 case Builtins::kSelect:
352 return replaceSelect(F);
353
354 case Builtins::kBitselect:
355 return replaceBitSelect(F);
356
357 case Builtins::kVload:
358 return replaceVload(F);
359
360 case Builtins::kVloadaHalf:
361 case Builtins::kVloadHalf:
362 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
363
364 case Builtins::kVstore:
365 return replaceVstore(F);
366
367 case Builtins::kVstoreHalf:
368 case Builtins::kVstoreaHalf:
369 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
370
371 case Builtins::kSmoothstep: {
372 int vec_size = FI.getLastParameter().vector_size;
373 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
374 return replaceStep(F, true, vec_size);
375 }
376 break;
377 }
378 case Builtins::kStep: {
379 int vec_size = FI.getLastParameter().vector_size;
380 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
381 return replaceStep(F, false, vec_size);
382 }
383 break;
384 }
385
386 case Builtins::kSignbit:
387 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
388
389 case Builtins::kReadImageh:
390 return replaceHalfReadImage(F);
391 case Builtins::kReadImagef:
392 case Builtins::kReadImagei:
393 case Builtins::kReadImageui: {
394 if (FI.getParameter(1).isSampler() &&
395 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
396 return replaceSampledReadImageWithIntCoords(F);
397 }
398 break;
399 }
400
401 case Builtins::kWriteImageh:
402 return replaceHalfWriteImage(F);
403
Kévin Petit1cb45112020-04-27 18:55:48 +0100404 case Builtins::kPrefetch:
405 return replacePrefetch(F);
406
SJW2c317da2020-03-23 07:39:13 -0500407 default:
408 break;
409 }
410
411 return false;
412}
413
414bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
415 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400416 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100417}
418
SJW2c317da2020-03-23 07:39:13 -0500419bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
420 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100421 auto XValue = CI->getOperand(0);
422 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100423
Kévin Petite8edce32019-04-10 14:23:32 +0100424 IRBuilder<> Builder(CI);
425 auto XmY = Builder.CreateSub(XValue, YValue);
426 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100427
SJW2c317da2020-03-23 07:39:13 -0500428 Value *Cmp = nullptr;
429 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100430 Cmp = Builder.CreateICmpSGT(YValue, XValue);
431 } else {
432 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100433 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100434
Kévin Petite8edce32019-04-10 14:23:32 +0100435 return Builder.CreateSelect(Cmp, YmX, XmY);
436 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100437}
438
SJW2c317da2020-03-23 07:39:13 -0500439bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
440 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100441 auto XValue = CI->getOperand(0);
442 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100443
Kévin Petite8edce32019-04-10 14:23:32 +0100444 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100445
SJW2c317da2020-03-23 07:39:13 -0500446 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400447 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
448 IntTy = VectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petit8c1be282019-04-02 19:34:25 +0100449 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100450
Kévin Petite8edce32019-04-10 14:23:32 +0100451 // Return X with the sign of Y
452
453 // Sign bit masks
454 auto SignBit = IntTy->getScalarSizeInBits() - 1;
455 auto SignBitMask = 1 << SignBit;
456 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
457 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
458
459 IRBuilder<> Builder(CI);
460
461 // Extract sign of Y
462 auto YInt = Builder.CreateBitCast(YValue, IntTy);
463 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
464
465 // Clear sign bit in X
466 auto XInt = Builder.CreateBitCast(XValue, IntTy);
467 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
468
469 // Insert sign bit of Y into X
470 auto NewXInt = Builder.CreateOr(XInt, YSign);
471
472 // And cast back to floating-point
473 return Builder.CreateBitCast(NewXInt, Ty);
474 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100475}
476
SJW2c317da2020-03-23 07:39:13 -0500477bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
478 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100479 // Recip has one arg.
480 auto Arg = CI->getOperand(0);
481 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
482 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
483 });
David Neto22f144c2017-06-12 14:26:21 -0400484}
485
SJW2c317da2020-03-23 07:39:13 -0500486bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
487 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100488 auto Op0 = CI->getOperand(0);
489 auto Op1 = CI->getOperand(1);
490 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
491 });
David Neto22f144c2017-06-12 14:26:21 -0400492}
493
SJW2c317da2020-03-23 07:39:13 -0500494bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
495 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100496 auto Op0 = CI->getOperand(0);
497 auto Op1 = CI->getOperand(1);
498
SJW2c317da2020-03-23 07:39:13 -0500499 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100500 if (Op0->getType()->isVectorTy()) {
501 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
502 CI->getType(), {Op0, Op1});
503 } else {
504 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
505 }
506
507 return V;
508 });
509}
510
SJW2c317da2020-03-23 07:39:13 -0500511bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
512 const std::string &basename,
513 int vec_size, int byte_len) {
514 // convert to natural
515 auto slen = basename.length() - 2;
516 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
517 if (vec_size) {
518 NewFName += "Dv" + std::to_string(vec_size) + "_";
519 }
520 switch (byte_len) {
521 case 4:
522 NewFName += "f";
523 break;
524 case 8:
525 NewFName += "d";
526 break;
527 default:
528 llvm_unreachable("Unsupported exp10 byte length");
529 break;
David Neto22f144c2017-06-12 14:26:21 -0400530 }
531
SJW2c317da2020-03-23 07:39:13 -0500532 Module &M = *F.getParent();
533 return replaceCallsWithValue(F, [&](CallInst *CI) {
534 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
535
536 auto Arg = CI->getOperand(0);
537
538 // Constant of the natural log of 10 (ln(10)).
539 const double Ln10 =
540 2.302585092994045684017991454684364207601101488628772976033;
541
542 auto Mul = BinaryOperator::Create(
543 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
544
545 return CallInst::Create(NewF, Mul, "", CI);
546 });
David Neto22f144c2017-06-12 14:26:21 -0400547}
548
SJW2c317da2020-03-23 07:39:13 -0500549bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100550 // OpenCL fmod(x,y) is x - y * trunc(x/y)
551 // The sign for a non-zero result is taken from x.
552 // (Try an example.)
553 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500554 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100555 auto Op0 = CI->getOperand(0);
556 auto Op1 = CI->getOperand(1);
557 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
558 });
559}
560
SJW2c317da2020-03-23 07:39:13 -0500561bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
562 const std::string &basename,
563 int vec_size, int byte_len) {
564 // convert to natural
565 auto slen = basename.length() - 2;
566 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
567 if (vec_size) {
568 NewFName += "Dv" + std::to_string(vec_size) + "_";
569 }
570 switch (byte_len) {
571 case 4:
572 NewFName += "f";
573 break;
574 case 8:
575 NewFName += "d";
576 break;
577 default:
578 llvm_unreachable("Unsupported log10 byte length");
579 break;
David Neto22f144c2017-06-12 14:26:21 -0400580 }
581
SJW2c317da2020-03-23 07:39:13 -0500582 Module &M = *F.getParent();
583 return replaceCallsWithValue(F, [&](CallInst *CI) {
584 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
585
586 auto Arg = CI->getOperand(0);
587
588 // Constant of the reciprocal of the natural log of 10 (ln(10)).
589 const double Ln10 =
590 0.434294481903251827651128918916605082294397005803666566114;
591
592 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
593
594 return BinaryOperator::Create(Instruction::FMul,
595 ConstantFP::get(Arg->getType(), Ln10), NewCI,
596 "", CI);
597 });
David Neto22f144c2017-06-12 14:26:21 -0400598}
599
SJW2c317da2020-03-23 07:39:13 -0500600bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -0400601
602 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
603
SJW2c317da2020-03-23 07:39:13 -0500604 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100605 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400606
Kévin Petitc4643922019-06-17 19:32:05 +0100607 // We need to map the OpenCL constants to the SPIR-V equivalents.
608 const auto LocalMemFence =
609 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
610 const auto GlobalMemFence =
611 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
612 const auto ConstantSequentiallyConsistent = ConstantInt::get(
613 Arg->getType(), spv::MemorySemanticsSequentiallyConsistentMask);
614 const auto ConstantScopeDevice =
615 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
616 const auto ConstantScopeWorkgroup =
617 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400618
Kévin Petitc4643922019-06-17 19:32:05 +0100619 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
620 const auto LocalMemFenceMask =
621 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
622 const auto WorkgroupShiftAmount =
623 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
624 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
625 Instruction::Shl, LocalMemFenceMask,
626 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400627
Kévin Petitc4643922019-06-17 19:32:05 +0100628 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
629 const auto GlobalMemFenceMask =
630 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
631 const auto UniformShiftAmount =
632 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
633 const auto MemorySemanticsUniform = BinaryOperator::Create(
634 Instruction::Shl, GlobalMemFenceMask,
635 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400636
Kévin Petitc4643922019-06-17 19:32:05 +0100637 // And combine the above together, also adding in
638 // MemorySemanticsSequentiallyConsistentMask.
639 auto MemorySemantics =
640 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
641 ConstantSequentiallyConsistent, "", CI);
642 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
643 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400644
Kévin Petitc4643922019-06-17 19:32:05 +0100645 // For Memory Scope if we used CLK_GLOBAL_MEM_FENCE, we need to use
646 // Device Scope, otherwise Workgroup Scope.
647 const auto Cmp =
648 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, GlobalMemFenceMask,
649 GlobalMemFence, "", CI);
650 const auto MemoryScope = SelectInst::Create(Cmp, ConstantScopeDevice,
651 ConstantScopeWorkgroup, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400652
Kévin Petitc4643922019-06-17 19:32:05 +0100653 // Lastly, the Execution Scope is always Workgroup Scope.
654 const auto ExecutionScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400655
Kévin Petitc4643922019-06-17 19:32:05 +0100656 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
657 {Attribute::NoDuplicate}, CI->getType(),
658 {ExecutionScope, MemoryScope, MemorySemantics});
659 });
David Neto22f144c2017-06-12 14:26:21 -0400660}
661
SJW2c317da2020-03-23 07:39:13 -0500662bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
663 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400664
SJW2c317da2020-03-23 07:39:13 -0500665 return replaceCallsWithValue(F, [&](CallInst *CI) {
666 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
David Neto22f144c2017-06-12 14:26:21 -0400667
SJW2c317da2020-03-23 07:39:13 -0500668 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400669
SJW2c317da2020-03-23 07:39:13 -0500670 // We need to map the OpenCL constants to the SPIR-V equivalents.
671 const auto LocalMemFence =
672 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
673 const auto GlobalMemFence =
674 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
675 const auto ConstantMemorySemantics =
676 ConstantInt::get(Arg->getType(), semantics);
677 const auto ConstantScopeDevice =
678 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -0400679
SJW2c317da2020-03-23 07:39:13 -0500680 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
681 const auto LocalMemFenceMask =
682 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
683 const auto WorkgroupShiftAmount =
684 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
685 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
686 Instruction::Shl, LocalMemFenceMask,
687 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400688
SJW2c317da2020-03-23 07:39:13 -0500689 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
690 const auto GlobalMemFenceMask =
691 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
692 const auto UniformShiftAmount =
693 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
694 const auto MemorySemanticsUniform = BinaryOperator::Create(
695 Instruction::Shl, GlobalMemFenceMask,
696 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400697
SJW2c317da2020-03-23 07:39:13 -0500698 // And combine the above together, also adding in
699 // MemorySemanticsSequentiallyConsistentMask.
700 auto MemorySemantics =
701 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
702 ConstantMemorySemantics, "", CI);
703 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
704 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400705
SJW2c317da2020-03-23 07:39:13 -0500706 // Memory Scope is always device.
707 const auto MemoryScope = ConstantScopeDevice;
David Neto22f144c2017-06-12 14:26:21 -0400708
SJW2c317da2020-03-23 07:39:13 -0500709 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier, {}, CI->getType(),
710 {MemoryScope, MemorySemantics});
711 });
David Neto22f144c2017-06-12 14:26:21 -0400712}
713
Kévin Petit1cb45112020-04-27 18:55:48 +0100714bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
715 bool Changed = false;
716
717 SmallVector<Instruction *, 4> ToRemoves;
718
719 // Find all calls to the function
720 for (auto &U : F.uses()) {
721 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
722 ToRemoves.push_back(CI);
723 }
724 }
725
726 Changed = !ToRemoves.empty();
727
728 // Delete them
729 for (auto V : ToRemoves) {
730 V->eraseFromParent();
731 }
732
733 return Changed;
734}
735
SJW2c317da2020-03-23 07:39:13 -0500736bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
737 CmpInst::Predicate P,
738 int32_t C) {
739 return replaceCallsWithValue(F, [&](CallInst *CI) {
740 // The predicate to use in the CmpInst.
741 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400742
SJW2c317da2020-03-23 07:39:13 -0500743 // The value to return for true.
744 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400745
SJW2c317da2020-03-23 07:39:13 -0500746 // The value to return for false.
747 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400748
SJW2c317da2020-03-23 07:39:13 -0500749 auto Arg1 = CI->getOperand(0);
750 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400751
SJW2c317da2020-03-23 07:39:13 -0500752 const auto Cmp =
753 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400754
SJW2c317da2020-03-23 07:39:13 -0500755 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
756 });
David Neto22f144c2017-06-12 14:26:21 -0400757}
758
SJW2c317da2020-03-23 07:39:13 -0500759bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
760 spv::Op SPIRVOp,
761 int32_t C) {
762 Module &M = *F.getParent();
763 return replaceCallsWithValue(F, [&](CallInst *CI) {
764 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400765
SJW2c317da2020-03-23 07:39:13 -0500766 // The value to return for true.
767 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400768
SJW2c317da2020-03-23 07:39:13 -0500769 // The value to return for false.
770 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400771
SJW2c317da2020-03-23 07:39:13 -0500772 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400773 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
SJW2c317da2020-03-23 07:39:13 -0500774 CorrespondingBoolTy = VectorType::get(Type::getInt1Ty(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -0400775 CIVecTy->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -0400776 }
David Neto22f144c2017-06-12 14:26:21 -0400777
SJW2c317da2020-03-23 07:39:13 -0500778 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
779 CorrespondingBoolTy, {CI->getOperand(0)});
780
781 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
782 });
David Neto22f144c2017-06-12 14:26:21 -0400783}
784
SJW2c317da2020-03-23 07:39:13 -0500785bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
786 Module &M = *F.getParent();
787 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100788 auto &C = M.getContext();
789 auto Val = CI->getOperand(0);
790 auto ValTy = Val->getType();
791 auto RetTy = CI->getType();
792
793 // Get a suitable integer type to represent the number
794 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
795
796 // Create Mask
797 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -0500798 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100799 switch (ScalarSize) {
800 case 16:
801 InfMask = ConstantInt::get(IntTy, 0x7C00U);
802 break;
803 case 32:
804 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
805 break;
806 case 64:
807 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
808 break;
809 default:
810 llvm_unreachable("Unsupported floating-point type");
811 }
812
813 IRBuilder<> Builder(CI);
814
815 // Bitcast to int
816 auto ValInt = Builder.CreateBitCast(Val, IntTy);
817
818 // Mask and compare
819 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
820 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
821
822 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -0500823 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100824 if (ValTy->isVectorTy()) {
825 RetTrue = ConstantInt::getSigned(RetTy, -1);
826 } else {
827 RetTrue = ConstantInt::get(RetTy, 1);
828 }
829 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
830 });
831}
832
SJW2c317da2020-03-23 07:39:13 -0500833bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
834 Module &M = *F.getParent();
835 return replaceCallsWithValue(F, [&](CallInst *CI) {
836 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400837
SJW2c317da2020-03-23 07:39:13 -0500838 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +0000839
SJW2c317da2020-03-23 07:39:13 -0500840 // If the argument is a 32-bit int, just use a shift
841 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
842 V = BinaryOperator::Create(Instruction::LShr, Arg,
843 ConstantInt::get(Arg->getType(), 31), "", CI);
844 } else {
845 // The value for zero to compare against.
846 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -0400847
SJW2c317da2020-03-23 07:39:13 -0500848 // The value to return for true.
849 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -0400850
SJW2c317da2020-03-23 07:39:13 -0500851 // The value to return for false.
852 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400853
SJW2c317da2020-03-23 07:39:13 -0500854 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
855 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400856
SJW2c317da2020-03-23 07:39:13 -0500857 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400858
SJW2c317da2020-03-23 07:39:13 -0500859 // If we have a function to call, call it!
860 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -0400861
SJW2c317da2020-03-23 07:39:13 -0500862 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -0400863
SJW2c317da2020-03-23 07:39:13 -0500864 const auto NewCI = clspv::InsertSPIRVOp(
865 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
866 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -0400867
SJW2c317da2020-03-23 07:39:13 -0500868 } else {
869 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -0400870 }
871
SJW2c317da2020-03-23 07:39:13 -0500872 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400873 }
SJW2c317da2020-03-23 07:39:13 -0500874 return V;
875 });
David Neto22f144c2017-06-12 14:26:21 -0400876}
877
SJW2c317da2020-03-23 07:39:13 -0500878bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
879 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
880 // Get arguments
881 auto HiValue = CI->getOperand(0);
882 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000883
SJW2c317da2020-03-23 07:39:13 -0500884 // Don't touch overloads that aren't in OpenCL C
885 auto HiType = HiValue->getType();
886 auto LoType = LoValue->getType();
887
888 if (HiType != LoType) {
889 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000890 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000891
SJW2c317da2020-03-23 07:39:13 -0500892 if (!HiType->isIntOrIntVectorTy()) {
893 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000894 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000895
SJW2c317da2020-03-23 07:39:13 -0500896 if (HiType->getScalarSizeInBits() * 2 !=
897 CI->getType()->getScalarSizeInBits()) {
898 return nullptr;
899 }
900
901 if ((HiType->getScalarSizeInBits() != 8) &&
902 (HiType->getScalarSizeInBits() != 16) &&
903 (HiType->getScalarSizeInBits() != 32)) {
904 return nullptr;
905 }
906
James Pricecf53df42020-04-20 14:41:24 -0400907 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
908 unsigned NumElements = HiVecType->getNumElements();
909 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
910 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500911 return nullptr;
912 }
913 }
914
915 // Convert both operands to the result type
916 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
917 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
918
919 // Shift high operand
920 auto ShiftAmount =
921 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
922 auto HiShifted =
923 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
924
925 // OR both results
926 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
927 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000928}
929
SJW2c317da2020-03-23 07:39:13 -0500930bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
931 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
932 // Get arguments
933 auto SrcValue = CI->getOperand(0);
934 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000935
SJW2c317da2020-03-23 07:39:13 -0500936 // Don't touch overloads that aren't in OpenCL C
937 auto SrcType = SrcValue->getType();
938 auto RotType = RotAmount->getType();
939
940 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
941 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000942 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000943
SJW2c317da2020-03-23 07:39:13 -0500944 if (!SrcType->isIntOrIntVectorTy()) {
945 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000946 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000947
SJW2c317da2020-03-23 07:39:13 -0500948 if ((SrcType->getScalarSizeInBits() != 8) &&
949 (SrcType->getScalarSizeInBits() != 16) &&
950 (SrcType->getScalarSizeInBits() != 32) &&
951 (SrcType->getScalarSizeInBits() != 64)) {
952 return nullptr;
953 }
954
James Pricecf53df42020-04-20 14:41:24 -0400955 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
956 unsigned NumElements = SrcVecType->getNumElements();
957 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
958 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500959 return nullptr;
960 }
961 }
962
963 // The approach used is to shift the top bits down, the bottom bits up
964 // and OR the two shifted values.
965
966 // The rotation amount is to be treated modulo the element size.
967 // Since SPIR-V shift ops don't support this, let's apply the
968 // modulo ahead of shifting. The element size is always a power of
969 // two so we can just AND with a mask.
970 auto ModMask =
971 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
972 RotAmount =
973 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
974
975 // Let's calc the amount by which to shift top bits down
976 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
977 auto DownAmount =
978 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
979
980 // Now shift the bottom bits up and the top bits down
981 auto LoRotated =
982 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
983 auto HiRotated =
984 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
985
986 // Finally OR the two shifted values
987 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
988 CI);
989 });
Kévin Petitd44eef52019-03-08 13:22:14 +0000990}
991
SJW2c317da2020-03-23 07:39:13 -0500992bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
993 bool DstIsSigned) {
994 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
995 Value *V = nullptr;
996 // Get arguments
997 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000998
SJW2c317da2020-03-23 07:39:13 -0500999 // Don't touch overloads that aren't in OpenCL C
1000 auto SrcType = SrcValue->getType();
1001 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001002
SJW2c317da2020-03-23 07:39:13 -05001003 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1004 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1005 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001006 }
1007
James Pricecf53df42020-04-20 14:41:24 -04001008 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
1009 unsigned SrcNumElements = SrcVecType->getNumElements();
1010 unsigned DstNumElements = cast<VectorType>(DstType)->getNumElements();
1011 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001012 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001013 }
1014
James Pricecf53df42020-04-20 14:41:24 -04001015 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1016 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1017 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001018 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001019 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001020 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001021
SJW2c317da2020-03-23 07:39:13 -05001022 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1023 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1024
1025 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1026 bool DstIsInt = DstType->isIntOrIntVectorTy();
1027
1028 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1029 // Unnecessary cast operation.
1030 V = SrcValue;
1031 } else if (SrcIsFloat && DstIsFloat) {
1032 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1033 } else if (SrcIsFloat && DstIsInt) {
1034 if (DstIsSigned) {
1035 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1036 } else {
1037 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1038 }
1039 } else if (SrcIsInt && DstIsFloat) {
1040 if (SrcIsSigned) {
1041 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1042 } else {
1043 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1044 }
1045 } else if (SrcIsInt && DstIsInt) {
1046 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1047 } else {
1048 // Not something we're supposed to handle, just move on
1049 }
1050
1051 return V;
1052 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001053}
1054
SJW2c317da2020-03-23 07:39:13 -05001055bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1056 bool is_mad) {
1057 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1058 Value *V = nullptr;
1059 // Get arguments
1060 auto AValue = CI->getOperand(0);
1061 auto BValue = CI->getOperand(1);
1062 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001063
SJW2c317da2020-03-23 07:39:13 -05001064 // Don't touch overloads that aren't in OpenCL C
1065 auto AType = AValue->getType();
1066 auto BType = BValue->getType();
1067 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001068
SJW2c317da2020-03-23 07:39:13 -05001069 if ((AType != BType) || (CI->getType() != AType) ||
1070 (is_mad && (AType != CType))) {
1071 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001072 }
1073
SJW2c317da2020-03-23 07:39:13 -05001074 if (!AType->isIntOrIntVectorTy()) {
1075 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001076 }
Kévin Petit8a560882019-03-21 15:24:34 +00001077
SJW2c317da2020-03-23 07:39:13 -05001078 if ((AType->getScalarSizeInBits() != 8) &&
1079 (AType->getScalarSizeInBits() != 16) &&
1080 (AType->getScalarSizeInBits() != 32) &&
1081 (AType->getScalarSizeInBits() != 64)) {
1082 return V;
1083 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001084
James Pricecf53df42020-04-20 14:41:24 -04001085 if (auto AVecType = dyn_cast<VectorType>(AType)) {
1086 unsigned NumElements = AVecType->getNumElements();
1087 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1088 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001089 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001090 }
1091 }
1092
SJW2c317da2020-03-23 07:39:13 -05001093 // Our SPIR-V op returns a struct, create a type for it
1094 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1095 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001096
SJW2c317da2020-03-23 07:39:13 -05001097 // Select the appropriate signed/unsigned SPIR-V op
1098 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1099
1100 // Call the SPIR-V op
1101 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1102 ExMulRetType, {AValue, BValue});
1103
1104 // Get the high part of the result
1105 unsigned Idxs[] = {1};
1106 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1107
1108 // If we're handling a mad_hi, add the third argument to the result
1109 if (is_mad) {
1110 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001111 }
1112
SJW2c317da2020-03-23 07:39:13 -05001113 return V;
1114 });
Kévin Petit8a560882019-03-21 15:24:34 +00001115}
1116
SJW2c317da2020-03-23 07:39:13 -05001117bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1118 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1119 // Get arguments
1120 auto FalseValue = CI->getOperand(0);
1121 auto TrueValue = CI->getOperand(1);
1122 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001123
SJW2c317da2020-03-23 07:39:13 -05001124 // Don't touch overloads that aren't in OpenCL C
1125 auto FalseType = FalseValue->getType();
1126 auto TrueType = TrueValue->getType();
1127 auto PredicateType = PredicateValue->getType();
1128
1129 if (FalseType != TrueType) {
1130 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001131 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001132
SJW2c317da2020-03-23 07:39:13 -05001133 if (!PredicateType->isIntOrIntVectorTy()) {
1134 return nullptr;
1135 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001136
SJW2c317da2020-03-23 07:39:13 -05001137 if (!FalseType->isIntOrIntVectorTy() &&
1138 !FalseType->getScalarType()->isFloatingPointTy()) {
1139 return nullptr;
1140 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001141
SJW2c317da2020-03-23 07:39:13 -05001142 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1143 return nullptr;
1144 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001145
SJW2c317da2020-03-23 07:39:13 -05001146 if (FalseType->getScalarSizeInBits() !=
1147 PredicateType->getScalarSizeInBits()) {
1148 return nullptr;
1149 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001150
James Pricecf53df42020-04-20 14:41:24 -04001151 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
1152 unsigned NumElements = FalseVecType->getNumElements();
1153 if (NumElements != cast<VectorType>(PredicateType)->getNumElements()) {
SJW2c317da2020-03-23 07:39:13 -05001154 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001155 }
1156
James Pricecf53df42020-04-20 14:41:24 -04001157 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1158 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001159 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001160 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001161 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001162
SJW2c317da2020-03-23 07:39:13 -05001163 // Create constant
1164 const auto ZeroValue = Constant::getNullValue(PredicateType);
1165
1166 // Scalar and vector are to be treated differently
1167 CmpInst::Predicate Pred;
1168 if (PredicateType->isVectorTy()) {
1169 Pred = CmpInst::ICMP_SLT;
1170 } else {
1171 Pred = CmpInst::ICMP_NE;
1172 }
1173
1174 // Create comparison instruction
1175 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1176 ZeroValue, "", CI);
1177
1178 // Create select
1179 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1180 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001181}
1182
SJW2c317da2020-03-23 07:39:13 -05001183bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1184 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1185 Value *V = nullptr;
1186 if (CI->getNumOperands() != 4) {
1187 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001188 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001189
SJW2c317da2020-03-23 07:39:13 -05001190 // Get arguments
1191 auto FalseValue = CI->getOperand(0);
1192 auto TrueValue = CI->getOperand(1);
1193 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001194
SJW2c317da2020-03-23 07:39:13 -05001195 // Don't touch overloads that aren't in OpenCL C
1196 auto FalseType = FalseValue->getType();
1197 auto TrueType = TrueValue->getType();
1198 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001199
SJW2c317da2020-03-23 07:39:13 -05001200 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1201 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001202 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001203
James Pricecf53df42020-04-20 14:41:24 -04001204 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001205 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1206 !TrueType->getScalarType()->isIntegerTy()) {
1207 return V;
1208 }
James Pricecf53df42020-04-20 14:41:24 -04001209 unsigned NumElements = TrueVecType->getNumElements();
1210 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1211 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001212 return V;
1213 }
1214 }
1215
1216 // Remember the type of the operands
1217 auto OpType = TrueType;
1218
1219 // The actual bit selection will always be done on an integer type,
1220 // declare it here
1221 Type *BitType;
1222
1223 // If the operands are float, then bitcast them to int
1224 if (OpType->getScalarType()->isFloatingPointTy()) {
1225
1226 // First create the new type
1227 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1228
1229 // Then bitcast all operands
1230 PredicateValue =
1231 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1232 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1233 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1234
1235 } else {
1236 // The operands have an integer type, use it directly
1237 BitType = OpType;
1238 }
1239
1240 // All the operands are now always integers
1241 // implement as (c & b) | (~c & a)
1242
1243 // Create our negated predicate value
1244 auto AllOnes = Constant::getAllOnesValue(BitType);
1245 auto NotPredicateValue = BinaryOperator::Create(
1246 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1247
1248 // Then put everything together
1249 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1250 FalseValue, "", CI);
1251 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1252 TrueValue, "", CI);
1253
1254 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1255
1256 // If we were dealing with a floating point type, we must bitcast
1257 // the result back to that
1258 if (OpType->getScalarType()->isFloatingPointTy()) {
1259 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1260 }
1261
1262 return V;
1263 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001264}
1265
SJW2c317da2020-03-23 07:39:13 -05001266bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth,
1267 int vec_size) {
1268 // convert to vector versions
1269 Module &M = *F.getParent();
1270 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1271 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1272 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001273
SJW2c317da2020-03-23 07:39:13 -05001274 std::string NewFName = "_Z";
1275 if (is_smooth) {
1276 NewFName += std::to_string(10) + "smoothstepDv" +
1277 std::to_string(vec_size) + "_fS_S_";
1278 } else {
1279 NewFName +=
1280 std::to_string(4) + "stepDv" + std::to_string(vec_size) + "_fS_";
Kévin Petit6b0a9532018-10-30 20:00:39 +00001281 }
Kévin Petit6b0a9532018-10-30 20:00:39 +00001282
SJW2c317da2020-03-23 07:39:13 -05001283 // First figure out which function we're dealing with
1284 if (is_smooth) {
1285 ArgsToSplat.push_back(CI->getOperand(1));
1286 VectorArg = CI->getOperand(2);
1287 } else {
1288 VectorArg = CI->getOperand(1);
1289 }
1290
1291 // Splat arguments that need to be
1292 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001293 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001294
1295 for (auto arg : ArgsToSplat) {
1296 Value *NewVectorArg = UndefValue::get(VecType);
James Pricecf53df42020-04-20 14:41:24 -04001297 for (auto i = 0; i < VecType->getNumElements(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001298 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1299 NewVectorArg =
1300 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1301 }
1302 SplatArgs.push_back(NewVectorArg);
1303 }
1304
1305 // Replace the call with the vector/vector flavour
1306 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1307 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1308
1309 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1310
1311 SmallVector<Value *, 3> NewArgs;
1312 for (auto arg : SplatArgs) {
1313 NewArgs.push_back(arg);
1314 }
1315 NewArgs.push_back(VectorArg);
1316
1317 return CallInst::Create(NewF, NewArgs, "", CI);
1318 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001319}
1320
SJW2c317da2020-03-23 07:39:13 -05001321bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001322 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1323 auto Arg = CI->getOperand(0);
1324 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001325
SJW2c317da2020-03-23 07:39:13 -05001326 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001327
SJW2c317da2020-03-23 07:39:13 -05001328 return BinaryOperator::Create(Op, Bitcast,
1329 ConstantInt::get(CI->getType(), 31), "", CI);
1330 });
David Neto22f144c2017-06-12 14:26:21 -04001331}
1332
SJW2c317da2020-03-23 07:39:13 -05001333bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1334 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001335 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1336 // The multiply instruction to use.
1337 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001338
SJW2c317da2020-03-23 07:39:13 -05001339 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001340
SJW2c317da2020-03-23 07:39:13 -05001341 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1342 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001343
SJW2c317da2020-03-23 07:39:13 -05001344 if (is_mad) {
1345 // The add instruction to use.
1346 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001347
SJW2c317da2020-03-23 07:39:13 -05001348 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001349 }
David Neto22f144c2017-06-12 14:26:21 -04001350
SJW2c317da2020-03-23 07:39:13 -05001351 return V;
1352 });
David Neto22f144c2017-06-12 14:26:21 -04001353}
1354
SJW2c317da2020-03-23 07:39:13 -05001355bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001356 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1357 Value *V = nullptr;
1358 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001359
SJW2c317da2020-03-23 07:39:13 -05001360 auto data_type = data->getType();
1361 if (!data_type->isVectorTy())
1362 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001363
James Pricecf53df42020-04-20 14:41:24 -04001364 auto vec_data_type = cast<VectorType>(data_type);
1365
1366 auto elems = vec_data_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001367 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1368 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001369
SJW2c317da2020-03-23 07:39:13 -05001370 auto offset = CI->getOperand(1);
1371 auto ptr = CI->getOperand(2);
1372 auto ptr_type = ptr->getType();
1373 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001374 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001375 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001376
SJW2c317da2020-03-23 07:39:13 -05001377 // Avoid pointer casts. Instead generate the correct number of stores
1378 // and rely on drivers to coalesce appropriately.
1379 IRBuilder<> builder(CI);
1380 auto elems_const = builder.getInt32(elems);
1381 auto adjust = builder.CreateMul(offset, elems_const);
1382 for (auto i = 0; i < elems; ++i) {
1383 auto idx = builder.getInt32(i);
1384 auto add = builder.CreateAdd(adjust, idx);
1385 auto gep = builder.CreateGEP(ptr, add);
1386 auto extract = builder.CreateExtractElement(data, i);
1387 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001388 }
SJW2c317da2020-03-23 07:39:13 -05001389 return V;
1390 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001391}
1392
SJW2c317da2020-03-23 07:39:13 -05001393bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001394 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1395 Value *V = nullptr;
1396 auto ret_type = F.getReturnType();
1397 if (!ret_type->isVectorTy())
1398 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001399
James Pricecf53df42020-04-20 14:41:24 -04001400 auto vec_ret_type = cast<VectorType>(ret_type);
1401
1402 auto elems = vec_ret_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001403 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1404 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001405
SJW2c317da2020-03-23 07:39:13 -05001406 auto offset = CI->getOperand(0);
1407 auto ptr = CI->getOperand(1);
1408 auto ptr_type = ptr->getType();
1409 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001410 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001411 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001412
SJW2c317da2020-03-23 07:39:13 -05001413 // Avoid pointer casts. Instead generate the correct number of loads
1414 // and rely on drivers to coalesce appropriately.
1415 IRBuilder<> builder(CI);
1416 auto elems_const = builder.getInt32(elems);
1417 V = UndefValue::get(ret_type);
1418 auto adjust = builder.CreateMul(offset, elems_const);
1419 for (auto i = 0; i < elems; ++i) {
1420 auto idx = builder.getInt32(i);
1421 auto add = builder.CreateAdd(adjust, idx);
1422 auto gep = builder.CreateGEP(ptr, add);
1423 auto load = builder.CreateLoad(gep);
1424 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001425 }
SJW2c317da2020-03-23 07:39:13 -05001426 return V;
1427 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001428}
1429
SJW2c317da2020-03-23 07:39:13 -05001430bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1431 const std::string &name,
1432 int vec_size) {
1433 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1434 if (!vec_size) {
1435 // deduce vec_size from last character of name (e.g. vload_half4)
1436 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001437 }
SJW2c317da2020-03-23 07:39:13 -05001438 switch (vec_size) {
1439 case 2:
1440 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1441 case 4:
1442 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1443 case 0:
1444 if (!is_clspv_version) {
1445 return replaceVloadHalf(F);
1446 }
1447 default:
1448 llvm_unreachable("Unsupported vload_half vector size");
1449 break;
1450 }
1451 return false;
David Neto22f144c2017-06-12 14:26:21 -04001452}
1453
SJW2c317da2020-03-23 07:39:13 -05001454bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1455 Module &M = *F.getParent();
1456 return replaceCallsWithValue(F, [&](CallInst *CI) {
1457 // The index argument from vload_half.
1458 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001459
SJW2c317da2020-03-23 07:39:13 -05001460 // The pointer argument from vload_half.
1461 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001462
SJW2c317da2020-03-23 07:39:13 -05001463 auto IntTy = Type::getInt32Ty(M.getContext());
1464 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1465 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1466
1467 // Our intrinsic to unpack a float2 from an int.
1468 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1469
1470 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1471
1472 Value *V = nullptr;
1473
alan-baker7efcaaa2020-05-06 19:33:27 -04001474 bool supports_16bit_storage = true;
1475 switch (Arg1->getType()->getPointerAddressSpace()) {
1476 case clspv::AddressSpace::Global:
1477 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1478 clspv::Option::StorageClass::kSSBO);
1479 break;
1480 case clspv::AddressSpace::Constant:
1481 if (clspv::Option::ConstantArgsInUniformBuffer())
1482 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1483 clspv::Option::StorageClass::kUBO);
1484 else
1485 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1486 clspv::Option::StorageClass::kSSBO);
1487 break;
1488 default:
1489 // Clspv will emit the Float16 capability if the half type is
1490 // encountered. That capability covers private and local addressspaces.
1491 break;
1492 }
1493
1494 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001495 auto ShortTy = Type::getInt16Ty(M.getContext());
1496 auto ShortPointerTy =
1497 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1498
1499 // Cast the half* pointer to short*.
1500 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1501
1502 // Index into the correct address of the casted pointer.
1503 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1504
1505 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001506 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001507
1508 // ZExt the short -> int.
1509 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1510
1511 // Get our float2.
1512 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1513
1514 // Extract out the bottom element which is our float result.
1515 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1516 } else {
1517 // Assume the pointer argument points to storage aligned to 32bits
1518 // or more.
1519 // TODO(dneto): Do more analysis to make sure this is true?
1520 //
1521 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1522 // with:
1523 //
1524 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1525 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1526 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1527 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1528 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1529 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1530 // x float> %converted, %index_is_odd32
1531
1532 auto IntPointerTy =
1533 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1534
1535 // Cast the base pointer to int*.
1536 // In a valid call (according to assumptions), this should get
1537 // optimized away in the simplify GEP pass.
1538 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1539
1540 auto One = ConstantInt::get(IntTy, 1);
1541 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1542 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1543
1544 // Index into the correct address of the casted pointer.
1545 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1546
1547 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001548 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001549
1550 // Get our float2.
1551 auto Call = CallInst::Create(NewF, Load, "", CI);
1552
1553 // Extract out the float result, where the element number is
1554 // determined by whether the original index was even or odd.
1555 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1556 }
1557 return V;
1558 });
1559}
1560
1561bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1562 Module &M = *F.getParent();
1563 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001564 // The index argument from vload_half.
1565 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001566
Kévin Petite8edce32019-04-10 14:23:32 +01001567 // The pointer argument from vload_half.
1568 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001569
Kévin Petite8edce32019-04-10 14:23:32 +01001570 auto IntTy = Type::getInt32Ty(M.getContext());
1571 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001572 auto NewPointerTy =
1573 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001574 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001575
Kévin Petite8edce32019-04-10 14:23:32 +01001576 // Cast the half* pointer to int*.
1577 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001578
Kévin Petite8edce32019-04-10 14:23:32 +01001579 // Index into the correct address of the casted pointer.
1580 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001581
Kévin Petite8edce32019-04-10 14:23:32 +01001582 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001583 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001584
Kévin Petite8edce32019-04-10 14:23:32 +01001585 // Our intrinsic to unpack a float2 from an int.
1586 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001587
Kévin Petite8edce32019-04-10 14:23:32 +01001588 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001589
Kévin Petite8edce32019-04-10 14:23:32 +01001590 // Get our float2.
1591 return CallInst::Create(NewF, Load, "", CI);
1592 });
David Neto22f144c2017-06-12 14:26:21 -04001593}
1594
SJW2c317da2020-03-23 07:39:13 -05001595bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1596 Module &M = *F.getParent();
1597 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001598 // The index argument from vload_half.
1599 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001600
Kévin Petite8edce32019-04-10 14:23:32 +01001601 // The pointer argument from vload_half.
1602 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001603
Kévin Petite8edce32019-04-10 14:23:32 +01001604 auto IntTy = Type::getInt32Ty(M.getContext());
1605 auto Int2Ty = VectorType::get(IntTy, 2);
1606 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001607 auto NewPointerTy =
1608 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001609 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001610
Kévin Petite8edce32019-04-10 14:23:32 +01001611 // Cast the half* pointer to int2*.
1612 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001613
Kévin Petite8edce32019-04-10 14:23:32 +01001614 // Index into the correct address of the casted pointer.
1615 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001616
Kévin Petite8edce32019-04-10 14:23:32 +01001617 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001618 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001619
Kévin Petite8edce32019-04-10 14:23:32 +01001620 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001621 auto X =
1622 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1623 auto Y =
1624 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001625
Kévin Petite8edce32019-04-10 14:23:32 +01001626 // Our intrinsic to unpack a float2 from an int.
1627 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001628
Kévin Petite8edce32019-04-10 14:23:32 +01001629 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001630
Kévin Petite8edce32019-04-10 14:23:32 +01001631 // Get the lower (x & y) components of our final float4.
1632 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001633
Kévin Petite8edce32019-04-10 14:23:32 +01001634 // Get the higher (z & w) components of our final float4.
1635 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001636
Kévin Petite8edce32019-04-10 14:23:32 +01001637 Constant *ShuffleMask[4] = {
1638 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1639 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001640
Kévin Petite8edce32019-04-10 14:23:32 +01001641 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001642 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1643 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001644 });
David Neto22f144c2017-06-12 14:26:21 -04001645}
1646
SJW2c317da2020-03-23 07:39:13 -05001647bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001648
1649 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1650 //
1651 // %u = load i32 %ptr
1652 // %fxy = call <2 x float> Unpack2xHalf(u)
1653 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001654 Module &M = *F.getParent();
1655 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001656 auto Index = CI->getOperand(0);
1657 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001658
Kévin Petite8edce32019-04-10 14:23:32 +01001659 auto IntTy = Type::getInt32Ty(M.getContext());
1660 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1661 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001662
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001663 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001664 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001665
Kévin Petite8edce32019-04-10 14:23:32 +01001666 // Our intrinsic to unpack a float2 from an int.
1667 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001668
Kévin Petite8edce32019-04-10 14:23:32 +01001669 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001670
Kévin Petite8edce32019-04-10 14:23:32 +01001671 // Get our final float2.
1672 return CallInst::Create(NewF, Load, "", CI);
1673 });
David Neto6ad93232018-06-07 15:42:58 -07001674}
1675
SJW2c317da2020-03-23 07:39:13 -05001676bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001677
1678 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1679 //
1680 // %u2 = load <2 x i32> %ptr
1681 // %u2xy = extractelement %u2, 0
1682 // %u2zw = extractelement %u2, 1
1683 // %fxy = call <2 x float> Unpack2xHalf(uint)
1684 // %fzw = call <2 x float> Unpack2xHalf(uint)
1685 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001686 Module &M = *F.getParent();
1687 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001688 auto Index = CI->getOperand(0);
1689 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001690
Kévin Petite8edce32019-04-10 14:23:32 +01001691 auto IntTy = Type::getInt32Ty(M.getContext());
1692 auto Int2Ty = VectorType::get(IntTy, 2);
1693 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1694 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001695
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001696 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001697 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001698
Kévin Petite8edce32019-04-10 14:23:32 +01001699 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001700 auto X =
1701 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1702 auto Y =
1703 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001704
Kévin Petite8edce32019-04-10 14:23:32 +01001705 // Our intrinsic to unpack a float2 from an int.
1706 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001707
Kévin Petite8edce32019-04-10 14:23:32 +01001708 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001709
Kévin Petite8edce32019-04-10 14:23:32 +01001710 // Get the lower (x & y) components of our final float4.
1711 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001712
Kévin Petite8edce32019-04-10 14:23:32 +01001713 // Get the higher (z & w) components of our final float4.
1714 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001715
Kévin Petite8edce32019-04-10 14:23:32 +01001716 Constant *ShuffleMask[4] = {
1717 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1718 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001719
Kévin Petite8edce32019-04-10 14:23:32 +01001720 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001721 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1722 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001723 });
David Neto6ad93232018-06-07 15:42:58 -07001724}
1725
SJW2c317da2020-03-23 07:39:13 -05001726bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1727 switch (vec_size) {
1728 case 0:
1729 return replaceVstoreHalf(F);
1730 case 2:
1731 return replaceVstoreHalf2(F);
1732 case 4:
1733 return replaceVstoreHalf4(F);
1734 default:
1735 llvm_unreachable("Unsupported vstore_half vector size");
1736 break;
1737 }
1738 return false;
1739}
David Neto22f144c2017-06-12 14:26:21 -04001740
SJW2c317da2020-03-23 07:39:13 -05001741bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1742 Module &M = *F.getParent();
1743 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001744 // The value to store.
1745 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001746
Kévin Petite8edce32019-04-10 14:23:32 +01001747 // The index argument from vstore_half.
1748 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001749
Kévin Petite8edce32019-04-10 14:23:32 +01001750 // The pointer argument from vstore_half.
1751 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001752
Kévin Petite8edce32019-04-10 14:23:32 +01001753 auto IntTy = Type::getInt32Ty(M.getContext());
1754 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1755 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1756 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001757
Kévin Petite8edce32019-04-10 14:23:32 +01001758 // Our intrinsic to pack a float2 to an int.
1759 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001760
Kévin Petite8edce32019-04-10 14:23:32 +01001761 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001762
Kévin Petite8edce32019-04-10 14:23:32 +01001763 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001764 auto TempVec = InsertElementInst::Create(
1765 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001766
Kévin Petite8edce32019-04-10 14:23:32 +01001767 // Pack the float2 -> half2 (in an int).
1768 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001769
alan-baker7efcaaa2020-05-06 19:33:27 -04001770 bool supports_16bit_storage = true;
1771 switch (Arg2->getType()->getPointerAddressSpace()) {
1772 case clspv::AddressSpace::Global:
1773 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1774 clspv::Option::StorageClass::kSSBO);
1775 break;
1776 case clspv::AddressSpace::Constant:
1777 if (clspv::Option::ConstantArgsInUniformBuffer())
1778 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1779 clspv::Option::StorageClass::kUBO);
1780 else
1781 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1782 clspv::Option::StorageClass::kSSBO);
1783 break;
1784 default:
1785 // Clspv will emit the Float16 capability if the half type is
1786 // encountered. That capability covers private and local addressspaces.
1787 break;
1788 }
1789
SJW2c317da2020-03-23 07:39:13 -05001790 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04001791 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01001792 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001793 auto ShortPointerTy =
1794 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001795
Kévin Petite8edce32019-04-10 14:23:32 +01001796 // Truncate our i32 to an i16.
1797 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001798
Kévin Petite8edce32019-04-10 14:23:32 +01001799 // Cast the half* pointer to short*.
1800 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001801
Kévin Petite8edce32019-04-10 14:23:32 +01001802 // Index into the correct address of the casted pointer.
1803 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001804
Kévin Petite8edce32019-04-10 14:23:32 +01001805 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001806 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001807 } else {
1808 // We can only write to 32-bit aligned words.
1809 //
1810 // Assuming base is aligned to 32-bits, replace the equivalent of
1811 // vstore_half(value, index, base)
1812 // with:
1813 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1814 // uint32_t write_to_upper_half = index & 1u;
1815 // uint32_t shift = write_to_upper_half << 4;
1816 //
1817 // // Pack the float value as a half number in bottom 16 bits
1818 // // of an i32.
1819 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1820 //
1821 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1822 // ^ ((packed & 0xffff) << shift)
1823 // // We only need relaxed consistency, but OpenCL 1.2 only has
1824 // // sequentially consistent atomics.
1825 // // TODO(dneto): Use relaxed consistency.
1826 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001827 auto IntPointerTy =
1828 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001829
Kévin Petite8edce32019-04-10 14:23:32 +01001830 auto Four = ConstantInt::get(IntTy, 4);
1831 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001832
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001833 auto IndexIsOdd =
1834 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001836 auto IndexIntoI32 =
1837 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1838 auto BaseI32Ptr =
1839 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1840 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1841 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001842 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001843 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001844 auto MaskBitsToWrite =
1845 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1846 auto MaskedCurrent = BinaryOperator::CreateAnd(
1847 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001848
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001849 auto XLowerBits =
1850 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1851 auto NewBitsToWrite =
1852 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1853 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1854 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001855
Kévin Petite8edce32019-04-10 14:23:32 +01001856 // Generate the call to atomi_xor.
1857 SmallVector<Type *, 5> ParamTypes;
1858 // The pointer type.
1859 ParamTypes.push_back(IntPointerTy);
1860 // The Types for memory scope, semantics, and value.
1861 ParamTypes.push_back(IntTy);
1862 ParamTypes.push_back(IntTy);
1863 ParamTypes.push_back(IntTy);
1864 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1865 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001866
Kévin Petite8edce32019-04-10 14:23:32 +01001867 const auto ConstantScopeDevice =
1868 ConstantInt::get(IntTy, spv::ScopeDevice);
1869 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1870 // (SPIR-V Workgroup).
1871 const auto AddrSpaceSemanticsBits =
1872 IntPointerTy->getPointerAddressSpace() == 1
1873 ? spv::MemorySemanticsUniformMemoryMask
1874 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001875
Kévin Petite8edce32019-04-10 14:23:32 +01001876 // We're using relaxed consistency here.
1877 const auto ConstantMemorySemantics =
1878 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1879 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001880
Kévin Petite8edce32019-04-10 14:23:32 +01001881 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1882 ConstantMemorySemantics, ValueToXor};
1883 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001884
1885 // Return a Nop so the old Call is removed
1886 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1887 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001888 }
David Neto22f144c2017-06-12 14:26:21 -04001889
SJW2c317da2020-03-23 07:39:13 -05001890 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001891 });
David Neto22f144c2017-06-12 14:26:21 -04001892}
1893
SJW2c317da2020-03-23 07:39:13 -05001894bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1895 Module &M = *F.getParent();
1896 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001897 // The value to store.
1898 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001899
Kévin Petite8edce32019-04-10 14:23:32 +01001900 // The index argument from vstore_half.
1901 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 // The pointer argument from vstore_half.
1904 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001905
Kévin Petite8edce32019-04-10 14:23:32 +01001906 auto IntTy = Type::getInt32Ty(M.getContext());
1907 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001908 auto NewPointerTy =
1909 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001910 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001911
Kévin Petite8edce32019-04-10 14:23:32 +01001912 // Our intrinsic to pack a float2 to an int.
1913 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001914
Kévin Petite8edce32019-04-10 14:23:32 +01001915 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001916
Kévin Petite8edce32019-04-10 14:23:32 +01001917 // Turn the packed x & y into the final packing.
1918 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001919
Kévin Petite8edce32019-04-10 14:23:32 +01001920 // Cast the half* pointer to int*.
1921 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001922
Kévin Petite8edce32019-04-10 14:23:32 +01001923 // Index into the correct address of the casted pointer.
1924 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001925
Kévin Petite8edce32019-04-10 14:23:32 +01001926 // Store to the int* we casted to.
1927 return new StoreInst(X, Index, CI);
1928 });
David Neto22f144c2017-06-12 14:26:21 -04001929}
1930
SJW2c317da2020-03-23 07:39:13 -05001931bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1932 Module &M = *F.getParent();
1933 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001934 // The value to store.
1935 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001936
Kévin Petite8edce32019-04-10 14:23:32 +01001937 // The index argument from vstore_half.
1938 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001939
Kévin Petite8edce32019-04-10 14:23:32 +01001940 // The pointer argument from vstore_half.
1941 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001942
Kévin Petite8edce32019-04-10 14:23:32 +01001943 auto IntTy = Type::getInt32Ty(M.getContext());
1944 auto Int2Ty = VectorType::get(IntTy, 2);
1945 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001946 auto NewPointerTy =
1947 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001948 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001949
Kévin Petite8edce32019-04-10 14:23:32 +01001950 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1951 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04001952
Kévin Petite8edce32019-04-10 14:23:32 +01001953 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001954 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1955 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001956
Kévin Petite8edce32019-04-10 14:23:32 +01001957 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1958 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001959
Kévin Petite8edce32019-04-10 14:23:32 +01001960 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001961 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1962 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001963
Kévin Petite8edce32019-04-10 14:23:32 +01001964 // Our intrinsic to pack a float2 to an int.
1965 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001966
Kévin Petite8edce32019-04-10 14:23:32 +01001967 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001968
Kévin Petite8edce32019-04-10 14:23:32 +01001969 // Turn the packed x & y into the final component of our int2.
1970 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001971
Kévin Petite8edce32019-04-10 14:23:32 +01001972 // Turn the packed z & w into the final component of our int2.
1973 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001974
Kévin Petite8edce32019-04-10 14:23:32 +01001975 auto Combine = InsertElementInst::Create(
1976 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001977 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
1978 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001979
Kévin Petite8edce32019-04-10 14:23:32 +01001980 // Cast the half* pointer to int2*.
1981 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001982
Kévin Petite8edce32019-04-10 14:23:32 +01001983 // Index into the correct address of the casted pointer.
1984 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001985
Kévin Petite8edce32019-04-10 14:23:32 +01001986 // Store to the int2* we casted to.
1987 return new StoreInst(Combine, Index, CI);
1988 });
David Neto22f144c2017-06-12 14:26:21 -04001989}
1990
SJW2c317da2020-03-23 07:39:13 -05001991bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
1992 // convert half to float
1993 Module &M = *F.getParent();
1994 return replaceCallsWithValue(F, [&](CallInst *CI) {
1995 SmallVector<Type *, 3> types;
1996 SmallVector<Value *, 3> args;
1997 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
1998 types.push_back(CI->getArgOperand(i)->getType());
1999 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002000 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002001
SJW2c317da2020-03-23 07:39:13 -05002002 auto NewFType = FunctionType::get(
2003 VectorType::get(Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04002004 cast<VectorType>(CI->getType())->getNumElements()),
SJW2c317da2020-03-23 07:39:13 -05002005 types, false);
2006
2007 std::string NewFName = "_Z11read_imagef";
2008 NewFName += F.getName().str().substr(15);
2009
2010 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2011
2012 auto NewCI = CallInst::Create(NewF, args, "", CI);
2013
2014 // Convert to the half type.
2015 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2016 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002017}
2018
SJW2c317da2020-03-23 07:39:13 -05002019bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2020 // convert half to float
2021 Module &M = *F.getParent();
2022 return replaceCallsWithValue(F, [&](CallInst *CI) {
2023 SmallVector<Type *, 3> types(3);
2024 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002025
SJW2c317da2020-03-23 07:39:13 -05002026 // Image
2027 types[0] = CI->getArgOperand(0)->getType();
2028 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002029
SJW2c317da2020-03-23 07:39:13 -05002030 // Coord
2031 types[1] = CI->getArgOperand(1)->getType();
2032 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002033
SJW2c317da2020-03-23 07:39:13 -05002034 // Data
2035 types[2] = VectorType::get(
2036 Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04002037 cast<VectorType>(CI->getArgOperand(2)->getType())->getNumElements());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002038
SJW2c317da2020-03-23 07:39:13 -05002039 auto NewFType =
2040 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002041
SJW2c317da2020-03-23 07:39:13 -05002042 int slen = F.getName().size();
2043 std::string NewFName = "_Z12write_imagef";
2044 NewFName += F.getName().str().substr(16, slen - 16 - 2) + "f";
alan-bakerf7e17cb2020-01-02 07:29:59 -05002045
SJW2c317da2020-03-23 07:39:13 -05002046 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002047
SJW2c317da2020-03-23 07:39:13 -05002048 // Convert data to the float type.
2049 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2050 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002051
SJW2c317da2020-03-23 07:39:13 -05002052 return CallInst::Create(NewF, args, "", CI);
2053 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002054}
2055
SJW2c317da2020-03-23 07:39:13 -05002056bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2057 Function &F) {
2058 // convert read_image with int coords to float coords
2059 Module &M = *F.getParent();
2060 return replaceCallsWithValue(F, [&](CallInst *CI) {
2061 // The image.
2062 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002063
SJW2c317da2020-03-23 07:39:13 -05002064 // The sampler.
2065 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002066
SJW2c317da2020-03-23 07:39:13 -05002067 // The coordinate (integer type that we can't handle).
2068 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002069
SJW2c317da2020-03-23 07:39:13 -05002070 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2071 uint32_t components =
2072 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2073 Type *float_ty = nullptr;
2074 if (components == 1) {
2075 float_ty = Type::getFloatTy(M.getContext());
2076 } else {
James Pricecf53df42020-04-20 14:41:24 -04002077 float_ty =
2078 VectorType::get(Type::getFloatTy(M.getContext()),
2079 cast<VectorType>(Arg2->getType())->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002080 }
David Neto22f144c2017-06-12 14:26:21 -04002081
SJW2c317da2020-03-23 07:39:13 -05002082 auto NewFType = FunctionType::get(
2083 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2084
2085 std::string NewFName = F.getName().str();
2086 NewFName[NewFName.length() - 1] = 'f';
2087
2088 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2089
2090 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2091
2092 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2093 });
David Neto22f144c2017-06-12 14:26:21 -04002094}
2095
SJW2c317da2020-03-23 07:39:13 -05002096bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2097 return replaceCallsWithValue(F, [&](CallInst *CI) {
2098 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002099
SJW2c317da2020-03-23 07:39:13 -05002100 // We need to map the OpenCL constants to the SPIR-V equivalents.
2101 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2102 const auto ConstantMemorySemantics = ConstantInt::get(
2103 IntTy, spv::MemorySemanticsUniformMemoryMask |
2104 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002105
SJW2c317da2020-03-23 07:39:13 -05002106 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002107
SJW2c317da2020-03-23 07:39:13 -05002108 // The pointer.
2109 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002110
SJW2c317da2020-03-23 07:39:13 -05002111 // The memory scope.
2112 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002113
SJW2c317da2020-03-23 07:39:13 -05002114 // The memory semantics.
2115 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002116
SJW2c317da2020-03-23 07:39:13 -05002117 if (2 < CI->getNumArgOperands()) {
2118 // The unequal memory semantics.
2119 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002120
SJW2c317da2020-03-23 07:39:13 -05002121 // The value.
2122 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002123
SJW2c317da2020-03-23 07:39:13 -05002124 // The comparator.
2125 Params.push_back(CI->getArgOperand(1));
2126 } else if (1 < CI->getNumArgOperands()) {
2127 // The value.
2128 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002129 }
David Neto22f144c2017-06-12 14:26:21 -04002130
SJW2c317da2020-03-23 07:39:13 -05002131 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2132 });
David Neto22f144c2017-06-12 14:26:21 -04002133}
2134
SJW2c317da2020-03-23 07:39:13 -05002135bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2136 llvm::AtomicRMWInst::BinOp Op) {
2137 return replaceCallsWithValue(F, [&](CallInst *CI) {
2138 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
2139 AtomicOrdering::SequentiallyConsistent,
2140 SyncScope::System, CI);
2141 });
2142}
David Neto22f144c2017-06-12 14:26:21 -04002143
SJW2c317da2020-03-23 07:39:13 -05002144bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2145 Module &M = *F.getParent();
2146 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002147 auto IntTy = Type::getInt32Ty(M.getContext());
2148 auto FloatTy = Type::getFloatTy(M.getContext());
2149
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002150 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2151 ConstantInt::get(IntTy, 1),
2152 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002153
2154 Constant *UpShuffleMask[4] = {
2155 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2156 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2157
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002158 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2159 UndefValue::get(FloatTy),
2160 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002161
Kévin Petite8edce32019-04-10 14:23:32 +01002162 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002163 auto Arg0 =
2164 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2165 ConstantVector::get(DownShuffleMask), "", CI);
2166 auto Arg1 =
2167 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2168 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002169 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002170
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002171 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
David Neto22f144c2017-06-12 14:26:21 -04002172
Kévin Petite8edce32019-04-10 14:23:32 +01002173 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002174
Kévin Petite8edce32019-04-10 14:23:32 +01002175 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002176
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002177 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2178 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002179 });
David Neto22f144c2017-06-12 14:26:21 -04002180}
David Neto62653202017-10-16 19:05:18 -04002181
SJW2c317da2020-03-23 07:39:13 -05002182bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002183 // OpenCL's float result = fract(float x, float* ptr)
2184 //
2185 // In the LLVM domain:
2186 //
2187 // %floor_result = call spir_func float @floor(float %x)
2188 // store float %floor_result, float * %ptr
2189 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2190 // %result = call spir_func float
2191 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2192 //
2193 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2194 // and clspv.fract occur in the SPIR-V generator pass:
2195 //
2196 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2197 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2198 // ...
2199 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2200 // OpStore %ptr %floor_result
2201 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2202 // %fract_result = OpExtInst %float
2203 // %glsl_ext Fmin %fract_intermediate %just_under_1
2204
David Neto62653202017-10-16 19:05:18 -04002205 using std::string;
2206
2207 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2208 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002209
SJW2c317da2020-03-23 07:39:13 -05002210 Module &M = *F.getParent();
2211 return replaceCallsWithValue(F, [&](CallInst *CI) {
SJW2c317da2020-03-23 07:39:13 -05002212 std::string floor_name = "_Z5floor";
2213 std::string fmin_name = "_Z4fmin";
2214 std::string clspv_fract_name = "clspv.fract.";
2215 if (vec_size) {
2216 floor_name += "Dv" + std::to_string(vec_size) + "_f";
2217 fmin_name += "Dv" + std::to_string(vec_size) + "_f";
2218 clspv_fract_name += "v" + std::to_string(vec_size) + "f";
2219 } else {
2220 floor_name += "ff";
2221 fmin_name += "ff";
2222 clspv_fract_name += "f";
David Neto62653202017-10-16 19:05:18 -04002223 }
David Neto62653202017-10-16 19:05:18 -04002224
SJW2c317da2020-03-23 07:39:13 -05002225 // This is either float or a float vector. All the float-like
2226 // types are this type.
2227 auto result_ty = F.getReturnType();
2228
2229 Function *fmin_fn = M.getFunction(fmin_name);
2230 if (!fmin_fn) {
2231 // Make the fmin function.
2232 FunctionType *fn_ty =
2233 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2234 fmin_fn =
2235 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2236 fmin_fn->addFnAttr(Attribute::ReadNone);
2237 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2238 }
2239
2240 Function *floor_fn = M.getFunction(floor_name);
2241 if (!floor_fn) {
2242 // Make the floor function.
2243 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2244 floor_fn =
2245 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2246 floor_fn->addFnAttr(Attribute::ReadNone);
2247 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2248 }
2249
2250 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2251 if (!clspv_fract_fn) {
2252 // Make the clspv_fract function.
2253 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2254 clspv_fract_fn = cast<Function>(
2255 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2256 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2257 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2258 }
2259
2260 // Number of significant significand bits, whether represented or not.
2261 unsigned num_significand_bits;
2262 switch (result_ty->getScalarType()->getTypeID()) {
2263 case Type::HalfTyID:
2264 num_significand_bits = 11;
2265 break;
2266 case Type::FloatTyID:
2267 num_significand_bits = 24;
2268 break;
2269 case Type::DoubleTyID:
2270 num_significand_bits = 53;
2271 break;
2272 default:
2273 llvm_unreachable("Unhandled float type when processing fract builtin");
2274 break;
2275 }
2276 // Beware that the disassembler displays this value as
2277 // OpConstant %float 1
2278 // which is not quite right.
2279 const double kJustUnderOneScalar =
2280 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2281
2282 Constant *just_under_one =
2283 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2284 if (result_ty->isVectorTy()) {
2285 just_under_one = ConstantVector::getSplat(
James Pricecf53df42020-04-20 14:41:24 -04002286 {cast<VectorType>(result_ty)->getNumElements(), false},
2287 just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002288 }
2289
2290 IRBuilder<> Builder(CI);
2291
2292 auto arg = CI->getArgOperand(0);
2293 auto ptr = CI->getArgOperand(1);
2294
2295 // Compute floor result and store it.
2296 auto floor = Builder.CreateCall(floor_fn, {arg});
2297 Builder.CreateStore(floor, ptr);
2298
2299 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2300 auto fract_result =
2301 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2302
2303 return fract_result;
2304 });
David Neto62653202017-10-16 19:05:18 -04002305}