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