blob: cf3b7b562914f6d5289ff4cf6a24b507afa586a4 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
David Neto62653202017-10-16 19:05:18 -040015#include <math.h>
16#include <string>
17#include <tuple>
18
Kévin Petit9d1a9d12019-03-25 15:23:46 +000019#include "llvm/ADT/StringSwitch.h"
David Neto118188e2018-08-24 11:27:54 -040020#include "llvm/IR/Constants.h"
David Neto118188e2018-08-24 11:27:54 -040021#include "llvm/IR/IRBuilder.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040022#include "llvm/IR/Instructions.h"
David Neto118188e2018-08-24 11:27:54 -040023#include "llvm/IR/Module.h"
Kévin Petitf5b78a22018-10-25 14:32:17 +000024#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040025#include "llvm/Pass.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040029
alan-bakere0902602020-03-23 08:43:40 -040030#include "spirv/unified1/spirv.hpp"
David Neto22f144c2017-06-12 14:26:21 -040031
alan-baker931d18a2019-12-12 08:21:32 -050032#include "clspv/AddressSpace.h"
James Pricec05f6052020-01-14 13:37:20 -050033#include "clspv/DescriptorMap.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040034#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070035
SJW2c317da2020-03-23 07:39:13 -050036#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050037#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040038#include "Passes.h"
39#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050040#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040041
SJW2c317da2020-03-23 07:39:13 -050042using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040043using namespace llvm;
44
45#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
46
47namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000048
David Neto22f144c2017-06-12 14:26:21 -040049uint32_t clz(uint32_t v) {
50 uint32_t r;
51 uint32_t shift;
52
53 r = (v > 0xFFFF) << 4;
54 v >>= r;
55 shift = (v > 0xFF) << 3;
56 v >>= shift;
57 r |= shift;
58 shift = (v > 0xF) << 2;
59 v >>= shift;
60 r |= shift;
61 shift = (v > 0x3) << 1;
62 v >>= shift;
63 r |= shift;
64 r |= (v >> 1);
65
66 return r;
67}
68
Kévin Petitfdfa92e2019-09-25 14:20:58 +010069Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
70 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040071 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
72 IntTy = VectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petitfdfa92e2019-09-25 14:20:58 +010073 }
74 return IntTy;
75}
76
SJW2c317da2020-03-23 07:39:13 -050077bool replaceCallsWithValue(Function &F,
78 std::function<Value *(CallInst *)> Replacer) {
79
80 bool Changed = false;
81
82 SmallVector<Instruction *, 4> ToRemoves;
83
84 // Walk the users of the function.
85 for (auto &U : F.uses()) {
86 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
87
88 auto NewValue = Replacer(CI);
89
90 if (NewValue != nullptr) {
91 CI->replaceAllUsesWith(NewValue);
92
93 // Lastly, remember to remove the user.
94 ToRemoves.push_back(CI);
95 }
96 }
97 }
98
99 Changed = !ToRemoves.empty();
100
101 // And cleanup the calls we don't use anymore.
102 for (auto V : ToRemoves) {
103 V->eraseFromParent();
104 }
105
106 return Changed;
107}
108
David Neto22f144c2017-06-12 14:26:21 -0400109struct ReplaceOpenCLBuiltinPass final : public ModulePass {
110 static char ID;
111 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
112
113 bool runOnModule(Module &M) override;
SJW2c317da2020-03-23 07:39:13 -0500114 bool runOnFunction(Function &F);
115 bool replaceAbs(Function &F);
116 bool replaceAbsDiff(Function &F, bool is_signed);
117 bool replaceCopysign(Function &F);
118 bool replaceRecip(Function &F);
119 bool replaceDivide(Function &F);
120 bool replaceDot(Function &F);
121 bool replaceFmod(Function &F);
122 bool replaceExp10(Function &F, const std::string &basename, int vec_size,
123 int byte_len);
124 bool replaceLog10(Function &F, const std::string &basename, int vec_size,
125 int byte_len);
126 bool replaceBarrier(Function &F);
127 bool replaceMemFence(Function &F, uint32_t semantics);
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());
James Pricecf53df42020-04-20 14:41:24 -0400443 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
444 IntTy = VectorType::get(IntTy, vec_ty->getNumElements());
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());
James Pricecf53df42020-04-20 14:41:24 -0400747 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
SJW2c317da2020-03-23 07:39:13 -0500748 CorrespondingBoolTy = VectorType::get(Type::getInt1Ty(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -0400749 CIVecTy->getNumElements());
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
James Pricecf53df42020-04-20 14:41:24 -0400881 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
882 unsigned NumElements = HiVecType->getNumElements();
883 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
884 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500885 return nullptr;
886 }
887 }
888
889 // Convert both operands to the result type
890 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
891 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
892
893 // Shift high operand
894 auto ShiftAmount =
895 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
896 auto HiShifted =
897 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
898
899 // OR both results
900 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
901 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000902}
903
SJW2c317da2020-03-23 07:39:13 -0500904bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
905 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
906 // Get arguments
907 auto SrcValue = CI->getOperand(0);
908 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000909
SJW2c317da2020-03-23 07:39:13 -0500910 // Don't touch overloads that aren't in OpenCL C
911 auto SrcType = SrcValue->getType();
912 auto RotType = RotAmount->getType();
913
914 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
915 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000916 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000917
SJW2c317da2020-03-23 07:39:13 -0500918 if (!SrcType->isIntOrIntVectorTy()) {
919 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000920 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000921
SJW2c317da2020-03-23 07:39:13 -0500922 if ((SrcType->getScalarSizeInBits() != 8) &&
923 (SrcType->getScalarSizeInBits() != 16) &&
924 (SrcType->getScalarSizeInBits() != 32) &&
925 (SrcType->getScalarSizeInBits() != 64)) {
926 return nullptr;
927 }
928
James Pricecf53df42020-04-20 14:41:24 -0400929 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
930 unsigned NumElements = SrcVecType->getNumElements();
931 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
932 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500933 return nullptr;
934 }
935 }
936
937 // The approach used is to shift the top bits down, the bottom bits up
938 // and OR the two shifted values.
939
940 // The rotation amount is to be treated modulo the element size.
941 // Since SPIR-V shift ops don't support this, let's apply the
942 // modulo ahead of shifting. The element size is always a power of
943 // two so we can just AND with a mask.
944 auto ModMask =
945 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
946 RotAmount =
947 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
948
949 // Let's calc the amount by which to shift top bits down
950 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
951 auto DownAmount =
952 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
953
954 // Now shift the bottom bits up and the top bits down
955 auto LoRotated =
956 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
957 auto HiRotated =
958 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
959
960 // Finally OR the two shifted values
961 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
962 CI);
963 });
Kévin Petitd44eef52019-03-08 13:22:14 +0000964}
965
SJW2c317da2020-03-23 07:39:13 -0500966bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
967 bool DstIsSigned) {
968 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
969 Value *V = nullptr;
970 // Get arguments
971 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000972
SJW2c317da2020-03-23 07:39:13 -0500973 // Don't touch overloads that aren't in OpenCL C
974 auto SrcType = SrcValue->getType();
975 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000976
SJW2c317da2020-03-23 07:39:13 -0500977 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
978 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
979 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000980 }
981
James Pricecf53df42020-04-20 14:41:24 -0400982 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
983 unsigned SrcNumElements = SrcVecType->getNumElements();
984 unsigned DstNumElements = cast<VectorType>(DstType)->getNumElements();
985 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -0500986 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000987 }
988
James Pricecf53df42020-04-20 14:41:24 -0400989 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
990 (SrcNumElements != 4) && (SrcNumElements != 8) &&
991 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500992 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000993 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000994 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000995
SJW2c317da2020-03-23 07:39:13 -0500996 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
997 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
998
999 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1000 bool DstIsInt = DstType->isIntOrIntVectorTy();
1001
1002 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1003 // Unnecessary cast operation.
1004 V = SrcValue;
1005 } else if (SrcIsFloat && DstIsFloat) {
1006 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1007 } else if (SrcIsFloat && DstIsInt) {
1008 if (DstIsSigned) {
1009 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1010 } else {
1011 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1012 }
1013 } else if (SrcIsInt && DstIsFloat) {
1014 if (SrcIsSigned) {
1015 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1016 } else {
1017 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1018 }
1019 } else if (SrcIsInt && DstIsInt) {
1020 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1021 } else {
1022 // Not something we're supposed to handle, just move on
1023 }
1024
1025 return V;
1026 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001027}
1028
SJW2c317da2020-03-23 07:39:13 -05001029bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1030 bool is_mad) {
1031 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1032 Value *V = nullptr;
1033 // Get arguments
1034 auto AValue = CI->getOperand(0);
1035 auto BValue = CI->getOperand(1);
1036 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001037
SJW2c317da2020-03-23 07:39:13 -05001038 // Don't touch overloads that aren't in OpenCL C
1039 auto AType = AValue->getType();
1040 auto BType = BValue->getType();
1041 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001042
SJW2c317da2020-03-23 07:39:13 -05001043 if ((AType != BType) || (CI->getType() != AType) ||
1044 (is_mad && (AType != CType))) {
1045 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001046 }
1047
SJW2c317da2020-03-23 07:39:13 -05001048 if (!AType->isIntOrIntVectorTy()) {
1049 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001050 }
Kévin Petit8a560882019-03-21 15:24:34 +00001051
SJW2c317da2020-03-23 07:39:13 -05001052 if ((AType->getScalarSizeInBits() != 8) &&
1053 (AType->getScalarSizeInBits() != 16) &&
1054 (AType->getScalarSizeInBits() != 32) &&
1055 (AType->getScalarSizeInBits() != 64)) {
1056 return V;
1057 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001058
James Pricecf53df42020-04-20 14:41:24 -04001059 if (auto AVecType = dyn_cast<VectorType>(AType)) {
1060 unsigned NumElements = AVecType->getNumElements();
1061 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1062 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001063 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001064 }
1065 }
1066
SJW2c317da2020-03-23 07:39:13 -05001067 // Our SPIR-V op returns a struct, create a type for it
1068 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1069 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001070
SJW2c317da2020-03-23 07:39:13 -05001071 // Select the appropriate signed/unsigned SPIR-V op
1072 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1073
1074 // Call the SPIR-V op
1075 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1076 ExMulRetType, {AValue, BValue});
1077
1078 // Get the high part of the result
1079 unsigned Idxs[] = {1};
1080 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1081
1082 // If we're handling a mad_hi, add the third argument to the result
1083 if (is_mad) {
1084 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001085 }
1086
SJW2c317da2020-03-23 07:39:13 -05001087 return V;
1088 });
Kévin Petit8a560882019-03-21 15:24:34 +00001089}
1090
SJW2c317da2020-03-23 07:39:13 -05001091bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1092 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1093 // Get arguments
1094 auto FalseValue = CI->getOperand(0);
1095 auto TrueValue = CI->getOperand(1);
1096 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001097
SJW2c317da2020-03-23 07:39:13 -05001098 // Don't touch overloads that aren't in OpenCL C
1099 auto FalseType = FalseValue->getType();
1100 auto TrueType = TrueValue->getType();
1101 auto PredicateType = PredicateValue->getType();
1102
1103 if (FalseType != TrueType) {
1104 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001105 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001106
SJW2c317da2020-03-23 07:39:13 -05001107 if (!PredicateType->isIntOrIntVectorTy()) {
1108 return nullptr;
1109 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001110
SJW2c317da2020-03-23 07:39:13 -05001111 if (!FalseType->isIntOrIntVectorTy() &&
1112 !FalseType->getScalarType()->isFloatingPointTy()) {
1113 return nullptr;
1114 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001115
SJW2c317da2020-03-23 07:39:13 -05001116 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1117 return nullptr;
1118 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001119
SJW2c317da2020-03-23 07:39:13 -05001120 if (FalseType->getScalarSizeInBits() !=
1121 PredicateType->getScalarSizeInBits()) {
1122 return nullptr;
1123 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001124
James Pricecf53df42020-04-20 14:41:24 -04001125 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
1126 unsigned NumElements = FalseVecType->getNumElements();
1127 if (NumElements != cast<VectorType>(PredicateType)->getNumElements()) {
SJW2c317da2020-03-23 07:39:13 -05001128 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001129 }
1130
James Pricecf53df42020-04-20 14:41:24 -04001131 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1132 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001133 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001134 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001135 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001136
SJW2c317da2020-03-23 07:39:13 -05001137 // Create constant
1138 const auto ZeroValue = Constant::getNullValue(PredicateType);
1139
1140 // Scalar and vector are to be treated differently
1141 CmpInst::Predicate Pred;
1142 if (PredicateType->isVectorTy()) {
1143 Pred = CmpInst::ICMP_SLT;
1144 } else {
1145 Pred = CmpInst::ICMP_NE;
1146 }
1147
1148 // Create comparison instruction
1149 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1150 ZeroValue, "", CI);
1151
1152 // Create select
1153 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1154 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001155}
1156
SJW2c317da2020-03-23 07:39:13 -05001157bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1158 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1159 Value *V = nullptr;
1160 if (CI->getNumOperands() != 4) {
1161 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001162 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001163
SJW2c317da2020-03-23 07:39:13 -05001164 // Get arguments
1165 auto FalseValue = CI->getOperand(0);
1166 auto TrueValue = CI->getOperand(1);
1167 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001168
SJW2c317da2020-03-23 07:39:13 -05001169 // Don't touch overloads that aren't in OpenCL C
1170 auto FalseType = FalseValue->getType();
1171 auto TrueType = TrueValue->getType();
1172 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001173
SJW2c317da2020-03-23 07:39:13 -05001174 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1175 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001176 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001177
James Pricecf53df42020-04-20 14:41:24 -04001178 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001179 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1180 !TrueType->getScalarType()->isIntegerTy()) {
1181 return V;
1182 }
James Pricecf53df42020-04-20 14:41:24 -04001183 unsigned NumElements = TrueVecType->getNumElements();
1184 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1185 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001186 return V;
1187 }
1188 }
1189
1190 // Remember the type of the operands
1191 auto OpType = TrueType;
1192
1193 // The actual bit selection will always be done on an integer type,
1194 // declare it here
1195 Type *BitType;
1196
1197 // If the operands are float, then bitcast them to int
1198 if (OpType->getScalarType()->isFloatingPointTy()) {
1199
1200 // First create the new type
1201 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1202
1203 // Then bitcast all operands
1204 PredicateValue =
1205 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1206 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1207 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1208
1209 } else {
1210 // The operands have an integer type, use it directly
1211 BitType = OpType;
1212 }
1213
1214 // All the operands are now always integers
1215 // implement as (c & b) | (~c & a)
1216
1217 // Create our negated predicate value
1218 auto AllOnes = Constant::getAllOnesValue(BitType);
1219 auto NotPredicateValue = BinaryOperator::Create(
1220 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1221
1222 // Then put everything together
1223 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1224 FalseValue, "", CI);
1225 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1226 TrueValue, "", CI);
1227
1228 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1229
1230 // If we were dealing with a floating point type, we must bitcast
1231 // the result back to that
1232 if (OpType->getScalarType()->isFloatingPointTy()) {
1233 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1234 }
1235
1236 return V;
1237 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001238}
1239
SJW2c317da2020-03-23 07:39:13 -05001240bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth,
1241 int vec_size) {
1242 // convert to vector versions
1243 Module &M = *F.getParent();
1244 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1245 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1246 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001247
SJW2c317da2020-03-23 07:39:13 -05001248 std::string NewFName = "_Z";
1249 if (is_smooth) {
1250 NewFName += std::to_string(10) + "smoothstepDv" +
1251 std::to_string(vec_size) + "_fS_S_";
1252 } else {
1253 NewFName +=
1254 std::to_string(4) + "stepDv" + std::to_string(vec_size) + "_fS_";
Kévin Petit6b0a9532018-10-30 20:00:39 +00001255 }
Kévin Petit6b0a9532018-10-30 20:00:39 +00001256
SJW2c317da2020-03-23 07:39:13 -05001257 // First figure out which function we're dealing with
1258 if (is_smooth) {
1259 ArgsToSplat.push_back(CI->getOperand(1));
1260 VectorArg = CI->getOperand(2);
1261 } else {
1262 VectorArg = CI->getOperand(1);
1263 }
1264
1265 // Splat arguments that need to be
1266 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001267 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001268
1269 for (auto arg : ArgsToSplat) {
1270 Value *NewVectorArg = UndefValue::get(VecType);
James Pricecf53df42020-04-20 14:41:24 -04001271 for (auto i = 0; i < VecType->getNumElements(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001272 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1273 NewVectorArg =
1274 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1275 }
1276 SplatArgs.push_back(NewVectorArg);
1277 }
1278
1279 // Replace the call with the vector/vector flavour
1280 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1281 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1282
1283 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1284
1285 SmallVector<Value *, 3> NewArgs;
1286 for (auto arg : SplatArgs) {
1287 NewArgs.push_back(arg);
1288 }
1289 NewArgs.push_back(VectorArg);
1290
1291 return CallInst::Create(NewF, NewArgs, "", CI);
1292 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001293}
1294
SJW2c317da2020-03-23 07:39:13 -05001295bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001296 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1297 auto Arg = CI->getOperand(0);
1298 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001299
SJW2c317da2020-03-23 07:39:13 -05001300 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001301
SJW2c317da2020-03-23 07:39:13 -05001302 return BinaryOperator::Create(Op, Bitcast,
1303 ConstantInt::get(CI->getType(), 31), "", CI);
1304 });
David Neto22f144c2017-06-12 14:26:21 -04001305}
1306
SJW2c317da2020-03-23 07:39:13 -05001307bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1308 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001309 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1310 // The multiply instruction to use.
1311 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001312
SJW2c317da2020-03-23 07:39:13 -05001313 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001314
SJW2c317da2020-03-23 07:39:13 -05001315 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1316 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001317
SJW2c317da2020-03-23 07:39:13 -05001318 if (is_mad) {
1319 // The add instruction to use.
1320 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001321
SJW2c317da2020-03-23 07:39:13 -05001322 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001323 }
David Neto22f144c2017-06-12 14:26:21 -04001324
SJW2c317da2020-03-23 07:39:13 -05001325 return V;
1326 });
David Neto22f144c2017-06-12 14:26:21 -04001327}
1328
SJW2c317da2020-03-23 07:39:13 -05001329bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001330 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1331 Value *V = nullptr;
1332 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001333
SJW2c317da2020-03-23 07:39:13 -05001334 auto data_type = data->getType();
1335 if (!data_type->isVectorTy())
1336 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001337
James Pricecf53df42020-04-20 14:41:24 -04001338 auto vec_data_type = cast<VectorType>(data_type);
1339
1340 auto elems = vec_data_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001341 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1342 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001343
SJW2c317da2020-03-23 07:39:13 -05001344 auto offset = CI->getOperand(1);
1345 auto ptr = CI->getOperand(2);
1346 auto ptr_type = ptr->getType();
1347 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001348 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001349 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001350
SJW2c317da2020-03-23 07:39:13 -05001351 // Avoid pointer casts. Instead generate the correct number of stores
1352 // and rely on drivers to coalesce appropriately.
1353 IRBuilder<> builder(CI);
1354 auto elems_const = builder.getInt32(elems);
1355 auto adjust = builder.CreateMul(offset, elems_const);
1356 for (auto i = 0; i < elems; ++i) {
1357 auto idx = builder.getInt32(i);
1358 auto add = builder.CreateAdd(adjust, idx);
1359 auto gep = builder.CreateGEP(ptr, add);
1360 auto extract = builder.CreateExtractElement(data, i);
1361 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001362 }
SJW2c317da2020-03-23 07:39:13 -05001363 return V;
1364 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001365}
1366
SJW2c317da2020-03-23 07:39:13 -05001367bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001368 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1369 Value *V = nullptr;
1370 auto ret_type = F.getReturnType();
1371 if (!ret_type->isVectorTy())
1372 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001373
James Pricecf53df42020-04-20 14:41:24 -04001374 auto vec_ret_type = cast<VectorType>(ret_type);
1375
1376 auto elems = vec_ret_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001377 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1378 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001379
SJW2c317da2020-03-23 07:39:13 -05001380 auto offset = CI->getOperand(0);
1381 auto ptr = CI->getOperand(1);
1382 auto ptr_type = ptr->getType();
1383 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001384 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001385 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001386
SJW2c317da2020-03-23 07:39:13 -05001387 // Avoid pointer casts. Instead generate the correct number of loads
1388 // and rely on drivers to coalesce appropriately.
1389 IRBuilder<> builder(CI);
1390 auto elems_const = builder.getInt32(elems);
1391 V = UndefValue::get(ret_type);
1392 auto adjust = builder.CreateMul(offset, elems_const);
1393 for (auto i = 0; i < elems; ++i) {
1394 auto idx = builder.getInt32(i);
1395 auto add = builder.CreateAdd(adjust, idx);
1396 auto gep = builder.CreateGEP(ptr, add);
1397 auto load = builder.CreateLoad(gep);
1398 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001399 }
SJW2c317da2020-03-23 07:39:13 -05001400 return V;
1401 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001402}
1403
SJW2c317da2020-03-23 07:39:13 -05001404bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1405 const std::string &name,
1406 int vec_size) {
1407 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1408 if (!vec_size) {
1409 // deduce vec_size from last character of name (e.g. vload_half4)
1410 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001411 }
SJW2c317da2020-03-23 07:39:13 -05001412 switch (vec_size) {
1413 case 2:
1414 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1415 case 4:
1416 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1417 case 0:
1418 if (!is_clspv_version) {
1419 return replaceVloadHalf(F);
1420 }
1421 default:
1422 llvm_unreachable("Unsupported vload_half vector size");
1423 break;
1424 }
1425 return false;
David Neto22f144c2017-06-12 14:26:21 -04001426}
1427
SJW2c317da2020-03-23 07:39:13 -05001428bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1429 Module &M = *F.getParent();
1430 return replaceCallsWithValue(F, [&](CallInst *CI) {
1431 // The index argument from vload_half.
1432 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001433
SJW2c317da2020-03-23 07:39:13 -05001434 // The pointer argument from vload_half.
1435 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001436
SJW2c317da2020-03-23 07:39:13 -05001437 auto IntTy = Type::getInt32Ty(M.getContext());
1438 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1439 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1440
1441 // Our intrinsic to unpack a float2 from an int.
1442 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1443
1444 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1445
1446 Value *V = nullptr;
1447
1448 if (clspv::Option::F16BitStorage()) {
1449 auto ShortTy = Type::getInt16Ty(M.getContext());
1450 auto ShortPointerTy =
1451 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1452
1453 // Cast the half* pointer to short*.
1454 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1455
1456 // Index into the correct address of the casted pointer.
1457 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1458
1459 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001460 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001461
1462 // ZExt the short -> int.
1463 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1464
1465 // Get our float2.
1466 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1467
1468 // Extract out the bottom element which is our float result.
1469 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1470 } else {
1471 // Assume the pointer argument points to storage aligned to 32bits
1472 // or more.
1473 // TODO(dneto): Do more analysis to make sure this is true?
1474 //
1475 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1476 // with:
1477 //
1478 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1479 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1480 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1481 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1482 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1483 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1484 // x float> %converted, %index_is_odd32
1485
1486 auto IntPointerTy =
1487 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1488
1489 // Cast the base pointer to int*.
1490 // In a valid call (according to assumptions), this should get
1491 // optimized away in the simplify GEP pass.
1492 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1493
1494 auto One = ConstantInt::get(IntTy, 1);
1495 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1496 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1497
1498 // Index into the correct address of the casted pointer.
1499 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1500
1501 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001502 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001503
1504 // Get our float2.
1505 auto Call = CallInst::Create(NewF, Load, "", CI);
1506
1507 // Extract out the float result, where the element number is
1508 // determined by whether the original index was even or odd.
1509 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1510 }
1511 return V;
1512 });
1513}
1514
1515bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1516 Module &M = *F.getParent();
1517 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001518 // The index argument from vload_half.
1519 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001520
Kévin Petite8edce32019-04-10 14:23:32 +01001521 // The pointer argument from vload_half.
1522 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001523
Kévin Petite8edce32019-04-10 14:23:32 +01001524 auto IntTy = Type::getInt32Ty(M.getContext());
1525 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001526 auto NewPointerTy =
1527 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001528 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001529
Kévin Petite8edce32019-04-10 14:23:32 +01001530 // Cast the half* pointer to int*.
1531 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001532
Kévin Petite8edce32019-04-10 14:23:32 +01001533 // Index into the correct address of the casted pointer.
1534 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001535
Kévin Petite8edce32019-04-10 14:23:32 +01001536 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001537 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001538
Kévin Petite8edce32019-04-10 14:23:32 +01001539 // Our intrinsic to unpack a float2 from an int.
1540 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001541
Kévin Petite8edce32019-04-10 14:23:32 +01001542 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001543
Kévin Petite8edce32019-04-10 14:23:32 +01001544 // Get our float2.
1545 return CallInst::Create(NewF, Load, "", CI);
1546 });
David Neto22f144c2017-06-12 14:26:21 -04001547}
1548
SJW2c317da2020-03-23 07:39:13 -05001549bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1550 Module &M = *F.getParent();
1551 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001552 // The index argument from vload_half.
1553 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001554
Kévin Petite8edce32019-04-10 14:23:32 +01001555 // The pointer argument from vload_half.
1556 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001557
Kévin Petite8edce32019-04-10 14:23:32 +01001558 auto IntTy = Type::getInt32Ty(M.getContext());
1559 auto Int2Ty = VectorType::get(IntTy, 2);
1560 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001561 auto NewPointerTy =
1562 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001563 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001564
Kévin Petite8edce32019-04-10 14:23:32 +01001565 // Cast the half* pointer to int2*.
1566 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001567
Kévin Petite8edce32019-04-10 14:23:32 +01001568 // Index into the correct address of the casted pointer.
1569 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001570
Kévin Petite8edce32019-04-10 14:23:32 +01001571 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001572 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001573
Kévin Petite8edce32019-04-10 14:23:32 +01001574 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001575 auto X =
1576 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1577 auto Y =
1578 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001579
Kévin Petite8edce32019-04-10 14:23:32 +01001580 // Our intrinsic to unpack a float2 from an int.
1581 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001582
Kévin Petite8edce32019-04-10 14:23:32 +01001583 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001584
Kévin Petite8edce32019-04-10 14:23:32 +01001585 // Get the lower (x & y) components of our final float4.
1586 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001587
Kévin Petite8edce32019-04-10 14:23:32 +01001588 // Get the higher (z & w) components of our final float4.
1589 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001590
Kévin Petite8edce32019-04-10 14:23:32 +01001591 Constant *ShuffleMask[4] = {
1592 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1593 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001594
Kévin Petite8edce32019-04-10 14:23:32 +01001595 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001596 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1597 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001598 });
David Neto22f144c2017-06-12 14:26:21 -04001599}
1600
SJW2c317da2020-03-23 07:39:13 -05001601bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001602
1603 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1604 //
1605 // %u = load i32 %ptr
1606 // %fxy = call <2 x float> Unpack2xHalf(u)
1607 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001608 Module &M = *F.getParent();
1609 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001610 auto Index = CI->getOperand(0);
1611 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001612
Kévin Petite8edce32019-04-10 14:23:32 +01001613 auto IntTy = Type::getInt32Ty(M.getContext());
1614 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1615 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001616
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001617 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001618 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001619
Kévin Petite8edce32019-04-10 14:23:32 +01001620 // Our intrinsic to unpack a float2 from an int.
1621 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001622
Kévin Petite8edce32019-04-10 14:23:32 +01001623 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001624
Kévin Petite8edce32019-04-10 14:23:32 +01001625 // Get our final float2.
1626 return CallInst::Create(NewF, Load, "", CI);
1627 });
David Neto6ad93232018-06-07 15:42:58 -07001628}
1629
SJW2c317da2020-03-23 07:39:13 -05001630bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001631
1632 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1633 //
1634 // %u2 = load <2 x i32> %ptr
1635 // %u2xy = extractelement %u2, 0
1636 // %u2zw = extractelement %u2, 1
1637 // %fxy = call <2 x float> Unpack2xHalf(uint)
1638 // %fzw = call <2 x float> Unpack2xHalf(uint)
1639 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001640 Module &M = *F.getParent();
1641 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001642 auto Index = CI->getOperand(0);
1643 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001644
Kévin Petite8edce32019-04-10 14:23:32 +01001645 auto IntTy = Type::getInt32Ty(M.getContext());
1646 auto Int2Ty = VectorType::get(IntTy, 2);
1647 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1648 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001649
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001650 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001651 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001652
Kévin Petite8edce32019-04-10 14:23:32 +01001653 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001654 auto X =
1655 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1656 auto Y =
1657 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001658
Kévin Petite8edce32019-04-10 14:23:32 +01001659 // Our intrinsic to unpack a float2 from an int.
1660 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001661
Kévin Petite8edce32019-04-10 14:23:32 +01001662 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001663
Kévin Petite8edce32019-04-10 14:23:32 +01001664 // Get the lower (x & y) components of our final float4.
1665 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001666
Kévin Petite8edce32019-04-10 14:23:32 +01001667 // Get the higher (z & w) components of our final float4.
1668 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001669
Kévin Petite8edce32019-04-10 14:23:32 +01001670 Constant *ShuffleMask[4] = {
1671 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1672 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001673
Kévin Petite8edce32019-04-10 14:23:32 +01001674 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001675 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1676 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001677 });
David Neto6ad93232018-06-07 15:42:58 -07001678}
1679
SJW2c317da2020-03-23 07:39:13 -05001680bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1681 switch (vec_size) {
1682 case 0:
1683 return replaceVstoreHalf(F);
1684 case 2:
1685 return replaceVstoreHalf2(F);
1686 case 4:
1687 return replaceVstoreHalf4(F);
1688 default:
1689 llvm_unreachable("Unsupported vstore_half vector size");
1690 break;
1691 }
1692 return false;
1693}
David Neto22f144c2017-06-12 14:26:21 -04001694
SJW2c317da2020-03-23 07:39:13 -05001695bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1696 Module &M = *F.getParent();
1697 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001698 // The value to store.
1699 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001700
Kévin Petite8edce32019-04-10 14:23:32 +01001701 // The index argument from vstore_half.
1702 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001703
Kévin Petite8edce32019-04-10 14:23:32 +01001704 // The pointer argument from vstore_half.
1705 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001706
Kévin Petite8edce32019-04-10 14:23:32 +01001707 auto IntTy = Type::getInt32Ty(M.getContext());
1708 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1709 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1710 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001711
Kévin Petite8edce32019-04-10 14:23:32 +01001712 // Our intrinsic to pack a float2 to an int.
1713 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001714
Kévin Petite8edce32019-04-10 14:23:32 +01001715 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001716
Kévin Petite8edce32019-04-10 14:23:32 +01001717 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001718 auto TempVec = InsertElementInst::Create(
1719 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001720
Kévin Petite8edce32019-04-10 14:23:32 +01001721 // Pack the float2 -> half2 (in an int).
1722 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001723
SJW2c317da2020-03-23 07:39:13 -05001724 Value *V = nullptr;
Kévin Petite8edce32019-04-10 14:23:32 +01001725 if (clspv::Option::F16BitStorage()) {
1726 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001727 auto ShortPointerTy =
1728 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001729
Kévin Petite8edce32019-04-10 14:23:32 +01001730 // Truncate our i32 to an i16.
1731 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001732
Kévin Petite8edce32019-04-10 14:23:32 +01001733 // Cast the half* pointer to short*.
1734 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001735
Kévin Petite8edce32019-04-10 14:23:32 +01001736 // Index into the correct address of the casted pointer.
1737 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001738
Kévin Petite8edce32019-04-10 14:23:32 +01001739 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001740 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001741 } else {
1742 // We can only write to 32-bit aligned words.
1743 //
1744 // Assuming base is aligned to 32-bits, replace the equivalent of
1745 // vstore_half(value, index, base)
1746 // with:
1747 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1748 // uint32_t write_to_upper_half = index & 1u;
1749 // uint32_t shift = write_to_upper_half << 4;
1750 //
1751 // // Pack the float value as a half number in bottom 16 bits
1752 // // of an i32.
1753 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1754 //
1755 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1756 // ^ ((packed & 0xffff) << shift)
1757 // // We only need relaxed consistency, but OpenCL 1.2 only has
1758 // // sequentially consistent atomics.
1759 // // TODO(dneto): Use relaxed consistency.
1760 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001761 auto IntPointerTy =
1762 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001763
Kévin Petite8edce32019-04-10 14:23:32 +01001764 auto Four = ConstantInt::get(IntTy, 4);
1765 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001766
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001767 auto IndexIsOdd =
1768 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001769 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001770 auto IndexIntoI32 =
1771 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1772 auto BaseI32Ptr =
1773 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1774 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1775 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001776 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001777 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001778 auto MaskBitsToWrite =
1779 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1780 auto MaskedCurrent = BinaryOperator::CreateAnd(
1781 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001782
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001783 auto XLowerBits =
1784 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1785 auto NewBitsToWrite =
1786 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1787 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1788 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001789
Kévin Petite8edce32019-04-10 14:23:32 +01001790 // Generate the call to atomi_xor.
1791 SmallVector<Type *, 5> ParamTypes;
1792 // The pointer type.
1793 ParamTypes.push_back(IntPointerTy);
1794 // The Types for memory scope, semantics, and value.
1795 ParamTypes.push_back(IntTy);
1796 ParamTypes.push_back(IntTy);
1797 ParamTypes.push_back(IntTy);
1798 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1799 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001800
Kévin Petite8edce32019-04-10 14:23:32 +01001801 const auto ConstantScopeDevice =
1802 ConstantInt::get(IntTy, spv::ScopeDevice);
1803 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1804 // (SPIR-V Workgroup).
1805 const auto AddrSpaceSemanticsBits =
1806 IntPointerTy->getPointerAddressSpace() == 1
1807 ? spv::MemorySemanticsUniformMemoryMask
1808 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001809
Kévin Petite8edce32019-04-10 14:23:32 +01001810 // We're using relaxed consistency here.
1811 const auto ConstantMemorySemantics =
1812 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1813 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001814
Kévin Petite8edce32019-04-10 14:23:32 +01001815 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1816 ConstantMemorySemantics, ValueToXor};
1817 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001818
1819 // Return a Nop so the old Call is removed
1820 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1821 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001822 }
David Neto22f144c2017-06-12 14:26:21 -04001823
SJW2c317da2020-03-23 07:39:13 -05001824 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001825 });
David Neto22f144c2017-06-12 14:26:21 -04001826}
1827
SJW2c317da2020-03-23 07:39:13 -05001828bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1829 Module &M = *F.getParent();
1830 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001831 // The value to store.
1832 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001833
Kévin Petite8edce32019-04-10 14:23:32 +01001834 // The index argument from vstore_half.
1835 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001836
Kévin Petite8edce32019-04-10 14:23:32 +01001837 // The pointer argument from vstore_half.
1838 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001839
Kévin Petite8edce32019-04-10 14:23:32 +01001840 auto IntTy = Type::getInt32Ty(M.getContext());
1841 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001842 auto NewPointerTy =
1843 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001844 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001845
Kévin Petite8edce32019-04-10 14:23:32 +01001846 // Our intrinsic to pack a float2 to an int.
1847 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001848
Kévin Petite8edce32019-04-10 14:23:32 +01001849 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001850
Kévin Petite8edce32019-04-10 14:23:32 +01001851 // Turn the packed x & y into the final packing.
1852 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001853
Kévin Petite8edce32019-04-10 14:23:32 +01001854 // Cast the half* pointer to int*.
1855 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001856
Kévin Petite8edce32019-04-10 14:23:32 +01001857 // Index into the correct address of the casted pointer.
1858 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001859
Kévin Petite8edce32019-04-10 14:23:32 +01001860 // Store to the int* we casted to.
1861 return new StoreInst(X, Index, CI);
1862 });
David Neto22f144c2017-06-12 14:26:21 -04001863}
1864
SJW2c317da2020-03-23 07:39:13 -05001865bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1866 Module &M = *F.getParent();
1867 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001868 // The value to store.
1869 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001870
Kévin Petite8edce32019-04-10 14:23:32 +01001871 // The index argument from vstore_half.
1872 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001873
Kévin Petite8edce32019-04-10 14:23:32 +01001874 // The pointer argument from vstore_half.
1875 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001876
Kévin Petite8edce32019-04-10 14:23:32 +01001877 auto IntTy = Type::getInt32Ty(M.getContext());
1878 auto Int2Ty = VectorType::get(IntTy, 2);
1879 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001880 auto NewPointerTy =
1881 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001882 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001883
Kévin Petite8edce32019-04-10 14:23:32 +01001884 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1885 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04001886
Kévin Petite8edce32019-04-10 14:23:32 +01001887 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001888 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1889 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001890
Kévin Petite8edce32019-04-10 14:23:32 +01001891 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1892 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001893
Kévin Petite8edce32019-04-10 14:23:32 +01001894 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001895 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1896 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001897
Kévin Petite8edce32019-04-10 14:23:32 +01001898 // Our intrinsic to pack a float2 to an int.
1899 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001900
Kévin Petite8edce32019-04-10 14:23:32 +01001901 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 // Turn the packed x & y into the final component of our int2.
1904 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001905
Kévin Petite8edce32019-04-10 14:23:32 +01001906 // Turn the packed z & w into the final component of our int2.
1907 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001908
Kévin Petite8edce32019-04-10 14:23:32 +01001909 auto Combine = InsertElementInst::Create(
1910 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001911 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
1912 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001913
Kévin Petite8edce32019-04-10 14:23:32 +01001914 // Cast the half* pointer to int2*.
1915 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001916
Kévin Petite8edce32019-04-10 14:23:32 +01001917 // Index into the correct address of the casted pointer.
1918 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001919
Kévin Petite8edce32019-04-10 14:23:32 +01001920 // Store to the int2* we casted to.
1921 return new StoreInst(Combine, Index, CI);
1922 });
David Neto22f144c2017-06-12 14:26:21 -04001923}
1924
SJW2c317da2020-03-23 07:39:13 -05001925bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
1926 // convert half to float
1927 Module &M = *F.getParent();
1928 return replaceCallsWithValue(F, [&](CallInst *CI) {
1929 SmallVector<Type *, 3> types;
1930 SmallVector<Value *, 3> args;
1931 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
1932 types.push_back(CI->getArgOperand(i)->getType());
1933 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05001934 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05001935
SJW2c317da2020-03-23 07:39:13 -05001936 auto NewFType = FunctionType::get(
1937 VectorType::get(Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04001938 cast<VectorType>(CI->getType())->getNumElements()),
SJW2c317da2020-03-23 07:39:13 -05001939 types, false);
1940
1941 std::string NewFName = "_Z11read_imagef";
1942 NewFName += F.getName().str().substr(15);
1943
1944 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1945
1946 auto NewCI = CallInst::Create(NewF, args, "", CI);
1947
1948 // Convert to the half type.
1949 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
1950 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05001951}
1952
SJW2c317da2020-03-23 07:39:13 -05001953bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
1954 // convert half to float
1955 Module &M = *F.getParent();
1956 return replaceCallsWithValue(F, [&](CallInst *CI) {
1957 SmallVector<Type *, 3> types(3);
1958 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001959
SJW2c317da2020-03-23 07:39:13 -05001960 // Image
1961 types[0] = CI->getArgOperand(0)->getType();
1962 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001963
SJW2c317da2020-03-23 07:39:13 -05001964 // Coord
1965 types[1] = CI->getArgOperand(1)->getType();
1966 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001967
SJW2c317da2020-03-23 07:39:13 -05001968 // Data
1969 types[2] = VectorType::get(
1970 Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04001971 cast<VectorType>(CI->getArgOperand(2)->getType())->getNumElements());
alan-bakerf7e17cb2020-01-02 07:29:59 -05001972
SJW2c317da2020-03-23 07:39:13 -05001973 auto NewFType =
1974 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001975
SJW2c317da2020-03-23 07:39:13 -05001976 int slen = F.getName().size();
1977 std::string NewFName = "_Z12write_imagef";
1978 NewFName += F.getName().str().substr(16, slen - 16 - 2) + "f";
alan-bakerf7e17cb2020-01-02 07:29:59 -05001979
SJW2c317da2020-03-23 07:39:13 -05001980 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001981
SJW2c317da2020-03-23 07:39:13 -05001982 // Convert data to the float type.
1983 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
1984 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05001985
SJW2c317da2020-03-23 07:39:13 -05001986 return CallInst::Create(NewF, args, "", CI);
1987 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05001988}
1989
SJW2c317da2020-03-23 07:39:13 -05001990bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
1991 Function &F) {
1992 // convert read_image with int coords to float coords
1993 Module &M = *F.getParent();
1994 return replaceCallsWithValue(F, [&](CallInst *CI) {
1995 // The image.
1996 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001997
SJW2c317da2020-03-23 07:39:13 -05001998 // The sampler.
1999 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002000
SJW2c317da2020-03-23 07:39:13 -05002001 // The coordinate (integer type that we can't handle).
2002 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002003
SJW2c317da2020-03-23 07:39:13 -05002004 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2005 uint32_t components =
2006 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2007 Type *float_ty = nullptr;
2008 if (components == 1) {
2009 float_ty = Type::getFloatTy(M.getContext());
2010 } else {
James Pricecf53df42020-04-20 14:41:24 -04002011 float_ty =
2012 VectorType::get(Type::getFloatTy(M.getContext()),
2013 cast<VectorType>(Arg2->getType())->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002014 }
David Neto22f144c2017-06-12 14:26:21 -04002015
SJW2c317da2020-03-23 07:39:13 -05002016 auto NewFType = FunctionType::get(
2017 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2018
2019 std::string NewFName = F.getName().str();
2020 NewFName[NewFName.length() - 1] = 'f';
2021
2022 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2023
2024 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2025
2026 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2027 });
David Neto22f144c2017-06-12 14:26:21 -04002028}
2029
SJW2c317da2020-03-23 07:39:13 -05002030bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2031 return replaceCallsWithValue(F, [&](CallInst *CI) {
2032 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002033
SJW2c317da2020-03-23 07:39:13 -05002034 // We need to map the OpenCL constants to the SPIR-V equivalents.
2035 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2036 const auto ConstantMemorySemantics = ConstantInt::get(
2037 IntTy, spv::MemorySemanticsUniformMemoryMask |
2038 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002039
SJW2c317da2020-03-23 07:39:13 -05002040 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002041
SJW2c317da2020-03-23 07:39:13 -05002042 // The pointer.
2043 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002044
SJW2c317da2020-03-23 07:39:13 -05002045 // The memory scope.
2046 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002047
SJW2c317da2020-03-23 07:39:13 -05002048 // The memory semantics.
2049 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002050
SJW2c317da2020-03-23 07:39:13 -05002051 if (2 < CI->getNumArgOperands()) {
2052 // The unequal memory semantics.
2053 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002054
SJW2c317da2020-03-23 07:39:13 -05002055 // The value.
2056 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002057
SJW2c317da2020-03-23 07:39:13 -05002058 // The comparator.
2059 Params.push_back(CI->getArgOperand(1));
2060 } else if (1 < CI->getNumArgOperands()) {
2061 // The value.
2062 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002063 }
David Neto22f144c2017-06-12 14:26:21 -04002064
SJW2c317da2020-03-23 07:39:13 -05002065 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2066 });
David Neto22f144c2017-06-12 14:26:21 -04002067}
2068
SJW2c317da2020-03-23 07:39:13 -05002069bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2070 llvm::AtomicRMWInst::BinOp Op) {
2071 return replaceCallsWithValue(F, [&](CallInst *CI) {
2072 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
2073 AtomicOrdering::SequentiallyConsistent,
2074 SyncScope::System, CI);
2075 });
2076}
David Neto22f144c2017-06-12 14:26:21 -04002077
SJW2c317da2020-03-23 07:39:13 -05002078bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2079 Module &M = *F.getParent();
2080 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002081 auto IntTy = Type::getInt32Ty(M.getContext());
2082 auto FloatTy = Type::getFloatTy(M.getContext());
2083
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002084 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2085 ConstantInt::get(IntTy, 1),
2086 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002087
2088 Constant *UpShuffleMask[4] = {
2089 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2090 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2091
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002092 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2093 UndefValue::get(FloatTy),
2094 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002095
Kévin Petite8edce32019-04-10 14:23:32 +01002096 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002097 auto Arg0 =
2098 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2099 ConstantVector::get(DownShuffleMask), "", CI);
2100 auto Arg1 =
2101 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2102 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002103 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002104
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002105 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
David Neto22f144c2017-06-12 14:26:21 -04002106
Kévin Petite8edce32019-04-10 14:23:32 +01002107 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002108
Kévin Petite8edce32019-04-10 14:23:32 +01002109 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002110
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002111 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2112 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002113 });
David Neto22f144c2017-06-12 14:26:21 -04002114}
David Neto62653202017-10-16 19:05:18 -04002115
SJW2c317da2020-03-23 07:39:13 -05002116bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002117 // OpenCL's float result = fract(float x, float* ptr)
2118 //
2119 // In the LLVM domain:
2120 //
2121 // %floor_result = call spir_func float @floor(float %x)
2122 // store float %floor_result, float * %ptr
2123 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2124 // %result = call spir_func float
2125 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2126 //
2127 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2128 // and clspv.fract occur in the SPIR-V generator pass:
2129 //
2130 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2131 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2132 // ...
2133 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2134 // OpStore %ptr %floor_result
2135 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2136 // %fract_result = OpExtInst %float
2137 // %glsl_ext Fmin %fract_intermediate %just_under_1
2138
David Neto62653202017-10-16 19:05:18 -04002139 using std::string;
2140
2141 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2142 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002143
SJW2c317da2020-03-23 07:39:13 -05002144 Module &M = *F.getParent();
2145 return replaceCallsWithValue(F, [&](CallInst *CI) {
SJW2c317da2020-03-23 07:39:13 -05002146 std::string floor_name = "_Z5floor";
2147 std::string fmin_name = "_Z4fmin";
2148 std::string clspv_fract_name = "clspv.fract.";
2149 if (vec_size) {
2150 floor_name += "Dv" + std::to_string(vec_size) + "_f";
2151 fmin_name += "Dv" + std::to_string(vec_size) + "_f";
2152 clspv_fract_name += "v" + std::to_string(vec_size) + "f";
2153 } else {
2154 floor_name += "ff";
2155 fmin_name += "ff";
2156 clspv_fract_name += "f";
David Neto62653202017-10-16 19:05:18 -04002157 }
David Neto62653202017-10-16 19:05:18 -04002158
SJW2c317da2020-03-23 07:39:13 -05002159 // This is either float or a float vector. All the float-like
2160 // types are this type.
2161 auto result_ty = F.getReturnType();
2162
2163 Function *fmin_fn = M.getFunction(fmin_name);
2164 if (!fmin_fn) {
2165 // Make the fmin function.
2166 FunctionType *fn_ty =
2167 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2168 fmin_fn =
2169 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2170 fmin_fn->addFnAttr(Attribute::ReadNone);
2171 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2172 }
2173
2174 Function *floor_fn = M.getFunction(floor_name);
2175 if (!floor_fn) {
2176 // Make the floor function.
2177 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2178 floor_fn =
2179 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2180 floor_fn->addFnAttr(Attribute::ReadNone);
2181 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2182 }
2183
2184 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2185 if (!clspv_fract_fn) {
2186 // Make the clspv_fract function.
2187 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2188 clspv_fract_fn = cast<Function>(
2189 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2190 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2191 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2192 }
2193
2194 // Number of significant significand bits, whether represented or not.
2195 unsigned num_significand_bits;
2196 switch (result_ty->getScalarType()->getTypeID()) {
2197 case Type::HalfTyID:
2198 num_significand_bits = 11;
2199 break;
2200 case Type::FloatTyID:
2201 num_significand_bits = 24;
2202 break;
2203 case Type::DoubleTyID:
2204 num_significand_bits = 53;
2205 break;
2206 default:
2207 llvm_unreachable("Unhandled float type when processing fract builtin");
2208 break;
2209 }
2210 // Beware that the disassembler displays this value as
2211 // OpConstant %float 1
2212 // which is not quite right.
2213 const double kJustUnderOneScalar =
2214 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2215
2216 Constant *just_under_one =
2217 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2218 if (result_ty->isVectorTy()) {
2219 just_under_one = ConstantVector::getSplat(
James Pricecf53df42020-04-20 14:41:24 -04002220 {cast<VectorType>(result_ty)->getNumElements(), false},
2221 just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002222 }
2223
2224 IRBuilder<> Builder(CI);
2225
2226 auto arg = CI->getArgOperand(0);
2227 auto ptr = CI->getArgOperand(1);
2228
2229 // Compute floor result and store it.
2230 auto floor = Builder.CreateCall(floor_fn, {arg});
2231 Builder.CreateStore(floor, ptr);
2232
2233 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2234 auto fract_result =
2235 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2236
2237 return fract_result;
2238 });
David Neto62653202017-10-16 19:05:18 -04002239}