1#!/usr/bin/env python3
2
3# OpenCL built-in library: type conversion functions
4#
5# Copyright (c) 2013 Victor Oliveira <[email protected]>
6# Copyright (c) 2013 Jesse Towner <[email protected]>
7#
8# Permission is hereby granted, free of charge, to any person obtaining a copy
9# of this software and associated documentation files (the "Software"), to deal
10# in the Software without restriction, including without limitation the rights
11# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12# copies of the Software, and to permit persons to whom the Software is
13# furnished to do so, subject to the following conditions:
14#
15# The above copyright notice and this permission notice shall be included in
16# all copies or substantial portions of the Software.
17#
18# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24# THE SOFTWARE.
25
26# This script generates the file convert_type.cl, which contains all of the
27# OpenCL functions in the form:
28#
29# convert_<destTypen><_sat><_roundingMode>(<sourceTypen>)
30
31types = ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double']
32int_types = ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'long', 'ulong']
33unsigned_types = ['uchar', 'ushort', 'uint', 'ulong']
34float_types = ['float', 'double']
35int64_types = ['long', 'ulong']
36float64_types = ['double']
37vector_sizes = ['', '2', '3', '4', '8', '16']
38half_sizes = [('2',''), ('4','2'), ('8','4'), ('16','8')]
39
40saturation = ['','_sat']
41rounding_modes = ['_rtz','_rte','_rtp','_rtn']
42float_prefix = {'float':'FLT_', 'double':'DBL_'}
43float_suffix = {'float':'f', 'double':''}
44
45bool_type = {'char'  : 'char',
46             'uchar' : 'char',
47             'short' : 'short',
48             'ushort': 'short',
49             'int'   : 'int',
50             'uint'  : 'int',
51             'long'  : 'long',
52             'ulong' : 'long',
53             'float'  : 'int',
54             'double' : 'long'}
55
56unsigned_type = {'char'  : 'uchar',
57                 'uchar' : 'uchar',
58                 'short' : 'ushort',
59                 'ushort': 'ushort',
60                 'int'   : 'uint',
61                 'uint'  : 'uint',
62                 'long'  : 'ulong',
63                 'ulong' : 'ulong'}
64
65sizeof_type = {'char'  : 1, 'uchar'  : 1,
66               'short' : 2, 'ushort' : 2,
67               'int'   : 4, 'uint'   : 4,
68               'long'  : 8, 'ulong'  : 8,
69               'float' : 4, 'double' : 8}
70
71limit_max = {'char'  : 'CHAR_MAX',
72             'uchar' : 'UCHAR_MAX',
73             'short' : 'SHRT_MAX',
74             'ushort': 'USHRT_MAX',
75             'int'   : 'INT_MAX',
76             'uint'  : 'UINT_MAX',
77             'long'  : 'LONG_MAX',
78             'ulong' : 'ULONG_MAX'}
79
80limit_min = {'char'  : 'CHAR_MIN',
81             'uchar' : '0',
82             'short' : 'SHRT_MIN',
83             'ushort': '0',
84             'int'   : 'INT_MIN',
85             'uint'  : '0',
86             'long'  : 'LONG_MIN',
87             'ulong' : '0'}
88
89def conditional_guard(src, dst):
90  int64_count = 0
91  float64_count = 0
92  if src in int64_types:
93    int64_count = int64_count +1
94  elif src in float64_types:
95    float64_count = float64_count + 1
96  if dst in int64_types:
97    int64_count = int64_count +1
98  elif dst in float64_types:
99    float64_count = float64_count + 1
100  if float64_count > 0 and int64_count > 0:
101    print("#if defined(cl_khr_fp64) && defined(cles_khr_int64)")
102    return True
103  elif float64_count > 0:
104    print("#ifdef cl_khr_fp64")
105    return True
106  elif int64_count > 0:
107    print("#ifdef cles_khr_int64")
108    return True
109  return False
110
111
112print("""/* !!!! AUTOGENERATED FILE generated by convert_type.py !!!!!
113
114   DON'T CHANGE THIS FILE. MAKE YOUR CHANGES TO convert_type.py AND RUN:
115   $ ./generate-conversion-type-cl.sh
116
117   OpenCL type conversion functions
118
119   Copyright (c) 2013 Victor Oliveira <[email protected]>
120   Copyright (c) 2013 Jesse Towner <[email protected]>
121
122   Permission is hereby granted, free of charge, to any person obtaining a copy
123   of this software and associated documentation files (the "Software"), to deal
124   in the Software without restriction, including without limitation the rights
125   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
126   copies of the Software, and to permit persons to whom the Software is
127   furnished to do so, subject to the following conditions:
128
129   The above copyright notice and this permission notice shall be included in
130   all copies or substantial portions of the Software.
131
132   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
133   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
134   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
135   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
136   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
137   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
138   THE SOFTWARE.
139*/
140
141#include <clc/clc.h>
142
143#ifdef cl_khr_fp64
144#pragma OPENCL EXTENSION cl_khr_fp64 : enable
145#endif
146
147""")
148
149#
150# Default Conversions
151#
152# All conversions are in accordance with the OpenCL specification,
153# which cites the C99 conversion rules.
154#
155# Casting from floating point to integer results in conversions
156# with truncation, so it should be suitable for the default convert
157# functions.
158#
159# Conversions from integer to floating-point, and floating-point to
160# floating-point through casting is done with the default rounding
161# mode. While C99 allows dynamically changing the rounding mode
162# during runtime, it is not a supported feature in OpenCL according
163# to Section 7.1 - Rounding Modes in the OpenCL 1.2 specification.
164#
165# Therefore, we can assume for optimization purposes that the
166# rounding mode is fixed to round-to-nearest-even. Platform target
167# authors should ensure that the rounding-control registers remain
168# in this state, and that this invariant holds.
169#
170# Also note, even though the OpenCL specification isn't entirely
171# clear on this matter, we implement all rounding mode combinations
172# even for integer-to-integer conversions. When such a conversion
173# is used, the rounding mode is ignored.
174#
175
176def generate_default_conversion(src, dst, mode):
177  close_conditional = conditional_guard(src, dst)
178
179  # scalar conversions
180  print("""_CLC_DEF _CLC_OVERLOAD
181{DST} convert_{DST}{M}({SRC} x)
182{{
183  return ({DST})x;
184}}
185""".format(SRC=src, DST=dst, M=mode))
186
187  # vector conversions, done through decomposition to components
188  for size, half_size in half_sizes:
189    print("""_CLC_DEF _CLC_OVERLOAD
190{DST}{N} convert_{DST}{N}{M}({SRC}{N} x)
191{{
192  return ({DST}{N})(convert_{DST}{H}(x.lo), convert_{DST}{H}(x.hi));
193}}
194""".format(SRC=src, DST=dst, N=size, H=half_size, M=mode))
195
196  # 3-component vector conversions
197  print("""_CLC_DEF _CLC_OVERLOAD
198{DST}3 convert_{DST}3{M}({SRC}3 x)
199{{
200  return ({DST}3)(convert_{DST}2(x.s01), convert_{DST}(x.s2));
201}}""".format(SRC=src, DST=dst, M=mode))
202
203  if close_conditional:
204    print("#endif")
205
206
207for src in types:
208  for dst in types:
209    generate_default_conversion(src, dst, '')
210
211for src in int_types:
212  for dst in int_types:
213    for mode in rounding_modes:
214      generate_default_conversion(src, dst, mode)
215
216#
217# Saturated Conversions To Integers
218#
219# These functions are dependent on the unsaturated conversion functions
220# generated above, and use clamp, max, min, and select to eliminate
221# branching and vectorize the conversions.
222#
223# Again, as above, we allow all rounding modes for integer-to-integer
224# conversions with saturation.
225#
226
227def generate_saturated_conversion(src, dst, size):
228  # Header
229  close_conditional = conditional_guard(src, dst)
230  print("""_CLC_DEF _CLC_OVERLOAD
231{DST}{N} convert_{DST}{N}_sat({SRC}{N} x)
232{{""".format(DST=dst, SRC=src, N=size))
233
234  # FIXME: This is a work around for lack of select function with
235  # signed third argument when the first two arguments are unsigned types.
236  # We cast to the signed type for sign-extension, then do a bitcast to
237  # the unsigned type.
238  if dst in unsigned_types:
239    bool_prefix = "as_{DST}{N}(convert_{BOOL}{N}".format(DST=dst, BOOL=bool_type[dst], N=size);
240    bool_suffix = ")"
241  else:
242    bool_prefix = "convert_{BOOL}{N}".format(BOOL=bool_type[dst], N=size);
243    bool_suffix = ""
244
245  # Body
246  if src == dst:
247
248    # Conversion between same types
249    print("  return x;")
250
251  elif src in float_types:
252
253    # Conversion from float to int
254    print("""  {DST}{N} y = convert_{DST}{N}(x);
255  y = select(y, ({DST}{N}){DST_MIN}, {BP}(x < ({SRC}{N}){DST_MIN}){BS});
256  y = select(y, ({DST}{N}){DST_MAX}, {BP}(x > ({SRC}{N}){DST_MAX}){BS});
257  return y;""".format(SRC=src, DST=dst, N=size,
258      DST_MIN=limit_min[dst], DST_MAX=limit_max[dst],
259      BP=bool_prefix, BS=bool_suffix))
260
261  else:
262
263    # Integer to integer convesion with sizeof(src) == sizeof(dst)
264    if sizeof_type[src] == sizeof_type[dst]:
265      if src in unsigned_types:
266        print("  x = min(x, ({SRC}){DST_MAX});".format(SRC=src, DST_MAX=limit_max[dst]))
267      else:
268        print("  x = max(x, ({SRC})0);".format(SRC=src))
269
270    # Integer to integer conversion where sizeof(src) > sizeof(dst)
271    elif sizeof_type[src] > sizeof_type[dst]:
272      if src in unsigned_types:
273        print("  x = min(x, ({SRC}){DST_MAX});".format(SRC=src, DST_MAX=limit_max[dst]))
274      else:
275        print("  x = clamp(x, ({SRC}){DST_MIN}, ({SRC}){DST_MAX});"
276          .format(SRC=src, DST_MIN=limit_min[dst], DST_MAX=limit_max[dst]))
277
278    # Integer to integer conversion where sizeof(src) < sizeof(dst)
279    elif src not in unsigned_types and dst in unsigned_types:
280        print("  x = max(x, ({SRC})0);".format(SRC=src))
281
282    print("  return convert_{DST}{N}(x);".format(DST=dst, N=size))
283
284  # Footer
285  print("}")
286  if close_conditional:
287    print("#endif")
288
289
290for src in types:
291  for dst in int_types:
292    for size in vector_sizes:
293      generate_saturated_conversion(src, dst, size)
294
295
296def generate_saturated_conversion_with_rounding(src, dst, size, mode):
297  # Header
298  close_conditional = conditional_guard(src, dst)
299
300  # Body
301  print("""_CLC_DEF _CLC_OVERLOAD
302{DST}{N} convert_{DST}{N}_sat{M}({SRC}{N} x)
303{{
304  return convert_{DST}{N}_sat(x);
305}}
306""".format(DST=dst, SRC=src, N=size, M=mode))
307
308  # Footer
309  if close_conditional:
310    print("#endif")
311
312
313for src in int_types:
314  for dst in int_types:
315    for size in vector_sizes:
316      for mode in rounding_modes:
317        generate_saturated_conversion_with_rounding(src, dst, size, mode)
318
319#
320# Conversions To/From Floating-Point With Rounding
321#
322# Note that we assume as above that casts from floating-point to
323# integer are done with truncation, and that the default rounding
324# mode is fixed to round-to-nearest-even, as per C99 and OpenCL
325# rounding rules.
326#
327# These functions rely on the use of abs, ceil, fabs, floor,
328# nextafter, sign, rint and the above generated conversion functions.
329#
330# Only conversions to integers can have saturation.
331#
332
333def generate_float_conversion(src, dst, size, mode, sat):
334  # Header
335  close_conditional = conditional_guard(src, dst)
336  print("""_CLC_DEF _CLC_OVERLOAD
337{DST}{N} convert_{DST}{N}{S}{M}({SRC}{N} x)
338{{""".format(SRC=src, DST=dst, N=size, M=mode, S=sat))
339
340  # Perform conversion
341  if dst in int_types:
342    if mode == '_rte':
343      print("  x = rint(x);");
344    elif mode == '_rtp':
345      print("  x = ceil(x);");
346    elif mode == '_rtn':
347      print("  x = floor(x);");
348    print("  return convert_{DST}{N}{S}(x);".format(DST=dst, N=size, S=sat))
349  elif mode == '_rte':
350    print("  return convert_{DST}{N}(x);".format(DST=dst, N=size))
351  else:
352    print("  {DST}{N} r = convert_{DST}{N}(x);".format(DST=dst, N=size))
353    print("  {SRC}{N} y = convert_{SRC}{N}(y);".format(SRC=src, N=size))
354    if mode == '_rtz':
355      if src in int_types:
356        print("  {USRC}{N} abs_x = abs(x);".format(USRC=unsigned_type[src], N=size))
357        print("  {USRC}{N} abs_y = abs(y);".format(USRC=unsigned_type[src], N=size))
358      else:
359        print("  {SRC}{N} abs_x = fabs(x);".format(SRC=src, N=size))
360        print("  {SRC}{N} abs_y = fabs(y);".format(SRC=src, N=size))
361      print("  return select(r, nextafter(r, sign(r) * ({DST}{N})-INFINITY), convert_{BOOL}{N}(abs_y > abs_x));"
362        .format(DST=dst, N=size, BOOL=bool_type[dst]))
363    if mode == '_rtp':
364      print("  return select(r, nextafter(r, ({DST}{N})INFINITY), convert_{BOOL}{N}(y < x));"
365        .format(DST=dst, N=size, BOOL=bool_type[dst]))
366    if mode == '_rtn':
367      print("  return select(r, nextafter(r, ({DST}{N})-INFINITY), convert_{BOOL}{N}(y > x));"
368        .format(DST=dst, N=size, BOOL=bool_type[dst]))
369
370  # Footer
371  print("}")
372  if close_conditional:
373    print("#endif")
374
375
376for src in float_types:
377  for dst in int_types:
378    for size in vector_sizes:
379      for mode in rounding_modes:
380        for sat in saturation:
381          generate_float_conversion(src, dst, size, mode, sat)
382
383
384for src in types:
385  for dst in float_types:
386    for size in vector_sizes:
387      for mode in rounding_modes:
388        generate_float_conversion(src, dst, size, mode, '')
389