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