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