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