blob: 8a9bdb683cce857937949addcc282a70a20f941b [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;
alan-baker6b9d1ee2020-11-03 23:11:32 -0500224
225private:
SJW2c317da2020-03-23 07:39:13 -0500226 bool runOnFunction(Function &F);
227 bool replaceAbs(Function &F);
228 bool replaceAbsDiff(Function &F, bool is_signed);
229 bool replaceCopysign(Function &F);
230 bool replaceRecip(Function &F);
231 bool replaceDivide(Function &F);
232 bool replaceDot(Function &F);
233 bool replaceFmod(Function &F);
SJW61531372020-06-09 07:31:08 -0500234 bool replaceExp10(Function &F, const std::string &basename);
235 bool replaceLog10(Function &F, const std::string &basename);
gnl21636e7992020-09-09 16:08:16 +0100236 bool replaceLog1p(Function &F);
alan-baker12d2c182020-07-20 08:22:42 -0400237 bool replaceBarrier(Function &F, bool subgroup = false);
SJW2c317da2020-03-23 07:39:13 -0500238 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100239 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500240 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
241 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
242 bool replaceIsFinite(Function &F);
243 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
244 bool replaceUpsample(Function &F);
245 bool replaceRotate(Function &F);
246 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
247 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
248 bool replaceSelect(Function &F);
249 bool replaceBitSelect(Function &F);
SJW61531372020-06-09 07:31:08 -0500250 bool replaceStep(Function &F, bool is_smooth);
SJW2c317da2020-03-23 07:39:13 -0500251 bool replaceSignbit(Function &F, bool is_vec);
252 bool replaceMul(Function &F, bool is_float, bool is_mad);
253 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
254 bool replaceVloadHalf(Function &F);
255 bool replaceVloadHalf2(Function &F);
256 bool replaceVloadHalf4(Function &F);
257 bool replaceClspvVloadaHalf2(Function &F);
258 bool replaceClspvVloadaHalf4(Function &F);
259 bool replaceVstoreHalf(Function &F, int vec_size);
260 bool replaceVstoreHalf(Function &F);
261 bool replaceVstoreHalf2(Function &F);
262 bool replaceVstoreHalf4(Function &F);
263 bool replaceHalfReadImage(Function &F);
264 bool replaceHalfWriteImage(Function &F);
265 bool replaceSampledReadImageWithIntCoords(Function &F);
266 bool replaceAtomics(Function &F, spv::Op Op);
267 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
alan-baker4986eff2020-10-29 13:38:00 -0400268 bool replaceAtomicLoad(Function &F);
269 bool replaceExplicitAtomics(Function &F, spv::Op Op,
270 spv::MemorySemanticsMask semantics =
271 spv::MemorySemanticsAcquireReleaseMask);
272 bool replaceAtomicCompareExchange(Function &);
SJW2c317da2020-03-23 07:39:13 -0500273 bool replaceCross(Function &F);
274 bool replaceFract(Function &F, int vec_size);
275 bool replaceVload(Function &F);
276 bool replaceVstore(Function &F);
alan-baker3f1bf492020-11-05 09:07:36 -0500277 bool replaceAddSubSat(Function &F, bool is_signed, bool is_add);
Kévin Petit8576f682020-11-02 14:51:32 +0000278 bool replaceHadd(Function &F, bool is_signed,
279 Instruction::BinaryOps join_opcode);
alan-bakercc2bafb2020-11-02 08:30:18 -0500280 bool replaceClz(Function &F);
alan-baker6b9d1ee2020-11-03 23:11:32 -0500281 bool replaceMadSat(Function &F, bool is_signed);
282
283 // Caches struct types for { |type|, |type| }. This prevents
284 // getOrInsertFunction from introducing a bitcasts between structs with
285 // identical contents.
286 Type *GetPairStruct(Type *type);
287
288 DenseMap<Type *, Type *> PairStructMap;
David Neto22f144c2017-06-12 14:26:21 -0400289};
SJW2c317da2020-03-23 07:39:13 -0500290
Kévin Petit91bc72e2019-04-08 15:17:46 +0100291} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400292
293char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400294INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
295 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400296
297namespace clspv {
298ModulePass *createReplaceOpenCLBuiltinPass() {
299 return new ReplaceOpenCLBuiltinPass();
300}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400301} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400302
303bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500304 std::list<Function *> func_list;
305 for (auto &F : M.getFunctionList()) {
306 // process only function declarations
307 if (F.isDeclaration() && runOnFunction(F)) {
308 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000309 }
310 }
SJW2c317da2020-03-23 07:39:13 -0500311 if (func_list.size() != 0) {
312 // recursively convert functions, but first remove dead
313 for (auto *F : func_list) {
314 if (F->use_empty()) {
315 F->eraseFromParent();
316 }
317 }
318 runOnModule(M);
319 return true;
320 }
321 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000322}
323
SJW2c317da2020-03-23 07:39:13 -0500324bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
325 auto &FI = Builtins::Lookup(&F);
326 switch (FI.getType()) {
327 case Builtins::kAbs:
328 if (!FI.getParameter(0).is_signed) {
329 return replaceAbs(F);
330 }
331 break;
332 case Builtins::kAbsDiff:
333 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400334
335 case Builtins::kAddSat:
alan-baker3f1bf492020-11-05 09:07:36 -0500336 return replaceAddSubSat(F, FI.getParameter(0).is_signed, true);
alan-bakera52b7312020-10-26 08:58:51 -0400337
alan-bakercc2bafb2020-11-02 08:30:18 -0500338 case Builtins::kClz:
339 return replaceClz(F);
340
alan-bakerb6da5132020-10-29 15:59:06 -0400341 case Builtins::kHadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000342 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::And);
alan-bakerb6da5132020-10-29 15:59:06 -0400343 case Builtins::kRhadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000344 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::Or);
alan-bakerb6da5132020-10-29 15:59:06 -0400345
SJW2c317da2020-03-23 07:39:13 -0500346 case Builtins::kCopysign:
347 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100348
SJW2c317da2020-03-23 07:39:13 -0500349 case Builtins::kHalfRecip:
350 case Builtins::kNativeRecip:
351 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100352
SJW2c317da2020-03-23 07:39:13 -0500353 case Builtins::kHalfDivide:
354 case Builtins::kNativeDivide:
355 return replaceDivide(F);
356
357 case Builtins::kDot:
358 return replaceDot(F);
359
360 case Builtins::kExp10:
361 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500362 case Builtins::kNativeExp10:
363 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500364
365 case Builtins::kLog10:
366 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500367 case Builtins::kNativeLog10:
368 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500369
gnl21636e7992020-09-09 16:08:16 +0100370 case Builtins::kLog1p:
371 return replaceLog1p(F);
372
SJW2c317da2020-03-23 07:39:13 -0500373 case Builtins::kFmod:
374 return replaceFmod(F);
375
376 case Builtins::kBarrier:
377 case Builtins::kWorkGroupBarrier:
378 return replaceBarrier(F);
379
alan-baker12d2c182020-07-20 08:22:42 -0400380 case Builtins::kSubGroupBarrier:
381 return replaceBarrier(F, true);
382
SJW2c317da2020-03-23 07:39:13 -0500383 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400384 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500385 case Builtins::kReadMemFence:
386 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
387 case Builtins::kWriteMemFence:
388 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
389
390 // Relational
391 case Builtins::kIsequal:
392 return replaceRelational(F, CmpInst::FCMP_OEQ,
393 FI.getParameter(0).vector_size ? -1 : 1);
394 case Builtins::kIsgreater:
395 return replaceRelational(F, CmpInst::FCMP_OGT,
396 FI.getParameter(0).vector_size ? -1 : 1);
397 case Builtins::kIsgreaterequal:
398 return replaceRelational(F, CmpInst::FCMP_OGE,
399 FI.getParameter(0).vector_size ? -1 : 1);
400 case Builtins::kIsless:
401 return replaceRelational(F, CmpInst::FCMP_OLT,
402 FI.getParameter(0).vector_size ? -1 : 1);
403 case Builtins::kIslessequal:
404 return replaceRelational(F, CmpInst::FCMP_OLE,
405 FI.getParameter(0).vector_size ? -1 : 1);
406 case Builtins::kIsnotequal:
407 return replaceRelational(F, CmpInst::FCMP_ONE,
408 FI.getParameter(0).vector_size ? -1 : 1);
409
410 case Builtins::kIsinf: {
411 bool is_vec = FI.getParameter(0).vector_size != 0;
412 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
413 }
414 case Builtins::kIsnan: {
415 bool is_vec = FI.getParameter(0).vector_size != 0;
416 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
417 }
418
419 case Builtins::kIsfinite:
420 return replaceIsFinite(F);
421
422 case Builtins::kAll: {
423 bool is_vec = FI.getParameter(0).vector_size != 0;
424 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
425 }
426 case Builtins::kAny: {
427 bool is_vec = FI.getParameter(0).vector_size != 0;
428 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
429 }
430
431 case Builtins::kUpsample:
432 return replaceUpsample(F);
433
434 case Builtins::kRotate:
435 return replaceRotate(F);
436
437 case Builtins::kConvert:
438 return replaceConvert(F, FI.getParameter(0).is_signed,
439 FI.getReturnType().is_signed);
440
alan-baker4986eff2020-10-29 13:38:00 -0400441 // OpenCL 2.0 explicit atomics have different default scopes and semantics
442 // than legacy atomic functions.
443 case Builtins::kAtomicLoad:
444 case Builtins::kAtomicLoadExplicit:
445 return replaceAtomicLoad(F);
446 case Builtins::kAtomicStore:
447 case Builtins::kAtomicStoreExplicit:
448 return replaceExplicitAtomics(F, spv::OpAtomicStore,
449 spv::MemorySemanticsReleaseMask);
450 case Builtins::kAtomicExchange:
451 case Builtins::kAtomicExchangeExplicit:
452 return replaceExplicitAtomics(F, spv::OpAtomicExchange);
453 case Builtins::kAtomicFetchAdd:
454 case Builtins::kAtomicFetchAddExplicit:
455 return replaceExplicitAtomics(F, spv::OpAtomicIAdd);
456 case Builtins::kAtomicFetchSub:
457 case Builtins::kAtomicFetchSubExplicit:
458 return replaceExplicitAtomics(F, spv::OpAtomicISub);
459 case Builtins::kAtomicFetchOr:
460 case Builtins::kAtomicFetchOrExplicit:
461 return replaceExplicitAtomics(F, spv::OpAtomicOr);
462 case Builtins::kAtomicFetchXor:
463 case Builtins::kAtomicFetchXorExplicit:
464 return replaceExplicitAtomics(F, spv::OpAtomicXor);
465 case Builtins::kAtomicFetchAnd:
466 case Builtins::kAtomicFetchAndExplicit:
467 return replaceExplicitAtomics(F, spv::OpAtomicAnd);
468 case Builtins::kAtomicFetchMin:
469 case Builtins::kAtomicFetchMinExplicit:
470 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
471 ? spv::OpAtomicSMin
472 : spv::OpAtomicUMin);
473 case Builtins::kAtomicFetchMax:
474 case Builtins::kAtomicFetchMaxExplicit:
475 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
476 ? spv::OpAtomicSMax
477 : spv::OpAtomicUMax);
478 // Weak compare exchange is generated as strong compare exchange.
479 case Builtins::kAtomicCompareExchangeWeak:
480 case Builtins::kAtomicCompareExchangeWeakExplicit:
481 case Builtins::kAtomicCompareExchangeStrong:
482 case Builtins::kAtomicCompareExchangeStrongExplicit:
483 return replaceAtomicCompareExchange(F);
484
485 // Legacy atomic functions.
SJW2c317da2020-03-23 07:39:13 -0500486 case Builtins::kAtomicInc:
487 return replaceAtomics(F, spv::OpAtomicIIncrement);
488 case Builtins::kAtomicDec:
489 return replaceAtomics(F, spv::OpAtomicIDecrement);
490 case Builtins::kAtomicCmpxchg:
491 return replaceAtomics(F, spv::OpAtomicCompareExchange);
492 case Builtins::kAtomicAdd:
493 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
494 case Builtins::kAtomicSub:
495 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
496 case Builtins::kAtomicXchg:
497 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
498 case Builtins::kAtomicMin:
499 return replaceAtomics(F, FI.getParameter(0).is_signed
500 ? llvm::AtomicRMWInst::Min
501 : llvm::AtomicRMWInst::UMin);
502 case Builtins::kAtomicMax:
503 return replaceAtomics(F, FI.getParameter(0).is_signed
504 ? llvm::AtomicRMWInst::Max
505 : llvm::AtomicRMWInst::UMax);
506 case Builtins::kAtomicAnd:
507 return replaceAtomics(F, llvm::AtomicRMWInst::And);
508 case Builtins::kAtomicOr:
509 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
510 case Builtins::kAtomicXor:
511 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
512
513 case Builtins::kCross:
514 if (FI.getParameter(0).vector_size == 4) {
515 return replaceCross(F);
516 }
517 break;
518
519 case Builtins::kFract:
520 if (FI.getParameterCount()) {
521 return replaceFract(F, FI.getParameter(0).vector_size);
522 }
523 break;
524
525 case Builtins::kMadHi:
526 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
527 case Builtins::kMulHi:
528 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
529
alan-baker6b9d1ee2020-11-03 23:11:32 -0500530 case Builtins::kMadSat:
531 return replaceMadSat(F, FI.getParameter(0).is_signed);
532
SJW2c317da2020-03-23 07:39:13 -0500533 case Builtins::kMad:
534 case Builtins::kMad24:
535 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
536 true);
537 case Builtins::kMul24:
538 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
539 false);
540
541 case Builtins::kSelect:
542 return replaceSelect(F);
543
544 case Builtins::kBitselect:
545 return replaceBitSelect(F);
546
547 case Builtins::kVload:
548 return replaceVload(F);
549
550 case Builtins::kVloadaHalf:
551 case Builtins::kVloadHalf:
552 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
553
554 case Builtins::kVstore:
555 return replaceVstore(F);
556
557 case Builtins::kVstoreHalf:
558 case Builtins::kVstoreaHalf:
559 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
560
561 case Builtins::kSmoothstep: {
562 int vec_size = FI.getLastParameter().vector_size;
563 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500564 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500565 }
566 break;
567 }
568 case Builtins::kStep: {
569 int vec_size = FI.getLastParameter().vector_size;
570 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500571 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500572 }
573 break;
574 }
575
576 case Builtins::kSignbit:
577 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
578
alan-baker3f1bf492020-11-05 09:07:36 -0500579 case Builtins::kSubSat:
580 return replaceAddSubSat(F, FI.getParameter(0).is_signed, false);
581
SJW2c317da2020-03-23 07:39:13 -0500582 case Builtins::kReadImageh:
583 return replaceHalfReadImage(F);
584 case Builtins::kReadImagef:
585 case Builtins::kReadImagei:
586 case Builtins::kReadImageui: {
587 if (FI.getParameter(1).isSampler() &&
588 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
589 return replaceSampledReadImageWithIntCoords(F);
590 }
591 break;
592 }
593
594 case Builtins::kWriteImageh:
595 return replaceHalfWriteImage(F);
596
Kévin Petit1cb45112020-04-27 18:55:48 +0100597 case Builtins::kPrefetch:
598 return replacePrefetch(F);
599
SJW2c317da2020-03-23 07:39:13 -0500600 default:
601 break;
602 }
603
604 return false;
605}
606
alan-baker6b9d1ee2020-11-03 23:11:32 -0500607Type *ReplaceOpenCLBuiltinPass::GetPairStruct(Type *type) {
608 auto iter = PairStructMap.find(type);
609 if (iter != PairStructMap.end())
610 return iter->second;
611
612 auto new_struct = StructType::get(type->getContext(), {type, type});
613 PairStructMap[type] = new_struct;
614 return new_struct;
615}
616
SJW2c317da2020-03-23 07:39:13 -0500617bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
618 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400619 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100620}
621
SJW2c317da2020-03-23 07:39:13 -0500622bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
623 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100624 auto XValue = CI->getOperand(0);
625 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100626
Kévin Petite8edce32019-04-10 14:23:32 +0100627 IRBuilder<> Builder(CI);
628 auto XmY = Builder.CreateSub(XValue, YValue);
629 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100630
SJW2c317da2020-03-23 07:39:13 -0500631 Value *Cmp = nullptr;
632 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100633 Cmp = Builder.CreateICmpSGT(YValue, XValue);
634 } else {
635 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100636 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100637
Kévin Petite8edce32019-04-10 14:23:32 +0100638 return Builder.CreateSelect(Cmp, YmX, XmY);
639 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100640}
641
SJW2c317da2020-03-23 07:39:13 -0500642bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
643 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100644 auto XValue = CI->getOperand(0);
645 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100646
Kévin Petite8edce32019-04-10 14:23:32 +0100647 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100648
SJW2c317da2020-03-23 07:39:13 -0500649 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400650 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400651 IntTy = FixedVectorType::get(
652 IntTy, vec_ty->getElementCount().getKnownMinValue());
Kévin Petit8c1be282019-04-02 19:34:25 +0100653 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100654
Kévin Petite8edce32019-04-10 14:23:32 +0100655 // Return X with the sign of Y
656
657 // Sign bit masks
658 auto SignBit = IntTy->getScalarSizeInBits() - 1;
659 auto SignBitMask = 1 << SignBit;
660 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
661 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
662
663 IRBuilder<> Builder(CI);
664
665 // Extract sign of Y
666 auto YInt = Builder.CreateBitCast(YValue, IntTy);
667 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
668
669 // Clear sign bit in X
670 auto XInt = Builder.CreateBitCast(XValue, IntTy);
671 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
672
673 // Insert sign bit of Y into X
674 auto NewXInt = Builder.CreateOr(XInt, YSign);
675
676 // And cast back to floating-point
677 return Builder.CreateBitCast(NewXInt, Ty);
678 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100679}
680
SJW2c317da2020-03-23 07:39:13 -0500681bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
682 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100683 // Recip has one arg.
684 auto Arg = CI->getOperand(0);
685 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
686 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
687 });
David Neto22f144c2017-06-12 14:26:21 -0400688}
689
SJW2c317da2020-03-23 07:39:13 -0500690bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
691 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100692 auto Op0 = CI->getOperand(0);
693 auto Op1 = CI->getOperand(1);
694 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
695 });
David Neto22f144c2017-06-12 14:26:21 -0400696}
697
SJW2c317da2020-03-23 07:39:13 -0500698bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
699 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100700 auto Op0 = CI->getOperand(0);
701 auto Op1 = CI->getOperand(1);
702
SJW2c317da2020-03-23 07:39:13 -0500703 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100704 if (Op0->getType()->isVectorTy()) {
705 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
706 CI->getType(), {Op0, Op1});
707 } else {
708 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
709 }
710
711 return V;
712 });
713}
714
SJW2c317da2020-03-23 07:39:13 -0500715bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500716 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500717 // convert to natural
718 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500719 std::string NewFName = basename.substr(0, slen);
720 NewFName =
721 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400722
SJW2c317da2020-03-23 07:39:13 -0500723 Module &M = *F.getParent();
724 return replaceCallsWithValue(F, [&](CallInst *CI) {
725 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
726
727 auto Arg = CI->getOperand(0);
728
729 // Constant of the natural log of 10 (ln(10)).
730 const double Ln10 =
731 2.302585092994045684017991454684364207601101488628772976033;
732
733 auto Mul = BinaryOperator::Create(
734 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
735
736 return CallInst::Create(NewF, Mul, "", CI);
737 });
David Neto22f144c2017-06-12 14:26:21 -0400738}
739
SJW2c317da2020-03-23 07:39:13 -0500740bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100741 // OpenCL fmod(x,y) is x - y * trunc(x/y)
742 // The sign for a non-zero result is taken from x.
743 // (Try an example.)
744 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500745 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100746 auto Op0 = CI->getOperand(0);
747 auto Op1 = CI->getOperand(1);
748 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
749 });
750}
751
SJW2c317da2020-03-23 07:39:13 -0500752bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500753 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500754 // convert to natural
755 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500756 std::string NewFName = basename.substr(0, slen);
757 NewFName =
758 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400759
SJW2c317da2020-03-23 07:39:13 -0500760 Module &M = *F.getParent();
761 return replaceCallsWithValue(F, [&](CallInst *CI) {
762 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
763
764 auto Arg = CI->getOperand(0);
765
766 // Constant of the reciprocal of the natural log of 10 (ln(10)).
767 const double Ln10 =
768 0.434294481903251827651128918916605082294397005803666566114;
769
770 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
771
772 return BinaryOperator::Create(Instruction::FMul,
773 ConstantFP::get(Arg->getType(), Ln10), NewCI,
774 "", CI);
775 });
David Neto22f144c2017-06-12 14:26:21 -0400776}
777
gnl21636e7992020-09-09 16:08:16 +0100778bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
779 // convert to natural
780 std::string NewFName =
781 Builtins::GetMangledFunctionName("log", F.getFunctionType());
782
783 Module &M = *F.getParent();
784 return replaceCallsWithValue(F, [&](CallInst *CI) {
785 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
786
787 auto Arg = CI->getOperand(0);
788
789 auto ArgP1 = BinaryOperator::Create(
790 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
791
792 return CallInst::Create(NewF, ArgP1, "", CI);
793 });
794}
795
alan-baker12d2c182020-07-20 08:22:42 -0400796bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400797
alan-bakerf6bc8252020-09-23 14:58:55 -0400798 enum {
799 CLK_LOCAL_MEM_FENCE = 0x01,
800 CLK_GLOBAL_MEM_FENCE = 0x02,
801 CLK_IMAGE_MEM_FENCE = 0x04
802 };
David Neto22f144c2017-06-12 14:26:21 -0400803
alan-baker12d2c182020-07-20 08:22:42 -0400804 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100805 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400806
Kévin Petitc4643922019-06-17 19:32:05 +0100807 // We need to map the OpenCL constants to the SPIR-V equivalents.
808 const auto LocalMemFence =
809 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
810 const auto GlobalMemFence =
811 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400812 const auto ImageMemFence =
813 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400814 const auto ConstantAcquireRelease = ConstantInt::get(
815 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100816 const auto ConstantScopeDevice =
817 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
818 const auto ConstantScopeWorkgroup =
819 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400820 const auto ConstantScopeSubgroup =
821 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400822
Kévin Petitc4643922019-06-17 19:32:05 +0100823 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
824 const auto LocalMemFenceMask =
825 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
826 const auto WorkgroupShiftAmount =
827 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
828 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
829 Instruction::Shl, LocalMemFenceMask,
830 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400831
Kévin Petitc4643922019-06-17 19:32:05 +0100832 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
833 const auto GlobalMemFenceMask =
834 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
835 const auto UniformShiftAmount =
836 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
837 const auto MemorySemanticsUniform = BinaryOperator::Create(
838 Instruction::Shl, GlobalMemFenceMask,
839 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400840
alan-bakerf6bc8252020-09-23 14:58:55 -0400841 // OpenCL 2.0
842 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
843 const auto ImageMemFenceMask =
844 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
845 const auto ImageShiftAmount =
846 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
847 const auto MemorySemanticsImage = BinaryOperator::Create(
848 Instruction::Shl, ImageMemFenceMask,
849 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
850
Kévin Petitc4643922019-06-17 19:32:05 +0100851 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400852 // MemorySemanticsSequentiallyConsistentMask.
853 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100854 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400855 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400856 auto MemorySemantics2 = BinaryOperator::Create(
857 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
858 auto MemorySemantics = BinaryOperator::Create(
859 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400860
alan-baker12d2c182020-07-20 08:22:42 -0400861 // If the memory scope is not specified explicitly, it is either Subgroup
862 // or Workgroup depending on the type of barrier.
863 Value *MemoryScope =
864 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
865 if (CI->data_operands_size() > 1) {
866 enum {
867 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
868 CL_MEMORY_SCOPE_DEVICE = 0x2,
869 CL_MEMORY_SCOPE_SUBGROUP = 0x4
870 };
871 // The call was given an explicit memory scope.
872 const auto MemoryScopeSubgroup =
873 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
874 const auto MemoryScopeDevice =
875 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400876
alan-baker12d2c182020-07-20 08:22:42 -0400877 auto Cmp =
878 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
879 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
880 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
881 ConstantScopeWorkgroup, "", CI);
882 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
883 MemoryScopeDevice, CI->getOperand(1), "", CI);
884 MemoryScope =
885 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
886 }
887
888 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
889 // the type of barrier;
890 const auto ExecutionScope =
891 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400892
Kévin Petitc4643922019-06-17 19:32:05 +0100893 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400894 {Attribute::NoDuplicate, Attribute::Convergent},
895 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100896 {ExecutionScope, MemoryScope, MemorySemantics});
897 });
David Neto22f144c2017-06-12 14:26:21 -0400898}
899
SJW2c317da2020-03-23 07:39:13 -0500900bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
901 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400902
SJW2c317da2020-03-23 07:39:13 -0500903 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400904 enum {
905 CLK_LOCAL_MEM_FENCE = 0x01,
906 CLK_GLOBAL_MEM_FENCE = 0x02,
907 CLK_IMAGE_MEM_FENCE = 0x04,
908 };
David Neto22f144c2017-06-12 14:26:21 -0400909
SJW2c317da2020-03-23 07:39:13 -0500910 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400911
SJW2c317da2020-03-23 07:39:13 -0500912 // We need to map the OpenCL constants to the SPIR-V equivalents.
913 const auto LocalMemFence =
914 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
915 const auto GlobalMemFence =
916 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400917 const auto ImageMemFence =
918 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500919 const auto ConstantMemorySemantics =
920 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400921 const auto ConstantScopeWorkgroup =
922 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400923
SJW2c317da2020-03-23 07:39:13 -0500924 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
925 const auto LocalMemFenceMask =
926 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
927 const auto WorkgroupShiftAmount =
928 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
929 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
930 Instruction::Shl, LocalMemFenceMask,
931 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400932
SJW2c317da2020-03-23 07:39:13 -0500933 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
934 const auto GlobalMemFenceMask =
935 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
936 const auto UniformShiftAmount =
937 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
938 const auto MemorySemanticsUniform = BinaryOperator::Create(
939 Instruction::Shl, GlobalMemFenceMask,
940 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400941
alan-bakerf6bc8252020-09-23 14:58:55 -0400942 // OpenCL 2.0
943 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
944 const auto ImageMemFenceMask =
945 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
946 const auto ImageShiftAmount =
947 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
948 const auto MemorySemanticsImage = BinaryOperator::Create(
949 Instruction::Shl, ImageMemFenceMask,
950 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
951
SJW2c317da2020-03-23 07:39:13 -0500952 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400953 // |semantics|.
954 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500955 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
956 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400957 auto MemorySemantics2 = BinaryOperator::Create(
958 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
959 auto MemorySemantics = BinaryOperator::Create(
960 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400961
alan-baker12d2c182020-07-20 08:22:42 -0400962 // Memory Scope is always workgroup.
963 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400964
alan-baker3d905692020-10-28 14:02:37 -0400965 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
966 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500967 {MemoryScope, MemorySemantics});
968 });
David Neto22f144c2017-06-12 14:26:21 -0400969}
970
Kévin Petit1cb45112020-04-27 18:55:48 +0100971bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
972 bool Changed = false;
973
974 SmallVector<Instruction *, 4> ToRemoves;
975
976 // Find all calls to the function
977 for (auto &U : F.uses()) {
978 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
979 ToRemoves.push_back(CI);
980 }
981 }
982
983 Changed = !ToRemoves.empty();
984
985 // Delete them
986 for (auto V : ToRemoves) {
987 V->eraseFromParent();
988 }
989
990 return Changed;
991}
992
SJW2c317da2020-03-23 07:39:13 -0500993bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
994 CmpInst::Predicate P,
995 int32_t C) {
996 return replaceCallsWithValue(F, [&](CallInst *CI) {
997 // The predicate to use in the CmpInst.
998 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400999
SJW2c317da2020-03-23 07:39:13 -05001000 // The value to return for true.
1001 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -04001002
SJW2c317da2020-03-23 07:39:13 -05001003 // The value to return for false.
1004 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001005
SJW2c317da2020-03-23 07:39:13 -05001006 auto Arg1 = CI->getOperand(0);
1007 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001008
SJW2c317da2020-03-23 07:39:13 -05001009 const auto Cmp =
1010 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001011
SJW2c317da2020-03-23 07:39:13 -05001012 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1013 });
David Neto22f144c2017-06-12 14:26:21 -04001014}
1015
SJW2c317da2020-03-23 07:39:13 -05001016bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
1017 spv::Op SPIRVOp,
1018 int32_t C) {
1019 Module &M = *F.getParent();
1020 return replaceCallsWithValue(F, [&](CallInst *CI) {
1021 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -04001022
SJW2c317da2020-03-23 07:39:13 -05001023 // The value to return for true.
1024 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -04001025
SJW2c317da2020-03-23 07:39:13 -05001026 // The value to return for false.
1027 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -04001028
SJW2c317da2020-03-23 07:39:13 -05001029 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -04001030 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001031 CorrespondingBoolTy =
1032 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
1033 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04001034 }
David Neto22f144c2017-06-12 14:26:21 -04001035
SJW2c317da2020-03-23 07:39:13 -05001036 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
1037 CorrespondingBoolTy, {CI->getOperand(0)});
1038
1039 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
1040 });
David Neto22f144c2017-06-12 14:26:21 -04001041}
1042
SJW2c317da2020-03-23 07:39:13 -05001043bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
1044 Module &M = *F.getParent();
1045 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001046 auto &C = M.getContext();
1047 auto Val = CI->getOperand(0);
1048 auto ValTy = Val->getType();
1049 auto RetTy = CI->getType();
1050
1051 // Get a suitable integer type to represent the number
1052 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
1053
1054 // Create Mask
1055 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -05001056 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001057 switch (ScalarSize) {
1058 case 16:
1059 InfMask = ConstantInt::get(IntTy, 0x7C00U);
1060 break;
1061 case 32:
1062 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
1063 break;
1064 case 64:
1065 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
1066 break;
1067 default:
1068 llvm_unreachable("Unsupported floating-point type");
1069 }
1070
1071 IRBuilder<> Builder(CI);
1072
1073 // Bitcast to int
1074 auto ValInt = Builder.CreateBitCast(Val, IntTy);
1075
1076 // Mask and compare
1077 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
1078 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
1079
1080 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -05001081 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001082 if (ValTy->isVectorTy()) {
1083 RetTrue = ConstantInt::getSigned(RetTy, -1);
1084 } else {
1085 RetTrue = ConstantInt::get(RetTy, 1);
1086 }
1087 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
1088 });
1089}
1090
SJW2c317da2020-03-23 07:39:13 -05001091bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
1092 Module &M = *F.getParent();
1093 return replaceCallsWithValue(F, [&](CallInst *CI) {
1094 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001095
SJW2c317da2020-03-23 07:39:13 -05001096 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001097
SJW2c317da2020-03-23 07:39:13 -05001098 // If the argument is a 32-bit int, just use a shift
1099 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1100 V = BinaryOperator::Create(Instruction::LShr, Arg,
1101 ConstantInt::get(Arg->getType(), 31), "", CI);
1102 } else {
1103 // The value for zero to compare against.
1104 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -04001105
SJW2c317da2020-03-23 07:39:13 -05001106 // The value to return for true.
1107 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04001108
SJW2c317da2020-03-23 07:39:13 -05001109 // The value to return for false.
1110 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001111
SJW2c317da2020-03-23 07:39:13 -05001112 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
1113 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001114
SJW2c317da2020-03-23 07:39:13 -05001115 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04001116
SJW2c317da2020-03-23 07:39:13 -05001117 // If we have a function to call, call it!
1118 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -04001119
SJW2c317da2020-03-23 07:39:13 -05001120 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -04001121
SJW2c317da2020-03-23 07:39:13 -05001122 const auto NewCI = clspv::InsertSPIRVOp(
1123 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
1124 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -04001125
SJW2c317da2020-03-23 07:39:13 -05001126 } else {
1127 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -04001128 }
1129
SJW2c317da2020-03-23 07:39:13 -05001130 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001131 }
SJW2c317da2020-03-23 07:39:13 -05001132 return V;
1133 });
David Neto22f144c2017-06-12 14:26:21 -04001134}
1135
SJW2c317da2020-03-23 07:39:13 -05001136bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
1137 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1138 // Get arguments
1139 auto HiValue = CI->getOperand(0);
1140 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001141
SJW2c317da2020-03-23 07:39:13 -05001142 // Don't touch overloads that aren't in OpenCL C
1143 auto HiType = HiValue->getType();
1144 auto LoType = LoValue->getType();
1145
1146 if (HiType != LoType) {
1147 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001148 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001149
SJW2c317da2020-03-23 07:39:13 -05001150 if (!HiType->isIntOrIntVectorTy()) {
1151 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001152 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001153
SJW2c317da2020-03-23 07:39:13 -05001154 if (HiType->getScalarSizeInBits() * 2 !=
1155 CI->getType()->getScalarSizeInBits()) {
1156 return nullptr;
1157 }
1158
1159 if ((HiType->getScalarSizeInBits() != 8) &&
1160 (HiType->getScalarSizeInBits() != 16) &&
1161 (HiType->getScalarSizeInBits() != 32)) {
1162 return nullptr;
1163 }
1164
James Pricecf53df42020-04-20 14:41:24 -04001165 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001166 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001167 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1168 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001169 return nullptr;
1170 }
1171 }
1172
1173 // Convert both operands to the result type
1174 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1175 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
1176
1177 // Shift high operand
1178 auto ShiftAmount =
1179 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
1180 auto HiShifted =
1181 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
1182
1183 // OR both results
1184 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
1185 });
Kévin Petitbf0036c2019-03-06 13:57:10 +00001186}
1187
SJW2c317da2020-03-23 07:39:13 -05001188bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
1189 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1190 // Get arguments
1191 auto SrcValue = CI->getOperand(0);
1192 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001193
SJW2c317da2020-03-23 07:39:13 -05001194 // Don't touch overloads that aren't in OpenCL C
1195 auto SrcType = SrcValue->getType();
1196 auto RotType = RotAmount->getType();
1197
1198 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1199 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001200 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001201
SJW2c317da2020-03-23 07:39:13 -05001202 if (!SrcType->isIntOrIntVectorTy()) {
1203 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001204 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001205
SJW2c317da2020-03-23 07:39:13 -05001206 if ((SrcType->getScalarSizeInBits() != 8) &&
1207 (SrcType->getScalarSizeInBits() != 16) &&
1208 (SrcType->getScalarSizeInBits() != 32) &&
1209 (SrcType->getScalarSizeInBits() != 64)) {
1210 return nullptr;
1211 }
1212
James Pricecf53df42020-04-20 14:41:24 -04001213 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001214 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001215 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1216 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001217 return nullptr;
1218 }
1219 }
1220
alan-bakerfd22ae12020-10-29 15:59:22 -04001221 // Replace with LLVM's funnel shift left intrinsic because it is more
1222 // generic than rotate.
1223 Function *intrinsic =
1224 Intrinsic::getDeclaration(F.getParent(), Intrinsic::fshl, SrcType);
1225 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
1226 {SrcValue, SrcValue, RotAmount}, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001227 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001228}
1229
SJW2c317da2020-03-23 07:39:13 -05001230bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1231 bool DstIsSigned) {
1232 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1233 Value *V = nullptr;
1234 // Get arguments
1235 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001236
SJW2c317da2020-03-23 07:39:13 -05001237 // Don't touch overloads that aren't in OpenCL C
1238 auto SrcType = SrcValue->getType();
1239 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001240
SJW2c317da2020-03-23 07:39:13 -05001241 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1242 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1243 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001244 }
1245
James Pricecf53df42020-04-20 14:41:24 -04001246 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001247 unsigned SrcNumElements =
1248 SrcVecType->getElementCount().getKnownMinValue();
1249 unsigned DstNumElements =
1250 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001251 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001252 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001253 }
1254
James Pricecf53df42020-04-20 14:41:24 -04001255 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1256 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1257 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001258 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001259 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001260 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001261
SJW2c317da2020-03-23 07:39:13 -05001262 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1263 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1264
1265 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1266 bool DstIsInt = DstType->isIntOrIntVectorTy();
1267
1268 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1269 // Unnecessary cast operation.
1270 V = SrcValue;
1271 } else if (SrcIsFloat && DstIsFloat) {
1272 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1273 } else if (SrcIsFloat && DstIsInt) {
1274 if (DstIsSigned) {
1275 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1276 } else {
1277 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1278 }
1279 } else if (SrcIsInt && DstIsFloat) {
1280 if (SrcIsSigned) {
1281 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1282 } else {
1283 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1284 }
1285 } else if (SrcIsInt && DstIsInt) {
1286 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1287 } else {
1288 // Not something we're supposed to handle, just move on
1289 }
1290
1291 return V;
1292 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001293}
1294
SJW2c317da2020-03-23 07:39:13 -05001295bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1296 bool is_mad) {
1297 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1298 Value *V = nullptr;
1299 // Get arguments
1300 auto AValue = CI->getOperand(0);
1301 auto BValue = CI->getOperand(1);
1302 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001303
SJW2c317da2020-03-23 07:39:13 -05001304 // Don't touch overloads that aren't in OpenCL C
1305 auto AType = AValue->getType();
1306 auto BType = BValue->getType();
1307 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001308
SJW2c317da2020-03-23 07:39:13 -05001309 if ((AType != BType) || (CI->getType() != AType) ||
1310 (is_mad && (AType != CType))) {
1311 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001312 }
1313
SJW2c317da2020-03-23 07:39:13 -05001314 if (!AType->isIntOrIntVectorTy()) {
1315 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001316 }
Kévin Petit8a560882019-03-21 15:24:34 +00001317
SJW2c317da2020-03-23 07:39:13 -05001318 if ((AType->getScalarSizeInBits() != 8) &&
1319 (AType->getScalarSizeInBits() != 16) &&
1320 (AType->getScalarSizeInBits() != 32) &&
1321 (AType->getScalarSizeInBits() != 64)) {
1322 return V;
1323 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001324
James Pricecf53df42020-04-20 14:41:24 -04001325 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001326 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001327 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1328 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001329 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001330 }
1331 }
1332
SJW2c317da2020-03-23 07:39:13 -05001333 // Our SPIR-V op returns a struct, create a type for it
alan-baker6b9d1ee2020-11-03 23:11:32 -05001334 auto ExMulRetType = GetPairStruct(AType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001335
SJW2c317da2020-03-23 07:39:13 -05001336 // Select the appropriate signed/unsigned SPIR-V op
1337 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1338
1339 // Call the SPIR-V op
1340 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1341 ExMulRetType, {AValue, BValue});
1342
1343 // Get the high part of the result
1344 unsigned Idxs[] = {1};
1345 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1346
1347 // If we're handling a mad_hi, add the third argument to the result
1348 if (is_mad) {
1349 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001350 }
1351
SJW2c317da2020-03-23 07:39:13 -05001352 return V;
1353 });
Kévin Petit8a560882019-03-21 15:24:34 +00001354}
1355
SJW2c317da2020-03-23 07:39:13 -05001356bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1357 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1358 // Get arguments
1359 auto FalseValue = CI->getOperand(0);
1360 auto TrueValue = CI->getOperand(1);
1361 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001362
SJW2c317da2020-03-23 07:39:13 -05001363 // Don't touch overloads that aren't in OpenCL C
1364 auto FalseType = FalseValue->getType();
1365 auto TrueType = TrueValue->getType();
1366 auto PredicateType = PredicateValue->getType();
1367
1368 if (FalseType != TrueType) {
1369 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001370 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001371
SJW2c317da2020-03-23 07:39:13 -05001372 if (!PredicateType->isIntOrIntVectorTy()) {
1373 return nullptr;
1374 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001375
SJW2c317da2020-03-23 07:39:13 -05001376 if (!FalseType->isIntOrIntVectorTy() &&
1377 !FalseType->getScalarType()->isFloatingPointTy()) {
1378 return nullptr;
1379 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001380
SJW2c317da2020-03-23 07:39:13 -05001381 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1382 return nullptr;
1383 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001384
SJW2c317da2020-03-23 07:39:13 -05001385 if (FalseType->getScalarSizeInBits() !=
1386 PredicateType->getScalarSizeInBits()) {
1387 return nullptr;
1388 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001389
James Pricecf53df42020-04-20 14:41:24 -04001390 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001391 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1392 if (NumElements != cast<VectorType>(PredicateType)
1393 ->getElementCount()
1394 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001395 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001396 }
1397
James Pricecf53df42020-04-20 14:41:24 -04001398 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1399 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001400 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001401 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001402 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001403
SJW2c317da2020-03-23 07:39:13 -05001404 // Create constant
1405 const auto ZeroValue = Constant::getNullValue(PredicateType);
1406
1407 // Scalar and vector are to be treated differently
1408 CmpInst::Predicate Pred;
1409 if (PredicateType->isVectorTy()) {
1410 Pred = CmpInst::ICMP_SLT;
1411 } else {
1412 Pred = CmpInst::ICMP_NE;
1413 }
1414
1415 // Create comparison instruction
1416 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1417 ZeroValue, "", CI);
1418
1419 // Create select
1420 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1421 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001422}
1423
SJW2c317da2020-03-23 07:39:13 -05001424bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1425 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1426 Value *V = nullptr;
1427 if (CI->getNumOperands() != 4) {
1428 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001429 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001430
SJW2c317da2020-03-23 07:39:13 -05001431 // Get arguments
1432 auto FalseValue = CI->getOperand(0);
1433 auto TrueValue = CI->getOperand(1);
1434 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001435
SJW2c317da2020-03-23 07:39:13 -05001436 // Don't touch overloads that aren't in OpenCL C
1437 auto FalseType = FalseValue->getType();
1438 auto TrueType = TrueValue->getType();
1439 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001440
SJW2c317da2020-03-23 07:39:13 -05001441 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1442 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001443 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001444
James Pricecf53df42020-04-20 14:41:24 -04001445 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001446 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1447 !TrueType->getScalarType()->isIntegerTy()) {
1448 return V;
1449 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001450 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001451 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1452 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001453 return V;
1454 }
1455 }
1456
1457 // Remember the type of the operands
1458 auto OpType = TrueType;
1459
1460 // The actual bit selection will always be done on an integer type,
1461 // declare it here
1462 Type *BitType;
1463
1464 // If the operands are float, then bitcast them to int
1465 if (OpType->getScalarType()->isFloatingPointTy()) {
1466
1467 // First create the new type
1468 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1469
1470 // Then bitcast all operands
1471 PredicateValue =
1472 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1473 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1474 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1475
1476 } else {
1477 // The operands have an integer type, use it directly
1478 BitType = OpType;
1479 }
1480
1481 // All the operands are now always integers
1482 // implement as (c & b) | (~c & a)
1483
1484 // Create our negated predicate value
1485 auto AllOnes = Constant::getAllOnesValue(BitType);
1486 auto NotPredicateValue = BinaryOperator::Create(
1487 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1488
1489 // Then put everything together
1490 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1491 FalseValue, "", CI);
1492 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1493 TrueValue, "", CI);
1494
1495 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1496
1497 // If we were dealing with a floating point type, we must bitcast
1498 // the result back to that
1499 if (OpType->getScalarType()->isFloatingPointTy()) {
1500 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1501 }
1502
1503 return V;
1504 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001505}
1506
SJW61531372020-06-09 07:31:08 -05001507bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001508 // convert to vector versions
1509 Module &M = *F.getParent();
1510 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1511 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1512 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001513
SJW2c317da2020-03-23 07:39:13 -05001514 // First figure out which function we're dealing with
1515 if (is_smooth) {
1516 ArgsToSplat.push_back(CI->getOperand(1));
1517 VectorArg = CI->getOperand(2);
1518 } else {
1519 VectorArg = CI->getOperand(1);
1520 }
1521
1522 // Splat arguments that need to be
1523 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001524 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001525
1526 for (auto arg : ArgsToSplat) {
1527 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001528 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001529 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1530 NewVectorArg =
1531 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1532 }
1533 SplatArgs.push_back(NewVectorArg);
1534 }
1535
1536 // Replace the call with the vector/vector flavour
1537 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1538 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1539
SJW61531372020-06-09 07:31:08 -05001540 std::string NewFName = Builtins::GetMangledFunctionName(
1541 is_smooth ? "smoothstep" : "step", NewFType);
1542
SJW2c317da2020-03-23 07:39:13 -05001543 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1544
1545 SmallVector<Value *, 3> NewArgs;
1546 for (auto arg : SplatArgs) {
1547 NewArgs.push_back(arg);
1548 }
1549 NewArgs.push_back(VectorArg);
1550
1551 return CallInst::Create(NewF, NewArgs, "", CI);
1552 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001553}
1554
SJW2c317da2020-03-23 07:39:13 -05001555bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001556 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1557 auto Arg = CI->getOperand(0);
1558 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001559
SJW2c317da2020-03-23 07:39:13 -05001560 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001561
SJW2c317da2020-03-23 07:39:13 -05001562 return BinaryOperator::Create(Op, Bitcast,
1563 ConstantInt::get(CI->getType(), 31), "", CI);
1564 });
David Neto22f144c2017-06-12 14:26:21 -04001565}
1566
SJW2c317da2020-03-23 07:39:13 -05001567bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1568 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001569 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1570 // The multiply instruction to use.
1571 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001572
SJW2c317da2020-03-23 07:39:13 -05001573 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001574
SJW2c317da2020-03-23 07:39:13 -05001575 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1576 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001577
SJW2c317da2020-03-23 07:39:13 -05001578 if (is_mad) {
1579 // The add instruction to use.
1580 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001581
SJW2c317da2020-03-23 07:39:13 -05001582 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001583 }
David Neto22f144c2017-06-12 14:26:21 -04001584
SJW2c317da2020-03-23 07:39:13 -05001585 return V;
1586 });
David Neto22f144c2017-06-12 14:26:21 -04001587}
1588
SJW2c317da2020-03-23 07:39:13 -05001589bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001590 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1591 Value *V = nullptr;
1592 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001593
SJW2c317da2020-03-23 07:39:13 -05001594 auto data_type = data->getType();
1595 if (!data_type->isVectorTy())
1596 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001597
James Pricecf53df42020-04-20 14:41:24 -04001598 auto vec_data_type = cast<VectorType>(data_type);
1599
alan-baker5a8c3be2020-09-09 13:44:26 -04001600 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001601 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1602 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001603
SJW2c317da2020-03-23 07:39:13 -05001604 auto offset = CI->getOperand(1);
1605 auto ptr = CI->getOperand(2);
1606 auto ptr_type = ptr->getType();
1607 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001608 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001609 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001610
SJW2c317da2020-03-23 07:39:13 -05001611 // Avoid pointer casts. Instead generate the correct number of stores
1612 // and rely on drivers to coalesce appropriately.
1613 IRBuilder<> builder(CI);
1614 auto elems_const = builder.getInt32(elems);
1615 auto adjust = builder.CreateMul(offset, elems_const);
1616 for (auto i = 0; i < elems; ++i) {
1617 auto idx = builder.getInt32(i);
1618 auto add = builder.CreateAdd(adjust, idx);
1619 auto gep = builder.CreateGEP(ptr, add);
1620 auto extract = builder.CreateExtractElement(data, i);
1621 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001622 }
SJW2c317da2020-03-23 07:39:13 -05001623 return V;
1624 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001625}
1626
SJW2c317da2020-03-23 07:39:13 -05001627bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001628 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1629 Value *V = nullptr;
1630 auto ret_type = F.getReturnType();
1631 if (!ret_type->isVectorTy())
1632 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001633
James Pricecf53df42020-04-20 14:41:24 -04001634 auto vec_ret_type = cast<VectorType>(ret_type);
1635
alan-baker5a8c3be2020-09-09 13:44:26 -04001636 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001637 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1638 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001639
SJW2c317da2020-03-23 07:39:13 -05001640 auto offset = CI->getOperand(0);
1641 auto ptr = CI->getOperand(1);
1642 auto ptr_type = ptr->getType();
1643 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001644 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001645 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001646
SJW2c317da2020-03-23 07:39:13 -05001647 // Avoid pointer casts. Instead generate the correct number of loads
1648 // and rely on drivers to coalesce appropriately.
1649 IRBuilder<> builder(CI);
1650 auto elems_const = builder.getInt32(elems);
1651 V = UndefValue::get(ret_type);
1652 auto adjust = builder.CreateMul(offset, elems_const);
1653 for (auto i = 0; i < elems; ++i) {
1654 auto idx = builder.getInt32(i);
1655 auto add = builder.CreateAdd(adjust, idx);
1656 auto gep = builder.CreateGEP(ptr, add);
1657 auto load = builder.CreateLoad(gep);
1658 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001659 }
SJW2c317da2020-03-23 07:39:13 -05001660 return V;
1661 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001662}
1663
SJW2c317da2020-03-23 07:39:13 -05001664bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1665 const std::string &name,
1666 int vec_size) {
1667 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1668 if (!vec_size) {
1669 // deduce vec_size from last character of name (e.g. vload_half4)
1670 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001671 }
SJW2c317da2020-03-23 07:39:13 -05001672 switch (vec_size) {
1673 case 2:
1674 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1675 case 4:
1676 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1677 case 0:
1678 if (!is_clspv_version) {
1679 return replaceVloadHalf(F);
1680 }
1681 default:
1682 llvm_unreachable("Unsupported vload_half vector size");
1683 break;
1684 }
1685 return false;
David Neto22f144c2017-06-12 14:26:21 -04001686}
1687
SJW2c317da2020-03-23 07:39:13 -05001688bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1689 Module &M = *F.getParent();
1690 return replaceCallsWithValue(F, [&](CallInst *CI) {
1691 // The index argument from vload_half.
1692 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001693
SJW2c317da2020-03-23 07:39:13 -05001694 // The pointer argument from vload_half.
1695 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001696
SJW2c317da2020-03-23 07:39:13 -05001697 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001698 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001699 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1700
1701 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001702 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001703
1704 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1705
1706 Value *V = nullptr;
1707
alan-baker7efcaaa2020-05-06 19:33:27 -04001708 bool supports_16bit_storage = true;
1709 switch (Arg1->getType()->getPointerAddressSpace()) {
1710 case clspv::AddressSpace::Global:
1711 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1712 clspv::Option::StorageClass::kSSBO);
1713 break;
1714 case clspv::AddressSpace::Constant:
1715 if (clspv::Option::ConstantArgsInUniformBuffer())
1716 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1717 clspv::Option::StorageClass::kUBO);
1718 else
1719 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1720 clspv::Option::StorageClass::kSSBO);
1721 break;
1722 default:
1723 // Clspv will emit the Float16 capability if the half type is
1724 // encountered. That capability covers private and local addressspaces.
1725 break;
1726 }
1727
1728 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001729 auto ShortTy = Type::getInt16Ty(M.getContext());
1730 auto ShortPointerTy =
1731 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1732
1733 // Cast the half* pointer to short*.
1734 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1735
1736 // Index into the correct address of the casted pointer.
1737 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1738
1739 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001740 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001741
1742 // ZExt the short -> int.
1743 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1744
1745 // Get our float2.
1746 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1747
1748 // Extract out the bottom element which is our float result.
1749 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1750 } else {
1751 // Assume the pointer argument points to storage aligned to 32bits
1752 // or more.
1753 // TODO(dneto): Do more analysis to make sure this is true?
1754 //
1755 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1756 // with:
1757 //
1758 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1759 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1760 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1761 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1762 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1763 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1764 // x float> %converted, %index_is_odd32
1765
1766 auto IntPointerTy =
1767 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1768
1769 // Cast the base pointer to int*.
1770 // In a valid call (according to assumptions), this should get
1771 // optimized away in the simplify GEP pass.
1772 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1773
1774 auto One = ConstantInt::get(IntTy, 1);
1775 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1776 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1777
1778 // Index into the correct address of the casted pointer.
1779 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1780
1781 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001782 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001783
1784 // Get our float2.
1785 auto Call = CallInst::Create(NewF, Load, "", CI);
1786
1787 // Extract out the float result, where the element number is
1788 // determined by whether the original index was even or odd.
1789 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1790 }
1791 return V;
1792 });
1793}
1794
1795bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1796 Module &M = *F.getParent();
1797 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001798 // The index argument from vload_half.
1799 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001800
Kévin Petite8edce32019-04-10 14:23:32 +01001801 // The pointer argument from vload_half.
1802 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001803
Kévin Petite8edce32019-04-10 14:23:32 +01001804 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001805 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001806 auto NewPointerTy =
1807 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001808 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001809
Kévin Petite8edce32019-04-10 14:23:32 +01001810 // Cast the half* pointer to int*.
1811 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001812
Kévin Petite8edce32019-04-10 14:23:32 +01001813 // Index into the correct address of the casted pointer.
1814 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001815
Kévin Petite8edce32019-04-10 14:23:32 +01001816 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001817 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001818
Kévin Petite8edce32019-04-10 14:23:32 +01001819 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001820 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001821
Kévin Petite8edce32019-04-10 14:23:32 +01001822 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001823
Kévin Petite8edce32019-04-10 14:23:32 +01001824 // Get our float2.
1825 return CallInst::Create(NewF, Load, "", CI);
1826 });
David Neto22f144c2017-06-12 14:26:21 -04001827}
1828
SJW2c317da2020-03-23 07:39:13 -05001829bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1830 Module &M = *F.getParent();
1831 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001832 // The index argument from vload_half.
1833 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001834
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // The pointer argument from vload_half.
1836 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001837
Kévin Petite8edce32019-04-10 14:23:32 +01001838 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001839 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1840 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001841 auto NewPointerTy =
1842 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001843 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001844
Kévin Petite8edce32019-04-10 14:23:32 +01001845 // Cast the half* pointer to int2*.
1846 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001847
Kévin Petite8edce32019-04-10 14:23:32 +01001848 // Index into the correct address of the casted pointer.
1849 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001850
Kévin Petite8edce32019-04-10 14:23:32 +01001851 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001852 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001853
Kévin Petite8edce32019-04-10 14:23:32 +01001854 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001855 auto X =
1856 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1857 auto Y =
1858 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001859
Kévin Petite8edce32019-04-10 14:23:32 +01001860 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001861 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001862
Kévin Petite8edce32019-04-10 14:23:32 +01001863 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001864
Kévin Petite8edce32019-04-10 14:23:32 +01001865 // Get the lower (x & y) components of our final float4.
1866 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001867
Kévin Petite8edce32019-04-10 14:23:32 +01001868 // Get the higher (z & w) components of our final float4.
1869 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001870
Kévin Petite8edce32019-04-10 14:23:32 +01001871 Constant *ShuffleMask[4] = {
1872 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1873 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001874
Kévin Petite8edce32019-04-10 14:23:32 +01001875 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001876 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1877 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001878 });
David Neto22f144c2017-06-12 14:26:21 -04001879}
1880
SJW2c317da2020-03-23 07:39:13 -05001881bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001882
1883 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1884 //
1885 // %u = load i32 %ptr
1886 // %fxy = call <2 x float> Unpack2xHalf(u)
1887 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001888 Module &M = *F.getParent();
1889 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001890 auto Index = CI->getOperand(0);
1891 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001892
Kévin Petite8edce32019-04-10 14:23:32 +01001893 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001894 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001895 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001896
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001897 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001898 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001899
Kévin Petite8edce32019-04-10 14:23:32 +01001900 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001901 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001904
Kévin Petite8edce32019-04-10 14:23:32 +01001905 // Get our final float2.
1906 return CallInst::Create(NewF, Load, "", CI);
1907 });
David Neto6ad93232018-06-07 15:42:58 -07001908}
1909
SJW2c317da2020-03-23 07:39:13 -05001910bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001911
1912 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1913 //
1914 // %u2 = load <2 x i32> %ptr
1915 // %u2xy = extractelement %u2, 0
1916 // %u2zw = extractelement %u2, 1
1917 // %fxy = call <2 x float> Unpack2xHalf(uint)
1918 // %fzw = call <2 x float> Unpack2xHalf(uint)
1919 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001920 Module &M = *F.getParent();
1921 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001922 auto Index = CI->getOperand(0);
1923 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001924
Kévin Petite8edce32019-04-10 14:23:32 +01001925 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001926 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1927 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001928 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001929
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001930 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001931 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001932
Kévin Petite8edce32019-04-10 14:23:32 +01001933 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001934 auto X =
1935 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1936 auto Y =
1937 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001938
Kévin Petite8edce32019-04-10 14:23:32 +01001939 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001940 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001941
Kévin Petite8edce32019-04-10 14:23:32 +01001942 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001943
Kévin Petite8edce32019-04-10 14:23:32 +01001944 // Get the lower (x & y) components of our final float4.
1945 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001946
Kévin Petite8edce32019-04-10 14:23:32 +01001947 // Get the higher (z & w) components of our final float4.
1948 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001949
Kévin Petite8edce32019-04-10 14:23:32 +01001950 Constant *ShuffleMask[4] = {
1951 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1952 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001953
Kévin Petite8edce32019-04-10 14:23:32 +01001954 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001955 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1956 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001957 });
David Neto6ad93232018-06-07 15:42:58 -07001958}
1959
SJW2c317da2020-03-23 07:39:13 -05001960bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1961 switch (vec_size) {
1962 case 0:
1963 return replaceVstoreHalf(F);
1964 case 2:
1965 return replaceVstoreHalf2(F);
1966 case 4:
1967 return replaceVstoreHalf4(F);
1968 default:
1969 llvm_unreachable("Unsupported vstore_half vector size");
1970 break;
1971 }
1972 return false;
1973}
David Neto22f144c2017-06-12 14:26:21 -04001974
SJW2c317da2020-03-23 07:39:13 -05001975bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1976 Module &M = *F.getParent();
1977 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001978 // The value to store.
1979 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001980
Kévin Petite8edce32019-04-10 14:23:32 +01001981 // The index argument from vstore_half.
1982 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001983
Kévin Petite8edce32019-04-10 14:23:32 +01001984 // The pointer argument from vstore_half.
1985 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001986
Kévin Petite8edce32019-04-10 14:23:32 +01001987 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001988 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001989 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1990 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001991
Kévin Petite8edce32019-04-10 14:23:32 +01001992 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001993 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001994
Kévin Petite8edce32019-04-10 14:23:32 +01001995 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001996
Kévin Petite8edce32019-04-10 14:23:32 +01001997 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001998 auto TempVec = InsertElementInst::Create(
1999 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002000
Kévin Petite8edce32019-04-10 14:23:32 +01002001 // Pack the float2 -> half2 (in an int).
2002 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002003
alan-baker7efcaaa2020-05-06 19:33:27 -04002004 bool supports_16bit_storage = true;
2005 switch (Arg2->getType()->getPointerAddressSpace()) {
2006 case clspv::AddressSpace::Global:
2007 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2008 clspv::Option::StorageClass::kSSBO);
2009 break;
2010 case clspv::AddressSpace::Constant:
2011 if (clspv::Option::ConstantArgsInUniformBuffer())
2012 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2013 clspv::Option::StorageClass::kUBO);
2014 else
2015 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2016 clspv::Option::StorageClass::kSSBO);
2017 break;
2018 default:
2019 // Clspv will emit the Float16 capability if the half type is
2020 // encountered. That capability covers private and local addressspaces.
2021 break;
2022 }
2023
SJW2c317da2020-03-23 07:39:13 -05002024 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04002025 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01002026 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002027 auto ShortPointerTy =
2028 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002029
Kévin Petite8edce32019-04-10 14:23:32 +01002030 // Truncate our i32 to an i16.
2031 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002032
Kévin Petite8edce32019-04-10 14:23:32 +01002033 // Cast the half* pointer to short*.
2034 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002035
Kévin Petite8edce32019-04-10 14:23:32 +01002036 // Index into the correct address of the casted pointer.
2037 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002038
Kévin Petite8edce32019-04-10 14:23:32 +01002039 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002040 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002041 } else {
2042 // We can only write to 32-bit aligned words.
2043 //
2044 // Assuming base is aligned to 32-bits, replace the equivalent of
2045 // vstore_half(value, index, base)
2046 // with:
2047 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2048 // uint32_t write_to_upper_half = index & 1u;
2049 // uint32_t shift = write_to_upper_half << 4;
2050 //
2051 // // Pack the float value as a half number in bottom 16 bits
2052 // // of an i32.
2053 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2054 //
2055 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2056 // ^ ((packed & 0xffff) << shift)
2057 // // We only need relaxed consistency, but OpenCL 1.2 only has
2058 // // sequentially consistent atomics.
2059 // // TODO(dneto): Use relaxed consistency.
2060 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002061 auto IntPointerTy =
2062 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002063
Kévin Petite8edce32019-04-10 14:23:32 +01002064 auto Four = ConstantInt::get(IntTy, 4);
2065 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002066
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002067 auto IndexIsOdd =
2068 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002069 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002070 auto IndexIntoI32 =
2071 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2072 auto BaseI32Ptr =
2073 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2074 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2075 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002076 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002077 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002078 auto MaskBitsToWrite =
2079 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2080 auto MaskedCurrent = BinaryOperator::CreateAnd(
2081 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002082
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002083 auto XLowerBits =
2084 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2085 auto NewBitsToWrite =
2086 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2087 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2088 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002089
Kévin Petite8edce32019-04-10 14:23:32 +01002090 // Generate the call to atomi_xor.
2091 SmallVector<Type *, 5> ParamTypes;
2092 // The pointer type.
2093 ParamTypes.push_back(IntPointerTy);
2094 // The Types for memory scope, semantics, and value.
2095 ParamTypes.push_back(IntTy);
2096 ParamTypes.push_back(IntTy);
2097 ParamTypes.push_back(IntTy);
2098 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2099 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002100
Kévin Petite8edce32019-04-10 14:23:32 +01002101 const auto ConstantScopeDevice =
2102 ConstantInt::get(IntTy, spv::ScopeDevice);
2103 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2104 // (SPIR-V Workgroup).
2105 const auto AddrSpaceSemanticsBits =
2106 IntPointerTy->getPointerAddressSpace() == 1
2107 ? spv::MemorySemanticsUniformMemoryMask
2108 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002109
Kévin Petite8edce32019-04-10 14:23:32 +01002110 // We're using relaxed consistency here.
2111 const auto ConstantMemorySemantics =
2112 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2113 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002114
Kévin Petite8edce32019-04-10 14:23:32 +01002115 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2116 ConstantMemorySemantics, ValueToXor};
2117 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002118
2119 // Return a Nop so the old Call is removed
2120 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2121 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002122 }
David Neto22f144c2017-06-12 14:26:21 -04002123
SJW2c317da2020-03-23 07:39:13 -05002124 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002125 });
David Neto22f144c2017-06-12 14:26:21 -04002126}
2127
SJW2c317da2020-03-23 07:39:13 -05002128bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2129 Module &M = *F.getParent();
2130 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002131 // The value to store.
2132 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002133
Kévin Petite8edce32019-04-10 14:23:32 +01002134 // The index argument from vstore_half.
2135 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002136
Kévin Petite8edce32019-04-10 14:23:32 +01002137 // The pointer argument from vstore_half.
2138 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002139
Kévin Petite8edce32019-04-10 14:23:32 +01002140 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002141 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002142 auto NewPointerTy =
2143 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002144 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002145
Kévin Petite8edce32019-04-10 14:23:32 +01002146 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002147 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002148
Kévin Petite8edce32019-04-10 14:23:32 +01002149 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002150
Kévin Petite8edce32019-04-10 14:23:32 +01002151 // Turn the packed x & y into the final packing.
2152 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002153
Kévin Petite8edce32019-04-10 14:23:32 +01002154 // Cast the half* pointer to int*.
2155 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002156
Kévin Petite8edce32019-04-10 14:23:32 +01002157 // Index into the correct address of the casted pointer.
2158 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002159
Kévin Petite8edce32019-04-10 14:23:32 +01002160 // Store to the int* we casted to.
2161 return new StoreInst(X, Index, CI);
2162 });
David Neto22f144c2017-06-12 14:26:21 -04002163}
2164
SJW2c317da2020-03-23 07:39:13 -05002165bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2166 Module &M = *F.getParent();
2167 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002168 // The value to store.
2169 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002170
Kévin Petite8edce32019-04-10 14:23:32 +01002171 // The index argument from vstore_half.
2172 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002173
Kévin Petite8edce32019-04-10 14:23:32 +01002174 // The pointer argument from vstore_half.
2175 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002176
Kévin Petite8edce32019-04-10 14:23:32 +01002177 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002178 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2179 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002180 auto NewPointerTy =
2181 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002182 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002183
Kévin Petite8edce32019-04-10 14:23:32 +01002184 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2185 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002186
Kévin Petite8edce32019-04-10 14:23:32 +01002187 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002188 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2189 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002190
Kévin Petite8edce32019-04-10 14:23:32 +01002191 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2192 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002193
Kévin Petite8edce32019-04-10 14:23:32 +01002194 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002195 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2196 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002197
Kévin Petite8edce32019-04-10 14:23:32 +01002198 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002199 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002200
Kévin Petite8edce32019-04-10 14:23:32 +01002201 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002202
Kévin Petite8edce32019-04-10 14:23:32 +01002203 // Turn the packed x & y into the final component of our int2.
2204 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002205
Kévin Petite8edce32019-04-10 14:23:32 +01002206 // Turn the packed z & w into the final component of our int2.
2207 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002208
Kévin Petite8edce32019-04-10 14:23:32 +01002209 auto Combine = InsertElementInst::Create(
2210 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002211 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2212 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002213
Kévin Petite8edce32019-04-10 14:23:32 +01002214 // Cast the half* pointer to int2*.
2215 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002216
Kévin Petite8edce32019-04-10 14:23:32 +01002217 // Index into the correct address of the casted pointer.
2218 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002219
Kévin Petite8edce32019-04-10 14:23:32 +01002220 // Store to the int2* we casted to.
2221 return new StoreInst(Combine, Index, CI);
2222 });
David Neto22f144c2017-06-12 14:26:21 -04002223}
2224
SJW2c317da2020-03-23 07:39:13 -05002225bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2226 // convert half to float
2227 Module &M = *F.getParent();
2228 return replaceCallsWithValue(F, [&](CallInst *CI) {
2229 SmallVector<Type *, 3> types;
2230 SmallVector<Value *, 3> args;
2231 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2232 types.push_back(CI->getArgOperand(i)->getType());
2233 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002234 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002235
alan-baker5a8c3be2020-09-09 13:44:26 -04002236 auto NewFType =
2237 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2238 cast<VectorType>(CI->getType())
2239 ->getElementCount()
2240 .getKnownMinValue()),
2241 types, false);
SJW2c317da2020-03-23 07:39:13 -05002242
SJW61531372020-06-09 07:31:08 -05002243 std::string NewFName =
2244 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002245
2246 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2247
2248 auto NewCI = CallInst::Create(NewF, args, "", CI);
2249
2250 // Convert to the half type.
2251 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2252 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002253}
2254
SJW2c317da2020-03-23 07:39:13 -05002255bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2256 // convert half to float
2257 Module &M = *F.getParent();
2258 return replaceCallsWithValue(F, [&](CallInst *CI) {
2259 SmallVector<Type *, 3> types(3);
2260 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002261
SJW2c317da2020-03-23 07:39:13 -05002262 // Image
2263 types[0] = CI->getArgOperand(0)->getType();
2264 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002265
SJW2c317da2020-03-23 07:39:13 -05002266 // Coord
2267 types[1] = CI->getArgOperand(1)->getType();
2268 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002269
SJW2c317da2020-03-23 07:39:13 -05002270 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002271 types[2] =
2272 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2273 cast<VectorType>(CI->getArgOperand(2)->getType())
2274 ->getElementCount()
2275 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002276
SJW2c317da2020-03-23 07:39:13 -05002277 auto NewFType =
2278 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002279
SJW61531372020-06-09 07:31:08 -05002280 std::string NewFName =
2281 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002282
SJW2c317da2020-03-23 07:39:13 -05002283 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002284
SJW2c317da2020-03-23 07:39:13 -05002285 // Convert data to the float type.
2286 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2287 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002288
SJW2c317da2020-03-23 07:39:13 -05002289 return CallInst::Create(NewF, args, "", CI);
2290 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002291}
2292
SJW2c317da2020-03-23 07:39:13 -05002293bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2294 Function &F) {
2295 // convert read_image with int coords to float coords
2296 Module &M = *F.getParent();
2297 return replaceCallsWithValue(F, [&](CallInst *CI) {
2298 // The image.
2299 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002300
SJW2c317da2020-03-23 07:39:13 -05002301 // The sampler.
2302 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002303
SJW2c317da2020-03-23 07:39:13 -05002304 // The coordinate (integer type that we can't handle).
2305 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002306
SJW2c317da2020-03-23 07:39:13 -05002307 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2308 uint32_t components =
2309 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2310 Type *float_ty = nullptr;
2311 if (components == 1) {
2312 float_ty = Type::getFloatTy(M.getContext());
2313 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002314 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2315 cast<VectorType>(Arg2->getType())
2316 ->getElementCount()
2317 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002318 }
David Neto22f144c2017-06-12 14:26:21 -04002319
SJW2c317da2020-03-23 07:39:13 -05002320 auto NewFType = FunctionType::get(
2321 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2322
2323 std::string NewFName = F.getName().str();
2324 NewFName[NewFName.length() - 1] = 'f';
2325
2326 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2327
2328 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2329
2330 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2331 });
David Neto22f144c2017-06-12 14:26:21 -04002332}
2333
SJW2c317da2020-03-23 07:39:13 -05002334bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2335 return replaceCallsWithValue(F, [&](CallInst *CI) {
2336 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002337
SJW2c317da2020-03-23 07:39:13 -05002338 // We need to map the OpenCL constants to the SPIR-V equivalents.
2339 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2340 const auto ConstantMemorySemantics = ConstantInt::get(
2341 IntTy, spv::MemorySemanticsUniformMemoryMask |
2342 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002343
SJW2c317da2020-03-23 07:39:13 -05002344 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002345
SJW2c317da2020-03-23 07:39:13 -05002346 // The pointer.
2347 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002348
SJW2c317da2020-03-23 07:39:13 -05002349 // The memory scope.
2350 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002351
SJW2c317da2020-03-23 07:39:13 -05002352 // The memory semantics.
2353 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002354
SJW2c317da2020-03-23 07:39:13 -05002355 if (2 < CI->getNumArgOperands()) {
2356 // The unequal memory semantics.
2357 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002358
SJW2c317da2020-03-23 07:39:13 -05002359 // The value.
2360 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002361
SJW2c317da2020-03-23 07:39:13 -05002362 // The comparator.
2363 Params.push_back(CI->getArgOperand(1));
2364 } else if (1 < CI->getNumArgOperands()) {
2365 // The value.
2366 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002367 }
David Neto22f144c2017-06-12 14:26:21 -04002368
SJW2c317da2020-03-23 07:39:13 -05002369 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2370 });
David Neto22f144c2017-06-12 14:26:21 -04002371}
2372
SJW2c317da2020-03-23 07:39:13 -05002373bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2374 llvm::AtomicRMWInst::BinOp Op) {
2375 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002376 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2377 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002378 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002379 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002380 SyncScope::System, CI);
2381 });
2382}
David Neto22f144c2017-06-12 14:26:21 -04002383
SJW2c317da2020-03-23 07:39:13 -05002384bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2385 Module &M = *F.getParent();
2386 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002387 auto IntTy = Type::getInt32Ty(M.getContext());
2388 auto FloatTy = Type::getFloatTy(M.getContext());
2389
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002390 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2391 ConstantInt::get(IntTy, 1),
2392 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002393
2394 Constant *UpShuffleMask[4] = {
2395 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2396 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2397
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002398 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2399 UndefValue::get(FloatTy),
2400 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002401
Kévin Petite8edce32019-04-10 14:23:32 +01002402 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002403 auto Arg0 =
2404 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2405 ConstantVector::get(DownShuffleMask), "", CI);
2406 auto Arg1 =
2407 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2408 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002409 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002410
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002411 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002412 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002413
SJW61531372020-06-09 07:31:08 -05002414 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002415
Kévin Petite8edce32019-04-10 14:23:32 +01002416 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002417
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002418 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2419 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002420 });
David Neto22f144c2017-06-12 14:26:21 -04002421}
David Neto62653202017-10-16 19:05:18 -04002422
SJW2c317da2020-03-23 07:39:13 -05002423bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002424 // OpenCL's float result = fract(float x, float* ptr)
2425 //
2426 // In the LLVM domain:
2427 //
2428 // %floor_result = call spir_func float @floor(float %x)
2429 // store float %floor_result, float * %ptr
2430 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2431 // %result = call spir_func float
2432 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2433 //
2434 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2435 // and clspv.fract occur in the SPIR-V generator pass:
2436 //
2437 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2438 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2439 // ...
2440 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2441 // OpStore %ptr %floor_result
2442 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2443 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002444 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002445
David Neto62653202017-10-16 19:05:18 -04002446 using std::string;
2447
2448 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2449 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002450
SJW2c317da2020-03-23 07:39:13 -05002451 Module &M = *F.getParent();
2452 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002453
SJW2c317da2020-03-23 07:39:13 -05002454 // This is either float or a float vector. All the float-like
2455 // types are this type.
2456 auto result_ty = F.getReturnType();
2457
SJW61531372020-06-09 07:31:08 -05002458 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002459 Function *fmin_fn = M.getFunction(fmin_name);
2460 if (!fmin_fn) {
2461 // Make the fmin function.
2462 FunctionType *fn_ty =
2463 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2464 fmin_fn =
2465 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2466 fmin_fn->addFnAttr(Attribute::ReadNone);
2467 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2468 }
2469
SJW61531372020-06-09 07:31:08 -05002470 std::string floor_name =
2471 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002472 Function *floor_fn = M.getFunction(floor_name);
2473 if (!floor_fn) {
2474 // Make the floor function.
2475 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2476 floor_fn =
2477 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2478 floor_fn->addFnAttr(Attribute::ReadNone);
2479 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2480 }
2481
SJW61531372020-06-09 07:31:08 -05002482 std::string clspv_fract_name =
2483 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002484 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2485 if (!clspv_fract_fn) {
2486 // Make the clspv_fract function.
2487 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2488 clspv_fract_fn = cast<Function>(
2489 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2490 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2491 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2492 }
2493
2494 // Number of significant significand bits, whether represented or not.
2495 unsigned num_significand_bits;
2496 switch (result_ty->getScalarType()->getTypeID()) {
2497 case Type::HalfTyID:
2498 num_significand_bits = 11;
2499 break;
2500 case Type::FloatTyID:
2501 num_significand_bits = 24;
2502 break;
2503 case Type::DoubleTyID:
2504 num_significand_bits = 53;
2505 break;
2506 default:
2507 llvm_unreachable("Unhandled float type when processing fract builtin");
2508 break;
2509 }
2510 // Beware that the disassembler displays this value as
2511 // OpConstant %float 1
2512 // which is not quite right.
2513 const double kJustUnderOneScalar =
2514 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2515
2516 Constant *just_under_one =
2517 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2518 if (result_ty->isVectorTy()) {
2519 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002520 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002521 }
2522
2523 IRBuilder<> Builder(CI);
2524
2525 auto arg = CI->getArgOperand(0);
2526 auto ptr = CI->getArgOperand(1);
2527
2528 // Compute floor result and store it.
2529 auto floor = Builder.CreateCall(floor_fn, {arg});
2530 Builder.CreateStore(floor, ptr);
2531
2532 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2533 auto fract_result =
2534 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2535
2536 return fract_result;
2537 });
David Neto62653202017-10-16 19:05:18 -04002538}
alan-bakera52b7312020-10-26 08:58:51 -04002539
Kévin Petit8576f682020-11-02 14:51:32 +00002540bool ReplaceOpenCLBuiltinPass::replaceHadd(Function &F, bool is_signed,
alan-bakerb6da5132020-10-29 15:59:06 -04002541 Instruction::BinaryOps join_opcode) {
Kévin Petit8576f682020-11-02 14:51:32 +00002542 return replaceCallsWithValue(F, [is_signed, join_opcode](CallInst *Call) {
alan-bakerb6da5132020-10-29 15:59:06 -04002543 // a_shr = a >> 1
2544 // b_shr = b >> 1
2545 // add1 = a_shr + b_shr
2546 // join = a |join_opcode| b
2547 // and = join & 1
2548 // add = add1 + and
2549 const auto a = Call->getArgOperand(0);
2550 const auto b = Call->getArgOperand(1);
2551 IRBuilder<> builder(Call);
Kévin Petit8576f682020-11-02 14:51:32 +00002552 Value *a_shift, *b_shift;
2553 if (is_signed) {
2554 a_shift = builder.CreateAShr(a, 1);
2555 b_shift = builder.CreateAShr(b, 1);
2556 } else {
2557 a_shift = builder.CreateLShr(a, 1);
2558 b_shift = builder.CreateLShr(b, 1);
2559 }
alan-bakerb6da5132020-10-29 15:59:06 -04002560 auto add = builder.CreateAdd(a_shift, b_shift);
2561 auto join = BinaryOperator::Create(join_opcode, a, b, "", Call);
2562 auto constant_one = ConstantInt::get(a->getType(), 1);
2563 auto and_bit = builder.CreateAnd(join, constant_one);
2564 return builder.CreateAdd(add, and_bit);
2565 });
2566}
2567
alan-baker3f1bf492020-11-05 09:07:36 -05002568bool ReplaceOpenCLBuiltinPass::replaceAddSubSat(Function &F, bool is_signed,
2569 bool is_add) {
2570 return replaceCallsWithValue(F, [&F, this, is_signed,
2571 is_add](CallInst *Call) {
2572 auto ty = Call->getType();
2573 auto a = Call->getArgOperand(0);
2574 auto b = Call->getArgOperand(1);
2575 IRBuilder<> builder(Call);
alan-bakera52b7312020-10-26 08:58:51 -04002576 if (is_signed) {
2577 unsigned bitwidth = ty->getScalarSizeInBits();
2578 if (bitwidth < 32) {
alan-baker3f1bf492020-11-05 09:07:36 -05002579 unsigned extended_width = bitwidth << 1;
2580 Type *extended_ty =
2581 IntegerType::get(Call->getContext(), extended_width);
2582 Constant *min = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002583 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002584 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2585 Constant *max = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002586 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002587 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
alan-bakera52b7312020-10-26 08:58:51 -04002588 // Don't use the type in GetMangledFunctionName to ensure we get
2589 // signed parameters.
2590 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
alan-bakera52b7312020-10-26 08:58:51 -04002591 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
alan-baker3f1bf492020-11-05 09:07:36 -05002592 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2593 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2594 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2595 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2596 if (extended_width == 32) {
alan-bakera52b7312020-10-26 08:58:51 -04002597 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
alan-bakera52b7312020-10-26 08:58:51 -04002598 } else {
2599 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2600 }
alan-baker3f1bf492020-11-05 09:07:36 -05002601 } else {
2602 if (extended_width == 32) {
2603 sclamp_name += "iii";
2604 } else {
2605 sclamp_name += "sss";
2606 }
alan-bakera52b7312020-10-26 08:58:51 -04002607 }
alan-baker3f1bf492020-11-05 09:07:36 -05002608
2609 auto sext_a = builder.CreateSExt(a, extended_ty);
2610 auto sext_b = builder.CreateSExt(b, extended_ty);
2611 Value *op = nullptr;
2612 // Extended operations won't wrap.
2613 if (is_add)
2614 op = builder.CreateAdd(sext_a, sext_b, "", true, true);
2615 else
2616 op = builder.CreateSub(sext_a, sext_b, "", true, true);
2617 auto clamp_ty = FunctionType::get(
2618 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2619 auto callee = F.getParent()->getOrInsertFunction(sclamp_name, clamp_ty);
2620 auto clamp = builder.CreateCall(callee, {op, min, max});
2621 return builder.CreateTrunc(clamp, ty);
alan-bakera52b7312020-10-26 08:58:51 -04002622 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002623 // Add:
2624 // c = a + b
alan-bakera52b7312020-10-26 08:58:51 -04002625 // if (b < 0)
2626 // c = c > a ? min : c;
2627 // else
alan-baker3f1bf492020-11-05 09:07:36 -05002628 // c = c < a ? max : c;
alan-bakera52b7312020-10-26 08:58:51 -04002629 //
alan-baker3f1bf492020-11-05 09:07:36 -05002630 // Sub:
2631 // c = a - b;
2632 // if (b < 0)
2633 // c = c < a ? max : c;
2634 // else
2635 // c = c > a ? min : c;
2636 Constant *min = ConstantInt::get(Call->getContext(),
2637 APInt::getSignedMinValue(bitwidth));
2638 Constant *max = ConstantInt::get(Call->getContext(),
2639 APInt::getSignedMaxValue(bitwidth));
alan-bakera52b7312020-10-26 08:58:51 -04002640 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2641 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2642 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2643 }
alan-baker3f1bf492020-11-05 09:07:36 -05002644 Value *op = nullptr;
2645 if (is_add) {
2646 op = builder.CreateAdd(a, b);
2647 } else {
2648 op = builder.CreateSub(a, b);
2649 }
2650 auto b_lt_0 = builder.CreateICmpSLT(b, Constant::getNullValue(ty));
2651 auto op_gt_a = builder.CreateICmpSGT(op, a);
2652 auto op_lt_a = builder.CreateICmpSLT(op, a);
2653 auto neg_cmp = is_add ? op_gt_a : op_lt_a;
2654 auto pos_cmp = is_add ? op_lt_a : op_gt_a;
2655 auto neg_value = is_add ? min : max;
2656 auto pos_value = is_add ? max : min;
2657 auto neg_clamp = builder.CreateSelect(neg_cmp, neg_value, op);
2658 auto pos_clamp = builder.CreateSelect(pos_cmp, pos_value, op);
2659 return builder.CreateSelect(b_lt_0, neg_clamp, pos_clamp);
alan-bakera52b7312020-10-26 08:58:51 -04002660 }
2661 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002662 // Replace with OpIAddCarry/OpISubBorrow and clamp to max/0 on a
2663 // carr/borrow.
2664 spv::Op op = is_add ? spv::OpIAddCarry : spv::OpISubBorrow;
2665 auto clamp_value =
2666 is_add ? Constant::getAllOnesValue(ty) : Constant::getNullValue(ty);
2667 auto struct_ty = GetPairStruct(ty);
2668 auto call =
2669 InsertSPIRVOp(Call, op, {Attribute::ReadNone}, struct_ty, {a, b});
2670 auto add_sub = builder.CreateExtractValue(call, {0});
2671 auto carry_borrow = builder.CreateExtractValue(call, {1});
2672 auto cmp = builder.CreateICmpEQ(carry_borrow, Constant::getNullValue(ty));
2673 return builder.CreateSelect(cmp, add_sub, clamp_value);
alan-bakera52b7312020-10-26 08:58:51 -04002674 }
alan-bakera52b7312020-10-26 08:58:51 -04002675 });
2676}
alan-baker4986eff2020-10-29 13:38:00 -04002677
2678bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2679 return replaceCallsWithValue(F, [](CallInst *Call) {
2680 auto pointer = Call->getArgOperand(0);
2681 // Clang emits an address space cast to the generic address space. Skip the
2682 // cast and use the input directly.
2683 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2684 pointer = cast->getPointerOperand();
2685 }
2686 Value *order_arg =
2687 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2688 Value *scope_arg =
2689 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2690 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2691 clspv::AddressSpace::Global;
2692 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2693 spv::MemorySemanticsAcquireMask);
2694 auto scope = MemoryScope(scope_arg, is_global, Call);
2695 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2696 Call->getType(), {pointer, scope, order});
2697 });
2698}
2699
2700bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2701 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2702 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2703 auto pointer = Call->getArgOperand(0);
2704 // Clang emits an address space cast to the generic address space. Skip the
2705 // cast and use the input directly.
2706 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2707 pointer = cast->getPointerOperand();
2708 }
2709 Value *value = Call->getArgOperand(1);
2710 Value *order_arg =
2711 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2712 Value *scope_arg =
2713 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2714 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2715 clspv::AddressSpace::Global;
2716 auto scope = MemoryScope(scope_arg, is_global, Call);
2717 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2718 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2719 {pointer, scope, order, value});
2720 });
2721}
2722
2723bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2724 return replaceCallsWithValue(F, [](CallInst *Call) {
2725 auto pointer = Call->getArgOperand(0);
2726 // Clang emits an address space cast to the generic address space. Skip the
2727 // cast and use the input directly.
2728 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2729 pointer = cast->getPointerOperand();
2730 }
2731 auto expected = Call->getArgOperand(1);
2732 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2733 expected = cast->getPointerOperand();
2734 }
2735 auto value = Call->getArgOperand(2);
2736 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2737 clspv::AddressSpace::Global;
2738 Value *success_arg =
2739 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2740 Value *failure_arg =
2741 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2742 Value *scope_arg =
2743 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2744 auto scope = MemoryScope(scope_arg, is_global, Call);
2745 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2746 spv::MemorySemanticsAcquireReleaseMask);
2747 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2748 spv::MemorySemanticsAcquireMask);
2749
2750 // If the value pointed to by |expected| equals the value pointed to by
2751 // |pointer|, |value| is written into |pointer|, otherwise the value in
2752 // |pointer| is written into |expected|. In order to avoid extra stores,
2753 // the basic block with the original atomic is split and the store is
2754 // performed in the |then| block. The condition is the inversion of the
2755 // comparison result.
2756 IRBuilder<> builder(Call);
2757 auto load = builder.CreateLoad(expected);
2758 auto cmp_xchg = InsertSPIRVOp(
2759 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2760 value->getType(), {pointer, scope, success, failure, value, load});
2761 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2762 auto not_cmp = builder.CreateNot(cmp);
2763 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2764 builder.SetInsertPoint(then_branch);
2765 builder.CreateStore(cmp_xchg, expected);
2766 return cmp;
2767 });
2768}
alan-bakercc2bafb2020-11-02 08:30:18 -05002769
2770bool ReplaceOpenCLBuiltinPass::replaceClz(Function &F) {
2771 if (!isa<IntegerType>(F.getReturnType()->getScalarType()))
2772 return false;
2773
2774 auto bitwidth = F.getReturnType()->getScalarSizeInBits();
2775 if (bitwidth == 32 || bitwidth > 64)
2776 return false;
2777
2778 return replaceCallsWithValue(F, [&F, bitwidth](CallInst *Call) {
2779 auto in = Call->getArgOperand(0);
2780 IRBuilder<> builder(Call);
2781 auto int32_ty = builder.getInt32Ty();
2782 Type *ty = int32_ty;
2783 if (auto vec_ty = dyn_cast<VectorType>(Call->getType())) {
2784 ty = VectorType::get(ty, vec_ty->getElementCount());
2785 }
2786 auto clz_32bit_ty = FunctionType::get(ty, {ty}, false);
2787 std::string clz_32bit_name = Builtins::GetMangledFunctionName("clz", ty);
2788 auto clz_32bit =
2789 F.getParent()->getOrInsertFunction(clz_32bit_name, clz_32bit_ty);
2790 if (bitwidth < 32) {
2791 // Extend the input to 32-bits and perform a clz. The clz for 32-bit is
2792 // translated as 31 - FindUMsb(in). Adjust that result to the right size.
2793 auto zext = builder.CreateZExt(in, ty);
2794 auto clz = builder.CreateCall(clz_32bit, {zext});
2795 Constant *sub_const = builder.getInt32(32 - bitwidth);
2796 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2797 sub_const =
2798 ConstantVector::getSplat(vec_ty->getElementCount(), sub_const);
2799 }
2800 auto sub = builder.CreateSub(clz, sub_const);
2801 return builder.CreateTrunc(sub, Call->getType());
2802 } else {
2803 // Split the input into top and bottom parts and perform clz on both. If
2804 // the most significant 1 is in the upper 32-bits, return the top result
2805 // directly. Otherwise return 32 + the bottom result to adjust for the
2806 // correct size.
2807 auto lshr = builder.CreateLShr(in, 32);
2808 auto top_bits = builder.CreateTrunc(lshr, ty);
2809 auto bot_bits = builder.CreateTrunc(in, ty);
2810 auto top_clz = builder.CreateCall(clz_32bit, {top_bits});
2811 auto bot_clz = builder.CreateCall(clz_32bit, {bot_bits});
2812 Constant *c32 = builder.getInt32(32);
2813 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2814 c32 = ConstantVector::getSplat(vec_ty->getElementCount(), c32);
2815 }
2816 auto cmp = builder.CreateICmpEQ(top_clz, c32);
2817 auto bot_adjust = builder.CreateAdd(bot_clz, c32);
2818 auto sel = builder.CreateSelect(cmp, bot_adjust, top_clz);
2819 return builder.CreateZExt(sel, Call->getType());
2820 }
2821 });
2822}
alan-baker6b9d1ee2020-11-03 23:11:32 -05002823
2824bool ReplaceOpenCLBuiltinPass::replaceMadSat(Function &F, bool is_signed) {
2825 return replaceCallsWithValue(F, [&F, is_signed, this](CallInst *Call) {
2826 const auto ty = Call->getType();
2827 const auto a = Call->getArgOperand(0);
2828 const auto b = Call->getArgOperand(1);
2829 const auto c = Call->getArgOperand(2);
2830 IRBuilder<> builder(Call);
2831 if (is_signed) {
2832 unsigned bitwidth = Call->getType()->getScalarSizeInBits();
2833 if (bitwidth < 32) {
2834 // mul = sext(a) * sext(b)
2835 // add = mul + sext(c)
2836 // res = clamp(add, MIN, MAX)
2837 unsigned extended_width = bitwidth << 1;
2838 Type *extended_ty = IntegerType::get(F.getContext(), extended_width);
2839 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2840 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2841 }
2842 auto a_sext = builder.CreateSExt(a, extended_ty);
2843 auto b_sext = builder.CreateSExt(b, extended_ty);
2844 auto c_sext = builder.CreateSExt(c, extended_ty);
2845 // Extended the size so no overflows occur.
2846 auto mul = builder.CreateMul(a_sext, b_sext, "", true, true);
2847 auto add = builder.CreateAdd(mul, c_sext, "", true, true);
2848 auto func_ty = FunctionType::get(
2849 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2850 // Don't use function type because we need signed parameters.
2851 std::string clamp_name = Builtins::GetMangledFunctionName("clamp");
2852 // The clamp values are the signed min and max of the original bitwidth
2853 // sign extended to the extended bitwidth.
2854 Constant *min = ConstantInt::get(
2855 Call->getContext(),
2856 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2857 Constant *max = ConstantInt::get(
2858 Call->getContext(),
2859 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
2860 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2861 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2862 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2863 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2864 if (extended_width == 32)
2865 clamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2866 else
2867 clamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2868 } else {
2869 if (extended_width == 32)
2870 clamp_name += "iii";
2871 else
2872 clamp_name += "sss";
2873 }
2874 auto callee = F.getParent()->getOrInsertFunction(clamp_name, func_ty);
2875 auto clamp = builder.CreateCall(callee, {add, min, max});
2876 return builder.CreateTrunc(clamp, ty);
2877 } else {
2878 auto struct_ty = GetPairStruct(ty);
2879 // Compute
2880 // {hi, lo} = smul_extended(a, b)
2881 // add = lo + c
2882 auto mul_ext = InsertSPIRVOp(Call, spv::OpSMulExtended,
2883 {Attribute::ReadNone}, struct_ty, {a, b});
2884 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2885 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2886 auto add = builder.CreateAdd(mul_lo, c);
2887
2888 // Constants for use in the calculation.
2889 Constant *min = ConstantInt::get(Call->getContext(),
2890 APInt::getSignedMinValue(bitwidth));
2891 Constant *max = ConstantInt::get(Call->getContext(),
2892 APInt::getSignedMaxValue(bitwidth));
2893 Constant *max_plus_1 = ConstantInt::get(
2894 Call->getContext(),
2895 APInt::getSignedMaxValue(bitwidth) + APInt(bitwidth, 1));
2896 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2897 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2898 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2899 max_plus_1 =
2900 ConstantVector::getSplat(vec_ty->getElementCount(), max_plus_1);
2901 }
2902
2903 auto a_xor_b = builder.CreateXor(a, b);
2904 auto same_sign =
2905 builder.CreateICmpSGT(a_xor_b, Constant::getAllOnesValue(ty));
2906 auto different_sign = builder.CreateNot(same_sign);
2907 auto hi_eq_0 = builder.CreateICmpEQ(mul_hi, Constant::getNullValue(ty));
2908 auto hi_ne_0 = builder.CreateNot(hi_eq_0);
2909 auto lo_ge_max = builder.CreateICmpUGE(mul_lo, max);
2910 auto c_gt_0 = builder.CreateICmpSGT(c, Constant::getNullValue(ty));
2911 auto c_lt_0 = builder.CreateICmpSLT(c, Constant::getNullValue(ty));
2912 auto add_gt_max = builder.CreateICmpUGT(add, max);
2913 auto hi_eq_m1 =
2914 builder.CreateICmpEQ(mul_hi, Constant::getAllOnesValue(ty));
2915 auto hi_ne_m1 = builder.CreateNot(hi_eq_m1);
2916 auto lo_le_max_plus_1 = builder.CreateICmpULE(mul_lo, max_plus_1);
2917 auto max_sub_lo = builder.CreateSub(max, mul_lo);
2918 auto c_lt_max_sub_lo = builder.CreateICmpULT(c, max_sub_lo);
2919
2920 // Equivalent to:
2921 // if (((x < 0) == (y < 0)) && mul_hi != 0)
2922 // return MAX
2923 // if (mul_hi == 0 && mul_lo >= MAX && (z > 0 || add > MAX))
2924 // return MAX
2925 // if (((x < 0) != (y < 0)) && mul_hi != -1)
2926 // return MIN
2927 // if (hi == -1 && mul_lo <= (MAX + 1) && (z < 0 || z < (MAX - mul_lo))
2928 // return MIN
2929 // return add
2930 auto max_clamp_1 = builder.CreateAnd(same_sign, hi_ne_0);
2931 auto max_clamp_2 = builder.CreateOr(c_gt_0, add_gt_max);
2932 auto tmp = builder.CreateAnd(hi_eq_0, lo_ge_max);
2933 max_clamp_2 = builder.CreateAnd(tmp, max_clamp_2);
2934 auto max_clamp = builder.CreateOr(max_clamp_1, max_clamp_2);
2935 auto min_clamp_1 = builder.CreateAnd(different_sign, hi_ne_m1);
2936 auto min_clamp_2 = builder.CreateOr(c_lt_0, c_lt_max_sub_lo);
2937 tmp = builder.CreateAnd(hi_eq_m1, lo_le_max_plus_1);
2938 min_clamp_2 = builder.CreateAnd(tmp, min_clamp_2);
2939 auto min_clamp = builder.CreateOr(min_clamp_1, min_clamp_2);
2940 auto sel = builder.CreateSelect(min_clamp, min, add);
2941 return builder.CreateSelect(max_clamp, max, sel);
2942 }
2943 } else {
2944 // {lo, hi} = mul_extended(a, b)
2945 // {add, carry} = add_carry(lo, c)
2946 // cmp = (mul_hi | carry) == 0
2947 // mad_sat = cmp ? add : MAX
2948 auto struct_ty = GetPairStruct(ty);
2949 auto mul_ext = InsertSPIRVOp(Call, spv::OpUMulExtended,
2950 {Attribute::ReadNone}, struct_ty, {a, b});
2951 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2952 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2953 auto add_carry =
2954 InsertSPIRVOp(Call, spv::OpIAddCarry, {Attribute::ReadNone},
2955 struct_ty, {mul_lo, c});
2956 auto add = builder.CreateExtractValue(add_carry, {0});
2957 auto carry = builder.CreateExtractValue(add_carry, {1});
2958 auto or_value = builder.CreateOr(mul_hi, carry);
2959 auto cmp = builder.CreateICmpEQ(or_value, Constant::getNullValue(ty));
2960 return builder.CreateSelect(cmp, add, Constant::getAllOnesValue(ty));
2961 }
2962 });
2963}