blob: 7c98cc73aee6299f9f3e2556f0d6b5abd5f3a117 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
David Neto62653202017-10-16 19:05:18 -040015#include <math.h>
16#include <string>
17#include <tuple>
18
Kévin Petit9d1a9d12019-03-25 15:23:46 +000019#include "llvm/ADT/StringSwitch.h"
David Neto118188e2018-08-24 11:27:54 -040020#include "llvm/IR/Constants.h"
David Neto118188e2018-08-24 11:27:54 -040021#include "llvm/IR/IRBuilder.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040022#include "llvm/IR/Instructions.h"
David Neto118188e2018-08-24 11:27:54 -040023#include "llvm/IR/Module.h"
Kévin Petitf5b78a22018-10-25 14:32:17 +000024#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040025#include "llvm/Pass.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040029
David Neto118188e2018-08-24 11:27:54 -040030#include "spirv/1.0/spirv.hpp"
David Neto22f144c2017-06-12 14:26:21 -040031
alan-baker931d18a2019-12-12 08:21:32 -050032#include "clspv/AddressSpace.h"
James Pricec05f6052020-01-14 13:37:20 -050033#include "clspv/DescriptorMap.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040034#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070035
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());
71 if (Ty->isVectorTy()) {
72 IntTy = VectorType::get(IntTy, Ty->getVectorNumElements());
73 }
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);
128 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
129 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
130 bool replaceIsFinite(Function &F);
131 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
132 bool replaceUpsample(Function &F);
133 bool replaceRotate(Function &F);
134 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
135 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
136 bool replaceSelect(Function &F);
137 bool replaceBitSelect(Function &F);
138 bool replaceStep(Function &F, bool is_smooth, int vec_size);
139 bool replaceSignbit(Function &F, bool is_vec);
140 bool replaceMul(Function &F, bool is_float, bool is_mad);
141 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
142 bool replaceVloadHalf(Function &F);
143 bool replaceVloadHalf2(Function &F);
144 bool replaceVloadHalf4(Function &F);
145 bool replaceClspvVloadaHalf2(Function &F);
146 bool replaceClspvVloadaHalf4(Function &F);
147 bool replaceVstoreHalf(Function &F, int vec_size);
148 bool replaceVstoreHalf(Function &F);
149 bool replaceVstoreHalf2(Function &F);
150 bool replaceVstoreHalf4(Function &F);
151 bool replaceHalfReadImage(Function &F);
152 bool replaceHalfWriteImage(Function &F);
153 bool replaceSampledReadImageWithIntCoords(Function &F);
154 bool replaceAtomics(Function &F, spv::Op Op);
155 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
156 bool replaceCross(Function &F);
157 bool replaceFract(Function &F, int vec_size);
158 bool replaceVload(Function &F);
159 bool replaceVstore(Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400160};
SJW2c317da2020-03-23 07:39:13 -0500161
Kévin Petit91bc72e2019-04-08 15:17:46 +0100162} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400163
164char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400165INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
166 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400167
168namespace clspv {
169ModulePass *createReplaceOpenCLBuiltinPass() {
170 return new ReplaceOpenCLBuiltinPass();
171}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400172} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400173
174bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500175 std::list<Function *> func_list;
176 for (auto &F : M.getFunctionList()) {
177 // process only function declarations
178 if (F.isDeclaration() && runOnFunction(F)) {
179 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000180 }
181 }
SJW2c317da2020-03-23 07:39:13 -0500182 if (func_list.size() != 0) {
183 // recursively convert functions, but first remove dead
184 for (auto *F : func_list) {
185 if (F->use_empty()) {
186 F->eraseFromParent();
187 }
188 }
189 runOnModule(M);
190 return true;
191 }
192 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000193}
194
SJW2c317da2020-03-23 07:39:13 -0500195bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
196 auto &FI = Builtins::Lookup(&F);
197 switch (FI.getType()) {
198 case Builtins::kAbs:
199 if (!FI.getParameter(0).is_signed) {
200 return replaceAbs(F);
201 }
202 break;
203 case Builtins::kAbsDiff:
204 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
205 case Builtins::kCopysign:
206 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100207
SJW2c317da2020-03-23 07:39:13 -0500208 case Builtins::kHalfRecip:
209 case Builtins::kNativeRecip:
210 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100211
SJW2c317da2020-03-23 07:39:13 -0500212 case Builtins::kHalfDivide:
213 case Builtins::kNativeDivide:
214 return replaceDivide(F);
215
216 case Builtins::kDot:
217 return replaceDot(F);
218
219 case Builtins::kExp10:
220 case Builtins::kHalfExp10:
221 case Builtins::kNativeExp10: {
222 auto &P0 = FI.getParameter(0);
223 return replaceExp10(F, FI.getName(), P0.vector_size, P0.byte_len);
224 }
225
226 case Builtins::kLog10:
227 case Builtins::kHalfLog10:
228 case Builtins::kNativeLog10: {
229 auto &P0 = FI.getParameter(0);
230 return replaceLog10(F, FI.getName(), P0.vector_size, P0.byte_len);
231 }
232
233 case Builtins::kFmod:
234 return replaceFmod(F);
235
236 case Builtins::kBarrier:
237 case Builtins::kWorkGroupBarrier:
238 return replaceBarrier(F);
239
240 case Builtins::kMemFence:
241 return replaceMemFence(F, spv::MemorySemanticsSequentiallyConsistentMask);
242 case Builtins::kReadMemFence:
243 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
244 case Builtins::kWriteMemFence:
245 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
246
247 // Relational
248 case Builtins::kIsequal:
249 return replaceRelational(F, CmpInst::FCMP_OEQ,
250 FI.getParameter(0).vector_size ? -1 : 1);
251 case Builtins::kIsgreater:
252 return replaceRelational(F, CmpInst::FCMP_OGT,
253 FI.getParameter(0).vector_size ? -1 : 1);
254 case Builtins::kIsgreaterequal:
255 return replaceRelational(F, CmpInst::FCMP_OGE,
256 FI.getParameter(0).vector_size ? -1 : 1);
257 case Builtins::kIsless:
258 return replaceRelational(F, CmpInst::FCMP_OLT,
259 FI.getParameter(0).vector_size ? -1 : 1);
260 case Builtins::kIslessequal:
261 return replaceRelational(F, CmpInst::FCMP_OLE,
262 FI.getParameter(0).vector_size ? -1 : 1);
263 case Builtins::kIsnotequal:
264 return replaceRelational(F, CmpInst::FCMP_ONE,
265 FI.getParameter(0).vector_size ? -1 : 1);
266
267 case Builtins::kIsinf: {
268 bool is_vec = FI.getParameter(0).vector_size != 0;
269 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
270 }
271 case Builtins::kIsnan: {
272 bool is_vec = FI.getParameter(0).vector_size != 0;
273 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
274 }
275
276 case Builtins::kIsfinite:
277 return replaceIsFinite(F);
278
279 case Builtins::kAll: {
280 bool is_vec = FI.getParameter(0).vector_size != 0;
281 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
282 }
283 case Builtins::kAny: {
284 bool is_vec = FI.getParameter(0).vector_size != 0;
285 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
286 }
287
288 case Builtins::kUpsample:
289 return replaceUpsample(F);
290
291 case Builtins::kRotate:
292 return replaceRotate(F);
293
294 case Builtins::kConvert:
295 return replaceConvert(F, FI.getParameter(0).is_signed,
296 FI.getReturnType().is_signed);
297
298 case Builtins::kAtomicInc:
299 return replaceAtomics(F, spv::OpAtomicIIncrement);
300 case Builtins::kAtomicDec:
301 return replaceAtomics(F, spv::OpAtomicIDecrement);
302 case Builtins::kAtomicCmpxchg:
303 return replaceAtomics(F, spv::OpAtomicCompareExchange);
304 case Builtins::kAtomicAdd:
305 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
306 case Builtins::kAtomicSub:
307 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
308 case Builtins::kAtomicXchg:
309 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
310 case Builtins::kAtomicMin:
311 return replaceAtomics(F, FI.getParameter(0).is_signed
312 ? llvm::AtomicRMWInst::Min
313 : llvm::AtomicRMWInst::UMin);
314 case Builtins::kAtomicMax:
315 return replaceAtomics(F, FI.getParameter(0).is_signed
316 ? llvm::AtomicRMWInst::Max
317 : llvm::AtomicRMWInst::UMax);
318 case Builtins::kAtomicAnd:
319 return replaceAtomics(F, llvm::AtomicRMWInst::And);
320 case Builtins::kAtomicOr:
321 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
322 case Builtins::kAtomicXor:
323 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
324
325 case Builtins::kCross:
326 if (FI.getParameter(0).vector_size == 4) {
327 return replaceCross(F);
328 }
329 break;
330
331 case Builtins::kFract:
332 if (FI.getParameterCount()) {
333 return replaceFract(F, FI.getParameter(0).vector_size);
334 }
335 break;
336
337 case Builtins::kMadHi:
338 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
339 case Builtins::kMulHi:
340 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
341
342 case Builtins::kMad:
343 case Builtins::kMad24:
344 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
345 true);
346 case Builtins::kMul24:
347 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
348 false);
349
350 case Builtins::kSelect:
351 return replaceSelect(F);
352
353 case Builtins::kBitselect:
354 return replaceBitSelect(F);
355
356 case Builtins::kVload:
357 return replaceVload(F);
358
359 case Builtins::kVloadaHalf:
360 case Builtins::kVloadHalf:
361 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
362
363 case Builtins::kVstore:
364 return replaceVstore(F);
365
366 case Builtins::kVstoreHalf:
367 case Builtins::kVstoreaHalf:
368 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
369
370 case Builtins::kSmoothstep: {
371 int vec_size = FI.getLastParameter().vector_size;
372 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
373 return replaceStep(F, true, vec_size);
374 }
375 break;
376 }
377 case Builtins::kStep: {
378 int vec_size = FI.getLastParameter().vector_size;
379 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
380 return replaceStep(F, false, vec_size);
381 }
382 break;
383 }
384
385 case Builtins::kSignbit:
386 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
387
388 case Builtins::kReadImageh:
389 return replaceHalfReadImage(F);
390 case Builtins::kReadImagef:
391 case Builtins::kReadImagei:
392 case Builtins::kReadImageui: {
393 if (FI.getParameter(1).isSampler() &&
394 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
395 return replaceSampledReadImageWithIntCoords(F);
396 }
397 break;
398 }
399
400 case Builtins::kWriteImageh:
401 return replaceHalfWriteImage(F);
402
403 default:
404 break;
405 }
406
407 return false;
408}
409
410bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
411 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400412 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100413}
414
SJW2c317da2020-03-23 07:39:13 -0500415bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
416 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100417 auto XValue = CI->getOperand(0);
418 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100419
Kévin Petite8edce32019-04-10 14:23:32 +0100420 IRBuilder<> Builder(CI);
421 auto XmY = Builder.CreateSub(XValue, YValue);
422 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100423
SJW2c317da2020-03-23 07:39:13 -0500424 Value *Cmp = nullptr;
425 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100426 Cmp = Builder.CreateICmpSGT(YValue, XValue);
427 } else {
428 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100429 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100430
Kévin Petite8edce32019-04-10 14:23:32 +0100431 return Builder.CreateSelect(Cmp, YmX, XmY);
432 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100433}
434
SJW2c317da2020-03-23 07:39:13 -0500435bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
436 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100437 auto XValue = CI->getOperand(0);
438 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100439
Kévin Petite8edce32019-04-10 14:23:32 +0100440 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100441
SJW2c317da2020-03-23 07:39:13 -0500442 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
Kévin Petite8edce32019-04-10 14:23:32 +0100443 if (Ty->isVectorTy()) {
444 IntTy = VectorType::get(IntTy, Ty->getVectorNumElements());
Kévin Petit8c1be282019-04-02 19:34:25 +0100445 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100446
Kévin Petite8edce32019-04-10 14:23:32 +0100447 // Return X with the sign of Y
448
449 // Sign bit masks
450 auto SignBit = IntTy->getScalarSizeInBits() - 1;
451 auto SignBitMask = 1 << SignBit;
452 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
453 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
454
455 IRBuilder<> Builder(CI);
456
457 // Extract sign of Y
458 auto YInt = Builder.CreateBitCast(YValue, IntTy);
459 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
460
461 // Clear sign bit in X
462 auto XInt = Builder.CreateBitCast(XValue, IntTy);
463 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
464
465 // Insert sign bit of Y into X
466 auto NewXInt = Builder.CreateOr(XInt, YSign);
467
468 // And cast back to floating-point
469 return Builder.CreateBitCast(NewXInt, Ty);
470 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100471}
472
SJW2c317da2020-03-23 07:39:13 -0500473bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
474 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100475 // Recip has one arg.
476 auto Arg = CI->getOperand(0);
477 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
478 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
479 });
David Neto22f144c2017-06-12 14:26:21 -0400480}
481
SJW2c317da2020-03-23 07:39:13 -0500482bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
483 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100484 auto Op0 = CI->getOperand(0);
485 auto Op1 = CI->getOperand(1);
486 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
487 });
David Neto22f144c2017-06-12 14:26:21 -0400488}
489
SJW2c317da2020-03-23 07:39:13 -0500490bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
491 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100492 auto Op0 = CI->getOperand(0);
493 auto Op1 = CI->getOperand(1);
494
SJW2c317da2020-03-23 07:39:13 -0500495 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100496 if (Op0->getType()->isVectorTy()) {
497 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
498 CI->getType(), {Op0, Op1});
499 } else {
500 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
501 }
502
503 return V;
504 });
505}
506
SJW2c317da2020-03-23 07:39:13 -0500507bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
508 const std::string &basename,
509 int vec_size, int byte_len) {
510 // convert to natural
511 auto slen = basename.length() - 2;
512 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
513 if (vec_size) {
514 NewFName += "Dv" + std::to_string(vec_size) + "_";
515 }
516 switch (byte_len) {
517 case 4:
518 NewFName += "f";
519 break;
520 case 8:
521 NewFName += "d";
522 break;
523 default:
524 llvm_unreachable("Unsupported exp10 byte length");
525 break;
David Neto22f144c2017-06-12 14:26:21 -0400526 }
527
SJW2c317da2020-03-23 07:39:13 -0500528 Module &M = *F.getParent();
529 return replaceCallsWithValue(F, [&](CallInst *CI) {
530 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
531
532 auto Arg = CI->getOperand(0);
533
534 // Constant of the natural log of 10 (ln(10)).
535 const double Ln10 =
536 2.302585092994045684017991454684364207601101488628772976033;
537
538 auto Mul = BinaryOperator::Create(
539 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
540
541 return CallInst::Create(NewF, Mul, "", CI);
542 });
David Neto22f144c2017-06-12 14:26:21 -0400543}
544
SJW2c317da2020-03-23 07:39:13 -0500545bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100546 // OpenCL fmod(x,y) is x - y * trunc(x/y)
547 // The sign for a non-zero result is taken from x.
548 // (Try an example.)
549 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500550 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100551 auto Op0 = CI->getOperand(0);
552 auto Op1 = CI->getOperand(1);
553 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
554 });
555}
556
SJW2c317da2020-03-23 07:39:13 -0500557bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
558 const std::string &basename,
559 int vec_size, int byte_len) {
560 // convert to natural
561 auto slen = basename.length() - 2;
562 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
563 if (vec_size) {
564 NewFName += "Dv" + std::to_string(vec_size) + "_";
565 }
566 switch (byte_len) {
567 case 4:
568 NewFName += "f";
569 break;
570 case 8:
571 NewFName += "d";
572 break;
573 default:
574 llvm_unreachable("Unsupported log10 byte length");
575 break;
David Neto22f144c2017-06-12 14:26:21 -0400576 }
577
SJW2c317da2020-03-23 07:39:13 -0500578 Module &M = *F.getParent();
579 return replaceCallsWithValue(F, [&](CallInst *CI) {
580 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
581
582 auto Arg = CI->getOperand(0);
583
584 // Constant of the reciprocal of the natural log of 10 (ln(10)).
585 const double Ln10 =
586 0.434294481903251827651128918916605082294397005803666566114;
587
588 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
589
590 return BinaryOperator::Create(Instruction::FMul,
591 ConstantFP::get(Arg->getType(), Ln10), NewCI,
592 "", CI);
593 });
David Neto22f144c2017-06-12 14:26:21 -0400594}
595
SJW2c317da2020-03-23 07:39:13 -0500596bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -0400597
598 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
599
SJW2c317da2020-03-23 07:39:13 -0500600 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100601 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400602
Kévin Petitc4643922019-06-17 19:32:05 +0100603 // We need to map the OpenCL constants to the SPIR-V equivalents.
604 const auto LocalMemFence =
605 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
606 const auto GlobalMemFence =
607 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
608 const auto ConstantSequentiallyConsistent = ConstantInt::get(
609 Arg->getType(), spv::MemorySemanticsSequentiallyConsistentMask);
610 const auto ConstantScopeDevice =
611 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
612 const auto ConstantScopeWorkgroup =
613 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400614
Kévin Petitc4643922019-06-17 19:32:05 +0100615 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
616 const auto LocalMemFenceMask =
617 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
618 const auto WorkgroupShiftAmount =
619 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
620 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
621 Instruction::Shl, LocalMemFenceMask,
622 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400623
Kévin Petitc4643922019-06-17 19:32:05 +0100624 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
625 const auto GlobalMemFenceMask =
626 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
627 const auto UniformShiftAmount =
628 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
629 const auto MemorySemanticsUniform = BinaryOperator::Create(
630 Instruction::Shl, GlobalMemFenceMask,
631 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400632
Kévin Petitc4643922019-06-17 19:32:05 +0100633 // And combine the above together, also adding in
634 // MemorySemanticsSequentiallyConsistentMask.
635 auto MemorySemantics =
636 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
637 ConstantSequentiallyConsistent, "", CI);
638 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
639 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400640
Kévin Petitc4643922019-06-17 19:32:05 +0100641 // For Memory Scope if we used CLK_GLOBAL_MEM_FENCE, we need to use
642 // Device Scope, otherwise Workgroup Scope.
643 const auto Cmp =
644 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, GlobalMemFenceMask,
645 GlobalMemFence, "", CI);
646 const auto MemoryScope = SelectInst::Create(Cmp, ConstantScopeDevice,
647 ConstantScopeWorkgroup, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400648
Kévin Petitc4643922019-06-17 19:32:05 +0100649 // Lastly, the Execution Scope is always Workgroup Scope.
650 const auto ExecutionScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400651
Kévin Petitc4643922019-06-17 19:32:05 +0100652 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
653 {Attribute::NoDuplicate}, CI->getType(),
654 {ExecutionScope, MemoryScope, MemorySemantics});
655 });
David Neto22f144c2017-06-12 14:26:21 -0400656}
657
SJW2c317da2020-03-23 07:39:13 -0500658bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
659 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400660
SJW2c317da2020-03-23 07:39:13 -0500661 return replaceCallsWithValue(F, [&](CallInst *CI) {
662 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
David Neto22f144c2017-06-12 14:26:21 -0400663
SJW2c317da2020-03-23 07:39:13 -0500664 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400665
SJW2c317da2020-03-23 07:39:13 -0500666 // We need to map the OpenCL constants to the SPIR-V equivalents.
667 const auto LocalMemFence =
668 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
669 const auto GlobalMemFence =
670 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
671 const auto ConstantMemorySemantics =
672 ConstantInt::get(Arg->getType(), semantics);
673 const auto ConstantScopeDevice =
674 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -0400675
SJW2c317da2020-03-23 07:39:13 -0500676 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
677 const auto LocalMemFenceMask =
678 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
679 const auto WorkgroupShiftAmount =
680 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
681 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
682 Instruction::Shl, LocalMemFenceMask,
683 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400684
SJW2c317da2020-03-23 07:39:13 -0500685 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
686 const auto GlobalMemFenceMask =
687 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
688 const auto UniformShiftAmount =
689 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
690 const auto MemorySemanticsUniform = BinaryOperator::Create(
691 Instruction::Shl, GlobalMemFenceMask,
692 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400693
SJW2c317da2020-03-23 07:39:13 -0500694 // And combine the above together, also adding in
695 // MemorySemanticsSequentiallyConsistentMask.
696 auto MemorySemantics =
697 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
698 ConstantMemorySemantics, "", CI);
699 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
700 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400701
SJW2c317da2020-03-23 07:39:13 -0500702 // Memory Scope is always device.
703 const auto MemoryScope = ConstantScopeDevice;
David Neto22f144c2017-06-12 14:26:21 -0400704
SJW2c317da2020-03-23 07:39:13 -0500705 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier, {}, CI->getType(),
706 {MemoryScope, MemorySemantics});
707 });
David Neto22f144c2017-06-12 14:26:21 -0400708}
709
SJW2c317da2020-03-23 07:39:13 -0500710bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
711 CmpInst::Predicate P,
712 int32_t C) {
713 return replaceCallsWithValue(F, [&](CallInst *CI) {
714 // The predicate to use in the CmpInst.
715 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400716
SJW2c317da2020-03-23 07:39:13 -0500717 // The value to return for true.
718 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400719
SJW2c317da2020-03-23 07:39:13 -0500720 // The value to return for false.
721 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400722
SJW2c317da2020-03-23 07:39:13 -0500723 auto Arg1 = CI->getOperand(0);
724 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400725
SJW2c317da2020-03-23 07:39:13 -0500726 const auto Cmp =
727 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400728
SJW2c317da2020-03-23 07:39:13 -0500729 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
730 });
David Neto22f144c2017-06-12 14:26:21 -0400731}
732
SJW2c317da2020-03-23 07:39:13 -0500733bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
734 spv::Op SPIRVOp,
735 int32_t C) {
736 Module &M = *F.getParent();
737 return replaceCallsWithValue(F, [&](CallInst *CI) {
738 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400739
SJW2c317da2020-03-23 07:39:13 -0500740 // The value to return for true.
741 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400742
SJW2c317da2020-03-23 07:39:13 -0500743 // The value to return for false.
744 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400745
SJW2c317da2020-03-23 07:39:13 -0500746 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
747 if (CITy->isVectorTy()) {
748 CorrespondingBoolTy = VectorType::get(Type::getInt1Ty(M.getContext()),
749 CITy->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -0400750 }
David Neto22f144c2017-06-12 14:26:21 -0400751
SJW2c317da2020-03-23 07:39:13 -0500752 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
753 CorrespondingBoolTy, {CI->getOperand(0)});
754
755 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
756 });
David Neto22f144c2017-06-12 14:26:21 -0400757}
758
SJW2c317da2020-03-23 07:39:13 -0500759bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
760 Module &M = *F.getParent();
761 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100762 auto &C = M.getContext();
763 auto Val = CI->getOperand(0);
764 auto ValTy = Val->getType();
765 auto RetTy = CI->getType();
766
767 // Get a suitable integer type to represent the number
768 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
769
770 // Create Mask
771 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -0500772 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100773 switch (ScalarSize) {
774 case 16:
775 InfMask = ConstantInt::get(IntTy, 0x7C00U);
776 break;
777 case 32:
778 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
779 break;
780 case 64:
781 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
782 break;
783 default:
784 llvm_unreachable("Unsupported floating-point type");
785 }
786
787 IRBuilder<> Builder(CI);
788
789 // Bitcast to int
790 auto ValInt = Builder.CreateBitCast(Val, IntTy);
791
792 // Mask and compare
793 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
794 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
795
796 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -0500797 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100798 if (ValTy->isVectorTy()) {
799 RetTrue = ConstantInt::getSigned(RetTy, -1);
800 } else {
801 RetTrue = ConstantInt::get(RetTy, 1);
802 }
803 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
804 });
805}
806
SJW2c317da2020-03-23 07:39:13 -0500807bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
808 Module &M = *F.getParent();
809 return replaceCallsWithValue(F, [&](CallInst *CI) {
810 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400811
SJW2c317da2020-03-23 07:39:13 -0500812 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +0000813
SJW2c317da2020-03-23 07:39:13 -0500814 // If the argument is a 32-bit int, just use a shift
815 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
816 V = BinaryOperator::Create(Instruction::LShr, Arg,
817 ConstantInt::get(Arg->getType(), 31), "", CI);
818 } else {
819 // The value for zero to compare against.
820 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -0400821
SJW2c317da2020-03-23 07:39:13 -0500822 // The value to return for true.
823 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -0400824
SJW2c317da2020-03-23 07:39:13 -0500825 // The value to return for false.
826 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400827
SJW2c317da2020-03-23 07:39:13 -0500828 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
829 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400830
SJW2c317da2020-03-23 07:39:13 -0500831 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400832
SJW2c317da2020-03-23 07:39:13 -0500833 // If we have a function to call, call it!
834 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -0400835
SJW2c317da2020-03-23 07:39:13 -0500836 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -0400837
SJW2c317da2020-03-23 07:39:13 -0500838 const auto NewCI = clspv::InsertSPIRVOp(
839 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
840 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -0400841
SJW2c317da2020-03-23 07:39:13 -0500842 } else {
843 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -0400844 }
845
SJW2c317da2020-03-23 07:39:13 -0500846 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400847 }
SJW2c317da2020-03-23 07:39:13 -0500848 return V;
849 });
David Neto22f144c2017-06-12 14:26:21 -0400850}
851
SJW2c317da2020-03-23 07:39:13 -0500852bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
853 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
854 // Get arguments
855 auto HiValue = CI->getOperand(0);
856 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000857
SJW2c317da2020-03-23 07:39:13 -0500858 // Don't touch overloads that aren't in OpenCL C
859 auto HiType = HiValue->getType();
860 auto LoType = LoValue->getType();
861
862 if (HiType != LoType) {
863 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000864 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000865
SJW2c317da2020-03-23 07:39:13 -0500866 if (!HiType->isIntOrIntVectorTy()) {
867 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000868 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000869
SJW2c317da2020-03-23 07:39:13 -0500870 if (HiType->getScalarSizeInBits() * 2 !=
871 CI->getType()->getScalarSizeInBits()) {
872 return nullptr;
873 }
874
875 if ((HiType->getScalarSizeInBits() != 8) &&
876 (HiType->getScalarSizeInBits() != 16) &&
877 (HiType->getScalarSizeInBits() != 32)) {
878 return nullptr;
879 }
880
881 if (HiType->isVectorTy()) {
882 if ((HiType->getVectorNumElements() != 2) &&
883 (HiType->getVectorNumElements() != 3) &&
884 (HiType->getVectorNumElements() != 4) &&
885 (HiType->getVectorNumElements() != 8) &&
886 (HiType->getVectorNumElements() != 16)) {
887 return nullptr;
888 }
889 }
890
891 // Convert both operands to the result type
892 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
893 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
894
895 // Shift high operand
896 auto ShiftAmount =
897 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
898 auto HiShifted =
899 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
900
901 // OR both results
902 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
903 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000904}
905
SJW2c317da2020-03-23 07:39:13 -0500906bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
907 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
908 // Get arguments
909 auto SrcValue = CI->getOperand(0);
910 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000911
SJW2c317da2020-03-23 07:39:13 -0500912 // Don't touch overloads that aren't in OpenCL C
913 auto SrcType = SrcValue->getType();
914 auto RotType = RotAmount->getType();
915
916 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
917 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000918 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000919
SJW2c317da2020-03-23 07:39:13 -0500920 if (!SrcType->isIntOrIntVectorTy()) {
921 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000922 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000923
SJW2c317da2020-03-23 07:39:13 -0500924 if ((SrcType->getScalarSizeInBits() != 8) &&
925 (SrcType->getScalarSizeInBits() != 16) &&
926 (SrcType->getScalarSizeInBits() != 32) &&
927 (SrcType->getScalarSizeInBits() != 64)) {
928 return nullptr;
929 }
930
931 if (SrcType->isVectorTy()) {
932 if ((SrcType->getVectorNumElements() != 2) &&
933 (SrcType->getVectorNumElements() != 3) &&
934 (SrcType->getVectorNumElements() != 4) &&
935 (SrcType->getVectorNumElements() != 8) &&
936 (SrcType->getVectorNumElements() != 16)) {
937 return nullptr;
938 }
939 }
940
941 // The approach used is to shift the top bits down, the bottom bits up
942 // and OR the two shifted values.
943
944 // The rotation amount is to be treated modulo the element size.
945 // Since SPIR-V shift ops don't support this, let's apply the
946 // modulo ahead of shifting. The element size is always a power of
947 // two so we can just AND with a mask.
948 auto ModMask =
949 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
950 RotAmount =
951 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
952
953 // Let's calc the amount by which to shift top bits down
954 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
955 auto DownAmount =
956 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
957
958 // Now shift the bottom bits up and the top bits down
959 auto LoRotated =
960 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
961 auto HiRotated =
962 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
963
964 // Finally OR the two shifted values
965 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
966 CI);
967 });
Kévin Petitd44eef52019-03-08 13:22:14 +0000968}
969
SJW2c317da2020-03-23 07:39:13 -0500970bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
971 bool DstIsSigned) {
972 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
973 Value *V = nullptr;
974 // Get arguments
975 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000976
SJW2c317da2020-03-23 07:39:13 -0500977 // Don't touch overloads that aren't in OpenCL C
978 auto SrcType = SrcValue->getType();
979 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000980
SJW2c317da2020-03-23 07:39:13 -0500981 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
982 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
983 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000984 }
985
SJW2c317da2020-03-23 07:39:13 -0500986 if (SrcType->isVectorTy()) {
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000987
SJW2c317da2020-03-23 07:39:13 -0500988 if (SrcType->getVectorNumElements() != DstType->getVectorNumElements()) {
989 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000990 }
991
SJW2c317da2020-03-23 07:39:13 -0500992 if ((SrcType->getVectorNumElements() != 2) &&
993 (SrcType->getVectorNumElements() != 3) &&
994 (SrcType->getVectorNumElements() != 4) &&
995 (SrcType->getVectorNumElements() != 8) &&
996 (SrcType->getVectorNumElements() != 16)) {
997 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000998 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000999 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001000
SJW2c317da2020-03-23 07:39:13 -05001001 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1002 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1003
1004 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1005 bool DstIsInt = DstType->isIntOrIntVectorTy();
1006
1007 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1008 // Unnecessary cast operation.
1009 V = SrcValue;
1010 } else if (SrcIsFloat && DstIsFloat) {
1011 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1012 } else if (SrcIsFloat && DstIsInt) {
1013 if (DstIsSigned) {
1014 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1015 } else {
1016 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1017 }
1018 } else if (SrcIsInt && DstIsFloat) {
1019 if (SrcIsSigned) {
1020 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1021 } else {
1022 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1023 }
1024 } else if (SrcIsInt && DstIsInt) {
1025 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1026 } else {
1027 // Not something we're supposed to handle, just move on
1028 }
1029
1030 return V;
1031 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001032}
1033
SJW2c317da2020-03-23 07:39:13 -05001034bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1035 bool is_mad) {
1036 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1037 Value *V = nullptr;
1038 // Get arguments
1039 auto AValue = CI->getOperand(0);
1040 auto BValue = CI->getOperand(1);
1041 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001042
SJW2c317da2020-03-23 07:39:13 -05001043 // Don't touch overloads that aren't in OpenCL C
1044 auto AType = AValue->getType();
1045 auto BType = BValue->getType();
1046 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001047
SJW2c317da2020-03-23 07:39:13 -05001048 if ((AType != BType) || (CI->getType() != AType) ||
1049 (is_mad && (AType != CType))) {
1050 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001051 }
1052
SJW2c317da2020-03-23 07:39:13 -05001053 if (!AType->isIntOrIntVectorTy()) {
1054 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001055 }
Kévin Petit8a560882019-03-21 15:24:34 +00001056
SJW2c317da2020-03-23 07:39:13 -05001057 if ((AType->getScalarSizeInBits() != 8) &&
1058 (AType->getScalarSizeInBits() != 16) &&
1059 (AType->getScalarSizeInBits() != 32) &&
1060 (AType->getScalarSizeInBits() != 64)) {
1061 return V;
1062 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001063
SJW2c317da2020-03-23 07:39:13 -05001064 if (AType->isVectorTy()) {
1065 if ((AType->getVectorNumElements() != 2) &&
1066 (AType->getVectorNumElements() != 3) &&
1067 (AType->getVectorNumElements() != 4) &&
1068 (AType->getVectorNumElements() != 8) &&
1069 (AType->getVectorNumElements() != 16)) {
1070 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001071 }
1072 }
1073
SJW2c317da2020-03-23 07:39:13 -05001074 // Our SPIR-V op returns a struct, create a type for it
1075 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1076 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001077
SJW2c317da2020-03-23 07:39:13 -05001078 // Select the appropriate signed/unsigned SPIR-V op
1079 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1080
1081 // Call the SPIR-V op
1082 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1083 ExMulRetType, {AValue, BValue});
1084
1085 // Get the high part of the result
1086 unsigned Idxs[] = {1};
1087 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1088
1089 // If we're handling a mad_hi, add the third argument to the result
1090 if (is_mad) {
1091 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001092 }
1093
SJW2c317da2020-03-23 07:39:13 -05001094 return V;
1095 });
Kévin Petit8a560882019-03-21 15:24:34 +00001096}
1097
SJW2c317da2020-03-23 07:39:13 -05001098bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1099 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1100 // Get arguments
1101 auto FalseValue = CI->getOperand(0);
1102 auto TrueValue = CI->getOperand(1);
1103 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001104
SJW2c317da2020-03-23 07:39:13 -05001105 // Don't touch overloads that aren't in OpenCL C
1106 auto FalseType = FalseValue->getType();
1107 auto TrueType = TrueValue->getType();
1108 auto PredicateType = PredicateValue->getType();
1109
1110 if (FalseType != TrueType) {
1111 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001112 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001113
SJW2c317da2020-03-23 07:39:13 -05001114 if (!PredicateType->isIntOrIntVectorTy()) {
1115 return nullptr;
1116 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001117
SJW2c317da2020-03-23 07:39:13 -05001118 if (!FalseType->isIntOrIntVectorTy() &&
1119 !FalseType->getScalarType()->isFloatingPointTy()) {
1120 return nullptr;
1121 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001122
SJW2c317da2020-03-23 07:39:13 -05001123 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1124 return nullptr;
1125 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001126
SJW2c317da2020-03-23 07:39:13 -05001127 if (FalseType->getScalarSizeInBits() !=
1128 PredicateType->getScalarSizeInBits()) {
1129 return nullptr;
1130 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001131
SJW2c317da2020-03-23 07:39:13 -05001132 if (FalseType->isVectorTy()) {
1133 if (FalseType->getVectorNumElements() !=
1134 PredicateType->getVectorNumElements()) {
1135 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001136 }
1137
SJW2c317da2020-03-23 07:39:13 -05001138 if ((FalseType->getVectorNumElements() != 2) &&
1139 (FalseType->getVectorNumElements() != 3) &&
1140 (FalseType->getVectorNumElements() != 4) &&
1141 (FalseType->getVectorNumElements() != 8) &&
1142 (FalseType->getVectorNumElements() != 16)) {
1143 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001144 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001145 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001146
SJW2c317da2020-03-23 07:39:13 -05001147 // Create constant
1148 const auto ZeroValue = Constant::getNullValue(PredicateType);
1149
1150 // Scalar and vector are to be treated differently
1151 CmpInst::Predicate Pred;
1152 if (PredicateType->isVectorTy()) {
1153 Pred = CmpInst::ICMP_SLT;
1154 } else {
1155 Pred = CmpInst::ICMP_NE;
1156 }
1157
1158 // Create comparison instruction
1159 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1160 ZeroValue, "", CI);
1161
1162 // Create select
1163 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1164 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001165}
1166
SJW2c317da2020-03-23 07:39:13 -05001167bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1168 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1169 Value *V = nullptr;
1170 if (CI->getNumOperands() != 4) {
1171 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001172 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001173
SJW2c317da2020-03-23 07:39:13 -05001174 // Get arguments
1175 auto FalseValue = CI->getOperand(0);
1176 auto TrueValue = CI->getOperand(1);
1177 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001178
SJW2c317da2020-03-23 07:39:13 -05001179 // Don't touch overloads that aren't in OpenCL C
1180 auto FalseType = FalseValue->getType();
1181 auto TrueType = TrueValue->getType();
1182 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001183
SJW2c317da2020-03-23 07:39:13 -05001184 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1185 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001186 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001187
SJW2c317da2020-03-23 07:39:13 -05001188 if (TrueType->isVectorTy()) {
1189 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1190 !TrueType->getScalarType()->isIntegerTy()) {
1191 return V;
1192 }
1193 if ((TrueType->getVectorNumElements() != 2) &&
1194 (TrueType->getVectorNumElements() != 3) &&
1195 (TrueType->getVectorNumElements() != 4) &&
1196 (TrueType->getVectorNumElements() != 8) &&
1197 (TrueType->getVectorNumElements() != 16)) {
1198 return V;
1199 }
1200 }
1201
1202 // Remember the type of the operands
1203 auto OpType = TrueType;
1204
1205 // The actual bit selection will always be done on an integer type,
1206 // declare it here
1207 Type *BitType;
1208
1209 // If the operands are float, then bitcast them to int
1210 if (OpType->getScalarType()->isFloatingPointTy()) {
1211
1212 // First create the new type
1213 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1214
1215 // Then bitcast all operands
1216 PredicateValue =
1217 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1218 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1219 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1220
1221 } else {
1222 // The operands have an integer type, use it directly
1223 BitType = OpType;
1224 }
1225
1226 // All the operands are now always integers
1227 // implement as (c & b) | (~c & a)
1228
1229 // Create our negated predicate value
1230 auto AllOnes = Constant::getAllOnesValue(BitType);
1231 auto NotPredicateValue = BinaryOperator::Create(
1232 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1233
1234 // Then put everything together
1235 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1236 FalseValue, "", CI);
1237 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1238 TrueValue, "", CI);
1239
1240 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1241
1242 // If we were dealing with a floating point type, we must bitcast
1243 // the result back to that
1244 if (OpType->getScalarType()->isFloatingPointTy()) {
1245 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1246 }
1247
1248 return V;
1249 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001250}
1251
SJW2c317da2020-03-23 07:39:13 -05001252bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth,
1253 int vec_size) {
1254 // convert to vector versions
1255 Module &M = *F.getParent();
1256 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1257 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1258 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001259
SJW2c317da2020-03-23 07:39:13 -05001260 std::string NewFName = "_Z";
1261 if (is_smooth) {
1262 NewFName += std::to_string(10) + "smoothstepDv" +
1263 std::to_string(vec_size) + "_fS_S_";
1264 } else {
1265 NewFName +=
1266 std::to_string(4) + "stepDv" + std::to_string(vec_size) + "_fS_";
Kévin Petit6b0a9532018-10-30 20:00:39 +00001267 }
Kévin Petit6b0a9532018-10-30 20:00:39 +00001268
SJW2c317da2020-03-23 07:39:13 -05001269 // First figure out which function we're dealing with
1270 if (is_smooth) {
1271 ArgsToSplat.push_back(CI->getOperand(1));
1272 VectorArg = CI->getOperand(2);
1273 } else {
1274 VectorArg = CI->getOperand(1);
1275 }
1276
1277 // Splat arguments that need to be
1278 SmallVector<Value *, 2> SplatArgs;
1279 auto VecType = VectorArg->getType();
1280
1281 for (auto arg : ArgsToSplat) {
1282 Value *NewVectorArg = UndefValue::get(VecType);
1283 for (auto i = 0; i < VecType->getVectorNumElements(); i++) {
1284 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1285 NewVectorArg =
1286 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1287 }
1288 SplatArgs.push_back(NewVectorArg);
1289 }
1290
1291 // Replace the call with the vector/vector flavour
1292 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1293 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1294
1295 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1296
1297 SmallVector<Value *, 3> NewArgs;
1298 for (auto arg : SplatArgs) {
1299 NewArgs.push_back(arg);
1300 }
1301 NewArgs.push_back(VectorArg);
1302
1303 return CallInst::Create(NewF, NewArgs, "", CI);
1304 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001305}
1306
SJW2c317da2020-03-23 07:39:13 -05001307bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
1308 Module &M = *F.getParent();
1309 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1310 auto Arg = CI->getOperand(0);
1311 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001312
SJW2c317da2020-03-23 07:39:13 -05001313 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001314
SJW2c317da2020-03-23 07:39:13 -05001315 return BinaryOperator::Create(Op, Bitcast,
1316 ConstantInt::get(CI->getType(), 31), "", CI);
1317 });
David Neto22f144c2017-06-12 14:26:21 -04001318}
1319
SJW2c317da2020-03-23 07:39:13 -05001320bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1321 bool is_mad) {
1322 Module &M = *F.getParent();
1323 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1324 // The multiply instruction to use.
1325 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001326
SJW2c317da2020-03-23 07:39:13 -05001327 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001328
SJW2c317da2020-03-23 07:39:13 -05001329 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1330 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001331
SJW2c317da2020-03-23 07:39:13 -05001332 if (is_mad) {
1333 // The add instruction to use.
1334 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001335
SJW2c317da2020-03-23 07:39:13 -05001336 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001337 }
David Neto22f144c2017-06-12 14:26:21 -04001338
SJW2c317da2020-03-23 07:39:13 -05001339 return V;
1340 });
David Neto22f144c2017-06-12 14:26:21 -04001341}
1342
SJW2c317da2020-03-23 07:39:13 -05001343bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
1344 Module &M = *F.getParent();
1345 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1346 Value *V = nullptr;
1347 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001348
SJW2c317da2020-03-23 07:39:13 -05001349 auto data_type = data->getType();
1350 if (!data_type->isVectorTy())
1351 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001352
SJW2c317da2020-03-23 07:39:13 -05001353 auto elems = data_type->getVectorNumElements();
1354 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1355 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001356
SJW2c317da2020-03-23 07:39:13 -05001357 auto offset = CI->getOperand(1);
1358 auto ptr = CI->getOperand(2);
1359 auto ptr_type = ptr->getType();
1360 auto pointee_type = ptr_type->getPointerElementType();
1361 if (pointee_type != data_type->getVectorElementType())
1362 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001363
SJW2c317da2020-03-23 07:39:13 -05001364 // Avoid pointer casts. Instead generate the correct number of stores
1365 // and rely on drivers to coalesce appropriately.
1366 IRBuilder<> builder(CI);
1367 auto elems_const = builder.getInt32(elems);
1368 auto adjust = builder.CreateMul(offset, elems_const);
1369 for (auto i = 0; i < elems; ++i) {
1370 auto idx = builder.getInt32(i);
1371 auto add = builder.CreateAdd(adjust, idx);
1372 auto gep = builder.CreateGEP(ptr, add);
1373 auto extract = builder.CreateExtractElement(data, i);
1374 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001375 }
SJW2c317da2020-03-23 07:39:13 -05001376 return V;
1377 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001378}
1379
SJW2c317da2020-03-23 07:39:13 -05001380bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
1381 Module &M = *F.getParent();
1382 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1383 Value *V = nullptr;
1384 auto ret_type = F.getReturnType();
1385 if (!ret_type->isVectorTy())
1386 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001387
SJW2c317da2020-03-23 07:39:13 -05001388 auto elems = ret_type->getVectorNumElements();
1389 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1390 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001391
SJW2c317da2020-03-23 07:39:13 -05001392 auto offset = CI->getOperand(0);
1393 auto ptr = CI->getOperand(1);
1394 auto ptr_type = ptr->getType();
1395 auto pointee_type = ptr_type->getPointerElementType();
1396 if (pointee_type != ret_type->getVectorElementType())
1397 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001398
SJW2c317da2020-03-23 07:39:13 -05001399 // Avoid pointer casts. Instead generate the correct number of loads
1400 // and rely on drivers to coalesce appropriately.
1401 IRBuilder<> builder(CI);
1402 auto elems_const = builder.getInt32(elems);
1403 V = UndefValue::get(ret_type);
1404 auto adjust = builder.CreateMul(offset, elems_const);
1405 for (auto i = 0; i < elems; ++i) {
1406 auto idx = builder.getInt32(i);
1407 auto add = builder.CreateAdd(adjust, idx);
1408 auto gep = builder.CreateGEP(ptr, add);
1409 auto load = builder.CreateLoad(gep);
1410 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001411 }
SJW2c317da2020-03-23 07:39:13 -05001412 return V;
1413 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001414}
1415
SJW2c317da2020-03-23 07:39:13 -05001416bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1417 const std::string &name,
1418 int vec_size) {
1419 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1420 if (!vec_size) {
1421 // deduce vec_size from last character of name (e.g. vload_half4)
1422 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001423 }
SJW2c317da2020-03-23 07:39:13 -05001424 switch (vec_size) {
1425 case 2:
1426 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1427 case 4:
1428 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1429 case 0:
1430 if (!is_clspv_version) {
1431 return replaceVloadHalf(F);
1432 }
1433 default:
1434 llvm_unreachable("Unsupported vload_half vector size");
1435 break;
1436 }
1437 return false;
David Neto22f144c2017-06-12 14:26:21 -04001438}
1439
SJW2c317da2020-03-23 07:39:13 -05001440bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1441 Module &M = *F.getParent();
1442 return replaceCallsWithValue(F, [&](CallInst *CI) {
1443 // The index argument from vload_half.
1444 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001445
SJW2c317da2020-03-23 07:39:13 -05001446 // The pointer argument from vload_half.
1447 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001448
SJW2c317da2020-03-23 07:39:13 -05001449 auto IntTy = Type::getInt32Ty(M.getContext());
1450 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1451 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1452
1453 // Our intrinsic to unpack a float2 from an int.
1454 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1455
1456 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1457
1458 Value *V = nullptr;
1459
1460 if (clspv::Option::F16BitStorage()) {
1461 auto ShortTy = Type::getInt16Ty(M.getContext());
1462 auto ShortPointerTy =
1463 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1464
1465 // Cast the half* pointer to short*.
1466 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1467
1468 // Index into the correct address of the casted pointer.
1469 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1470
1471 // Load from the short* we casted to.
1472 auto Load = new LoadInst(Index, "", CI);
1473
1474 // ZExt the short -> int.
1475 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1476
1477 // Get our float2.
1478 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1479
1480 // Extract out the bottom element which is our float result.
1481 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1482 } else {
1483 // Assume the pointer argument points to storage aligned to 32bits
1484 // or more.
1485 // TODO(dneto): Do more analysis to make sure this is true?
1486 //
1487 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1488 // with:
1489 //
1490 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1491 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1492 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1493 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1494 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1495 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1496 // x float> %converted, %index_is_odd32
1497
1498 auto IntPointerTy =
1499 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1500
1501 // Cast the base pointer to int*.
1502 // In a valid call (according to assumptions), this should get
1503 // optimized away in the simplify GEP pass.
1504 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1505
1506 auto One = ConstantInt::get(IntTy, 1);
1507 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1508 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1509
1510 // Index into the correct address of the casted pointer.
1511 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1512
1513 // Load from the int* we casted to.
1514 auto Load = new LoadInst(Ptr, "", CI);
1515
1516 // Get our float2.
1517 auto Call = CallInst::Create(NewF, Load, "", CI);
1518
1519 // Extract out the float result, where the element number is
1520 // determined by whether the original index was even or odd.
1521 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1522 }
1523 return V;
1524 });
1525}
1526
1527bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1528 Module &M = *F.getParent();
1529 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001530 // The index argument from vload_half.
1531 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001532
Kévin Petite8edce32019-04-10 14:23:32 +01001533 // The pointer argument from vload_half.
1534 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001535
Kévin Petite8edce32019-04-10 14:23:32 +01001536 auto IntTy = Type::getInt32Ty(M.getContext());
1537 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001538 auto NewPointerTy =
1539 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001540 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001541
Kévin Petite8edce32019-04-10 14:23:32 +01001542 // Cast the half* pointer to int*.
1543 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001544
Kévin Petite8edce32019-04-10 14:23:32 +01001545 // Index into the correct address of the casted pointer.
1546 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001547
Kévin Petite8edce32019-04-10 14:23:32 +01001548 // Load from the int* we casted to.
1549 auto Load = new LoadInst(Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001550
Kévin Petite8edce32019-04-10 14:23:32 +01001551 // Our intrinsic to unpack a float2 from an int.
1552 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001553
Kévin Petite8edce32019-04-10 14:23:32 +01001554 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001555
Kévin Petite8edce32019-04-10 14:23:32 +01001556 // Get our float2.
1557 return CallInst::Create(NewF, Load, "", CI);
1558 });
David Neto22f144c2017-06-12 14:26:21 -04001559}
1560
SJW2c317da2020-03-23 07:39:13 -05001561bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(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 Int2Ty = VectorType::get(IntTy, 2);
1572 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001573 auto NewPointerTy =
1574 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001575 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001576
Kévin Petite8edce32019-04-10 14:23:32 +01001577 // Cast the half* pointer to int2*.
1578 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001579
Kévin Petite8edce32019-04-10 14:23:32 +01001580 // Index into the correct address of the casted pointer.
1581 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001582
Kévin Petite8edce32019-04-10 14:23:32 +01001583 // Load from the int2* we casted to.
1584 auto Load = new LoadInst(Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001585
Kévin Petite8edce32019-04-10 14:23:32 +01001586 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001587 auto X =
1588 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1589 auto Y =
1590 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001591
Kévin Petite8edce32019-04-10 14:23:32 +01001592 // Our intrinsic to unpack a float2 from an int.
1593 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001594
Kévin Petite8edce32019-04-10 14:23:32 +01001595 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001596
Kévin Petite8edce32019-04-10 14:23:32 +01001597 // Get the lower (x & y) components of our final float4.
1598 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001599
Kévin Petite8edce32019-04-10 14:23:32 +01001600 // Get the higher (z & w) components of our final float4.
1601 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001602
Kévin Petite8edce32019-04-10 14:23:32 +01001603 Constant *ShuffleMask[4] = {
1604 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1605 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001606
Kévin Petite8edce32019-04-10 14:23:32 +01001607 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001608 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1609 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001610 });
David Neto22f144c2017-06-12 14:26:21 -04001611}
1612
SJW2c317da2020-03-23 07:39:13 -05001613bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001614
1615 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1616 //
1617 // %u = load i32 %ptr
1618 // %fxy = call <2 x float> Unpack2xHalf(u)
1619 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001620 Module &M = *F.getParent();
1621 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001622 auto Index = CI->getOperand(0);
1623 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001624
Kévin Petite8edce32019-04-10 14:23:32 +01001625 auto IntTy = Type::getInt32Ty(M.getContext());
1626 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1627 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001628
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001629 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001630 auto Load = new LoadInst(IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001631
Kévin Petite8edce32019-04-10 14:23:32 +01001632 // Our intrinsic to unpack a float2 from an int.
1633 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001634
Kévin Petite8edce32019-04-10 14:23:32 +01001635 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001636
Kévin Petite8edce32019-04-10 14:23:32 +01001637 // Get our final float2.
1638 return CallInst::Create(NewF, Load, "", CI);
1639 });
David Neto6ad93232018-06-07 15:42:58 -07001640}
1641
SJW2c317da2020-03-23 07:39:13 -05001642bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001643
1644 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1645 //
1646 // %u2 = load <2 x i32> %ptr
1647 // %u2xy = extractelement %u2, 0
1648 // %u2zw = extractelement %u2, 1
1649 // %fxy = call <2 x float> Unpack2xHalf(uint)
1650 // %fzw = call <2 x float> Unpack2xHalf(uint)
1651 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001652 Module &M = *F.getParent();
1653 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001654 auto Index = CI->getOperand(0);
1655 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001656
Kévin Petite8edce32019-04-10 14:23:32 +01001657 auto IntTy = Type::getInt32Ty(M.getContext());
1658 auto Int2Ty = VectorType::get(IntTy, 2);
1659 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1660 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001661
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001662 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001663 auto Load = new LoadInst(IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001664
Kévin Petite8edce32019-04-10 14:23:32 +01001665 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001666 auto X =
1667 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1668 auto Y =
1669 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001670
Kévin Petite8edce32019-04-10 14:23:32 +01001671 // Our intrinsic to unpack a float2 from an int.
1672 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001673
Kévin Petite8edce32019-04-10 14:23:32 +01001674 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001675
Kévin Petite8edce32019-04-10 14:23:32 +01001676 // Get the lower (x & y) components of our final float4.
1677 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001678
Kévin Petite8edce32019-04-10 14:23:32 +01001679 // Get the higher (z & w) components of our final float4.
1680 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001681
Kévin Petite8edce32019-04-10 14:23:32 +01001682 Constant *ShuffleMask[4] = {
1683 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1684 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001685
Kévin Petite8edce32019-04-10 14:23:32 +01001686 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001687 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1688 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001689 });
David Neto6ad93232018-06-07 15:42:58 -07001690}
1691
SJW2c317da2020-03-23 07:39:13 -05001692bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1693 switch (vec_size) {
1694 case 0:
1695 return replaceVstoreHalf(F);
1696 case 2:
1697 return replaceVstoreHalf2(F);
1698 case 4:
1699 return replaceVstoreHalf4(F);
1700 default:
1701 llvm_unreachable("Unsupported vstore_half vector size");
1702 break;
1703 }
1704 return false;
1705}
David Neto22f144c2017-06-12 14:26:21 -04001706
SJW2c317da2020-03-23 07:39:13 -05001707bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1708 Module &M = *F.getParent();
1709 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001710 // The value to store.
1711 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001712
Kévin Petite8edce32019-04-10 14:23:32 +01001713 // The index argument from vstore_half.
1714 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001715
Kévin Petite8edce32019-04-10 14:23:32 +01001716 // The pointer argument from vstore_half.
1717 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001718
Kévin Petite8edce32019-04-10 14:23:32 +01001719 auto IntTy = Type::getInt32Ty(M.getContext());
1720 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1721 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1722 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001723
Kévin Petite8edce32019-04-10 14:23:32 +01001724 // Our intrinsic to pack a float2 to an int.
1725 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001726
Kévin Petite8edce32019-04-10 14:23:32 +01001727 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001728
Kévin Petite8edce32019-04-10 14:23:32 +01001729 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001730 auto TempVec = InsertElementInst::Create(
1731 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001732
Kévin Petite8edce32019-04-10 14:23:32 +01001733 // Pack the float2 -> half2 (in an int).
1734 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001735
SJW2c317da2020-03-23 07:39:13 -05001736 Value *V = nullptr;
Kévin Petite8edce32019-04-10 14:23:32 +01001737 if (clspv::Option::F16BitStorage()) {
1738 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001739 auto ShortPointerTy =
1740 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001741
Kévin Petite8edce32019-04-10 14:23:32 +01001742 // Truncate our i32 to an i16.
1743 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001744
Kévin Petite8edce32019-04-10 14:23:32 +01001745 // Cast the half* pointer to short*.
1746 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001747
Kévin Petite8edce32019-04-10 14:23:32 +01001748 // Index into the correct address of the casted pointer.
1749 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001750
Kévin Petite8edce32019-04-10 14:23:32 +01001751 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001752 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001753 } else {
1754 // We can only write to 32-bit aligned words.
1755 //
1756 // Assuming base is aligned to 32-bits, replace the equivalent of
1757 // vstore_half(value, index, base)
1758 // with:
1759 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1760 // uint32_t write_to_upper_half = index & 1u;
1761 // uint32_t shift = write_to_upper_half << 4;
1762 //
1763 // // Pack the float value as a half number in bottom 16 bits
1764 // // of an i32.
1765 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1766 //
1767 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1768 // ^ ((packed & 0xffff) << shift)
1769 // // We only need relaxed consistency, but OpenCL 1.2 only has
1770 // // sequentially consistent atomics.
1771 // // TODO(dneto): Use relaxed consistency.
1772 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001773 auto IntPointerTy =
1774 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001775
Kévin Petite8edce32019-04-10 14:23:32 +01001776 auto Four = ConstantInt::get(IntTy, 4);
1777 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001778
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001779 auto IndexIsOdd =
1780 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001781 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001782 auto IndexIntoI32 =
1783 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1784 auto BaseI32Ptr =
1785 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1786 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1787 "base_i32_ptr", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001788 auto CurrentValue = new LoadInst(OutPtr, "current_value", CI);
1789 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001790 auto MaskBitsToWrite =
1791 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1792 auto MaskedCurrent = BinaryOperator::CreateAnd(
1793 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001794
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001795 auto XLowerBits =
1796 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1797 auto NewBitsToWrite =
1798 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1799 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1800 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001801
Kévin Petite8edce32019-04-10 14:23:32 +01001802 // Generate the call to atomi_xor.
1803 SmallVector<Type *, 5> ParamTypes;
1804 // The pointer type.
1805 ParamTypes.push_back(IntPointerTy);
1806 // The Types for memory scope, semantics, and value.
1807 ParamTypes.push_back(IntTy);
1808 ParamTypes.push_back(IntTy);
1809 ParamTypes.push_back(IntTy);
1810 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1811 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001812
Kévin Petite8edce32019-04-10 14:23:32 +01001813 const auto ConstantScopeDevice =
1814 ConstantInt::get(IntTy, spv::ScopeDevice);
1815 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1816 // (SPIR-V Workgroup).
1817 const auto AddrSpaceSemanticsBits =
1818 IntPointerTy->getPointerAddressSpace() == 1
1819 ? spv::MemorySemanticsUniformMemoryMask
1820 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001821
Kévin Petite8edce32019-04-10 14:23:32 +01001822 // We're using relaxed consistency here.
1823 const auto ConstantMemorySemantics =
1824 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1825 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001826
Kévin Petite8edce32019-04-10 14:23:32 +01001827 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1828 ConstantMemorySemantics, ValueToXor};
1829 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001830
1831 // Return a Nop so the old Call is removed
1832 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1833 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001834 }
David Neto22f144c2017-06-12 14:26:21 -04001835
SJW2c317da2020-03-23 07:39:13 -05001836 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001837 });
David Neto22f144c2017-06-12 14:26:21 -04001838}
1839
SJW2c317da2020-03-23 07:39:13 -05001840bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1841 Module &M = *F.getParent();
1842 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001843 // The value to store.
1844 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001845
Kévin Petite8edce32019-04-10 14:23:32 +01001846 // The index argument from vstore_half.
1847 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001848
Kévin Petite8edce32019-04-10 14:23:32 +01001849 // The pointer argument from vstore_half.
1850 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001851
Kévin Petite8edce32019-04-10 14:23:32 +01001852 auto IntTy = Type::getInt32Ty(M.getContext());
1853 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001854 auto NewPointerTy =
1855 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001856 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001857
Kévin Petite8edce32019-04-10 14:23:32 +01001858 // Our intrinsic to pack a float2 to an int.
1859 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001860
Kévin Petite8edce32019-04-10 14:23:32 +01001861 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001862
Kévin Petite8edce32019-04-10 14:23:32 +01001863 // Turn the packed x & y into the final packing.
1864 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001865
Kévin Petite8edce32019-04-10 14:23:32 +01001866 // Cast the half* pointer to int*.
1867 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001868
Kévin Petite8edce32019-04-10 14:23:32 +01001869 // Index into the correct address of the casted pointer.
1870 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001871
Kévin Petite8edce32019-04-10 14:23:32 +01001872 // Store to the int* we casted to.
1873 return new StoreInst(X, Index, CI);
1874 });
David Neto22f144c2017-06-12 14:26:21 -04001875}
1876
SJW2c317da2020-03-23 07:39:13 -05001877bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1878 Module &M = *F.getParent();
1879 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001880 // The value to store.
1881 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001882
Kévin Petite8edce32019-04-10 14:23:32 +01001883 // The index argument from vstore_half.
1884 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001885
Kévin Petite8edce32019-04-10 14:23:32 +01001886 // The pointer argument from vstore_half.
1887 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001888
Kévin Petite8edce32019-04-10 14:23:32 +01001889 auto IntTy = Type::getInt32Ty(M.getContext());
1890 auto Int2Ty = VectorType::get(IntTy, 2);
1891 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001892 auto NewPointerTy =
1893 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001894 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001895
Kévin Petite8edce32019-04-10 14:23:32 +01001896 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1897 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04001898
Kévin Petite8edce32019-04-10 14:23:32 +01001899 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001900 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1901 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1904 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001905
Kévin Petite8edce32019-04-10 14:23:32 +01001906 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001907 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1908 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001909
Kévin Petite8edce32019-04-10 14:23:32 +01001910 // Our intrinsic to pack a float2 to an int.
1911 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001912
Kévin Petite8edce32019-04-10 14:23:32 +01001913 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001914
Kévin Petite8edce32019-04-10 14:23:32 +01001915 // Turn the packed x & y into the final component of our int2.
1916 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001917
Kévin Petite8edce32019-04-10 14:23:32 +01001918 // Turn the packed z & w into the final component of our int2.
1919 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001920
Kévin Petite8edce32019-04-10 14:23:32 +01001921 auto Combine = InsertElementInst::Create(
1922 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001923 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
1924 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001925
Kévin Petite8edce32019-04-10 14:23:32 +01001926 // Cast the half* pointer to int2*.
1927 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001928
Kévin Petite8edce32019-04-10 14:23:32 +01001929 // Index into the correct address of the casted pointer.
1930 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001931
Kévin Petite8edce32019-04-10 14:23:32 +01001932 // Store to the int2* we casted to.
1933 return new StoreInst(Combine, Index, CI);
1934 });
David Neto22f144c2017-06-12 14:26:21 -04001935}
1936
SJW2c317da2020-03-23 07:39:13 -05001937bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
1938 // convert half to float
1939 Module &M = *F.getParent();
1940 return replaceCallsWithValue(F, [&](CallInst *CI) {
1941 SmallVector<Type *, 3> types;
1942 SmallVector<Value *, 3> args;
1943 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
1944 types.push_back(CI->getArgOperand(i)->getType());
1945 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05001946 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05001947
SJW2c317da2020-03-23 07:39:13 -05001948 auto NewFType = FunctionType::get(
1949 VectorType::get(Type::getFloatTy(M.getContext()),
1950 CI->getType()->getVectorNumElements()),
1951 types, false);
1952
1953 std::string NewFName = "_Z11read_imagef";
1954 NewFName += F.getName().str().substr(15);
1955
1956 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1957
1958 auto NewCI = CallInst::Create(NewF, args, "", CI);
1959
1960 // Convert to the half type.
1961 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
1962 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05001963}
1964
SJW2c317da2020-03-23 07:39:13 -05001965bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
1966 // convert half to float
1967 Module &M = *F.getParent();
1968 return replaceCallsWithValue(F, [&](CallInst *CI) {
1969 SmallVector<Type *, 3> types(3);
1970 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001971
SJW2c317da2020-03-23 07:39:13 -05001972 // Image
1973 types[0] = CI->getArgOperand(0)->getType();
1974 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001975
SJW2c317da2020-03-23 07:39:13 -05001976 // Coord
1977 types[1] = CI->getArgOperand(1)->getType();
1978 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001979
SJW2c317da2020-03-23 07:39:13 -05001980 // Data
1981 types[2] = VectorType::get(
1982 Type::getFloatTy(M.getContext()),
1983 CI->getArgOperand(2)->getType()->getVectorNumElements());
alan-bakerf7e17cb2020-01-02 07:29:59 -05001984
SJW2c317da2020-03-23 07:39:13 -05001985 auto NewFType =
1986 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001987
SJW2c317da2020-03-23 07:39:13 -05001988 int slen = F.getName().size();
1989 std::string NewFName = "_Z12write_imagef";
1990 NewFName += F.getName().str().substr(16, slen - 16 - 2) + "f";
alan-bakerf7e17cb2020-01-02 07:29:59 -05001991
SJW2c317da2020-03-23 07:39:13 -05001992 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001993
SJW2c317da2020-03-23 07:39:13 -05001994 // Convert data to the float type.
1995 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
1996 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05001997
SJW2c317da2020-03-23 07:39:13 -05001998 return CallInst::Create(NewF, args, "", CI);
1999 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002000}
2001
SJW2c317da2020-03-23 07:39:13 -05002002bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2003 Function &F) {
2004 // convert read_image with int coords to float coords
2005 Module &M = *F.getParent();
2006 return replaceCallsWithValue(F, [&](CallInst *CI) {
2007 // The image.
2008 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002009
SJW2c317da2020-03-23 07:39:13 -05002010 // The sampler.
2011 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002012
SJW2c317da2020-03-23 07:39:13 -05002013 // The coordinate (integer type that we can't handle).
2014 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002015
SJW2c317da2020-03-23 07:39:13 -05002016 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2017 uint32_t components =
2018 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2019 Type *float_ty = nullptr;
2020 if (components == 1) {
2021 float_ty = Type::getFloatTy(M.getContext());
2022 } else {
2023 float_ty = VectorType::get(Type::getFloatTy(M.getContext()),
2024 Arg2->getType()->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002025 }
David Neto22f144c2017-06-12 14:26:21 -04002026
SJW2c317da2020-03-23 07:39:13 -05002027 auto NewFType = FunctionType::get(
2028 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2029
2030 std::string NewFName = F.getName().str();
2031 NewFName[NewFName.length() - 1] = 'f';
2032
2033 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2034
2035 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2036
2037 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2038 });
David Neto22f144c2017-06-12 14:26:21 -04002039}
2040
SJW2c317da2020-03-23 07:39:13 -05002041bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2042 return replaceCallsWithValue(F, [&](CallInst *CI) {
2043 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002044
SJW2c317da2020-03-23 07:39:13 -05002045 // We need to map the OpenCL constants to the SPIR-V equivalents.
2046 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2047 const auto ConstantMemorySemantics = ConstantInt::get(
2048 IntTy, spv::MemorySemanticsUniformMemoryMask |
2049 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002050
SJW2c317da2020-03-23 07:39:13 -05002051 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002052
SJW2c317da2020-03-23 07:39:13 -05002053 // The pointer.
2054 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002055
SJW2c317da2020-03-23 07:39:13 -05002056 // The memory scope.
2057 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002058
SJW2c317da2020-03-23 07:39:13 -05002059 // The memory semantics.
2060 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002061
SJW2c317da2020-03-23 07:39:13 -05002062 if (2 < CI->getNumArgOperands()) {
2063 // The unequal memory semantics.
2064 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002065
SJW2c317da2020-03-23 07:39:13 -05002066 // The value.
2067 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002068
SJW2c317da2020-03-23 07:39:13 -05002069 // The comparator.
2070 Params.push_back(CI->getArgOperand(1));
2071 } else if (1 < CI->getNumArgOperands()) {
2072 // The value.
2073 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002074 }
David Neto22f144c2017-06-12 14:26:21 -04002075
SJW2c317da2020-03-23 07:39:13 -05002076 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2077 });
David Neto22f144c2017-06-12 14:26:21 -04002078}
2079
SJW2c317da2020-03-23 07:39:13 -05002080bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2081 llvm::AtomicRMWInst::BinOp Op) {
2082 return replaceCallsWithValue(F, [&](CallInst *CI) {
2083 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
2084 AtomicOrdering::SequentiallyConsistent,
2085 SyncScope::System, CI);
2086 });
2087}
David Neto22f144c2017-06-12 14:26:21 -04002088
SJW2c317da2020-03-23 07:39:13 -05002089bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2090 Module &M = *F.getParent();
2091 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002092 auto IntTy = Type::getInt32Ty(M.getContext());
2093 auto FloatTy = Type::getFloatTy(M.getContext());
2094
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002095 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2096 ConstantInt::get(IntTy, 1),
2097 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002098
2099 Constant *UpShuffleMask[4] = {
2100 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2101 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2102
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002103 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2104 UndefValue::get(FloatTy),
2105 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002106
Kévin Petite8edce32019-04-10 14:23:32 +01002107 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002108 auto Arg0 =
2109 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2110 ConstantVector::get(DownShuffleMask), "", CI);
2111 auto Arg1 =
2112 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2113 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002114 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002115
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002116 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
David Neto22f144c2017-06-12 14:26:21 -04002117
Kévin Petite8edce32019-04-10 14:23:32 +01002118 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002119
Kévin Petite8edce32019-04-10 14:23:32 +01002120 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002121
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002122 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2123 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002124 });
David Neto22f144c2017-06-12 14:26:21 -04002125}
David Neto62653202017-10-16 19:05:18 -04002126
SJW2c317da2020-03-23 07:39:13 -05002127bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002128 // OpenCL's float result = fract(float x, float* ptr)
2129 //
2130 // In the LLVM domain:
2131 //
2132 // %floor_result = call spir_func float @floor(float %x)
2133 // store float %floor_result, float * %ptr
2134 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2135 // %result = call spir_func float
2136 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2137 //
2138 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2139 // and clspv.fract occur in the SPIR-V generator pass:
2140 //
2141 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2142 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2143 // ...
2144 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2145 // OpStore %ptr %floor_result
2146 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2147 // %fract_result = OpExtInst %float
2148 // %glsl_ext Fmin %fract_intermediate %just_under_1
2149
David Neto62653202017-10-16 19:05:18 -04002150 using std::string;
2151
2152 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2153 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002154
SJW2c317da2020-03-23 07:39:13 -05002155 Module &M = *F.getParent();
2156 return replaceCallsWithValue(F, [&](CallInst *CI) {
2157 auto &Context = M.getContext();
David Neto62653202017-10-16 19:05:18 -04002158
SJW2c317da2020-03-23 07:39:13 -05002159 std::string floor_name = "_Z5floor";
2160 std::string fmin_name = "_Z4fmin";
2161 std::string clspv_fract_name = "clspv.fract.";
2162 if (vec_size) {
2163 floor_name += "Dv" + std::to_string(vec_size) + "_f";
2164 fmin_name += "Dv" + std::to_string(vec_size) + "_f";
2165 clspv_fract_name += "v" + std::to_string(vec_size) + "f";
2166 } else {
2167 floor_name += "ff";
2168 fmin_name += "ff";
2169 clspv_fract_name += "f";
David Neto62653202017-10-16 19:05:18 -04002170 }
David Neto62653202017-10-16 19:05:18 -04002171
SJW2c317da2020-03-23 07:39:13 -05002172 // This is either float or a float vector. All the float-like
2173 // types are this type.
2174 auto result_ty = F.getReturnType();
2175
2176 Function *fmin_fn = M.getFunction(fmin_name);
2177 if (!fmin_fn) {
2178 // Make the fmin function.
2179 FunctionType *fn_ty =
2180 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2181 fmin_fn =
2182 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2183 fmin_fn->addFnAttr(Attribute::ReadNone);
2184 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2185 }
2186
2187 Function *floor_fn = M.getFunction(floor_name);
2188 if (!floor_fn) {
2189 // Make the floor function.
2190 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2191 floor_fn =
2192 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2193 floor_fn->addFnAttr(Attribute::ReadNone);
2194 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2195 }
2196
2197 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2198 if (!clspv_fract_fn) {
2199 // Make the clspv_fract function.
2200 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2201 clspv_fract_fn = cast<Function>(
2202 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2203 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2204 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2205 }
2206
2207 // Number of significant significand bits, whether represented or not.
2208 unsigned num_significand_bits;
2209 switch (result_ty->getScalarType()->getTypeID()) {
2210 case Type::HalfTyID:
2211 num_significand_bits = 11;
2212 break;
2213 case Type::FloatTyID:
2214 num_significand_bits = 24;
2215 break;
2216 case Type::DoubleTyID:
2217 num_significand_bits = 53;
2218 break;
2219 default:
2220 llvm_unreachable("Unhandled float type when processing fract builtin");
2221 break;
2222 }
2223 // Beware that the disassembler displays this value as
2224 // OpConstant %float 1
2225 // which is not quite right.
2226 const double kJustUnderOneScalar =
2227 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2228
2229 Constant *just_under_one =
2230 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2231 if (result_ty->isVectorTy()) {
2232 just_under_one = ConstantVector::getSplat(
2233 {result_ty->getVectorNumElements(), false}, just_under_one);
2234 }
2235
2236 IRBuilder<> Builder(CI);
2237
2238 auto arg = CI->getArgOperand(0);
2239 auto ptr = CI->getArgOperand(1);
2240
2241 // Compute floor result and store it.
2242 auto floor = Builder.CreateCall(floor_fn, {arg});
2243 Builder.CreateStore(floor, ptr);
2244
2245 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2246 auto fract_result =
2247 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2248
2249 return fract_result;
2250 });
David Neto62653202017-10-16 19:05:18 -04002251}