[SampleProfileLoader] Fix integer overflow in generateMDProfMetadata (#90217)
[llvm-project.git] / libclc / generic / lib / integer / add_sat.cl
blob252dce9775bfaff8699b5829ba4803c3d2978225
1 #include <clc/clc.h>
2 #include "../clcmacro.h"
4 // From add_sat.ll
5 _CLC_DECL char __clc_add_sat_s8(char, char);
6 _CLC_DECL uchar __clc_add_sat_u8(uchar, uchar);
7 _CLC_DECL short __clc_add_sat_s16(short, short);
8 _CLC_DECL ushort __clc_add_sat_u16(ushort, ushort);
9 _CLC_DECL int __clc_add_sat_s32(int, int);
10 _CLC_DECL uint __clc_add_sat_u32(uint, uint);
11 _CLC_DECL long __clc_add_sat_s64(long, long);
12 _CLC_DECL ulong __clc_add_sat_u64(ulong, ulong);
14 _CLC_OVERLOAD _CLC_DEF char add_sat(char x, char y) {
15 short r = x + y;
16 return convert_char_sat(r);
19 _CLC_OVERLOAD _CLC_DEF uchar add_sat(uchar x, uchar y) {
20 ushort r = x + y;
21 return convert_uchar_sat(r);
24 _CLC_OVERLOAD _CLC_DEF short add_sat(short x, short y) {
25 int r = x + y;
26 return convert_short_sat(r);
29 _CLC_OVERLOAD _CLC_DEF ushort add_sat(ushort x, ushort y) {
30 uint r = x + y;
31 return convert_ushort_sat(r);
34 _CLC_OVERLOAD _CLC_DEF int add_sat(int x, int y) {
35 int r;
36 if (__builtin_sadd_overflow(x, y, &r))
37 // The oveflow can only occur if both are pos or both are neg,
38 // thus we only need to check one operand
39 return x > 0 ? INT_MAX : INT_MIN;
40 return r;
43 _CLC_OVERLOAD _CLC_DEF uint add_sat(uint x, uint y) {
44 uint r;
45 if (__builtin_uadd_overflow(x, y, &r))
46 return UINT_MAX;
47 return r;
50 _CLC_OVERLOAD _CLC_DEF long add_sat(long x, long y) {
51 long r;
52 if (__builtin_saddl_overflow(x, y, &r))
53 // The oveflow can only occur if both are pos or both are neg,
54 // thus we only need to check one operand
55 return x > 0 ? LONG_MAX : LONG_MIN;
56 return r;
59 _CLC_OVERLOAD _CLC_DEF ulong add_sat(ulong x, ulong y) {
60 ulong r;
61 if (__builtin_uaddl_overflow(x, y, &r))
62 return ULONG_MAX;
63 return r;
66 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, char, add_sat, char, char)
67 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, uchar, add_sat, uchar, uchar)
68 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, short, add_sat, short, short)
69 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, ushort, add_sat, ushort, ushort)
70 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, int, add_sat, int, int)
71 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, uint, add_sat, uint, uint)
72 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, long, add_sat, long, long)
73 _CLC_BINARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, ulong, add_sat, ulong, ulong)