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