]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.c
Some things. Fix testsuite as well. One test will fail (inexact).
[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,
52     SFLOAT_DIVBYZERO = 4,
53     SFLOAT_OVERFLOW  = 8,
54     SFLOAT_UNDERFLOW = 16,
55     SFLOAT_INEXACT   = 32
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     (void)inexact;
696
697     vec_push(fold->imm_float, out);
698
699     return (ast_expression*)out;
700 }
701
702 ast_expression *fold_constgen_vector(fold_t *fold, vec3_t value) {
703     ast_value *out;
704     size_t     i;
705
706     for (i = 0; i < vec_size(fold->imm_vector); i++) {
707         if (vec3_cmp(fold->imm_vector[i]->constval.vvec, value))
708             return (ast_expression*)fold->imm_vector[i];
709     }
710
711     out                = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_VECTOR);
712     out->cvq           = CV_CONST;
713     out->hasvalue      = true;
714     out->constval.vvec = value;
715
716     vec_push(fold->imm_vector, out);
717
718     return (ast_expression*)out;
719 }
720
721 ast_expression *fold_constgen_string(fold_t *fold, const char *str, bool translate) {
722     hash_table_t *table = (translate) ? fold->imm_string_untranslate : fold->imm_string_dotranslate;
723     ast_value    *out   = NULL;
724     size_t        hash  = util_hthash(table, str);
725
726     if ((out = (ast_value*)util_htgeth(table, str, hash)))
727         return (ast_expression*)out;
728
729     if (translate) {
730         char name[32];
731         util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(fold->parser->translated++));
732         out                    = ast_value_new(parser_ctx(fold->parser), name, TYPE_STRING);
733         out->expression.flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
734     } else
735         out                    = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_STRING);
736
737     out->cvq              = CV_CONST;
738     out->hasvalue         = true;
739     out->isimm            = true;
740     out->constval.vstring = parser_strdup(str);
741
742     vec_push(fold->imm_string, out);
743     util_htseth(table, str, hash, out);
744
745     return (ast_expression*)out;
746 }
747
748
749 static GMQCC_INLINE ast_expression *fold_op_mul_vec(fold_t *fold, vec3_t vec, ast_value *sel, const char *set) {
750     /*
751      * vector-component constant folding works by matching the component sets
752      * to eliminate expensive operations on whole-vectors (3 components at runtime).
753      * to achive this effect in a clean manner this function generalizes the
754      * values through the use of a set paramater, which is used as an indexing method
755      * for creating the elided ast binary expression.
756      *
757      * Consider 'n 0 0' where y, and z need to be tested for 0, and x is
758      * used as the value in a binary operation generating an INSTR_MUL instruction,
759      * to acomplish the indexing of the correct component value we use set[0], set[1], set[2]
760      * as x, y, z, where the values of those operations return 'x', 'y', 'z'. Because
761      * of how ASCII works we can easily deliniate:
762      * vec.z is the same as set[2]-'x' for when set[2] is 'z', 'z'-'x' results in a
763      * literal value of 2, using this 2, we know that taking the address of vec->x (float)
764      * and indxing it with this literal will yeild the immediate address of that component
765      *
766      * Of course more work needs to be done to generate the correct index for the ast_member_new
767      * call, which is no problem: set[0]-'x' suffices that job.
768      */
769     qcfloat_t x = (&vec.x)[set[0]-'x'];
770     qcfloat_t y = (&vec.x)[set[1]-'x'];
771     qcfloat_t z = (&vec.x)[set[2]-'x'];
772
773     if (!y && !z) {
774         ast_expression *out;
775         ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
776         out                        = (ast_expression*)ast_member_new(fold_ctx(fold), (ast_expression*)sel, set[0]-'x', NULL);
777         out->node.keep             = false;
778         ((ast_member*)out)->rvalue = true;
779         if (x != -1.0f)
780             return (ast_expression*)ast_binary_new(fold_ctx(fold), INSTR_MUL_F, fold_constgen_float(fold, x, false), out);
781     }
782     return NULL;
783 }
784
785
786 static GMQCC_INLINE ast_expression *fold_op_neg(fold_t *fold, ast_value *a) {
787     if (isfloat(a)) {
788         if (fold_can_1(a))
789             return fold_constgen_float(fold, -fold_immvalue_float(a), false);
790     } else if (isvector(a)) {
791         if (fold_can_1(a))
792             return fold_constgen_vector(fold, vec3_neg(fold_immvalue_vector(a)));
793     }
794     return NULL;
795 }
796
797 static GMQCC_INLINE ast_expression *fold_op_not(fold_t *fold, ast_value *a) {
798     if (isfloat(a)) {
799         if (fold_can_1(a))
800             return fold_constgen_float(fold, !fold_immvalue_float(a), false);
801     } else if (isvector(a)) {
802         if (fold_can_1(a))
803             return fold_constgen_float(fold, vec3_notf(fold_immvalue_vector(a)), false);
804     } else if (isstring(a)) {
805         if (fold_can_1(a)) {
806             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
807                 return fold_constgen_float(fold, !fold_immvalue_string(a), false);
808             else
809                 return fold_constgen_float(fold, !fold_immvalue_string(a) || !*fold_immvalue_string(a), false);
810         }
811     }
812     return NULL;
813 }
814
815 static bool fold_check_except_float(sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t),
816                                     fold_t    *fold,
817                                     ast_value *a,
818                                     ast_value *b)
819 {
820     sfloat_state_t s;
821     sfloat_cast_t ca;
822     sfloat_cast_t cb;
823
824     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
825         return false;
826
827     s.roundingmode   = SFLOAT_ROUND_NEAREST_EVEN;
828     s.tiny           = SFLOAT_TBEFORE;
829     s.exceptionflags = 0;
830     ca.f             = fold_immvalue_float(a);
831     cb.f             = fold_immvalue_float(b);
832
833     callback(&s, ca.s, cb.s);
834     if (s.exceptionflags == 0)
835         return false;
836
837     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
838         goto inexact_possible;
839
840     if (s.exceptionflags & SFLOAT_DIVBYZERO)
841         compile_error(fold_ctx(fold), "division by zero");
842     if (s.exceptionflags & SFLOAT_INVALID)
843         compile_error(fold_ctx(fold), "undefined (inf)");
844     if (s.exceptionflags & SFLOAT_OVERFLOW)
845         compile_error(fold_ctx(fold), "arithmetic overflow");
846     if (s.exceptionflags & SFLOAT_UNDERFLOW)
847         compile_error(fold_ctx(fold), "arithmetic underflow");
848
849 inexact_possible:
850     return s.exceptionflags & SFLOAT_INEXACT;
851 }
852
853 static bool fold_check_inexact_float(fold_t *fold, ast_value *a, ast_value *b) {
854     lex_ctx_t ctx = fold_ctx(fold);
855     if (!OPTS_WARN(WARN_INEXACT_COMPARES))
856         return false;
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             ast_expression *e;
927             con_out("inexact: %d (%x:%x)\n", inexact, a, b);
928             e = fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b), inexact);
929             con_out("%x\n", e);
930             return e;
931         } else if (fold_can_1(b)) {
932             return (ast_expression*)ast_binary_new(
933                 fold_ctx(fold),
934                 INSTR_MUL_F,
935                 (ast_expression*)a,
936                 fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
937             );
938         }
939     } else if (isvector(a)) {
940         if (fold_can_2(a, b)) {
941             return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
942         } else {
943             return (ast_expression*)ast_binary_new(
944                 fold_ctx(fold),
945                 INSTR_MUL_VF,
946                 (ast_expression*)a,
947                 (fold_can_1(b))
948                     ? (ast_expression*)fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
949                     : (ast_expression*)ast_binary_new(
950                                             fold_ctx(fold),
951                                             INSTR_DIV_F,
952                                             (ast_expression*)fold->imm_float[1],
953                                             (ast_expression*)b
954                     )
955             );
956         }
957     }
958     return NULL;
959 }
960
961 static GMQCC_INLINE ast_expression *fold_op_mod(fold_t *fold, ast_value *a, ast_value *b) {
962     return (fold_can_2(a, b))
963                 ? fold_constgen_float(fold, fmod(fold_immvalue_float(a), fold_immvalue_float(b)), false)
964                 : NULL;
965 }
966
967 static GMQCC_INLINE ast_expression *fold_op_bor(fold_t *fold, ast_value *a, ast_value *b) {
968     if (isfloat(a)) {
969         if (fold_can_2(a, b))
970             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) | ((qcint_t)fold_immvalue_float(b))), false);
971     } else {
972         if (isvector(b)) {
973             if (fold_can_2(a, b))
974                 return fold_constgen_vector(fold, vec3_or(fold_immvalue_vector(a), fold_immvalue_vector(b)));
975         } else {
976             if (fold_can_2(a, b))
977                 return fold_constgen_vector(fold, vec3_orvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
978         }
979     }
980     return NULL;
981 }
982
983 static GMQCC_INLINE ast_expression *fold_op_band(fold_t *fold, ast_value *a, ast_value *b) {
984     if (isfloat(a)) {
985         if (fold_can_2(a, b))
986             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) & ((qcint_t)fold_immvalue_float(b))), false);
987     } else {
988         if (isvector(b)) {
989             if (fold_can_2(a, b))
990                 return fold_constgen_vector(fold, vec3_and(fold_immvalue_vector(a), fold_immvalue_vector(b)));
991         } else {
992             if (fold_can_2(a, b))
993                 return fold_constgen_vector(fold, vec3_andvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
994         }
995     }
996     return NULL;
997 }
998
999 static GMQCC_INLINE ast_expression *fold_op_xor(fold_t *fold, ast_value *a, ast_value *b) {
1000     if (isfloat(a)) {
1001         if (fold_can_2(a, b))
1002             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) ^ ((qcint_t)fold_immvalue_float(b))), false);
1003     } else {
1004         if (fold_can_2(a, b)) {
1005             if (isvector(b))
1006                 return fold_constgen_vector(fold, vec3_xor(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1007             else
1008                 return fold_constgen_vector(fold, vec3_xorvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1009         }
1010     }
1011     return NULL;
1012 }
1013
1014 static GMQCC_INLINE ast_expression *fold_op_lshift(fold_t *fold, ast_value *a, ast_value *b) {
1015     if (fold_can_2(a, b) && isfloats(a, b))
1016         return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) * powf(2.0f, fold_immvalue_float(b))), false);
1017     return NULL;
1018 }
1019
1020 static GMQCC_INLINE ast_expression *fold_op_rshift(fold_t *fold, ast_value *a, ast_value *b) {
1021     if (fold_can_2(a, b) && isfloats(a, b))
1022         return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) / powf(2.0f, fold_immvalue_float(b))), false);
1023     return NULL;
1024 }
1025
1026 static GMQCC_INLINE ast_expression *fold_op_andor(fold_t *fold, ast_value *a, ast_value *b, float expr) {
1027     if (fold_can_2(a, b)) {
1028         if (OPTS_FLAG(PERL_LOGIC)) {
1029             if (expr)
1030                 return (fold_immediate_true(fold, a)) ? (ast_expression*)a : (ast_expression*)b;
1031             else
1032                 return (fold_immediate_true(fold, a)) ? (ast_expression*)b : (ast_expression*)a;
1033         } else {
1034             return fold_constgen_float (
1035                 fold,
1036                 ((expr) ? (fold_immediate_true(fold, a) || fold_immediate_true(fold, b))
1037                         : (fold_immediate_true(fold, a) && fold_immediate_true(fold, b)))
1038                             ? 1
1039                             : 0,
1040                 false
1041             );
1042         }
1043     }
1044     return NULL;
1045 }
1046
1047 static GMQCC_INLINE ast_expression *fold_op_tern(fold_t *fold, ast_value *a, ast_value *b, ast_value *c) {
1048     if (fold_can_1(a)) {
1049         return fold_immediate_true(fold, a)
1050                     ? (ast_expression*)b
1051                     : (ast_expression*)c;
1052     }
1053     return NULL;
1054 }
1055
1056 static GMQCC_INLINE ast_expression *fold_op_exp(fold_t *fold, ast_value *a, ast_value *b) {
1057     if (fold_can_2(a, b))
1058         return fold_constgen_float(fold, (qcfloat_t)powf(fold_immvalue_float(a), fold_immvalue_float(b)), false);
1059     return NULL;
1060 }
1061
1062 static GMQCC_INLINE ast_expression *fold_op_lteqgt(fold_t *fold, ast_value *a, ast_value *b) {
1063     if (fold_can_2(a,b)) {
1064         fold_check_inexact_float(fold, a, b);
1065         if (fold_immvalue_float(a) <  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[2];
1066         if (fold_immvalue_float(a) == fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[0];
1067         if (fold_immvalue_float(a) >  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[1];
1068     }
1069     return NULL;
1070 }
1071
1072 static GMQCC_INLINE ast_expression *fold_op_ltgt(fold_t *fold, ast_value *a, ast_value *b, bool lt) {
1073     if (fold_can_2(a, b)) {
1074         fold_check_inexact_float(fold, a, b);
1075         return (lt) ? (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) < fold_immvalue_float(b))]
1076                     : (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) > fold_immvalue_float(b))];
1077     }
1078     return NULL;
1079 }
1080
1081 static GMQCC_INLINE ast_expression *fold_op_cmp(fold_t *fold, ast_value *a, ast_value *b, bool ne) {
1082     if (fold_can_2(a, b)) {
1083         if (isfloat(a) && isfloat(b)) {
1084             float la = fold_immvalue_float(a);
1085             float lb = fold_immvalue_float(b);
1086             con_out("CMP: %x:%x\n", a, b);
1087             fold_check_inexact_float(fold, a, b);
1088             return (ast_expression*)fold->imm_float[!(ne ? la == lb : la != lb)];
1089         } if (isvector(a) && isvector(b)) {
1090             vec3_t la = fold_immvalue_vector(a);
1091             vec3_t lb = fold_immvalue_vector(b);
1092             return (ast_expression*)fold->imm_float[!(ne ? vec3_cmp(la, lb) : !vec3_cmp(la, lb))];
1093         }
1094     }
1095     return NULL;
1096 }
1097
1098 static GMQCC_INLINE ast_expression *fold_op_bnot(fold_t *fold, ast_value *a) {
1099     if (isfloat(a)) {
1100         if (fold_can_1(a))
1101             return fold_constgen_float(fold, -1-fold_immvalue_float(a), false);
1102     } else {
1103         if (isvector(a)) {
1104             if (fold_can_1(a))
1105                 return fold_constgen_vector(fold, vec3_not(fold_immvalue_vector(a)));
1106         }
1107     }
1108     return NULL;
1109 }
1110
1111 static GMQCC_INLINE ast_expression *fold_op_cross(fold_t *fold, ast_value *a, ast_value *b) {
1112     if (fold_can_2(a, b))
1113         return fold_constgen_vector(fold, vec3_cross(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1114     return NULL;
1115 }
1116
1117 ast_expression *fold_op(fold_t *fold, const oper_info *info, ast_expression **opexprs) {
1118     ast_value      *a = (ast_value*)opexprs[0];
1119     ast_value      *b = (ast_value*)opexprs[1];
1120     ast_value      *c = (ast_value*)opexprs[2];
1121     ast_expression *e = NULL;
1122
1123     /* can a fold operation be applied to this operator usage? */
1124     if (!info->folds)
1125         return NULL;
1126
1127     switch(info->operands) {
1128         case 3: if(!c) return NULL;
1129         case 2: if(!b) return NULL;
1130         case 1:
1131         if(!a) {
1132             compile_error(fold_ctx(fold), "internal error: fold_op no operands to fold\n");
1133             return NULL;
1134         }
1135     }
1136
1137     /*
1138      * we could use a boolean and default case but ironically gcc produces
1139      * invalid broken assembly from that operation. clang/tcc get it right,
1140      * but interestingly ignore compiling this to a jump-table when I do that,
1141      * this happens to be the most efficent method, since you have per-level
1142      * granularity on the pointer check happening only for the case you check
1143      * it in. Opposed to the default method which would involve a boolean and
1144      * pointer check after wards.
1145      */
1146     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
1147         case opid##ARGS ARGS_OPID:                          \
1148             if ((e = fold_op_##OP ARGS_FOLD)) {             \
1149                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1150             }                                               \
1151             return e
1152
1153     switch(info->id) {
1154         fold_op_case(2, ('-', 'P'),    neg,    (fold, a));
1155         fold_op_case(2, ('!', 'P'),    not,    (fold, a));
1156         fold_op_case(1, ('+'),         add,    (fold, a, b));
1157         fold_op_case(1, ('-'),         sub,    (fold, a, b));
1158         fold_op_case(1, ('*'),         mul,    (fold, a, b));
1159         fold_op_case(1, ('/'),         div,    (fold, a, b));
1160         fold_op_case(1, ('%'),         mod,    (fold, a, b));
1161         fold_op_case(1, ('|'),         bor,    (fold, a, b));
1162         fold_op_case(1, ('&'),         band,   (fold, a, b));
1163         fold_op_case(1, ('^'),         xor,    (fold, a, b));
1164         fold_op_case(1, ('<'),         ltgt,   (fold, a, b, true));
1165         fold_op_case(1, ('>'),         ltgt,   (fold, a, b, false));
1166         fold_op_case(2, ('<', '<'),    lshift, (fold, a, b));
1167         fold_op_case(2, ('>', '>'),    rshift, (fold, a, b));
1168         fold_op_case(2, ('|', '|'),    andor,  (fold, a, b, true));
1169         fold_op_case(2, ('&', '&'),    andor,  (fold, a, b, false));
1170         fold_op_case(2, ('?', ':'),    tern,   (fold, a, b, c));
1171         fold_op_case(2, ('*', '*'),    exp,    (fold, a, b));
1172         fold_op_case(3, ('<','=','>'), lteqgt, (fold, a, b));
1173         fold_op_case(2, ('!', '='),    cmp,    (fold, a, b, true));
1174         fold_op_case(2, ('=', '='),    cmp,    (fold, a, b, false));
1175         fold_op_case(2, ('~', 'P'),    bnot,   (fold, a));
1176         fold_op_case(2, ('>', '<'),    cross,  (fold, a, b));
1177     }
1178     #undef fold_op_case
1179     compile_error(fold_ctx(fold), "internal error: attempted to constant-fold for unsupported operator");
1180     return NULL;
1181 }
1182
1183 /*
1184  * Constant folding for compiler intrinsics, simaler approach to operator
1185  * folding, primarly: individual functions for each intrinsics to fold,
1186  * and a generic selection function.
1187  */
1188 static GMQCC_INLINE ast_expression *fold_intrin_isfinite(fold_t *fold, ast_value *a) {
1189     return fold_constgen_float(fold, isfinite(fold_immvalue_float(a)), false);
1190 }
1191 static GMQCC_INLINE ast_expression *fold_intrin_isinf(fold_t *fold, ast_value *a) {
1192     return fold_constgen_float(fold, isinf(fold_immvalue_float(a)), false);
1193 }
1194 static GMQCC_INLINE ast_expression *fold_intrin_isnan(fold_t *fold, ast_value *a) {
1195     return fold_constgen_float(fold, isnan(fold_immvalue_float(a)), false);
1196 }
1197 static GMQCC_INLINE ast_expression *fold_intrin_isnormal(fold_t *fold, ast_value *a) {
1198     return fold_constgen_float(fold, isnormal(fold_immvalue_float(a)), false);
1199 }
1200 static GMQCC_INLINE ast_expression *fold_intrin_signbit(fold_t *fold, ast_value *a) {
1201     return fold_constgen_float(fold, signbit(fold_immvalue_float(a)), false);
1202 }
1203 static GMQCC_INLINE ast_expression *fold_intirn_acosh(fold_t *fold, ast_value *a) {
1204     return fold_constgen_float(fold, acoshf(fold_immvalue_float(a)), false);
1205 }
1206 static GMQCC_INLINE ast_expression *fold_intrin_asinh(fold_t *fold, ast_value *a) {
1207     return fold_constgen_float(fold, asinhf(fold_immvalue_float(a)), false);
1208 }
1209 static GMQCC_INLINE ast_expression *fold_intrin_atanh(fold_t *fold, ast_value *a) {
1210     return fold_constgen_float(fold, (float)atanh(fold_immvalue_float(a)), false);
1211 }
1212 static GMQCC_INLINE ast_expression *fold_intrin_exp(fold_t *fold, ast_value *a) {
1213     return fold_constgen_float(fold, expf(fold_immvalue_float(a)), false);
1214 }
1215 static GMQCC_INLINE ast_expression *fold_intrin_exp2(fold_t *fold, ast_value *a) {
1216     return fold_constgen_float(fold, exp2f(fold_immvalue_float(a)), false);
1217 }
1218 static GMQCC_INLINE ast_expression *fold_intrin_expm1(fold_t *fold, ast_value *a) {
1219     return fold_constgen_float(fold, expm1f(fold_immvalue_float(a)), false);
1220 }
1221 static GMQCC_INLINE ast_expression *fold_intrin_mod(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1222     return fold_constgen_float(fold, fmodf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1223 }
1224 static GMQCC_INLINE ast_expression *fold_intrin_pow(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1225     return fold_constgen_float(fold, powf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1226 }
1227 static GMQCC_INLINE ast_expression *fold_intrin_fabs(fold_t *fold, ast_value *a) {
1228     return fold_constgen_float(fold, fabsf(fold_immvalue_float(a)), false);
1229 }
1230
1231
1232 ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **arg) {
1233     ast_expression *ret = NULL;
1234     ast_value      *a   = (ast_value*)arg[0];
1235     ast_value      *b   = (ast_value*)arg[1];
1236
1237     if (!strcmp(intrin, "isfinite")) ret = fold_intrin_isfinite(fold, a);
1238     if (!strcmp(intrin, "isinf"))    ret = fold_intrin_isinf(fold, a);
1239     if (!strcmp(intrin, "isnan"))    ret = fold_intrin_isnan(fold, a);
1240     if (!strcmp(intrin, "isnormal")) ret = fold_intrin_isnormal(fold, a);
1241     if (!strcmp(intrin, "signbit"))  ret = fold_intrin_signbit(fold, a);
1242     if (!strcmp(intrin, "acosh"))    ret = fold_intirn_acosh(fold, a);
1243     if (!strcmp(intrin, "asinh"))    ret = fold_intrin_asinh(fold, a);
1244     if (!strcmp(intrin, "atanh"))    ret = fold_intrin_atanh(fold, a);
1245     if (!strcmp(intrin, "exp"))      ret = fold_intrin_exp(fold, a);
1246     if (!strcmp(intrin, "exp2"))     ret = fold_intrin_exp2(fold, a);
1247     if (!strcmp(intrin, "expm1"))    ret = fold_intrin_expm1(fold, a);
1248     if (!strcmp(intrin, "mod"))      ret = fold_intrin_mod(fold, a, b);
1249     if (!strcmp(intrin, "pow"))      ret = fold_intrin_pow(fold, a, b);
1250     if (!strcmp(intrin, "fabs"))     ret = fold_intrin_fabs(fold, a);
1251
1252     if (ret)
1253         ++opts_optimizationcount[OPTIM_CONST_FOLD];
1254
1255     return ret;
1256 }
1257
1258 /*
1259  * These are all the actual constant folding methods that happen in between
1260  * the AST/IR stage of the compiler , i.e eliminating branches for const
1261  * expressions, which is the only supported thing so far. We undefine the
1262  * testing macros here because an ir_value is differant than an ast_value.
1263  */
1264 #undef expect
1265 #undef isfloat
1266 #undef isstring
1267 #undef isvector
1268 #undef fold_immvalue_float
1269 #undef fold_immvalue_string
1270 #undef fold_immvalue_vector
1271 #undef fold_can_1
1272 #undef fold_can_2
1273
1274 #define isfloat(X)              ((X)->vtype == TYPE_FLOAT)
1275 /*#define isstring(X)             ((X)->vtype == TYPE_STRING)*/
1276 /*#define isvector(X)             ((X)->vtype == TYPE_VECTOR)*/
1277 #define fold_immvalue_float(X)  ((X)->constval.vfloat)
1278 #define fold_immvalue_vector(X) ((X)->constval.vvec)
1279 /*#define fold_immvalue_string(X) ((X)->constval.vstring)*/
1280 #define fold_can_1(X)           ((X)->hasvalue && (X)->cvq == CV_CONST)
1281 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
1282
1283 static ast_expression *fold_superfluous(ast_expression *left, ast_expression *right, int op) {
1284     ast_expression *swapped = NULL; /* using this as bool */
1285     ast_value *load;
1286
1287     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1288         swapped = left;
1289         left    = right;
1290         right   = swapped;
1291     }
1292
1293     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1294         return NULL;
1295
1296     switch (op) {
1297         case INSTR_DIV_F:
1298             if (swapped)
1299                 return NULL;
1300         case INSTR_MUL_F:
1301             if (fold_immvalue_float(load) == 1.0f) {
1302                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1303                 ast_unref(right);
1304                 return left;
1305             }
1306             break;
1307
1308
1309         case INSTR_SUB_F:
1310             if (swapped)
1311                 return NULL;
1312         case INSTR_ADD_F:
1313             if (fold_immvalue_float(load) == 0.0f) {
1314                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1315                 ast_unref(right);
1316                 return left;
1317             }
1318             break;
1319
1320         case INSTR_MUL_V:
1321             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(1, 1, 1))) {
1322                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1323                 ast_unref(right);
1324                 return left;
1325             }
1326             break;
1327
1328         case INSTR_SUB_V:
1329             if (swapped)
1330                 return NULL;
1331         case INSTR_ADD_V:
1332             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(0, 0, 0))) {
1333                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1334                 ast_unref(right);
1335                 return left;
1336             }
1337             break;
1338     }
1339
1340     return NULL;
1341 }
1342
1343 ast_expression *fold_binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1344     ast_expression *ret = fold_superfluous(left, right, op);
1345     if (ret)
1346         return ret;
1347     return (ast_expression*)ast_binary_new(ctx, op, left, right);
1348 }
1349
1350 static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1351     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1352         ast_expression_codegen *cgen;
1353         ir_block               *elide;
1354         ir_value               *dummy;
1355         bool                    istrue  = (fold_immvalue_float(condval) != 0.0f && branch->on_true);
1356         bool                    isfalse = (fold_immvalue_float(condval) == 0.0f && branch->on_false);
1357         ast_expression         *path    = (istrue)  ? branch->on_true  :
1358                                           (isfalse) ? branch->on_false : NULL;
1359         if (!path) {
1360             /*
1361              * no path to take implies that the evaluation is if(0) and there
1362              * is no else block. so eliminate all the code.
1363              */
1364             ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1365             return true;
1366         }
1367
1368         if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
1369             return false;
1370         if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
1371             return false;
1372         if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
1373             return false;
1374         /*
1375          * now the branch has been eliminated and the correct block for the constant evaluation
1376          * is expanded into the current block for the function.
1377          */
1378         func->curblock = elide;
1379         ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1380         return true;
1381     }
1382     return -1; /* nothing done */
1383 }
1384
1385 int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1386     return fold_cond(condval, func, (ast_ifthen*)branch);
1387 }
1388
1389 int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1390     return fold_cond(condval, func, branch);
1391 }