]> git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.cpp
ir: more aggressively reuse const floats
[xonotic/gmqcc.git] / fold.cpp
1 #include <string.h>
2 #include <math.h>
3
4 #include "fold.h"
5 #include "ast.h"
6 #include "ir.h"
7
8 #include "parser.h"
9
10 #define FOLD_STRING_UNTRANSLATE_HTSIZE 1024
11 #define FOLD_STRING_DOTRANSLATE_HTSIZE 1024
12
13 /* The options to use for inexact and arithmetic exceptions */
14 #define FOLD_ROUNDING SFLOAT_ROUND_NEAREST_EVEN
15 #define FOLD_TINYNESS SFLOAT_TBEFORE
16
17 /*
18  * Comparing float values is an unsafe operation when the operands to the
19  * comparison are floating point values that are inexact. For instance 1/3 is an
20  * inexact value. The FPU is meant to raise exceptions when these sorts of things
21  * happen, including division by zero, underflows and overflows. The C standard
22  * library provides us with the <fenv.h> header to gain access to the floating-
23  * point environment and lets us set the rounding mode and check for these exceptions.
24  * The problem is the standard C library allows an implementation to leave these
25  * stubbed out and does not require they be implemented. Furthermore, depending
26  * on implementations there is no control over the FPU. This is an IEE 754
27  * conforming implementation in software to compensate.
28  */
29 typedef uint32_t sfloat_t;
30
31 union sfloat_cast_t {
32     qcfloat_t f;
33     sfloat_t s;
34 };
35
36 /* Exception flags */
37 enum sfloat_exceptionflags_t {
38     SFLOAT_NOEXCEPT  = 0,
39     SFLOAT_INVALID   = 1,
40     SFLOAT_DIVBYZERO = 4,
41     SFLOAT_OVERFLOW  = 8,
42     SFLOAT_UNDERFLOW = 16,
43     SFLOAT_INEXACT   = 32
44 };
45
46 /* Rounding modes */
47 enum sfloat_roundingmode_t {
48     SFLOAT_ROUND_NEAREST_EVEN,
49     SFLOAT_ROUND_DOWN,
50     SFLOAT_ROUND_UP,
51     SFLOAT_ROUND_TO_ZERO
52 };
53
54 /* Underflow tininess-detection mode */
55 enum sfloat_tdetect_t {
56     SFLOAT_TAFTER,
57     SFLOAT_TBEFORE
58 };
59
60 struct sfloat_state_t {
61     sfloat_roundingmode_t roundingmode;
62     sfloat_exceptionflags_t exceptionflags;
63     sfloat_tdetect_t tiny;
64 };
65
66 /* Counts the number of leading zero bits before the most-significand one bit. */
67 #ifdef _MSC_VER
68 /* MSVC has an intrinsic for this */
69     static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
70         int r = 0;
71         _BitScanForward(&r, x);
72         return r;
73     }
74 #   define SFLOAT_CLZ(X, SUB) \
75         (sfloat_clz((X)) - (SUB))
76 #elif defined(__GNUC__) || defined(__CLANG__)
77 /* Clang and GCC have a builtin for this */
78 #   define SFLOAT_CLZ(X, SUB) \
79         (__builtin_clz((X)) - (SUB))
80 #else
81 /* Native fallback */
82     static GMQCC_INLINE uint32_t sfloat_popcnt(uint32_t x) {
83         x -= ((x >> 1) & 0x55555555);
84         x  = (((x >> 2) & 0x33333333) + (x & 0x33333333));
85         x  = (((x >> 4) + x) & 0x0F0F0F0F);
86         x += x >> 8;
87         x += x >> 16;
88         return x & 0x0000003F;
89     }
90     static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
91         x |= (x >> 1);
92         x |= (x >> 2);
93         x |= (x >> 4);
94         x |= (x >> 8);
95         x |= (x >> 16);
96         return 32 - sfloat_popcnt(x);
97     }
98 #   define SFLOAT_CLZ(X, SUB) \
99         (sfloat_clz((X) - (SUB)))
100 #endif
101
102 /* The value of a NaN */
103 #define SFLOAT_NAN 0xFFFFFFFF
104 /* Test if NaN */
105 #define SFLOAT_ISNAN(A) \
106     (0xFF000000 < (uint32_t)((A) << 1))
107 /* Test if signaling NaN */
108 #define SFLOAT_ISSNAN(A) \
109     (((((A) >> 22) & 0x1FF) == 0x1FE) && ((A) & 0x003FFFFF))
110 /* Raise exception */
111 #define SFLOAT_RAISE(STATE, FLAGS) \
112     ((STATE)->exceptionflags = (sfloat_exceptionflags_t)((STATE)->exceptionflags | (FLAGS)))
113 /*
114  * Shifts `A' right by the number of bits given in `COUNT'. If any non-zero bits
115  * are shifted off they are forced into the least significand bit of the result
116  * by setting it to one. As a result of this, the value of `COUNT' can be
117  * arbitrarily large; if `COUNT' is greater than 32, the result will be either
118  * zero or one, depending on whether `A' is a zero or non-zero. The result is
119  * stored into the value pointed by `Z'.
120  */
121 #define SFLOAT_SHIFT(SIZE, A, COUNT, Z)                                      \
122     *(Z) = ((COUNT) == 0)                                                    \
123         ? 1                                                                  \
124         : (((COUNT) < (SIZE))                                                \
125             ? ((A) >> (COUNT)) | (((A) << ((-(COUNT)) & ((SIZE) - 1))) != 0) \
126             : ((A) != 0))
127
128 /* Extract fractional component */
129 #define SFLOAT_EXTRACT_FRAC(X) \
130     ((uint32_t)((X) & 0x007FFFFF))
131 /* Extract exponent component */
132 #define SFLOAT_EXTRACT_EXP(X) \
133     ((int16_t)((X) >> 23) & 0xFF)
134 /* Extract sign bit */
135 #define SFLOAT_EXTRACT_SIGN(X) \
136     ((X) >> 31)
137 /*
138  * Normalizes the subnormal value represented by the denormalized significand
139  * `SA'. The normalized exponent and significand are stored at the locations
140  * pointed by `Z' and `SZ' respectively.
141  */
142 #define SFLOAT_SUBNORMALIZE(SA, Z, SZ) \
143     (void)(*(SZ) = (SA) << SFLOAT_CLZ((SA), 8), *(Z) = 1 - SFLOAT_CLZ((SA), 8))
144 /*
145  * Packs the sign `SIGN', exponent `EXP' and significand `SIG' into the value
146  * giving the result.
147  *
148  * After the shifting into their proper positions, the fields are added together
149  * to form the result. This means any integer portion of `SIG' will be added
150  * to the exponent. Similarly, because a properly normalized significand will
151  * always have an integer portion equal to one, the exponent input `EXP' should
152  * be one less than the desired result exponent whenever the significant input
153  * `SIG' is a complete, normalized significand.
154  */
155 #define SFLOAT_PACK(SIGN, EXP, SIG) \
156     (sfloat_t)((((uint32_t)(SIGN)) << 31) + (((uint32_t)(EXP)) << 23) + (SIG))
157
158 /*
159  * Takes two values `a' and `b', one of which is a NaN, and returns the appropriate
160  * NaN result. If either `a' or `b' is a signaling NaN than an invalid exception is
161  * raised.
162  */
163 static sfloat_t sfloat_propagate_nan(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
164     bool isnan_a  = SFLOAT_ISNAN(a);
165     bool issnan_a = SFLOAT_ISSNAN(a);
166     bool isnan_b  = SFLOAT_ISNAN(b);
167     bool issnan_b = SFLOAT_ISSNAN(b);
168
169     a |= 0x00400000;
170     b |= 0x00400000;
171
172     if (issnan_a | issnan_b)
173         SFLOAT_RAISE(state, SFLOAT_INVALID);
174     if (isnan_a)
175         return (issnan_a & isnan_b) ? b : a;
176     return b;
177 }
178
179 /*
180  * Takes an abstract value having sign `sign_z', exponent `exp_z', and significand
181  * `sig_z' and returns the appropriate value corresponding to the abstract input.
182  *
183  * The abstract value is simply rounded and packed into the format. If the abstract
184  * input cannot be represented exactly an inexact exception is raised. If the
185  * abstract input is too large, the overflow and inexact exceptions are both raised
186  * and an infinity or maximal finite value is returned. If the abstract value is
187  * too small, the value is rounded to a subnormal and the underflow and inexact
188  * exceptions are only raised if the value cannot be represented exactly with
189  * a subnormal.
190  *
191  * The input significand `sig_z' has it's binary point between bits 30 and 29,
192  * this is seven bits to the left of its usual location. The shifted significand
193  * must be normalized or smaller than this. If it's not normalized then the exponent
194  * `exp_z' must be zero; in that case, the result returned is a subnormal number
195  * which must not require rounding. In the more usual case where the significand
196  * is normalized, the exponent must be one less than the *true* exponent.
197  *
198  * The handling of underflow and overflow is otherwise in alignment with IEC/IEEE.
199  */
200 static sfloat_t SFLOAT_PACK_round(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
201     sfloat_roundingmode_t mode      = state->roundingmode;
202     bool                  even      = !!(mode == SFLOAT_ROUND_NEAREST_EVEN);
203     unsigned char         increment = 0x40;
204     unsigned char         bits      = sig_z & 0x7F;
205
206     if (!even) {
207         if (mode == SFLOAT_ROUND_TO_ZERO)
208             increment = 0;
209         else {
210             increment = 0x7F;
211             if (sign_z) {
212                 if (mode == SFLOAT_ROUND_UP)
213                     increment = 0;
214             } else {
215                 if (mode == SFLOAT_ROUND_DOWN)
216                     increment = 0;
217             }
218         }
219     }
220
221     if (0xFD <= (uint16_t)exp_z) {
222         if ((0xFD < exp_z) || ((exp_z == 0xFD) && ((int32_t)(sig_z + increment) < 0))) {
223             SFLOAT_RAISE(state, SFLOAT_OVERFLOW | SFLOAT_INEXACT);
224             return SFLOAT_PACK(sign_z, 0xFF, 0) - (increment == 0);
225         }
226         if (exp_z < 0) {
227             /* Check for underflow */
228             bool tiny = (state->tiny == SFLOAT_TBEFORE) || (exp_z < -1) || (sig_z + increment < 0x80000000);
229             SFLOAT_SHIFT(32, sig_z, -exp_z, &sig_z);
230             exp_z = 0;
231             bits = sig_z & 0x7F;
232             if (tiny && bits)
233                 SFLOAT_RAISE(state, SFLOAT_UNDERFLOW);
234         }
235     }
236     if (bits)
237         SFLOAT_RAISE(state, SFLOAT_INEXACT);
238     sig_z = (sig_z + increment) >> 7;
239     sig_z &= ~(((bits ^ 0x40) == 0) & even);
240     if (sig_z == 0)
241         exp_z = 0;
242     return SFLOAT_PACK(sign_z, exp_z, sig_z);
243 }
244
245 /*
246  * Takes an abstract value having sign `sign_z', exponent `exp_z' and significand
247  * `sig_z' and returns the appropriate value corresponding to the abstract input.
248  * This function is exactly like `PACK_round' except the significand does not have
249  * to be normalized.
250  *
251  * Bit 31 of the significand must be zero and the exponent must be one less than
252  * the *true* exponent.
253  */
254 static sfloat_t SFLOAT_PACK_normal(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
255     unsigned char c = SFLOAT_CLZ(sig_z, 1);
256     return SFLOAT_PACK_round(state, sign_z, exp_z - c, sig_z << c);
257 }
258
259 /*
260  * Returns the result of adding the absolute values of `a' and `b'. The sign
261  * `sign_z' is ignored if the result is a NaN.
262  */
263 static sfloat_t sfloat_add_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
264     int16_t  exp_a = SFLOAT_EXTRACT_EXP(a);
265     int16_t  exp_b = SFLOAT_EXTRACT_EXP(b);
266     int16_t  exp_z = 0;
267     int16_t  exp_d = exp_a - exp_b;
268     uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 6;
269     uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 6;
270     uint32_t sig_z = 0;
271
272     if (0 < exp_d) {
273         if (exp_a == 0xFF)
274             return sig_a ? sfloat_propagate_nan(state, a, b) : a;
275         if (exp_b == 0)
276             --exp_d;
277         else
278             sig_b |= 0x20000000;
279         SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
280         exp_z = exp_a;
281     } else if (exp_d < 0) {
282         if (exp_b == 0xFF)
283             return sig_b ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0xFF, 0);
284         if (exp_a == 0)
285             ++exp_d;
286         else
287             sig_a |= 0x20000000;
288         SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
289         exp_z = exp_b;
290     } else {
291         if (exp_a == 0xFF)
292             return (sig_a | sig_b) ? sfloat_propagate_nan(state, a, b) : a;
293         if (exp_a == 0)
294             return SFLOAT_PACK(sign_z, 0, (sig_a + sig_b) >> 6);
295         sig_z = 0x40000000 + sig_a + sig_b;
296         exp_z = exp_a;
297         goto end;
298     }
299     sig_a |= 0x20000000;
300     sig_z = (sig_a + sig_b) << 1;
301     --exp_z;
302     if ((int32_t)sig_z < 0) {
303         sig_z = sig_a + sig_b;
304         ++exp_z;
305     }
306 end:
307     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
308 }
309
310 /*
311  * Returns the result of subtracting the absolute values of `a' and `b'. If the
312  * sign `sign_z' is one, the difference is negated before being returned. The
313  * sign is ignored if the result is a NaN.
314  */
315 static sfloat_t sfloat_sub_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
316     int16_t  exp_a = SFLOAT_EXTRACT_EXP(a);
317     int16_t  exp_b = SFLOAT_EXTRACT_EXP(b);
318     int16_t  exp_z = 0;
319     int16_t  exp_d = exp_a - exp_b;
320     uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 7;
321     uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 7;
322     uint32_t sig_z = 0;
323
324     if (0 < exp_d) goto exp_greater_a;
325     if (exp_d < 0) goto exp_greater_b;
326
327     if (exp_a == 0xFF) {
328         if (sig_a | sig_b)
329             return sfloat_propagate_nan(state, a, b);
330         SFLOAT_RAISE(state, SFLOAT_INVALID);
331         return SFLOAT_NAN;
332     }
333
334     if (exp_a == 0)
335         exp_a = exp_b = 1;
336
337     if (sig_b < sig_a) goto greater_a;
338     if (sig_a < sig_b) goto greater_b;
339
340     return SFLOAT_PACK(state->roundingmode == SFLOAT_ROUND_DOWN, 0, 0);
341
342 exp_greater_b:
343     if (exp_b == 0xFF)
344         return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z ^ 1, 0xFF, 0);
345     if (exp_a == 0)
346         ++exp_d;
347     else
348         sig_a |= 0x40000000;
349     SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
350     sig_b |= 0x40000000;
351 greater_b:
352     sig_z = sig_b - sig_a;
353     exp_z = exp_b;
354     sign_z ^= 1;
355     goto end;
356
357 exp_greater_a:
358     if (exp_a == 0xFF)
359         return (sig_a) ? sfloat_propagate_nan(state, a, b) : a;
360     if (exp_b == 0)
361         --exp_d;
362     else
363         sig_b |= 0x40000000;
364     SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
365     sig_a |= 0x40000000;
366 greater_a:
367     sig_z = sig_a - sig_b;
368     exp_z = exp_a;
369
370 end:
371     --exp_z;
372     return SFLOAT_PACK_normal(state, sign_z, exp_z, sig_z);
373 }
374
375 static GMQCC_INLINE sfloat_t sfloat_add(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
376     bool sign_a = SFLOAT_EXTRACT_SIGN(a);
377     bool sign_b = SFLOAT_EXTRACT_SIGN(b);
378     return (sign_a == sign_b) ? sfloat_add_impl(state, a, b, sign_a)
379                               : sfloat_sub_impl(state, a, b, sign_a);
380 }
381
382 static GMQCC_INLINE sfloat_t sfloat_sub(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
383     bool sign_a = SFLOAT_EXTRACT_SIGN(a);
384     bool sign_b = SFLOAT_EXTRACT_SIGN(b);
385     return (sign_a == sign_b) ? sfloat_sub_impl(state, a, b, sign_a)
386                               : sfloat_add_impl(state, a, b, sign_a);
387 }
388
389 static sfloat_t sfloat_mul(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
390     int16_t  exp_a   = SFLOAT_EXTRACT_EXP(a);
391     int16_t  exp_b   = SFLOAT_EXTRACT_EXP(b);
392     int16_t  exp_z   = 0;
393     uint32_t sig_a   = SFLOAT_EXTRACT_FRAC(a);
394     uint32_t sig_b   = SFLOAT_EXTRACT_FRAC(b);
395     uint32_t sig_z   = 0;
396     uint64_t sig_z64 = 0;
397     bool     sign_a  = SFLOAT_EXTRACT_SIGN(a);
398     bool     sign_b  = SFLOAT_EXTRACT_SIGN(b);
399     bool     sign_z  = sign_a ^ sign_b;
400
401     if (exp_a == 0xFF) {
402         if (sig_a || ((exp_b == 0xFF) && sig_b))
403             return sfloat_propagate_nan(state, a, b);
404         if ((exp_b | sig_b) == 0) {
405             SFLOAT_RAISE(state, SFLOAT_INVALID);
406             return SFLOAT_NAN;
407         }
408         return SFLOAT_PACK(sign_z, 0xFF, 0);
409     }
410     if (exp_b == 0xFF) {
411         if (sig_b)
412             return sfloat_propagate_nan(state, a, b);
413         if ((exp_a | sig_a) == 0) {
414             SFLOAT_RAISE(state, SFLOAT_INVALID);
415             return SFLOAT_NAN;
416         }
417         return SFLOAT_PACK(sign_z, 0xFF, 0);
418     }
419     if (exp_a == 0) {
420         if (sig_a == 0)
421             return SFLOAT_PACK(sign_z, 0, 0);
422         SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
423     }
424     if (exp_b == 0) {
425         if (sig_b == 0)
426             return SFLOAT_PACK(sign_z, 0, 0);
427         SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
428     }
429     exp_z = exp_a + exp_b - 0x7F;
430     sig_a = (sig_a | 0x00800000) << 7;
431     sig_b = (sig_b | 0x00800000) << 8;
432     SFLOAT_SHIFT(64, ((uint64_t)sig_a) * sig_b, 32, &sig_z64);
433     sig_z = sig_z64;
434     if (0 <= (int32_t)(sig_z << 1)) {
435         sig_z <<= 1;
436         --exp_z;
437     }
438     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
439 }
440
441 static sfloat_t sfloat_div(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
442     int16_t  exp_a   = SFLOAT_EXTRACT_EXP(a);
443     int16_t  exp_b   = SFLOAT_EXTRACT_EXP(b);
444     int16_t  exp_z   = 0;
445     uint32_t sig_a   = SFLOAT_EXTRACT_FRAC(a);
446     uint32_t sig_b   = SFLOAT_EXTRACT_FRAC(b);
447     uint32_t sig_z   = 0;
448     bool     sign_a  = SFLOAT_EXTRACT_SIGN(a);
449     bool     sign_b  = SFLOAT_EXTRACT_SIGN(b);
450     bool     sign_z  = sign_a ^ sign_b;
451
452     if (exp_a == 0xFF) {
453         if (sig_a)
454             return sfloat_propagate_nan(state, a, b);
455         if (exp_b == 0xFF) {
456             if (sig_b)
457                 return sfloat_propagate_nan(state, a, b);
458             SFLOAT_RAISE(state, SFLOAT_INVALID);
459             return SFLOAT_NAN;
460         }
461         return SFLOAT_PACK(sign_z, 0xFF, 0);
462     }
463     if (exp_b == 0xFF)
464         return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0, 0);
465     if (exp_b == 0) {
466         if (sig_b == 0) {
467             if ((exp_a | sig_a) == 0) {
468                 SFLOAT_RAISE(state, SFLOAT_INVALID);
469                 return SFLOAT_NAN;
470             }
471             SFLOAT_RAISE(state, SFLOAT_DIVBYZERO);
472             return SFLOAT_PACK(sign_z, 0xFF, 0);
473         }
474         SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
475     }
476     if (exp_a == 0) {
477         if (sig_a == 0)
478             return SFLOAT_PACK(sign_z, 0, 0);
479         SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
480     }
481     exp_z = exp_a - exp_b + 0x7D;
482     sig_a = (sig_a | 0x00800000) << 7;
483     sig_b = (sig_b | 0x00800000) << 8;
484     if (sig_b <= (sig_a + sig_a)) {
485         sig_a >>= 1;
486         ++exp_z;
487     }
488     sig_z = (((uint64_t)sig_a) << 32) / sig_b;
489     if ((sig_z & 0x3F) == 0)
490         sig_z |= ((uint64_t)sig_b * sig_z != ((uint64_t)sig_a) << 32);
491     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
492 }
493
494 static sfloat_t sfloat_neg(sfloat_state_t *state, sfloat_t a) {
495     sfloat_cast_t neg;
496     neg.f = -1;
497     return sfloat_mul(state, a, neg.s);
498 }
499
500 static GMQCC_INLINE void sfloat_check(lex_ctx_t ctx, sfloat_state_t *state, const char *vec) {
501     /* Exception comes from vector component */
502     if (vec) {
503         if (state->exceptionflags & SFLOAT_DIVBYZERO)
504             compile_error(ctx, "division by zero in `%s' component", vec);
505         if (state->exceptionflags & SFLOAT_INVALID)
506             compile_error(ctx, "undefined (inf) in `%s' component", vec);
507         if (state->exceptionflags & SFLOAT_OVERFLOW)
508             compile_error(ctx, "arithmetic overflow in `%s' component", vec);
509         if (state->exceptionflags & SFLOAT_UNDERFLOW)
510             compile_error(ctx, "arithmetic underflow in `%s' component", vec);
511         return;
512     }
513     if (state->exceptionflags & SFLOAT_DIVBYZERO)
514         compile_error(ctx, "division by zero");
515     if (state->exceptionflags & SFLOAT_INVALID)
516         compile_error(ctx, "undefined (inf)");
517     if (state->exceptionflags & SFLOAT_OVERFLOW)
518         compile_error(ctx, "arithmetic overflow");
519     if (state->exceptionflags & SFLOAT_UNDERFLOW)
520         compile_error(ctx, "arithmetic underflow");
521 }
522
523 static GMQCC_INLINE void sfloat_init(sfloat_state_t *state) {
524     state->exceptionflags = SFLOAT_NOEXCEPT;
525     state->roundingmode   = FOLD_ROUNDING;
526     state->tiny           = FOLD_TINYNESS;
527 }
528
529 /*
530  * There is two stages to constant folding in GMQCC: there is the parse
531  * stage constant folding, where, with the help of the AST, operator
532  * usages can be constant folded. Then there is the constant folding
533  * in the IR for things like eliding if statements, can occur.
534  *
535  * This file is thus, split into two parts.
536  */
537
538 #define isfloat(X)      (((X))->m_vtype == TYPE_FLOAT)
539 #define isvector(X)     (((X))->m_vtype == TYPE_VECTOR)
540 #define isstring(X)     (((X))->m_vtype == TYPE_STRING)
541 #define isarray(X)      (((X))->m_vtype == TYPE_ARRAY)
542 #define isfloats(X,Y)   (isfloat  (X) && isfloat (Y))
543
544 /*
545  * Implementation of basic vector math for vec3_t, for trivial constant
546  * folding.
547  *
548  * TODO: gcc/clang hinting for autovectorization
549  */
550 enum vec3_comp_t {
551     VEC_COMP_X = 1 << 0,
552     VEC_COMP_Y = 1 << 1,
553     VEC_COMP_Z = 1 << 2
554 };
555
556 struct vec3_soft_t {
557     sfloat_cast_t x;
558     sfloat_cast_t y;
559     sfloat_cast_t z;
560 };
561
562 struct vec3_soft_state_t {
563     vec3_comp_t faults;
564     sfloat_state_t state[3];
565 };
566
567 static GMQCC_INLINE vec3_soft_t vec3_soft_convert(vec3_t vec) {
568     vec3_soft_t soft;
569     soft.x.f = vec.x;
570     soft.y.f = vec.y;
571     soft.z.f = vec.z;
572     return soft;
573 }
574
575 static GMQCC_INLINE bool vec3_soft_exception(vec3_soft_state_t *vstate, size_t index) {
576     sfloat_exceptionflags_t flags = vstate->state[index].exceptionflags;
577     if (flags & SFLOAT_DIVBYZERO) return true;
578     if (flags & SFLOAT_INVALID)   return true;
579     if (flags & SFLOAT_OVERFLOW)  return true;
580     if (flags & SFLOAT_UNDERFLOW) return true;
581     return false;
582 }
583
584 static GMQCC_INLINE void vec3_soft_eval(vec3_soft_state_t *state,
585                                         sfloat_t         (*callback)(sfloat_state_t *, sfloat_t, sfloat_t),
586                                         vec3_t             a,
587                                         vec3_t             b)
588 {
589     vec3_soft_t sa = vec3_soft_convert(a);
590     vec3_soft_t sb = vec3_soft_convert(b);
591     callback(&state->state[0], sa.x.s, sb.x.s);
592     if (vec3_soft_exception(state, 0)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_X);
593     callback(&state->state[1], sa.y.s, sb.y.s);
594     if (vec3_soft_exception(state, 1)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Y);
595     callback(&state->state[2], sa.z.s, sb.z.s);
596     if (vec3_soft_exception(state, 2)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Z);
597 }
598
599 static GMQCC_INLINE void vec3_check_except(vec3_t     a,
600                                            vec3_t     b,
601                                            lex_ctx_t  ctx,
602                                            sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t))
603 {
604     vec3_soft_state_t state = {};
605
606     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
607         return;
608
609     sfloat_init(&state.state[0]);
610     sfloat_init(&state.state[1]);
611     sfloat_init(&state.state[2]);
612
613     vec3_soft_eval(&state, callback, a, b);
614     if (state.faults & VEC_COMP_X) sfloat_check(ctx, &state.state[0], "x");
615     if (state.faults & VEC_COMP_Y) sfloat_check(ctx, &state.state[1], "y");
616     if (state.faults & VEC_COMP_Z) sfloat_check(ctx, &state.state[2], "z");
617 }
618
619 static GMQCC_INLINE vec3_t vec3_add(lex_ctx_t ctx, vec3_t a, vec3_t b) {
620     vec3_t out;
621     vec3_check_except(a, b, ctx, &sfloat_add);
622     out.x = a.x + b.x;
623     out.y = a.y + b.y;
624     out.z = a.z + b.z;
625     return out;
626 }
627
628 static GMQCC_INLINE vec3_t vec3_sub(lex_ctx_t ctx, vec3_t a, vec3_t b) {
629     vec3_t out;
630     vec3_check_except(a, b, ctx, &sfloat_sub);
631     out.x = a.x - b.x;
632     out.y = a.y - b.y;
633     out.z = a.z - b.z;
634     return out;
635 }
636
637 static GMQCC_INLINE vec3_t vec3_neg(lex_ctx_t ctx, vec3_t a) {
638     vec3_t         out;
639     sfloat_cast_t  v[3];
640     sfloat_state_t s[3];
641
642     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
643         goto end;
644
645     v[0].f = a.x;
646     v[1].f = a.y;
647     v[2].f = a.z;
648
649     sfloat_init(&s[0]);
650     sfloat_init(&s[1]);
651     sfloat_init(&s[2]);
652
653     sfloat_neg(&s[0], v[0].s);
654     sfloat_neg(&s[1], v[1].s);
655     sfloat_neg(&s[2], v[2].s);
656
657     sfloat_check(ctx, &s[0], nullptr);
658     sfloat_check(ctx, &s[1], nullptr);
659     sfloat_check(ctx, &s[2], nullptr);
660
661 end:
662     out.x = -a.x;
663     out.y = -a.y;
664     out.z = -a.z;
665     return out;
666 }
667
668 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
669     vec3_t out;
670     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
671     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
672     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
673     return out;
674 }
675
676 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
677     vec3_t out;
678     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
679     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
680     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
681     return out;
682 }
683
684 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
685     vec3_t out;
686     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
687     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
688     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
689     return out;
690 }
691
692 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
693     vec3_t out;
694     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
695     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
696     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
697     return out;
698 }
699
700 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
701     vec3_t out;
702     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
703     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
704     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
705     return out;
706 }
707
708 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
709     vec3_t out;
710     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
711     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
712     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
713     return out;
714 }
715
716 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
717     vec3_t out;
718     out.x = -1-a.x;
719     out.y = -1-a.y;
720     out.z = -1-a.z;
721     return out;
722 }
723
724 static GMQCC_INLINE qcfloat_t vec3_mulvv(lex_ctx_t ctx, vec3_t a, vec3_t b) {
725     vec3_soft_t    sa;
726     vec3_soft_t    sb;
727     sfloat_state_t s[5];
728     sfloat_t       r[5];
729
730     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
731         goto end;
732
733     sa = vec3_soft_convert(a);
734     sb = vec3_soft_convert(b);
735
736     sfloat_init(&s[0]);
737     sfloat_init(&s[1]);
738     sfloat_init(&s[2]);
739     sfloat_init(&s[3]);
740     sfloat_init(&s[4]);
741
742     r[0] = sfloat_mul(&s[0], sa.x.s, sb.x.s);
743     r[1] = sfloat_mul(&s[1], sa.y.s, sb.y.s);
744     r[2] = sfloat_mul(&s[2], sa.z.s, sb.z.s);
745     r[3] = sfloat_add(&s[3], r[0],   r[1]);
746     r[4] = sfloat_add(&s[4], r[3],   r[2]);
747
748     sfloat_check(ctx, &s[0], nullptr);
749     sfloat_check(ctx, &s[1], nullptr);
750     sfloat_check(ctx, &s[2], nullptr);
751     sfloat_check(ctx, &s[3], nullptr);
752     sfloat_check(ctx, &s[4], nullptr);
753
754 end:
755     return (a.x * b.x + a.y * b.y + a.z * b.z);
756 }
757
758 static GMQCC_INLINE vec3_t vec3_mulvf(lex_ctx_t ctx, vec3_t a, qcfloat_t b) {
759     vec3_t         out;
760     vec3_soft_t    sa;
761     sfloat_cast_t  sb;
762     sfloat_state_t s[3];
763
764     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
765         goto end;
766
767     sa   = vec3_soft_convert(a);
768     sb.f = b;
769     sfloat_init(&s[0]);
770     sfloat_init(&s[1]);
771     sfloat_init(&s[2]);
772
773     sfloat_mul(&s[0], sa.x.s, sb.s);
774     sfloat_mul(&s[1], sa.y.s, sb.s);
775     sfloat_mul(&s[2], sa.z.s, sb.s);
776
777     sfloat_check(ctx, &s[0], "x");
778     sfloat_check(ctx, &s[1], "y");
779     sfloat_check(ctx, &s[2], "z");
780
781 end:
782     out.x = a.x * b;
783     out.y = a.y * b;
784     out.z = a.z * b;
785     return out;
786 }
787
788 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
789     return a.x == b.x &&
790            a.y == b.y &&
791            a.z == b.z;
792 }
793
794 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
795     vec3_t out;
796     out.x = x;
797     out.y = y;
798     out.z = z;
799     return out;
800 }
801
802 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
803     return (!a.x && !a.y && !a.z);
804 }
805
806 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
807     return (a.x || a.y || a.z);
808 }
809
810 static GMQCC_INLINE vec3_t vec3_cross(lex_ctx_t ctx, vec3_t a, vec3_t b) {
811     vec3_t         out;
812     vec3_soft_t    sa;
813     vec3_soft_t    sb;
814     sfloat_t       r[9];
815     sfloat_state_t s[9];
816
817     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
818         goto end;
819
820     sa = vec3_soft_convert(a);
821     sb = vec3_soft_convert(b);
822
823     sfloat_init(&s[0]);
824     sfloat_init(&s[1]);
825     sfloat_init(&s[2]);
826     sfloat_init(&s[3]);
827     sfloat_init(&s[4]);
828     sfloat_init(&s[5]);
829     sfloat_init(&s[6]);
830     sfloat_init(&s[7]);
831     sfloat_init(&s[8]);
832
833     r[0] = sfloat_mul(&s[0], sa.y.s, sb.z.s);
834     r[1] = sfloat_mul(&s[1], sa.z.s, sb.y.s);
835     r[2] = sfloat_mul(&s[2], sa.z.s, sb.x.s);
836     r[3] = sfloat_mul(&s[3], sa.x.s, sb.z.s);
837     r[4] = sfloat_mul(&s[4], sa.x.s, sb.y.s);
838     r[5] = sfloat_mul(&s[5], sa.y.s, sb.x.s);
839     r[6] = sfloat_sub(&s[6], r[0],   r[1]);
840     r[7] = sfloat_sub(&s[7], r[2],   r[3]);
841     r[8] = sfloat_sub(&s[8], r[4],   r[5]);
842
843     sfloat_check(ctx, &s[0], nullptr);
844     sfloat_check(ctx, &s[1], nullptr);
845     sfloat_check(ctx, &s[2], nullptr);
846     sfloat_check(ctx, &s[3], nullptr);
847     sfloat_check(ctx, &s[4], nullptr);
848     sfloat_check(ctx, &s[5], nullptr);
849     sfloat_check(ctx, &s[6], "x");
850     sfloat_check(ctx, &s[7], "y");
851     sfloat_check(ctx, &s[8], "z");
852
853 end:
854     out.x = a.y * b.z - a.z * b.y;
855     out.y = a.z * b.x - a.x * b.z;
856     out.z = a.x * b.y - a.y * b.x;
857     return out;
858 }
859
860 qcfloat_t fold::immvalue_float(ast_value *value) {
861     return value->m_constval.vfloat;
862 }
863
864 vec3_t fold::immvalue_vector(ast_value *value) {
865     return value->m_constval.vvec;
866 }
867
868 const char *fold::immvalue_string(ast_value *value) {
869     return value->m_constval.vstring;
870 }
871
872 lex_ctx_t fold::ctx() {
873     lex_ctx_t ctx;
874     if (m_parser->lex)
875         return parser_ctx(m_parser);
876     memset(&ctx, 0, sizeof(ctx));
877     return ctx;
878 }
879
880 bool fold::immediate_true(ast_value *v) {
881     switch (v->m_vtype) {
882         case TYPE_FLOAT:
883             return !!v->m_constval.vfloat;
884         case TYPE_INTEGER:
885             return !!v->m_constval.vint;
886         case TYPE_VECTOR:
887             if (OPTS_FLAG(CORRECT_LOGIC))
888                 return vec3_pbool(v->m_constval.vvec);
889             return !!(v->m_constval.vvec.x);
890         case TYPE_STRING:
891             if (!v->m_constval.vstring)
892                 return false;
893             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
894                 return true;
895             return !!v->m_constval.vstring[0];
896         default:
897             compile_error(ctx(), "internal error: fold_immediate_true on invalid type");
898             break;
899     }
900     return !!v->m_constval.vfunc;
901 }
902
903 /* Handy macros to determine if an ast_value can be constant folded. */
904 #define fold_can_1(X)  \
905     (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
906                 ((X))->m_vtype != TYPE_FUNCTION)
907
908 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
909
910 fold::fold()
911     : m_parser(nullptr)
912 {
913 }
914
915 fold::fold(parser_t *parser)
916     : m_parser(parser)
917 {
918     m_imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
919     m_imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
920
921     constgen_float(0.0f, false);
922     constgen_float(1.0f, false);
923     constgen_float(-1.0f, false);
924     constgen_float(2.0f, false);
925
926     constgen_vector(vec3_create(0.0f, 0.0f, 0.0f));
927     constgen_vector(vec3_create(-1.0f, -1.0f, -1.0f));
928 }
929
930 bool fold::generate(ir_builder *ir) {
931     // generate globals for immediate folded values
932     ast_value *cur;
933     for (auto &it : m_imm_float)
934         if (!(cur = it)->generateGlobal(ir, false)) goto err;
935     for (auto &it : m_imm_vector)
936         if (!(cur = it)->generateGlobal(ir, false)) goto err;
937     for (auto &it : m_imm_string)
938         if (!(cur = it)->generateGlobal(ir, false)) goto err;
939     return true;
940 err:
941     con_out("failed to generate global %s\n", cur->m_name.c_str());
942     delete ir;
943     return false;
944 }
945
946 fold::~fold() {
947 // TODO: parser lifetime so this is called when it should be
948 #if 0
949     for (auto &it : m_imm_float) ast_delete(it);
950     for (auto &it : m_imm_vector) ast_delete(it);
951     for (auto &it : m_imm_string) ast_delete(it);
952
953     util_htdel(m_imm_string_untranslate);
954     util_htdel(m_imm_string_dotranslate);
955 #endif
956 }
957
958 ast_expression *fold::constgen_float(qcfloat_t value, bool inexact) {
959     for (auto &it : m_imm_float)
960         if (!memcmp(&it->m_constval.vfloat, &value, sizeof(qcfloat_t)))
961             return it;
962
963     ast_value *out  = new ast_value(ctx(), "#IMMEDIATE", TYPE_FLOAT);
964     out->m_cvq = CV_CONST;
965     out->m_hasvalue = true;
966     out->m_inexact = inexact;
967     out->m_constval.vfloat = value;
968
969     m_imm_float.push_back(out);
970
971     return out;
972 }
973
974 ast_expression *fold::constgen_vector(vec3_t value) {
975     for (auto &it : m_imm_vector)
976         if (vec3_cmp(it->m_constval.vvec, value))
977             return it;
978
979     ast_value *out = new ast_value(ctx(), "#IMMEDIATE", TYPE_VECTOR);
980     out->m_cvq = CV_CONST;
981     out->m_hasvalue = true;
982     out->m_constval.vvec = value;
983
984     m_imm_vector.push_back(out);
985
986     return out;
987 }
988
989 ast_expression *fold::constgen_string(const char *str, bool translate) {
990     hash_table_t *table = translate ? m_imm_string_untranslate : m_imm_string_dotranslate;
991     ast_value *out = nullptr;
992     size_t hash = util_hthash(table, str);
993
994     if ((out = (ast_value*)util_htgeth(table, str, hash)))
995         return out;
996
997     if (translate) {
998         char name[32];
999         util_snprintf(name, sizeof(name), "dotranslate_%zu", m_parser->translated++);
1000         out = new ast_value(ctx(), name, TYPE_STRING);
1001         out->m_flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
1002     } else {
1003         out = new ast_value(ctx(), "#IMMEDIATE", TYPE_STRING);
1004     }
1005
1006     out->m_cvq = CV_CONST;
1007     out->m_hasvalue = true;
1008     out->m_isimm = true;
1009     out->m_constval.vstring = parser_strdup(str);
1010
1011     m_imm_string.push_back(out);
1012     util_htseth(table, str, hash, out);
1013
1014     return out;
1015 }
1016
1017 ast_expression *fold::constgen_string(const std::string &str, bool translate) {
1018   return constgen_string(str.c_str(), translate);
1019 }
1020
1021 typedef union {
1022     void (*callback)(void);
1023     sfloat_t (*binary)(sfloat_state_t *, sfloat_t, sfloat_t);
1024     sfloat_t (*unary)(sfloat_state_t *, sfloat_t);
1025 } float_check_callback_t;
1026
1027 bool fold::check_except_float_impl(void (*callback)(void), ast_value *a, ast_value *b) {
1028     float_check_callback_t call;
1029     sfloat_state_t s;
1030     sfloat_cast_t ca;
1031
1032     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
1033         return false;
1034
1035     call.callback = callback;
1036     sfloat_init(&s);
1037     ca.f = immvalue_float(a);
1038     if (b) {
1039         sfloat_cast_t cb;
1040         cb.f = immvalue_float(b);
1041         call.binary(&s, ca.s, cb.s);
1042     } else {
1043         call.unary(&s, ca.s);
1044     }
1045
1046     if (s.exceptionflags == 0)
1047         return false;
1048
1049     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
1050         goto inexact_possible;
1051
1052     sfloat_check(ctx(), &s, nullptr);
1053
1054 inexact_possible:
1055     return s.exceptionflags & SFLOAT_INEXACT;
1056 }
1057
1058 #define check_except_float(CALLBACK, A, B) \
1059     check_except_float_impl(((void (*)(void))(CALLBACK)), (A), (B))
1060
1061 bool fold::check_inexact_float(ast_value *a, ast_value *b) {
1062     if (!OPTS_WARN(WARN_INEXACT_COMPARES))
1063         return false;
1064     if (!a->m_inexact && !b->m_inexact)
1065         return false;
1066     return compile_warning(ctx(), WARN_INEXACT_COMPARES, "inexact value in comparison");
1067 }
1068
1069 uint32_t fold::cond(ast_value* condval, ast_ifthen *branch) {
1070     // Optimization is disabled.
1071     if (!OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1072         // Generate code for both.
1073         return ON_TRUE | ON_FALSE;
1074     }
1075
1076     // Only float literals can be DCE in conditions.
1077     if (!isfloat(condval) || !fold_can_1(condval)) {
1078         // Generate code for both.
1079         return ON_TRUE | ON_FALSE;
1080     }
1081
1082     qcfloat_t value = immvalue_float(condval);
1083
1084     bool is_true = value != 0.0f && branch->m_on_true;
1085     bool is_false = value == 0.0f && branch->m_on_false;
1086
1087     ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1088
1089     // Determine which path we want to take based on constant fold.
1090     if (is_true) {
1091         // Generate code only for true path.
1092         return ON_TRUE;
1093     } else if (is_false) {
1094         // Generate code only for false path.
1095         return ON_FALSE;
1096     }
1097
1098     // Generate code for no paths.
1099     return 0;
1100 }
1101
1102 uint32_t fold::cond_ternary(ast_value *condval, ast_ternary *branch) {
1103     return cond(condval, (ast_ifthen*)branch);
1104 }
1105
1106 uint32_t fold::cond_ifthen(ast_value *condval, ast_ifthen *branch) {
1107     return cond(condval, branch);
1108 }
1109
1110 ast_expression *fold::op_mul_vec(vec3_t vec, ast_value *sel, const char *set) {
1111     qcfloat_t x = (&vec.x)[set[0]-'x'];
1112     qcfloat_t y = (&vec.x)[set[1]-'x'];
1113     qcfloat_t z = (&vec.x)[set[2]-'x'];
1114     if (!y && !z) {
1115         ast_expression *out;
1116         ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
1117         out = ast_member::make(ctx(), sel, set[0]-'x', "");
1118         out->m_keep_node = false;
1119         ((ast_member*)out)->m_rvalue = true;
1120         if (x != -1.0f)
1121             return new ast_binary(ctx(), INSTR_MUL_F, constgen_float(x, false), out);
1122     }
1123     return nullptr;
1124 }
1125
1126 ast_expression *fold::op_neg(ast_value *a) {
1127     if (isfloat(a)) {
1128         if (fold_can_1(a)) {
1129             /* Negation can produce inexact as well */
1130             bool inexact = check_except_float(&sfloat_neg, a, nullptr);
1131             return constgen_float(-immvalue_float(a), inexact);
1132         }
1133     } else if (isvector(a)) {
1134         if (fold_can_1(a))
1135             return constgen_vector(vec3_neg(ctx(), immvalue_vector(a)));
1136     }
1137     return nullptr;
1138 }
1139
1140 ast_expression *fold::op_not(ast_value *a) {
1141     if (isfloat(a)) {
1142         if (fold_can_1(a))
1143             return constgen_float(!immvalue_float(a), false);
1144     } else if (isvector(a)) {
1145         if (fold_can_1(a))
1146             return constgen_float(vec3_notf(immvalue_vector(a)), false);
1147     } else if (isstring(a)) {
1148         if (fold_can_1(a)) {
1149             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
1150                 return constgen_float(!immvalue_string(a), false);
1151             else
1152                 return constgen_float(!immvalue_string(a) || !*immvalue_string(a), false);
1153         }
1154     }
1155     return nullptr;
1156 }
1157
1158 ast_expression *fold::op_add(ast_value *a, ast_value *b) {
1159     if (isfloat(a)) {
1160         if (fold_can_2(a, b)) {
1161             bool inexact = check_except_float(&sfloat_add, a, b);
1162             return constgen_float(immvalue_float(a) + immvalue_float(b), inexact);
1163         }
1164     } else if (isvector(a)) {
1165         if (fold_can_2(a, b))
1166             return constgen_vector(vec3_add(ctx(),
1167                                                        immvalue_vector(a),
1168                                                        immvalue_vector(b)));
1169     }
1170     return nullptr;
1171 }
1172
1173 ast_expression *fold::op_sub(ast_value *a, ast_value *b) {
1174     if (isfloat(a)) {
1175         if (fold_can_2(a, b)) {
1176             bool inexact = check_except_float(&sfloat_sub, a, b);
1177             return constgen_float(immvalue_float(a) - immvalue_float(b), inexact);
1178         }
1179     } else if (isvector(a)) {
1180         if (fold_can_2(a, b))
1181             return constgen_vector(vec3_sub(ctx(),
1182                                                        immvalue_vector(a),
1183                                                        immvalue_vector(b)));
1184     }
1185     return nullptr;
1186 }
1187
1188 ast_expression *fold::op_mul(ast_value *a, ast_value *b) {
1189     if (isfloat(a)) {
1190         if (isvector(b)) {
1191             if (fold_can_2(a, b))
1192                 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(b), immvalue_float(a)));
1193         } else {
1194             if (fold_can_2(a, b)) {
1195                 bool inexact = check_except_float(&sfloat_mul, a, b);
1196                 return constgen_float(immvalue_float(a) * immvalue_float(b), inexact);
1197             }
1198         }
1199     } else if (isvector(a)) {
1200         if (isfloat(b)) {
1201             if (fold_can_2(a, b))
1202                 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), immvalue_float(b)));
1203         } else {
1204             if (fold_can_2(a, b)) {
1205                 return constgen_float(vec3_mulvv(ctx(), immvalue_vector(a), immvalue_vector(b)), false);
1206             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
1207                 ast_expression *out;
1208                 if ((out = op_mul_vec(immvalue_vector(a), b, "xyz"))) return out;
1209                 if ((out = op_mul_vec(immvalue_vector(a), b, "yxz"))) return out;
1210                 if ((out = op_mul_vec(immvalue_vector(a), b, "zxy"))) return out;
1211             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
1212                 ast_expression *out;
1213                 if ((out = op_mul_vec(immvalue_vector(b), a, "xyz"))) return out;
1214                 if ((out = op_mul_vec(immvalue_vector(b), a, "yxz"))) return out;
1215                 if ((out = op_mul_vec(immvalue_vector(b), a, "zxy"))) return out;
1216             }
1217         }
1218     }
1219     return nullptr;
1220 }
1221
1222 ast_expression *fold::op_div(ast_value *a, ast_value *b) {
1223     if (isfloat(a)) {
1224         if (fold_can_2(a, b)) {
1225             bool inexact = check_except_float(&sfloat_div, a, b);
1226             return constgen_float(immvalue_float(a) / immvalue_float(b), inexact);
1227         } else if (fold_can_1(b)) {
1228             return new ast_binary(
1229                 ctx(),
1230                 INSTR_MUL_F,
1231                 a,
1232                 constgen_float(1.0f / immvalue_float(b), false)
1233             );
1234         }
1235     } else if (isvector(a)) {
1236         if (fold_can_2(a, b)) {
1237             return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), 1.0f / immvalue_float(b)));
1238         } else {
1239             return new ast_binary(
1240                 ctx(),
1241                 INSTR_MUL_VF,
1242                 a,
1243                 (fold_can_1(b))
1244                     ? constgen_float(1.0f / immvalue_float(b), false)
1245                     : new ast_binary(ctx(),
1246                                      INSTR_DIV_F,
1247                                      m_imm_float[1],
1248                                      b
1249                     )
1250             );
1251         }
1252     }
1253     return nullptr;
1254 }
1255
1256 ast_expression *fold::op_mod(ast_value *a, ast_value *b) {
1257     return (fold_can_2(a, b))
1258                 ? constgen_float(fmod(immvalue_float(a), immvalue_float(b)), false)
1259                 : nullptr;
1260 }
1261
1262 ast_expression *fold::op_bor(ast_value *a, ast_value *b) {
1263     if (isfloat(a)) {
1264         if (fold_can_2(a, b))
1265             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) | ((qcint_t)immvalue_float(b))), false);
1266     } else {
1267         if (isvector(b)) {
1268             if (fold_can_2(a, b))
1269                 return constgen_vector(vec3_or(immvalue_vector(a), immvalue_vector(b)));
1270         } else {
1271             if (fold_can_2(a, b))
1272                 return constgen_vector(vec3_orvf(immvalue_vector(a), immvalue_float(b)));
1273         }
1274     }
1275     return nullptr;
1276 }
1277
1278 ast_expression *fold::op_band(ast_value *a, ast_value *b) {
1279     if (isfloat(a)) {
1280         if (fold_can_2(a, b))
1281             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) & ((qcint_t)immvalue_float(b))), false);
1282     } else {
1283         if (isvector(b)) {
1284             if (fold_can_2(a, b))
1285                 return constgen_vector(vec3_and(immvalue_vector(a), immvalue_vector(b)));
1286         } else {
1287             if (fold_can_2(a, b))
1288                 return constgen_vector(vec3_andvf(immvalue_vector(a), immvalue_float(b)));
1289         }
1290     }
1291     return nullptr;
1292 }
1293
1294 ast_expression *fold::op_xor(ast_value *a, ast_value *b) {
1295     if (isfloat(a)) {
1296         if (fold_can_2(a, b))
1297             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) ^ ((qcint_t)immvalue_float(b))), false);
1298     } else {
1299         if (fold_can_2(a, b)) {
1300             if (isvector(b))
1301                 return constgen_vector(vec3_xor(immvalue_vector(a), immvalue_vector(b)));
1302             else
1303                 return constgen_vector(vec3_xorvf(immvalue_vector(a), immvalue_float(b)));
1304         }
1305     }
1306     return nullptr;
1307 }
1308
1309 ast_expression *fold::op_lshift(ast_value *a, ast_value *b) {
1310     if (fold_can_2(a, b) && isfloats(a, b))
1311         return constgen_float((qcfloat_t)floorf(immvalue_float(a) * powf(2.0f, immvalue_float(b))), false);
1312     return nullptr;
1313 }
1314
1315 ast_expression *fold::op_rshift(ast_value *a, ast_value *b) {
1316     if (fold_can_2(a, b) && isfloats(a, b))
1317         return constgen_float((qcfloat_t)floorf(immvalue_float(a) / powf(2.0f, immvalue_float(b))), false);
1318     return nullptr;
1319 }
1320
1321 ast_expression *fold::op_andor(ast_value *a, ast_value *b, float expr) {
1322     if (fold_can_2(a, b)) {
1323         if (OPTS_FLAG(PERL_LOGIC)) {
1324             if (expr)
1325                 return immediate_true(a) ? a : b;
1326             else
1327                 return immediate_true(a) ? b : a;
1328         } else {
1329             return constgen_float(
1330                 ((expr) ? (immediate_true(a) || immediate_true(b))
1331                         : (immediate_true(a) && immediate_true(b)))
1332                             ? 1
1333                             : 0,
1334                 false
1335             );
1336         }
1337     }
1338     return nullptr;
1339 }
1340
1341 ast_expression *fold::op_tern(ast_value *a, ast_value *b, ast_value *c) {
1342     if (fold_can_1(a)) {
1343         return immediate_true(a)
1344                     ? b
1345                     : c;
1346     }
1347     return nullptr;
1348 }
1349
1350 ast_expression *fold::op_exp(ast_value *a, ast_value *b) {
1351     if (fold_can_2(a, b))
1352         return constgen_float((qcfloat_t)powf(immvalue_float(a), immvalue_float(b)), false);
1353     return nullptr;
1354 }
1355
1356 ast_expression *fold::op_lteqgt(ast_value *a, ast_value *b) {
1357     if (fold_can_2(a,b)) {
1358         check_inexact_float(a, b);
1359         if (immvalue_float(a) <  immvalue_float(b)) return m_imm_float[2];
1360         if (immvalue_float(a) == immvalue_float(b)) return m_imm_float[0];
1361         if (immvalue_float(a) >  immvalue_float(b)) return m_imm_float[1];
1362     }
1363     return nullptr;
1364 }
1365
1366 ast_expression *fold::op_ltgt(ast_value *a, ast_value *b, bool lt) {
1367     if (fold_can_2(a, b)) {
1368         check_inexact_float(a, b);
1369         return (lt) ? m_imm_float[!!(immvalue_float(a) < immvalue_float(b))]
1370                     : m_imm_float[!!(immvalue_float(a) > immvalue_float(b))];
1371     }
1372     return nullptr;
1373 }
1374
1375 ast_expression *fold::op_cmp(ast_value *a, ast_value *b, bool ne) {
1376     if (fold_can_2(a, b)) {
1377         if (isfloat(a) && isfloat(b)) {
1378             float la = immvalue_float(a);
1379             float lb = immvalue_float(b);
1380             check_inexact_float(a, b);
1381             return m_imm_float[ne ? la != lb : la == lb];
1382         } else if (isvector(a) && isvector(b)) {
1383             vec3_t la = immvalue_vector(a);
1384             vec3_t lb = immvalue_vector(b);
1385             bool compare = vec3_cmp(la, lb);
1386             return m_imm_float[ne ? !compare : compare];
1387         } else if (isstring(a) && isstring(b)) {
1388             bool compare = !strcmp(immvalue_string(a), immvalue_string(b));
1389             return m_imm_float[ne ? !compare : compare];
1390         }
1391     }
1392     return nullptr;
1393 }
1394
1395 ast_expression *fold::op_bnot(ast_value *a) {
1396     if (isfloat(a)) {
1397         if (fold_can_1(a))
1398             return constgen_float(-1-immvalue_float(a), false);
1399     } else {
1400         if (isvector(a)) {
1401             if (fold_can_1(a))
1402                 return constgen_vector(vec3_not(immvalue_vector(a)));
1403         }
1404     }
1405     return nullptr;
1406 }
1407
1408 ast_expression *fold::op_cross(ast_value *a, ast_value *b) {
1409     if (fold_can_2(a, b))
1410         return constgen_vector(vec3_cross(ctx(),
1411                                           immvalue_vector(a),
1412                                           immvalue_vector(b)));
1413     return nullptr;
1414 }
1415
1416 ast_expression *fold::op_length(ast_value *a) {
1417     if (fold_can_1(a) && isstring(a))
1418         return constgen_float(strlen(immvalue_string(a)), false);
1419     if (isarray(a))
1420         return constgen_float(a->m_initlist.size(), false);
1421     return nullptr;
1422 }
1423
1424 ast_expression *fold::op(const oper_info *info, ast_expression **opexprs) {
1425     ast_value *a = (ast_value*)opexprs[0];
1426     ast_value *b = (ast_value*)opexprs[1];
1427     ast_value *c = (ast_value*)opexprs[2];
1428     ast_expression *e = nullptr;
1429
1430     /* can a fold operation be applied to this operator usage? */
1431     if (!info->folds)
1432         return nullptr;
1433
1434     switch(info->operands) {
1435         case 3: if(!c) return nullptr; [[fallthrough]];
1436         case 2: if(!b) return nullptr; [[fallthrough]];
1437         case 1:
1438         if(!a) {
1439             compile_error(ctx(), "internal error: fold_op no operands to fold\n");
1440             return nullptr;
1441         }
1442     }
1443
1444     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
1445         case opid##ARGS ARGS_OPID:                          \
1446             if ((e = op_##OP ARGS_FOLD)) {                  \
1447                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1448             }                                               \
1449             return e
1450
1451     switch(info->id) {
1452         fold_op_case(2, ('-', 'P'),      neg,    (a));
1453         fold_op_case(2, ('!', 'P'),      not,    (a));
1454         fold_op_case(1, ('+'),           add,    (a, b));
1455         fold_op_case(1, ('-'),           sub,    (a, b));
1456         fold_op_case(1, ('*'),           mul,    (a, b));
1457         fold_op_case(1, ('/'),           div,    (a, b));
1458         fold_op_case(1, ('%'),           mod,    (a, b));
1459         fold_op_case(1, ('|'),           bor,    (a, b));
1460         fold_op_case(1, ('&'),           band,   (a, b));
1461         fold_op_case(1, ('^'),           xor,    (a, b));
1462         fold_op_case(1, ('<'),           ltgt,   (a, b, true));
1463         fold_op_case(1, ('>'),           ltgt,   (a, b, false));
1464         fold_op_case(2, ('<', '<'),      lshift, (a, b));
1465         fold_op_case(2, ('>', '>'),      rshift, (a, b));
1466         fold_op_case(2, ('|', '|'),      andor,  (a, b, true));
1467         fold_op_case(2, ('&', '&'),      andor,  (a, b, false));
1468         fold_op_case(2, ('?', ':'),      tern,   (a, b, c));
1469         fold_op_case(2, ('*', '*'),      exp,    (a, b));
1470         fold_op_case(3, ('<','=','>'),   lteqgt, (a, b));
1471         fold_op_case(2, ('!', '='),      cmp,    (a, b, true));
1472         fold_op_case(2, ('=', '='),      cmp,    (a, b, false));
1473         fold_op_case(2, ('~', 'P'),      bnot,   (a));
1474         fold_op_case(2, ('>', '<'),      cross,  (a, b));
1475         fold_op_case(3, ('l', 'e', 'n'), length, (a));
1476     }
1477     #undef fold_op_case
1478     compile_error(ctx(), "internal error: attempted to constant-fold for unsupported operator");
1479     return nullptr;
1480 }
1481
1482 /*
1483  * Constant folding for compiler intrinsics, similar approach to operator
1484  * folding, primarily: individual functions for each intrinsics to fold,
1485  * and a generic selection function.
1486  */
1487 ast_expression *fold::intrinsic_isfinite(ast_value *a) {
1488     return constgen_float(isfinite(immvalue_float(a)), false);
1489 }
1490 ast_expression *fold::intrinsic_isinf(ast_value *a) {
1491     return constgen_float(isinf(immvalue_float(a)), false);
1492 }
1493 ast_expression *fold::intrinsic_isnan(ast_value *a) {
1494     return constgen_float(isnan(immvalue_float(a)), false);
1495 }
1496 ast_expression *fold::intrinsic_isnormal(ast_value *a) {
1497     return constgen_float(isnormal(immvalue_float(a)), false);
1498 }
1499 ast_expression *fold::intrinsic_signbit(ast_value *a) {
1500     return constgen_float(signbit(immvalue_float(a)), false);
1501 }
1502 ast_expression *fold::intrinsic_acosh(ast_value *a) {
1503     return constgen_float(acoshf(immvalue_float(a)), false);
1504 }
1505 ast_expression *fold::intrinsic_asinh(ast_value *a) {
1506     return constgen_float(asinhf(immvalue_float(a)), false);
1507 }
1508 ast_expression *fold::intrinsic_atanh(ast_value *a) {
1509     return constgen_float((float)atanh(immvalue_float(a)), false);
1510 }
1511 ast_expression *fold::intrinsic_exp(ast_value *a) {
1512     return constgen_float(expf(immvalue_float(a)), false);
1513 }
1514 ast_expression *fold::intrinsic_exp2(ast_value *a) {
1515     return constgen_float(exp2f(immvalue_float(a)), false);
1516 }
1517 ast_expression *fold::intrinsic_expm1(ast_value *a) {
1518     return constgen_float(expm1f(immvalue_float(a)), false);
1519 }
1520 ast_expression *fold::intrinsic_mod(ast_value *lhs, ast_value *rhs) {
1521     return constgen_float(fmodf(immvalue_float(lhs), immvalue_float(rhs)), false);
1522 }
1523 ast_expression *fold::intrinsic_pow(ast_value *lhs, ast_value *rhs) {
1524     return constgen_float(powf(immvalue_float(lhs), immvalue_float(rhs)), false);
1525 }
1526 ast_expression *fold::intrinsic_fabs(ast_value *a) {
1527     return constgen_float(fabsf(immvalue_float(a)), false);
1528 }
1529 ast_expression* fold::intrinsic_nan(void) {
1530     return constgen_float(0.0f / 0.0f, false);
1531 }
1532 ast_expression* fold::intrinsic_epsilon(void) {
1533   static bool calculated = false;
1534   static float eps = 1.0f;
1535   if (!calculated) {
1536     do {
1537       eps /= 2.0f;
1538     } while ((1.0f + (eps / 2.0f)) != 1.0f);
1539     calculated = true;
1540   }
1541   return constgen_float(eps, false);
1542 }
1543
1544 ast_expression* fold::intrinsic_inf(void) {
1545   return constgen_float(1.0f / 0.0f, false);
1546 }
1547
1548 ast_expression *fold::intrinsic(const char *intrinsic, size_t n_args, ast_expression **args) {
1549     ast_expression *ret = nullptr;
1550
1551     if (n_args) {
1552       ast_value *a = (ast_value*)args[0];
1553       ast_value *b = (ast_value*)args[1];
1554       if (!strcmp(intrinsic, "isfinite")) ret = intrinsic_isfinite(a);
1555       if (!strcmp(intrinsic, "isinf"))    ret = intrinsic_isinf(a);
1556       if (!strcmp(intrinsic, "isnan"))    ret = intrinsic_isnan(a);
1557       if (!strcmp(intrinsic, "isnormal")) ret = intrinsic_isnormal(a);
1558       if (!strcmp(intrinsic, "signbit"))  ret = intrinsic_signbit(a);
1559       if (!strcmp(intrinsic, "acosh"))    ret = intrinsic_acosh(a);
1560       if (!strcmp(intrinsic, "asinh"))    ret = intrinsic_asinh(a);
1561       if (!strcmp(intrinsic, "atanh"))    ret = intrinsic_atanh(a);
1562       if (!strcmp(intrinsic, "exp"))      ret = intrinsic_exp(a);
1563       if (!strcmp(intrinsic, "exp2"))     ret = intrinsic_exp2(a);
1564       if (!strcmp(intrinsic, "expm1"))    ret = intrinsic_expm1(a);
1565       if (!strcmp(intrinsic, "mod"))      ret = intrinsic_mod(a, b);
1566       if (!strcmp(intrinsic, "pow"))      ret = intrinsic_pow(a, b);
1567       if (!strcmp(intrinsic, "fabs"))     ret = intrinsic_fabs(a);
1568     } else {
1569       if (!strcmp(intrinsic, "nan"))      ret = intrinsic_nan();
1570       if (!strcmp(intrinsic, "epsilon"))  ret = intrinsic_epsilon();
1571       if (!strcmp(intrinsic, "inf"))      ret = intrinsic_inf();
1572     }
1573
1574     if (ret) {
1575         ++opts_optimizationcount[OPTIM_CONST_FOLD];
1576     }
1577
1578     return ret;
1579 }
1580
1581 /*
1582  * These are all the actual constant folding methods that happen in between
1583  * the AST/IR stage of the compiler , i.e eliminating branches for const
1584  * expressions, which is the only supported thing so far. We undefine the
1585  * testing macros here because an ir_value is differant than an ast_value.
1586  */
1587 #undef expect
1588 #undef isfloat
1589 #undef isstring
1590 #undef isvector
1591 #undef fold__immvalue_float
1592 #undef fold__immvalue_string
1593 #undef fold__immvalue_vector
1594 #undef fold_can_1
1595 #undef fold_can_2
1596
1597 #define isfloat(X)              ((X)->m_vtype == TYPE_FLOAT)
1598 /*#define isstring(X)             ((X)->m_vtype == TYPE_STRING)*/
1599 /*#define isvector(X)             ((X)->m_vtype == TYPE_VECTOR)*/
1600 #define fold_can_1(X)           ((X)->m_hasvalue && (X)->m_cvq == CV_CONST)
1601 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
1602
1603 qcfloat_t fold::immvalue_float(ir_value *value) {
1604     return value->m_constval.vfloat;
1605 }
1606
1607 vec3_t fold::immvalue_vector(ir_value *value) {
1608     return value->m_constval.vvec;
1609 }
1610
1611 ast_expression *fold::superfluous(ast_expression *left, ast_expression *right, int op) {
1612     ast_expression *swapped = nullptr; /* using this as bool */
1613     ast_value *load;
1614
1615     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1616         swapped = left;
1617         left    = right;
1618         right   = swapped;
1619     }
1620
1621     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1622         return nullptr;
1623
1624     switch (op) {
1625         case INSTR_DIV_F:
1626             if (swapped)
1627                 return nullptr;
1628             [[fallthrough]];
1629         case INSTR_MUL_F:
1630             if (immvalue_float(load) == 1.0f) {
1631                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1632                 ast_unref(right);
1633                 return left;
1634             }
1635             break;
1636
1637
1638         case INSTR_SUB_F:
1639             if (swapped)
1640                 return nullptr;
1641             [[fallthrough]];
1642         case INSTR_ADD_F:
1643             if (immvalue_float(load) == 0.0f) {
1644                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1645                 ast_unref(right);
1646                 return left;
1647             }
1648             break;
1649
1650         case INSTR_MUL_V:
1651             if (vec3_cmp(immvalue_vector(load), vec3_create(1, 1, 1))) {
1652                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1653                 ast_unref(right);
1654                 return left;
1655             }
1656             break;
1657
1658         case INSTR_SUB_V:
1659             if (swapped)
1660                 return nullptr;
1661             [[fallthrough]];
1662         case INSTR_ADD_V:
1663             if (vec3_cmp(immvalue_vector(load), vec3_create(0, 0, 0))) {
1664                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1665                 ast_unref(right);
1666                 return left;
1667             }
1668             break;
1669     }
1670
1671     return nullptr;
1672 }
1673
1674 ast_expression *fold::binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1675     ast_expression *ret = superfluous(left, right, op);
1676     if (ret)
1677         return ret;
1678     return new ast_binary(ctx, op, left, right);
1679 }