Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/docs/SPIRVRepresentationInLLVM.rst

raw
1 ================================
2 SPIR-V representation in LLVM IR
3 ================================
4 .. contents::
5 :local:
6
7 Overview
8 ========
9
10 As one of the goals of SPIR-V is to `"map easily to other IRs, including LLVM
11 IR" <https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#_goals>`_,
12 most of SPIR-V entities (global variables, constants, types, functions, basic
13 blocks, instructions) have straightforward counterparts in LLVM. Therefore the
14 focus of this document is those entities in SPIR-V which do not map to LLVM in
15 an obvious way. These include:
16
17 * SPIR-V types mapped to LLVM types
18 * SPIR-V instructions mapped to LLVM function calls
19 * SPIR-V extended instructions mapped to LLVM function calls
20 * SPIR-V builtin variables mapped to LLVM function calls or LLVM global variables
21 * SPIR-V instructions mapped to LLVM metadata
22 * SPIR-V types mapped to LLVM opaque types
23 * SPIR-V decorations mapped to LLVM metadata or named attributes
24 * Additional requirements for LLVM module
25
26 SPIR-V Types Mapped to LLVM Types
27 =================================
28 Limited to this section, we define the following common postfix.
29
30 * {Access} - Postifix indicating the access qualifier.
31 {Access} take integer literal values which are defined by the SPIR-V spec.
32
33 OpTypeImage
34 -----------
35 OpTypeImage is mapped to LLVM opaque type
36 spirv.Image._{SampledType}_{Dim}_{Depth}_{Arrayed}_{MS}_{Sampled}_{Format}_{Access}
37 and mangled as __spirv_Image__{SampledType}_{Dim}_{Depth}_{Arrayed}_{MS}_{Sampled}_{Format}_{Access},
38
39 where
40
41 * {SampledType}={float|half|int|uint|void} - Postfix indicating the sampled data type
42 - void for unknown sampled data type
43 * {Dim} - Postfix indicating the dimension of the image
44 * {Depth} - Postfix indicating whether the image is a depth image
45 * {Arrayed} - Postfix indicating whether the image is arrayed image
46 * {MS} - Postfix indicating whether the image is multi-sampled
47 * {Sampled} - Postfix indicating whether the image is associated with sampler
48 * {Format} - Postfix indicating the image format
49
50 Postfixes {Dim}, {Depth}, {Arrayed}, {MS}, {Sampled} and {Format} take integer
51 literal values which are defined by the SPIR-V spec.
52
53 OpTypeSampledImage
54 ------------------
55 OpTypeSampledImage is mapped to LLVM opaque type
56 spirv.SampledImage._{Postfixes} and mangled as __spirv_SampledImage__{Postfixes},
57 where {Postfixes} are the same as the postfixes of the original image type, as
58 defined above in this section.
59
60 OpTypePipe
61 ----------
62 OpTypePipe is mapped to LLVM opaque type
63 spirv.Pipe._{Access} and mangled as __spirv_Pipe__{Access}.
64
65 Other SPIR-V Types
66 ------------------
67 * OpTypeEvent
68 * OpTypeDeviceEvent
69 * OpTypeReserveId
70 * OpTypeQueue
71 * OpTypeSampler
72 * OpTypePipeStorage (SPIR-V 1.1)
73 The above SPIR-V types are mapped to LLVM opaque type spirv.{TypeName} and
74 mangled as __spirv_{TypeName}, where {TypeName} is the name of the SPIR-V
75 type with "OpType" removed, e.g., OpTypeEvent is mapped to spirv.Event and
76 mangled as __spirv_Event.
77
78 Address spaces
79 --------------
80
81 The following
82 `SPIR-V storage classes <https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#Storage_Class>`_
83 are naturally represented as LLVM IR address spaces with the following mapping:
84
85 ==================== ====================================
86 SPIR-V storage class LLVM IR address space
87 ==================== ====================================
88 ``Function`` No address space or ``addrspace(0)``
89 ``CrossWorkgroup`` ``addrspace(1)``
90 ``UniformConstant`` ``addrspace(2)``
91 ``Workgroup`` ``addrspace(3)``
92 ``Generic`` ``addrspace(4)``
93 ==================== ====================================
94
95 SPIR-V extensions are allowed to add new storage classes. For example,
96 SPV_INTEL_usm_storage_classes extension adds ``DeviceOnlyINTEL`` and
97 ``HostOnlyINTEL`` storage classes which are mapped to ``addrspace(5)`` and
98 ``addrspace(6)`` respectively.
99
100 SPIR-V Instructions Mapped to LLVM Function Calls
101 =================================================
102
103 Some SPIR-V instructions which can be included in basic blocks do not have
104 corresponding LLVM instructions or intrinsics. These SPIR-V instructions are
105 represented by function calls in LLVM. The function corresponding to a SPIR-V
106 instruction is termed SPIR-V builtin function and its name is `IA64 mangled
107 <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling>`_ with extensions
108 for SPIR-V specific types. The unmangled name of a SPIR-V builtin function
109 follows the convention
110
111 .. code-block:: c
112
113 __spirv_{OpCodeName}{_OptionalPostfixes}
114
115 where {OpCodeName} is the op code name of the SPIR-V instructions without the
116 "Op" prefix, e.g. EnqueueKernel. {OptionalPostfixes} are optional postfixes to
117 specify decorations for the SPIR-V instruction. The SPIR-V op code name and
118 each postfix does not contain "_".
119
120 SPIR-V builtin functions accepts all argument types accepted by the
121 corresponding SPIR-V instructions. The literal operands of extended
122 instruction are mapped to function call arguments with type i32.
123
124 Optional Postfixes for SPIR-V Builtin Function Names
125 ----------------------------------------------------
126
127 SPIR-V builtin functions corresponding to the following SPIR-V instructions are
128 postfixed following the order specified as below:
129
130 * Instructions having identical argument types but different return types are postfixed with "_R{ReturnType}" where
131 - {ReturnType} = {ScalarType}|{VectorType}
132 - {ScalarType} = char|uchar|short|ushort|int|uint|long|ulong|half|float|double|bool
133 - {VectorType} = {ScalarType}{2|3|4|8|16}
134 * Instructions with saturation decoration are postfixed with "_sat"
135 * Instructions with floating point rounding mode decoration are postfixed with "_rtp|_rtn|_rtz|_rte"
136
137 SPIR-V Builtin Conversion Function Names
138 ----------------------------------------
139
140 The unmangled names of SPIR-V builtin conversion functions follow the convention:
141
142 .. code-block:: c
143
144 __spirv_{ConversionOpCodeName}_R{ReturnType}{_sat}{_rtp|_rtn|_rtz|_rte}
145
146 where
147
148 * {ConversionOpCodeName} = ConvertFToU|ConvertFToS|ConvertUToF|ConvertUToS|UConvert|SConvert|FConvert|SatConvertSToU|SatConvertUToS
149
150 SPIR-V Builtin Reinterpret / Bitcast Function Names
151 ---------------------------------------------------
152
153 The unmangled names of SPIR-V builtin reinterpret / bitcast functions follow the convention:
154
155 .. code-block:: c
156
157 __spirv_{BitcastOpCodeName}_R{ReturnType}
158
159 SPIR-V Builtin ImageSample Function Names
160 ----------------------------------------
161
162 The unmangled names of SPIR-V builtin ImageSample functions follow the convention:
163
164 .. code-block:: c
165
166 __spirv_{ImageSampleOpCodeName}_R{ReturnType}
167
168 SPIR-V Builtin GenericCastToPtr Function Name
169 ----------------------------------------
170
171 The unmangled names of SPIR-V builtin GenericCastToPtrExplicit function follow the convention:
172
173 .. code-block:: c
174
175 __spirv_GenericCastToPtrExplicit_To{Global|Local|Private}
176
177 SPIR-V Builtin BuildNDRange Function Name
178 ----------------------------------------
179
180 The unmangled names of SPIR-V builtin BuildNDRange functions follow the convention:
181
182 .. code-block:: c
183
184 __spirv_{BuildNDRange}_{1|2|3}D
185
186 SPIR-V 1.1 Builtin CreatePipeFromPipeStorage Function Name
187 ----------------------------------------
188
189 The unmangled names of SPIR-V builtin CreatePipeFromPipeStorage function follow the convention:
190
191 .. code-block:: c
192
193 __spirv_CreatePipeFromPipeStorage_{read|write}
194
195 SPIR-V Extended Instructions Mapped to LLVM Function Calls
196 ==========================================================
197
198 SPIR-V extended instructions are mapped to LLVM function calls. The function
199 name is IA64 mangled and the unmangled name has the format
200
201 .. code-block:: c
202
203 __spirv_{ExtendedInstructionSetName}_{ExtendedInstrutionName}{__OptionalPostfixes}
204
205 where {ExtendedInstructionSetName} for OpenCL is "ocl".
206
207 The translated functions accepts all argument types accepted by the
208 corresponding SPIR-V instructions. The literal operands of extended
209 instruction are mapped to function call arguments with type i32.
210
211 The optional postfixes take the same format as SPIR-V builtin functions. The first postfix
212 starts with two underscores to facilitate identification since extended instruction name
213 may contain underscore. The remaining postfixes start with one underscore.
214
215 OpenCL Extended Builtin Vector Load Function Names
216 ----------------------------------------
217
218 The unmangled names of OpenCL extended vector load functions follow the convention:
219
220 .. code-block:: c
221
222 __spirv_ocl_{VectorLoadOpCodeName}__R{ReturnType}
223
224 where
225
226 * {VectorLoadOpCodeName} = vloadn|vload_half|vload_halfn|vloada_halfn
227
228
229 SPIR-V Builtin Variables Mapped to LLVM Function Calls or LLVM Global Variables
230 ===============================================================================
231
232 By default each access of SPIR-V builtin variable's value is mapped to LLVM
233 function call. The unmangled names of these functions follow the convention:
234
235 .. code-block:: c
236
237 __spirv_BuiltIn{VariableName}
238
239 In case if SPIR-V builtin variable has vector type, the corresponding
240 LLVM function will have an integer argument, so each access of the variable's
241 scalar component is mapped to a function call with index argument, i.e.:
242
243 .. code-block:: llvm
244
245 ; For scalar variables
246 ; SPIR-V
247 OpDecorate %__spirv_BuiltInGlobalInvocationId BuiltIn GlobalInvocationId
248 %13 = OpLoad %uint %__spirv_BuiltInGlobalLinearId Aligned 4
249
250 ; Will be transformed into the following LLVM IR:
251 %0 = call spir_func i32 @_Z29__spirv_BuiltInGlobalLinearIdv()
252
253 ; For vector variables
254 ; SPIRV
255 OpDecorate %__spirv_BuiltInGlobalInvocationId BuiltIn GlobalInvocationId
256 %14 = OpLoad %v3ulong %__spirv_BuiltInGlobalInvocationId Aligned 32
257 %15 = OpCompositeExtract %ulong %14 1
258
259 ; Can be transformed into the following LLVM IR:
260 %0 = call spir_func i64 @_Z33__spirv_BuiltInGlobalInvocationIdi(i32 1)
261
262 ; However SPIRV-LLVM translator will transform it to the following pattern:
263 %1 = call spir_func i64 @_Z33__spirv_BuiltInGlobalInvocationIdi(i32 0)
264 %2 = insertelement <3 x i64> undef, i64 %1, i32 0
265 %3 = call spir_func i64 @_Z33__spirv_BuiltInGlobalInvocationIdi(i32 1)
266 %4 = insertelement <3 x i64> %2, i64 %3, i32 1
267 %5 = call spir_func i64 @_Z33__spirv_BuiltInGlobalInvocationIdi(i32 2)
268 %6 = insertelement <3 x i64> %4, i64 %5, i32 2
269 %7 = extractelement <3 x i64> %6, i32 1
270 ; In case some actions are performed with the variable's value in vector form.
271
272 SPIR-V builtin variables can also be mapped to LLVM global variables with
273 unmangled name __spirv_BuiltIn{Name}.
274
275 The representation with variables is closer to SPIR-V, so it is easier to
276 translate from SPIR-V to LLVM and back using it.
277 Hovewer in languages like OpenCL the functionality covered by SPIR-V builtin
278 variables is usually represented by builtin functions, so it is easier to
279 translate from/to SPIR-V friendly IR to/from LLVM IR produced from OpenCL-like
280 source languages. That is why both forms of mapping are supported.
281
282 SPIR-V instructions mapped to LLVM metadata
283 ===========================================
284
285 SPIR-V specification allows multiple module scope instructions, whereas LLVM
286 named metadata must be unique, so encoding of such instructions has the
287 following format:
288
289 .. code-block:: llvm
290
291 !spirv.<OpCodeName> = !{!<InstructionMetadata1>, !<InstructionMetadata2>, ..}
292 !<InstructionMetadata1> = !{<Operand1>, <Operand2>, ..}
293 !<InstructionMetadata2> = !{<Operand1>, <Operand2>, ..}
294
295 +--------------------+---------------------------------------------------------+
296 | SPIR-V instruction | LLVM IR |
297 +====================+=========================================================+
298 | OpSource | .. code-block:: llvm |
299 | | |
300 | | !spirv.Source = !{!0} |
301 | | !0 = !{i32 3, i32 66048, !1} |
302 | | ; 3 - OpenCL_C |
303 | | ; 66048 = 0x10200 - OpenCL version 1.2 |
304 | | ; !1 - optional file id. |
305 | | !1 = !{!"/tmp/opencl/program.cl"} |
306 +--------------------+---------------------------------------------------------+
307 | OpSourceExtension | .. code-block:: llvm |
308 | | |
309 | | !spirv.SourceExtension = !{!0, !1} |
310 | | !0 = !{!"cl_khr_fp16"} |
311 | | !1 = !{!"cl_khr_gl_sharing"} |
312 +--------------------+---------------------------------------------------------+
313 | OpExtension | .. code-block:: llvm |
314 | | |
315 | | !spirv.Extension = !{!0} |
316 | | !0 = !{!"SPV_KHR_expect_assume"} |
317 +--------------------+---------------------------------------------------------+
318 | OpCapability | .. code-block:: llvm |
319 | | |
320 | | !spirv.Capability = !{!0} |
321 | | !0 = !{i32 10} ; Float64 - program uses doubles |
322 +--------------------+---------------------------------------------------------+
323 | OpExecutionMode | .. code-block:: llvm |
324 | | |
325 | | !spirv.ExecutionMode = !{!0} |
326 | | !0 = !{void ()* @worker, i32 30, i32 262149} |
327 | | ; Set execution mode with id 30 (VecTypeHint) and |
328 | | ; literal `262149` operand. |
329 +--------------------+---------------------------------------------------------+
330 | Generator's magic | .. code-block:: llvm |
331 | number - word # 2 | |
332 | in SPIR-V module | !spirv.Generator = !{!0} |
333 | | !0 = !{i16 6, i16 123} |
334 | | ; 6 - Generator Id, 123 - Generator Version |
335 +--------------------+---------------------------------------------------------+
336
337 For example:
338
339 .. code-block:: llvm
340
341 !spirv.Source = !{!0}
342 !spirv.SourceExtension = !{!2, !3}
343 !spirv.Extension = !{!2}
344 !spirv.Capability = !{!4}
345 !spirv.MemoryModel = !{!5}
346 !spirv.EntryPoint = !{!6 ,!7}
347 !spirv.ExecutionMode = !{!8, !9}
348 !spirv.Generator = !{!10 }
349
350 ; 3 - OpenCL_C, 102000 - OpenCL version 1.2, !1 - optional file id.
351 !0 = !{i32 3, i32 102000, !1}
352 !1 = !{!"/tmp/opencl/program.cl"}
353 !2 = !{!"cl_khr_fp16"}
354 !3 = !{!"cl_khr_gl_sharing"}
355 !4 = !{i32 10} ; Float64 - program uses doubles
356 !5 = !{i32 1, i32 2} ; 1 - 32-bit addressing model, 2 - OpenCL memory model
357 !6 = !{i32 6, TBD, !"kernel1", TBD}
358 !7 = !{i32 6, TBD, !"kernel2", TBD}
359 !8 = !{!6, i32 18, i32 16, i32 1, i32 1} ; local size hint <16, 1, 1> for 'kernel1'
360 !9 = !{!7, i32 32} ; independent forward progress is required for 'kernel2'
361 !10 = !{i16 6, i16 123} ; 6 - Generator Id, 123 - Generator Version
362
363 Additional requirements for LLVM module
364 =======================================
365
366 Target triple and datalayout string
367 -----------------------------------
368
369 Target triple architecture must be ``spir`` (32-bit architecture) or ``spir64``
370 (64-bit architecture) and ``datalayout`` string must be aligned with OpenCL
371 environment specification requirements for data type sizes and alignments (e.g.
372 3-element vector must have 4-element vector alignment). For example:
373
374 .. code-block:: llvm
375
376 target datalayout = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024"
377 target triple = "spir-unknown-unknown"
378
379 Target triple architecture is translated to
380 `addressing model operand <https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#_a_id_addressing_model_a_addressing_model>`_
381 of
382 `OpMemoryModel <https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#_a_id_mode_setting_a_mode_setting_instructions>`_
383 SPIR-V instruction.
384
385 - ``spir`` -> Physical32
386 - ``spir64`` -> Physical64
387
388 Calling convention
389 ------------------
390
391 ``OpEntryPoint`` information is represented in LLVM IR in calling convention.
392 A function with ``spir_kernel`` calling convention will be translated as an entry
393 point of the SPIR-V module.
394
395 Function metadata
396 -----------------
397
398 Some kernel parameter information is stored in LLVM IR as a function metadata.
399
400 For example:
401
402 .. code-block:: llvm
403
404 !kernel_arg_addr_space !1
405 !kernel_arg_access_qual !2
406 !kernel_arg_type !3
407 !kernel_arg_base_type !4
408 !kernel_arg_type_qual !5
409
410 **NOTE**: All metadata from the example above are optional. Access qualifiers
411 are translated for image types, but they should be encoded in LLVM IR type name
412 rather than function metadata.
413
414 Function parameter, instruction and global variable decoration through metadata
415 ------------------------------------------------------------------
416
417 Function parameters, instructions and global variables can be decorated using LLVM
418 metadata through the metadata names ``spirv.ParameterDecorations`` and
419 ``spirv.Decorations`` respectively. ``spirv.ParameterDecorations`` must be tied
420 to the kernel function while ``spirv.Decorations`` is tied directly to the
421 instruction or global variable.
422
423 A "decoration-node" is a metadata node consisting of one or more operands. The
424 first operand is an integer literal representing the SPIR-V decoration
425 identifier. The other operands are either an integer or string literal
426 representing the remaining extra operands of the corresponding SPIR-V
427 decoration.
428
429 A "decoration-list" is a metadata node consisting of references to zero or more
430 decoration-nodes.
431
432 ``spirv.Decorations`` must refer to a decoration-list while
433 ``spirv.ParameterDecorations`` must refer to a metadata node that contains N
434 references to decoration-lists, where N is the number of arguments of the
435 function the metadata is tied to.
436
437 ``spirv.Decorations`` applied on a global variable example:
438
439 .. code-block:: llvm
440
441 @v = global i32 0, !spirv.Decorations !1
442 ...
443 !1 = !{!2, !3} ; decoration-list with two decoration nodes
444 !2 = !{i32 22} ; decoration-node with no extra operands
445 !3 = !{i32 41, !"v", i32 0} ; decoration-node with 2 extra operands
446
447 decorates a global variable ``v`` with ``Constant`` and ``LinkageAttributes``
448 with extra operands ``"v"`` and ``Export`` in SPIR-V.
449
450 ``spirv.Decorations`` applied on an instruction example:
451
452 .. code-block:: llvm
453
454 %idx = getelementptr inbounds i32, ptr addrspace(1) %b, i64 1, !spirv.Decorations !1
455 ...
456 !1 = !{!2}
457 !2 = !{i32 6442, i32 1, i32 2} ; {CacheControlLoadINTEL, CacheLevel=1, Cached}
458
459 decorates getelementptr instruction with CacheControlLoadINTEL decoration with
460 extra operands ``i32 1`` and ``i32 2``.
461
462 ``spirv.ParameterDecorations`` example:
463
464 .. code-block:: llvm
465
466 define spir_kernel void @k(float %a, float %b) #0 !spirv.ParameterDecorations !1
467 ...
468 !1 = !{!2, !3} ; metadata node with 2 decoration-lists
469 !2 = !{} ; empty decoration-list
470 !3 = !{!4} ; decoration-list with one decoration node
471 !4 = !{i32 19} ; decoration-node with no extra operands
472
473 decorates the argument ``b`` of ``k`` with ``Restrict`` in SPIR-V while not
474 adding any decoration to argument ``a``.
475
476 Member decoration through pointer annotations
477 ---------------------------------------------
478
479 Class members can be decorated using the ``llvm.ptr.annotation`` LLVM IR
480 intrinsic. Member decorations specified in ``llvm.ptr.annotation`` must be in
481 the second argument and must have the format ``{X}`` or ``{X:Y}`` where ``X`` is
482 either one of the reserved names or an integer literal representing the SPIR-V
483 decoration identifier and ``Y`` is 1 or more arguments separated by ",", where
484 each argument must be either a word (including numbers) or a string enclosed by
485 quotation marks. The ``llvm.ptr.annotation`` can contain any number decorations
486 following this format.
487
488 For example, both ``{5835:1,2,3}`` and ``{bank_bits:1,2,3}`` will result in the
489 ``BankwidthINTEL`` decoration with literals 1, 2, and 3 attached to the
490 annotated member.
491
492 The translator accepts a number of reserved names that correspond to SPIR-V
493 member decorations.
494
495 +-----------------------+------------------+-----------------------------------+
496 | Decoration | Reserved Name | Note |
497 +=======================+==================+===================================+
498 | RegisterINTEL | register | Additional arguments are ignored, |
499 | | | but reverse translation will add |
500 | | | a 1 argument, i.e. |
501 | | | ``{register:1}``. |
502 +-----------------------+------------------+-----------------------------------+
503 | MemoryINTEL | memory | |
504 +-----------------------+------------------+-----------------------------------+
505 | NumbanksINTEL | numbanks | |
506 +-----------------------+------------------+-----------------------------------+
507 | BankwidthINTEL | bankwidth | |
508 +-----------------------+------------------+-----------------------------------+
509 | MaxPrivateCopiesINTEL | private_copies | |
510 +-----------------------+------------------+-----------------------------------+
511 | SinglepumpINTEL | pump | Reserved name is shared with |
512 | | | DoublepumpINTEL. SinglepumpINTEL |
513 | | | will be selected if the argument |
514 | | | is 2, i.e ``{pump:1}``. |
515 +-----------------------+------------------+-----------------------------------+
516 | DoublepumpINTEL | pump | Reserved name is shared with |
517 | | | SinglepumpINTEL. DoublepumpINTEL |
518 | | | will be selected if the argument |
519 | | | is 2, i.e ``{pump:2}``. |
520 +-----------------------+------------------+-----------------------------------+
521 | MaxReplicatesINTEL | max_replicates | |
522 +-----------------------+------------------+-----------------------------------+
523 | SimpleDualPortINTEL | simple_dual_port | Additional arguments are ignored, |
524 | | | but reverse translation will add |
525 | | | a 1 argument, i.e. |
526 | | | ``{simple_dual_port:1}``. |
527 +-----------------------+------------------+-----------------------------------+
528 | MergeINTEL | merge | Arguments of this are separated by|
529 | | | ":" rather than ",", i.e. |
530 | | | ``{merge:X:Y}``. |
531 +-----------------------+------------------+-----------------------------------+
532 | BankBitsINTEL | bank_bits | |
533 +-----------------------+------------------+-----------------------------------+
534 | ForcePow2DepthINTEL | force_pow2_depth | |
535 +-----------------------+------------------+-----------------------------------+
536
537 None of the special requirements imposed from using the reserved names apply to
538 using decoration identifiers directly.
539
540 During reverse translation, the translator prioritizes reserved names over
541 decoration identifiers, even if the member decoration was generated using the
542 corresponding decoration identifier. For example, this means that translating
543 ``{5825}`` to SPIR-V and back to LLVM IR will result in ``{register:1}`` being
544 in the annotation string argument instead of the initial value.
545
546 Debug information extension
547 ===========================
548
549 **TBD**