Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/OCLUtil.cpp

raw
1 //===- OCLUtil.cpp - OCL Utilities ----------------------------------------===//
2 //
3 // The LLVM/SPIRV Translator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining a
11 // copy of this software and associated documentation files (the "Software"),
12 // to deal with the Software without restriction, including without limitation
13 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
14 // and/or sell copies of the Software, and to permit persons to whom the
15 // Software is furnished to do so, subject to the following conditions:
16 //
17 // Redistributions of source code must retain the above copyright notice,
18 // this list of conditions and the following disclaimers.
19 // Redistributions in binary form must reproduce the above copyright notice,
20 // this list of conditions and the following disclaimers in the documentation
21 // and/or other materials provided with the distribution.
22 // Neither the names of Advanced Micro Devices, Inc., nor the names of its
23 // contributors may be used to endorse or promote products derived from this
24 // Software without specific prior written permission.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 // CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
31 // THE SOFTWARE.
32 //
33 //===----------------------------------------------------------------------===//
34 //
35 // This file implements OCL utility functions.
36 //
37 //===----------------------------------------------------------------------===//
38 #define DEBUG_TYPE "oclutil"
39
40 #include "OCLUtil.h"
41 #include "SPIRVEntry.h"
42 #include "SPIRVFunction.h"
43 #include "SPIRVInstruction.h"
44 #include "SPIRVInternal.h"
45 #include "llvm/ADT/StringSwitch.h"
46 #include "llvm/IR/IRBuilder.h"
47 #include "llvm/IR/InstVisitor.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/Pass.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52
53 using namespace llvm;
54 using namespace SPIRV;
55
56 namespace OCLUtil {
57
58 #ifndef SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE
59 #define SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE SPIRAS_Private
60 #endif
61
62 #ifndef SPIRV_QUEUE_T_ADDR_SPACE
63 #define SPIRV_QUEUE_T_ADDR_SPACE SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE
64 #endif
65
66 #ifndef SPIRV_EVENT_T_ADDR_SPACE
67 #define SPIRV_EVENT_T_ADDR_SPACE SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE
68 #endif
69
70 #ifndef SPIRV_AVC_INTEL_T_ADDR_SPACE
71 #define SPIRV_AVC_INTEL_T_ADDR_SPACE SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE
72 #endif
73
74 #ifndef SPIRV_CLK_EVENT_T_ADDR_SPACE
75 #define SPIRV_CLK_EVENT_T_ADDR_SPACE SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE
76 #endif
77
78 #ifndef SPIRV_SAMPLER_T_ADDR_SPACE
79 #define SPIRV_SAMPLER_T_ADDR_SPACE SPIRAS_Constant
80 #endif
81
82 #ifndef SPIRV_RESERVE_ID_T_ADDR_SPACE
83 #define SPIRV_RESERVE_ID_T_ADDR_SPACE SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE
84 #endif
85 // Excerpt from SPIR 2.0 spec.:
86 // Pipe objects are represented using pointers to the opaque %opencl.pipe LLVM
87 // structure type which reside in the global address space.
88 #ifndef SPIRV_PIPE_ADDR_SPACE
89 #define SPIRV_PIPE_ADDR_SPACE SPIRAS_Global
90 #endif
91 // Excerpt from SPIR 2.0 spec.:
92 // Note: Images data types reside in global memory and hence should be marked
93 // as such in the "kernel arg addr space" metadata.
94 #ifndef SPIRV_IMAGE_ADDR_SPACE
95 #define SPIRV_IMAGE_ADDR_SPACE SPIRAS_Global
96 #endif
97
98 } // namespace OCLUtil
99
100 ///////////////////////////////////////////////////////////////////////////////
101 //
102 // Map definitions
103 //
104 ///////////////////////////////////////////////////////////////////////////////
105
106 using namespace OCLUtil;
107 namespace SPIRV {
108
109 template <> void SPIRVMap<OCLMemFenceKind, MemorySemanticsMask>::init() {
110 add(OCLMF_Local, MemorySemanticsWorkgroupMemoryMask);
111 add(OCLMF_Global, MemorySemanticsCrossWorkgroupMemoryMask);
112 add(OCLMF_Image, MemorySemanticsImageMemoryMask);
113 }
114
115 template <>
116 void SPIRVMap<OCLMemFenceExtendedKind, MemorySemanticsMask>::init() {
117 add(OCLMFEx_Local, MemorySemanticsWorkgroupMemoryMask);
118 add(OCLMFEx_Global, MemorySemanticsCrossWorkgroupMemoryMask);
119 add(OCLMFEx_Local_Global, MemorySemanticsWorkgroupMemoryMask |
120 MemorySemanticsCrossWorkgroupMemoryMask);
121 add(OCLMFEx_Image, MemorySemanticsImageMemoryMask);
122 add(OCLMFEx_Image_Local,
123 MemorySemanticsWorkgroupMemoryMask | MemorySemanticsImageMemoryMask);
124 add(OCLMFEx_Image_Global,
125 MemorySemanticsCrossWorkgroupMemoryMask | MemorySemanticsImageMemoryMask);
126 add(OCLMFEx_Image_Local_Global, MemorySemanticsWorkgroupMemoryMask |
127 MemorySemanticsCrossWorkgroupMemoryMask |
128 MemorySemanticsImageMemoryMask);
129 }
130
131 template <>
132 void SPIRVMap<OCLMemOrderKind, unsigned, MemorySemanticsMask>::init() {
133 add(OCLMO_relaxed, MemorySemanticsMaskNone);
134 add(OCLMO_acquire, MemorySemanticsAcquireMask);
135 add(OCLMO_release, MemorySemanticsReleaseMask);
136 add(OCLMO_acq_rel, MemorySemanticsAcquireReleaseMask);
137 add(OCLMO_seq_cst, MemorySemanticsSequentiallyConsistentMask);
138 }
139
140 template <> void SPIRVMap<OCLScopeKind, Scope>::init() {
141 add(OCLMS_work_item, ScopeInvocation);
142 add(OCLMS_work_group, ScopeWorkgroup);
143 add(OCLMS_device, ScopeDevice);
144 add(OCLMS_all_svm_devices, ScopeCrossDevice);
145 add(OCLMS_sub_group, ScopeSubgroup);
146 }
147
148 template <> void SPIRVMap<std::string, SPIRVGroupOperationKind>::init() {
149 add("reduce", GroupOperationReduce);
150 add("scan_inclusive", GroupOperationInclusiveScan);
151 add("scan_exclusive", GroupOperationExclusiveScan);
152 add("ballot_bit_count", GroupOperationReduce);
153 add("ballot_inclusive_scan", GroupOperationInclusiveScan);
154 add("ballot_exclusive_scan", GroupOperationExclusiveScan);
155 add("non_uniform_reduce", GroupOperationReduce);
156 add("non_uniform_scan_inclusive", GroupOperationInclusiveScan);
157 add("non_uniform_scan_exclusive", GroupOperationExclusiveScan);
158 add("non_uniform_reduce_logical", GroupOperationReduce);
159 add("non_uniform_scan_inclusive_logical", GroupOperationInclusiveScan);
160 add("non_uniform_scan_exclusive_logical", GroupOperationExclusiveScan);
161 add("clustered_reduce", GroupOperationClusteredReduce);
162 }
163
164 template <> void SPIRVMap<std::string, SPIRVFPRoundingModeKind>::init() {
165 add("rte", FPRoundingModeRTE);
166 add("rtz", FPRoundingModeRTZ);
167 add("rtp", FPRoundingModeRTP);
168 add("rtn", FPRoundingModeRTN);
169 }
170
171 template <> void SPIRVMap<OclExt::Kind, std::string>::init() {
172 #define _SPIRV_OP(x) add(OclExt::x, #x);
173 _SPIRV_OP(cl_images)
174 _SPIRV_OP(cl_doubles)
175 _SPIRV_OP(cl_khr_int64_base_atomics)
176 _SPIRV_OP(cl_khr_int64_extended_atomics)
177 _SPIRV_OP(cl_khr_fp16)
178 _SPIRV_OP(cl_khr_gl_sharing)
179 _SPIRV_OP(cl_khr_gl_event)
180 _SPIRV_OP(cl_khr_d3d10_sharing)
181 _SPIRV_OP(cl_khr_media_sharing)
182 _SPIRV_OP(cl_khr_d3d11_sharing)
183 _SPIRV_OP(cl_khr_global_int32_base_atomics)
184 _SPIRV_OP(cl_khr_global_int32_extended_atomics)
185 _SPIRV_OP(cl_khr_local_int32_base_atomics)
186 _SPIRV_OP(cl_khr_local_int32_extended_atomics)
187 _SPIRV_OP(cl_khr_byte_addressable_store)
188 _SPIRV_OP(cl_khr_3d_image_writes)
189 _SPIRV_OP(cl_khr_gl_msaa_sharing)
190 _SPIRV_OP(cl_khr_depth_images)
191 _SPIRV_OP(cl_khr_gl_depth_images)
192 _SPIRV_OP(cl_khr_subgroups)
193 _SPIRV_OP(cl_khr_mipmap_image)
194 _SPIRV_OP(cl_khr_mipmap_image_writes)
195 _SPIRV_OP(cl_khr_egl_event)
196 _SPIRV_OP(cl_khr_srgb_image_writes)
197 _SPIRV_OP(cl_khr_extended_bit_ops)
198 #undef _SPIRV_OP
199 }
200
201 template <> void SPIRVMap<OclExt::Kind, SPIRVCapabilityKind>::init() {
202 add(OclExt::cl_images, CapabilityImageBasic);
203 add(OclExt::cl_doubles, CapabilityFloat64);
204 add(OclExt::cl_khr_int64_base_atomics, CapabilityInt64Atomics);
205 add(OclExt::cl_khr_int64_extended_atomics, CapabilityInt64Atomics);
206 add(OclExt::cl_khr_fp16, CapabilityFloat16);
207 add(OclExt::cl_khr_subgroups, CapabilityGroups);
208 add(OclExt::cl_khr_mipmap_image, CapabilityImageMipmap);
209 add(OclExt::cl_khr_mipmap_image_writes, CapabilityImageMipmap);
210 add(OclExt::cl_khr_extended_bit_ops, CapabilityBitInstructions);
211 }
212
213 /// Map OpenCL work functions to SPIR-V builtin variables.
214 template <> void SPIRVMap<std::string, SPIRVBuiltinVariableKind>::init() {
215 add("get_work_dim", BuiltInWorkDim);
216 add("get_global_size", BuiltInGlobalSize);
217 add("get_global_id", BuiltInGlobalInvocationId);
218 add("get_global_offset", BuiltInGlobalOffset);
219 add("get_local_size", BuiltInWorkgroupSize);
220 add("get_enqueued_local_size", BuiltInEnqueuedWorkgroupSize);
221 add("get_local_id", BuiltInLocalInvocationId);
222 add("get_num_groups", BuiltInNumWorkgroups);
223 add("get_group_id", BuiltInWorkgroupId);
224 add("get_global_linear_id", BuiltInGlobalLinearId);
225 add("get_local_linear_id", BuiltInLocalInvocationIndex);
226 // cl_khr_subgroups
227 add("get_sub_group_size", BuiltInSubgroupSize);
228 add("get_max_sub_group_size", BuiltInSubgroupMaxSize);
229 add("get_num_sub_groups", BuiltInNumSubgroups);
230 add("get_enqueued_num_sub_groups", BuiltInNumEnqueuedSubgroups);
231 add("get_sub_group_id", BuiltInSubgroupId);
232 add("get_sub_group_local_id", BuiltInSubgroupLocalInvocationId);
233 // cl_khr_subgroup_ballot
234 add("get_sub_group_eq_mask", BuiltInSubgroupEqMask);
235 add("get_sub_group_ge_mask", BuiltInSubgroupGeMask);
236 add("get_sub_group_gt_mask", BuiltInSubgroupGtMask);
237 add("get_sub_group_le_mask", BuiltInSubgroupLeMask);
238 add("get_sub_group_lt_mask", BuiltInSubgroupLtMask);
239 }
240
241 // Maps uniqued OCL builtin function name to SPIR-V op code.
242 // A uniqued OCL builtin function name may be different from the real
243 // OCL builtin function name. e.g. instead of atomic_min, atomic_umin
244 // is used for atomic_min with unsigned integer parameter.
245 // work_group_ and sub_group_ functions are unified as group_ functions
246 // except work_group_barrier.
247 class SPIRVInstruction;
248 template <> void SPIRVMap<std::string, Op, SPIRVInstruction>::init() {
249 #define _SPIRV_OP(x, y) add("atom_" #x, OpAtomic##y);
250 // cl_khr_int64_base_atomics builtins
251 _SPIRV_OP(add, IAdd)
252 _SPIRV_OP(sub, ISub)
253 _SPIRV_OP(xchg, Exchange)
254 _SPIRV_OP(dec, IDecrement)
255 _SPIRV_OP(inc, IIncrement)
256 _SPIRV_OP(cmpxchg, CompareExchange)
257 // cl_khr_int64_extended_atomics builtins
258 _SPIRV_OP(min, SMin)
259 _SPIRV_OP(max, SMax)
260 _SPIRV_OP(and, And)
261 _SPIRV_OP(or, Or)
262 _SPIRV_OP(xor, Xor)
263 #undef _SPIRV_OP
264 #define _SPIRV_OP(x, y) add("atomic_" #x, Op##y);
265 // CL 2.0 atomic builtins
266 _SPIRV_OP(flag_test_and_set_explicit, AtomicFlagTestAndSet)
267 _SPIRV_OP(flag_clear_explicit, AtomicFlagClear)
268 _SPIRV_OP(load_explicit, AtomicLoad)
269 _SPIRV_OP(store_explicit, AtomicStore)
270 _SPIRV_OP(exchange_explicit, AtomicExchange)
271 _SPIRV_OP(compare_exchange_strong_explicit, AtomicCompareExchange)
272 _SPIRV_OP(compare_exchange_weak_explicit, AtomicCompareExchangeWeak)
273 _SPIRV_OP(inc, AtomicIIncrement)
274 _SPIRV_OP(dec, AtomicIDecrement)
275 _SPIRV_OP(fetch_add_explicit, AtomicIAdd)
276 _SPIRV_OP(fetch_sub_explicit, AtomicISub)
277 _SPIRV_OP(fetch_umin_explicit, AtomicUMin)
278 _SPIRV_OP(fetch_umax_explicit, AtomicUMax)
279 _SPIRV_OP(fetch_min_explicit, AtomicSMin)
280 _SPIRV_OP(fetch_max_explicit, AtomicSMax)
281 _SPIRV_OP(fetch_and_explicit, AtomicAnd)
282 _SPIRV_OP(fetch_or_explicit, AtomicOr)
283 _SPIRV_OP(fetch_xor_explicit, AtomicXor)
284 #undef _SPIRV_OP
285 #define _SPIRV_OP(x, y) add(#x, Op##y);
286 _SPIRV_OP(dot, Dot)
287 _SPIRV_OP(async_work_group_copy, GroupAsyncCopy)
288 _SPIRV_OP(async_work_group_strided_copy, GroupAsyncCopy)
289 _SPIRV_OP(wait_group_events, GroupWaitEvents)
290 _SPIRV_OP(isequal, FOrdEqual)
291 _SPIRV_OP(isnotequal, FUnordNotEqual)
292 _SPIRV_OP(isgreater, FOrdGreaterThan)
293 _SPIRV_OP(isgreaterequal, FOrdGreaterThanEqual)
294 _SPIRV_OP(isless, FOrdLessThan)
295 _SPIRV_OP(islessequal, FOrdLessThanEqual)
296 _SPIRV_OP(islessgreater, FOrdNotEqual)
297 _SPIRV_OP(isordered, Ordered)
298 _SPIRV_OP(isunordered, Unordered)
299 _SPIRV_OP(isfinite, IsFinite)
300 _SPIRV_OP(isinf, IsInf)
301 _SPIRV_OP(isnan, IsNan)
302 _SPIRV_OP(isnormal, IsNormal)
303 _SPIRV_OP(signbit, SignBitSet)
304 _SPIRV_OP(any, Any)
305 _SPIRV_OP(all, All)
306 _SPIRV_OP(popcount, BitCount)
307 _SPIRV_OP(get_fence, GenericPtrMemSemantics)
308 // CL 2.0 kernel enqueue builtins
309 _SPIRV_OP(enqueue_marker, EnqueueMarker)
310 _SPIRV_OP(enqueue_kernel, EnqueueKernel)
311 _SPIRV_OP(get_kernel_sub_group_count_for_ndrange_impl,
312 GetKernelNDrangeSubGroupCount)
313 _SPIRV_OP(get_kernel_max_sub_group_size_for_ndrange_impl,
314 GetKernelNDrangeMaxSubGroupSize)
315 _SPIRV_OP(get_kernel_work_group_size_impl, GetKernelWorkGroupSize)
316 _SPIRV_OP(get_kernel_preferred_work_group_size_multiple_impl,
317 GetKernelPreferredWorkGroupSizeMultiple)
318 _SPIRV_OP(retain_event, RetainEvent)
319 _SPIRV_OP(release_event, ReleaseEvent)
320 _SPIRV_OP(create_user_event, CreateUserEvent)
321 _SPIRV_OP(is_valid_event, IsValidEvent)
322 _SPIRV_OP(set_user_event_status, SetUserEventStatus)
323 _SPIRV_OP(capture_event_profiling_info, CaptureEventProfilingInfo)
324 _SPIRV_OP(get_default_queue, GetDefaultQueue)
325 _SPIRV_OP(ndrange_1D, BuildNDRange)
326 _SPIRV_OP(ndrange_2D, BuildNDRange)
327 _SPIRV_OP(ndrange_3D, BuildNDRange)
328 // Generic Address Space Casts
329 _SPIRV_OP(to_global, GenericCastToPtrExplicit)
330 _SPIRV_OP(to_local, GenericCastToPtrExplicit)
331 _SPIRV_OP(to_private, GenericCastToPtrExplicit)
332 // CL 2.0 pipe builtins
333 _SPIRV_OP(read_pipe_2, ReadPipe)
334 _SPIRV_OP(write_pipe_2, WritePipe)
335 _SPIRV_OP(read_pipe_2_bl, ReadPipeBlockingINTEL)
336 _SPIRV_OP(write_pipe_2_bl, WritePipeBlockingINTEL)
337 _SPIRV_OP(read_pipe_4, ReservedReadPipe)
338 _SPIRV_OP(write_pipe_4, ReservedWritePipe)
339 _SPIRV_OP(reserve_read_pipe, ReserveReadPipePackets)
340 _SPIRV_OP(reserve_write_pipe, ReserveWritePipePackets)
341 _SPIRV_OP(commit_read_pipe, CommitReadPipe)
342 _SPIRV_OP(commit_write_pipe, CommitWritePipe)
343 _SPIRV_OP(is_valid_reserve_id, IsValidReserveId)
344 _SPIRV_OP(group_reserve_read_pipe, GroupReserveReadPipePackets)
345 _SPIRV_OP(group_reserve_write_pipe, GroupReserveWritePipePackets)
346 _SPIRV_OP(group_commit_read_pipe, GroupCommitReadPipe)
347 _SPIRV_OP(group_commit_write_pipe, GroupCommitWritePipe)
348 _SPIRV_OP(get_pipe_num_packets_ro, GetNumPipePackets)
349 _SPIRV_OP(get_pipe_num_packets_wo, GetNumPipePackets)
350 _SPIRV_OP(get_pipe_max_packets_ro, GetMaxPipePackets)
351 _SPIRV_OP(get_pipe_max_packets_wo, GetMaxPipePackets)
352 // CL 2.0 workgroup builtins
353 _SPIRV_OP(group_all, GroupAll)
354 _SPIRV_OP(group_any, GroupAny)
355 _SPIRV_OP(group_broadcast, GroupBroadcast)
356 _SPIRV_OP(group_iadd, GroupIAdd)
357 _SPIRV_OP(group_fadd, GroupFAdd)
358 _SPIRV_OP(group_fmin, GroupFMin)
359 _SPIRV_OP(group_umin, GroupUMin)
360 _SPIRV_OP(group_smin, GroupSMin)
361 _SPIRV_OP(group_fmax, GroupFMax)
362 _SPIRV_OP(group_umax, GroupUMax)
363 _SPIRV_OP(group_smax, GroupSMax)
364 _SPIRV_OP(group_imul, GroupIMulKHR)
365 _SPIRV_OP(group_fmul, GroupFMulKHR)
366 _SPIRV_OP(group_ibitwise_and, GroupBitwiseAndKHR)
367 _SPIRV_OP(group_ibitwise_or, GroupBitwiseOrKHR)
368 _SPIRV_OP(group_ibitwise_xor, GroupBitwiseXorKHR)
369 _SPIRV_OP(group_ilogical_and, GroupLogicalAndKHR)
370 _SPIRV_OP(group_ilogical_or, GroupLogicalOrKHR)
371 _SPIRV_OP(group_ilogical_xor, GroupLogicalXorKHR)
372 // CL image builtins
373 _SPIRV_OP(SampledImage, SampledImage)
374 _SPIRV_OP(ImageSampleExplicitLod, ImageSampleExplicitLod)
375 _SPIRV_OP(read_image, ImageRead)
376 _SPIRV_OP(write_image, ImageWrite)
377 _SPIRV_OP(get_image_channel_data_type, ImageQueryFormat)
378 _SPIRV_OP(get_image_channel_order, ImageQueryOrder)
379 _SPIRV_OP(get_image_num_mip_levels, ImageQueryLevels)
380 _SPIRV_OP(get_image_num_samples, ImageQuerySamples)
381 // Intel Subgroups builtins
382 _SPIRV_OP(intel_sub_group_shuffle, SubgroupShuffleINTEL)
383 _SPIRV_OP(intel_sub_group_shuffle_down, SubgroupShuffleDownINTEL)
384 _SPIRV_OP(intel_sub_group_shuffle_up, SubgroupShuffleUpINTEL)
385 _SPIRV_OP(intel_sub_group_shuffle_xor, SubgroupShuffleXorINTEL)
386 // Intel media_block_io builtins
387 _SPIRV_OP(intel_sub_group_media_block_read, SubgroupImageMediaBlockReadINTEL)
388 _SPIRV_OP(intel_sub_group_media_block_write,
389 SubgroupImageMediaBlockWriteINTEL)
390 // cl_khr_subgroup_non_uniform_vote
391 _SPIRV_OP(group_elect, GroupNonUniformElect)
392 _SPIRV_OP(group_non_uniform_all, GroupNonUniformAll)
393 _SPIRV_OP(group_non_uniform_any, GroupNonUniformAny)
394 _SPIRV_OP(group_non_uniform_all_equal, GroupNonUniformAllEqual)
395 // cl_khr_subgroup_ballot
396 _SPIRV_OP(group_non_uniform_broadcast, GroupNonUniformBroadcast)
397 _SPIRV_OP(group_broadcast_first, GroupNonUniformBroadcastFirst)
398 _SPIRV_OP(group_ballot, GroupNonUniformBallot)
399 _SPIRV_OP(group_inverse_ballot, GroupNonUniformInverseBallot)
400 _SPIRV_OP(group_ballot_bit_extract, GroupNonUniformBallotBitExtract)
401 _SPIRV_OP(group_ballot_bit_count_iadd, GroupNonUniformBallotBitCount)
402 _SPIRV_OP(group_ballot_find_lsb, GroupNonUniformBallotFindLSB)
403 _SPIRV_OP(group_ballot_find_msb, GroupNonUniformBallotFindMSB)
404 // cl_khr_subgroup_non_uniform_arithmetic
405 _SPIRV_OP(group_non_uniform_iadd, GroupNonUniformIAdd)
406 _SPIRV_OP(group_non_uniform_fadd, GroupNonUniformFAdd)
407 _SPIRV_OP(group_non_uniform_imul, GroupNonUniformIMul)
408 _SPIRV_OP(group_non_uniform_fmul, GroupNonUniformFMul)
409 _SPIRV_OP(group_non_uniform_smin, GroupNonUniformSMin)
410 _SPIRV_OP(group_non_uniform_umin, GroupNonUniformUMin)
411 _SPIRV_OP(group_non_uniform_fmin, GroupNonUniformFMin)
412 _SPIRV_OP(group_non_uniform_smax, GroupNonUniformSMax)
413 _SPIRV_OP(group_non_uniform_umax, GroupNonUniformUMax)
414 _SPIRV_OP(group_non_uniform_fmax, GroupNonUniformFMax)
415 _SPIRV_OP(group_non_uniform_iand, GroupNonUniformBitwiseAnd)
416 _SPIRV_OP(group_non_uniform_ior, GroupNonUniformBitwiseOr)
417 _SPIRV_OP(group_non_uniform_ixor, GroupNonUniformBitwiseXor)
418 _SPIRV_OP(group_non_uniform_logical_iand, GroupNonUniformLogicalAnd)
419 _SPIRV_OP(group_non_uniform_logical_ior, GroupNonUniformLogicalOr)
420 _SPIRV_OP(group_non_uniform_logical_ixor, GroupNonUniformLogicalXor)
421 // cl_khr_subgroup_shuffle
422 _SPIRV_OP(group_shuffle, GroupNonUniformShuffle)
423 _SPIRV_OP(group_shuffle_xor, GroupNonUniformShuffleXor)
424 // cl_khr_subgroup_shuffle_relative
425 _SPIRV_OP(group_shuffle_up, GroupNonUniformShuffleUp)
426 _SPIRV_OP(group_shuffle_down, GroupNonUniformShuffleDown)
427 // cl_khr_subgroup_rotate
428 _SPIRV_OP(group_rotate, GroupNonUniformRotateKHR)
429 _SPIRV_OP(group_clustered_rotate, GroupNonUniformRotateKHR)
430 // cl_khr_extended_bit_ops
431 _SPIRV_OP(bitfield_insert, BitFieldInsert)
432 _SPIRV_OP(bitfield_extract_signed, BitFieldSExtract)
433 _SPIRV_OP(bitfield_extract_unsigned, BitFieldUExtract)
434 _SPIRV_OP(bit_reverse, BitReverse)
435 // cl_khr_split_work_group_barrier
436 _SPIRV_OP(intel_work_group_barrier_arrive, ControlBarrierArriveINTEL)
437 _SPIRV_OP(intel_work_group_barrier_wait, ControlBarrierWaitINTEL)
438 #undef _SPIRV_OP
439 }
440
441 template <> void SPIRVMap<std::string, Op, OCL12Builtin>::init() {
442 #define _SPIRV_OP(x, y) add(#x, Op##y);
443 _SPIRV_OP(add, AtomicIAdd)
444 _SPIRV_OP(sub, AtomicISub)
445 _SPIRV_OP(xchg, AtomicExchange)
446 _SPIRV_OP(cmpxchg, AtomicCompareExchange)
447 _SPIRV_OP(inc, AtomicIIncrement)
448 _SPIRV_OP(dec, AtomicIDecrement)
449 _SPIRV_OP(min, AtomicSMin)
450 _SPIRV_OP(max, AtomicSMax)
451 _SPIRV_OP(umin, AtomicUMin)
452 _SPIRV_OP(umax, AtomicUMax)
453 _SPIRV_OP(and, AtomicAnd)
454 _SPIRV_OP(or, AtomicOr)
455 _SPIRV_OP(xor, AtomicXor)
456 #undef _SPIRV_OP
457 }
458
459 // SPV_INTEL_device_side_avc_motion_estimation extension builtins
460 class SPIRVSubgroupsAVCIntelInst;
461 template <> void SPIRVMap<std::string, Op, SPIRVSubgroupsAVCIntelInst>::init() {
462 // Here is a workaround for a bug in the specification:
463 // 'avc' missed in 'intel_sub_group_avc' prefix.
464 add("intel_sub_group_ime_ref_window_size",
465 OpSubgroupAvcImeRefWindowSizeINTEL);
466
467 #define _SPIRV_OP(x, y) add("intel_sub_group_avc_" #x, OpSubgroupAvc##y##INTEL);
468 // Initialization phase functions
469 _SPIRV_OP(ime_initialize, ImeInitialize)
470 _SPIRV_OP(fme_initialize, FmeInitialize)
471 _SPIRV_OP(bme_initialize, BmeInitialize)
472 _SPIRV_OP(sic_initialize, SicInitialize)
473
474 // Result and payload types conversion functions
475 _SPIRV_OP(mce_convert_to_ime_payload, MceConvertToImePayload)
476 _SPIRV_OP(mce_convert_to_ime_result, MceConvertToImeResult)
477 _SPIRV_OP(mce_convert_to_ref_payload, MceConvertToRefPayload)
478 _SPIRV_OP(mce_convert_to_ref_result, MceConvertToRefResult)
479 _SPIRV_OP(mce_convert_to_sic_payload, MceConvertToSicPayload)
480 _SPIRV_OP(mce_convert_to_sic_result, MceConvertToSicResult)
481 _SPIRV_OP(ime_convert_to_mce_payload, ImeConvertToMcePayload)
482 _SPIRV_OP(ime_convert_to_mce_result, ImeConvertToMceResult)
483 _SPIRV_OP(ref_convert_to_mce_payload, RefConvertToMcePayload)
484 _SPIRV_OP(ref_convert_to_mce_result, RefConvertToMceResult)
485 _SPIRV_OP(sic_convert_to_mce_payload, SicConvertToMcePayload)
486 _SPIRV_OP(sic_convert_to_mce_result, SicConvertToMceResult)
487 #undef _SPIRV_OP
488
489 // MCE instructions
490 #define _SPIRV_OP(x, y) \
491 add("intel_sub_group_avc_mce_" #x, OpSubgroupAvcMce##y##INTEL);
492 _SPIRV_OP(get_default_inter_base_multi_reference_penalty,
493 GetDefaultInterBaseMultiReferencePenalty)
494 _SPIRV_OP(set_inter_base_multi_reference_penalty,
495 SetInterBaseMultiReferencePenalty)
496 _SPIRV_OP(get_default_inter_shape_penalty, GetDefaultInterShapePenalty)
497 _SPIRV_OP(set_inter_shape_penalty, SetInterShapePenalty)
498 _SPIRV_OP(get_default_inter_direction_penalty,
499 GetDefaultInterDirectionPenalty)
500 _SPIRV_OP(set_inter_direction_penalty, SetInterDirectionPenalty)
501 _SPIRV_OP(get_default_intra_luma_shape_penalty,
502 GetDefaultIntraLumaShapePenalty)
503 _SPIRV_OP(get_default_inter_motion_vector_cost_table,
504 GetDefaultInterMotionVectorCostTable)
505 _SPIRV_OP(get_default_high_penalty_cost_table, GetDefaultHighPenaltyCostTable)
506 _SPIRV_OP(get_default_medium_penalty_cost_table,
507 GetDefaultMediumPenaltyCostTable)
508 _SPIRV_OP(get_default_low_penalty_cost_table, GetDefaultLowPenaltyCostTable)
509 _SPIRV_OP(set_motion_vector_cost_function, SetMotionVectorCostFunction)
510 _SPIRV_OP(get_default_intra_luma_mode_penalty, GetDefaultIntraLumaModePenalty)
511 _SPIRV_OP(get_default_non_dc_luma_intra_penalty,
512 GetDefaultNonDcLumaIntraPenalty)
513 _SPIRV_OP(get_default_intra_chroma_mode_base_penalty,
514 GetDefaultIntraChromaModeBasePenalty)
515 _SPIRV_OP(set_ac_only_haar, SetAcOnlyHaar)
516 _SPIRV_OP(set_source_interlaced_field_polarity,
517 SetSourceInterlacedFieldPolarity)
518 _SPIRV_OP(set_single_reference_interlaced_field_polarity,
519 SetSingleReferenceInterlacedFieldPolarity)
520 _SPIRV_OP(set_dual_reference_interlaced_field_polarities,
521 SetDualReferenceInterlacedFieldPolarities)
522 _SPIRV_OP(get_motion_vectors, GetMotionVectors)
523 _SPIRV_OP(get_inter_distortions, GetInterDistortions)
524 _SPIRV_OP(get_best_inter_distortion, GetBestInterDistortions)
525 _SPIRV_OP(get_inter_major_shape, GetInterMajorShape)
526 _SPIRV_OP(get_inter_minor_shapes, GetInterMinorShape)
527 _SPIRV_OP(get_inter_directions, GetInterDirections)
528 _SPIRV_OP(get_inter_motion_vector_count, GetInterMotionVectorCount)
529 _SPIRV_OP(get_inter_reference_ids, GetInterReferenceIds)
530 _SPIRV_OP(get_inter_reference_interlaced_field_polarities,
531 GetInterReferenceInterlacedFieldPolarities)
532 #undef _SPIRV_OP
533
534 // IME instructions
535 #define _SPIRV_OP(x, y) \
536 add("intel_sub_group_avc_ime_" #x, OpSubgroupAvcIme##y##INTEL);
537 _SPIRV_OP(set_single_reference, SetSingleReference)
538 _SPIRV_OP(set_dual_reference, SetDualReference)
539 _SPIRV_OP(ref_window_size, RefWindowSize)
540 _SPIRV_OP(adjust_ref_offset, AdjustRefOffset)
541 _SPIRV_OP(set_max_motion_vector_count, SetMaxMotionVectorCount)
542 _SPIRV_OP(set_unidirectional_mix_disable, SetUnidirectionalMixDisable)
543 _SPIRV_OP(set_early_search_termination_threshold,
544 SetEarlySearchTerminationThreshold)
545 _SPIRV_OP(set_weighted_sad, SetWeightedSad)
546 _SPIRV_OP(evaluate_with_single_reference, EvaluateWithSingleReference)
547 _SPIRV_OP(evaluate_with_dual_reference, EvaluateWithDualReference)
548 _SPIRV_OP(evaluate_with_single_reference_streamin,
549 EvaluateWithSingleReferenceStreamin)
550 _SPIRV_OP(evaluate_with_dual_reference_streamin,
551 EvaluateWithDualReferenceStreamin)
552 _SPIRV_OP(evaluate_with_single_reference_streamout,
553 EvaluateWithSingleReferenceStreamout)
554 _SPIRV_OP(evaluate_with_dual_reference_streamout,
555 EvaluateWithDualReferenceStreamout)
556 _SPIRV_OP(evaluate_with_single_reference_streaminout,
557 EvaluateWithSingleReferenceStreaminout)
558 _SPIRV_OP(evaluate_with_dual_reference_streaminout,
559 EvaluateWithDualReferenceStreaminout)
560 _SPIRV_OP(get_single_reference_streamin, GetSingleReferenceStreamin)
561 _SPIRV_OP(get_dual_reference_streamin, GetDualReferenceStreamin)
562 _SPIRV_OP(strip_single_reference_streamout, StripSingleReferenceStreamout)
563 _SPIRV_OP(strip_dual_reference_streamout, StripDualReferenceStreamout)
564 _SPIRV_OP(get_border_reached, GetBorderReached)
565 _SPIRV_OP(get_truncated_search_indication, GetTruncatedSearchIndication)
566 _SPIRV_OP(get_unidirectional_early_search_termination,
567 GetUnidirectionalEarlySearchTermination)
568 _SPIRV_OP(get_weighting_pattern_minimum_motion_vector,
569 GetWeightingPatternMinimumMotionVector)
570 _SPIRV_OP(get_weighting_pattern_minimum_distortion,
571 GetWeightingPatternMinimumDistortion)
572 #undef _SPIRV_OP
573
574 #define _SPIRV_OP(x, y) \
575 add("intel_sub_group_avc_ime_get_streamout_major_shape_" #x, \
576 OpSubgroupAvcImeGetStreamout##y##INTEL);
577 _SPIRV_OP(motion_vectors_single_reference,
578 SingleReferenceMajorShapeMotionVectors)
579 _SPIRV_OP(distortions_single_reference, SingleReferenceMajorShapeDistortions)
580 _SPIRV_OP(reference_ids_single_reference,
581 SingleReferenceMajorShapeReferenceIds)
582 _SPIRV_OP(motion_vectors_dual_reference, DualReferenceMajorShapeMotionVectors)
583 _SPIRV_OP(distortions_dual_reference, DualReferenceMajorShapeDistortions)
584 _SPIRV_OP(reference_ids_dual_reference, DualReferenceMajorShapeReferenceIds)
585 #undef _SPIRV_OP
586
587 // REF instructions
588 #define _SPIRV_OP(x, y) \
589 add("intel_sub_group_avc_ref_" #x, OpSubgroupAvcRef##y##INTEL);
590 _SPIRV_OP(set_bidirectional_mix_disable, SetBidirectionalMixDisable)
591 _SPIRV_OP(set_bilinear_filter_enable, SetBilinearFilterEnable)
592 _SPIRV_OP(evaluate_with_single_reference, EvaluateWithSingleReference)
593 _SPIRV_OP(evaluate_with_dual_reference, EvaluateWithDualReference)
594 _SPIRV_OP(evaluate_with_multi_reference, EvaluateWithMultiReference)
595 _SPIRV_OP(evaluate_with_multi_reference_interlaced,
596 EvaluateWithMultiReferenceInterlaced)
597 #undef _SPIRV_OP
598
599 // SIC instructions
600 #define _SPIRV_OP(x, y) \
601 add("intel_sub_group_avc_sic_" #x, OpSubgroupAvcSic##y##INTEL);
602 _SPIRV_OP(configure_skc, ConfigureSkc)
603 _SPIRV_OP(configure_ipe_luma, ConfigureIpeLuma)
604 _SPIRV_OP(configure_ipe_luma_chroma, ConfigureIpeLumaChroma)
605 _SPIRV_OP(get_motion_vector_mask, GetMotionVectorMask)
606 _SPIRV_OP(set_intra_luma_shape_penalty, SetIntraLumaShapePenalty)
607 _SPIRV_OP(set_intra_luma_mode_cost_function, SetIntraLumaModeCostFunction)
608 _SPIRV_OP(set_intra_chroma_mode_cost_function, SetIntraChromaModeCostFunction)
609 _SPIRV_OP(set_skc_bilinear_filter_enable, SetBilinearFilterEnable)
610 _SPIRV_OP(set_skc_forward_transform_enable, SetSkcForwardTransformEnable)
611 _SPIRV_OP(set_block_based_raw_skip_sad, SetBlockBasedRawSkipSad)
612 _SPIRV_OP(evaluate_ipe, EvaluateIpe)
613 _SPIRV_OP(evaluate_with_single_reference, EvaluateWithSingleReference)
614 _SPIRV_OP(evaluate_with_dual_reference, EvaluateWithDualReference)
615 _SPIRV_OP(evaluate_with_multi_reference, EvaluateWithMultiReference)
616 _SPIRV_OP(evaluate_with_multi_reference_interlaced,
617 EvaluateWithMultiReferenceInterlaced)
618 _SPIRV_OP(get_ipe_luma_shape, GetIpeLumaShape)
619 _SPIRV_OP(get_best_ipe_luma_distortion, GetBestIpeLumaDistortion)
620 _SPIRV_OP(get_best_ipe_chroma_distortion, GetBestIpeChromaDistortion)
621 _SPIRV_OP(get_packed_ipe_luma_modes, GetPackedIpeLumaModes)
622 _SPIRV_OP(get_ipe_chroma_mode, GetIpeChromaMode)
623 _SPIRV_OP(get_packed_skc_luma_count_threshold, GetPackedSkcLumaCountThreshold)
624 _SPIRV_OP(get_packed_skc_luma_sum_threshold, GetPackedSkcLumaSumThreshold)
625 _SPIRV_OP(get_inter_raw_sads, GetInterRawSads)
626 #undef _SPIRV_OP
627 }
628
629 template <> void SPIRVMap<std::string, Op, OCLOpaqueType>::init() {
630 add("opencl.event_t", OpTypeEvent);
631 add("opencl.pipe_t", OpTypePipe);
632 add("opencl.clk_event_t", OpTypeDeviceEvent);
633 add("opencl.reserve_id_t", OpTypeReserveId);
634 add("opencl.queue_t", OpTypeQueue);
635 add("opencl.sampler_t", OpTypeSampler);
636 }
637
638 template <> void LLVMSPIRVAtomicRmwOpCodeMap::init() {
639 add(llvm::AtomicRMWInst::Xchg, OpAtomicExchange);
640 add(llvm::AtomicRMWInst::Add, OpAtomicIAdd);
641 add(llvm::AtomicRMWInst::Sub, OpAtomicISub);
642 add(llvm::AtomicRMWInst::And, OpAtomicAnd);
643 add(llvm::AtomicRMWInst::Or, OpAtomicOr);
644 add(llvm::AtomicRMWInst::Xor, OpAtomicXor);
645 add(llvm::AtomicRMWInst::Max, OpAtomicSMax);
646 add(llvm::AtomicRMWInst::Min, OpAtomicSMin);
647 add(llvm::AtomicRMWInst::UMax, OpAtomicUMax);
648 add(llvm::AtomicRMWInst::UMin, OpAtomicUMin);
649 add(llvm::AtomicRMWInst::FAdd, OpAtomicFAddEXT);
650 add(llvm::AtomicRMWInst::FMin, OpAtomicFMinEXT);
651 add(llvm::AtomicRMWInst::FMax, OpAtomicFMaxEXT);
652 }
653
654 } // namespace SPIRV
655
656 ///////////////////////////////////////////////////////////////////////////////
657 //
658 // Functions for getting builtin call info
659 //
660 ///////////////////////////////////////////////////////////////////////////////
661
662 namespace OCLUtil {
663
664 AtomicWorkItemFenceLiterals getAtomicWorkItemFenceLiterals(CallInst *CI) {
665 return std::make_tuple(getArgAsInt(CI, 0),
666 static_cast<OCLMemOrderKind>(getArgAsInt(CI, 1)),
667 static_cast<OCLScopeKind>(getArgAsInt(CI, 2)));
668 }
669
670 size_t getAtomicBuiltinNumMemoryOrderArgs(StringRef Name) {
671 if (Name.startswith("atomic_compare_exchange"))
672 return 2;
673 return 1;
674 }
675
676 size_t getSPIRVAtomicBuiltinNumMemoryOrderArgs(Op OC) {
677 if (OC == OpAtomicCompareExchange || OC == OpAtomicCompareExchangeWeak)
678 return 2;
679 return 1;
680 }
681
682 // atomic_fetch_[add, sub, min, max] and atomic_fetch_[add, sub, min,
683 // max]_explicit functions declared in clang headers should be translated
684 // to corresponding FP-typed Atomic Instructions
685 bool isComputeAtomicOCLBuiltin(StringRef DemangledName) {
686 if (!DemangledName.startswith(kOCLBuiltinName::AtomicPrefix) &&
687 !DemangledName.startswith(kOCLBuiltinName::AtomPrefix))
688 return false;
689
690 return llvm::StringSwitch<bool>(DemangledName)
691 .EndsWith("atomic_add", true)
692 .EndsWith("atomic_sub", true)
693 .EndsWith("atomic_min", true)
694 .EndsWith("atomic_max", true)
695 .EndsWith("atom_add", true)
696 .EndsWith("atom_sub", true)
697 .EndsWith("atom_min", true)
698 .EndsWith("atom_max", true)
699 .EndsWith("inc", true)
700 .EndsWith("dec", true)
701 .EndsWith("cmpxchg", true)
702 .EndsWith("and", true)
703 .EndsWith("or", true)
704 .EndsWith("xor", true)
705 .EndsWith("or_explicit", true)
706 .EndsWith("xor_explicit", true)
707 .EndsWith("and_explicit", true)
708 .Default(false);
709 }
710
711 BarrierLiterals getBarrierLiterals(CallInst *CI) {
712 auto N = CI->arg_size();
713 assert(N == 1 || N == 2);
714
715 StringRef DemangledName;
716 assert(CI->getCalledFunction() && "Unexpected indirect call");
717 if (!oclIsBuiltin(CI->getCalledFunction()->getName(), DemangledName)) {
718 assert(0 &&
719 "call must a builtin (work_group_barrier or sub_group_barrier)");
720 }
721
722 OCLScopeKind Scope = OCLMS_work_group;
723 if (DemangledName == kOCLBuiltinName::SubGroupBarrier) {
724 Scope = OCLMS_sub_group;
725 }
726
727 return std::make_tuple(getArgAsInt(CI, 0),
728 N == 1 ? OCLMS_work_group
729 : static_cast<OCLScopeKind>(getArgAsInt(CI, 1)),
730 Scope);
731 }
732
733 unsigned getExtOp(StringRef OrigName, StringRef GivenDemangledName) {
734 std::string DemangledName{GivenDemangledName};
735 if (DemangledName.empty() || !oclIsBuiltin(OrigName, GivenDemangledName))
736 return ~0U;
737 LLVM_DEBUG(dbgs() << "getExtOp: demangled name: " << DemangledName << '\n');
738 OCLExtOpKind EOC;
739 bool Found = OCLExtOpMap::rfind(DemangledName, &EOC);
740 if (!Found) {
741 std::string Prefix;
742 switch (lastFuncParamType(OrigName)) {
743 case ParamType::UNSIGNED:
744 Prefix = "u_";
745 break;
746 case ParamType::SIGNED:
747 Prefix = "s_";
748 break;
749 case ParamType::FLOAT:
750 Prefix = "f";
751 break;
752 case ParamType::UNKNOWN:
753 break;
754 }
755 Found = OCLExtOpMap::rfind(Prefix + DemangledName, &EOC);
756 }
757 if (Found)
758 return EOC;
759 else
760 return ~0U;
761 }
762
763 ///////////////////////////////////////////////////////////////////////////////
764 //
765 // Functions for getting module info
766 //
767 ///////////////////////////////////////////////////////////////////////////////
768
769 unsigned encodeOCLVer(unsigned short Major, unsigned char Minor,
770 unsigned char Rev) {
771 return (Major * 100 + Minor) * 1000 + Rev;
772 }
773
774 std::tuple<unsigned short, unsigned char, unsigned char>
775 decodeOCLVer(unsigned Ver) {
776 unsigned short Major = Ver / 100000;
777 unsigned char Minor = (Ver % 100000) / 1000;
778 unsigned char Rev = Ver % 1000;
779 return std::make_tuple(Major, Minor, Rev);
780 }
781
782 unsigned getOCLVersion(Module *M, bool AllowMulti) {
783 NamedMDNode *NamedMD = M->getNamedMetadata(kSPIR2MD::OCLVer);
784 if (!NamedMD)
785 return 0;
786 assert(NamedMD->getNumOperands() > 0 && "Invalid SPIR");
787 if (!AllowMulti && NamedMD->getNumOperands() != 1)
788 report_fatal_error(
789 llvm::Twine("Multiple OCL version metadata not allowed"));
790
791 // If the module was linked with another module, there may be multiple
792 // operands.
793 auto GetVer = [=](unsigned I) {
794 auto MD = NamedMD->getOperand(I);
795 return std::make_pair(getMDOperandAsInt(MD, 0), getMDOperandAsInt(MD, 1));
796 };
797 auto Ver = GetVer(0);
798 for (unsigned I = 1, E = NamedMD->getNumOperands(); I != E; ++I)
799 if (Ver != GetVer(I))
800 report_fatal_error(llvm::Twine("OCL version mismatch"));
801
802 return encodeOCLVer(Ver.first, Ver.second, 0);
803 }
804
805 SmallVector<unsigned, 3> decodeMDNode(MDNode *N) {
806 if (N == NULL)
807 return {};
808 size_t NumOperands = N->getNumOperands();
809 SmallVector<unsigned, 3> ReadVals;
810 ReadVals.reserve(NumOperands);
811 for (unsigned I = 0; I < NumOperands; ++I)
812 ReadVals.push_back(getMDOperandAsInt(N, I));
813 return ReadVals;
814 }
815
816 /// Encode LLVM type by SPIR-V execution mode VecTypeHint
817 unsigned encodeVecTypeHint(Type *Ty) {
818 if (Ty->isHalfTy())
819 return 4;
820 if (Ty->isFloatTy())
821 return 5;
822 if (Ty->isDoubleTy())
823 return 6;
824 if (IntegerType *IntTy = dyn_cast<IntegerType>(Ty)) {
825 switch (IntTy->getIntegerBitWidth()) {
826 case 8:
827 return 0;
828 case 16:
829 return 1;
830 case 32:
831 return 2;
832 case 64:
833 return 3;
834 default:
835 llvm_unreachable("invalid integer type");
836 }
837 }
838 if (FixedVectorType *VecTy = dyn_cast<FixedVectorType>(Ty)) {
839 Type *EleTy = VecTy->getElementType();
840 unsigned Size = VecTy->getNumElements();
841 return Size << 16 | encodeVecTypeHint(EleTy);
842 }
843 llvm_unreachable("invalid type");
844 return ~0U;
845 }
846
847 Type *decodeVecTypeHint(LLVMContext &C, unsigned Code) {
848 unsigned VecWidth = Code >> 16;
849 unsigned Scalar = Code & 0xFFFF;
850 Type *ST = nullptr;
851 switch (Scalar) {
852 case 0:
853 case 1:
854 case 2:
855 case 3:
856 ST = IntegerType::get(C, 1 << (3 + Scalar));
857 break;
858 case 4:
859 ST = Type::getHalfTy(C);
860 break;
861 case 5:
862 ST = Type::getFloatTy(C);
863 break;
864 case 6:
865 ST = Type::getDoubleTy(C);
866 break;
867 default:
868 llvm_unreachable("Invalid vec type hint");
869 return nullptr;
870 }
871 if (VecWidth < 1)
872 return ST;
873 return FixedVectorType::get(ST, VecWidth);
874 }
875
876 unsigned transVecTypeHint(MDNode *Node) {
877 return encodeVecTypeHint(getMDOperandAsType(Node, 0));
878 }
879
880 SPIRAddressSpace getOCLOpaqueTypeAddrSpace(Op OpCode) {
881 switch ((unsigned)OpCode) {
882 case OpTypeQueue:
883 return SPIRV_QUEUE_T_ADDR_SPACE;
884 case OpTypeEvent:
885 return SPIRV_EVENT_T_ADDR_SPACE;
886 case OpTypeDeviceEvent:
887 return SPIRV_CLK_EVENT_T_ADDR_SPACE;
888 case OpTypeReserveId:
889 return SPIRV_RESERVE_ID_T_ADDR_SPACE;
890 case OpTypePipe:
891 case OpTypePipeStorage:
892 return SPIRV_PIPE_ADDR_SPACE;
893 case OpTypeImage:
894 case OpTypeSampledImage:
895 case OpTypeVmeImageINTEL:
896 return SPIRV_IMAGE_ADDR_SPACE;
897 case OpConstantSampler:
898 case OpTypeSampler:
899 return SPIRV_SAMPLER_T_ADDR_SPACE;
900 case internal::OpTypeJointMatrixINTEL:
901 case OpTypeCooperativeMatrixKHR:
902 return SPIRAS_Global;
903 default:
904 if (isSubgroupAvcINTELTypeOpCode(OpCode))
905 return SPIRV_AVC_INTEL_T_ADDR_SPACE;
906 assert(false && "No address space is determined for some OCL type");
907 return SPIRV_OCL_SPECIAL_TYPES_DEFAULT_ADDR_SPACE;
908 }
909 }
910
911 static SPIR::TypeAttributeEnum mapAddrSpaceEnums(SPIRAddressSpace Addrspace) {
912 switch (Addrspace) {
913 case SPIRAS_Private:
914 return SPIR::ATTR_PRIVATE;
915 case SPIRAS_Global:
916 return SPIR::ATTR_GLOBAL;
917 case SPIRAS_Constant:
918 return SPIR::ATTR_CONSTANT;
919 case SPIRAS_Local:
920 return SPIR::ATTR_LOCAL;
921 case SPIRAS_Generic:
922 return SPIR::ATTR_GENERIC;
923 case SPIRAS_GlobalDevice:
924 return SPIR::ATTR_GLOBAL_DEVICE;
925 case SPIRAS_GlobalHost:
926 return SPIR::ATTR_GLOBAL_HOST;
927 default:
928 llvm_unreachable("Invalid addrspace enum member");
929 }
930 return SPIR::ATTR_NONE;
931 }
932
933 SPIR::TypeAttributeEnum
934 getOCLOpaqueTypeAddrSpace(SPIR::TypePrimitiveEnum Prim) {
935 switch (Prim) {
936 case SPIR::PRIMITIVE_QUEUE_T:
937 return mapAddrSpaceEnums(SPIRV_QUEUE_T_ADDR_SPACE);
938 case SPIR::PRIMITIVE_EVENT_T:
939 return mapAddrSpaceEnums(SPIRV_EVENT_T_ADDR_SPACE);
940 case SPIR::PRIMITIVE_CLK_EVENT_T:
941 return mapAddrSpaceEnums(SPIRV_CLK_EVENT_T_ADDR_SPACE);
942 case SPIR::PRIMITIVE_RESERVE_ID_T:
943 return mapAddrSpaceEnums(SPIRV_RESERVE_ID_T_ADDR_SPACE);
944 case SPIR::PRIMITIVE_PIPE_RO_T:
945 case SPIR::PRIMITIVE_PIPE_WO_T:
946 return mapAddrSpaceEnums(SPIRV_PIPE_ADDR_SPACE);
947 case SPIR::PRIMITIVE_IMAGE1D_RO_T:
948 case SPIR::PRIMITIVE_IMAGE1D_ARRAY_RO_T:
949 case SPIR::PRIMITIVE_IMAGE1D_BUFFER_RO_T:
950 case SPIR::PRIMITIVE_IMAGE2D_RO_T:
951 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_RO_T:
952 case SPIR::PRIMITIVE_IMAGE2D_DEPTH_RO_T:
953 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_DEPTH_RO_T:
954 case SPIR::PRIMITIVE_IMAGE2D_MSAA_RO_T:
955 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_RO_T:
956 case SPIR::PRIMITIVE_IMAGE2D_MSAA_DEPTH_RO_T:
957 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_DEPTH_RO_T:
958 case SPIR::PRIMITIVE_IMAGE3D_RO_T:
959 case SPIR::PRIMITIVE_IMAGE1D_WO_T:
960 case SPIR::PRIMITIVE_IMAGE1D_ARRAY_WO_T:
961 case SPIR::PRIMITIVE_IMAGE1D_BUFFER_WO_T:
962 case SPIR::PRIMITIVE_IMAGE2D_WO_T:
963 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_WO_T:
964 case SPIR::PRIMITIVE_IMAGE2D_DEPTH_WO_T:
965 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_DEPTH_WO_T:
966 case SPIR::PRIMITIVE_IMAGE2D_MSAA_WO_T:
967 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_WO_T:
968 case SPIR::PRIMITIVE_IMAGE2D_MSAA_DEPTH_WO_T:
969 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_DEPTH_WO_T:
970 case SPIR::PRIMITIVE_IMAGE3D_WO_T:
971 case SPIR::PRIMITIVE_IMAGE1D_RW_T:
972 case SPIR::PRIMITIVE_IMAGE1D_ARRAY_RW_T:
973 case SPIR::PRIMITIVE_IMAGE1D_BUFFER_RW_T:
974 case SPIR::PRIMITIVE_IMAGE2D_RW_T:
975 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_RW_T:
976 case SPIR::PRIMITIVE_IMAGE2D_DEPTH_RW_T:
977 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_DEPTH_RW_T:
978 case SPIR::PRIMITIVE_IMAGE2D_MSAA_RW_T:
979 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_RW_T:
980 case SPIR::PRIMITIVE_IMAGE2D_MSAA_DEPTH_RW_T:
981 case SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_DEPTH_RW_T:
982 case SPIR::PRIMITIVE_IMAGE3D_RW_T:
983 return mapAddrSpaceEnums(SPIRV_IMAGE_ADDR_SPACE);
984 default:
985 llvm_unreachable("No address space is determined for a SPIR primitive");
986 }
987 return SPIR::ATTR_NONE;
988 }
989
990 // Fetch type of invoke function passed to device execution built-ins
991 static FunctionType *getBlockInvokeTy(Function *F, unsigned BlockIdx) {
992 auto Params = F->getFunctionType()->params();
993 PointerType *FuncPtr = cast<PointerType>(Params[BlockIdx]);
994 return FunctionType::get(FuncPtr, Params, false);
995 }
996
997 class OCLBuiltinFuncMangleInfo : public SPIRV::BuiltinFuncMangleInfo {
998 public:
999 OCLBuiltinFuncMangleInfo(Function *F) : F(F) {}
1000 OCLBuiltinFuncMangleInfo() = default;
1001 void init(StringRef UniqName) override {
1002 // Make a local copy as we will modify the string in init function
1003 std::string TempStorage = UniqName.str();
1004 auto NameRef = StringRef(TempStorage);
1005
1006 // Helper functions to erase substrings from NameRef (i.e. TempStorage)
1007 auto EraseSubstring = [&NameRef, &TempStorage](const std::string &ToErase) {
1008 size_t Pos = TempStorage.find(ToErase);
1009 if (Pos != std::string::npos) {
1010 TempStorage.erase(Pos, ToErase.length());
1011 // re-take StringRef as TempStorage was updated
1012 NameRef = StringRef(TempStorage);
1013 }
1014 };
1015 auto EraseSymbol = [&NameRef, &TempStorage](size_t Index) {
1016 TempStorage.erase(Index, 1);
1017 // re-take StringRef as TempStorage was updated
1018 NameRef = StringRef(TempStorage);
1019 };
1020
1021 if (NameRef.startswith("async_work_group")) {
1022 addUnsignedArg(-1);
1023 setArgAttr(1, SPIR::ATTR_CONST);
1024 } else if (NameRef.startswith("printf"))
1025 setVarArg(1);
1026 else if (NameRef.startswith("write_imageui"))
1027 addUnsignedArg(2);
1028 else if (NameRef.equals("prefetch")) {
1029 addUnsignedArg(1);
1030 setArgAttr(0, SPIR::ATTR_CONST);
1031 } else if (NameRef.equals("get_kernel_work_group_size") ||
1032 NameRef.equals(
1033 "get_kernel_preferred_work_group_size_multiple")) {
1034 assert(F && "lack of necessary information");
1035 const size_t BlockArgIdx = 0;
1036 FunctionType *InvokeTy = getBlockInvokeTy(F, BlockArgIdx);
1037 if (InvokeTy->getNumParams() > 1)
1038 setLocalArgBlock(BlockArgIdx);
1039 } else if (NameRef.startswith("__enqueue_kernel")) {
1040 // clang doesn't mangle enqueue_kernel builtins
1041 setAsDontMangle();
1042 } else if (NameRef.startswith("get_") || NameRef.equals("nan") ||
1043 NameRef.equals("mem_fence") || NameRef.startswith("shuffle")) {
1044 addUnsignedArg(-1);
1045 if (NameRef.startswith(kOCLBuiltinName::GetFence)) {
1046 setArgAttr(0, SPIR::ATTR_CONST);
1047 addVoidPtrArg(0);
1048 }
1049 } else if (NameRef.contains("barrier")) {
1050 addUnsignedArg(0);
1051 if (NameRef.equals("work_group_barrier") ||
1052 NameRef.equals("sub_group_barrier") ||
1053 NameRef.equals("intel_work_group_barrier_arrive") ||
1054 NameRef.equals("intel_work_group_barrier_wait"))
1055 setEnumArg(1, SPIR::PRIMITIVE_MEMORY_SCOPE);
1056 } else if (NameRef.startswith("atomic_work_item_fence")) {
1057 addUnsignedArg(0);
1058 setEnumArg(1, SPIR::PRIMITIVE_MEMORY_ORDER);
1059 setEnumArg(2, SPIR::PRIMITIVE_MEMORY_SCOPE);
1060 } else if (NameRef.startswith("atom_")) {
1061 setArgAttr(0, SPIR::ATTR_VOLATILE);
1062 if (NameRef.endswith("_umax") || NameRef.endswith("_umin")) {
1063 addUnsignedArg(-1);
1064 // We need to remove u to match OpenCL C built-in function name
1065 EraseSymbol(5);
1066 }
1067 } else if (NameRef.startswith("atomic")) {
1068 setArgAttr(0, SPIR::ATTR_VOLATILE);
1069 if (NameRef.contains("_umax") || NameRef.contains("_umin")) {
1070 addUnsignedArg(-1);
1071 // We need to remove u to match OpenCL C built-in function name
1072 if (NameRef.contains("_fetch"))
1073 EraseSymbol(13);
1074 else
1075 EraseSymbol(7);
1076 }
1077 if (NameRef.contains("store_explicit") ||
1078 NameRef.contains("exchange_explicit") ||
1079 (NameRef.startswith("atomic_fetch") &&
1080 NameRef.contains("explicit"))) {
1081 setEnumArg(2, SPIR::PRIMITIVE_MEMORY_ORDER);
1082 setEnumArg(3, SPIR::PRIMITIVE_MEMORY_SCOPE);
1083 } else if (NameRef.contains("load_explicit") ||
1084 (NameRef.startswith("atomic_flag") &&
1085 NameRef.contains("explicit"))) {
1086 setEnumArg(1, SPIR::PRIMITIVE_MEMORY_ORDER);
1087 setEnumArg(2, SPIR::PRIMITIVE_MEMORY_SCOPE);
1088 } else if (NameRef.endswith("compare_exchange_strong_explicit") ||
1089 NameRef.endswith("compare_exchange_weak_explicit")) {
1090 setEnumArg(3, SPIR::PRIMITIVE_MEMORY_ORDER);
1091 setEnumArg(4, SPIR::PRIMITIVE_MEMORY_ORDER);
1092 setEnumArg(5, SPIR::PRIMITIVE_MEMORY_SCOPE);
1093 }
1094 // Don't set atomic property to the first argument of 1.2 atomic
1095 // built-ins.
1096 if (!NameRef.endswith("xchg") && // covers _cmpxchg too
1097 (NameRef.contains("fetch") ||
1098 !(NameRef.endswith("_add") || NameRef.endswith("_sub") ||
1099 NameRef.endswith("_inc") || NameRef.endswith("_dec") ||
1100 NameRef.endswith("_min") || NameRef.endswith("_max") ||
1101 NameRef.endswith("_and") || NameRef.endswith("_or") ||
1102 NameRef.endswith("_xor")))) {
1103 addAtomicArg(0);
1104 }
1105 } else if (NameRef.startswith("uconvert_")) {
1106 addUnsignedArg(0);
1107 NameRef = NameRef.drop_front(1);
1108 UnmangledName.erase(0, 1);
1109 } else if (NameRef.startswith("s_")) {
1110 if (NameRef.equals("s_upsample"))
1111 addUnsignedArg(1);
1112 NameRef = NameRef.drop_front(2);
1113 } else if (NameRef.startswith("u_")) {
1114 addUnsignedArg(-1);
1115 NameRef = NameRef.drop_front(2);
1116 } else if (NameRef.equals("fclamp")) {
1117 NameRef = NameRef.drop_front(1);
1118 }
1119 // handle [read|write]pipe builtins (plus two i32 literal args
1120 // required by SPIR 2.0 provisional specification):
1121 else if (NameRef.equals("read_pipe_2") || NameRef.equals("write_pipe_2")) {
1122 // with 2 arguments (plus two i32 literals):
1123 // int read_pipe (read_only pipe gentype p, gentype *ptr)
1124 // int write_pipe (write_only pipe gentype p, const gentype *ptr)
1125 addVoidPtrArg(1);
1126 addUnsignedArg(2);
1127 addUnsignedArg(3);
1128 // OpenCL-like representation of blocking pipes
1129 } else if (NameRef.equals("read_pipe_2_bl") ||
1130 NameRef.equals("write_pipe_2_bl")) {
1131 // with 2 arguments (plus two i32 literals):
1132 // int read_pipe_bl (read_only pipe gentype p, gentype *ptr)
1133 // int write_pipe_bl (write_only pipe gentype p, const gentype *ptr)
1134 addVoidPtrArg(1);
1135 addUnsignedArg(2);
1136 addUnsignedArg(3);
1137 } else if (NameRef.equals("read_pipe_4") ||
1138 NameRef.equals("write_pipe_4")) {
1139 // with 4 arguments (plus two i32 literals):
1140 // int read_pipe (read_only pipe gentype p, reserve_id_t reserve_id, uint
1141 // index, gentype *ptr) int write_pipe (write_only pipe gentype p,
1142 // reserve_id_t reserve_id, uint index, const gentype *ptr)
1143 addUnsignedArg(2);
1144 addVoidPtrArg(3);
1145 addUnsignedArg(4);
1146 addUnsignedArg(5);
1147 } else if (NameRef.contains("reserve_read_pipe") ||
1148 NameRef.contains("reserve_write_pipe")) {
1149 // process [|work_group|sub_group]reserve[read|write]pipe builtins
1150 addUnsignedArg(1);
1151 addUnsignedArg(2);
1152 addUnsignedArg(3);
1153 } else if (NameRef.contains("commit_read_pipe") ||
1154 NameRef.contains("commit_write_pipe")) {
1155 // process [|work_group|sub_group]commit[read|write]pipe builtins
1156 addUnsignedArg(2);
1157 addUnsignedArg(3);
1158 } else if (NameRef.equals("capture_event_profiling_info")) {
1159 addVoidPtrArg(2);
1160 setEnumArg(1, SPIR::PRIMITIVE_CLK_PROFILING_INFO);
1161 } else if (NameRef.equals("enqueue_marker")) {
1162 setArgAttr(2, SPIR::ATTR_CONST);
1163 addUnsignedArg(1);
1164 } else if (NameRef.startswith("vload")) {
1165 addUnsignedArg(0);
1166 setArgAttr(1, SPIR::ATTR_CONST);
1167 } else if (NameRef.startswith("vstore")) {
1168 addUnsignedArg(1);
1169 } else if (NameRef.startswith("ndrange_")) {
1170 addUnsignedArgs(0, 2);
1171 if (NameRef[8] == '2' || NameRef[8] == '3') {
1172 setArgAttr(0, SPIR::ATTR_CONST);
1173 setArgAttr(1, SPIR::ATTR_CONST);
1174 setArgAttr(2, SPIR::ATTR_CONST);
1175 }
1176 } else if (NameRef.contains("umax")) {
1177 addUnsignedArg(-1);
1178 EraseSymbol(NameRef.find("umax"));
1179 } else if (NameRef.contains("umin")) {
1180 addUnsignedArg(-1);
1181 EraseSymbol(NameRef.find("umin"));
1182 } else if (NameRef.contains("broadcast")) {
1183 addUnsignedArg(-1);
1184 } else if (NameRef.startswith(kOCLBuiltinName::SampledReadImage)) {
1185 if (!NameRef.consume_front(kOCLBuiltinName::Sampled))
1186 report_fatal_error(llvm::Twine("Builtin name illformed"));
1187 addSamplerArg(1);
1188 } else if (NameRef.contains(kOCLSubgroupsAVCIntel::Prefix)) {
1189 if (NameRef.contains("evaluate_ipe"))
1190 addSamplerArg(1);
1191 else if (NameRef.contains("evaluate_with_single_reference"))
1192 addSamplerArg(2);
1193 else if (NameRef.contains("evaluate_with_multi_reference")) {
1194 addUnsignedArg(1);
1195 std::string PostFix = "_interlaced";
1196 if (NameRef.contains(PostFix)) {
1197 addUnsignedArg(2);
1198 addSamplerArg(3);
1199 EraseSubstring(PostFix);
1200 } else
1201 addSamplerArg(2);
1202 } else if (NameRef.contains("evaluate_with_dual_reference"))
1203 addSamplerArg(3);
1204 else if (NameRef.contains("fme_initialize"))
1205 addUnsignedArgs(0, 6);
1206 else if (NameRef.contains("bme_initialize"))
1207 addUnsignedArgs(0, 7);
1208 else if (NameRef.contains("set_inter_base_multi_reference_penalty") ||
1209 NameRef.contains("set_inter_shape_penalty") ||
1210 NameRef.contains("set_inter_direction_penalty"))
1211 addUnsignedArg(0);
1212 else if (NameRef.contains("set_motion_vector_cost_function"))
1213 addUnsignedArgs(0, 2);
1214 else if (NameRef.contains("interlaced_field_polarity"))
1215 addUnsignedArg(0);
1216 else if (NameRef.contains("interlaced_field_polarities"))
1217 addUnsignedArgs(0, 1);
1218 else if (NameRef.contains(kOCLSubgroupsAVCIntel::MCEPrefix)) {
1219 if (NameRef.contains("get_default"))
1220 addUnsignedArgs(0, 1);
1221 } else if (NameRef.contains(kOCLSubgroupsAVCIntel::IMEPrefix)) {
1222 if (NameRef.contains("initialize"))
1223 addUnsignedArgs(0, 2);
1224 else if (NameRef.contains("set_single_reference"))
1225 addUnsignedArg(1);
1226 else if (NameRef.contains("set_dual_reference"))
1227 addUnsignedArg(2);
1228 else if (NameRef.contains("set_weighted_sad") ||
1229 NameRef.contains("set_early_search_termination_threshold"))
1230 addUnsignedArg(0);
1231 else if (NameRef.contains("adjust_ref_offset"))
1232 addUnsignedArgs(1, 3);
1233 else if (NameRef.contains("set_max_motion_vector_count") ||
1234 NameRef.contains("get_border_reached"))
1235 addUnsignedArg(0);
1236 else if (NameRef.contains("shape_distortions") ||
1237 NameRef.contains("shape_motion_vectors") ||
1238 NameRef.contains("shape_reference_ids")) {
1239 if (NameRef.contains("single_reference")) {
1240 addUnsignedArg(1);
1241 EraseSubstring("_single_reference");
1242 } else if (NameRef.contains("dual_reference")) {
1243 addUnsignedArgs(1, 2);
1244 EraseSubstring("_dual_reference");
1245 }
1246 } else if (NameRef.contains("ref_window_size"))
1247 addUnsignedArg(0);
1248 } else if (NameRef.contains(kOCLSubgroupsAVCIntel::SICPrefix)) {
1249 if (NameRef.contains("initialize") ||
1250 NameRef.contains("set_intra_luma_shape_penalty"))
1251 addUnsignedArg(0);
1252 else if (NameRef.contains("configure_ipe")) {
1253 if (NameRef.contains("_luma")) {
1254 addUnsignedArgs(0, 6);
1255 EraseSubstring("_luma");
1256 }
1257 if (NameRef.contains("_chroma")) {
1258 addUnsignedArgs(7, 9);
1259 EraseSubstring("_chroma");
1260 }
1261 } else if (NameRef.contains("configure_skc"))
1262 addUnsignedArgs(0, 4);
1263 else if (NameRef.contains("set_skc")) {
1264 if (NameRef.contains("forward_transform_enable"))
1265 addUnsignedArg(0);
1266 } else if (NameRef.contains("set_block")) {
1267 if (NameRef.contains("based_raw_skip_sad"))
1268 addUnsignedArg(0);
1269 } else if (NameRef.contains("get_motion_vector_mask")) {
1270 addUnsignedArgs(0, 1);
1271 } else if (NameRef.contains("luma_mode_cost_function"))
1272 addUnsignedArgs(0, 2);
1273 else if (NameRef.contains("chroma_mode_cost_function"))
1274 addUnsignedArg(0);
1275 }
1276 } else if (NameRef.startswith("intel_sub_group_shuffle")) {
1277 if (NameRef.endswith("_down") || NameRef.endswith("_up"))
1278 addUnsignedArg(2);
1279 else
1280 addUnsignedArg(1);
1281 } else if (NameRef.startswith("intel_sub_group_block_write")) {
1282 // distinguish write to image and other data types based on number of
1283 // arguments--images have one more argument.
1284 if (F->getFunctionType()->getNumParams() == 2) {
1285 addUnsignedArg(0);
1286 addUnsignedArg(1);
1287 } else {
1288 addUnsignedArg(2);
1289 }
1290 } else if (NameRef.startswith("intel_sub_group_block_read")) {
1291 // distinguish read from image and other data types based on number of
1292 // arguments--images have one more argument.
1293 if (F->getFunctionType()->getNumParams() == 1) {
1294 setArgAttr(0, SPIR::ATTR_CONST);
1295 addUnsignedArg(0);
1296 }
1297 } else if (NameRef.startswith("intel_sub_group_media_block_write")) {
1298 addUnsignedArg(3);
1299 } else if (NameRef.startswith(kOCLBuiltinName::SubGroupPrefix)) {
1300 if (NameRef.contains("ballot")) {
1301 if (NameRef.contains("inverse") || NameRef.contains("bit_count") ||
1302 NameRef.contains("inclusive_scan") ||
1303 NameRef.contains("exclusive_scan") ||
1304 NameRef.contains("find_lsb") || NameRef.contains("find_msb"))
1305 addUnsignedArg(0);
1306 else if (NameRef.contains("bit_extract")) {
1307 addUnsignedArgs(0, 1);
1308 }
1309 } else if (NameRef.startswith("sub_group_clustered_rotate")) {
1310 addUnsignedArg(2);
1311 } else if (NameRef.contains("shuffle") || NameRef.contains("clustered"))
1312 addUnsignedArg(1);
1313 } else if (NameRef.startswith("bitfield_insert")) {
1314 addUnsignedArgs(2, 3);
1315 } else if (NameRef.startswith("bitfield_extract_signed") ||
1316 NameRef.startswith("bitfield_extract_unsigned")) {
1317 addUnsignedArgs(1, 2);
1318 }
1319
1320 // Store the final version of a function name
1321 UnmangledName = NameRef.str();
1322 }
1323 // Auxiliarry information, it is expected that it is relevant at the moment
1324 // the init method is called.
1325 Function *F; // SPIRV decorated function
1326 };
1327
1328 std::unique_ptr<SPIRV::BuiltinFuncMangleInfo> makeMangler(Function &F) {
1329 return std::make_unique<OCLBuiltinFuncMangleInfo>(&F);
1330 }
1331
1332 static StringRef getStructName(Type *Ty) {
1333 if (auto *STy = dyn_cast<StructType>(Ty))
1334 return STy->isLiteral() ? "" : Ty->getStructName();
1335 return "";
1336 }
1337
1338 Value *unwrapSpecialTypeInitializer(Value *V) {
1339 if (auto *BC = dyn_cast<BitCastOperator>(V)) {
1340 Type *DestTy = BC->getDestTy();
1341 Type *SrcTy = BC->getSrcTy();
1342 if (SrcTy->isPointerTy() && !SrcTy->isOpaquePointerTy()) {
1343 StringRef SrcName =
1344 getStructName(SrcTy->getNonOpaquePointerElementType());
1345 StringRef DestName =
1346 getStructName(DestTy->getNonOpaquePointerElementType());
1347 if (DestName == getSPIRVTypeName(kSPIRVTypeName::PipeStorage) &&
1348 SrcName == getSPIRVTypeName(kSPIRVTypeName::ConstantPipeStorage))
1349 return BC->getOperand(0);
1350 if (DestName == getSPIRVTypeName(kSPIRVTypeName::Sampler) &&
1351 SrcName == getSPIRVTypeName(kSPIRVTypeName::ConstantSampler))
1352 return BC->getOperand(0);
1353 }
1354 }
1355 return nullptr;
1356 }
1357
1358 bool isSamplerTy(Type *Ty) {
1359 if (auto *TPT = dyn_cast_or_null<TypedPointerType>(Ty)) {
1360 auto *STy = dyn_cast_or_null<StructType>(TPT->getElementType());
1361 return STy && STy->hasName() && STy->getName() == kSPR2TypeName::Sampler;
1362 }
1363 if (auto *TET = dyn_cast_or_null<TargetExtType>(Ty)) {
1364 return TET->getName() == "spirv.Sampler";
1365 }
1366 return false;
1367 }
1368
1369 bool isPipeOrAddressSpaceCastBI(const StringRef MangledName) {
1370 return MangledName == "write_pipe_2" || MangledName == "read_pipe_2" ||
1371 MangledName == "write_pipe_2_bl" || MangledName == "read_pipe_2_bl" ||
1372 MangledName == "write_pipe_4" || MangledName == "read_pipe_4" ||
1373 MangledName == "reserve_write_pipe" ||
1374 MangledName == "reserve_read_pipe" ||
1375 MangledName == "commit_write_pipe" ||
1376 MangledName == "commit_read_pipe" ||
1377 MangledName == "work_group_reserve_write_pipe" ||
1378 MangledName == "work_group_reserve_read_pipe" ||
1379 MangledName == "work_group_commit_write_pipe" ||
1380 MangledName == "work_group_commit_read_pipe" ||
1381 MangledName == "get_pipe_num_packets_ro" ||
1382 MangledName == "get_pipe_max_packets_ro" ||
1383 MangledName == "get_pipe_num_packets_wo" ||
1384 MangledName == "get_pipe_max_packets_wo" ||
1385 MangledName == "sub_group_reserve_write_pipe" ||
1386 MangledName == "sub_group_reserve_read_pipe" ||
1387 MangledName == "sub_group_commit_write_pipe" ||
1388 MangledName == "sub_group_commit_read_pipe" ||
1389 MangledName == "to_global" || MangledName == "to_local" ||
1390 MangledName == "to_private";
1391 }
1392
1393 bool isEnqueueKernelBI(const StringRef MangledName) {
1394 return MangledName == "__enqueue_kernel_basic" ||
1395 MangledName == "__enqueue_kernel_basic_events" ||
1396 MangledName == "__enqueue_kernel_varargs" ||
1397 MangledName == "__enqueue_kernel_events_varargs";
1398 }
1399
1400 bool isKernelQueryBI(const StringRef MangledName) {
1401 return MangledName == "__get_kernel_work_group_size_impl" ||
1402 MangledName == "__get_kernel_sub_group_count_for_ndrange_impl" ||
1403 MangledName == "__get_kernel_max_sub_group_size_for_ndrange_impl" ||
1404 MangledName == "__get_kernel_preferred_work_group_size_multiple_impl";
1405 }
1406
1407 // isUnfusedMulAdd checks if we have the following (most common for fp
1408 // contranction) pattern in LLVM IR:
1409 //
1410 // %mul = fmul float %a, %b
1411 // %add = fadd float %mul, %c
1412 //
1413 // This pattern indicates that fp contraction could have been disabled by
1414 // #pragma OPENCL FP_CONTRACT OFF. When contraction is enabled (by a pragma or
1415 // by clang's -ffp-contract=fast), clang would generate:
1416 //
1417 // %0 = call float @llvm.fmuladd.f32(float %a, float %b, float %c)
1418 //
1419 // or
1420 //
1421 // %mul = fmul contract float %a, %b
1422 // %add = fadd contract float %mul, %c
1423 //
1424 // Note that optimizations may form an unfused fmuladd from fadd+load or
1425 // fadd+call, so this check is quite restrictive (see the comment below).
1426 //
1427 bool isUnfusedMulAdd(BinaryOperator *B) {
1428 if (B->getOpcode() != Instruction::FAdd &&
1429 B->getOpcode() != Instruction::FSub)
1430 return false;
1431
1432 if (B->hasAllowContract()) {
1433 // If this fadd or fsub itself has a contract flag, the operation can be
1434 // contracted regardless of the operands.
1435 return false;
1436 }
1437
1438 // Otherwise, we cannot easily tell if the operation can be a candidate for
1439 // contraction or not. Consider the following cases:
1440 //
1441 // %mul = alloca float
1442 // %t1 = fmul float %a, %b
1443 // store float* %mul, float %t
1444 // %t2 = load %mul
1445 // %r = fadd float %t2, %c
1446 //
1447 // LLVM IR does not allow %r to be contracted. However, after an optimization
1448 // it becomes a candidate for contraction if ContractionOFF is not set in
1449 // SPIR-V:
1450 //
1451 // %t1 = fmul float %a, %b
1452 // %r = fadd float %t1, %c
1453 //
1454 // To be on a safe side, we disallow everything that is even remotely similar
1455 // to fmul + fadd.
1456 return true;
1457 }
1458
1459 std::string getIntelSubgroupBlockDataPostfix(unsigned ElementBitSize,
1460 unsigned VectorNumElements) {
1461 std::ostringstream OSS;
1462 switch (ElementBitSize) {
1463 case 8:
1464 OSS << "_uc";
1465 break;
1466 case 16:
1467 OSS << "_us";
1468 break;
1469 case 32:
1470 // Intentionally does nothing since _ui variant is only an alias.
1471 break;
1472 case 64:
1473 OSS << "_ul";
1474 break;
1475 default:
1476 llvm_unreachable(
1477 "Incorrect data bitsize for intel_subgroup_block builtins");
1478 }
1479 switch (VectorNumElements) {
1480 case 1:
1481 break;
1482 case 2:
1483 case 4:
1484 case 8:
1485 OSS << VectorNumElements;
1486 break;
1487 case 16:
1488 assert((ElementBitSize == 8 || ElementBitSize == 16) &&
1489 "16 elements vector allowed only for char and short builtins");
1490 OSS << VectorNumElements;
1491 break;
1492 default:
1493 llvm_unreachable(
1494 "Incorrect vector length for intel_subgroup_block builtins");
1495 }
1496 return OSS.str();
1497 }
1498
1499 void insertImageNameAccessQualifier(SPIRVAccessQualifierKind Acc,
1500 std::string &Name) {
1501 std::string QName = rmap<std::string>(Acc);
1502 // transform: read_only -> ro, write_only -> wo, read_write -> rw
1503 QName = QName.substr(0, 1) + QName.substr(QName.find("_") + 1, 1) + "_";
1504 assert(!Name.empty() && "image name should not be empty");
1505 Name.insert(Name.size() - 1, QName);
1506 }
1507 } // namespace OCLUtil
1508
1509 Value *SPIRV::transOCLMemScopeIntoSPIRVScope(Value *MemScope,
1510 std::optional<int> DefaultCase,
1511 Instruction *InsertBefore) {
1512 if (auto *C = dyn_cast<ConstantInt>(MemScope)) {
1513 return ConstantInt::get(
1514 C->getType(), map<Scope>(static_cast<OCLScopeKind>(C->getZExtValue())));
1515 }
1516
1517 // If memory_scope is not a constant, then we have to insert dynamic mapping:
1518 return getOrCreateSwitchFunc(kSPIRVName::TranslateOCLMemScope, MemScope,
1519 OCLMemScopeMap::getMap(), /* IsReverse */ false,
1520 DefaultCase, InsertBefore);
1521 }
1522
1523 Value *
1524 SPIRV::transOCLMemOrderIntoSPIRVMemorySemantics(Value *MemOrder,
1525 std::optional<int> DefaultCase,
1526 Instruction *InsertBefore) {
1527 if (auto *C = dyn_cast<ConstantInt>(MemOrder)) {
1528 return ConstantInt::get(
1529 C->getType(), mapOCLMemSemanticToSPIRV(
1530 0, static_cast<OCLMemOrderKind>(C->getZExtValue())));
1531 }
1532
1533 return getOrCreateSwitchFunc(kSPIRVName::TranslateOCLMemOrder, MemOrder,
1534 OCLMemOrderMap::getMap(), /* IsReverse */ false,
1535 DefaultCase, InsertBefore);
1536 }
1537
1538 Value *
1539 SPIRV::transSPIRVMemoryScopeIntoOCLMemoryScope(Value *MemScope,
1540 Instruction *InsertBefore) {
1541 if (auto *C = dyn_cast<ConstantInt>(MemScope)) {
1542 return ConstantInt::get(C->getType(), rmap<OCLScopeKind>(static_cast<Scope>(
1543 C->getZExtValue())));
1544 }
1545
1546 if (auto *CI = dyn_cast<CallInst>(MemScope)) {
1547 Function *F = CI->getCalledFunction();
1548 if (F && F->getName().equals(kSPIRVName::TranslateOCLMemScope)) {
1549 // In case the SPIR-V module was created from an OpenCL program by
1550 // *this* SPIR-V generator, we know that the value passed to
1551 // __translate_ocl_memory_scope is what we should pass to the
1552 // OpenCL builtin now.
1553 return CI->getArgOperand(0);
1554 }
1555 }
1556
1557 return getOrCreateSwitchFunc(
1558 kSPIRVName::TranslateSPIRVMemScope, MemScope, OCLMemScopeMap::getRMap(),
1559 /* IsReverse */ true, std::nullopt, InsertBefore);
1560 }
1561
1562 Value *
1563 SPIRV::transSPIRVMemorySemanticsIntoOCLMemoryOrder(Value *MemorySemantics,
1564 Instruction *InsertBefore) {
1565 if (auto *C = dyn_cast<ConstantInt>(MemorySemantics)) {
1566 return ConstantInt::get(C->getType(),
1567 mapSPIRVMemSemanticToOCL(C->getZExtValue()).second);
1568 }
1569
1570 if (auto *CI = dyn_cast<CallInst>(MemorySemantics)) {
1571 Function *F = CI->getCalledFunction();
1572 if (F && F->getName().equals(kSPIRVName::TranslateOCLMemOrder)) {
1573 // In case the SPIR-V module was created from an OpenCL program by
1574 // *this* SPIR-V generator, we know that the value passed to
1575 // __translate_ocl_memory_order is what we should pass to the
1576 // OpenCL builtin now.
1577 return CI->getArgOperand(0);
1578 }
1579 }
1580
1581 // SPIR-V MemorySemantics contains both OCL mem_fence_flags and mem_order and
1582 // therefore, we need to apply mask
1583 int Mask = MemorySemanticsMaskNone | MemorySemanticsAcquireMask |
1584 MemorySemanticsReleaseMask | MemorySemanticsAcquireReleaseMask |
1585 MemorySemanticsSequentiallyConsistentMask;
1586 return getOrCreateSwitchFunc(kSPIRVName::TranslateSPIRVMemOrder,
1587 MemorySemantics, OCLMemOrderMap::getRMap(),
1588 /* IsReverse */ true, std::nullopt, InsertBefore,
1589 Mask);
1590 }
1591
1592 Value *SPIRV::transSPIRVMemorySemanticsIntoOCLMemFenceFlags(
1593 Value *MemorySemantics, Instruction *InsertBefore) {
1594 if (auto *C = dyn_cast<ConstantInt>(MemorySemantics)) {
1595 return ConstantInt::get(C->getType(),
1596 mapSPIRVMemSemanticToOCL(C->getZExtValue()).first);
1597 }
1598
1599 // TODO: any possible optimizations?
1600 // SPIR-V MemorySemantics contains both OCL mem_fence_flags and mem_order and
1601 // therefore, we need to apply mask
1602 int Mask = MemorySemanticsWorkgroupMemoryMask |
1603 MemorySemanticsCrossWorkgroupMemoryMask |
1604 MemorySemanticsImageMemoryMask;
1605 return getOrCreateSwitchFunc(
1606 kSPIRVName::TranslateSPIRVMemFence, MemorySemantics,
1607 OCLMemFenceExtendedMap::getRMap(),
1608 /* IsReverse */ true, std::nullopt, InsertBefore, Mask);
1609 }
1610
1611 void llvm::mangleOpenClBuiltin(const std::string &UniqName,
1612 ArrayRef<Type *> ArgTypes,
1613 std::string &MangledName) {
1614 OCLUtil::OCLBuiltinFuncMangleInfo BtnInfo;
1615 MangledName = SPIRV::mangleBuiltin(UniqName, ArgTypes, &BtnInfo);
1616 }