13a801c18a2ea687cccc0c74edf79a5c95dcfe7d
[platform/upstream/mesa.git] / src / mesa / shader / slang / slang_codegen.c
1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright (C) 2005-2007  Brian Paul   All Rights Reserved.
5  * Copyright (C) 2008 VMware, Inc.  All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included
15  * in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21  * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24
25 /**
26  * \file slang_codegen.c
27  * Generate IR tree from AST.
28  * \author Brian Paul
29  */
30
31
32 /***
33  *** NOTES:
34  *** The new_() functions return a new instance of a simple IR node.
35  *** The gen_() functions generate larger IR trees from the simple nodes.
36  ***/
37
38
39
40 #include "main/imports.h"
41 #include "main/macros.h"
42 #include "main/mtypes.h"
43 #include "shader/program.h"
44 #include "shader/prog_instruction.h"
45 #include "shader/prog_parameter.h"
46 #include "shader/prog_print.h"
47 #include "shader/prog_statevars.h"
48 #include "slang_typeinfo.h"
49 #include "slang_codegen.h"
50 #include "slang_compile.h"
51 #include "slang_label.h"
52 #include "slang_mem.h"
53 #include "slang_simplify.h"
54 #include "slang_emit.h"
55 #include "slang_vartable.h"
56 #include "slang_ir.h"
57 #include "slang_print.h"
58
59
60 /** Max iterations to unroll */
61 const GLuint MAX_FOR_LOOP_UNROLL_ITERATIONS = 32;
62
63 /** Max for-loop body size (in slang operations) to unroll */
64 const GLuint MAX_FOR_LOOP_UNROLL_BODY_SIZE = 50;
65
66 /** Max for-loop body complexity to unroll.
67  * We'll compute complexity as the product of the number of iterations
68  * and the size of the body.  So long-ish loops with very simple bodies
69  * can be unrolled, as well as short loops with larger bodies.
70  */
71 const GLuint MAX_FOR_LOOP_UNROLL_COMPLEXITY = 256;
72
73
74
75 static slang_ir_node *
76 _slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper);
77
78
79 /**
80  * Retrieves type information about an operation.
81  * Returns GL_TRUE on success.
82  * Returns GL_FALSE otherwise.
83  */
84 static GLboolean
85 typeof_operation(const struct slang_assemble_ctx_ *A,
86                  slang_operation *op,
87                  slang_typeinfo *ti)
88 {
89    return _slang_typeof_operation(op, &A->space, ti, A->atoms, A->log);
90 }
91
92
93 static GLboolean
94 is_sampler_type(const slang_fully_specified_type *t)
95 {
96    switch (t->specifier.type) {
97    case SLANG_SPEC_SAMPLER1D:
98    case SLANG_SPEC_SAMPLER2D:
99    case SLANG_SPEC_SAMPLER3D:
100    case SLANG_SPEC_SAMPLERCUBE:
101    case SLANG_SPEC_SAMPLER1DSHADOW:
102    case SLANG_SPEC_SAMPLER2DSHADOW:
103    case SLANG_SPEC_SAMPLER2DRECT:
104    case SLANG_SPEC_SAMPLER2DRECTSHADOW:
105       return GL_TRUE;
106    default:
107       return GL_FALSE;
108    }
109 }
110
111
112 /**
113  * Return the offset (in floats or ints) of the named field within
114  * the given struct.  Return -1 if field not found.
115  * If field is NULL, return the size of the struct instead.
116  */
117 static GLint
118 _slang_field_offset(const slang_type_specifier *spec, slang_atom field)
119 {
120    GLint offset = 0;
121    GLuint i;
122    for (i = 0; i < spec->_struct->fields->num_variables; i++) {
123       const slang_variable *v = spec->_struct->fields->variables[i];
124       const GLuint sz = _slang_sizeof_type_specifier(&v->type.specifier);
125       if (sz > 1) {
126          /* types larger than 1 float are register (4-float) aligned */
127          offset = (offset + 3) & ~3;
128       }
129       if (field && v->a_name == field) {
130          return offset;
131       }
132       offset += sz;
133    }
134    if (field)
135       return -1; /* field not found */
136    else
137       return offset;  /* struct size */
138 }
139
140
141 /**
142  * Return the size (in floats) of the given type specifier.
143  * If the size is greater than 4, the size should be a multiple of 4
144  * so that the correct number of 4-float registers are allocated.
145  * For example, a mat3x2 is size 12 because we want to store the
146  * 3 columns in 3 float[4] registers.
147  */
148 GLuint
149 _slang_sizeof_type_specifier(const slang_type_specifier *spec)
150 {
151    GLuint sz;
152    switch (spec->type) {
153    case SLANG_SPEC_VOID:
154       sz = 0;
155       break;
156    case SLANG_SPEC_BOOL:
157       sz = 1;
158       break;
159    case SLANG_SPEC_BVEC2:
160       sz = 2;
161       break;
162    case SLANG_SPEC_BVEC3:
163       sz = 3;
164       break;
165    case SLANG_SPEC_BVEC4:
166       sz = 4;
167       break;
168    case SLANG_SPEC_INT:
169       sz = 1;
170       break;
171    case SLANG_SPEC_IVEC2:
172       sz = 2;
173       break;
174    case SLANG_SPEC_IVEC3:
175       sz = 3;
176       break;
177    case SLANG_SPEC_IVEC4:
178       sz = 4;
179       break;
180    case SLANG_SPEC_FLOAT:
181       sz = 1;
182       break;
183    case SLANG_SPEC_VEC2:
184       sz = 2;
185       break;
186    case SLANG_SPEC_VEC3:
187       sz = 3;
188       break;
189    case SLANG_SPEC_VEC4:
190       sz = 4;
191       break;
192    case SLANG_SPEC_MAT2:
193       sz = 2 * 4; /* 2 columns (regs) */
194       break;
195    case SLANG_SPEC_MAT3:
196       sz = 3 * 4;
197       break;
198    case SLANG_SPEC_MAT4:
199       sz = 4 * 4;
200       break;
201    case SLANG_SPEC_MAT23:
202       sz = 2 * 4; /* 2 columns (regs) */
203       break;
204    case SLANG_SPEC_MAT32:
205       sz = 3 * 4; /* 3 columns (regs) */
206       break;
207    case SLANG_SPEC_MAT24:
208       sz = 2 * 4;
209       break;
210    case SLANG_SPEC_MAT42:
211       sz = 4 * 4; /* 4 columns (regs) */
212       break;
213    case SLANG_SPEC_MAT34:
214       sz = 3 * 4;
215       break;
216    case SLANG_SPEC_MAT43:
217       sz = 4 * 4; /* 4 columns (regs) */
218       break;
219    case SLANG_SPEC_SAMPLER1D:
220    case SLANG_SPEC_SAMPLER2D:
221    case SLANG_SPEC_SAMPLER3D:
222    case SLANG_SPEC_SAMPLERCUBE:
223    case SLANG_SPEC_SAMPLER1DSHADOW:
224    case SLANG_SPEC_SAMPLER2DSHADOW:
225    case SLANG_SPEC_SAMPLER2DRECT:
226    case SLANG_SPEC_SAMPLER2DRECTSHADOW:
227       sz = 1; /* a sampler is basically just an integer index */
228       break;
229    case SLANG_SPEC_STRUCT:
230       sz = _slang_field_offset(spec, 0); /* special use */
231       if (sz == 1) {
232          /* 1-float structs are actually troublesome to deal with since they
233           * might get placed at R.x, R.y, R.z or R.z.  Return size=2 to
234           * ensure the object is placed at R.x
235           */
236          sz = 2;
237       }
238       else if (sz > 4) {
239          sz = (sz + 3) & ~0x3; /* round up to multiple of four */
240       }
241       break;
242    case SLANG_SPEC_ARRAY:
243       sz = _slang_sizeof_type_specifier(spec->_array);
244       break;
245    default:
246       _mesa_problem(NULL, "Unexpected type in _slang_sizeof_type_specifier()");
247       sz = 0;
248    }
249
250    if (sz > 4) {
251       /* if size is > 4, it should be a multiple of four */
252       assert((sz & 0x3) == 0);
253    }
254    return sz;
255 }
256
257
258 /**
259  * Query variable/array length (number of elements).
260  * This is slightly non-trivial because there are two ways to express
261  * arrays: "float x[3]" vs. "float[3] x".
262  * \return the length of the array for the given variable, or 0 if not an array
263  */
264 static GLint
265 _slang_array_length(const slang_variable *var)
266 {
267    if (var->type.array_len > 0) {
268       /* Ex: float[4] x; */
269       return var->type.array_len;
270    }
271    if (var->array_len > 0) {
272       /* Ex: float x[4]; */
273       return var->array_len;
274    }
275    return 0;
276 }
277
278
279 /**
280  * Compute total size of array give size of element, number of elements.
281  * \return size in floats
282  */
283 static GLint
284 _slang_array_size(GLint elemSize, GLint arrayLen)
285 {
286    GLint total;
287    assert(elemSize > 0);
288    if (arrayLen > 1) {
289       /* round up base type to multiple of 4 */
290       total = ((elemSize + 3) & ~0x3) * MAX2(arrayLen, 1);
291    }
292    else {
293       total = elemSize;
294    }
295    return total;
296 }
297
298
299 /**
300  * Return the TEXTURE_*_INDEX value that corresponds to a sampler type,
301  * or -1 if the type is not a sampler.
302  */
303 static GLint
304 sampler_to_texture_index(const slang_type_specifier_type type)
305 {
306    switch (type) {
307    case SLANG_SPEC_SAMPLER1D:
308       return TEXTURE_1D_INDEX;
309    case SLANG_SPEC_SAMPLER2D:
310       return TEXTURE_2D_INDEX;
311    case SLANG_SPEC_SAMPLER3D:
312       return TEXTURE_3D_INDEX;
313    case SLANG_SPEC_SAMPLERCUBE:
314       return TEXTURE_CUBE_INDEX;
315    case SLANG_SPEC_SAMPLER1DSHADOW:
316       return TEXTURE_1D_INDEX; /* XXX fix */
317    case SLANG_SPEC_SAMPLER2DSHADOW:
318       return TEXTURE_2D_INDEX; /* XXX fix */
319    case SLANG_SPEC_SAMPLER2DRECT:
320       return TEXTURE_RECT_INDEX;
321    case SLANG_SPEC_SAMPLER2DRECTSHADOW:
322       return TEXTURE_RECT_INDEX; /* XXX fix */
323    default:
324       return -1;
325    }
326 }
327
328
329 #define SWIZZLE_ZWWW MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_W, SWIZZLE_W)
330
331 /**
332  * Return the VERT_ATTRIB_* or FRAG_ATTRIB_* value that corresponds to
333  * a vertex or fragment program input variable.  Return -1 if the input
334  * name is invalid.
335  * XXX return size too
336  */
337 static GLint
338 _slang_input_index(const char *name, GLenum target, GLuint *swizzleOut)
339 {
340    struct input_info {
341       const char *Name;
342       GLuint Attrib;
343       GLuint Swizzle;
344    };
345    static const struct input_info vertInputs[] = {
346       { "gl_Vertex", VERT_ATTRIB_POS, SWIZZLE_NOOP },
347       { "gl_Normal", VERT_ATTRIB_NORMAL, SWIZZLE_NOOP },
348       { "gl_Color", VERT_ATTRIB_COLOR0, SWIZZLE_NOOP },
349       { "gl_SecondaryColor", VERT_ATTRIB_COLOR1, SWIZZLE_NOOP },
350       { "gl_FogCoord", VERT_ATTRIB_FOG, SWIZZLE_XXXX },
351       { "gl_MultiTexCoord0", VERT_ATTRIB_TEX0, SWIZZLE_NOOP },
352       { "gl_MultiTexCoord1", VERT_ATTRIB_TEX1, SWIZZLE_NOOP },
353       { "gl_MultiTexCoord2", VERT_ATTRIB_TEX2, SWIZZLE_NOOP },
354       { "gl_MultiTexCoord3", VERT_ATTRIB_TEX3, SWIZZLE_NOOP },
355       { "gl_MultiTexCoord4", VERT_ATTRIB_TEX4, SWIZZLE_NOOP },
356       { "gl_MultiTexCoord5", VERT_ATTRIB_TEX5, SWIZZLE_NOOP },
357       { "gl_MultiTexCoord6", VERT_ATTRIB_TEX6, SWIZZLE_NOOP },
358       { "gl_MultiTexCoord7", VERT_ATTRIB_TEX7, SWIZZLE_NOOP },
359       { NULL, 0, SWIZZLE_NOOP }
360    };
361    static const struct input_info fragInputs[] = {
362       { "gl_FragCoord", FRAG_ATTRIB_WPOS, SWIZZLE_NOOP },
363       { "gl_Color", FRAG_ATTRIB_COL0, SWIZZLE_NOOP },
364       { "gl_SecondaryColor", FRAG_ATTRIB_COL1, SWIZZLE_NOOP },
365       { "gl_TexCoord", FRAG_ATTRIB_TEX0, SWIZZLE_NOOP },
366       /* note: we're packing several quantities into the fogcoord vector */
367       { "gl_FogFragCoord", FRAG_ATTRIB_FOGC, SWIZZLE_XXXX },
368       { "gl_FrontFacing", FRAG_ATTRIB_FOGC, SWIZZLE_YYYY }, /*XXX*/
369       { "gl_PointCoord", FRAG_ATTRIB_FOGC, SWIZZLE_ZWWW },
370       { NULL, 0, SWIZZLE_NOOP }
371    };
372    GLuint i;
373    const struct input_info *inputs
374       = (target == GL_VERTEX_PROGRAM_ARB) ? vertInputs : fragInputs;
375
376    ASSERT(MAX_TEXTURE_COORD_UNITS == 8); /* if this fails, fix vertInputs above */
377
378    for (i = 0; inputs[i].Name; i++) {
379       if (strcmp(inputs[i].Name, name) == 0) {
380          /* found */
381          *swizzleOut = inputs[i].Swizzle;
382          return inputs[i].Attrib;
383       }
384    }
385    return -1;
386 }
387
388
389 /**
390  * Return the VERT_RESULT_* or FRAG_RESULT_* value that corresponds to
391  * a vertex or fragment program output variable.  Return -1 for an invalid
392  * output name.
393  */
394 static GLint
395 _slang_output_index(const char *name, GLenum target)
396 {
397    struct output_info {
398       const char *Name;
399       GLuint Attrib;
400    };
401    static const struct output_info vertOutputs[] = {
402       { "gl_Position", VERT_RESULT_HPOS },
403       { "gl_FrontColor", VERT_RESULT_COL0 },
404       { "gl_BackColor", VERT_RESULT_BFC0 },
405       { "gl_FrontSecondaryColor", VERT_RESULT_COL1 },
406       { "gl_BackSecondaryColor", VERT_RESULT_BFC1 },
407       { "gl_TexCoord", VERT_RESULT_TEX0 },
408       { "gl_FogFragCoord", VERT_RESULT_FOGC },
409       { "gl_PointSize", VERT_RESULT_PSIZ },
410       { NULL, 0 }
411    };
412    static const struct output_info fragOutputs[] = {
413       { "gl_FragColor", FRAG_RESULT_COLOR },
414       { "gl_FragDepth", FRAG_RESULT_DEPTH },
415       { "gl_FragData", FRAG_RESULT_DATA0 },
416       { NULL, 0 }
417    };
418    GLuint i;
419    const struct output_info *outputs
420       = (target == GL_VERTEX_PROGRAM_ARB) ? vertOutputs : fragOutputs;
421
422    for (i = 0; outputs[i].Name; i++) {
423       if (strcmp(outputs[i].Name, name) == 0) {
424          /* found */
425          return outputs[i].Attrib;
426       }
427    }
428    return -1;
429 }
430
431
432
433 /**********************************************************************/
434
435
436 /**
437  * Map "_asm foo" to IR_FOO, etc.
438  */
439 typedef struct
440 {
441    const char *Name;
442    slang_ir_opcode Opcode;
443    GLuint HaveRetValue, NumParams;
444 } slang_asm_info;
445
446
447 static slang_asm_info AsmInfo[] = {
448    /* vec4 binary op */
449    { "vec4_add", IR_ADD, 1, 2 },
450    { "vec4_subtract", IR_SUB, 1, 2 },
451    { "vec4_multiply", IR_MUL, 1, 2 },
452    { "vec4_dot", IR_DOT4, 1, 2 },
453    { "vec3_dot", IR_DOT3, 1, 2 },
454    { "vec2_dot", IR_DOT2, 1, 2 },
455    { "vec3_nrm", IR_NRM3, 1, 1 },
456    { "vec4_nrm", IR_NRM4, 1, 1 },
457    { "vec3_cross", IR_CROSS, 1, 2 },
458    { "vec4_lrp", IR_LRP, 1, 3 },
459    { "vec4_min", IR_MIN, 1, 2 },
460    { "vec4_max", IR_MAX, 1, 2 },
461    { "vec4_clamp", IR_CLAMP, 1, 3 },
462    { "vec4_seq", IR_SEQUAL, 1, 2 },
463    { "vec4_sne", IR_SNEQUAL, 1, 2 },
464    { "vec4_sge", IR_SGE, 1, 2 },
465    { "vec4_sgt", IR_SGT, 1, 2 },
466    { "vec4_sle", IR_SLE, 1, 2 },
467    { "vec4_slt", IR_SLT, 1, 2 },
468    /* vec4 unary */
469    { "vec4_move", IR_MOVE, 1, 1 },
470    { "vec4_floor", IR_FLOOR, 1, 1 },
471    { "vec4_frac", IR_FRAC, 1, 1 },
472    { "vec4_abs", IR_ABS, 1, 1 },
473    { "vec4_negate", IR_NEG, 1, 1 },
474    { "vec4_ddx", IR_DDX, 1, 1 },
475    { "vec4_ddy", IR_DDY, 1, 1 },
476    /* float binary op */
477    { "float_power", IR_POW, 1, 2 },
478    /* texture / sampler */
479    { "vec4_tex_1d", IR_TEX, 1, 2 },
480    { "vec4_tex_1d_bias", IR_TEXB, 1, 2 },  /* 1d w/ bias */
481    { "vec4_tex_1d_proj", IR_TEXP, 1, 2 },  /* 1d w/ projection */
482    { "vec4_tex_2d", IR_TEX, 1, 2 },
483    { "vec4_tex_2d_bias", IR_TEXB, 1, 2 },  /* 2d w/ bias */
484    { "vec4_tex_2d_proj", IR_TEXP, 1, 2 },  /* 2d w/ projection */
485    { "vec4_tex_3d", IR_TEX, 1, 2 },
486    { "vec4_tex_3d_bias", IR_TEXB, 1, 2 },  /* 3d w/ bias */
487    { "vec4_tex_3d_proj", IR_TEXP, 1, 2 },  /* 3d w/ projection */
488    { "vec4_tex_cube", IR_TEX, 1, 2 },      /* cubemap */
489    { "vec4_tex_rect", IR_TEX, 1, 2 },      /* rectangle */
490    { "vec4_tex_rect_bias", IR_TEX, 1, 2 }, /* rectangle w/ projection */
491
492    /* texture / sampler but with shadow comparison */
493    { "vec4_tex_1d_shadow", IR_TEX_SH, 1, 2 },
494    { "vec4_tex_1d_bias_shadow", IR_TEXB_SH, 1, 2 },
495    { "vec4_tex_1d_proj_shadow", IR_TEXP_SH, 1, 2 },
496    { "vec4_tex_2d_shadow", IR_TEX_SH, 1, 2 },
497    { "vec4_tex_2d_bias_shadow", IR_TEXB_SH, 1, 2 },
498    { "vec4_tex_2d_proj_shadow", IR_TEXP_SH, 1, 2 },
499    { "vec4_tex_rect_shadow", IR_TEX_SH, 1, 2 },
500    { "vec4_tex_rect_proj_shadow", IR_TEXP_SH, 1, 2 },
501
502    /* unary op */
503    { "ivec4_to_vec4", IR_I_TO_F, 1, 1 }, /* int[4] to float[4] */
504    { "vec4_to_ivec4", IR_F_TO_I, 1, 1 },  /* float[4] to int[4] */
505    { "float_exp", IR_EXP, 1, 1 },
506    { "float_exp2", IR_EXP2, 1, 1 },
507    { "float_log2", IR_LOG2, 1, 1 },
508    { "float_rsq", IR_RSQ, 1, 1 },
509    { "float_rcp", IR_RCP, 1, 1 },
510    { "float_sine", IR_SIN, 1, 1 },
511    { "float_cosine", IR_COS, 1, 1 },
512    { "float_noise1", IR_NOISE1, 1, 1},
513    { "float_noise2", IR_NOISE2, 1, 1},
514    { "float_noise3", IR_NOISE3, 1, 1},
515    { "float_noise4", IR_NOISE4, 1, 1},
516
517    { NULL, IR_NOP, 0, 0 }
518 };
519
520
521 static slang_ir_node *
522 new_node3(slang_ir_opcode op,
523           slang_ir_node *c0, slang_ir_node *c1, slang_ir_node *c2)
524 {
525    slang_ir_node *n = (slang_ir_node *) _slang_alloc(sizeof(slang_ir_node));
526    if (n) {
527       n->Opcode = op;
528       n->Children[0] = c0;
529       n->Children[1] = c1;
530       n->Children[2] = c2;
531       n->InstLocation = -1;
532    }
533    return n;
534 }
535
536 static slang_ir_node *
537 new_node2(slang_ir_opcode op, slang_ir_node *c0, slang_ir_node *c1)
538 {
539    return new_node3(op, c0, c1, NULL);
540 }
541
542 static slang_ir_node *
543 new_node1(slang_ir_opcode op, slang_ir_node *c0)
544 {
545    return new_node3(op, c0, NULL, NULL);
546 }
547
548 static slang_ir_node *
549 new_node0(slang_ir_opcode op)
550 {
551    return new_node3(op, NULL, NULL, NULL);
552 }
553
554
555 /**
556  * Create sequence of two nodes.
557  */
558 static slang_ir_node *
559 new_seq(slang_ir_node *left, slang_ir_node *right)
560 {
561    if (!left)
562       return right;
563    if (!right)
564       return left;
565    return new_node2(IR_SEQ, left, right);
566 }
567
568 static slang_ir_node *
569 new_label(slang_label *label)
570 {
571    slang_ir_node *n = new_node0(IR_LABEL);
572    assert(label);
573    if (n)
574       n->Label = label;
575    return n;
576 }
577
578 static slang_ir_node *
579 new_float_literal(const float v[4], GLuint size)
580 {
581    slang_ir_node *n = new_node0(IR_FLOAT);
582    assert(size <= 4);
583    COPY_4V(n->Value, v);
584    /* allocate a storage object, but compute actual location (Index) later */
585    n->Store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
586    return n;
587 }
588
589
590 static slang_ir_node *
591 new_not(slang_ir_node *n)
592 {
593    return new_node1(IR_NOT, n);
594 }
595
596
597 /**
598  * Non-inlined function call.
599  */
600 static slang_ir_node *
601 new_function_call(slang_ir_node *code, slang_label *name)
602 {
603    slang_ir_node *n = new_node1(IR_CALL, code);
604    assert(name);
605    if (n)
606       n->Label = name;
607    return n;
608 }
609
610
611 /**
612  * Unconditional jump.
613  */
614 static slang_ir_node *
615 new_return(slang_label *dest)
616 {
617    slang_ir_node *n = new_node0(IR_RETURN);
618    assert(dest);
619    if (n)
620       n->Label = dest;
621    return n;
622 }
623
624
625 static slang_ir_node *
626 new_loop(slang_ir_node *body)
627 {
628    return new_node1(IR_LOOP, body);
629 }
630
631
632 static slang_ir_node *
633 new_break(slang_ir_node *loopNode)
634 {
635    slang_ir_node *n = new_node0(IR_BREAK);
636    assert(loopNode);
637    assert(loopNode->Opcode == IR_LOOP);
638    if (n) {
639       /* insert this node at head of linked list */
640       n->List = loopNode->List;
641       loopNode->List = n;
642    }
643    return n;
644 }
645
646
647 /**
648  * Make new IR_BREAK_IF_TRUE.
649  */
650 static slang_ir_node *
651 new_break_if_true(slang_ir_node *loopNode, slang_ir_node *cond)
652 {
653    slang_ir_node *n;
654    assert(loopNode);
655    assert(loopNode->Opcode == IR_LOOP);
656    n = new_node1(IR_BREAK_IF_TRUE, cond);
657    if (n) {
658       /* insert this node at head of linked list */
659       n->List = loopNode->List;
660       loopNode->List = n;
661    }
662    return n;
663 }
664
665
666 /**
667  * Make new IR_CONT_IF_TRUE node.
668  */
669 static slang_ir_node *
670 new_cont_if_true(slang_ir_node *loopNode, slang_ir_node *cond)
671 {
672    slang_ir_node *n;
673    assert(loopNode);
674    assert(loopNode->Opcode == IR_LOOP);
675    n = new_node1(IR_CONT_IF_TRUE, cond);
676    if (n) {
677       /* insert this node at head of linked list */
678       n->List = loopNode->List;
679       loopNode->List = n;
680    }
681    return n;
682 }
683
684
685 static slang_ir_node *
686 new_cond(slang_ir_node *n)
687 {
688    slang_ir_node *c = new_node1(IR_COND, n);
689    return c;
690 }
691
692
693 static slang_ir_node *
694 new_if(slang_ir_node *cond, slang_ir_node *ifPart, slang_ir_node *elsePart)
695 {
696    return new_node3(IR_IF, cond, ifPart, elsePart);
697 }
698
699
700 /**
701  * New IR_VAR node - a reference to a previously declared variable.
702  */
703 static slang_ir_node *
704 new_var(slang_assemble_ctx *A, slang_variable *var)
705 {
706    slang_ir_node *n = new_node0(IR_VAR);
707    if (n) {
708       ASSERT(var);
709       ASSERT(var->store);
710       ASSERT(!n->Store);
711       ASSERT(!n->Var);
712
713       /* Set IR node's Var and Store pointers */
714       n->Var = var;
715       n->Store = var->store;
716    }
717    return n;
718 }
719
720
721 /**
722  * Check if the given function is really just a wrapper for a
723  * basic assembly instruction.
724  */
725 static GLboolean
726 slang_is_asm_function(const slang_function *fun)
727 {
728    if (fun->body->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE &&
729        fun->body->num_children == 1 &&
730        fun->body->children[0].type == SLANG_OPER_ASM) {
731       return GL_TRUE;
732    }
733    return GL_FALSE;
734 }
735
736
737 static GLboolean
738 _slang_is_noop(const slang_operation *oper)
739 {
740    if (!oper ||
741        oper->type == SLANG_OPER_VOID ||
742        (oper->num_children == 1 && oper->children[0].type == SLANG_OPER_VOID))
743       return GL_TRUE;
744    else
745       return GL_FALSE;
746 }
747
748
749 /**
750  * Recursively search tree for a node of the given type.
751  */
752 static slang_operation *
753 _slang_find_node_type(slang_operation *oper, slang_operation_type type)
754 {
755    GLuint i;
756    if (oper->type == type)
757       return oper;
758    for (i = 0; i < oper->num_children; i++) {
759       slang_operation *p = _slang_find_node_type(&oper->children[i], type);
760       if (p)
761          return p;
762    }
763    return NULL;
764 }
765
766
767 /**
768  * Count the number of operations of the given time rooted at 'oper'.
769  */
770 static GLuint
771 _slang_count_node_type(slang_operation *oper, slang_operation_type type)
772 {
773    GLuint i, count = 0;
774    if (oper->type == type) {
775       return 1;
776    }
777    for (i = 0; i < oper->num_children; i++) {
778       count += _slang_count_node_type(&oper->children[i], type);
779    }
780    return count;
781 }
782
783
784 /**
785  * Check if the 'return' statement found under 'oper' is a "tail return"
786  * that can be no-op'd.  For example:
787  *
788  * void func(void)
789  * {
790  *    .. do something ..
791  *    return;   // this is a no-op
792  * }
793  *
794  * This is used when determining if a function can be inlined.  If the
795  * 'return' is not the last statement, we can't inline the function since
796  * we still need the semantic behaviour of the 'return' but we don't want
797  * to accidentally return from the _calling_ function.  We'd need to use an
798  * unconditional branch, but we don't have such a GPU instruction (not
799  * always, at least).
800  */
801 static GLboolean
802 _slang_is_tail_return(const slang_operation *oper)
803 {
804    GLuint k = oper->num_children;
805
806    while (k > 0) {
807       const slang_operation *last = &oper->children[k - 1];
808       if (last->type == SLANG_OPER_RETURN)
809          return GL_TRUE;
810       else if (last->type == SLANG_OPER_IDENTIFIER ||
811                last->type == SLANG_OPER_LABEL)
812          k--; /* try prev child */
813       else if (last->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE ||
814                last->type == SLANG_OPER_BLOCK_NEW_SCOPE)
815          /* try sub-children */
816          return _slang_is_tail_return(last);
817       else
818          break;
819    }
820
821    return GL_FALSE;
822 }
823
824
825 static void
826 slang_resolve_variable(slang_operation *oper)
827 {
828    if (oper->type == SLANG_OPER_IDENTIFIER && !oper->var) {
829       oper->var = _slang_variable_locate(oper->locals, oper->a_id, GL_TRUE);
830    }
831 }
832
833
834 /**
835  * Replace particular variables (SLANG_OPER_IDENTIFIER) with new expressions.
836  */
837 static void
838 slang_substitute(slang_assemble_ctx *A, slang_operation *oper,
839                  GLuint substCount, slang_variable **substOld,
840                  slang_operation **substNew, GLboolean isLHS)
841 {
842    switch (oper->type) {
843    case SLANG_OPER_VARIABLE_DECL:
844       {
845          slang_variable *v = _slang_variable_locate(oper->locals,
846                                                     oper->a_id, GL_TRUE);
847          assert(v);
848          if (v->initializer && oper->num_children == 0) {
849             /* set child of oper to copy of initializer */
850             oper->num_children = 1;
851             oper->children = slang_operation_new(1);
852             slang_operation_copy(&oper->children[0], v->initializer);
853          }
854          if (oper->num_children == 1) {
855             /* the initializer */
856             slang_substitute(A, &oper->children[0], substCount,
857                              substOld, substNew, GL_FALSE);
858          }
859       }
860       break;
861    case SLANG_OPER_IDENTIFIER:
862       assert(oper->num_children == 0);
863       if (1/**!isLHS XXX FIX */) {
864          slang_atom id = oper->a_id;
865          slang_variable *v;
866          GLuint i;
867          v = _slang_variable_locate(oper->locals, id, GL_TRUE);
868          if (!v) {
869             _mesa_problem(NULL, "var %s not found!\n", (char *) oper->a_id);
870             return;
871          }
872
873          /* look for a substitution */
874          for (i = 0; i < substCount; i++) {
875             if (v == substOld[i]) {
876                /* OK, replace this SLANG_OPER_IDENTIFIER with a new expr */
877 #if 0 /* DEBUG only */
878                if (substNew[i]->type == SLANG_OPER_IDENTIFIER) {
879                   assert(substNew[i]->var);
880                   assert(substNew[i]->var->a_name);
881                   printf("Substitute %s with %s in id node %p\n",
882                          (char*)v->a_name, (char*) substNew[i]->var->a_name,
883                          (void*) oper);
884                }
885                else {
886                   printf("Substitute %s with %f in id node %p\n",
887                          (char*)v->a_name, substNew[i]->literal[0],
888                          (void*) oper);
889                }
890 #endif
891                slang_operation_copy(oper, substNew[i]);
892                break;
893             }
894          }
895       }
896       break;
897
898    case SLANG_OPER_RETURN:
899       /* do return replacement here too */
900       assert(oper->num_children == 0 || oper->num_children == 1);
901       if (oper->num_children == 1 && !_slang_is_noop(&oper->children[0])) {
902          /* replace:
903           *   return expr;
904           * with:
905           *   __retVal = expr;
906           *   return;
907           * then do substitutions on the assignment.
908           */
909          slang_operation *blockOper, *assignOper, *returnOper;
910
911          /* check if function actually has a return type */
912          assert(A->CurFunction);
913          if (A->CurFunction->header.type.specifier.type == SLANG_SPEC_VOID) {
914             slang_info_log_error(A->log, "illegal return expression");
915             return;
916          }
917
918          blockOper = slang_operation_new(1);
919          blockOper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE;
920          blockOper->num_children = 2;
921          blockOper->locals->outer_scope = oper->locals->outer_scope;
922          blockOper->children = slang_operation_new(2);
923          assignOper = blockOper->children + 0;
924          returnOper = blockOper->children + 1;
925
926          assignOper->type = SLANG_OPER_ASSIGN;
927          assignOper->num_children = 2;
928          assignOper->locals->outer_scope = blockOper->locals;
929          assignOper->children = slang_operation_new(2);
930          assignOper->children[0].type = SLANG_OPER_IDENTIFIER;
931          assignOper->children[0].a_id = slang_atom_pool_atom(A->atoms, "__retVal");
932          assignOper->children[0].locals->outer_scope = assignOper->locals;
933
934          slang_operation_copy(&assignOper->children[1],
935                               &oper->children[0]);
936
937          returnOper->type = SLANG_OPER_RETURN; /* return w/ no value */
938          assert(returnOper->num_children == 0);
939
940          /* do substitutions on the "__retVal = expr" sub-tree */
941          slang_substitute(A, assignOper,
942                           substCount, substOld, substNew, GL_FALSE);
943
944          /* install new code */
945          slang_operation_copy(oper, blockOper);
946          slang_operation_destruct(blockOper);
947       }
948       else {
949          /* check if return value was expected */
950          assert(A->CurFunction);
951          if (A->CurFunction->header.type.specifier.type != SLANG_SPEC_VOID) {
952             slang_info_log_error(A->log, "return statement requires an expression");
953             return;
954          }
955       }
956       break;
957
958    case SLANG_OPER_ASSIGN:
959    case SLANG_OPER_SUBSCRIPT:
960       /* special case:
961        * child[0] can't have substitutions but child[1] can.
962        */
963       slang_substitute(A, &oper->children[0],
964                        substCount, substOld, substNew, GL_TRUE);
965       slang_substitute(A, &oper->children[1],
966                        substCount, substOld, substNew, GL_FALSE);
967       break;
968    case SLANG_OPER_FIELD:
969       /* XXX NEW - test */
970       slang_substitute(A, &oper->children[0],
971                        substCount, substOld, substNew, GL_TRUE);
972       break;
973    default:
974       {
975          GLuint i;
976          for (i = 0; i < oper->num_children; i++) 
977             slang_substitute(A, &oper->children[i],
978                              substCount, substOld, substNew, GL_FALSE);
979       }
980    }
981 }
982
983
984 /**
985  * Produce inline code for a call to an assembly instruction.
986  * This is typically used to compile a call to a built-in function like this:
987  *
988  * vec4 mix(const vec4 x, const vec4 y, const vec4 a)
989  * {
990  *    __asm vec4_lrp __retVal, a, y, x;
991  * }
992  *
993  *
994  * A call to
995  *     r = mix(p1, p2, p3);
996  *
997  * Becomes:
998  *
999  *              mov
1000  *             /   \
1001  *            r   vec4_lrp
1002  *                 /  |  \
1003  *                p3  p2  p1
1004  *
1005  * We basically translate a SLANG_OPER_CALL into a SLANG_OPER_ASM.
1006  */
1007 static slang_operation *
1008 slang_inline_asm_function(slang_assemble_ctx *A,
1009                           slang_function *fun, slang_operation *oper)
1010 {
1011    const GLuint numArgs = oper->num_children;
1012    GLuint i;
1013    slang_operation *inlined;
1014    const GLboolean haveRetValue = _slang_function_has_return_value(fun);
1015    slang_variable **substOld;
1016    slang_operation **substNew;
1017
1018    ASSERT(slang_is_asm_function(fun));
1019    ASSERT(fun->param_count == numArgs + haveRetValue);
1020
1021    /*
1022    printf("Inline %s as %s\n",
1023           (char*) fun->header.a_name,
1024           (char*) fun->body->children[0].a_id);
1025    */
1026
1027    /*
1028     * We'll substitute formal params with actual args in the asm call.
1029     */
1030    substOld = (slang_variable **)
1031       _slang_alloc(numArgs * sizeof(slang_variable *));
1032    substNew = (slang_operation **)
1033       _slang_alloc(numArgs * sizeof(slang_operation *));
1034    for (i = 0; i < numArgs; i++) {
1035       substOld[i] = fun->parameters->variables[i];
1036       substNew[i] = oper->children + i;
1037    }
1038
1039    /* make a copy of the code to inline */
1040    inlined = slang_operation_new(1);
1041    slang_operation_copy(inlined, &fun->body->children[0]);
1042    if (haveRetValue) {
1043       /* get rid of the __retVal child */
1044       inlined->num_children--;
1045       for (i = 0; i < inlined->num_children; i++) {
1046          inlined->children[i] = inlined->children[i + 1];
1047       }
1048    }
1049
1050    /* now do formal->actual substitutions */
1051    slang_substitute(A, inlined, numArgs, substOld, substNew, GL_FALSE);
1052
1053    _slang_free(substOld);
1054    _slang_free(substNew);
1055
1056 #if 0
1057    printf("+++++++++++++ inlined asm function %s +++++++++++++\n",
1058           (char *) fun->header.a_name);
1059    slang_print_tree(inlined, 3);
1060    printf("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
1061 #endif
1062
1063    return inlined;
1064 }
1065
1066
1067 /**
1068  * Inline the given function call operation.
1069  * Return a new slang_operation that corresponds to the inlined code.
1070  */
1071 static slang_operation *
1072 slang_inline_function_call(slang_assemble_ctx * A, slang_function *fun,
1073                            slang_operation *oper, slang_operation *returnOper)
1074 {
1075    typedef enum {
1076       SUBST = 1,
1077       COPY_IN,
1078       COPY_OUT
1079    } ParamMode;
1080    ParamMode *paramMode;
1081    const GLboolean haveRetValue = _slang_function_has_return_value(fun);
1082    const GLuint numArgs = oper->num_children;
1083    const GLuint totalArgs = numArgs + haveRetValue;
1084    slang_operation *args = oper->children;
1085    slang_operation *inlined, *top;
1086    slang_variable **substOld;
1087    slang_operation **substNew;
1088    GLuint substCount, numCopyIn, i;
1089    slang_function *prevFunction;
1090    slang_variable_scope *newScope = NULL;
1091
1092    /* save / push */
1093    prevFunction = A->CurFunction;
1094    A->CurFunction = fun;
1095
1096    /*assert(oper->type == SLANG_OPER_CALL); (or (matrix) multiply, etc) */
1097    assert(fun->param_count == totalArgs);
1098
1099    /* allocate temporary arrays */
1100    paramMode = (ParamMode *)
1101       _slang_alloc(totalArgs * sizeof(ParamMode));
1102    substOld = (slang_variable **)
1103       _slang_alloc(totalArgs * sizeof(slang_variable *));
1104    substNew = (slang_operation **)
1105       _slang_alloc(totalArgs * sizeof(slang_operation *));
1106
1107 #if 0
1108    printf("\nInline call to %s  (total vars=%d  nparams=%d)\n",
1109           (char *) fun->header.a_name,
1110           fun->parameters->num_variables, numArgs);
1111 #endif
1112
1113    if (haveRetValue && !returnOper) {
1114       /* Create 3-child comma sequence for inlined code:
1115        * child[0]:  declare __resultTmp
1116        * child[1]:  inlined function body
1117        * child[2]:  __resultTmp
1118        */
1119       slang_operation *commaSeq;
1120       slang_operation *declOper = NULL;
1121       slang_variable *resultVar;
1122
1123       commaSeq = slang_operation_new(1);
1124       commaSeq->type = SLANG_OPER_SEQUENCE;
1125       assert(commaSeq->locals);
1126       commaSeq->locals->outer_scope = oper->locals->outer_scope;
1127       commaSeq->num_children = 3;
1128       commaSeq->children = slang_operation_new(3);
1129       /* allocate the return var */
1130       resultVar = slang_variable_scope_grow(commaSeq->locals);
1131       /*
1132       printf("Alloc __resultTmp in scope %p for retval of calling %s\n",
1133              (void*)commaSeq->locals, (char *) fun->header.a_name);
1134       */
1135
1136       resultVar->a_name = slang_atom_pool_atom(A->atoms, "__resultTmp");
1137       resultVar->type = fun->header.type; /* XXX copy? */
1138       resultVar->isTemp = GL_TRUE;
1139
1140       /* child[0] = __resultTmp declaration */
1141       declOper = &commaSeq->children[0];
1142       declOper->type = SLANG_OPER_VARIABLE_DECL;
1143       declOper->a_id = resultVar->a_name;
1144       declOper->locals->outer_scope = commaSeq->locals;
1145
1146       /* child[1] = function body */
1147       inlined = &commaSeq->children[1];
1148       inlined->locals->outer_scope = commaSeq->locals;
1149
1150       /* child[2] = __resultTmp reference */
1151       returnOper = &commaSeq->children[2];
1152       returnOper->type = SLANG_OPER_IDENTIFIER;
1153       returnOper->a_id = resultVar->a_name;
1154       returnOper->locals->outer_scope = commaSeq->locals;
1155
1156       top = commaSeq;
1157    }
1158    else {
1159       top = inlined = slang_operation_new(1);
1160       /* XXXX this may be inappropriate!!!! */
1161       inlined->locals->outer_scope = oper->locals->outer_scope;
1162    }
1163
1164
1165    assert(inlined->locals);
1166
1167    /* Examine the parameters, look for inout/out params, look for possible
1168     * substitutions, etc:
1169     *    param type      behaviour
1170     *     in             copy actual to local
1171     *     const in       substitute param with actual
1172     *     out            copy out
1173     */
1174    substCount = 0;
1175    for (i = 0; i < totalArgs; i++) {
1176       slang_variable *p = fun->parameters->variables[i];
1177       /*
1178       printf("Param %d: %s %s \n", i,
1179              slang_type_qual_string(p->type.qualifier),
1180              (char *) p->a_name);
1181       */
1182       if (p->type.qualifier == SLANG_QUAL_INOUT ||
1183           p->type.qualifier == SLANG_QUAL_OUT) {
1184          /* an output param */
1185          slang_operation *arg;
1186          if (i < numArgs)
1187             arg = &args[i];
1188          else
1189             arg = returnOper;
1190          paramMode[i] = SUBST;
1191
1192          if (arg->type == SLANG_OPER_IDENTIFIER)
1193             slang_resolve_variable(arg);
1194
1195          /* replace parameter 'p' with argument 'arg' */
1196          substOld[substCount] = p;
1197          substNew[substCount] = arg; /* will get copied */
1198          substCount++;
1199       }
1200       else if (p->type.qualifier == SLANG_QUAL_CONST) {
1201          /* a constant input param */
1202          if (args[i].type == SLANG_OPER_IDENTIFIER ||
1203              args[i].type == SLANG_OPER_LITERAL_FLOAT) {
1204             /* replace all occurances of this parameter variable with the
1205              * actual argument variable or a literal.
1206              */
1207             paramMode[i] = SUBST;
1208             slang_resolve_variable(&args[i]);
1209             substOld[substCount] = p;
1210             substNew[substCount] = &args[i]; /* will get copied */
1211             substCount++;
1212          }
1213          else {
1214             paramMode[i] = COPY_IN;
1215          }
1216       }
1217       else {
1218          paramMode[i] = COPY_IN;
1219       }
1220       assert(paramMode[i]);
1221    }
1222
1223    /* actual code inlining: */
1224    slang_operation_copy(inlined, fun->body);
1225
1226    /*** XXX review this */
1227    assert(inlined->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE ||
1228           inlined->type == SLANG_OPER_BLOCK_NEW_SCOPE);
1229    inlined->type = SLANG_OPER_BLOCK_NEW_SCOPE;
1230
1231 #if 0
1232    printf("======================= orig body code ======================\n");
1233    printf("=== params scope = %p\n", (void*) fun->parameters);
1234    slang_print_tree(fun->body, 8);
1235    printf("======================= copied code =========================\n");
1236    slang_print_tree(inlined, 8);
1237 #endif
1238
1239    /* do parameter substitution in inlined code: */
1240    slang_substitute(A, inlined, substCount, substOld, substNew, GL_FALSE);
1241
1242 #if 0
1243    printf("======================= subst code ==========================\n");
1244    slang_print_tree(inlined, 8);
1245    printf("=============================================================\n");
1246 #endif
1247
1248    /* New prolog statements: (inserted before the inlined code)
1249     * Copy the 'in' arguments.
1250     */
1251    numCopyIn = 0;
1252    for (i = 0; i < numArgs; i++) {
1253       if (paramMode[i] == COPY_IN) {
1254          slang_variable *p = fun->parameters->variables[i];
1255          /* declare parameter 'p' */
1256          slang_operation *decl = slang_operation_insert(&inlined->num_children,
1257                                                         &inlined->children,
1258                                                         numCopyIn);
1259
1260          decl->type = SLANG_OPER_VARIABLE_DECL;
1261          assert(decl->locals);
1262          decl->locals->outer_scope = inlined->locals;
1263          decl->a_id = p->a_name;
1264          decl->num_children = 1;
1265          decl->children = slang_operation_new(1);
1266
1267          /* child[0] is the var's initializer */
1268          slang_operation_copy(&decl->children[0], args + i);
1269
1270          /* add parameter 'p' to the local variable scope here */
1271          {
1272             slang_variable *pCopy = slang_variable_scope_grow(inlined->locals);
1273             pCopy->type = p->type;
1274             pCopy->a_name = p->a_name;
1275             pCopy->array_len = p->array_len;
1276          }
1277
1278          newScope = inlined->locals;
1279          numCopyIn++;
1280       }
1281    }
1282
1283    /* Now add copies of the function's local vars to the new variable scope */
1284    for (i = totalArgs; i < fun->parameters->num_variables; i++) {
1285       slang_variable *p = fun->parameters->variables[i];
1286       slang_variable *pCopy = slang_variable_scope_grow(inlined->locals);
1287       pCopy->type = p->type;
1288       pCopy->a_name = p->a_name;
1289       pCopy->array_len = p->array_len;
1290    }
1291
1292
1293    /* New epilog statements:
1294     * 1. Create end of function label to jump to from return statements.
1295     * 2. Copy the 'out' parameter vars
1296     */
1297    {
1298       slang_operation *lab = slang_operation_insert(&inlined->num_children,
1299                                                     &inlined->children,
1300                                                     inlined->num_children);
1301       lab->type = SLANG_OPER_LABEL;
1302       lab->label = A->curFuncEndLabel;
1303    }
1304
1305    for (i = 0; i < totalArgs; i++) {
1306       if (paramMode[i] == COPY_OUT) {
1307          const slang_variable *p = fun->parameters->variables[i];
1308          /* actualCallVar = outParam */
1309          /*if (i > 0 || !haveRetValue)*/
1310          slang_operation *ass = slang_operation_insert(&inlined->num_children,
1311                                                        &inlined->children,
1312                                                        inlined->num_children);
1313          ass->type = SLANG_OPER_ASSIGN;
1314          ass->num_children = 2;
1315          ass->locals->outer_scope = inlined->locals;
1316          ass->children = slang_operation_new(2);
1317          ass->children[0] = args[i]; /*XXX copy */
1318          ass->children[1].type = SLANG_OPER_IDENTIFIER;
1319          ass->children[1].a_id = p->a_name;
1320          ass->children[1].locals->outer_scope = ass->locals;
1321       }
1322    }
1323
1324    _slang_free(paramMode);
1325    _slang_free(substOld);
1326    _slang_free(substNew);
1327
1328    /* Update scoping to use the new local vars instead of the
1329     * original function's vars.  This is especially important
1330     * for nested inlining.
1331     */
1332    if (newScope)
1333       slang_replace_scope(inlined, fun->parameters, newScope);
1334
1335 #if 0
1336    printf("Done Inline call to %s  (total vars=%d  nparams=%d)\n\n",
1337           (char *) fun->header.a_name,
1338           fun->parameters->num_variables, numArgs);
1339    slang_print_tree(top, 0);
1340 #endif
1341
1342    /* pop */
1343    A->CurFunction = prevFunction;
1344
1345    return top;
1346 }
1347
1348
1349 static slang_ir_node *
1350 _slang_gen_function_call(slang_assemble_ctx *A, slang_function *fun,
1351                          slang_operation *oper, slang_operation *dest)
1352 {
1353    slang_ir_node *n;
1354    slang_operation *inlined;
1355    slang_label *prevFuncEndLabel;
1356    char name[200];
1357
1358    prevFuncEndLabel = A->curFuncEndLabel;
1359    sprintf(name, "__endOfFunc_%s_", (char *) fun->header.a_name);
1360    A->curFuncEndLabel = _slang_label_new(name);
1361    assert(A->curFuncEndLabel);
1362
1363    if (slang_is_asm_function(fun) && !dest) {
1364       /* assemble assembly function - tree style */
1365       inlined = slang_inline_asm_function(A, fun, oper);
1366    }
1367    else {
1368       /* non-assembly function */
1369       /* We always generate an "inline-able" block of code here.
1370        * We may either:
1371        *  1. insert the inline code
1372        *  2. Generate a call to the "inline" code as a subroutine
1373        */
1374
1375
1376       slang_operation *ret = NULL;
1377
1378       inlined = slang_inline_function_call(A, fun, oper, dest);
1379       if (!inlined)
1380          return NULL;
1381
1382       ret = _slang_find_node_type(inlined, SLANG_OPER_RETURN);
1383       if (ret) {
1384          /* check if this is a "tail" return */
1385          if (_slang_count_node_type(inlined, SLANG_OPER_RETURN) == 1 &&
1386              _slang_is_tail_return(inlined)) {
1387             /* The only RETURN is the last stmt in the function, no-op it
1388              * and inline the function body.
1389              */
1390             ret->type = SLANG_OPER_NONE;
1391          }
1392          else {
1393             slang_operation *callOper;
1394             /* The function we're calling has one or more 'return' statements.
1395              * So, we can't truly inline this function because we need to
1396              * implement 'return' with RET (and CAL).
1397              * Nevertheless, we performed "inlining" to make a new instance
1398              * of the function body to deal with static register allocation.
1399              *
1400              * XXX check if there's one 'return' and if it's the very last
1401              * statement in the function - we can optimize that case.
1402              */
1403             assert(inlined->type == SLANG_OPER_BLOCK_NEW_SCOPE ||
1404                    inlined->type == SLANG_OPER_SEQUENCE);
1405
1406             if (_slang_function_has_return_value(fun) && !dest) {
1407                assert(inlined->children[0].type == SLANG_OPER_VARIABLE_DECL);
1408                assert(inlined->children[2].type == SLANG_OPER_IDENTIFIER);
1409                callOper = &inlined->children[1];
1410             }
1411             else {
1412                callOper = inlined;
1413             }
1414             callOper->type = SLANG_OPER_NON_INLINED_CALL;
1415             callOper->fun = fun;
1416             callOper->label = _slang_label_new_unique((char*) fun->header.a_name);
1417          }
1418       }
1419    }
1420
1421    if (!inlined)
1422       return NULL;
1423
1424    /* Replace the function call with the inlined block (or new CALL stmt) */
1425    slang_operation_destruct(oper);
1426    *oper = *inlined;
1427    _slang_free(inlined);
1428
1429 #if 0
1430    assert(inlined->locals);
1431    printf("*** Inlined code for call to %s:\n",
1432           (char*) fun->header.a_name);
1433    slang_print_tree(oper, 10);
1434    printf("\n");
1435 #endif
1436
1437    n = _slang_gen_operation(A, oper);
1438
1439    /*_slang_label_delete(A->curFuncEndLabel);*/
1440    A->curFuncEndLabel = prevFuncEndLabel;
1441
1442    if (A->pragmas->Debug) {
1443       char s[1000];
1444       snprintf(s, sizeof(s), "Call/inline %s()", (char *) fun->header.a_name);
1445       n->Comment = _slang_strdup(s);
1446    }
1447
1448    return n;
1449 }
1450
1451
1452 static slang_asm_info *
1453 slang_find_asm_info(const char *name)
1454 {
1455    GLuint i;
1456    for (i = 0; AsmInfo[i].Name; i++) {
1457       if (_mesa_strcmp(AsmInfo[i].Name, name) == 0) {
1458          return AsmInfo + i;
1459       }
1460    }
1461    return NULL;
1462 }
1463
1464
1465 /**
1466  * Some write-masked assignments are simple, but others are hard.
1467  * Simple example:
1468  *    vec3 v;
1469  *    v.xy = vec2(a, b);
1470  * Hard example:
1471  *    vec3 v;
1472  *    v.zy = vec2(a, b);
1473  * this gets transformed/swizzled into:
1474  *    v.zy = vec2(a, b).*yx*         (* = don't care)
1475  * This function helps to determine simple vs. non-simple.
1476  */
1477 static GLboolean
1478 _slang_simple_writemask(GLuint writemask, GLuint swizzle)
1479 {
1480    switch (writemask) {
1481    case WRITEMASK_X:
1482       return GET_SWZ(swizzle, 0) == SWIZZLE_X;
1483    case WRITEMASK_Y:
1484       return GET_SWZ(swizzle, 1) == SWIZZLE_Y;
1485    case WRITEMASK_Z:
1486       return GET_SWZ(swizzle, 2) == SWIZZLE_Z;
1487    case WRITEMASK_W:
1488       return GET_SWZ(swizzle, 3) == SWIZZLE_W;
1489    case WRITEMASK_XY:
1490       return (GET_SWZ(swizzle, 0) == SWIZZLE_X)
1491          && (GET_SWZ(swizzle, 1) == SWIZZLE_Y);
1492    case WRITEMASK_XYZ:
1493       return (GET_SWZ(swizzle, 0) == SWIZZLE_X)
1494          && (GET_SWZ(swizzle, 1) == SWIZZLE_Y)
1495          && (GET_SWZ(swizzle, 2) == SWIZZLE_Z);
1496    case WRITEMASK_XYZW:
1497       return swizzle == SWIZZLE_NOOP;
1498    default:
1499       return GL_FALSE;
1500    }
1501 }
1502
1503
1504 /**
1505  * Convert the given swizzle into a writemask.  In some cases this
1506  * is trivial, in other cases, we'll need to also swizzle the right
1507  * hand side to put components in the right places.
1508  * See comment above for more info.
1509  * XXX this function could be simplified and should probably be renamed.
1510  * \param swizzle  the incoming swizzle
1511  * \param writemaskOut  returns the writemask
1512  * \param swizzleOut  swizzle to apply to the right-hand-side
1513  * \return GL_FALSE for simple writemasks, GL_TRUE for non-simple
1514  */
1515 static GLboolean
1516 swizzle_to_writemask(slang_assemble_ctx *A, GLuint swizzle,
1517                      GLuint *writemaskOut, GLuint *swizzleOut)
1518 {
1519    GLuint mask = 0x0, newSwizzle[4];
1520    GLint i, size;
1521
1522    /* make new dst writemask, compute size */
1523    for (i = 0; i < 4; i++) {
1524       const GLuint swz = GET_SWZ(swizzle, i);
1525       if (swz == SWIZZLE_NIL) {
1526          /* end */
1527          break;
1528       }
1529       assert(swz >= 0 && swz <= 3);
1530
1531       if (swizzle != SWIZZLE_XXXX &&
1532           swizzle != SWIZZLE_YYYY &&
1533           swizzle != SWIZZLE_ZZZZ &&
1534           swizzle != SWIZZLE_WWWW &&
1535           (mask & (1 << swz))) {
1536          /* a channel can't be specified twice (ex: ".xyyz") */
1537          slang_info_log_error(A->log, "Invalid writemask '%s'",
1538                               _mesa_swizzle_string(swizzle, 0, 0));
1539          return GL_FALSE;
1540       }
1541
1542       mask |= (1 << swz);
1543    }
1544    assert(mask <= 0xf);
1545    size = i;  /* number of components in mask/swizzle */
1546
1547    *writemaskOut = mask;
1548
1549    /* make new src swizzle, by inversion */
1550    for (i = 0; i < 4; i++) {
1551       newSwizzle[i] = i; /*identity*/
1552    }
1553    for (i = 0; i < size; i++) {
1554       const GLuint swz = GET_SWZ(swizzle, i);
1555       newSwizzle[swz] = i;
1556    }
1557    *swizzleOut = MAKE_SWIZZLE4(newSwizzle[0],
1558                                newSwizzle[1],
1559                                newSwizzle[2],
1560                                newSwizzle[3]);
1561
1562    if (_slang_simple_writemask(mask, *swizzleOut)) {
1563       if (size >= 1)
1564          assert(GET_SWZ(*swizzleOut, 0) == SWIZZLE_X);
1565       if (size >= 2)
1566          assert(GET_SWZ(*swizzleOut, 1) == SWIZZLE_Y);
1567       if (size >= 3)
1568          assert(GET_SWZ(*swizzleOut, 2) == SWIZZLE_Z);
1569       if (size >= 4)
1570          assert(GET_SWZ(*swizzleOut, 3) == SWIZZLE_W);
1571       return GL_TRUE;
1572    }
1573    else
1574       return GL_FALSE;
1575 }
1576
1577
1578 #if 0 /* not used, but don't remove just yet */
1579 /**
1580  * Recursively traverse 'oper' to produce a swizzle mask in the event
1581  * of any vector subscripts and swizzle suffixes.
1582  * Ex:  for "vec4 v",  "v[2].x" resolves to v.z
1583  */
1584 static GLuint
1585 resolve_swizzle(const slang_operation *oper)
1586 {
1587    if (oper->type == SLANG_OPER_FIELD) {
1588       /* writemask from .xyzw suffix */
1589       slang_swizzle swz;
1590       if (_slang_is_swizzle((char*) oper->a_id, 4, &swz)) {
1591          GLuint swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
1592                                         swz.swizzle[1],
1593                                         swz.swizzle[2],
1594                                         swz.swizzle[3]);
1595          GLuint child_swizzle = resolve_swizzle(&oper->children[0]);
1596          GLuint s = _slang_swizzle_swizzle(child_swizzle, swizzle);
1597          return s;
1598       }
1599       else
1600          return SWIZZLE_XYZW;
1601    }
1602    else if (oper->type == SLANG_OPER_SUBSCRIPT &&
1603             oper->children[1].type == SLANG_OPER_LITERAL_INT) {
1604       /* writemask from [index] */
1605       GLuint child_swizzle = resolve_swizzle(&oper->children[0]);
1606       GLuint i = (GLuint) oper->children[1].literal[0];
1607       GLuint swizzle;
1608       GLuint s;
1609       switch (i) {
1610       case 0:
1611          swizzle = SWIZZLE_XXXX;
1612          break;
1613       case 1:
1614          swizzle = SWIZZLE_YYYY;
1615          break;
1616       case 2:
1617          swizzle = SWIZZLE_ZZZZ;
1618          break;
1619       case 3:
1620          swizzle = SWIZZLE_WWWW;
1621          break;
1622       default:
1623          swizzle = SWIZZLE_XYZW;
1624       }
1625       s = _slang_swizzle_swizzle(child_swizzle, swizzle);
1626       return s;
1627    }
1628    else {
1629       return SWIZZLE_XYZW;
1630    }
1631 }
1632 #endif
1633
1634
1635 #if 0
1636 /**
1637  * Recursively descend through swizzle nodes to find the node's storage info.
1638  */
1639 static slang_ir_storage *
1640 get_store(const slang_ir_node *n)
1641 {
1642    if (n->Opcode == IR_SWIZZLE) {
1643       return get_store(n->Children[0]);
1644    }
1645    return n->Store;
1646 }
1647 #endif
1648
1649
1650 /**
1651  * Generate IR tree for an asm instruction/operation such as:
1652  *    __asm vec4_dot __retVal.x, v1, v2;
1653  */
1654 static slang_ir_node *
1655 _slang_gen_asm(slang_assemble_ctx *A, slang_operation *oper,
1656                slang_operation *dest)
1657 {
1658    const slang_asm_info *info;
1659    slang_ir_node *kids[3], *n;
1660    GLuint j, firstOperand;
1661
1662    assert(oper->type == SLANG_OPER_ASM);
1663
1664    info = slang_find_asm_info((char *) oper->a_id);
1665    if (!info) {
1666       _mesa_problem(NULL, "undefined __asm function %s\n",
1667                     (char *) oper->a_id);
1668       assert(info);
1669    }
1670    assert(info->NumParams <= 3);
1671
1672    if (info->NumParams == oper->num_children) {
1673       /* Storage for result is not specified.
1674        * Children[0], [1], [2] are the operands.
1675        */
1676       firstOperand = 0;
1677    }
1678    else {
1679       /* Storage for result (child[0]) is specified.
1680        * Children[1], [2], [3] are the operands.
1681        */
1682       firstOperand = 1;
1683    }
1684
1685    /* assemble child(ren) */
1686    kids[0] = kids[1] = kids[2] = NULL;
1687    for (j = 0; j < info->NumParams; j++) {
1688       kids[j] = _slang_gen_operation(A, &oper->children[firstOperand + j]);
1689       if (!kids[j])
1690          return NULL;
1691    }
1692
1693    n = new_node3(info->Opcode, kids[0], kids[1], kids[2]);
1694
1695    if (firstOperand) {
1696       /* Setup n->Store to be a particular location.  Otherwise, storage
1697        * for the result (a temporary) will be allocated later.
1698        */
1699       slang_operation *dest_oper;
1700       slang_ir_node *n0;
1701
1702       dest_oper = &oper->children[0];
1703
1704       n0 = _slang_gen_operation(A, dest_oper);
1705       if (!n0)
1706          return NULL;
1707
1708       assert(!n->Store);
1709       n->Store = n0->Store;
1710
1711       assert(n->Store->File != PROGRAM_UNDEFINED || n->Store->Parent);
1712
1713       _slang_free(n0);
1714    }
1715
1716    return n;
1717 }
1718
1719
1720 #if 0
1721 static void
1722 print_funcs(struct slang_function_scope_ *scope, const char *name)
1723 {
1724    GLuint i;
1725    for (i = 0; i < scope->num_functions; i++) {
1726       slang_function *f = &scope->functions[i];
1727       if (!name || strcmp(name, (char*) f->header.a_name) == 0)
1728           printf("  %s (%d args)\n", name, f->param_count);
1729
1730    }
1731    if (scope->outer_scope)
1732       print_funcs(scope->outer_scope, name);
1733 }
1734 #endif
1735
1736
1737 /**
1738  * Find a function of the given name, taking 'numArgs' arguments.
1739  * This is the function we'll try to call when there is no exact match
1740  * between function parameters and call arguments.
1741  *
1742  * XXX we should really create a list of candidate functions and try
1743  * all of them...
1744  */
1745 static slang_function *
1746 _slang_find_function_by_argc(slang_function_scope *scope,
1747                              const char *name, int numArgs)
1748 {
1749    while (scope) {
1750       GLuint i;
1751       for (i = 0; i < scope->num_functions; i++) {
1752          slang_function *f = &scope->functions[i];
1753          if (strcmp(name, (char*) f->header.a_name) == 0) {
1754             int haveRetValue = _slang_function_has_return_value(f);
1755             if (numArgs == f->param_count - haveRetValue)
1756                return f;
1757          }
1758       }
1759       scope = scope->outer_scope;
1760    }
1761
1762    return NULL;
1763 }
1764
1765
1766 static slang_function *
1767 _slang_find_function_by_max_argc(slang_function_scope *scope,
1768                                  const char *name)
1769 {
1770    slang_function *maxFunc = NULL;
1771    GLuint maxArgs = 0;
1772
1773    while (scope) {
1774       GLuint i;
1775       for (i = 0; i < scope->num_functions; i++) {
1776          slang_function *f = &scope->functions[i];
1777          if (strcmp(name, (char*) f->header.a_name) == 0) {
1778             if (f->param_count > maxArgs) {
1779                maxArgs = f->param_count;
1780                maxFunc = f;
1781             }
1782          }
1783       }
1784       scope = scope->outer_scope;
1785    }
1786
1787    return maxFunc;
1788 }
1789
1790
1791 /**
1792  * Generate a new slang_function which is a constructor for a user-defined
1793  * struct type.
1794  */
1795 static slang_function *
1796 _slang_make_struct_constructor(slang_assemble_ctx *A, slang_struct *str)
1797 {
1798    const GLint numFields = str->fields->num_variables;
1799    slang_function *fun = slang_function_new(SLANG_FUNC_CONSTRUCTOR);
1800
1801    /* function header (name, return type) */
1802    fun->header.a_name = str->a_name;
1803    fun->header.type.qualifier = SLANG_QUAL_NONE;
1804    fun->header.type.specifier.type = SLANG_SPEC_STRUCT;
1805    fun->header.type.specifier._struct = str;
1806
1807    /* function parameters (= struct's fields) */
1808    {
1809       GLint i;
1810       for (i = 0; i < numFields; i++) {
1811          /*
1812          printf("Field %d: %s\n", i, (char*) str->fields->variables[i]->a_name);
1813          */
1814          slang_variable *p = slang_variable_scope_grow(fun->parameters);
1815          *p = *str->fields->variables[i]; /* copy the variable and type */
1816          p->type.qualifier = SLANG_QUAL_CONST;
1817       }
1818       fun->param_count = fun->parameters->num_variables;
1819    }
1820
1821    /* Add __retVal to params */
1822    {
1823       slang_variable *p = slang_variable_scope_grow(fun->parameters);
1824       slang_atom a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
1825       assert(a_retVal);
1826       p->a_name = a_retVal;
1827       p->type = fun->header.type;
1828       p->type.qualifier = SLANG_QUAL_OUT;
1829       fun->param_count++;
1830    }
1831
1832    /* function body is:
1833     *    block:
1834     *       declare T;
1835     *       T.f1 = p1;
1836     *       T.f2 = p2;
1837     *       ...
1838     *       T.fn = pn;
1839     *       return T;
1840     */
1841    {
1842       slang_variable_scope *scope;
1843       slang_variable *var;
1844       GLint i;
1845
1846       fun->body = slang_operation_new(1);
1847       fun->body->type = SLANG_OPER_BLOCK_NEW_SCOPE;
1848       fun->body->num_children = numFields + 2;
1849       fun->body->children = slang_operation_new(numFields + 2);
1850
1851       scope = fun->body->locals;
1852       scope->outer_scope = fun->parameters;
1853
1854       /* create local var 't' */
1855       var = slang_variable_scope_grow(scope);
1856       var->a_name = slang_atom_pool_atom(A->atoms, "t");
1857       var->type = fun->header.type;
1858
1859       /* declare t */
1860       {
1861          slang_operation *decl;
1862
1863          decl = &fun->body->children[0];
1864          decl->type = SLANG_OPER_VARIABLE_DECL;
1865          decl->locals = _slang_variable_scope_new(scope);
1866          decl->a_id = var->a_name;
1867       }
1868
1869       /* assign params to fields of t */
1870       for (i = 0; i < numFields; i++) {
1871          slang_operation *assign = &fun->body->children[1 + i];
1872
1873          assign->type = SLANG_OPER_ASSIGN;
1874          assign->locals = _slang_variable_scope_new(scope);
1875          assign->num_children = 2;
1876          assign->children = slang_operation_new(2);
1877          
1878          {
1879             slang_operation *lhs = &assign->children[0];
1880
1881             lhs->type = SLANG_OPER_FIELD;
1882             lhs->locals = _slang_variable_scope_new(scope);
1883             lhs->num_children = 1;
1884             lhs->children = slang_operation_new(1);
1885             lhs->a_id = str->fields->variables[i]->a_name;
1886
1887             lhs->children[0].type = SLANG_OPER_IDENTIFIER;
1888             lhs->children[0].a_id = var->a_name;
1889             lhs->children[0].locals = _slang_variable_scope_new(scope);
1890
1891 #if 0
1892             lhs->children[1].num_children = 1;
1893             lhs->children[1].children = slang_operation_new(1);
1894             lhs->children[1].children[0].type = SLANG_OPER_IDENTIFIER;
1895             lhs->children[1].children[0].a_id = str->fields->variables[i]->a_name;
1896             lhs->children[1].children->locals = _slang_variable_scope_new(scope);
1897 #endif
1898          }
1899
1900          {
1901             slang_operation *rhs = &assign->children[1];
1902
1903             rhs->type = SLANG_OPER_IDENTIFIER;
1904             rhs->locals = _slang_variable_scope_new(scope);
1905             rhs->a_id = str->fields->variables[i]->a_name;
1906          }         
1907       }
1908
1909       /* return t; */
1910       {
1911          slang_operation *ret = &fun->body->children[numFields + 1];
1912
1913          ret->type = SLANG_OPER_RETURN;
1914          ret->locals = _slang_variable_scope_new(scope);
1915          ret->num_children = 1;
1916          ret->children = slang_operation_new(1);
1917          ret->children[0].type = SLANG_OPER_IDENTIFIER;
1918          ret->children[0].a_id = var->a_name;
1919          ret->children[0].locals = _slang_variable_scope_new(scope);
1920       }
1921    }
1922    /*
1923    slang_print_function(fun, 1);
1924    */
1925    return fun;
1926 }
1927
1928
1929 /**
1930  * Find/create a function (constructor) for the given structure name.
1931  */
1932 static slang_function *
1933 _slang_locate_struct_constructor(slang_assemble_ctx *A, const char *name)
1934 {
1935    unsigned int i;
1936    for (i = 0; i < A->space.structs->num_structs; i++) {
1937       slang_struct *str = &A->space.structs->structs[i];
1938       if (strcmp(name, (const char *) str->a_name) == 0) {
1939          /* found a structure type that matches the function name */
1940          if (!str->constructor) {
1941             /* create the constructor function now */
1942             str->constructor = _slang_make_struct_constructor(A, str);
1943          }
1944          return str->constructor;
1945       }
1946    }
1947    return NULL;
1948 }
1949
1950
1951 /**
1952  * Generate a new slang_function to satisfy a call to an array constructor.
1953  * Ex:  float[3](1., 2., 3.)
1954  */
1955 static slang_function *
1956 _slang_make_array_constructor(slang_assemble_ctx *A, slang_operation *oper)
1957 {
1958    slang_type_specifier_type baseType;
1959    slang_function *fun;
1960    int num_elements;
1961
1962    fun = slang_function_new(SLANG_FUNC_CONSTRUCTOR);
1963    if (!fun)
1964       return NULL;
1965
1966    baseType = slang_type_specifier_type_from_string((char *) oper->a_id);
1967
1968    num_elements = oper->num_children;
1969
1970    /* function header, return type */
1971    {
1972       fun->header.a_name = oper->a_id;
1973       fun->header.type.qualifier = SLANG_QUAL_NONE;
1974       fun->header.type.specifier.type = SLANG_SPEC_ARRAY;
1975       fun->header.type.specifier._array =
1976          slang_type_specifier_new(baseType, NULL, NULL);
1977       fun->header.type.array_len = num_elements;
1978    }
1979
1980    /* function parameters (= number of elements) */
1981    {
1982       GLint i;
1983       for (i = 0; i < num_elements; i++) {
1984          /*
1985          printf("Field %d: %s\n", i, (char*) str->fields->variables[i]->a_name);
1986          */
1987          slang_variable *p = slang_variable_scope_grow(fun->parameters);
1988          char name[10];
1989          _mesa_snprintf(name, sizeof(name), "p%d", i);
1990          p->a_name = slang_atom_pool_atom(A->atoms, name);
1991          p->type.qualifier = SLANG_QUAL_CONST;
1992          p->type.specifier.type = baseType;
1993       }
1994       fun->param_count = fun->parameters->num_variables;
1995    }
1996
1997    /* Add __retVal to params */
1998    {
1999       slang_variable *p = slang_variable_scope_grow(fun->parameters);
2000       slang_atom a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
2001       assert(a_retVal);
2002       p->a_name = a_retVal;
2003       p->type = fun->header.type;
2004       p->type.qualifier = SLANG_QUAL_OUT;
2005       p->type.specifier.type = baseType;
2006       fun->param_count++;
2007    }
2008
2009    /* function body is:
2010     *    block:
2011     *       declare T;
2012     *       T[0] = p0;
2013     *       T[1] = p1;
2014     *       ...
2015     *       T[n] = pn;
2016     *       return T;
2017     */
2018    {
2019       slang_variable_scope *scope;
2020       slang_variable *var;
2021       GLint i;
2022
2023       fun->body = slang_operation_new(1);
2024       fun->body->type = SLANG_OPER_BLOCK_NEW_SCOPE;
2025       fun->body->num_children = num_elements + 2;
2026       fun->body->children = slang_operation_new(num_elements + 2);
2027
2028       scope = fun->body->locals;
2029       scope->outer_scope = fun->parameters;
2030
2031       /* create local var 't' */
2032       var = slang_variable_scope_grow(scope);
2033       var->a_name = slang_atom_pool_atom(A->atoms, "ttt");
2034       var->type = fun->header.type;/*XXX copy*/
2035
2036       /* declare t */
2037       {
2038          slang_operation *decl;
2039
2040          decl = &fun->body->children[0];
2041          decl->type = SLANG_OPER_VARIABLE_DECL;
2042          decl->locals = _slang_variable_scope_new(scope);
2043          decl->a_id = var->a_name;
2044       }
2045
2046       /* assign params to elements of t */
2047       for (i = 0; i < num_elements; i++) {
2048          slang_operation *assign = &fun->body->children[1 + i];
2049
2050          assign->type = SLANG_OPER_ASSIGN;
2051          assign->locals = _slang_variable_scope_new(scope);
2052          assign->num_children = 2;
2053          assign->children = slang_operation_new(2);
2054          
2055          {
2056             slang_operation *lhs = &assign->children[0];
2057
2058             lhs->type = SLANG_OPER_SUBSCRIPT;
2059             lhs->locals = _slang_variable_scope_new(scope);
2060             lhs->num_children = 2;
2061             lhs->children = slang_operation_new(2);
2062  
2063             lhs->children[0].type = SLANG_OPER_IDENTIFIER;
2064             lhs->children[0].a_id = var->a_name;
2065             lhs->children[0].locals = _slang_variable_scope_new(scope);
2066
2067             lhs->children[1].type = SLANG_OPER_LITERAL_INT;
2068             lhs->children[1].literal[0] = (GLfloat) i;
2069          }
2070
2071          {
2072             slang_operation *rhs = &assign->children[1];
2073
2074             rhs->type = SLANG_OPER_IDENTIFIER;
2075             rhs->locals = _slang_variable_scope_new(scope);
2076             rhs->a_id = fun->parameters->variables[i]->a_name;
2077          }         
2078       }
2079
2080       /* return t; */
2081       {
2082          slang_operation *ret = &fun->body->children[num_elements + 1];
2083
2084          ret->type = SLANG_OPER_RETURN;
2085          ret->locals = _slang_variable_scope_new(scope);
2086          ret->num_children = 1;
2087          ret->children = slang_operation_new(1);
2088          ret->children[0].type = SLANG_OPER_IDENTIFIER;
2089          ret->children[0].a_id = var->a_name;
2090          ret->children[0].locals = _slang_variable_scope_new(scope);
2091       }
2092    }
2093
2094    /*
2095    slang_print_function(fun, 1);
2096    */
2097
2098    return fun;
2099 }
2100
2101
2102 static GLboolean
2103 _slang_is_vec_mat_type(const char *name)
2104 {
2105    static const char *vecmat_types[] = {
2106       "float", "int", "bool",
2107       "vec2", "vec3", "vec4",
2108       "ivec2", "ivec3", "ivec4",
2109       "bvec2", "bvec3", "bvec4",
2110       "mat2", "mat3", "mat4",
2111       "mat2x3", "mat2x4", "mat3x2", "mat3x4", "mat4x2", "mat4x3",
2112       NULL
2113    };
2114    int i;
2115    for (i = 0; vecmat_types[i]; i++)
2116       if (_mesa_strcmp(name, vecmat_types[i]) == 0)
2117          return GL_TRUE;
2118    return GL_FALSE;
2119 }
2120
2121
2122 /**
2123  * Assemble a function call, given a particular function name.
2124  * \param name  the function's name (operators like '*' are possible).
2125  */
2126 static slang_ir_node *
2127 _slang_gen_function_call_name(slang_assemble_ctx *A, const char *name,
2128                               slang_operation *oper, slang_operation *dest)
2129 {
2130    slang_operation *params = oper->children;
2131    const GLuint param_count = oper->num_children;
2132    slang_atom atom;
2133    slang_function *fun;
2134    slang_ir_node *n;
2135
2136    atom = slang_atom_pool_atom(A->atoms, name);
2137    if (atom == SLANG_ATOM_NULL)
2138       return NULL;
2139
2140    if (oper->array_constructor) {
2141       /* this needs special handling */
2142       fun = _slang_make_array_constructor(A, oper);
2143    }
2144    else {
2145       /* Try to find function by name and exact argument type matching */
2146       GLboolean error = GL_FALSE;
2147       fun = _slang_function_locate(A->space.funcs, atom, params, param_count,
2148                                    &A->space, A->atoms, A->log, &error);
2149       if (error) {
2150          slang_info_log_error(A->log,
2151                               "Function '%s' not found (check argument types)",
2152                               name);
2153          return NULL;
2154       }
2155    }
2156
2157    if (!fun) {
2158       /* Next, try locating a constructor function for a user-defined type */
2159       fun = _slang_locate_struct_constructor(A, name);
2160    }
2161
2162    /*
2163     * At this point, some heuristics are used to try to find a function
2164     * that matches the calling signature by means of casting or "unrolling"
2165     * of constructors.
2166     */
2167
2168    if (!fun && _slang_is_vec_mat_type(name)) {
2169       /* Next, if this call looks like a vec() or mat() constructor call,
2170        * try "unwinding" the args to satisfy a constructor.
2171        */
2172       fun = _slang_find_function_by_max_argc(A->space.funcs, name);
2173       if (fun) {
2174          if (!_slang_adapt_call(oper, fun, &A->space, A->atoms, A->log)) {
2175             slang_info_log_error(A->log,
2176                                  "Function '%s' not found (check argument types)",
2177                                  name);
2178             return NULL;
2179          }
2180       }
2181    }
2182
2183    if (!fun && _slang_is_vec_mat_type(name)) {
2184       /* Next, try casting args to the types of the formal parameters */
2185       int numArgs = oper->num_children;
2186       fun = _slang_find_function_by_argc(A->space.funcs, name, numArgs);
2187       if (!fun || !_slang_cast_func_params(oper, fun, &A->space, A->atoms, A->log)) {
2188          slang_info_log_error(A->log,
2189                               "Function '%s' not found (check argument types)",
2190                               name);
2191          return NULL;
2192       }
2193       assert(fun);
2194    }
2195
2196    if (!fun) {
2197       slang_info_log_error(A->log,
2198                            "Function '%s' not found (check argument types)",
2199                            name);
2200       return NULL;
2201    }
2202    if (!fun->body) {
2203       slang_info_log_error(A->log,
2204                            "Function '%s' prototyped but not defined.  "
2205                            "Separate compilation units not supported.",
2206                            name);
2207       return NULL;
2208    }
2209
2210    /* type checking to be sure function's return type matches 'dest' type */
2211    if (dest) {
2212       slang_typeinfo t0;
2213
2214       slang_typeinfo_construct(&t0);
2215       typeof_operation(A, dest, &t0);
2216
2217       if (!slang_type_specifier_equal(&t0.spec, &fun->header.type.specifier)) {
2218          slang_info_log_error(A->log,
2219                               "Incompatible type returned by call to '%s'",
2220                               name);
2221          return NULL;
2222       }
2223    }
2224
2225    n = _slang_gen_function_call(A, fun, oper, dest);
2226
2227    if (n && !n->Store && !dest
2228        && fun->header.type.specifier.type != SLANG_SPEC_VOID) {
2229       /* setup n->Store for the result of the function call */
2230       GLint size = _slang_sizeof_type_specifier(&fun->header.type.specifier);
2231       n->Store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -1, size);
2232       /*printf("Alloc storage for function result, size %d \n", size);*/
2233    }
2234
2235    if (oper->array_constructor) {
2236       /* free the temporary array constructor function now */
2237       slang_function_destruct(fun);
2238    }
2239
2240    return n;
2241 }
2242
2243
2244 static slang_ir_node *
2245 _slang_gen_method_call(slang_assemble_ctx *A, slang_operation *oper)
2246 {
2247    slang_atom *a_length = slang_atom_pool_atom(A->atoms, "length");
2248    slang_ir_node *n;
2249    slang_variable *var;
2250
2251    /* NOTE: In GLSL 1.20, there's only one kind of method
2252     * call: array.length().  Anything else is an error.
2253     */
2254    if (oper->a_id != a_length) {
2255       slang_info_log_error(A->log,
2256                            "Undefined method call '%s'", (char *) oper->a_id);
2257       return NULL;
2258    }
2259
2260    /* length() takes no arguments */
2261    if (oper->num_children > 0) {
2262       slang_info_log_error(A->log, "Invalid arguments to length() method");
2263       return NULL;
2264    }
2265
2266    /* lookup the object/variable */
2267    var = _slang_variable_locate(oper->locals, oper->a_obj, GL_TRUE);
2268    if (!var || var->type.specifier.type != SLANG_SPEC_ARRAY) {
2269       slang_info_log_error(A->log,
2270                            "Undefined object '%s'", (char *) oper->a_obj);
2271       return NULL;
2272    }
2273
2274    /* Create a float/literal IR node encoding the array length */
2275    n = new_node0(IR_FLOAT);
2276    if (n) {
2277       n->Value[0] = (float) _slang_array_length(var);
2278       n->Store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, 1);
2279    }
2280    return n;
2281 }
2282
2283
2284 static GLboolean
2285 _slang_is_constant_cond(const slang_operation *oper, GLboolean *value)
2286 {
2287    if (oper->type == SLANG_OPER_LITERAL_FLOAT ||
2288        oper->type == SLANG_OPER_LITERAL_INT ||
2289        oper->type == SLANG_OPER_LITERAL_BOOL) {
2290       if (oper->literal[0])
2291          *value = GL_TRUE;
2292       else
2293          *value = GL_FALSE;
2294       return GL_TRUE;
2295    }
2296    else if (oper->type == SLANG_OPER_EXPRESSION &&
2297             oper->num_children == 1) {
2298       return _slang_is_constant_cond(&oper->children[0], value);
2299    }
2300    return GL_FALSE;
2301 }
2302
2303
2304 /**
2305  * Test if an operation is a scalar or boolean.
2306  */
2307 static GLboolean
2308 _slang_is_scalar_or_boolean(slang_assemble_ctx *A, slang_operation *oper)
2309 {
2310    slang_typeinfo type;
2311    GLint size;
2312
2313    slang_typeinfo_construct(&type);
2314    typeof_operation(A, oper, &type);
2315    size = _slang_sizeof_type_specifier(&type.spec);
2316    slang_typeinfo_destruct(&type);
2317    return size == 1;
2318 }
2319
2320
2321 /**
2322  * Test if an operation is boolean.
2323  */
2324 static GLboolean
2325 _slang_is_boolean(slang_assemble_ctx *A, slang_operation *oper)
2326 {
2327    slang_typeinfo type;
2328    GLboolean isBool;
2329
2330    slang_typeinfo_construct(&type);
2331    typeof_operation(A, oper, &type);
2332    isBool = (type.spec.type == SLANG_SPEC_BOOL);
2333    slang_typeinfo_destruct(&type);
2334    return isBool;
2335 }
2336
2337
2338 /**
2339  * Generate loop code using high-level IR_LOOP instruction
2340  */
2341 static slang_ir_node *
2342 _slang_gen_while(slang_assemble_ctx * A, const slang_operation *oper)
2343 {
2344    /*
2345     * LOOP:
2346     *    BREAK if !expr (child[0])
2347     *    body code (child[1])
2348     */
2349    slang_ir_node *prevLoop, *loop, *breakIf, *body;
2350    GLboolean isConst, constTrue;
2351
2352    /* type-check expression */
2353    if (!_slang_is_boolean(A, &oper->children[0])) {
2354       slang_info_log_error(A->log, "scalar/boolean expression expected for 'while'");
2355       return NULL;
2356    }
2357
2358    /* Check if loop condition is a constant */
2359    isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);
2360
2361    if (isConst && !constTrue) {
2362       /* loop is never executed! */
2363       return new_node0(IR_NOP);
2364    }
2365
2366    loop = new_loop(NULL);
2367
2368    /* save old, push new loop */
2369    prevLoop = A->CurLoop;
2370    A->CurLoop = loop;
2371
2372    if (isConst && constTrue) {
2373       /* while(nonzero constant), no conditional break */
2374       breakIf = NULL;
2375    }
2376    else {
2377       slang_ir_node *cond
2378          = new_cond(new_not(_slang_gen_operation(A, &oper->children[0])));
2379       breakIf = new_break_if_true(A->CurLoop, cond);
2380    }
2381    body = _slang_gen_operation(A, &oper->children[1]);
2382    loop->Children[0] = new_seq(breakIf, body);
2383
2384    /* Do infinite loop detection */
2385    /* loop->List is head of linked list of break/continue nodes */
2386    if (!loop->List && isConst && constTrue) {
2387       /* infinite loop detected */
2388       A->CurLoop = prevLoop; /* clean-up */
2389       slang_info_log_error(A->log, "Infinite loop detected!");
2390       return NULL;
2391    }
2392
2393    /* pop loop, restore prev */
2394    A->CurLoop = prevLoop;
2395
2396    return loop;
2397 }
2398
2399
2400 /**
2401  * Generate IR tree for a do-while loop using high-level LOOP, IF instructions.
2402  */
2403 static slang_ir_node *
2404 _slang_gen_do(slang_assemble_ctx * A, const slang_operation *oper)
2405 {
2406    /*
2407     * LOOP:
2408     *    body code (child[0])
2409     *    tail code:
2410     *       BREAK if !expr (child[1])
2411     */
2412    slang_ir_node *prevLoop, *loop;
2413    GLboolean isConst, constTrue;
2414
2415    /* type-check expression */
2416    if (!_slang_is_boolean(A, &oper->children[1])) {
2417       slang_info_log_error(A->log, "scalar/boolean expression expected for 'do/while'");
2418       return NULL;
2419    }
2420
2421    loop = new_loop(NULL);
2422
2423    /* save old, push new loop */
2424    prevLoop = A->CurLoop;
2425    A->CurLoop = loop;
2426
2427    /* loop body: */
2428    loop->Children[0] = _slang_gen_operation(A, &oper->children[0]);
2429
2430    /* Check if loop condition is a constant */
2431    isConst = _slang_is_constant_cond(&oper->children[1], &constTrue);
2432    if (isConst && constTrue) {
2433       /* do { } while(1)   ==> no conditional break */
2434       loop->Children[1] = NULL; /* no tail code */
2435    }
2436    else {
2437       slang_ir_node *cond
2438          = new_cond(new_not(_slang_gen_operation(A, &oper->children[1])));
2439       loop->Children[1] = new_break_if_true(A->CurLoop, cond);
2440    }
2441
2442    /* XXX we should do infinite loop detection, as above */
2443
2444    /* pop loop, restore prev */
2445    A->CurLoop = prevLoop;
2446
2447    return loop;
2448 }
2449
2450
2451 /**
2452  * Recursively count the number of operations rooted at 'oper'.
2453  * This gives some kind of indication of the size/complexity of an operation.
2454  */
2455 static GLuint
2456 sizeof_operation(const slang_operation *oper)
2457 {
2458    if (oper) {
2459       GLuint count = 1; /* me */
2460       GLuint i;
2461       for (i = 0; i < oper->num_children; i++) {
2462          count += sizeof_operation(&oper->children[i]);
2463       }
2464       return count;
2465    }
2466    else {
2467       return 0;
2468    }
2469 }
2470
2471
2472 /**
2473  * Determine if a for-loop can be unrolled.
2474  * At this time, only a rather narrow class of for loops can be unrolled.
2475  * See code for details.
2476  * When a loop can't be unrolled because it's too large we'll emit a
2477  * message to the log.
2478  */
2479 static GLboolean
2480 _slang_can_unroll_for_loop(slang_assemble_ctx * A, const slang_operation *oper)
2481 {
2482    GLuint bodySize;
2483    GLint start, end;
2484    const char *varName;
2485    slang_atom varId;
2486
2487    assert(oper->type == SLANG_OPER_FOR);
2488    assert(oper->num_children == 4);
2489
2490    /* children[0] must be either "int i=constant" or "i=constant" */
2491    if (oper->children[0].type == SLANG_OPER_BLOCK_NO_NEW_SCOPE) {
2492       slang_variable *var;
2493
2494       if (oper->children[0].children[0].type != SLANG_OPER_VARIABLE_DECL)
2495          return GL_FALSE;
2496
2497       varId = oper->children[0].children[0].a_id;
2498
2499       var = _slang_variable_locate(oper->children[0].children[0].locals,
2500                                    varId, GL_TRUE);
2501       if (!var)
2502          return GL_FALSE;
2503       if (!var->initializer)
2504          return GL_FALSE;
2505       if (var->initializer->type != SLANG_OPER_LITERAL_INT)
2506          return GL_FALSE;
2507       start = (GLint) var->initializer->literal[0];
2508    }
2509    else if (oper->children[0].type == SLANG_OPER_EXPRESSION) {
2510       if (oper->children[0].children[0].type != SLANG_OPER_ASSIGN)
2511          return GL_FALSE;
2512       if (oper->children[0].children[0].children[0].type != SLANG_OPER_IDENTIFIER)
2513          return GL_FALSE;
2514       if (oper->children[0].children[0].children[1].type != SLANG_OPER_LITERAL_INT)
2515          return GL_FALSE;
2516
2517       varId = oper->children[0].children[0].children[0].a_id;
2518
2519       start = (GLint) oper->children[0].children[0].children[1].literal[0];
2520    }
2521    else {
2522       return GL_FALSE;
2523    }
2524
2525    /* children[1] must be "i<constant" */
2526    if (oper->children[1].type != SLANG_OPER_EXPRESSION)
2527       return GL_FALSE;
2528    if (oper->children[1].children[0].type != SLANG_OPER_LESS)
2529       return GL_FALSE;
2530    if (oper->children[1].children[0].children[0].type != SLANG_OPER_IDENTIFIER)
2531       return GL_FALSE;
2532    if (oper->children[1].children[0].children[1].type != SLANG_OPER_LITERAL_INT)
2533       return GL_FALSE;
2534
2535    end = (GLint) oper->children[1].children[0].children[1].literal[0];
2536
2537    /* children[2] must be "i++" or "++i" */
2538    if (oper->children[2].type != SLANG_OPER_POSTINCREMENT &&
2539        oper->children[2].type != SLANG_OPER_PREINCREMENT)
2540       return GL_FALSE;
2541    if (oper->children[2].children[0].type != SLANG_OPER_IDENTIFIER)
2542       return GL_FALSE;
2543
2544    /* make sure the same variable name is used in all places */
2545    if ((oper->children[1].children[0].children[0].a_id != varId) ||
2546        (oper->children[2].children[0].a_id != varId))
2547       return GL_FALSE;
2548
2549    varName = (const char *) varId;
2550
2551    /* children[3], the loop body, can't be too large */
2552    bodySize = sizeof_operation(&oper->children[3]);
2553    if (bodySize > MAX_FOR_LOOP_UNROLL_BODY_SIZE) {
2554       slang_info_log_print(A->log,
2555                            "Note: 'for (%s ... )' body is too large/complex"
2556                            " to unroll",
2557                            varName);
2558       return GL_FALSE;
2559    }
2560
2561    if (start >= end)
2562       return GL_FALSE; /* degenerate case */
2563
2564    if (end - start > MAX_FOR_LOOP_UNROLL_ITERATIONS) {
2565       slang_info_log_print(A->log,
2566                            "Note: 'for (%s=%d; %s<%d; ++%s)' is too"
2567                            " many iterations to unroll",
2568                            varName, start, varName, end, varName);
2569       return GL_FALSE;
2570    }
2571
2572    if ((end - start) * bodySize > MAX_FOR_LOOP_UNROLL_COMPLEXITY) {
2573       slang_info_log_print(A->log,
2574                            "Note: 'for (%s=%d; %s<%d; ++%s)' will generate"
2575                            " too much code to unroll",
2576                            varName, start, varName, end, varName);
2577       return GL_FALSE;
2578    }
2579
2580    return GL_TRUE; /* we can unroll the loop */
2581 }
2582
2583
2584 static void
2585 _unroll_loop_inc(slang_assemble_ctx * A)
2586 {
2587    A->UnrollLoop++;
2588 }
2589
2590
2591 static void
2592 _unroll_loop_dec(slang_assemble_ctx * A)
2593 {
2594    A->UnrollLoop--;
2595 }
2596
2597
2598 /**
2599  * Unroll a for-loop.
2600  * First we determine the number of iterations to unroll.
2601  * Then for each iteration:
2602  *   make a copy of the loop body
2603  *   replace instances of the loop variable with the current iteration value
2604  *   generate IR code for the body
2605  * \return pointer to generated IR code or NULL if error, out of memory, etc.
2606  */
2607 static slang_ir_node *
2608 _slang_unroll_for_loop(slang_assemble_ctx * A, const slang_operation *oper)
2609 {
2610    GLint start, end, iter;
2611    slang_ir_node *n, *root = NULL;
2612    slang_atom varId;
2613
2614    /* Set flag so code generator knows we're unrolling loops */
2615    _unroll_loop_inc( A );
2616
2617    if (oper->children[0].type == SLANG_OPER_BLOCK_NO_NEW_SCOPE) {
2618       /* for (int i=0; ... */
2619       slang_variable *var;
2620
2621       varId = oper->children[0].children[0].a_id;
2622       var = _slang_variable_locate(oper->children[0].children[0].locals,
2623                                    varId, GL_TRUE);
2624       start = (GLint) var->initializer->literal[0];
2625    }
2626    else {
2627       /* for (i=0; ... */
2628       varId = oper->children[0].children[0].children[0].a_id;
2629       start = (GLint) oper->children[0].children[0].children[1].literal[0];
2630    }
2631
2632    end = (GLint) oper->children[1].children[0].children[1].literal[0];
2633
2634    for (iter = start; iter < end; iter++) {
2635       slang_operation *body;
2636
2637       /* make a copy of the loop body */
2638       body = slang_operation_new(1);
2639       if (!body) {
2640          _unroll_loop_dec( A );
2641          return NULL;
2642       }
2643
2644       if (!slang_operation_copy(body, &oper->children[3])) {
2645          _unroll_loop_dec( A );
2646          return NULL;
2647       }
2648
2649       /* in body, replace instances of 'varId' with literal 'iter' */
2650       {
2651          slang_variable *oldVar;
2652          slang_operation *newOper;
2653
2654          oldVar = _slang_variable_locate(oper->locals, varId, GL_TRUE);
2655          if (!oldVar) {
2656             /* undeclared loop variable */
2657             slang_operation_delete(body);
2658             _unroll_loop_dec( A );
2659             return NULL;
2660          }
2661
2662          newOper = slang_operation_new(1);
2663          newOper->type = SLANG_OPER_LITERAL_INT;
2664          newOper->literal_size = 1;
2665          newOper->literal[0] = iter;
2666
2667          /* replace instances of the loop variable with newOper */
2668          slang_substitute(A, body, 1, &oldVar, &newOper, GL_FALSE);
2669       }
2670
2671       /* do IR codegen for body */
2672       n = _slang_gen_operation(A, body);
2673       if (!n) {
2674          _unroll_loop_dec( A );
2675          return NULL;
2676       }
2677
2678       root = new_seq(root, n);
2679
2680       slang_operation_delete(body);
2681    }
2682
2683    _unroll_loop_dec( A );
2684
2685    return root;
2686 }
2687
2688
2689 /**
2690  * Generate IR for a for-loop.  Unrolling will be done when possible.
2691  */
2692 static slang_ir_node *
2693 _slang_gen_for(slang_assemble_ctx * A, const slang_operation *oper)
2694 {
2695    GLboolean unroll = _slang_can_unroll_for_loop(A, oper);
2696
2697    if (unroll) {
2698       slang_ir_node *code = _slang_unroll_for_loop(A, oper);
2699       if (code)
2700          return code;
2701    }
2702
2703    /* conventional for-loop code generation */
2704    {
2705       /*
2706        * init code (child[0])
2707        * LOOP:
2708        *    BREAK if !expr (child[1])
2709        *    body code (child[3])
2710        *    tail code:
2711        *       incr code (child[2])   // XXX continue here
2712        */
2713       slang_ir_node *prevLoop, *loop, *cond, *breakIf, *body, *init, *incr;
2714       init = _slang_gen_operation(A, &oper->children[0]);
2715       loop = new_loop(NULL);
2716
2717       /* save old, push new loop */
2718       prevLoop = A->CurLoop;
2719       A->CurLoop = loop;
2720
2721       cond = new_cond(new_not(_slang_gen_operation(A, &oper->children[1])));
2722       breakIf = new_break_if_true(A->CurLoop, cond);
2723       body = _slang_gen_operation(A, &oper->children[3]);
2724       incr = _slang_gen_operation(A, &oper->children[2]);
2725
2726       loop->Children[0] = new_seq(breakIf, body);
2727       loop->Children[1] = incr;  /* tail code */
2728
2729       /* pop loop, restore prev */
2730       A->CurLoop = prevLoop;
2731
2732       return new_seq(init, loop);
2733    }
2734 }
2735
2736
2737 static slang_ir_node *
2738 _slang_gen_continue(slang_assemble_ctx * A, const slang_operation *oper)
2739 {
2740    slang_ir_node *n, *loopNode;
2741    assert(oper->type == SLANG_OPER_CONTINUE);
2742    loopNode = A->CurLoop;
2743    assert(loopNode);
2744    assert(loopNode->Opcode == IR_LOOP);
2745    n = new_node0(IR_CONT);
2746    if (n) {
2747       n->Parent = loopNode;
2748       /* insert this node at head of linked list */
2749       n->List = loopNode->List;
2750       loopNode->List = n;
2751    }
2752    return n;
2753 }
2754
2755
2756 /**
2757  * Determine if the given operation is of a specific type.
2758  */
2759 static GLboolean
2760 is_operation_type(const slang_operation *oper, slang_operation_type type)
2761 {
2762    if (oper->type == type)
2763       return GL_TRUE;
2764    else if ((oper->type == SLANG_OPER_BLOCK_NEW_SCOPE ||
2765              oper->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE) &&
2766             oper->num_children == 1)
2767       return is_operation_type(&oper->children[0], type);
2768    else
2769       return GL_FALSE;
2770 }
2771
2772
2773 /**
2774  * Generate IR tree for an if/then/else conditional using high-level
2775  * IR_IF instruction.
2776  */
2777 static slang_ir_node *
2778 _slang_gen_if(slang_assemble_ctx * A, const slang_operation *oper)
2779 {
2780    /*
2781     * eval expr (child[0])
2782     * IF expr THEN
2783     *    if-body code
2784     * ELSE
2785     *    else-body code
2786     * ENDIF
2787     */
2788    const GLboolean haveElseClause = !_slang_is_noop(&oper->children[2]);
2789    slang_ir_node *ifNode, *cond, *ifBody, *elseBody;
2790    GLboolean isConst, constTrue;
2791
2792    /* type-check expression */
2793    if (!_slang_is_boolean(A, &oper->children[0])) {
2794       slang_info_log_error(A->log, "boolean expression expected for 'if'");
2795       return NULL;
2796    }
2797
2798    if (!_slang_is_scalar_or_boolean(A, &oper->children[0])) {
2799       slang_info_log_error(A->log, "scalar/boolean expression expected for 'if'");
2800       return NULL;
2801    }
2802
2803    isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);
2804    if (isConst) {
2805       if (constTrue) {
2806          /* if (true) ... */
2807          return _slang_gen_operation(A, &oper->children[1]);
2808       }
2809       else {
2810          /* if (false) ... */
2811          return _slang_gen_operation(A, &oper->children[2]);
2812       }
2813    }
2814
2815    cond = _slang_gen_operation(A, &oper->children[0]);
2816    cond = new_cond(cond);
2817
2818    if (is_operation_type(&oper->children[1], SLANG_OPER_BREAK)
2819        && !haveElseClause) {
2820       /* Special case: generate a conditional break */
2821       if (!A->CurLoop && A->UnrollLoop) /* trying to unroll */
2822          return NULL;
2823       ifBody = new_break_if_true(A->CurLoop, cond);
2824       return ifBody;
2825    }
2826    else if (is_operation_type(&oper->children[1], SLANG_OPER_CONTINUE)
2827             && !haveElseClause) {
2828       /* Special case: generate a conditional continue */
2829       if (!A->CurLoop && A->UnrollLoop) /* trying to unroll */
2830          return NULL;
2831       ifBody = new_cont_if_true(A->CurLoop, cond);
2832       return ifBody;
2833    }
2834    else {
2835       /* general case */
2836       ifBody = _slang_gen_operation(A, &oper->children[1]);
2837       if (!ifBody)
2838          return NULL;
2839       if (haveElseClause)
2840          elseBody = _slang_gen_operation(A, &oper->children[2]);
2841       else
2842          elseBody = NULL;
2843       ifNode = new_if(cond, ifBody, elseBody);
2844       return ifNode;
2845    }
2846 }
2847
2848
2849
2850 static slang_ir_node *
2851 _slang_gen_not(slang_assemble_ctx * A, const slang_operation *oper)
2852 {
2853    slang_ir_node *n;
2854
2855    assert(oper->type == SLANG_OPER_NOT);
2856
2857    /* type-check expression */
2858    if (!_slang_is_scalar_or_boolean(A, &oper->children[0])) {
2859       slang_info_log_error(A->log,
2860                            "scalar/boolean expression expected for '!'");
2861       return NULL;
2862    }
2863
2864    n = _slang_gen_operation(A, &oper->children[0]);
2865    if (n)
2866       return new_not(n);
2867    else
2868       return NULL;
2869 }
2870
2871
2872 static slang_ir_node *
2873 _slang_gen_xor(slang_assemble_ctx * A, const slang_operation *oper)
2874 {
2875    slang_ir_node *n1, *n2;
2876
2877    assert(oper->type == SLANG_OPER_LOGICALXOR);
2878
2879    if (!_slang_is_scalar_or_boolean(A, &oper->children[0]) ||
2880        !_slang_is_scalar_or_boolean(A, &oper->children[0])) {
2881       slang_info_log_error(A->log,
2882                            "scalar/boolean expressions expected for '^^'");
2883       return NULL;
2884    }
2885
2886    n1 = _slang_gen_operation(A, &oper->children[0]);
2887    if (!n1)
2888       return NULL;
2889    n2 = _slang_gen_operation(A, &oper->children[1]);
2890    if (!n2)
2891       return NULL;
2892    return new_node2(IR_NOTEQUAL, n1, n2);
2893 }
2894
2895
2896 /**
2897  * Generate IR node for storage of a temporary of given size.
2898  */
2899 static slang_ir_node *
2900 _slang_gen_temporary(GLint size)
2901 {
2902    slang_ir_storage *store;
2903    slang_ir_node *n = NULL;
2904
2905    store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -2, size);
2906    if (store) {
2907       n = new_node0(IR_VAR_DECL);
2908       if (n) {
2909          n->Store = store;
2910       }
2911       else {
2912          _slang_free(store);
2913       }
2914    }
2915    return n;
2916 }
2917
2918
2919 /**
2920  * Generate program constants for an array.
2921  * Ex: const vec2[3] v = vec2[3](vec2(1,1), vec2(2,2), vec2(3,3));
2922  * This will allocate and initialize three vector constants, storing
2923  * the array in constant memory, not temporaries like a non-const array.
2924  * This can also be used for uniform array initializers.
2925  * \return GL_TRUE for success, GL_FALSE if failure (semantic error, etc).
2926  */
2927 static GLboolean
2928 make_constant_array(slang_assemble_ctx *A,
2929                     slang_variable *var,
2930                     slang_operation *initializer)
2931 {
2932    struct gl_program *prog = A->program;
2933    const GLenum datatype = _slang_gltype_from_specifier(&var->type.specifier);
2934    const char *varName = (char *) var->a_name;
2935    const GLuint numElements = initializer->num_children;
2936    GLint size;
2937    GLuint i, j;
2938    GLfloat *values;
2939
2940    if (!var->store) {
2941       var->store = _slang_new_ir_storage(PROGRAM_UNDEFINED, -6, -6);
2942    }
2943    size = var->store->Size;
2944
2945    assert(var->type.qualifier == SLANG_QUAL_CONST ||
2946           var->type.qualifier == SLANG_QUAL_UNIFORM);
2947    assert(initializer->type == SLANG_OPER_CALL);
2948    assert(initializer->array_constructor);
2949
2950    values = (GLfloat *) _mesa_malloc(numElements * 4 * sizeof(GLfloat));
2951
2952    /* convert constructor params into ordinary floats */
2953    for (i = 0; i < numElements; i++) {
2954       const slang_operation *op = &initializer->children[i];
2955       if (op->type != SLANG_OPER_LITERAL_FLOAT) {
2956          /* unsupported type for this optimization */
2957          free(values);
2958          return GL_FALSE;
2959       }
2960       for (j = 0; j < op->literal_size; j++) {
2961          values[i * 4 + j] = op->literal[j];
2962       }
2963       for ( ; j < 4; j++) {
2964          values[i * 4 + j] = 0.0f;
2965       }
2966    }
2967
2968    /* slightly different paths for constants vs. uniforms */
2969    if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
2970       var->store->File = PROGRAM_UNIFORM;
2971       var->store->Index = _mesa_add_uniform(prog->Parameters, varName,
2972                                             size, datatype, values);
2973    }
2974    else {
2975       var->store->File = PROGRAM_CONSTANT;
2976       var->store->Index = _mesa_add_named_constant(prog->Parameters, varName,
2977                                                    values, size);
2978    }
2979    assert(var->store->Size == size);
2980
2981    _mesa_free(values);
2982
2983    return GL_TRUE;
2984 }
2985
2986
2987
2988 /**
2989  * Generate IR node for allocating/declaring a variable (either a local or
2990  * a global).
2991  * Generally, this involves allocating an slang_ir_storage instance for the
2992  * variable, choosing a register file (temporary, constant, etc).
2993  * For ordinary variables we do not yet allocate storage though.  We do that
2994  * when we find the first actual use of the variable to avoid allocating temp
2995  * regs that will never get used.
2996  * At this time, uniforms are always allocated space in this function.
2997  *
2998  * \param initializer  Optional initializer expression for the variable.
2999  */
3000 static slang_ir_node *
3001 _slang_gen_var_decl(slang_assemble_ctx *A, slang_variable *var,
3002                     slang_operation *initializer)
3003 {
3004    const char *varName = (const char *) var->a_name;
3005    const GLenum datatype = _slang_gltype_from_specifier(&var->type.specifier);
3006    slang_ir_node *varDecl, *n;
3007    slang_ir_storage *store;
3008    GLint arrayLen, size, totalSize;  /* if array then totalSize > size */
3009    gl_register_file file;
3010
3011    /*assert(!var->declared);*/
3012    var->declared = GL_TRUE;
3013
3014    /* determine GPU register file for simple cases */
3015    if (is_sampler_type(&var->type)) {
3016       file = PROGRAM_SAMPLER;
3017    }
3018    else if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
3019       file = PROGRAM_UNIFORM;
3020    }
3021    else {
3022       file = PROGRAM_TEMPORARY;
3023    }
3024
3025    size = _slang_sizeof_type_specifier(&var->type.specifier);
3026    if (size <= 0) {
3027       slang_info_log_error(A->log, "invalid declaration for '%s'", varName);
3028       return NULL;
3029    }
3030
3031    arrayLen = _slang_array_length(var);
3032    totalSize = _slang_array_size(size, arrayLen);
3033
3034    /* Allocate IR node for the declaration */
3035    varDecl = new_node0(IR_VAR_DECL);
3036    if (!varDecl)
3037       return NULL;
3038
3039    /* Allocate slang_ir_storage for this variable if needed.
3040     * Note that we may not actually allocate a constant or temporary register
3041     * until later.
3042     */
3043    if (!var->store) {
3044       GLint index = -7;  /* TBD / unknown */
3045       var->store = _slang_new_ir_storage(file, index, totalSize);
3046       if (!var->store)
3047          return NULL; /* out of memory */
3048    }
3049
3050    /* set the IR node's Var and Store pointers */
3051    varDecl->Var = var;
3052    varDecl->Store = var->store;
3053
3054
3055    store = var->store;
3056
3057    /* if there's an initializer, generate IR for the expression */
3058    if (initializer) {
3059       slang_ir_node *varRef, *init;
3060
3061       if (var->type.qualifier == SLANG_QUAL_CONST) {
3062          /* if the variable is const, the initializer must be a const
3063           * expression as well.
3064           */
3065 #if 0
3066          if (!_slang_is_constant_expr(initializer)) {
3067             slang_info_log_error(A->log,
3068                                  "initializer for %s not constant", varName);
3069             return NULL;
3070          }
3071 #endif
3072       }
3073
3074       /* IR for the variable we're initializing */
3075       varRef = new_var(A, var);
3076       if (!varRef) {
3077          slang_info_log_error(A->log, "out of memory");
3078          return NULL;
3079       }
3080
3081       /* constant-folding, etc here */
3082       _slang_simplify(initializer, &A->space, A->atoms); 
3083
3084       /* look for simple constant-valued variables and uniforms */
3085       if (var->type.qualifier == SLANG_QUAL_CONST ||
3086           var->type.qualifier == SLANG_QUAL_UNIFORM) {
3087
3088          if (initializer->type == SLANG_OPER_CALL &&
3089              initializer->array_constructor) {
3090             /* array initializer */
3091             if (make_constant_array(A, var, initializer))
3092                return varRef;
3093          }
3094          else if (initializer->type == SLANG_OPER_LITERAL_FLOAT ||
3095                   initializer->type == SLANG_OPER_LITERAL_INT) {
3096             /* simple float/vector initializer */
3097             if (store->File == PROGRAM_UNIFORM) {
3098                store->Index = _mesa_add_uniform(A->program->Parameters,
3099                                                 varName,
3100                                                 totalSize, datatype,
3101                                                 initializer->literal);
3102                store->Swizzle = _slang_var_swizzle(size, 0);
3103                return varRef;
3104             }
3105 #if 0
3106             else {
3107                store->File = PROGRAM_CONSTANT;
3108                store->Index = _mesa_add_named_constant(A->program->Parameters,
3109                                                        varName,
3110                                                        initializer->literal,
3111                                                        totalSize);
3112                store->Swizzle = _slang_var_swizzle(size, 0);
3113                return varRef;
3114             }
3115 #endif
3116          }
3117       }
3118
3119       /* IR for initializer */
3120       init = _slang_gen_operation(A, initializer);
3121       if (!init)
3122          return NULL;
3123
3124       /* XXX remove this when type checking is added above */
3125       if (init->Store && init->Store->Size != totalSize) {
3126          slang_info_log_error(A->log, "invalid assignment (wrong types)");
3127          return NULL;
3128       }
3129
3130       /* assign RHS to LHS */
3131       n = new_node2(IR_COPY, varRef, init);
3132       n = new_seq(varDecl, n);
3133    }
3134    else {
3135       /* no initializer */
3136       n = varDecl;
3137    }
3138
3139    if (store->File == PROGRAM_UNIFORM && store->Index < 0) {
3140       /* always need to allocate storage for uniforms at this point */
3141       store->Index = _mesa_add_uniform(A->program->Parameters, varName,
3142                                        totalSize, datatype, NULL);
3143       store->Swizzle = _slang_var_swizzle(size, 0);
3144    }
3145
3146 #if 0
3147    printf("%s var %p %s  store=%p index=%d size=%d\n",
3148           __FUNCTION__, (void *) var, (char *) varName,
3149           (void *) store, store->Index, store->Size);
3150 #endif
3151
3152    return n;
3153 }
3154
3155
3156 /**
3157  * Generate code for a selection expression:   b ? x : y
3158  * XXX In some cases we could implement a selection expression
3159  * with an LRP instruction (use the boolean as the interpolant).
3160  * Otherwise, we use an IF/ELSE/ENDIF construct.
3161  */
3162 static slang_ir_node *
3163 _slang_gen_select(slang_assemble_ctx *A, slang_operation *oper)
3164 {
3165    slang_ir_node *cond, *ifNode, *trueExpr, *falseExpr, *trueNode, *falseNode;
3166    slang_ir_node *tmpDecl, *tmpVar, *tree;
3167    slang_typeinfo type0, type1, type2;
3168    int size, isBool, isEqual;
3169
3170    assert(oper->type == SLANG_OPER_SELECT);
3171    assert(oper->num_children == 3);
3172
3173    /* type of children[0] must be boolean */
3174    slang_typeinfo_construct(&type0);
3175    typeof_operation(A, &oper->children[0], &type0);
3176    isBool = (type0.spec.type == SLANG_SPEC_BOOL);
3177    slang_typeinfo_destruct(&type0);
3178    if (!isBool) {
3179       slang_info_log_error(A->log, "selector type is not boolean");
3180       return NULL;
3181    }
3182
3183    slang_typeinfo_construct(&type1);
3184    slang_typeinfo_construct(&type2);
3185    typeof_operation(A, &oper->children[1], &type1);
3186    typeof_operation(A, &oper->children[2], &type2);
3187    isEqual = slang_type_specifier_equal(&type1.spec, &type2.spec);
3188    slang_typeinfo_destruct(&type1);
3189    slang_typeinfo_destruct(&type2);
3190    if (!isEqual) {
3191       slang_info_log_error(A->log, "incompatible types for ?: operator");
3192       return NULL;
3193    }
3194
3195    /* size of x or y's type */
3196    size = _slang_sizeof_type_specifier(&type1.spec);
3197    assert(size > 0);
3198
3199    /* temporary var */
3200    tmpDecl = _slang_gen_temporary(size);
3201
3202    /* the condition (child 0) */
3203    cond = _slang_gen_operation(A, &oper->children[0]);
3204    cond = new_cond(cond);
3205
3206    /* if-true body (child 1) */
3207    tmpVar = new_node0(IR_VAR);
3208    tmpVar->Store = tmpDecl->Store;
3209    trueExpr = _slang_gen_operation(A, &oper->children[1]);
3210    trueNode = new_node2(IR_COPY, tmpVar, trueExpr);
3211
3212    /* if-false body (child 2) */
3213    tmpVar = new_node0(IR_VAR);
3214    tmpVar->Store = tmpDecl->Store;
3215    falseExpr = _slang_gen_operation(A, &oper->children[2]);
3216    falseNode = new_node2(IR_COPY, tmpVar, falseExpr);
3217
3218    ifNode = new_if(cond, trueNode, falseNode);
3219
3220    /* tmp var value */
3221    tmpVar = new_node0(IR_VAR);
3222    tmpVar->Store = tmpDecl->Store;
3223
3224    tree = new_seq(ifNode, tmpVar);
3225    tree = new_seq(tmpDecl, tree);
3226
3227    /*_slang_print_ir_tree(tree, 10);*/
3228    return tree;
3229 }
3230
3231
3232 /**
3233  * Generate code for &&.
3234  */
3235 static slang_ir_node *
3236 _slang_gen_logical_and(slang_assemble_ctx *A, slang_operation *oper)
3237 {
3238    /* rewrite "a && b" as  "a ? b : false" */
3239    slang_operation *select;
3240    slang_ir_node *n;
3241
3242    select = slang_operation_new(1);
3243    select->type = SLANG_OPER_SELECT;
3244    select->num_children = 3;
3245    select->children = slang_operation_new(3);
3246
3247    slang_operation_copy(&select->children[0], &oper->children[0]);
3248    slang_operation_copy(&select->children[1], &oper->children[1]);
3249    select->children[2].type = SLANG_OPER_LITERAL_BOOL;
3250    ASSIGN_4V(select->children[2].literal, 0, 0, 0, 0); /* false */
3251    select->children[2].literal_size = 1;
3252
3253    n = _slang_gen_select(A, select);
3254    return n;
3255 }
3256
3257
3258 /**
3259  * Generate code for ||.
3260  */
3261 static slang_ir_node *
3262 _slang_gen_logical_or(slang_assemble_ctx *A, slang_operation *oper)
3263 {
3264    /* rewrite "a || b" as  "a ? true : b" */
3265    slang_operation *select;
3266    slang_ir_node *n;
3267
3268    select = slang_operation_new(1);
3269    select->type = SLANG_OPER_SELECT;
3270    select->num_children = 3;
3271    select->children = slang_operation_new(3);
3272
3273    slang_operation_copy(&select->children[0], &oper->children[0]);
3274    select->children[1].type = SLANG_OPER_LITERAL_BOOL;
3275    ASSIGN_4V(select->children[1].literal, 1, 1, 1, 1); /* true */
3276    select->children[1].literal_size = 1;
3277    slang_operation_copy(&select->children[2], &oper->children[1]);
3278
3279    n = _slang_gen_select(A, select);
3280    return n;
3281 }
3282
3283
3284 /**
3285  * Generate IR tree for a return statement.
3286  */
3287 static slang_ir_node *
3288 _slang_gen_return(slang_assemble_ctx * A, slang_operation *oper)
3289 {
3290    const GLboolean haveReturnValue
3291       = (oper->num_children == 1 && oper->children[0].type != SLANG_OPER_VOID);
3292
3293    /* error checking */
3294    assert(A->CurFunction);
3295    if (haveReturnValue &&
3296        A->CurFunction->header.type.specifier.type == SLANG_SPEC_VOID) {
3297       slang_info_log_error(A->log, "illegal return expression");
3298       return NULL;
3299    }
3300    else if (!haveReturnValue &&
3301             A->CurFunction->header.type.specifier.type != SLANG_SPEC_VOID) {
3302       slang_info_log_error(A->log, "return statement requires an expression");
3303       return NULL;
3304    }
3305
3306    if (!haveReturnValue) {
3307       return new_return(A->curFuncEndLabel);
3308    }
3309    else {
3310       /*
3311        * Convert from:
3312        *   return expr;
3313        * To:
3314        *   __retVal = expr;
3315        *   return;  // goto __endOfFunction
3316        */
3317       slang_operation *assign;
3318       slang_atom a_retVal;
3319       slang_ir_node *n;
3320
3321       a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
3322       assert(a_retVal);
3323
3324 #if 1 /* DEBUG */
3325       {
3326          slang_variable *v =
3327             _slang_variable_locate(oper->locals, a_retVal, GL_TRUE);
3328          if (!v) {
3329             /* trying to return a value in a void-valued function */
3330             return NULL;
3331          }
3332       }
3333 #endif
3334
3335       assign = slang_operation_new(1);
3336       assign->type = SLANG_OPER_ASSIGN;
3337       assign->num_children = 2;
3338       assign->children = slang_operation_new(2);
3339       /* lhs (__retVal) */
3340       assign->children[0].type = SLANG_OPER_IDENTIFIER;
3341       assign->children[0].a_id = a_retVal;
3342       assign->children[0].locals->outer_scope = assign->locals;
3343       /* rhs (expr) */
3344       /* XXX we might be able to avoid this copy someday */
3345       slang_operation_copy(&assign->children[1], &oper->children[0]);
3346
3347       /* assemble the new code */
3348       n = new_seq(_slang_gen_operation(A, assign),
3349                   new_return(A->curFuncEndLabel));
3350
3351       slang_operation_delete(assign);
3352       return n;
3353    }
3354 }
3355
3356
3357 #if 0
3358 /**
3359  * Determine if the given operation/expression is const-valued.
3360  */
3361 static GLboolean
3362 _slang_is_constant_expr(const slang_operation *oper)
3363 {
3364    slang_variable *var;
3365    GLuint i;
3366
3367    switch (oper->type) {
3368    case SLANG_OPER_IDENTIFIER:
3369       var = _slang_variable_locate(oper->locals, oper->a_id, GL_TRUE);
3370       if (var && var->type.qualifier == SLANG_QUAL_CONST)
3371          return GL_TRUE;
3372       return GL_FALSE;
3373    default:
3374       for (i = 0; i < oper->num_children; i++) {
3375          if (!_slang_is_constant_expr(&oper->children[i]))
3376             return GL_FALSE;
3377       }
3378       return GL_TRUE;
3379    }
3380 }
3381 #endif
3382
3383
3384 /**
3385  * Check if an assignment of type t1 to t0 is legal.
3386  * XXX more cases needed.
3387  */
3388 static GLboolean
3389 _slang_assignment_compatible(slang_assemble_ctx *A,
3390                              slang_operation *op0,
3391                              slang_operation *op1)
3392 {
3393    slang_typeinfo t0, t1;
3394    GLuint sz0, sz1;
3395
3396    if (op0->type == SLANG_OPER_POSTINCREMENT ||
3397        op0->type == SLANG_OPER_POSTDECREMENT) {
3398       return GL_FALSE;
3399    }
3400
3401    slang_typeinfo_construct(&t0);
3402    typeof_operation(A, op0, &t0);
3403
3404    slang_typeinfo_construct(&t1);
3405    typeof_operation(A, op1, &t1);
3406
3407    sz0 = _slang_sizeof_type_specifier(&t0.spec);
3408    sz1 = _slang_sizeof_type_specifier(&t1.spec);
3409
3410 #if 1
3411    if (sz0 != sz1) {
3412       /*printf("assignment size mismatch %u vs %u\n", sz0, sz1);*/
3413       return GL_FALSE;
3414    }
3415 #endif
3416
3417    if (t0.spec.type == SLANG_SPEC_STRUCT &&
3418        t1.spec.type == SLANG_SPEC_STRUCT &&
3419        t0.spec._struct->a_name != t1.spec._struct->a_name)
3420       return GL_FALSE;
3421
3422    if (t0.spec.type == SLANG_SPEC_FLOAT &&
3423        t1.spec.type == SLANG_SPEC_BOOL)
3424       return GL_FALSE;
3425
3426 #if 0 /* not used just yet - causes problems elsewhere */
3427    if (t0.spec.type == SLANG_SPEC_INT &&
3428        t1.spec.type == SLANG_SPEC_FLOAT)
3429       return GL_FALSE;
3430 #endif
3431
3432    if (t0.spec.type == SLANG_SPEC_BOOL &&
3433        t1.spec.type == SLANG_SPEC_FLOAT)
3434       return GL_FALSE;
3435
3436    if (t0.spec.type == SLANG_SPEC_BOOL &&
3437        t1.spec.type == SLANG_SPEC_INT)
3438       return GL_FALSE;
3439
3440    return GL_TRUE;
3441 }
3442
3443
3444 /**
3445  * Generate IR tree for a local variable declaration.
3446  * Basically do some error checking and call _slang_gen_var_decl().
3447  */
3448 static slang_ir_node *
3449 _slang_gen_declaration(slang_assemble_ctx *A, slang_operation *oper)
3450 {
3451    const char *varName = (char *) oper->a_id;
3452    slang_variable *var;
3453    slang_ir_node *varDecl;
3454    slang_operation *initializer;
3455
3456    assert(oper->type == SLANG_OPER_VARIABLE_DECL);
3457    assert(oper->num_children <= 1);
3458
3459    /* lookup the variable by name */
3460    var = _slang_variable_locate(oper->locals, oper->a_id, GL_TRUE);
3461    if (!var)
3462       return NULL;  /* "shouldn't happen" */
3463
3464    if (var->type.qualifier == SLANG_QUAL_ATTRIBUTE ||
3465        var->type.qualifier == SLANG_QUAL_VARYING ||
3466        var->type.qualifier == SLANG_QUAL_UNIFORM) {
3467       /* can't declare attribute/uniform vars inside functions */
3468       slang_info_log_error(A->log,
3469                 "local variable '%s' cannot be an attribute/uniform/varying",
3470                 varName);
3471       return NULL;
3472    }
3473
3474 #if 0
3475    if (v->declared) {
3476       slang_info_log_error(A->log, "variable '%s' redeclared", varName);
3477       return NULL;
3478    }
3479 #endif
3480
3481    /* check if the var has an initializer */
3482    if (oper->num_children > 0) {
3483       assert(oper->num_children == 1);
3484       initializer = &oper->children[0];
3485    }
3486    else if (var->initializer) {
3487       initializer = var->initializer;
3488    }
3489    else {
3490       initializer = NULL;
3491    }
3492
3493    if (initializer) {
3494       /* check/compare var type and initializer type */
3495       if (!_slang_assignment_compatible(A, oper, initializer)) {
3496          slang_info_log_error(A->log, "incompatible types in assignment");
3497          return NULL;
3498       }         
3499    }
3500    else {
3501       if (var->type.qualifier == SLANG_QUAL_CONST) {
3502          slang_info_log_error(A->log,
3503                        "const-qualified variable '%s' requires initializer",
3504                        varName);
3505          return NULL;
3506       }
3507    }
3508
3509    /* Generate IR node */
3510    varDecl = _slang_gen_var_decl(A, var, initializer);
3511    if (!varDecl)
3512       return NULL;
3513
3514    return varDecl;
3515 }
3516
3517
3518 /**
3519  * Generate IR tree for a reference to a variable (such as in an expression).
3520  * This is different from a variable declaration.
3521  */
3522 static slang_ir_node *
3523 _slang_gen_variable(slang_assemble_ctx * A, slang_operation *oper)
3524 {
3525    /* If there's a variable associated with this oper (from inlining)
3526     * use it.  Otherwise, use the oper's var id.
3527     */
3528    slang_atom name = oper->var ? oper->var->a_name : oper->a_id;
3529    slang_variable *var = _slang_variable_locate(oper->locals, name, GL_TRUE);
3530    slang_ir_node *n;
3531    if (!var) {
3532       slang_info_log_error(A->log, "undefined variable '%s'", (char *) name);
3533       return NULL;
3534    }
3535    assert(var->declared);
3536    n = new_var(A, var);
3537    return n;
3538 }
3539
3540
3541
3542 /**
3543  * Return the number of components actually named by the swizzle.
3544  * Recall that swizzles may have undefined/don't-care values.
3545  */
3546 static GLuint
3547 swizzle_size(GLuint swizzle)
3548 {
3549    GLuint size = 0, i;
3550    for (i = 0; i < 4; i++) {
3551       GLuint swz = GET_SWZ(swizzle, i);
3552       size += (swz >= 0 && swz <= 3);
3553    }
3554    return size;
3555 }
3556
3557
3558 static slang_ir_node *
3559 _slang_gen_swizzle(slang_ir_node *child, GLuint swizzle)
3560 {
3561    slang_ir_node *n = new_node1(IR_SWIZZLE, child);
3562    assert(child);
3563    if (n) {
3564       assert(!n->Store);
3565       n->Store = _slang_new_ir_storage_relative(0,
3566                                                 swizzle_size(swizzle),
3567                                                 child->Store);
3568       n->Store->Swizzle = swizzle;
3569    }
3570    return n;
3571 }
3572
3573
3574 static GLboolean
3575 is_store_writable(const slang_assemble_ctx *A, const slang_ir_storage *store)
3576 {
3577    while (store->Parent)
3578       store = store->Parent;
3579
3580    if (!(store->File == PROGRAM_OUTPUT ||
3581          store->File == PROGRAM_TEMPORARY ||
3582          (store->File == PROGRAM_VARYING &&
3583           A->program->Target == GL_VERTEX_PROGRAM_ARB))) {
3584       return GL_FALSE;
3585    }
3586    else {
3587       return GL_TRUE;
3588    }
3589 }
3590
3591
3592 /**
3593  * Walk up an IR storage path to compute the final swizzle.
3594  * This is used when we find an expression such as "foo.xz.yx".
3595  */
3596 static GLuint
3597 root_swizzle(const slang_ir_storage *st)
3598 {
3599    GLuint swizzle = st->Swizzle;
3600    while (st->Parent) {
3601       st = st->Parent;
3602       swizzle = _slang_swizzle_swizzle(st->Swizzle, swizzle);
3603    }
3604    return swizzle;
3605 }
3606
3607
3608 /**
3609  * Generate IR tree for an assignment (=).
3610  */
3611 static slang_ir_node *
3612 _slang_gen_assignment(slang_assemble_ctx * A, slang_operation *oper)
3613 {
3614    if (oper->children[0].type == SLANG_OPER_IDENTIFIER) {
3615       /* Check that var is writeable */
3616       slang_variable *var
3617          = _slang_variable_locate(oper->children[0].locals,
3618                                   oper->children[0].a_id, GL_TRUE);
3619       if (!var) {
3620          slang_info_log_error(A->log, "undefined variable '%s'",
3621                               (char *) oper->children[0].a_id);
3622          return NULL;
3623       }
3624       if (var->type.qualifier == SLANG_QUAL_CONST ||
3625           var->type.qualifier == SLANG_QUAL_ATTRIBUTE ||
3626           var->type.qualifier == SLANG_QUAL_UNIFORM ||
3627           (var->type.qualifier == SLANG_QUAL_VARYING &&
3628            A->program->Target == GL_FRAGMENT_PROGRAM_ARB)) {
3629          slang_info_log_error(A->log,
3630                               "illegal assignment to read-only variable '%s'",
3631                               (char *) oper->children[0].a_id);
3632          return NULL;
3633       }
3634    }
3635
3636    if (oper->children[0].type == SLANG_OPER_IDENTIFIER &&
3637        oper->children[1].type == SLANG_OPER_CALL) {
3638       /* Special case of:  x = f(a, b)
3639        * Replace with f(a, b, x)  (where x == hidden __retVal out param)
3640        *
3641        * XXX this could be even more effective if we could accomodate
3642        * cases such as "v.x = f();"  - would help with typical vertex
3643        * transformation.
3644        */
3645       slang_ir_node *n;
3646       n = _slang_gen_function_call_name(A,
3647                                       (const char *) oper->children[1].a_id,
3648                                       &oper->children[1], &oper->children[0]);
3649       return n;
3650    }
3651    else {
3652       slang_ir_node *n, *lhs, *rhs;
3653
3654       /* lhs and rhs type checking */
3655       if (!_slang_assignment_compatible(A,
3656                                         &oper->children[0],
3657                                         &oper->children[1])) {
3658          slang_info_log_error(A->log, "incompatible types in assignment");
3659          return NULL;
3660       }
3661
3662       lhs = _slang_gen_operation(A, &oper->children[0]);
3663       if (!lhs) {
3664          return NULL;
3665       }
3666
3667       if (!lhs->Store) {
3668          slang_info_log_error(A->log,
3669                               "invalid left hand side for assignment");
3670          return NULL;
3671       }
3672
3673       /* check that lhs is writable */
3674       if (!is_store_writable(A, lhs->Store)) {
3675          slang_info_log_error(A->log,
3676                               "illegal assignment to read-only l-value");
3677          return NULL;
3678       }
3679
3680       rhs = _slang_gen_operation(A, &oper->children[1]);
3681       if (lhs && rhs) {
3682          /* convert lhs swizzle into writemask */
3683          const GLuint swizzle = root_swizzle(lhs->Store);
3684          GLuint writemask, newSwizzle = 0x0;
3685          if (!swizzle_to_writemask(A, swizzle, &writemask, &newSwizzle)) {
3686             /* Non-simple writemask, need to swizzle right hand side in
3687              * order to put components into the right place.
3688              */
3689             rhs = _slang_gen_swizzle(rhs, newSwizzle);
3690          }
3691          n = new_node2(IR_COPY, lhs, rhs);
3692          return n;
3693       }
3694       else {
3695          return NULL;
3696       }
3697    }
3698 }
3699
3700
3701 /**
3702  * Generate IR tree for referencing a field in a struct (or basic vector type)
3703  */
3704 static slang_ir_node *
3705 _slang_gen_struct_field(slang_assemble_ctx * A, slang_operation *oper)
3706 {
3707    slang_typeinfo ti;
3708
3709    /* type of struct */
3710    slang_typeinfo_construct(&ti);
3711    typeof_operation(A, &oper->children[0], &ti);
3712
3713    if (_slang_type_is_vector(ti.spec.type)) {
3714       /* the field should be a swizzle */
3715       const GLuint rows = _slang_type_dim(ti.spec.type);
3716       slang_swizzle swz;
3717       slang_ir_node *n;
3718       GLuint swizzle;
3719       if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
3720          slang_info_log_error(A->log, "Bad swizzle");
3721          return NULL;
3722       }
3723       swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
3724                               swz.swizzle[1],
3725                               swz.swizzle[2],
3726                               swz.swizzle[3]);
3727
3728       n = _slang_gen_operation(A, &oper->children[0]);
3729       /* create new parent node with swizzle */
3730       if (n)
3731          n = _slang_gen_swizzle(n, swizzle);
3732       return n;
3733    }
3734    else if (   ti.spec.type == SLANG_SPEC_FLOAT
3735             || ti.spec.type == SLANG_SPEC_INT
3736             || ti.spec.type == SLANG_SPEC_BOOL) {
3737       const GLuint rows = 1;
3738       slang_swizzle swz;
3739       slang_ir_node *n;
3740       GLuint swizzle;
3741       if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
3742          slang_info_log_error(A->log, "Bad swizzle");
3743       }
3744       swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
3745                               swz.swizzle[1],
3746                               swz.swizzle[2],
3747                               swz.swizzle[3]);
3748       n = _slang_gen_operation(A, &oper->children[0]);
3749       /* create new parent node with swizzle */
3750       n = _slang_gen_swizzle(n, swizzle);
3751       return n;
3752    }
3753    else {
3754       /* the field is a structure member (base.field) */
3755       /* oper->children[0] is the base */
3756       /* oper->a_id is the field name */
3757       slang_ir_node *base, *n;
3758       slang_typeinfo field_ti;
3759       GLint fieldSize, fieldOffset = -1;
3760
3761       /* type of field */
3762       slang_typeinfo_construct(&field_ti);
3763       typeof_operation(A, oper, &field_ti);
3764
3765       fieldSize = _slang_sizeof_type_specifier(&field_ti.spec);
3766       if (fieldSize > 0)
3767          fieldOffset = _slang_field_offset(&ti.spec, oper->a_id);
3768
3769       if (fieldSize == 0 || fieldOffset < 0) {
3770          const char *structName;
3771          if (ti.spec._struct)
3772             structName = (char *) ti.spec._struct->a_name;
3773          else
3774             structName = "unknown";
3775          slang_info_log_error(A->log,
3776                               "\"%s\" is not a member of struct \"%s\"",
3777                               (char *) oper->a_id, structName);
3778          return NULL;
3779       }
3780       assert(fieldSize >= 0);
3781
3782       base = _slang_gen_operation(A, &oper->children[0]);
3783       if (!base) {
3784          /* error msg should have already been logged */
3785          return NULL;
3786       }
3787
3788       n = new_node1(IR_FIELD, base);
3789       if (!n)
3790          return NULL;
3791
3792       n->Field = (char *) oper->a_id;
3793
3794       /* Store the field's offset in storage->Index */
3795       n->Store = _slang_new_ir_storage(base->Store->File,
3796                                        fieldOffset,
3797                                        fieldSize);
3798
3799       return n;
3800    }
3801 }
3802
3803
3804 /**
3805  * Gen code for array indexing.
3806  */
3807 static slang_ir_node *
3808 _slang_gen_array_element(slang_assemble_ctx * A, slang_operation *oper)
3809 {
3810    slang_typeinfo array_ti;
3811
3812    /* get array's type info */
3813    slang_typeinfo_construct(&array_ti);
3814    typeof_operation(A, &oper->children[0], &array_ti);
3815
3816    if (_slang_type_is_vector(array_ti.spec.type)) {
3817       /* indexing a simple vector type: "vec4 v; v[0]=p;" */
3818       /* translate the index into a swizzle/writemask: "v.x=p" */
3819       const GLuint max = _slang_type_dim(array_ti.spec.type);
3820       GLint index;
3821       slang_ir_node *n;
3822
3823       index = (GLint) oper->children[1].literal[0];
3824       if (oper->children[1].type != SLANG_OPER_LITERAL_INT ||
3825           index >= (GLint) max) {
3826 #if 0
3827          slang_info_log_error(A->log, "Invalid array index for vector type");
3828          printf("type = %d\n", oper->children[1].type);
3829          printf("index = %d, max = %d\n", index, max);
3830          printf("array = %s\n", (char*)oper->children[0].a_id);
3831          printf("index = %s\n", (char*)oper->children[1].a_id);
3832          return NULL;
3833 #else
3834          index = 0;
3835 #endif
3836       }
3837
3838       n = _slang_gen_operation(A, &oper->children[0]);
3839       if (n) {
3840          /* use swizzle to access the element */
3841          GLuint swizzle = MAKE_SWIZZLE4(SWIZZLE_X + index,
3842                                         SWIZZLE_NIL,
3843                                         SWIZZLE_NIL,
3844                                         SWIZZLE_NIL);
3845          n = _slang_gen_swizzle(n, swizzle);
3846       }
3847       assert(n->Store);
3848       return n;
3849    }
3850    else {
3851       /* conventional array */
3852       slang_typeinfo elem_ti;
3853       slang_ir_node *elem, *array, *index;
3854       GLint elemSize, arrayLen;
3855
3856       /* size of array element */
3857       slang_typeinfo_construct(&elem_ti);
3858       typeof_operation(A, oper, &elem_ti);
3859       elemSize = _slang_sizeof_type_specifier(&elem_ti.spec);
3860
3861       if (_slang_type_is_matrix(array_ti.spec.type))
3862          arrayLen = _slang_type_dim(array_ti.spec.type);
3863       else
3864          arrayLen = array_ti.array_len;
3865
3866       slang_typeinfo_destruct(&array_ti);
3867       slang_typeinfo_destruct(&elem_ti);
3868
3869       if (elemSize <= 0) {
3870          /* unknown var or type */
3871          slang_info_log_error(A->log, "Undefined variable or type");
3872          return NULL;
3873       }
3874
3875       array = _slang_gen_operation(A, &oper->children[0]);
3876       index = _slang_gen_operation(A, &oper->children[1]);
3877       if (array && index) {
3878          /* bounds check */
3879          GLint constIndex = -1;
3880          if (index->Opcode == IR_FLOAT) {
3881             constIndex = (int) index->Value[0];
3882             if (constIndex < 0 || constIndex >= arrayLen) {
3883                slang_info_log_error(A->log,
3884                                 "Array index out of bounds (index=%d size=%d)",
3885                                  constIndex, arrayLen);
3886                _slang_free_ir_tree(array);
3887                _slang_free_ir_tree(index);
3888                return NULL;
3889             }
3890          }
3891
3892          if (!array->Store) {
3893             slang_info_log_error(A->log, "Invalid array");
3894             return NULL;
3895          }
3896
3897          elem = new_node2(IR_ELEMENT, array, index);
3898
3899          /* The storage info here will be updated during code emit */
3900          elem->Store = _slang_new_ir_storage(array->Store->File,
3901                                              array->Store->Index,
3902                                              elemSize);
3903          elem->Store->Swizzle = _slang_var_swizzle(elemSize, 0);
3904          return elem;
3905       }
3906       else {
3907          _slang_free_ir_tree(array);
3908          _slang_free_ir_tree(index);
3909          return NULL;
3910       }
3911    }
3912 }
3913
3914
3915 static slang_ir_node *
3916 _slang_gen_compare(slang_assemble_ctx *A, slang_operation *oper,
3917                    slang_ir_opcode opcode)
3918 {
3919    slang_typeinfo t0, t1;
3920    slang_ir_node *n;
3921    
3922    slang_typeinfo_construct(&t0);
3923    typeof_operation(A, &oper->children[0], &t0);
3924
3925    slang_typeinfo_construct(&t1);
3926    typeof_operation(A, &oper->children[0], &t1);
3927
3928    if (t0.spec.type == SLANG_SPEC_ARRAY ||
3929        t1.spec.type == SLANG_SPEC_ARRAY) {
3930       slang_info_log_error(A->log, "Illegal array comparison");
3931       return NULL;
3932    }
3933
3934    if (oper->type != SLANG_OPER_EQUAL &&
3935        oper->type != SLANG_OPER_NOTEQUAL) {
3936       /* <, <=, >, >= can only be used with scalars */
3937       if ((t0.spec.type != SLANG_SPEC_INT &&
3938            t0.spec.type != SLANG_SPEC_FLOAT) ||
3939           (t1.spec.type != SLANG_SPEC_INT &&
3940            t1.spec.type != SLANG_SPEC_FLOAT)) {
3941          slang_info_log_error(A->log, "Incompatible type(s) for inequality operator");
3942          return NULL;
3943       }
3944    }
3945
3946    n =  new_node2(opcode,
3947                   _slang_gen_operation(A, &oper->children[0]),
3948                   _slang_gen_operation(A, &oper->children[1]));
3949
3950    /* result is a bool (size 1) */
3951    n->Store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -1, 1);
3952
3953    return n;
3954 }
3955
3956
3957 #if 0
3958 static void
3959 print_vars(slang_variable_scope *s)
3960 {
3961    int i;
3962    printf("vars: ");
3963    for (i = 0; i < s->num_variables; i++) {
3964       printf("%s %d, \n",
3965              (char*) s->variables[i]->a_name,
3966              s->variables[i]->declared);
3967    }
3968
3969    printf("\n");
3970 }
3971 #endif
3972
3973
3974 #if 0
3975 static void
3976 _slang_undeclare_vars(slang_variable_scope *locals)
3977 {
3978    if (locals->num_variables > 0) {
3979       int i;
3980       for (i = 0; i < locals->num_variables; i++) {
3981          slang_variable *v = locals->variables[i];
3982          printf("undeclare %s at %p\n", (char*) v->a_name, v);
3983          v->declared = GL_FALSE;
3984       }
3985    }
3986 }
3987 #endif
3988
3989
3990 /**
3991  * Generate IR tree for a slang_operation (AST node)
3992  */
3993 static slang_ir_node *
3994 _slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper)
3995 {
3996    switch (oper->type) {
3997    case SLANG_OPER_BLOCK_NEW_SCOPE:
3998       {
3999          slang_ir_node *n;
4000
4001          _slang_push_var_table(A->vartable);
4002
4003          oper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE; /* temp change */
4004          n = _slang_gen_operation(A, oper);
4005          oper->type = SLANG_OPER_BLOCK_NEW_SCOPE; /* restore */
4006
4007          _slang_pop_var_table(A->vartable);
4008
4009          /*_slang_undeclare_vars(oper->locals);*/
4010          /*print_vars(oper->locals);*/
4011
4012          if (n)
4013             n = new_node1(IR_SCOPE, n);
4014          return n;
4015       }
4016       break;
4017
4018    case SLANG_OPER_BLOCK_NO_NEW_SCOPE:
4019       /* list of operations */
4020       if (oper->num_children > 0)
4021       {
4022          slang_ir_node *n, *tree = NULL;
4023          GLuint i;
4024
4025          for (i = 0; i < oper->num_children; i++) {
4026             n = _slang_gen_operation(A, &oper->children[i]);
4027             if (!n) {
4028                _slang_free_ir_tree(tree);
4029                return NULL; /* error must have occured */
4030             }
4031             tree = new_seq(tree, n);
4032          }
4033
4034          return tree;
4035       }
4036       else {
4037          return new_node0(IR_NOP);
4038       }
4039
4040    case SLANG_OPER_EXPRESSION:
4041       return _slang_gen_operation(A, &oper->children[0]);
4042
4043    case SLANG_OPER_FOR:
4044       return _slang_gen_for(A, oper);
4045    case SLANG_OPER_DO:
4046       return _slang_gen_do(A, oper);
4047    case SLANG_OPER_WHILE:
4048       return _slang_gen_while(A, oper);
4049    case SLANG_OPER_BREAK:
4050       if (!A->CurLoop) {
4051          if (!A->UnrollLoop)
4052             slang_info_log_error(A->log, "'break' not in loop");
4053          return NULL;
4054       }
4055       return new_break(A->CurLoop);
4056    case SLANG_OPER_CONTINUE:
4057       if (!A->CurLoop) {
4058          if (!A->UnrollLoop)
4059             slang_info_log_error(A->log, "'continue' not in loop");
4060          return NULL;
4061       }
4062       return _slang_gen_continue(A, oper);
4063    case SLANG_OPER_DISCARD:
4064       return new_node0(IR_KILL);
4065
4066    case SLANG_OPER_EQUAL:
4067       return _slang_gen_compare(A, oper, IR_EQUAL);
4068    case SLANG_OPER_NOTEQUAL:
4069       return _slang_gen_compare(A, oper, IR_NOTEQUAL);
4070    case SLANG_OPER_GREATER:
4071       return _slang_gen_compare(A, oper, IR_SGT);
4072    case SLANG_OPER_LESS:
4073       return _slang_gen_compare(A, oper, IR_SLT);
4074    case SLANG_OPER_GREATEREQUAL:
4075       return _slang_gen_compare(A, oper, IR_SGE);
4076    case SLANG_OPER_LESSEQUAL:
4077       return _slang_gen_compare(A, oper, IR_SLE);
4078    case SLANG_OPER_ADD:
4079       {
4080          slang_ir_node *n;
4081          assert(oper->num_children == 2);
4082          n = _slang_gen_function_call_name(A, "+", oper, NULL);
4083          return n;
4084       }
4085    case SLANG_OPER_SUBTRACT:
4086       {
4087          slang_ir_node *n;
4088          assert(oper->num_children == 2);
4089          n = _slang_gen_function_call_name(A, "-", oper, NULL);
4090          return n;
4091       }
4092    case SLANG_OPER_MULTIPLY:
4093       {
4094          slang_ir_node *n;
4095          assert(oper->num_children == 2);
4096          n = _slang_gen_function_call_name(A, "*", oper, NULL);
4097          return n;
4098       }
4099    case SLANG_OPER_DIVIDE:
4100       {
4101          slang_ir_node *n;
4102          assert(oper->num_children == 2);
4103          n = _slang_gen_function_call_name(A, "/", oper, NULL);
4104          return n;
4105       }
4106    case SLANG_OPER_MINUS:
4107       {
4108          slang_ir_node *n;
4109          assert(oper->num_children == 1);
4110          n = _slang_gen_function_call_name(A, "-", oper, NULL);
4111          return n;
4112       }
4113    case SLANG_OPER_PLUS:
4114       /* +expr   --> do nothing */
4115       return _slang_gen_operation(A, &oper->children[0]);
4116    case SLANG_OPER_VARIABLE_DECL:
4117       return _slang_gen_declaration(A, oper);
4118    case SLANG_OPER_ASSIGN:
4119       return _slang_gen_assignment(A, oper);
4120    case SLANG_OPER_ADDASSIGN:
4121       {
4122          slang_ir_node *n;
4123          assert(oper->num_children == 2);
4124          n = _slang_gen_function_call_name(A, "+=", oper, NULL);
4125          return n;
4126       }
4127    case SLANG_OPER_SUBASSIGN:
4128       {
4129          slang_ir_node *n;
4130          assert(oper->num_children == 2);
4131          n = _slang_gen_function_call_name(A, "-=", oper, NULL);
4132          return n;
4133       }
4134       break;
4135    case SLANG_OPER_MULASSIGN:
4136       {
4137          slang_ir_node *n;
4138          assert(oper->num_children == 2);
4139          n = _slang_gen_function_call_name(A, "*=", oper, NULL);
4140          return n;
4141       }
4142    case SLANG_OPER_DIVASSIGN:
4143       {
4144          slang_ir_node *n;
4145          assert(oper->num_children == 2);
4146          n = _slang_gen_function_call_name(A, "/=", oper, NULL);
4147          return n;
4148       }
4149    case SLANG_OPER_LOGICALAND:
4150       {
4151          slang_ir_node *n;
4152          assert(oper->num_children == 2);
4153          n = _slang_gen_logical_and(A, oper);
4154          return n;
4155       }
4156    case SLANG_OPER_LOGICALOR:
4157       {
4158          slang_ir_node *n;
4159          assert(oper->num_children == 2);
4160          n = _slang_gen_logical_or(A, oper);
4161          return n;
4162       }
4163    case SLANG_OPER_LOGICALXOR:
4164       return _slang_gen_xor(A, oper);
4165    case SLANG_OPER_NOT:
4166       return _slang_gen_not(A, oper);
4167    case SLANG_OPER_SELECT:  /* b ? x : y */
4168       {
4169          slang_ir_node *n;
4170          assert(oper->num_children == 3);
4171          n = _slang_gen_select(A, oper);
4172          return n;
4173       }
4174
4175    case SLANG_OPER_ASM:
4176       return _slang_gen_asm(A, oper, NULL);
4177    case SLANG_OPER_CALL:
4178       return _slang_gen_function_call_name(A, (const char *) oper->a_id,
4179                                            oper, NULL);
4180    case SLANG_OPER_METHOD:
4181       return _slang_gen_method_call(A, oper);
4182    case SLANG_OPER_RETURN:
4183       return _slang_gen_return(A, oper);
4184    case SLANG_OPER_LABEL:
4185       return new_label(oper->label);
4186    case SLANG_OPER_IDENTIFIER:
4187       return _slang_gen_variable(A, oper);
4188    case SLANG_OPER_IF:
4189       return _slang_gen_if(A, oper);
4190    case SLANG_OPER_FIELD:
4191       return _slang_gen_struct_field(A, oper);
4192    case SLANG_OPER_SUBSCRIPT:
4193       return _slang_gen_array_element(A, oper);
4194    case SLANG_OPER_LITERAL_FLOAT:
4195       /* fall-through */
4196    case SLANG_OPER_LITERAL_INT:
4197       /* fall-through */
4198    case SLANG_OPER_LITERAL_BOOL:
4199       return new_float_literal(oper->literal, oper->literal_size);
4200
4201    case SLANG_OPER_POSTINCREMENT:   /* var++ */
4202       {
4203          slang_ir_node *n;
4204          assert(oper->num_children == 1);
4205          n = _slang_gen_function_call_name(A, "__postIncr", oper, NULL);
4206          return n;
4207       }
4208    case SLANG_OPER_POSTDECREMENT:   /* var-- */
4209       {
4210          slang_ir_node *n;
4211          assert(oper->num_children == 1);
4212          n = _slang_gen_function_call_name(A, "__postDecr", oper, NULL);
4213          return n;
4214       }
4215    case SLANG_OPER_PREINCREMENT:   /* ++var */
4216       {
4217          slang_ir_node *n;
4218          assert(oper->num_children == 1);
4219          n = _slang_gen_function_call_name(A, "++", oper, NULL);
4220          return n;
4221       }
4222    case SLANG_OPER_PREDECREMENT:   /* --var */
4223       {
4224          slang_ir_node *n;
4225          assert(oper->num_children == 1);
4226          n = _slang_gen_function_call_name(A, "--", oper, NULL);
4227          return n;
4228       }
4229
4230    case SLANG_OPER_NON_INLINED_CALL:
4231    case SLANG_OPER_SEQUENCE:
4232       {
4233          slang_ir_node *tree = NULL;
4234          GLuint i;
4235          for (i = 0; i < oper->num_children; i++) {
4236             slang_ir_node *n = _slang_gen_operation(A, &oper->children[i]);
4237             tree = new_seq(tree, n);
4238             if (n)
4239                tree->Store = n->Store;
4240          }
4241          if (oper->type == SLANG_OPER_NON_INLINED_CALL) {
4242             tree = new_function_call(tree, oper->label);
4243          }
4244          return tree;
4245       }
4246
4247    case SLANG_OPER_NONE:
4248    case SLANG_OPER_VOID:
4249       /* returning NULL here would generate an error */
4250       return new_node0(IR_NOP);
4251
4252    default:
4253       _mesa_problem(NULL, "bad node type %d in _slang_gen_operation",
4254                     oper->type);
4255       return new_node0(IR_NOP);
4256    }
4257
4258    return NULL;
4259 }
4260
4261
4262 /**
4263  * Check if the given type specifier is a rectangular texture sampler.
4264  */
4265 static GLboolean
4266 is_rect_sampler_spec(const slang_type_specifier *spec)
4267 {
4268    while (spec->_array) {
4269       spec = spec->_array;
4270    }
4271    return spec->type == SLANG_SPEC_SAMPLER2DRECT ||
4272           spec->type == SLANG_SPEC_SAMPLER2DRECTSHADOW;
4273 }
4274
4275
4276
4277 /**
4278  * Called by compiler when a global variable has been parsed/compiled.
4279  * Here we examine the variable's type to determine what kind of register
4280  * storage will be used.
4281  *
4282  * A uniform such as "gl_Position" will become the register specification
4283  * (PROGRAM_OUTPUT, VERT_RESULT_HPOS).  Or, uniform "gl_FogFragCoord"
4284  * will be (PROGRAM_INPUT, FRAG_ATTRIB_FOGC).
4285  *
4286  * Samplers are interesting.  For "uniform sampler2D tex;" we'll specify
4287  * (PROGRAM_SAMPLER, index) where index is resolved at link-time to an
4288  * actual texture unit (as specified by the user calling glUniform1i()).
4289  */
4290 GLboolean
4291 _slang_codegen_global_variable(slang_assemble_ctx *A, slang_variable *var,
4292                                slang_unit_type type)
4293 {
4294    struct gl_program *prog = A->program;
4295    const char *varName = (char *) var->a_name;
4296    GLboolean success = GL_TRUE;
4297    slang_ir_storage *store = NULL;
4298    int dbg = 0;
4299    const GLenum datatype = _slang_gltype_from_specifier(&var->type.specifier);
4300    const GLint size = _slang_sizeof_type_specifier(&var->type.specifier);
4301    const GLint arrayLen = _slang_array_length(var);
4302    const GLint totalSize = _slang_array_size(size, arrayLen);
4303    GLint texIndex = sampler_to_texture_index(var->type.specifier.type);
4304
4305    /* check for sampler2D arrays */
4306    if (texIndex == -1 && var->type.specifier._array)
4307       texIndex = sampler_to_texture_index(var->type.specifier._array->type);
4308
4309    if (texIndex != -1) {
4310       /* This is a texture sampler variable...
4311        * store->File = PROGRAM_SAMPLER
4312        * store->Index = sampler number (0..7, typically)
4313        * store->Size = texture type index (1D, 2D, 3D, cube, etc)
4314        */
4315       if (var->initializer) {
4316          slang_info_log_error(A->log, "illegal assignment to '%s'", varName);
4317          return GL_FALSE;
4318       }
4319 #if FEATURE_es2_glsl /* XXX should use FEATURE_texture_rect */
4320       /* disallow rect samplers */
4321       if (is_rect_sampler_spec(&var->type.specifier)) {
4322          slang_info_log_error(A->log, "invalid sampler type for '%s'", varName);
4323          return GL_FALSE;
4324       }
4325 #else
4326       (void) is_rect_sampler_spec; /* silence warning */
4327 #endif
4328       {
4329          GLint sampNum = _mesa_add_sampler(prog->Parameters, varName, datatype);
4330          store = _slang_new_ir_storage_sampler(sampNum, texIndex, totalSize);
4331
4332          /* If we have a sampler array, then we need to allocate the 
4333           * additional samplers to ensure we don't allocate them elsewhere.
4334           * We can't directly use _mesa_add_sampler() as that checks the
4335           * varName and gets a match, so we call _mesa_add_parameter()
4336           * directly and use the last sampler number from the call above.
4337           */
4338          if (arrayLen > 0) {
4339             GLint a = arrayLen - 1;
4340             GLint i;
4341             for (i = 0; i < a; i++) {
4342                GLfloat value = (GLfloat)(i + sampNum + 1);
4343                (void) _mesa_add_parameter(prog->Parameters, PROGRAM_SAMPLER,
4344                                  varName, 1, datatype, &value, NULL, 0x0);
4345             }
4346          }
4347       }
4348       if (dbg) printf("SAMPLER ");
4349    }
4350    else if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
4351       /* Uniform variable */
4352       const GLuint swizzle = _slang_var_swizzle(totalSize, 0);
4353
4354       if (prog) {
4355          /* user-defined uniform */
4356          if (datatype == GL_NONE) {
4357             if (var->type.specifier.type == SLANG_SPEC_STRUCT) {
4358                /* temporary work-around */
4359                GLenum datatype = GL_FLOAT;
4360                GLint uniformLoc = _mesa_add_uniform(prog->Parameters, varName,
4361                                                     totalSize, datatype, NULL);
4362                store = _slang_new_ir_storage_swz(PROGRAM_UNIFORM, uniformLoc,
4363                                                  totalSize, swizzle);
4364
4365                /* XXX what we need to do is unroll the struct into its
4366                 * basic types, creating a uniform variable for each.
4367                 * For example:
4368                 * struct foo {
4369                 *   vec3 a;
4370                 *   vec4 b;
4371                 * };
4372                 * uniform foo f;
4373                 *
4374                 * Should produce uniforms:
4375                 * "f.a"  (GL_FLOAT_VEC3)
4376                 * "f.b"  (GL_FLOAT_VEC4)
4377                 */
4378
4379                if (var->initializer) {
4380                   slang_info_log_error(A->log,
4381                      "unsupported initializer for uniform '%s'", varName);
4382                   return GL_FALSE;
4383                }
4384             }
4385             else {
4386                slang_info_log_error(A->log,
4387                                     "invalid datatype for uniform variable %s",
4388                                     varName);
4389                return GL_FALSE;
4390             }
4391          }
4392          else {
4393             /* non-struct uniform */
4394             if (!_slang_gen_var_decl(A, var, var->initializer))
4395                return GL_FALSE;
4396             store = var->store;
4397          }
4398       }
4399       else {
4400          /* pre-defined uniform, like gl_ModelviewMatrix */
4401          /* We know it's a uniform, but don't allocate storage unless
4402           * it's really used.
4403           */
4404          store = _slang_new_ir_storage_swz(PROGRAM_STATE_VAR, -1,
4405                                            totalSize, swizzle);
4406       }
4407       if (dbg) printf("UNIFORM (sz %d) ", totalSize);
4408    }
4409    else if (var->type.qualifier == SLANG_QUAL_VARYING) {
4410       /* varyings must be float, vec or mat */
4411       if (!_slang_type_is_float_vec_mat(var->type.specifier.type) &&
4412           var->type.specifier.type != SLANG_SPEC_ARRAY) {
4413          slang_info_log_error(A->log,
4414                               "varying '%s' must be float/vector/matrix",
4415                               varName);
4416          return GL_FALSE;
4417       }
4418
4419       if (var->initializer) {
4420          slang_info_log_error(A->log, "illegal initializer for varying '%s'",
4421                               varName);
4422          return GL_FALSE;
4423       }
4424
4425       if (prog) {
4426          /* user-defined varying */
4427          GLbitfield flags;
4428          GLint varyingLoc;
4429          GLuint swizzle;
4430
4431          flags = 0x0;
4432          if (var->type.centroid == SLANG_CENTROID)
4433             flags |= PROG_PARAM_BIT_CENTROID;
4434          if (var->type.variant == SLANG_INVARIANT)
4435             flags |= PROG_PARAM_BIT_INVARIANT;
4436
4437          varyingLoc = _mesa_add_varying(prog->Varying, varName,
4438                                         totalSize, flags);
4439          swizzle = _slang_var_swizzle(size, 0);
4440          store = _slang_new_ir_storage_swz(PROGRAM_VARYING, varyingLoc,
4441                                            totalSize, swizzle);
4442       }
4443       else {
4444          /* pre-defined varying, like gl_Color or gl_TexCoord */
4445          if (type == SLANG_UNIT_FRAGMENT_BUILTIN) {
4446             /* fragment program input */
4447             GLuint swizzle;
4448             GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB,
4449                                              &swizzle);
4450             assert(index >= 0);
4451             assert(index < FRAG_ATTRIB_MAX);
4452             store = _slang_new_ir_storage_swz(PROGRAM_INPUT, index,
4453                                               size, swizzle);
4454          }
4455          else {
4456             /* vertex program output */
4457             GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
4458             GLuint swizzle = _slang_var_swizzle(size, 0);
4459             assert(index >= 0);
4460             assert(index < VERT_RESULT_MAX);
4461             assert(type == SLANG_UNIT_VERTEX_BUILTIN);
4462             store = _slang_new_ir_storage_swz(PROGRAM_OUTPUT, index,
4463                                               size, swizzle);
4464          }
4465          if (dbg) printf("V/F ");
4466       }
4467       if (dbg) printf("VARYING ");
4468    }
4469    else if (var->type.qualifier == SLANG_QUAL_ATTRIBUTE) {
4470       GLuint swizzle;
4471       GLint index;
4472       /* attributes must be float, vec or mat */
4473       if (!_slang_type_is_float_vec_mat(var->type.specifier.type)) {
4474          slang_info_log_error(A->log,
4475                               "attribute '%s' must be float/vector/matrix",
4476                               varName);
4477          return GL_FALSE;
4478       }
4479
4480       if (prog) {
4481          /* user-defined vertex attribute */
4482          const GLint attr = -1; /* unknown */
4483          swizzle = _slang_var_swizzle(size, 0);
4484          index = _mesa_add_attribute(prog->Attributes, varName,
4485                                      size, datatype, attr);
4486          assert(index >= 0);
4487          index = VERT_ATTRIB_GENERIC0 + index;
4488       }
4489       else {
4490          /* pre-defined vertex attrib */
4491          index = _slang_input_index(varName, GL_VERTEX_PROGRAM_ARB, &swizzle);
4492          assert(index >= 0);
4493       }
4494       store = _slang_new_ir_storage_swz(PROGRAM_INPUT, index, size, swizzle);
4495       if (dbg) printf("ATTRIB ");
4496    }
4497    else if (var->type.qualifier == SLANG_QUAL_FIXEDINPUT) {
4498       GLuint swizzle = SWIZZLE_XYZW; /* silence compiler warning */
4499       GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB,
4500                                        &swizzle);
4501       store = _slang_new_ir_storage_swz(PROGRAM_INPUT, index, size, swizzle);
4502       if (dbg) printf("INPUT ");
4503    }
4504    else if (var->type.qualifier == SLANG_QUAL_FIXEDOUTPUT) {
4505       if (type == SLANG_UNIT_VERTEX_BUILTIN) {
4506          GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
4507          store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
4508       }
4509       else {
4510          GLint index = _slang_output_index(varName, GL_FRAGMENT_PROGRAM_ARB);
4511          GLint specialSize = 4; /* treat all fragment outputs as float[4] */
4512          assert(type == SLANG_UNIT_FRAGMENT_BUILTIN);
4513          store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, specialSize);
4514       }
4515       if (dbg) printf("OUTPUT ");
4516    }
4517    else if (var->type.qualifier == SLANG_QUAL_CONST && !prog) {
4518       /* pre-defined global constant, like gl_MaxLights */
4519       store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
4520       if (dbg) printf("CONST ");
4521    }
4522    else {
4523       /* ordinary variable (may be const) */
4524       slang_ir_node *n;
4525
4526       /* IR node to declare the variable */
4527       n = _slang_gen_var_decl(A, var, var->initializer);
4528
4529       /* emit GPU instructions */
4530       success = _slang_emit_code(n, A->vartable, A->program, A->pragmas, GL_FALSE, A->log);
4531
4532       _slang_free_ir_tree(n);
4533    }
4534
4535    if (dbg) printf("GLOBAL VAR %s  idx %d\n", (char*) var->a_name,
4536                    store ? store->Index : -2);
4537
4538    if (store)
4539       var->store = store;  /* save var's storage info */
4540
4541    var->declared = GL_TRUE;
4542
4543    return success;
4544 }
4545
4546
4547 /**
4548  * Produce an IR tree from a function AST (fun->body).
4549  * Then call the code emitter to convert the IR tree into gl_program
4550  * instructions.
4551  */
4552 GLboolean
4553 _slang_codegen_function(slang_assemble_ctx * A, slang_function * fun)
4554 {
4555    slang_ir_node *n;
4556    GLboolean success = GL_TRUE;
4557
4558    if (_mesa_strcmp((char *) fun->header.a_name, "main") != 0) {
4559       /* we only really generate code for main, all other functions get
4560        * inlined or codegen'd upon an actual call.
4561        */
4562 #if 0
4563       /* do some basic error checking though */
4564       if (fun->header.type.specifier.type != SLANG_SPEC_VOID) {
4565          /* check that non-void functions actually return something */
4566          slang_operation *op
4567             = _slang_find_node_type(fun->body, SLANG_OPER_RETURN);
4568          if (!op) {
4569             slang_info_log_error(A->log,
4570                                  "function \"%s\" has no return statement",
4571                                  (char *) fun->header.a_name);
4572             printf(
4573                    "function \"%s\" has no return statement\n",
4574                    (char *) fun->header.a_name);
4575             return GL_FALSE;
4576          }
4577       }
4578 #endif
4579       return GL_TRUE;  /* not an error */
4580    }
4581
4582 #if 0
4583    printf("\n*********** codegen_function %s\n", (char *) fun->header.a_name);
4584    slang_print_function(fun, 1);
4585 #endif
4586
4587    /* should have been allocated earlier: */
4588    assert(A->program->Parameters );
4589    assert(A->program->Varying);
4590    assert(A->vartable);
4591    A->CurLoop = NULL;
4592    A->CurFunction = fun;
4593
4594    /* fold constant expressions, etc. */
4595    _slang_simplify(fun->body, &A->space, A->atoms);
4596
4597 #if 0
4598    printf("\n*********** simplified %s\n", (char *) fun->header.a_name);
4599    slang_print_function(fun, 1);
4600 #endif
4601
4602    /* Create an end-of-function label */
4603    A->curFuncEndLabel = _slang_label_new("__endOfFunc__main");
4604
4605    /* push new vartable scope */
4606    _slang_push_var_table(A->vartable);
4607
4608    /* Generate IR tree for the function body code */
4609    n = _slang_gen_operation(A, fun->body);
4610    if (n)
4611       n = new_node1(IR_SCOPE, n);
4612
4613    /* pop vartable, restore previous */
4614    _slang_pop_var_table(A->vartable);
4615
4616    if (!n) {
4617       /* XXX record error */
4618       return GL_FALSE;
4619    }
4620
4621    /* append an end-of-function-label to IR tree */
4622    n = new_seq(n, new_label(A->curFuncEndLabel));
4623
4624    /*_slang_label_delete(A->curFuncEndLabel);*/
4625    A->curFuncEndLabel = NULL;
4626
4627 #if 0
4628    printf("************* New AST for %s *****\n", (char*)fun->header.a_name);
4629    slang_print_function(fun, 1);
4630 #endif
4631 #if 0
4632    printf("************* IR for %s *******\n", (char*)fun->header.a_name);
4633    _slang_print_ir_tree(n, 0);
4634 #endif
4635 #if 0
4636    printf("************* End codegen function ************\n\n");
4637 #endif
4638
4639    /* Emit program instructions */
4640    success = _slang_emit_code(n, A->vartable, A->program, A->pragmas, GL_TRUE, A->log);
4641    _slang_free_ir_tree(n);
4642
4643    /* free codegen context */
4644    /*
4645    _mesa_free(A->codegen);
4646    */
4647
4648    return success;
4649 }
4650