blob: 689d0b5bd5cb3769839f4e7ac059c9120a3e41ac [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
David Neto22f144c2017-06-12 14:26:21 -040019#include <llvm/IR/Constants.h>
20#include <llvm/IR/Instructions.h>
David Neto62653202017-10-16 19:05:18 -040021#include <llvm/IR/IRBuilder.h>
David Neto22f144c2017-06-12 14:26:21 -040022#include <llvm/IR/Module.h>
23#include <llvm/Pass.h>
David Neto17852de2017-05-29 17:29:31 -040024#include <llvm/Support/CommandLine.h>
David Neto22f144c2017-06-12 14:26:21 -040025#include <llvm/Support/raw_ostream.h>
26#include <llvm/Transforms/Utils/Cloning.h>
27
28#include <spirv/1.0/spirv.hpp>
29
David Neto482550a2018-03-24 05:21:07 -070030#include "clspv/Option.h"
31
David Neto22f144c2017-06-12 14:26:21 -040032using namespace llvm;
33
34#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
35
36namespace {
37uint32_t clz(uint32_t v) {
38 uint32_t r;
39 uint32_t shift;
40
41 r = (v > 0xFFFF) << 4;
42 v >>= r;
43 shift = (v > 0xFF) << 3;
44 v >>= shift;
45 r |= shift;
46 shift = (v > 0xF) << 2;
47 v >>= shift;
48 r |= shift;
49 shift = (v > 0x3) << 1;
50 v >>= shift;
51 r |= shift;
52 r |= (v >> 1);
53
54 return r;
55}
56
57Type *getBoolOrBoolVectorTy(LLVMContext &C, unsigned elements) {
58 if (1 == elements) {
59 return Type::getInt1Ty(C);
60 } else {
61 return VectorType::get(Type::getInt1Ty(C), elements);
62 }
63}
64
65struct ReplaceOpenCLBuiltinPass final : public ModulePass {
66 static char ID;
67 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
68
69 bool runOnModule(Module &M) override;
70 bool replaceRecip(Module &M);
71 bool replaceDivide(Module &M);
72 bool replaceExp10(Module &M);
73 bool replaceLog10(Module &M);
74 bool replaceBarrier(Module &M);
75 bool replaceMemFence(Module &M);
76 bool replaceRelational(Module &M);
77 bool replaceIsInfAndIsNan(Module &M);
78 bool replaceAllAndAny(Module &M);
79 bool replaceSignbit(Module &M);
80 bool replaceMadandMad24andMul24(Module &M);
81 bool replaceVloadHalf(Module &M);
82 bool replaceVloadHalf2(Module &M);
83 bool replaceVloadHalf4(Module &M);
David Neto6ad93232018-06-07 15:42:58 -070084 bool replaceClspvVloadaHalf2(Module &M);
85 bool replaceClspvVloadaHalf4(Module &M);
David Neto22f144c2017-06-12 14:26:21 -040086 bool replaceVstoreHalf(Module &M);
87 bool replaceVstoreHalf2(Module &M);
88 bool replaceVstoreHalf4(Module &M);
89 bool replaceReadImageF(Module &M);
90 bool replaceAtomics(Module &M);
91 bool replaceCross(Module &M);
David Neto62653202017-10-16 19:05:18 -040092 bool replaceFract(Module &M);
Derek Chowcfd368b2017-10-19 20:58:45 -070093 bool replaceVload(Module &M);
94 bool replaceVstore(Module &M);
David Neto22f144c2017-06-12 14:26:21 -040095};
96}
97
98char ReplaceOpenCLBuiltinPass::ID = 0;
99static RegisterPass<ReplaceOpenCLBuiltinPass> X("ReplaceOpenCLBuiltin",
100 "Replace OpenCL Builtins Pass");
101
102namespace clspv {
103ModulePass *createReplaceOpenCLBuiltinPass() {
104 return new ReplaceOpenCLBuiltinPass();
105}
106}
107
108bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
109 bool Changed = false;
110
111 Changed |= replaceRecip(M);
112 Changed |= replaceDivide(M);
113 Changed |= replaceExp10(M);
114 Changed |= replaceLog10(M);
115 Changed |= replaceBarrier(M);
116 Changed |= replaceMemFence(M);
117 Changed |= replaceRelational(M);
118 Changed |= replaceIsInfAndIsNan(M);
119 Changed |= replaceAllAndAny(M);
120 Changed |= replaceSignbit(M);
121 Changed |= replaceMadandMad24andMul24(M);
122 Changed |= replaceVloadHalf(M);
123 Changed |= replaceVloadHalf2(M);
124 Changed |= replaceVloadHalf4(M);
David Neto6ad93232018-06-07 15:42:58 -0700125 Changed |= replaceClspvVloadaHalf2(M);
126 Changed |= replaceClspvVloadaHalf4(M);
David Neto22f144c2017-06-12 14:26:21 -0400127 Changed |= replaceVstoreHalf(M);
128 Changed |= replaceVstoreHalf2(M);
129 Changed |= replaceVstoreHalf4(M);
130 Changed |= replaceReadImageF(M);
131 Changed |= replaceAtomics(M);
132 Changed |= replaceCross(M);
David Neto62653202017-10-16 19:05:18 -0400133 Changed |= replaceFract(M);
Derek Chowcfd368b2017-10-19 20:58:45 -0700134 Changed |= replaceVload(M);
135 Changed |= replaceVstore(M);
David Neto22f144c2017-06-12 14:26:21 -0400136
137 return Changed;
138}
139
140bool ReplaceOpenCLBuiltinPass::replaceRecip(Module &M) {
141 bool Changed = false;
142
143 const char *Names[] = {
144 "_Z10half_recipf", "_Z12native_recipf", "_Z10half_recipDv2_f",
145 "_Z12native_recipDv2_f", "_Z10half_recipDv3_f", "_Z12native_recipDv3_f",
146 "_Z10half_recipDv4_f", "_Z12native_recipDv4_f",
147 };
148
149 for (auto Name : Names) {
150 // If we find a function with the matching name.
151 if (auto F = M.getFunction(Name)) {
152 SmallVector<Instruction *, 4> ToRemoves;
153
154 // Walk the users of the function.
155 for (auto &U : F->uses()) {
156 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
157 // Recip has one arg.
158 auto Arg = CI->getOperand(0);
159
160 auto Div = BinaryOperator::Create(
161 Instruction::FDiv, ConstantFP::get(Arg->getType(), 1.0), Arg, "",
162 CI);
163
164 CI->replaceAllUsesWith(Div);
165
166 // Lastly, remember to remove the user.
167 ToRemoves.push_back(CI);
168 }
169 }
170
171 Changed = !ToRemoves.empty();
172
173 // And cleanup the calls we don't use anymore.
174 for (auto V : ToRemoves) {
175 V->eraseFromParent();
176 }
177
178 // And remove the function we don't need either too.
179 F->eraseFromParent();
180 }
181 }
182
183 return Changed;
184}
185
186bool ReplaceOpenCLBuiltinPass::replaceDivide(Module &M) {
187 bool Changed = false;
188
189 const char *Names[] = {
190 "_Z11half_divideff", "_Z13native_divideff",
191 "_Z11half_divideDv2_fS_", "_Z13native_divideDv2_fS_",
192 "_Z11half_divideDv3_fS_", "_Z13native_divideDv3_fS_",
193 "_Z11half_divideDv4_fS_", "_Z13native_divideDv4_fS_",
194 };
195
196 for (auto Name : Names) {
197 // If we find a function with the matching name.
198 if (auto F = M.getFunction(Name)) {
199 SmallVector<Instruction *, 4> ToRemoves;
200
201 // Walk the users of the function.
202 for (auto &U : F->uses()) {
203 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
204 auto Div = BinaryOperator::Create(
205 Instruction::FDiv, CI->getOperand(0), CI->getOperand(1), "", CI);
206
207 CI->replaceAllUsesWith(Div);
208
209 // Lastly, remember to remove the user.
210 ToRemoves.push_back(CI);
211 }
212 }
213
214 Changed = !ToRemoves.empty();
215
216 // And cleanup the calls we don't use anymore.
217 for (auto V : ToRemoves) {
218 V->eraseFromParent();
219 }
220
221 // And remove the function we don't need either too.
222 F->eraseFromParent();
223 }
224 }
225
226 return Changed;
227}
228
229bool ReplaceOpenCLBuiltinPass::replaceExp10(Module &M) {
230 bool Changed = false;
231
232 const std::map<const char *, const char *> Map = {
233 {"_Z5exp10f", "_Z3expf"},
234 {"_Z10half_exp10f", "_Z8half_expf"},
235 {"_Z12native_exp10f", "_Z10native_expf"},
236 {"_Z5exp10Dv2_f", "_Z3expDv2_f"},
237 {"_Z10half_exp10Dv2_f", "_Z8half_expDv2_f"},
238 {"_Z12native_exp10Dv2_f", "_Z10native_expDv2_f"},
239 {"_Z5exp10Dv3_f", "_Z3expDv3_f"},
240 {"_Z10half_exp10Dv3_f", "_Z8half_expDv3_f"},
241 {"_Z12native_exp10Dv3_f", "_Z10native_expDv3_f"},
242 {"_Z5exp10Dv4_f", "_Z3expDv4_f"},
243 {"_Z10half_exp10Dv4_f", "_Z8half_expDv4_f"},
244 {"_Z12native_exp10Dv4_f", "_Z10native_expDv4_f"}};
245
246 for (auto Pair : Map) {
247 // If we find a function with the matching name.
248 if (auto F = M.getFunction(Pair.first)) {
249 SmallVector<Instruction *, 4> ToRemoves;
250
251 // Walk the users of the function.
252 for (auto &U : F->uses()) {
253 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
254 auto NewF = M.getOrInsertFunction(Pair.second, F->getFunctionType());
255
256 auto Arg = CI->getOperand(0);
257
258 // Constant of the natural log of 10 (ln(10)).
259 const double Ln10 =
260 2.302585092994045684017991454684364207601101488628772976033;
261
262 auto Mul = BinaryOperator::Create(
263 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "",
264 CI);
265
266 auto NewCI = CallInst::Create(NewF, Mul, "", CI);
267
268 CI->replaceAllUsesWith(NewCI);
269
270 // Lastly, remember to remove the user.
271 ToRemoves.push_back(CI);
272 }
273 }
274
275 Changed = !ToRemoves.empty();
276
277 // And cleanup the calls we don't use anymore.
278 for (auto V : ToRemoves) {
279 V->eraseFromParent();
280 }
281
282 // And remove the function we don't need either too.
283 F->eraseFromParent();
284 }
285 }
286
287 return Changed;
288}
289
290bool ReplaceOpenCLBuiltinPass::replaceLog10(Module &M) {
291 bool Changed = false;
292
293 const std::map<const char *, const char *> Map = {
294 {"_Z5log10f", "_Z3logf"},
295 {"_Z10half_log10f", "_Z8half_logf"},
296 {"_Z12native_log10f", "_Z10native_logf"},
297 {"_Z5log10Dv2_f", "_Z3logDv2_f"},
298 {"_Z10half_log10Dv2_f", "_Z8half_logDv2_f"},
299 {"_Z12native_log10Dv2_f", "_Z10native_logDv2_f"},
300 {"_Z5log10Dv3_f", "_Z3logDv3_f"},
301 {"_Z10half_log10Dv3_f", "_Z8half_logDv3_f"},
302 {"_Z12native_log10Dv3_f", "_Z10native_logDv3_f"},
303 {"_Z5log10Dv4_f", "_Z3logDv4_f"},
304 {"_Z10half_log10Dv4_f", "_Z8half_logDv4_f"},
305 {"_Z12native_log10Dv4_f", "_Z10native_logDv4_f"}};
306
307 for (auto Pair : Map) {
308 // If we find a function with the matching name.
309 if (auto F = M.getFunction(Pair.first)) {
310 SmallVector<Instruction *, 4> ToRemoves;
311
312 // Walk the users of the function.
313 for (auto &U : F->uses()) {
314 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
315 auto NewF = M.getOrInsertFunction(Pair.second, F->getFunctionType());
316
317 auto Arg = CI->getOperand(0);
318
319 // Constant of the reciprocal of the natural log of 10 (ln(10)).
320 const double Ln10 =
321 0.434294481903251827651128918916605082294397005803666566114;
322
323 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
324
325 auto Mul = BinaryOperator::Create(
326 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), NewCI,
327 "", CI);
328
329 CI->replaceAllUsesWith(Mul);
330
331 // Lastly, remember to remove the user.
332 ToRemoves.push_back(CI);
333 }
334 }
335
336 Changed = !ToRemoves.empty();
337
338 // And cleanup the calls we don't use anymore.
339 for (auto V : ToRemoves) {
340 V->eraseFromParent();
341 }
342
343 // And remove the function we don't need either too.
344 F->eraseFromParent();
345 }
346 }
347
348 return Changed;
349}
350
351bool ReplaceOpenCLBuiltinPass::replaceBarrier(Module &M) {
352 bool Changed = false;
353
354 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
355
356 const std::map<const char *, const char *> Map = {
357 {"_Z7barrierj", "__spirv_control_barrier"}};
358
359 for (auto Pair : Map) {
360 // If we find a function with the matching name.
361 if (auto F = M.getFunction(Pair.first)) {
362 SmallVector<Instruction *, 4> ToRemoves;
363
364 // Walk the users of the function.
365 for (auto &U : F->uses()) {
366 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
367 auto FType = F->getFunctionType();
368 SmallVector<Type *, 3> Params;
369 for (unsigned i = 0; i < 3; i++) {
370 Params.push_back(FType->getParamType(0));
371 }
372 auto NewFType =
373 FunctionType::get(FType->getReturnType(), Params, false);
374 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
375
376 auto Arg = CI->getOperand(0);
377
378 // We need to map the OpenCL constants to the SPIR-V equivalents.
379 const auto LocalMemFence =
380 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
381 const auto GlobalMemFence =
382 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
383 const auto ConstantSequentiallyConsistent = ConstantInt::get(
384 Arg->getType(), spv::MemorySemanticsSequentiallyConsistentMask);
385 const auto ConstantScopeDevice =
386 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
387 const auto ConstantScopeWorkgroup =
388 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
389
390 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
391 const auto LocalMemFenceMask = BinaryOperator::Create(
392 Instruction::And, LocalMemFence, Arg, "", CI);
393 const auto WorkgroupShiftAmount =
394 clz(spv::MemorySemanticsWorkgroupMemoryMask) -
395 clz(CLK_LOCAL_MEM_FENCE);
396 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
397 Instruction::Shl, LocalMemFenceMask,
398 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
399
400 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
401 const auto GlobalMemFenceMask = BinaryOperator::Create(
402 Instruction::And, GlobalMemFence, Arg, "", CI);
403 const auto UniformShiftAmount =
404 clz(spv::MemorySemanticsUniformMemoryMask) -
405 clz(CLK_GLOBAL_MEM_FENCE);
406 const auto MemorySemanticsUniform = BinaryOperator::Create(
407 Instruction::Shl, GlobalMemFenceMask,
408 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
409
410 // And combine the above together, also adding in
411 // MemorySemanticsSequentiallyConsistentMask.
412 auto MemorySemantics =
413 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
414 ConstantSequentiallyConsistent, "", CI);
415 MemorySemantics = BinaryOperator::Create(
416 Instruction::Or, MemorySemantics, MemorySemanticsUniform, "", CI);
417
418 // For Memory Scope if we used CLK_GLOBAL_MEM_FENCE, we need to use
419 // Device Scope, otherwise Workgroup Scope.
420 const auto Cmp =
421 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
422 GlobalMemFenceMask, GlobalMemFence, "", CI);
423 const auto MemoryScope = SelectInst::Create(
424 Cmp, ConstantScopeDevice, ConstantScopeWorkgroup, "", CI);
425
426 // Lastly, the Execution Scope is always Workgroup Scope.
427 const auto ExecutionScope = ConstantScopeWorkgroup;
428
429 auto NewCI = CallInst::Create(
430 NewF, {ExecutionScope, MemoryScope, MemorySemantics}, "", CI);
431
432 CI->replaceAllUsesWith(NewCI);
433
434 // Lastly, remember to remove the user.
435 ToRemoves.push_back(CI);
436 }
437 }
438
439 Changed = !ToRemoves.empty();
440
441 // And cleanup the calls we don't use anymore.
442 for (auto V : ToRemoves) {
443 V->eraseFromParent();
444 }
445
446 // And remove the function we don't need either too.
447 F->eraseFromParent();
448 }
449 }
450
451 return Changed;
452}
453
454bool ReplaceOpenCLBuiltinPass::replaceMemFence(Module &M) {
455 bool Changed = false;
456
457 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
458
Neil Henning39672102017-09-29 14:33:13 +0100459 using Tuple = std::tuple<const char *, unsigned>;
460 const std::map<const char *, Tuple> Map = {
461 {"_Z9mem_fencej",
462 Tuple("__spirv_memory_barrier",
463 spv::MemorySemanticsSequentiallyConsistentMask)},
464 {"_Z14read_mem_fencej",
465 Tuple("__spirv_memory_barrier", spv::MemorySemanticsAcquireMask)},
466 {"_Z15write_mem_fencej",
467 Tuple("__spirv_memory_barrier", spv::MemorySemanticsReleaseMask)}};
David Neto22f144c2017-06-12 14:26:21 -0400468
469 for (auto Pair : Map) {
470 // If we find a function with the matching name.
471 if (auto F = M.getFunction(Pair.first)) {
472 SmallVector<Instruction *, 4> ToRemoves;
473
474 // Walk the users of the function.
475 for (auto &U : F->uses()) {
476 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
477 auto FType = F->getFunctionType();
478 SmallVector<Type *, 2> Params;
479 for (unsigned i = 0; i < 2; i++) {
480 Params.push_back(FType->getParamType(0));
481 }
482 auto NewFType =
483 FunctionType::get(FType->getReturnType(), Params, false);
Neil Henning39672102017-09-29 14:33:13 +0100484 auto NewF = M.getOrInsertFunction(std::get<0>(Pair.second), NewFType);
David Neto22f144c2017-06-12 14:26:21 -0400485
486 auto Arg = CI->getOperand(0);
487
488 // We need to map the OpenCL constants to the SPIR-V equivalents.
489 const auto LocalMemFence =
490 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
491 const auto GlobalMemFence =
492 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
493 const auto ConstantMemorySemantics =
Neil Henning39672102017-09-29 14:33:13 +0100494 ConstantInt::get(Arg->getType(), std::get<1>(Pair.second));
David Neto22f144c2017-06-12 14:26:21 -0400495 const auto ConstantScopeDevice =
496 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
497
498 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
499 const auto LocalMemFenceMask = BinaryOperator::Create(
500 Instruction::And, LocalMemFence, Arg, "", CI);
501 const auto WorkgroupShiftAmount =
502 clz(spv::MemorySemanticsWorkgroupMemoryMask) -
503 clz(CLK_LOCAL_MEM_FENCE);
504 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
505 Instruction::Shl, LocalMemFenceMask,
506 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
507
508 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
509 const auto GlobalMemFenceMask = BinaryOperator::Create(
510 Instruction::And, GlobalMemFence, Arg, "", CI);
511 const auto UniformShiftAmount =
512 clz(spv::MemorySemanticsUniformMemoryMask) -
513 clz(CLK_GLOBAL_MEM_FENCE);
514 const auto MemorySemanticsUniform = BinaryOperator::Create(
515 Instruction::Shl, GlobalMemFenceMask,
516 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
517
518 // And combine the above together, also adding in
519 // MemorySemanticsSequentiallyConsistentMask.
520 auto MemorySemantics =
521 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
522 ConstantMemorySemantics, "", CI);
523 MemorySemantics = BinaryOperator::Create(
524 Instruction::Or, MemorySemantics, MemorySemanticsUniform, "", CI);
525
526 // Memory Scope is always device.
527 const auto MemoryScope = ConstantScopeDevice;
528
529 auto NewCI =
530 CallInst::Create(NewF, {MemoryScope, MemorySemantics}, "", CI);
531
532 CI->replaceAllUsesWith(NewCI);
533
534 // Lastly, remember to remove the user.
535 ToRemoves.push_back(CI);
536 }
537 }
538
539 Changed = !ToRemoves.empty();
540
541 // And cleanup the calls we don't use anymore.
542 for (auto V : ToRemoves) {
543 V->eraseFromParent();
544 }
545
546 // And remove the function we don't need either too.
547 F->eraseFromParent();
548 }
549 }
550
551 return Changed;
552}
553
554bool ReplaceOpenCLBuiltinPass::replaceRelational(Module &M) {
555 bool Changed = false;
556
557 const std::map<const char *, std::pair<CmpInst::Predicate, int32_t>> Map = {
558 {"_Z7isequalff", {CmpInst::FCMP_OEQ, 1}},
559 {"_Z7isequalDv2_fS_", {CmpInst::FCMP_OEQ, -1}},
560 {"_Z7isequalDv3_fS_", {CmpInst::FCMP_OEQ, -1}},
561 {"_Z7isequalDv4_fS_", {CmpInst::FCMP_OEQ, -1}},
562 {"_Z9isgreaterff", {CmpInst::FCMP_OGT, 1}},
563 {"_Z9isgreaterDv2_fS_", {CmpInst::FCMP_OGT, -1}},
564 {"_Z9isgreaterDv3_fS_", {CmpInst::FCMP_OGT, -1}},
565 {"_Z9isgreaterDv4_fS_", {CmpInst::FCMP_OGT, -1}},
566 {"_Z14isgreaterequalff", {CmpInst::FCMP_OGE, 1}},
567 {"_Z14isgreaterequalDv2_fS_", {CmpInst::FCMP_OGE, -1}},
568 {"_Z14isgreaterequalDv3_fS_", {CmpInst::FCMP_OGE, -1}},
569 {"_Z14isgreaterequalDv4_fS_", {CmpInst::FCMP_OGE, -1}},
570 {"_Z6islessff", {CmpInst::FCMP_OLT, 1}},
571 {"_Z6islessDv2_fS_", {CmpInst::FCMP_OLT, -1}},
572 {"_Z6islessDv3_fS_", {CmpInst::FCMP_OLT, -1}},
573 {"_Z6islessDv4_fS_", {CmpInst::FCMP_OLT, -1}},
574 {"_Z11islessequalff", {CmpInst::FCMP_OLE, 1}},
575 {"_Z11islessequalDv2_fS_", {CmpInst::FCMP_OLE, -1}},
576 {"_Z11islessequalDv3_fS_", {CmpInst::FCMP_OLE, -1}},
577 {"_Z11islessequalDv4_fS_", {CmpInst::FCMP_OLE, -1}},
578 {"_Z10isnotequalff", {CmpInst::FCMP_ONE, 1}},
579 {"_Z10isnotequalDv2_fS_", {CmpInst::FCMP_ONE, -1}},
580 {"_Z10isnotequalDv3_fS_", {CmpInst::FCMP_ONE, -1}},
581 {"_Z10isnotequalDv4_fS_", {CmpInst::FCMP_ONE, -1}},
582 };
583
584 for (auto Pair : Map) {
585 // If we find a function with the matching name.
586 if (auto F = M.getFunction(Pair.first)) {
587 SmallVector<Instruction *, 4> ToRemoves;
588
589 // Walk the users of the function.
590 for (auto &U : F->uses()) {
591 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
592 // The predicate to use in the CmpInst.
593 auto Predicate = Pair.second.first;
594
595 // The value to return for true.
596 auto TrueValue =
597 ConstantInt::getSigned(CI->getType(), Pair.second.second);
598
599 // The value to return for false.
600 auto FalseValue = Constant::getNullValue(CI->getType());
601
602 auto Arg1 = CI->getOperand(0);
603 auto Arg2 = CI->getOperand(1);
604
605 const auto Cmp =
606 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
607
608 const auto Select =
609 SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
610
611 CI->replaceAllUsesWith(Select);
612
613 // Lastly, remember to remove the user.
614 ToRemoves.push_back(CI);
615 }
616 }
617
618 Changed = !ToRemoves.empty();
619
620 // And cleanup the calls we don't use anymore.
621 for (auto V : ToRemoves) {
622 V->eraseFromParent();
623 }
624
625 // And remove the function we don't need either too.
626 F->eraseFromParent();
627 }
628 }
629
630 return Changed;
631}
632
633bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Module &M) {
634 bool Changed = false;
635
636 const std::map<const char *, std::pair<const char *, int32_t>> Map = {
637 {"_Z5isinff", {"__spirv_isinff", 1}},
638 {"_Z5isinfDv2_f", {"__spirv_isinfDv2_f", -1}},
639 {"_Z5isinfDv3_f", {"__spirv_isinfDv3_f", -1}},
640 {"_Z5isinfDv4_f", {"__spirv_isinfDv4_f", -1}},
641 {"_Z5isnanf", {"__spirv_isnanf", 1}},
642 {"_Z5isnanDv2_f", {"__spirv_isnanDv2_f", -1}},
643 {"_Z5isnanDv3_f", {"__spirv_isnanDv3_f", -1}},
644 {"_Z5isnanDv4_f", {"__spirv_isnanDv4_f", -1}},
645 };
646
647 for (auto Pair : Map) {
648 // If we find a function with the matching name.
649 if (auto F = M.getFunction(Pair.first)) {
650 SmallVector<Instruction *, 4> ToRemoves;
651
652 // Walk the users of the function.
653 for (auto &U : F->uses()) {
654 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
655 const auto CITy = CI->getType();
656
657 // The fake SPIR-V intrinsic to generate.
658 auto SPIRVIntrinsic = Pair.second.first;
659
660 // The value to return for true.
661 auto TrueValue = ConstantInt::getSigned(CITy, Pair.second.second);
662
663 // The value to return for false.
664 auto FalseValue = Constant::getNullValue(CITy);
665
666 const auto CorrespondingBoolTy = getBoolOrBoolVectorTy(
667 M.getContext(),
668 CITy->isVectorTy() ? CITy->getVectorNumElements() : 1);
669
670 auto NewFType =
671 FunctionType::get(CorrespondingBoolTy,
672 F->getFunctionType()->getParamType(0), false);
673
674 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
675
676 auto Arg = CI->getOperand(0);
677
678 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
679
680 const auto Select =
681 SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
682
683 CI->replaceAllUsesWith(Select);
684
685 // Lastly, remember to remove the user.
686 ToRemoves.push_back(CI);
687 }
688 }
689
690 Changed = !ToRemoves.empty();
691
692 // And cleanup the calls we don't use anymore.
693 for (auto V : ToRemoves) {
694 V->eraseFromParent();
695 }
696
697 // And remove the function we don't need either too.
698 F->eraseFromParent();
699 }
700 }
701
702 return Changed;
703}
704
705bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Module &M) {
706 bool Changed = false;
707
708 const std::map<const char *, const char *> Map = {
709 {"_Z3alli", ""},
710 {"_Z3allDv2_i", "__spirv_allDv2_i"},
711 {"_Z3allDv3_i", "__spirv_allDv3_i"},
712 {"_Z3allDv4_i", "__spirv_allDv4_i"},
713 {"_Z3anyi", ""},
714 {"_Z3anyDv2_i", "__spirv_anyDv2_i"},
715 {"_Z3anyDv3_i", "__spirv_anyDv3_i"},
716 {"_Z3anyDv4_i", "__spirv_anyDv4_i"},
717 };
718
719 for (auto Pair : Map) {
720 // If we find a function with the matching name.
721 if (auto F = M.getFunction(Pair.first)) {
722 SmallVector<Instruction *, 4> ToRemoves;
723
724 // Walk the users of the function.
725 for (auto &U : F->uses()) {
726 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
727 // The fake SPIR-V intrinsic to generate.
728 auto SPIRVIntrinsic = Pair.second;
729
730 auto Arg = CI->getOperand(0);
731
732 Value *V;
733
734 // If we have a function to call, call it!
735 if (0 < strlen(SPIRVIntrinsic)) {
736 // The value for zero to compare against.
737 const auto ZeroValue = Constant::getNullValue(Arg->getType());
738
739 const auto Cmp = CmpInst::Create(
740 Instruction::ICmp, CmpInst::ICMP_SLT, Arg, ZeroValue, "", CI);
741 const auto NewFType = FunctionType::get(
742 Type::getInt1Ty(M.getContext()), Cmp->getType(), false);
743
744 const auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
745
746 const auto NewCI = CallInst::Create(NewF, Cmp, "", CI);
747
748 // The value to return for true.
749 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
750
751 // The value to return for false.
752 const auto FalseValue = Constant::getNullValue(CI->getType());
753
754 V = SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
755 } else {
756 V = BinaryOperator::Create(Instruction::LShr, Arg,
757 ConstantInt::get(CI->getType(), 31), "",
758 CI);
759 }
760
761 CI->replaceAllUsesWith(V);
762
763 // Lastly, remember to remove the user.
764 ToRemoves.push_back(CI);
765 }
766 }
767
768 Changed = !ToRemoves.empty();
769
770 // And cleanup the calls we don't use anymore.
771 for (auto V : ToRemoves) {
772 V->eraseFromParent();
773 }
774
775 // And remove the function we don't need either too.
776 F->eraseFromParent();
777 }
778 }
779
780 return Changed;
781}
782
783bool ReplaceOpenCLBuiltinPass::replaceSignbit(Module &M) {
784 bool Changed = false;
785
786 const std::map<const char *, Instruction::BinaryOps> Map = {
787 {"_Z7signbitf", Instruction::LShr},
788 {"_Z7signbitDv2_f", Instruction::AShr},
789 {"_Z7signbitDv3_f", Instruction::AShr},
790 {"_Z7signbitDv4_f", Instruction::AShr},
791 };
792
793 for (auto Pair : Map) {
794 // If we find a function with the matching name.
795 if (auto F = M.getFunction(Pair.first)) {
796 SmallVector<Instruction *, 4> ToRemoves;
797
798 // Walk the users of the function.
799 for (auto &U : F->uses()) {
800 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
801 auto Arg = CI->getOperand(0);
802
803 auto Bitcast =
804 CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
805
806 auto Shr = BinaryOperator::Create(Pair.second, Bitcast,
807 ConstantInt::get(CI->getType(), 31),
808 "", CI);
809
810 CI->replaceAllUsesWith(Shr);
811
812 // Lastly, remember to remove the user.
813 ToRemoves.push_back(CI);
814 }
815 }
816
817 Changed = !ToRemoves.empty();
818
819 // And cleanup the calls we don't use anymore.
820 for (auto V : ToRemoves) {
821 V->eraseFromParent();
822 }
823
824 // And remove the function we don't need either too.
825 F->eraseFromParent();
826 }
827 }
828
829 return Changed;
830}
831
832bool ReplaceOpenCLBuiltinPass::replaceMadandMad24andMul24(Module &M) {
833 bool Changed = false;
834
835 const std::map<const char *,
836 std::pair<Instruction::BinaryOps, Instruction::BinaryOps>>
837 Map = {
838 {"_Z3madfff", {Instruction::FMul, Instruction::FAdd}},
839 {"_Z3madDv2_fS_S_", {Instruction::FMul, Instruction::FAdd}},
840 {"_Z3madDv3_fS_S_", {Instruction::FMul, Instruction::FAdd}},
841 {"_Z3madDv4_fS_S_", {Instruction::FMul, Instruction::FAdd}},
842 {"_Z5mad24iii", {Instruction::Mul, Instruction::Add}},
843 {"_Z5mad24Dv2_iS_S_", {Instruction::Mul, Instruction::Add}},
844 {"_Z5mad24Dv3_iS_S_", {Instruction::Mul, Instruction::Add}},
845 {"_Z5mad24Dv4_iS_S_", {Instruction::Mul, Instruction::Add}},
846 {"_Z5mad24jjj", {Instruction::Mul, Instruction::Add}},
847 {"_Z5mad24Dv2_jS_S_", {Instruction::Mul, Instruction::Add}},
848 {"_Z5mad24Dv3_jS_S_", {Instruction::Mul, Instruction::Add}},
849 {"_Z5mad24Dv4_jS_S_", {Instruction::Mul, Instruction::Add}},
850 {"_Z5mul24ii", {Instruction::Mul, Instruction::BinaryOpsEnd}},
851 {"_Z5mul24Dv2_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
852 {"_Z5mul24Dv3_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
853 {"_Z5mul24Dv4_iS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
854 {"_Z5mul24jj", {Instruction::Mul, Instruction::BinaryOpsEnd}},
855 {"_Z5mul24Dv2_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
856 {"_Z5mul24Dv3_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
857 {"_Z5mul24Dv4_jS_", {Instruction::Mul, Instruction::BinaryOpsEnd}},
858 };
859
860 for (auto Pair : Map) {
861 // If we find a function with the matching name.
862 if (auto F = M.getFunction(Pair.first)) {
863 SmallVector<Instruction *, 4> ToRemoves;
864
865 // Walk the users of the function.
866 for (auto &U : F->uses()) {
867 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
868 // The multiply instruction to use.
869 auto MulInst = Pair.second.first;
870
871 // The add instruction to use.
872 auto AddInst = Pair.second.second;
873
874 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
875
876 auto I = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
877 CI->getArgOperand(1), "", CI);
878
879 if (Instruction::BinaryOpsEnd != AddInst) {
880 I = BinaryOperator::Create(AddInst, I, CI->getArgOperand(2), "",
881 CI);
882 }
883
884 CI->replaceAllUsesWith(I);
885
886 // Lastly, remember to remove the user.
887 ToRemoves.push_back(CI);
888 }
889 }
890
891 Changed = !ToRemoves.empty();
892
893 // And cleanup the calls we don't use anymore.
894 for (auto V : ToRemoves) {
895 V->eraseFromParent();
896 }
897
898 // And remove the function we don't need either too.
899 F->eraseFromParent();
900 }
901 }
902
903 return Changed;
904}
905
Derek Chowcfd368b2017-10-19 20:58:45 -0700906bool ReplaceOpenCLBuiltinPass::replaceVstore(Module &M) {
907 bool Changed = false;
908
909 struct VectorStoreOps {
910 const char* name;
911 int n;
912 Type* (*get_scalar_type_function)(LLVMContext&);
913 } vector_store_ops[] = {
914 // TODO(derekjchow): Expand this list.
915 { "_Z7vstore4Dv4_fjPU3AS1f", 4, Type::getFloatTy }
916 };
917
David Neto544fffc2017-11-16 18:35:14 -0500918 for (const auto& Op : vector_store_ops) {
Derek Chowcfd368b2017-10-19 20:58:45 -0700919 auto Name = Op.name;
920 auto N = Op.n;
921 auto TypeFn = Op.get_scalar_type_function;
922 if (auto F = M.getFunction(Name)) {
923 SmallVector<Instruction *, 4> ToRemoves;
924
925 // Walk the users of the function.
926 for (auto &U : F->uses()) {
927 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
928 // The value argument from vstoren.
929 auto Arg0 = CI->getOperand(0);
930
931 // The index argument from vstoren.
932 auto Arg1 = CI->getOperand(1);
933
934 // The pointer argument from vstoren.
935 auto Arg2 = CI->getOperand(2);
936
937 // Get types.
938 auto ScalarNTy = VectorType::get(TypeFn(M.getContext()), N);
939 auto ScalarNPointerTy = PointerType::get(
940 ScalarNTy, Arg2->getType()->getPointerAddressSpace());
941
942 // Cast to scalarn
943 auto Cast = CastInst::CreatePointerCast(
944 Arg2, ScalarNPointerTy, "", CI);
945 // Index to correct address
946 auto Index = GetElementPtrInst::Create(ScalarNTy, Cast, Arg1, "", CI);
947 // Store
948 auto Store = new StoreInst(Arg0, Index, CI);
949
950 CI->replaceAllUsesWith(Store);
951 ToRemoves.push_back(CI);
952 }
953 }
954
955 Changed = !ToRemoves.empty();
956
957 // And cleanup the calls we don't use anymore.
958 for (auto V : ToRemoves) {
959 V->eraseFromParent();
960 }
961
962 // And remove the function we don't need either too.
963 F->eraseFromParent();
964 }
965 }
966
967 return Changed;
968}
969
970bool ReplaceOpenCLBuiltinPass::replaceVload(Module &M) {
971 bool Changed = false;
972
973 struct VectorLoadOps {
974 const char* name;
975 int n;
976 Type* (*get_scalar_type_function)(LLVMContext&);
977 } vector_load_ops[] = {
978 // TODO(derekjchow): Expand this list.
979 { "_Z6vload4jPU3AS1Kf", 4, Type::getFloatTy }
980 };
981
David Neto544fffc2017-11-16 18:35:14 -0500982 for (const auto& Op : vector_load_ops) {
Derek Chowcfd368b2017-10-19 20:58:45 -0700983 auto Name = Op.name;
984 auto N = Op.n;
985 auto TypeFn = Op.get_scalar_type_function;
986 // If we find a function with the matching name.
987 if (auto F = M.getFunction(Name)) {
988 SmallVector<Instruction *, 4> ToRemoves;
989
990 // Walk the users of the function.
991 for (auto &U : F->uses()) {
992 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
993 // The index argument from vloadn.
994 auto Arg0 = CI->getOperand(0);
995
996 // The pointer argument from vloadn.
997 auto Arg1 = CI->getOperand(1);
998
999 // Get types.
1000 auto ScalarNTy = VectorType::get(TypeFn(M.getContext()), N);
1001 auto ScalarNPointerTy = PointerType::get(
1002 ScalarNTy, Arg1->getType()->getPointerAddressSpace());
1003
1004 // Cast to scalarn
1005 auto Cast = CastInst::CreatePointerCast(
1006 Arg1, ScalarNPointerTy, "", CI);
1007 // Index to correct address
1008 auto Index = GetElementPtrInst::Create(ScalarNTy, Cast, Arg0, "", CI);
1009 // Load
1010 auto Load = new LoadInst(Index, "", CI);
1011
1012 CI->replaceAllUsesWith(Load);
1013 ToRemoves.push_back(CI);
1014 }
1015 }
1016
1017 Changed = !ToRemoves.empty();
1018
1019 // And cleanup the calls we don't use anymore.
1020 for (auto V : ToRemoves) {
1021 V->eraseFromParent();
1022 }
1023
1024 // And remove the function we don't need either too.
1025 F->eraseFromParent();
1026
1027 }
1028 }
1029
1030 return Changed;
1031}
1032
David Neto22f144c2017-06-12 14:26:21 -04001033bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Module &M) {
1034 bool Changed = false;
1035
1036 const std::vector<const char *> Map = {"_Z10vload_halfjPU3AS1KDh",
1037 "_Z10vload_halfjPU3AS2KDh"};
1038
1039 for (auto Name : Map) {
1040 // If we find a function with the matching name.
1041 if (auto F = M.getFunction(Name)) {
1042 SmallVector<Instruction *, 4> ToRemoves;
1043
1044 // Walk the users of the function.
1045 for (auto &U : F->uses()) {
1046 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1047 // The index argument from vload_half.
1048 auto Arg0 = CI->getOperand(0);
1049
1050 // The pointer argument from vload_half.
1051 auto Arg1 = CI->getOperand(1);
1052
David Neto22f144c2017-06-12 14:26:21 -04001053 auto IntTy = Type::getInt32Ty(M.getContext());
1054 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
David Neto22f144c2017-06-12 14:26:21 -04001055 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1056
David Neto22f144c2017-06-12 14:26:21 -04001057 // Our intrinsic to unpack a float2 from an int.
1058 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1059
1060 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1061
David Neto482550a2018-03-24 05:21:07 -07001062 if (clspv::Option::F16BitStorage()) {
David Netoac825b82017-05-30 12:49:01 -04001063 auto ShortTy = Type::getInt16Ty(M.getContext());
1064 auto ShortPointerTy = PointerType::get(
1065 ShortTy, Arg1->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001066
David Netoac825b82017-05-30 12:49:01 -04001067 // Cast the half* pointer to short*.
1068 auto Cast =
1069 CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001070
David Netoac825b82017-05-30 12:49:01 -04001071 // Index into the correct address of the casted pointer.
1072 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1073
1074 // Load from the short* we casted to.
1075 auto Load = new LoadInst(Index, "", CI);
1076
1077 // ZExt the short -> int.
1078 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1079
1080 // Get our float2.
1081 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1082
1083 // Extract out the bottom element which is our float result.
1084 auto Extract = ExtractElementInst::Create(
1085 Call, ConstantInt::get(IntTy, 0), "", CI);
1086
1087 CI->replaceAllUsesWith(Extract);
1088 } else {
1089 // Assume the pointer argument points to storage aligned to 32bits
1090 // or more.
1091 // TODO(dneto): Do more analysis to make sure this is true?
1092 //
1093 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1094 // with:
1095 //
1096 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1097 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1098 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1099 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1100 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1101 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1102 // x float> %converted, %index_is_odd32
1103
1104 auto IntPointerTy = PointerType::get(
1105 IntTy, Arg1->getType()->getPointerAddressSpace());
1106
David Neto973e6a82017-05-30 13:48:18 -04001107 // Cast the base pointer to int*.
David Netoac825b82017-05-30 12:49:01 -04001108 // In a valid call (according to assumptions), this should get
David Neto973e6a82017-05-30 13:48:18 -04001109 // optimized away in the simplify GEP pass.
David Netoac825b82017-05-30 12:49:01 -04001110 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1111
1112 auto One = ConstantInt::get(IntTy, 1);
1113 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1114 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1115
1116 // Index into the correct address of the casted pointer.
1117 auto Ptr =
1118 GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1119
1120 // Load from the int* we casted to.
1121 auto Load = new LoadInst(Ptr, "", CI);
1122
1123 // Get our float2.
1124 auto Call = CallInst::Create(NewF, Load, "", CI);
1125
1126 // Extract out the float result, where the element number is
1127 // determined by whether the original index was even or odd.
1128 auto Extract = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1129
1130 CI->replaceAllUsesWith(Extract);
1131 }
David Neto22f144c2017-06-12 14:26:21 -04001132
1133 // Lastly, remember to remove the user.
1134 ToRemoves.push_back(CI);
1135 }
1136 }
1137
1138 Changed = !ToRemoves.empty();
1139
1140 // And cleanup the calls we don't use anymore.
1141 for (auto V : ToRemoves) {
1142 V->eraseFromParent();
1143 }
1144
1145 // And remove the function we don't need either too.
1146 F->eraseFromParent();
1147 }
1148 }
1149
1150 return Changed;
1151}
1152
1153bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Module &M) {
1154 bool Changed = false;
1155
1156 const std::vector<const char *> Map = {"_Z11vload_half2jPU3AS1KDh",
1157 "_Z11vload_half2jPU3AS2KDh"};
1158
1159 for (auto Name : Map) {
1160 // If we find a function with the matching name.
1161 if (auto F = M.getFunction(Name)) {
1162 SmallVector<Instruction *, 4> ToRemoves;
1163
1164 // Walk the users of the function.
1165 for (auto &U : F->uses()) {
1166 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1167 // The index argument from vload_half.
1168 auto Arg0 = CI->getOperand(0);
1169
1170 // The pointer argument from vload_half.
1171 auto Arg1 = CI->getOperand(1);
1172
1173 auto IntTy = Type::getInt32Ty(M.getContext());
1174 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1175 auto NewPointerTy = PointerType::get(
1176 IntTy, Arg1->getType()->getPointerAddressSpace());
1177 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1178
1179 // Cast the half* pointer to int*.
1180 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
1181
1182 // Index into the correct address of the casted pointer.
1183 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
1184
1185 // Load from the int* we casted to.
1186 auto Load = new LoadInst(Index, "", CI);
1187
1188 // Our intrinsic to unpack a float2 from an int.
1189 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1190
1191 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1192
1193 // Get our float2.
1194 auto Call = CallInst::Create(NewF, Load, "", CI);
1195
1196 CI->replaceAllUsesWith(Call);
1197
1198 // Lastly, remember to remove the user.
1199 ToRemoves.push_back(CI);
1200 }
1201 }
1202
1203 Changed = !ToRemoves.empty();
1204
1205 // And cleanup the calls we don't use anymore.
1206 for (auto V : ToRemoves) {
1207 V->eraseFromParent();
1208 }
1209
1210 // And remove the function we don't need either too.
1211 F->eraseFromParent();
1212 }
1213 }
1214
1215 return Changed;
1216}
1217
1218bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Module &M) {
1219 bool Changed = false;
1220
1221 const std::vector<const char *> Map = {"_Z11vload_half4jPU3AS1KDh",
1222 "_Z11vload_half4jPU3AS2KDh"};
1223
1224 for (auto Name : Map) {
1225 // If we find a function with the matching name.
1226 if (auto F = M.getFunction(Name)) {
1227 SmallVector<Instruction *, 4> ToRemoves;
1228
1229 // Walk the users of the function.
1230 for (auto &U : F->uses()) {
1231 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1232 // The index argument from vload_half.
1233 auto Arg0 = CI->getOperand(0);
1234
1235 // The pointer argument from vload_half.
1236 auto Arg1 = CI->getOperand(1);
1237
1238 auto IntTy = Type::getInt32Ty(M.getContext());
1239 auto Int2Ty = VectorType::get(IntTy, 2);
1240 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1241 auto NewPointerTy = PointerType::get(
1242 Int2Ty, Arg1->getType()->getPointerAddressSpace());
1243 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1244
1245 // Cast the half* pointer to int2*.
1246 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
1247
1248 // Index into the correct address of the casted pointer.
1249 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
1250
1251 // Load from the int2* we casted to.
1252 auto Load = new LoadInst(Index, "", CI);
1253
1254 // Extract each element from the loaded int2.
1255 auto X = ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0),
1256 "", CI);
1257 auto Y = ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1),
1258 "", CI);
1259
1260 // Our intrinsic to unpack a float2 from an int.
1261 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1262
1263 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1264
1265 // Get the lower (x & y) components of our final float4.
1266 auto Lo = CallInst::Create(NewF, X, "", CI);
1267
1268 // Get the higher (z & w) components of our final float4.
1269 auto Hi = CallInst::Create(NewF, Y, "", CI);
1270
1271 Constant *ShuffleMask[4] = {
1272 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1273 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
1274
1275 // Combine our two float2's into one float4.
1276 auto Combine = new ShuffleVectorInst(
1277 Lo, Hi, ConstantVector::get(ShuffleMask), "", CI);
1278
1279 CI->replaceAllUsesWith(Combine);
1280
1281 // Lastly, remember to remove the user.
1282 ToRemoves.push_back(CI);
1283 }
1284 }
1285
1286 Changed = !ToRemoves.empty();
1287
1288 // And cleanup the calls we don't use anymore.
1289 for (auto V : ToRemoves) {
1290 V->eraseFromParent();
1291 }
1292
1293 // And remove the function we don't need either too.
1294 F->eraseFromParent();
1295 }
1296 }
1297
1298 return Changed;
1299}
1300
David Neto6ad93232018-06-07 15:42:58 -07001301bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Module &M) {
1302 bool Changed = false;
1303
1304 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1305 //
1306 // %u = load i32 %ptr
1307 // %fxy = call <2 x float> Unpack2xHalf(u)
1308 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
1309 const std::vector<const char *> Map = {
1310 "_Z20__clspv_vloada_half2jPU3AS1Kj", // global
1311 "_Z20__clspv_vloada_half2jPU3AS3Kj", // local
1312 "_Z20__clspv_vloada_half2jPKj", // private
1313 };
1314
1315 for (auto Name : Map) {
1316 // If we find a function with the matching name.
1317 if (auto F = M.getFunction(Name)) {
1318 SmallVector<Instruction *, 4> ToRemoves;
1319
1320 // Walk the users of the function.
1321 for (auto &U : F->uses()) {
1322 if (auto* CI = dyn_cast<CallInst>(U.getUser())) {
1323 auto Index = CI->getOperand(0);
1324 auto Ptr = CI->getOperand(1);
1325
1326 auto IntTy = Type::getInt32Ty(M.getContext());
1327 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1328 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1329
1330 auto IndexedPtr =
1331 GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
1332 auto Load = new LoadInst(IndexedPtr, "", CI);
1333
1334 // Our intrinsic to unpack a float2 from an int.
1335 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1336
1337 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1338
1339 // Get our final float2.
1340 auto Result = CallInst::Create(NewF, Load, "", CI);
1341
1342 CI->replaceAllUsesWith(Result);
1343
1344 // Lastly, remember to remove the user.
1345 ToRemoves.push_back(CI);
1346 }
1347 }
1348
1349 Changed = true;
1350
1351 // And cleanup the calls we don't use anymore.
1352 for (auto V : ToRemoves) {
1353 V->eraseFromParent();
1354 }
1355
1356 // And remove the function we don't need either too.
1357 F->eraseFromParent();
1358 }
1359 }
1360
1361 return Changed;
1362}
1363
1364bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Module &M) {
1365 bool Changed = false;
1366
1367 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1368 //
1369 // %u2 = load <2 x i32> %ptr
1370 // %u2xy = extractelement %u2, 0
1371 // %u2zw = extractelement %u2, 1
1372 // %fxy = call <2 x float> Unpack2xHalf(uint)
1373 // %fzw = call <2 x float> Unpack2xHalf(uint)
1374 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
1375 const std::vector<const char *> Map = {
1376 "_Z20__clspv_vloada_half4jPU3AS1KDv2_j", // global
1377 "_Z20__clspv_vloada_half4jPU3AS3KDv2_j", // local
1378 "_Z20__clspv_vloada_half4jPKDv2_j", // private
1379 };
1380
1381 for (auto Name : Map) {
1382 // If we find a function with the matching name.
1383 if (auto F = M.getFunction(Name)) {
1384 SmallVector<Instruction *, 4> ToRemoves;
1385
1386 // Walk the users of the function.
1387 for (auto &U : F->uses()) {
1388 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1389 auto Index = CI->getOperand(0);
1390 auto Ptr = CI->getOperand(1);
1391
1392 auto IntTy = Type::getInt32Ty(M.getContext());
1393 auto Int2Ty = VectorType::get(IntTy, 2);
1394 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1395 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1396
1397 auto IndexedPtr =
1398 GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
1399 auto Load = new LoadInst(IndexedPtr, "", CI);
1400
1401 // Extract each element from the loaded int2.
1402 auto X = ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0),
1403 "", CI);
1404 auto Y = ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1),
1405 "", CI);
1406
1407 // Our intrinsic to unpack a float2 from an int.
1408 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1409
1410 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1411
1412 // Get the lower (x & y) components of our final float4.
1413 auto Lo = CallInst::Create(NewF, X, "", CI);
1414
1415 // Get the higher (z & w) components of our final float4.
1416 auto Hi = CallInst::Create(NewF, Y, "", CI);
1417
1418 Constant *ShuffleMask[4] = {
1419 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1420 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
1421
1422 // Combine our two float2's into one float4.
1423 auto Combine = new ShuffleVectorInst(
1424 Lo, Hi, ConstantVector::get(ShuffleMask), "", CI);
1425
1426 CI->replaceAllUsesWith(Combine);
1427
1428 // Lastly, remember to remove the user.
1429 ToRemoves.push_back(CI);
1430 }
1431 }
1432
1433 Changed = true;
1434
1435 // And cleanup the calls we don't use anymore.
1436 for (auto V : ToRemoves) {
1437 V->eraseFromParent();
1438 }
1439
1440 // And remove the function we don't need either too.
1441 F->eraseFromParent();
1442 }
1443 }
1444
1445 return Changed;
1446}
1447
David Neto22f144c2017-06-12 14:26:21 -04001448bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Module &M) {
1449 bool Changed = false;
1450
1451 const std::vector<const char *> Map = {"_Z11vstore_halffjPU3AS1Dh",
1452 "_Z15vstore_half_rtefjPU3AS1Dh",
1453 "_Z15vstore_half_rtzfjPU3AS1Dh"};
1454
1455 for (auto Name : Map) {
1456 // If we find a function with the matching name.
1457 if (auto F = M.getFunction(Name)) {
1458 SmallVector<Instruction *, 4> ToRemoves;
1459
1460 // Walk the users of the function.
1461 for (auto &U : F->uses()) {
1462 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1463 // The value to store.
1464 auto Arg0 = CI->getOperand(0);
1465
1466 // The index argument from vstore_half.
1467 auto Arg1 = CI->getOperand(1);
1468
1469 // The pointer argument from vstore_half.
1470 auto Arg2 = CI->getOperand(2);
1471
David Neto22f144c2017-06-12 14:26:21 -04001472 auto IntTy = Type::getInt32Ty(M.getContext());
1473 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
David Neto22f144c2017-06-12 14:26:21 -04001474 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto17852de2017-05-29 17:29:31 -04001475 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001476
1477 // Our intrinsic to pack a float2 to an int.
1478 auto SPIRVIntrinsic = "spirv.pack.v2f16";
1479
1480 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1481
1482 // Insert our value into a float2 so that we can pack it.
David Neto17852de2017-05-29 17:29:31 -04001483 auto TempVec =
1484 InsertElementInst::Create(UndefValue::get(Float2Ty), Arg0,
1485 ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001486
1487 // Pack the float2 -> half2 (in an int).
1488 auto X = CallInst::Create(NewF, TempVec, "", CI);
1489
David Neto482550a2018-03-24 05:21:07 -07001490 if (clspv::Option::F16BitStorage()) {
David Neto17852de2017-05-29 17:29:31 -04001491 auto ShortTy = Type::getInt16Ty(M.getContext());
1492 auto ShortPointerTy = PointerType::get(
1493 ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001494
David Neto17852de2017-05-29 17:29:31 -04001495 // Truncate our i32 to an i16.
1496 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001497
David Neto17852de2017-05-29 17:29:31 -04001498 // Cast the half* pointer to short*.
1499 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001500
David Neto17852de2017-05-29 17:29:31 -04001501 // Index into the correct address of the casted pointer.
1502 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001503
David Neto17852de2017-05-29 17:29:31 -04001504 // Store to the int* we casted to.
1505 auto Store = new StoreInst(Trunc, Index, CI);
1506
1507 CI->replaceAllUsesWith(Store);
1508 } else {
1509 // We can only write to 32-bit aligned words.
1510 //
1511 // Assuming base is aligned to 32-bits, replace the equivalent of
1512 // vstore_half(value, index, base)
1513 // with:
1514 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1515 // uint32_t write_to_upper_half = index & 1u;
1516 // uint32_t shift = write_to_upper_half << 4;
1517 //
1518 // // Pack the float value as a half number in bottom 16 bits
1519 // // of an i32.
1520 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1521 //
1522 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1523 // ^ ((packed & 0xffff) << shift)
1524 // // We only need relaxed consistency, but OpenCL 1.2 only has
1525 // // sequentially consistent atomics.
1526 // // TODO(dneto): Use relaxed consistency.
1527 // atomic_xor(target_ptr, xor_value)
1528 auto IntPointerTy = PointerType::get(
1529 IntTy, Arg2->getType()->getPointerAddressSpace());
1530
1531 auto Four = ConstantInt::get(IntTy, 4);
1532 auto FFFF = ConstantInt::get(IntTy, 0xffff);
1533
1534 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
1535 // Compute index / 2
1536 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1537 auto BaseI32Ptr = CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1538 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32, "base_i32_ptr", CI);
1539 auto CurrentValue = new LoadInst(OutPtr, "current_value", CI);
1540 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
1541 auto MaskBitsToWrite = BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1542 auto MaskedCurrent = BinaryOperator::CreateAnd(MaskBitsToWrite, CurrentValue, "masked_current", CI);
1543
1544 auto XLowerBits = BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1545 auto NewBitsToWrite = BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1546 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite, "value_to_xor", CI);
1547
1548 // Generate the call to atomi_xor.
1549 SmallVector<Type *, 5> ParamTypes;
1550 // The pointer type.
1551 ParamTypes.push_back(IntPointerTy);
1552 // The Types for memory scope, semantics, and value.
1553 ParamTypes.push_back(IntTy);
1554 ParamTypes.push_back(IntTy);
1555 ParamTypes.push_back(IntTy);
1556 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1557 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
1558
1559 const auto ConstantScopeDevice =
1560 ConstantInt::get(IntTy, spv::ScopeDevice);
1561 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1562 // (SPIR-V Workgroup).
1563 const auto AddrSpaceSemanticsBits =
1564 IntPointerTy->getPointerAddressSpace() == 1
1565 ? spv::MemorySemanticsUniformMemoryMask
1566 : spv::MemorySemanticsWorkgroupMemoryMask;
1567
1568 // We're using relaxed consistency here.
1569 const auto ConstantMemorySemantics =
1570 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1571 AddrSpaceSemanticsBits);
1572
1573 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1574 ConstantMemorySemantics, ValueToXor};
1575 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
1576 }
David Neto22f144c2017-06-12 14:26:21 -04001577
1578 // Lastly, remember to remove the user.
1579 ToRemoves.push_back(CI);
1580 }
1581 }
1582
1583 Changed = !ToRemoves.empty();
1584
1585 // And cleanup the calls we don't use anymore.
1586 for (auto V : ToRemoves) {
1587 V->eraseFromParent();
1588 }
1589
1590 // And remove the function we don't need either too.
1591 F->eraseFromParent();
1592 }
1593 }
1594
1595 return Changed;
1596}
1597
1598bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Module &M) {
1599 bool Changed = false;
1600
1601 const std::vector<const char *> Map = {"_Z12vstore_half2Dv2_fjPU3AS1Dh",
1602 "_Z16vstore_half2_rteDv2_fjPU3AS1Dh",
1603 "_Z16vstore_half2_rtzDv2_fjPU3AS1Dh"};
1604
1605 for (auto Name : Map) {
1606 // If we find a function with the matching name.
1607 if (auto F = M.getFunction(Name)) {
1608 SmallVector<Instruction *, 4> ToRemoves;
1609
1610 // Walk the users of the function.
1611 for (auto &U : F->uses()) {
1612 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1613 // The value to store.
1614 auto Arg0 = CI->getOperand(0);
1615
1616 // The index argument from vstore_half.
1617 auto Arg1 = CI->getOperand(1);
1618
1619 // The pointer argument from vstore_half.
1620 auto Arg2 = CI->getOperand(2);
1621
1622 auto IntTy = Type::getInt32Ty(M.getContext());
1623 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1624 auto NewPointerTy = PointerType::get(
1625 IntTy, Arg2->getType()->getPointerAddressSpace());
1626 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1627
1628 // Our intrinsic to pack a float2 to an int.
1629 auto SPIRVIntrinsic = "spirv.pack.v2f16";
1630
1631 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1632
1633 // Turn the packed x & y into the final packing.
1634 auto X = CallInst::Create(NewF, Arg0, "", CI);
1635
1636 // Cast the half* pointer to int*.
1637 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
1638
1639 // Index into the correct address of the casted pointer.
1640 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
1641
1642 // Store to the int* we casted to.
1643 auto Store = new StoreInst(X, Index, CI);
1644
1645 CI->replaceAllUsesWith(Store);
1646
1647 // Lastly, remember to remove the user.
1648 ToRemoves.push_back(CI);
1649 }
1650 }
1651
1652 Changed = !ToRemoves.empty();
1653
1654 // And cleanup the calls we don't use anymore.
1655 for (auto V : ToRemoves) {
1656 V->eraseFromParent();
1657 }
1658
1659 // And remove the function we don't need either too.
1660 F->eraseFromParent();
1661 }
1662 }
1663
1664 return Changed;
1665}
1666
1667bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Module &M) {
1668 bool Changed = false;
1669
1670 const std::vector<const char *> Map = {"_Z12vstore_half4Dv4_fjPU3AS1Dh",
1671 "_Z16vstore_half4_rteDv4_fjPU3AS1Dh",
1672 "_Z16vstore_half4_rtzDv4_fjPU3AS1Dh"};
1673
1674 for (auto Name : Map) {
1675 // If we find a function with the matching name.
1676 if (auto F = M.getFunction(Name)) {
1677 SmallVector<Instruction *, 4> ToRemoves;
1678
1679 // Walk the users of the function.
1680 for (auto &U : F->uses()) {
1681 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1682 // The value to store.
1683 auto Arg0 = CI->getOperand(0);
1684
1685 // The index argument from vstore_half.
1686 auto Arg1 = CI->getOperand(1);
1687
1688 // The pointer argument from vstore_half.
1689 auto Arg2 = CI->getOperand(2);
1690
1691 auto IntTy = Type::getInt32Ty(M.getContext());
1692 auto Int2Ty = VectorType::get(IntTy, 2);
1693 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1694 auto NewPointerTy = PointerType::get(
1695 Int2Ty, Arg2->getType()->getPointerAddressSpace());
1696 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1697
1698 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1699 ConstantInt::get(IntTy, 1)};
1700
1701 // Extract out the x & y components of our to store value.
1702 auto Lo =
1703 new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1704 ConstantVector::get(LoShuffleMask), "", CI);
1705
1706 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1707 ConstantInt::get(IntTy, 3)};
1708
1709 // Extract out the z & w components of our to store value.
1710 auto Hi =
1711 new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1712 ConstantVector::get(HiShuffleMask), "", CI);
1713
1714 // Our intrinsic to pack a float2 to an int.
1715 auto SPIRVIntrinsic = "spirv.pack.v2f16";
1716
1717 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1718
1719 // Turn the packed x & y into the final component of our int2.
1720 auto X = CallInst::Create(NewF, Lo, "", CI);
1721
1722 // Turn the packed z & w into the final component of our int2.
1723 auto Y = CallInst::Create(NewF, Hi, "", CI);
1724
1725 auto Combine = InsertElementInst::Create(
1726 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
1727 Combine = InsertElementInst::Create(
1728 Combine, Y, ConstantInt::get(IntTy, 1), "", CI);
1729
1730 // Cast the half* pointer to int2*.
1731 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
1732
1733 // Index into the correct address of the casted pointer.
1734 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
1735
1736 // Store to the int2* we casted to.
1737 auto Store = new StoreInst(Combine, Index, CI);
1738
1739 CI->replaceAllUsesWith(Store);
1740
1741 // Lastly, remember to remove the user.
1742 ToRemoves.push_back(CI);
1743 }
1744 }
1745
1746 Changed = !ToRemoves.empty();
1747
1748 // And cleanup the calls we don't use anymore.
1749 for (auto V : ToRemoves) {
1750 V->eraseFromParent();
1751 }
1752
1753 // And remove the function we don't need either too.
1754 F->eraseFromParent();
1755 }
1756 }
1757
1758 return Changed;
1759}
1760
1761bool ReplaceOpenCLBuiltinPass::replaceReadImageF(Module &M) {
1762 bool Changed = false;
1763
1764 const std::map<const char *, const char*> Map = {
1765 { "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_i", "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f" },
1766 { "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv4_i", "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv4_f" }
1767 };
1768
1769 for (auto Pair : Map) {
1770 // If we find a function with the matching name.
1771 if (auto F = M.getFunction(Pair.first)) {
1772 SmallVector<Instruction *, 4> ToRemoves;
1773
1774 // Walk the users of the function.
1775 for (auto &U : F->uses()) {
1776 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1777 // The image.
1778 auto Arg0 = CI->getOperand(0);
1779
1780 // The sampler.
1781 auto Arg1 = CI->getOperand(1);
1782
1783 // The coordinate (integer type that we can't handle).
1784 auto Arg2 = CI->getOperand(2);
1785
1786 auto FloatVecTy = VectorType::get(Type::getFloatTy(M.getContext()), Arg2->getType()->getVectorNumElements());
1787
1788 auto NewFType = FunctionType::get(CI->getType(), {Arg0->getType(), Arg1->getType(), FloatVecTy}, false);
1789
1790 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
1791
1792 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, FloatVecTy, "", CI);
1793
1794 auto NewCI = CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
1795
1796 CI->replaceAllUsesWith(NewCI);
1797
1798 // Lastly, remember to remove the user.
1799 ToRemoves.push_back(CI);
1800 }
1801 }
1802
1803 Changed = !ToRemoves.empty();
1804
1805 // And cleanup the calls we don't use anymore.
1806 for (auto V : ToRemoves) {
1807 V->eraseFromParent();
1808 }
1809
1810 // And remove the function we don't need either too.
1811 F->eraseFromParent();
1812 }
1813 }
1814
1815 return Changed;
1816}
1817
1818bool ReplaceOpenCLBuiltinPass::replaceAtomics(Module &M) {
1819 bool Changed = false;
1820
1821 const std::map<const char *, const char *> Map = {
David Neto22f144c2017-06-12 14:26:21 -04001822 {"_Z10atomic_incPU3AS1Vi", "spirv.atomic_inc"},
1823 {"_Z10atomic_incPU3AS1Vj", "spirv.atomic_inc"},
1824 {"_Z10atomic_decPU3AS1Vi", "spirv.atomic_dec"},
1825 {"_Z10atomic_decPU3AS1Vj", "spirv.atomic_dec"},
1826 {"_Z14atomic_cmpxchgPU3AS1Viii", "spirv.atomic_compare_exchange"},
Neil Henning39672102017-09-29 14:33:13 +01001827 {"_Z14atomic_cmpxchgPU3AS1Vjjj", "spirv.atomic_compare_exchange"}};
David Neto22f144c2017-06-12 14:26:21 -04001828
1829 for (auto Pair : Map) {
1830 // If we find a function with the matching name.
1831 if (auto F = M.getFunction(Pair.first)) {
1832 SmallVector<Instruction *, 4> ToRemoves;
1833
1834 // Walk the users of the function.
1835 for (auto &U : F->uses()) {
1836 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1837 auto FType = F->getFunctionType();
1838 SmallVector<Type *, 5> ParamTypes;
1839
1840 // The pointer type.
1841 ParamTypes.push_back(FType->getParamType(0));
1842
1843 auto IntTy = Type::getInt32Ty(M.getContext());
1844
1845 // The memory scope type.
1846 ParamTypes.push_back(IntTy);
1847
1848 // The memory semantics type.
1849 ParamTypes.push_back(IntTy);
1850
1851 if (2 < CI->getNumArgOperands()) {
1852 // The unequal memory semantics type.
1853 ParamTypes.push_back(IntTy);
1854
1855 // The value type.
1856 ParamTypes.push_back(FType->getParamType(2));
1857
1858 // The comparator type.
1859 ParamTypes.push_back(FType->getParamType(1));
1860 } else if (1 < CI->getNumArgOperands()) {
1861 // The value type.
1862 ParamTypes.push_back(FType->getParamType(1));
1863 }
1864
1865 auto NewFType =
1866 FunctionType::get(FType->getReturnType(), ParamTypes, false);
1867 auto NewF = M.getOrInsertFunction(Pair.second, NewFType);
1868
1869 // We need to map the OpenCL constants to the SPIR-V equivalents.
1870 const auto ConstantScopeDevice =
1871 ConstantInt::get(IntTy, spv::ScopeDevice);
1872 const auto ConstantMemorySemantics = ConstantInt::get(
1873 IntTy, spv::MemorySemanticsUniformMemoryMask |
1874 spv::MemorySemanticsSequentiallyConsistentMask);
1875
1876 SmallVector<Value *, 5> Params;
1877
1878 // The pointer.
1879 Params.push_back(CI->getArgOperand(0));
1880
1881 // The memory scope.
1882 Params.push_back(ConstantScopeDevice);
1883
1884 // The memory semantics.
1885 Params.push_back(ConstantMemorySemantics);
1886
1887 if (2 < CI->getNumArgOperands()) {
1888 // The unequal memory semantics.
1889 Params.push_back(ConstantMemorySemantics);
1890
1891 // The value.
1892 Params.push_back(CI->getArgOperand(2));
1893
1894 // The comparator.
1895 Params.push_back(CI->getArgOperand(1));
1896 } else if (1 < CI->getNumArgOperands()) {
1897 // The value.
1898 Params.push_back(CI->getArgOperand(1));
1899 }
1900
1901 auto NewCI = CallInst::Create(NewF, Params, "", CI);
1902
1903 CI->replaceAllUsesWith(NewCI);
1904
1905 // Lastly, remember to remove the user.
1906 ToRemoves.push_back(CI);
1907 }
1908 }
1909
1910 Changed = !ToRemoves.empty();
1911
1912 // And cleanup the calls we don't use anymore.
1913 for (auto V : ToRemoves) {
1914 V->eraseFromParent();
1915 }
1916
1917 // And remove the function we don't need either too.
1918 F->eraseFromParent();
1919 }
1920 }
1921
Neil Henning39672102017-09-29 14:33:13 +01001922 const std::map<const char *, llvm::AtomicRMWInst::BinOp> Map2 = {
1923 {"_Z10atomic_addPU3AS1Vii", llvm::AtomicRMWInst::Add},
1924 {"_Z10atomic_addPU3AS1Vjj", llvm::AtomicRMWInst::Add},
1925 {"_Z10atomic_subPU3AS1Vii", llvm::AtomicRMWInst::Sub},
1926 {"_Z10atomic_subPU3AS1Vjj", llvm::AtomicRMWInst::Sub},
1927 {"_Z11atomic_xchgPU3AS1Vii", llvm::AtomicRMWInst::Xchg},
1928 {"_Z11atomic_xchgPU3AS1Vjj", llvm::AtomicRMWInst::Xchg},
1929 {"_Z10atomic_minPU3AS1Vii", llvm::AtomicRMWInst::Min},
1930 {"_Z10atomic_minPU3AS1Vjj", llvm::AtomicRMWInst::UMin},
1931 {"_Z10atomic_maxPU3AS1Vii", llvm::AtomicRMWInst::Max},
1932 {"_Z10atomic_maxPU3AS1Vjj", llvm::AtomicRMWInst::UMax},
1933 {"_Z10atomic_andPU3AS1Vii", llvm::AtomicRMWInst::And},
1934 {"_Z10atomic_andPU3AS1Vjj", llvm::AtomicRMWInst::And},
1935 {"_Z9atomic_orPU3AS1Vii", llvm::AtomicRMWInst::Or},
1936 {"_Z9atomic_orPU3AS1Vjj", llvm::AtomicRMWInst::Or},
1937 {"_Z10atomic_xorPU3AS1Vii", llvm::AtomicRMWInst::Xor},
1938 {"_Z10atomic_xorPU3AS1Vjj", llvm::AtomicRMWInst::Xor}};
1939
1940 for (auto Pair : Map2) {
1941 // If we find a function with the matching name.
1942 if (auto F = M.getFunction(Pair.first)) {
1943 SmallVector<Instruction *, 4> ToRemoves;
1944
1945 // Walk the users of the function.
1946 for (auto &U : F->uses()) {
1947 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1948 auto AtomicOp = new AtomicRMWInst(
1949 Pair.second, CI->getArgOperand(0), CI->getArgOperand(1),
1950 AtomicOrdering::SequentiallyConsistent, SyncScope::System, CI);
1951
1952 CI->replaceAllUsesWith(AtomicOp);
1953
1954 // Lastly, remember to remove the user.
1955 ToRemoves.push_back(CI);
1956 }
1957 }
1958
1959 Changed = !ToRemoves.empty();
1960
1961 // And cleanup the calls we don't use anymore.
1962 for (auto V : ToRemoves) {
1963 V->eraseFromParent();
1964 }
1965
1966 // And remove the function we don't need either too.
1967 F->eraseFromParent();
1968 }
1969 }
1970
David Neto22f144c2017-06-12 14:26:21 -04001971 return Changed;
1972}
1973
1974bool ReplaceOpenCLBuiltinPass::replaceCross(Module &M) {
1975 bool Changed = false;
1976
1977 // If we find a function with the matching name.
1978 if (auto F = M.getFunction("_Z5crossDv4_fS_")) {
1979 SmallVector<Instruction *, 4> ToRemoves;
1980
1981 auto IntTy = Type::getInt32Ty(M.getContext());
1982 auto FloatTy = Type::getFloatTy(M.getContext());
1983
1984 Constant *DownShuffleMask[3] = {
1985 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1986 ConstantInt::get(IntTy, 2)};
1987
1988 Constant *UpShuffleMask[4] = {
1989 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1990 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
1991
1992 Constant *FloatVec[3] = {
1993 ConstantFP::get(FloatTy, 0.0f), UndefValue::get(FloatTy), UndefValue::get(FloatTy)
1994 };
1995
1996 // Walk the users of the function.
1997 for (auto &U : F->uses()) {
1998 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
1999 auto Vec4Ty = CI->getArgOperand(0)->getType();
2000 auto Arg0 = new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty), ConstantVector::get(DownShuffleMask), "", CI);
2001 auto Arg1 = new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty), ConstantVector::get(DownShuffleMask), "", CI);
2002 auto Vec3Ty = Arg0->getType();
2003
2004 auto NewFType =
2005 FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
2006
2007 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
2008
2009 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
2010
2011 auto Result = new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec), ConstantVector::get(UpShuffleMask), "", CI);
2012
2013 CI->replaceAllUsesWith(Result);
2014
2015 // Lastly, remember to remove the user.
2016 ToRemoves.push_back(CI);
2017 }
2018 }
2019
2020 Changed = !ToRemoves.empty();
2021
2022 // And cleanup the calls we don't use anymore.
2023 for (auto V : ToRemoves) {
2024 V->eraseFromParent();
2025 }
2026
2027 // And remove the function we don't need either too.
2028 F->eraseFromParent();
2029 }
2030
2031 return Changed;
2032}
David Neto62653202017-10-16 19:05:18 -04002033
2034bool ReplaceOpenCLBuiltinPass::replaceFract(Module &M) {
2035 bool Changed = false;
2036
2037 // OpenCL's float result = fract(float x, float* ptr)
2038 //
2039 // In the LLVM domain:
2040 //
2041 // %floor_result = call spir_func float @floor(float %x)
2042 // store float %floor_result, float * %ptr
2043 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2044 // %result = call spir_func float
2045 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2046 //
2047 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2048 // and clspv.fract occur in the SPIR-V generator pass:
2049 //
2050 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2051 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2052 // ...
2053 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2054 // OpStore %ptr %floor_result
2055 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2056 // %fract_result = OpExtInst %float
2057 // %glsl_ext Fmin %fract_intermediate %just_under_1
2058
2059
2060 using std::string;
2061
2062 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2063 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
2064 using QuadType = std::tuple<const char *, const char *, const char *, const char *>;
2065 auto make_quad = [](const char *a, const char *b, const char *c,
2066 const char *d) {
2067 return std::tuple<const char *, const char *, const char *, const char *>(
2068 a, b, c, d);
2069 };
2070 const std::vector<QuadType> Functions = {
2071 make_quad("_Z5fractfPf", "_Z5floorff", "_Z4fminff", "clspv.fract.f"),
2072 make_quad("_Z5fractDv2_fPS_", "_Z5floorDv2_f", "_Z4fminDv2_ff", "clspv.fract.v2f"),
2073 make_quad("_Z5fractDv3_fPS_", "_Z5floorDv3_f", "_Z4fminDv3_ff", "clspv.fract.v3f"),
2074 make_quad("_Z5fractDv4_fPS_", "_Z5floorDv4_f", "_Z4fminDv4_ff", "clspv.fract.v4f"),
2075 };
2076
2077 for (auto& quad : Functions) {
2078 const StringRef fract_name(std::get<0>(quad));
2079
2080 // If we find a function with the matching name.
2081 if (auto F = M.getFunction(fract_name)) {
2082 if (F->use_begin() == F->use_end())
2083 continue;
2084
2085 // We have some uses.
2086 Changed = true;
2087
2088 auto& Context = M.getContext();
2089
2090 const StringRef floor_name(std::get<1>(quad));
2091 const StringRef fmin_name(std::get<2>(quad));
2092 const StringRef clspv_fract_name(std::get<3>(quad));
2093
2094 // This is either float or a float vector. All the float-like
2095 // types are this type.
2096 auto result_ty = F->getReturnType();
2097
2098 Function* fmin_fn = M.getFunction(fmin_name);
2099 if (!fmin_fn) {
2100 // Make the fmin function.
2101 FunctionType* fn_ty = FunctionType::get(result_ty, {result_ty, result_ty}, false);
2102 fmin_fn = cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty));
2103 fmin_fn->addFnAttr(Attribute::ReadOnly);
2104 fmin_fn->addFnAttr(Attribute::ReadNone);
2105 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2106 }
2107
2108 Function* floor_fn = M.getFunction(floor_name);
2109 if (!floor_fn) {
2110 // Make the floor function.
2111 FunctionType* fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2112 floor_fn = cast<Function>(M.getOrInsertFunction(floor_name, fn_ty));
2113 floor_fn->addFnAttr(Attribute::ReadOnly);
2114 floor_fn->addFnAttr(Attribute::ReadNone);
2115 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2116 }
2117
2118 Function* clspv_fract_fn = M.getFunction(clspv_fract_name);
2119 if (!clspv_fract_fn) {
2120 // Make the clspv_fract function.
2121 FunctionType* fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2122 clspv_fract_fn = cast<Function>(M.getOrInsertFunction(clspv_fract_name, fn_ty));
2123 clspv_fract_fn->addFnAttr(Attribute::ReadOnly);
2124 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2125 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2126 }
2127
2128 // Number of significant significand bits, whether represented or not.
2129 unsigned num_significand_bits;
2130 switch (result_ty->getScalarType()->getTypeID()) {
2131 case Type::HalfTyID:
2132 num_significand_bits = 11;
2133 break;
2134 case Type::FloatTyID:
2135 num_significand_bits = 24;
2136 break;
2137 case Type::DoubleTyID:
2138 num_significand_bits = 53;
2139 break;
2140 default:
2141 assert(false && "Unhandled float type when processing fract builtin");
2142 break;
2143 }
2144 // Beware that the disassembler displays this value as
2145 // OpConstant %float 1
2146 // which is not quite right.
2147 const double kJustUnderOneScalar =
2148 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2149
2150 Constant *just_under_one =
2151 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2152 if (result_ty->isVectorTy()) {
2153 just_under_one = ConstantVector::getSplat(
2154 result_ty->getVectorNumElements(), just_under_one);
2155 }
2156
2157 IRBuilder<> Builder(Context);
2158
2159 SmallVector<Instruction *, 4> ToRemoves;
2160
2161 // Walk the users of the function.
2162 for (auto &U : F->uses()) {
2163 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
2164
2165 Builder.SetInsertPoint(CI);
2166 auto arg = CI->getArgOperand(0);
2167 auto ptr = CI->getArgOperand(1);
2168
2169 // Compute floor result and store it.
2170 auto floor = Builder.CreateCall(floor_fn, {arg});
2171 Builder.CreateStore(floor, ptr);
2172
2173 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2174 auto fract_result = Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2175
2176 CI->replaceAllUsesWith(fract_result);
2177
2178 // Lastly, remember to remove the user.
2179 ToRemoves.push_back(CI);
2180 }
2181 }
2182
2183 // And cleanup the calls we don't use anymore.
2184 for (auto V : ToRemoves) {
2185 V->eraseFromParent();
2186 }
2187
2188 // And remove the function we don't need either too.
2189 F->eraseFromParent();
2190 }
2191 }
2192
2193 return Changed;
2194}