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