blob: 40c66d3f420251a068ea288f9cfe4d5a3ec26b25 [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);
alan-bakerb6da5132020-10-29 15:59:06 -0400276 bool replaceHadd(Function &F, Instruction::BinaryOps join_opcode);
alan-bakercc2bafb2020-11-02 08:30:18 -0500277 bool replaceClz(Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400278};
SJW2c317da2020-03-23 07:39:13 -0500279
Kévin Petit91bc72e2019-04-08 15:17:46 +0100280} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400281
282char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400283INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
284 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400285
286namespace clspv {
287ModulePass *createReplaceOpenCLBuiltinPass() {
288 return new ReplaceOpenCLBuiltinPass();
289}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400290} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400291
292bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500293 std::list<Function *> func_list;
294 for (auto &F : M.getFunctionList()) {
295 // process only function declarations
296 if (F.isDeclaration() && runOnFunction(F)) {
297 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000298 }
299 }
SJW2c317da2020-03-23 07:39:13 -0500300 if (func_list.size() != 0) {
301 // recursively convert functions, but first remove dead
302 for (auto *F : func_list) {
303 if (F->use_empty()) {
304 F->eraseFromParent();
305 }
306 }
307 runOnModule(M);
308 return true;
309 }
310 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000311}
312
SJW2c317da2020-03-23 07:39:13 -0500313bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
314 auto &FI = Builtins::Lookup(&F);
315 switch (FI.getType()) {
316 case Builtins::kAbs:
317 if (!FI.getParameter(0).is_signed) {
318 return replaceAbs(F);
319 }
320 break;
321 case Builtins::kAbsDiff:
322 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400323
324 case Builtins::kAddSat:
325 return replaceAddSat(F, FI.getParameter(0).is_signed);
326
alan-bakercc2bafb2020-11-02 08:30:18 -0500327 case Builtins::kClz:
328 return replaceClz(F);
329
alan-bakerb6da5132020-10-29 15:59:06 -0400330 case Builtins::kHadd:
331 return replaceHadd(F, Instruction::And);
332 case Builtins::kRhadd:
333 return replaceHadd(F, Instruction::Or);
334
SJW2c317da2020-03-23 07:39:13 -0500335 case Builtins::kCopysign:
336 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100337
SJW2c317da2020-03-23 07:39:13 -0500338 case Builtins::kHalfRecip:
339 case Builtins::kNativeRecip:
340 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100341
SJW2c317da2020-03-23 07:39:13 -0500342 case Builtins::kHalfDivide:
343 case Builtins::kNativeDivide:
344 return replaceDivide(F);
345
346 case Builtins::kDot:
347 return replaceDot(F);
348
349 case Builtins::kExp10:
350 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500351 case Builtins::kNativeExp10:
352 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500353
354 case Builtins::kLog10:
355 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500356 case Builtins::kNativeLog10:
357 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500358
gnl21636e7992020-09-09 16:08:16 +0100359 case Builtins::kLog1p:
360 return replaceLog1p(F);
361
SJW2c317da2020-03-23 07:39:13 -0500362 case Builtins::kFmod:
363 return replaceFmod(F);
364
365 case Builtins::kBarrier:
366 case Builtins::kWorkGroupBarrier:
367 return replaceBarrier(F);
368
alan-baker12d2c182020-07-20 08:22:42 -0400369 case Builtins::kSubGroupBarrier:
370 return replaceBarrier(F, true);
371
SJW2c317da2020-03-23 07:39:13 -0500372 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400373 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500374 case Builtins::kReadMemFence:
375 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
376 case Builtins::kWriteMemFence:
377 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
378
379 // Relational
380 case Builtins::kIsequal:
381 return replaceRelational(F, CmpInst::FCMP_OEQ,
382 FI.getParameter(0).vector_size ? -1 : 1);
383 case Builtins::kIsgreater:
384 return replaceRelational(F, CmpInst::FCMP_OGT,
385 FI.getParameter(0).vector_size ? -1 : 1);
386 case Builtins::kIsgreaterequal:
387 return replaceRelational(F, CmpInst::FCMP_OGE,
388 FI.getParameter(0).vector_size ? -1 : 1);
389 case Builtins::kIsless:
390 return replaceRelational(F, CmpInst::FCMP_OLT,
391 FI.getParameter(0).vector_size ? -1 : 1);
392 case Builtins::kIslessequal:
393 return replaceRelational(F, CmpInst::FCMP_OLE,
394 FI.getParameter(0).vector_size ? -1 : 1);
395 case Builtins::kIsnotequal:
396 return replaceRelational(F, CmpInst::FCMP_ONE,
397 FI.getParameter(0).vector_size ? -1 : 1);
398
399 case Builtins::kIsinf: {
400 bool is_vec = FI.getParameter(0).vector_size != 0;
401 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
402 }
403 case Builtins::kIsnan: {
404 bool is_vec = FI.getParameter(0).vector_size != 0;
405 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
406 }
407
408 case Builtins::kIsfinite:
409 return replaceIsFinite(F);
410
411 case Builtins::kAll: {
412 bool is_vec = FI.getParameter(0).vector_size != 0;
413 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
414 }
415 case Builtins::kAny: {
416 bool is_vec = FI.getParameter(0).vector_size != 0;
417 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
418 }
419
420 case Builtins::kUpsample:
421 return replaceUpsample(F);
422
423 case Builtins::kRotate:
424 return replaceRotate(F);
425
426 case Builtins::kConvert:
427 return replaceConvert(F, FI.getParameter(0).is_signed,
428 FI.getReturnType().is_signed);
429
alan-baker4986eff2020-10-29 13:38:00 -0400430 // OpenCL 2.0 explicit atomics have different default scopes and semantics
431 // than legacy atomic functions.
432 case Builtins::kAtomicLoad:
433 case Builtins::kAtomicLoadExplicit:
434 return replaceAtomicLoad(F);
435 case Builtins::kAtomicStore:
436 case Builtins::kAtomicStoreExplicit:
437 return replaceExplicitAtomics(F, spv::OpAtomicStore,
438 spv::MemorySemanticsReleaseMask);
439 case Builtins::kAtomicExchange:
440 case Builtins::kAtomicExchangeExplicit:
441 return replaceExplicitAtomics(F, spv::OpAtomicExchange);
442 case Builtins::kAtomicFetchAdd:
443 case Builtins::kAtomicFetchAddExplicit:
444 return replaceExplicitAtomics(F, spv::OpAtomicIAdd);
445 case Builtins::kAtomicFetchSub:
446 case Builtins::kAtomicFetchSubExplicit:
447 return replaceExplicitAtomics(F, spv::OpAtomicISub);
448 case Builtins::kAtomicFetchOr:
449 case Builtins::kAtomicFetchOrExplicit:
450 return replaceExplicitAtomics(F, spv::OpAtomicOr);
451 case Builtins::kAtomicFetchXor:
452 case Builtins::kAtomicFetchXorExplicit:
453 return replaceExplicitAtomics(F, spv::OpAtomicXor);
454 case Builtins::kAtomicFetchAnd:
455 case Builtins::kAtomicFetchAndExplicit:
456 return replaceExplicitAtomics(F, spv::OpAtomicAnd);
457 case Builtins::kAtomicFetchMin:
458 case Builtins::kAtomicFetchMinExplicit:
459 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
460 ? spv::OpAtomicSMin
461 : spv::OpAtomicUMin);
462 case Builtins::kAtomicFetchMax:
463 case Builtins::kAtomicFetchMaxExplicit:
464 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
465 ? spv::OpAtomicSMax
466 : spv::OpAtomicUMax);
467 // Weak compare exchange is generated as strong compare exchange.
468 case Builtins::kAtomicCompareExchangeWeak:
469 case Builtins::kAtomicCompareExchangeWeakExplicit:
470 case Builtins::kAtomicCompareExchangeStrong:
471 case Builtins::kAtomicCompareExchangeStrongExplicit:
472 return replaceAtomicCompareExchange(F);
473
474 // Legacy atomic functions.
SJW2c317da2020-03-23 07:39:13 -0500475 case Builtins::kAtomicInc:
476 return replaceAtomics(F, spv::OpAtomicIIncrement);
477 case Builtins::kAtomicDec:
478 return replaceAtomics(F, spv::OpAtomicIDecrement);
479 case Builtins::kAtomicCmpxchg:
480 return replaceAtomics(F, spv::OpAtomicCompareExchange);
481 case Builtins::kAtomicAdd:
482 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
483 case Builtins::kAtomicSub:
484 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
485 case Builtins::kAtomicXchg:
486 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
487 case Builtins::kAtomicMin:
488 return replaceAtomics(F, FI.getParameter(0).is_signed
489 ? llvm::AtomicRMWInst::Min
490 : llvm::AtomicRMWInst::UMin);
491 case Builtins::kAtomicMax:
492 return replaceAtomics(F, FI.getParameter(0).is_signed
493 ? llvm::AtomicRMWInst::Max
494 : llvm::AtomicRMWInst::UMax);
495 case Builtins::kAtomicAnd:
496 return replaceAtomics(F, llvm::AtomicRMWInst::And);
497 case Builtins::kAtomicOr:
498 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
499 case Builtins::kAtomicXor:
500 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
501
502 case Builtins::kCross:
503 if (FI.getParameter(0).vector_size == 4) {
504 return replaceCross(F);
505 }
506 break;
507
508 case Builtins::kFract:
509 if (FI.getParameterCount()) {
510 return replaceFract(F, FI.getParameter(0).vector_size);
511 }
512 break;
513
514 case Builtins::kMadHi:
515 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
516 case Builtins::kMulHi:
517 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
518
519 case Builtins::kMad:
520 case Builtins::kMad24:
521 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
522 true);
523 case Builtins::kMul24:
524 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
525 false);
526
527 case Builtins::kSelect:
528 return replaceSelect(F);
529
530 case Builtins::kBitselect:
531 return replaceBitSelect(F);
532
533 case Builtins::kVload:
534 return replaceVload(F);
535
536 case Builtins::kVloadaHalf:
537 case Builtins::kVloadHalf:
538 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
539
540 case Builtins::kVstore:
541 return replaceVstore(F);
542
543 case Builtins::kVstoreHalf:
544 case Builtins::kVstoreaHalf:
545 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
546
547 case Builtins::kSmoothstep: {
548 int vec_size = FI.getLastParameter().vector_size;
549 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500550 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500551 }
552 break;
553 }
554 case Builtins::kStep: {
555 int vec_size = FI.getLastParameter().vector_size;
556 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500557 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500558 }
559 break;
560 }
561
562 case Builtins::kSignbit:
563 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
564
565 case Builtins::kReadImageh:
566 return replaceHalfReadImage(F);
567 case Builtins::kReadImagef:
568 case Builtins::kReadImagei:
569 case Builtins::kReadImageui: {
570 if (FI.getParameter(1).isSampler() &&
571 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
572 return replaceSampledReadImageWithIntCoords(F);
573 }
574 break;
575 }
576
577 case Builtins::kWriteImageh:
578 return replaceHalfWriteImage(F);
579
Kévin Petit1cb45112020-04-27 18:55:48 +0100580 case Builtins::kPrefetch:
581 return replacePrefetch(F);
582
SJW2c317da2020-03-23 07:39:13 -0500583 default:
584 break;
585 }
586
587 return false;
588}
589
590bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
591 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400592 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100593}
594
SJW2c317da2020-03-23 07:39:13 -0500595bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
596 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100597 auto XValue = CI->getOperand(0);
598 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100599
Kévin Petite8edce32019-04-10 14:23:32 +0100600 IRBuilder<> Builder(CI);
601 auto XmY = Builder.CreateSub(XValue, YValue);
602 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100603
SJW2c317da2020-03-23 07:39:13 -0500604 Value *Cmp = nullptr;
605 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100606 Cmp = Builder.CreateICmpSGT(YValue, XValue);
607 } else {
608 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100609 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100610
Kévin Petite8edce32019-04-10 14:23:32 +0100611 return Builder.CreateSelect(Cmp, YmX, XmY);
612 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100613}
614
SJW2c317da2020-03-23 07:39:13 -0500615bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
616 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100617 auto XValue = CI->getOperand(0);
618 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100619
Kévin Petite8edce32019-04-10 14:23:32 +0100620 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100621
SJW2c317da2020-03-23 07:39:13 -0500622 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400623 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400624 IntTy = FixedVectorType::get(
625 IntTy, vec_ty->getElementCount().getKnownMinValue());
Kévin Petit8c1be282019-04-02 19:34:25 +0100626 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100627
Kévin Petite8edce32019-04-10 14:23:32 +0100628 // Return X with the sign of Y
629
630 // Sign bit masks
631 auto SignBit = IntTy->getScalarSizeInBits() - 1;
632 auto SignBitMask = 1 << SignBit;
633 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
634 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
635
636 IRBuilder<> Builder(CI);
637
638 // Extract sign of Y
639 auto YInt = Builder.CreateBitCast(YValue, IntTy);
640 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
641
642 // Clear sign bit in X
643 auto XInt = Builder.CreateBitCast(XValue, IntTy);
644 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
645
646 // Insert sign bit of Y into X
647 auto NewXInt = Builder.CreateOr(XInt, YSign);
648
649 // And cast back to floating-point
650 return Builder.CreateBitCast(NewXInt, Ty);
651 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100652}
653
SJW2c317da2020-03-23 07:39:13 -0500654bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
655 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100656 // Recip has one arg.
657 auto Arg = CI->getOperand(0);
658 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
659 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
660 });
David Neto22f144c2017-06-12 14:26:21 -0400661}
662
SJW2c317da2020-03-23 07:39:13 -0500663bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
664 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100665 auto Op0 = CI->getOperand(0);
666 auto Op1 = CI->getOperand(1);
667 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
668 });
David Neto22f144c2017-06-12 14:26:21 -0400669}
670
SJW2c317da2020-03-23 07:39:13 -0500671bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
672 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100673 auto Op0 = CI->getOperand(0);
674 auto Op1 = CI->getOperand(1);
675
SJW2c317da2020-03-23 07:39:13 -0500676 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100677 if (Op0->getType()->isVectorTy()) {
678 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
679 CI->getType(), {Op0, Op1});
680 } else {
681 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
682 }
683
684 return V;
685 });
686}
687
SJW2c317da2020-03-23 07:39:13 -0500688bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500689 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500690 // convert to natural
691 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500692 std::string NewFName = basename.substr(0, slen);
693 NewFName =
694 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400695
SJW2c317da2020-03-23 07:39:13 -0500696 Module &M = *F.getParent();
697 return replaceCallsWithValue(F, [&](CallInst *CI) {
698 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
699
700 auto Arg = CI->getOperand(0);
701
702 // Constant of the natural log of 10 (ln(10)).
703 const double Ln10 =
704 2.302585092994045684017991454684364207601101488628772976033;
705
706 auto Mul = BinaryOperator::Create(
707 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
708
709 return CallInst::Create(NewF, Mul, "", CI);
710 });
David Neto22f144c2017-06-12 14:26:21 -0400711}
712
SJW2c317da2020-03-23 07:39:13 -0500713bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100714 // OpenCL fmod(x,y) is x - y * trunc(x/y)
715 // The sign for a non-zero result is taken from x.
716 // (Try an example.)
717 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500718 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100719 auto Op0 = CI->getOperand(0);
720 auto Op1 = CI->getOperand(1);
721 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
722 });
723}
724
SJW2c317da2020-03-23 07:39:13 -0500725bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500726 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500727 // convert to natural
728 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500729 std::string NewFName = basename.substr(0, slen);
730 NewFName =
731 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400732
SJW2c317da2020-03-23 07:39:13 -0500733 Module &M = *F.getParent();
734 return replaceCallsWithValue(F, [&](CallInst *CI) {
735 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
736
737 auto Arg = CI->getOperand(0);
738
739 // Constant of the reciprocal of the natural log of 10 (ln(10)).
740 const double Ln10 =
741 0.434294481903251827651128918916605082294397005803666566114;
742
743 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
744
745 return BinaryOperator::Create(Instruction::FMul,
746 ConstantFP::get(Arg->getType(), Ln10), NewCI,
747 "", CI);
748 });
David Neto22f144c2017-06-12 14:26:21 -0400749}
750
gnl21636e7992020-09-09 16:08:16 +0100751bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
752 // convert to natural
753 std::string NewFName =
754 Builtins::GetMangledFunctionName("log", F.getFunctionType());
755
756 Module &M = *F.getParent();
757 return replaceCallsWithValue(F, [&](CallInst *CI) {
758 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
759
760 auto Arg = CI->getOperand(0);
761
762 auto ArgP1 = BinaryOperator::Create(
763 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
764
765 return CallInst::Create(NewF, ArgP1, "", CI);
766 });
767}
768
alan-baker12d2c182020-07-20 08:22:42 -0400769bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400770
alan-bakerf6bc8252020-09-23 14:58:55 -0400771 enum {
772 CLK_LOCAL_MEM_FENCE = 0x01,
773 CLK_GLOBAL_MEM_FENCE = 0x02,
774 CLK_IMAGE_MEM_FENCE = 0x04
775 };
David Neto22f144c2017-06-12 14:26:21 -0400776
alan-baker12d2c182020-07-20 08:22:42 -0400777 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100778 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400779
Kévin Petitc4643922019-06-17 19:32:05 +0100780 // We need to map the OpenCL constants to the SPIR-V equivalents.
781 const auto LocalMemFence =
782 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
783 const auto GlobalMemFence =
784 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400785 const auto ImageMemFence =
786 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400787 const auto ConstantAcquireRelease = ConstantInt::get(
788 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100789 const auto ConstantScopeDevice =
790 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
791 const auto ConstantScopeWorkgroup =
792 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400793 const auto ConstantScopeSubgroup =
794 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400795
Kévin Petitc4643922019-06-17 19:32:05 +0100796 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
797 const auto LocalMemFenceMask =
798 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
799 const auto WorkgroupShiftAmount =
800 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
801 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
802 Instruction::Shl, LocalMemFenceMask,
803 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400804
Kévin Petitc4643922019-06-17 19:32:05 +0100805 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
806 const auto GlobalMemFenceMask =
807 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
808 const auto UniformShiftAmount =
809 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
810 const auto MemorySemanticsUniform = BinaryOperator::Create(
811 Instruction::Shl, GlobalMemFenceMask,
812 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400813
alan-bakerf6bc8252020-09-23 14:58:55 -0400814 // OpenCL 2.0
815 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
816 const auto ImageMemFenceMask =
817 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
818 const auto ImageShiftAmount =
819 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
820 const auto MemorySemanticsImage = BinaryOperator::Create(
821 Instruction::Shl, ImageMemFenceMask,
822 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
823
Kévin Petitc4643922019-06-17 19:32:05 +0100824 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400825 // MemorySemanticsSequentiallyConsistentMask.
826 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100827 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400828 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400829 auto MemorySemantics2 = BinaryOperator::Create(
830 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
831 auto MemorySemantics = BinaryOperator::Create(
832 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400833
alan-baker12d2c182020-07-20 08:22:42 -0400834 // If the memory scope is not specified explicitly, it is either Subgroup
835 // or Workgroup depending on the type of barrier.
836 Value *MemoryScope =
837 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
838 if (CI->data_operands_size() > 1) {
839 enum {
840 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
841 CL_MEMORY_SCOPE_DEVICE = 0x2,
842 CL_MEMORY_SCOPE_SUBGROUP = 0x4
843 };
844 // The call was given an explicit memory scope.
845 const auto MemoryScopeSubgroup =
846 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
847 const auto MemoryScopeDevice =
848 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400849
alan-baker12d2c182020-07-20 08:22:42 -0400850 auto Cmp =
851 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
852 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
853 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
854 ConstantScopeWorkgroup, "", CI);
855 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
856 MemoryScopeDevice, CI->getOperand(1), "", CI);
857 MemoryScope =
858 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
859 }
860
861 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
862 // the type of barrier;
863 const auto ExecutionScope =
864 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400865
Kévin Petitc4643922019-06-17 19:32:05 +0100866 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400867 {Attribute::NoDuplicate, Attribute::Convergent},
868 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100869 {ExecutionScope, MemoryScope, MemorySemantics});
870 });
David Neto22f144c2017-06-12 14:26:21 -0400871}
872
SJW2c317da2020-03-23 07:39:13 -0500873bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
874 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400875
SJW2c317da2020-03-23 07:39:13 -0500876 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400877 enum {
878 CLK_LOCAL_MEM_FENCE = 0x01,
879 CLK_GLOBAL_MEM_FENCE = 0x02,
880 CLK_IMAGE_MEM_FENCE = 0x04,
881 };
David Neto22f144c2017-06-12 14:26:21 -0400882
SJW2c317da2020-03-23 07:39:13 -0500883 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400884
SJW2c317da2020-03-23 07:39:13 -0500885 // We need to map the OpenCL constants to the SPIR-V equivalents.
886 const auto LocalMemFence =
887 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
888 const auto GlobalMemFence =
889 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400890 const auto ImageMemFence =
891 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500892 const auto ConstantMemorySemantics =
893 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400894 const auto ConstantScopeWorkgroup =
895 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400896
SJW2c317da2020-03-23 07:39:13 -0500897 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
898 const auto LocalMemFenceMask =
899 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
900 const auto WorkgroupShiftAmount =
901 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
902 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
903 Instruction::Shl, LocalMemFenceMask,
904 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400905
SJW2c317da2020-03-23 07:39:13 -0500906 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
907 const auto GlobalMemFenceMask =
908 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
909 const auto UniformShiftAmount =
910 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
911 const auto MemorySemanticsUniform = BinaryOperator::Create(
912 Instruction::Shl, GlobalMemFenceMask,
913 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400914
alan-bakerf6bc8252020-09-23 14:58:55 -0400915 // OpenCL 2.0
916 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
917 const auto ImageMemFenceMask =
918 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
919 const auto ImageShiftAmount =
920 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
921 const auto MemorySemanticsImage = BinaryOperator::Create(
922 Instruction::Shl, ImageMemFenceMask,
923 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
924
SJW2c317da2020-03-23 07:39:13 -0500925 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400926 // |semantics|.
927 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500928 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
929 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400930 auto MemorySemantics2 = BinaryOperator::Create(
931 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
932 auto MemorySemantics = BinaryOperator::Create(
933 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400934
alan-baker12d2c182020-07-20 08:22:42 -0400935 // Memory Scope is always workgroup.
936 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400937
alan-baker3d905692020-10-28 14:02:37 -0400938 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
939 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500940 {MemoryScope, MemorySemantics});
941 });
David Neto22f144c2017-06-12 14:26:21 -0400942}
943
Kévin Petit1cb45112020-04-27 18:55:48 +0100944bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
945 bool Changed = false;
946
947 SmallVector<Instruction *, 4> ToRemoves;
948
949 // Find all calls to the function
950 for (auto &U : F.uses()) {
951 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
952 ToRemoves.push_back(CI);
953 }
954 }
955
956 Changed = !ToRemoves.empty();
957
958 // Delete them
959 for (auto V : ToRemoves) {
960 V->eraseFromParent();
961 }
962
963 return Changed;
964}
965
SJW2c317da2020-03-23 07:39:13 -0500966bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
967 CmpInst::Predicate P,
968 int32_t C) {
969 return replaceCallsWithValue(F, [&](CallInst *CI) {
970 // The predicate to use in the CmpInst.
971 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400972
SJW2c317da2020-03-23 07:39:13 -0500973 // The value to return for true.
974 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400975
SJW2c317da2020-03-23 07:39:13 -0500976 // The value to return for false.
977 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400978
SJW2c317da2020-03-23 07:39:13 -0500979 auto Arg1 = CI->getOperand(0);
980 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400981
SJW2c317da2020-03-23 07:39:13 -0500982 const auto Cmp =
983 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400984
SJW2c317da2020-03-23 07:39:13 -0500985 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
986 });
David Neto22f144c2017-06-12 14:26:21 -0400987}
988
SJW2c317da2020-03-23 07:39:13 -0500989bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
990 spv::Op SPIRVOp,
991 int32_t C) {
992 Module &M = *F.getParent();
993 return replaceCallsWithValue(F, [&](CallInst *CI) {
994 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400995
SJW2c317da2020-03-23 07:39:13 -0500996 // The value to return for true.
997 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400998
SJW2c317da2020-03-23 07:39:13 -0500999 // The value to return for false.
1000 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -04001001
SJW2c317da2020-03-23 07:39:13 -05001002 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -04001003 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001004 CorrespondingBoolTy =
1005 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
1006 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04001007 }
David Neto22f144c2017-06-12 14:26:21 -04001008
SJW2c317da2020-03-23 07:39:13 -05001009 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
1010 CorrespondingBoolTy, {CI->getOperand(0)});
1011
1012 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
1013 });
David Neto22f144c2017-06-12 14:26:21 -04001014}
1015
SJW2c317da2020-03-23 07:39:13 -05001016bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
1017 Module &M = *F.getParent();
1018 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001019 auto &C = M.getContext();
1020 auto Val = CI->getOperand(0);
1021 auto ValTy = Val->getType();
1022 auto RetTy = CI->getType();
1023
1024 // Get a suitable integer type to represent the number
1025 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
1026
1027 // Create Mask
1028 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -05001029 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001030 switch (ScalarSize) {
1031 case 16:
1032 InfMask = ConstantInt::get(IntTy, 0x7C00U);
1033 break;
1034 case 32:
1035 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
1036 break;
1037 case 64:
1038 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
1039 break;
1040 default:
1041 llvm_unreachable("Unsupported floating-point type");
1042 }
1043
1044 IRBuilder<> Builder(CI);
1045
1046 // Bitcast to int
1047 auto ValInt = Builder.CreateBitCast(Val, IntTy);
1048
1049 // Mask and compare
1050 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
1051 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
1052
1053 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -05001054 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001055 if (ValTy->isVectorTy()) {
1056 RetTrue = ConstantInt::getSigned(RetTy, -1);
1057 } else {
1058 RetTrue = ConstantInt::get(RetTy, 1);
1059 }
1060 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
1061 });
1062}
1063
SJW2c317da2020-03-23 07:39:13 -05001064bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
1065 Module &M = *F.getParent();
1066 return replaceCallsWithValue(F, [&](CallInst *CI) {
1067 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001068
SJW2c317da2020-03-23 07:39:13 -05001069 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001070
SJW2c317da2020-03-23 07:39:13 -05001071 // If the argument is a 32-bit int, just use a shift
1072 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1073 V = BinaryOperator::Create(Instruction::LShr, Arg,
1074 ConstantInt::get(Arg->getType(), 31), "", CI);
1075 } else {
1076 // The value for zero to compare against.
1077 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -04001078
SJW2c317da2020-03-23 07:39:13 -05001079 // The value to return for true.
1080 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04001081
SJW2c317da2020-03-23 07:39:13 -05001082 // The value to return for false.
1083 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001084
SJW2c317da2020-03-23 07:39:13 -05001085 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
1086 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001087
SJW2c317da2020-03-23 07:39:13 -05001088 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04001089
SJW2c317da2020-03-23 07:39:13 -05001090 // If we have a function to call, call it!
1091 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -04001092
SJW2c317da2020-03-23 07:39:13 -05001093 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -04001094
SJW2c317da2020-03-23 07:39:13 -05001095 const auto NewCI = clspv::InsertSPIRVOp(
1096 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
1097 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -04001098
SJW2c317da2020-03-23 07:39:13 -05001099 } else {
1100 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -04001101 }
1102
SJW2c317da2020-03-23 07:39:13 -05001103 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001104 }
SJW2c317da2020-03-23 07:39:13 -05001105 return V;
1106 });
David Neto22f144c2017-06-12 14:26:21 -04001107}
1108
SJW2c317da2020-03-23 07:39:13 -05001109bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
1110 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1111 // Get arguments
1112 auto HiValue = CI->getOperand(0);
1113 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001114
SJW2c317da2020-03-23 07:39:13 -05001115 // Don't touch overloads that aren't in OpenCL C
1116 auto HiType = HiValue->getType();
1117 auto LoType = LoValue->getType();
1118
1119 if (HiType != LoType) {
1120 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001121 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001122
SJW2c317da2020-03-23 07:39:13 -05001123 if (!HiType->isIntOrIntVectorTy()) {
1124 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001125 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001126
SJW2c317da2020-03-23 07:39:13 -05001127 if (HiType->getScalarSizeInBits() * 2 !=
1128 CI->getType()->getScalarSizeInBits()) {
1129 return nullptr;
1130 }
1131
1132 if ((HiType->getScalarSizeInBits() != 8) &&
1133 (HiType->getScalarSizeInBits() != 16) &&
1134 (HiType->getScalarSizeInBits() != 32)) {
1135 return nullptr;
1136 }
1137
James Pricecf53df42020-04-20 14:41:24 -04001138 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001139 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001140 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1141 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001142 return nullptr;
1143 }
1144 }
1145
1146 // Convert both operands to the result type
1147 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1148 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
1149
1150 // Shift high operand
1151 auto ShiftAmount =
1152 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
1153 auto HiShifted =
1154 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
1155
1156 // OR both results
1157 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
1158 });
Kévin Petitbf0036c2019-03-06 13:57:10 +00001159}
1160
SJW2c317da2020-03-23 07:39:13 -05001161bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
1162 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1163 // Get arguments
1164 auto SrcValue = CI->getOperand(0);
1165 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001166
SJW2c317da2020-03-23 07:39:13 -05001167 // Don't touch overloads that aren't in OpenCL C
1168 auto SrcType = SrcValue->getType();
1169 auto RotType = RotAmount->getType();
1170
1171 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1172 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001173 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001174
SJW2c317da2020-03-23 07:39:13 -05001175 if (!SrcType->isIntOrIntVectorTy()) {
1176 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001177 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001178
SJW2c317da2020-03-23 07:39:13 -05001179 if ((SrcType->getScalarSizeInBits() != 8) &&
1180 (SrcType->getScalarSizeInBits() != 16) &&
1181 (SrcType->getScalarSizeInBits() != 32) &&
1182 (SrcType->getScalarSizeInBits() != 64)) {
1183 return nullptr;
1184 }
1185
James Pricecf53df42020-04-20 14:41:24 -04001186 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001187 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001188 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1189 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001190 return nullptr;
1191 }
1192 }
1193
alan-bakerfd22ae12020-10-29 15:59:22 -04001194 // Replace with LLVM's funnel shift left intrinsic because it is more
1195 // generic than rotate.
1196 Function *intrinsic =
1197 Intrinsic::getDeclaration(F.getParent(), Intrinsic::fshl, SrcType);
1198 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
1199 {SrcValue, SrcValue, RotAmount}, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001200 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001201}
1202
SJW2c317da2020-03-23 07:39:13 -05001203bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1204 bool DstIsSigned) {
1205 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1206 Value *V = nullptr;
1207 // Get arguments
1208 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001209
SJW2c317da2020-03-23 07:39:13 -05001210 // Don't touch overloads that aren't in OpenCL C
1211 auto SrcType = SrcValue->getType();
1212 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001213
SJW2c317da2020-03-23 07:39:13 -05001214 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1215 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1216 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001217 }
1218
James Pricecf53df42020-04-20 14:41:24 -04001219 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001220 unsigned SrcNumElements =
1221 SrcVecType->getElementCount().getKnownMinValue();
1222 unsigned DstNumElements =
1223 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001224 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001225 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001226 }
1227
James Pricecf53df42020-04-20 14:41:24 -04001228 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1229 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1230 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001231 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001232 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001233 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001234
SJW2c317da2020-03-23 07:39:13 -05001235 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1236 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1237
1238 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1239 bool DstIsInt = DstType->isIntOrIntVectorTy();
1240
1241 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1242 // Unnecessary cast operation.
1243 V = SrcValue;
1244 } else if (SrcIsFloat && DstIsFloat) {
1245 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1246 } else if (SrcIsFloat && DstIsInt) {
1247 if (DstIsSigned) {
1248 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1249 } else {
1250 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1251 }
1252 } else if (SrcIsInt && DstIsFloat) {
1253 if (SrcIsSigned) {
1254 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1255 } else {
1256 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1257 }
1258 } else if (SrcIsInt && DstIsInt) {
1259 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1260 } else {
1261 // Not something we're supposed to handle, just move on
1262 }
1263
1264 return V;
1265 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001266}
1267
SJW2c317da2020-03-23 07:39:13 -05001268bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1269 bool is_mad) {
1270 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1271 Value *V = nullptr;
1272 // Get arguments
1273 auto AValue = CI->getOperand(0);
1274 auto BValue = CI->getOperand(1);
1275 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001276
SJW2c317da2020-03-23 07:39:13 -05001277 // Don't touch overloads that aren't in OpenCL C
1278 auto AType = AValue->getType();
1279 auto BType = BValue->getType();
1280 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001281
SJW2c317da2020-03-23 07:39:13 -05001282 if ((AType != BType) || (CI->getType() != AType) ||
1283 (is_mad && (AType != CType))) {
1284 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001285 }
1286
SJW2c317da2020-03-23 07:39:13 -05001287 if (!AType->isIntOrIntVectorTy()) {
1288 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001289 }
Kévin Petit8a560882019-03-21 15:24:34 +00001290
SJW2c317da2020-03-23 07:39:13 -05001291 if ((AType->getScalarSizeInBits() != 8) &&
1292 (AType->getScalarSizeInBits() != 16) &&
1293 (AType->getScalarSizeInBits() != 32) &&
1294 (AType->getScalarSizeInBits() != 64)) {
1295 return V;
1296 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001297
James Pricecf53df42020-04-20 14:41:24 -04001298 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001299 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001300 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1301 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001302 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001303 }
1304 }
1305
SJW2c317da2020-03-23 07:39:13 -05001306 // Our SPIR-V op returns a struct, create a type for it
1307 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1308 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001309
SJW2c317da2020-03-23 07:39:13 -05001310 // Select the appropriate signed/unsigned SPIR-V op
1311 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1312
1313 // Call the SPIR-V op
1314 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1315 ExMulRetType, {AValue, BValue});
1316
1317 // Get the high part of the result
1318 unsigned Idxs[] = {1};
1319 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1320
1321 // If we're handling a mad_hi, add the third argument to the result
1322 if (is_mad) {
1323 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001324 }
1325
SJW2c317da2020-03-23 07:39:13 -05001326 return V;
1327 });
Kévin Petit8a560882019-03-21 15:24:34 +00001328}
1329
SJW2c317da2020-03-23 07:39:13 -05001330bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1331 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1332 // Get arguments
1333 auto FalseValue = CI->getOperand(0);
1334 auto TrueValue = CI->getOperand(1);
1335 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001336
SJW2c317da2020-03-23 07:39:13 -05001337 // Don't touch overloads that aren't in OpenCL C
1338 auto FalseType = FalseValue->getType();
1339 auto TrueType = TrueValue->getType();
1340 auto PredicateType = PredicateValue->getType();
1341
1342 if (FalseType != TrueType) {
1343 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001344 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001345
SJW2c317da2020-03-23 07:39:13 -05001346 if (!PredicateType->isIntOrIntVectorTy()) {
1347 return nullptr;
1348 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001349
SJW2c317da2020-03-23 07:39:13 -05001350 if (!FalseType->isIntOrIntVectorTy() &&
1351 !FalseType->getScalarType()->isFloatingPointTy()) {
1352 return nullptr;
1353 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001354
SJW2c317da2020-03-23 07:39:13 -05001355 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1356 return nullptr;
1357 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001358
SJW2c317da2020-03-23 07:39:13 -05001359 if (FalseType->getScalarSizeInBits() !=
1360 PredicateType->getScalarSizeInBits()) {
1361 return nullptr;
1362 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001363
James Pricecf53df42020-04-20 14:41:24 -04001364 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001365 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1366 if (NumElements != cast<VectorType>(PredicateType)
1367 ->getElementCount()
1368 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001369 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001370 }
1371
James Pricecf53df42020-04-20 14:41:24 -04001372 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1373 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001374 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001375 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001376 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001377
SJW2c317da2020-03-23 07:39:13 -05001378 // Create constant
1379 const auto ZeroValue = Constant::getNullValue(PredicateType);
1380
1381 // Scalar and vector are to be treated differently
1382 CmpInst::Predicate Pred;
1383 if (PredicateType->isVectorTy()) {
1384 Pred = CmpInst::ICMP_SLT;
1385 } else {
1386 Pred = CmpInst::ICMP_NE;
1387 }
1388
1389 // Create comparison instruction
1390 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1391 ZeroValue, "", CI);
1392
1393 // Create select
1394 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1395 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001396}
1397
SJW2c317da2020-03-23 07:39:13 -05001398bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1399 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1400 Value *V = nullptr;
1401 if (CI->getNumOperands() != 4) {
1402 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001403 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001404
SJW2c317da2020-03-23 07:39:13 -05001405 // Get arguments
1406 auto FalseValue = CI->getOperand(0);
1407 auto TrueValue = CI->getOperand(1);
1408 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001409
SJW2c317da2020-03-23 07:39:13 -05001410 // Don't touch overloads that aren't in OpenCL C
1411 auto FalseType = FalseValue->getType();
1412 auto TrueType = TrueValue->getType();
1413 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001414
SJW2c317da2020-03-23 07:39:13 -05001415 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1416 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001417 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001418
James Pricecf53df42020-04-20 14:41:24 -04001419 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001420 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1421 !TrueType->getScalarType()->isIntegerTy()) {
1422 return V;
1423 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001424 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001425 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1426 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001427 return V;
1428 }
1429 }
1430
1431 // Remember the type of the operands
1432 auto OpType = TrueType;
1433
1434 // The actual bit selection will always be done on an integer type,
1435 // declare it here
1436 Type *BitType;
1437
1438 // If the operands are float, then bitcast them to int
1439 if (OpType->getScalarType()->isFloatingPointTy()) {
1440
1441 // First create the new type
1442 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1443
1444 // Then bitcast all operands
1445 PredicateValue =
1446 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1447 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1448 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1449
1450 } else {
1451 // The operands have an integer type, use it directly
1452 BitType = OpType;
1453 }
1454
1455 // All the operands are now always integers
1456 // implement as (c & b) | (~c & a)
1457
1458 // Create our negated predicate value
1459 auto AllOnes = Constant::getAllOnesValue(BitType);
1460 auto NotPredicateValue = BinaryOperator::Create(
1461 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1462
1463 // Then put everything together
1464 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1465 FalseValue, "", CI);
1466 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1467 TrueValue, "", CI);
1468
1469 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1470
1471 // If we were dealing with a floating point type, we must bitcast
1472 // the result back to that
1473 if (OpType->getScalarType()->isFloatingPointTy()) {
1474 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1475 }
1476
1477 return V;
1478 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001479}
1480
SJW61531372020-06-09 07:31:08 -05001481bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001482 // convert to vector versions
1483 Module &M = *F.getParent();
1484 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1485 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1486 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001487
SJW2c317da2020-03-23 07:39:13 -05001488 // First figure out which function we're dealing with
1489 if (is_smooth) {
1490 ArgsToSplat.push_back(CI->getOperand(1));
1491 VectorArg = CI->getOperand(2);
1492 } else {
1493 VectorArg = CI->getOperand(1);
1494 }
1495
1496 // Splat arguments that need to be
1497 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001498 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001499
1500 for (auto arg : ArgsToSplat) {
1501 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001502 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001503 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1504 NewVectorArg =
1505 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1506 }
1507 SplatArgs.push_back(NewVectorArg);
1508 }
1509
1510 // Replace the call with the vector/vector flavour
1511 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1512 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1513
SJW61531372020-06-09 07:31:08 -05001514 std::string NewFName = Builtins::GetMangledFunctionName(
1515 is_smooth ? "smoothstep" : "step", NewFType);
1516
SJW2c317da2020-03-23 07:39:13 -05001517 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1518
1519 SmallVector<Value *, 3> NewArgs;
1520 for (auto arg : SplatArgs) {
1521 NewArgs.push_back(arg);
1522 }
1523 NewArgs.push_back(VectorArg);
1524
1525 return CallInst::Create(NewF, NewArgs, "", CI);
1526 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001527}
1528
SJW2c317da2020-03-23 07:39:13 -05001529bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001530 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1531 auto Arg = CI->getOperand(0);
1532 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001533
SJW2c317da2020-03-23 07:39:13 -05001534 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001535
SJW2c317da2020-03-23 07:39:13 -05001536 return BinaryOperator::Create(Op, Bitcast,
1537 ConstantInt::get(CI->getType(), 31), "", CI);
1538 });
David Neto22f144c2017-06-12 14:26:21 -04001539}
1540
SJW2c317da2020-03-23 07:39:13 -05001541bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1542 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001543 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1544 // The multiply instruction to use.
1545 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001546
SJW2c317da2020-03-23 07:39:13 -05001547 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001548
SJW2c317da2020-03-23 07:39:13 -05001549 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1550 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001551
SJW2c317da2020-03-23 07:39:13 -05001552 if (is_mad) {
1553 // The add instruction to use.
1554 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001555
SJW2c317da2020-03-23 07:39:13 -05001556 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001557 }
David Neto22f144c2017-06-12 14:26:21 -04001558
SJW2c317da2020-03-23 07:39:13 -05001559 return V;
1560 });
David Neto22f144c2017-06-12 14:26:21 -04001561}
1562
SJW2c317da2020-03-23 07:39:13 -05001563bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001564 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1565 Value *V = nullptr;
1566 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001567
SJW2c317da2020-03-23 07:39:13 -05001568 auto data_type = data->getType();
1569 if (!data_type->isVectorTy())
1570 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001571
James Pricecf53df42020-04-20 14:41:24 -04001572 auto vec_data_type = cast<VectorType>(data_type);
1573
alan-baker5a8c3be2020-09-09 13:44:26 -04001574 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001575 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1576 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001577
SJW2c317da2020-03-23 07:39:13 -05001578 auto offset = CI->getOperand(1);
1579 auto ptr = CI->getOperand(2);
1580 auto ptr_type = ptr->getType();
1581 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001582 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001583 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001584
SJW2c317da2020-03-23 07:39:13 -05001585 // Avoid pointer casts. Instead generate the correct number of stores
1586 // and rely on drivers to coalesce appropriately.
1587 IRBuilder<> builder(CI);
1588 auto elems_const = builder.getInt32(elems);
1589 auto adjust = builder.CreateMul(offset, elems_const);
1590 for (auto i = 0; i < elems; ++i) {
1591 auto idx = builder.getInt32(i);
1592 auto add = builder.CreateAdd(adjust, idx);
1593 auto gep = builder.CreateGEP(ptr, add);
1594 auto extract = builder.CreateExtractElement(data, i);
1595 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001596 }
SJW2c317da2020-03-23 07:39:13 -05001597 return V;
1598 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001599}
1600
SJW2c317da2020-03-23 07:39:13 -05001601bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001602 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1603 Value *V = nullptr;
1604 auto ret_type = F.getReturnType();
1605 if (!ret_type->isVectorTy())
1606 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001607
James Pricecf53df42020-04-20 14:41:24 -04001608 auto vec_ret_type = cast<VectorType>(ret_type);
1609
alan-baker5a8c3be2020-09-09 13:44:26 -04001610 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001611 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1612 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001613
SJW2c317da2020-03-23 07:39:13 -05001614 auto offset = CI->getOperand(0);
1615 auto ptr = CI->getOperand(1);
1616 auto ptr_type = ptr->getType();
1617 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001618 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001619 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001620
SJW2c317da2020-03-23 07:39:13 -05001621 // Avoid pointer casts. Instead generate the correct number of loads
1622 // and rely on drivers to coalesce appropriately.
1623 IRBuilder<> builder(CI);
1624 auto elems_const = builder.getInt32(elems);
1625 V = UndefValue::get(ret_type);
1626 auto adjust = builder.CreateMul(offset, elems_const);
1627 for (auto i = 0; i < elems; ++i) {
1628 auto idx = builder.getInt32(i);
1629 auto add = builder.CreateAdd(adjust, idx);
1630 auto gep = builder.CreateGEP(ptr, add);
1631 auto load = builder.CreateLoad(gep);
1632 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001633 }
SJW2c317da2020-03-23 07:39:13 -05001634 return V;
1635 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001636}
1637
SJW2c317da2020-03-23 07:39:13 -05001638bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1639 const std::string &name,
1640 int vec_size) {
1641 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1642 if (!vec_size) {
1643 // deduce vec_size from last character of name (e.g. vload_half4)
1644 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001645 }
SJW2c317da2020-03-23 07:39:13 -05001646 switch (vec_size) {
1647 case 2:
1648 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1649 case 4:
1650 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1651 case 0:
1652 if (!is_clspv_version) {
1653 return replaceVloadHalf(F);
1654 }
1655 default:
1656 llvm_unreachable("Unsupported vload_half vector size");
1657 break;
1658 }
1659 return false;
David Neto22f144c2017-06-12 14:26:21 -04001660}
1661
SJW2c317da2020-03-23 07:39:13 -05001662bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1663 Module &M = *F.getParent();
1664 return replaceCallsWithValue(F, [&](CallInst *CI) {
1665 // The index argument from vload_half.
1666 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001667
SJW2c317da2020-03-23 07:39:13 -05001668 // The pointer argument from vload_half.
1669 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001670
SJW2c317da2020-03-23 07:39:13 -05001671 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001672 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001673 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1674
1675 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001676 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001677
1678 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1679
1680 Value *V = nullptr;
1681
alan-baker7efcaaa2020-05-06 19:33:27 -04001682 bool supports_16bit_storage = true;
1683 switch (Arg1->getType()->getPointerAddressSpace()) {
1684 case clspv::AddressSpace::Global:
1685 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1686 clspv::Option::StorageClass::kSSBO);
1687 break;
1688 case clspv::AddressSpace::Constant:
1689 if (clspv::Option::ConstantArgsInUniformBuffer())
1690 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1691 clspv::Option::StorageClass::kUBO);
1692 else
1693 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1694 clspv::Option::StorageClass::kSSBO);
1695 break;
1696 default:
1697 // Clspv will emit the Float16 capability if the half type is
1698 // encountered. That capability covers private and local addressspaces.
1699 break;
1700 }
1701
1702 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001703 auto ShortTy = Type::getInt16Ty(M.getContext());
1704 auto ShortPointerTy =
1705 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1706
1707 // Cast the half* pointer to short*.
1708 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1709
1710 // Index into the correct address of the casted pointer.
1711 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1712
1713 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001714 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001715
1716 // ZExt the short -> int.
1717 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1718
1719 // Get our float2.
1720 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1721
1722 // Extract out the bottom element which is our float result.
1723 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1724 } else {
1725 // Assume the pointer argument points to storage aligned to 32bits
1726 // or more.
1727 // TODO(dneto): Do more analysis to make sure this is true?
1728 //
1729 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1730 // with:
1731 //
1732 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1733 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1734 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1735 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1736 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1737 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1738 // x float> %converted, %index_is_odd32
1739
1740 auto IntPointerTy =
1741 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1742
1743 // Cast the base pointer to int*.
1744 // In a valid call (according to assumptions), this should get
1745 // optimized away in the simplify GEP pass.
1746 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1747
1748 auto One = ConstantInt::get(IntTy, 1);
1749 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1750 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1751
1752 // Index into the correct address of the casted pointer.
1753 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1754
1755 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001756 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001757
1758 // Get our float2.
1759 auto Call = CallInst::Create(NewF, Load, "", CI);
1760
1761 // Extract out the float result, where the element number is
1762 // determined by whether the original index was even or odd.
1763 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1764 }
1765 return V;
1766 });
1767}
1768
1769bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1770 Module &M = *F.getParent();
1771 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001772 // The index argument from vload_half.
1773 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001774
Kévin Petite8edce32019-04-10 14:23:32 +01001775 // The pointer argument from vload_half.
1776 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001777
Kévin Petite8edce32019-04-10 14:23:32 +01001778 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001779 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001780 auto NewPointerTy =
1781 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001782 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001783
Kévin Petite8edce32019-04-10 14:23:32 +01001784 // Cast the half* pointer to int*.
1785 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001786
Kévin Petite8edce32019-04-10 14:23:32 +01001787 // Index into the correct address of the casted pointer.
1788 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001789
Kévin Petite8edce32019-04-10 14:23:32 +01001790 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001791 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001792
Kévin Petite8edce32019-04-10 14:23:32 +01001793 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001794 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001795
Kévin Petite8edce32019-04-10 14:23:32 +01001796 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001797
Kévin Petite8edce32019-04-10 14:23:32 +01001798 // Get our float2.
1799 return CallInst::Create(NewF, Load, "", CI);
1800 });
David Neto22f144c2017-06-12 14:26:21 -04001801}
1802
SJW2c317da2020-03-23 07:39:13 -05001803bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1804 Module &M = *F.getParent();
1805 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001806 // The index argument from vload_half.
1807 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001808
Kévin Petite8edce32019-04-10 14:23:32 +01001809 // The pointer argument from vload_half.
1810 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001811
Kévin Petite8edce32019-04-10 14:23:32 +01001812 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001813 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1814 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001815 auto NewPointerTy =
1816 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001817 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001818
Kévin Petite8edce32019-04-10 14:23:32 +01001819 // Cast the half* pointer to int2*.
1820 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001821
Kévin Petite8edce32019-04-10 14:23:32 +01001822 // Index into the correct address of the casted pointer.
1823 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001824
Kévin Petite8edce32019-04-10 14:23:32 +01001825 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001826 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001827
Kévin Petite8edce32019-04-10 14:23:32 +01001828 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001829 auto X =
1830 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1831 auto Y =
1832 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001833
Kévin Petite8edce32019-04-10 14:23:32 +01001834 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001835 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001836
Kévin Petite8edce32019-04-10 14:23:32 +01001837 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001838
Kévin Petite8edce32019-04-10 14:23:32 +01001839 // Get the lower (x & y) components of our final float4.
1840 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001841
Kévin Petite8edce32019-04-10 14:23:32 +01001842 // Get the higher (z & w) components of our final float4.
1843 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001844
Kévin Petite8edce32019-04-10 14:23:32 +01001845 Constant *ShuffleMask[4] = {
1846 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1847 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001848
Kévin Petite8edce32019-04-10 14:23:32 +01001849 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001850 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1851 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001852 });
David Neto22f144c2017-06-12 14:26:21 -04001853}
1854
SJW2c317da2020-03-23 07:39:13 -05001855bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001856
1857 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1858 //
1859 // %u = load i32 %ptr
1860 // %fxy = call <2 x float> Unpack2xHalf(u)
1861 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001862 Module &M = *F.getParent();
1863 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001864 auto Index = CI->getOperand(0);
1865 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001866
Kévin Petite8edce32019-04-10 14:23:32 +01001867 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001868 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001869 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001870
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001871 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001872 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001873
Kévin Petite8edce32019-04-10 14:23:32 +01001874 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001875 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001876
Kévin Petite8edce32019-04-10 14:23:32 +01001877 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001878
Kévin Petite8edce32019-04-10 14:23:32 +01001879 // Get our final float2.
1880 return CallInst::Create(NewF, Load, "", CI);
1881 });
David Neto6ad93232018-06-07 15:42:58 -07001882}
1883
SJW2c317da2020-03-23 07:39:13 -05001884bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001885
1886 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1887 //
1888 // %u2 = load <2 x i32> %ptr
1889 // %u2xy = extractelement %u2, 0
1890 // %u2zw = extractelement %u2, 1
1891 // %fxy = call <2 x float> Unpack2xHalf(uint)
1892 // %fzw = call <2 x float> Unpack2xHalf(uint)
1893 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001894 Module &M = *F.getParent();
1895 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001896 auto Index = CI->getOperand(0);
1897 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001898
Kévin Petite8edce32019-04-10 14:23:32 +01001899 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001900 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1901 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001902 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001903
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001904 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001905 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001906
Kévin Petite8edce32019-04-10 14:23:32 +01001907 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001908 auto X =
1909 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1910 auto Y =
1911 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001912
Kévin Petite8edce32019-04-10 14:23:32 +01001913 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001914 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001915
Kévin Petite8edce32019-04-10 14:23:32 +01001916 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001917
Kévin Petite8edce32019-04-10 14:23:32 +01001918 // Get the lower (x & y) components of our final float4.
1919 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001920
Kévin Petite8edce32019-04-10 14:23:32 +01001921 // Get the higher (z & w) components of our final float4.
1922 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001923
Kévin Petite8edce32019-04-10 14:23:32 +01001924 Constant *ShuffleMask[4] = {
1925 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1926 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001927
Kévin Petite8edce32019-04-10 14:23:32 +01001928 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001929 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1930 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001931 });
David Neto6ad93232018-06-07 15:42:58 -07001932}
1933
SJW2c317da2020-03-23 07:39:13 -05001934bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1935 switch (vec_size) {
1936 case 0:
1937 return replaceVstoreHalf(F);
1938 case 2:
1939 return replaceVstoreHalf2(F);
1940 case 4:
1941 return replaceVstoreHalf4(F);
1942 default:
1943 llvm_unreachable("Unsupported vstore_half vector size");
1944 break;
1945 }
1946 return false;
1947}
David Neto22f144c2017-06-12 14:26:21 -04001948
SJW2c317da2020-03-23 07:39:13 -05001949bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1950 Module &M = *F.getParent();
1951 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001952 // The value to store.
1953 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001954
Kévin Petite8edce32019-04-10 14:23:32 +01001955 // The index argument from vstore_half.
1956 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001957
Kévin Petite8edce32019-04-10 14:23:32 +01001958 // The pointer argument from vstore_half.
1959 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001960
Kévin Petite8edce32019-04-10 14:23:32 +01001961 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001962 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001963 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1964 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001965
Kévin Petite8edce32019-04-10 14:23:32 +01001966 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001967 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001968
Kévin Petite8edce32019-04-10 14:23:32 +01001969 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001970
Kévin Petite8edce32019-04-10 14:23:32 +01001971 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001972 auto TempVec = InsertElementInst::Create(
1973 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001974
Kévin Petite8edce32019-04-10 14:23:32 +01001975 // Pack the float2 -> half2 (in an int).
1976 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001977
alan-baker7efcaaa2020-05-06 19:33:27 -04001978 bool supports_16bit_storage = true;
1979 switch (Arg2->getType()->getPointerAddressSpace()) {
1980 case clspv::AddressSpace::Global:
1981 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1982 clspv::Option::StorageClass::kSSBO);
1983 break;
1984 case clspv::AddressSpace::Constant:
1985 if (clspv::Option::ConstantArgsInUniformBuffer())
1986 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1987 clspv::Option::StorageClass::kUBO);
1988 else
1989 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1990 clspv::Option::StorageClass::kSSBO);
1991 break;
1992 default:
1993 // Clspv will emit the Float16 capability if the half type is
1994 // encountered. That capability covers private and local addressspaces.
1995 break;
1996 }
1997
SJW2c317da2020-03-23 07:39:13 -05001998 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04001999 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01002000 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002001 auto ShortPointerTy =
2002 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002003
Kévin Petite8edce32019-04-10 14:23:32 +01002004 // Truncate our i32 to an i16.
2005 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002006
Kévin Petite8edce32019-04-10 14:23:32 +01002007 // Cast the half* pointer to short*.
2008 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002009
Kévin Petite8edce32019-04-10 14:23:32 +01002010 // Index into the correct address of the casted pointer.
2011 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002012
Kévin Petite8edce32019-04-10 14:23:32 +01002013 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002014 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002015 } else {
2016 // We can only write to 32-bit aligned words.
2017 //
2018 // Assuming base is aligned to 32-bits, replace the equivalent of
2019 // vstore_half(value, index, base)
2020 // with:
2021 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2022 // uint32_t write_to_upper_half = index & 1u;
2023 // uint32_t shift = write_to_upper_half << 4;
2024 //
2025 // // Pack the float value as a half number in bottom 16 bits
2026 // // of an i32.
2027 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2028 //
2029 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2030 // ^ ((packed & 0xffff) << shift)
2031 // // We only need relaxed consistency, but OpenCL 1.2 only has
2032 // // sequentially consistent atomics.
2033 // // TODO(dneto): Use relaxed consistency.
2034 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002035 auto IntPointerTy =
2036 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002037
Kévin Petite8edce32019-04-10 14:23:32 +01002038 auto Four = ConstantInt::get(IntTy, 4);
2039 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002040
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002041 auto IndexIsOdd =
2042 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002043 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002044 auto IndexIntoI32 =
2045 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2046 auto BaseI32Ptr =
2047 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2048 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2049 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002050 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002051 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002052 auto MaskBitsToWrite =
2053 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2054 auto MaskedCurrent = BinaryOperator::CreateAnd(
2055 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002056
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002057 auto XLowerBits =
2058 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2059 auto NewBitsToWrite =
2060 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2061 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2062 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002063
Kévin Petite8edce32019-04-10 14:23:32 +01002064 // Generate the call to atomi_xor.
2065 SmallVector<Type *, 5> ParamTypes;
2066 // The pointer type.
2067 ParamTypes.push_back(IntPointerTy);
2068 // The Types for memory scope, semantics, and value.
2069 ParamTypes.push_back(IntTy);
2070 ParamTypes.push_back(IntTy);
2071 ParamTypes.push_back(IntTy);
2072 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2073 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002074
Kévin Petite8edce32019-04-10 14:23:32 +01002075 const auto ConstantScopeDevice =
2076 ConstantInt::get(IntTy, spv::ScopeDevice);
2077 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2078 // (SPIR-V Workgroup).
2079 const auto AddrSpaceSemanticsBits =
2080 IntPointerTy->getPointerAddressSpace() == 1
2081 ? spv::MemorySemanticsUniformMemoryMask
2082 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002083
Kévin Petite8edce32019-04-10 14:23:32 +01002084 // We're using relaxed consistency here.
2085 const auto ConstantMemorySemantics =
2086 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2087 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002088
Kévin Petite8edce32019-04-10 14:23:32 +01002089 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2090 ConstantMemorySemantics, ValueToXor};
2091 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002092
2093 // Return a Nop so the old Call is removed
2094 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2095 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002096 }
David Neto22f144c2017-06-12 14:26:21 -04002097
SJW2c317da2020-03-23 07:39:13 -05002098 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002099 });
David Neto22f144c2017-06-12 14:26:21 -04002100}
2101
SJW2c317da2020-03-23 07:39:13 -05002102bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2103 Module &M = *F.getParent();
2104 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002105 // The value to store.
2106 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002107
Kévin Petite8edce32019-04-10 14:23:32 +01002108 // The index argument from vstore_half.
2109 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002110
Kévin Petite8edce32019-04-10 14:23:32 +01002111 // The pointer argument from vstore_half.
2112 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002113
Kévin Petite8edce32019-04-10 14:23:32 +01002114 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002115 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002116 auto NewPointerTy =
2117 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002118 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002119
Kévin Petite8edce32019-04-10 14:23:32 +01002120 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002121 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002122
Kévin Petite8edce32019-04-10 14:23:32 +01002123 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002124
Kévin Petite8edce32019-04-10 14:23:32 +01002125 // Turn the packed x & y into the final packing.
2126 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002127
Kévin Petite8edce32019-04-10 14:23:32 +01002128 // Cast the half* pointer to int*.
2129 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002130
Kévin Petite8edce32019-04-10 14:23:32 +01002131 // Index into the correct address of the casted pointer.
2132 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002133
Kévin Petite8edce32019-04-10 14:23:32 +01002134 // Store to the int* we casted to.
2135 return new StoreInst(X, Index, CI);
2136 });
David Neto22f144c2017-06-12 14:26:21 -04002137}
2138
SJW2c317da2020-03-23 07:39:13 -05002139bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2140 Module &M = *F.getParent();
2141 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002142 // The value to store.
2143 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002144
Kévin Petite8edce32019-04-10 14:23:32 +01002145 // The index argument from vstore_half.
2146 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002147
Kévin Petite8edce32019-04-10 14:23:32 +01002148 // The pointer argument from vstore_half.
2149 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002150
Kévin Petite8edce32019-04-10 14:23:32 +01002151 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002152 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2153 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002154 auto NewPointerTy =
2155 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002156 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002157
Kévin Petite8edce32019-04-10 14:23:32 +01002158 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2159 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002160
Kévin Petite8edce32019-04-10 14:23:32 +01002161 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002162 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2163 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002164
Kévin Petite8edce32019-04-10 14:23:32 +01002165 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2166 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002167
Kévin Petite8edce32019-04-10 14:23:32 +01002168 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002169 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2170 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002171
Kévin Petite8edce32019-04-10 14:23:32 +01002172 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002173 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002174
Kévin Petite8edce32019-04-10 14:23:32 +01002175 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002176
Kévin Petite8edce32019-04-10 14:23:32 +01002177 // Turn the packed x & y into the final component of our int2.
2178 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002179
Kévin Petite8edce32019-04-10 14:23:32 +01002180 // Turn the packed z & w into the final component of our int2.
2181 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002182
Kévin Petite8edce32019-04-10 14:23:32 +01002183 auto Combine = InsertElementInst::Create(
2184 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002185 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2186 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002187
Kévin Petite8edce32019-04-10 14:23:32 +01002188 // Cast the half* pointer to int2*.
2189 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002190
Kévin Petite8edce32019-04-10 14:23:32 +01002191 // Index into the correct address of the casted pointer.
2192 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002193
Kévin Petite8edce32019-04-10 14:23:32 +01002194 // Store to the int2* we casted to.
2195 return new StoreInst(Combine, Index, CI);
2196 });
David Neto22f144c2017-06-12 14:26:21 -04002197}
2198
SJW2c317da2020-03-23 07:39:13 -05002199bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2200 // convert half to float
2201 Module &M = *F.getParent();
2202 return replaceCallsWithValue(F, [&](CallInst *CI) {
2203 SmallVector<Type *, 3> types;
2204 SmallVector<Value *, 3> args;
2205 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2206 types.push_back(CI->getArgOperand(i)->getType());
2207 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002208 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002209
alan-baker5a8c3be2020-09-09 13:44:26 -04002210 auto NewFType =
2211 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2212 cast<VectorType>(CI->getType())
2213 ->getElementCount()
2214 .getKnownMinValue()),
2215 types, false);
SJW2c317da2020-03-23 07:39:13 -05002216
SJW61531372020-06-09 07:31:08 -05002217 std::string NewFName =
2218 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002219
2220 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2221
2222 auto NewCI = CallInst::Create(NewF, args, "", CI);
2223
2224 // Convert to the half type.
2225 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2226 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002227}
2228
SJW2c317da2020-03-23 07:39:13 -05002229bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2230 // convert half to float
2231 Module &M = *F.getParent();
2232 return replaceCallsWithValue(F, [&](CallInst *CI) {
2233 SmallVector<Type *, 3> types(3);
2234 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002235
SJW2c317da2020-03-23 07:39:13 -05002236 // Image
2237 types[0] = CI->getArgOperand(0)->getType();
2238 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002239
SJW2c317da2020-03-23 07:39:13 -05002240 // Coord
2241 types[1] = CI->getArgOperand(1)->getType();
2242 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002243
SJW2c317da2020-03-23 07:39:13 -05002244 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002245 types[2] =
2246 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2247 cast<VectorType>(CI->getArgOperand(2)->getType())
2248 ->getElementCount()
2249 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002250
SJW2c317da2020-03-23 07:39:13 -05002251 auto NewFType =
2252 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002253
SJW61531372020-06-09 07:31:08 -05002254 std::string NewFName =
2255 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002256
SJW2c317da2020-03-23 07:39:13 -05002257 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002258
SJW2c317da2020-03-23 07:39:13 -05002259 // Convert data to the float type.
2260 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2261 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002262
SJW2c317da2020-03-23 07:39:13 -05002263 return CallInst::Create(NewF, args, "", CI);
2264 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002265}
2266
SJW2c317da2020-03-23 07:39:13 -05002267bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2268 Function &F) {
2269 // convert read_image with int coords to float coords
2270 Module &M = *F.getParent();
2271 return replaceCallsWithValue(F, [&](CallInst *CI) {
2272 // The image.
2273 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002274
SJW2c317da2020-03-23 07:39:13 -05002275 // The sampler.
2276 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002277
SJW2c317da2020-03-23 07:39:13 -05002278 // The coordinate (integer type that we can't handle).
2279 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002280
SJW2c317da2020-03-23 07:39:13 -05002281 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2282 uint32_t components =
2283 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2284 Type *float_ty = nullptr;
2285 if (components == 1) {
2286 float_ty = Type::getFloatTy(M.getContext());
2287 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002288 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2289 cast<VectorType>(Arg2->getType())
2290 ->getElementCount()
2291 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002292 }
David Neto22f144c2017-06-12 14:26:21 -04002293
SJW2c317da2020-03-23 07:39:13 -05002294 auto NewFType = FunctionType::get(
2295 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2296
2297 std::string NewFName = F.getName().str();
2298 NewFName[NewFName.length() - 1] = 'f';
2299
2300 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2301
2302 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2303
2304 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2305 });
David Neto22f144c2017-06-12 14:26:21 -04002306}
2307
SJW2c317da2020-03-23 07:39:13 -05002308bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2309 return replaceCallsWithValue(F, [&](CallInst *CI) {
2310 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002311
SJW2c317da2020-03-23 07:39:13 -05002312 // We need to map the OpenCL constants to the SPIR-V equivalents.
2313 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2314 const auto ConstantMemorySemantics = ConstantInt::get(
2315 IntTy, spv::MemorySemanticsUniformMemoryMask |
2316 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002317
SJW2c317da2020-03-23 07:39:13 -05002318 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002319
SJW2c317da2020-03-23 07:39:13 -05002320 // The pointer.
2321 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002322
SJW2c317da2020-03-23 07:39:13 -05002323 // The memory scope.
2324 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002325
SJW2c317da2020-03-23 07:39:13 -05002326 // The memory semantics.
2327 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002328
SJW2c317da2020-03-23 07:39:13 -05002329 if (2 < CI->getNumArgOperands()) {
2330 // The unequal memory semantics.
2331 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002332
SJW2c317da2020-03-23 07:39:13 -05002333 // The value.
2334 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002335
SJW2c317da2020-03-23 07:39:13 -05002336 // The comparator.
2337 Params.push_back(CI->getArgOperand(1));
2338 } else if (1 < CI->getNumArgOperands()) {
2339 // The value.
2340 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002341 }
David Neto22f144c2017-06-12 14:26:21 -04002342
SJW2c317da2020-03-23 07:39:13 -05002343 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2344 });
David Neto22f144c2017-06-12 14:26:21 -04002345}
2346
SJW2c317da2020-03-23 07:39:13 -05002347bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2348 llvm::AtomicRMWInst::BinOp Op) {
2349 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002350 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2351 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002352 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002353 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002354 SyncScope::System, CI);
2355 });
2356}
David Neto22f144c2017-06-12 14:26:21 -04002357
SJW2c317da2020-03-23 07:39:13 -05002358bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2359 Module &M = *F.getParent();
2360 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002361 auto IntTy = Type::getInt32Ty(M.getContext());
2362 auto FloatTy = Type::getFloatTy(M.getContext());
2363
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002364 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2365 ConstantInt::get(IntTy, 1),
2366 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002367
2368 Constant *UpShuffleMask[4] = {
2369 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2370 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2371
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002372 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2373 UndefValue::get(FloatTy),
2374 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002375
Kévin Petite8edce32019-04-10 14:23:32 +01002376 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002377 auto Arg0 =
2378 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2379 ConstantVector::get(DownShuffleMask), "", CI);
2380 auto Arg1 =
2381 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2382 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002383 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002384
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002385 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002386 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002387
SJW61531372020-06-09 07:31:08 -05002388 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002389
Kévin Petite8edce32019-04-10 14:23:32 +01002390 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002391
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002392 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2393 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002394 });
David Neto22f144c2017-06-12 14:26:21 -04002395}
David Neto62653202017-10-16 19:05:18 -04002396
SJW2c317da2020-03-23 07:39:13 -05002397bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002398 // OpenCL's float result = fract(float x, float* ptr)
2399 //
2400 // In the LLVM domain:
2401 //
2402 // %floor_result = call spir_func float @floor(float %x)
2403 // store float %floor_result, float * %ptr
2404 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2405 // %result = call spir_func float
2406 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2407 //
2408 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2409 // and clspv.fract occur in the SPIR-V generator pass:
2410 //
2411 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2412 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2413 // ...
2414 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2415 // OpStore %ptr %floor_result
2416 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2417 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002418 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002419
David Neto62653202017-10-16 19:05:18 -04002420 using std::string;
2421
2422 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2423 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002424
SJW2c317da2020-03-23 07:39:13 -05002425 Module &M = *F.getParent();
2426 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002427
SJW2c317da2020-03-23 07:39:13 -05002428 // This is either float or a float vector. All the float-like
2429 // types are this type.
2430 auto result_ty = F.getReturnType();
2431
SJW61531372020-06-09 07:31:08 -05002432 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002433 Function *fmin_fn = M.getFunction(fmin_name);
2434 if (!fmin_fn) {
2435 // Make the fmin function.
2436 FunctionType *fn_ty =
2437 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2438 fmin_fn =
2439 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2440 fmin_fn->addFnAttr(Attribute::ReadNone);
2441 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2442 }
2443
SJW61531372020-06-09 07:31:08 -05002444 std::string floor_name =
2445 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002446 Function *floor_fn = M.getFunction(floor_name);
2447 if (!floor_fn) {
2448 // Make the floor function.
2449 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2450 floor_fn =
2451 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2452 floor_fn->addFnAttr(Attribute::ReadNone);
2453 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2454 }
2455
SJW61531372020-06-09 07:31:08 -05002456 std::string clspv_fract_name =
2457 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002458 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2459 if (!clspv_fract_fn) {
2460 // Make the clspv_fract function.
2461 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2462 clspv_fract_fn = cast<Function>(
2463 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2464 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2465 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2466 }
2467
2468 // Number of significant significand bits, whether represented or not.
2469 unsigned num_significand_bits;
2470 switch (result_ty->getScalarType()->getTypeID()) {
2471 case Type::HalfTyID:
2472 num_significand_bits = 11;
2473 break;
2474 case Type::FloatTyID:
2475 num_significand_bits = 24;
2476 break;
2477 case Type::DoubleTyID:
2478 num_significand_bits = 53;
2479 break;
2480 default:
2481 llvm_unreachable("Unhandled float type when processing fract builtin");
2482 break;
2483 }
2484 // Beware that the disassembler displays this value as
2485 // OpConstant %float 1
2486 // which is not quite right.
2487 const double kJustUnderOneScalar =
2488 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2489
2490 Constant *just_under_one =
2491 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2492 if (result_ty->isVectorTy()) {
2493 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002494 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002495 }
2496
2497 IRBuilder<> Builder(CI);
2498
2499 auto arg = CI->getArgOperand(0);
2500 auto ptr = CI->getArgOperand(1);
2501
2502 // Compute floor result and store it.
2503 auto floor = Builder.CreateCall(floor_fn, {arg});
2504 Builder.CreateStore(floor, ptr);
2505
2506 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2507 auto fract_result =
2508 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2509
2510 return fract_result;
2511 });
David Neto62653202017-10-16 19:05:18 -04002512}
alan-bakera52b7312020-10-26 08:58:51 -04002513
alan-bakerb6da5132020-10-29 15:59:06 -04002514bool ReplaceOpenCLBuiltinPass::replaceHadd(Function &F,
2515 Instruction::BinaryOps join_opcode) {
2516 return replaceCallsWithValue(F, [join_opcode](CallInst *Call) {
2517 // a_shr = a >> 1
2518 // b_shr = b >> 1
2519 // add1 = a_shr + b_shr
2520 // join = a |join_opcode| b
2521 // and = join & 1
2522 // add = add1 + and
2523 const auto a = Call->getArgOperand(0);
2524 const auto b = Call->getArgOperand(1);
2525 IRBuilder<> builder(Call);
2526 auto a_shift = builder.CreateLShr(a, 1);
2527 auto b_shift = builder.CreateLShr(b, 1);
2528 auto add = builder.CreateAdd(a_shift, b_shift);
2529 auto join = BinaryOperator::Create(join_opcode, a, b, "", Call);
2530 auto constant_one = ConstantInt::get(a->getType(), 1);
2531 auto and_bit = builder.CreateAnd(join, constant_one);
2532 return builder.CreateAdd(add, and_bit);
2533 });
2534}
2535
alan-bakera52b7312020-10-26 08:58:51 -04002536bool ReplaceOpenCLBuiltinPass::replaceAddSat(Function &F, bool is_signed) {
2537 Module *module = F.getParent();
2538 return replaceCallsWithValue(F, [&module, is_signed](CallInst *Call) {
2539 // SPIR-V OpIAddCarry interprets inputs as unsigned. We use that
2540 // instruction for unsigned additions. For signed addition, it is more
2541 // complicated. For values with bit widths less than 32 bits, we extend
2542 // to the next power of two and perform the addition. For 32- and
2543 // 64-bit values we test the signedness of op1 to determine how to clamp
2544 // the addition.
2545 Type *ty = Call->getType();
2546 Value *op0 = Call->getArgOperand(0);
2547 Value *op1 = Call->getArgOperand(1);
2548 Value *result = nullptr;
2549 if (is_signed) {
2550 unsigned bitwidth = ty->getScalarSizeInBits();
2551 if (bitwidth < 32) {
2552 // sext_op0 = sext op0
2553 // sext_op1 = sext op1
2554 // add = add sext_op0 sext_op1
2555 // clamp = clamp(add, min, max)
2556 // result = trunc clamp
2557 unsigned extended_bits = static_cast<unsigned>(bitwidth << 1);
2558 // The clamp values are the signed min and max of the original bitwidth
2559 // sign extended to the extended bitwidth.
2560 Constant *scalar_min = ConstantInt::get(
2561 Call->getContext(),
2562 APInt::getSignedMinValue(bitwidth).sext(extended_bits));
2563 Constant *scalar_max = ConstantInt::get(
2564 Call->getContext(),
2565 APInt::getSignedMaxValue(bitwidth).sext(extended_bits));
2566 Constant *min = scalar_min;
2567 Constant *max = scalar_max;
2568 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2569 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2570 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2571 }
2572 Type *extended_scalar_ty =
2573 IntegerType::get(Call->getContext(), extended_bits);
2574 Type *extended_ty = extended_scalar_ty;
2575 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2576 extended_ty =
2577 VectorType::get(extended_scalar_ty, vec_ty->getElementCount());
2578 }
2579 auto sext_op0 =
2580 CastInst::Create(Instruction::SExt, op0, extended_ty, "", Call);
2581 auto sext_op1 =
2582 CastInst::Create(Instruction::SExt, op1, extended_ty, "", Call);
2583 // Add the nsw flag since we know no overflow can occur.
2584 auto add = BinaryOperator::CreateNSW(Instruction::Add, sext_op0,
2585 sext_op1, "", Call);
2586 FunctionType *func_ty = FunctionType::get(
2587 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2588
2589 // Don't use the type in GetMangledFunctionName to ensure we get
2590 // signed parameters.
2591 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
2592 uint32_t vec_width = 1;
2593 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2594 vec_width = vec_ty->getElementCount().getKnownMinValue();
2595 }
2596 if (extended_bits == 32) {
2597 if (vec_width == 1) {
2598 sclamp_name += "iii";
2599 } else {
2600 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2601 }
2602 } else {
2603 if (vec_width == 1) {
2604 sclamp_name += "sss";
2605 } else {
2606 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2607 }
2608 }
2609 auto sclamp_callee = module->getOrInsertFunction(sclamp_name, func_ty);
2610 auto clamp = CallInst::Create(sclamp_callee, {add, min, max}, "", Call);
2611 result = CastInst::Create(Instruction::Trunc, clamp, ty, "", Call);
2612 } else {
2613 // Pseudo-code:
2614 // c = a + b;
2615 // if (b < 0)
2616 // c = c > a ? min : c;
2617 // else
2618 // c = c < a ? max : c;
2619 //
2620 unsigned bitwidth = ty->getScalarSizeInBits();
2621 Constant *scalar_min = ConstantInt::get(
2622 Call->getContext(), APInt::getSignedMinValue(bitwidth));
2623 Constant *scalar_max = ConstantInt::get(
2624 Call->getContext(), APInt::getSignedMaxValue(bitwidth));
2625 Constant *min = scalar_min;
2626 Constant *max = scalar_max;
2627 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2628 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2629 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2630 }
2631 auto zero = Constant::getNullValue(ty);
2632 // Cannot add the nsw flag.
2633 auto add = BinaryOperator::Create(Instruction::Add, op0, op1, "", Call);
2634 auto add_gt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT,
2635 add, op0, "", Call);
2636 auto min_clamp = SelectInst::Create(add_gt_op0, min, add, "", Call);
2637 auto add_lt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2638 add, op0, "", Call);
2639 auto max_clamp = SelectInst::Create(add_lt_op0, max, add, "", Call);
2640 auto op1_lt_0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2641 op1, zero, "", Call);
2642 result = SelectInst::Create(op1_lt_0, min_clamp, max_clamp, "", Call);
2643 }
2644 } else {
2645 // Just use OpIAddCarry and use the carry to clamp the result.
2646 auto ret_ty = StructType::get(Call->getContext(), {ty, ty});
2647 auto add = clspv::InsertSPIRVOp(
2648 Call, spv::OpIAddCarry, {Attribute::ReadNone}, ret_ty, {op0, op1});
2649 auto ex0 = ExtractValueInst::Create(add, {0}, "", Call);
2650 auto ex1 = ExtractValueInst::Create(add, {1}, "", Call);
2651 auto cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, ex1,
2652 Constant::getNullValue(ty), "", Call);
2653 result =
2654 SelectInst::Create(cmp, ex0, Constant::getAllOnesValue(ty), "", Call);
2655 }
2656
2657 return result;
2658 });
2659}
alan-baker4986eff2020-10-29 13:38:00 -04002660
2661bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2662 return replaceCallsWithValue(F, [](CallInst *Call) {
2663 auto pointer = Call->getArgOperand(0);
2664 // Clang emits an address space cast to the generic address space. Skip the
2665 // cast and use the input directly.
2666 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2667 pointer = cast->getPointerOperand();
2668 }
2669 Value *order_arg =
2670 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2671 Value *scope_arg =
2672 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2673 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2674 clspv::AddressSpace::Global;
2675 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2676 spv::MemorySemanticsAcquireMask);
2677 auto scope = MemoryScope(scope_arg, is_global, Call);
2678 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2679 Call->getType(), {pointer, scope, order});
2680 });
2681}
2682
2683bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2684 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2685 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2686 auto pointer = Call->getArgOperand(0);
2687 // Clang emits an address space cast to the generic address space. Skip the
2688 // cast and use the input directly.
2689 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2690 pointer = cast->getPointerOperand();
2691 }
2692 Value *value = Call->getArgOperand(1);
2693 Value *order_arg =
2694 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2695 Value *scope_arg =
2696 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2697 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2698 clspv::AddressSpace::Global;
2699 auto scope = MemoryScope(scope_arg, is_global, Call);
2700 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2701 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2702 {pointer, scope, order, value});
2703 });
2704}
2705
2706bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2707 return replaceCallsWithValue(F, [](CallInst *Call) {
2708 auto pointer = Call->getArgOperand(0);
2709 // Clang emits an address space cast to the generic address space. Skip the
2710 // cast and use the input directly.
2711 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2712 pointer = cast->getPointerOperand();
2713 }
2714 auto expected = Call->getArgOperand(1);
2715 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2716 expected = cast->getPointerOperand();
2717 }
2718 auto value = Call->getArgOperand(2);
2719 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2720 clspv::AddressSpace::Global;
2721 Value *success_arg =
2722 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2723 Value *failure_arg =
2724 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2725 Value *scope_arg =
2726 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2727 auto scope = MemoryScope(scope_arg, is_global, Call);
2728 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2729 spv::MemorySemanticsAcquireReleaseMask);
2730 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2731 spv::MemorySemanticsAcquireMask);
2732
2733 // If the value pointed to by |expected| equals the value pointed to by
2734 // |pointer|, |value| is written into |pointer|, otherwise the value in
2735 // |pointer| is written into |expected|. In order to avoid extra stores,
2736 // the basic block with the original atomic is split and the store is
2737 // performed in the |then| block. The condition is the inversion of the
2738 // comparison result.
2739 IRBuilder<> builder(Call);
2740 auto load = builder.CreateLoad(expected);
2741 auto cmp_xchg = InsertSPIRVOp(
2742 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2743 value->getType(), {pointer, scope, success, failure, value, load});
2744 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2745 auto not_cmp = builder.CreateNot(cmp);
2746 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2747 builder.SetInsertPoint(then_branch);
2748 builder.CreateStore(cmp_xchg, expected);
2749 return cmp;
2750 });
2751}
alan-bakercc2bafb2020-11-02 08:30:18 -05002752
2753bool ReplaceOpenCLBuiltinPass::replaceClz(Function &F) {
2754 if (!isa<IntegerType>(F.getReturnType()->getScalarType()))
2755 return false;
2756
2757 auto bitwidth = F.getReturnType()->getScalarSizeInBits();
2758 if (bitwidth == 32 || bitwidth > 64)
2759 return false;
2760
2761 return replaceCallsWithValue(F, [&F, bitwidth](CallInst *Call) {
2762 auto in = Call->getArgOperand(0);
2763 IRBuilder<> builder(Call);
2764 auto int32_ty = builder.getInt32Ty();
2765 Type *ty = int32_ty;
2766 if (auto vec_ty = dyn_cast<VectorType>(Call->getType())) {
2767 ty = VectorType::get(ty, vec_ty->getElementCount());
2768 }
2769 auto clz_32bit_ty = FunctionType::get(ty, {ty}, false);
2770 std::string clz_32bit_name = Builtins::GetMangledFunctionName("clz", ty);
2771 auto clz_32bit =
2772 F.getParent()->getOrInsertFunction(clz_32bit_name, clz_32bit_ty);
2773 if (bitwidth < 32) {
2774 // Extend the input to 32-bits and perform a clz. The clz for 32-bit is
2775 // translated as 31 - FindUMsb(in). Adjust that result to the right size.
2776 auto zext = builder.CreateZExt(in, ty);
2777 auto clz = builder.CreateCall(clz_32bit, {zext});
2778 Constant *sub_const = builder.getInt32(32 - bitwidth);
2779 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2780 sub_const =
2781 ConstantVector::getSplat(vec_ty->getElementCount(), sub_const);
2782 }
2783 auto sub = builder.CreateSub(clz, sub_const);
2784 return builder.CreateTrunc(sub, Call->getType());
2785 } else {
2786 // Split the input into top and bottom parts and perform clz on both. If
2787 // the most significant 1 is in the upper 32-bits, return the top result
2788 // directly. Otherwise return 32 + the bottom result to adjust for the
2789 // correct size.
2790 auto lshr = builder.CreateLShr(in, 32);
2791 auto top_bits = builder.CreateTrunc(lshr, ty);
2792 auto bot_bits = builder.CreateTrunc(in, ty);
2793 auto top_clz = builder.CreateCall(clz_32bit, {top_bits});
2794 auto bot_clz = builder.CreateCall(clz_32bit, {bot_bits});
2795 Constant *c32 = builder.getInt32(32);
2796 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2797 c32 = ConstantVector::getSplat(vec_ty->getElementCount(), c32);
2798 }
2799 auto cmp = builder.CreateICmpEQ(top_clz, c32);
2800 auto bot_adjust = builder.CreateAdd(bot_clz, c32);
2801 auto sel = builder.CreateSelect(cmp, bot_adjust, top_clz);
2802 return builder.CreateZExt(sel, Call->getType());
2803 }
2804 });
2805}