glsl2: fix signed/unsigned comparison warning
[mesa.git] / src / mesa / program / ir_to_mesa.cpp
1 /*
2 * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.
3 * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
4 * Copyright © 2010 Intel Corporation
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 * DEALINGS IN THE SOFTWARE.
24 */
25
26 /**
27 * \file ir_to_mesa.cpp
28 *
29 * Translates the IR to ARB_fragment_program text if possible,
30 * printing the result
31 */
32
33 #include <stdio.h>
34 #include "main/compiler.h"
35 #include "ir.h"
36 #include "ir_visitor.h"
37 #include "ir_print_visitor.h"
38 #include "ir_expression_flattening.h"
39 #include "glsl_types.h"
40 #include "glsl_parser_extras.h"
41 #include "../glsl/program.h"
42 #include "ir_optimization.h"
43 #include "ast.h"
44
45 extern "C" {
46 #include "main/mtypes.h"
47 #include "main/shaderapi.h"
48 #include "main/shaderobj.h"
49 #include "main/uniforms.h"
50 #include "program/hash_table.h"
51 #include "program/prog_instruction.h"
52 #include "program/prog_optimize.h"
53 #include "program/prog_print.h"
54 #include "program/program.h"
55 #include "program/prog_uniform.h"
56 #include "program/prog_parameter.h"
57 }
58
59 static int swizzle_for_size(int size);
60
61 /**
62 * This struct is a corresponding struct to Mesa prog_src_register, with
63 * wider fields.
64 */
65 typedef struct ir_to_mesa_src_reg {
66 ir_to_mesa_src_reg(int file, int index, const glsl_type *type)
67 {
68 this->file = file;
69 this->index = index;
70 if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
71 this->swizzle = swizzle_for_size(type->vector_elements);
72 else
73 this->swizzle = SWIZZLE_XYZW;
74 this->negate = 0;
75 this->reladdr = NULL;
76 }
77
78 ir_to_mesa_src_reg()
79 {
80 this->file = PROGRAM_UNDEFINED;
81 this->index = 0;
82 this->swizzle = 0;
83 this->negate = 0;
84 this->reladdr = NULL;
85 }
86
87 int file; /**< PROGRAM_* from Mesa */
88 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
89 GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
90 int negate; /**< NEGATE_XYZW mask from mesa */
91 /** Register index should be offset by the integer in this reg. */
92 ir_to_mesa_src_reg *reladdr;
93 } ir_to_mesa_src_reg;
94
95 typedef struct ir_to_mesa_dst_reg {
96 int file; /**< PROGRAM_* from Mesa */
97 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
98 int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
99 GLuint cond_mask:4;
100 /** Register index should be offset by the integer in this reg. */
101 ir_to_mesa_src_reg *reladdr;
102 } ir_to_mesa_dst_reg;
103
104 extern ir_to_mesa_src_reg ir_to_mesa_undef;
105
106 class ir_to_mesa_instruction : public exec_node {
107 public:
108 /* Callers of this talloc-based new need not call delete. It's
109 * easier to just talloc_free 'ctx' (or any of its ancestors). */
110 static void* operator new(size_t size, void *ctx)
111 {
112 void *node;
113
114 node = talloc_zero_size(ctx, size);
115 assert(node != NULL);
116
117 return node;
118 }
119
120 enum prog_opcode op;
121 ir_to_mesa_dst_reg dst_reg;
122 ir_to_mesa_src_reg src_reg[3];
123 /** Pointer to the ir source this tree came from for debugging */
124 ir_instruction *ir;
125 GLboolean cond_update;
126 int sampler; /**< sampler index */
127 int tex_target; /**< One of TEXTURE_*_INDEX */
128 GLboolean tex_shadow;
129
130 class function_entry *function; /* Set on OPCODE_CAL or OPCODE_BGNSUB */
131 };
132
133 class variable_storage : public exec_node {
134 public:
135 variable_storage(ir_variable *var, int file, int index)
136 : file(file), index(index), var(var)
137 {
138 /* empty */
139 }
140
141 int file;
142 int index;
143 ir_variable *var; /* variable that maps to this, if any */
144 };
145
146 class function_entry : public exec_node {
147 public:
148 ir_function_signature *sig;
149
150 /**
151 * identifier of this function signature used by the program.
152 *
153 * At the point that Mesa instructions for function calls are
154 * generated, we don't know the address of the first instruction of
155 * the function body. So we make the BranchTarget that is called a
156 * small integer and rewrite them during set_branchtargets().
157 */
158 int sig_id;
159
160 /**
161 * Pointer to first instruction of the function body.
162 *
163 * Set during function body emits after main() is processed.
164 */
165 ir_to_mesa_instruction *bgn_inst;
166
167 /**
168 * Index of the first instruction of the function body in actual
169 * Mesa IR.
170 *
171 * Set after convertion from ir_to_mesa_instruction to prog_instruction.
172 */
173 int inst;
174
175 /** Storage for the return value. */
176 ir_to_mesa_src_reg return_reg;
177 };
178
179 class ir_to_mesa_visitor : public ir_visitor {
180 public:
181 ir_to_mesa_visitor();
182 ~ir_to_mesa_visitor();
183
184 function_entry *current_function;
185
186 GLcontext *ctx;
187 struct gl_program *prog;
188 struct gl_shader_program *shader_program;
189 struct gl_shader_compiler_options *options;
190
191 int next_temp;
192
193 variable_storage *find_variable_storage(ir_variable *var);
194
195 function_entry *get_function_signature(ir_function_signature *sig);
196
197 ir_to_mesa_src_reg get_temp(const glsl_type *type);
198 void reladdr_to_temp(ir_instruction *ir,
199 ir_to_mesa_src_reg *reg, int *num_reladdr);
200
201 struct ir_to_mesa_src_reg src_reg_for_float(float val);
202
203 /**
204 * \name Visit methods
205 *
206 * As typical for the visitor pattern, there must be one \c visit method for
207 * each concrete subclass of \c ir_instruction. Virtual base classes within
208 * the hierarchy should not have \c visit methods.
209 */
210 /*@{*/
211 virtual void visit(ir_variable *);
212 virtual void visit(ir_loop *);
213 virtual void visit(ir_loop_jump *);
214 virtual void visit(ir_function_signature *);
215 virtual void visit(ir_function *);
216 virtual void visit(ir_expression *);
217 virtual void visit(ir_swizzle *);
218 virtual void visit(ir_dereference_variable *);
219 virtual void visit(ir_dereference_array *);
220 virtual void visit(ir_dereference_record *);
221 virtual void visit(ir_assignment *);
222 virtual void visit(ir_constant *);
223 virtual void visit(ir_call *);
224 virtual void visit(ir_return *);
225 virtual void visit(ir_discard *);
226 virtual void visit(ir_texture *);
227 virtual void visit(ir_if *);
228 /*@}*/
229
230 struct ir_to_mesa_src_reg result;
231
232 /** List of variable_storage */
233 exec_list variables;
234
235 /** List of function_entry */
236 exec_list function_signatures;
237 int next_signature_id;
238
239 /** List of ir_to_mesa_instruction */
240 exec_list instructions;
241
242 ir_to_mesa_instruction *ir_to_mesa_emit_op0(ir_instruction *ir,
243 enum prog_opcode op);
244
245 ir_to_mesa_instruction *ir_to_mesa_emit_op1(ir_instruction *ir,
246 enum prog_opcode op,
247 ir_to_mesa_dst_reg dst,
248 ir_to_mesa_src_reg src0);
249
250 ir_to_mesa_instruction *ir_to_mesa_emit_op2(ir_instruction *ir,
251 enum prog_opcode op,
252 ir_to_mesa_dst_reg dst,
253 ir_to_mesa_src_reg src0,
254 ir_to_mesa_src_reg src1);
255
256 ir_to_mesa_instruction *ir_to_mesa_emit_op3(ir_instruction *ir,
257 enum prog_opcode op,
258 ir_to_mesa_dst_reg dst,
259 ir_to_mesa_src_reg src0,
260 ir_to_mesa_src_reg src1,
261 ir_to_mesa_src_reg src2);
262
263 void ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
264 enum prog_opcode op,
265 ir_to_mesa_dst_reg dst,
266 ir_to_mesa_src_reg src0);
267
268 void ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
269 enum prog_opcode op,
270 ir_to_mesa_dst_reg dst,
271 ir_to_mesa_src_reg src0,
272 ir_to_mesa_src_reg src1);
273
274 GLboolean try_emit_mad(ir_expression *ir,
275 int mul_operand);
276
277 int get_sampler_uniform_value(ir_dereference *deref);
278
279 void *mem_ctx;
280 };
281
282 ir_to_mesa_src_reg ir_to_mesa_undef = ir_to_mesa_src_reg(PROGRAM_UNDEFINED, 0, NULL);
283
284 ir_to_mesa_dst_reg ir_to_mesa_undef_dst = {
285 PROGRAM_UNDEFINED, 0, SWIZZLE_NOOP, COND_TR, NULL,
286 };
287
288 ir_to_mesa_dst_reg ir_to_mesa_address_reg = {
289 PROGRAM_ADDRESS, 0, WRITEMASK_X, COND_TR, NULL
290 };
291
292 static void fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
293
294 static void fail_link(struct gl_shader_program *prog, const char *fmt, ...)
295 {
296 va_list args;
297 va_start(args, fmt);
298 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, args);
299 va_end(args);
300
301 prog->LinkStatus = GL_FALSE;
302 }
303
304 static int swizzle_for_size(int size)
305 {
306 int size_swizzles[4] = {
307 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
308 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
309 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
310 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
311 };
312
313 return size_swizzles[size - 1];
314 }
315
316 ir_to_mesa_instruction *
317 ir_to_mesa_visitor::ir_to_mesa_emit_op3(ir_instruction *ir,
318 enum prog_opcode op,
319 ir_to_mesa_dst_reg dst,
320 ir_to_mesa_src_reg src0,
321 ir_to_mesa_src_reg src1,
322 ir_to_mesa_src_reg src2)
323 {
324 ir_to_mesa_instruction *inst = new(mem_ctx) ir_to_mesa_instruction();
325 int num_reladdr = 0;
326
327 /* If we have to do relative addressing, we want to load the ARL
328 * reg directly for one of the regs, and preload the other reladdr
329 * sources into temps.
330 */
331 num_reladdr += dst.reladdr != NULL;
332 num_reladdr += src0.reladdr != NULL;
333 num_reladdr += src1.reladdr != NULL;
334 num_reladdr += src2.reladdr != NULL;
335
336 reladdr_to_temp(ir, &src2, &num_reladdr);
337 reladdr_to_temp(ir, &src1, &num_reladdr);
338 reladdr_to_temp(ir, &src0, &num_reladdr);
339
340 if (dst.reladdr) {
341 ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg,
342 *dst.reladdr);
343
344 num_reladdr--;
345 }
346 assert(num_reladdr == 0);
347
348 inst->op = op;
349 inst->dst_reg = dst;
350 inst->src_reg[0] = src0;
351 inst->src_reg[1] = src1;
352 inst->src_reg[2] = src2;
353 inst->ir = ir;
354
355 inst->function = NULL;
356
357 this->instructions.push_tail(inst);
358
359 return inst;
360 }
361
362
363 ir_to_mesa_instruction *
364 ir_to_mesa_visitor::ir_to_mesa_emit_op2(ir_instruction *ir,
365 enum prog_opcode op,
366 ir_to_mesa_dst_reg dst,
367 ir_to_mesa_src_reg src0,
368 ir_to_mesa_src_reg src1)
369 {
370 return ir_to_mesa_emit_op3(ir, op, dst, src0, src1, ir_to_mesa_undef);
371 }
372
373 ir_to_mesa_instruction *
374 ir_to_mesa_visitor::ir_to_mesa_emit_op1(ir_instruction *ir,
375 enum prog_opcode op,
376 ir_to_mesa_dst_reg dst,
377 ir_to_mesa_src_reg src0)
378 {
379 assert(dst.writemask != 0);
380 return ir_to_mesa_emit_op3(ir, op, dst,
381 src0, ir_to_mesa_undef, ir_to_mesa_undef);
382 }
383
384 ir_to_mesa_instruction *
385 ir_to_mesa_visitor::ir_to_mesa_emit_op0(ir_instruction *ir,
386 enum prog_opcode op)
387 {
388 return ir_to_mesa_emit_op3(ir, op, ir_to_mesa_undef_dst,
389 ir_to_mesa_undef,
390 ir_to_mesa_undef,
391 ir_to_mesa_undef);
392 }
393
394 inline ir_to_mesa_dst_reg
395 ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg reg)
396 {
397 ir_to_mesa_dst_reg dst_reg;
398
399 dst_reg.file = reg.file;
400 dst_reg.index = reg.index;
401 dst_reg.writemask = WRITEMASK_XYZW;
402 dst_reg.cond_mask = COND_TR;
403 dst_reg.reladdr = reg.reladdr;
404
405 return dst_reg;
406 }
407
408 inline ir_to_mesa_src_reg
409 ir_to_mesa_src_reg_from_dst(ir_to_mesa_dst_reg reg)
410 {
411 return ir_to_mesa_src_reg(reg.file, reg.index, NULL);
412 }
413
414 /**
415 * Emits Mesa scalar opcodes to produce unique answers across channels.
416 *
417 * Some Mesa opcodes are scalar-only, like ARB_fp/vp. The src X
418 * channel determines the result across all channels. So to do a vec4
419 * of this operation, we want to emit a scalar per source channel used
420 * to produce dest channels.
421 */
422 void
423 ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
424 enum prog_opcode op,
425 ir_to_mesa_dst_reg dst,
426 ir_to_mesa_src_reg orig_src0,
427 ir_to_mesa_src_reg orig_src1)
428 {
429 int i, j;
430 int done_mask = ~dst.writemask;
431
432 /* Mesa RCP is a scalar operation splatting results to all channels,
433 * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
434 * dst channels.
435 */
436 for (i = 0; i < 4; i++) {
437 GLuint this_mask = (1 << i);
438 ir_to_mesa_instruction *inst;
439 ir_to_mesa_src_reg src0 = orig_src0;
440 ir_to_mesa_src_reg src1 = orig_src1;
441
442 if (done_mask & this_mask)
443 continue;
444
445 GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
446 GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
447 for (j = i + 1; j < 4; j++) {
448 if (!(done_mask & (1 << j)) &&
449 GET_SWZ(src0.swizzle, j) == src0_swiz &&
450 GET_SWZ(src1.swizzle, j) == src1_swiz) {
451 this_mask |= (1 << j);
452 }
453 }
454 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
455 src0_swiz, src0_swiz);
456 src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
457 src1_swiz, src1_swiz);
458
459 inst = ir_to_mesa_emit_op2(ir, op,
460 dst,
461 src0,
462 src1);
463 inst->dst_reg.writemask = this_mask;
464 done_mask |= this_mask;
465 }
466 }
467
468 void
469 ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
470 enum prog_opcode op,
471 ir_to_mesa_dst_reg dst,
472 ir_to_mesa_src_reg src0)
473 {
474 ir_to_mesa_src_reg undef = ir_to_mesa_undef;
475
476 undef.swizzle = SWIZZLE_XXXX;
477
478 ir_to_mesa_emit_scalar_op2(ir, op, dst, src0, undef);
479 }
480
481 struct ir_to_mesa_src_reg
482 ir_to_mesa_visitor::src_reg_for_float(float val)
483 {
484 ir_to_mesa_src_reg src_reg(PROGRAM_CONSTANT, -1, NULL);
485
486 src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
487 &val, 1, &src_reg.swizzle);
488
489 return src_reg;
490 }
491
492 static int
493 type_size(const struct glsl_type *type)
494 {
495 unsigned int i;
496 int size;
497
498 switch (type->base_type) {
499 case GLSL_TYPE_UINT:
500 case GLSL_TYPE_INT:
501 case GLSL_TYPE_FLOAT:
502 case GLSL_TYPE_BOOL:
503 if (type->is_matrix()) {
504 return type->matrix_columns;
505 } else {
506 /* Regardless of size of vector, it gets a vec4. This is bad
507 * packing for things like floats, but otherwise arrays become a
508 * mess. Hopefully a later pass over the code can pack scalars
509 * down if appropriate.
510 */
511 return 1;
512 }
513 case GLSL_TYPE_ARRAY:
514 return type_size(type->fields.array) * type->length;
515 case GLSL_TYPE_STRUCT:
516 size = 0;
517 for (i = 0; i < type->length; i++) {
518 size += type_size(type->fields.structure[i].type);
519 }
520 return size;
521 case GLSL_TYPE_SAMPLER:
522 /* Samplers take up one slot in UNIFORMS[], but they're baked in
523 * at link time.
524 */
525 return 1;
526 default:
527 assert(0);
528 return 0;
529 }
530 }
531
532 /**
533 * In the initial pass of codegen, we assign temporary numbers to
534 * intermediate results. (not SSA -- variable assignments will reuse
535 * storage). Actual register allocation for the Mesa VM occurs in a
536 * pass over the Mesa IR later.
537 */
538 ir_to_mesa_src_reg
539 ir_to_mesa_visitor::get_temp(const glsl_type *type)
540 {
541 ir_to_mesa_src_reg src_reg;
542 int swizzle[4];
543 int i;
544
545 src_reg.file = PROGRAM_TEMPORARY;
546 src_reg.index = next_temp;
547 src_reg.reladdr = NULL;
548 next_temp += type_size(type);
549
550 if (type->is_array() || type->is_record()) {
551 src_reg.swizzle = SWIZZLE_NOOP;
552 } else {
553 for (i = 0; i < type->vector_elements; i++)
554 swizzle[i] = i;
555 for (; i < 4; i++)
556 swizzle[i] = type->vector_elements - 1;
557 src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1],
558 swizzle[2], swizzle[3]);
559 }
560 src_reg.negate = 0;
561
562 return src_reg;
563 }
564
565 variable_storage *
566 ir_to_mesa_visitor::find_variable_storage(ir_variable *var)
567 {
568
569 variable_storage *entry;
570
571 foreach_iter(exec_list_iterator, iter, this->variables) {
572 entry = (variable_storage *)iter.get();
573
574 if (entry->var == var)
575 return entry;
576 }
577
578 return NULL;
579 }
580
581 struct statevar_element {
582 const char *field;
583 int tokens[STATE_LENGTH];
584 int swizzle;
585 bool array_indexed;
586 };
587
588 static struct statevar_element gl_DepthRange_elements[] = {
589 {"near", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_XXXX},
590 {"far", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_YYYY},
591 {"diff", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_ZZZZ},
592 };
593
594 static struct statevar_element gl_ClipPlane_elements[] = {
595 {NULL, {STATE_CLIPPLANE, 0, 0}, SWIZZLE_XYZW}
596 };
597
598 static struct statevar_element gl_Point_elements[] = {
599 {"size", {STATE_POINT_SIZE}, SWIZZLE_XXXX},
600 {"sizeMin", {STATE_POINT_SIZE}, SWIZZLE_YYYY},
601 {"sizeMax", {STATE_POINT_SIZE}, SWIZZLE_ZZZZ},
602 {"fadeThresholdSize", {STATE_POINT_SIZE}, SWIZZLE_WWWW},
603 {"distanceConstantAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_XXXX},
604 {"distanceLinearAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_YYYY},
605 {"distanceQuadraticAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_ZZZZ},
606 };
607
608 static struct statevar_element gl_FrontMaterial_elements[] = {
609 {"emission", {STATE_MATERIAL, 0, STATE_EMISSION}, SWIZZLE_XYZW},
610 {"ambient", {STATE_MATERIAL, 0, STATE_AMBIENT}, SWIZZLE_XYZW},
611 {"diffuse", {STATE_MATERIAL, 0, STATE_DIFFUSE}, SWIZZLE_XYZW},
612 {"specular", {STATE_MATERIAL, 0, STATE_SPECULAR}, SWIZZLE_XYZW},
613 {"shininess", {STATE_MATERIAL, 0, STATE_SHININESS}, SWIZZLE_XXXX},
614 };
615
616 static struct statevar_element gl_BackMaterial_elements[] = {
617 {"emission", {STATE_MATERIAL, 1, STATE_EMISSION}, SWIZZLE_XYZW},
618 {"ambient", {STATE_MATERIAL, 1, STATE_AMBIENT}, SWIZZLE_XYZW},
619 {"diffuse", {STATE_MATERIAL, 1, STATE_DIFFUSE}, SWIZZLE_XYZW},
620 {"specular", {STATE_MATERIAL, 1, STATE_SPECULAR}, SWIZZLE_XYZW},
621 {"shininess", {STATE_MATERIAL, 1, STATE_SHININESS}, SWIZZLE_XXXX},
622 };
623
624 static struct statevar_element gl_LightSource_elements[] = {
625 {"ambient", {STATE_LIGHT, 0, STATE_AMBIENT}, SWIZZLE_XYZW},
626 {"diffuse", {STATE_LIGHT, 0, STATE_DIFFUSE}, SWIZZLE_XYZW},
627 {"specular", {STATE_LIGHT, 0, STATE_SPECULAR}, SWIZZLE_XYZW},
628 {"position", {STATE_LIGHT, 0, STATE_POSITION}, SWIZZLE_XYZW},
629 {"halfVector", {STATE_LIGHT, 0, STATE_HALF_VECTOR}, SWIZZLE_XYZW},
630 {"spotDirection", {STATE_LIGHT, 0, STATE_SPOT_DIRECTION}, SWIZZLE_XYZW},
631 {"spotCosCutoff", {STATE_LIGHT, 0, STATE_SPOT_DIRECTION}, SWIZZLE_WWWW},
632 {"spotCutoff", {STATE_LIGHT, 0, STATE_SPOT_CUTOFF}, SWIZZLE_XXXX},
633 {"spotExponent", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_WWWW},
634 {"constantAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_XXXX},
635 {"linearAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_YYYY},
636 {"quadraticAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_ZZZZ},
637 };
638
639 static struct statevar_element gl_LightModel_elements[] = {
640 {"ambient", {STATE_LIGHTMODEL_AMBIENT, 0}, SWIZZLE_XYZW},
641 };
642
643 static struct statevar_element gl_FrontLightModelProduct_elements[] = {
644 {"sceneColor", {STATE_LIGHTMODEL_SCENECOLOR, 0}, SWIZZLE_XYZW},
645 };
646
647 static struct statevar_element gl_BackLightModelProduct_elements[] = {
648 {"sceneColor", {STATE_LIGHTMODEL_SCENECOLOR, 1}, SWIZZLE_XYZW},
649 };
650
651 static struct statevar_element gl_FrontLightProduct_elements[] = {
652 {"ambient", {STATE_LIGHTPROD, 0, 0, STATE_AMBIENT}, SWIZZLE_XYZW},
653 {"diffuse", {STATE_LIGHTPROD, 0, 0, STATE_DIFFUSE}, SWIZZLE_XYZW},
654 {"specular", {STATE_LIGHTPROD, 0, 0, STATE_SPECULAR}, SWIZZLE_XYZW},
655 };
656
657 static struct statevar_element gl_BackLightProduct_elements[] = {
658 {"ambient", {STATE_LIGHTPROD, 0, 1, STATE_AMBIENT}, SWIZZLE_XYZW},
659 {"diffuse", {STATE_LIGHTPROD, 0, 1, STATE_DIFFUSE}, SWIZZLE_XYZW},
660 {"specular", {STATE_LIGHTPROD, 0, 1, STATE_SPECULAR}, SWIZZLE_XYZW},
661 };
662
663 static struct statevar_element gl_TextureEnvColor_elements[] = {
664 {NULL, {STATE_TEXENV_COLOR, 0}, SWIZZLE_XYZW},
665 };
666
667 static struct statevar_element gl_EyePlaneS_elements[] = {
668 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_S}, SWIZZLE_XYZW},
669 };
670
671 static struct statevar_element gl_EyePlaneT_elements[] = {
672 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_T}, SWIZZLE_XYZW},
673 };
674
675 static struct statevar_element gl_EyePlaneR_elements[] = {
676 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_R}, SWIZZLE_XYZW},
677 };
678
679 static struct statevar_element gl_EyePlaneQ_elements[] = {
680 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_Q}, SWIZZLE_XYZW},
681 };
682
683 static struct statevar_element gl_ObjectPlaneS_elements[] = {
684 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_S}, SWIZZLE_XYZW},
685 };
686
687 static struct statevar_element gl_ObjectPlaneT_elements[] = {
688 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_T}, SWIZZLE_XYZW},
689 };
690
691 static struct statevar_element gl_ObjectPlaneR_elements[] = {
692 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_R}, SWIZZLE_XYZW},
693 };
694
695 static struct statevar_element gl_ObjectPlaneQ_elements[] = {
696 {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_Q}, SWIZZLE_XYZW},
697 };
698
699 static struct statevar_element gl_Fog_elements[] = {
700 {"color", {STATE_FOG_COLOR}, SWIZZLE_XYZW},
701 {"density", {STATE_FOG_PARAMS}, SWIZZLE_XXXX},
702 {"start", {STATE_FOG_PARAMS}, SWIZZLE_YYYY},
703 {"end", {STATE_FOG_PARAMS}, SWIZZLE_ZZZZ},
704 {"scale", {STATE_FOG_PARAMS}, SWIZZLE_WWWW},
705 };
706
707 static struct statevar_element gl_NormalScale_elements[] = {
708 {NULL, {STATE_NORMAL_SCALE}, SWIZZLE_XXXX},
709 };
710
711 #define MATRIX(name, statevar, modifier) \
712 static struct statevar_element name ## _elements[] = { \
713 { NULL, { statevar, 0, 0, 0, modifier}, SWIZZLE_XYZW }, \
714 { NULL, { statevar, 0, 1, 1, modifier}, SWIZZLE_XYZW }, \
715 { NULL, { statevar, 0, 2, 2, modifier}, SWIZZLE_XYZW }, \
716 { NULL, { statevar, 0, 3, 3, modifier}, SWIZZLE_XYZW }, \
717 }
718
719 MATRIX(gl_ModelViewMatrix,
720 STATE_MODELVIEW_MATRIX, STATE_MATRIX_TRANSPOSE);
721 MATRIX(gl_ModelViewMatrixInverse,
722 STATE_MODELVIEW_MATRIX, STATE_MATRIX_INVTRANS);
723 MATRIX(gl_ModelViewMatrixTranspose,
724 STATE_MODELVIEW_MATRIX, 0);
725 MATRIX(gl_ModelViewMatrixInverseTranspose,
726 STATE_MODELVIEW_MATRIX, STATE_MATRIX_INVERSE);
727
728 MATRIX(gl_ProjectionMatrix,
729 STATE_PROJECTION_MATRIX, STATE_MATRIX_TRANSPOSE);
730 MATRIX(gl_ProjectionMatrixInverse,
731 STATE_PROJECTION_MATRIX, STATE_MATRIX_INVTRANS);
732 MATRIX(gl_ProjectionMatrixTranspose,
733 STATE_PROJECTION_MATRIX, 0);
734 MATRIX(gl_ProjectionMatrixInverseTranspose,
735 STATE_PROJECTION_MATRIX, STATE_MATRIX_INVERSE);
736
737 MATRIX(gl_ModelViewProjectionMatrix,
738 STATE_MVP_MATRIX, STATE_MATRIX_TRANSPOSE);
739 MATRIX(gl_ModelViewProjectionMatrixInverse,
740 STATE_MVP_MATRIX, STATE_MATRIX_INVTRANS);
741 MATRIX(gl_ModelViewProjectionMatrixTranspose,
742 STATE_MVP_MATRIX, 0);
743 MATRIX(gl_ModelViewProjectionMatrixInverseTranspose,
744 STATE_MVP_MATRIX, STATE_MATRIX_INVERSE);
745
746 MATRIX(gl_TextureMatrix,
747 STATE_TEXTURE_MATRIX, STATE_MATRIX_TRANSPOSE);
748 MATRIX(gl_TextureMatrixInverse,
749 STATE_TEXTURE_MATRIX, STATE_MATRIX_INVTRANS);
750 MATRIX(gl_TextureMatrixTranspose,
751 STATE_TEXTURE_MATRIX, 0);
752 MATRIX(gl_TextureMatrixInverseTranspose,
753 STATE_TEXTURE_MATRIX, STATE_MATRIX_INVERSE);
754
755 static struct statevar_element gl_NormalMatrix_elements[] = {
756 { NULL, { STATE_MODELVIEW_MATRIX, 0, 0, 0, STATE_MATRIX_INVERSE},
757 SWIZZLE_XYZW },
758 { NULL, { STATE_MODELVIEW_MATRIX, 0, 1, 1, STATE_MATRIX_INVERSE},
759 SWIZZLE_XYZW },
760 { NULL, { STATE_MODELVIEW_MATRIX, 0, 2, 2, STATE_MATRIX_INVERSE},
761 SWIZZLE_XYZW },
762 };
763
764 #undef MATRIX
765
766 #define STATEVAR(name) {#name, name ## _elements, Elements(name ## _elements)}
767
768 static const struct statevar {
769 const char *name;
770 struct statevar_element *elements;
771 unsigned int num_elements;
772 } statevars[] = {
773 STATEVAR(gl_DepthRange),
774 STATEVAR(gl_ClipPlane),
775 STATEVAR(gl_Point),
776 STATEVAR(gl_FrontMaterial),
777 STATEVAR(gl_BackMaterial),
778 STATEVAR(gl_LightSource),
779 STATEVAR(gl_LightModel),
780 STATEVAR(gl_FrontLightModelProduct),
781 STATEVAR(gl_BackLightModelProduct),
782 STATEVAR(gl_FrontLightProduct),
783 STATEVAR(gl_BackLightProduct),
784 STATEVAR(gl_TextureEnvColor),
785 STATEVAR(gl_EyePlaneS),
786 STATEVAR(gl_EyePlaneT),
787 STATEVAR(gl_EyePlaneR),
788 STATEVAR(gl_EyePlaneQ),
789 STATEVAR(gl_ObjectPlaneS),
790 STATEVAR(gl_ObjectPlaneT),
791 STATEVAR(gl_ObjectPlaneR),
792 STATEVAR(gl_ObjectPlaneQ),
793 STATEVAR(gl_Fog),
794
795 STATEVAR(gl_ModelViewMatrix),
796 STATEVAR(gl_ModelViewMatrixInverse),
797 STATEVAR(gl_ModelViewMatrixTranspose),
798 STATEVAR(gl_ModelViewMatrixInverseTranspose),
799
800 STATEVAR(gl_ProjectionMatrix),
801 STATEVAR(gl_ProjectionMatrixInverse),
802 STATEVAR(gl_ProjectionMatrixTranspose),
803 STATEVAR(gl_ProjectionMatrixInverseTranspose),
804
805 STATEVAR(gl_ModelViewProjectionMatrix),
806 STATEVAR(gl_ModelViewProjectionMatrixInverse),
807 STATEVAR(gl_ModelViewProjectionMatrixTranspose),
808 STATEVAR(gl_ModelViewProjectionMatrixInverseTranspose),
809
810 STATEVAR(gl_TextureMatrix),
811 STATEVAR(gl_TextureMatrixInverse),
812 STATEVAR(gl_TextureMatrixTranspose),
813 STATEVAR(gl_TextureMatrixInverseTranspose),
814
815 STATEVAR(gl_NormalMatrix),
816 STATEVAR(gl_NormalScale),
817 };
818
819 void
820 ir_to_mesa_visitor::visit(ir_variable *ir)
821 {
822 if (strcmp(ir->name, "gl_FragCoord") == 0) {
823 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
824
825 fp->OriginUpperLeft = ir->origin_upper_left;
826 fp->PixelCenterInteger = ir->pixel_center_integer;
827 }
828
829 if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
830 unsigned int i;
831
832 for (i = 0; i < Elements(statevars); i++) {
833 if (strcmp(ir->name, statevars[i].name) == 0)
834 break;
835 }
836
837 if (i == Elements(statevars)) {
838 fail_link(this->shader_program,
839 "Failed to find builtin uniform `%s'\n", ir->name);
840 return;
841 }
842
843 const struct statevar *statevar = &statevars[i];
844
845 int array_count;
846 if (ir->type->is_array()) {
847 array_count = ir->type->length;
848 } else {
849 array_count = 1;
850 }
851
852 /* Check if this statevar's setup in the STATE file exactly
853 * matches how we'll want to reference it as a
854 * struct/array/whatever. If not, then we need to move it into
855 * temporary storage and hope that it'll get copy-propagated
856 * out.
857 */
858 for (i = 0; i < statevar->num_elements; i++) {
859 if (statevar->elements[i].swizzle != SWIZZLE_XYZW) {
860 break;
861 }
862 }
863
864 struct variable_storage *storage;
865 ir_to_mesa_dst_reg dst;
866 if (i == statevar->num_elements) {
867 /* We'll set the index later. */
868 storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
869 this->variables.push_tail(storage);
870
871 dst = ir_to_mesa_undef_dst;
872 } else {
873 storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
874 this->next_temp);
875 this->variables.push_tail(storage);
876 this->next_temp += type_size(ir->type);
877
878 dst = ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg(PROGRAM_TEMPORARY,
879 storage->index,
880 NULL));
881 }
882
883
884 for (int a = 0; a < array_count; a++) {
885 for (unsigned int i = 0; i < statevar->num_elements; i++) {
886 struct statevar_element *element = &statevar->elements[i];
887 int tokens[STATE_LENGTH];
888
889 memcpy(tokens, element->tokens, sizeof(element->tokens));
890 if (ir->type->is_array()) {
891 tokens[1] = a;
892 }
893
894 int index = _mesa_add_state_reference(this->prog->Parameters,
895 (gl_state_index *)tokens);
896
897 if (storage->file == PROGRAM_STATE_VAR) {
898 if (storage->index == -1) {
899 storage->index = index;
900 } else {
901 assert(index ==
902 (int)(storage->index + a * statevar->num_elements + i));
903 }
904 } else {
905 ir_to_mesa_src_reg src(PROGRAM_STATE_VAR, index, NULL);
906 src.swizzle = element->swizzle;
907 ir_to_mesa_emit_op1(ir, OPCODE_MOV, dst, src);
908 /* even a float takes up a whole vec4 reg in a struct/array. */
909 dst.index++;
910 }
911 }
912 }
913 if (storage->file == PROGRAM_TEMPORARY &&
914 dst.index != storage->index + type_size(ir->type)) {
915 fail_link(this->shader_program,
916 "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
917 ir->name, dst.index - storage->index,
918 type_size(ir->type));
919 }
920 }
921 }
922
923 void
924 ir_to_mesa_visitor::visit(ir_loop *ir)
925 {
926 ir_dereference_variable *counter = NULL;
927
928 if (ir->counter != NULL)
929 counter = new(ir) ir_dereference_variable(ir->counter);
930
931 if (ir->from != NULL) {
932 assert(ir->counter != NULL);
933
934 ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
935
936 a->accept(this);
937 delete a;
938 }
939
940 ir_to_mesa_emit_op0(NULL, OPCODE_BGNLOOP);
941
942 if (ir->to) {
943 ir_expression *e =
944 new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
945 counter, ir->to);
946 ir_if *if_stmt = new(ir) ir_if(e);
947
948 ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
949
950 if_stmt->then_instructions.push_tail(brk);
951
952 if_stmt->accept(this);
953
954 delete if_stmt;
955 delete e;
956 delete brk;
957 }
958
959 visit_exec_list(&ir->body_instructions, this);
960
961 if (ir->increment) {
962 ir_expression *e =
963 new(ir) ir_expression(ir_binop_add, counter->type,
964 counter, ir->increment);
965
966 ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
967
968 a->accept(this);
969 delete a;
970 delete e;
971 }
972
973 ir_to_mesa_emit_op0(NULL, OPCODE_ENDLOOP);
974 }
975
976 void
977 ir_to_mesa_visitor::visit(ir_loop_jump *ir)
978 {
979 switch (ir->mode) {
980 case ir_loop_jump::jump_break:
981 ir_to_mesa_emit_op0(NULL, OPCODE_BRK);
982 break;
983 case ir_loop_jump::jump_continue:
984 ir_to_mesa_emit_op0(NULL, OPCODE_CONT);
985 break;
986 }
987 }
988
989
990 void
991 ir_to_mesa_visitor::visit(ir_function_signature *ir)
992 {
993 assert(0);
994 (void)ir;
995 }
996
997 void
998 ir_to_mesa_visitor::visit(ir_function *ir)
999 {
1000 /* Ignore function bodies other than main() -- we shouldn't see calls to
1001 * them since they should all be inlined before we get to ir_to_mesa.
1002 */
1003 if (strcmp(ir->name, "main") == 0) {
1004 const ir_function_signature *sig;
1005 exec_list empty;
1006
1007 sig = ir->matching_signature(&empty);
1008
1009 assert(sig);
1010
1011 foreach_iter(exec_list_iterator, iter, sig->body) {
1012 ir_instruction *ir = (ir_instruction *)iter.get();
1013
1014 ir->accept(this);
1015 }
1016 }
1017 }
1018
1019 GLboolean
1020 ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
1021 {
1022 int nonmul_operand = 1 - mul_operand;
1023 ir_to_mesa_src_reg a, b, c;
1024
1025 ir_expression *expr = ir->operands[mul_operand]->as_expression();
1026 if (!expr || expr->operation != ir_binop_mul)
1027 return false;
1028
1029 expr->operands[0]->accept(this);
1030 a = this->result;
1031 expr->operands[1]->accept(this);
1032 b = this->result;
1033 ir->operands[nonmul_operand]->accept(this);
1034 c = this->result;
1035
1036 this->result = get_temp(ir->type);
1037 ir_to_mesa_emit_op3(ir, OPCODE_MAD,
1038 ir_to_mesa_dst_reg_from_src(this->result), a, b, c);
1039
1040 return true;
1041 }
1042
1043 void
1044 ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
1045 ir_to_mesa_src_reg *reg, int *num_reladdr)
1046 {
1047 if (!reg->reladdr)
1048 return;
1049
1050 ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg, *reg->reladdr);
1051
1052 if (*num_reladdr != 1) {
1053 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
1054
1055 ir_to_mesa_emit_op1(ir, OPCODE_MOV,
1056 ir_to_mesa_dst_reg_from_src(temp), *reg);
1057 *reg = temp;
1058 }
1059
1060 (*num_reladdr)--;
1061 }
1062
1063 void
1064 ir_to_mesa_visitor::visit(ir_expression *ir)
1065 {
1066 unsigned int operand;
1067 struct ir_to_mesa_src_reg op[2];
1068 struct ir_to_mesa_src_reg result_src;
1069 struct ir_to_mesa_dst_reg result_dst;
1070 const glsl_type *vec4_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 4, 1);
1071 const glsl_type *vec3_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 3, 1);
1072 const glsl_type *vec2_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 2, 1);
1073
1074 /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
1075 */
1076 if (ir->operation == ir_binop_add) {
1077 if (try_emit_mad(ir, 1))
1078 return;
1079 if (try_emit_mad(ir, 0))
1080 return;
1081 }
1082
1083 for (operand = 0; operand < ir->get_num_operands(); operand++) {
1084 this->result.file = PROGRAM_UNDEFINED;
1085 ir->operands[operand]->accept(this);
1086 if (this->result.file == PROGRAM_UNDEFINED) {
1087 ir_print_visitor v;
1088 printf("Failed to get tree for expression operand:\n");
1089 ir->operands[operand]->accept(&v);
1090 exit(1);
1091 }
1092 op[operand] = this->result;
1093
1094 /* Matrix expression operands should have been broken down to vector
1095 * operations already.
1096 */
1097 assert(!ir->operands[operand]->type->is_matrix());
1098 }
1099
1100 this->result.file = PROGRAM_UNDEFINED;
1101
1102 /* Storage for our result. Ideally for an assignment we'd be using
1103 * the actual storage for the result here, instead.
1104 */
1105 result_src = get_temp(ir->type);
1106 /* convenience for the emit functions below. */
1107 result_dst = ir_to_mesa_dst_reg_from_src(result_src);
1108 /* Limit writes to the channels that will be used by result_src later.
1109 * This does limit this temp's use as a temporary for multi-instruction
1110 * sequences.
1111 */
1112 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1113
1114 switch (ir->operation) {
1115 case ir_unop_logic_not:
1116 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst,
1117 op[0], src_reg_for_float(0.0));
1118 break;
1119 case ir_unop_neg:
1120 op[0].negate = ~op[0].negate;
1121 result_src = op[0];
1122 break;
1123 case ir_unop_abs:
1124 ir_to_mesa_emit_op1(ir, OPCODE_ABS, result_dst, op[0]);
1125 break;
1126 case ir_unop_sign:
1127 ir_to_mesa_emit_op1(ir, OPCODE_SSG, result_dst, op[0]);
1128 break;
1129 case ir_unop_rcp:
1130 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RCP, result_dst, op[0]);
1131 break;
1132
1133 case ir_unop_exp2:
1134 ir_to_mesa_emit_scalar_op1(ir, OPCODE_EX2, result_dst, op[0]);
1135 break;
1136 case ir_unop_exp:
1137 case ir_unop_log:
1138 assert(!"not reached: should be handled by ir_explog_to_explog2");
1139 break;
1140 case ir_unop_log2:
1141 ir_to_mesa_emit_scalar_op1(ir, OPCODE_LG2, result_dst, op[0]);
1142 break;
1143 case ir_unop_sin:
1144 ir_to_mesa_emit_scalar_op1(ir, OPCODE_SIN, result_dst, op[0]);
1145 break;
1146 case ir_unop_cos:
1147 ir_to_mesa_emit_scalar_op1(ir, OPCODE_COS, result_dst, op[0]);
1148 break;
1149
1150 case ir_unop_dFdx:
1151 ir_to_mesa_emit_op1(ir, OPCODE_DDX, result_dst, op[0]);
1152 break;
1153 case ir_unop_dFdy:
1154 ir_to_mesa_emit_op1(ir, OPCODE_DDY, result_dst, op[0]);
1155 break;
1156
1157 case ir_unop_noise: {
1158 const enum prog_opcode opcode =
1159 prog_opcode(OPCODE_NOISE1
1160 + (ir->operands[0]->type->vector_elements) - 1);
1161 assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
1162
1163 ir_to_mesa_emit_op1(ir, opcode, result_dst, op[0]);
1164 break;
1165 }
1166
1167 case ir_binop_add:
1168 ir_to_mesa_emit_op2(ir, OPCODE_ADD, result_dst, op[0], op[1]);
1169 break;
1170 case ir_binop_sub:
1171 ir_to_mesa_emit_op2(ir, OPCODE_SUB, result_dst, op[0], op[1]);
1172 break;
1173
1174 case ir_binop_mul:
1175 ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, op[0], op[1]);
1176 break;
1177 case ir_binop_div:
1178 assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1179 case ir_binop_mod:
1180 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1181 break;
1182
1183 case ir_binop_less:
1184 ir_to_mesa_emit_op2(ir, OPCODE_SLT, result_dst, op[0], op[1]);
1185 break;
1186 case ir_binop_greater:
1187 ir_to_mesa_emit_op2(ir, OPCODE_SGT, result_dst, op[0], op[1]);
1188 break;
1189 case ir_binop_lequal:
1190 ir_to_mesa_emit_op2(ir, OPCODE_SLE, result_dst, op[0], op[1]);
1191 break;
1192 case ir_binop_gequal:
1193 ir_to_mesa_emit_op2(ir, OPCODE_SGE, result_dst, op[0], op[1]);
1194 break;
1195 case ir_binop_equal:
1196 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1197 break;
1198 case ir_binop_nequal:
1199 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1200 break;
1201 case ir_binop_all_equal:
1202 /* "==" operator producing a scalar boolean. */
1203 if (ir->operands[0]->type->is_vector() ||
1204 ir->operands[1]->type->is_vector()) {
1205 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
1206 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1207 ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
1208 ir_to_mesa_emit_op2(ir, OPCODE_DP4, result_dst, temp, temp);
1209 ir_to_mesa_emit_op2(ir, OPCODE_SEQ,
1210 result_dst, result_src, src_reg_for_float(0.0));
1211 } else {
1212 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1213 }
1214 break;
1215 case ir_binop_any_nequal:
1216 /* "!=" operator producing a scalar boolean. */
1217 if (ir->operands[0]->type->is_vector() ||
1218 ir->operands[1]->type->is_vector()) {
1219 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
1220 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1221 ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
1222 ir_to_mesa_emit_op2(ir, OPCODE_DP4, result_dst, temp, temp);
1223 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1224 result_dst, result_src, src_reg_for_float(0.0));
1225 } else {
1226 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1227 }
1228 break;
1229
1230 case ir_unop_any:
1231 switch (ir->operands[0]->type->vector_elements) {
1232 case 4:
1233 ir_to_mesa_emit_op2(ir, OPCODE_DP4, result_dst, op[0], op[0]);
1234 break;
1235 case 3:
1236 ir_to_mesa_emit_op2(ir, OPCODE_DP3, result_dst, op[0], op[0]);
1237 break;
1238 case 2:
1239 ir_to_mesa_emit_op2(ir, OPCODE_DP2, result_dst, op[0], op[0]);
1240 break;
1241 default:
1242 assert(!"unreached: ir_unop_any of non-bvec");
1243 break;
1244 }
1245 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1246 result_dst, result_src, src_reg_for_float(0.0));
1247 break;
1248
1249 case ir_binop_logic_xor:
1250 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1251 break;
1252
1253 case ir_binop_logic_or:
1254 /* This could be a saturated add and skip the SNE. */
1255 ir_to_mesa_emit_op2(ir, OPCODE_ADD,
1256 result_dst,
1257 op[0], op[1]);
1258
1259 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1260 result_dst,
1261 result_src, src_reg_for_float(0.0));
1262 break;
1263
1264 case ir_binop_logic_and:
1265 /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
1266 ir_to_mesa_emit_op2(ir, OPCODE_MUL,
1267 result_dst,
1268 op[0], op[1]);
1269 break;
1270
1271 case ir_binop_dot:
1272 if (ir->operands[0]->type == vec4_type) {
1273 assert(ir->operands[1]->type == vec4_type);
1274 ir_to_mesa_emit_op2(ir, OPCODE_DP4,
1275 result_dst,
1276 op[0], op[1]);
1277 } else if (ir->operands[0]->type == vec3_type) {
1278 assert(ir->operands[1]->type == vec3_type);
1279 ir_to_mesa_emit_op2(ir, OPCODE_DP3,
1280 result_dst,
1281 op[0], op[1]);
1282 } else if (ir->operands[0]->type == vec2_type) {
1283 assert(ir->operands[1]->type == vec2_type);
1284 ir_to_mesa_emit_op2(ir, OPCODE_DP2,
1285 result_dst,
1286 op[0], op[1]);
1287 }
1288 break;
1289
1290 case ir_binop_cross:
1291 ir_to_mesa_emit_op2(ir, OPCODE_XPD, result_dst, op[0], op[1]);
1292 break;
1293
1294 case ir_unop_sqrt:
1295 /* sqrt(x) = x * rsq(x). */
1296 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
1297 ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, result_src, op[0]);
1298 /* For incoming channels <= 0, set the result to 0. */
1299 op[0].negate = ~op[0].negate;
1300 ir_to_mesa_emit_op3(ir, OPCODE_CMP, result_dst,
1301 op[0], result_src, src_reg_for_float(0.0));
1302 break;
1303 case ir_unop_rsq:
1304 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
1305 break;
1306 case ir_unop_i2f:
1307 case ir_unop_b2f:
1308 case ir_unop_b2i:
1309 /* Mesa IR lacks types, ints are stored as truncated floats. */
1310 result_src = op[0];
1311 break;
1312 case ir_unop_f2i:
1313 ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
1314 break;
1315 case ir_unop_f2b:
1316 case ir_unop_i2b:
1317 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst,
1318 op[0], src_reg_for_float(0.0));
1319 break;
1320 case ir_unop_trunc:
1321 ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
1322 break;
1323 case ir_unop_ceil:
1324 op[0].negate = ~op[0].negate;
1325 ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
1326 result_src.negate = ~result_src.negate;
1327 break;
1328 case ir_unop_floor:
1329 ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
1330 break;
1331 case ir_unop_fract:
1332 ir_to_mesa_emit_op1(ir, OPCODE_FRC, result_dst, op[0]);
1333 break;
1334
1335 case ir_binop_min:
1336 ir_to_mesa_emit_op2(ir, OPCODE_MIN, result_dst, op[0], op[1]);
1337 break;
1338 case ir_binop_max:
1339 ir_to_mesa_emit_op2(ir, OPCODE_MAX, result_dst, op[0], op[1]);
1340 break;
1341 case ir_binop_pow:
1342 ir_to_mesa_emit_scalar_op2(ir, OPCODE_POW, result_dst, op[0], op[1]);
1343 break;
1344
1345 case ir_unop_bit_not:
1346 case ir_unop_u2f:
1347 case ir_binop_lshift:
1348 case ir_binop_rshift:
1349 case ir_binop_bit_and:
1350 case ir_binop_bit_xor:
1351 case ir_binop_bit_or:
1352 assert(!"GLSL 1.30 features unsupported");
1353 break;
1354 }
1355
1356 this->result = result_src;
1357 }
1358
1359
1360 void
1361 ir_to_mesa_visitor::visit(ir_swizzle *ir)
1362 {
1363 ir_to_mesa_src_reg src_reg;
1364 int i;
1365 int swizzle[4];
1366
1367 /* Note that this is only swizzles in expressions, not those on the left
1368 * hand side of an assignment, which do write masking. See ir_assignment
1369 * for that.
1370 */
1371
1372 ir->val->accept(this);
1373 src_reg = this->result;
1374 assert(src_reg.file != PROGRAM_UNDEFINED);
1375
1376 for (i = 0; i < 4; i++) {
1377 if (i < ir->type->vector_elements) {
1378 switch (i) {
1379 case 0:
1380 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.x);
1381 break;
1382 case 1:
1383 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.y);
1384 break;
1385 case 2:
1386 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.z);
1387 break;
1388 case 3:
1389 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.w);
1390 break;
1391 }
1392 } else {
1393 /* If the type is smaller than a vec4, replicate the last
1394 * channel out.
1395 */
1396 swizzle[i] = swizzle[ir->type->vector_elements - 1];
1397 }
1398 }
1399
1400 src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0],
1401 swizzle[1],
1402 swizzle[2],
1403 swizzle[3]);
1404
1405 this->result = src_reg;
1406 }
1407
1408 void
1409 ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
1410 {
1411 variable_storage *entry = find_variable_storage(ir->var);
1412
1413 if (!entry) {
1414 switch (ir->var->mode) {
1415 case ir_var_uniform:
1416 entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_UNIFORM,
1417 ir->var->location);
1418 this->variables.push_tail(entry);
1419 break;
1420 case ir_var_in:
1421 case ir_var_out:
1422 case ir_var_inout:
1423 /* The linker assigns locations for varyings and attributes,
1424 * including deprecated builtins (like gl_Color), user-assign
1425 * generic attributes (glBindVertexLocation), and
1426 * user-defined varyings.
1427 *
1428 * FINISHME: We would hit this path for function arguments. Fix!
1429 */
1430 assert(ir->var->location != -1);
1431 if (ir->var->mode == ir_var_in ||
1432 ir->var->mode == ir_var_inout) {
1433 entry = new(mem_ctx) variable_storage(ir->var,
1434 PROGRAM_INPUT,
1435 ir->var->location);
1436
1437 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
1438 ir->var->location >= VERT_ATTRIB_GENERIC0) {
1439 _mesa_add_attribute(prog->Attributes,
1440 ir->var->name,
1441 _mesa_sizeof_glsl_type(ir->var->type->gl_type),
1442 ir->var->type->gl_type,
1443 ir->var->location - VERT_ATTRIB_GENERIC0);
1444 }
1445 } else {
1446 entry = new(mem_ctx) variable_storage(ir->var,
1447 PROGRAM_OUTPUT,
1448 ir->var->location);
1449 }
1450
1451 break;
1452 case ir_var_auto:
1453 case ir_var_temporary:
1454 entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_TEMPORARY,
1455 this->next_temp);
1456 this->variables.push_tail(entry);
1457
1458 next_temp += type_size(ir->var->type);
1459 break;
1460 }
1461
1462 if (!entry) {
1463 printf("Failed to make storage for %s\n", ir->var->name);
1464 exit(1);
1465 }
1466 }
1467
1468 this->result = ir_to_mesa_src_reg(entry->file, entry->index, ir->var->type);
1469 }
1470
1471 void
1472 ir_to_mesa_visitor::visit(ir_dereference_array *ir)
1473 {
1474 ir_constant *index;
1475 ir_to_mesa_src_reg src_reg;
1476 int element_size = type_size(ir->type);
1477
1478 index = ir->array_index->constant_expression_value();
1479
1480 ir->array->accept(this);
1481 src_reg = this->result;
1482
1483 if (index) {
1484 src_reg.index += index->value.i[0] * element_size;
1485 } else {
1486 ir_to_mesa_src_reg array_base = this->result;
1487 /* Variable index array dereference. It eats the "vec4" of the
1488 * base of the array and an index that offsets the Mesa register
1489 * index.
1490 */
1491 ir->array_index->accept(this);
1492
1493 ir_to_mesa_src_reg index_reg;
1494
1495 if (element_size == 1) {
1496 index_reg = this->result;
1497 } else {
1498 index_reg = get_temp(glsl_type::float_type);
1499
1500 ir_to_mesa_emit_op2(ir, OPCODE_MUL,
1501 ir_to_mesa_dst_reg_from_src(index_reg),
1502 this->result, src_reg_for_float(element_size));
1503 }
1504
1505 src_reg.reladdr = talloc(mem_ctx, ir_to_mesa_src_reg);
1506 memcpy(src_reg.reladdr, &index_reg, sizeof(index_reg));
1507 }
1508
1509 /* If the type is smaller than a vec4, replicate the last channel out. */
1510 if (ir->type->is_scalar() || ir->type->is_vector())
1511 src_reg.swizzle = swizzle_for_size(ir->type->vector_elements);
1512 else
1513 src_reg.swizzle = SWIZZLE_NOOP;
1514
1515 this->result = src_reg;
1516 }
1517
1518 void
1519 ir_to_mesa_visitor::visit(ir_dereference_record *ir)
1520 {
1521 unsigned int i;
1522 const glsl_type *struct_type = ir->record->type;
1523 int offset = 0;
1524
1525 ir->record->accept(this);
1526
1527 for (i = 0; i < struct_type->length; i++) {
1528 if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
1529 break;
1530 offset += type_size(struct_type->fields.structure[i].type);
1531 }
1532 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
1533 this->result.index += offset;
1534 }
1535
1536 /**
1537 * We want to be careful in assignment setup to hit the actual storage
1538 * instead of potentially using a temporary like we might with the
1539 * ir_dereference handler.
1540 */
1541 static struct ir_to_mesa_dst_reg
1542 get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
1543 {
1544 /* The LHS must be a dereference. If the LHS is a variable indexed array
1545 * access of a vector, it must be separated into a series conditional moves
1546 * before reaching this point (see ir_vec_index_to_cond_assign).
1547 */
1548 assert(ir->as_dereference());
1549 ir_dereference_array *deref_array = ir->as_dereference_array();
1550 if (deref_array) {
1551 assert(!deref_array->array->type->is_vector());
1552 }
1553
1554 /* Use the rvalue deref handler for the most part. We'll ignore
1555 * swizzles in it and write swizzles using writemask, though.
1556 */
1557 ir->accept(v);
1558 return ir_to_mesa_dst_reg_from_src(v->result);
1559 }
1560
1561 void
1562 ir_to_mesa_visitor::visit(ir_assignment *ir)
1563 {
1564 struct ir_to_mesa_dst_reg l;
1565 struct ir_to_mesa_src_reg r;
1566 int i;
1567
1568 ir->rhs->accept(this);
1569 r = this->result;
1570
1571 l = get_assignment_lhs(ir->lhs, this);
1572
1573 /* FINISHME: This should really set to the correct maximal writemask for each
1574 * FINISHME: component written (in the loops below). This case can only
1575 * FINISHME: occur for matrices, arrays, and structures.
1576 */
1577 if (ir->write_mask == 0) {
1578 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
1579 l.writemask = WRITEMASK_XYZW;
1580 } else if (ir->lhs->type->is_scalar()) {
1581 /* FINISHME: This hack makes writing to gl_FragData, which lives in the
1582 * FINISHME: W component of fragment shader output zero, work correctly.
1583 */
1584 l.writemask = WRITEMASK_XYZW;
1585 } else {
1586 assert(ir->lhs->type->is_vector());
1587 l.writemask = ir->write_mask;
1588 }
1589
1590 assert(l.file != PROGRAM_UNDEFINED);
1591 assert(r.file != PROGRAM_UNDEFINED);
1592
1593 if (ir->condition) {
1594 ir_to_mesa_src_reg condition;
1595
1596 ir->condition->accept(this);
1597 condition = this->result;
1598
1599 /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves,
1600 * and the condition we produced is 0.0 or 1.0. By flipping the
1601 * sign, we can choose which value OPCODE_CMP produces without
1602 * an extra computing the condition.
1603 */
1604 condition.negate = ~condition.negate;
1605 for (i = 0; i < type_size(ir->lhs->type); i++) {
1606 ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
1607 condition, r, ir_to_mesa_src_reg_from_dst(l));
1608 l.index++;
1609 r.index++;
1610 }
1611 } else {
1612 for (i = 0; i < type_size(ir->lhs->type); i++) {
1613 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
1614 l.index++;
1615 r.index++;
1616 }
1617 }
1618 }
1619
1620
1621 void
1622 ir_to_mesa_visitor::visit(ir_constant *ir)
1623 {
1624 ir_to_mesa_src_reg src_reg;
1625 GLfloat stack_vals[4] = { 0 };
1626 GLfloat *values = stack_vals;
1627 unsigned int i;
1628
1629 /* Unfortunately, 4 floats is all we can get into
1630 * _mesa_add_unnamed_constant. So, make a temp to store an
1631 * aggregate constant and move each constant value into it. If we
1632 * get lucky, copy propagation will eliminate the extra moves.
1633 */
1634
1635 if (ir->type->base_type == GLSL_TYPE_STRUCT) {
1636 ir_to_mesa_src_reg temp_base = get_temp(ir->type);
1637 ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
1638
1639 foreach_iter(exec_list_iterator, iter, ir->components) {
1640 ir_constant *field_value = (ir_constant *)iter.get();
1641 int size = type_size(field_value->type);
1642
1643 assert(size > 0);
1644
1645 field_value->accept(this);
1646 src_reg = this->result;
1647
1648 for (i = 0; i < (unsigned int)size; i++) {
1649 ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
1650
1651 src_reg.index++;
1652 temp.index++;
1653 }
1654 }
1655 this->result = temp_base;
1656 return;
1657 }
1658
1659 if (ir->type->is_array()) {
1660 ir_to_mesa_src_reg temp_base = get_temp(ir->type);
1661 ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
1662 int size = type_size(ir->type->fields.array);
1663
1664 assert(size > 0);
1665
1666 for (i = 0; i < ir->type->length; i++) {
1667 ir->array_elements[i]->accept(this);
1668 src_reg = this->result;
1669 for (int j = 0; j < size; j++) {
1670 ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
1671
1672 src_reg.index++;
1673 temp.index++;
1674 }
1675 }
1676 this->result = temp_base;
1677 return;
1678 }
1679
1680 if (ir->type->is_matrix()) {
1681 ir_to_mesa_src_reg mat = get_temp(ir->type);
1682 ir_to_mesa_dst_reg mat_column = ir_to_mesa_dst_reg_from_src(mat);
1683
1684 for (i = 0; i < ir->type->matrix_columns; i++) {
1685 assert(ir->type->base_type == GLSL_TYPE_FLOAT);
1686 values = &ir->value.f[i * ir->type->vector_elements];
1687
1688 src_reg = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, NULL);
1689 src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1690 values,
1691 ir->type->vector_elements,
1692 &src_reg.swizzle);
1693 ir_to_mesa_emit_op1(ir, OPCODE_MOV, mat_column, src_reg);
1694
1695 mat_column.index++;
1696 }
1697
1698 this->result = mat;
1699 return;
1700 }
1701
1702 src_reg.file = PROGRAM_CONSTANT;
1703 switch (ir->type->base_type) {
1704 case GLSL_TYPE_FLOAT:
1705 values = &ir->value.f[0];
1706 break;
1707 case GLSL_TYPE_UINT:
1708 for (i = 0; i < ir->type->vector_elements; i++) {
1709 values[i] = ir->value.u[i];
1710 }
1711 break;
1712 case GLSL_TYPE_INT:
1713 for (i = 0; i < ir->type->vector_elements; i++) {
1714 values[i] = ir->value.i[i];
1715 }
1716 break;
1717 case GLSL_TYPE_BOOL:
1718 for (i = 0; i < ir->type->vector_elements; i++) {
1719 values[i] = ir->value.b[i];
1720 }
1721 break;
1722 default:
1723 assert(!"Non-float/uint/int/bool constant");
1724 }
1725
1726 this->result = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, ir->type);
1727 this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1728 values,
1729 ir->type->vector_elements,
1730 &this->result.swizzle);
1731 }
1732
1733 function_entry *
1734 ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
1735 {
1736 function_entry *entry;
1737
1738 foreach_iter(exec_list_iterator, iter, this->function_signatures) {
1739 entry = (function_entry *)iter.get();
1740
1741 if (entry->sig == sig)
1742 return entry;
1743 }
1744
1745 entry = talloc(mem_ctx, function_entry);
1746 entry->sig = sig;
1747 entry->sig_id = this->next_signature_id++;
1748 entry->bgn_inst = NULL;
1749
1750 /* Allocate storage for all the parameters. */
1751 foreach_iter(exec_list_iterator, iter, sig->parameters) {
1752 ir_variable *param = (ir_variable *)iter.get();
1753 variable_storage *storage;
1754
1755 storage = find_variable_storage(param);
1756 assert(!storage);
1757
1758 storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
1759 this->next_temp);
1760 this->variables.push_tail(storage);
1761
1762 this->next_temp += type_size(param->type);
1763 }
1764
1765 if (!sig->return_type->is_void()) {
1766 entry->return_reg = get_temp(sig->return_type);
1767 } else {
1768 entry->return_reg = ir_to_mesa_undef;
1769 }
1770
1771 this->function_signatures.push_tail(entry);
1772 return entry;
1773 }
1774
1775 void
1776 ir_to_mesa_visitor::visit(ir_call *ir)
1777 {
1778 ir_to_mesa_instruction *call_inst;
1779 ir_function_signature *sig = ir->get_callee();
1780 function_entry *entry = get_function_signature(sig);
1781 int i;
1782
1783 /* Process in parameters. */
1784 exec_list_iterator sig_iter = sig->parameters.iterator();
1785 foreach_iter(exec_list_iterator, iter, *ir) {
1786 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1787 ir_variable *param = (ir_variable *)sig_iter.get();
1788
1789 if (param->mode == ir_var_in ||
1790 param->mode == ir_var_inout) {
1791 variable_storage *storage = find_variable_storage(param);
1792 assert(storage);
1793
1794 param_rval->accept(this);
1795 ir_to_mesa_src_reg r = this->result;
1796
1797 ir_to_mesa_dst_reg l;
1798 l.file = storage->file;
1799 l.index = storage->index;
1800 l.reladdr = NULL;
1801 l.writemask = WRITEMASK_XYZW;
1802 l.cond_mask = COND_TR;
1803
1804 for (i = 0; i < type_size(param->type); i++) {
1805 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
1806 l.index++;
1807 r.index++;
1808 }
1809 }
1810
1811 sig_iter.next();
1812 }
1813 assert(!sig_iter.has_next());
1814
1815 /* Emit call instruction */
1816 call_inst = ir_to_mesa_emit_op1(ir, OPCODE_CAL,
1817 ir_to_mesa_undef_dst, ir_to_mesa_undef);
1818 call_inst->function = entry;
1819
1820 /* Process out parameters. */
1821 sig_iter = sig->parameters.iterator();
1822 foreach_iter(exec_list_iterator, iter, *ir) {
1823 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1824 ir_variable *param = (ir_variable *)sig_iter.get();
1825
1826 if (param->mode == ir_var_out ||
1827 param->mode == ir_var_inout) {
1828 variable_storage *storage = find_variable_storage(param);
1829 assert(storage);
1830
1831 ir_to_mesa_src_reg r;
1832 r.file = storage->file;
1833 r.index = storage->index;
1834 r.reladdr = NULL;
1835 r.swizzle = SWIZZLE_NOOP;
1836 r.negate = 0;
1837
1838 param_rval->accept(this);
1839 ir_to_mesa_dst_reg l = ir_to_mesa_dst_reg_from_src(this->result);
1840
1841 for (i = 0; i < type_size(param->type); i++) {
1842 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
1843 l.index++;
1844 r.index++;
1845 }
1846 }
1847
1848 sig_iter.next();
1849 }
1850 assert(!sig_iter.has_next());
1851
1852 /* Process return value. */
1853 this->result = entry->return_reg;
1854 }
1855
1856 class get_sampler_name : public ir_hierarchical_visitor
1857 {
1858 public:
1859 get_sampler_name(ir_to_mesa_visitor *mesa, ir_dereference *last)
1860 {
1861 this->mem_ctx = mesa->mem_ctx;
1862 this->mesa = mesa;
1863 this->name = NULL;
1864 this->offset = 0;
1865 this->last = last;
1866 }
1867
1868 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1869 {
1870 this->name = ir->var->name;
1871 return visit_continue;
1872 }
1873
1874 virtual ir_visitor_status visit_leave(ir_dereference_record *ir)
1875 {
1876 this->name = talloc_asprintf(mem_ctx, "%s.%s", name, ir->field);
1877 return visit_continue;
1878 }
1879
1880 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
1881 {
1882 ir_constant *index = ir->array_index->as_constant();
1883 int i;
1884
1885 if (index) {
1886 i = index->value.i[0];
1887 } else {
1888 /* GLSL 1.10 and 1.20 allowed variable sampler array indices,
1889 * while GLSL 1.30 requires that the array indices be
1890 * constant integer expressions. We don't expect any driver
1891 * to actually work with a really variable array index, so
1892 * all that would work would be an unrolled loop counter that ends
1893 * up being constant above.
1894 */
1895 mesa->shader_program->InfoLog =
1896 talloc_asprintf_append(mesa->shader_program->InfoLog,
1897 "warning: Variable sampler array index "
1898 "unsupported.\nThis feature of the language "
1899 "was removed in GLSL 1.20 and is unlikely "
1900 "to be supported for 1.10 in Mesa.\n");
1901 i = 0;
1902 }
1903 if (ir != last) {
1904 this->name = talloc_asprintf(mem_ctx, "%s[%d]", name, i);
1905 } else {
1906 offset = i;
1907 }
1908 return visit_continue;
1909 }
1910
1911 ir_to_mesa_visitor *mesa;
1912 const char *name;
1913 void *mem_ctx;
1914 int offset;
1915 ir_dereference *last;
1916 };
1917
1918 int
1919 ir_to_mesa_visitor::get_sampler_uniform_value(ir_dereference *sampler)
1920 {
1921 get_sampler_name getname(this, sampler);
1922
1923 sampler->accept(&getname);
1924
1925 GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
1926 getname.name);
1927
1928 if (index < 0) {
1929 fail_link(this->shader_program,
1930 "failed to find sampler named %s.\n", getname.name);
1931 return 0;
1932 }
1933
1934 index += getname.offset;
1935
1936 return this->prog->Parameters->ParameterValues[index][0];
1937 }
1938
1939 void
1940 ir_to_mesa_visitor::visit(ir_texture *ir)
1941 {
1942 ir_to_mesa_src_reg result_src, coord, lod_info, projector;
1943 ir_to_mesa_dst_reg result_dst, coord_dst;
1944 ir_to_mesa_instruction *inst = NULL;
1945 prog_opcode opcode = OPCODE_NOP;
1946
1947 ir->coordinate->accept(this);
1948
1949 /* Put our coords in a temp. We'll need to modify them for shadow,
1950 * projection, or LOD, so the only case we'd use it as is is if
1951 * we're doing plain old texturing. Mesa IR optimization should
1952 * handle cleaning up our mess in that case.
1953 */
1954 coord = get_temp(glsl_type::vec4_type);
1955 coord_dst = ir_to_mesa_dst_reg_from_src(coord);
1956 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst,
1957 this->result);
1958
1959 if (ir->projector) {
1960 ir->projector->accept(this);
1961 projector = this->result;
1962 }
1963
1964 /* Storage for our result. Ideally for an assignment we'd be using
1965 * the actual storage for the result here, instead.
1966 */
1967 result_src = get_temp(glsl_type::vec4_type);
1968 result_dst = ir_to_mesa_dst_reg_from_src(result_src);
1969
1970 switch (ir->op) {
1971 case ir_tex:
1972 opcode = OPCODE_TEX;
1973 break;
1974 case ir_txb:
1975 opcode = OPCODE_TXB;
1976 ir->lod_info.bias->accept(this);
1977 lod_info = this->result;
1978 break;
1979 case ir_txl:
1980 opcode = OPCODE_TXL;
1981 ir->lod_info.lod->accept(this);
1982 lod_info = this->result;
1983 break;
1984 case ir_txd:
1985 case ir_txf:
1986 assert(!"GLSL 1.30 features unsupported");
1987 break;
1988 }
1989
1990 if (ir->projector) {
1991 if (opcode == OPCODE_TEX) {
1992 /* Slot the projector in as the last component of the coord. */
1993 coord_dst.writemask = WRITEMASK_W;
1994 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, projector);
1995 coord_dst.writemask = WRITEMASK_XYZW;
1996 opcode = OPCODE_TXP;
1997 } else {
1998 ir_to_mesa_src_reg coord_w = coord;
1999 coord_w.swizzle = SWIZZLE_WWWW;
2000
2001 /* For the other TEX opcodes there's no projective version
2002 * since the last slot is taken up by lod info. Do the
2003 * projective divide now.
2004 */
2005 coord_dst.writemask = WRITEMASK_W;
2006 ir_to_mesa_emit_op1(ir, OPCODE_RCP, coord_dst, projector);
2007
2008 coord_dst.writemask = WRITEMASK_XYZ;
2009 ir_to_mesa_emit_op2(ir, OPCODE_MUL, coord_dst, coord, coord_w);
2010
2011 coord_dst.writemask = WRITEMASK_XYZW;
2012 coord.swizzle = SWIZZLE_XYZW;
2013 }
2014 }
2015
2016 if (ir->shadow_comparitor) {
2017 /* Slot the shadow value in as the second to last component of the
2018 * coord.
2019 */
2020 ir->shadow_comparitor->accept(this);
2021 coord_dst.writemask = WRITEMASK_Z;
2022 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, this->result);
2023 coord_dst.writemask = WRITEMASK_XYZW;
2024 }
2025
2026 if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
2027 /* Mesa IR stores lod or lod bias in the last channel of the coords. */
2028 coord_dst.writemask = WRITEMASK_W;
2029 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, lod_info);
2030 coord_dst.writemask = WRITEMASK_XYZW;
2031 }
2032
2033 inst = ir_to_mesa_emit_op1(ir, opcode, result_dst, coord);
2034
2035 if (ir->shadow_comparitor)
2036 inst->tex_shadow = GL_TRUE;
2037
2038 inst->sampler = get_sampler_uniform_value(ir->sampler);
2039
2040 const glsl_type *sampler_type = ir->sampler->type;
2041
2042 switch (sampler_type->sampler_dimensionality) {
2043 case GLSL_SAMPLER_DIM_1D:
2044 inst->tex_target = (sampler_type->sampler_array)
2045 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
2046 break;
2047 case GLSL_SAMPLER_DIM_2D:
2048 inst->tex_target = (sampler_type->sampler_array)
2049 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
2050 break;
2051 case GLSL_SAMPLER_DIM_3D:
2052 inst->tex_target = TEXTURE_3D_INDEX;
2053 break;
2054 case GLSL_SAMPLER_DIM_CUBE:
2055 inst->tex_target = TEXTURE_CUBE_INDEX;
2056 break;
2057 case GLSL_SAMPLER_DIM_RECT:
2058 inst->tex_target = TEXTURE_RECT_INDEX;
2059 break;
2060 case GLSL_SAMPLER_DIM_BUF:
2061 assert(!"FINISHME: Implement ARB_texture_buffer_object");
2062 break;
2063 default:
2064 assert(!"Should not get here.");
2065 }
2066
2067 this->result = result_src;
2068 }
2069
2070 void
2071 ir_to_mesa_visitor::visit(ir_return *ir)
2072 {
2073 if (ir->get_value()) {
2074 ir_to_mesa_dst_reg l;
2075 int i;
2076
2077 assert(current_function);
2078
2079 ir->get_value()->accept(this);
2080 ir_to_mesa_src_reg r = this->result;
2081
2082 l = ir_to_mesa_dst_reg_from_src(current_function->return_reg);
2083
2084 for (i = 0; i < type_size(current_function->sig->return_type); i++) {
2085 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
2086 l.index++;
2087 r.index++;
2088 }
2089 }
2090
2091 ir_to_mesa_emit_op0(ir, OPCODE_RET);
2092 }
2093
2094 void
2095 ir_to_mesa_visitor::visit(ir_discard *ir)
2096 {
2097 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
2098
2099 assert(ir->condition == NULL); /* FINISHME */
2100
2101 ir_to_mesa_emit_op0(ir, OPCODE_KIL_NV);
2102 fp->UsesKill = GL_TRUE;
2103 }
2104
2105 void
2106 ir_to_mesa_visitor::visit(ir_if *ir)
2107 {
2108 ir_to_mesa_instruction *cond_inst, *if_inst, *else_inst = NULL;
2109 ir_to_mesa_instruction *prev_inst;
2110
2111 prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2112
2113 ir->condition->accept(this);
2114 assert(this->result.file != PROGRAM_UNDEFINED);
2115
2116 if (this->options->EmitCondCodes) {
2117 cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2118
2119 /* See if we actually generated any instruction for generating
2120 * the condition. If not, then cook up a move to a temp so we
2121 * have something to set cond_update on.
2122 */
2123 if (cond_inst == prev_inst) {
2124 ir_to_mesa_src_reg temp = get_temp(glsl_type::bool_type);
2125 cond_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_MOV,
2126 ir_to_mesa_dst_reg_from_src(temp),
2127 result);
2128 }
2129 cond_inst->cond_update = GL_TRUE;
2130
2131 if_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_IF);
2132 if_inst->dst_reg.cond_mask = COND_NE;
2133 } else {
2134 if_inst = ir_to_mesa_emit_op1(ir->condition,
2135 OPCODE_IF, ir_to_mesa_undef_dst,
2136 this->result);
2137 }
2138
2139 this->instructions.push_tail(if_inst);
2140
2141 visit_exec_list(&ir->then_instructions, this);
2142
2143 if (!ir->else_instructions.is_empty()) {
2144 else_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_ELSE);
2145 visit_exec_list(&ir->else_instructions, this);
2146 }
2147
2148 if_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_ENDIF,
2149 ir_to_mesa_undef_dst, ir_to_mesa_undef);
2150 }
2151
2152 ir_to_mesa_visitor::ir_to_mesa_visitor()
2153 {
2154 result.file = PROGRAM_UNDEFINED;
2155 next_temp = 1;
2156 next_signature_id = 1;
2157 current_function = NULL;
2158 mem_ctx = talloc_new(NULL);
2159 }
2160
2161 ir_to_mesa_visitor::~ir_to_mesa_visitor()
2162 {
2163 talloc_free(mem_ctx);
2164 }
2165
2166 static struct prog_src_register
2167 mesa_src_reg_from_ir_src_reg(ir_to_mesa_src_reg reg)
2168 {
2169 struct prog_src_register mesa_reg;
2170
2171 mesa_reg.File = reg.file;
2172 assert(reg.index < (1 << INST_INDEX_BITS) - 1);
2173 mesa_reg.Index = reg.index;
2174 mesa_reg.Swizzle = reg.swizzle;
2175 mesa_reg.RelAddr = reg.reladdr != NULL;
2176 mesa_reg.Negate = reg.negate;
2177 mesa_reg.Abs = 0;
2178 mesa_reg.HasIndex2 = GL_FALSE;
2179 mesa_reg.RelAddr2 = 0;
2180 mesa_reg.Index2 = 0;
2181
2182 return mesa_reg;
2183 }
2184
2185 static void
2186 set_branchtargets(ir_to_mesa_visitor *v,
2187 struct prog_instruction *mesa_instructions,
2188 int num_instructions)
2189 {
2190 int if_count = 0, loop_count = 0;
2191 int *if_stack, *loop_stack;
2192 int if_stack_pos = 0, loop_stack_pos = 0;
2193 int i, j;
2194
2195 for (i = 0; i < num_instructions; i++) {
2196 switch (mesa_instructions[i].Opcode) {
2197 case OPCODE_IF:
2198 if_count++;
2199 break;
2200 case OPCODE_BGNLOOP:
2201 loop_count++;
2202 break;
2203 case OPCODE_BRK:
2204 case OPCODE_CONT:
2205 mesa_instructions[i].BranchTarget = -1;
2206 break;
2207 default:
2208 break;
2209 }
2210 }
2211
2212 if_stack = talloc_zero_array(v->mem_ctx, int, if_count);
2213 loop_stack = talloc_zero_array(v->mem_ctx, int, loop_count);
2214
2215 for (i = 0; i < num_instructions; i++) {
2216 switch (mesa_instructions[i].Opcode) {
2217 case OPCODE_IF:
2218 if_stack[if_stack_pos] = i;
2219 if_stack_pos++;
2220 break;
2221 case OPCODE_ELSE:
2222 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2223 if_stack[if_stack_pos - 1] = i;
2224 break;
2225 case OPCODE_ENDIF:
2226 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2227 if_stack_pos--;
2228 break;
2229 case OPCODE_BGNLOOP:
2230 loop_stack[loop_stack_pos] = i;
2231 loop_stack_pos++;
2232 break;
2233 case OPCODE_ENDLOOP:
2234 loop_stack_pos--;
2235 /* Rewrite any breaks/conts at this nesting level (haven't
2236 * already had a BranchTarget assigned) to point to the end
2237 * of the loop.
2238 */
2239 for (j = loop_stack[loop_stack_pos]; j < i; j++) {
2240 if (mesa_instructions[j].Opcode == OPCODE_BRK ||
2241 mesa_instructions[j].Opcode == OPCODE_CONT) {
2242 if (mesa_instructions[j].BranchTarget == -1) {
2243 mesa_instructions[j].BranchTarget = i;
2244 }
2245 }
2246 }
2247 /* The loop ends point at each other. */
2248 mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
2249 mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
2250 break;
2251 case OPCODE_CAL:
2252 foreach_iter(exec_list_iterator, iter, v->function_signatures) {
2253 function_entry *entry = (function_entry *)iter.get();
2254
2255 if (entry->sig_id == mesa_instructions[i].BranchTarget) {
2256 mesa_instructions[i].BranchTarget = entry->inst;
2257 break;
2258 }
2259 }
2260 break;
2261 default:
2262 break;
2263 }
2264 }
2265 }
2266
2267 static void
2268 print_program(struct prog_instruction *mesa_instructions,
2269 ir_instruction **mesa_instruction_annotation,
2270 int num_instructions)
2271 {
2272 ir_instruction *last_ir = NULL;
2273 int i;
2274 int indent = 0;
2275
2276 for (i = 0; i < num_instructions; i++) {
2277 struct prog_instruction *mesa_inst = mesa_instructions + i;
2278 ir_instruction *ir = mesa_instruction_annotation[i];
2279
2280 fprintf(stdout, "%3d: ", i);
2281
2282 if (last_ir != ir && ir) {
2283 int j;
2284
2285 for (j = 0; j < indent; j++) {
2286 fprintf(stdout, " ");
2287 }
2288 ir->print();
2289 printf("\n");
2290 last_ir = ir;
2291
2292 fprintf(stdout, " "); /* line number spacing. */
2293 }
2294
2295 indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
2296 PROG_PRINT_DEBUG, NULL);
2297 }
2298 }
2299
2300 static void
2301 count_resources(struct gl_program *prog)
2302 {
2303 unsigned int i;
2304
2305 prog->SamplersUsed = 0;
2306
2307 for (i = 0; i < prog->NumInstructions; i++) {
2308 struct prog_instruction *inst = &prog->Instructions[i];
2309
2310 if (_mesa_is_tex_instruction(inst->Opcode)) {
2311 prog->SamplerTargets[inst->TexSrcUnit] =
2312 (gl_texture_index)inst->TexSrcTarget;
2313 prog->SamplersUsed |= 1 << inst->TexSrcUnit;
2314 if (inst->TexShadow) {
2315 prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
2316 }
2317 }
2318 }
2319
2320 _mesa_update_shader_textures_used(prog);
2321 }
2322
2323 struct uniform_sort {
2324 struct gl_uniform *u;
2325 int pos;
2326 };
2327
2328 /* The shader_program->Uniforms list is almost sorted in increasing
2329 * uniform->{Frag,Vert}Pos locations, but not quite when there are
2330 * uniforms shared between targets. We need to add parameters in
2331 * increasing order for the targets.
2332 */
2333 static int
2334 sort_uniforms(const void *a, const void *b)
2335 {
2336 struct uniform_sort *u1 = (struct uniform_sort *)a;
2337 struct uniform_sort *u2 = (struct uniform_sort *)b;
2338
2339 return u1->pos - u2->pos;
2340 }
2341
2342 /* Add the uniforms to the parameters. The linker chose locations
2343 * in our parameters lists (which weren't created yet), which the
2344 * uniforms code will use to poke values into our parameters list
2345 * when uniforms are updated.
2346 */
2347 static void
2348 add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
2349 struct gl_shader *shader,
2350 struct gl_program *prog)
2351 {
2352 unsigned int i;
2353 unsigned int next_sampler = 0, num_uniforms = 0;
2354 struct uniform_sort *sorted_uniforms;
2355
2356 sorted_uniforms = talloc_array(NULL, struct uniform_sort,
2357 shader_program->Uniforms->NumUniforms);
2358
2359 for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
2360 struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
2361 int parameter_index = -1;
2362
2363 switch (shader->Type) {
2364 case GL_VERTEX_SHADER:
2365 parameter_index = uniform->VertPos;
2366 break;
2367 case GL_FRAGMENT_SHADER:
2368 parameter_index = uniform->FragPos;
2369 break;
2370 case GL_GEOMETRY_SHADER:
2371 parameter_index = uniform->GeomPos;
2372 break;
2373 }
2374
2375 /* Only add uniforms used in our target. */
2376 if (parameter_index != -1) {
2377 sorted_uniforms[num_uniforms].pos = parameter_index;
2378 sorted_uniforms[num_uniforms].u = uniform;
2379 num_uniforms++;
2380 }
2381 }
2382
2383 qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
2384 sort_uniforms);
2385
2386 for (i = 0; i < num_uniforms; i++) {
2387 struct gl_uniform *uniform = sorted_uniforms[i].u;
2388 int parameter_index = sorted_uniforms[i].pos;
2389 const glsl_type *type = uniform->Type;
2390 unsigned int size;
2391
2392 if (type->is_vector() ||
2393 type->is_scalar()) {
2394 size = type->vector_elements;
2395 } else {
2396 size = type_size(type) * 4;
2397 }
2398
2399 gl_register_file file;
2400 if (type->is_sampler() ||
2401 (type->is_array() && type->fields.array->is_sampler())) {
2402 file = PROGRAM_SAMPLER;
2403 } else {
2404 file = PROGRAM_UNIFORM;
2405 }
2406
2407 GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
2408 uniform->Name);
2409
2410 if (index < 0) {
2411 index = _mesa_add_parameter(prog->Parameters, file,
2412 uniform->Name, size, type->gl_type,
2413 NULL, NULL, 0x0);
2414
2415 /* Sampler uniform values are stored in prog->SamplerUnits,
2416 * and the entry in that array is selected by this index we
2417 * store in ParameterValues[].
2418 */
2419 if (file == PROGRAM_SAMPLER) {
2420 for (unsigned int j = 0; j < size / 4; j++)
2421 prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
2422 }
2423
2424 /* The location chosen in the Parameters list here (returned
2425 * from _mesa_add_uniform) has to match what the linker chose.
2426 */
2427 if (index != parameter_index) {
2428 fail_link(shader_program, "Allocation of uniform `%s' to target "
2429 "failed (%d vs %d)\n",
2430 uniform->Name, index, parameter_index);
2431 }
2432 }
2433 }
2434
2435 talloc_free(sorted_uniforms);
2436 }
2437
2438 static void
2439 set_uniform_initializer(GLcontext *ctx, void *mem_ctx,
2440 struct gl_shader_program *shader_program,
2441 const char *name, const glsl_type *type,
2442 ir_constant *val)
2443 {
2444 if (type->is_record()) {
2445 ir_constant *field_constant;
2446
2447 field_constant = (ir_constant *)val->components.get_head();
2448
2449 for (unsigned int i = 0; i < type->length; i++) {
2450 const glsl_type *field_type = type->fields.structure[i].type;
2451 const char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
2452 type->fields.structure[i].name);
2453 set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
2454 field_type, field_constant);
2455 field_constant = (ir_constant *)field_constant->next;
2456 }
2457 return;
2458 }
2459
2460 int loc = _mesa_get_uniform_location(ctx, shader_program, name);
2461
2462 if (loc == -1) {
2463 fail_link(shader_program,
2464 "Couldn't find uniform for initializer %s\n", name);
2465 return;
2466 }
2467
2468 for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
2469 ir_constant *element;
2470 const glsl_type *element_type;
2471 if (type->is_array()) {
2472 element = val->array_elements[i];
2473 element_type = type->fields.array;
2474 } else {
2475 element = val;
2476 element_type = type;
2477 }
2478
2479 void *values;
2480
2481 if (element_type->base_type == GLSL_TYPE_BOOL) {
2482 int *conv = talloc_array(mem_ctx, int, element_type->components());
2483 for (unsigned int j = 0; j < element_type->components(); j++) {
2484 conv[j] = element->value.b[j];
2485 }
2486 values = (void *)conv;
2487 element_type = glsl_type::get_instance(GLSL_TYPE_INT,
2488 element_type->vector_elements,
2489 1);
2490 } else {
2491 values = &element->value;
2492 }
2493
2494 if (element_type->is_matrix()) {
2495 _mesa_uniform_matrix(ctx, shader_program,
2496 element_type->matrix_columns,
2497 element_type->vector_elements,
2498 loc, 1, GL_FALSE, (GLfloat *)values);
2499 loc += element_type->matrix_columns;
2500 } else {
2501 _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
2502 values, element_type->gl_type);
2503 loc += type_size(element_type);
2504 }
2505 }
2506 }
2507
2508 static void
2509 set_uniform_initializers(GLcontext *ctx,
2510 struct gl_shader_program *shader_program)
2511 {
2512 void *mem_ctx = NULL;
2513
2514 for (unsigned int i = 0; i < shader_program->_NumLinkedShaders; i++) {
2515 struct gl_shader *shader = shader_program->_LinkedShaders[i];
2516 foreach_iter(exec_list_iterator, iter, *shader->ir) {
2517 ir_instruction *ir = (ir_instruction *)iter.get();
2518 ir_variable *var = ir->as_variable();
2519
2520 if (!var || var->mode != ir_var_uniform || !var->constant_value)
2521 continue;
2522
2523 if (!mem_ctx)
2524 mem_ctx = talloc_new(NULL);
2525
2526 set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
2527 var->type, var->constant_value);
2528 }
2529 }
2530
2531 talloc_free(mem_ctx);
2532 }
2533
2534 struct gl_program *
2535 get_mesa_program(GLcontext *ctx, struct gl_shader_program *shader_program,
2536 struct gl_shader *shader)
2537 {
2538 ir_to_mesa_visitor v;
2539 struct prog_instruction *mesa_instructions, *mesa_inst;
2540 ir_instruction **mesa_instruction_annotation;
2541 int i;
2542 struct gl_program *prog;
2543 GLenum target;
2544 const char *target_string;
2545 GLboolean progress;
2546 struct gl_shader_compiler_options *options =
2547 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
2548
2549 switch (shader->Type) {
2550 case GL_VERTEX_SHADER:
2551 target = GL_VERTEX_PROGRAM_ARB;
2552 target_string = "vertex";
2553 break;
2554 case GL_FRAGMENT_SHADER:
2555 target = GL_FRAGMENT_PROGRAM_ARB;
2556 target_string = "fragment";
2557 break;
2558 default:
2559 assert(!"should not be reached");
2560 return NULL;
2561 }
2562
2563 validate_ir_tree(shader->ir);
2564
2565 prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
2566 if (!prog)
2567 return NULL;
2568 prog->Parameters = _mesa_new_parameter_list();
2569 prog->Varying = _mesa_new_parameter_list();
2570 prog->Attributes = _mesa_new_parameter_list();
2571 v.ctx = ctx;
2572 v.prog = prog;
2573 v.shader_program = shader_program;
2574 v.options = options;
2575
2576 add_uniforms_to_parameters_list(shader_program, shader, prog);
2577
2578 /* Emit Mesa IR for main(). */
2579 visit_exec_list(shader->ir, &v);
2580 v.ir_to_mesa_emit_op0(NULL, OPCODE_END);
2581
2582 /* Now emit bodies for any functions that were used. */
2583 do {
2584 progress = GL_FALSE;
2585
2586 foreach_iter(exec_list_iterator, iter, v.function_signatures) {
2587 function_entry *entry = (function_entry *)iter.get();
2588
2589 if (!entry->bgn_inst) {
2590 v.current_function = entry;
2591
2592 entry->bgn_inst = v.ir_to_mesa_emit_op0(NULL, OPCODE_BGNSUB);
2593 entry->bgn_inst->function = entry;
2594
2595 visit_exec_list(&entry->sig->body, &v);
2596
2597 ir_to_mesa_instruction *last;
2598 last = (ir_to_mesa_instruction *)v.instructions.get_tail();
2599 if (last->op != OPCODE_RET)
2600 v.ir_to_mesa_emit_op0(NULL, OPCODE_RET);
2601
2602 ir_to_mesa_instruction *end;
2603 end = v.ir_to_mesa_emit_op0(NULL, OPCODE_ENDSUB);
2604 end->function = entry;
2605
2606 progress = GL_TRUE;
2607 }
2608 }
2609 } while (progress);
2610
2611 prog->NumTemporaries = v.next_temp;
2612
2613 int num_instructions = 0;
2614 foreach_iter(exec_list_iterator, iter, v.instructions) {
2615 num_instructions++;
2616 }
2617
2618 mesa_instructions =
2619 (struct prog_instruction *)calloc(num_instructions,
2620 sizeof(*mesa_instructions));
2621 mesa_instruction_annotation = talloc_array(v.mem_ctx, ir_instruction *,
2622 num_instructions);
2623
2624 mesa_inst = mesa_instructions;
2625 i = 0;
2626 foreach_iter(exec_list_iterator, iter, v.instructions) {
2627 ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2628
2629 mesa_inst->Opcode = inst->op;
2630 mesa_inst->CondUpdate = inst->cond_update;
2631 mesa_inst->DstReg.File = inst->dst_reg.file;
2632 mesa_inst->DstReg.Index = inst->dst_reg.index;
2633 mesa_inst->DstReg.CondMask = inst->dst_reg.cond_mask;
2634 mesa_inst->DstReg.WriteMask = inst->dst_reg.writemask;
2635 mesa_inst->DstReg.RelAddr = inst->dst_reg.reladdr != NULL;
2636 mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src_reg[0]);
2637 mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src_reg[1]);
2638 mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src_reg[2]);
2639 mesa_inst->TexSrcUnit = inst->sampler;
2640 mesa_inst->TexSrcTarget = inst->tex_target;
2641 mesa_inst->TexShadow = inst->tex_shadow;
2642 mesa_instruction_annotation[i] = inst->ir;
2643
2644 /* Set IndirectRegisterFiles. */
2645 if (mesa_inst->DstReg.RelAddr)
2646 prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
2647
2648 for (unsigned src = 0; src < 3; src++)
2649 if (mesa_inst->SrcReg[src].RelAddr)
2650 prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
2651
2652 if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
2653 fail_link(shader_program, "Couldn't flatten if statement\n");
2654 }
2655
2656 switch (mesa_inst->Opcode) {
2657 case OPCODE_BGNSUB:
2658 inst->function->inst = i;
2659 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2660 break;
2661 case OPCODE_ENDSUB:
2662 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2663 break;
2664 case OPCODE_CAL:
2665 mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
2666 break;
2667 case OPCODE_ARL:
2668 prog->NumAddressRegs = 1;
2669 break;
2670 default:
2671 break;
2672 }
2673
2674 mesa_inst++;
2675 i++;
2676 }
2677
2678 set_branchtargets(&v, mesa_instructions, num_instructions);
2679
2680 if (ctx->Shader.Flags & GLSL_DUMP) {
2681 printf("\n");
2682 printf("GLSL IR for linked %s program %d:\n", target_string,
2683 shader_program->Name);
2684 _mesa_print_ir(shader->ir, NULL);
2685 printf("\n");
2686 printf("\n");
2687 printf("Mesa IR for linked %s program %d:\n", target_string,
2688 shader_program->Name);
2689 print_program(mesa_instructions, mesa_instruction_annotation,
2690 num_instructions);
2691 }
2692
2693 prog->Instructions = mesa_instructions;
2694 prog->NumInstructions = num_instructions;
2695
2696 do_set_program_inouts(shader->ir, prog);
2697 count_resources(prog);
2698
2699 _mesa_reference_program(ctx, &shader->Program, prog);
2700
2701 if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
2702 _mesa_optimize_program(ctx, prog);
2703 }
2704
2705 return prog;
2706 }
2707
2708 extern "C" {
2709 GLboolean
2710 _mesa_ir_compile_shader(GLcontext *ctx, struct gl_shader *shader)
2711 {
2712 assert(shader->CompileStatus);
2713 (void) ctx;
2714
2715 return GL_TRUE;
2716 }
2717
2718 GLboolean
2719 _mesa_ir_link_shader(GLcontext *ctx, struct gl_shader_program *prog)
2720 {
2721 assert(prog->LinkStatus);
2722
2723 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
2724 bool progress;
2725 exec_list *ir = prog->_LinkedShaders[i]->ir;
2726 struct gl_shader_compiler_options *options =
2727 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
2728
2729 do {
2730 progress = false;
2731
2732 /* Lowering */
2733 do_mat_op_to_vec(ir);
2734 do_mod_to_fract(ir);
2735 do_div_to_mul_rcp(ir);
2736 do_explog_to_explog2(ir);
2737
2738 progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
2739
2740 progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
2741
2742 if (options->EmitNoIfs)
2743 progress = do_if_to_cond_assign(ir) || progress;
2744
2745 if (options->EmitNoNoise)
2746 progress = lower_noise(ir) || progress;
2747
2748 progress = do_vec_index_to_cond_assign(ir) || progress;
2749 } while (progress);
2750
2751 validate_ir_tree(ir);
2752 }
2753
2754 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
2755 struct gl_program *linked_prog;
2756 bool ok = true;
2757
2758 linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
2759
2760 switch (prog->_LinkedShaders[i]->Type) {
2761 case GL_VERTEX_SHADER:
2762 _mesa_reference_vertprog(ctx, &prog->VertexProgram,
2763 (struct gl_vertex_program *)linked_prog);
2764 ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
2765 linked_prog);
2766 break;
2767 case GL_FRAGMENT_SHADER:
2768 _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
2769 (struct gl_fragment_program *)linked_prog);
2770 ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
2771 linked_prog);
2772 break;
2773 }
2774 if (!ok) {
2775 return GL_FALSE;
2776 }
2777 _mesa_reference_program(ctx, &linked_prog, NULL);
2778 }
2779
2780 return GL_TRUE;
2781 }
2782
2783 void
2784 _mesa_glsl_compile_shader(GLcontext *ctx, struct gl_shader *shader)
2785 {
2786 struct _mesa_glsl_parse_state *state =
2787 new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
2788
2789 const char *source = shader->Source;
2790 /* Check if the user called glCompileShader without first calling
2791 * glShaderSource. This should fail to compile, but not raise a GL_ERROR.
2792 */
2793 if (source == NULL) {
2794 shader->CompileStatus = GL_FALSE;
2795 return;
2796 }
2797
2798 state->error = preprocess(state, &source, &state->info_log,
2799 &ctx->Extensions, ctx->API);
2800
2801 if (ctx->Shader.Flags & GLSL_DUMP) {
2802 printf("GLSL source for shader %d:\n", shader->Name);
2803 printf("%s\n", shader->Source);
2804 }
2805
2806 if (!state->error) {
2807 _mesa_glsl_lexer_ctor(state, source);
2808 _mesa_glsl_parse(state);
2809 _mesa_glsl_lexer_dtor(state);
2810 }
2811
2812 talloc_free(shader->ir);
2813 shader->ir = new(shader) exec_list;
2814 if (!state->error && !state->translation_unit.is_empty())
2815 _mesa_ast_to_hir(shader->ir, state);
2816
2817 if (!state->error && !shader->ir->is_empty()) {
2818 validate_ir_tree(shader->ir);
2819
2820 /* Do some optimization at compile time to reduce shader IR size
2821 * and reduce later work if the same shader is linked multiple times
2822 */
2823 while (do_common_optimization(shader->ir, false, 32))
2824 ;
2825
2826 validate_ir_tree(shader->ir);
2827 }
2828
2829 shader->symbols = state->symbols;
2830
2831 shader->CompileStatus = !state->error;
2832 shader->InfoLog = state->info_log;
2833 shader->Version = state->language_version;
2834 memcpy(shader->builtins_to_link, state->builtins_to_link,
2835 sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
2836 shader->num_builtins_to_link = state->num_builtins_to_link;
2837
2838 if (ctx->Shader.Flags & GLSL_LOG) {
2839 _mesa_write_shader_to_file(shader);
2840 }
2841
2842 if (ctx->Shader.Flags & GLSL_DUMP) {
2843 if (shader->CompileStatus) {
2844 printf("GLSL IR for shader %d:\n", shader->Name);
2845 _mesa_print_ir(shader->ir, NULL);
2846 printf("\n\n");
2847 } else {
2848 printf("GLSL shader %d failed to compile.\n", shader->Name);
2849 }
2850 if (shader->InfoLog && shader->InfoLog[0] != 0) {
2851 printf("GLSL shader %d info log:\n", shader->Name);
2852 printf("%s\n", shader->InfoLog);
2853 }
2854 }
2855
2856 /* Retain any live IR, but trash the rest. */
2857 reparent_ir(shader->ir, shader->ir);
2858
2859 talloc_free(state);
2860
2861 if (shader->CompileStatus) {
2862 if (!ctx->Driver.CompileShader(ctx, shader))
2863 shader->CompileStatus = GL_FALSE;
2864 }
2865 }
2866
2867 void
2868 _mesa_glsl_link_shader(GLcontext *ctx, struct gl_shader_program *prog)
2869 {
2870 unsigned int i;
2871
2872 _mesa_clear_shader_program_data(ctx, prog);
2873
2874 prog->LinkStatus = GL_TRUE;
2875
2876 for (i = 0; i < prog->NumShaders; i++) {
2877 if (!prog->Shaders[i]->CompileStatus) {
2878 fail_link(prog, "linking with uncompiled shader");
2879 prog->LinkStatus = GL_FALSE;
2880 }
2881 }
2882
2883 prog->Varying = _mesa_new_parameter_list();
2884 _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
2885 _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
2886
2887 if (prog->LinkStatus) {
2888 link_shaders(ctx, prog);
2889 }
2890
2891 if (prog->LinkStatus) {
2892 if (!ctx->Driver.LinkShader(ctx, prog)) {
2893 prog->LinkStatus = GL_FALSE;
2894 }
2895 }
2896
2897 set_uniform_initializers(ctx, prog);
2898
2899 if (ctx->Shader.Flags & GLSL_DUMP) {
2900 if (!prog->LinkStatus) {
2901 printf("GLSL shader program %d failed to link\n", prog->Name);
2902 }
2903
2904 if (prog->InfoLog && prog->InfoLog[0] != 0) {
2905 printf("GLSL shader program %d info log:\n", prog->Name);
2906 printf("%s\n", prog->InfoLog);
2907 }
2908 }
2909 }
2910
2911 } /* extern "C" */