]> git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.c
6d5d37ad403a4130e0fc8a989077c778f93e4831
[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     s.roundingmode   = SFLOAT_ROUND_NEAREST_EVEN;
824     s.tiny           = SFLOAT_TBEFORE;
825     s.exceptionflags = 0;
826     ca.f             = fold_immvalue_float(a);
827     cb.f             = fold_immvalue_float(b);
828
829     callback(&s, ca.s, cb.s);
830     if (s.exceptionflags == 0)
831         return false;
832
833     if (s.exceptionflags & SFLOAT_DIVBYZERO)
834         compile_error(fold_ctx(fold), "division by zero");
835 #if 0
836     /*
837      * To be enabled once softfloat implementations for stuff like sqrt()
838      * exist
839      */
840     if (s.exceptionflags & SFLOAT_INVALID)
841         compile_error(fold_ctx(fold), "invalid argument");
842 #endif
843
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     return s.exceptionflags == SFLOAT_INEXACT;
850 }
851
852 static bool fold_check_inexact_float(fold_t *fold, ast_value *a, ast_value *b) {
853     lex_ctx_t ctx = fold_ctx(fold);
854     if (!a->inexact && !b->inexact)
855         return false;
856     return compile_warning(ctx, WARN_INEXACT_COMPARES, "inexact value in comparison");
857 }
858
859 static GMQCC_INLINE ast_expression *fold_op_add(fold_t *fold, ast_value *a, ast_value *b) {
860     if (isfloat(a)) {
861         if (fold_can_2(a, b)) {
862             bool inexact = fold_check_except_float(&sfloat_add, fold, a, b);
863             return fold_constgen_float(fold, fold_immvalue_float(a) + fold_immvalue_float(b), inexact);
864         }
865     } else if (isvector(a)) {
866         if (fold_can_2(a, b))
867             return fold_constgen_vector(fold, vec3_add(fold_immvalue_vector(a), fold_immvalue_vector(b)));
868     }
869     return NULL;
870 }
871
872 static GMQCC_INLINE ast_expression *fold_op_sub(fold_t *fold, ast_value *a, ast_value *b) {
873     if (isfloat(a)) {
874         if (fold_can_2(a, b)) {
875             bool inexact = fold_check_except_float(&sfloat_sub, fold, a, b);
876             return fold_constgen_float(fold, fold_immvalue_float(a) - fold_immvalue_float(b), inexact);
877         }
878     } else if (isvector(a)) {
879         if (fold_can_2(a, b))
880             return fold_constgen_vector(fold, vec3_sub(fold_immvalue_vector(a), fold_immvalue_vector(b)));
881     }
882     return NULL;
883 }
884
885 static GMQCC_INLINE ast_expression *fold_op_mul(fold_t *fold, ast_value *a, ast_value *b) {
886     if (isfloat(a)) {
887         if (isvector(b)) {
888             if (fold_can_2(a, b))
889                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(b), fold_immvalue_float(a)));
890         } else {
891             if (fold_can_2(a, b)) {
892                 bool inexact = fold_check_except_float(&sfloat_mul, fold, a, b);
893                 return fold_constgen_float(fold, fold_immvalue_float(a) * fold_immvalue_float(b), inexact);
894             }
895         }
896     } else if (isvector(a)) {
897         if (isfloat(b)) {
898             if (fold_can_2(a, b))
899                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
900         } else {
901             if (fold_can_2(a, b)) {
902                 return fold_constgen_float(fold, vec3_mulvv(fold_immvalue_vector(a), fold_immvalue_vector(b)), false);
903             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
904                 ast_expression *out;
905                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "xyz"))) return out;
906                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "yxz"))) return out;
907                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "zxy"))) return out;
908             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
909                 ast_expression *out;
910                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "xyz"))) return out;
911                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "yxz"))) return out;
912                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "zxy"))) return out;
913             }
914         }
915     }
916     return NULL;
917 }
918
919 static GMQCC_INLINE ast_expression *fold_op_div(fold_t *fold, ast_value *a, ast_value *b) {
920     if (isfloat(a)) {
921         if (fold_can_2(a, b)) {
922             bool inexact = fold_check_except_float(&sfloat_div, fold, a, b);
923             return fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b), inexact);
924         } else if (fold_can_1(b)) {
925             return (ast_expression*)ast_binary_new(
926                 fold_ctx(fold),
927                 INSTR_MUL_F,
928                 (ast_expression*)a,
929                 fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
930             );
931         }
932     } else if (isvector(a)) {
933         if (fold_can_2(a, b)) {
934             return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
935         } else {
936             return (ast_expression*)ast_binary_new(
937                 fold_ctx(fold),
938                 INSTR_MUL_VF,
939                 (ast_expression*)a,
940                 (fold_can_1(b))
941                     ? (ast_expression*)fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
942                     : (ast_expression*)ast_binary_new(
943                                             fold_ctx(fold),
944                                             INSTR_DIV_F,
945                                             (ast_expression*)fold->imm_float[1],
946                                             (ast_expression*)b
947                     )
948             );
949         }
950     }
951     return NULL;
952 }
953
954 static GMQCC_INLINE ast_expression *fold_op_mod(fold_t *fold, ast_value *a, ast_value *b) {
955     return (fold_can_2(a, b))
956                 ? fold_constgen_float(fold, fmod(fold_immvalue_float(a), fold_immvalue_float(b)), false)
957                 : NULL;
958 }
959
960 static GMQCC_INLINE ast_expression *fold_op_bor(fold_t *fold, ast_value *a, ast_value *b) {
961     if (isfloat(a)) {
962         if (fold_can_2(a, b))
963             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) | ((qcint_t)fold_immvalue_float(b))), false);
964     } else {
965         if (isvector(b)) {
966             if (fold_can_2(a, b))
967                 return fold_constgen_vector(fold, vec3_or(fold_immvalue_vector(a), fold_immvalue_vector(b)));
968         } else {
969             if (fold_can_2(a, b))
970                 return fold_constgen_vector(fold, vec3_orvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
971         }
972     }
973     return NULL;
974 }
975
976 static GMQCC_INLINE ast_expression *fold_op_band(fold_t *fold, ast_value *a, ast_value *b) {
977     if (isfloat(a)) {
978         if (fold_can_2(a, b))
979             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) & ((qcint_t)fold_immvalue_float(b))), false);
980     } else {
981         if (isvector(b)) {
982             if (fold_can_2(a, b))
983                 return fold_constgen_vector(fold, vec3_and(fold_immvalue_vector(a), fold_immvalue_vector(b)));
984         } else {
985             if (fold_can_2(a, b))
986                 return fold_constgen_vector(fold, vec3_andvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
987         }
988     }
989     return NULL;
990 }
991
992 static GMQCC_INLINE ast_expression *fold_op_xor(fold_t *fold, ast_value *a, ast_value *b) {
993     if (isfloat(a)) {
994         if (fold_can_2(a, b))
995             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) ^ ((qcint_t)fold_immvalue_float(b))), false);
996     } else {
997         if (fold_can_2(a, b)) {
998             if (isvector(b))
999                 return fold_constgen_vector(fold, vec3_xor(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1000             else
1001                 return fold_constgen_vector(fold, vec3_xorvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1002         }
1003     }
1004     return NULL;
1005 }
1006
1007 static GMQCC_INLINE ast_expression *fold_op_lshift(fold_t *fold, ast_value *a, ast_value *b) {
1008     if (fold_can_2(a, b) && isfloats(a, b))
1009         return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) * powf(2.0f, fold_immvalue_float(b))), false);
1010     return NULL;
1011 }
1012
1013 static GMQCC_INLINE ast_expression *fold_op_rshift(fold_t *fold, ast_value *a, ast_value *b) {
1014     if (fold_can_2(a, b) && isfloats(a, b))
1015         return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) / powf(2.0f, fold_immvalue_float(b))), false);
1016     return NULL;
1017 }
1018
1019 static GMQCC_INLINE ast_expression *fold_op_andor(fold_t *fold, ast_value *a, ast_value *b, float expr) {
1020     if (fold_can_2(a, b)) {
1021         if (OPTS_FLAG(PERL_LOGIC)) {
1022             if (expr)
1023                 return (fold_immediate_true(fold, a)) ? (ast_expression*)a : (ast_expression*)b;
1024             else
1025                 return (fold_immediate_true(fold, a)) ? (ast_expression*)b : (ast_expression*)a;
1026         } else {
1027             return fold_constgen_float (
1028                 fold,
1029                 ((expr) ? (fold_immediate_true(fold, a) || fold_immediate_true(fold, b))
1030                         : (fold_immediate_true(fold, a) && fold_immediate_true(fold, b)))
1031                             ? 1
1032                             : 0,
1033                 false
1034             );
1035         }
1036     }
1037     return NULL;
1038 }
1039
1040 static GMQCC_INLINE ast_expression *fold_op_tern(fold_t *fold, ast_value *a, ast_value *b, ast_value *c) {
1041     if (fold_can_1(a)) {
1042         return fold_immediate_true(fold, a)
1043                     ? (ast_expression*)b
1044                     : (ast_expression*)c;
1045     }
1046     return NULL;
1047 }
1048
1049 static GMQCC_INLINE ast_expression *fold_op_exp(fold_t *fold, ast_value *a, ast_value *b) {
1050     if (fold_can_2(a, b))
1051         return fold_constgen_float(fold, (qcfloat_t)powf(fold_immvalue_float(a), fold_immvalue_float(b)), false);
1052     return NULL;
1053 }
1054
1055 static GMQCC_INLINE ast_expression *fold_op_lteqgt(fold_t *fold, ast_value *a, ast_value *b) {
1056     if (fold_can_2(a,b)) {
1057         fold_check_inexact_float(fold, a, b);
1058         if (fold_immvalue_float(a) <  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[2];
1059         if (fold_immvalue_float(a) == fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[0];
1060         if (fold_immvalue_float(a) >  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[1];
1061     }
1062     return NULL;
1063 }
1064
1065 static GMQCC_INLINE ast_expression *fold_op_ltgt(fold_t *fold, ast_value *a, ast_value *b, bool lt) {
1066     if (fold_can_2(a, b)) {
1067         fold_check_inexact_float(fold, a, b);
1068         return (lt) ? (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) < fold_immvalue_float(b))]
1069                     : (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) > fold_immvalue_float(b))];
1070     }
1071     return NULL;
1072 }
1073
1074 static GMQCC_INLINE ast_expression *fold_op_cmp(fold_t *fold, ast_value *a, ast_value *b, bool ne) {
1075     if (fold_can_2(a, b)) {
1076         if (isfloat(a) && isfloat(b)) {
1077             float la = fold_immvalue_float(a);
1078             float lb = fold_immvalue_float(b);
1079             fold_check_inexact_float(fold, a, b);
1080             return (ast_expression*)fold->imm_float[!(ne ? la == lb : la != lb)];
1081         } if (isvector(a) && isvector(b)) {
1082             vec3_t la = fold_immvalue_vector(a);
1083             vec3_t lb = fold_immvalue_vector(b);
1084             return (ast_expression*)fold->imm_float[!(ne ? vec3_cmp(la, lb) : !vec3_cmp(la, lb))];
1085         }
1086     }
1087     return NULL;
1088 }
1089
1090 static GMQCC_INLINE ast_expression *fold_op_bnot(fold_t *fold, ast_value *a) {
1091     if (isfloat(a)) {
1092         if (fold_can_1(a))
1093             return fold_constgen_float(fold, -1-fold_immvalue_float(a), false);
1094     } else {
1095         if (isvector(a)) {
1096             if (fold_can_1(a))
1097                 return fold_constgen_vector(fold, vec3_not(fold_immvalue_vector(a)));
1098         }
1099     }
1100     return NULL;
1101 }
1102
1103 static GMQCC_INLINE ast_expression *fold_op_cross(fold_t *fold, ast_value *a, ast_value *b) {
1104     if (fold_can_2(a, b))
1105         return fold_constgen_vector(fold, vec3_cross(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1106     return NULL;
1107 }
1108
1109 ast_expression *fold_op(fold_t *fold, const oper_info *info, ast_expression **opexprs) {
1110     ast_value      *a = (ast_value*)opexprs[0];
1111     ast_value      *b = (ast_value*)opexprs[1];
1112     ast_value      *c = (ast_value*)opexprs[2];
1113     ast_expression *e = NULL;
1114
1115     /* can a fold operation be applied to this operator usage? */
1116     if (!info->folds)
1117         return NULL;
1118
1119     switch(info->operands) {
1120         case 3: if(!c) return NULL;
1121         case 2: if(!b) return NULL;
1122         case 1:
1123         if(!a) {
1124             compile_error(fold_ctx(fold), "internal error: fold_op no operands to fold\n");
1125             return NULL;
1126         }
1127     }
1128
1129     /*
1130      * we could use a boolean and default case but ironically gcc produces
1131      * invalid broken assembly from that operation. clang/tcc get it right,
1132      * but interestingly ignore compiling this to a jump-table when I do that,
1133      * this happens to be the most efficent method, since you have per-level
1134      * granularity on the pointer check happening only for the case you check
1135      * it in. Opposed to the default method which would involve a boolean and
1136      * pointer check after wards.
1137      */
1138     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
1139         case opid##ARGS ARGS_OPID:                          \
1140             if ((e = fold_op_##OP ARGS_FOLD)) {             \
1141                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1142             }                                               \
1143             return e
1144
1145     switch(info->id) {
1146         fold_op_case(2, ('-', 'P'),    neg,    (fold, a));
1147         fold_op_case(2, ('!', 'P'),    not,    (fold, a));
1148         fold_op_case(1, ('+'),         add,    (fold, a, b));
1149         fold_op_case(1, ('-'),         sub,    (fold, a, b));
1150         fold_op_case(1, ('*'),         mul,    (fold, a, b));
1151         fold_op_case(1, ('/'),         div,    (fold, a, b));
1152         fold_op_case(1, ('%'),         mod,    (fold, a, b));
1153         fold_op_case(1, ('|'),         bor,    (fold, a, b));
1154         fold_op_case(1, ('&'),         band,   (fold, a, b));
1155         fold_op_case(1, ('^'),         xor,    (fold, a, b));
1156         fold_op_case(1, ('<'),         ltgt,   (fold, a, b, true));
1157         fold_op_case(1, ('>'),         ltgt,   (fold, a, b, false));
1158         fold_op_case(2, ('<', '<'),    lshift, (fold, a, b));
1159         fold_op_case(2, ('>', '>'),    rshift, (fold, a, b));
1160         fold_op_case(2, ('|', '|'),    andor,  (fold, a, b, true));
1161         fold_op_case(2, ('&', '&'),    andor,  (fold, a, b, false));
1162         fold_op_case(2, ('?', ':'),    tern,   (fold, a, b, c));
1163         fold_op_case(2, ('*', '*'),    exp,    (fold, a, b));
1164         fold_op_case(3, ('<','=','>'), lteqgt, (fold, a, b));
1165         fold_op_case(2, ('!', '='),    cmp,    (fold, a, b, true));
1166         fold_op_case(2, ('=', '='),    cmp,    (fold, a, b, false));
1167         fold_op_case(2, ('~', 'P'),    bnot,   (fold, a));
1168         fold_op_case(2, ('>', '<'),    cross,  (fold, a, b));
1169     }
1170     #undef fold_op_case
1171     compile_error(fold_ctx(fold), "internal error: attempted to constant-fold for unsupported operator");
1172     return NULL;
1173 }
1174
1175 /*
1176  * Constant folding for compiler intrinsics, simaler approach to operator
1177  * folding, primarly: individual functions for each intrinsics to fold,
1178  * and a generic selection function.
1179  */
1180 static GMQCC_INLINE ast_expression *fold_intrin_isfinite(fold_t *fold, ast_value *a) {
1181     return fold_constgen_float(fold, isfinite(fold_immvalue_float(a)), false);
1182 }
1183 static GMQCC_INLINE ast_expression *fold_intrin_isinf(fold_t *fold, ast_value *a) {
1184     return fold_constgen_float(fold, isinf(fold_immvalue_float(a)), false);
1185 }
1186 static GMQCC_INLINE ast_expression *fold_intrin_isnan(fold_t *fold, ast_value *a) {
1187     return fold_constgen_float(fold, isnan(fold_immvalue_float(a)), false);
1188 }
1189 static GMQCC_INLINE ast_expression *fold_intrin_isnormal(fold_t *fold, ast_value *a) {
1190     return fold_constgen_float(fold, isnormal(fold_immvalue_float(a)), false);
1191 }
1192 static GMQCC_INLINE ast_expression *fold_intrin_signbit(fold_t *fold, ast_value *a) {
1193     return fold_constgen_float(fold, signbit(fold_immvalue_float(a)), false);
1194 }
1195 static GMQCC_INLINE ast_expression *fold_intirn_acosh(fold_t *fold, ast_value *a) {
1196     return fold_constgen_float(fold, acoshf(fold_immvalue_float(a)), false);
1197 }
1198 static GMQCC_INLINE ast_expression *fold_intrin_asinh(fold_t *fold, ast_value *a) {
1199     return fold_constgen_float(fold, asinhf(fold_immvalue_float(a)), false);
1200 }
1201 static GMQCC_INLINE ast_expression *fold_intrin_atanh(fold_t *fold, ast_value *a) {
1202     return fold_constgen_float(fold, (float)atanh(fold_immvalue_float(a)), false);
1203 }
1204 static GMQCC_INLINE ast_expression *fold_intrin_exp(fold_t *fold, ast_value *a) {
1205     return fold_constgen_float(fold, expf(fold_immvalue_float(a)), false);
1206 }
1207 static GMQCC_INLINE ast_expression *fold_intrin_exp2(fold_t *fold, ast_value *a) {
1208     return fold_constgen_float(fold, exp2f(fold_immvalue_float(a)), false);
1209 }
1210 static GMQCC_INLINE ast_expression *fold_intrin_expm1(fold_t *fold, ast_value *a) {
1211     return fold_constgen_float(fold, expm1f(fold_immvalue_float(a)), false);
1212 }
1213 static GMQCC_INLINE ast_expression *fold_intrin_mod(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1214     return fold_constgen_float(fold, fmodf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1215 }
1216 static GMQCC_INLINE ast_expression *fold_intrin_pow(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1217     return fold_constgen_float(fold, powf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1218 }
1219 static GMQCC_INLINE ast_expression *fold_intrin_fabs(fold_t *fold, ast_value *a) {
1220     return fold_constgen_float(fold, fabsf(fold_immvalue_float(a)), false);
1221 }
1222
1223
1224 ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **arg) {
1225     ast_expression *ret = NULL;
1226     ast_value      *a   = (ast_value*)arg[0];
1227     ast_value      *b   = (ast_value*)arg[1];
1228
1229     if (!strcmp(intrin, "isfinite")) ret = fold_intrin_isfinite(fold, a);
1230     if (!strcmp(intrin, "isinf"))    ret = fold_intrin_isinf(fold, a);
1231     if (!strcmp(intrin, "isnan"))    ret = fold_intrin_isnan(fold, a);
1232     if (!strcmp(intrin, "isnormal")) ret = fold_intrin_isnormal(fold, a);
1233     if (!strcmp(intrin, "signbit"))  ret = fold_intrin_signbit(fold, a);
1234     if (!strcmp(intrin, "acosh"))    ret = fold_intirn_acosh(fold, a);
1235     if (!strcmp(intrin, "asinh"))    ret = fold_intrin_asinh(fold, a);
1236     if (!strcmp(intrin, "atanh"))    ret = fold_intrin_atanh(fold, a);
1237     if (!strcmp(intrin, "exp"))      ret = fold_intrin_exp(fold, a);
1238     if (!strcmp(intrin, "exp2"))     ret = fold_intrin_exp2(fold, a);
1239     if (!strcmp(intrin, "expm1"))    ret = fold_intrin_expm1(fold, a);
1240     if (!strcmp(intrin, "mod"))      ret = fold_intrin_mod(fold, a, b);
1241     if (!strcmp(intrin, "pow"))      ret = fold_intrin_pow(fold, a, b);
1242     if (!strcmp(intrin, "fabs"))     ret = fold_intrin_fabs(fold, a);
1243
1244     if (ret)
1245         ++opts_optimizationcount[OPTIM_CONST_FOLD];
1246
1247     return ret;
1248 }
1249
1250 /*
1251  * These are all the actual constant folding methods that happen in between
1252  * the AST/IR stage of the compiler , i.e eliminating branches for const
1253  * expressions, which is the only supported thing so far. We undefine the
1254  * testing macros here because an ir_value is differant than an ast_value.
1255  */
1256 #undef expect
1257 #undef isfloat
1258 #undef isstring
1259 #undef isvector
1260 #undef fold_immvalue_float
1261 #undef fold_immvalue_string
1262 #undef fold_immvalue_vector
1263 #undef fold_can_1
1264 #undef fold_can_2
1265
1266 #define isfloat(X)              ((X)->vtype == TYPE_FLOAT)
1267 /*#define isstring(X)             ((X)->vtype == TYPE_STRING)*/
1268 /*#define isvector(X)             ((X)->vtype == TYPE_VECTOR)*/
1269 #define fold_immvalue_float(X)  ((X)->constval.vfloat)
1270 #define fold_immvalue_vector(X) ((X)->constval.vvec)
1271 /*#define fold_immvalue_string(X) ((X)->constval.vstring)*/
1272 #define fold_can_1(X)           ((X)->hasvalue && (X)->cvq == CV_CONST)
1273 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
1274
1275 static ast_expression *fold_superfluous(ast_expression *left, ast_expression *right, int op) {
1276     ast_expression *swapped = NULL; /* using this as bool */
1277     ast_value *load;
1278
1279     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1280         swapped = left;
1281         left    = right;
1282         right   = swapped;
1283     }
1284
1285     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1286         return NULL;
1287
1288     switch (op) {
1289         case INSTR_DIV_F:
1290             if (swapped)
1291                 return NULL;
1292         case INSTR_MUL_F:
1293             if (fold_immvalue_float(load) == 1.0f) {
1294                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1295                 ast_unref(right);
1296                 return left;
1297             }
1298             break;
1299
1300
1301         case INSTR_SUB_F:
1302             if (swapped)
1303                 return NULL;
1304         case INSTR_ADD_F:
1305             if (fold_immvalue_float(load) == 0.0f) {
1306                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1307                 ast_unref(right);
1308                 return left;
1309             }
1310             break;
1311
1312         case INSTR_MUL_V:
1313             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(1, 1, 1))) {
1314                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1315                 ast_unref(right);
1316                 return left;
1317             }
1318             break;
1319
1320         case INSTR_SUB_V:
1321             if (swapped)
1322                 return NULL;
1323         case INSTR_ADD_V:
1324             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(0, 0, 0))) {
1325                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1326                 ast_unref(right);
1327                 return left;
1328             }
1329             break;
1330     }
1331
1332     return NULL;
1333 }
1334
1335 ast_expression *fold_binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1336     ast_expression *ret = fold_superfluous(left, right, op);
1337     if (ret)
1338         return ret;
1339     return (ast_expression*)ast_binary_new(ctx, op, left, right);
1340 }
1341
1342 static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1343     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1344         ast_expression_codegen *cgen;
1345         ir_block               *elide;
1346         ir_value               *dummy;
1347         bool                    istrue  = (fold_immvalue_float(condval) != 0.0f && branch->on_true);
1348         bool                    isfalse = (fold_immvalue_float(condval) == 0.0f && branch->on_false);
1349         ast_expression         *path    = (istrue)  ? branch->on_true  :
1350                                           (isfalse) ? branch->on_false : NULL;
1351         if (!path) {
1352             /*
1353              * no path to take implies that the evaluation is if(0) and there
1354              * is no else block. so eliminate all the code.
1355              */
1356             ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1357             return true;
1358         }
1359
1360         if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
1361             return false;
1362         if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
1363             return false;
1364         if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
1365             return false;
1366         /*
1367          * now the branch has been eliminated and the correct block for the constant evaluation
1368          * is expanded into the current block for the function.
1369          */
1370         func->curblock = elide;
1371         ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1372         return true;
1373     }
1374     return -1; /* nothing done */
1375 }
1376
1377 int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1378     return fold_cond(condval, func, (ast_ifthen*)branch);
1379 }
1380
1381 int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1382     return fold_cond(condval, func, branch);
1383 }