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