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