]> git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.c
Happy new year redux!
[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  * There is two stages to constant folding in GMQCC: there is the parse
34  * stage constant folding, where, witht he help of the AST, operator
35  * usages can be constant folded. Then there is the constant folding
36  * in the IR for things like eliding if statements, can occur.
37  *
38  * This file is thus, split into two parts.
39  */
40
41 #define isfloat(X)      (((ast_expression*)(X))->vtype == TYPE_FLOAT)
42 #define isvector(X)     (((ast_expression*)(X))->vtype == TYPE_VECTOR)
43 #define isstring(X)     (((ast_expression*)(X))->vtype == TYPE_STRING)
44 #define isfloats(X,Y)   (isfloat  (X) && isfloat (Y))
45
46 /*
47  * Implementation of basic vector math for vec3_t, for trivial constant
48  * folding.
49  *
50  * TODO: gcc/clang hinting for autovectorization
51  */
52 static GMQCC_INLINE vec3_t vec3_add(vec3_t a, vec3_t b) {
53     vec3_t out;
54     out.x = a.x + b.x;
55     out.y = a.y + b.y;
56     out.z = a.z + b.z;
57     return out;
58 }
59
60 static GMQCC_INLINE vec3_t vec3_sub(vec3_t a, vec3_t b) {
61     vec3_t out;
62     out.x = a.x - b.x;
63     out.y = a.y - b.y;
64     out.z = a.z - b.z;
65     return out;
66 }
67
68 static GMQCC_INLINE vec3_t vec3_neg(vec3_t a) {
69     vec3_t out;
70     out.x = -a.x;
71     out.y = -a.y;
72     out.z = -a.z;
73     return out;
74 }
75
76 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
77     vec3_t out;
78     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
79     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
80     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
81     return out;
82 }
83
84 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
85     vec3_t out;
86     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
87     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
88     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
89     return out;
90 }
91
92 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
93     vec3_t out;
94     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
95     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
96     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
97     return out;
98 }
99
100 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
101     vec3_t out;
102     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
103     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
104     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
105     return out;
106 }
107
108 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
109     vec3_t out;
110     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
111     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
112     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
113     return out;
114 }
115
116 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
117     vec3_t out;
118     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
119     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
120     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
121     return out;
122 }
123
124 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
125     vec3_t out;
126     out.x = -1-a.x;
127     out.y = -1-a.y;
128     out.z = -1-a.z;
129     return out;
130 }
131
132 static GMQCC_INLINE qcfloat_t vec3_mulvv(vec3_t a, vec3_t b) {
133     return (a.x * b.x + a.y * b.y + a.z * b.z);
134 }
135
136 static GMQCC_INLINE vec3_t vec3_mulvf(vec3_t a, qcfloat_t b) {
137     vec3_t out;
138     out.x = a.x * b;
139     out.y = a.y * b;
140     out.z = a.z * b;
141     return out;
142 }
143
144 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
145     return a.x == b.x &&
146            a.y == b.y &&
147            a.z == b.z;
148 }
149
150 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
151     vec3_t out;
152     out.x = x;
153     out.y = y;
154     out.z = z;
155     return out;
156 }
157
158 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
159     return (!a.x && !a.y && !a.z);
160 }
161
162 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
163     return (a.x || a.y || a.z);
164 }
165
166 static GMQCC_INLINE vec3_t vec3_cross(vec3_t a, vec3_t b) {
167     vec3_t out;
168     out.x = a.y * b.z - a.z * b.y;
169     out.y = a.z * b.x - a.x * b.z;
170     out.z = a.x * b.y - a.y * b.x;
171     return out;
172 }
173
174 static lex_ctx_t fold_ctx(fold_t *fold) {
175     lex_ctx_t ctx;
176     if (fold->parser->lex)
177         return parser_ctx(fold->parser);
178
179     memset(&ctx, 0, sizeof(ctx));
180     return ctx;
181 }
182
183 static GMQCC_INLINE bool fold_immediate_true(fold_t *fold, ast_value *v) {
184     switch (v->expression.vtype) {
185         case TYPE_FLOAT:
186             return !!v->constval.vfloat;
187         case TYPE_INTEGER:
188             return !!v->constval.vint;
189         case TYPE_VECTOR:
190             if (OPTS_FLAG(CORRECT_LOGIC))
191                 return vec3_pbool(v->constval.vvec);
192             return !!(v->constval.vvec.x);
193         case TYPE_STRING:
194             if (!v->constval.vstring)
195                 return false;
196             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
197                 return true;
198             return !!v->constval.vstring[0];
199         default:
200             compile_error(fold_ctx(fold), "internal error: fold_immediate_true on invalid type");
201             break;
202     }
203     return !!v->constval.vfunc;
204 }
205
206 /* Handy macros to determine if an ast_value can be constant folded. */
207 #define fold_can_1(X)  \
208     (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
209                 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
210
211 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
212
213 #define fold_immvalue_float(E)  ((E)->constval.vfloat)
214 #define fold_immvalue_vector(E) ((E)->constval.vvec)
215 #define fold_immvalue_string(E) ((E)->constval.vstring)
216
217 fold_t *fold_init(parser_t *parser) {
218     fold_t *fold                 = (fold_t*)mem_a(sizeof(fold_t));
219     fold->parser                 = parser;
220     fold->imm_float              = NULL;
221     fold->imm_vector             = NULL;
222     fold->imm_string             = NULL;
223     fold->imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
224     fold->imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
225
226     /*
227      * prime the tables with common constant values at constant
228      * locations.
229      */
230     (void)fold_constgen_float (fold,  0.0f);
231     (void)fold_constgen_float (fold,  1.0f);
232     (void)fold_constgen_float (fold, -1.0f);
233     (void)fold_constgen_float (fold,  2.0f);
234
235     (void)fold_constgen_vector(fold, vec3_create(0.0f, 0.0f, 0.0f));
236     (void)fold_constgen_vector(fold, vec3_create(-1.0f, -1.0f, -1.0f));
237
238     return fold;
239 }
240
241 bool fold_generate(fold_t *fold, ir_builder *ir) {
242     /* generate globals for immediate folded values */
243     size_t     i;
244     ast_value *cur;
245
246     for (i = 0; i < vec_size(fold->imm_float);   ++i)
247         if (!ast_global_codegen ((cur = fold->imm_float[i]), ir, false)) goto err;
248     for (i = 0; i < vec_size(fold->imm_vector);  ++i)
249         if (!ast_global_codegen((cur = fold->imm_vector[i]), ir, false)) goto err;
250     for (i = 0; i < vec_size(fold->imm_string);  ++i)
251         if (!ast_global_codegen((cur = fold->imm_string[i]), ir, false)) goto err;
252
253     return true;
254
255 err:
256     con_out("failed to generate global %s\n", cur->name);
257     ir_builder_delete(ir);
258     return false;
259 }
260
261 void fold_cleanup(fold_t *fold) {
262     size_t i;
263
264     for (i = 0; i < vec_size(fold->imm_float);  ++i) ast_delete(fold->imm_float[i]);
265     for (i = 0; i < vec_size(fold->imm_vector); ++i) ast_delete(fold->imm_vector[i]);
266     for (i = 0; i < vec_size(fold->imm_string); ++i) ast_delete(fold->imm_string[i]);
267
268     vec_free(fold->imm_float);
269     vec_free(fold->imm_vector);
270     vec_free(fold->imm_string);
271
272     util_htdel(fold->imm_string_untranslate);
273     util_htdel(fold->imm_string_dotranslate);
274
275     mem_d(fold);
276 }
277
278 ast_expression *fold_constgen_float(fold_t *fold, qcfloat_t value) {
279     ast_value  *out = NULL;
280     size_t      i;
281
282     for (i = 0; i < vec_size(fold->imm_float); i++) {
283         if (!memcmp(&fold->imm_float[i]->constval.vfloat, &value, sizeof(qcfloat_t)))
284             return (ast_expression*)fold->imm_float[i];
285     }
286
287     out                  = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_FLOAT);
288     out->cvq             = CV_CONST;
289     out->hasvalue        = true;
290     out->constval.vfloat = value;
291
292     vec_push(fold->imm_float, out);
293
294     return (ast_expression*)out;
295 }
296
297 ast_expression *fold_constgen_vector(fold_t *fold, vec3_t value) {
298     ast_value *out;
299     size_t     i;
300
301     for (i = 0; i < vec_size(fold->imm_vector); i++) {
302         if (vec3_cmp(fold->imm_vector[i]->constval.vvec, value))
303             return (ast_expression*)fold->imm_vector[i];
304     }
305
306     out                = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_VECTOR);
307     out->cvq           = CV_CONST;
308     out->hasvalue      = true;
309     out->constval.vvec = value;
310
311     vec_push(fold->imm_vector, out);
312
313     return (ast_expression*)out;
314 }
315
316 ast_expression *fold_constgen_string(fold_t *fold, const char *str, bool translate) {
317     hash_table_t *table = (translate) ? fold->imm_string_untranslate : fold->imm_string_dotranslate;
318     ast_value    *out   = NULL;
319     size_t        hash  = util_hthash(table, str);
320
321     if ((out = (ast_value*)util_htgeth(table, str, hash)))
322         return (ast_expression*)out;
323
324     if (translate) {
325         char name[32];
326         util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(fold->parser->translated++));
327         out                    = ast_value_new(parser_ctx(fold->parser), name, TYPE_STRING);
328         out->expression.flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
329     } else
330         out                    = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_STRING);
331
332     out->cvq              = CV_CONST;
333     out->hasvalue         = true;
334     out->isimm            = true;
335     out->constval.vstring = parser_strdup(str);
336
337     vec_push(fold->imm_string, out);
338     util_htseth(table, str, hash, out);
339
340     return (ast_expression*)out;
341 }
342
343
344 static GMQCC_INLINE ast_expression *fold_op_mul_vec(fold_t *fold, vec3_t vec, ast_value *sel, const char *set) {
345     /*
346      * vector-component constant folding works by matching the component sets
347      * to eliminate expensive operations on whole-vectors (3 components at runtime).
348      * to achive this effect in a clean manner this function generalizes the
349      * values through the use of a set paramater, which is used as an indexing method
350      * for creating the elided ast binary expression.
351      *
352      * Consider 'n 0 0' where y, and z need to be tested for 0, and x is
353      * used as the value in a binary operation generating an INSTR_MUL instruction,
354      * to acomplish the indexing of the correct component value we use set[0], set[1], set[2]
355      * as x, y, z, where the values of those operations return 'x', 'y', 'z'. Because
356      * of how ASCII works we can easily deliniate:
357      * vec.z is the same as set[2]-'x' for when set[2] is 'z', 'z'-'x' results in a
358      * literal value of 2, using this 2, we know that taking the address of vec->x (float)
359      * and indxing it with this literal will yeild the immediate address of that component
360      *
361      * Of course more work needs to be done to generate the correct index for the ast_member_new
362      * call, which is no problem: set[0]-'x' suffices that job.
363      */
364     qcfloat_t x = (&vec.x)[set[0]-'x'];
365     qcfloat_t y = (&vec.x)[set[1]-'x'];
366     qcfloat_t z = (&vec.x)[set[2]-'x'];
367
368     if (!y && !z) {
369         ast_expression *out;
370         ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
371         out                        = (ast_expression*)ast_member_new(fold_ctx(fold), (ast_expression*)sel, set[0]-'x', NULL);
372         out->node.keep             = false;
373         ((ast_member*)out)->rvalue = true;
374         if (x != -1.0f)
375             return (ast_expression*)ast_binary_new(fold_ctx(fold), INSTR_MUL_F, fold_constgen_float(fold, x), out);
376     }
377     return NULL;
378 }
379
380
381 static GMQCC_INLINE ast_expression *fold_op_neg(fold_t *fold, ast_value *a) {
382     if (isfloat(a)) {
383         if (fold_can_1(a))
384             return fold_constgen_float(fold, -fold_immvalue_float(a));
385     } else if (isvector(a)) {
386         if (fold_can_1(a))
387             return fold_constgen_vector(fold, vec3_neg(fold_immvalue_vector(a)));
388     }
389     return NULL;
390 }
391
392 static GMQCC_INLINE ast_expression *fold_op_not(fold_t *fold, ast_value *a) {
393     if (isfloat(a)) {
394         if (fold_can_1(a))
395             return fold_constgen_float(fold, !fold_immvalue_float(a));
396     } else if (isvector(a)) {
397         if (fold_can_1(a))
398             return fold_constgen_float(fold, vec3_notf(fold_immvalue_vector(a)));
399     } else if (isstring(a)) {
400         if (fold_can_1(a)) {
401             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
402                 return fold_constgen_float(fold, !fold_immvalue_string(a));
403             else
404                 return fold_constgen_float(fold, !fold_immvalue_string(a) || !*fold_immvalue_string(a));
405         }
406     }
407     return NULL;
408 }
409
410 static GMQCC_INLINE ast_expression *fold_op_add(fold_t *fold, ast_value *a, ast_value *b) {
411     if (isfloat(a)) {
412         if (fold_can_2(a, b))
413             return fold_constgen_float(fold, fold_immvalue_float(a) + fold_immvalue_float(b));
414     } else if (isvector(a)) {
415         if (fold_can_2(a, b))
416             return fold_constgen_vector(fold, vec3_add(fold_immvalue_vector(a), fold_immvalue_vector(b)));
417     }
418     return NULL;
419 }
420
421 static GMQCC_INLINE ast_expression *fold_op_sub(fold_t *fold, ast_value *a, ast_value *b) {
422     if (isfloat(a)) {
423         if (fold_can_2(a, b))
424             return fold_constgen_float(fold, fold_immvalue_float(a) - fold_immvalue_float(b));
425     } else if (isvector(a)) {
426         if (fold_can_2(a, b))
427             return fold_constgen_vector(fold, vec3_sub(fold_immvalue_vector(a), fold_immvalue_vector(b)));
428     }
429     return NULL;
430 }
431
432 static GMQCC_INLINE ast_expression *fold_op_mul(fold_t *fold, ast_value *a, ast_value *b) {
433     if (isfloat(a)) {
434         if (isvector(b)) {
435             if (fold_can_2(a, b))
436                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(b), fold_immvalue_float(a)));
437         } else {
438             if (fold_can_2(a, b))
439                 return fold_constgen_float(fold, fold_immvalue_float(a) * fold_immvalue_float(b));
440         }
441     } else if (isvector(a)) {
442         if (isfloat(b)) {
443             if (fold_can_2(a, b))
444                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
445         } else {
446             if (fold_can_2(a, b)) {
447                 return fold_constgen_float(fold, vec3_mulvv(fold_immvalue_vector(a), fold_immvalue_vector(b)));
448             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
449                 ast_expression *out;
450                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "xyz"))) return out;
451                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "yxz"))) return out;
452                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "zxy"))) return out;
453             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
454                 ast_expression *out;
455                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "xyz"))) return out;
456                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "yxz"))) return out;
457                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "zxy"))) return out;
458             }
459         }
460     }
461     return NULL;
462 }
463
464 static GMQCC_INLINE ast_expression *fold_op_div(fold_t *fold, ast_value *a, ast_value *b) {
465     if (isfloat(a)) {
466         if (fold_can_2(a, b)) {
467             return fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b));
468         } else if (fold_can_1(b)) {
469             return (ast_expression*)ast_binary_new(
470                 fold_ctx(fold),
471                 INSTR_MUL_F,
472                 (ast_expression*)a,
473                 fold_constgen_float(fold, 1.0f / fold_immvalue_float(b))
474             );
475         }
476     } else if (isvector(a)) {
477         if (fold_can_2(a, b)) {
478             return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
479         } else {
480             return (ast_expression*)ast_binary_new(
481                 fold_ctx(fold),
482                 INSTR_MUL_VF,
483                 (ast_expression*)a,
484                 (fold_can_1(b))
485                     ? (ast_expression*)fold_constgen_float(fold, 1.0f / fold_immvalue_float(b))
486                     : (ast_expression*)ast_binary_new(
487                                             fold_ctx(fold),
488                                             INSTR_DIV_F,
489                                             (ast_expression*)fold->imm_float[1],
490                                             (ast_expression*)b
491                     )
492             );
493         }
494     }
495     return NULL;
496 }
497
498 static GMQCC_INLINE ast_expression *fold_op_mod(fold_t *fold, ast_value *a, ast_value *b) {
499     return (fold_can_2(a, b))
500                 ? fold_constgen_float(fold, fmod(fold_immvalue_float(a), fold_immvalue_float(b)))
501                 : NULL;
502 }
503
504 static GMQCC_INLINE ast_expression *fold_op_bor(fold_t *fold, ast_value *a, ast_value *b) {
505     if (isfloat(a)) {
506         if (fold_can_2(a, b))
507             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) | ((qcint_t)fold_immvalue_float(b))));
508     } else {
509         if (isvector(b)) {
510             if (fold_can_2(a, b))
511                 return fold_constgen_vector(fold, vec3_or(fold_immvalue_vector(a), fold_immvalue_vector(b)));
512         } else {
513             if (fold_can_2(a, b))
514                 return fold_constgen_vector(fold, vec3_orvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
515         }
516     }
517     return NULL;
518 }
519
520 static GMQCC_INLINE ast_expression *fold_op_band(fold_t *fold, ast_value *a, ast_value *b) {
521     if (isfloat(a)) {
522         if (fold_can_2(a, b))
523             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) & ((qcint_t)fold_immvalue_float(b))));
524     } else {
525         if (isvector(b)) {
526             if (fold_can_2(a, b))
527                 return fold_constgen_vector(fold, vec3_and(fold_immvalue_vector(a), fold_immvalue_vector(b)));
528         } else {
529             if (fold_can_2(a, b))
530                 return fold_constgen_vector(fold, vec3_andvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
531         }
532     }
533     return NULL;
534 }
535
536 static GMQCC_INLINE ast_expression *fold_op_xor(fold_t *fold, ast_value *a, ast_value *b) {
537     if (isfloat(a)) {
538         if (fold_can_2(a, b))
539             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) ^ ((qcint_t)fold_immvalue_float(b))));
540     } else {
541         if (fold_can_2(a, b)) {
542             if (isvector(b))
543                 return fold_constgen_vector(fold, vec3_xor(fold_immvalue_vector(a), fold_immvalue_vector(b)));
544             else
545                 return fold_constgen_vector(fold, vec3_xorvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
546         }
547     }
548     return NULL;
549 }
550
551 static GMQCC_INLINE ast_expression *fold_op_lshift(fold_t *fold, ast_value *a, ast_value *b) {
552     if (fold_can_2(a, b) && isfloats(a, b))
553         return fold_constgen_float(fold, (qcfloat_t)((qcuint_t)(fold_immvalue_float(a)) << (qcuint_t)(fold_immvalue_float(b))));
554     return NULL;
555 }
556
557 static GMQCC_INLINE ast_expression *fold_op_rshift(fold_t *fold, ast_value *a, ast_value *b) {
558     if (fold_can_2(a, b) && isfloats(a, b))
559         return fold_constgen_float(fold, (qcfloat_t)((qcuint_t)(fold_immvalue_float(a)) >> (qcuint_t)(fold_immvalue_float(b))));
560     return NULL;
561 }
562
563 static GMQCC_INLINE ast_expression *fold_op_andor(fold_t *fold, ast_value *a, ast_value *b, float expr) {
564     if (fold_can_2(a, b)) {
565         if (OPTS_FLAG(PERL_LOGIC)) {
566             if (expr)
567                 return (fold_immediate_true(fold, a)) ? (ast_expression*)a : (ast_expression*)b;
568             else
569                 return (fold_immediate_true(fold, a)) ? (ast_expression*)b : (ast_expression*)a;
570         } else {
571             return fold_constgen_float (
572                 fold,
573                 ((expr) ? (fold_immediate_true(fold, a) || fold_immediate_true(fold, b))
574                         : (fold_immediate_true(fold, a) && fold_immediate_true(fold, b)))
575                             ? 1
576                             : 0
577             );
578         }
579     }
580     return NULL;
581 }
582
583 static GMQCC_INLINE ast_expression *fold_op_tern(fold_t *fold, ast_value *a, ast_value *b, ast_value *c) {
584     if (fold_can_1(a)) {
585         return fold_immediate_true(fold, a)
586                     ? (ast_expression*)b
587                     : (ast_expression*)c;
588     }
589     return NULL;
590 }
591
592 static GMQCC_INLINE ast_expression *fold_op_exp(fold_t *fold, ast_value *a, ast_value *b) {
593     if (fold_can_2(a, b))
594         return fold_constgen_float(fold, (qcfloat_t)powf(fold_immvalue_float(a), fold_immvalue_float(b)));
595     return NULL;
596 }
597
598 static GMQCC_INLINE ast_expression *fold_op_lteqgt(fold_t *fold, ast_value *a, ast_value *b) {
599     if (fold_can_2(a,b)) {
600         if (fold_immvalue_float(a) <  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[2];
601         if (fold_immvalue_float(a) == fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[0];
602         if (fold_immvalue_float(a) >  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[1];
603     }
604     return NULL;
605 }
606
607 static GMQCC_INLINE ast_expression *fold_op_cmp(fold_t *fold, ast_value *a, ast_value *b, bool ne) {
608     if (fold_can_2(a, b)) {
609         if (isfloat(a) && isfloat(b)) {
610             float la = fold_immvalue_float(a);
611             float lb = fold_immvalue_float(b);
612             return (ast_expression*)fold->imm_float[!(ne ? la == lb : la != lb)];
613         } if (isvector(a) && isvector(b)) {
614             vec3_t la = fold_immvalue_vector(a);
615             vec3_t lb = fold_immvalue_vector(b);
616             return (ast_expression*)fold->imm_float[!(ne ? vec3_cmp(la, lb) : !vec3_cmp(la, lb))];
617         }
618     }
619     return NULL;
620 }
621
622 static GMQCC_INLINE ast_expression *fold_op_bnot(fold_t *fold, ast_value *a) {
623     if (isfloat(a)) {
624         if (fold_can_1(a))
625             return fold_constgen_float(fold, -1-fold_immvalue_float(a));
626     } else {
627         if (isvector(a)) {
628             if (fold_can_1(a))
629                 return fold_constgen_vector(fold, vec3_not(fold_immvalue_vector(a)));
630         }
631     }
632     return NULL;
633 }
634
635 static GMQCC_INLINE ast_expression *fold_op_cross(fold_t *fold, ast_value *a, ast_value *b) {
636     if (fold_can_2(a, b))
637         return fold_constgen_vector(fold, vec3_cross(fold_immvalue_vector(a), fold_immvalue_vector(b)));
638     return NULL;
639 }
640
641 ast_expression *fold_op(fold_t *fold, const oper_info *info, ast_expression **opexprs) {
642     ast_value      *a = (ast_value*)opexprs[0];
643     ast_value      *b = (ast_value*)opexprs[1];
644     ast_value      *c = (ast_value*)opexprs[2];
645     ast_expression *e = NULL;
646
647     /* can a fold operation be applied to this operator usage? */
648     if (!info->folds)
649         return NULL;
650
651     switch(info->operands) {
652         case 3: if(!c) return NULL;
653         case 2: if(!b) return NULL;
654         case 1:
655         if(!a) {
656             compile_error(fold_ctx(fold), "internal error: fold_op no operands to fold\n");
657             return NULL;
658         }
659     }
660
661     /*
662      * we could use a boolean and default case but ironically gcc produces
663      * invalid broken assembly from that operation. clang/tcc get it right,
664      * but interestingly ignore compiling this to a jump-table when I do that,
665      * this happens to be the most efficent method, since you have per-level
666      * granularity on the pointer check happening only for the case you check
667      * it in. Opposed to the default method which would involve a boolean and
668      * pointer check after wards.
669      */
670     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
671         case opid##ARGS ARGS_OPID:                          \
672             if ((e = fold_op_##OP ARGS_FOLD)) {             \
673                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
674             }                                               \
675             return e
676
677     switch(info->id) {
678         fold_op_case(2, ('-', 'P'),    neg,    (fold, a));
679         fold_op_case(2, ('!', 'P'),    not,    (fold, a));
680         fold_op_case(1, ('+'),         add,    (fold, a, b));
681         fold_op_case(1, ('-'),         sub,    (fold, a, b));
682         fold_op_case(1, ('*'),         mul,    (fold, a, b));
683         fold_op_case(1, ('/'),         div,    (fold, a, b));
684         fold_op_case(1, ('%'),         mod,    (fold, a, b));
685         fold_op_case(1, ('|'),         bor,    (fold, a, b));
686         fold_op_case(1, ('&'),         band,   (fold, a, b));
687         fold_op_case(1, ('^'),         xor,    (fold, a, b));
688         fold_op_case(2, ('<', '<'),    lshift, (fold, a, b));
689         fold_op_case(2, ('>', '>'),    rshift, (fold, a, b));
690         fold_op_case(2, ('|', '|'),    andor,  (fold, a, b, true));
691         fold_op_case(2, ('&', '&'),    andor,  (fold, a, b, false));
692         fold_op_case(2, ('?', ':'),    tern,   (fold, a, b, c));
693         fold_op_case(2, ('*', '*'),    exp,    (fold, a, b));
694         fold_op_case(3, ('<','=','>'), lteqgt, (fold, a, b));
695         fold_op_case(2, ('!', '='),    cmp,    (fold, a, b, true));
696         fold_op_case(2, ('=', '='),    cmp,    (fold, a, b, false));
697         fold_op_case(2, ('~', 'P'),    bnot,   (fold, a));
698         fold_op_case(2, ('>', '<'),    cross,  (fold, a, b));
699     }
700     #undef fold_op_case
701     compile_error(fold_ctx(fold), "internal error: attempted to constant-fold for unsupported operator");
702     return NULL;
703 }
704
705 /*
706  * Constant folding for compiler intrinsics, simaler approach to operator
707  * folding, primarly: individual functions for each intrinsics to fold,
708  * and a generic selection function.
709  */
710 static GMQCC_INLINE ast_expression *fold_intrin_isfinite(fold_t *fold, ast_value *a) {
711     return fold_constgen_float(fold, isfinite(fold_immvalue_float(a)));
712 }
713 static GMQCC_INLINE ast_expression *fold_intrin_isinf(fold_t *fold, ast_value *a) {
714     return fold_constgen_float(fold, isinf(fold_immvalue_float(a)));
715 }
716 static GMQCC_INLINE ast_expression *fold_intrin_isnan(fold_t *fold, ast_value *a) {
717     return fold_constgen_float(fold, isnan(fold_immvalue_float(a)));
718 }
719 static GMQCC_INLINE ast_expression *fold_intrin_isnormal(fold_t *fold, ast_value *a) {
720     return fold_constgen_float(fold, isnormal(fold_immvalue_float(a)));
721 }
722 static GMQCC_INLINE ast_expression *fold_intrin_signbit(fold_t *fold, ast_value *a) {
723     return fold_constgen_float(fold, signbit(fold_immvalue_float(a)));
724 }
725 static GMQCC_INLINE ast_expression *fold_intirn_acosh(fold_t *fold, ast_value *a) {
726     return fold_constgen_float(fold, acoshf(fold_immvalue_float(a)));
727 }
728 static GMQCC_INLINE ast_expression *fold_intrin_asinh(fold_t *fold, ast_value *a) {
729     return fold_constgen_float(fold, asinhf(fold_immvalue_float(a)));
730 }
731 static GMQCC_INLINE ast_expression *fold_intrin_atanh(fold_t *fold, ast_value *a) {
732     return fold_constgen_float(fold, atanhf(fold_immvalue_float(a)));
733 }
734 static GMQCC_INLINE ast_expression *fold_intrin_exp(fold_t *fold, ast_value *a) {
735     return fold_constgen_float(fold, expf(fold_immvalue_float(a)));
736 }
737 static GMQCC_INLINE ast_expression *fold_intrin_exp2(fold_t *fold, ast_value *a) {
738     return fold_constgen_float(fold, exp2f(fold_immvalue_float(a)));
739 }
740 static GMQCC_INLINE ast_expression *fold_intrin_expm1(fold_t *fold, ast_value *a) {
741     return fold_constgen_float(fold, expm1f(fold_immvalue_float(a)));
742 }
743 static GMQCC_INLINE ast_expression *fold_intrin_mod(fold_t *fold, ast_value *lhs, ast_value *rhs) {
744     return fold_constgen_float(fold, fmodf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)));
745 }
746 static GMQCC_INLINE ast_expression *fold_intrin_pow(fold_t *fold, ast_value *lhs, ast_value *rhs) {
747     return fold_constgen_float(fold, powf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)));
748 }
749 static GMQCC_INLINE ast_expression *fold_intrin_fabs(fold_t *fold, ast_value *a) {
750     return fold_constgen_float(fold, fabsf(fold_immvalue_float(a)));
751 }
752
753
754 ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **arg) {
755     ast_expression *ret = NULL;
756     ast_value      *a   = (ast_value*)arg[0];
757     ast_value      *b   = (ast_value*)arg[1];
758
759     if (!strcmp(intrin, "isfinite")) ret = fold_intrin_isfinite(fold, a);
760     if (!strcmp(intrin, "isinf"))    ret = fold_intrin_isinf(fold, a);
761     if (!strcmp(intrin, "isnan"))    ret = fold_intrin_isnan(fold, a);
762     if (!strcmp(intrin, "isnormal")) ret = fold_intrin_isnormal(fold, a);
763     if (!strcmp(intrin, "signbit"))  ret = fold_intrin_signbit(fold, a);
764     if (!strcmp(intrin, "acosh"))    ret = fold_intirn_acosh(fold, a);
765     if (!strcmp(intrin, "asinh"))    ret = fold_intrin_asinh(fold, a);
766     if (!strcmp(intrin, "atanh"))    ret = fold_intrin_atanh(fold, a);
767     if (!strcmp(intrin, "exp"))      ret = fold_intrin_exp(fold, a);
768     if (!strcmp(intrin, "exp2"))     ret = fold_intrin_exp2(fold, a);
769     if (!strcmp(intrin, "expm1"))    ret = fold_intrin_expm1(fold, a);
770     if (!strcmp(intrin, "mod"))      ret = fold_intrin_mod(fold, a, b);
771     if (!strcmp(intrin, "pow"))      ret = fold_intrin_pow(fold, a, b);
772     if (!strcmp(intrin, "fabs"))     ret = fold_intrin_fabs(fold, a);
773
774     if (ret)
775         ++opts_optimizationcount[OPTIM_CONST_FOLD];
776
777     return ret;
778 }
779
780 /*
781  * These are all the actual constant folding methods that happen in between
782  * the AST/IR stage of the compiler , i.e eliminating branches for const
783  * expressions, which is the only supported thing so far. We undefine the
784  * testing macros here because an ir_value is differant than an ast_value.
785  */
786 #undef expect
787 #undef isfloat
788 #undef isstring
789 #undef isvector
790 #undef fold_immvalue_float
791 #undef fold_immvalue_string
792 #undef fold_immvalue_vector
793 #undef fold_can_1
794 #undef fold_can_2
795
796 #define isfloat(X)              ((X)->vtype == TYPE_FLOAT)
797 /*#define isstring(X)             ((X)->vtype == TYPE_STRING)*/
798 /*#define isvector(X)             ((X)->vtype == TYPE_VECTOR)*/
799 #define fold_immvalue_float(X)  ((X)->constval.vfloat)
800 #define fold_immvalue_vector(X) ((X)->constval.vvec)
801 /*#define fold_immvalue_string(X) ((X)->constval.vstring)*/
802 #define fold_can_1(X)           ((X)->hasvalue && (X)->cvq == CV_CONST)
803 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
804
805 static ast_expression *fold_superfluous(ast_expression *left, ast_expression *right, int op) {
806     ast_expression *swapped = NULL; /* using this as bool */
807     ast_value *load;
808
809     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
810         swapped = left;
811         left    = right;
812         right   = swapped;
813     }
814
815     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
816         return NULL;
817
818     switch (op) {
819         case INSTR_DIV_F:
820             if (swapped)
821                 return NULL;
822         case INSTR_MUL_F:
823             if (fold_immvalue_float(load) == 1.0f) {
824                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
825                 ast_unref(right);
826                 return left;
827             }
828             break;
829
830
831         case INSTR_SUB_F:
832             if (swapped)
833                 return NULL;
834         case INSTR_ADD_F:
835             if (fold_immvalue_float(load) == 0.0f) {
836                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
837                 ast_unref(right);
838                 return left;
839             }
840             break;
841
842         case INSTR_MUL_V:
843             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(1, 1, 1))) {
844                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
845                 ast_unref(right);
846                 return left;
847             }
848             break;
849
850         case INSTR_SUB_V:
851             if (swapped)
852                 return NULL;
853         case INSTR_ADD_V:
854             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(0, 0, 0))) {
855                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
856                 ast_unref(right);
857                 return left;
858             }
859             break;
860     }
861
862     return NULL;
863 }
864
865 ast_expression *fold_binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
866     ast_expression *ret = fold_superfluous(left, right, op);
867     if (ret)
868         return ret;
869     return (ast_expression*)ast_binary_new(ctx, op, left, right);
870 }
871
872 static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
873     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
874         ast_expression_codegen *cgen;
875         ir_block               *elide;
876         ir_value               *dummy;
877         bool                    istrue  = (fold_immvalue_float(condval) != 0.0f && branch->on_true);
878         bool                    isfalse = (fold_immvalue_float(condval) == 0.0f && branch->on_false);
879         ast_expression         *path    = (istrue)  ? branch->on_true  :
880                                           (isfalse) ? branch->on_false : NULL;
881         if (!path) {
882             /*
883              * no path to take implies that the evaluation is if(0) and there
884              * is no else block. so eliminate all the code.
885              */
886             ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
887             return true;
888         }
889
890         if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
891             return false;
892         if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
893             return false;
894         if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
895             return false;
896         /*
897          * now the branch has been eliminated and the correct block for the constant evaluation
898          * is expanded into the current block for the function.
899          */
900         func->curblock = elide;
901         ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
902         return true;
903     }
904     return -1; /* nothing done */
905 }
906
907 int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
908     return fold_cond(condval, func, (ast_ifthen*)branch);
909 }
910
911 int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
912     return fold_cond(condval, func, branch);
913 }