blob: f6b869ce100d09e98c22fbb78033af1670ab41d6 [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"
alan-baker4986eff2020-10-29 13:38:00 -040024#include "llvm/IR/Operator.h"
Kévin Petitf5b78a22018-10-25 14:32:17 +000025#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040026#include "llvm/Pass.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/raw_ostream.h"
alan-baker4986eff2020-10-29 13:38:00 -040029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
David Neto118188e2018-08-24 11:27:54 -040030#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040031
alan-bakere0902602020-03-23 08:43:40 -040032#include "spirv/unified1/spirv.hpp"
David Neto22f144c2017-06-12 14:26:21 -040033
alan-baker931d18a2019-12-12 08:21:32 -050034#include "clspv/AddressSpace.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040035#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070036
SJW2c317da2020-03-23 07:39:13 -050037#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050038#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040039#include "Passes.h"
40#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050041#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040042
SJW2c317da2020-03-23 07:39:13 -050043using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040044using namespace llvm;
45
46#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
47
48namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000049
David Neto22f144c2017-06-12 14:26:21 -040050uint32_t clz(uint32_t v) {
51 uint32_t r;
52 uint32_t shift;
53
54 r = (v > 0xFFFF) << 4;
55 v >>= r;
56 shift = (v > 0xFF) << 3;
57 v >>= shift;
58 r |= shift;
59 shift = (v > 0xF) << 2;
60 v >>= shift;
61 r |= shift;
62 shift = (v > 0x3) << 1;
63 v >>= shift;
64 r |= shift;
65 r |= (v >> 1);
66
67 return r;
68}
69
Kévin Petitfdfa92e2019-09-25 14:20:58 +010070Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
71 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040072 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -040073 IntTy = FixedVectorType::get(IntTy,
74 vec_ty->getElementCount().getKnownMinValue());
Kévin Petitfdfa92e2019-09-25 14:20:58 +010075 }
76 return IntTy;
77}
78
alan-baker4986eff2020-10-29 13:38:00 -040079Value *MemoryOrderSemantics(Value *order, bool is_global,
80 Instruction *InsertBefore,
81 spv::MemorySemanticsMask base_semantics) {
82 enum AtomicMemoryOrder : uint32_t {
83 kMemoryOrderRelaxed = 0,
84 kMemoryOrderAcquire = 2,
85 kMemoryOrderRelease = 3,
86 kMemoryOrderAcqRel = 4,
87 kMemoryOrderSeqCst = 5
88 };
89
90 IRBuilder<> builder(InsertBefore);
91
92 // Constants for OpenCL C 2.0 memory_order.
93 const auto relaxed = builder.getInt32(AtomicMemoryOrder::kMemoryOrderRelaxed);
94 const auto acquire = builder.getInt32(AtomicMemoryOrder::kMemoryOrderAcquire);
95 const auto release = builder.getInt32(AtomicMemoryOrder::kMemoryOrderRelease);
96 const auto acq_rel = builder.getInt32(AtomicMemoryOrder::kMemoryOrderAcqRel);
97
98 // Constants for SPIR-V ordering memory semantics.
99 const auto RelaxedSemantics = builder.getInt32(spv::MemorySemanticsMaskNone);
100 const auto AcquireSemantics =
101 builder.getInt32(spv::MemorySemanticsAcquireMask);
102 const auto ReleaseSemantics =
103 builder.getInt32(spv::MemorySemanticsReleaseMask);
104 const auto AcqRelSemantics =
105 builder.getInt32(spv::MemorySemanticsAcquireReleaseMask);
106
107 // Constants for SPIR-V storage class semantics.
108 const auto UniformSemantics =
109 builder.getInt32(spv::MemorySemanticsUniformMemoryMask);
110 const auto WorkgroupSemantics =
111 builder.getInt32(spv::MemorySemanticsWorkgroupMemoryMask);
112
113 // Instead of sequentially consistent, use acquire, release or acquire
114 // release semantics.
115 Value *base_order = nullptr;
116 switch (base_semantics) {
117 case spv::MemorySemanticsAcquireMask:
118 base_order = AcquireSemantics;
119 break;
120 case spv::MemorySemanticsReleaseMask:
121 base_order = ReleaseSemantics;
122 break;
123 default:
124 base_order = AcqRelSemantics;
125 break;
126 }
127
128 Value *storage = is_global ? UniformSemantics : WorkgroupSemantics;
129 if (order == nullptr)
130 return builder.CreateOr({storage, base_order});
131
132 auto is_relaxed = builder.CreateICmpEQ(order, relaxed);
133 auto is_acquire = builder.CreateICmpEQ(order, acquire);
134 auto is_release = builder.CreateICmpEQ(order, release);
135 auto is_acq_rel = builder.CreateICmpEQ(order, acq_rel);
136 auto semantics =
137 builder.CreateSelect(is_relaxed, RelaxedSemantics, base_order);
138 semantics = builder.CreateSelect(is_acquire, AcquireSemantics, semantics);
139 semantics = builder.CreateSelect(is_release, ReleaseSemantics, semantics);
140 semantics = builder.CreateSelect(is_acq_rel, AcqRelSemantics, semantics);
141 return builder.CreateOr({storage, semantics});
142}
143
144Value *MemoryScope(Value *scope, bool is_global, Instruction *InsertBefore) {
145 enum AtomicMemoryScope : uint32_t {
146 kMemoryScopeWorkItem = 0,
147 kMemoryScopeWorkGroup = 1,
148 kMemoryScopeDevice = 2,
149 kMemoryScopeAllSVMDevices = 3, // not supported
150 kMemoryScopeSubGroup = 4
151 };
152
153 IRBuilder<> builder(InsertBefore);
154
155 // Constants for OpenCL C 2.0 memory_scope.
156 const auto work_item =
157 builder.getInt32(AtomicMemoryScope::kMemoryScopeWorkItem);
158 const auto work_group =
159 builder.getInt32(AtomicMemoryScope::kMemoryScopeWorkGroup);
160 const auto sub_group =
161 builder.getInt32(AtomicMemoryScope::kMemoryScopeSubGroup);
162 const auto device = builder.getInt32(AtomicMemoryScope::kMemoryScopeDevice);
163
164 // Constants for SPIR-V memory scopes.
165 const auto InvocationScope = builder.getInt32(spv::ScopeInvocation);
166 const auto WorkgroupScope = builder.getInt32(spv::ScopeWorkgroup);
167 const auto DeviceScope = builder.getInt32(spv::ScopeDevice);
168 const auto SubgroupScope = builder.getInt32(spv::ScopeSubgroup);
169
170 auto base_scope = is_global ? DeviceScope : WorkgroupScope;
171 if (scope == nullptr)
172 return base_scope;
173
174 auto is_work_item = builder.CreateICmpEQ(scope, work_item);
175 auto is_work_group = builder.CreateICmpEQ(scope, work_group);
176 auto is_sub_group = builder.CreateICmpEQ(scope, sub_group);
177 auto is_device = builder.CreateICmpEQ(scope, device);
178
179 scope = builder.CreateSelect(is_work_item, InvocationScope, base_scope);
180 scope = builder.CreateSelect(is_work_group, WorkgroupScope, scope);
181 scope = builder.CreateSelect(is_sub_group, SubgroupScope, scope);
182 scope = builder.CreateSelect(is_device, DeviceScope, scope);
183
184 return scope;
185}
186
SJW2c317da2020-03-23 07:39:13 -0500187bool replaceCallsWithValue(Function &F,
188 std::function<Value *(CallInst *)> Replacer) {
189
190 bool Changed = false;
191
192 SmallVector<Instruction *, 4> ToRemoves;
193
194 // Walk the users of the function.
195 for (auto &U : F.uses()) {
196 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
197
198 auto NewValue = Replacer(CI);
199
200 if (NewValue != nullptr) {
201 CI->replaceAllUsesWith(NewValue);
202
203 // Lastly, remember to remove the user.
204 ToRemoves.push_back(CI);
205 }
206 }
207 }
208
209 Changed = !ToRemoves.empty();
210
211 // And cleanup the calls we don't use anymore.
212 for (auto V : ToRemoves) {
213 V->eraseFromParent();
214 }
215
216 return Changed;
217}
218
David Neto22f144c2017-06-12 14:26:21 -0400219struct ReplaceOpenCLBuiltinPass final : public ModulePass {
220 static char ID;
221 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
222
223 bool runOnModule(Module &M) override;
SJW2c317da2020-03-23 07:39:13 -0500224 bool runOnFunction(Function &F);
225 bool replaceAbs(Function &F);
226 bool replaceAbsDiff(Function &F, bool is_signed);
227 bool replaceCopysign(Function &F);
228 bool replaceRecip(Function &F);
229 bool replaceDivide(Function &F);
230 bool replaceDot(Function &F);
231 bool replaceFmod(Function &F);
SJW61531372020-06-09 07:31:08 -0500232 bool replaceExp10(Function &F, const std::string &basename);
233 bool replaceLog10(Function &F, const std::string &basename);
gnl21636e7992020-09-09 16:08:16 +0100234 bool replaceLog1p(Function &F);
alan-baker12d2c182020-07-20 08:22:42 -0400235 bool replaceBarrier(Function &F, bool subgroup = false);
SJW2c317da2020-03-23 07:39:13 -0500236 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100237 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500238 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
239 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
240 bool replaceIsFinite(Function &F);
241 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
242 bool replaceUpsample(Function &F);
243 bool replaceRotate(Function &F);
244 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
245 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
246 bool replaceSelect(Function &F);
247 bool replaceBitSelect(Function &F);
SJW61531372020-06-09 07:31:08 -0500248 bool replaceStep(Function &F, bool is_smooth);
SJW2c317da2020-03-23 07:39:13 -0500249 bool replaceSignbit(Function &F, bool is_vec);
250 bool replaceMul(Function &F, bool is_float, bool is_mad);
251 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
252 bool replaceVloadHalf(Function &F);
253 bool replaceVloadHalf2(Function &F);
254 bool replaceVloadHalf4(Function &F);
255 bool replaceClspvVloadaHalf2(Function &F);
256 bool replaceClspvVloadaHalf4(Function &F);
257 bool replaceVstoreHalf(Function &F, int vec_size);
258 bool replaceVstoreHalf(Function &F);
259 bool replaceVstoreHalf2(Function &F);
260 bool replaceVstoreHalf4(Function &F);
261 bool replaceHalfReadImage(Function &F);
262 bool replaceHalfWriteImage(Function &F);
263 bool replaceSampledReadImageWithIntCoords(Function &F);
264 bool replaceAtomics(Function &F, spv::Op Op);
265 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
alan-baker4986eff2020-10-29 13:38:00 -0400266 bool replaceAtomicLoad(Function &F);
267 bool replaceExplicitAtomics(Function &F, spv::Op Op,
268 spv::MemorySemanticsMask semantics =
269 spv::MemorySemanticsAcquireReleaseMask);
270 bool replaceAtomicCompareExchange(Function &);
SJW2c317da2020-03-23 07:39:13 -0500271 bool replaceCross(Function &F);
272 bool replaceFract(Function &F, int vec_size);
273 bool replaceVload(Function &F);
274 bool replaceVstore(Function &F);
alan-bakera52b7312020-10-26 08:58:51 -0400275 bool replaceAddSat(Function &F, bool is_signed);
David Neto22f144c2017-06-12 14:26:21 -0400276};
SJW2c317da2020-03-23 07:39:13 -0500277
Kévin Petit91bc72e2019-04-08 15:17:46 +0100278} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400279
280char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400281INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
282 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400283
284namespace clspv {
285ModulePass *createReplaceOpenCLBuiltinPass() {
286 return new ReplaceOpenCLBuiltinPass();
287}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400288} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400289
290bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500291 std::list<Function *> func_list;
292 for (auto &F : M.getFunctionList()) {
293 // process only function declarations
294 if (F.isDeclaration() && runOnFunction(F)) {
295 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000296 }
297 }
SJW2c317da2020-03-23 07:39:13 -0500298 if (func_list.size() != 0) {
299 // recursively convert functions, but first remove dead
300 for (auto *F : func_list) {
301 if (F->use_empty()) {
302 F->eraseFromParent();
303 }
304 }
305 runOnModule(M);
306 return true;
307 }
308 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000309}
310
SJW2c317da2020-03-23 07:39:13 -0500311bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
312 auto &FI = Builtins::Lookup(&F);
313 switch (FI.getType()) {
314 case Builtins::kAbs:
315 if (!FI.getParameter(0).is_signed) {
316 return replaceAbs(F);
317 }
318 break;
319 case Builtins::kAbsDiff:
320 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400321
322 case Builtins::kAddSat:
323 return replaceAddSat(F, FI.getParameter(0).is_signed);
324
SJW2c317da2020-03-23 07:39:13 -0500325 case Builtins::kCopysign:
326 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100327
SJW2c317da2020-03-23 07:39:13 -0500328 case Builtins::kHalfRecip:
329 case Builtins::kNativeRecip:
330 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100331
SJW2c317da2020-03-23 07:39:13 -0500332 case Builtins::kHalfDivide:
333 case Builtins::kNativeDivide:
334 return replaceDivide(F);
335
336 case Builtins::kDot:
337 return replaceDot(F);
338
339 case Builtins::kExp10:
340 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500341 case Builtins::kNativeExp10:
342 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500343
344 case Builtins::kLog10:
345 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500346 case Builtins::kNativeLog10:
347 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500348
gnl21636e7992020-09-09 16:08:16 +0100349 case Builtins::kLog1p:
350 return replaceLog1p(F);
351
SJW2c317da2020-03-23 07:39:13 -0500352 case Builtins::kFmod:
353 return replaceFmod(F);
354
355 case Builtins::kBarrier:
356 case Builtins::kWorkGroupBarrier:
357 return replaceBarrier(F);
358
alan-baker12d2c182020-07-20 08:22:42 -0400359 case Builtins::kSubGroupBarrier:
360 return replaceBarrier(F, true);
361
SJW2c317da2020-03-23 07:39:13 -0500362 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400363 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500364 case Builtins::kReadMemFence:
365 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
366 case Builtins::kWriteMemFence:
367 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
368
369 // Relational
370 case Builtins::kIsequal:
371 return replaceRelational(F, CmpInst::FCMP_OEQ,
372 FI.getParameter(0).vector_size ? -1 : 1);
373 case Builtins::kIsgreater:
374 return replaceRelational(F, CmpInst::FCMP_OGT,
375 FI.getParameter(0).vector_size ? -1 : 1);
376 case Builtins::kIsgreaterequal:
377 return replaceRelational(F, CmpInst::FCMP_OGE,
378 FI.getParameter(0).vector_size ? -1 : 1);
379 case Builtins::kIsless:
380 return replaceRelational(F, CmpInst::FCMP_OLT,
381 FI.getParameter(0).vector_size ? -1 : 1);
382 case Builtins::kIslessequal:
383 return replaceRelational(F, CmpInst::FCMP_OLE,
384 FI.getParameter(0).vector_size ? -1 : 1);
385 case Builtins::kIsnotequal:
386 return replaceRelational(F, CmpInst::FCMP_ONE,
387 FI.getParameter(0).vector_size ? -1 : 1);
388
389 case Builtins::kIsinf: {
390 bool is_vec = FI.getParameter(0).vector_size != 0;
391 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
392 }
393 case Builtins::kIsnan: {
394 bool is_vec = FI.getParameter(0).vector_size != 0;
395 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
396 }
397
398 case Builtins::kIsfinite:
399 return replaceIsFinite(F);
400
401 case Builtins::kAll: {
402 bool is_vec = FI.getParameter(0).vector_size != 0;
403 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
404 }
405 case Builtins::kAny: {
406 bool is_vec = FI.getParameter(0).vector_size != 0;
407 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
408 }
409
410 case Builtins::kUpsample:
411 return replaceUpsample(F);
412
413 case Builtins::kRotate:
414 return replaceRotate(F);
415
416 case Builtins::kConvert:
417 return replaceConvert(F, FI.getParameter(0).is_signed,
418 FI.getReturnType().is_signed);
419
alan-baker4986eff2020-10-29 13:38:00 -0400420 // OpenCL 2.0 explicit atomics have different default scopes and semantics
421 // than legacy atomic functions.
422 case Builtins::kAtomicLoad:
423 case Builtins::kAtomicLoadExplicit:
424 return replaceAtomicLoad(F);
425 case Builtins::kAtomicStore:
426 case Builtins::kAtomicStoreExplicit:
427 return replaceExplicitAtomics(F, spv::OpAtomicStore,
428 spv::MemorySemanticsReleaseMask);
429 case Builtins::kAtomicExchange:
430 case Builtins::kAtomicExchangeExplicit:
431 return replaceExplicitAtomics(F, spv::OpAtomicExchange);
432 case Builtins::kAtomicFetchAdd:
433 case Builtins::kAtomicFetchAddExplicit:
434 return replaceExplicitAtomics(F, spv::OpAtomicIAdd);
435 case Builtins::kAtomicFetchSub:
436 case Builtins::kAtomicFetchSubExplicit:
437 return replaceExplicitAtomics(F, spv::OpAtomicISub);
438 case Builtins::kAtomicFetchOr:
439 case Builtins::kAtomicFetchOrExplicit:
440 return replaceExplicitAtomics(F, spv::OpAtomicOr);
441 case Builtins::kAtomicFetchXor:
442 case Builtins::kAtomicFetchXorExplicit:
443 return replaceExplicitAtomics(F, spv::OpAtomicXor);
444 case Builtins::kAtomicFetchAnd:
445 case Builtins::kAtomicFetchAndExplicit:
446 return replaceExplicitAtomics(F, spv::OpAtomicAnd);
447 case Builtins::kAtomicFetchMin:
448 case Builtins::kAtomicFetchMinExplicit:
449 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
450 ? spv::OpAtomicSMin
451 : spv::OpAtomicUMin);
452 case Builtins::kAtomicFetchMax:
453 case Builtins::kAtomicFetchMaxExplicit:
454 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
455 ? spv::OpAtomicSMax
456 : spv::OpAtomicUMax);
457 // Weak compare exchange is generated as strong compare exchange.
458 case Builtins::kAtomicCompareExchangeWeak:
459 case Builtins::kAtomicCompareExchangeWeakExplicit:
460 case Builtins::kAtomicCompareExchangeStrong:
461 case Builtins::kAtomicCompareExchangeStrongExplicit:
462 return replaceAtomicCompareExchange(F);
463
464 // Legacy atomic functions.
SJW2c317da2020-03-23 07:39:13 -0500465 case Builtins::kAtomicInc:
466 return replaceAtomics(F, spv::OpAtomicIIncrement);
467 case Builtins::kAtomicDec:
468 return replaceAtomics(F, spv::OpAtomicIDecrement);
469 case Builtins::kAtomicCmpxchg:
470 return replaceAtomics(F, spv::OpAtomicCompareExchange);
471 case Builtins::kAtomicAdd:
472 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
473 case Builtins::kAtomicSub:
474 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
475 case Builtins::kAtomicXchg:
476 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
477 case Builtins::kAtomicMin:
478 return replaceAtomics(F, FI.getParameter(0).is_signed
479 ? llvm::AtomicRMWInst::Min
480 : llvm::AtomicRMWInst::UMin);
481 case Builtins::kAtomicMax:
482 return replaceAtomics(F, FI.getParameter(0).is_signed
483 ? llvm::AtomicRMWInst::Max
484 : llvm::AtomicRMWInst::UMax);
485 case Builtins::kAtomicAnd:
486 return replaceAtomics(F, llvm::AtomicRMWInst::And);
487 case Builtins::kAtomicOr:
488 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
489 case Builtins::kAtomicXor:
490 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
491
492 case Builtins::kCross:
493 if (FI.getParameter(0).vector_size == 4) {
494 return replaceCross(F);
495 }
496 break;
497
498 case Builtins::kFract:
499 if (FI.getParameterCount()) {
500 return replaceFract(F, FI.getParameter(0).vector_size);
501 }
502 break;
503
504 case Builtins::kMadHi:
505 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
506 case Builtins::kMulHi:
507 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
508
509 case Builtins::kMad:
510 case Builtins::kMad24:
511 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
512 true);
513 case Builtins::kMul24:
514 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
515 false);
516
517 case Builtins::kSelect:
518 return replaceSelect(F);
519
520 case Builtins::kBitselect:
521 return replaceBitSelect(F);
522
523 case Builtins::kVload:
524 return replaceVload(F);
525
526 case Builtins::kVloadaHalf:
527 case Builtins::kVloadHalf:
528 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
529
530 case Builtins::kVstore:
531 return replaceVstore(F);
532
533 case Builtins::kVstoreHalf:
534 case Builtins::kVstoreaHalf:
535 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
536
537 case Builtins::kSmoothstep: {
538 int vec_size = FI.getLastParameter().vector_size;
539 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500540 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500541 }
542 break;
543 }
544 case Builtins::kStep: {
545 int vec_size = FI.getLastParameter().vector_size;
546 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500547 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500548 }
549 break;
550 }
551
552 case Builtins::kSignbit:
553 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
554
555 case Builtins::kReadImageh:
556 return replaceHalfReadImage(F);
557 case Builtins::kReadImagef:
558 case Builtins::kReadImagei:
559 case Builtins::kReadImageui: {
560 if (FI.getParameter(1).isSampler() &&
561 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
562 return replaceSampledReadImageWithIntCoords(F);
563 }
564 break;
565 }
566
567 case Builtins::kWriteImageh:
568 return replaceHalfWriteImage(F);
569
Kévin Petit1cb45112020-04-27 18:55:48 +0100570 case Builtins::kPrefetch:
571 return replacePrefetch(F);
572
SJW2c317da2020-03-23 07:39:13 -0500573 default:
574 break;
575 }
576
577 return false;
578}
579
580bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
581 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400582 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100583}
584
SJW2c317da2020-03-23 07:39:13 -0500585bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
586 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100587 auto XValue = CI->getOperand(0);
588 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100589
Kévin Petite8edce32019-04-10 14:23:32 +0100590 IRBuilder<> Builder(CI);
591 auto XmY = Builder.CreateSub(XValue, YValue);
592 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100593
SJW2c317da2020-03-23 07:39:13 -0500594 Value *Cmp = nullptr;
595 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100596 Cmp = Builder.CreateICmpSGT(YValue, XValue);
597 } else {
598 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100599 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100600
Kévin Petite8edce32019-04-10 14:23:32 +0100601 return Builder.CreateSelect(Cmp, YmX, XmY);
602 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100603}
604
SJW2c317da2020-03-23 07:39:13 -0500605bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
606 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100607 auto XValue = CI->getOperand(0);
608 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100609
Kévin Petite8edce32019-04-10 14:23:32 +0100610 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100611
SJW2c317da2020-03-23 07:39:13 -0500612 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400613 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400614 IntTy = FixedVectorType::get(
615 IntTy, vec_ty->getElementCount().getKnownMinValue());
Kévin Petit8c1be282019-04-02 19:34:25 +0100616 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100617
Kévin Petite8edce32019-04-10 14:23:32 +0100618 // Return X with the sign of Y
619
620 // Sign bit masks
621 auto SignBit = IntTy->getScalarSizeInBits() - 1;
622 auto SignBitMask = 1 << SignBit;
623 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
624 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
625
626 IRBuilder<> Builder(CI);
627
628 // Extract sign of Y
629 auto YInt = Builder.CreateBitCast(YValue, IntTy);
630 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
631
632 // Clear sign bit in X
633 auto XInt = Builder.CreateBitCast(XValue, IntTy);
634 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
635
636 // Insert sign bit of Y into X
637 auto NewXInt = Builder.CreateOr(XInt, YSign);
638
639 // And cast back to floating-point
640 return Builder.CreateBitCast(NewXInt, Ty);
641 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100642}
643
SJW2c317da2020-03-23 07:39:13 -0500644bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
645 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100646 // Recip has one arg.
647 auto Arg = CI->getOperand(0);
648 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
649 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
650 });
David Neto22f144c2017-06-12 14:26:21 -0400651}
652
SJW2c317da2020-03-23 07:39:13 -0500653bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
654 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100655 auto Op0 = CI->getOperand(0);
656 auto Op1 = CI->getOperand(1);
657 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
658 });
David Neto22f144c2017-06-12 14:26:21 -0400659}
660
SJW2c317da2020-03-23 07:39:13 -0500661bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
662 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100663 auto Op0 = CI->getOperand(0);
664 auto Op1 = CI->getOperand(1);
665
SJW2c317da2020-03-23 07:39:13 -0500666 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100667 if (Op0->getType()->isVectorTy()) {
668 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
669 CI->getType(), {Op0, Op1});
670 } else {
671 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
672 }
673
674 return V;
675 });
676}
677
SJW2c317da2020-03-23 07:39:13 -0500678bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500679 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500680 // convert to natural
681 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500682 std::string NewFName = basename.substr(0, slen);
683 NewFName =
684 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400685
SJW2c317da2020-03-23 07:39:13 -0500686 Module &M = *F.getParent();
687 return replaceCallsWithValue(F, [&](CallInst *CI) {
688 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
689
690 auto Arg = CI->getOperand(0);
691
692 // Constant of the natural log of 10 (ln(10)).
693 const double Ln10 =
694 2.302585092994045684017991454684364207601101488628772976033;
695
696 auto Mul = BinaryOperator::Create(
697 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
698
699 return CallInst::Create(NewF, Mul, "", CI);
700 });
David Neto22f144c2017-06-12 14:26:21 -0400701}
702
SJW2c317da2020-03-23 07:39:13 -0500703bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100704 // OpenCL fmod(x,y) is x - y * trunc(x/y)
705 // The sign for a non-zero result is taken from x.
706 // (Try an example.)
707 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500708 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100709 auto Op0 = CI->getOperand(0);
710 auto Op1 = CI->getOperand(1);
711 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
712 });
713}
714
SJW2c317da2020-03-23 07:39:13 -0500715bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500716 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500717 // convert to natural
718 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500719 std::string NewFName = basename.substr(0, slen);
720 NewFName =
721 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400722
SJW2c317da2020-03-23 07:39:13 -0500723 Module &M = *F.getParent();
724 return replaceCallsWithValue(F, [&](CallInst *CI) {
725 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
726
727 auto Arg = CI->getOperand(0);
728
729 // Constant of the reciprocal of the natural log of 10 (ln(10)).
730 const double Ln10 =
731 0.434294481903251827651128918916605082294397005803666566114;
732
733 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
734
735 return BinaryOperator::Create(Instruction::FMul,
736 ConstantFP::get(Arg->getType(), Ln10), NewCI,
737 "", CI);
738 });
David Neto22f144c2017-06-12 14:26:21 -0400739}
740
gnl21636e7992020-09-09 16:08:16 +0100741bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
742 // convert to natural
743 std::string NewFName =
744 Builtins::GetMangledFunctionName("log", F.getFunctionType());
745
746 Module &M = *F.getParent();
747 return replaceCallsWithValue(F, [&](CallInst *CI) {
748 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
749
750 auto Arg = CI->getOperand(0);
751
752 auto ArgP1 = BinaryOperator::Create(
753 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
754
755 return CallInst::Create(NewF, ArgP1, "", CI);
756 });
757}
758
alan-baker12d2c182020-07-20 08:22:42 -0400759bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400760
alan-bakerf6bc8252020-09-23 14:58:55 -0400761 enum {
762 CLK_LOCAL_MEM_FENCE = 0x01,
763 CLK_GLOBAL_MEM_FENCE = 0x02,
764 CLK_IMAGE_MEM_FENCE = 0x04
765 };
David Neto22f144c2017-06-12 14:26:21 -0400766
alan-baker12d2c182020-07-20 08:22:42 -0400767 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100768 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400769
Kévin Petitc4643922019-06-17 19:32:05 +0100770 // We need to map the OpenCL constants to the SPIR-V equivalents.
771 const auto LocalMemFence =
772 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
773 const auto GlobalMemFence =
774 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400775 const auto ImageMemFence =
776 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400777 const auto ConstantAcquireRelease = ConstantInt::get(
778 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100779 const auto ConstantScopeDevice =
780 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
781 const auto ConstantScopeWorkgroup =
782 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400783 const auto ConstantScopeSubgroup =
784 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400785
Kévin Petitc4643922019-06-17 19:32:05 +0100786 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
787 const auto LocalMemFenceMask =
788 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
789 const auto WorkgroupShiftAmount =
790 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
791 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
792 Instruction::Shl, LocalMemFenceMask,
793 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400794
Kévin Petitc4643922019-06-17 19:32:05 +0100795 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
796 const auto GlobalMemFenceMask =
797 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
798 const auto UniformShiftAmount =
799 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
800 const auto MemorySemanticsUniform = BinaryOperator::Create(
801 Instruction::Shl, GlobalMemFenceMask,
802 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400803
alan-bakerf6bc8252020-09-23 14:58:55 -0400804 // OpenCL 2.0
805 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
806 const auto ImageMemFenceMask =
807 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
808 const auto ImageShiftAmount =
809 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
810 const auto MemorySemanticsImage = BinaryOperator::Create(
811 Instruction::Shl, ImageMemFenceMask,
812 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
813
Kévin Petitc4643922019-06-17 19:32:05 +0100814 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400815 // MemorySemanticsSequentiallyConsistentMask.
816 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100817 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400818 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400819 auto MemorySemantics2 = BinaryOperator::Create(
820 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
821 auto MemorySemantics = BinaryOperator::Create(
822 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400823
alan-baker12d2c182020-07-20 08:22:42 -0400824 // If the memory scope is not specified explicitly, it is either Subgroup
825 // or Workgroup depending on the type of barrier.
826 Value *MemoryScope =
827 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
828 if (CI->data_operands_size() > 1) {
829 enum {
830 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
831 CL_MEMORY_SCOPE_DEVICE = 0x2,
832 CL_MEMORY_SCOPE_SUBGROUP = 0x4
833 };
834 // The call was given an explicit memory scope.
835 const auto MemoryScopeSubgroup =
836 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
837 const auto MemoryScopeDevice =
838 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400839
alan-baker12d2c182020-07-20 08:22:42 -0400840 auto Cmp =
841 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
842 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
843 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
844 ConstantScopeWorkgroup, "", CI);
845 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
846 MemoryScopeDevice, CI->getOperand(1), "", CI);
847 MemoryScope =
848 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
849 }
850
851 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
852 // the type of barrier;
853 const auto ExecutionScope =
854 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400855
Kévin Petitc4643922019-06-17 19:32:05 +0100856 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400857 {Attribute::NoDuplicate, Attribute::Convergent},
858 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100859 {ExecutionScope, MemoryScope, MemorySemantics});
860 });
David Neto22f144c2017-06-12 14:26:21 -0400861}
862
SJW2c317da2020-03-23 07:39:13 -0500863bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
864 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400865
SJW2c317da2020-03-23 07:39:13 -0500866 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400867 enum {
868 CLK_LOCAL_MEM_FENCE = 0x01,
869 CLK_GLOBAL_MEM_FENCE = 0x02,
870 CLK_IMAGE_MEM_FENCE = 0x04,
871 };
David Neto22f144c2017-06-12 14:26:21 -0400872
SJW2c317da2020-03-23 07:39:13 -0500873 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400874
SJW2c317da2020-03-23 07:39:13 -0500875 // We need to map the OpenCL constants to the SPIR-V equivalents.
876 const auto LocalMemFence =
877 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
878 const auto GlobalMemFence =
879 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400880 const auto ImageMemFence =
881 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500882 const auto ConstantMemorySemantics =
883 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400884 const auto ConstantScopeWorkgroup =
885 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400886
SJW2c317da2020-03-23 07:39:13 -0500887 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
888 const auto LocalMemFenceMask =
889 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
890 const auto WorkgroupShiftAmount =
891 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
892 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
893 Instruction::Shl, LocalMemFenceMask,
894 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400895
SJW2c317da2020-03-23 07:39:13 -0500896 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
897 const auto GlobalMemFenceMask =
898 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
899 const auto UniformShiftAmount =
900 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
901 const auto MemorySemanticsUniform = BinaryOperator::Create(
902 Instruction::Shl, GlobalMemFenceMask,
903 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400904
alan-bakerf6bc8252020-09-23 14:58:55 -0400905 // OpenCL 2.0
906 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
907 const auto ImageMemFenceMask =
908 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
909 const auto ImageShiftAmount =
910 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
911 const auto MemorySemanticsImage = BinaryOperator::Create(
912 Instruction::Shl, ImageMemFenceMask,
913 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
914
SJW2c317da2020-03-23 07:39:13 -0500915 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400916 // |semantics|.
917 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500918 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
919 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400920 auto MemorySemantics2 = BinaryOperator::Create(
921 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
922 auto MemorySemantics = BinaryOperator::Create(
923 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400924
alan-baker12d2c182020-07-20 08:22:42 -0400925 // Memory Scope is always workgroup.
926 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400927
alan-baker3d905692020-10-28 14:02:37 -0400928 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
929 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500930 {MemoryScope, MemorySemantics});
931 });
David Neto22f144c2017-06-12 14:26:21 -0400932}
933
Kévin Petit1cb45112020-04-27 18:55:48 +0100934bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
935 bool Changed = false;
936
937 SmallVector<Instruction *, 4> ToRemoves;
938
939 // Find all calls to the function
940 for (auto &U : F.uses()) {
941 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
942 ToRemoves.push_back(CI);
943 }
944 }
945
946 Changed = !ToRemoves.empty();
947
948 // Delete them
949 for (auto V : ToRemoves) {
950 V->eraseFromParent();
951 }
952
953 return Changed;
954}
955
SJW2c317da2020-03-23 07:39:13 -0500956bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
957 CmpInst::Predicate P,
958 int32_t C) {
959 return replaceCallsWithValue(F, [&](CallInst *CI) {
960 // The predicate to use in the CmpInst.
961 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400962
SJW2c317da2020-03-23 07:39:13 -0500963 // The value to return for true.
964 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400965
SJW2c317da2020-03-23 07:39:13 -0500966 // The value to return for false.
967 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400968
SJW2c317da2020-03-23 07:39:13 -0500969 auto Arg1 = CI->getOperand(0);
970 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400971
SJW2c317da2020-03-23 07:39:13 -0500972 const auto Cmp =
973 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400974
SJW2c317da2020-03-23 07:39:13 -0500975 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
976 });
David Neto22f144c2017-06-12 14:26:21 -0400977}
978
SJW2c317da2020-03-23 07:39:13 -0500979bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
980 spv::Op SPIRVOp,
981 int32_t C) {
982 Module &M = *F.getParent();
983 return replaceCallsWithValue(F, [&](CallInst *CI) {
984 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400985
SJW2c317da2020-03-23 07:39:13 -0500986 // The value to return for true.
987 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400988
SJW2c317da2020-03-23 07:39:13 -0500989 // The value to return for false.
990 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400991
SJW2c317da2020-03-23 07:39:13 -0500992 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400993 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400994 CorrespondingBoolTy =
995 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
996 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -0400997 }
David Neto22f144c2017-06-12 14:26:21 -0400998
SJW2c317da2020-03-23 07:39:13 -0500999 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
1000 CorrespondingBoolTy, {CI->getOperand(0)});
1001
1002 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
1003 });
David Neto22f144c2017-06-12 14:26:21 -04001004}
1005
SJW2c317da2020-03-23 07:39:13 -05001006bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
1007 Module &M = *F.getParent();
1008 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001009 auto &C = M.getContext();
1010 auto Val = CI->getOperand(0);
1011 auto ValTy = Val->getType();
1012 auto RetTy = CI->getType();
1013
1014 // Get a suitable integer type to represent the number
1015 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
1016
1017 // Create Mask
1018 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -05001019 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001020 switch (ScalarSize) {
1021 case 16:
1022 InfMask = ConstantInt::get(IntTy, 0x7C00U);
1023 break;
1024 case 32:
1025 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
1026 break;
1027 case 64:
1028 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
1029 break;
1030 default:
1031 llvm_unreachable("Unsupported floating-point type");
1032 }
1033
1034 IRBuilder<> Builder(CI);
1035
1036 // Bitcast to int
1037 auto ValInt = Builder.CreateBitCast(Val, IntTy);
1038
1039 // Mask and compare
1040 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
1041 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
1042
1043 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -05001044 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001045 if (ValTy->isVectorTy()) {
1046 RetTrue = ConstantInt::getSigned(RetTy, -1);
1047 } else {
1048 RetTrue = ConstantInt::get(RetTy, 1);
1049 }
1050 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
1051 });
1052}
1053
SJW2c317da2020-03-23 07:39:13 -05001054bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
1055 Module &M = *F.getParent();
1056 return replaceCallsWithValue(F, [&](CallInst *CI) {
1057 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001058
SJW2c317da2020-03-23 07:39:13 -05001059 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001060
SJW2c317da2020-03-23 07:39:13 -05001061 // If the argument is a 32-bit int, just use a shift
1062 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1063 V = BinaryOperator::Create(Instruction::LShr, Arg,
1064 ConstantInt::get(Arg->getType(), 31), "", CI);
1065 } else {
1066 // The value for zero to compare against.
1067 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -04001068
SJW2c317da2020-03-23 07:39:13 -05001069 // The value to return for true.
1070 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04001071
SJW2c317da2020-03-23 07:39:13 -05001072 // The value to return for false.
1073 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001074
SJW2c317da2020-03-23 07:39:13 -05001075 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
1076 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001077
SJW2c317da2020-03-23 07:39:13 -05001078 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04001079
SJW2c317da2020-03-23 07:39:13 -05001080 // If we have a function to call, call it!
1081 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -04001082
SJW2c317da2020-03-23 07:39:13 -05001083 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -04001084
SJW2c317da2020-03-23 07:39:13 -05001085 const auto NewCI = clspv::InsertSPIRVOp(
1086 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
1087 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -04001088
SJW2c317da2020-03-23 07:39:13 -05001089 } else {
1090 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -04001091 }
1092
SJW2c317da2020-03-23 07:39:13 -05001093 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001094 }
SJW2c317da2020-03-23 07:39:13 -05001095 return V;
1096 });
David Neto22f144c2017-06-12 14:26:21 -04001097}
1098
SJW2c317da2020-03-23 07:39:13 -05001099bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
1100 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1101 // Get arguments
1102 auto HiValue = CI->getOperand(0);
1103 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001104
SJW2c317da2020-03-23 07:39:13 -05001105 // Don't touch overloads that aren't in OpenCL C
1106 auto HiType = HiValue->getType();
1107 auto LoType = LoValue->getType();
1108
1109 if (HiType != LoType) {
1110 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001111 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001112
SJW2c317da2020-03-23 07:39:13 -05001113 if (!HiType->isIntOrIntVectorTy()) {
1114 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001115 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001116
SJW2c317da2020-03-23 07:39:13 -05001117 if (HiType->getScalarSizeInBits() * 2 !=
1118 CI->getType()->getScalarSizeInBits()) {
1119 return nullptr;
1120 }
1121
1122 if ((HiType->getScalarSizeInBits() != 8) &&
1123 (HiType->getScalarSizeInBits() != 16) &&
1124 (HiType->getScalarSizeInBits() != 32)) {
1125 return nullptr;
1126 }
1127
James Pricecf53df42020-04-20 14:41:24 -04001128 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001129 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001130 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1131 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001132 return nullptr;
1133 }
1134 }
1135
1136 // Convert both operands to the result type
1137 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1138 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
1139
1140 // Shift high operand
1141 auto ShiftAmount =
1142 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
1143 auto HiShifted =
1144 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
1145
1146 // OR both results
1147 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
1148 });
Kévin Petitbf0036c2019-03-06 13:57:10 +00001149}
1150
SJW2c317da2020-03-23 07:39:13 -05001151bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
1152 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1153 // Get arguments
1154 auto SrcValue = CI->getOperand(0);
1155 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001156
SJW2c317da2020-03-23 07:39:13 -05001157 // Don't touch overloads that aren't in OpenCL C
1158 auto SrcType = SrcValue->getType();
1159 auto RotType = RotAmount->getType();
1160
1161 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1162 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001163 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001164
SJW2c317da2020-03-23 07:39:13 -05001165 if (!SrcType->isIntOrIntVectorTy()) {
1166 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001167 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001168
SJW2c317da2020-03-23 07:39:13 -05001169 if ((SrcType->getScalarSizeInBits() != 8) &&
1170 (SrcType->getScalarSizeInBits() != 16) &&
1171 (SrcType->getScalarSizeInBits() != 32) &&
1172 (SrcType->getScalarSizeInBits() != 64)) {
1173 return nullptr;
1174 }
1175
James Pricecf53df42020-04-20 14:41:24 -04001176 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001177 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001178 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1179 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001180 return nullptr;
1181 }
1182 }
1183
1184 // The approach used is to shift the top bits down, the bottom bits up
1185 // and OR the two shifted values.
1186
1187 // The rotation amount is to be treated modulo the element size.
1188 // Since SPIR-V shift ops don't support this, let's apply the
1189 // modulo ahead of shifting. The element size is always a power of
1190 // two so we can just AND with a mask.
1191 auto ModMask =
1192 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
1193 RotAmount =
1194 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
1195
1196 // Let's calc the amount by which to shift top bits down
1197 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
1198 auto DownAmount =
1199 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
1200
1201 // Now shift the bottom bits up and the top bits down
1202 auto LoRotated =
1203 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
1204 auto HiRotated =
1205 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
1206
1207 // Finally OR the two shifted values
1208 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
1209 CI);
1210 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001211}
1212
SJW2c317da2020-03-23 07:39:13 -05001213bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1214 bool DstIsSigned) {
1215 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1216 Value *V = nullptr;
1217 // Get arguments
1218 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001219
SJW2c317da2020-03-23 07:39:13 -05001220 // Don't touch overloads that aren't in OpenCL C
1221 auto SrcType = SrcValue->getType();
1222 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001223
SJW2c317da2020-03-23 07:39:13 -05001224 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1225 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1226 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001227 }
1228
James Pricecf53df42020-04-20 14:41:24 -04001229 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001230 unsigned SrcNumElements =
1231 SrcVecType->getElementCount().getKnownMinValue();
1232 unsigned DstNumElements =
1233 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001234 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001235 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001236 }
1237
James Pricecf53df42020-04-20 14:41:24 -04001238 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1239 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1240 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001241 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001242 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001243 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001244
SJW2c317da2020-03-23 07:39:13 -05001245 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1246 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1247
1248 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1249 bool DstIsInt = DstType->isIntOrIntVectorTy();
1250
1251 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1252 // Unnecessary cast operation.
1253 V = SrcValue;
1254 } else if (SrcIsFloat && DstIsFloat) {
1255 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1256 } else if (SrcIsFloat && DstIsInt) {
1257 if (DstIsSigned) {
1258 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1259 } else {
1260 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1261 }
1262 } else if (SrcIsInt && DstIsFloat) {
1263 if (SrcIsSigned) {
1264 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1265 } else {
1266 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1267 }
1268 } else if (SrcIsInt && DstIsInt) {
1269 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1270 } else {
1271 // Not something we're supposed to handle, just move on
1272 }
1273
1274 return V;
1275 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001276}
1277
SJW2c317da2020-03-23 07:39:13 -05001278bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1279 bool is_mad) {
1280 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1281 Value *V = nullptr;
1282 // Get arguments
1283 auto AValue = CI->getOperand(0);
1284 auto BValue = CI->getOperand(1);
1285 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001286
SJW2c317da2020-03-23 07:39:13 -05001287 // Don't touch overloads that aren't in OpenCL C
1288 auto AType = AValue->getType();
1289 auto BType = BValue->getType();
1290 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001291
SJW2c317da2020-03-23 07:39:13 -05001292 if ((AType != BType) || (CI->getType() != AType) ||
1293 (is_mad && (AType != CType))) {
1294 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001295 }
1296
SJW2c317da2020-03-23 07:39:13 -05001297 if (!AType->isIntOrIntVectorTy()) {
1298 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001299 }
Kévin Petit8a560882019-03-21 15:24:34 +00001300
SJW2c317da2020-03-23 07:39:13 -05001301 if ((AType->getScalarSizeInBits() != 8) &&
1302 (AType->getScalarSizeInBits() != 16) &&
1303 (AType->getScalarSizeInBits() != 32) &&
1304 (AType->getScalarSizeInBits() != 64)) {
1305 return V;
1306 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001307
James Pricecf53df42020-04-20 14:41:24 -04001308 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001309 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001310 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1311 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001312 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001313 }
1314 }
1315
SJW2c317da2020-03-23 07:39:13 -05001316 // Our SPIR-V op returns a struct, create a type for it
1317 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1318 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001319
SJW2c317da2020-03-23 07:39:13 -05001320 // Select the appropriate signed/unsigned SPIR-V op
1321 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1322
1323 // Call the SPIR-V op
1324 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1325 ExMulRetType, {AValue, BValue});
1326
1327 // Get the high part of the result
1328 unsigned Idxs[] = {1};
1329 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1330
1331 // If we're handling a mad_hi, add the third argument to the result
1332 if (is_mad) {
1333 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001334 }
1335
SJW2c317da2020-03-23 07:39:13 -05001336 return V;
1337 });
Kévin Petit8a560882019-03-21 15:24:34 +00001338}
1339
SJW2c317da2020-03-23 07:39:13 -05001340bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1341 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1342 // Get arguments
1343 auto FalseValue = CI->getOperand(0);
1344 auto TrueValue = CI->getOperand(1);
1345 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001346
SJW2c317da2020-03-23 07:39:13 -05001347 // Don't touch overloads that aren't in OpenCL C
1348 auto FalseType = FalseValue->getType();
1349 auto TrueType = TrueValue->getType();
1350 auto PredicateType = PredicateValue->getType();
1351
1352 if (FalseType != TrueType) {
1353 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001354 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001355
SJW2c317da2020-03-23 07:39:13 -05001356 if (!PredicateType->isIntOrIntVectorTy()) {
1357 return nullptr;
1358 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001359
SJW2c317da2020-03-23 07:39:13 -05001360 if (!FalseType->isIntOrIntVectorTy() &&
1361 !FalseType->getScalarType()->isFloatingPointTy()) {
1362 return nullptr;
1363 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001364
SJW2c317da2020-03-23 07:39:13 -05001365 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1366 return nullptr;
1367 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001368
SJW2c317da2020-03-23 07:39:13 -05001369 if (FalseType->getScalarSizeInBits() !=
1370 PredicateType->getScalarSizeInBits()) {
1371 return nullptr;
1372 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001373
James Pricecf53df42020-04-20 14:41:24 -04001374 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001375 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1376 if (NumElements != cast<VectorType>(PredicateType)
1377 ->getElementCount()
1378 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001379 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001380 }
1381
James Pricecf53df42020-04-20 14:41:24 -04001382 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1383 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001384 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001385 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001386 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001387
SJW2c317da2020-03-23 07:39:13 -05001388 // Create constant
1389 const auto ZeroValue = Constant::getNullValue(PredicateType);
1390
1391 // Scalar and vector are to be treated differently
1392 CmpInst::Predicate Pred;
1393 if (PredicateType->isVectorTy()) {
1394 Pred = CmpInst::ICMP_SLT;
1395 } else {
1396 Pred = CmpInst::ICMP_NE;
1397 }
1398
1399 // Create comparison instruction
1400 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1401 ZeroValue, "", CI);
1402
1403 // Create select
1404 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1405 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001406}
1407
SJW2c317da2020-03-23 07:39:13 -05001408bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1409 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1410 Value *V = nullptr;
1411 if (CI->getNumOperands() != 4) {
1412 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001413 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001414
SJW2c317da2020-03-23 07:39:13 -05001415 // Get arguments
1416 auto FalseValue = CI->getOperand(0);
1417 auto TrueValue = CI->getOperand(1);
1418 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001419
SJW2c317da2020-03-23 07:39:13 -05001420 // Don't touch overloads that aren't in OpenCL C
1421 auto FalseType = FalseValue->getType();
1422 auto TrueType = TrueValue->getType();
1423 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001424
SJW2c317da2020-03-23 07:39:13 -05001425 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1426 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001427 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001428
James Pricecf53df42020-04-20 14:41:24 -04001429 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001430 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1431 !TrueType->getScalarType()->isIntegerTy()) {
1432 return V;
1433 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001434 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001435 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1436 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001437 return V;
1438 }
1439 }
1440
1441 // Remember the type of the operands
1442 auto OpType = TrueType;
1443
1444 // The actual bit selection will always be done on an integer type,
1445 // declare it here
1446 Type *BitType;
1447
1448 // If the operands are float, then bitcast them to int
1449 if (OpType->getScalarType()->isFloatingPointTy()) {
1450
1451 // First create the new type
1452 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1453
1454 // Then bitcast all operands
1455 PredicateValue =
1456 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1457 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1458 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1459
1460 } else {
1461 // The operands have an integer type, use it directly
1462 BitType = OpType;
1463 }
1464
1465 // All the operands are now always integers
1466 // implement as (c & b) | (~c & a)
1467
1468 // Create our negated predicate value
1469 auto AllOnes = Constant::getAllOnesValue(BitType);
1470 auto NotPredicateValue = BinaryOperator::Create(
1471 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1472
1473 // Then put everything together
1474 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1475 FalseValue, "", CI);
1476 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1477 TrueValue, "", CI);
1478
1479 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1480
1481 // If we were dealing with a floating point type, we must bitcast
1482 // the result back to that
1483 if (OpType->getScalarType()->isFloatingPointTy()) {
1484 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1485 }
1486
1487 return V;
1488 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001489}
1490
SJW61531372020-06-09 07:31:08 -05001491bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001492 // convert to vector versions
1493 Module &M = *F.getParent();
1494 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1495 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1496 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001497
SJW2c317da2020-03-23 07:39:13 -05001498 // First figure out which function we're dealing with
1499 if (is_smooth) {
1500 ArgsToSplat.push_back(CI->getOperand(1));
1501 VectorArg = CI->getOperand(2);
1502 } else {
1503 VectorArg = CI->getOperand(1);
1504 }
1505
1506 // Splat arguments that need to be
1507 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001508 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001509
1510 for (auto arg : ArgsToSplat) {
1511 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001512 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001513 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1514 NewVectorArg =
1515 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1516 }
1517 SplatArgs.push_back(NewVectorArg);
1518 }
1519
1520 // Replace the call with the vector/vector flavour
1521 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1522 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1523
SJW61531372020-06-09 07:31:08 -05001524 std::string NewFName = Builtins::GetMangledFunctionName(
1525 is_smooth ? "smoothstep" : "step", NewFType);
1526
SJW2c317da2020-03-23 07:39:13 -05001527 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1528
1529 SmallVector<Value *, 3> NewArgs;
1530 for (auto arg : SplatArgs) {
1531 NewArgs.push_back(arg);
1532 }
1533 NewArgs.push_back(VectorArg);
1534
1535 return CallInst::Create(NewF, NewArgs, "", CI);
1536 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001537}
1538
SJW2c317da2020-03-23 07:39:13 -05001539bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001540 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1541 auto Arg = CI->getOperand(0);
1542 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001543
SJW2c317da2020-03-23 07:39:13 -05001544 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001545
SJW2c317da2020-03-23 07:39:13 -05001546 return BinaryOperator::Create(Op, Bitcast,
1547 ConstantInt::get(CI->getType(), 31), "", CI);
1548 });
David Neto22f144c2017-06-12 14:26:21 -04001549}
1550
SJW2c317da2020-03-23 07:39:13 -05001551bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1552 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001553 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1554 // The multiply instruction to use.
1555 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001556
SJW2c317da2020-03-23 07:39:13 -05001557 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001558
SJW2c317da2020-03-23 07:39:13 -05001559 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1560 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001561
SJW2c317da2020-03-23 07:39:13 -05001562 if (is_mad) {
1563 // The add instruction to use.
1564 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001565
SJW2c317da2020-03-23 07:39:13 -05001566 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001567 }
David Neto22f144c2017-06-12 14:26:21 -04001568
SJW2c317da2020-03-23 07:39:13 -05001569 return V;
1570 });
David Neto22f144c2017-06-12 14:26:21 -04001571}
1572
SJW2c317da2020-03-23 07:39:13 -05001573bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001574 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1575 Value *V = nullptr;
1576 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001577
SJW2c317da2020-03-23 07:39:13 -05001578 auto data_type = data->getType();
1579 if (!data_type->isVectorTy())
1580 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001581
James Pricecf53df42020-04-20 14:41:24 -04001582 auto vec_data_type = cast<VectorType>(data_type);
1583
alan-baker5a8c3be2020-09-09 13:44:26 -04001584 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001585 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1586 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001587
SJW2c317da2020-03-23 07:39:13 -05001588 auto offset = CI->getOperand(1);
1589 auto ptr = CI->getOperand(2);
1590 auto ptr_type = ptr->getType();
1591 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001592 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001593 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001594
SJW2c317da2020-03-23 07:39:13 -05001595 // Avoid pointer casts. Instead generate the correct number of stores
1596 // and rely on drivers to coalesce appropriately.
1597 IRBuilder<> builder(CI);
1598 auto elems_const = builder.getInt32(elems);
1599 auto adjust = builder.CreateMul(offset, elems_const);
1600 for (auto i = 0; i < elems; ++i) {
1601 auto idx = builder.getInt32(i);
1602 auto add = builder.CreateAdd(adjust, idx);
1603 auto gep = builder.CreateGEP(ptr, add);
1604 auto extract = builder.CreateExtractElement(data, i);
1605 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001606 }
SJW2c317da2020-03-23 07:39:13 -05001607 return V;
1608 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001609}
1610
SJW2c317da2020-03-23 07:39:13 -05001611bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001612 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1613 Value *V = nullptr;
1614 auto ret_type = F.getReturnType();
1615 if (!ret_type->isVectorTy())
1616 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001617
James Pricecf53df42020-04-20 14:41:24 -04001618 auto vec_ret_type = cast<VectorType>(ret_type);
1619
alan-baker5a8c3be2020-09-09 13:44:26 -04001620 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001621 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1622 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001623
SJW2c317da2020-03-23 07:39:13 -05001624 auto offset = CI->getOperand(0);
1625 auto ptr = CI->getOperand(1);
1626 auto ptr_type = ptr->getType();
1627 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001628 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001629 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001630
SJW2c317da2020-03-23 07:39:13 -05001631 // Avoid pointer casts. Instead generate the correct number of loads
1632 // and rely on drivers to coalesce appropriately.
1633 IRBuilder<> builder(CI);
1634 auto elems_const = builder.getInt32(elems);
1635 V = UndefValue::get(ret_type);
1636 auto adjust = builder.CreateMul(offset, elems_const);
1637 for (auto i = 0; i < elems; ++i) {
1638 auto idx = builder.getInt32(i);
1639 auto add = builder.CreateAdd(adjust, idx);
1640 auto gep = builder.CreateGEP(ptr, add);
1641 auto load = builder.CreateLoad(gep);
1642 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001643 }
SJW2c317da2020-03-23 07:39:13 -05001644 return V;
1645 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001646}
1647
SJW2c317da2020-03-23 07:39:13 -05001648bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1649 const std::string &name,
1650 int vec_size) {
1651 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1652 if (!vec_size) {
1653 // deduce vec_size from last character of name (e.g. vload_half4)
1654 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001655 }
SJW2c317da2020-03-23 07:39:13 -05001656 switch (vec_size) {
1657 case 2:
1658 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1659 case 4:
1660 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1661 case 0:
1662 if (!is_clspv_version) {
1663 return replaceVloadHalf(F);
1664 }
1665 default:
1666 llvm_unreachable("Unsupported vload_half vector size");
1667 break;
1668 }
1669 return false;
David Neto22f144c2017-06-12 14:26:21 -04001670}
1671
SJW2c317da2020-03-23 07:39:13 -05001672bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1673 Module &M = *F.getParent();
1674 return replaceCallsWithValue(F, [&](CallInst *CI) {
1675 // The index argument from vload_half.
1676 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001677
SJW2c317da2020-03-23 07:39:13 -05001678 // The pointer argument from vload_half.
1679 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001680
SJW2c317da2020-03-23 07:39:13 -05001681 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001682 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001683 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1684
1685 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001686 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001687
1688 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1689
1690 Value *V = nullptr;
1691
alan-baker7efcaaa2020-05-06 19:33:27 -04001692 bool supports_16bit_storage = true;
1693 switch (Arg1->getType()->getPointerAddressSpace()) {
1694 case clspv::AddressSpace::Global:
1695 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1696 clspv::Option::StorageClass::kSSBO);
1697 break;
1698 case clspv::AddressSpace::Constant:
1699 if (clspv::Option::ConstantArgsInUniformBuffer())
1700 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1701 clspv::Option::StorageClass::kUBO);
1702 else
1703 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1704 clspv::Option::StorageClass::kSSBO);
1705 break;
1706 default:
1707 // Clspv will emit the Float16 capability if the half type is
1708 // encountered. That capability covers private and local addressspaces.
1709 break;
1710 }
1711
1712 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001713 auto ShortTy = Type::getInt16Ty(M.getContext());
1714 auto ShortPointerTy =
1715 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1716
1717 // Cast the half* pointer to short*.
1718 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1719
1720 // Index into the correct address of the casted pointer.
1721 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1722
1723 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001724 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001725
1726 // ZExt the short -> int.
1727 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1728
1729 // Get our float2.
1730 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1731
1732 // Extract out the bottom element which is our float result.
1733 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1734 } else {
1735 // Assume the pointer argument points to storage aligned to 32bits
1736 // or more.
1737 // TODO(dneto): Do more analysis to make sure this is true?
1738 //
1739 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1740 // with:
1741 //
1742 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1743 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1744 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1745 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1746 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1747 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1748 // x float> %converted, %index_is_odd32
1749
1750 auto IntPointerTy =
1751 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1752
1753 // Cast the base pointer to int*.
1754 // In a valid call (according to assumptions), this should get
1755 // optimized away in the simplify GEP pass.
1756 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1757
1758 auto One = ConstantInt::get(IntTy, 1);
1759 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1760 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1761
1762 // Index into the correct address of the casted pointer.
1763 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1764
1765 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001766 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001767
1768 // Get our float2.
1769 auto Call = CallInst::Create(NewF, Load, "", CI);
1770
1771 // Extract out the float result, where the element number is
1772 // determined by whether the original index was even or odd.
1773 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1774 }
1775 return V;
1776 });
1777}
1778
1779bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1780 Module &M = *F.getParent();
1781 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001782 // The index argument from vload_half.
1783 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001784
Kévin Petite8edce32019-04-10 14:23:32 +01001785 // The pointer argument from vload_half.
1786 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001787
Kévin Petite8edce32019-04-10 14:23:32 +01001788 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001789 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001790 auto NewPointerTy =
1791 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001792 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001793
Kévin Petite8edce32019-04-10 14:23:32 +01001794 // Cast the half* pointer to int*.
1795 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001796
Kévin Petite8edce32019-04-10 14:23:32 +01001797 // Index into the correct address of the casted pointer.
1798 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001799
Kévin Petite8edce32019-04-10 14:23:32 +01001800 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001801 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001802
Kévin Petite8edce32019-04-10 14:23:32 +01001803 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001804 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001805
Kévin Petite8edce32019-04-10 14:23:32 +01001806 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001807
Kévin Petite8edce32019-04-10 14:23:32 +01001808 // Get our float2.
1809 return CallInst::Create(NewF, Load, "", CI);
1810 });
David Neto22f144c2017-06-12 14:26:21 -04001811}
1812
SJW2c317da2020-03-23 07:39:13 -05001813bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1814 Module &M = *F.getParent();
1815 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001816 // The index argument from vload_half.
1817 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001818
Kévin Petite8edce32019-04-10 14:23:32 +01001819 // The pointer argument from vload_half.
1820 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001821
Kévin Petite8edce32019-04-10 14:23:32 +01001822 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001823 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1824 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001825 auto NewPointerTy =
1826 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001827 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001828
Kévin Petite8edce32019-04-10 14:23:32 +01001829 // Cast the half* pointer to int2*.
1830 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001831
Kévin Petite8edce32019-04-10 14:23:32 +01001832 // Index into the correct address of the casted pointer.
1833 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001834
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001836 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001837
Kévin Petite8edce32019-04-10 14:23:32 +01001838 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001839 auto X =
1840 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1841 auto Y =
1842 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001843
Kévin Petite8edce32019-04-10 14:23:32 +01001844 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001845 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001846
Kévin Petite8edce32019-04-10 14:23:32 +01001847 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001848
Kévin Petite8edce32019-04-10 14:23:32 +01001849 // Get the lower (x & y) components of our final float4.
1850 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001851
Kévin Petite8edce32019-04-10 14:23:32 +01001852 // Get the higher (z & w) components of our final float4.
1853 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001854
Kévin Petite8edce32019-04-10 14:23:32 +01001855 Constant *ShuffleMask[4] = {
1856 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1857 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001858
Kévin Petite8edce32019-04-10 14:23:32 +01001859 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001860 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1861 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001862 });
David Neto22f144c2017-06-12 14:26:21 -04001863}
1864
SJW2c317da2020-03-23 07:39:13 -05001865bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001866
1867 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1868 //
1869 // %u = load i32 %ptr
1870 // %fxy = call <2 x float> Unpack2xHalf(u)
1871 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001872 Module &M = *F.getParent();
1873 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001874 auto Index = CI->getOperand(0);
1875 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001876
Kévin Petite8edce32019-04-10 14:23:32 +01001877 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001878 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001879 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001880
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001881 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001882 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001883
Kévin Petite8edce32019-04-10 14:23:32 +01001884 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001885 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001886
Kévin Petite8edce32019-04-10 14:23:32 +01001887 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001888
Kévin Petite8edce32019-04-10 14:23:32 +01001889 // Get our final float2.
1890 return CallInst::Create(NewF, Load, "", CI);
1891 });
David Neto6ad93232018-06-07 15:42:58 -07001892}
1893
SJW2c317da2020-03-23 07:39:13 -05001894bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001895
1896 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1897 //
1898 // %u2 = load <2 x i32> %ptr
1899 // %u2xy = extractelement %u2, 0
1900 // %u2zw = extractelement %u2, 1
1901 // %fxy = call <2 x float> Unpack2xHalf(uint)
1902 // %fzw = call <2 x float> Unpack2xHalf(uint)
1903 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001904 Module &M = *F.getParent();
1905 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001906 auto Index = CI->getOperand(0);
1907 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001908
Kévin Petite8edce32019-04-10 14:23:32 +01001909 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001910 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1911 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001912 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001913
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001914 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001915 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001916
Kévin Petite8edce32019-04-10 14:23:32 +01001917 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001918 auto X =
1919 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1920 auto Y =
1921 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001922
Kévin Petite8edce32019-04-10 14:23:32 +01001923 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001924 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001925
Kévin Petite8edce32019-04-10 14:23:32 +01001926 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001927
Kévin Petite8edce32019-04-10 14:23:32 +01001928 // Get the lower (x & y) components of our final float4.
1929 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001930
Kévin Petite8edce32019-04-10 14:23:32 +01001931 // Get the higher (z & w) components of our final float4.
1932 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001933
Kévin Petite8edce32019-04-10 14:23:32 +01001934 Constant *ShuffleMask[4] = {
1935 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1936 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001937
Kévin Petite8edce32019-04-10 14:23:32 +01001938 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001939 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1940 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001941 });
David Neto6ad93232018-06-07 15:42:58 -07001942}
1943
SJW2c317da2020-03-23 07:39:13 -05001944bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1945 switch (vec_size) {
1946 case 0:
1947 return replaceVstoreHalf(F);
1948 case 2:
1949 return replaceVstoreHalf2(F);
1950 case 4:
1951 return replaceVstoreHalf4(F);
1952 default:
1953 llvm_unreachable("Unsupported vstore_half vector size");
1954 break;
1955 }
1956 return false;
1957}
David Neto22f144c2017-06-12 14:26:21 -04001958
SJW2c317da2020-03-23 07:39:13 -05001959bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1960 Module &M = *F.getParent();
1961 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001962 // The value to store.
1963 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001964
Kévin Petite8edce32019-04-10 14:23:32 +01001965 // The index argument from vstore_half.
1966 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001967
Kévin Petite8edce32019-04-10 14:23:32 +01001968 // The pointer argument from vstore_half.
1969 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001970
Kévin Petite8edce32019-04-10 14:23:32 +01001971 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001972 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001973 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1974 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001975
Kévin Petite8edce32019-04-10 14:23:32 +01001976 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001977 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001978
Kévin Petite8edce32019-04-10 14:23:32 +01001979 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001980
Kévin Petite8edce32019-04-10 14:23:32 +01001981 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001982 auto TempVec = InsertElementInst::Create(
1983 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001984
Kévin Petite8edce32019-04-10 14:23:32 +01001985 // Pack the float2 -> half2 (in an int).
1986 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001987
alan-baker7efcaaa2020-05-06 19:33:27 -04001988 bool supports_16bit_storage = true;
1989 switch (Arg2->getType()->getPointerAddressSpace()) {
1990 case clspv::AddressSpace::Global:
1991 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1992 clspv::Option::StorageClass::kSSBO);
1993 break;
1994 case clspv::AddressSpace::Constant:
1995 if (clspv::Option::ConstantArgsInUniformBuffer())
1996 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1997 clspv::Option::StorageClass::kUBO);
1998 else
1999 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2000 clspv::Option::StorageClass::kSSBO);
2001 break;
2002 default:
2003 // Clspv will emit the Float16 capability if the half type is
2004 // encountered. That capability covers private and local addressspaces.
2005 break;
2006 }
2007
SJW2c317da2020-03-23 07:39:13 -05002008 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04002009 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01002010 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002011 auto ShortPointerTy =
2012 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002013
Kévin Petite8edce32019-04-10 14:23:32 +01002014 // Truncate our i32 to an i16.
2015 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002016
Kévin Petite8edce32019-04-10 14:23:32 +01002017 // Cast the half* pointer to short*.
2018 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002019
Kévin Petite8edce32019-04-10 14:23:32 +01002020 // Index into the correct address of the casted pointer.
2021 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002022
Kévin Petite8edce32019-04-10 14:23:32 +01002023 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002024 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002025 } else {
2026 // We can only write to 32-bit aligned words.
2027 //
2028 // Assuming base is aligned to 32-bits, replace the equivalent of
2029 // vstore_half(value, index, base)
2030 // with:
2031 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2032 // uint32_t write_to_upper_half = index & 1u;
2033 // uint32_t shift = write_to_upper_half << 4;
2034 //
2035 // // Pack the float value as a half number in bottom 16 bits
2036 // // of an i32.
2037 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2038 //
2039 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2040 // ^ ((packed & 0xffff) << shift)
2041 // // We only need relaxed consistency, but OpenCL 1.2 only has
2042 // // sequentially consistent atomics.
2043 // // TODO(dneto): Use relaxed consistency.
2044 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002045 auto IntPointerTy =
2046 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002047
Kévin Petite8edce32019-04-10 14:23:32 +01002048 auto Four = ConstantInt::get(IntTy, 4);
2049 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002050
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002051 auto IndexIsOdd =
2052 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002053 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002054 auto IndexIntoI32 =
2055 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2056 auto BaseI32Ptr =
2057 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2058 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2059 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002060 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002061 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002062 auto MaskBitsToWrite =
2063 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2064 auto MaskedCurrent = BinaryOperator::CreateAnd(
2065 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002066
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002067 auto XLowerBits =
2068 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2069 auto NewBitsToWrite =
2070 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2071 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2072 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002073
Kévin Petite8edce32019-04-10 14:23:32 +01002074 // Generate the call to atomi_xor.
2075 SmallVector<Type *, 5> ParamTypes;
2076 // The pointer type.
2077 ParamTypes.push_back(IntPointerTy);
2078 // The Types for memory scope, semantics, and value.
2079 ParamTypes.push_back(IntTy);
2080 ParamTypes.push_back(IntTy);
2081 ParamTypes.push_back(IntTy);
2082 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2083 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002084
Kévin Petite8edce32019-04-10 14:23:32 +01002085 const auto ConstantScopeDevice =
2086 ConstantInt::get(IntTy, spv::ScopeDevice);
2087 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2088 // (SPIR-V Workgroup).
2089 const auto AddrSpaceSemanticsBits =
2090 IntPointerTy->getPointerAddressSpace() == 1
2091 ? spv::MemorySemanticsUniformMemoryMask
2092 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002093
Kévin Petite8edce32019-04-10 14:23:32 +01002094 // We're using relaxed consistency here.
2095 const auto ConstantMemorySemantics =
2096 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2097 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002098
Kévin Petite8edce32019-04-10 14:23:32 +01002099 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2100 ConstantMemorySemantics, ValueToXor};
2101 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002102
2103 // Return a Nop so the old Call is removed
2104 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2105 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002106 }
David Neto22f144c2017-06-12 14:26:21 -04002107
SJW2c317da2020-03-23 07:39:13 -05002108 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002109 });
David Neto22f144c2017-06-12 14:26:21 -04002110}
2111
SJW2c317da2020-03-23 07:39:13 -05002112bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2113 Module &M = *F.getParent();
2114 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002115 // The value to store.
2116 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002117
Kévin Petite8edce32019-04-10 14:23:32 +01002118 // The index argument from vstore_half.
2119 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002120
Kévin Petite8edce32019-04-10 14:23:32 +01002121 // The pointer argument from vstore_half.
2122 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002123
Kévin Petite8edce32019-04-10 14:23:32 +01002124 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002125 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002126 auto NewPointerTy =
2127 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002128 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002129
Kévin Petite8edce32019-04-10 14:23:32 +01002130 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002131 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002132
Kévin Petite8edce32019-04-10 14:23:32 +01002133 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002134
Kévin Petite8edce32019-04-10 14:23:32 +01002135 // Turn the packed x & y into the final packing.
2136 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002137
Kévin Petite8edce32019-04-10 14:23:32 +01002138 // Cast the half* pointer to int*.
2139 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002140
Kévin Petite8edce32019-04-10 14:23:32 +01002141 // Index into the correct address of the casted pointer.
2142 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002143
Kévin Petite8edce32019-04-10 14:23:32 +01002144 // Store to the int* we casted to.
2145 return new StoreInst(X, Index, CI);
2146 });
David Neto22f144c2017-06-12 14:26:21 -04002147}
2148
SJW2c317da2020-03-23 07:39:13 -05002149bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2150 Module &M = *F.getParent();
2151 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002152 // The value to store.
2153 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002154
Kévin Petite8edce32019-04-10 14:23:32 +01002155 // The index argument from vstore_half.
2156 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002157
Kévin Petite8edce32019-04-10 14:23:32 +01002158 // The pointer argument from vstore_half.
2159 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002160
Kévin Petite8edce32019-04-10 14:23:32 +01002161 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002162 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2163 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002164 auto NewPointerTy =
2165 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002166 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002167
Kévin Petite8edce32019-04-10 14:23:32 +01002168 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2169 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002170
Kévin Petite8edce32019-04-10 14:23:32 +01002171 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002172 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2173 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002174
Kévin Petite8edce32019-04-10 14:23:32 +01002175 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2176 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002177
Kévin Petite8edce32019-04-10 14:23:32 +01002178 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002179 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2180 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002181
Kévin Petite8edce32019-04-10 14:23:32 +01002182 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002183 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002184
Kévin Petite8edce32019-04-10 14:23:32 +01002185 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002186
Kévin Petite8edce32019-04-10 14:23:32 +01002187 // Turn the packed x & y into the final component of our int2.
2188 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002189
Kévin Petite8edce32019-04-10 14:23:32 +01002190 // Turn the packed z & w into the final component of our int2.
2191 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002192
Kévin Petite8edce32019-04-10 14:23:32 +01002193 auto Combine = InsertElementInst::Create(
2194 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002195 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2196 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002197
Kévin Petite8edce32019-04-10 14:23:32 +01002198 // Cast the half* pointer to int2*.
2199 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002200
Kévin Petite8edce32019-04-10 14:23:32 +01002201 // Index into the correct address of the casted pointer.
2202 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002203
Kévin Petite8edce32019-04-10 14:23:32 +01002204 // Store to the int2* we casted to.
2205 return new StoreInst(Combine, Index, CI);
2206 });
David Neto22f144c2017-06-12 14:26:21 -04002207}
2208
SJW2c317da2020-03-23 07:39:13 -05002209bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2210 // convert half to float
2211 Module &M = *F.getParent();
2212 return replaceCallsWithValue(F, [&](CallInst *CI) {
2213 SmallVector<Type *, 3> types;
2214 SmallVector<Value *, 3> args;
2215 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2216 types.push_back(CI->getArgOperand(i)->getType());
2217 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002218 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002219
alan-baker5a8c3be2020-09-09 13:44:26 -04002220 auto NewFType =
2221 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2222 cast<VectorType>(CI->getType())
2223 ->getElementCount()
2224 .getKnownMinValue()),
2225 types, false);
SJW2c317da2020-03-23 07:39:13 -05002226
SJW61531372020-06-09 07:31:08 -05002227 std::string NewFName =
2228 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002229
2230 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2231
2232 auto NewCI = CallInst::Create(NewF, args, "", CI);
2233
2234 // Convert to the half type.
2235 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2236 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002237}
2238
SJW2c317da2020-03-23 07:39:13 -05002239bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2240 // convert half to float
2241 Module &M = *F.getParent();
2242 return replaceCallsWithValue(F, [&](CallInst *CI) {
2243 SmallVector<Type *, 3> types(3);
2244 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002245
SJW2c317da2020-03-23 07:39:13 -05002246 // Image
2247 types[0] = CI->getArgOperand(0)->getType();
2248 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002249
SJW2c317da2020-03-23 07:39:13 -05002250 // Coord
2251 types[1] = CI->getArgOperand(1)->getType();
2252 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002253
SJW2c317da2020-03-23 07:39:13 -05002254 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002255 types[2] =
2256 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2257 cast<VectorType>(CI->getArgOperand(2)->getType())
2258 ->getElementCount()
2259 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002260
SJW2c317da2020-03-23 07:39:13 -05002261 auto NewFType =
2262 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002263
SJW61531372020-06-09 07:31:08 -05002264 std::string NewFName =
2265 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002266
SJW2c317da2020-03-23 07:39:13 -05002267 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002268
SJW2c317da2020-03-23 07:39:13 -05002269 // Convert data to the float type.
2270 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2271 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002272
SJW2c317da2020-03-23 07:39:13 -05002273 return CallInst::Create(NewF, args, "", CI);
2274 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002275}
2276
SJW2c317da2020-03-23 07:39:13 -05002277bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2278 Function &F) {
2279 // convert read_image with int coords to float coords
2280 Module &M = *F.getParent();
2281 return replaceCallsWithValue(F, [&](CallInst *CI) {
2282 // The image.
2283 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002284
SJW2c317da2020-03-23 07:39:13 -05002285 // The sampler.
2286 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002287
SJW2c317da2020-03-23 07:39:13 -05002288 // The coordinate (integer type that we can't handle).
2289 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002290
SJW2c317da2020-03-23 07:39:13 -05002291 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2292 uint32_t components =
2293 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2294 Type *float_ty = nullptr;
2295 if (components == 1) {
2296 float_ty = Type::getFloatTy(M.getContext());
2297 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002298 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2299 cast<VectorType>(Arg2->getType())
2300 ->getElementCount()
2301 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002302 }
David Neto22f144c2017-06-12 14:26:21 -04002303
SJW2c317da2020-03-23 07:39:13 -05002304 auto NewFType = FunctionType::get(
2305 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2306
2307 std::string NewFName = F.getName().str();
2308 NewFName[NewFName.length() - 1] = 'f';
2309
2310 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2311
2312 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2313
2314 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2315 });
David Neto22f144c2017-06-12 14:26:21 -04002316}
2317
SJW2c317da2020-03-23 07:39:13 -05002318bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2319 return replaceCallsWithValue(F, [&](CallInst *CI) {
2320 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002321
SJW2c317da2020-03-23 07:39:13 -05002322 // We need to map the OpenCL constants to the SPIR-V equivalents.
2323 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2324 const auto ConstantMemorySemantics = ConstantInt::get(
2325 IntTy, spv::MemorySemanticsUniformMemoryMask |
2326 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002327
SJW2c317da2020-03-23 07:39:13 -05002328 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002329
SJW2c317da2020-03-23 07:39:13 -05002330 // The pointer.
2331 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002332
SJW2c317da2020-03-23 07:39:13 -05002333 // The memory scope.
2334 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002335
SJW2c317da2020-03-23 07:39:13 -05002336 // The memory semantics.
2337 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002338
SJW2c317da2020-03-23 07:39:13 -05002339 if (2 < CI->getNumArgOperands()) {
2340 // The unequal memory semantics.
2341 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002342
SJW2c317da2020-03-23 07:39:13 -05002343 // The value.
2344 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002345
SJW2c317da2020-03-23 07:39:13 -05002346 // The comparator.
2347 Params.push_back(CI->getArgOperand(1));
2348 } else if (1 < CI->getNumArgOperands()) {
2349 // The value.
2350 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002351 }
David Neto22f144c2017-06-12 14:26:21 -04002352
SJW2c317da2020-03-23 07:39:13 -05002353 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2354 });
David Neto22f144c2017-06-12 14:26:21 -04002355}
2356
SJW2c317da2020-03-23 07:39:13 -05002357bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2358 llvm::AtomicRMWInst::BinOp Op) {
2359 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002360 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2361 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002362 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002363 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002364 SyncScope::System, CI);
2365 });
2366}
David Neto22f144c2017-06-12 14:26:21 -04002367
SJW2c317da2020-03-23 07:39:13 -05002368bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2369 Module &M = *F.getParent();
2370 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002371 auto IntTy = Type::getInt32Ty(M.getContext());
2372 auto FloatTy = Type::getFloatTy(M.getContext());
2373
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002374 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2375 ConstantInt::get(IntTy, 1),
2376 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002377
2378 Constant *UpShuffleMask[4] = {
2379 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2380 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2381
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002382 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2383 UndefValue::get(FloatTy),
2384 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002385
Kévin Petite8edce32019-04-10 14:23:32 +01002386 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002387 auto Arg0 =
2388 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2389 ConstantVector::get(DownShuffleMask), "", CI);
2390 auto Arg1 =
2391 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2392 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002393 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002394
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002395 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002396 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002397
SJW61531372020-06-09 07:31:08 -05002398 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002399
Kévin Petite8edce32019-04-10 14:23:32 +01002400 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002401
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002402 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2403 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002404 });
David Neto22f144c2017-06-12 14:26:21 -04002405}
David Neto62653202017-10-16 19:05:18 -04002406
SJW2c317da2020-03-23 07:39:13 -05002407bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002408 // OpenCL's float result = fract(float x, float* ptr)
2409 //
2410 // In the LLVM domain:
2411 //
2412 // %floor_result = call spir_func float @floor(float %x)
2413 // store float %floor_result, float * %ptr
2414 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2415 // %result = call spir_func float
2416 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2417 //
2418 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2419 // and clspv.fract occur in the SPIR-V generator pass:
2420 //
2421 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2422 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2423 // ...
2424 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2425 // OpStore %ptr %floor_result
2426 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2427 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002428 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002429
David Neto62653202017-10-16 19:05:18 -04002430 using std::string;
2431
2432 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2433 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002434
SJW2c317da2020-03-23 07:39:13 -05002435 Module &M = *F.getParent();
2436 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002437
SJW2c317da2020-03-23 07:39:13 -05002438 // This is either float or a float vector. All the float-like
2439 // types are this type.
2440 auto result_ty = F.getReturnType();
2441
SJW61531372020-06-09 07:31:08 -05002442 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002443 Function *fmin_fn = M.getFunction(fmin_name);
2444 if (!fmin_fn) {
2445 // Make the fmin function.
2446 FunctionType *fn_ty =
2447 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2448 fmin_fn =
2449 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2450 fmin_fn->addFnAttr(Attribute::ReadNone);
2451 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2452 }
2453
SJW61531372020-06-09 07:31:08 -05002454 std::string floor_name =
2455 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002456 Function *floor_fn = M.getFunction(floor_name);
2457 if (!floor_fn) {
2458 // Make the floor function.
2459 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2460 floor_fn =
2461 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2462 floor_fn->addFnAttr(Attribute::ReadNone);
2463 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2464 }
2465
SJW61531372020-06-09 07:31:08 -05002466 std::string clspv_fract_name =
2467 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002468 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2469 if (!clspv_fract_fn) {
2470 // Make the clspv_fract function.
2471 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2472 clspv_fract_fn = cast<Function>(
2473 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2474 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2475 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2476 }
2477
2478 // Number of significant significand bits, whether represented or not.
2479 unsigned num_significand_bits;
2480 switch (result_ty->getScalarType()->getTypeID()) {
2481 case Type::HalfTyID:
2482 num_significand_bits = 11;
2483 break;
2484 case Type::FloatTyID:
2485 num_significand_bits = 24;
2486 break;
2487 case Type::DoubleTyID:
2488 num_significand_bits = 53;
2489 break;
2490 default:
2491 llvm_unreachable("Unhandled float type when processing fract builtin");
2492 break;
2493 }
2494 // Beware that the disassembler displays this value as
2495 // OpConstant %float 1
2496 // which is not quite right.
2497 const double kJustUnderOneScalar =
2498 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2499
2500 Constant *just_under_one =
2501 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2502 if (result_ty->isVectorTy()) {
2503 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002504 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002505 }
2506
2507 IRBuilder<> Builder(CI);
2508
2509 auto arg = CI->getArgOperand(0);
2510 auto ptr = CI->getArgOperand(1);
2511
2512 // Compute floor result and store it.
2513 auto floor = Builder.CreateCall(floor_fn, {arg});
2514 Builder.CreateStore(floor, ptr);
2515
2516 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2517 auto fract_result =
2518 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2519
2520 return fract_result;
2521 });
David Neto62653202017-10-16 19:05:18 -04002522}
alan-bakera52b7312020-10-26 08:58:51 -04002523
2524bool ReplaceOpenCLBuiltinPass::replaceAddSat(Function &F, bool is_signed) {
2525 Module *module = F.getParent();
2526 return replaceCallsWithValue(F, [&module, is_signed](CallInst *Call) {
2527 // SPIR-V OpIAddCarry interprets inputs as unsigned. We use that
2528 // instruction for unsigned additions. For signed addition, it is more
2529 // complicated. For values with bit widths less than 32 bits, we extend
2530 // to the next power of two and perform the addition. For 32- and
2531 // 64-bit values we test the signedness of op1 to determine how to clamp
2532 // the addition.
2533 Type *ty = Call->getType();
2534 Value *op0 = Call->getArgOperand(0);
2535 Value *op1 = Call->getArgOperand(1);
2536 Value *result = nullptr;
2537 if (is_signed) {
2538 unsigned bitwidth = ty->getScalarSizeInBits();
2539 if (bitwidth < 32) {
2540 // sext_op0 = sext op0
2541 // sext_op1 = sext op1
2542 // add = add sext_op0 sext_op1
2543 // clamp = clamp(add, min, max)
2544 // result = trunc clamp
2545 unsigned extended_bits = static_cast<unsigned>(bitwidth << 1);
2546 // The clamp values are the signed min and max of the original bitwidth
2547 // sign extended to the extended bitwidth.
2548 Constant *scalar_min = ConstantInt::get(
2549 Call->getContext(),
2550 APInt::getSignedMinValue(bitwidth).sext(extended_bits));
2551 Constant *scalar_max = ConstantInt::get(
2552 Call->getContext(),
2553 APInt::getSignedMaxValue(bitwidth).sext(extended_bits));
2554 Constant *min = scalar_min;
2555 Constant *max = scalar_max;
2556 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2557 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2558 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2559 }
2560 Type *extended_scalar_ty =
2561 IntegerType::get(Call->getContext(), extended_bits);
2562 Type *extended_ty = extended_scalar_ty;
2563 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2564 extended_ty =
2565 VectorType::get(extended_scalar_ty, vec_ty->getElementCount());
2566 }
2567 auto sext_op0 =
2568 CastInst::Create(Instruction::SExt, op0, extended_ty, "", Call);
2569 auto sext_op1 =
2570 CastInst::Create(Instruction::SExt, op1, extended_ty, "", Call);
2571 // Add the nsw flag since we know no overflow can occur.
2572 auto add = BinaryOperator::CreateNSW(Instruction::Add, sext_op0,
2573 sext_op1, "", Call);
2574 FunctionType *func_ty = FunctionType::get(
2575 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2576
2577 // Don't use the type in GetMangledFunctionName to ensure we get
2578 // signed parameters.
2579 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
2580 uint32_t vec_width = 1;
2581 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2582 vec_width = vec_ty->getElementCount().getKnownMinValue();
2583 }
2584 if (extended_bits == 32) {
2585 if (vec_width == 1) {
2586 sclamp_name += "iii";
2587 } else {
2588 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2589 }
2590 } else {
2591 if (vec_width == 1) {
2592 sclamp_name += "sss";
2593 } else {
2594 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2595 }
2596 }
2597 auto sclamp_callee = module->getOrInsertFunction(sclamp_name, func_ty);
2598 auto clamp = CallInst::Create(sclamp_callee, {add, min, max}, "", Call);
2599 result = CastInst::Create(Instruction::Trunc, clamp, ty, "", Call);
2600 } else {
2601 // Pseudo-code:
2602 // c = a + b;
2603 // if (b < 0)
2604 // c = c > a ? min : c;
2605 // else
2606 // c = c < a ? max : c;
2607 //
2608 unsigned bitwidth = ty->getScalarSizeInBits();
2609 Constant *scalar_min = ConstantInt::get(
2610 Call->getContext(), APInt::getSignedMinValue(bitwidth));
2611 Constant *scalar_max = ConstantInt::get(
2612 Call->getContext(), APInt::getSignedMaxValue(bitwidth));
2613 Constant *min = scalar_min;
2614 Constant *max = scalar_max;
2615 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2616 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2617 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2618 }
2619 auto zero = Constant::getNullValue(ty);
2620 // Cannot add the nsw flag.
2621 auto add = BinaryOperator::Create(Instruction::Add, op0, op1, "", Call);
2622 auto add_gt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT,
2623 add, op0, "", Call);
2624 auto min_clamp = SelectInst::Create(add_gt_op0, min, add, "", Call);
2625 auto add_lt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2626 add, op0, "", Call);
2627 auto max_clamp = SelectInst::Create(add_lt_op0, max, add, "", Call);
2628 auto op1_lt_0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2629 op1, zero, "", Call);
2630 result = SelectInst::Create(op1_lt_0, min_clamp, max_clamp, "", Call);
2631 }
2632 } else {
2633 // Just use OpIAddCarry and use the carry to clamp the result.
2634 auto ret_ty = StructType::get(Call->getContext(), {ty, ty});
2635 auto add = clspv::InsertSPIRVOp(
2636 Call, spv::OpIAddCarry, {Attribute::ReadNone}, ret_ty, {op0, op1});
2637 auto ex0 = ExtractValueInst::Create(add, {0}, "", Call);
2638 auto ex1 = ExtractValueInst::Create(add, {1}, "", Call);
2639 auto cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, ex1,
2640 Constant::getNullValue(ty), "", Call);
2641 result =
2642 SelectInst::Create(cmp, ex0, Constant::getAllOnesValue(ty), "", Call);
2643 }
2644
2645 return result;
2646 });
2647}
alan-baker4986eff2020-10-29 13:38:00 -04002648
2649bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2650 return replaceCallsWithValue(F, [](CallInst *Call) {
2651 auto pointer = Call->getArgOperand(0);
2652 // Clang emits an address space cast to the generic address space. Skip the
2653 // cast and use the input directly.
2654 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2655 pointer = cast->getPointerOperand();
2656 }
2657 Value *order_arg =
2658 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2659 Value *scope_arg =
2660 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2661 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2662 clspv::AddressSpace::Global;
2663 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2664 spv::MemorySemanticsAcquireMask);
2665 auto scope = MemoryScope(scope_arg, is_global, Call);
2666 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2667 Call->getType(), {pointer, scope, order});
2668 });
2669}
2670
2671bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2672 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2673 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2674 auto pointer = Call->getArgOperand(0);
2675 // Clang emits an address space cast to the generic address space. Skip the
2676 // cast and use the input directly.
2677 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2678 pointer = cast->getPointerOperand();
2679 }
2680 Value *value = Call->getArgOperand(1);
2681 Value *order_arg =
2682 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2683 Value *scope_arg =
2684 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2685 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2686 clspv::AddressSpace::Global;
2687 auto scope = MemoryScope(scope_arg, is_global, Call);
2688 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2689 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2690 {pointer, scope, order, value});
2691 });
2692}
2693
2694bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2695 return replaceCallsWithValue(F, [](CallInst *Call) {
2696 auto pointer = Call->getArgOperand(0);
2697 // Clang emits an address space cast to the generic address space. Skip the
2698 // cast and use the input directly.
2699 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2700 pointer = cast->getPointerOperand();
2701 }
2702 auto expected = Call->getArgOperand(1);
2703 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2704 expected = cast->getPointerOperand();
2705 }
2706 auto value = Call->getArgOperand(2);
2707 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2708 clspv::AddressSpace::Global;
2709 Value *success_arg =
2710 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2711 Value *failure_arg =
2712 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2713 Value *scope_arg =
2714 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2715 auto scope = MemoryScope(scope_arg, is_global, Call);
2716 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2717 spv::MemorySemanticsAcquireReleaseMask);
2718 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2719 spv::MemorySemanticsAcquireMask);
2720
2721 // If the value pointed to by |expected| equals the value pointed to by
2722 // |pointer|, |value| is written into |pointer|, otherwise the value in
2723 // |pointer| is written into |expected|. In order to avoid extra stores,
2724 // the basic block with the original atomic is split and the store is
2725 // performed in the |then| block. The condition is the inversion of the
2726 // comparison result.
2727 IRBuilder<> builder(Call);
2728 auto load = builder.CreateLoad(expected);
2729 auto cmp_xchg = InsertSPIRVOp(
2730 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2731 value->getType(), {pointer, scope, success, failure, value, load});
2732 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2733 auto not_cmp = builder.CreateNot(cmp);
2734 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2735 builder.SetInsertPoint(then_branch);
2736 builder.CreateStore(cmp_xchg, expected);
2737 return cmp;
2738 });
2739}