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