blob: fe83aa034f36ec938fbaf5a0d1ab32aa004858d3 [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"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040033#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070034
SJW2c317da2020-03-23 07:39:13 -050035#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050036#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040037#include "Passes.h"
38#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050039#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040040
SJW2c317da2020-03-23 07:39:13 -050041using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040042using namespace llvm;
43
44#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
45
46namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000047
David Neto22f144c2017-06-12 14:26:21 -040048uint32_t clz(uint32_t v) {
49 uint32_t r;
50 uint32_t shift;
51
52 r = (v > 0xFFFF) << 4;
53 v >>= r;
54 shift = (v > 0xFF) << 3;
55 v >>= shift;
56 r |= shift;
57 shift = (v > 0xF) << 2;
58 v >>= shift;
59 r |= shift;
60 shift = (v > 0x3) << 1;
61 v >>= shift;
62 r |= shift;
63 r |= (v >> 1);
64
65 return r;
66}
67
Kévin Petitfdfa92e2019-09-25 14:20:58 +010068Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
69 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040070 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -040071 IntTy = FixedVectorType::get(IntTy,
72 vec_ty->getElementCount().getKnownMinValue());
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);
SJW61531372020-06-09 07:31:08 -0500122 bool replaceExp10(Function &F, const std::string &basename);
123 bool replaceLog10(Function &F, const std::string &basename);
gnl21636e7992020-09-09 16:08:16 +0100124 bool replaceLog1p(Function &F);
alan-baker12d2c182020-07-20 08:22:42 -0400125 bool replaceBarrier(Function &F, bool subgroup = false);
SJW2c317da2020-03-23 07:39:13 -0500126 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100127 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500128 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);
SJW61531372020-06-09 07:31:08 -0500138 bool replaceStep(Function &F, bool is_smooth);
SJW2c317da2020-03-23 07:39:13 -0500139 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:
SJW61531372020-06-09 07:31:08 -0500221 case Builtins::kNativeExp10:
222 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500223
224 case Builtins::kLog10:
225 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500226 case Builtins::kNativeLog10:
227 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500228
gnl21636e7992020-09-09 16:08:16 +0100229 case Builtins::kLog1p:
230 return replaceLog1p(F);
231
SJW2c317da2020-03-23 07:39:13 -0500232 case Builtins::kFmod:
233 return replaceFmod(F);
234
235 case Builtins::kBarrier:
236 case Builtins::kWorkGroupBarrier:
237 return replaceBarrier(F);
238
alan-baker12d2c182020-07-20 08:22:42 -0400239 case Builtins::kSubGroupBarrier:
240 return replaceBarrier(F, true);
241
SJW2c317da2020-03-23 07:39:13 -0500242 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400243 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500244 case Builtins::kReadMemFence:
245 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
246 case Builtins::kWriteMemFence:
247 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
248
249 // Relational
250 case Builtins::kIsequal:
251 return replaceRelational(F, CmpInst::FCMP_OEQ,
252 FI.getParameter(0).vector_size ? -1 : 1);
253 case Builtins::kIsgreater:
254 return replaceRelational(F, CmpInst::FCMP_OGT,
255 FI.getParameter(0).vector_size ? -1 : 1);
256 case Builtins::kIsgreaterequal:
257 return replaceRelational(F, CmpInst::FCMP_OGE,
258 FI.getParameter(0).vector_size ? -1 : 1);
259 case Builtins::kIsless:
260 return replaceRelational(F, CmpInst::FCMP_OLT,
261 FI.getParameter(0).vector_size ? -1 : 1);
262 case Builtins::kIslessequal:
263 return replaceRelational(F, CmpInst::FCMP_OLE,
264 FI.getParameter(0).vector_size ? -1 : 1);
265 case Builtins::kIsnotequal:
266 return replaceRelational(F, CmpInst::FCMP_ONE,
267 FI.getParameter(0).vector_size ? -1 : 1);
268
269 case Builtins::kIsinf: {
270 bool is_vec = FI.getParameter(0).vector_size != 0;
271 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
272 }
273 case Builtins::kIsnan: {
274 bool is_vec = FI.getParameter(0).vector_size != 0;
275 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
276 }
277
278 case Builtins::kIsfinite:
279 return replaceIsFinite(F);
280
281 case Builtins::kAll: {
282 bool is_vec = FI.getParameter(0).vector_size != 0;
283 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
284 }
285 case Builtins::kAny: {
286 bool is_vec = FI.getParameter(0).vector_size != 0;
287 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
288 }
289
290 case Builtins::kUpsample:
291 return replaceUpsample(F);
292
293 case Builtins::kRotate:
294 return replaceRotate(F);
295
296 case Builtins::kConvert:
297 return replaceConvert(F, FI.getParameter(0).is_signed,
298 FI.getReturnType().is_signed);
299
300 case Builtins::kAtomicInc:
301 return replaceAtomics(F, spv::OpAtomicIIncrement);
302 case Builtins::kAtomicDec:
303 return replaceAtomics(F, spv::OpAtomicIDecrement);
304 case Builtins::kAtomicCmpxchg:
305 return replaceAtomics(F, spv::OpAtomicCompareExchange);
306 case Builtins::kAtomicAdd:
307 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
308 case Builtins::kAtomicSub:
309 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
310 case Builtins::kAtomicXchg:
311 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
312 case Builtins::kAtomicMin:
313 return replaceAtomics(F, FI.getParameter(0).is_signed
314 ? llvm::AtomicRMWInst::Min
315 : llvm::AtomicRMWInst::UMin);
316 case Builtins::kAtomicMax:
317 return replaceAtomics(F, FI.getParameter(0).is_signed
318 ? llvm::AtomicRMWInst::Max
319 : llvm::AtomicRMWInst::UMax);
320 case Builtins::kAtomicAnd:
321 return replaceAtomics(F, llvm::AtomicRMWInst::And);
322 case Builtins::kAtomicOr:
323 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
324 case Builtins::kAtomicXor:
325 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
326
327 case Builtins::kCross:
328 if (FI.getParameter(0).vector_size == 4) {
329 return replaceCross(F);
330 }
331 break;
332
333 case Builtins::kFract:
334 if (FI.getParameterCount()) {
335 return replaceFract(F, FI.getParameter(0).vector_size);
336 }
337 break;
338
339 case Builtins::kMadHi:
340 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
341 case Builtins::kMulHi:
342 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
343
344 case Builtins::kMad:
345 case Builtins::kMad24:
346 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
347 true);
348 case Builtins::kMul24:
349 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
350 false);
351
352 case Builtins::kSelect:
353 return replaceSelect(F);
354
355 case Builtins::kBitselect:
356 return replaceBitSelect(F);
357
358 case Builtins::kVload:
359 return replaceVload(F);
360
361 case Builtins::kVloadaHalf:
362 case Builtins::kVloadHalf:
363 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
364
365 case Builtins::kVstore:
366 return replaceVstore(F);
367
368 case Builtins::kVstoreHalf:
369 case Builtins::kVstoreaHalf:
370 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
371
372 case Builtins::kSmoothstep: {
373 int vec_size = FI.getLastParameter().vector_size;
374 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500375 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500376 }
377 break;
378 }
379 case Builtins::kStep: {
380 int vec_size = FI.getLastParameter().vector_size;
381 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500382 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500383 }
384 break;
385 }
386
387 case Builtins::kSignbit:
388 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
389
390 case Builtins::kReadImageh:
391 return replaceHalfReadImage(F);
392 case Builtins::kReadImagef:
393 case Builtins::kReadImagei:
394 case Builtins::kReadImageui: {
395 if (FI.getParameter(1).isSampler() &&
396 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
397 return replaceSampledReadImageWithIntCoords(F);
398 }
399 break;
400 }
401
402 case Builtins::kWriteImageh:
403 return replaceHalfWriteImage(F);
404
Kévin Petit1cb45112020-04-27 18:55:48 +0100405 case Builtins::kPrefetch:
406 return replacePrefetch(F);
407
SJW2c317da2020-03-23 07:39:13 -0500408 default:
409 break;
410 }
411
412 return false;
413}
414
415bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
416 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400417 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100418}
419
SJW2c317da2020-03-23 07:39:13 -0500420bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
421 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100422 auto XValue = CI->getOperand(0);
423 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100424
Kévin Petite8edce32019-04-10 14:23:32 +0100425 IRBuilder<> Builder(CI);
426 auto XmY = Builder.CreateSub(XValue, YValue);
427 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100428
SJW2c317da2020-03-23 07:39:13 -0500429 Value *Cmp = nullptr;
430 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100431 Cmp = Builder.CreateICmpSGT(YValue, XValue);
432 } else {
433 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100434 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100435
Kévin Petite8edce32019-04-10 14:23:32 +0100436 return Builder.CreateSelect(Cmp, YmX, XmY);
437 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100438}
439
SJW2c317da2020-03-23 07:39:13 -0500440bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
441 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100442 auto XValue = CI->getOperand(0);
443 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100444
Kévin Petite8edce32019-04-10 14:23:32 +0100445 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100446
SJW2c317da2020-03-23 07:39:13 -0500447 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400448 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400449 IntTy = FixedVectorType::get(
450 IntTy, vec_ty->getElementCount().getKnownMinValue());
Kévin Petit8c1be282019-04-02 19:34:25 +0100451 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100452
Kévin Petite8edce32019-04-10 14:23:32 +0100453 // Return X with the sign of Y
454
455 // Sign bit masks
456 auto SignBit = IntTy->getScalarSizeInBits() - 1;
457 auto SignBitMask = 1 << SignBit;
458 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
459 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
460
461 IRBuilder<> Builder(CI);
462
463 // Extract sign of Y
464 auto YInt = Builder.CreateBitCast(YValue, IntTy);
465 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
466
467 // Clear sign bit in X
468 auto XInt = Builder.CreateBitCast(XValue, IntTy);
469 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
470
471 // Insert sign bit of Y into X
472 auto NewXInt = Builder.CreateOr(XInt, YSign);
473
474 // And cast back to floating-point
475 return Builder.CreateBitCast(NewXInt, Ty);
476 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100477}
478
SJW2c317da2020-03-23 07:39:13 -0500479bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
480 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100481 // Recip has one arg.
482 auto Arg = CI->getOperand(0);
483 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
484 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
485 });
David Neto22f144c2017-06-12 14:26:21 -0400486}
487
SJW2c317da2020-03-23 07:39:13 -0500488bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
489 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100490 auto Op0 = CI->getOperand(0);
491 auto Op1 = CI->getOperand(1);
492 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
493 });
David Neto22f144c2017-06-12 14:26:21 -0400494}
495
SJW2c317da2020-03-23 07:39:13 -0500496bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
497 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100498 auto Op0 = CI->getOperand(0);
499 auto Op1 = CI->getOperand(1);
500
SJW2c317da2020-03-23 07:39:13 -0500501 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100502 if (Op0->getType()->isVectorTy()) {
503 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
504 CI->getType(), {Op0, Op1});
505 } else {
506 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
507 }
508
509 return V;
510 });
511}
512
SJW2c317da2020-03-23 07:39:13 -0500513bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500514 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500515 // convert to natural
516 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500517 std::string NewFName = basename.substr(0, slen);
518 NewFName =
519 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400520
SJW2c317da2020-03-23 07:39:13 -0500521 Module &M = *F.getParent();
522 return replaceCallsWithValue(F, [&](CallInst *CI) {
523 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
524
525 auto Arg = CI->getOperand(0);
526
527 // Constant of the natural log of 10 (ln(10)).
528 const double Ln10 =
529 2.302585092994045684017991454684364207601101488628772976033;
530
531 auto Mul = BinaryOperator::Create(
532 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
533
534 return CallInst::Create(NewF, Mul, "", CI);
535 });
David Neto22f144c2017-06-12 14:26:21 -0400536}
537
SJW2c317da2020-03-23 07:39:13 -0500538bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100539 // OpenCL fmod(x,y) is x - y * trunc(x/y)
540 // The sign for a non-zero result is taken from x.
541 // (Try an example.)
542 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500543 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100544 auto Op0 = CI->getOperand(0);
545 auto Op1 = CI->getOperand(1);
546 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
547 });
548}
549
SJW2c317da2020-03-23 07:39:13 -0500550bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500551 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500552 // convert to natural
553 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500554 std::string NewFName = basename.substr(0, slen);
555 NewFName =
556 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400557
SJW2c317da2020-03-23 07:39:13 -0500558 Module &M = *F.getParent();
559 return replaceCallsWithValue(F, [&](CallInst *CI) {
560 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
561
562 auto Arg = CI->getOperand(0);
563
564 // Constant of the reciprocal of the natural log of 10 (ln(10)).
565 const double Ln10 =
566 0.434294481903251827651128918916605082294397005803666566114;
567
568 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
569
570 return BinaryOperator::Create(Instruction::FMul,
571 ConstantFP::get(Arg->getType(), Ln10), NewCI,
572 "", CI);
573 });
David Neto22f144c2017-06-12 14:26:21 -0400574}
575
gnl21636e7992020-09-09 16:08:16 +0100576bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
577 // convert to natural
578 std::string NewFName =
579 Builtins::GetMangledFunctionName("log", F.getFunctionType());
580
581 Module &M = *F.getParent();
582 return replaceCallsWithValue(F, [&](CallInst *CI) {
583 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
584
585 auto Arg = CI->getOperand(0);
586
587 auto ArgP1 = BinaryOperator::Create(
588 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
589
590 return CallInst::Create(NewF, ArgP1, "", CI);
591 });
592}
593
alan-baker12d2c182020-07-20 08:22:42 -0400594bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400595
596 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
597
alan-baker12d2c182020-07-20 08:22:42 -0400598 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100599 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400600
Kévin Petitc4643922019-06-17 19:32:05 +0100601 // We need to map the OpenCL constants to the SPIR-V equivalents.
602 const auto LocalMemFence =
603 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
604 const auto GlobalMemFence =
605 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400606 const auto ConstantAcquireRelease = ConstantInt::get(
607 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100608 const auto ConstantScopeDevice =
609 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
610 const auto ConstantScopeWorkgroup =
611 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400612 const auto ConstantScopeSubgroup =
613 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
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
alan-baker12d2c182020-07-20 08:22:42 -0400634 // MemorySemanticsAcquireReleaseMask.
Kévin Petitc4643922019-06-17 19:32:05 +0100635 auto MemorySemantics =
636 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400637 ConstantAcquireRelease, "", CI);
Kévin Petitc4643922019-06-17 19:32:05 +0100638 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
639 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400640
alan-baker12d2c182020-07-20 08:22:42 -0400641 // If the memory scope is not specified explicitly, it is either Subgroup
642 // or Workgroup depending on the type of barrier.
643 Value *MemoryScope =
644 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
645 if (CI->data_operands_size() > 1) {
646 enum {
647 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
648 CL_MEMORY_SCOPE_DEVICE = 0x2,
649 CL_MEMORY_SCOPE_SUBGROUP = 0x4
650 };
651 // The call was given an explicit memory scope.
652 const auto MemoryScopeSubgroup =
653 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
654 const auto MemoryScopeDevice =
655 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400656
alan-baker12d2c182020-07-20 08:22:42 -0400657 auto Cmp =
658 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
659 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
660 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
661 ConstantScopeWorkgroup, "", CI);
662 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
663 MemoryScopeDevice, CI->getOperand(1), "", CI);
664 MemoryScope =
665 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
666 }
667
668 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
669 // the type of barrier;
670 const auto ExecutionScope =
671 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400672
Kévin Petitc4643922019-06-17 19:32:05 +0100673 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
674 {Attribute::NoDuplicate}, CI->getType(),
675 {ExecutionScope, MemoryScope, MemorySemantics});
676 });
David Neto22f144c2017-06-12 14:26:21 -0400677}
678
SJW2c317da2020-03-23 07:39:13 -0500679bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
680 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400681
SJW2c317da2020-03-23 07:39:13 -0500682 return replaceCallsWithValue(F, [&](CallInst *CI) {
683 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
David Neto22f144c2017-06-12 14:26:21 -0400684
SJW2c317da2020-03-23 07:39:13 -0500685 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400686
SJW2c317da2020-03-23 07:39:13 -0500687 // We need to map the OpenCL constants to the SPIR-V equivalents.
688 const auto LocalMemFence =
689 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
690 const auto GlobalMemFence =
691 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
692 const auto ConstantMemorySemantics =
693 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400694 const auto ConstantScopeWorkgroup =
695 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400696
SJW2c317da2020-03-23 07:39:13 -0500697 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
698 const auto LocalMemFenceMask =
699 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
700 const auto WorkgroupShiftAmount =
701 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
702 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
703 Instruction::Shl, LocalMemFenceMask,
704 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400705
SJW2c317da2020-03-23 07:39:13 -0500706 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
707 const auto GlobalMemFenceMask =
708 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
709 const auto UniformShiftAmount =
710 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
711 const auto MemorySemanticsUniform = BinaryOperator::Create(
712 Instruction::Shl, GlobalMemFenceMask,
713 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400714
SJW2c317da2020-03-23 07:39:13 -0500715 // And combine the above together, also adding in
716 // MemorySemanticsSequentiallyConsistentMask.
717 auto MemorySemantics =
718 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
719 ConstantMemorySemantics, "", CI);
720 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
721 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400722
alan-baker12d2c182020-07-20 08:22:42 -0400723 // Memory Scope is always workgroup.
724 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400725
SJW2c317da2020-03-23 07:39:13 -0500726 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier, {}, CI->getType(),
727 {MemoryScope, MemorySemantics});
728 });
David Neto22f144c2017-06-12 14:26:21 -0400729}
730
Kévin Petit1cb45112020-04-27 18:55:48 +0100731bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
732 bool Changed = false;
733
734 SmallVector<Instruction *, 4> ToRemoves;
735
736 // Find all calls to the function
737 for (auto &U : F.uses()) {
738 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
739 ToRemoves.push_back(CI);
740 }
741 }
742
743 Changed = !ToRemoves.empty();
744
745 // Delete them
746 for (auto V : ToRemoves) {
747 V->eraseFromParent();
748 }
749
750 return Changed;
751}
752
SJW2c317da2020-03-23 07:39:13 -0500753bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
754 CmpInst::Predicate P,
755 int32_t C) {
756 return replaceCallsWithValue(F, [&](CallInst *CI) {
757 // The predicate to use in the CmpInst.
758 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400759
SJW2c317da2020-03-23 07:39:13 -0500760 // The value to return for true.
761 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400762
SJW2c317da2020-03-23 07:39:13 -0500763 // The value to return for false.
764 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400765
SJW2c317da2020-03-23 07:39:13 -0500766 auto Arg1 = CI->getOperand(0);
767 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400768
SJW2c317da2020-03-23 07:39:13 -0500769 const auto Cmp =
770 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400771
SJW2c317da2020-03-23 07:39:13 -0500772 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
773 });
David Neto22f144c2017-06-12 14:26:21 -0400774}
775
SJW2c317da2020-03-23 07:39:13 -0500776bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
777 spv::Op SPIRVOp,
778 int32_t C) {
779 Module &M = *F.getParent();
780 return replaceCallsWithValue(F, [&](CallInst *CI) {
781 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400782
SJW2c317da2020-03-23 07:39:13 -0500783 // The value to return for true.
784 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400785
SJW2c317da2020-03-23 07:39:13 -0500786 // The value to return for false.
787 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400788
SJW2c317da2020-03-23 07:39:13 -0500789 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400790 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400791 CorrespondingBoolTy =
792 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
793 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -0400794 }
David Neto22f144c2017-06-12 14:26:21 -0400795
SJW2c317da2020-03-23 07:39:13 -0500796 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
797 CorrespondingBoolTy, {CI->getOperand(0)});
798
799 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
800 });
David Neto22f144c2017-06-12 14:26:21 -0400801}
802
SJW2c317da2020-03-23 07:39:13 -0500803bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
804 Module &M = *F.getParent();
805 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100806 auto &C = M.getContext();
807 auto Val = CI->getOperand(0);
808 auto ValTy = Val->getType();
809 auto RetTy = CI->getType();
810
811 // Get a suitable integer type to represent the number
812 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
813
814 // Create Mask
815 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -0500816 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100817 switch (ScalarSize) {
818 case 16:
819 InfMask = ConstantInt::get(IntTy, 0x7C00U);
820 break;
821 case 32:
822 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
823 break;
824 case 64:
825 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
826 break;
827 default:
828 llvm_unreachable("Unsupported floating-point type");
829 }
830
831 IRBuilder<> Builder(CI);
832
833 // Bitcast to int
834 auto ValInt = Builder.CreateBitCast(Val, IntTy);
835
836 // Mask and compare
837 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
838 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
839
840 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -0500841 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100842 if (ValTy->isVectorTy()) {
843 RetTrue = ConstantInt::getSigned(RetTy, -1);
844 } else {
845 RetTrue = ConstantInt::get(RetTy, 1);
846 }
847 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
848 });
849}
850
SJW2c317da2020-03-23 07:39:13 -0500851bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
852 Module &M = *F.getParent();
853 return replaceCallsWithValue(F, [&](CallInst *CI) {
854 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400855
SJW2c317da2020-03-23 07:39:13 -0500856 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +0000857
SJW2c317da2020-03-23 07:39:13 -0500858 // If the argument is a 32-bit int, just use a shift
859 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
860 V = BinaryOperator::Create(Instruction::LShr, Arg,
861 ConstantInt::get(Arg->getType(), 31), "", CI);
862 } else {
863 // The value for zero to compare against.
864 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -0400865
SJW2c317da2020-03-23 07:39:13 -0500866 // The value to return for true.
867 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -0400868
SJW2c317da2020-03-23 07:39:13 -0500869 // The value to return for false.
870 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400871
SJW2c317da2020-03-23 07:39:13 -0500872 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
873 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400874
SJW2c317da2020-03-23 07:39:13 -0500875 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400876
SJW2c317da2020-03-23 07:39:13 -0500877 // If we have a function to call, call it!
878 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -0400879
SJW2c317da2020-03-23 07:39:13 -0500880 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -0400881
SJW2c317da2020-03-23 07:39:13 -0500882 const auto NewCI = clspv::InsertSPIRVOp(
883 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
884 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -0400885
SJW2c317da2020-03-23 07:39:13 -0500886 } else {
887 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -0400888 }
889
SJW2c317da2020-03-23 07:39:13 -0500890 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400891 }
SJW2c317da2020-03-23 07:39:13 -0500892 return V;
893 });
David Neto22f144c2017-06-12 14:26:21 -0400894}
895
SJW2c317da2020-03-23 07:39:13 -0500896bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
897 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
898 // Get arguments
899 auto HiValue = CI->getOperand(0);
900 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000901
SJW2c317da2020-03-23 07:39:13 -0500902 // Don't touch overloads that aren't in OpenCL C
903 auto HiType = HiValue->getType();
904 auto LoType = LoValue->getType();
905
906 if (HiType != LoType) {
907 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000908 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000909
SJW2c317da2020-03-23 07:39:13 -0500910 if (!HiType->isIntOrIntVectorTy()) {
911 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000912 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000913
SJW2c317da2020-03-23 07:39:13 -0500914 if (HiType->getScalarSizeInBits() * 2 !=
915 CI->getType()->getScalarSizeInBits()) {
916 return nullptr;
917 }
918
919 if ((HiType->getScalarSizeInBits() != 8) &&
920 (HiType->getScalarSizeInBits() != 16) &&
921 (HiType->getScalarSizeInBits() != 32)) {
922 return nullptr;
923 }
924
James Pricecf53df42020-04-20 14:41:24 -0400925 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400926 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -0400927 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
928 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500929 return nullptr;
930 }
931 }
932
933 // Convert both operands to the result type
934 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
935 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
936
937 // Shift high operand
938 auto ShiftAmount =
939 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
940 auto HiShifted =
941 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
942
943 // OR both results
944 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
945 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000946}
947
SJW2c317da2020-03-23 07:39:13 -0500948bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
949 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
950 // Get arguments
951 auto SrcValue = CI->getOperand(0);
952 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000953
SJW2c317da2020-03-23 07:39:13 -0500954 // Don't touch overloads that aren't in OpenCL C
955 auto SrcType = SrcValue->getType();
956 auto RotType = RotAmount->getType();
957
958 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
959 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000960 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000961
SJW2c317da2020-03-23 07:39:13 -0500962 if (!SrcType->isIntOrIntVectorTy()) {
963 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000964 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000965
SJW2c317da2020-03-23 07:39:13 -0500966 if ((SrcType->getScalarSizeInBits() != 8) &&
967 (SrcType->getScalarSizeInBits() != 16) &&
968 (SrcType->getScalarSizeInBits() != 32) &&
969 (SrcType->getScalarSizeInBits() != 64)) {
970 return nullptr;
971 }
972
James Pricecf53df42020-04-20 14:41:24 -0400973 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400974 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -0400975 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
976 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500977 return nullptr;
978 }
979 }
980
981 // The approach used is to shift the top bits down, the bottom bits up
982 // and OR the two shifted values.
983
984 // The rotation amount is to be treated modulo the element size.
985 // Since SPIR-V shift ops don't support this, let's apply the
986 // modulo ahead of shifting. The element size is always a power of
987 // two so we can just AND with a mask.
988 auto ModMask =
989 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
990 RotAmount =
991 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
992
993 // Let's calc the amount by which to shift top bits down
994 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
995 auto DownAmount =
996 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
997
998 // Now shift the bottom bits up and the top bits down
999 auto LoRotated =
1000 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
1001 auto HiRotated =
1002 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
1003
1004 // Finally OR the two shifted values
1005 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
1006 CI);
1007 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001008}
1009
SJW2c317da2020-03-23 07:39:13 -05001010bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1011 bool DstIsSigned) {
1012 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1013 Value *V = nullptr;
1014 // Get arguments
1015 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001016
SJW2c317da2020-03-23 07:39:13 -05001017 // Don't touch overloads that aren't in OpenCL C
1018 auto SrcType = SrcValue->getType();
1019 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001020
SJW2c317da2020-03-23 07:39:13 -05001021 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1022 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1023 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001024 }
1025
James Pricecf53df42020-04-20 14:41:24 -04001026 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001027 unsigned SrcNumElements =
1028 SrcVecType->getElementCount().getKnownMinValue();
1029 unsigned DstNumElements =
1030 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001031 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001032 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001033 }
1034
James Pricecf53df42020-04-20 14:41:24 -04001035 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1036 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1037 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001038 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001039 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001040 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001041
SJW2c317da2020-03-23 07:39:13 -05001042 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1043 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1044
1045 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1046 bool DstIsInt = DstType->isIntOrIntVectorTy();
1047
1048 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1049 // Unnecessary cast operation.
1050 V = SrcValue;
1051 } else if (SrcIsFloat && DstIsFloat) {
1052 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1053 } else if (SrcIsFloat && DstIsInt) {
1054 if (DstIsSigned) {
1055 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1056 } else {
1057 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1058 }
1059 } else if (SrcIsInt && DstIsFloat) {
1060 if (SrcIsSigned) {
1061 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1062 } else {
1063 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1064 }
1065 } else if (SrcIsInt && DstIsInt) {
1066 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1067 } else {
1068 // Not something we're supposed to handle, just move on
1069 }
1070
1071 return V;
1072 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001073}
1074
SJW2c317da2020-03-23 07:39:13 -05001075bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1076 bool is_mad) {
1077 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1078 Value *V = nullptr;
1079 // Get arguments
1080 auto AValue = CI->getOperand(0);
1081 auto BValue = CI->getOperand(1);
1082 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001083
SJW2c317da2020-03-23 07:39:13 -05001084 // Don't touch overloads that aren't in OpenCL C
1085 auto AType = AValue->getType();
1086 auto BType = BValue->getType();
1087 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001088
SJW2c317da2020-03-23 07:39:13 -05001089 if ((AType != BType) || (CI->getType() != AType) ||
1090 (is_mad && (AType != CType))) {
1091 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001092 }
1093
SJW2c317da2020-03-23 07:39:13 -05001094 if (!AType->isIntOrIntVectorTy()) {
1095 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001096 }
Kévin Petit8a560882019-03-21 15:24:34 +00001097
SJW2c317da2020-03-23 07:39:13 -05001098 if ((AType->getScalarSizeInBits() != 8) &&
1099 (AType->getScalarSizeInBits() != 16) &&
1100 (AType->getScalarSizeInBits() != 32) &&
1101 (AType->getScalarSizeInBits() != 64)) {
1102 return V;
1103 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001104
James Pricecf53df42020-04-20 14:41:24 -04001105 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001106 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001107 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1108 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001109 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001110 }
1111 }
1112
SJW2c317da2020-03-23 07:39:13 -05001113 // Our SPIR-V op returns a struct, create a type for it
1114 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1115 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001116
SJW2c317da2020-03-23 07:39:13 -05001117 // Select the appropriate signed/unsigned SPIR-V op
1118 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1119
1120 // Call the SPIR-V op
1121 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1122 ExMulRetType, {AValue, BValue});
1123
1124 // Get the high part of the result
1125 unsigned Idxs[] = {1};
1126 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1127
1128 // If we're handling a mad_hi, add the third argument to the result
1129 if (is_mad) {
1130 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001131 }
1132
SJW2c317da2020-03-23 07:39:13 -05001133 return V;
1134 });
Kévin Petit8a560882019-03-21 15:24:34 +00001135}
1136
SJW2c317da2020-03-23 07:39:13 -05001137bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1138 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1139 // Get arguments
1140 auto FalseValue = CI->getOperand(0);
1141 auto TrueValue = CI->getOperand(1);
1142 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001143
SJW2c317da2020-03-23 07:39:13 -05001144 // Don't touch overloads that aren't in OpenCL C
1145 auto FalseType = FalseValue->getType();
1146 auto TrueType = TrueValue->getType();
1147 auto PredicateType = PredicateValue->getType();
1148
1149 if (FalseType != TrueType) {
1150 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001151 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001152
SJW2c317da2020-03-23 07:39:13 -05001153 if (!PredicateType->isIntOrIntVectorTy()) {
1154 return nullptr;
1155 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001156
SJW2c317da2020-03-23 07:39:13 -05001157 if (!FalseType->isIntOrIntVectorTy() &&
1158 !FalseType->getScalarType()->isFloatingPointTy()) {
1159 return nullptr;
1160 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001161
SJW2c317da2020-03-23 07:39:13 -05001162 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1163 return nullptr;
1164 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001165
SJW2c317da2020-03-23 07:39:13 -05001166 if (FalseType->getScalarSizeInBits() !=
1167 PredicateType->getScalarSizeInBits()) {
1168 return nullptr;
1169 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001170
James Pricecf53df42020-04-20 14:41:24 -04001171 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001172 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1173 if (NumElements != cast<VectorType>(PredicateType)
1174 ->getElementCount()
1175 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001176 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001177 }
1178
James Pricecf53df42020-04-20 14:41:24 -04001179 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1180 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001181 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001182 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001183 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001184
SJW2c317da2020-03-23 07:39:13 -05001185 // Create constant
1186 const auto ZeroValue = Constant::getNullValue(PredicateType);
1187
1188 // Scalar and vector are to be treated differently
1189 CmpInst::Predicate Pred;
1190 if (PredicateType->isVectorTy()) {
1191 Pred = CmpInst::ICMP_SLT;
1192 } else {
1193 Pred = CmpInst::ICMP_NE;
1194 }
1195
1196 // Create comparison instruction
1197 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1198 ZeroValue, "", CI);
1199
1200 // Create select
1201 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1202 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001203}
1204
SJW2c317da2020-03-23 07:39:13 -05001205bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1206 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1207 Value *V = nullptr;
1208 if (CI->getNumOperands() != 4) {
1209 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001210 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001211
SJW2c317da2020-03-23 07:39:13 -05001212 // Get arguments
1213 auto FalseValue = CI->getOperand(0);
1214 auto TrueValue = CI->getOperand(1);
1215 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001216
SJW2c317da2020-03-23 07:39:13 -05001217 // Don't touch overloads that aren't in OpenCL C
1218 auto FalseType = FalseValue->getType();
1219 auto TrueType = TrueValue->getType();
1220 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001221
SJW2c317da2020-03-23 07:39:13 -05001222 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1223 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001224 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001225
James Pricecf53df42020-04-20 14:41:24 -04001226 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001227 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1228 !TrueType->getScalarType()->isIntegerTy()) {
1229 return V;
1230 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001231 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001232 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1233 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001234 return V;
1235 }
1236 }
1237
1238 // Remember the type of the operands
1239 auto OpType = TrueType;
1240
1241 // The actual bit selection will always be done on an integer type,
1242 // declare it here
1243 Type *BitType;
1244
1245 // If the operands are float, then bitcast them to int
1246 if (OpType->getScalarType()->isFloatingPointTy()) {
1247
1248 // First create the new type
1249 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1250
1251 // Then bitcast all operands
1252 PredicateValue =
1253 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1254 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1255 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1256
1257 } else {
1258 // The operands have an integer type, use it directly
1259 BitType = OpType;
1260 }
1261
1262 // All the operands are now always integers
1263 // implement as (c & b) | (~c & a)
1264
1265 // Create our negated predicate value
1266 auto AllOnes = Constant::getAllOnesValue(BitType);
1267 auto NotPredicateValue = BinaryOperator::Create(
1268 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1269
1270 // Then put everything together
1271 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1272 FalseValue, "", CI);
1273 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1274 TrueValue, "", CI);
1275
1276 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1277
1278 // If we were dealing with a floating point type, we must bitcast
1279 // the result back to that
1280 if (OpType->getScalarType()->isFloatingPointTy()) {
1281 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1282 }
1283
1284 return V;
1285 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001286}
1287
SJW61531372020-06-09 07:31:08 -05001288bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001289 // convert to vector versions
1290 Module &M = *F.getParent();
1291 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1292 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1293 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001294
SJW2c317da2020-03-23 07:39:13 -05001295 // First figure out which function we're dealing with
1296 if (is_smooth) {
1297 ArgsToSplat.push_back(CI->getOperand(1));
1298 VectorArg = CI->getOperand(2);
1299 } else {
1300 VectorArg = CI->getOperand(1);
1301 }
1302
1303 // Splat arguments that need to be
1304 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001305 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001306
1307 for (auto arg : ArgsToSplat) {
1308 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001309 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001310 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1311 NewVectorArg =
1312 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1313 }
1314 SplatArgs.push_back(NewVectorArg);
1315 }
1316
1317 // Replace the call with the vector/vector flavour
1318 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1319 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1320
SJW61531372020-06-09 07:31:08 -05001321 std::string NewFName = Builtins::GetMangledFunctionName(
1322 is_smooth ? "smoothstep" : "step", NewFType);
1323
SJW2c317da2020-03-23 07:39:13 -05001324 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1325
1326 SmallVector<Value *, 3> NewArgs;
1327 for (auto arg : SplatArgs) {
1328 NewArgs.push_back(arg);
1329 }
1330 NewArgs.push_back(VectorArg);
1331
1332 return CallInst::Create(NewF, NewArgs, "", CI);
1333 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001334}
1335
SJW2c317da2020-03-23 07:39:13 -05001336bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001337 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1338 auto Arg = CI->getOperand(0);
1339 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001340
SJW2c317da2020-03-23 07:39:13 -05001341 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001342
SJW2c317da2020-03-23 07:39:13 -05001343 return BinaryOperator::Create(Op, Bitcast,
1344 ConstantInt::get(CI->getType(), 31), "", CI);
1345 });
David Neto22f144c2017-06-12 14:26:21 -04001346}
1347
SJW2c317da2020-03-23 07:39:13 -05001348bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1349 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001350 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1351 // The multiply instruction to use.
1352 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001353
SJW2c317da2020-03-23 07:39:13 -05001354 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001355
SJW2c317da2020-03-23 07:39:13 -05001356 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1357 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001358
SJW2c317da2020-03-23 07:39:13 -05001359 if (is_mad) {
1360 // The add instruction to use.
1361 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001362
SJW2c317da2020-03-23 07:39:13 -05001363 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001364 }
David Neto22f144c2017-06-12 14:26:21 -04001365
SJW2c317da2020-03-23 07:39:13 -05001366 return V;
1367 });
David Neto22f144c2017-06-12 14:26:21 -04001368}
1369
SJW2c317da2020-03-23 07:39:13 -05001370bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001371 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1372 Value *V = nullptr;
1373 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001374
SJW2c317da2020-03-23 07:39:13 -05001375 auto data_type = data->getType();
1376 if (!data_type->isVectorTy())
1377 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001378
James Pricecf53df42020-04-20 14:41:24 -04001379 auto vec_data_type = cast<VectorType>(data_type);
1380
alan-baker5a8c3be2020-09-09 13:44:26 -04001381 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001382 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1383 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001384
SJW2c317da2020-03-23 07:39:13 -05001385 auto offset = CI->getOperand(1);
1386 auto ptr = CI->getOperand(2);
1387 auto ptr_type = ptr->getType();
1388 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001389 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001390 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001391
SJW2c317da2020-03-23 07:39:13 -05001392 // Avoid pointer casts. Instead generate the correct number of stores
1393 // and rely on drivers to coalesce appropriately.
1394 IRBuilder<> builder(CI);
1395 auto elems_const = builder.getInt32(elems);
1396 auto adjust = builder.CreateMul(offset, elems_const);
1397 for (auto i = 0; i < elems; ++i) {
1398 auto idx = builder.getInt32(i);
1399 auto add = builder.CreateAdd(adjust, idx);
1400 auto gep = builder.CreateGEP(ptr, add);
1401 auto extract = builder.CreateExtractElement(data, i);
1402 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001403 }
SJW2c317da2020-03-23 07:39:13 -05001404 return V;
1405 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001406}
1407
SJW2c317da2020-03-23 07:39:13 -05001408bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001409 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1410 Value *V = nullptr;
1411 auto ret_type = F.getReturnType();
1412 if (!ret_type->isVectorTy())
1413 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001414
James Pricecf53df42020-04-20 14:41:24 -04001415 auto vec_ret_type = cast<VectorType>(ret_type);
1416
alan-baker5a8c3be2020-09-09 13:44:26 -04001417 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001418 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1419 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001420
SJW2c317da2020-03-23 07:39:13 -05001421 auto offset = CI->getOperand(0);
1422 auto ptr = CI->getOperand(1);
1423 auto ptr_type = ptr->getType();
1424 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001425 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001426 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001427
SJW2c317da2020-03-23 07:39:13 -05001428 // Avoid pointer casts. Instead generate the correct number of loads
1429 // and rely on drivers to coalesce appropriately.
1430 IRBuilder<> builder(CI);
1431 auto elems_const = builder.getInt32(elems);
1432 V = UndefValue::get(ret_type);
1433 auto adjust = builder.CreateMul(offset, elems_const);
1434 for (auto i = 0; i < elems; ++i) {
1435 auto idx = builder.getInt32(i);
1436 auto add = builder.CreateAdd(adjust, idx);
1437 auto gep = builder.CreateGEP(ptr, add);
1438 auto load = builder.CreateLoad(gep);
1439 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001440 }
SJW2c317da2020-03-23 07:39:13 -05001441 return V;
1442 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001443}
1444
SJW2c317da2020-03-23 07:39:13 -05001445bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1446 const std::string &name,
1447 int vec_size) {
1448 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1449 if (!vec_size) {
1450 // deduce vec_size from last character of name (e.g. vload_half4)
1451 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001452 }
SJW2c317da2020-03-23 07:39:13 -05001453 switch (vec_size) {
1454 case 2:
1455 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1456 case 4:
1457 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1458 case 0:
1459 if (!is_clspv_version) {
1460 return replaceVloadHalf(F);
1461 }
1462 default:
1463 llvm_unreachable("Unsupported vload_half vector size");
1464 break;
1465 }
1466 return false;
David Neto22f144c2017-06-12 14:26:21 -04001467}
1468
SJW2c317da2020-03-23 07:39:13 -05001469bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1470 Module &M = *F.getParent();
1471 return replaceCallsWithValue(F, [&](CallInst *CI) {
1472 // The index argument from vload_half.
1473 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001474
SJW2c317da2020-03-23 07:39:13 -05001475 // The pointer argument from vload_half.
1476 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001477
SJW2c317da2020-03-23 07:39:13 -05001478 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001479 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001480 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1481
1482 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001483 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001484
1485 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1486
1487 Value *V = nullptr;
1488
alan-baker7efcaaa2020-05-06 19:33:27 -04001489 bool supports_16bit_storage = true;
1490 switch (Arg1->getType()->getPointerAddressSpace()) {
1491 case clspv::AddressSpace::Global:
1492 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1493 clspv::Option::StorageClass::kSSBO);
1494 break;
1495 case clspv::AddressSpace::Constant:
1496 if (clspv::Option::ConstantArgsInUniformBuffer())
1497 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1498 clspv::Option::StorageClass::kUBO);
1499 else
1500 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1501 clspv::Option::StorageClass::kSSBO);
1502 break;
1503 default:
1504 // Clspv will emit the Float16 capability if the half type is
1505 // encountered. That capability covers private and local addressspaces.
1506 break;
1507 }
1508
1509 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001510 auto ShortTy = Type::getInt16Ty(M.getContext());
1511 auto ShortPointerTy =
1512 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1513
1514 // Cast the half* pointer to short*.
1515 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1516
1517 // Index into the correct address of the casted pointer.
1518 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1519
1520 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001521 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001522
1523 // ZExt the short -> int.
1524 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1525
1526 // Get our float2.
1527 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1528
1529 // Extract out the bottom element which is our float result.
1530 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1531 } else {
1532 // Assume the pointer argument points to storage aligned to 32bits
1533 // or more.
1534 // TODO(dneto): Do more analysis to make sure this is true?
1535 //
1536 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1537 // with:
1538 //
1539 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1540 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1541 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1542 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1543 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1544 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1545 // x float> %converted, %index_is_odd32
1546
1547 auto IntPointerTy =
1548 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1549
1550 // Cast the base pointer to int*.
1551 // In a valid call (according to assumptions), this should get
1552 // optimized away in the simplify GEP pass.
1553 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1554
1555 auto One = ConstantInt::get(IntTy, 1);
1556 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1557 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1558
1559 // Index into the correct address of the casted pointer.
1560 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1561
1562 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001563 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001564
1565 // Get our float2.
1566 auto Call = CallInst::Create(NewF, Load, "", CI);
1567
1568 // Extract out the float result, where the element number is
1569 // determined by whether the original index was even or odd.
1570 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1571 }
1572 return V;
1573 });
1574}
1575
1576bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1577 Module &M = *F.getParent();
1578 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001579 // The index argument from vload_half.
1580 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001581
Kévin Petite8edce32019-04-10 14:23:32 +01001582 // The pointer argument from vload_half.
1583 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001584
Kévin Petite8edce32019-04-10 14:23:32 +01001585 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001586 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001587 auto NewPointerTy =
1588 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001589 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001590
Kévin Petite8edce32019-04-10 14:23:32 +01001591 // Cast the half* pointer to int*.
1592 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001593
Kévin Petite8edce32019-04-10 14:23:32 +01001594 // Index into the correct address of the casted pointer.
1595 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001596
Kévin Petite8edce32019-04-10 14:23:32 +01001597 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001598 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001599
Kévin Petite8edce32019-04-10 14:23:32 +01001600 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001601 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001602
Kévin Petite8edce32019-04-10 14:23:32 +01001603 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001604
Kévin Petite8edce32019-04-10 14:23:32 +01001605 // Get our float2.
1606 return CallInst::Create(NewF, Load, "", CI);
1607 });
David Neto22f144c2017-06-12 14:26:21 -04001608}
1609
SJW2c317da2020-03-23 07:39:13 -05001610bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1611 Module &M = *F.getParent();
1612 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001613 // The index argument from vload_half.
1614 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001615
Kévin Petite8edce32019-04-10 14:23:32 +01001616 // The pointer argument from vload_half.
1617 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001618
Kévin Petite8edce32019-04-10 14:23:32 +01001619 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001620 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1621 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001622 auto NewPointerTy =
1623 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001624 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001625
Kévin Petite8edce32019-04-10 14:23:32 +01001626 // Cast the half* pointer to int2*.
1627 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001628
Kévin Petite8edce32019-04-10 14:23:32 +01001629 // Index into the correct address of the casted pointer.
1630 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001631
Kévin Petite8edce32019-04-10 14:23:32 +01001632 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001633 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001634
Kévin Petite8edce32019-04-10 14:23:32 +01001635 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001636 auto X =
1637 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1638 auto Y =
1639 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001640
Kévin Petite8edce32019-04-10 14:23:32 +01001641 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001642 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001643
Kévin Petite8edce32019-04-10 14:23:32 +01001644 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001645
Kévin Petite8edce32019-04-10 14:23:32 +01001646 // Get the lower (x & y) components of our final float4.
1647 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001648
Kévin Petite8edce32019-04-10 14:23:32 +01001649 // Get the higher (z & w) components of our final float4.
1650 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001651
Kévin Petite8edce32019-04-10 14:23:32 +01001652 Constant *ShuffleMask[4] = {
1653 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1654 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001655
Kévin Petite8edce32019-04-10 14:23:32 +01001656 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001657 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1658 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001659 });
David Neto22f144c2017-06-12 14:26:21 -04001660}
1661
SJW2c317da2020-03-23 07:39:13 -05001662bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001663
1664 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1665 //
1666 // %u = load i32 %ptr
1667 // %fxy = call <2 x float> Unpack2xHalf(u)
1668 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001669 Module &M = *F.getParent();
1670 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001671 auto Index = CI->getOperand(0);
1672 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001673
Kévin Petite8edce32019-04-10 14:23:32 +01001674 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001675 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001676 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001677
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001678 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001679 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001680
Kévin Petite8edce32019-04-10 14:23:32 +01001681 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001682 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001683
Kévin Petite8edce32019-04-10 14:23:32 +01001684 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001685
Kévin Petite8edce32019-04-10 14:23:32 +01001686 // Get our final float2.
1687 return CallInst::Create(NewF, Load, "", CI);
1688 });
David Neto6ad93232018-06-07 15:42:58 -07001689}
1690
SJW2c317da2020-03-23 07:39:13 -05001691bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001692
1693 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1694 //
1695 // %u2 = load <2 x i32> %ptr
1696 // %u2xy = extractelement %u2, 0
1697 // %u2zw = extractelement %u2, 1
1698 // %fxy = call <2 x float> Unpack2xHalf(uint)
1699 // %fzw = call <2 x float> Unpack2xHalf(uint)
1700 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001701 Module &M = *F.getParent();
1702 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001703 auto Index = CI->getOperand(0);
1704 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001705
Kévin Petite8edce32019-04-10 14:23:32 +01001706 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001707 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1708 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001709 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001710
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001711 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001712 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001713
Kévin Petite8edce32019-04-10 14:23:32 +01001714 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001715 auto X =
1716 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1717 auto Y =
1718 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001719
Kévin Petite8edce32019-04-10 14:23:32 +01001720 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001721 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001722
Kévin Petite8edce32019-04-10 14:23:32 +01001723 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001724
Kévin Petite8edce32019-04-10 14:23:32 +01001725 // Get the lower (x & y) components of our final float4.
1726 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001727
Kévin Petite8edce32019-04-10 14:23:32 +01001728 // Get the higher (z & w) components of our final float4.
1729 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001730
Kévin Petite8edce32019-04-10 14:23:32 +01001731 Constant *ShuffleMask[4] = {
1732 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1733 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001734
Kévin Petite8edce32019-04-10 14:23:32 +01001735 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001736 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1737 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001738 });
David Neto6ad93232018-06-07 15:42:58 -07001739}
1740
SJW2c317da2020-03-23 07:39:13 -05001741bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1742 switch (vec_size) {
1743 case 0:
1744 return replaceVstoreHalf(F);
1745 case 2:
1746 return replaceVstoreHalf2(F);
1747 case 4:
1748 return replaceVstoreHalf4(F);
1749 default:
1750 llvm_unreachable("Unsupported vstore_half vector size");
1751 break;
1752 }
1753 return false;
1754}
David Neto22f144c2017-06-12 14:26:21 -04001755
SJW2c317da2020-03-23 07:39:13 -05001756bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1757 Module &M = *F.getParent();
1758 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001759 // The value to store.
1760 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001761
Kévin Petite8edce32019-04-10 14:23:32 +01001762 // The index argument from vstore_half.
1763 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001764
Kévin Petite8edce32019-04-10 14:23:32 +01001765 // The pointer argument from vstore_half.
1766 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001767
Kévin Petite8edce32019-04-10 14:23:32 +01001768 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001769 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001770 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1771 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001772
Kévin Petite8edce32019-04-10 14:23:32 +01001773 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001774 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001775
Kévin Petite8edce32019-04-10 14:23:32 +01001776 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001777
Kévin Petite8edce32019-04-10 14:23:32 +01001778 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001779 auto TempVec = InsertElementInst::Create(
1780 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001781
Kévin Petite8edce32019-04-10 14:23:32 +01001782 // Pack the float2 -> half2 (in an int).
1783 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001784
alan-baker7efcaaa2020-05-06 19:33:27 -04001785 bool supports_16bit_storage = true;
1786 switch (Arg2->getType()->getPointerAddressSpace()) {
1787 case clspv::AddressSpace::Global:
1788 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1789 clspv::Option::StorageClass::kSSBO);
1790 break;
1791 case clspv::AddressSpace::Constant:
1792 if (clspv::Option::ConstantArgsInUniformBuffer())
1793 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1794 clspv::Option::StorageClass::kUBO);
1795 else
1796 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1797 clspv::Option::StorageClass::kSSBO);
1798 break;
1799 default:
1800 // Clspv will emit the Float16 capability if the half type is
1801 // encountered. That capability covers private and local addressspaces.
1802 break;
1803 }
1804
SJW2c317da2020-03-23 07:39:13 -05001805 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04001806 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01001807 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001808 auto ShortPointerTy =
1809 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001810
Kévin Petite8edce32019-04-10 14:23:32 +01001811 // Truncate our i32 to an i16.
1812 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001813
Kévin Petite8edce32019-04-10 14:23:32 +01001814 // Cast the half* pointer to short*.
1815 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001816
Kévin Petite8edce32019-04-10 14:23:32 +01001817 // Index into the correct address of the casted pointer.
1818 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001819
Kévin Petite8edce32019-04-10 14:23:32 +01001820 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001821 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001822 } else {
1823 // We can only write to 32-bit aligned words.
1824 //
1825 // Assuming base is aligned to 32-bits, replace the equivalent of
1826 // vstore_half(value, index, base)
1827 // with:
1828 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1829 // uint32_t write_to_upper_half = index & 1u;
1830 // uint32_t shift = write_to_upper_half << 4;
1831 //
1832 // // Pack the float value as a half number in bottom 16 bits
1833 // // of an i32.
1834 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1835 //
1836 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1837 // ^ ((packed & 0xffff) << shift)
1838 // // We only need relaxed consistency, but OpenCL 1.2 only has
1839 // // sequentially consistent atomics.
1840 // // TODO(dneto): Use relaxed consistency.
1841 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001842 auto IntPointerTy =
1843 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001844
Kévin Petite8edce32019-04-10 14:23:32 +01001845 auto Four = ConstantInt::get(IntTy, 4);
1846 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001847
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001848 auto IndexIsOdd =
1849 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001850 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001851 auto IndexIntoI32 =
1852 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1853 auto BaseI32Ptr =
1854 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1855 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1856 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001857 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001858 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001859 auto MaskBitsToWrite =
1860 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1861 auto MaskedCurrent = BinaryOperator::CreateAnd(
1862 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001863
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001864 auto XLowerBits =
1865 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1866 auto NewBitsToWrite =
1867 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1868 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1869 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001870
Kévin Petite8edce32019-04-10 14:23:32 +01001871 // Generate the call to atomi_xor.
1872 SmallVector<Type *, 5> ParamTypes;
1873 // The pointer type.
1874 ParamTypes.push_back(IntPointerTy);
1875 // The Types for memory scope, semantics, and value.
1876 ParamTypes.push_back(IntTy);
1877 ParamTypes.push_back(IntTy);
1878 ParamTypes.push_back(IntTy);
1879 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1880 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001881
Kévin Petite8edce32019-04-10 14:23:32 +01001882 const auto ConstantScopeDevice =
1883 ConstantInt::get(IntTy, spv::ScopeDevice);
1884 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1885 // (SPIR-V Workgroup).
1886 const auto AddrSpaceSemanticsBits =
1887 IntPointerTy->getPointerAddressSpace() == 1
1888 ? spv::MemorySemanticsUniformMemoryMask
1889 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001890
Kévin Petite8edce32019-04-10 14:23:32 +01001891 // We're using relaxed consistency here.
1892 const auto ConstantMemorySemantics =
1893 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1894 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001895
Kévin Petite8edce32019-04-10 14:23:32 +01001896 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1897 ConstantMemorySemantics, ValueToXor};
1898 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001899
1900 // Return a Nop so the old Call is removed
1901 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1902 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001903 }
David Neto22f144c2017-06-12 14:26:21 -04001904
SJW2c317da2020-03-23 07:39:13 -05001905 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001906 });
David Neto22f144c2017-06-12 14:26:21 -04001907}
1908
SJW2c317da2020-03-23 07:39:13 -05001909bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1910 Module &M = *F.getParent();
1911 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001912 // The value to store.
1913 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001914
Kévin Petite8edce32019-04-10 14:23:32 +01001915 // The index argument from vstore_half.
1916 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001917
Kévin Petite8edce32019-04-10 14:23:32 +01001918 // The pointer argument from vstore_half.
1919 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001920
Kévin Petite8edce32019-04-10 14:23:32 +01001921 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001922 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001923 auto NewPointerTy =
1924 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001925 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001926
Kévin Petite8edce32019-04-10 14:23:32 +01001927 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001928 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001929
Kévin Petite8edce32019-04-10 14:23:32 +01001930 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001931
Kévin Petite8edce32019-04-10 14:23:32 +01001932 // Turn the packed x & y into the final packing.
1933 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001934
Kévin Petite8edce32019-04-10 14:23:32 +01001935 // Cast the half* pointer to int*.
1936 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001937
Kévin Petite8edce32019-04-10 14:23:32 +01001938 // Index into the correct address of the casted pointer.
1939 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001940
Kévin Petite8edce32019-04-10 14:23:32 +01001941 // Store to the int* we casted to.
1942 return new StoreInst(X, Index, CI);
1943 });
David Neto22f144c2017-06-12 14:26:21 -04001944}
1945
SJW2c317da2020-03-23 07:39:13 -05001946bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1947 Module &M = *F.getParent();
1948 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001949 // The value to store.
1950 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001951
Kévin Petite8edce32019-04-10 14:23:32 +01001952 // The index argument from vstore_half.
1953 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001954
Kévin Petite8edce32019-04-10 14:23:32 +01001955 // The pointer argument from vstore_half.
1956 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001957
Kévin Petite8edce32019-04-10 14:23:32 +01001958 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001959 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1960 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001961 auto NewPointerTy =
1962 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001963 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001964
Kévin Petite8edce32019-04-10 14:23:32 +01001965 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1966 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04001967
Kévin Petite8edce32019-04-10 14:23:32 +01001968 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001969 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1970 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001971
Kévin Petite8edce32019-04-10 14:23:32 +01001972 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1973 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001974
Kévin Petite8edce32019-04-10 14:23:32 +01001975 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001976 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1977 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001978
Kévin Petite8edce32019-04-10 14:23:32 +01001979 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001980 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001981
Kévin Petite8edce32019-04-10 14:23:32 +01001982 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001983
Kévin Petite8edce32019-04-10 14:23:32 +01001984 // Turn the packed x & y into the final component of our int2.
1985 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001986
Kévin Petite8edce32019-04-10 14:23:32 +01001987 // Turn the packed z & w into the final component of our int2.
1988 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001989
Kévin Petite8edce32019-04-10 14:23:32 +01001990 auto Combine = InsertElementInst::Create(
1991 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001992 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
1993 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001994
Kévin Petite8edce32019-04-10 14:23:32 +01001995 // Cast the half* pointer to int2*.
1996 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001997
Kévin Petite8edce32019-04-10 14:23:32 +01001998 // Index into the correct address of the casted pointer.
1999 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002000
Kévin Petite8edce32019-04-10 14:23:32 +01002001 // Store to the int2* we casted to.
2002 return new StoreInst(Combine, Index, CI);
2003 });
David Neto22f144c2017-06-12 14:26:21 -04002004}
2005
SJW2c317da2020-03-23 07:39:13 -05002006bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2007 // convert half to float
2008 Module &M = *F.getParent();
2009 return replaceCallsWithValue(F, [&](CallInst *CI) {
2010 SmallVector<Type *, 3> types;
2011 SmallVector<Value *, 3> args;
2012 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2013 types.push_back(CI->getArgOperand(i)->getType());
2014 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002015 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002016
alan-baker5a8c3be2020-09-09 13:44:26 -04002017 auto NewFType =
2018 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2019 cast<VectorType>(CI->getType())
2020 ->getElementCount()
2021 .getKnownMinValue()),
2022 types, false);
SJW2c317da2020-03-23 07:39:13 -05002023
SJW61531372020-06-09 07:31:08 -05002024 std::string NewFName =
2025 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002026
2027 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2028
2029 auto NewCI = CallInst::Create(NewF, args, "", CI);
2030
2031 // Convert to the half type.
2032 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2033 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002034}
2035
SJW2c317da2020-03-23 07:39:13 -05002036bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2037 // convert half to float
2038 Module &M = *F.getParent();
2039 return replaceCallsWithValue(F, [&](CallInst *CI) {
2040 SmallVector<Type *, 3> types(3);
2041 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002042
SJW2c317da2020-03-23 07:39:13 -05002043 // Image
2044 types[0] = CI->getArgOperand(0)->getType();
2045 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002046
SJW2c317da2020-03-23 07:39:13 -05002047 // Coord
2048 types[1] = CI->getArgOperand(1)->getType();
2049 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002050
SJW2c317da2020-03-23 07:39:13 -05002051 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002052 types[2] =
2053 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2054 cast<VectorType>(CI->getArgOperand(2)->getType())
2055 ->getElementCount()
2056 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002057
SJW2c317da2020-03-23 07:39:13 -05002058 auto NewFType =
2059 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002060
SJW61531372020-06-09 07:31:08 -05002061 std::string NewFName =
2062 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002063
SJW2c317da2020-03-23 07:39:13 -05002064 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002065
SJW2c317da2020-03-23 07:39:13 -05002066 // Convert data to the float type.
2067 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2068 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002069
SJW2c317da2020-03-23 07:39:13 -05002070 return CallInst::Create(NewF, args, "", CI);
2071 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002072}
2073
SJW2c317da2020-03-23 07:39:13 -05002074bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2075 Function &F) {
2076 // convert read_image with int coords to float coords
2077 Module &M = *F.getParent();
2078 return replaceCallsWithValue(F, [&](CallInst *CI) {
2079 // The image.
2080 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002081
SJW2c317da2020-03-23 07:39:13 -05002082 // The sampler.
2083 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002084
SJW2c317da2020-03-23 07:39:13 -05002085 // The coordinate (integer type that we can't handle).
2086 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002087
SJW2c317da2020-03-23 07:39:13 -05002088 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2089 uint32_t components =
2090 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2091 Type *float_ty = nullptr;
2092 if (components == 1) {
2093 float_ty = Type::getFloatTy(M.getContext());
2094 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002095 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2096 cast<VectorType>(Arg2->getType())
2097 ->getElementCount()
2098 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002099 }
David Neto22f144c2017-06-12 14:26:21 -04002100
SJW2c317da2020-03-23 07:39:13 -05002101 auto NewFType = FunctionType::get(
2102 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2103
2104 std::string NewFName = F.getName().str();
2105 NewFName[NewFName.length() - 1] = 'f';
2106
2107 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2108
2109 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2110
2111 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2112 });
David Neto22f144c2017-06-12 14:26:21 -04002113}
2114
SJW2c317da2020-03-23 07:39:13 -05002115bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2116 return replaceCallsWithValue(F, [&](CallInst *CI) {
2117 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002118
SJW2c317da2020-03-23 07:39:13 -05002119 // We need to map the OpenCL constants to the SPIR-V equivalents.
2120 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2121 const auto ConstantMemorySemantics = ConstantInt::get(
2122 IntTy, spv::MemorySemanticsUniformMemoryMask |
2123 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002124
SJW2c317da2020-03-23 07:39:13 -05002125 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002126
SJW2c317da2020-03-23 07:39:13 -05002127 // The pointer.
2128 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002129
SJW2c317da2020-03-23 07:39:13 -05002130 // The memory scope.
2131 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002132
SJW2c317da2020-03-23 07:39:13 -05002133 // The memory semantics.
2134 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002135
SJW2c317da2020-03-23 07:39:13 -05002136 if (2 < CI->getNumArgOperands()) {
2137 // The unequal memory semantics.
2138 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002139
SJW2c317da2020-03-23 07:39:13 -05002140 // The value.
2141 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002142
SJW2c317da2020-03-23 07:39:13 -05002143 // The comparator.
2144 Params.push_back(CI->getArgOperand(1));
2145 } else if (1 < CI->getNumArgOperands()) {
2146 // The value.
2147 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002148 }
David Neto22f144c2017-06-12 14:26:21 -04002149
SJW2c317da2020-03-23 07:39:13 -05002150 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2151 });
David Neto22f144c2017-06-12 14:26:21 -04002152}
2153
SJW2c317da2020-03-23 07:39:13 -05002154bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2155 llvm::AtomicRMWInst::BinOp Op) {
2156 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002157 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2158 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002159 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002160 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002161 SyncScope::System, CI);
2162 });
2163}
David Neto22f144c2017-06-12 14:26:21 -04002164
SJW2c317da2020-03-23 07:39:13 -05002165bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2166 Module &M = *F.getParent();
2167 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002168 auto IntTy = Type::getInt32Ty(M.getContext());
2169 auto FloatTy = Type::getFloatTy(M.getContext());
2170
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002171 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2172 ConstantInt::get(IntTy, 1),
2173 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002174
2175 Constant *UpShuffleMask[4] = {
2176 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2177 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2178
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002179 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2180 UndefValue::get(FloatTy),
2181 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002182
Kévin Petite8edce32019-04-10 14:23:32 +01002183 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002184 auto Arg0 =
2185 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2186 ConstantVector::get(DownShuffleMask), "", CI);
2187 auto Arg1 =
2188 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2189 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002190 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002191
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002192 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002193 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002194
SJW61531372020-06-09 07:31:08 -05002195 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002196
Kévin Petite8edce32019-04-10 14:23:32 +01002197 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002198
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002199 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2200 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002201 });
David Neto22f144c2017-06-12 14:26:21 -04002202}
David Neto62653202017-10-16 19:05:18 -04002203
SJW2c317da2020-03-23 07:39:13 -05002204bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002205 // OpenCL's float result = fract(float x, float* ptr)
2206 //
2207 // In the LLVM domain:
2208 //
2209 // %floor_result = call spir_func float @floor(float %x)
2210 // store float %floor_result, float * %ptr
2211 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2212 // %result = call spir_func float
2213 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2214 //
2215 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2216 // and clspv.fract occur in the SPIR-V generator pass:
2217 //
2218 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2219 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2220 // ...
2221 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2222 // OpStore %ptr %floor_result
2223 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2224 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002225 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002226
David Neto62653202017-10-16 19:05:18 -04002227 using std::string;
2228
2229 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2230 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002231
SJW2c317da2020-03-23 07:39:13 -05002232 Module &M = *F.getParent();
2233 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002234
SJW2c317da2020-03-23 07:39:13 -05002235 // This is either float or a float vector. All the float-like
2236 // types are this type.
2237 auto result_ty = F.getReturnType();
2238
SJW61531372020-06-09 07:31:08 -05002239 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002240 Function *fmin_fn = M.getFunction(fmin_name);
2241 if (!fmin_fn) {
2242 // Make the fmin function.
2243 FunctionType *fn_ty =
2244 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2245 fmin_fn =
2246 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2247 fmin_fn->addFnAttr(Attribute::ReadNone);
2248 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2249 }
2250
SJW61531372020-06-09 07:31:08 -05002251 std::string floor_name =
2252 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002253 Function *floor_fn = M.getFunction(floor_name);
2254 if (!floor_fn) {
2255 // Make the floor function.
2256 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2257 floor_fn =
2258 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2259 floor_fn->addFnAttr(Attribute::ReadNone);
2260 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2261 }
2262
SJW61531372020-06-09 07:31:08 -05002263 std::string clspv_fract_name =
2264 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002265 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2266 if (!clspv_fract_fn) {
2267 // Make the clspv_fract function.
2268 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2269 clspv_fract_fn = cast<Function>(
2270 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2271 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2272 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2273 }
2274
2275 // Number of significant significand bits, whether represented or not.
2276 unsigned num_significand_bits;
2277 switch (result_ty->getScalarType()->getTypeID()) {
2278 case Type::HalfTyID:
2279 num_significand_bits = 11;
2280 break;
2281 case Type::FloatTyID:
2282 num_significand_bits = 24;
2283 break;
2284 case Type::DoubleTyID:
2285 num_significand_bits = 53;
2286 break;
2287 default:
2288 llvm_unreachable("Unhandled float type when processing fract builtin");
2289 break;
2290 }
2291 // Beware that the disassembler displays this value as
2292 // OpConstant %float 1
2293 // which is not quite right.
2294 const double kJustUnderOneScalar =
2295 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2296
2297 Constant *just_under_one =
2298 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2299 if (result_ty->isVectorTy()) {
2300 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002301 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002302 }
2303
2304 IRBuilder<> Builder(CI);
2305
2306 auto arg = CI->getArgOperand(0);
2307 auto ptr = CI->getArgOperand(1);
2308
2309 // Compute floor result and store it.
2310 auto floor = Builder.CreateCall(floor_fn, {arg});
2311 Builder.CreateStore(floor, ptr);
2312
2313 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2314 auto fract_result =
2315 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2316
2317 return fract_result;
2318 });
David Neto62653202017-10-16 19:05:18 -04002319}