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