blob: 8e0a554756e61c5f44c7b4f80fe296d9a4c42167 [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);
alan-baker3e217772020-11-07 17:29:40 -0500240 bool replaceRelational(Function &F, CmpInst::Predicate P);
SJW2c317da2020-03-23 07:39:13 -0500241 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-baker2cecaa72020-11-05 14:05:20 -0500280 bool replaceCountZeroes(Function &F, bool leading);
alan-baker6b9d1ee2020-11-03 23:11:32 -0500281 bool replaceMadSat(Function &F, bool is_signed);
alan-baker15106572020-11-06 15:08:10 -0500282 bool replaceOrdered(Function &F, bool is_ordered);
alan-baker497920b2020-11-09 16:41:36 -0500283 bool replaceIsNormal(Function &F);
alan-bakere0406e72020-11-10 12:32:04 -0500284 bool replaceFDim(Function &F);
alan-baker3e0de472020-12-08 15:57:17 -0500285 bool replaceRound(Function &F);
286 bool replaceTrigPi(Function &F, Builtins::BuiltinType type);
alan-baker8b968112020-12-15 15:53:29 -0500287 bool replaceSincos(Function &F);
288 bool replaceExpm1(Function &F);
289 bool replacePown(Function &F);
alan-baker6b9d1ee2020-11-03 23:11:32 -0500290
291 // Caches struct types for { |type|, |type| }. This prevents
292 // getOrInsertFunction from introducing a bitcasts between structs with
293 // identical contents.
294 Type *GetPairStruct(Type *type);
295
296 DenseMap<Type *, Type *> PairStructMap;
David Neto22f144c2017-06-12 14:26:21 -0400297};
SJW2c317da2020-03-23 07:39:13 -0500298
Kévin Petit91bc72e2019-04-08 15:17:46 +0100299} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400300
301char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400302INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
303 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400304
305namespace clspv {
306ModulePass *createReplaceOpenCLBuiltinPass() {
307 return new ReplaceOpenCLBuiltinPass();
308}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400309} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400310
311bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500312 std::list<Function *> func_list;
313 for (auto &F : M.getFunctionList()) {
314 // process only function declarations
315 if (F.isDeclaration() && runOnFunction(F)) {
316 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000317 }
318 }
SJW2c317da2020-03-23 07:39:13 -0500319 if (func_list.size() != 0) {
320 // recursively convert functions, but first remove dead
321 for (auto *F : func_list) {
322 if (F->use_empty()) {
323 F->eraseFromParent();
324 }
325 }
326 runOnModule(M);
327 return true;
328 }
329 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000330}
331
SJW2c317da2020-03-23 07:39:13 -0500332bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
333 auto &FI = Builtins::Lookup(&F);
334 switch (FI.getType()) {
335 case Builtins::kAbs:
336 if (!FI.getParameter(0).is_signed) {
337 return replaceAbs(F);
338 }
339 break;
340 case Builtins::kAbsDiff:
341 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400342
343 case Builtins::kAddSat:
alan-baker3f1bf492020-11-05 09:07:36 -0500344 return replaceAddSubSat(F, FI.getParameter(0).is_signed, true);
alan-bakera52b7312020-10-26 08:58:51 -0400345
alan-bakercc2bafb2020-11-02 08:30:18 -0500346 case Builtins::kClz:
alan-baker2cecaa72020-11-05 14:05:20 -0500347 return replaceCountZeroes(F, true);
348
349 case Builtins::kCtz:
350 return replaceCountZeroes(F, false);
alan-bakercc2bafb2020-11-02 08:30:18 -0500351
alan-bakerb6da5132020-10-29 15:59:06 -0400352 case Builtins::kHadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000353 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::And);
alan-bakerb6da5132020-10-29 15:59:06 -0400354 case Builtins::kRhadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000355 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::Or);
alan-bakerb6da5132020-10-29 15:59:06 -0400356
SJW2c317da2020-03-23 07:39:13 -0500357 case Builtins::kCopysign:
358 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100359
SJW2c317da2020-03-23 07:39:13 -0500360 case Builtins::kHalfRecip:
361 case Builtins::kNativeRecip:
362 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100363
SJW2c317da2020-03-23 07:39:13 -0500364 case Builtins::kHalfDivide:
365 case Builtins::kNativeDivide:
366 return replaceDivide(F);
367
368 case Builtins::kDot:
369 return replaceDot(F);
370
371 case Builtins::kExp10:
372 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500373 case Builtins::kNativeExp10:
374 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500375
alan-baker8b968112020-12-15 15:53:29 -0500376 case Builtins::kExpm1:
377 return replaceExpm1(F);
378
SJW2c317da2020-03-23 07:39:13 -0500379 case Builtins::kLog10:
380 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500381 case Builtins::kNativeLog10:
382 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500383
gnl21636e7992020-09-09 16:08:16 +0100384 case Builtins::kLog1p:
385 return replaceLog1p(F);
386
alan-bakere0406e72020-11-10 12:32:04 -0500387 case Builtins::kFdim:
388 return replaceFDim(F);
389
SJW2c317da2020-03-23 07:39:13 -0500390 case Builtins::kFmod:
391 return replaceFmod(F);
392
alan-baker8b968112020-12-15 15:53:29 -0500393 case Builtins::kPown:
394 return replacePown(F);
395
alan-baker3e0de472020-12-08 15:57:17 -0500396 case Builtins::kRound:
397 return replaceRound(F);
398
399 case Builtins::kCospi:
400 case Builtins::kSinpi:
401 case Builtins::kTanpi:
402 return replaceTrigPi(F, FI.getType());
403
alan-baker8b968112020-12-15 15:53:29 -0500404 case Builtins::kSincos:
405 return replaceSincos(F);
406
SJW2c317da2020-03-23 07:39:13 -0500407 case Builtins::kBarrier:
408 case Builtins::kWorkGroupBarrier:
409 return replaceBarrier(F);
410
alan-baker12d2c182020-07-20 08:22:42 -0400411 case Builtins::kSubGroupBarrier:
412 return replaceBarrier(F, true);
413
SJW2c317da2020-03-23 07:39:13 -0500414 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400415 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500416 case Builtins::kReadMemFence:
417 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
418 case Builtins::kWriteMemFence:
419 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
420
421 // Relational
422 case Builtins::kIsequal:
alan-baker3e217772020-11-07 17:29:40 -0500423 return replaceRelational(F, CmpInst::FCMP_OEQ);
SJW2c317da2020-03-23 07:39:13 -0500424 case Builtins::kIsgreater:
alan-baker3e217772020-11-07 17:29:40 -0500425 return replaceRelational(F, CmpInst::FCMP_OGT);
SJW2c317da2020-03-23 07:39:13 -0500426 case Builtins::kIsgreaterequal:
alan-baker3e217772020-11-07 17:29:40 -0500427 return replaceRelational(F, CmpInst::FCMP_OGE);
SJW2c317da2020-03-23 07:39:13 -0500428 case Builtins::kIsless:
alan-baker3e217772020-11-07 17:29:40 -0500429 return replaceRelational(F, CmpInst::FCMP_OLT);
SJW2c317da2020-03-23 07:39:13 -0500430 case Builtins::kIslessequal:
alan-baker3e217772020-11-07 17:29:40 -0500431 return replaceRelational(F, CmpInst::FCMP_OLE);
SJW2c317da2020-03-23 07:39:13 -0500432 case Builtins::kIsnotequal:
alan-baker3e217772020-11-07 17:29:40 -0500433 return replaceRelational(F, CmpInst::FCMP_UNE);
434 case Builtins::kIslessgreater:
435 return replaceRelational(F, CmpInst::FCMP_ONE);
SJW2c317da2020-03-23 07:39:13 -0500436
alan-baker15106572020-11-06 15:08:10 -0500437 case Builtins::kIsordered:
438 return replaceOrdered(F, true);
439
440 case Builtins::kIsunordered:
441 return replaceOrdered(F, false);
442
SJW2c317da2020-03-23 07:39:13 -0500443 case Builtins::kIsinf: {
444 bool is_vec = FI.getParameter(0).vector_size != 0;
445 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
446 }
447 case Builtins::kIsnan: {
448 bool is_vec = FI.getParameter(0).vector_size != 0;
449 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
450 }
451
452 case Builtins::kIsfinite:
453 return replaceIsFinite(F);
454
455 case Builtins::kAll: {
456 bool is_vec = FI.getParameter(0).vector_size != 0;
457 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
458 }
459 case Builtins::kAny: {
460 bool is_vec = FI.getParameter(0).vector_size != 0;
461 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
462 }
463
alan-baker497920b2020-11-09 16:41:36 -0500464 case Builtins::kIsnormal:
465 return replaceIsNormal(F);
466
SJW2c317da2020-03-23 07:39:13 -0500467 case Builtins::kUpsample:
468 return replaceUpsample(F);
469
470 case Builtins::kRotate:
471 return replaceRotate(F);
472
473 case Builtins::kConvert:
474 return replaceConvert(F, FI.getParameter(0).is_signed,
475 FI.getReturnType().is_signed);
476
alan-baker4986eff2020-10-29 13:38:00 -0400477 // OpenCL 2.0 explicit atomics have different default scopes and semantics
478 // than legacy atomic functions.
479 case Builtins::kAtomicLoad:
480 case Builtins::kAtomicLoadExplicit:
481 return replaceAtomicLoad(F);
482 case Builtins::kAtomicStore:
483 case Builtins::kAtomicStoreExplicit:
484 return replaceExplicitAtomics(F, spv::OpAtomicStore,
485 spv::MemorySemanticsReleaseMask);
486 case Builtins::kAtomicExchange:
487 case Builtins::kAtomicExchangeExplicit:
488 return replaceExplicitAtomics(F, spv::OpAtomicExchange);
489 case Builtins::kAtomicFetchAdd:
490 case Builtins::kAtomicFetchAddExplicit:
491 return replaceExplicitAtomics(F, spv::OpAtomicIAdd);
492 case Builtins::kAtomicFetchSub:
493 case Builtins::kAtomicFetchSubExplicit:
494 return replaceExplicitAtomics(F, spv::OpAtomicISub);
495 case Builtins::kAtomicFetchOr:
496 case Builtins::kAtomicFetchOrExplicit:
497 return replaceExplicitAtomics(F, spv::OpAtomicOr);
498 case Builtins::kAtomicFetchXor:
499 case Builtins::kAtomicFetchXorExplicit:
500 return replaceExplicitAtomics(F, spv::OpAtomicXor);
501 case Builtins::kAtomicFetchAnd:
502 case Builtins::kAtomicFetchAndExplicit:
503 return replaceExplicitAtomics(F, spv::OpAtomicAnd);
504 case Builtins::kAtomicFetchMin:
505 case Builtins::kAtomicFetchMinExplicit:
506 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
507 ? spv::OpAtomicSMin
508 : spv::OpAtomicUMin);
509 case Builtins::kAtomicFetchMax:
510 case Builtins::kAtomicFetchMaxExplicit:
511 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
512 ? spv::OpAtomicSMax
513 : spv::OpAtomicUMax);
514 // Weak compare exchange is generated as strong compare exchange.
515 case Builtins::kAtomicCompareExchangeWeak:
516 case Builtins::kAtomicCompareExchangeWeakExplicit:
517 case Builtins::kAtomicCompareExchangeStrong:
518 case Builtins::kAtomicCompareExchangeStrongExplicit:
519 return replaceAtomicCompareExchange(F);
520
521 // Legacy atomic functions.
SJW2c317da2020-03-23 07:39:13 -0500522 case Builtins::kAtomicInc:
523 return replaceAtomics(F, spv::OpAtomicIIncrement);
524 case Builtins::kAtomicDec:
525 return replaceAtomics(F, spv::OpAtomicIDecrement);
526 case Builtins::kAtomicCmpxchg:
527 return replaceAtomics(F, spv::OpAtomicCompareExchange);
528 case Builtins::kAtomicAdd:
529 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
530 case Builtins::kAtomicSub:
531 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
532 case Builtins::kAtomicXchg:
533 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
534 case Builtins::kAtomicMin:
535 return replaceAtomics(F, FI.getParameter(0).is_signed
536 ? llvm::AtomicRMWInst::Min
537 : llvm::AtomicRMWInst::UMin);
538 case Builtins::kAtomicMax:
539 return replaceAtomics(F, FI.getParameter(0).is_signed
540 ? llvm::AtomicRMWInst::Max
541 : llvm::AtomicRMWInst::UMax);
542 case Builtins::kAtomicAnd:
543 return replaceAtomics(F, llvm::AtomicRMWInst::And);
544 case Builtins::kAtomicOr:
545 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
546 case Builtins::kAtomicXor:
547 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
548
549 case Builtins::kCross:
550 if (FI.getParameter(0).vector_size == 4) {
551 return replaceCross(F);
552 }
553 break;
554
555 case Builtins::kFract:
556 if (FI.getParameterCount()) {
557 return replaceFract(F, FI.getParameter(0).vector_size);
558 }
559 break;
560
561 case Builtins::kMadHi:
562 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
563 case Builtins::kMulHi:
564 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
565
alan-baker6b9d1ee2020-11-03 23:11:32 -0500566 case Builtins::kMadSat:
567 return replaceMadSat(F, FI.getParameter(0).is_signed);
568
SJW2c317da2020-03-23 07:39:13 -0500569 case Builtins::kMad:
570 case Builtins::kMad24:
571 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
572 true);
573 case Builtins::kMul24:
574 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
575 false);
576
577 case Builtins::kSelect:
578 return replaceSelect(F);
579
580 case Builtins::kBitselect:
581 return replaceBitSelect(F);
582
583 case Builtins::kVload:
584 return replaceVload(F);
585
586 case Builtins::kVloadaHalf:
587 case Builtins::kVloadHalf:
588 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
589
590 case Builtins::kVstore:
591 return replaceVstore(F);
592
593 case Builtins::kVstoreHalf:
594 case Builtins::kVstoreaHalf:
595 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
596
597 case Builtins::kSmoothstep: {
598 int vec_size = FI.getLastParameter().vector_size;
599 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500600 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500601 }
602 break;
603 }
604 case Builtins::kStep: {
605 int vec_size = FI.getLastParameter().vector_size;
606 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500607 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500608 }
609 break;
610 }
611
612 case Builtins::kSignbit:
613 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
614
alan-baker3f1bf492020-11-05 09:07:36 -0500615 case Builtins::kSubSat:
616 return replaceAddSubSat(F, FI.getParameter(0).is_signed, false);
617
SJW2c317da2020-03-23 07:39:13 -0500618 case Builtins::kReadImageh:
619 return replaceHalfReadImage(F);
620 case Builtins::kReadImagef:
621 case Builtins::kReadImagei:
622 case Builtins::kReadImageui: {
623 if (FI.getParameter(1).isSampler() &&
624 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
625 return replaceSampledReadImageWithIntCoords(F);
626 }
627 break;
628 }
629
630 case Builtins::kWriteImageh:
631 return replaceHalfWriteImage(F);
632
Kévin Petit1cb45112020-04-27 18:55:48 +0100633 case Builtins::kPrefetch:
634 return replacePrefetch(F);
635
SJW2c317da2020-03-23 07:39:13 -0500636 default:
637 break;
638 }
639
640 return false;
641}
642
alan-baker6b9d1ee2020-11-03 23:11:32 -0500643Type *ReplaceOpenCLBuiltinPass::GetPairStruct(Type *type) {
644 auto iter = PairStructMap.find(type);
645 if (iter != PairStructMap.end())
646 return iter->second;
647
648 auto new_struct = StructType::get(type->getContext(), {type, type});
649 PairStructMap[type] = new_struct;
650 return new_struct;
651}
652
SJW2c317da2020-03-23 07:39:13 -0500653bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
654 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400655 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100656}
657
SJW2c317da2020-03-23 07:39:13 -0500658bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
659 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100660 auto XValue = CI->getOperand(0);
661 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100662
Kévin Petite8edce32019-04-10 14:23:32 +0100663 IRBuilder<> Builder(CI);
664 auto XmY = Builder.CreateSub(XValue, YValue);
665 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100666
SJW2c317da2020-03-23 07:39:13 -0500667 Value *Cmp = nullptr;
668 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100669 Cmp = Builder.CreateICmpSGT(YValue, XValue);
670 } else {
671 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100672 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100673
Kévin Petite8edce32019-04-10 14:23:32 +0100674 return Builder.CreateSelect(Cmp, YmX, XmY);
675 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100676}
677
SJW2c317da2020-03-23 07:39:13 -0500678bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
alan-baker5f2e88e2020-12-07 15:24:04 -0500679 return replaceCallsWithValue(F, [&F](CallInst *Call) {
680 const auto x = Call->getArgOperand(0);
681 const auto y = Call->getArgOperand(1);
682 auto intrinsic = Intrinsic::getDeclaration(
683 F.getParent(), Intrinsic::copysign, Call->getType());
684 return CallInst::Create(intrinsic->getFunctionType(), intrinsic, {x, y}, "",
685 Call);
Kévin Petite8edce32019-04-10 14:23:32 +0100686 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100687}
688
SJW2c317da2020-03-23 07:39:13 -0500689bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
690 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100691 // Recip has one arg.
692 auto Arg = CI->getOperand(0);
693 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
694 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
695 });
David Neto22f144c2017-06-12 14:26:21 -0400696}
697
SJW2c317da2020-03-23 07:39:13 -0500698bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
699 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100700 auto Op0 = CI->getOperand(0);
701 auto Op1 = CI->getOperand(1);
702 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
703 });
David Neto22f144c2017-06-12 14:26:21 -0400704}
705
SJW2c317da2020-03-23 07:39:13 -0500706bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
707 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100708 auto Op0 = CI->getOperand(0);
709 auto Op1 = CI->getOperand(1);
710
SJW2c317da2020-03-23 07:39:13 -0500711 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100712 if (Op0->getType()->isVectorTy()) {
713 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
714 CI->getType(), {Op0, Op1});
715 } else {
716 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
717 }
718
719 return V;
720 });
721}
722
SJW2c317da2020-03-23 07:39:13 -0500723bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500724 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500725 // convert to natural
726 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500727 std::string NewFName = basename.substr(0, slen);
728 NewFName =
729 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400730
SJW2c317da2020-03-23 07:39:13 -0500731 Module &M = *F.getParent();
732 return replaceCallsWithValue(F, [&](CallInst *CI) {
733 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
734
735 auto Arg = CI->getOperand(0);
736
737 // Constant of the natural log of 10 (ln(10)).
738 const double Ln10 =
739 2.302585092994045684017991454684364207601101488628772976033;
740
741 auto Mul = BinaryOperator::Create(
742 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
743
744 return CallInst::Create(NewF, Mul, "", CI);
745 });
David Neto22f144c2017-06-12 14:26:21 -0400746}
747
SJW2c317da2020-03-23 07:39:13 -0500748bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100749 // OpenCL fmod(x,y) is x - y * trunc(x/y)
750 // The sign for a non-zero result is taken from x.
751 // (Try an example.)
752 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500753 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100754 auto Op0 = CI->getOperand(0);
755 auto Op1 = CI->getOperand(1);
756 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
757 });
758}
759
SJW2c317da2020-03-23 07:39:13 -0500760bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500761 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500762 // convert to natural
763 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500764 std::string NewFName = basename.substr(0, slen);
765 NewFName =
766 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400767
SJW2c317da2020-03-23 07:39:13 -0500768 Module &M = *F.getParent();
769 return replaceCallsWithValue(F, [&](CallInst *CI) {
770 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
771
772 auto Arg = CI->getOperand(0);
773
774 // Constant of the reciprocal of the natural log of 10 (ln(10)).
775 const double Ln10 =
776 0.434294481903251827651128918916605082294397005803666566114;
777
778 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
779
780 return BinaryOperator::Create(Instruction::FMul,
781 ConstantFP::get(Arg->getType(), Ln10), NewCI,
782 "", CI);
783 });
David Neto22f144c2017-06-12 14:26:21 -0400784}
785
gnl21636e7992020-09-09 16:08:16 +0100786bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
787 // convert to natural
alan-baker8b968112020-12-15 15:53:29 -0500788 return replaceCallsWithValue(F, [&F](CallInst *CI) {
gnl21636e7992020-09-09 16:08:16 +0100789 auto Arg = CI->getOperand(0);
790
791 auto ArgP1 = BinaryOperator::Create(
792 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
793
alan-baker8b968112020-12-15 15:53:29 -0500794 auto log =
795 Intrinsic::getDeclaration(F.getParent(), Intrinsic::log, CI->getType());
796 return CallInst::Create(log, ArgP1, "", CI);
gnl21636e7992020-09-09 16:08:16 +0100797 });
798}
799
alan-baker12d2c182020-07-20 08:22:42 -0400800bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400801
alan-bakerf6bc8252020-09-23 14:58:55 -0400802 enum {
803 CLK_LOCAL_MEM_FENCE = 0x01,
804 CLK_GLOBAL_MEM_FENCE = 0x02,
805 CLK_IMAGE_MEM_FENCE = 0x04
806 };
David Neto22f144c2017-06-12 14:26:21 -0400807
alan-baker12d2c182020-07-20 08:22:42 -0400808 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100809 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400810
Kévin Petitc4643922019-06-17 19:32:05 +0100811 // We need to map the OpenCL constants to the SPIR-V equivalents.
812 const auto LocalMemFence =
813 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
814 const auto GlobalMemFence =
815 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400816 const auto ImageMemFence =
817 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400818 const auto ConstantAcquireRelease = ConstantInt::get(
819 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100820 const auto ConstantScopeDevice =
821 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
822 const auto ConstantScopeWorkgroup =
823 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400824 const auto ConstantScopeSubgroup =
825 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400826
Kévin Petitc4643922019-06-17 19:32:05 +0100827 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
828 const auto LocalMemFenceMask =
829 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
830 const auto WorkgroupShiftAmount =
831 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
832 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
833 Instruction::Shl, LocalMemFenceMask,
834 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400835
Kévin Petitc4643922019-06-17 19:32:05 +0100836 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
837 const auto GlobalMemFenceMask =
838 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
839 const auto UniformShiftAmount =
840 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
841 const auto MemorySemanticsUniform = BinaryOperator::Create(
842 Instruction::Shl, GlobalMemFenceMask,
843 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400844
alan-bakerf6bc8252020-09-23 14:58:55 -0400845 // OpenCL 2.0
846 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
847 const auto ImageMemFenceMask =
848 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
849 const auto ImageShiftAmount =
850 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
851 const auto MemorySemanticsImage = BinaryOperator::Create(
852 Instruction::Shl, ImageMemFenceMask,
853 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
854
Kévin Petitc4643922019-06-17 19:32:05 +0100855 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400856 // MemorySemanticsSequentiallyConsistentMask.
857 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100858 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400859 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400860 auto MemorySemantics2 = BinaryOperator::Create(
861 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
862 auto MemorySemantics = BinaryOperator::Create(
863 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400864
alan-baker12d2c182020-07-20 08:22:42 -0400865 // If the memory scope is not specified explicitly, it is either Subgroup
866 // or Workgroup depending on the type of barrier.
867 Value *MemoryScope =
868 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
869 if (CI->data_operands_size() > 1) {
870 enum {
871 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
872 CL_MEMORY_SCOPE_DEVICE = 0x2,
873 CL_MEMORY_SCOPE_SUBGROUP = 0x4
874 };
875 // The call was given an explicit memory scope.
876 const auto MemoryScopeSubgroup =
877 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
878 const auto MemoryScopeDevice =
879 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400880
alan-baker12d2c182020-07-20 08:22:42 -0400881 auto Cmp =
882 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
883 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
884 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
885 ConstantScopeWorkgroup, "", CI);
886 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
887 MemoryScopeDevice, CI->getOperand(1), "", CI);
888 MemoryScope =
889 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
890 }
891
892 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
893 // the type of barrier;
894 const auto ExecutionScope =
895 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400896
Kévin Petitc4643922019-06-17 19:32:05 +0100897 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400898 {Attribute::NoDuplicate, Attribute::Convergent},
899 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100900 {ExecutionScope, MemoryScope, MemorySemantics});
901 });
David Neto22f144c2017-06-12 14:26:21 -0400902}
903
SJW2c317da2020-03-23 07:39:13 -0500904bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
905 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400906
SJW2c317da2020-03-23 07:39:13 -0500907 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400908 enum {
909 CLK_LOCAL_MEM_FENCE = 0x01,
910 CLK_GLOBAL_MEM_FENCE = 0x02,
911 CLK_IMAGE_MEM_FENCE = 0x04,
912 };
David Neto22f144c2017-06-12 14:26:21 -0400913
SJW2c317da2020-03-23 07:39:13 -0500914 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400915
SJW2c317da2020-03-23 07:39:13 -0500916 // We need to map the OpenCL constants to the SPIR-V equivalents.
917 const auto LocalMemFence =
918 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
919 const auto GlobalMemFence =
920 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400921 const auto ImageMemFence =
922 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500923 const auto ConstantMemorySemantics =
924 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400925 const auto ConstantScopeWorkgroup =
926 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400927
SJW2c317da2020-03-23 07:39:13 -0500928 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
929 const auto LocalMemFenceMask =
930 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
931 const auto WorkgroupShiftAmount =
932 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
933 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
934 Instruction::Shl, LocalMemFenceMask,
935 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400936
SJW2c317da2020-03-23 07:39:13 -0500937 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
938 const auto GlobalMemFenceMask =
939 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
940 const auto UniformShiftAmount =
941 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
942 const auto MemorySemanticsUniform = BinaryOperator::Create(
943 Instruction::Shl, GlobalMemFenceMask,
944 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400945
alan-bakerf6bc8252020-09-23 14:58:55 -0400946 // OpenCL 2.0
947 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
948 const auto ImageMemFenceMask =
949 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
950 const auto ImageShiftAmount =
951 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
952 const auto MemorySemanticsImage = BinaryOperator::Create(
953 Instruction::Shl, ImageMemFenceMask,
954 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
955
SJW2c317da2020-03-23 07:39:13 -0500956 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400957 // |semantics|.
958 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500959 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
960 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400961 auto MemorySemantics2 = BinaryOperator::Create(
962 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
963 auto MemorySemantics = BinaryOperator::Create(
964 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400965
alan-baker12d2c182020-07-20 08:22:42 -0400966 // Memory Scope is always workgroup.
967 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400968
alan-baker3d905692020-10-28 14:02:37 -0400969 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
970 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500971 {MemoryScope, MemorySemantics});
972 });
David Neto22f144c2017-06-12 14:26:21 -0400973}
974
Kévin Petit1cb45112020-04-27 18:55:48 +0100975bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
976 bool Changed = false;
977
978 SmallVector<Instruction *, 4> ToRemoves;
979
980 // Find all calls to the function
981 for (auto &U : F.uses()) {
982 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
983 ToRemoves.push_back(CI);
984 }
985 }
986
987 Changed = !ToRemoves.empty();
988
989 // Delete them
990 for (auto V : ToRemoves) {
991 V->eraseFromParent();
992 }
993
994 return Changed;
995}
996
SJW2c317da2020-03-23 07:39:13 -0500997bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
alan-baker3e217772020-11-07 17:29:40 -0500998 CmpInst::Predicate P) {
SJW2c317da2020-03-23 07:39:13 -0500999 return replaceCallsWithValue(F, [&](CallInst *CI) {
1000 // The predicate to use in the CmpInst.
1001 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -04001002
SJW2c317da2020-03-23 07:39:13 -05001003 auto Arg1 = CI->getOperand(0);
1004 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001005
SJW2c317da2020-03-23 07:39:13 -05001006 const auto Cmp =
1007 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
alan-baker3e217772020-11-07 17:29:40 -05001008 if (isa<VectorType>(F.getReturnType()))
1009 return CastInst::Create(Instruction::SExt, Cmp, CI->getType(), "", CI);
1010 return CastInst::Create(Instruction::ZExt, Cmp, CI->getType(), "", CI);
SJW2c317da2020-03-23 07:39:13 -05001011 });
David Neto22f144c2017-06-12 14:26:21 -04001012}
1013
SJW2c317da2020-03-23 07:39:13 -05001014bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
1015 spv::Op SPIRVOp,
1016 int32_t C) {
1017 Module &M = *F.getParent();
1018 return replaceCallsWithValue(F, [&](CallInst *CI) {
1019 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -04001020
SJW2c317da2020-03-23 07:39:13 -05001021 // The value to return for true.
1022 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -04001023
SJW2c317da2020-03-23 07:39:13 -05001024 // The value to return for false.
1025 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -04001026
SJW2c317da2020-03-23 07:39:13 -05001027 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -04001028 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001029 CorrespondingBoolTy =
1030 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
1031 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04001032 }
David Neto22f144c2017-06-12 14:26:21 -04001033
SJW2c317da2020-03-23 07:39:13 -05001034 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
1035 CorrespondingBoolTy, {CI->getOperand(0)});
1036
1037 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
1038 });
David Neto22f144c2017-06-12 14:26:21 -04001039}
1040
SJW2c317da2020-03-23 07:39:13 -05001041bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
1042 Module &M = *F.getParent();
1043 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001044 auto &C = M.getContext();
1045 auto Val = CI->getOperand(0);
1046 auto ValTy = Val->getType();
1047 auto RetTy = CI->getType();
1048
1049 // Get a suitable integer type to represent the number
1050 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
1051
1052 // Create Mask
1053 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -05001054 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001055 switch (ScalarSize) {
1056 case 16:
1057 InfMask = ConstantInt::get(IntTy, 0x7C00U);
1058 break;
1059 case 32:
1060 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
1061 break;
1062 case 64:
1063 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
1064 break;
1065 default:
1066 llvm_unreachable("Unsupported floating-point type");
1067 }
1068
1069 IRBuilder<> Builder(CI);
1070
1071 // Bitcast to int
1072 auto ValInt = Builder.CreateBitCast(Val, IntTy);
1073
1074 // Mask and compare
1075 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
1076 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
1077
1078 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -05001079 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001080 if (ValTy->isVectorTy()) {
1081 RetTrue = ConstantInt::getSigned(RetTy, -1);
1082 } else {
1083 RetTrue = ConstantInt::get(RetTy, 1);
1084 }
1085 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
1086 });
1087}
1088
SJW2c317da2020-03-23 07:39:13 -05001089bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
1090 Module &M = *F.getParent();
1091 return replaceCallsWithValue(F, [&](CallInst *CI) {
1092 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001093
SJW2c317da2020-03-23 07:39:13 -05001094 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001095
SJW2c317da2020-03-23 07:39:13 -05001096 // If the argument is a 32-bit int, just use a shift
1097 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1098 V = BinaryOperator::Create(Instruction::LShr, Arg,
1099 ConstantInt::get(Arg->getType(), 31), "", CI);
1100 } else {
1101 // The value for zero to compare against.
1102 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -04001103
SJW2c317da2020-03-23 07:39:13 -05001104 // The value to return for true.
1105 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04001106
SJW2c317da2020-03-23 07:39:13 -05001107 // The value to return for false.
1108 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001109
SJW2c317da2020-03-23 07:39:13 -05001110 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
1111 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001112
SJW2c317da2020-03-23 07:39:13 -05001113 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04001114
SJW2c317da2020-03-23 07:39:13 -05001115 // If we have a function to call, call it!
1116 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -04001117
SJW2c317da2020-03-23 07:39:13 -05001118 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -04001119
SJW2c317da2020-03-23 07:39:13 -05001120 const auto NewCI = clspv::InsertSPIRVOp(
1121 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
1122 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -04001123
SJW2c317da2020-03-23 07:39:13 -05001124 } else {
1125 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -04001126 }
1127
SJW2c317da2020-03-23 07:39:13 -05001128 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001129 }
SJW2c317da2020-03-23 07:39:13 -05001130 return V;
1131 });
David Neto22f144c2017-06-12 14:26:21 -04001132}
1133
SJW2c317da2020-03-23 07:39:13 -05001134bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
1135 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1136 // Get arguments
1137 auto HiValue = CI->getOperand(0);
1138 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001139
SJW2c317da2020-03-23 07:39:13 -05001140 // Don't touch overloads that aren't in OpenCL C
1141 auto HiType = HiValue->getType();
1142 auto LoType = LoValue->getType();
1143
1144 if (HiType != LoType) {
1145 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001146 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001147
SJW2c317da2020-03-23 07:39:13 -05001148 if (!HiType->isIntOrIntVectorTy()) {
1149 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001150 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001151
SJW2c317da2020-03-23 07:39:13 -05001152 if (HiType->getScalarSizeInBits() * 2 !=
1153 CI->getType()->getScalarSizeInBits()) {
1154 return nullptr;
1155 }
1156
1157 if ((HiType->getScalarSizeInBits() != 8) &&
1158 (HiType->getScalarSizeInBits() != 16) &&
1159 (HiType->getScalarSizeInBits() != 32)) {
1160 return nullptr;
1161 }
1162
James Pricecf53df42020-04-20 14:41:24 -04001163 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001164 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001165 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1166 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001167 return nullptr;
1168 }
1169 }
1170
1171 // Convert both operands to the result type
1172 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1173 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
1174
1175 // Shift high operand
1176 auto ShiftAmount =
1177 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
1178 auto HiShifted =
1179 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
1180
1181 // OR both results
1182 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
1183 });
Kévin Petitbf0036c2019-03-06 13:57:10 +00001184}
1185
SJW2c317da2020-03-23 07:39:13 -05001186bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
1187 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1188 // Get arguments
1189 auto SrcValue = CI->getOperand(0);
1190 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001191
SJW2c317da2020-03-23 07:39:13 -05001192 // Don't touch overloads that aren't in OpenCL C
1193 auto SrcType = SrcValue->getType();
1194 auto RotType = RotAmount->getType();
1195
1196 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1197 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001198 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001199
SJW2c317da2020-03-23 07:39:13 -05001200 if (!SrcType->isIntOrIntVectorTy()) {
1201 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001202 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001203
SJW2c317da2020-03-23 07:39:13 -05001204 if ((SrcType->getScalarSizeInBits() != 8) &&
1205 (SrcType->getScalarSizeInBits() != 16) &&
1206 (SrcType->getScalarSizeInBits() != 32) &&
1207 (SrcType->getScalarSizeInBits() != 64)) {
1208 return nullptr;
1209 }
1210
James Pricecf53df42020-04-20 14:41:24 -04001211 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001212 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001213 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1214 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001215 return nullptr;
1216 }
1217 }
1218
alan-bakerfd22ae12020-10-29 15:59:22 -04001219 // Replace with LLVM's funnel shift left intrinsic because it is more
1220 // generic than rotate.
1221 Function *intrinsic =
1222 Intrinsic::getDeclaration(F.getParent(), Intrinsic::fshl, SrcType);
1223 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
1224 {SrcValue, SrcValue, RotAmount}, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001225 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001226}
1227
SJW2c317da2020-03-23 07:39:13 -05001228bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1229 bool DstIsSigned) {
1230 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1231 Value *V = nullptr;
1232 // Get arguments
1233 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001234
SJW2c317da2020-03-23 07:39:13 -05001235 // Don't touch overloads that aren't in OpenCL C
1236 auto SrcType = SrcValue->getType();
1237 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001238
SJW2c317da2020-03-23 07:39:13 -05001239 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1240 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1241 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001242 }
1243
James Pricecf53df42020-04-20 14:41:24 -04001244 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001245 unsigned SrcNumElements =
1246 SrcVecType->getElementCount().getKnownMinValue();
1247 unsigned DstNumElements =
1248 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001249 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001250 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001251 }
1252
James Pricecf53df42020-04-20 14:41:24 -04001253 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1254 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1255 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001256 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001257 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001258 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001259
SJW2c317da2020-03-23 07:39:13 -05001260 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1261 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1262
1263 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1264 bool DstIsInt = DstType->isIntOrIntVectorTy();
1265
1266 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1267 // Unnecessary cast operation.
1268 V = SrcValue;
1269 } else if (SrcIsFloat && DstIsFloat) {
1270 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1271 } else if (SrcIsFloat && DstIsInt) {
1272 if (DstIsSigned) {
1273 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1274 } else {
1275 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1276 }
1277 } else if (SrcIsInt && DstIsFloat) {
1278 if (SrcIsSigned) {
1279 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1280 } else {
1281 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1282 }
1283 } else if (SrcIsInt && DstIsInt) {
1284 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1285 } else {
1286 // Not something we're supposed to handle, just move on
1287 }
1288
1289 return V;
1290 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001291}
1292
SJW2c317da2020-03-23 07:39:13 -05001293bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1294 bool is_mad) {
1295 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1296 Value *V = nullptr;
1297 // Get arguments
1298 auto AValue = CI->getOperand(0);
1299 auto BValue = CI->getOperand(1);
1300 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001301
SJW2c317da2020-03-23 07:39:13 -05001302 // Don't touch overloads that aren't in OpenCL C
1303 auto AType = AValue->getType();
1304 auto BType = BValue->getType();
1305 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001306
SJW2c317da2020-03-23 07:39:13 -05001307 if ((AType != BType) || (CI->getType() != AType) ||
1308 (is_mad && (AType != CType))) {
1309 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001310 }
1311
SJW2c317da2020-03-23 07:39:13 -05001312 if (!AType->isIntOrIntVectorTy()) {
1313 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001314 }
Kévin Petit8a560882019-03-21 15:24:34 +00001315
SJW2c317da2020-03-23 07:39:13 -05001316 if ((AType->getScalarSizeInBits() != 8) &&
1317 (AType->getScalarSizeInBits() != 16) &&
1318 (AType->getScalarSizeInBits() != 32) &&
1319 (AType->getScalarSizeInBits() != 64)) {
1320 return V;
1321 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001322
James Pricecf53df42020-04-20 14:41:24 -04001323 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001324 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001325 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1326 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001327 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001328 }
1329 }
1330
SJW2c317da2020-03-23 07:39:13 -05001331 // Our SPIR-V op returns a struct, create a type for it
alan-baker6b9d1ee2020-11-03 23:11:32 -05001332 auto ExMulRetType = GetPairStruct(AType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001333
SJW2c317da2020-03-23 07:39:13 -05001334 // Select the appropriate signed/unsigned SPIR-V op
1335 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1336
1337 // Call the SPIR-V op
1338 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1339 ExMulRetType, {AValue, BValue});
1340
1341 // Get the high part of the result
1342 unsigned Idxs[] = {1};
1343 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1344
1345 // If we're handling a mad_hi, add the third argument to the result
1346 if (is_mad) {
1347 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001348 }
1349
SJW2c317da2020-03-23 07:39:13 -05001350 return V;
1351 });
Kévin Petit8a560882019-03-21 15:24:34 +00001352}
1353
SJW2c317da2020-03-23 07:39:13 -05001354bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1355 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1356 // Get arguments
1357 auto FalseValue = CI->getOperand(0);
1358 auto TrueValue = CI->getOperand(1);
1359 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001360
SJW2c317da2020-03-23 07:39:13 -05001361 // Don't touch overloads that aren't in OpenCL C
1362 auto FalseType = FalseValue->getType();
1363 auto TrueType = TrueValue->getType();
1364 auto PredicateType = PredicateValue->getType();
1365
1366 if (FalseType != TrueType) {
1367 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001368 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001369
SJW2c317da2020-03-23 07:39:13 -05001370 if (!PredicateType->isIntOrIntVectorTy()) {
1371 return nullptr;
1372 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001373
SJW2c317da2020-03-23 07:39:13 -05001374 if (!FalseType->isIntOrIntVectorTy() &&
1375 !FalseType->getScalarType()->isFloatingPointTy()) {
1376 return nullptr;
1377 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001378
SJW2c317da2020-03-23 07:39:13 -05001379 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1380 return nullptr;
1381 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001382
SJW2c317da2020-03-23 07:39:13 -05001383 if (FalseType->getScalarSizeInBits() !=
1384 PredicateType->getScalarSizeInBits()) {
1385 return nullptr;
1386 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001387
James Pricecf53df42020-04-20 14:41:24 -04001388 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001389 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1390 if (NumElements != cast<VectorType>(PredicateType)
1391 ->getElementCount()
1392 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001393 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001394 }
1395
James Pricecf53df42020-04-20 14:41:24 -04001396 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1397 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001398 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001399 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001400 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001401
SJW2c317da2020-03-23 07:39:13 -05001402 // Create constant
1403 const auto ZeroValue = Constant::getNullValue(PredicateType);
1404
1405 // Scalar and vector are to be treated differently
1406 CmpInst::Predicate Pred;
1407 if (PredicateType->isVectorTy()) {
1408 Pred = CmpInst::ICMP_SLT;
1409 } else {
1410 Pred = CmpInst::ICMP_NE;
1411 }
1412
1413 // Create comparison instruction
1414 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1415 ZeroValue, "", CI);
1416
1417 // Create select
1418 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1419 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001420}
1421
SJW2c317da2020-03-23 07:39:13 -05001422bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1423 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1424 Value *V = nullptr;
1425 if (CI->getNumOperands() != 4) {
1426 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001427 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001428
SJW2c317da2020-03-23 07:39:13 -05001429 // Get arguments
1430 auto FalseValue = CI->getOperand(0);
1431 auto TrueValue = CI->getOperand(1);
1432 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001433
SJW2c317da2020-03-23 07:39:13 -05001434 // Don't touch overloads that aren't in OpenCL C
1435 auto FalseType = FalseValue->getType();
1436 auto TrueType = TrueValue->getType();
1437 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001438
SJW2c317da2020-03-23 07:39:13 -05001439 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1440 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001441 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001442
James Pricecf53df42020-04-20 14:41:24 -04001443 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001444 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1445 !TrueType->getScalarType()->isIntegerTy()) {
1446 return V;
1447 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001448 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001449 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1450 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001451 return V;
1452 }
1453 }
1454
1455 // Remember the type of the operands
1456 auto OpType = TrueType;
1457
1458 // The actual bit selection will always be done on an integer type,
1459 // declare it here
1460 Type *BitType;
1461
1462 // If the operands are float, then bitcast them to int
1463 if (OpType->getScalarType()->isFloatingPointTy()) {
1464
1465 // First create the new type
1466 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1467
1468 // Then bitcast all operands
1469 PredicateValue =
1470 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1471 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1472 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1473
1474 } else {
1475 // The operands have an integer type, use it directly
1476 BitType = OpType;
1477 }
1478
1479 // All the operands are now always integers
1480 // implement as (c & b) | (~c & a)
1481
1482 // Create our negated predicate value
1483 auto AllOnes = Constant::getAllOnesValue(BitType);
1484 auto NotPredicateValue = BinaryOperator::Create(
1485 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1486
1487 // Then put everything together
1488 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1489 FalseValue, "", CI);
1490 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1491 TrueValue, "", CI);
1492
1493 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1494
1495 // If we were dealing with a floating point type, we must bitcast
1496 // the result back to that
1497 if (OpType->getScalarType()->isFloatingPointTy()) {
1498 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1499 }
1500
1501 return V;
1502 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001503}
1504
SJW61531372020-06-09 07:31:08 -05001505bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001506 // convert to vector versions
1507 Module &M = *F.getParent();
1508 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1509 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1510 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001511
SJW2c317da2020-03-23 07:39:13 -05001512 // First figure out which function we're dealing with
1513 if (is_smooth) {
1514 ArgsToSplat.push_back(CI->getOperand(1));
1515 VectorArg = CI->getOperand(2);
1516 } else {
1517 VectorArg = CI->getOperand(1);
1518 }
1519
1520 // Splat arguments that need to be
1521 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001522 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001523
1524 for (auto arg : ArgsToSplat) {
1525 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001526 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001527 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1528 NewVectorArg =
1529 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1530 }
1531 SplatArgs.push_back(NewVectorArg);
1532 }
1533
1534 // Replace the call with the vector/vector flavour
1535 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1536 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1537
SJW61531372020-06-09 07:31:08 -05001538 std::string NewFName = Builtins::GetMangledFunctionName(
1539 is_smooth ? "smoothstep" : "step", NewFType);
1540
SJW2c317da2020-03-23 07:39:13 -05001541 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1542
1543 SmallVector<Value *, 3> NewArgs;
1544 for (auto arg : SplatArgs) {
1545 NewArgs.push_back(arg);
1546 }
1547 NewArgs.push_back(VectorArg);
1548
1549 return CallInst::Create(NewF, NewArgs, "", CI);
1550 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001551}
1552
SJW2c317da2020-03-23 07:39:13 -05001553bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001554 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1555 auto Arg = CI->getOperand(0);
1556 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001557
SJW2c317da2020-03-23 07:39:13 -05001558 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001559
SJW2c317da2020-03-23 07:39:13 -05001560 return BinaryOperator::Create(Op, Bitcast,
1561 ConstantInt::get(CI->getType(), 31), "", CI);
1562 });
David Neto22f144c2017-06-12 14:26:21 -04001563}
1564
SJW2c317da2020-03-23 07:39:13 -05001565bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1566 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001567 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1568 // The multiply instruction to use.
1569 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001570
SJW2c317da2020-03-23 07:39:13 -05001571 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001572
SJW2c317da2020-03-23 07:39:13 -05001573 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1574 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001575
SJW2c317da2020-03-23 07:39:13 -05001576 if (is_mad) {
1577 // The add instruction to use.
1578 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001579
SJW2c317da2020-03-23 07:39:13 -05001580 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001581 }
David Neto22f144c2017-06-12 14:26:21 -04001582
SJW2c317da2020-03-23 07:39:13 -05001583 return V;
1584 });
David Neto22f144c2017-06-12 14:26:21 -04001585}
1586
SJW2c317da2020-03-23 07:39:13 -05001587bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001588 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1589 Value *V = nullptr;
1590 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001591
SJW2c317da2020-03-23 07:39:13 -05001592 auto data_type = data->getType();
1593 if (!data_type->isVectorTy())
1594 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001595
James Pricecf53df42020-04-20 14:41:24 -04001596 auto vec_data_type = cast<VectorType>(data_type);
1597
alan-baker5a8c3be2020-09-09 13:44:26 -04001598 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001599 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1600 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001601
SJW2c317da2020-03-23 07:39:13 -05001602 auto offset = CI->getOperand(1);
1603 auto ptr = CI->getOperand(2);
1604 auto ptr_type = ptr->getType();
1605 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001606 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001607 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001608
SJW2c317da2020-03-23 07:39:13 -05001609 // Avoid pointer casts. Instead generate the correct number of stores
1610 // and rely on drivers to coalesce appropriately.
1611 IRBuilder<> builder(CI);
1612 auto elems_const = builder.getInt32(elems);
1613 auto adjust = builder.CreateMul(offset, elems_const);
1614 for (auto i = 0; i < elems; ++i) {
1615 auto idx = builder.getInt32(i);
1616 auto add = builder.CreateAdd(adjust, idx);
1617 auto gep = builder.CreateGEP(ptr, add);
1618 auto extract = builder.CreateExtractElement(data, i);
1619 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001620 }
SJW2c317da2020-03-23 07:39:13 -05001621 return V;
1622 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001623}
1624
SJW2c317da2020-03-23 07:39:13 -05001625bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001626 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1627 Value *V = nullptr;
1628 auto ret_type = F.getReturnType();
1629 if (!ret_type->isVectorTy())
1630 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001631
James Pricecf53df42020-04-20 14:41:24 -04001632 auto vec_ret_type = cast<VectorType>(ret_type);
1633
alan-baker5a8c3be2020-09-09 13:44:26 -04001634 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001635 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1636 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001637
SJW2c317da2020-03-23 07:39:13 -05001638 auto offset = CI->getOperand(0);
1639 auto ptr = CI->getOperand(1);
1640 auto ptr_type = ptr->getType();
1641 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001642 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001643 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001644
SJW2c317da2020-03-23 07:39:13 -05001645 // Avoid pointer casts. Instead generate the correct number of loads
1646 // and rely on drivers to coalesce appropriately.
1647 IRBuilder<> builder(CI);
1648 auto elems_const = builder.getInt32(elems);
1649 V = UndefValue::get(ret_type);
1650 auto adjust = builder.CreateMul(offset, elems_const);
1651 for (auto i = 0; i < elems; ++i) {
1652 auto idx = builder.getInt32(i);
1653 auto add = builder.CreateAdd(adjust, idx);
1654 auto gep = builder.CreateGEP(ptr, add);
1655 auto load = builder.CreateLoad(gep);
1656 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001657 }
SJW2c317da2020-03-23 07:39:13 -05001658 return V;
1659 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001660}
1661
SJW2c317da2020-03-23 07:39:13 -05001662bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1663 const std::string &name,
1664 int vec_size) {
1665 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1666 if (!vec_size) {
1667 // deduce vec_size from last character of name (e.g. vload_half4)
1668 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001669 }
SJW2c317da2020-03-23 07:39:13 -05001670 switch (vec_size) {
1671 case 2:
1672 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1673 case 4:
1674 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1675 case 0:
1676 if (!is_clspv_version) {
1677 return replaceVloadHalf(F);
1678 }
1679 default:
1680 llvm_unreachable("Unsupported vload_half vector size");
1681 break;
1682 }
1683 return false;
David Neto22f144c2017-06-12 14:26:21 -04001684}
1685
SJW2c317da2020-03-23 07:39:13 -05001686bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1687 Module &M = *F.getParent();
1688 return replaceCallsWithValue(F, [&](CallInst *CI) {
1689 // The index argument from vload_half.
1690 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001691
SJW2c317da2020-03-23 07:39:13 -05001692 // The pointer argument from vload_half.
1693 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001694
SJW2c317da2020-03-23 07:39:13 -05001695 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001696 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001697 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1698
1699 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001700 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001701
1702 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1703
1704 Value *V = nullptr;
1705
alan-baker7efcaaa2020-05-06 19:33:27 -04001706 bool supports_16bit_storage = true;
1707 switch (Arg1->getType()->getPointerAddressSpace()) {
1708 case clspv::AddressSpace::Global:
1709 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1710 clspv::Option::StorageClass::kSSBO);
1711 break;
1712 case clspv::AddressSpace::Constant:
1713 if (clspv::Option::ConstantArgsInUniformBuffer())
1714 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1715 clspv::Option::StorageClass::kUBO);
1716 else
1717 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1718 clspv::Option::StorageClass::kSSBO);
1719 break;
1720 default:
1721 // Clspv will emit the Float16 capability if the half type is
1722 // encountered. That capability covers private and local addressspaces.
1723 break;
1724 }
1725
1726 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001727 auto ShortTy = Type::getInt16Ty(M.getContext());
1728 auto ShortPointerTy =
1729 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1730
1731 // Cast the half* pointer to short*.
1732 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1733
1734 // Index into the correct address of the casted pointer.
1735 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1736
1737 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001738 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001739
1740 // ZExt the short -> int.
1741 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1742
1743 // Get our float2.
1744 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1745
1746 // Extract out the bottom element which is our float result.
1747 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1748 } else {
1749 // Assume the pointer argument points to storage aligned to 32bits
1750 // or more.
1751 // TODO(dneto): Do more analysis to make sure this is true?
1752 //
1753 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1754 // with:
1755 //
1756 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1757 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1758 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1759 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1760 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1761 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1762 // x float> %converted, %index_is_odd32
1763
1764 auto IntPointerTy =
1765 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1766
1767 // Cast the base pointer to int*.
1768 // In a valid call (according to assumptions), this should get
1769 // optimized away in the simplify GEP pass.
1770 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1771
1772 auto One = ConstantInt::get(IntTy, 1);
1773 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1774 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1775
1776 // Index into the correct address of the casted pointer.
1777 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1778
1779 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001780 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001781
1782 // Get our float2.
1783 auto Call = CallInst::Create(NewF, Load, "", CI);
1784
1785 // Extract out the float result, where the element number is
1786 // determined by whether the original index was even or odd.
1787 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1788 }
1789 return V;
1790 });
1791}
1792
1793bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1794 Module &M = *F.getParent();
1795 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001796 // The index argument from vload_half.
1797 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001798
Kévin Petite8edce32019-04-10 14:23:32 +01001799 // The pointer argument from vload_half.
1800 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001801
Kévin Petite8edce32019-04-10 14:23:32 +01001802 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001803 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001804 auto NewPointerTy =
1805 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001806 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001807
Kévin Petite8edce32019-04-10 14:23:32 +01001808 // Cast the half* pointer to int*.
1809 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001810
Kévin Petite8edce32019-04-10 14:23:32 +01001811 // Index into the correct address of the casted pointer.
1812 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001813
Kévin Petite8edce32019-04-10 14:23:32 +01001814 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001815 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001816
Kévin Petite8edce32019-04-10 14:23:32 +01001817 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001818 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001819
Kévin Petite8edce32019-04-10 14:23:32 +01001820 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001821
Kévin Petite8edce32019-04-10 14:23:32 +01001822 // Get our float2.
1823 return CallInst::Create(NewF, Load, "", CI);
1824 });
David Neto22f144c2017-06-12 14:26:21 -04001825}
1826
SJW2c317da2020-03-23 07:39:13 -05001827bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1828 Module &M = *F.getParent();
1829 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001830 // The index argument from vload_half.
1831 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001832
Kévin Petite8edce32019-04-10 14:23:32 +01001833 // The pointer argument from vload_half.
1834 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001835
Kévin Petite8edce32019-04-10 14:23:32 +01001836 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001837 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1838 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001839 auto NewPointerTy =
1840 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001841 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001842
Kévin Petite8edce32019-04-10 14:23:32 +01001843 // Cast the half* pointer to int2*.
1844 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001845
Kévin Petite8edce32019-04-10 14:23:32 +01001846 // Index into the correct address of the casted pointer.
1847 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001848
Kévin Petite8edce32019-04-10 14:23:32 +01001849 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001850 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001851
Kévin Petite8edce32019-04-10 14:23:32 +01001852 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001853 auto X =
1854 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1855 auto Y =
1856 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001857
Kévin Petite8edce32019-04-10 14:23:32 +01001858 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001859 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001860
Kévin Petite8edce32019-04-10 14:23:32 +01001861 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001862
Kévin Petite8edce32019-04-10 14:23:32 +01001863 // Get the lower (x & y) components of our final float4.
1864 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001865
Kévin Petite8edce32019-04-10 14:23:32 +01001866 // Get the higher (z & w) components of our final float4.
1867 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001868
Kévin Petite8edce32019-04-10 14:23:32 +01001869 Constant *ShuffleMask[4] = {
1870 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1871 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001872
Kévin Petite8edce32019-04-10 14:23:32 +01001873 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001874 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1875 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001876 });
David Neto22f144c2017-06-12 14:26:21 -04001877}
1878
SJW2c317da2020-03-23 07:39:13 -05001879bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001880
1881 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1882 //
1883 // %u = load i32 %ptr
1884 // %fxy = call <2 x float> Unpack2xHalf(u)
1885 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001886 Module &M = *F.getParent();
1887 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001888 auto Index = CI->getOperand(0);
1889 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001890
Kévin Petite8edce32019-04-10 14:23:32 +01001891 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001892 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001893 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001894
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001895 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001896 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001897
Kévin Petite8edce32019-04-10 14:23:32 +01001898 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001899 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001900
Kévin Petite8edce32019-04-10 14:23:32 +01001901 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 // Get our final float2.
1904 return CallInst::Create(NewF, Load, "", CI);
1905 });
David Neto6ad93232018-06-07 15:42:58 -07001906}
1907
SJW2c317da2020-03-23 07:39:13 -05001908bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001909
1910 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1911 //
1912 // %u2 = load <2 x i32> %ptr
1913 // %u2xy = extractelement %u2, 0
1914 // %u2zw = extractelement %u2, 1
1915 // %fxy = call <2 x float> Unpack2xHalf(uint)
1916 // %fzw = call <2 x float> Unpack2xHalf(uint)
1917 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001918 Module &M = *F.getParent();
1919 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001920 auto Index = CI->getOperand(0);
1921 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001922
Kévin Petite8edce32019-04-10 14:23:32 +01001923 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001924 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1925 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001926 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001927
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001928 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001929 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001930
Kévin Petite8edce32019-04-10 14:23:32 +01001931 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001932 auto X =
1933 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1934 auto Y =
1935 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001936
Kévin Petite8edce32019-04-10 14:23:32 +01001937 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001938 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001939
Kévin Petite8edce32019-04-10 14:23:32 +01001940 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001941
Kévin Petite8edce32019-04-10 14:23:32 +01001942 // Get the lower (x & y) components of our final float4.
1943 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001944
Kévin Petite8edce32019-04-10 14:23:32 +01001945 // Get the higher (z & w) components of our final float4.
1946 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001947
Kévin Petite8edce32019-04-10 14:23:32 +01001948 Constant *ShuffleMask[4] = {
1949 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1950 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001951
Kévin Petite8edce32019-04-10 14:23:32 +01001952 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001953 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1954 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001955 });
David Neto6ad93232018-06-07 15:42:58 -07001956}
1957
SJW2c317da2020-03-23 07:39:13 -05001958bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1959 switch (vec_size) {
1960 case 0:
1961 return replaceVstoreHalf(F);
1962 case 2:
1963 return replaceVstoreHalf2(F);
1964 case 4:
1965 return replaceVstoreHalf4(F);
1966 default:
1967 llvm_unreachable("Unsupported vstore_half vector size");
1968 break;
1969 }
1970 return false;
1971}
David Neto22f144c2017-06-12 14:26:21 -04001972
SJW2c317da2020-03-23 07:39:13 -05001973bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1974 Module &M = *F.getParent();
1975 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001976 // The value to store.
1977 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001978
Kévin Petite8edce32019-04-10 14:23:32 +01001979 // The index argument from vstore_half.
1980 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001981
Kévin Petite8edce32019-04-10 14:23:32 +01001982 // The pointer argument from vstore_half.
1983 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001984
Kévin Petite8edce32019-04-10 14:23:32 +01001985 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001986 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001987 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1988 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001989
Kévin Petite8edce32019-04-10 14:23:32 +01001990 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001991 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001992
Kévin Petite8edce32019-04-10 14:23:32 +01001993 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001994
Kévin Petite8edce32019-04-10 14:23:32 +01001995 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001996 auto TempVec = InsertElementInst::Create(
1997 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001998
Kévin Petite8edce32019-04-10 14:23:32 +01001999 // Pack the float2 -> half2 (in an int).
2000 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002001
alan-baker7efcaaa2020-05-06 19:33:27 -04002002 bool supports_16bit_storage = true;
2003 switch (Arg2->getType()->getPointerAddressSpace()) {
2004 case clspv::AddressSpace::Global:
2005 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2006 clspv::Option::StorageClass::kSSBO);
2007 break;
2008 case clspv::AddressSpace::Constant:
2009 if (clspv::Option::ConstantArgsInUniformBuffer())
2010 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2011 clspv::Option::StorageClass::kUBO);
2012 else
2013 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2014 clspv::Option::StorageClass::kSSBO);
2015 break;
2016 default:
2017 // Clspv will emit the Float16 capability if the half type is
2018 // encountered. That capability covers private and local addressspaces.
2019 break;
2020 }
2021
SJW2c317da2020-03-23 07:39:13 -05002022 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04002023 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01002024 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002025 auto ShortPointerTy =
2026 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002027
Kévin Petite8edce32019-04-10 14:23:32 +01002028 // Truncate our i32 to an i16.
2029 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002030
Kévin Petite8edce32019-04-10 14:23:32 +01002031 // Cast the half* pointer to short*.
2032 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002033
Kévin Petite8edce32019-04-10 14:23:32 +01002034 // Index into the correct address of the casted pointer.
2035 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002036
Kévin Petite8edce32019-04-10 14:23:32 +01002037 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002038 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002039 } else {
2040 // We can only write to 32-bit aligned words.
2041 //
2042 // Assuming base is aligned to 32-bits, replace the equivalent of
2043 // vstore_half(value, index, base)
2044 // with:
2045 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2046 // uint32_t write_to_upper_half = index & 1u;
2047 // uint32_t shift = write_to_upper_half << 4;
2048 //
2049 // // Pack the float value as a half number in bottom 16 bits
2050 // // of an i32.
2051 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2052 //
2053 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2054 // ^ ((packed & 0xffff) << shift)
2055 // // We only need relaxed consistency, but OpenCL 1.2 only has
2056 // // sequentially consistent atomics.
2057 // // TODO(dneto): Use relaxed consistency.
2058 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002059 auto IntPointerTy =
2060 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002061
Kévin Petite8edce32019-04-10 14:23:32 +01002062 auto Four = ConstantInt::get(IntTy, 4);
2063 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002064
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002065 auto IndexIsOdd =
2066 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002067 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002068 auto IndexIntoI32 =
2069 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2070 auto BaseI32Ptr =
2071 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2072 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2073 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002074 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002075 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002076 auto MaskBitsToWrite =
2077 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2078 auto MaskedCurrent = BinaryOperator::CreateAnd(
2079 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002080
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002081 auto XLowerBits =
2082 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2083 auto NewBitsToWrite =
2084 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2085 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2086 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002087
Kévin Petite8edce32019-04-10 14:23:32 +01002088 // Generate the call to atomi_xor.
2089 SmallVector<Type *, 5> ParamTypes;
2090 // The pointer type.
2091 ParamTypes.push_back(IntPointerTy);
2092 // The Types for memory scope, semantics, and value.
2093 ParamTypes.push_back(IntTy);
2094 ParamTypes.push_back(IntTy);
2095 ParamTypes.push_back(IntTy);
2096 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2097 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002098
Kévin Petite8edce32019-04-10 14:23:32 +01002099 const auto ConstantScopeDevice =
2100 ConstantInt::get(IntTy, spv::ScopeDevice);
2101 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2102 // (SPIR-V Workgroup).
2103 const auto AddrSpaceSemanticsBits =
2104 IntPointerTy->getPointerAddressSpace() == 1
2105 ? spv::MemorySemanticsUniformMemoryMask
2106 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002107
Kévin Petite8edce32019-04-10 14:23:32 +01002108 // We're using relaxed consistency here.
2109 const auto ConstantMemorySemantics =
2110 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2111 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002112
Kévin Petite8edce32019-04-10 14:23:32 +01002113 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2114 ConstantMemorySemantics, ValueToXor};
2115 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002116
2117 // Return a Nop so the old Call is removed
2118 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2119 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002120 }
David Neto22f144c2017-06-12 14:26:21 -04002121
SJW2c317da2020-03-23 07:39:13 -05002122 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002123 });
David Neto22f144c2017-06-12 14:26:21 -04002124}
2125
SJW2c317da2020-03-23 07:39:13 -05002126bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2127 Module &M = *F.getParent();
2128 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002129 // The value to store.
2130 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002131
Kévin Petite8edce32019-04-10 14:23:32 +01002132 // The index argument from vstore_half.
2133 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002134
Kévin Petite8edce32019-04-10 14:23:32 +01002135 // The pointer argument from vstore_half.
2136 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002137
Kévin Petite8edce32019-04-10 14:23:32 +01002138 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002139 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002140 auto NewPointerTy =
2141 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002142 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002143
Kévin Petite8edce32019-04-10 14:23:32 +01002144 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002145 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002146
Kévin Petite8edce32019-04-10 14:23:32 +01002147 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002148
Kévin Petite8edce32019-04-10 14:23:32 +01002149 // Turn the packed x & y into the final packing.
2150 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002151
Kévin Petite8edce32019-04-10 14:23:32 +01002152 // Cast the half* pointer to int*.
2153 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002154
Kévin Petite8edce32019-04-10 14:23:32 +01002155 // Index into the correct address of the casted pointer.
2156 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002157
Kévin Petite8edce32019-04-10 14:23:32 +01002158 // Store to the int* we casted to.
2159 return new StoreInst(X, Index, CI);
2160 });
David Neto22f144c2017-06-12 14:26:21 -04002161}
2162
SJW2c317da2020-03-23 07:39:13 -05002163bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2164 Module &M = *F.getParent();
2165 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002166 // The value to store.
2167 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002168
Kévin Petite8edce32019-04-10 14:23:32 +01002169 // The index argument from vstore_half.
2170 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002171
Kévin Petite8edce32019-04-10 14:23:32 +01002172 // The pointer argument from vstore_half.
2173 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002174
Kévin Petite8edce32019-04-10 14:23:32 +01002175 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002176 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2177 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002178 auto NewPointerTy =
2179 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002180 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002181
Kévin Petite8edce32019-04-10 14:23:32 +01002182 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2183 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002184
Kévin Petite8edce32019-04-10 14:23:32 +01002185 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002186 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2187 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002188
Kévin Petite8edce32019-04-10 14:23:32 +01002189 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2190 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002191
Kévin Petite8edce32019-04-10 14:23:32 +01002192 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002193 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2194 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002195
Kévin Petite8edce32019-04-10 14:23:32 +01002196 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002197 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002198
Kévin Petite8edce32019-04-10 14:23:32 +01002199 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002200
Kévin Petite8edce32019-04-10 14:23:32 +01002201 // Turn the packed x & y into the final component of our int2.
2202 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002203
Kévin Petite8edce32019-04-10 14:23:32 +01002204 // Turn the packed z & w into the final component of our int2.
2205 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002206
Kévin Petite8edce32019-04-10 14:23:32 +01002207 auto Combine = InsertElementInst::Create(
2208 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002209 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2210 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002211
Kévin Petite8edce32019-04-10 14:23:32 +01002212 // Cast the half* pointer to int2*.
2213 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002214
Kévin Petite8edce32019-04-10 14:23:32 +01002215 // Index into the correct address of the casted pointer.
2216 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002217
Kévin Petite8edce32019-04-10 14:23:32 +01002218 // Store to the int2* we casted to.
2219 return new StoreInst(Combine, Index, CI);
2220 });
David Neto22f144c2017-06-12 14:26:21 -04002221}
2222
SJW2c317da2020-03-23 07:39:13 -05002223bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2224 // convert half to float
2225 Module &M = *F.getParent();
2226 return replaceCallsWithValue(F, [&](CallInst *CI) {
2227 SmallVector<Type *, 3> types;
2228 SmallVector<Value *, 3> args;
2229 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2230 types.push_back(CI->getArgOperand(i)->getType());
2231 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002232 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002233
alan-baker5a8c3be2020-09-09 13:44:26 -04002234 auto NewFType =
2235 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2236 cast<VectorType>(CI->getType())
2237 ->getElementCount()
2238 .getKnownMinValue()),
2239 types, false);
SJW2c317da2020-03-23 07:39:13 -05002240
SJW61531372020-06-09 07:31:08 -05002241 std::string NewFName =
2242 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002243
2244 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2245
2246 auto NewCI = CallInst::Create(NewF, args, "", CI);
2247
2248 // Convert to the half type.
2249 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2250 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002251}
2252
SJW2c317da2020-03-23 07:39:13 -05002253bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2254 // convert half to float
2255 Module &M = *F.getParent();
2256 return replaceCallsWithValue(F, [&](CallInst *CI) {
2257 SmallVector<Type *, 3> types(3);
2258 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002259
SJW2c317da2020-03-23 07:39:13 -05002260 // Image
2261 types[0] = CI->getArgOperand(0)->getType();
2262 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002263
SJW2c317da2020-03-23 07:39:13 -05002264 // Coord
2265 types[1] = CI->getArgOperand(1)->getType();
2266 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002267
SJW2c317da2020-03-23 07:39:13 -05002268 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002269 types[2] =
2270 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2271 cast<VectorType>(CI->getArgOperand(2)->getType())
2272 ->getElementCount()
2273 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002274
SJW2c317da2020-03-23 07:39:13 -05002275 auto NewFType =
2276 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002277
SJW61531372020-06-09 07:31:08 -05002278 std::string NewFName =
2279 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002280
SJW2c317da2020-03-23 07:39:13 -05002281 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002282
SJW2c317da2020-03-23 07:39:13 -05002283 // Convert data to the float type.
2284 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2285 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002286
SJW2c317da2020-03-23 07:39:13 -05002287 return CallInst::Create(NewF, args, "", CI);
2288 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002289}
2290
SJW2c317da2020-03-23 07:39:13 -05002291bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2292 Function &F) {
2293 // convert read_image with int coords to float coords
2294 Module &M = *F.getParent();
2295 return replaceCallsWithValue(F, [&](CallInst *CI) {
2296 // The image.
2297 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002298
SJW2c317da2020-03-23 07:39:13 -05002299 // The sampler.
2300 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002301
SJW2c317da2020-03-23 07:39:13 -05002302 // The coordinate (integer type that we can't handle).
2303 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002304
SJW2c317da2020-03-23 07:39:13 -05002305 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2306 uint32_t components =
2307 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2308 Type *float_ty = nullptr;
2309 if (components == 1) {
2310 float_ty = Type::getFloatTy(M.getContext());
2311 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002312 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2313 cast<VectorType>(Arg2->getType())
2314 ->getElementCount()
2315 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002316 }
David Neto22f144c2017-06-12 14:26:21 -04002317
SJW2c317da2020-03-23 07:39:13 -05002318 auto NewFType = FunctionType::get(
2319 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2320
2321 std::string NewFName = F.getName().str();
2322 NewFName[NewFName.length() - 1] = 'f';
2323
2324 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2325
2326 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2327
2328 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2329 });
David Neto22f144c2017-06-12 14:26:21 -04002330}
2331
SJW2c317da2020-03-23 07:39:13 -05002332bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2333 return replaceCallsWithValue(F, [&](CallInst *CI) {
2334 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002335
SJW2c317da2020-03-23 07:39:13 -05002336 // We need to map the OpenCL constants to the SPIR-V equivalents.
2337 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2338 const auto ConstantMemorySemantics = ConstantInt::get(
2339 IntTy, spv::MemorySemanticsUniformMemoryMask |
2340 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002341
SJW2c317da2020-03-23 07:39:13 -05002342 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002343
SJW2c317da2020-03-23 07:39:13 -05002344 // The pointer.
2345 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002346
SJW2c317da2020-03-23 07:39:13 -05002347 // The memory scope.
2348 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002349
SJW2c317da2020-03-23 07:39:13 -05002350 // The memory semantics.
2351 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002352
SJW2c317da2020-03-23 07:39:13 -05002353 if (2 < CI->getNumArgOperands()) {
2354 // The unequal memory semantics.
2355 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002356
SJW2c317da2020-03-23 07:39:13 -05002357 // The value.
2358 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002359
SJW2c317da2020-03-23 07:39:13 -05002360 // The comparator.
2361 Params.push_back(CI->getArgOperand(1));
2362 } else if (1 < CI->getNumArgOperands()) {
2363 // The value.
2364 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002365 }
David Neto22f144c2017-06-12 14:26:21 -04002366
SJW2c317da2020-03-23 07:39:13 -05002367 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2368 });
David Neto22f144c2017-06-12 14:26:21 -04002369}
2370
SJW2c317da2020-03-23 07:39:13 -05002371bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2372 llvm::AtomicRMWInst::BinOp Op) {
2373 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002374 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2375 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002376 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002377 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002378 SyncScope::System, CI);
2379 });
2380}
David Neto22f144c2017-06-12 14:26:21 -04002381
SJW2c317da2020-03-23 07:39:13 -05002382bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2383 Module &M = *F.getParent();
2384 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002385 auto IntTy = Type::getInt32Ty(M.getContext());
2386 auto FloatTy = Type::getFloatTy(M.getContext());
2387
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002388 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2389 ConstantInt::get(IntTy, 1),
2390 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002391
2392 Constant *UpShuffleMask[4] = {
2393 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2394 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2395
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002396 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2397 UndefValue::get(FloatTy),
2398 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002399
Kévin Petite8edce32019-04-10 14:23:32 +01002400 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002401 auto Arg0 =
2402 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2403 ConstantVector::get(DownShuffleMask), "", CI);
2404 auto Arg1 =
2405 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2406 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002407 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002408
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002409 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002410 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002411
SJW61531372020-06-09 07:31:08 -05002412 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002413
Kévin Petite8edce32019-04-10 14:23:32 +01002414 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002415
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002416 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2417 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002418 });
David Neto22f144c2017-06-12 14:26:21 -04002419}
David Neto62653202017-10-16 19:05:18 -04002420
SJW2c317da2020-03-23 07:39:13 -05002421bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002422 // OpenCL's float result = fract(float x, float* ptr)
2423 //
2424 // In the LLVM domain:
2425 //
2426 // %floor_result = call spir_func float @floor(float %x)
2427 // store float %floor_result, float * %ptr
2428 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2429 // %result = call spir_func float
2430 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2431 //
2432 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2433 // and clspv.fract occur in the SPIR-V generator pass:
2434 //
2435 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2436 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2437 // ...
2438 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2439 // OpStore %ptr %floor_result
2440 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2441 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002442 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002443
David Neto62653202017-10-16 19:05:18 -04002444 using std::string;
2445
2446 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2447 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002448
SJW2c317da2020-03-23 07:39:13 -05002449 Module &M = *F.getParent();
2450 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002451
SJW2c317da2020-03-23 07:39:13 -05002452 // This is either float or a float vector. All the float-like
2453 // types are this type.
2454 auto result_ty = F.getReturnType();
2455
SJW61531372020-06-09 07:31:08 -05002456 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002457 Function *fmin_fn = M.getFunction(fmin_name);
2458 if (!fmin_fn) {
2459 // Make the fmin function.
2460 FunctionType *fn_ty =
2461 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2462 fmin_fn =
2463 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2464 fmin_fn->addFnAttr(Attribute::ReadNone);
2465 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2466 }
2467
SJW61531372020-06-09 07:31:08 -05002468 std::string floor_name =
2469 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002470 Function *floor_fn = M.getFunction(floor_name);
2471 if (!floor_fn) {
2472 // Make the floor function.
2473 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2474 floor_fn =
2475 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2476 floor_fn->addFnAttr(Attribute::ReadNone);
2477 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2478 }
2479
SJW61531372020-06-09 07:31:08 -05002480 std::string clspv_fract_name =
2481 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002482 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2483 if (!clspv_fract_fn) {
2484 // Make the clspv_fract function.
2485 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2486 clspv_fract_fn = cast<Function>(
2487 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2488 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2489 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2490 }
2491
2492 // Number of significant significand bits, whether represented or not.
2493 unsigned num_significand_bits;
2494 switch (result_ty->getScalarType()->getTypeID()) {
2495 case Type::HalfTyID:
2496 num_significand_bits = 11;
2497 break;
2498 case Type::FloatTyID:
2499 num_significand_bits = 24;
2500 break;
2501 case Type::DoubleTyID:
2502 num_significand_bits = 53;
2503 break;
2504 default:
2505 llvm_unreachable("Unhandled float type when processing fract builtin");
2506 break;
2507 }
2508 // Beware that the disassembler displays this value as
2509 // OpConstant %float 1
2510 // which is not quite right.
2511 const double kJustUnderOneScalar =
2512 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2513
2514 Constant *just_under_one =
2515 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2516 if (result_ty->isVectorTy()) {
2517 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002518 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002519 }
2520
2521 IRBuilder<> Builder(CI);
2522
2523 auto arg = CI->getArgOperand(0);
2524 auto ptr = CI->getArgOperand(1);
2525
2526 // Compute floor result and store it.
2527 auto floor = Builder.CreateCall(floor_fn, {arg});
2528 Builder.CreateStore(floor, ptr);
2529
2530 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2531 auto fract_result =
2532 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2533
2534 return fract_result;
2535 });
David Neto62653202017-10-16 19:05:18 -04002536}
alan-bakera52b7312020-10-26 08:58:51 -04002537
Kévin Petit8576f682020-11-02 14:51:32 +00002538bool ReplaceOpenCLBuiltinPass::replaceHadd(Function &F, bool is_signed,
alan-bakerb6da5132020-10-29 15:59:06 -04002539 Instruction::BinaryOps join_opcode) {
Kévin Petit8576f682020-11-02 14:51:32 +00002540 return replaceCallsWithValue(F, [is_signed, join_opcode](CallInst *Call) {
alan-bakerb6da5132020-10-29 15:59:06 -04002541 // a_shr = a >> 1
2542 // b_shr = b >> 1
2543 // add1 = a_shr + b_shr
2544 // join = a |join_opcode| b
2545 // and = join & 1
2546 // add = add1 + and
2547 const auto a = Call->getArgOperand(0);
2548 const auto b = Call->getArgOperand(1);
2549 IRBuilder<> builder(Call);
Kévin Petit8576f682020-11-02 14:51:32 +00002550 Value *a_shift, *b_shift;
2551 if (is_signed) {
2552 a_shift = builder.CreateAShr(a, 1);
2553 b_shift = builder.CreateAShr(b, 1);
2554 } else {
2555 a_shift = builder.CreateLShr(a, 1);
2556 b_shift = builder.CreateLShr(b, 1);
2557 }
alan-bakerb6da5132020-10-29 15:59:06 -04002558 auto add = builder.CreateAdd(a_shift, b_shift);
2559 auto join = BinaryOperator::Create(join_opcode, a, b, "", Call);
2560 auto constant_one = ConstantInt::get(a->getType(), 1);
2561 auto and_bit = builder.CreateAnd(join, constant_one);
2562 return builder.CreateAdd(add, and_bit);
2563 });
2564}
2565
alan-baker3f1bf492020-11-05 09:07:36 -05002566bool ReplaceOpenCLBuiltinPass::replaceAddSubSat(Function &F, bool is_signed,
2567 bool is_add) {
2568 return replaceCallsWithValue(F, [&F, this, is_signed,
2569 is_add](CallInst *Call) {
2570 auto ty = Call->getType();
2571 auto a = Call->getArgOperand(0);
2572 auto b = Call->getArgOperand(1);
2573 IRBuilder<> builder(Call);
alan-bakera52b7312020-10-26 08:58:51 -04002574 if (is_signed) {
2575 unsigned bitwidth = ty->getScalarSizeInBits();
2576 if (bitwidth < 32) {
alan-baker3f1bf492020-11-05 09:07:36 -05002577 unsigned extended_width = bitwidth << 1;
2578 Type *extended_ty =
2579 IntegerType::get(Call->getContext(), extended_width);
2580 Constant *min = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002581 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002582 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2583 Constant *max = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002584 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002585 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
alan-bakera52b7312020-10-26 08:58:51 -04002586 // Don't use the type in GetMangledFunctionName to ensure we get
2587 // signed parameters.
2588 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
alan-bakera52b7312020-10-26 08:58:51 -04002589 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
alan-baker3f1bf492020-11-05 09:07:36 -05002590 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2591 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2592 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2593 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2594 if (extended_width == 32) {
alan-bakera52b7312020-10-26 08:58:51 -04002595 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
alan-bakera52b7312020-10-26 08:58:51 -04002596 } else {
2597 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2598 }
alan-baker3f1bf492020-11-05 09:07:36 -05002599 } else {
2600 if (extended_width == 32) {
2601 sclamp_name += "iii";
2602 } else {
2603 sclamp_name += "sss";
2604 }
alan-bakera52b7312020-10-26 08:58:51 -04002605 }
alan-baker3f1bf492020-11-05 09:07:36 -05002606
2607 auto sext_a = builder.CreateSExt(a, extended_ty);
2608 auto sext_b = builder.CreateSExt(b, extended_ty);
2609 Value *op = nullptr;
2610 // Extended operations won't wrap.
2611 if (is_add)
2612 op = builder.CreateAdd(sext_a, sext_b, "", true, true);
2613 else
2614 op = builder.CreateSub(sext_a, sext_b, "", true, true);
2615 auto clamp_ty = FunctionType::get(
2616 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2617 auto callee = F.getParent()->getOrInsertFunction(sclamp_name, clamp_ty);
2618 auto clamp = builder.CreateCall(callee, {op, min, max});
2619 return builder.CreateTrunc(clamp, ty);
alan-bakera52b7312020-10-26 08:58:51 -04002620 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002621 // Add:
2622 // c = a + b
alan-bakera52b7312020-10-26 08:58:51 -04002623 // if (b < 0)
2624 // c = c > a ? min : c;
2625 // else
alan-baker3f1bf492020-11-05 09:07:36 -05002626 // c = c < a ? max : c;
alan-bakera52b7312020-10-26 08:58:51 -04002627 //
alan-baker3f1bf492020-11-05 09:07:36 -05002628 // Sub:
2629 // c = a - b;
2630 // if (b < 0)
2631 // c = c < a ? max : c;
2632 // else
2633 // c = c > a ? min : c;
2634 Constant *min = ConstantInt::get(Call->getContext(),
2635 APInt::getSignedMinValue(bitwidth));
2636 Constant *max = ConstantInt::get(Call->getContext(),
2637 APInt::getSignedMaxValue(bitwidth));
alan-bakera52b7312020-10-26 08:58:51 -04002638 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2639 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2640 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2641 }
alan-baker3f1bf492020-11-05 09:07:36 -05002642 Value *op = nullptr;
2643 if (is_add) {
2644 op = builder.CreateAdd(a, b);
2645 } else {
2646 op = builder.CreateSub(a, b);
2647 }
2648 auto b_lt_0 = builder.CreateICmpSLT(b, Constant::getNullValue(ty));
2649 auto op_gt_a = builder.CreateICmpSGT(op, a);
2650 auto op_lt_a = builder.CreateICmpSLT(op, a);
2651 auto neg_cmp = is_add ? op_gt_a : op_lt_a;
2652 auto pos_cmp = is_add ? op_lt_a : op_gt_a;
2653 auto neg_value = is_add ? min : max;
2654 auto pos_value = is_add ? max : min;
2655 auto neg_clamp = builder.CreateSelect(neg_cmp, neg_value, op);
2656 auto pos_clamp = builder.CreateSelect(pos_cmp, pos_value, op);
2657 return builder.CreateSelect(b_lt_0, neg_clamp, pos_clamp);
alan-bakera52b7312020-10-26 08:58:51 -04002658 }
2659 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002660 // Replace with OpIAddCarry/OpISubBorrow and clamp to max/0 on a
2661 // carr/borrow.
2662 spv::Op op = is_add ? spv::OpIAddCarry : spv::OpISubBorrow;
2663 auto clamp_value =
2664 is_add ? Constant::getAllOnesValue(ty) : Constant::getNullValue(ty);
2665 auto struct_ty = GetPairStruct(ty);
2666 auto call =
2667 InsertSPIRVOp(Call, op, {Attribute::ReadNone}, struct_ty, {a, b});
2668 auto add_sub = builder.CreateExtractValue(call, {0});
2669 auto carry_borrow = builder.CreateExtractValue(call, {1});
2670 auto cmp = builder.CreateICmpEQ(carry_borrow, Constant::getNullValue(ty));
2671 return builder.CreateSelect(cmp, add_sub, clamp_value);
alan-bakera52b7312020-10-26 08:58:51 -04002672 }
alan-bakera52b7312020-10-26 08:58:51 -04002673 });
2674}
alan-baker4986eff2020-10-29 13:38:00 -04002675
2676bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2677 return replaceCallsWithValue(F, [](CallInst *Call) {
2678 auto pointer = Call->getArgOperand(0);
2679 // Clang emits an address space cast to the generic address space. Skip the
2680 // cast and use the input directly.
2681 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2682 pointer = cast->getPointerOperand();
2683 }
2684 Value *order_arg =
2685 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2686 Value *scope_arg =
2687 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2688 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2689 clspv::AddressSpace::Global;
2690 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2691 spv::MemorySemanticsAcquireMask);
2692 auto scope = MemoryScope(scope_arg, is_global, Call);
2693 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2694 Call->getType(), {pointer, scope, order});
2695 });
2696}
2697
2698bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2699 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2700 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2701 auto pointer = Call->getArgOperand(0);
2702 // Clang emits an address space cast to the generic address space. Skip the
2703 // cast and use the input directly.
2704 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2705 pointer = cast->getPointerOperand();
2706 }
2707 Value *value = Call->getArgOperand(1);
2708 Value *order_arg =
2709 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2710 Value *scope_arg =
2711 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2712 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2713 clspv::AddressSpace::Global;
2714 auto scope = MemoryScope(scope_arg, is_global, Call);
2715 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2716 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2717 {pointer, scope, order, value});
2718 });
2719}
2720
2721bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2722 return replaceCallsWithValue(F, [](CallInst *Call) {
2723 auto pointer = Call->getArgOperand(0);
2724 // Clang emits an address space cast to the generic address space. Skip the
2725 // cast and use the input directly.
2726 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2727 pointer = cast->getPointerOperand();
2728 }
2729 auto expected = Call->getArgOperand(1);
2730 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2731 expected = cast->getPointerOperand();
2732 }
2733 auto value = Call->getArgOperand(2);
2734 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2735 clspv::AddressSpace::Global;
2736 Value *success_arg =
2737 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2738 Value *failure_arg =
2739 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2740 Value *scope_arg =
2741 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2742 auto scope = MemoryScope(scope_arg, is_global, Call);
2743 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2744 spv::MemorySemanticsAcquireReleaseMask);
2745 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2746 spv::MemorySemanticsAcquireMask);
2747
2748 // If the value pointed to by |expected| equals the value pointed to by
2749 // |pointer|, |value| is written into |pointer|, otherwise the value in
2750 // |pointer| is written into |expected|. In order to avoid extra stores,
2751 // the basic block with the original atomic is split and the store is
2752 // performed in the |then| block. The condition is the inversion of the
2753 // comparison result.
2754 IRBuilder<> builder(Call);
2755 auto load = builder.CreateLoad(expected);
2756 auto cmp_xchg = InsertSPIRVOp(
2757 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2758 value->getType(), {pointer, scope, success, failure, value, load});
2759 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2760 auto not_cmp = builder.CreateNot(cmp);
2761 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2762 builder.SetInsertPoint(then_branch);
2763 builder.CreateStore(cmp_xchg, expected);
2764 return cmp;
2765 });
2766}
alan-bakercc2bafb2020-11-02 08:30:18 -05002767
alan-baker2cecaa72020-11-05 14:05:20 -05002768bool ReplaceOpenCLBuiltinPass::replaceCountZeroes(Function &F, bool leading) {
alan-bakercc2bafb2020-11-02 08:30:18 -05002769 if (!isa<IntegerType>(F.getReturnType()->getScalarType()))
2770 return false;
2771
2772 auto bitwidth = F.getReturnType()->getScalarSizeInBits();
alan-baker5f2e88e2020-12-07 15:24:04 -05002773 if (bitwidth > 64)
alan-bakercc2bafb2020-11-02 08:30:18 -05002774 return false;
2775
alan-baker5f2e88e2020-12-07 15:24:04 -05002776 return replaceCallsWithValue(F, [&F, leading](CallInst *Call) {
2777 Function *intrinsic = Intrinsic::getDeclaration(
2778 F.getParent(), leading ? Intrinsic::ctlz : Intrinsic::cttz,
2779 Call->getType());
2780 const auto c_false = ConstantInt::getFalse(Call->getContext());
2781 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
2782 {Call->getArgOperand(0), c_false}, "", Call);
alan-bakercc2bafb2020-11-02 08:30:18 -05002783 });
2784}
alan-baker6b9d1ee2020-11-03 23:11:32 -05002785
2786bool ReplaceOpenCLBuiltinPass::replaceMadSat(Function &F, bool is_signed) {
2787 return replaceCallsWithValue(F, [&F, is_signed, this](CallInst *Call) {
2788 const auto ty = Call->getType();
2789 const auto a = Call->getArgOperand(0);
2790 const auto b = Call->getArgOperand(1);
2791 const auto c = Call->getArgOperand(2);
2792 IRBuilder<> builder(Call);
2793 if (is_signed) {
2794 unsigned bitwidth = Call->getType()->getScalarSizeInBits();
2795 if (bitwidth < 32) {
2796 // mul = sext(a) * sext(b)
2797 // add = mul + sext(c)
2798 // res = clamp(add, MIN, MAX)
2799 unsigned extended_width = bitwidth << 1;
2800 Type *extended_ty = IntegerType::get(F.getContext(), extended_width);
2801 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2802 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2803 }
2804 auto a_sext = builder.CreateSExt(a, extended_ty);
2805 auto b_sext = builder.CreateSExt(b, extended_ty);
2806 auto c_sext = builder.CreateSExt(c, extended_ty);
2807 // Extended the size so no overflows occur.
2808 auto mul = builder.CreateMul(a_sext, b_sext, "", true, true);
2809 auto add = builder.CreateAdd(mul, c_sext, "", true, true);
2810 auto func_ty = FunctionType::get(
2811 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2812 // Don't use function type because we need signed parameters.
2813 std::string clamp_name = Builtins::GetMangledFunctionName("clamp");
2814 // The clamp values are the signed min and max of the original bitwidth
2815 // sign extended to the extended bitwidth.
2816 Constant *min = ConstantInt::get(
2817 Call->getContext(),
2818 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2819 Constant *max = ConstantInt::get(
2820 Call->getContext(),
2821 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
2822 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2823 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2824 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2825 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2826 if (extended_width == 32)
2827 clamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2828 else
2829 clamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2830 } else {
2831 if (extended_width == 32)
2832 clamp_name += "iii";
2833 else
2834 clamp_name += "sss";
2835 }
2836 auto callee = F.getParent()->getOrInsertFunction(clamp_name, func_ty);
2837 auto clamp = builder.CreateCall(callee, {add, min, max});
2838 return builder.CreateTrunc(clamp, ty);
2839 } else {
2840 auto struct_ty = GetPairStruct(ty);
2841 // Compute
2842 // {hi, lo} = smul_extended(a, b)
2843 // add = lo + c
2844 auto mul_ext = InsertSPIRVOp(Call, spv::OpSMulExtended,
2845 {Attribute::ReadNone}, struct_ty, {a, b});
2846 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2847 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2848 auto add = builder.CreateAdd(mul_lo, c);
2849
2850 // Constants for use in the calculation.
2851 Constant *min = ConstantInt::get(Call->getContext(),
2852 APInt::getSignedMinValue(bitwidth));
2853 Constant *max = ConstantInt::get(Call->getContext(),
2854 APInt::getSignedMaxValue(bitwidth));
2855 Constant *max_plus_1 = ConstantInt::get(
2856 Call->getContext(),
2857 APInt::getSignedMaxValue(bitwidth) + APInt(bitwidth, 1));
2858 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2859 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2860 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2861 max_plus_1 =
2862 ConstantVector::getSplat(vec_ty->getElementCount(), max_plus_1);
2863 }
2864
2865 auto a_xor_b = builder.CreateXor(a, b);
2866 auto same_sign =
2867 builder.CreateICmpSGT(a_xor_b, Constant::getAllOnesValue(ty));
2868 auto different_sign = builder.CreateNot(same_sign);
2869 auto hi_eq_0 = builder.CreateICmpEQ(mul_hi, Constant::getNullValue(ty));
2870 auto hi_ne_0 = builder.CreateNot(hi_eq_0);
2871 auto lo_ge_max = builder.CreateICmpUGE(mul_lo, max);
2872 auto c_gt_0 = builder.CreateICmpSGT(c, Constant::getNullValue(ty));
2873 auto c_lt_0 = builder.CreateICmpSLT(c, Constant::getNullValue(ty));
2874 auto add_gt_max = builder.CreateICmpUGT(add, max);
2875 auto hi_eq_m1 =
2876 builder.CreateICmpEQ(mul_hi, Constant::getAllOnesValue(ty));
2877 auto hi_ne_m1 = builder.CreateNot(hi_eq_m1);
2878 auto lo_le_max_plus_1 = builder.CreateICmpULE(mul_lo, max_plus_1);
2879 auto max_sub_lo = builder.CreateSub(max, mul_lo);
2880 auto c_lt_max_sub_lo = builder.CreateICmpULT(c, max_sub_lo);
2881
2882 // Equivalent to:
2883 // if (((x < 0) == (y < 0)) && mul_hi != 0)
2884 // return MAX
2885 // if (mul_hi == 0 && mul_lo >= MAX && (z > 0 || add > MAX))
2886 // return MAX
2887 // if (((x < 0) != (y < 0)) && mul_hi != -1)
2888 // return MIN
2889 // if (hi == -1 && mul_lo <= (MAX + 1) && (z < 0 || z < (MAX - mul_lo))
2890 // return MIN
2891 // return add
2892 auto max_clamp_1 = builder.CreateAnd(same_sign, hi_ne_0);
2893 auto max_clamp_2 = builder.CreateOr(c_gt_0, add_gt_max);
2894 auto tmp = builder.CreateAnd(hi_eq_0, lo_ge_max);
2895 max_clamp_2 = builder.CreateAnd(tmp, max_clamp_2);
2896 auto max_clamp = builder.CreateOr(max_clamp_1, max_clamp_2);
2897 auto min_clamp_1 = builder.CreateAnd(different_sign, hi_ne_m1);
2898 auto min_clamp_2 = builder.CreateOr(c_lt_0, c_lt_max_sub_lo);
2899 tmp = builder.CreateAnd(hi_eq_m1, lo_le_max_plus_1);
2900 min_clamp_2 = builder.CreateAnd(tmp, min_clamp_2);
2901 auto min_clamp = builder.CreateOr(min_clamp_1, min_clamp_2);
2902 auto sel = builder.CreateSelect(min_clamp, min, add);
2903 return builder.CreateSelect(max_clamp, max, sel);
2904 }
2905 } else {
2906 // {lo, hi} = mul_extended(a, b)
2907 // {add, carry} = add_carry(lo, c)
2908 // cmp = (mul_hi | carry) == 0
2909 // mad_sat = cmp ? add : MAX
2910 auto struct_ty = GetPairStruct(ty);
2911 auto mul_ext = InsertSPIRVOp(Call, spv::OpUMulExtended,
2912 {Attribute::ReadNone}, struct_ty, {a, b});
2913 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2914 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2915 auto add_carry =
2916 InsertSPIRVOp(Call, spv::OpIAddCarry, {Attribute::ReadNone},
2917 struct_ty, {mul_lo, c});
2918 auto add = builder.CreateExtractValue(add_carry, {0});
2919 auto carry = builder.CreateExtractValue(add_carry, {1});
2920 auto or_value = builder.CreateOr(mul_hi, carry);
2921 auto cmp = builder.CreateICmpEQ(or_value, Constant::getNullValue(ty));
2922 return builder.CreateSelect(cmp, add, Constant::getAllOnesValue(ty));
2923 }
2924 });
2925}
alan-baker15106572020-11-06 15:08:10 -05002926
2927bool ReplaceOpenCLBuiltinPass::replaceOrdered(Function &F, bool is_ordered) {
2928 if (!isa<IntegerType>(F.getReturnType()->getScalarType()))
2929 return false;
2930
2931 if (F.getFunctionType()->getNumParams() != 2)
2932 return false;
2933
2934 if (F.getFunctionType()->getParamType(0) !=
2935 F.getFunctionType()->getParamType(1)) {
2936 return false;
2937 }
2938
2939 switch (F.getFunctionType()->getParamType(0)->getScalarType()->getTypeID()) {
2940 case Type::FloatTyID:
2941 case Type::HalfTyID:
2942 case Type::DoubleTyID:
2943 break;
2944 default:
2945 return false;
2946 }
2947
2948 // Scalar versions all return an int, while vector versions return a vector
2949 // of an equally sized integer types (e.g. short, int or long).
2950 if (isa<VectorType>(F.getReturnType())) {
2951 if (F.getReturnType()->getScalarSizeInBits() !=
2952 F.getFunctionType()->getParamType(0)->getScalarSizeInBits()) {
2953 return false;
2954 }
2955 } else {
2956 if (F.getReturnType()->getScalarSizeInBits() != 32)
2957 return false;
2958 }
2959
2960 return replaceCallsWithValue(F, [is_ordered](CallInst *Call) {
2961 // Replace with a floating point [un]ordered comparison followed by an
2962 // extension.
2963 auto x = Call->getArgOperand(0);
2964 auto y = Call->getArgOperand(1);
2965 IRBuilder<> builder(Call);
2966 Value *tmp = nullptr;
2967 if (is_ordered) {
2968 // This leads to a slight inefficiency in the SPIR-V that is easy for
2969 // drivers to optimize where the SPIR-V for the comparison and the
2970 // extension could be fused to drop the inversion of the OpIsNan.
2971 tmp = builder.CreateFCmpORD(x, y);
2972 } else {
2973 tmp = builder.CreateFCmpUNO(x, y);
2974 }
2975 // OpenCL CTS requires that vector versions use sign extension, but scalar
2976 // versions use zero extension.
2977 if (isa<VectorType>(Call->getType()))
2978 return builder.CreateSExt(tmp, Call->getType());
2979 return builder.CreateZExt(tmp, Call->getType());
2980 });
2981}
alan-baker497920b2020-11-09 16:41:36 -05002982
2983bool ReplaceOpenCLBuiltinPass::replaceIsNormal(Function &F) {
2984 return replaceCallsWithValue(F, [this](CallInst *Call) {
2985 auto ty = Call->getType();
2986 auto x = Call->getArgOperand(0);
2987 unsigned width = x->getType()->getScalarSizeInBits();
2988 Type *int_ty = IntegerType::get(Call->getContext(), width);
2989 uint64_t abs_mask = 0x7fffffff;
2990 uint64_t exp_mask = 0x7f800000;
2991 uint64_t min_mask = 0x00800000;
2992 if (width == 16) {
2993 abs_mask = 0x7fff;
2994 exp_mask = 0x7c00;
2995 min_mask = 0x0400;
2996 } else if (width == 64) {
2997 abs_mask = 0x7fffffffffffffff;
2998 exp_mask = 0x7ff0000000000000;
2999 min_mask = 0x0010000000000000;
3000 }
3001 Constant *abs_const = ConstantInt::get(int_ty, APInt(width, abs_mask));
3002 Constant *exp_const = ConstantInt::get(int_ty, APInt(width, exp_mask));
3003 Constant *min_const = ConstantInt::get(int_ty, APInt(width, min_mask));
3004 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
3005 int_ty = VectorType::get(int_ty, vec_ty->getElementCount());
3006 abs_const =
3007 ConstantVector::getSplat(vec_ty->getElementCount(), abs_const);
3008 exp_const =
3009 ConstantVector::getSplat(vec_ty->getElementCount(), exp_const);
3010 min_const =
3011 ConstantVector::getSplat(vec_ty->getElementCount(), min_const);
3012 }
3013 // Drop the sign bit and then check that the number is between
3014 // (exclusive) the min and max exponent values for the bit width.
3015 IRBuilder<> builder(Call);
3016 auto bitcast = builder.CreateBitCast(x, int_ty);
3017 auto abs = builder.CreateAnd(bitcast, abs_const);
3018 auto lt = builder.CreateICmpULT(abs, exp_const);
3019 auto ge = builder.CreateICmpUGE(abs, min_const);
3020 auto tmp = builder.CreateAnd(lt, ge);
3021 // OpenCL CTS requires that vector versions use sign extension, but scalar
3022 // versions use zero extension.
3023 if (isa<VectorType>(ty))
3024 return builder.CreateSExt(tmp, ty);
3025 return builder.CreateZExt(tmp, ty);
3026 });
3027}
alan-bakere0406e72020-11-10 12:32:04 -05003028
3029bool ReplaceOpenCLBuiltinPass::replaceFDim(Function &F) {
3030 return replaceCallsWithValue(F, [](CallInst *Call) {
3031 const auto x = Call->getArgOperand(0);
3032 const auto y = Call->getArgOperand(1);
3033 IRBuilder<> builder(Call);
3034 auto sub = builder.CreateFSub(x, y);
3035 auto cmp = builder.CreateFCmpUGT(x, y);
3036 return builder.CreateSelect(cmp, sub,
3037 Constant::getNullValue(Call->getType()));
3038 });
3039}
alan-baker3e0de472020-12-08 15:57:17 -05003040
3041bool ReplaceOpenCLBuiltinPass::replaceRound(Function &F) {
3042 return replaceCallsWithValue(F, [&F](CallInst *Call) {
3043 const auto x = Call->getArgOperand(0);
3044 const double c_halfway = 0.5;
3045 auto halfway = ConstantFP::get(Call->getType(), c_halfway);
3046
3047 const auto clspv_fract_name =
3048 Builtins::GetMangledFunctionName("clspv.fract", F.getFunctionType());
3049 Function *clspv_fract_fn = F.getParent()->getFunction(clspv_fract_name);
3050 if (!clspv_fract_fn) {
3051 // Make the clspv_fract function.
3052 clspv_fract_fn = cast<Function>(
3053 F.getParent()
3054 ->getOrInsertFunction(clspv_fract_name, F.getFunctionType())
3055 .getCallee());
3056 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
3057 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
3058 }
3059
3060 auto ceil = Intrinsic::getDeclaration(F.getParent(), Intrinsic::ceil,
3061 Call->getType());
3062 auto floor = Intrinsic::getDeclaration(F.getParent(), Intrinsic::floor,
3063 Call->getType());
3064 auto fabs = Intrinsic::getDeclaration(F.getParent(), Intrinsic::fabs,
3065 Call->getType());
3066 auto copysign = Intrinsic::getDeclaration(
3067 F.getParent(), Intrinsic::copysign, {Call->getType(), Call->getType()});
3068
3069 IRBuilder<> builder(Call);
3070
3071 auto fabs_call = builder.CreateCall(F.getFunctionType(), fabs, {x});
3072 auto ceil_call = builder.CreateCall(F.getFunctionType(), ceil, {fabs_call});
3073 auto floor_call =
3074 builder.CreateCall(F.getFunctionType(), floor, {fabs_call});
3075 auto fract_call =
3076 builder.CreateCall(F.getFunctionType(), clspv_fract_fn, {fabs_call});
3077 auto cmp = builder.CreateFCmpOGE(fract_call, halfway);
3078 auto sel = builder.CreateSelect(cmp, ceil_call, floor_call);
3079 return builder.CreateCall(copysign->getFunctionType(), copysign, {sel, x});
3080 });
3081}
3082
3083bool ReplaceOpenCLBuiltinPass::replaceTrigPi(Function &F,
3084 Builtins::BuiltinType type) {
3085 return replaceCallsWithValue(F, [&F, type](CallInst *Call) -> Value * {
3086 const auto x = Call->getArgOperand(0);
3087 const double k_pi = 0x1.921fb54442d18p+1;
3088 Constant *pi = ConstantFP::get(x->getType(), k_pi);
3089
3090 IRBuilder<> builder(Call);
3091 auto mul = builder.CreateFMul(x, pi);
3092 switch (type) {
3093 case Builtins::kSinpi: {
3094 auto func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::sin,
3095 x->getType());
3096 return builder.CreateCall(func->getFunctionType(), func, {mul});
3097 }
3098 case Builtins::kCospi: {
3099 auto func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::cos,
3100 x->getType());
3101 return builder.CreateCall(func->getFunctionType(), func, {mul});
3102 }
3103 case Builtins::kTanpi: {
3104 auto sin = Intrinsic::getDeclaration(F.getParent(), Intrinsic::sin,
3105 x->getType());
3106 auto sin_call = builder.CreateCall(sin->getFunctionType(), sin, {mul});
3107 auto cos = Intrinsic::getDeclaration(F.getParent(), Intrinsic::cos,
3108 x->getType());
3109 auto cos_call = builder.CreateCall(cos->getFunctionType(), cos, {mul});
3110 return builder.CreateFDiv(sin_call, cos_call);
3111 }
3112 default:
3113 llvm_unreachable("unexpected builtin");
3114 break;
3115 }
3116 return nullptr;
3117 });
3118}
alan-baker8b968112020-12-15 15:53:29 -05003119
3120bool ReplaceOpenCLBuiltinPass::replaceSincos(Function &F) {
3121 return replaceCallsWithValue(F, [&F](CallInst *Call) {
3122 auto sin_func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::sin,
3123 Call->getType());
3124 auto cos_func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::cos,
3125 Call->getType());
3126
3127 IRBuilder<> builder(Call);
3128 auto sin = builder.CreateCall(sin_func->getFunctionType(), sin_func,
3129 {Call->getArgOperand(0)});
3130 auto cos = builder.CreateCall(cos_func->getFunctionType(), cos_func,
3131 {Call->getArgOperand(0)});
3132 builder.CreateStore(cos, Call->getArgOperand(1));
3133 return sin;
3134 });
3135}
3136
3137bool ReplaceOpenCLBuiltinPass::replaceExpm1(Function &F) {
3138 return replaceCallsWithValue(F, [&F](CallInst *Call) {
3139 auto exp_func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::exp,
3140 Call->getType());
3141
3142 IRBuilder<> builder(Call);
3143 auto exp = builder.CreateCall(exp_func->getFunctionType(), exp_func,
3144 {Call->getArgOperand(0)});
3145 return builder.CreateFSub(exp, ConstantFP::get(Call->getType(), 1.0));
3146 });
3147}
3148
3149bool ReplaceOpenCLBuiltinPass::replacePown(Function &F) {
3150 return replaceCallsWithValue(F, [&F](CallInst *Call) {
3151 auto pow_func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::pow,
3152 Call->getType());
3153
3154 IRBuilder<> builder(Call);
3155 auto conv = builder.CreateSIToFP(Call->getArgOperand(1), Call->getType());
3156 return builder.CreateCall(pow_func->getFunctionType(), pow_func,
3157 {Call->getArgOperand(0), conv});
3158 });
3159}