blob: f566e98f8b6dda8c911a3d2d0387eb817e595591 [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"
Kévin Petitf5b78a22018-10-25 14:32:17 +000024#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040025#include "llvm/Pass.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040029
alan-bakere0902602020-03-23 08:43:40 -040030#include "spirv/unified1/spirv.hpp"
David Neto22f144c2017-06-12 14:26:21 -040031
alan-baker931d18a2019-12-12 08:21:32 -050032#include "clspv/AddressSpace.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040033#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070034
SJW2c317da2020-03-23 07:39:13 -050035#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050036#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040037#include "Passes.h"
38#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050039#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040040
SJW2c317da2020-03-23 07:39:13 -050041using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040042using namespace llvm;
43
44#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
45
46namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000047
David Neto22f144c2017-06-12 14:26:21 -040048uint32_t clz(uint32_t v) {
49 uint32_t r;
50 uint32_t shift;
51
52 r = (v > 0xFFFF) << 4;
53 v >>= r;
54 shift = (v > 0xFF) << 3;
55 v >>= shift;
56 r |= shift;
57 shift = (v > 0xF) << 2;
58 v >>= shift;
59 r |= shift;
60 shift = (v > 0x3) << 1;
61 v >>= shift;
62 r |= shift;
63 r |= (v >> 1);
64
65 return r;
66}
67
Kévin Petitfdfa92e2019-09-25 14:20:58 +010068Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
69 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040070 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-bakerb3e2b6d2020-06-24 23:59:57 -040071 IntTy = FixedVectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petitfdfa92e2019-09-25 14:20:58 +010072 }
73 return IntTy;
74}
75
SJW2c317da2020-03-23 07:39:13 -050076bool replaceCallsWithValue(Function &F,
77 std::function<Value *(CallInst *)> Replacer) {
78
79 bool Changed = false;
80
81 SmallVector<Instruction *, 4> ToRemoves;
82
83 // Walk the users of the function.
84 for (auto &U : F.uses()) {
85 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
86
87 auto NewValue = Replacer(CI);
88
89 if (NewValue != nullptr) {
90 CI->replaceAllUsesWith(NewValue);
91
92 // Lastly, remember to remove the user.
93 ToRemoves.push_back(CI);
94 }
95 }
96 }
97
98 Changed = !ToRemoves.empty();
99
100 // And cleanup the calls we don't use anymore.
101 for (auto V : ToRemoves) {
102 V->eraseFromParent();
103 }
104
105 return Changed;
106}
107
David Neto22f144c2017-06-12 14:26:21 -0400108struct ReplaceOpenCLBuiltinPass final : public ModulePass {
109 static char ID;
110 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
111
112 bool runOnModule(Module &M) override;
SJW2c317da2020-03-23 07:39:13 -0500113 bool runOnFunction(Function &F);
114 bool replaceAbs(Function &F);
115 bool replaceAbsDiff(Function &F, bool is_signed);
116 bool replaceCopysign(Function &F);
117 bool replaceRecip(Function &F);
118 bool replaceDivide(Function &F);
119 bool replaceDot(Function &F);
120 bool replaceFmod(Function &F);
SJW61531372020-06-09 07:31:08 -0500121 bool replaceExp10(Function &F, const std::string &basename);
122 bool replaceLog10(Function &F, const std::string &basename);
alan-baker12d2c182020-07-20 08:22:42 -0400123 bool replaceBarrier(Function &F, bool subgroup = false);
SJW2c317da2020-03-23 07:39:13 -0500124 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100125 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500126 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
127 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
128 bool replaceIsFinite(Function &F);
129 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
130 bool replaceUpsample(Function &F);
131 bool replaceRotate(Function &F);
132 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
133 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
134 bool replaceSelect(Function &F);
135 bool replaceBitSelect(Function &F);
SJW61531372020-06-09 07:31:08 -0500136 bool replaceStep(Function &F, bool is_smooth);
SJW2c317da2020-03-23 07:39:13 -0500137 bool replaceSignbit(Function &F, bool is_vec);
138 bool replaceMul(Function &F, bool is_float, bool is_mad);
139 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
140 bool replaceVloadHalf(Function &F);
141 bool replaceVloadHalf2(Function &F);
142 bool replaceVloadHalf4(Function &F);
143 bool replaceClspvVloadaHalf2(Function &F);
144 bool replaceClspvVloadaHalf4(Function &F);
145 bool replaceVstoreHalf(Function &F, int vec_size);
146 bool replaceVstoreHalf(Function &F);
147 bool replaceVstoreHalf2(Function &F);
148 bool replaceVstoreHalf4(Function &F);
149 bool replaceHalfReadImage(Function &F);
150 bool replaceHalfWriteImage(Function &F);
151 bool replaceSampledReadImageWithIntCoords(Function &F);
152 bool replaceAtomics(Function &F, spv::Op Op);
153 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
154 bool replaceCross(Function &F);
155 bool replaceFract(Function &F, int vec_size);
156 bool replaceVload(Function &F);
157 bool replaceVstore(Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400158};
SJW2c317da2020-03-23 07:39:13 -0500159
Kévin Petit91bc72e2019-04-08 15:17:46 +0100160} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400161
162char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400163INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
164 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400165
166namespace clspv {
167ModulePass *createReplaceOpenCLBuiltinPass() {
168 return new ReplaceOpenCLBuiltinPass();
169}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400170} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400171
172bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500173 std::list<Function *> func_list;
174 for (auto &F : M.getFunctionList()) {
175 // process only function declarations
176 if (F.isDeclaration() && runOnFunction(F)) {
177 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000178 }
179 }
SJW2c317da2020-03-23 07:39:13 -0500180 if (func_list.size() != 0) {
181 // recursively convert functions, but first remove dead
182 for (auto *F : func_list) {
183 if (F->use_empty()) {
184 F->eraseFromParent();
185 }
186 }
187 runOnModule(M);
188 return true;
189 }
190 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000191}
192
SJW2c317da2020-03-23 07:39:13 -0500193bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
194 auto &FI = Builtins::Lookup(&F);
195 switch (FI.getType()) {
196 case Builtins::kAbs:
197 if (!FI.getParameter(0).is_signed) {
198 return replaceAbs(F);
199 }
200 break;
201 case Builtins::kAbsDiff:
202 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
203 case Builtins::kCopysign:
204 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100205
SJW2c317da2020-03-23 07:39:13 -0500206 case Builtins::kHalfRecip:
207 case Builtins::kNativeRecip:
208 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100209
SJW2c317da2020-03-23 07:39:13 -0500210 case Builtins::kHalfDivide:
211 case Builtins::kNativeDivide:
212 return replaceDivide(F);
213
214 case Builtins::kDot:
215 return replaceDot(F);
216
217 case Builtins::kExp10:
218 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500219 case Builtins::kNativeExp10:
220 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500221
222 case Builtins::kLog10:
223 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500224 case Builtins::kNativeLog10:
225 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500226
227 case Builtins::kFmod:
228 return replaceFmod(F);
229
230 case Builtins::kBarrier:
231 case Builtins::kWorkGroupBarrier:
232 return replaceBarrier(F);
233
alan-baker12d2c182020-07-20 08:22:42 -0400234 case Builtins::kSubGroupBarrier:
235 return replaceBarrier(F, true);
236
SJW2c317da2020-03-23 07:39:13 -0500237 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400238 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500239 case Builtins::kReadMemFence:
240 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
241 case Builtins::kWriteMemFence:
242 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
243
244 // Relational
245 case Builtins::kIsequal:
246 return replaceRelational(F, CmpInst::FCMP_OEQ,
247 FI.getParameter(0).vector_size ? -1 : 1);
248 case Builtins::kIsgreater:
249 return replaceRelational(F, CmpInst::FCMP_OGT,
250 FI.getParameter(0).vector_size ? -1 : 1);
251 case Builtins::kIsgreaterequal:
252 return replaceRelational(F, CmpInst::FCMP_OGE,
253 FI.getParameter(0).vector_size ? -1 : 1);
254 case Builtins::kIsless:
255 return replaceRelational(F, CmpInst::FCMP_OLT,
256 FI.getParameter(0).vector_size ? -1 : 1);
257 case Builtins::kIslessequal:
258 return replaceRelational(F, CmpInst::FCMP_OLE,
259 FI.getParameter(0).vector_size ? -1 : 1);
260 case Builtins::kIsnotequal:
261 return replaceRelational(F, CmpInst::FCMP_ONE,
262 FI.getParameter(0).vector_size ? -1 : 1);
263
264 case Builtins::kIsinf: {
265 bool is_vec = FI.getParameter(0).vector_size != 0;
266 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
267 }
268 case Builtins::kIsnan: {
269 bool is_vec = FI.getParameter(0).vector_size != 0;
270 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
271 }
272
273 case Builtins::kIsfinite:
274 return replaceIsFinite(F);
275
276 case Builtins::kAll: {
277 bool is_vec = FI.getParameter(0).vector_size != 0;
278 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
279 }
280 case Builtins::kAny: {
281 bool is_vec = FI.getParameter(0).vector_size != 0;
282 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
283 }
284
285 case Builtins::kUpsample:
286 return replaceUpsample(F);
287
288 case Builtins::kRotate:
289 return replaceRotate(F);
290
291 case Builtins::kConvert:
292 return replaceConvert(F, FI.getParameter(0).is_signed,
293 FI.getReturnType().is_signed);
294
295 case Builtins::kAtomicInc:
296 return replaceAtomics(F, spv::OpAtomicIIncrement);
297 case Builtins::kAtomicDec:
298 return replaceAtomics(F, spv::OpAtomicIDecrement);
299 case Builtins::kAtomicCmpxchg:
300 return replaceAtomics(F, spv::OpAtomicCompareExchange);
301 case Builtins::kAtomicAdd:
302 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
303 case Builtins::kAtomicSub:
304 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
305 case Builtins::kAtomicXchg:
306 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
307 case Builtins::kAtomicMin:
308 return replaceAtomics(F, FI.getParameter(0).is_signed
309 ? llvm::AtomicRMWInst::Min
310 : llvm::AtomicRMWInst::UMin);
311 case Builtins::kAtomicMax:
312 return replaceAtomics(F, FI.getParameter(0).is_signed
313 ? llvm::AtomicRMWInst::Max
314 : llvm::AtomicRMWInst::UMax);
315 case Builtins::kAtomicAnd:
316 return replaceAtomics(F, llvm::AtomicRMWInst::And);
317 case Builtins::kAtomicOr:
318 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
319 case Builtins::kAtomicXor:
320 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
321
322 case Builtins::kCross:
323 if (FI.getParameter(0).vector_size == 4) {
324 return replaceCross(F);
325 }
326 break;
327
328 case Builtins::kFract:
329 if (FI.getParameterCount()) {
330 return replaceFract(F, FI.getParameter(0).vector_size);
331 }
332 break;
333
334 case Builtins::kMadHi:
335 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
336 case Builtins::kMulHi:
337 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
338
339 case Builtins::kMad:
340 case Builtins::kMad24:
341 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
342 true);
343 case Builtins::kMul24:
344 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
345 false);
346
347 case Builtins::kSelect:
348 return replaceSelect(F);
349
350 case Builtins::kBitselect:
351 return replaceBitSelect(F);
352
353 case Builtins::kVload:
354 return replaceVload(F);
355
356 case Builtins::kVloadaHalf:
357 case Builtins::kVloadHalf:
358 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
359
360 case Builtins::kVstore:
361 return replaceVstore(F);
362
363 case Builtins::kVstoreHalf:
364 case Builtins::kVstoreaHalf:
365 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
366
367 case Builtins::kSmoothstep: {
368 int vec_size = FI.getLastParameter().vector_size;
369 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500370 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500371 }
372 break;
373 }
374 case Builtins::kStep: {
375 int vec_size = FI.getLastParameter().vector_size;
376 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500377 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500378 }
379 break;
380 }
381
382 case Builtins::kSignbit:
383 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
384
385 case Builtins::kReadImageh:
386 return replaceHalfReadImage(F);
387 case Builtins::kReadImagef:
388 case Builtins::kReadImagei:
389 case Builtins::kReadImageui: {
390 if (FI.getParameter(1).isSampler() &&
391 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
392 return replaceSampledReadImageWithIntCoords(F);
393 }
394 break;
395 }
396
397 case Builtins::kWriteImageh:
398 return replaceHalfWriteImage(F);
399
Kévin Petit1cb45112020-04-27 18:55:48 +0100400 case Builtins::kPrefetch:
401 return replacePrefetch(F);
402
SJW2c317da2020-03-23 07:39:13 -0500403 default:
404 break;
405 }
406
407 return false;
408}
409
410bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
411 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400412 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100413}
414
SJW2c317da2020-03-23 07:39:13 -0500415bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
416 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100417 auto XValue = CI->getOperand(0);
418 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100419
Kévin Petite8edce32019-04-10 14:23:32 +0100420 IRBuilder<> Builder(CI);
421 auto XmY = Builder.CreateSub(XValue, YValue);
422 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100423
SJW2c317da2020-03-23 07:39:13 -0500424 Value *Cmp = nullptr;
425 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100426 Cmp = Builder.CreateICmpSGT(YValue, XValue);
427 } else {
428 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100429 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100430
Kévin Petite8edce32019-04-10 14:23:32 +0100431 return Builder.CreateSelect(Cmp, YmX, XmY);
432 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100433}
434
SJW2c317da2020-03-23 07:39:13 -0500435bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
436 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100437 auto XValue = CI->getOperand(0);
438 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100439
Kévin Petite8edce32019-04-10 14:23:32 +0100440 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100441
SJW2c317da2020-03-23 07:39:13 -0500442 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400443 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-bakerb3e2b6d2020-06-24 23:59:57 -0400444 IntTy = FixedVectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petit8c1be282019-04-02 19:34:25 +0100445 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100446
Kévin Petite8edce32019-04-10 14:23:32 +0100447 // Return X with the sign of Y
448
449 // Sign bit masks
450 auto SignBit = IntTy->getScalarSizeInBits() - 1;
451 auto SignBitMask = 1 << SignBit;
452 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
453 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
454
455 IRBuilder<> Builder(CI);
456
457 // Extract sign of Y
458 auto YInt = Builder.CreateBitCast(YValue, IntTy);
459 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
460
461 // Clear sign bit in X
462 auto XInt = Builder.CreateBitCast(XValue, IntTy);
463 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
464
465 // Insert sign bit of Y into X
466 auto NewXInt = Builder.CreateOr(XInt, YSign);
467
468 // And cast back to floating-point
469 return Builder.CreateBitCast(NewXInt, Ty);
470 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100471}
472
SJW2c317da2020-03-23 07:39:13 -0500473bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
474 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100475 // Recip has one arg.
476 auto Arg = CI->getOperand(0);
477 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
478 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
479 });
David Neto22f144c2017-06-12 14:26:21 -0400480}
481
SJW2c317da2020-03-23 07:39:13 -0500482bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
483 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100484 auto Op0 = CI->getOperand(0);
485 auto Op1 = CI->getOperand(1);
486 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
487 });
David Neto22f144c2017-06-12 14:26:21 -0400488}
489
SJW2c317da2020-03-23 07:39:13 -0500490bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
491 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100492 auto Op0 = CI->getOperand(0);
493 auto Op1 = CI->getOperand(1);
494
SJW2c317da2020-03-23 07:39:13 -0500495 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100496 if (Op0->getType()->isVectorTy()) {
497 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
498 CI->getType(), {Op0, Op1});
499 } else {
500 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
501 }
502
503 return V;
504 });
505}
506
SJW2c317da2020-03-23 07:39:13 -0500507bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500508 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500509 // convert to natural
510 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500511 std::string NewFName = basename.substr(0, slen);
512 NewFName =
513 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400514
SJW2c317da2020-03-23 07:39:13 -0500515 Module &M = *F.getParent();
516 return replaceCallsWithValue(F, [&](CallInst *CI) {
517 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
518
519 auto Arg = CI->getOperand(0);
520
521 // Constant of the natural log of 10 (ln(10)).
522 const double Ln10 =
523 2.302585092994045684017991454684364207601101488628772976033;
524
525 auto Mul = BinaryOperator::Create(
526 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
527
528 return CallInst::Create(NewF, Mul, "", CI);
529 });
David Neto22f144c2017-06-12 14:26:21 -0400530}
531
SJW2c317da2020-03-23 07:39:13 -0500532bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100533 // OpenCL fmod(x,y) is x - y * trunc(x/y)
534 // The sign for a non-zero result is taken from x.
535 // (Try an example.)
536 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500537 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100538 auto Op0 = CI->getOperand(0);
539 auto Op1 = CI->getOperand(1);
540 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
541 });
542}
543
SJW2c317da2020-03-23 07:39:13 -0500544bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500545 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500546 // convert to natural
547 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500548 std::string NewFName = basename.substr(0, slen);
549 NewFName =
550 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400551
SJW2c317da2020-03-23 07:39:13 -0500552 Module &M = *F.getParent();
553 return replaceCallsWithValue(F, [&](CallInst *CI) {
554 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
555
556 auto Arg = CI->getOperand(0);
557
558 // Constant of the reciprocal of the natural log of 10 (ln(10)).
559 const double Ln10 =
560 0.434294481903251827651128918916605082294397005803666566114;
561
562 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
563
564 return BinaryOperator::Create(Instruction::FMul,
565 ConstantFP::get(Arg->getType(), Ln10), NewCI,
566 "", CI);
567 });
David Neto22f144c2017-06-12 14:26:21 -0400568}
569
alan-baker12d2c182020-07-20 08:22:42 -0400570bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400571
572 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
573
alan-baker12d2c182020-07-20 08:22:42 -0400574 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100575 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400576
Kévin Petitc4643922019-06-17 19:32:05 +0100577 // We need to map the OpenCL constants to the SPIR-V equivalents.
578 const auto LocalMemFence =
579 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
580 const auto GlobalMemFence =
581 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400582 const auto ConstantAcquireRelease = ConstantInt::get(
583 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100584 const auto ConstantScopeDevice =
585 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
586 const auto ConstantScopeWorkgroup =
587 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400588 const auto ConstantScopeSubgroup =
589 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400590
Kévin Petitc4643922019-06-17 19:32:05 +0100591 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
592 const auto LocalMemFenceMask =
593 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
594 const auto WorkgroupShiftAmount =
595 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
596 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
597 Instruction::Shl, LocalMemFenceMask,
598 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400599
Kévin Petitc4643922019-06-17 19:32:05 +0100600 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
601 const auto GlobalMemFenceMask =
602 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
603 const auto UniformShiftAmount =
604 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
605 const auto MemorySemanticsUniform = BinaryOperator::Create(
606 Instruction::Shl, GlobalMemFenceMask,
607 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400608
Kévin Petitc4643922019-06-17 19:32:05 +0100609 // And combine the above together, also adding in
alan-baker12d2c182020-07-20 08:22:42 -0400610 // MemorySemanticsAcquireReleaseMask.
Kévin Petitc4643922019-06-17 19:32:05 +0100611 auto MemorySemantics =
612 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400613 ConstantAcquireRelease, "", CI);
Kévin Petitc4643922019-06-17 19:32:05 +0100614 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
615 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400616
alan-baker12d2c182020-07-20 08:22:42 -0400617 // If the memory scope is not specified explicitly, it is either Subgroup
618 // or Workgroup depending on the type of barrier.
619 Value *MemoryScope =
620 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
621 if (CI->data_operands_size() > 1) {
622 enum {
623 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
624 CL_MEMORY_SCOPE_DEVICE = 0x2,
625 CL_MEMORY_SCOPE_SUBGROUP = 0x4
626 };
627 // The call was given an explicit memory scope.
628 const auto MemoryScopeSubgroup =
629 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
630 const auto MemoryScopeDevice =
631 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400632
alan-baker12d2c182020-07-20 08:22:42 -0400633 auto Cmp =
634 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
635 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
636 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
637 ConstantScopeWorkgroup, "", CI);
638 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
639 MemoryScopeDevice, CI->getOperand(1), "", CI);
640 MemoryScope =
641 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
642 }
643
644 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
645 // the type of barrier;
646 const auto ExecutionScope =
647 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400648
Kévin Petitc4643922019-06-17 19:32:05 +0100649 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
650 {Attribute::NoDuplicate}, CI->getType(),
651 {ExecutionScope, MemoryScope, MemorySemantics});
652 });
David Neto22f144c2017-06-12 14:26:21 -0400653}
654
SJW2c317da2020-03-23 07:39:13 -0500655bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
656 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400657
SJW2c317da2020-03-23 07:39:13 -0500658 return replaceCallsWithValue(F, [&](CallInst *CI) {
659 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
David Neto22f144c2017-06-12 14:26:21 -0400660
SJW2c317da2020-03-23 07:39:13 -0500661 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400662
SJW2c317da2020-03-23 07:39:13 -0500663 // We need to map the OpenCL constants to the SPIR-V equivalents.
664 const auto LocalMemFence =
665 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
666 const auto GlobalMemFence =
667 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
668 const auto ConstantMemorySemantics =
669 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400670 const auto ConstantScopeWorkgroup =
671 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400672
SJW2c317da2020-03-23 07:39:13 -0500673 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
674 const auto LocalMemFenceMask =
675 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
676 const auto WorkgroupShiftAmount =
677 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
678 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
679 Instruction::Shl, LocalMemFenceMask,
680 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400681
SJW2c317da2020-03-23 07:39:13 -0500682 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
683 const auto GlobalMemFenceMask =
684 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
685 const auto UniformShiftAmount =
686 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
687 const auto MemorySemanticsUniform = BinaryOperator::Create(
688 Instruction::Shl, GlobalMemFenceMask,
689 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400690
SJW2c317da2020-03-23 07:39:13 -0500691 // And combine the above together, also adding in
692 // MemorySemanticsSequentiallyConsistentMask.
693 auto MemorySemantics =
694 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
695 ConstantMemorySemantics, "", CI);
696 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
697 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400698
alan-baker12d2c182020-07-20 08:22:42 -0400699 // Memory Scope is always workgroup.
700 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400701
SJW2c317da2020-03-23 07:39:13 -0500702 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier, {}, CI->getType(),
703 {MemoryScope, MemorySemantics});
704 });
David Neto22f144c2017-06-12 14:26:21 -0400705}
706
Kévin Petit1cb45112020-04-27 18:55:48 +0100707bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
708 bool Changed = false;
709
710 SmallVector<Instruction *, 4> ToRemoves;
711
712 // Find all calls to the function
713 for (auto &U : F.uses()) {
714 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
715 ToRemoves.push_back(CI);
716 }
717 }
718
719 Changed = !ToRemoves.empty();
720
721 // Delete them
722 for (auto V : ToRemoves) {
723 V->eraseFromParent();
724 }
725
726 return Changed;
727}
728
SJW2c317da2020-03-23 07:39:13 -0500729bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
730 CmpInst::Predicate P,
731 int32_t C) {
732 return replaceCallsWithValue(F, [&](CallInst *CI) {
733 // The predicate to use in the CmpInst.
734 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400735
SJW2c317da2020-03-23 07:39:13 -0500736 // The value to return for true.
737 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400738
SJW2c317da2020-03-23 07:39:13 -0500739 // The value to return for false.
740 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400741
SJW2c317da2020-03-23 07:39:13 -0500742 auto Arg1 = CI->getOperand(0);
743 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400744
SJW2c317da2020-03-23 07:39:13 -0500745 const auto Cmp =
746 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400747
SJW2c317da2020-03-23 07:39:13 -0500748 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
749 });
David Neto22f144c2017-06-12 14:26:21 -0400750}
751
SJW2c317da2020-03-23 07:39:13 -0500752bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
753 spv::Op SPIRVOp,
754 int32_t C) {
755 Module &M = *F.getParent();
756 return replaceCallsWithValue(F, [&](CallInst *CI) {
757 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400758
SJW2c317da2020-03-23 07:39:13 -0500759 // The value to return for true.
760 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400761
SJW2c317da2020-03-23 07:39:13 -0500762 // The value to return for false.
763 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400764
SJW2c317da2020-03-23 07:39:13 -0500765 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400766 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-bakerb3e2b6d2020-06-24 23:59:57 -0400767 CorrespondingBoolTy = FixedVectorType::get(
768 Type::getInt1Ty(M.getContext()), CIVecTy->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -0400769 }
David Neto22f144c2017-06-12 14:26:21 -0400770
SJW2c317da2020-03-23 07:39:13 -0500771 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
772 CorrespondingBoolTy, {CI->getOperand(0)});
773
774 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
775 });
David Neto22f144c2017-06-12 14:26:21 -0400776}
777
SJW2c317da2020-03-23 07:39:13 -0500778bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
779 Module &M = *F.getParent();
780 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100781 auto &C = M.getContext();
782 auto Val = CI->getOperand(0);
783 auto ValTy = Val->getType();
784 auto RetTy = CI->getType();
785
786 // Get a suitable integer type to represent the number
787 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
788
789 // Create Mask
790 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -0500791 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100792 switch (ScalarSize) {
793 case 16:
794 InfMask = ConstantInt::get(IntTy, 0x7C00U);
795 break;
796 case 32:
797 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
798 break;
799 case 64:
800 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
801 break;
802 default:
803 llvm_unreachable("Unsupported floating-point type");
804 }
805
806 IRBuilder<> Builder(CI);
807
808 // Bitcast to int
809 auto ValInt = Builder.CreateBitCast(Val, IntTy);
810
811 // Mask and compare
812 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
813 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
814
815 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -0500816 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100817 if (ValTy->isVectorTy()) {
818 RetTrue = ConstantInt::getSigned(RetTy, -1);
819 } else {
820 RetTrue = ConstantInt::get(RetTy, 1);
821 }
822 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
823 });
824}
825
SJW2c317da2020-03-23 07:39:13 -0500826bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
827 Module &M = *F.getParent();
828 return replaceCallsWithValue(F, [&](CallInst *CI) {
829 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400830
SJW2c317da2020-03-23 07:39:13 -0500831 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +0000832
SJW2c317da2020-03-23 07:39:13 -0500833 // If the argument is a 32-bit int, just use a shift
834 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
835 V = BinaryOperator::Create(Instruction::LShr, Arg,
836 ConstantInt::get(Arg->getType(), 31), "", CI);
837 } else {
838 // The value for zero to compare against.
839 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -0400840
SJW2c317da2020-03-23 07:39:13 -0500841 // The value to return for true.
842 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -0400843
SJW2c317da2020-03-23 07:39:13 -0500844 // The value to return for false.
845 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400846
SJW2c317da2020-03-23 07:39:13 -0500847 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
848 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400849
SJW2c317da2020-03-23 07:39:13 -0500850 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400851
SJW2c317da2020-03-23 07:39:13 -0500852 // If we have a function to call, call it!
853 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -0400854
SJW2c317da2020-03-23 07:39:13 -0500855 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -0400856
SJW2c317da2020-03-23 07:39:13 -0500857 const auto NewCI = clspv::InsertSPIRVOp(
858 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
859 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -0400860
SJW2c317da2020-03-23 07:39:13 -0500861 } else {
862 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -0400863 }
864
SJW2c317da2020-03-23 07:39:13 -0500865 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400866 }
SJW2c317da2020-03-23 07:39:13 -0500867 return V;
868 });
David Neto22f144c2017-06-12 14:26:21 -0400869}
870
SJW2c317da2020-03-23 07:39:13 -0500871bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
872 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
873 // Get arguments
874 auto HiValue = CI->getOperand(0);
875 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000876
SJW2c317da2020-03-23 07:39:13 -0500877 // Don't touch overloads that aren't in OpenCL C
878 auto HiType = HiValue->getType();
879 auto LoType = LoValue->getType();
880
881 if (HiType != LoType) {
882 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000883 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000884
SJW2c317da2020-03-23 07:39:13 -0500885 if (!HiType->isIntOrIntVectorTy()) {
886 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000887 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000888
SJW2c317da2020-03-23 07:39:13 -0500889 if (HiType->getScalarSizeInBits() * 2 !=
890 CI->getType()->getScalarSizeInBits()) {
891 return nullptr;
892 }
893
894 if ((HiType->getScalarSizeInBits() != 8) &&
895 (HiType->getScalarSizeInBits() != 16) &&
896 (HiType->getScalarSizeInBits() != 32)) {
897 return nullptr;
898 }
899
James Pricecf53df42020-04-20 14:41:24 -0400900 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
901 unsigned NumElements = HiVecType->getNumElements();
902 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
903 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500904 return nullptr;
905 }
906 }
907
908 // Convert both operands to the result type
909 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
910 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
911
912 // Shift high operand
913 auto ShiftAmount =
914 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
915 auto HiShifted =
916 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
917
918 // OR both results
919 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
920 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000921}
922
SJW2c317da2020-03-23 07:39:13 -0500923bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
924 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
925 // Get arguments
926 auto SrcValue = CI->getOperand(0);
927 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000928
SJW2c317da2020-03-23 07:39:13 -0500929 // Don't touch overloads that aren't in OpenCL C
930 auto SrcType = SrcValue->getType();
931 auto RotType = RotAmount->getType();
932
933 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
934 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000935 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000936
SJW2c317da2020-03-23 07:39:13 -0500937 if (!SrcType->isIntOrIntVectorTy()) {
938 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000939 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000940
SJW2c317da2020-03-23 07:39:13 -0500941 if ((SrcType->getScalarSizeInBits() != 8) &&
942 (SrcType->getScalarSizeInBits() != 16) &&
943 (SrcType->getScalarSizeInBits() != 32) &&
944 (SrcType->getScalarSizeInBits() != 64)) {
945 return nullptr;
946 }
947
James Pricecf53df42020-04-20 14:41:24 -0400948 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
949 unsigned NumElements = SrcVecType->getNumElements();
950 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
951 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500952 return nullptr;
953 }
954 }
955
956 // The approach used is to shift the top bits down, the bottom bits up
957 // and OR the two shifted values.
958
959 // The rotation amount is to be treated modulo the element size.
960 // Since SPIR-V shift ops don't support this, let's apply the
961 // modulo ahead of shifting. The element size is always a power of
962 // two so we can just AND with a mask.
963 auto ModMask =
964 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
965 RotAmount =
966 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
967
968 // Let's calc the amount by which to shift top bits down
969 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
970 auto DownAmount =
971 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
972
973 // Now shift the bottom bits up and the top bits down
974 auto LoRotated =
975 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
976 auto HiRotated =
977 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
978
979 // Finally OR the two shifted values
980 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
981 CI);
982 });
Kévin Petitd44eef52019-03-08 13:22:14 +0000983}
984
SJW2c317da2020-03-23 07:39:13 -0500985bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
986 bool DstIsSigned) {
987 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
988 Value *V = nullptr;
989 // Get arguments
990 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000991
SJW2c317da2020-03-23 07:39:13 -0500992 // Don't touch overloads that aren't in OpenCL C
993 auto SrcType = SrcValue->getType();
994 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000995
SJW2c317da2020-03-23 07:39:13 -0500996 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
997 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
998 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000999 }
1000
James Pricecf53df42020-04-20 14:41:24 -04001001 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
1002 unsigned SrcNumElements = SrcVecType->getNumElements();
1003 unsigned DstNumElements = cast<VectorType>(DstType)->getNumElements();
1004 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001005 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001006 }
1007
James Pricecf53df42020-04-20 14:41:24 -04001008 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1009 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1010 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001011 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001012 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001013 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001014
SJW2c317da2020-03-23 07:39:13 -05001015 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1016 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1017
1018 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1019 bool DstIsInt = DstType->isIntOrIntVectorTy();
1020
1021 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1022 // Unnecessary cast operation.
1023 V = SrcValue;
1024 } else if (SrcIsFloat && DstIsFloat) {
1025 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1026 } else if (SrcIsFloat && DstIsInt) {
1027 if (DstIsSigned) {
1028 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1029 } else {
1030 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1031 }
1032 } else if (SrcIsInt && DstIsFloat) {
1033 if (SrcIsSigned) {
1034 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1035 } else {
1036 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1037 }
1038 } else if (SrcIsInt && DstIsInt) {
1039 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1040 } else {
1041 // Not something we're supposed to handle, just move on
1042 }
1043
1044 return V;
1045 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001046}
1047
SJW2c317da2020-03-23 07:39:13 -05001048bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1049 bool is_mad) {
1050 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1051 Value *V = nullptr;
1052 // Get arguments
1053 auto AValue = CI->getOperand(0);
1054 auto BValue = CI->getOperand(1);
1055 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001056
SJW2c317da2020-03-23 07:39:13 -05001057 // Don't touch overloads that aren't in OpenCL C
1058 auto AType = AValue->getType();
1059 auto BType = BValue->getType();
1060 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001061
SJW2c317da2020-03-23 07:39:13 -05001062 if ((AType != BType) || (CI->getType() != AType) ||
1063 (is_mad && (AType != CType))) {
1064 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001065 }
1066
SJW2c317da2020-03-23 07:39:13 -05001067 if (!AType->isIntOrIntVectorTy()) {
1068 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001069 }
Kévin Petit8a560882019-03-21 15:24:34 +00001070
SJW2c317da2020-03-23 07:39:13 -05001071 if ((AType->getScalarSizeInBits() != 8) &&
1072 (AType->getScalarSizeInBits() != 16) &&
1073 (AType->getScalarSizeInBits() != 32) &&
1074 (AType->getScalarSizeInBits() != 64)) {
1075 return V;
1076 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001077
James Pricecf53df42020-04-20 14:41:24 -04001078 if (auto AVecType = dyn_cast<VectorType>(AType)) {
1079 unsigned NumElements = AVecType->getNumElements();
1080 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1081 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001082 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001083 }
1084 }
1085
SJW2c317da2020-03-23 07:39:13 -05001086 // Our SPIR-V op returns a struct, create a type for it
1087 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1088 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001089
SJW2c317da2020-03-23 07:39:13 -05001090 // Select the appropriate signed/unsigned SPIR-V op
1091 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1092
1093 // Call the SPIR-V op
1094 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1095 ExMulRetType, {AValue, BValue});
1096
1097 // Get the high part of the result
1098 unsigned Idxs[] = {1};
1099 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1100
1101 // If we're handling a mad_hi, add the third argument to the result
1102 if (is_mad) {
1103 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001104 }
1105
SJW2c317da2020-03-23 07:39:13 -05001106 return V;
1107 });
Kévin Petit8a560882019-03-21 15:24:34 +00001108}
1109
SJW2c317da2020-03-23 07:39:13 -05001110bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1111 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1112 // Get arguments
1113 auto FalseValue = CI->getOperand(0);
1114 auto TrueValue = CI->getOperand(1);
1115 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001116
SJW2c317da2020-03-23 07:39:13 -05001117 // Don't touch overloads that aren't in OpenCL C
1118 auto FalseType = FalseValue->getType();
1119 auto TrueType = TrueValue->getType();
1120 auto PredicateType = PredicateValue->getType();
1121
1122 if (FalseType != TrueType) {
1123 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001124 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001125
SJW2c317da2020-03-23 07:39:13 -05001126 if (!PredicateType->isIntOrIntVectorTy()) {
1127 return nullptr;
1128 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001129
SJW2c317da2020-03-23 07:39:13 -05001130 if (!FalseType->isIntOrIntVectorTy() &&
1131 !FalseType->getScalarType()->isFloatingPointTy()) {
1132 return nullptr;
1133 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001134
SJW2c317da2020-03-23 07:39:13 -05001135 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1136 return nullptr;
1137 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001138
SJW2c317da2020-03-23 07:39:13 -05001139 if (FalseType->getScalarSizeInBits() !=
1140 PredicateType->getScalarSizeInBits()) {
1141 return nullptr;
1142 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001143
James Pricecf53df42020-04-20 14:41:24 -04001144 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
1145 unsigned NumElements = FalseVecType->getNumElements();
1146 if (NumElements != cast<VectorType>(PredicateType)->getNumElements()) {
SJW2c317da2020-03-23 07:39:13 -05001147 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001148 }
1149
James Pricecf53df42020-04-20 14:41:24 -04001150 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1151 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001152 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001153 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001154 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001155
SJW2c317da2020-03-23 07:39:13 -05001156 // Create constant
1157 const auto ZeroValue = Constant::getNullValue(PredicateType);
1158
1159 // Scalar and vector are to be treated differently
1160 CmpInst::Predicate Pred;
1161 if (PredicateType->isVectorTy()) {
1162 Pred = CmpInst::ICMP_SLT;
1163 } else {
1164 Pred = CmpInst::ICMP_NE;
1165 }
1166
1167 // Create comparison instruction
1168 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1169 ZeroValue, "", CI);
1170
1171 // Create select
1172 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1173 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001174}
1175
SJW2c317da2020-03-23 07:39:13 -05001176bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1177 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1178 Value *V = nullptr;
1179 if (CI->getNumOperands() != 4) {
1180 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001181 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001182
SJW2c317da2020-03-23 07:39:13 -05001183 // Get arguments
1184 auto FalseValue = CI->getOperand(0);
1185 auto TrueValue = CI->getOperand(1);
1186 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001187
SJW2c317da2020-03-23 07:39:13 -05001188 // Don't touch overloads that aren't in OpenCL C
1189 auto FalseType = FalseValue->getType();
1190 auto TrueType = TrueValue->getType();
1191 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001192
SJW2c317da2020-03-23 07:39:13 -05001193 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1194 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001195 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001196
James Pricecf53df42020-04-20 14:41:24 -04001197 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001198 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1199 !TrueType->getScalarType()->isIntegerTy()) {
1200 return V;
1201 }
James Pricecf53df42020-04-20 14:41:24 -04001202 unsigned NumElements = TrueVecType->getNumElements();
1203 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1204 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001205 return V;
1206 }
1207 }
1208
1209 // Remember the type of the operands
1210 auto OpType = TrueType;
1211
1212 // The actual bit selection will always be done on an integer type,
1213 // declare it here
1214 Type *BitType;
1215
1216 // If the operands are float, then bitcast them to int
1217 if (OpType->getScalarType()->isFloatingPointTy()) {
1218
1219 // First create the new type
1220 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1221
1222 // Then bitcast all operands
1223 PredicateValue =
1224 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1225 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1226 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1227
1228 } else {
1229 // The operands have an integer type, use it directly
1230 BitType = OpType;
1231 }
1232
1233 // All the operands are now always integers
1234 // implement as (c & b) | (~c & a)
1235
1236 // Create our negated predicate value
1237 auto AllOnes = Constant::getAllOnesValue(BitType);
1238 auto NotPredicateValue = BinaryOperator::Create(
1239 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1240
1241 // Then put everything together
1242 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1243 FalseValue, "", CI);
1244 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1245 TrueValue, "", CI);
1246
1247 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1248
1249 // If we were dealing with a floating point type, we must bitcast
1250 // the result back to that
1251 if (OpType->getScalarType()->isFloatingPointTy()) {
1252 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1253 }
1254
1255 return V;
1256 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001257}
1258
SJW61531372020-06-09 07:31:08 -05001259bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001260 // convert to vector versions
1261 Module &M = *F.getParent();
1262 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1263 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1264 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001265
SJW2c317da2020-03-23 07:39:13 -05001266 // First figure out which function we're dealing with
1267 if (is_smooth) {
1268 ArgsToSplat.push_back(CI->getOperand(1));
1269 VectorArg = CI->getOperand(2);
1270 } else {
1271 VectorArg = CI->getOperand(1);
1272 }
1273
1274 // Splat arguments that need to be
1275 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001276 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001277
1278 for (auto arg : ArgsToSplat) {
1279 Value *NewVectorArg = UndefValue::get(VecType);
James Pricecf53df42020-04-20 14:41:24 -04001280 for (auto i = 0; i < VecType->getNumElements(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001281 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1282 NewVectorArg =
1283 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1284 }
1285 SplatArgs.push_back(NewVectorArg);
1286 }
1287
1288 // Replace the call with the vector/vector flavour
1289 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1290 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1291
SJW61531372020-06-09 07:31:08 -05001292 std::string NewFName = Builtins::GetMangledFunctionName(
1293 is_smooth ? "smoothstep" : "step", NewFType);
1294
SJW2c317da2020-03-23 07:39:13 -05001295 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1296
1297 SmallVector<Value *, 3> NewArgs;
1298 for (auto arg : SplatArgs) {
1299 NewArgs.push_back(arg);
1300 }
1301 NewArgs.push_back(VectorArg);
1302
1303 return CallInst::Create(NewF, NewArgs, "", CI);
1304 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001305}
1306
SJW2c317da2020-03-23 07:39:13 -05001307bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001308 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1309 auto Arg = CI->getOperand(0);
1310 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001311
SJW2c317da2020-03-23 07:39:13 -05001312 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001313
SJW2c317da2020-03-23 07:39:13 -05001314 return BinaryOperator::Create(Op, Bitcast,
1315 ConstantInt::get(CI->getType(), 31), "", CI);
1316 });
David Neto22f144c2017-06-12 14:26:21 -04001317}
1318
SJW2c317da2020-03-23 07:39:13 -05001319bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1320 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001321 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1322 // The multiply instruction to use.
1323 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001324
SJW2c317da2020-03-23 07:39:13 -05001325 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001326
SJW2c317da2020-03-23 07:39:13 -05001327 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1328 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001329
SJW2c317da2020-03-23 07:39:13 -05001330 if (is_mad) {
1331 // The add instruction to use.
1332 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001333
SJW2c317da2020-03-23 07:39:13 -05001334 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001335 }
David Neto22f144c2017-06-12 14:26:21 -04001336
SJW2c317da2020-03-23 07:39:13 -05001337 return V;
1338 });
David Neto22f144c2017-06-12 14:26:21 -04001339}
1340
SJW2c317da2020-03-23 07:39:13 -05001341bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001342 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1343 Value *V = nullptr;
1344 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001345
SJW2c317da2020-03-23 07:39:13 -05001346 auto data_type = data->getType();
1347 if (!data_type->isVectorTy())
1348 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001349
James Pricecf53df42020-04-20 14:41:24 -04001350 auto vec_data_type = cast<VectorType>(data_type);
1351
1352 auto elems = vec_data_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001353 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1354 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001355
SJW2c317da2020-03-23 07:39:13 -05001356 auto offset = CI->getOperand(1);
1357 auto ptr = CI->getOperand(2);
1358 auto ptr_type = ptr->getType();
1359 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001360 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001361 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001362
SJW2c317da2020-03-23 07:39:13 -05001363 // Avoid pointer casts. Instead generate the correct number of stores
1364 // and rely on drivers to coalesce appropriately.
1365 IRBuilder<> builder(CI);
1366 auto elems_const = builder.getInt32(elems);
1367 auto adjust = builder.CreateMul(offset, elems_const);
1368 for (auto i = 0; i < elems; ++i) {
1369 auto idx = builder.getInt32(i);
1370 auto add = builder.CreateAdd(adjust, idx);
1371 auto gep = builder.CreateGEP(ptr, add);
1372 auto extract = builder.CreateExtractElement(data, i);
1373 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001374 }
SJW2c317da2020-03-23 07:39:13 -05001375 return V;
1376 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001377}
1378
SJW2c317da2020-03-23 07:39:13 -05001379bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001380 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1381 Value *V = nullptr;
1382 auto ret_type = F.getReturnType();
1383 if (!ret_type->isVectorTy())
1384 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001385
James Pricecf53df42020-04-20 14:41:24 -04001386 auto vec_ret_type = cast<VectorType>(ret_type);
1387
1388 auto elems = vec_ret_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001389 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1390 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001391
SJW2c317da2020-03-23 07:39:13 -05001392 auto offset = CI->getOperand(0);
1393 auto ptr = CI->getOperand(1);
1394 auto ptr_type = ptr->getType();
1395 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001396 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001397 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001398
SJW2c317da2020-03-23 07:39:13 -05001399 // Avoid pointer casts. Instead generate the correct number of loads
1400 // and rely on drivers to coalesce appropriately.
1401 IRBuilder<> builder(CI);
1402 auto elems_const = builder.getInt32(elems);
1403 V = UndefValue::get(ret_type);
1404 auto adjust = builder.CreateMul(offset, elems_const);
1405 for (auto i = 0; i < elems; ++i) {
1406 auto idx = builder.getInt32(i);
1407 auto add = builder.CreateAdd(adjust, idx);
1408 auto gep = builder.CreateGEP(ptr, add);
1409 auto load = builder.CreateLoad(gep);
1410 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001411 }
SJW2c317da2020-03-23 07:39:13 -05001412 return V;
1413 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001414}
1415
SJW2c317da2020-03-23 07:39:13 -05001416bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1417 const std::string &name,
1418 int vec_size) {
1419 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1420 if (!vec_size) {
1421 // deduce vec_size from last character of name (e.g. vload_half4)
1422 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001423 }
SJW2c317da2020-03-23 07:39:13 -05001424 switch (vec_size) {
1425 case 2:
1426 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1427 case 4:
1428 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1429 case 0:
1430 if (!is_clspv_version) {
1431 return replaceVloadHalf(F);
1432 }
1433 default:
1434 llvm_unreachable("Unsupported vload_half vector size");
1435 break;
1436 }
1437 return false;
David Neto22f144c2017-06-12 14:26:21 -04001438}
1439
SJW2c317da2020-03-23 07:39:13 -05001440bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1441 Module &M = *F.getParent();
1442 return replaceCallsWithValue(F, [&](CallInst *CI) {
1443 // The index argument from vload_half.
1444 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001445
SJW2c317da2020-03-23 07:39:13 -05001446 // The pointer argument from vload_half.
1447 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001448
SJW2c317da2020-03-23 07:39:13 -05001449 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001450 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001451 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1452
1453 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001454 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001455
1456 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1457
1458 Value *V = nullptr;
1459
alan-baker7efcaaa2020-05-06 19:33:27 -04001460 bool supports_16bit_storage = true;
1461 switch (Arg1->getType()->getPointerAddressSpace()) {
1462 case clspv::AddressSpace::Global:
1463 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1464 clspv::Option::StorageClass::kSSBO);
1465 break;
1466 case clspv::AddressSpace::Constant:
1467 if (clspv::Option::ConstantArgsInUniformBuffer())
1468 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1469 clspv::Option::StorageClass::kUBO);
1470 else
1471 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1472 clspv::Option::StorageClass::kSSBO);
1473 break;
1474 default:
1475 // Clspv will emit the Float16 capability if the half type is
1476 // encountered. That capability covers private and local addressspaces.
1477 break;
1478 }
1479
1480 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001481 auto ShortTy = Type::getInt16Ty(M.getContext());
1482 auto ShortPointerTy =
1483 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1484
1485 // Cast the half* pointer to short*.
1486 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1487
1488 // Index into the correct address of the casted pointer.
1489 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1490
1491 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001492 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001493
1494 // ZExt the short -> int.
1495 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1496
1497 // Get our float2.
1498 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1499
1500 // Extract out the bottom element which is our float result.
1501 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1502 } else {
1503 // Assume the pointer argument points to storage aligned to 32bits
1504 // or more.
1505 // TODO(dneto): Do more analysis to make sure this is true?
1506 //
1507 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1508 // with:
1509 //
1510 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1511 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1512 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1513 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1514 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1515 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1516 // x float> %converted, %index_is_odd32
1517
1518 auto IntPointerTy =
1519 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1520
1521 // Cast the base pointer to int*.
1522 // In a valid call (according to assumptions), this should get
1523 // optimized away in the simplify GEP pass.
1524 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1525
1526 auto One = ConstantInt::get(IntTy, 1);
1527 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1528 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1529
1530 // Index into the correct address of the casted pointer.
1531 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1532
1533 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001534 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001535
1536 // Get our float2.
1537 auto Call = CallInst::Create(NewF, Load, "", CI);
1538
1539 // Extract out the float result, where the element number is
1540 // determined by whether the original index was even or odd.
1541 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1542 }
1543 return V;
1544 });
1545}
1546
1547bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1548 Module &M = *F.getParent();
1549 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001550 // The index argument from vload_half.
1551 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001552
Kévin Petite8edce32019-04-10 14:23:32 +01001553 // The pointer argument from vload_half.
1554 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001555
Kévin Petite8edce32019-04-10 14:23:32 +01001556 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001557 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001558 auto NewPointerTy =
1559 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001560 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001561
Kévin Petite8edce32019-04-10 14:23:32 +01001562 // Cast the half* pointer to int*.
1563 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001564
Kévin Petite8edce32019-04-10 14:23:32 +01001565 // Index into the correct address of the casted pointer.
1566 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001567
Kévin Petite8edce32019-04-10 14:23:32 +01001568 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001569 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001570
Kévin Petite8edce32019-04-10 14:23:32 +01001571 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001572 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001573
Kévin Petite8edce32019-04-10 14:23:32 +01001574 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001575
Kévin Petite8edce32019-04-10 14:23:32 +01001576 // Get our float2.
1577 return CallInst::Create(NewF, Load, "", CI);
1578 });
David Neto22f144c2017-06-12 14:26:21 -04001579}
1580
SJW2c317da2020-03-23 07:39:13 -05001581bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1582 Module &M = *F.getParent();
1583 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001584 // The index argument from vload_half.
1585 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001586
Kévin Petite8edce32019-04-10 14:23:32 +01001587 // The pointer argument from vload_half.
1588 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001589
Kévin Petite8edce32019-04-10 14:23:32 +01001590 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001591 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1592 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001593 auto NewPointerTy =
1594 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001595 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001596
Kévin Petite8edce32019-04-10 14:23:32 +01001597 // Cast the half* pointer to int2*.
1598 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001599
Kévin Petite8edce32019-04-10 14:23:32 +01001600 // Index into the correct address of the casted pointer.
1601 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001602
Kévin Petite8edce32019-04-10 14:23:32 +01001603 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001604 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001605
Kévin Petite8edce32019-04-10 14:23:32 +01001606 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001607 auto X =
1608 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1609 auto Y =
1610 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001611
Kévin Petite8edce32019-04-10 14:23:32 +01001612 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001613 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001614
Kévin Petite8edce32019-04-10 14:23:32 +01001615 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001616
Kévin Petite8edce32019-04-10 14:23:32 +01001617 // Get the lower (x & y) components of our final float4.
1618 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001619
Kévin Petite8edce32019-04-10 14:23:32 +01001620 // Get the higher (z & w) components of our final float4.
1621 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001622
Kévin Petite8edce32019-04-10 14:23:32 +01001623 Constant *ShuffleMask[4] = {
1624 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1625 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001626
Kévin Petite8edce32019-04-10 14:23:32 +01001627 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001628 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1629 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001630 });
David Neto22f144c2017-06-12 14:26:21 -04001631}
1632
SJW2c317da2020-03-23 07:39:13 -05001633bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001634
1635 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1636 //
1637 // %u = load i32 %ptr
1638 // %fxy = call <2 x float> Unpack2xHalf(u)
1639 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001640 Module &M = *F.getParent();
1641 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001642 auto Index = CI->getOperand(0);
1643 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001644
Kévin Petite8edce32019-04-10 14:23:32 +01001645 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001646 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001647 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001648
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001649 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001650 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001651
Kévin Petite8edce32019-04-10 14:23:32 +01001652 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001653 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001654
Kévin Petite8edce32019-04-10 14:23:32 +01001655 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001656
Kévin Petite8edce32019-04-10 14:23:32 +01001657 // Get our final float2.
1658 return CallInst::Create(NewF, Load, "", CI);
1659 });
David Neto6ad93232018-06-07 15:42:58 -07001660}
1661
SJW2c317da2020-03-23 07:39:13 -05001662bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001663
1664 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1665 //
1666 // %u2 = load <2 x i32> %ptr
1667 // %u2xy = extractelement %u2, 0
1668 // %u2zw = extractelement %u2, 1
1669 // %fxy = call <2 x float> Unpack2xHalf(uint)
1670 // %fzw = call <2 x float> Unpack2xHalf(uint)
1671 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001672 Module &M = *F.getParent();
1673 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001674 auto Index = CI->getOperand(0);
1675 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001676
Kévin Petite8edce32019-04-10 14:23:32 +01001677 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001678 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1679 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001680 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001681
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001682 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001683 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001684
Kévin Petite8edce32019-04-10 14:23:32 +01001685 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001686 auto X =
1687 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1688 auto Y =
1689 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001690
Kévin Petite8edce32019-04-10 14:23:32 +01001691 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001692 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001693
Kévin Petite8edce32019-04-10 14:23:32 +01001694 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001695
Kévin Petite8edce32019-04-10 14:23:32 +01001696 // Get the lower (x & y) components of our final float4.
1697 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001698
Kévin Petite8edce32019-04-10 14:23:32 +01001699 // Get the higher (z & w) components of our final float4.
1700 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001701
Kévin Petite8edce32019-04-10 14:23:32 +01001702 Constant *ShuffleMask[4] = {
1703 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1704 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001705
Kévin Petite8edce32019-04-10 14:23:32 +01001706 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001707 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1708 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001709 });
David Neto6ad93232018-06-07 15:42:58 -07001710}
1711
SJW2c317da2020-03-23 07:39:13 -05001712bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1713 switch (vec_size) {
1714 case 0:
1715 return replaceVstoreHalf(F);
1716 case 2:
1717 return replaceVstoreHalf2(F);
1718 case 4:
1719 return replaceVstoreHalf4(F);
1720 default:
1721 llvm_unreachable("Unsupported vstore_half vector size");
1722 break;
1723 }
1724 return false;
1725}
David Neto22f144c2017-06-12 14:26:21 -04001726
SJW2c317da2020-03-23 07:39:13 -05001727bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1728 Module &M = *F.getParent();
1729 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001730 // The value to store.
1731 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001732
Kévin Petite8edce32019-04-10 14:23:32 +01001733 // The index argument from vstore_half.
1734 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001735
Kévin Petite8edce32019-04-10 14:23:32 +01001736 // The pointer argument from vstore_half.
1737 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001738
Kévin Petite8edce32019-04-10 14:23:32 +01001739 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001740 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001741 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1742 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001743
Kévin Petite8edce32019-04-10 14:23:32 +01001744 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001745 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001746
Kévin Petite8edce32019-04-10 14:23:32 +01001747 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001748
Kévin Petite8edce32019-04-10 14:23:32 +01001749 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001750 auto TempVec = InsertElementInst::Create(
1751 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001752
Kévin Petite8edce32019-04-10 14:23:32 +01001753 // Pack the float2 -> half2 (in an int).
1754 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001755
alan-baker7efcaaa2020-05-06 19:33:27 -04001756 bool supports_16bit_storage = true;
1757 switch (Arg2->getType()->getPointerAddressSpace()) {
1758 case clspv::AddressSpace::Global:
1759 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1760 clspv::Option::StorageClass::kSSBO);
1761 break;
1762 case clspv::AddressSpace::Constant:
1763 if (clspv::Option::ConstantArgsInUniformBuffer())
1764 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1765 clspv::Option::StorageClass::kUBO);
1766 else
1767 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1768 clspv::Option::StorageClass::kSSBO);
1769 break;
1770 default:
1771 // Clspv will emit the Float16 capability if the half type is
1772 // encountered. That capability covers private and local addressspaces.
1773 break;
1774 }
1775
SJW2c317da2020-03-23 07:39:13 -05001776 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04001777 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01001778 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001779 auto ShortPointerTy =
1780 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001781
Kévin Petite8edce32019-04-10 14:23:32 +01001782 // Truncate our i32 to an i16.
1783 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001784
Kévin Petite8edce32019-04-10 14:23:32 +01001785 // Cast the half* pointer to short*.
1786 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001787
Kévin Petite8edce32019-04-10 14:23:32 +01001788 // Index into the correct address of the casted pointer.
1789 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001790
Kévin Petite8edce32019-04-10 14:23:32 +01001791 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001792 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001793 } else {
1794 // We can only write to 32-bit aligned words.
1795 //
1796 // Assuming base is aligned to 32-bits, replace the equivalent of
1797 // vstore_half(value, index, base)
1798 // with:
1799 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1800 // uint32_t write_to_upper_half = index & 1u;
1801 // uint32_t shift = write_to_upper_half << 4;
1802 //
1803 // // Pack the float value as a half number in bottom 16 bits
1804 // // of an i32.
1805 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1806 //
1807 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1808 // ^ ((packed & 0xffff) << shift)
1809 // // We only need relaxed consistency, but OpenCL 1.2 only has
1810 // // sequentially consistent atomics.
1811 // // TODO(dneto): Use relaxed consistency.
1812 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001813 auto IntPointerTy =
1814 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001815
Kévin Petite8edce32019-04-10 14:23:32 +01001816 auto Four = ConstantInt::get(IntTy, 4);
1817 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001818
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001819 auto IndexIsOdd =
1820 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001821 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001822 auto IndexIntoI32 =
1823 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1824 auto BaseI32Ptr =
1825 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1826 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1827 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001828 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001829 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001830 auto MaskBitsToWrite =
1831 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1832 auto MaskedCurrent = BinaryOperator::CreateAnd(
1833 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001834
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001835 auto XLowerBits =
1836 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1837 auto NewBitsToWrite =
1838 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1839 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1840 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001841
Kévin Petite8edce32019-04-10 14:23:32 +01001842 // Generate the call to atomi_xor.
1843 SmallVector<Type *, 5> ParamTypes;
1844 // The pointer type.
1845 ParamTypes.push_back(IntPointerTy);
1846 // The Types for memory scope, semantics, and value.
1847 ParamTypes.push_back(IntTy);
1848 ParamTypes.push_back(IntTy);
1849 ParamTypes.push_back(IntTy);
1850 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1851 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001852
Kévin Petite8edce32019-04-10 14:23:32 +01001853 const auto ConstantScopeDevice =
1854 ConstantInt::get(IntTy, spv::ScopeDevice);
1855 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1856 // (SPIR-V Workgroup).
1857 const auto AddrSpaceSemanticsBits =
1858 IntPointerTy->getPointerAddressSpace() == 1
1859 ? spv::MemorySemanticsUniformMemoryMask
1860 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001861
Kévin Petite8edce32019-04-10 14:23:32 +01001862 // We're using relaxed consistency here.
1863 const auto ConstantMemorySemantics =
1864 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1865 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001866
Kévin Petite8edce32019-04-10 14:23:32 +01001867 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1868 ConstantMemorySemantics, ValueToXor};
1869 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001870
1871 // Return a Nop so the old Call is removed
1872 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1873 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001874 }
David Neto22f144c2017-06-12 14:26:21 -04001875
SJW2c317da2020-03-23 07:39:13 -05001876 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001877 });
David Neto22f144c2017-06-12 14:26:21 -04001878}
1879
SJW2c317da2020-03-23 07:39:13 -05001880bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1881 Module &M = *F.getParent();
1882 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001883 // The value to store.
1884 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001885
Kévin Petite8edce32019-04-10 14:23:32 +01001886 // The index argument from vstore_half.
1887 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001888
Kévin Petite8edce32019-04-10 14:23:32 +01001889 // The pointer argument from vstore_half.
1890 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001891
Kévin Petite8edce32019-04-10 14:23:32 +01001892 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001893 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001894 auto NewPointerTy =
1895 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001896 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001897
Kévin Petite8edce32019-04-10 14:23:32 +01001898 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001899 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001900
Kévin Petite8edce32019-04-10 14:23:32 +01001901 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 // Turn the packed x & y into the final packing.
1904 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001905
Kévin Petite8edce32019-04-10 14:23:32 +01001906 // Cast the half* pointer to int*.
1907 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001908
Kévin Petite8edce32019-04-10 14:23:32 +01001909 // Index into the correct address of the casted pointer.
1910 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001911
Kévin Petite8edce32019-04-10 14:23:32 +01001912 // Store to the int* we casted to.
1913 return new StoreInst(X, Index, CI);
1914 });
David Neto22f144c2017-06-12 14:26:21 -04001915}
1916
SJW2c317da2020-03-23 07:39:13 -05001917bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1918 Module &M = *F.getParent();
1919 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001920 // The value to store.
1921 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001922
Kévin Petite8edce32019-04-10 14:23:32 +01001923 // The index argument from vstore_half.
1924 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001925
Kévin Petite8edce32019-04-10 14:23:32 +01001926 // The pointer argument from vstore_half.
1927 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001928
Kévin Petite8edce32019-04-10 14:23:32 +01001929 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001930 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1931 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001932 auto NewPointerTy =
1933 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001934 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001935
Kévin Petite8edce32019-04-10 14:23:32 +01001936 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1937 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04001938
Kévin Petite8edce32019-04-10 14:23:32 +01001939 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001940 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1941 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001942
Kévin Petite8edce32019-04-10 14:23:32 +01001943 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1944 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001945
Kévin Petite8edce32019-04-10 14:23:32 +01001946 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001947 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1948 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001949
Kévin Petite8edce32019-04-10 14:23:32 +01001950 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001951 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001952
Kévin Petite8edce32019-04-10 14:23:32 +01001953 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001954
Kévin Petite8edce32019-04-10 14:23:32 +01001955 // Turn the packed x & y into the final component of our int2.
1956 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001957
Kévin Petite8edce32019-04-10 14:23:32 +01001958 // Turn the packed z & w into the final component of our int2.
1959 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001960
Kévin Petite8edce32019-04-10 14:23:32 +01001961 auto Combine = InsertElementInst::Create(
1962 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001963 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
1964 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001965
Kévin Petite8edce32019-04-10 14:23:32 +01001966 // Cast the half* pointer to int2*.
1967 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001968
Kévin Petite8edce32019-04-10 14:23:32 +01001969 // Index into the correct address of the casted pointer.
1970 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001971
Kévin Petite8edce32019-04-10 14:23:32 +01001972 // Store to the int2* we casted to.
1973 return new StoreInst(Combine, Index, CI);
1974 });
David Neto22f144c2017-06-12 14:26:21 -04001975}
1976
SJW2c317da2020-03-23 07:39:13 -05001977bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
1978 // convert half to float
1979 Module &M = *F.getParent();
1980 return replaceCallsWithValue(F, [&](CallInst *CI) {
1981 SmallVector<Type *, 3> types;
1982 SmallVector<Value *, 3> args;
1983 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
1984 types.push_back(CI->getArgOperand(i)->getType());
1985 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05001986 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05001987
SJW2c317da2020-03-23 07:39:13 -05001988 auto NewFType = FunctionType::get(
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001989 FixedVectorType::get(Type::getFloatTy(M.getContext()),
1990 cast<VectorType>(CI->getType())->getNumElements()),
SJW2c317da2020-03-23 07:39:13 -05001991 types, false);
1992
SJW61531372020-06-09 07:31:08 -05001993 std::string NewFName =
1994 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05001995
1996 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1997
1998 auto NewCI = CallInst::Create(NewF, args, "", CI);
1999
2000 // Convert to the half type.
2001 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2002 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002003}
2004
SJW2c317da2020-03-23 07:39:13 -05002005bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2006 // convert half to float
2007 Module &M = *F.getParent();
2008 return replaceCallsWithValue(F, [&](CallInst *CI) {
2009 SmallVector<Type *, 3> types(3);
2010 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002011
SJW2c317da2020-03-23 07:39:13 -05002012 // Image
2013 types[0] = CI->getArgOperand(0)->getType();
2014 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002015
SJW2c317da2020-03-23 07:39:13 -05002016 // Coord
2017 types[1] = CI->getArgOperand(1)->getType();
2018 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002019
SJW2c317da2020-03-23 07:39:13 -05002020 // Data
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002021 types[2] = FixedVectorType::get(
SJW2c317da2020-03-23 07:39:13 -05002022 Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04002023 cast<VectorType>(CI->getArgOperand(2)->getType())->getNumElements());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002024
SJW2c317da2020-03-23 07:39:13 -05002025 auto NewFType =
2026 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002027
SJW61531372020-06-09 07:31:08 -05002028 std::string NewFName =
2029 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002030
SJW2c317da2020-03-23 07:39:13 -05002031 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002032
SJW2c317da2020-03-23 07:39:13 -05002033 // Convert data to the float type.
2034 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2035 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002036
SJW2c317da2020-03-23 07:39:13 -05002037 return CallInst::Create(NewF, args, "", CI);
2038 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002039}
2040
SJW2c317da2020-03-23 07:39:13 -05002041bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2042 Function &F) {
2043 // convert read_image with int coords to float coords
2044 Module &M = *F.getParent();
2045 return replaceCallsWithValue(F, [&](CallInst *CI) {
2046 // The image.
2047 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002048
SJW2c317da2020-03-23 07:39:13 -05002049 // The sampler.
2050 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002051
SJW2c317da2020-03-23 07:39:13 -05002052 // The coordinate (integer type that we can't handle).
2053 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002054
SJW2c317da2020-03-23 07:39:13 -05002055 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2056 uint32_t components =
2057 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2058 Type *float_ty = nullptr;
2059 if (components == 1) {
2060 float_ty = Type::getFloatTy(M.getContext());
2061 } else {
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002062 float_ty = FixedVectorType::get(
2063 Type::getFloatTy(M.getContext()),
2064 cast<VectorType>(Arg2->getType())->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002065 }
David Neto22f144c2017-06-12 14:26:21 -04002066
SJW2c317da2020-03-23 07:39:13 -05002067 auto NewFType = FunctionType::get(
2068 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2069
2070 std::string NewFName = F.getName().str();
2071 NewFName[NewFName.length() - 1] = 'f';
2072
2073 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2074
2075 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2076
2077 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2078 });
David Neto22f144c2017-06-12 14:26:21 -04002079}
2080
SJW2c317da2020-03-23 07:39:13 -05002081bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2082 return replaceCallsWithValue(F, [&](CallInst *CI) {
2083 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002084
SJW2c317da2020-03-23 07:39:13 -05002085 // We need to map the OpenCL constants to the SPIR-V equivalents.
2086 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2087 const auto ConstantMemorySemantics = ConstantInt::get(
2088 IntTy, spv::MemorySemanticsUniformMemoryMask |
2089 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002090
SJW2c317da2020-03-23 07:39:13 -05002091 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002092
SJW2c317da2020-03-23 07:39:13 -05002093 // The pointer.
2094 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002095
SJW2c317da2020-03-23 07:39:13 -05002096 // The memory scope.
2097 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002098
SJW2c317da2020-03-23 07:39:13 -05002099 // The memory semantics.
2100 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002101
SJW2c317da2020-03-23 07:39:13 -05002102 if (2 < CI->getNumArgOperands()) {
2103 // The unequal memory semantics.
2104 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002105
SJW2c317da2020-03-23 07:39:13 -05002106 // The value.
2107 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002108
SJW2c317da2020-03-23 07:39:13 -05002109 // The comparator.
2110 Params.push_back(CI->getArgOperand(1));
2111 } else if (1 < CI->getNumArgOperands()) {
2112 // The value.
2113 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002114 }
David Neto22f144c2017-06-12 14:26:21 -04002115
SJW2c317da2020-03-23 07:39:13 -05002116 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2117 });
David Neto22f144c2017-06-12 14:26:21 -04002118}
2119
SJW2c317da2020-03-23 07:39:13 -05002120bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2121 llvm::AtomicRMWInst::BinOp Op) {
2122 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002123 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2124 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002125 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002126 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002127 SyncScope::System, CI);
2128 });
2129}
David Neto22f144c2017-06-12 14:26:21 -04002130
SJW2c317da2020-03-23 07:39:13 -05002131bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2132 Module &M = *F.getParent();
2133 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002134 auto IntTy = Type::getInt32Ty(M.getContext());
2135 auto FloatTy = Type::getFloatTy(M.getContext());
2136
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002137 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2138 ConstantInt::get(IntTy, 1),
2139 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002140
2141 Constant *UpShuffleMask[4] = {
2142 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2143 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2144
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002145 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2146 UndefValue::get(FloatTy),
2147 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002148
Kévin Petite8edce32019-04-10 14:23:32 +01002149 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002150 auto Arg0 =
2151 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2152 ConstantVector::get(DownShuffleMask), "", CI);
2153 auto Arg1 =
2154 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2155 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002156 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002157
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002158 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002159 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002160
SJW61531372020-06-09 07:31:08 -05002161 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002162
Kévin Petite8edce32019-04-10 14:23:32 +01002163 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002164
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002165 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2166 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002167 });
David Neto22f144c2017-06-12 14:26:21 -04002168}
David Neto62653202017-10-16 19:05:18 -04002169
SJW2c317da2020-03-23 07:39:13 -05002170bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002171 // OpenCL's float result = fract(float x, float* ptr)
2172 //
2173 // In the LLVM domain:
2174 //
2175 // %floor_result = call spir_func float @floor(float %x)
2176 // store float %floor_result, float * %ptr
2177 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2178 // %result = call spir_func float
2179 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2180 //
2181 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2182 // and clspv.fract occur in the SPIR-V generator pass:
2183 //
2184 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2185 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2186 // ...
2187 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2188 // OpStore %ptr %floor_result
2189 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2190 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002191 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002192
David Neto62653202017-10-16 19:05:18 -04002193 using std::string;
2194
2195 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2196 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002197
SJW2c317da2020-03-23 07:39:13 -05002198 Module &M = *F.getParent();
2199 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002200
SJW2c317da2020-03-23 07:39:13 -05002201 // This is either float or a float vector. All the float-like
2202 // types are this type.
2203 auto result_ty = F.getReturnType();
2204
SJW61531372020-06-09 07:31:08 -05002205 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002206 Function *fmin_fn = M.getFunction(fmin_name);
2207 if (!fmin_fn) {
2208 // Make the fmin function.
2209 FunctionType *fn_ty =
2210 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2211 fmin_fn =
2212 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2213 fmin_fn->addFnAttr(Attribute::ReadNone);
2214 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2215 }
2216
SJW61531372020-06-09 07:31:08 -05002217 std::string floor_name =
2218 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002219 Function *floor_fn = M.getFunction(floor_name);
2220 if (!floor_fn) {
2221 // Make the floor function.
2222 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2223 floor_fn =
2224 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2225 floor_fn->addFnAttr(Attribute::ReadNone);
2226 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2227 }
2228
SJW61531372020-06-09 07:31:08 -05002229 std::string clspv_fract_name =
2230 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002231 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2232 if (!clspv_fract_fn) {
2233 // Make the clspv_fract function.
2234 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2235 clspv_fract_fn = cast<Function>(
2236 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2237 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2238 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2239 }
2240
2241 // Number of significant significand bits, whether represented or not.
2242 unsigned num_significand_bits;
2243 switch (result_ty->getScalarType()->getTypeID()) {
2244 case Type::HalfTyID:
2245 num_significand_bits = 11;
2246 break;
2247 case Type::FloatTyID:
2248 num_significand_bits = 24;
2249 break;
2250 case Type::DoubleTyID:
2251 num_significand_bits = 53;
2252 break;
2253 default:
2254 llvm_unreachable("Unhandled float type when processing fract builtin");
2255 break;
2256 }
2257 // Beware that the disassembler displays this value as
2258 // OpConstant %float 1
2259 // which is not quite right.
2260 const double kJustUnderOneScalar =
2261 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2262
2263 Constant *just_under_one =
2264 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2265 if (result_ty->isVectorTy()) {
2266 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002267 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002268 }
2269
2270 IRBuilder<> Builder(CI);
2271
2272 auto arg = CI->getArgOperand(0);
2273 auto ptr = CI->getArgOperand(1);
2274
2275 // Compute floor result and store it.
2276 auto floor = Builder.CreateCall(floor_fn, {arg});
2277 Builder.CreateStore(floor, ptr);
2278
2279 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2280 auto fract_result =
2281 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2282
2283 return fract_result;
2284 });
David Neto62653202017-10-16 19:05:18 -04002285}