ir_to_mesa: Add each relative address to the previous
[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 * Translate GLSL IR to Mesa's gl_program representation.
30 */
31
32 #include <stdio.h>
33 #include "main/compiler.h"
34 #include "ir.h"
35 #include "ir_visitor.h"
36 #include "ir_print_visitor.h"
37 #include "ir_expression_flattening.h"
38 #include "glsl_types.h"
39 #include "glsl_parser_extras.h"
40 #include "../glsl/program.h"
41 #include "ir_optimization.h"
42 #include "ast.h"
43
44 extern "C" {
45 #include "main/mtypes.h"
46 #include "main/shaderapi.h"
47 #include "main/shaderobj.h"
48 #include "main/uniforms.h"
49 #include "program/hash_table.h"
50 #include "program/prog_instruction.h"
51 #include "program/prog_optimize.h"
52 #include "program/prog_print.h"
53 #include "program/program.h"
54 #include "program/prog_uniform.h"
55 #include "program/prog_parameter.h"
56 #include "program/sampler.h"
57 }
58
59 class src_reg;
60 class dst_reg;
61
62 static int swizzle_for_size(int size);
63
64 /**
65 * This struct is a corresponding struct to Mesa prog_src_register, with
66 * wider fields.
67 */
68 class src_reg {
69 public:
70 src_reg(gl_register_file file, int index, const glsl_type *type)
71 {
72 this->file = file;
73 this->index = index;
74 if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
75 this->swizzle = swizzle_for_size(type->vector_elements);
76 else
77 this->swizzle = SWIZZLE_XYZW;
78 this->negate = 0;
79 this->reladdr = NULL;
80 }
81
82 src_reg()
83 {
84 this->file = PROGRAM_UNDEFINED;
85 this->index = 0;
86 this->swizzle = 0;
87 this->negate = 0;
88 this->reladdr = NULL;
89 }
90
91 explicit src_reg(dst_reg reg);
92
93 gl_register_file file; /**< PROGRAM_* from Mesa */
94 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
95 GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
96 int negate; /**< NEGATE_XYZW mask from mesa */
97 /** Register index should be offset by the integer in this reg. */
98 src_reg *reladdr;
99 };
100
101 class dst_reg {
102 public:
103 dst_reg(gl_register_file file, int writemask)
104 {
105 this->file = file;
106 this->index = 0;
107 this->writemask = writemask;
108 this->cond_mask = COND_TR;
109 this->reladdr = NULL;
110 }
111
112 dst_reg()
113 {
114 this->file = PROGRAM_UNDEFINED;
115 this->index = 0;
116 this->writemask = 0;
117 this->cond_mask = COND_TR;
118 this->reladdr = NULL;
119 }
120
121 explicit dst_reg(src_reg reg);
122
123 gl_register_file file; /**< PROGRAM_* from Mesa */
124 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
125 int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
126 GLuint cond_mask:4;
127 /** Register index should be offset by the integer in this reg. */
128 src_reg *reladdr;
129 };
130
131 src_reg::src_reg(dst_reg reg)
132 {
133 this->file = reg.file;
134 this->index = reg.index;
135 this->swizzle = SWIZZLE_XYZW;
136 this->negate = 0;
137 this->reladdr = NULL;
138 }
139
140 dst_reg::dst_reg(src_reg reg)
141 {
142 this->file = reg.file;
143 this->index = reg.index;
144 this->writemask = WRITEMASK_XYZW;
145 this->cond_mask = COND_TR;
146 this->reladdr = reg.reladdr;
147 }
148
149 class ir_to_mesa_instruction : public exec_node {
150 public:
151 /* Callers of this ralloc-based new need not call delete. It's
152 * easier to just ralloc_free 'ctx' (or any of its ancestors). */
153 static void* operator new(size_t size, void *ctx)
154 {
155 void *node;
156
157 node = rzalloc_size(ctx, size);
158 assert(node != NULL);
159
160 return node;
161 }
162
163 enum prog_opcode op;
164 dst_reg dst;
165 src_reg src[3];
166 /** Pointer to the ir source this tree came from for debugging */
167 ir_instruction *ir;
168 GLboolean cond_update;
169 bool saturate;
170 int sampler; /**< sampler index */
171 int tex_target; /**< One of TEXTURE_*_INDEX */
172 GLboolean tex_shadow;
173
174 class function_entry *function; /* Set on OPCODE_CAL or OPCODE_BGNSUB */
175 };
176
177 class variable_storage : public exec_node {
178 public:
179 variable_storage(ir_variable *var, gl_register_file file, int index)
180 : file(file), index(index), var(var)
181 {
182 /* empty */
183 }
184
185 gl_register_file file;
186 int index;
187 ir_variable *var; /* variable that maps to this, if any */
188 };
189
190 class function_entry : public exec_node {
191 public:
192 ir_function_signature *sig;
193
194 /**
195 * identifier of this function signature used by the program.
196 *
197 * At the point that Mesa instructions for function calls are
198 * generated, we don't know the address of the first instruction of
199 * the function body. So we make the BranchTarget that is called a
200 * small integer and rewrite them during set_branchtargets().
201 */
202 int sig_id;
203
204 /**
205 * Pointer to first instruction of the function body.
206 *
207 * Set during function body emits after main() is processed.
208 */
209 ir_to_mesa_instruction *bgn_inst;
210
211 /**
212 * Index of the first instruction of the function body in actual
213 * Mesa IR.
214 *
215 * Set after convertion from ir_to_mesa_instruction to prog_instruction.
216 */
217 int inst;
218
219 /** Storage for the return value. */
220 src_reg return_reg;
221 };
222
223 class ir_to_mesa_visitor : public ir_visitor {
224 public:
225 ir_to_mesa_visitor();
226 ~ir_to_mesa_visitor();
227
228 function_entry *current_function;
229
230 struct gl_context *ctx;
231 struct gl_program *prog;
232 struct gl_shader_program *shader_program;
233 struct gl_shader_compiler_options *options;
234
235 int next_temp;
236
237 variable_storage *find_variable_storage(ir_variable *var);
238
239 function_entry *get_function_signature(ir_function_signature *sig);
240
241 src_reg get_temp(const glsl_type *type);
242 void reladdr_to_temp(ir_instruction *ir, src_reg *reg, int *num_reladdr);
243
244 src_reg src_reg_for_float(float val);
245
246 /**
247 * \name Visit methods
248 *
249 * As typical for the visitor pattern, there must be one \c visit method for
250 * each concrete subclass of \c ir_instruction. Virtual base classes within
251 * the hierarchy should not have \c visit methods.
252 */
253 /*@{*/
254 virtual void visit(ir_variable *);
255 virtual void visit(ir_loop *);
256 virtual void visit(ir_loop_jump *);
257 virtual void visit(ir_function_signature *);
258 virtual void visit(ir_function *);
259 virtual void visit(ir_expression *);
260 virtual void visit(ir_swizzle *);
261 virtual void visit(ir_dereference_variable *);
262 virtual void visit(ir_dereference_array *);
263 virtual void visit(ir_dereference_record *);
264 virtual void visit(ir_assignment *);
265 virtual void visit(ir_constant *);
266 virtual void visit(ir_call *);
267 virtual void visit(ir_return *);
268 virtual void visit(ir_discard *);
269 virtual void visit(ir_texture *);
270 virtual void visit(ir_if *);
271 /*@}*/
272
273 src_reg result;
274
275 /** List of variable_storage */
276 exec_list variables;
277
278 /** List of function_entry */
279 exec_list function_signatures;
280 int next_signature_id;
281
282 /** List of ir_to_mesa_instruction */
283 exec_list instructions;
284
285 ir_to_mesa_instruction *emit(ir_instruction *ir, enum prog_opcode op);
286
287 ir_to_mesa_instruction *emit(ir_instruction *ir, enum prog_opcode op,
288 dst_reg dst, src_reg src0);
289
290 ir_to_mesa_instruction *emit(ir_instruction *ir, enum prog_opcode op,
291 dst_reg dst, src_reg src0, src_reg src1);
292
293 ir_to_mesa_instruction *emit(ir_instruction *ir, enum prog_opcode op,
294 dst_reg dst,
295 src_reg src0, src_reg src1, src_reg src2);
296
297 /**
298 * Emit the correct dot-product instruction for the type of arguments
299 */
300 void emit_dp(ir_instruction *ir,
301 dst_reg dst,
302 src_reg src0,
303 src_reg src1,
304 unsigned elements);
305
306 void emit_scalar(ir_instruction *ir, enum prog_opcode op,
307 dst_reg dst, src_reg src0);
308
309 void emit_scalar(ir_instruction *ir, enum prog_opcode op,
310 dst_reg dst, src_reg src0, src_reg src1);
311
312 void emit_scs(ir_instruction *ir, enum prog_opcode op,
313 dst_reg dst, const src_reg &src);
314
315 GLboolean try_emit_mad(ir_expression *ir,
316 int mul_operand);
317 GLboolean try_emit_sat(ir_expression *ir);
318
319 void emit_swz(ir_expression *ir);
320
321 bool process_move_condition(ir_rvalue *ir);
322
323 void copy_propagate(void);
324
325 void *mem_ctx;
326 };
327
328 src_reg undef_src = src_reg(PROGRAM_UNDEFINED, 0, NULL);
329
330 dst_reg undef_dst = dst_reg(PROGRAM_UNDEFINED, SWIZZLE_NOOP);
331
332 dst_reg address_reg = dst_reg(PROGRAM_ADDRESS, WRITEMASK_X);
333
334 static void
335 fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
336
337 static void
338 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
339 {
340 va_list args;
341 va_start(args, fmt);
342 ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
343 va_end(args);
344
345 prog->LinkStatus = GL_FALSE;
346 }
347
348 static int
349 swizzle_for_size(int size)
350 {
351 int size_swizzles[4] = {
352 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
353 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
354 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
355 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
356 };
357
358 assert((size >= 1) && (size <= 4));
359 return size_swizzles[size - 1];
360 }
361
362 ir_to_mesa_instruction *
363 ir_to_mesa_visitor::emit(ir_instruction *ir, enum prog_opcode op,
364 dst_reg dst,
365 src_reg src0, src_reg src1, src_reg src2)
366 {
367 ir_to_mesa_instruction *inst = new(mem_ctx) ir_to_mesa_instruction();
368 int num_reladdr = 0;
369
370 /* If we have to do relative addressing, we want to load the ARL
371 * reg directly for one of the regs, and preload the other reladdr
372 * sources into temps.
373 */
374 num_reladdr += dst.reladdr != NULL;
375 num_reladdr += src0.reladdr != NULL;
376 num_reladdr += src1.reladdr != NULL;
377 num_reladdr += src2.reladdr != NULL;
378
379 reladdr_to_temp(ir, &src2, &num_reladdr);
380 reladdr_to_temp(ir, &src1, &num_reladdr);
381 reladdr_to_temp(ir, &src0, &num_reladdr);
382
383 if (dst.reladdr) {
384 emit(ir, OPCODE_ARL, address_reg, *dst.reladdr);
385 num_reladdr--;
386 }
387 assert(num_reladdr == 0);
388
389 inst->op = op;
390 inst->dst = dst;
391 inst->src[0] = src0;
392 inst->src[1] = src1;
393 inst->src[2] = src2;
394 inst->ir = ir;
395
396 inst->function = NULL;
397
398 this->instructions.push_tail(inst);
399
400 return inst;
401 }
402
403
404 ir_to_mesa_instruction *
405 ir_to_mesa_visitor::emit(ir_instruction *ir, enum prog_opcode op,
406 dst_reg dst, src_reg src0, src_reg src1)
407 {
408 return emit(ir, op, dst, src0, src1, undef_src);
409 }
410
411 ir_to_mesa_instruction *
412 ir_to_mesa_visitor::emit(ir_instruction *ir, enum prog_opcode op,
413 dst_reg dst, src_reg src0)
414 {
415 assert(dst.writemask != 0);
416 return emit(ir, op, dst, src0, undef_src, undef_src);
417 }
418
419 ir_to_mesa_instruction *
420 ir_to_mesa_visitor::emit(ir_instruction *ir, enum prog_opcode op)
421 {
422 return emit(ir, op, undef_dst, undef_src, undef_src, undef_src);
423 }
424
425 void
426 ir_to_mesa_visitor::emit_dp(ir_instruction *ir,
427 dst_reg dst, src_reg src0, src_reg src1,
428 unsigned elements)
429 {
430 static const gl_inst_opcode dot_opcodes[] = {
431 OPCODE_DP2, OPCODE_DP3, OPCODE_DP4
432 };
433
434 emit(ir, dot_opcodes[elements - 2], dst, src0, src1);
435 }
436
437 /**
438 * Emits Mesa scalar opcodes to produce unique answers across channels.
439 *
440 * Some Mesa opcodes are scalar-only, like ARB_fp/vp. The src X
441 * channel determines the result across all channels. So to do a vec4
442 * of this operation, we want to emit a scalar per source channel used
443 * to produce dest channels.
444 */
445 void
446 ir_to_mesa_visitor::emit_scalar(ir_instruction *ir, enum prog_opcode op,
447 dst_reg dst,
448 src_reg orig_src0, src_reg orig_src1)
449 {
450 int i, j;
451 int done_mask = ~dst.writemask;
452
453 /* Mesa RCP is a scalar operation splatting results to all channels,
454 * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
455 * dst channels.
456 */
457 for (i = 0; i < 4; i++) {
458 GLuint this_mask = (1 << i);
459 ir_to_mesa_instruction *inst;
460 src_reg src0 = orig_src0;
461 src_reg src1 = orig_src1;
462
463 if (done_mask & this_mask)
464 continue;
465
466 GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
467 GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
468 for (j = i + 1; j < 4; j++) {
469 /* If there is another enabled component in the destination that is
470 * derived from the same inputs, generate its value on this pass as
471 * well.
472 */
473 if (!(done_mask & (1 << j)) &&
474 GET_SWZ(src0.swizzle, j) == src0_swiz &&
475 GET_SWZ(src1.swizzle, j) == src1_swiz) {
476 this_mask |= (1 << j);
477 }
478 }
479 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
480 src0_swiz, src0_swiz);
481 src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
482 src1_swiz, src1_swiz);
483
484 inst = emit(ir, op, dst, src0, src1);
485 inst->dst.writemask = this_mask;
486 done_mask |= this_mask;
487 }
488 }
489
490 void
491 ir_to_mesa_visitor::emit_scalar(ir_instruction *ir, enum prog_opcode op,
492 dst_reg dst, src_reg src0)
493 {
494 src_reg undef = undef_src;
495
496 undef.swizzle = SWIZZLE_XXXX;
497
498 emit_scalar(ir, op, dst, src0, undef);
499 }
500
501 /**
502 * Emit an OPCODE_SCS instruction
503 *
504 * The \c SCS opcode functions a bit differently than the other Mesa (or
505 * ARB_fragment_program) opcodes. Instead of splatting its result across all
506 * four components of the destination, it writes one value to the \c x
507 * component and another value to the \c y component.
508 *
509 * \param ir IR instruction being processed
510 * \param op Either \c OPCODE_SIN or \c OPCODE_COS depending on which
511 * value is desired.
512 * \param dst Destination register
513 * \param src Source register
514 */
515 void
516 ir_to_mesa_visitor::emit_scs(ir_instruction *ir, enum prog_opcode op,
517 dst_reg dst,
518 const src_reg &src)
519 {
520 /* Vertex programs cannot use the SCS opcode.
521 */
522 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
523 emit_scalar(ir, op, dst, src);
524 return;
525 }
526
527 const unsigned component = (op == OPCODE_SIN) ? 0 : 1;
528 const unsigned scs_mask = (1U << component);
529 int done_mask = ~dst.writemask;
530 src_reg tmp;
531
532 assert(op == OPCODE_SIN || op == OPCODE_COS);
533
534 /* If there are compnents in the destination that differ from the component
535 * that will be written by the SCS instrution, we'll need a temporary.
536 */
537 if (scs_mask != unsigned(dst.writemask)) {
538 tmp = get_temp(glsl_type::vec4_type);
539 }
540
541 for (unsigned i = 0; i < 4; i++) {
542 unsigned this_mask = (1U << i);
543 src_reg src0 = src;
544
545 if ((done_mask & this_mask) != 0)
546 continue;
547
548 /* The source swizzle specified which component of the source generates
549 * sine / cosine for the current component in the destination. The SCS
550 * instruction requires that this value be swizzle to the X component.
551 * Replace the current swizzle with a swizzle that puts the source in
552 * the X component.
553 */
554 unsigned src0_swiz = GET_SWZ(src.swizzle, i);
555
556 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
557 src0_swiz, src0_swiz);
558 for (unsigned j = i + 1; j < 4; j++) {
559 /* If there is another enabled component in the destination that is
560 * derived from the same inputs, generate its value on this pass as
561 * well.
562 */
563 if (!(done_mask & (1 << j)) &&
564 GET_SWZ(src0.swizzle, j) == src0_swiz) {
565 this_mask |= (1 << j);
566 }
567 }
568
569 if (this_mask != scs_mask) {
570 ir_to_mesa_instruction *inst;
571 dst_reg tmp_dst = dst_reg(tmp);
572
573 /* Emit the SCS instruction.
574 */
575 inst = emit(ir, OPCODE_SCS, tmp_dst, src0);
576 inst->dst.writemask = scs_mask;
577
578 /* Move the result of the SCS instruction to the desired location in
579 * the destination.
580 */
581 tmp.swizzle = MAKE_SWIZZLE4(component, component,
582 component, component);
583 inst = emit(ir, OPCODE_SCS, dst, tmp);
584 inst->dst.writemask = this_mask;
585 } else {
586 /* Emit the SCS instruction to write directly to the destination.
587 */
588 ir_to_mesa_instruction *inst = emit(ir, OPCODE_SCS, dst, src0);
589 inst->dst.writemask = scs_mask;
590 }
591
592 done_mask |= this_mask;
593 }
594 }
595
596 struct src_reg
597 ir_to_mesa_visitor::src_reg_for_float(float val)
598 {
599 src_reg src(PROGRAM_CONSTANT, -1, NULL);
600
601 src.index = _mesa_add_unnamed_constant(this->prog->Parameters,
602 &val, 1, &src.swizzle);
603
604 return src;
605 }
606
607 static int
608 type_size(const struct glsl_type *type)
609 {
610 unsigned int i;
611 int size;
612
613 switch (type->base_type) {
614 case GLSL_TYPE_UINT:
615 case GLSL_TYPE_INT:
616 case GLSL_TYPE_FLOAT:
617 case GLSL_TYPE_BOOL:
618 if (type->is_matrix()) {
619 return type->matrix_columns;
620 } else {
621 /* Regardless of size of vector, it gets a vec4. This is bad
622 * packing for things like floats, but otherwise arrays become a
623 * mess. Hopefully a later pass over the code can pack scalars
624 * down if appropriate.
625 */
626 return 1;
627 }
628 case GLSL_TYPE_ARRAY:
629 assert(type->length > 0);
630 return type_size(type->fields.array) * type->length;
631 case GLSL_TYPE_STRUCT:
632 size = 0;
633 for (i = 0; i < type->length; i++) {
634 size += type_size(type->fields.structure[i].type);
635 }
636 return size;
637 case GLSL_TYPE_SAMPLER:
638 /* Samplers take up one slot in UNIFORMS[], but they're baked in
639 * at link time.
640 */
641 return 1;
642 default:
643 assert(0);
644 return 0;
645 }
646 }
647
648 /**
649 * In the initial pass of codegen, we assign temporary numbers to
650 * intermediate results. (not SSA -- variable assignments will reuse
651 * storage). Actual register allocation for the Mesa VM occurs in a
652 * pass over the Mesa IR later.
653 */
654 src_reg
655 ir_to_mesa_visitor::get_temp(const glsl_type *type)
656 {
657 src_reg src;
658 int swizzle[4];
659 int i;
660
661 src.file = PROGRAM_TEMPORARY;
662 src.index = next_temp;
663 src.reladdr = NULL;
664 next_temp += type_size(type);
665
666 if (type->is_array() || type->is_record()) {
667 src.swizzle = SWIZZLE_NOOP;
668 } else {
669 for (i = 0; i < type->vector_elements; i++)
670 swizzle[i] = i;
671 for (; i < 4; i++)
672 swizzle[i] = type->vector_elements - 1;
673 src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1],
674 swizzle[2], swizzle[3]);
675 }
676 src.negate = 0;
677
678 return src;
679 }
680
681 variable_storage *
682 ir_to_mesa_visitor::find_variable_storage(ir_variable *var)
683 {
684
685 variable_storage *entry;
686
687 foreach_iter(exec_list_iterator, iter, this->variables) {
688 entry = (variable_storage *)iter.get();
689
690 if (entry->var == var)
691 return entry;
692 }
693
694 return NULL;
695 }
696
697 void
698 ir_to_mesa_visitor::visit(ir_variable *ir)
699 {
700 if (strcmp(ir->name, "gl_FragCoord") == 0) {
701 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
702
703 fp->OriginUpperLeft = ir->origin_upper_left;
704 fp->PixelCenterInteger = ir->pixel_center_integer;
705
706 } else if (strcmp(ir->name, "gl_FragDepth") == 0) {
707 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
708 switch (ir->depth_layout) {
709 case ir_depth_layout_none:
710 fp->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
711 break;
712 case ir_depth_layout_any:
713 fp->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
714 break;
715 case ir_depth_layout_greater:
716 fp->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
717 break;
718 case ir_depth_layout_less:
719 fp->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
720 break;
721 case ir_depth_layout_unchanged:
722 fp->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
723 break;
724 default:
725 assert(0);
726 break;
727 }
728 }
729
730 if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
731 unsigned int i;
732 const ir_state_slot *const slots = ir->state_slots;
733 assert(ir->state_slots != NULL);
734
735 /* Check if this statevar's setup in the STATE file exactly
736 * matches how we'll want to reference it as a
737 * struct/array/whatever. If not, then we need to move it into
738 * temporary storage and hope that it'll get copy-propagated
739 * out.
740 */
741 for (i = 0; i < ir->num_state_slots; i++) {
742 if (slots[i].swizzle != SWIZZLE_XYZW) {
743 break;
744 }
745 }
746
747 struct variable_storage *storage;
748 dst_reg dst;
749 if (i == ir->num_state_slots) {
750 /* We'll set the index later. */
751 storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
752 this->variables.push_tail(storage);
753
754 dst = undef_dst;
755 } else {
756 /* The variable_storage constructor allocates slots based on the size
757 * of the type. However, this had better match the number of state
758 * elements that we're going to copy into the new temporary.
759 */
760 assert((int) ir->num_state_slots == type_size(ir->type));
761
762 storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
763 this->next_temp);
764 this->variables.push_tail(storage);
765 this->next_temp += type_size(ir->type);
766
767 dst = dst_reg(src_reg(PROGRAM_TEMPORARY, storage->index, NULL));
768 }
769
770
771 for (unsigned int i = 0; i < ir->num_state_slots; i++) {
772 int index = _mesa_add_state_reference(this->prog->Parameters,
773 (gl_state_index *)slots[i].tokens);
774
775 if (storage->file == PROGRAM_STATE_VAR) {
776 if (storage->index == -1) {
777 storage->index = index;
778 } else {
779 assert(index == storage->index + (int)i);
780 }
781 } else {
782 src_reg src(PROGRAM_STATE_VAR, index, NULL);
783 src.swizzle = slots[i].swizzle;
784 emit(ir, OPCODE_MOV, dst, src);
785 /* even a float takes up a whole vec4 reg in a struct/array. */
786 dst.index++;
787 }
788 }
789
790 if (storage->file == PROGRAM_TEMPORARY &&
791 dst.index != storage->index + (int) ir->num_state_slots) {
792 fail_link(this->shader_program,
793 "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
794 ir->name, dst.index - storage->index,
795 type_size(ir->type));
796 }
797 }
798 }
799
800 void
801 ir_to_mesa_visitor::visit(ir_loop *ir)
802 {
803 ir_dereference_variable *counter = NULL;
804
805 if (ir->counter != NULL)
806 counter = new(mem_ctx) ir_dereference_variable(ir->counter);
807
808 if (ir->from != NULL) {
809 assert(ir->counter != NULL);
810
811 ir_assignment *a =
812 new(mem_ctx) ir_assignment(counter, ir->from, NULL);
813
814 a->accept(this);
815 }
816
817 emit(NULL, OPCODE_BGNLOOP);
818
819 if (ir->to) {
820 ir_expression *e =
821 new(mem_ctx) ir_expression(ir->cmp, glsl_type::bool_type,
822 counter, ir->to);
823 ir_if *if_stmt = new(mem_ctx) ir_if(e);
824
825 ir_loop_jump *brk =
826 new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_break);
827
828 if_stmt->then_instructions.push_tail(brk);
829
830 if_stmt->accept(this);
831 }
832
833 visit_exec_list(&ir->body_instructions, this);
834
835 if (ir->increment) {
836 ir_expression *e =
837 new(mem_ctx) ir_expression(ir_binop_add, counter->type,
838 counter, ir->increment);
839
840 ir_assignment *a =
841 new(mem_ctx) ir_assignment(counter, e, NULL);
842
843 a->accept(this);
844 }
845
846 emit(NULL, OPCODE_ENDLOOP);
847 }
848
849 void
850 ir_to_mesa_visitor::visit(ir_loop_jump *ir)
851 {
852 switch (ir->mode) {
853 case ir_loop_jump::jump_break:
854 emit(NULL, OPCODE_BRK);
855 break;
856 case ir_loop_jump::jump_continue:
857 emit(NULL, OPCODE_CONT);
858 break;
859 }
860 }
861
862
863 void
864 ir_to_mesa_visitor::visit(ir_function_signature *ir)
865 {
866 assert(0);
867 (void)ir;
868 }
869
870 void
871 ir_to_mesa_visitor::visit(ir_function *ir)
872 {
873 /* Ignore function bodies other than main() -- we shouldn't see calls to
874 * them since they should all be inlined before we get to ir_to_mesa.
875 */
876 if (strcmp(ir->name, "main") == 0) {
877 const ir_function_signature *sig;
878 exec_list empty;
879
880 sig = ir->matching_signature(&empty);
881
882 assert(sig);
883
884 foreach_iter(exec_list_iterator, iter, sig->body) {
885 ir_instruction *ir = (ir_instruction *)iter.get();
886
887 ir->accept(this);
888 }
889 }
890 }
891
892 GLboolean
893 ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
894 {
895 int nonmul_operand = 1 - mul_operand;
896 src_reg a, b, c;
897
898 ir_expression *expr = ir->operands[mul_operand]->as_expression();
899 if (!expr || expr->operation != ir_binop_mul)
900 return false;
901
902 expr->operands[0]->accept(this);
903 a = this->result;
904 expr->operands[1]->accept(this);
905 b = this->result;
906 ir->operands[nonmul_operand]->accept(this);
907 c = this->result;
908
909 this->result = get_temp(ir->type);
910 emit(ir, OPCODE_MAD, dst_reg(this->result), a, b, c);
911
912 return true;
913 }
914
915 GLboolean
916 ir_to_mesa_visitor::try_emit_sat(ir_expression *ir)
917 {
918 /* Saturates were only introduced to vertex programs in
919 * NV_vertex_program3, so don't give them to drivers in the VP.
920 */
921 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
922 return false;
923
924 ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
925 if (!sat_src)
926 return false;
927
928 sat_src->accept(this);
929 src_reg src = this->result;
930
931 this->result = get_temp(ir->type);
932 ir_to_mesa_instruction *inst;
933 inst = emit(ir, OPCODE_MOV, dst_reg(this->result), src);
934 inst->saturate = true;
935
936 return true;
937 }
938
939 void
940 ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
941 src_reg *reg, int *num_reladdr)
942 {
943 if (!reg->reladdr)
944 return;
945
946 emit(ir, OPCODE_ARL, address_reg, *reg->reladdr);
947
948 if (*num_reladdr != 1) {
949 src_reg temp = get_temp(glsl_type::vec4_type);
950
951 emit(ir, OPCODE_MOV, dst_reg(temp), *reg);
952 *reg = temp;
953 }
954
955 (*num_reladdr)--;
956 }
957
958 void
959 ir_to_mesa_visitor::emit_swz(ir_expression *ir)
960 {
961 /* Assume that the vector operator is in a form compatible with OPCODE_SWZ.
962 * This means that each of the operands is either an immediate value of -1,
963 * 0, or 1, or is a component from one source register (possibly with
964 * negation).
965 */
966 uint8_t components[4] = { 0 };
967 bool negate[4] = { false };
968 ir_variable *var = NULL;
969
970 for (unsigned i = 0; i < ir->type->vector_elements; i++) {
971 ir_rvalue *op = ir->operands[i];
972
973 assert(op->type->is_scalar());
974
975 while (op != NULL) {
976 switch (op->ir_type) {
977 case ir_type_constant: {
978
979 assert(op->type->is_scalar());
980
981 const ir_constant *const c = op->as_constant();
982 if (c->is_one()) {
983 components[i] = SWIZZLE_ONE;
984 } else if (c->is_zero()) {
985 components[i] = SWIZZLE_ZERO;
986 } else if (c->is_negative_one()) {
987 components[i] = SWIZZLE_ONE;
988 negate[i] = true;
989 } else {
990 assert(!"SWZ constant must be 0.0 or 1.0.");
991 }
992
993 op = NULL;
994 break;
995 }
996
997 case ir_type_dereference_variable: {
998 ir_dereference_variable *const deref =
999 (ir_dereference_variable *) op;
1000
1001 assert((var == NULL) || (deref->var == var));
1002 components[i] = SWIZZLE_X;
1003 var = deref->var;
1004 op = NULL;
1005 break;
1006 }
1007
1008 case ir_type_expression: {
1009 ir_expression *const expr = (ir_expression *) op;
1010
1011 assert(expr->operation == ir_unop_neg);
1012 negate[i] = true;
1013
1014 op = expr->operands[0];
1015 break;
1016 }
1017
1018 case ir_type_swizzle: {
1019 ir_swizzle *const swiz = (ir_swizzle *) op;
1020
1021 components[i] = swiz->mask.x;
1022 op = swiz->val;
1023 break;
1024 }
1025
1026 default:
1027 assert(!"Should not get here.");
1028 return;
1029 }
1030 }
1031 }
1032
1033 assert(var != NULL);
1034
1035 ir_dereference_variable *const deref =
1036 new(mem_ctx) ir_dereference_variable(var);
1037
1038 this->result.file = PROGRAM_UNDEFINED;
1039 deref->accept(this);
1040 if (this->result.file == PROGRAM_UNDEFINED) {
1041 ir_print_visitor v;
1042 printf("Failed to get tree for expression operand:\n");
1043 deref->accept(&v);
1044 exit(1);
1045 }
1046
1047 src_reg src;
1048
1049 src = this->result;
1050 src.swizzle = MAKE_SWIZZLE4(components[0],
1051 components[1],
1052 components[2],
1053 components[3]);
1054 src.negate = ((unsigned(negate[0]) << 0)
1055 | (unsigned(negate[1]) << 1)
1056 | (unsigned(negate[2]) << 2)
1057 | (unsigned(negate[3]) << 3));
1058
1059 /* Storage for our result. Ideally for an assignment we'd be using the
1060 * actual storage for the result here, instead.
1061 */
1062 const src_reg result_src = get_temp(ir->type);
1063 dst_reg result_dst = dst_reg(result_src);
1064
1065 /* Limit writes to the channels that will be used by result_src later.
1066 * This does limit this temp's use as a temporary for multi-instruction
1067 * sequences.
1068 */
1069 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1070
1071 emit(ir, OPCODE_SWZ, result_dst, src);
1072 this->result = result_src;
1073 }
1074
1075 void
1076 ir_to_mesa_visitor::visit(ir_expression *ir)
1077 {
1078 unsigned int operand;
1079 src_reg op[Elements(ir->operands)];
1080 src_reg result_src;
1081 dst_reg result_dst;
1082
1083 /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
1084 */
1085 if (ir->operation == ir_binop_add) {
1086 if (try_emit_mad(ir, 1))
1087 return;
1088 if (try_emit_mad(ir, 0))
1089 return;
1090 }
1091 if (try_emit_sat(ir))
1092 return;
1093
1094 if (ir->operation == ir_quadop_vector) {
1095 this->emit_swz(ir);
1096 return;
1097 }
1098
1099 for (operand = 0; operand < ir->get_num_operands(); operand++) {
1100 this->result.file = PROGRAM_UNDEFINED;
1101 ir->operands[operand]->accept(this);
1102 if (this->result.file == PROGRAM_UNDEFINED) {
1103 ir_print_visitor v;
1104 printf("Failed to get tree for expression operand:\n");
1105 ir->operands[operand]->accept(&v);
1106 exit(1);
1107 }
1108 op[operand] = this->result;
1109
1110 /* Matrix expression operands should have been broken down to vector
1111 * operations already.
1112 */
1113 assert(!ir->operands[operand]->type->is_matrix());
1114 }
1115
1116 int vector_elements = ir->operands[0]->type->vector_elements;
1117 if (ir->operands[1]) {
1118 vector_elements = MAX2(vector_elements,
1119 ir->operands[1]->type->vector_elements);
1120 }
1121
1122 this->result.file = PROGRAM_UNDEFINED;
1123
1124 /* Storage for our result. Ideally for an assignment we'd be using
1125 * the actual storage for the result here, instead.
1126 */
1127 result_src = get_temp(ir->type);
1128 /* convenience for the emit functions below. */
1129 result_dst = dst_reg(result_src);
1130 /* Limit writes to the channels that will be used by result_src later.
1131 * This does limit this temp's use as a temporary for multi-instruction
1132 * sequences.
1133 */
1134 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1135
1136 switch (ir->operation) {
1137 case ir_unop_logic_not:
1138 emit(ir, OPCODE_SEQ, result_dst, op[0], src_reg_for_float(0.0));
1139 break;
1140 case ir_unop_neg:
1141 op[0].negate = ~op[0].negate;
1142 result_src = op[0];
1143 break;
1144 case ir_unop_abs:
1145 emit(ir, OPCODE_ABS, result_dst, op[0]);
1146 break;
1147 case ir_unop_sign:
1148 emit(ir, OPCODE_SSG, result_dst, op[0]);
1149 break;
1150 case ir_unop_rcp:
1151 emit_scalar(ir, OPCODE_RCP, result_dst, op[0]);
1152 break;
1153
1154 case ir_unop_exp2:
1155 emit_scalar(ir, OPCODE_EX2, result_dst, op[0]);
1156 break;
1157 case ir_unop_exp:
1158 case ir_unop_log:
1159 assert(!"not reached: should be handled by ir_explog_to_explog2");
1160 break;
1161 case ir_unop_log2:
1162 emit_scalar(ir, OPCODE_LG2, result_dst, op[0]);
1163 break;
1164 case ir_unop_sin:
1165 emit_scalar(ir, OPCODE_SIN, result_dst, op[0]);
1166 break;
1167 case ir_unop_cos:
1168 emit_scalar(ir, OPCODE_COS, result_dst, op[0]);
1169 break;
1170 case ir_unop_sin_reduced:
1171 emit_scs(ir, OPCODE_SIN, result_dst, op[0]);
1172 break;
1173 case ir_unop_cos_reduced:
1174 emit_scs(ir, OPCODE_COS, result_dst, op[0]);
1175 break;
1176
1177 case ir_unop_dFdx:
1178 emit(ir, OPCODE_DDX, result_dst, op[0]);
1179 break;
1180 case ir_unop_dFdy:
1181 emit(ir, OPCODE_DDY, result_dst, op[0]);
1182 break;
1183
1184 case ir_unop_noise: {
1185 const enum prog_opcode opcode =
1186 prog_opcode(OPCODE_NOISE1
1187 + (ir->operands[0]->type->vector_elements) - 1);
1188 assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
1189
1190 emit(ir, opcode, result_dst, op[0]);
1191 break;
1192 }
1193
1194 case ir_binop_add:
1195 emit(ir, OPCODE_ADD, result_dst, op[0], op[1]);
1196 break;
1197 case ir_binop_sub:
1198 emit(ir, OPCODE_SUB, result_dst, op[0], op[1]);
1199 break;
1200
1201 case ir_binop_mul:
1202 emit(ir, OPCODE_MUL, result_dst, op[0], op[1]);
1203 break;
1204 case ir_binop_div:
1205 assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1206 case ir_binop_mod:
1207 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1208 break;
1209
1210 case ir_binop_less:
1211 emit(ir, OPCODE_SLT, result_dst, op[0], op[1]);
1212 break;
1213 case ir_binop_greater:
1214 emit(ir, OPCODE_SGT, result_dst, op[0], op[1]);
1215 break;
1216 case ir_binop_lequal:
1217 emit(ir, OPCODE_SLE, result_dst, op[0], op[1]);
1218 break;
1219 case ir_binop_gequal:
1220 emit(ir, OPCODE_SGE, result_dst, op[0], op[1]);
1221 break;
1222 case ir_binop_equal:
1223 emit(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1224 break;
1225 case ir_binop_nequal:
1226 emit(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1227 break;
1228 case ir_binop_all_equal:
1229 /* "==" operator producing a scalar boolean. */
1230 if (ir->operands[0]->type->is_vector() ||
1231 ir->operands[1]->type->is_vector()) {
1232 src_reg temp = get_temp(glsl_type::vec4_type);
1233 emit(ir, OPCODE_SNE, dst_reg(temp), op[0], op[1]);
1234 emit_dp(ir, result_dst, temp, temp, vector_elements);
1235 emit(ir, OPCODE_SEQ, result_dst, result_src, src_reg_for_float(0.0));
1236 } else {
1237 emit(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1238 }
1239 break;
1240 case ir_binop_any_nequal:
1241 /* "!=" operator producing a scalar boolean. */
1242 if (ir->operands[0]->type->is_vector() ||
1243 ir->operands[1]->type->is_vector()) {
1244 src_reg temp = get_temp(glsl_type::vec4_type);
1245 emit(ir, OPCODE_SNE, dst_reg(temp), op[0], op[1]);
1246 emit_dp(ir, result_dst, temp, temp, vector_elements);
1247 emit(ir, OPCODE_SNE, result_dst, result_src, src_reg_for_float(0.0));
1248 } else {
1249 emit(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1250 }
1251 break;
1252
1253 case ir_unop_any:
1254 assert(ir->operands[0]->type->is_vector());
1255 emit_dp(ir, result_dst, op[0], op[0],
1256 ir->operands[0]->type->vector_elements);
1257 emit(ir, OPCODE_SNE, result_dst, result_src, src_reg_for_float(0.0));
1258 break;
1259
1260 case ir_binop_logic_xor:
1261 emit(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1262 break;
1263
1264 case ir_binop_logic_or:
1265 /* This could be a saturated add and skip the SNE. */
1266 emit(ir, OPCODE_ADD, result_dst, op[0], op[1]);
1267 emit(ir, OPCODE_SNE, result_dst, result_src, src_reg_for_float(0.0));
1268 break;
1269
1270 case ir_binop_logic_and:
1271 /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
1272 emit(ir, OPCODE_MUL, result_dst, op[0], op[1]);
1273 break;
1274
1275 case ir_binop_dot:
1276 assert(ir->operands[0]->type->is_vector());
1277 assert(ir->operands[0]->type == ir->operands[1]->type);
1278 emit_dp(ir, result_dst, op[0], op[1],
1279 ir->operands[0]->type->vector_elements);
1280 break;
1281
1282 case ir_unop_sqrt:
1283 /* sqrt(x) = x * rsq(x). */
1284 emit_scalar(ir, OPCODE_RSQ, result_dst, op[0]);
1285 emit(ir, OPCODE_MUL, result_dst, result_src, op[0]);
1286 /* For incoming channels <= 0, set the result to 0. */
1287 op[0].negate = ~op[0].negate;
1288 emit(ir, OPCODE_CMP, result_dst,
1289 op[0], result_src, src_reg_for_float(0.0));
1290 break;
1291 case ir_unop_rsq:
1292 emit_scalar(ir, OPCODE_RSQ, result_dst, op[0]);
1293 break;
1294 case ir_unop_i2f:
1295 case ir_unop_u2f:
1296 case ir_unop_b2f:
1297 case ir_unop_b2i:
1298 case ir_unop_i2u:
1299 case ir_unop_u2i:
1300 /* Mesa IR lacks types, ints are stored as truncated floats. */
1301 result_src = op[0];
1302 break;
1303 case ir_unop_f2i:
1304 emit(ir, OPCODE_TRUNC, result_dst, op[0]);
1305 break;
1306 case ir_unop_f2b:
1307 case ir_unop_i2b:
1308 emit(ir, OPCODE_SNE, result_dst,
1309 op[0], src_reg_for_float(0.0));
1310 break;
1311 case ir_unop_trunc:
1312 emit(ir, OPCODE_TRUNC, result_dst, op[0]);
1313 break;
1314 case ir_unop_ceil:
1315 op[0].negate = ~op[0].negate;
1316 emit(ir, OPCODE_FLR, result_dst, op[0]);
1317 result_src.negate = ~result_src.negate;
1318 break;
1319 case ir_unop_floor:
1320 emit(ir, OPCODE_FLR, result_dst, op[0]);
1321 break;
1322 case ir_unop_fract:
1323 emit(ir, OPCODE_FRC, result_dst, op[0]);
1324 break;
1325
1326 case ir_binop_min:
1327 emit(ir, OPCODE_MIN, result_dst, op[0], op[1]);
1328 break;
1329 case ir_binop_max:
1330 emit(ir, OPCODE_MAX, result_dst, op[0], op[1]);
1331 break;
1332 case ir_binop_pow:
1333 emit_scalar(ir, OPCODE_POW, result_dst, op[0], op[1]);
1334 break;
1335
1336 case ir_unop_bit_not:
1337 case ir_binop_lshift:
1338 case ir_binop_rshift:
1339 case ir_binop_bit_and:
1340 case ir_binop_bit_xor:
1341 case ir_binop_bit_or:
1342 case ir_unop_round_even:
1343 assert(!"GLSL 1.30 features unsupported");
1344 break;
1345
1346 case ir_quadop_vector:
1347 /* This operation should have already been handled.
1348 */
1349 assert(!"Should not get here.");
1350 break;
1351 }
1352
1353 this->result = result_src;
1354 }
1355
1356
1357 void
1358 ir_to_mesa_visitor::visit(ir_swizzle *ir)
1359 {
1360 src_reg src;
1361 int i;
1362 int swizzle[4];
1363
1364 /* Note that this is only swizzles in expressions, not those on the left
1365 * hand side of an assignment, which do write masking. See ir_assignment
1366 * for that.
1367 */
1368
1369 ir->val->accept(this);
1370 src = this->result;
1371 assert(src.file != PROGRAM_UNDEFINED);
1372
1373 for (i = 0; i < 4; i++) {
1374 if (i < ir->type->vector_elements) {
1375 switch (i) {
1376 case 0:
1377 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.x);
1378 break;
1379 case 1:
1380 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.y);
1381 break;
1382 case 2:
1383 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.z);
1384 break;
1385 case 3:
1386 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.w);
1387 break;
1388 }
1389 } else {
1390 /* If the type is smaller than a vec4, replicate the last
1391 * channel out.
1392 */
1393 swizzle[i] = swizzle[ir->type->vector_elements - 1];
1394 }
1395 }
1396
1397 src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
1398
1399 this->result = src;
1400 }
1401
1402 void
1403 ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
1404 {
1405 variable_storage *entry = find_variable_storage(ir->var);
1406 ir_variable *var = ir->var;
1407
1408 if (!entry) {
1409 switch (var->mode) {
1410 case ir_var_uniform:
1411 entry = new(mem_ctx) variable_storage(var, PROGRAM_UNIFORM,
1412 var->location);
1413 this->variables.push_tail(entry);
1414 break;
1415 case ir_var_in:
1416 case ir_var_inout:
1417 /* The linker assigns locations for varyings and attributes,
1418 * including deprecated builtins (like gl_Color),
1419 * user-assigned generic attributes (glBindVertexLocation),
1420 * and user-defined varyings.
1421 *
1422 * FINISHME: We would hit this path for function arguments. Fix!
1423 */
1424 assert(var->location != -1);
1425 entry = new(mem_ctx) variable_storage(var,
1426 PROGRAM_INPUT,
1427 var->location);
1428 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
1429 var->location >= VERT_ATTRIB_GENERIC0) {
1430 _mesa_add_attribute(this->prog->Attributes,
1431 var->name,
1432 _mesa_sizeof_glsl_type(var->type->gl_type),
1433 var->type->gl_type,
1434 var->location - VERT_ATTRIB_GENERIC0);
1435 }
1436 break;
1437 case ir_var_out:
1438 assert(var->location != -1);
1439 entry = new(mem_ctx) variable_storage(var,
1440 PROGRAM_OUTPUT,
1441 var->location);
1442 break;
1443 case ir_var_system_value:
1444 entry = new(mem_ctx) variable_storage(var,
1445 PROGRAM_SYSTEM_VALUE,
1446 var->location);
1447 break;
1448 case ir_var_auto:
1449 case ir_var_temporary:
1450 entry = new(mem_ctx) variable_storage(var, PROGRAM_TEMPORARY,
1451 this->next_temp);
1452 this->variables.push_tail(entry);
1453
1454 next_temp += type_size(var->type);
1455 break;
1456 }
1457
1458 if (!entry) {
1459 printf("Failed to make storage for %s\n", var->name);
1460 exit(1);
1461 }
1462 }
1463
1464 this->result = src_reg(entry->file, entry->index, var->type);
1465 }
1466
1467 void
1468 ir_to_mesa_visitor::visit(ir_dereference_array *ir)
1469 {
1470 ir_constant *index;
1471 src_reg src;
1472 int element_size = type_size(ir->type);
1473
1474 index = ir->array_index->constant_expression_value();
1475
1476 ir->array->accept(this);
1477 src = this->result;
1478
1479 if (index) {
1480 src.index += index->value.i[0] * element_size;
1481 } else {
1482 /* Variable index array dereference. It eats the "vec4" of the
1483 * base of the array and an index that offsets the Mesa register
1484 * index.
1485 */
1486 ir->array_index->accept(this);
1487
1488 src_reg index_reg;
1489
1490 if (element_size == 1) {
1491 index_reg = this->result;
1492 } else {
1493 index_reg = get_temp(glsl_type::float_type);
1494
1495 emit(ir, OPCODE_MUL, dst_reg(index_reg),
1496 this->result, src_reg_for_float(element_size));
1497 }
1498
1499 /* If there was already a relative address register involved, add the
1500 * new and the old together to get the new offset.
1501 */
1502 if (src.reladdr != NULL) {
1503 src_reg accum_reg = get_temp(glsl_type::float_type);
1504
1505 emit(ir, OPCODE_ADD, dst_reg(accum_reg),
1506 index_reg, *src.reladdr);
1507
1508 index_reg = accum_reg;
1509 }
1510
1511 src.reladdr = ralloc(mem_ctx, src_reg);
1512 memcpy(src.reladdr, &index_reg, sizeof(index_reg));
1513 }
1514
1515 /* If the type is smaller than a vec4, replicate the last channel out. */
1516 if (ir->type->is_scalar() || ir->type->is_vector())
1517 src.swizzle = swizzle_for_size(ir->type->vector_elements);
1518 else
1519 src.swizzle = SWIZZLE_NOOP;
1520
1521 this->result = src;
1522 }
1523
1524 void
1525 ir_to_mesa_visitor::visit(ir_dereference_record *ir)
1526 {
1527 unsigned int i;
1528 const glsl_type *struct_type = ir->record->type;
1529 int offset = 0;
1530
1531 ir->record->accept(this);
1532
1533 for (i = 0; i < struct_type->length; i++) {
1534 if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
1535 break;
1536 offset += type_size(struct_type->fields.structure[i].type);
1537 }
1538
1539 /* If the type is smaller than a vec4, replicate the last channel out. */
1540 if (ir->type->is_scalar() || ir->type->is_vector())
1541 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
1542 else
1543 this->result.swizzle = SWIZZLE_NOOP;
1544
1545 this->result.index += offset;
1546 }
1547
1548 /**
1549 * We want to be careful in assignment setup to hit the actual storage
1550 * instead of potentially using a temporary like we might with the
1551 * ir_dereference handler.
1552 */
1553 static dst_reg
1554 get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
1555 {
1556 /* The LHS must be a dereference. If the LHS is a variable indexed array
1557 * access of a vector, it must be separated into a series conditional moves
1558 * before reaching this point (see ir_vec_index_to_cond_assign).
1559 */
1560 assert(ir->as_dereference());
1561 ir_dereference_array *deref_array = ir->as_dereference_array();
1562 if (deref_array) {
1563 assert(!deref_array->array->type->is_vector());
1564 }
1565
1566 /* Use the rvalue deref handler for the most part. We'll ignore
1567 * swizzles in it and write swizzles using writemask, though.
1568 */
1569 ir->accept(v);
1570 return dst_reg(v->result);
1571 }
1572
1573 /**
1574 * Process the condition of a conditional assignment
1575 *
1576 * Examines the condition of a conditional assignment to generate the optimal
1577 * first operand of a \c CMP instruction. If the condition is a relational
1578 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
1579 * used as the source for the \c CMP instruction. Otherwise the comparison
1580 * is processed to a boolean result, and the boolean result is used as the
1581 * operand to the CMP instruction.
1582 */
1583 bool
1584 ir_to_mesa_visitor::process_move_condition(ir_rvalue *ir)
1585 {
1586 ir_rvalue *src_ir = ir;
1587 bool negate = true;
1588 bool switch_order = false;
1589
1590 ir_expression *const expr = ir->as_expression();
1591 if ((expr != NULL) && (expr->get_num_operands() == 2)) {
1592 bool zero_on_left = false;
1593
1594 if (expr->operands[0]->is_zero()) {
1595 src_ir = expr->operands[1];
1596 zero_on_left = true;
1597 } else if (expr->operands[1]->is_zero()) {
1598 src_ir = expr->operands[0];
1599 zero_on_left = false;
1600 }
1601
1602 /* a is - 0 + - 0 +
1603 * (a < 0) T F F ( a < 0) T F F
1604 * (0 < a) F F T (-a < 0) F F T
1605 * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
1606 * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
1607 * (a > 0) F F T (-a < 0) F F T
1608 * (0 > a) T F F ( a < 0) T F F
1609 * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
1610 * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
1611 *
1612 * Note that exchanging the order of 0 and 'a' in the comparison simply
1613 * means that the value of 'a' should be negated.
1614 */
1615 if (src_ir != ir) {
1616 switch (expr->operation) {
1617 case ir_binop_less:
1618 switch_order = false;
1619 negate = zero_on_left;
1620 break;
1621
1622 case ir_binop_greater:
1623 switch_order = false;
1624 negate = !zero_on_left;
1625 break;
1626
1627 case ir_binop_lequal:
1628 switch_order = true;
1629 negate = !zero_on_left;
1630 break;
1631
1632 case ir_binop_gequal:
1633 switch_order = true;
1634 negate = zero_on_left;
1635 break;
1636
1637 default:
1638 /* This isn't the right kind of comparison afterall, so make sure
1639 * the whole condition is visited.
1640 */
1641 src_ir = ir;
1642 break;
1643 }
1644 }
1645 }
1646
1647 src_ir->accept(this);
1648
1649 /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
1650 * condition we produced is 0.0 or 1.0. By flipping the sign, we can
1651 * choose which value OPCODE_CMP produces without an extra instruction
1652 * computing the condition.
1653 */
1654 if (negate)
1655 this->result.negate = ~this->result.negate;
1656
1657 return switch_order;
1658 }
1659
1660 void
1661 ir_to_mesa_visitor::visit(ir_assignment *ir)
1662 {
1663 dst_reg l;
1664 src_reg r;
1665 int i;
1666
1667 ir->rhs->accept(this);
1668 r = this->result;
1669
1670 l = get_assignment_lhs(ir->lhs, this);
1671
1672 /* FINISHME: This should really set to the correct maximal writemask for each
1673 * FINISHME: component written (in the loops below). This case can only
1674 * FINISHME: occur for matrices, arrays, and structures.
1675 */
1676 if (ir->write_mask == 0) {
1677 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
1678 l.writemask = WRITEMASK_XYZW;
1679 } else if (ir->lhs->type->is_scalar()) {
1680 /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
1681 * FINISHME: W component of fragment shader output zero, work correctly.
1682 */
1683 l.writemask = WRITEMASK_XYZW;
1684 } else {
1685 int swizzles[4];
1686 int first_enabled_chan = 0;
1687 int rhs_chan = 0;
1688
1689 assert(ir->lhs->type->is_vector());
1690 l.writemask = ir->write_mask;
1691
1692 for (int i = 0; i < 4; i++) {
1693 if (l.writemask & (1 << i)) {
1694 first_enabled_chan = GET_SWZ(r.swizzle, i);
1695 break;
1696 }
1697 }
1698
1699 /* Swizzle a small RHS vector into the channels being written.
1700 *
1701 * glsl ir treats write_mask as dictating how many channels are
1702 * present on the RHS while Mesa IR treats write_mask as just
1703 * showing which channels of the vec4 RHS get written.
1704 */
1705 for (int i = 0; i < 4; i++) {
1706 if (l.writemask & (1 << i))
1707 swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
1708 else
1709 swizzles[i] = first_enabled_chan;
1710 }
1711 r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
1712 swizzles[2], swizzles[3]);
1713 }
1714
1715 assert(l.file != PROGRAM_UNDEFINED);
1716 assert(r.file != PROGRAM_UNDEFINED);
1717
1718 if (ir->condition) {
1719 const bool switch_order = this->process_move_condition(ir->condition);
1720 src_reg condition = this->result;
1721
1722 for (i = 0; i < type_size(ir->lhs->type); i++) {
1723 if (switch_order) {
1724 emit(ir, OPCODE_CMP, l, condition, src_reg(l), r);
1725 } else {
1726 emit(ir, OPCODE_CMP, l, condition, r, src_reg(l));
1727 }
1728
1729 l.index++;
1730 r.index++;
1731 }
1732 } else {
1733 for (i = 0; i < type_size(ir->lhs->type); i++) {
1734 emit(ir, OPCODE_MOV, l, r);
1735 l.index++;
1736 r.index++;
1737 }
1738 }
1739 }
1740
1741
1742 void
1743 ir_to_mesa_visitor::visit(ir_constant *ir)
1744 {
1745 src_reg src;
1746 GLfloat stack_vals[4] = { 0 };
1747 GLfloat *values = stack_vals;
1748 unsigned int i;
1749
1750 /* Unfortunately, 4 floats is all we can get into
1751 * _mesa_add_unnamed_constant. So, make a temp to store an
1752 * aggregate constant and move each constant value into it. If we
1753 * get lucky, copy propagation will eliminate the extra moves.
1754 */
1755
1756 if (ir->type->base_type == GLSL_TYPE_STRUCT) {
1757 src_reg temp_base = get_temp(ir->type);
1758 dst_reg temp = dst_reg(temp_base);
1759
1760 foreach_iter(exec_list_iterator, iter, ir->components) {
1761 ir_constant *field_value = (ir_constant *)iter.get();
1762 int size = type_size(field_value->type);
1763
1764 assert(size > 0);
1765
1766 field_value->accept(this);
1767 src = this->result;
1768
1769 for (i = 0; i < (unsigned int)size; i++) {
1770 emit(ir, OPCODE_MOV, temp, src);
1771
1772 src.index++;
1773 temp.index++;
1774 }
1775 }
1776 this->result = temp_base;
1777 return;
1778 }
1779
1780 if (ir->type->is_array()) {
1781 src_reg temp_base = get_temp(ir->type);
1782 dst_reg temp = dst_reg(temp_base);
1783 int size = type_size(ir->type->fields.array);
1784
1785 assert(size > 0);
1786
1787 for (i = 0; i < ir->type->length; i++) {
1788 ir->array_elements[i]->accept(this);
1789 src = this->result;
1790 for (int j = 0; j < size; j++) {
1791 emit(ir, OPCODE_MOV, temp, src);
1792
1793 src.index++;
1794 temp.index++;
1795 }
1796 }
1797 this->result = temp_base;
1798 return;
1799 }
1800
1801 if (ir->type->is_matrix()) {
1802 src_reg mat = get_temp(ir->type);
1803 dst_reg mat_column = dst_reg(mat);
1804
1805 for (i = 0; i < ir->type->matrix_columns; i++) {
1806 assert(ir->type->base_type == GLSL_TYPE_FLOAT);
1807 values = &ir->value.f[i * ir->type->vector_elements];
1808
1809 src = src_reg(PROGRAM_CONSTANT, -1, NULL);
1810 src.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1811 values,
1812 ir->type->vector_elements,
1813 &src.swizzle);
1814 emit(ir, OPCODE_MOV, mat_column, src);
1815
1816 mat_column.index++;
1817 }
1818
1819 this->result = mat;
1820 return;
1821 }
1822
1823 src.file = PROGRAM_CONSTANT;
1824 switch (ir->type->base_type) {
1825 case GLSL_TYPE_FLOAT:
1826 values = &ir->value.f[0];
1827 break;
1828 case GLSL_TYPE_UINT:
1829 for (i = 0; i < ir->type->vector_elements; i++) {
1830 values[i] = ir->value.u[i];
1831 }
1832 break;
1833 case GLSL_TYPE_INT:
1834 for (i = 0; i < ir->type->vector_elements; i++) {
1835 values[i] = ir->value.i[i];
1836 }
1837 break;
1838 case GLSL_TYPE_BOOL:
1839 for (i = 0; i < ir->type->vector_elements; i++) {
1840 values[i] = ir->value.b[i];
1841 }
1842 break;
1843 default:
1844 assert(!"Non-float/uint/int/bool constant");
1845 }
1846
1847 this->result = src_reg(PROGRAM_CONSTANT, -1, ir->type);
1848 this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1849 values,
1850 ir->type->vector_elements,
1851 &this->result.swizzle);
1852 }
1853
1854 function_entry *
1855 ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
1856 {
1857 function_entry *entry;
1858
1859 foreach_iter(exec_list_iterator, iter, this->function_signatures) {
1860 entry = (function_entry *)iter.get();
1861
1862 if (entry->sig == sig)
1863 return entry;
1864 }
1865
1866 entry = ralloc(mem_ctx, function_entry);
1867 entry->sig = sig;
1868 entry->sig_id = this->next_signature_id++;
1869 entry->bgn_inst = NULL;
1870
1871 /* Allocate storage for all the parameters. */
1872 foreach_iter(exec_list_iterator, iter, sig->parameters) {
1873 ir_variable *param = (ir_variable *)iter.get();
1874 variable_storage *storage;
1875
1876 storage = find_variable_storage(param);
1877 assert(!storage);
1878
1879 storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
1880 this->next_temp);
1881 this->variables.push_tail(storage);
1882
1883 this->next_temp += type_size(param->type);
1884 }
1885
1886 if (!sig->return_type->is_void()) {
1887 entry->return_reg = get_temp(sig->return_type);
1888 } else {
1889 entry->return_reg = undef_src;
1890 }
1891
1892 this->function_signatures.push_tail(entry);
1893 return entry;
1894 }
1895
1896 void
1897 ir_to_mesa_visitor::visit(ir_call *ir)
1898 {
1899 ir_to_mesa_instruction *call_inst;
1900 ir_function_signature *sig = ir->get_callee();
1901 function_entry *entry = get_function_signature(sig);
1902 int i;
1903
1904 /* Process in parameters. */
1905 exec_list_iterator sig_iter = sig->parameters.iterator();
1906 foreach_iter(exec_list_iterator, iter, *ir) {
1907 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1908 ir_variable *param = (ir_variable *)sig_iter.get();
1909
1910 if (param->mode == ir_var_in ||
1911 param->mode == ir_var_inout) {
1912 variable_storage *storage = find_variable_storage(param);
1913 assert(storage);
1914
1915 param_rval->accept(this);
1916 src_reg r = this->result;
1917
1918 dst_reg l;
1919 l.file = storage->file;
1920 l.index = storage->index;
1921 l.reladdr = NULL;
1922 l.writemask = WRITEMASK_XYZW;
1923 l.cond_mask = COND_TR;
1924
1925 for (i = 0; i < type_size(param->type); i++) {
1926 emit(ir, OPCODE_MOV, l, r);
1927 l.index++;
1928 r.index++;
1929 }
1930 }
1931
1932 sig_iter.next();
1933 }
1934 assert(!sig_iter.has_next());
1935
1936 /* Emit call instruction */
1937 call_inst = emit(ir, OPCODE_CAL);
1938 call_inst->function = entry;
1939
1940 /* Process out parameters. */
1941 sig_iter = sig->parameters.iterator();
1942 foreach_iter(exec_list_iterator, iter, *ir) {
1943 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1944 ir_variable *param = (ir_variable *)sig_iter.get();
1945
1946 if (param->mode == ir_var_out ||
1947 param->mode == ir_var_inout) {
1948 variable_storage *storage = find_variable_storage(param);
1949 assert(storage);
1950
1951 src_reg r;
1952 r.file = storage->file;
1953 r.index = storage->index;
1954 r.reladdr = NULL;
1955 r.swizzle = SWIZZLE_NOOP;
1956 r.negate = 0;
1957
1958 param_rval->accept(this);
1959 dst_reg l = dst_reg(this->result);
1960
1961 for (i = 0; i < type_size(param->type); i++) {
1962 emit(ir, OPCODE_MOV, l, r);
1963 l.index++;
1964 r.index++;
1965 }
1966 }
1967
1968 sig_iter.next();
1969 }
1970 assert(!sig_iter.has_next());
1971
1972 /* Process return value. */
1973 this->result = entry->return_reg;
1974 }
1975
1976 void
1977 ir_to_mesa_visitor::visit(ir_texture *ir)
1978 {
1979 src_reg result_src, coord, lod_info, projector, dx, dy;
1980 dst_reg result_dst, coord_dst;
1981 ir_to_mesa_instruction *inst = NULL;
1982 prog_opcode opcode = OPCODE_NOP;
1983
1984 ir->coordinate->accept(this);
1985
1986 /* Put our coords in a temp. We'll need to modify them for shadow,
1987 * projection, or LOD, so the only case we'd use it as is is if
1988 * we're doing plain old texturing. Mesa IR optimization should
1989 * handle cleaning up our mess in that case.
1990 */
1991 coord = get_temp(glsl_type::vec4_type);
1992 coord_dst = dst_reg(coord);
1993 emit(ir, OPCODE_MOV, coord_dst, this->result);
1994
1995 if (ir->projector) {
1996 ir->projector->accept(this);
1997 projector = this->result;
1998 }
1999
2000 /* Storage for our result. Ideally for an assignment we'd be using
2001 * the actual storage for the result here, instead.
2002 */
2003 result_src = get_temp(glsl_type::vec4_type);
2004 result_dst = dst_reg(result_src);
2005
2006 switch (ir->op) {
2007 case ir_tex:
2008 opcode = OPCODE_TEX;
2009 break;
2010 case ir_txb:
2011 opcode = OPCODE_TXB;
2012 ir->lod_info.bias->accept(this);
2013 lod_info = this->result;
2014 break;
2015 case ir_txl:
2016 opcode = OPCODE_TXL;
2017 ir->lod_info.lod->accept(this);
2018 lod_info = this->result;
2019 break;
2020 case ir_txd:
2021 opcode = OPCODE_TXD;
2022 ir->lod_info.grad.dPdx->accept(this);
2023 dx = this->result;
2024 ir->lod_info.grad.dPdy->accept(this);
2025 dy = this->result;
2026 break;
2027 case ir_txf:
2028 assert(!"GLSL 1.30 features unsupported");
2029 break;
2030 }
2031
2032 if (ir->projector) {
2033 if (opcode == OPCODE_TEX) {
2034 /* Slot the projector in as the last component of the coord. */
2035 coord_dst.writemask = WRITEMASK_W;
2036 emit(ir, OPCODE_MOV, coord_dst, projector);
2037 coord_dst.writemask = WRITEMASK_XYZW;
2038 opcode = OPCODE_TXP;
2039 } else {
2040 src_reg coord_w = coord;
2041 coord_w.swizzle = SWIZZLE_WWWW;
2042
2043 /* For the other TEX opcodes there's no projective version
2044 * since the last slot is taken up by lod info. Do the
2045 * projective divide now.
2046 */
2047 coord_dst.writemask = WRITEMASK_W;
2048 emit(ir, OPCODE_RCP, coord_dst, projector);
2049
2050 /* In the case where we have to project the coordinates "by hand,"
2051 * the shadow comparitor value must also be projected.
2052 */
2053 src_reg tmp_src = coord;
2054 if (ir->shadow_comparitor) {
2055 /* Slot the shadow value in as the second to last component of the
2056 * coord.
2057 */
2058 ir->shadow_comparitor->accept(this);
2059
2060 tmp_src = get_temp(glsl_type::vec4_type);
2061 dst_reg tmp_dst = dst_reg(tmp_src);
2062
2063 tmp_dst.writemask = WRITEMASK_Z;
2064 emit(ir, OPCODE_MOV, tmp_dst, this->result);
2065
2066 tmp_dst.writemask = WRITEMASK_XY;
2067 emit(ir, OPCODE_MOV, tmp_dst, coord);
2068 }
2069
2070 coord_dst.writemask = WRITEMASK_XYZ;
2071 emit(ir, OPCODE_MUL, coord_dst, tmp_src, coord_w);
2072
2073 coord_dst.writemask = WRITEMASK_XYZW;
2074 coord.swizzle = SWIZZLE_XYZW;
2075 }
2076 }
2077
2078 /* If projection is done and the opcode is not OPCODE_TXP, then the shadow
2079 * comparitor was put in the correct place (and projected) by the code,
2080 * above, that handles by-hand projection.
2081 */
2082 if (ir->shadow_comparitor && (!ir->projector || opcode == OPCODE_TXP)) {
2083 /* Slot the shadow value in as the second to last component of the
2084 * coord.
2085 */
2086 ir->shadow_comparitor->accept(this);
2087 coord_dst.writemask = WRITEMASK_Z;
2088 emit(ir, OPCODE_MOV, coord_dst, this->result);
2089 coord_dst.writemask = WRITEMASK_XYZW;
2090 }
2091
2092 if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
2093 /* Mesa IR stores lod or lod bias in the last channel of the coords. */
2094 coord_dst.writemask = WRITEMASK_W;
2095 emit(ir, OPCODE_MOV, coord_dst, lod_info);
2096 coord_dst.writemask = WRITEMASK_XYZW;
2097 }
2098
2099 if (opcode == OPCODE_TXD)
2100 inst = emit(ir, opcode, result_dst, coord, dx, dy);
2101 else
2102 inst = emit(ir, opcode, result_dst, coord);
2103
2104 if (ir->shadow_comparitor)
2105 inst->tex_shadow = GL_TRUE;
2106
2107 inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
2108 this->shader_program,
2109 this->prog);
2110
2111 const glsl_type *sampler_type = ir->sampler->type;
2112
2113 switch (sampler_type->sampler_dimensionality) {
2114 case GLSL_SAMPLER_DIM_1D:
2115 inst->tex_target = (sampler_type->sampler_array)
2116 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
2117 break;
2118 case GLSL_SAMPLER_DIM_2D:
2119 inst->tex_target = (sampler_type->sampler_array)
2120 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
2121 break;
2122 case GLSL_SAMPLER_DIM_3D:
2123 inst->tex_target = TEXTURE_3D_INDEX;
2124 break;
2125 case GLSL_SAMPLER_DIM_CUBE:
2126 inst->tex_target = TEXTURE_CUBE_INDEX;
2127 break;
2128 case GLSL_SAMPLER_DIM_RECT:
2129 inst->tex_target = TEXTURE_RECT_INDEX;
2130 break;
2131 case GLSL_SAMPLER_DIM_BUF:
2132 assert(!"FINISHME: Implement ARB_texture_buffer_object");
2133 break;
2134 default:
2135 assert(!"Should not get here.");
2136 }
2137
2138 this->result = result_src;
2139 }
2140
2141 void
2142 ir_to_mesa_visitor::visit(ir_return *ir)
2143 {
2144 if (ir->get_value()) {
2145 dst_reg l;
2146 int i;
2147
2148 assert(current_function);
2149
2150 ir->get_value()->accept(this);
2151 src_reg r = this->result;
2152
2153 l = dst_reg(current_function->return_reg);
2154
2155 for (i = 0; i < type_size(current_function->sig->return_type); i++) {
2156 emit(ir, OPCODE_MOV, l, r);
2157 l.index++;
2158 r.index++;
2159 }
2160 }
2161
2162 emit(ir, OPCODE_RET);
2163 }
2164
2165 void
2166 ir_to_mesa_visitor::visit(ir_discard *ir)
2167 {
2168 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
2169
2170 if (ir->condition) {
2171 ir->condition->accept(this);
2172 this->result.negate = ~this->result.negate;
2173 emit(ir, OPCODE_KIL, undef_dst, this->result);
2174 } else {
2175 emit(ir, OPCODE_KIL_NV);
2176 }
2177
2178 fp->UsesKill = GL_TRUE;
2179 }
2180
2181 void
2182 ir_to_mesa_visitor::visit(ir_if *ir)
2183 {
2184 ir_to_mesa_instruction *cond_inst, *if_inst;
2185 ir_to_mesa_instruction *prev_inst;
2186
2187 prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2188
2189 ir->condition->accept(this);
2190 assert(this->result.file != PROGRAM_UNDEFINED);
2191
2192 if (this->options->EmitCondCodes) {
2193 cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2194
2195 /* See if we actually generated any instruction for generating
2196 * the condition. If not, then cook up a move to a temp so we
2197 * have something to set cond_update on.
2198 */
2199 if (cond_inst == prev_inst) {
2200 src_reg temp = get_temp(glsl_type::bool_type);
2201 cond_inst = emit(ir->condition, OPCODE_MOV, dst_reg(temp), result);
2202 }
2203 cond_inst->cond_update = GL_TRUE;
2204
2205 if_inst = emit(ir->condition, OPCODE_IF);
2206 if_inst->dst.cond_mask = COND_NE;
2207 } else {
2208 if_inst = emit(ir->condition, OPCODE_IF, undef_dst, this->result);
2209 }
2210
2211 this->instructions.push_tail(if_inst);
2212
2213 visit_exec_list(&ir->then_instructions, this);
2214
2215 if (!ir->else_instructions.is_empty()) {
2216 emit(ir->condition, OPCODE_ELSE);
2217 visit_exec_list(&ir->else_instructions, this);
2218 }
2219
2220 if_inst = emit(ir->condition, OPCODE_ENDIF);
2221 }
2222
2223 ir_to_mesa_visitor::ir_to_mesa_visitor()
2224 {
2225 result.file = PROGRAM_UNDEFINED;
2226 next_temp = 1;
2227 next_signature_id = 1;
2228 current_function = NULL;
2229 mem_ctx = ralloc_context(NULL);
2230 }
2231
2232 ir_to_mesa_visitor::~ir_to_mesa_visitor()
2233 {
2234 ralloc_free(mem_ctx);
2235 }
2236
2237 static struct prog_src_register
2238 mesa_src_reg_from_ir_src_reg(src_reg reg)
2239 {
2240 struct prog_src_register mesa_reg;
2241
2242 mesa_reg.File = reg.file;
2243 assert(reg.index < (1 << INST_INDEX_BITS));
2244 mesa_reg.Index = reg.index;
2245 mesa_reg.Swizzle = reg.swizzle;
2246 mesa_reg.RelAddr = reg.reladdr != NULL;
2247 mesa_reg.Negate = reg.negate;
2248 mesa_reg.Abs = 0;
2249 mesa_reg.HasIndex2 = GL_FALSE;
2250 mesa_reg.RelAddr2 = 0;
2251 mesa_reg.Index2 = 0;
2252
2253 return mesa_reg;
2254 }
2255
2256 static void
2257 set_branchtargets(ir_to_mesa_visitor *v,
2258 struct prog_instruction *mesa_instructions,
2259 int num_instructions)
2260 {
2261 int if_count = 0, loop_count = 0;
2262 int *if_stack, *loop_stack;
2263 int if_stack_pos = 0, loop_stack_pos = 0;
2264 int i, j;
2265
2266 for (i = 0; i < num_instructions; i++) {
2267 switch (mesa_instructions[i].Opcode) {
2268 case OPCODE_IF:
2269 if_count++;
2270 break;
2271 case OPCODE_BGNLOOP:
2272 loop_count++;
2273 break;
2274 case OPCODE_BRK:
2275 case OPCODE_CONT:
2276 mesa_instructions[i].BranchTarget = -1;
2277 break;
2278 default:
2279 break;
2280 }
2281 }
2282
2283 if_stack = rzalloc_array(v->mem_ctx, int, if_count);
2284 loop_stack = rzalloc_array(v->mem_ctx, int, loop_count);
2285
2286 for (i = 0; i < num_instructions; i++) {
2287 switch (mesa_instructions[i].Opcode) {
2288 case OPCODE_IF:
2289 if_stack[if_stack_pos] = i;
2290 if_stack_pos++;
2291 break;
2292 case OPCODE_ELSE:
2293 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2294 if_stack[if_stack_pos - 1] = i;
2295 break;
2296 case OPCODE_ENDIF:
2297 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2298 if_stack_pos--;
2299 break;
2300 case OPCODE_BGNLOOP:
2301 loop_stack[loop_stack_pos] = i;
2302 loop_stack_pos++;
2303 break;
2304 case OPCODE_ENDLOOP:
2305 loop_stack_pos--;
2306 /* Rewrite any breaks/conts at this nesting level (haven't
2307 * already had a BranchTarget assigned) to point to the end
2308 * of the loop.
2309 */
2310 for (j = loop_stack[loop_stack_pos]; j < i; j++) {
2311 if (mesa_instructions[j].Opcode == OPCODE_BRK ||
2312 mesa_instructions[j].Opcode == OPCODE_CONT) {
2313 if (mesa_instructions[j].BranchTarget == -1) {
2314 mesa_instructions[j].BranchTarget = i;
2315 }
2316 }
2317 }
2318 /* The loop ends point at each other. */
2319 mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
2320 mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
2321 break;
2322 case OPCODE_CAL:
2323 foreach_iter(exec_list_iterator, iter, v->function_signatures) {
2324 function_entry *entry = (function_entry *)iter.get();
2325
2326 if (entry->sig_id == mesa_instructions[i].BranchTarget) {
2327 mesa_instructions[i].BranchTarget = entry->inst;
2328 break;
2329 }
2330 }
2331 break;
2332 default:
2333 break;
2334 }
2335 }
2336 }
2337
2338 static void
2339 print_program(struct prog_instruction *mesa_instructions,
2340 ir_instruction **mesa_instruction_annotation,
2341 int num_instructions)
2342 {
2343 ir_instruction *last_ir = NULL;
2344 int i;
2345 int indent = 0;
2346
2347 for (i = 0; i < num_instructions; i++) {
2348 struct prog_instruction *mesa_inst = mesa_instructions + i;
2349 ir_instruction *ir = mesa_instruction_annotation[i];
2350
2351 fprintf(stdout, "%3d: ", i);
2352
2353 if (last_ir != ir && ir) {
2354 int j;
2355
2356 for (j = 0; j < indent; j++) {
2357 fprintf(stdout, " ");
2358 }
2359 ir->print();
2360 printf("\n");
2361 last_ir = ir;
2362
2363 fprintf(stdout, " "); /* line number spacing. */
2364 }
2365
2366 indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
2367 PROG_PRINT_DEBUG, NULL);
2368 }
2369 }
2370
2371
2372 /**
2373 * Count resources used by the given gpu program (number of texture
2374 * samplers, etc).
2375 */
2376 static void
2377 count_resources(struct gl_program *prog)
2378 {
2379 unsigned int i;
2380
2381 prog->SamplersUsed = 0;
2382
2383 for (i = 0; i < prog->NumInstructions; i++) {
2384 struct prog_instruction *inst = &prog->Instructions[i];
2385
2386 if (_mesa_is_tex_instruction(inst->Opcode)) {
2387 prog->SamplerTargets[inst->TexSrcUnit] =
2388 (gl_texture_index)inst->TexSrcTarget;
2389 prog->SamplersUsed |= 1 << inst->TexSrcUnit;
2390 if (inst->TexShadow) {
2391 prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
2392 }
2393 }
2394 }
2395
2396 _mesa_update_shader_textures_used(prog);
2397 }
2398
2399
2400 /**
2401 * Check if the given vertex/fragment/shader program is within the
2402 * resource limits of the context (number of texture units, etc).
2403 * If any of those checks fail, record a linker error.
2404 *
2405 * XXX more checks are needed...
2406 */
2407 static void
2408 check_resources(const struct gl_context *ctx,
2409 struct gl_shader_program *shader_program,
2410 struct gl_program *prog)
2411 {
2412 switch (prog->Target) {
2413 case GL_VERTEX_PROGRAM_ARB:
2414 if (_mesa_bitcount(prog->SamplersUsed) >
2415 ctx->Const.MaxVertexTextureImageUnits) {
2416 fail_link(shader_program, "Too many vertex shader texture samplers");
2417 }
2418 if (prog->Parameters->NumParameters > MAX_UNIFORMS) {
2419 fail_link(shader_program, "Too many vertex shader constants");
2420 }
2421 break;
2422 case MESA_GEOMETRY_PROGRAM:
2423 if (_mesa_bitcount(prog->SamplersUsed) >
2424 ctx->Const.MaxGeometryTextureImageUnits) {
2425 fail_link(shader_program, "Too many geometry shader texture samplers");
2426 }
2427 if (prog->Parameters->NumParameters >
2428 MAX_GEOMETRY_UNIFORM_COMPONENTS / 4) {
2429 fail_link(shader_program, "Too many geometry shader constants");
2430 }
2431 break;
2432 case GL_FRAGMENT_PROGRAM_ARB:
2433 if (_mesa_bitcount(prog->SamplersUsed) >
2434 ctx->Const.MaxTextureImageUnits) {
2435 fail_link(shader_program, "Too many fragment shader texture samplers");
2436 }
2437 if (prog->Parameters->NumParameters > MAX_UNIFORMS) {
2438 fail_link(shader_program, "Too many fragment shader constants");
2439 }
2440 break;
2441 default:
2442 _mesa_problem(ctx, "unexpected program type in check_resources()");
2443 }
2444 }
2445
2446
2447
2448 struct uniform_sort {
2449 struct gl_uniform *u;
2450 int pos;
2451 };
2452
2453 /* The shader_program->Uniforms list is almost sorted in increasing
2454 * uniform->{Frag,Vert}Pos locations, but not quite when there are
2455 * uniforms shared between targets. We need to add parameters in
2456 * increasing order for the targets.
2457 */
2458 static int
2459 sort_uniforms(const void *a, const void *b)
2460 {
2461 struct uniform_sort *u1 = (struct uniform_sort *)a;
2462 struct uniform_sort *u2 = (struct uniform_sort *)b;
2463
2464 return u1->pos - u2->pos;
2465 }
2466
2467 /* Add the uniforms to the parameters. The linker chose locations
2468 * in our parameters lists (which weren't created yet), which the
2469 * uniforms code will use to poke values into our parameters list
2470 * when uniforms are updated.
2471 */
2472 static void
2473 add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
2474 struct gl_shader *shader,
2475 struct gl_program *prog)
2476 {
2477 unsigned int i;
2478 unsigned int next_sampler = 0, num_uniforms = 0;
2479 struct uniform_sort *sorted_uniforms;
2480
2481 sorted_uniforms = ralloc_array(NULL, struct uniform_sort,
2482 shader_program->Uniforms->NumUniforms);
2483
2484 for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
2485 struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
2486 int parameter_index = -1;
2487
2488 switch (shader->Type) {
2489 case GL_VERTEX_SHADER:
2490 parameter_index = uniform->VertPos;
2491 break;
2492 case GL_FRAGMENT_SHADER:
2493 parameter_index = uniform->FragPos;
2494 break;
2495 case GL_GEOMETRY_SHADER:
2496 parameter_index = uniform->GeomPos;
2497 break;
2498 }
2499
2500 /* Only add uniforms used in our target. */
2501 if (parameter_index != -1) {
2502 sorted_uniforms[num_uniforms].pos = parameter_index;
2503 sorted_uniforms[num_uniforms].u = uniform;
2504 num_uniforms++;
2505 }
2506 }
2507
2508 qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
2509 sort_uniforms);
2510
2511 for (i = 0; i < num_uniforms; i++) {
2512 struct gl_uniform *uniform = sorted_uniforms[i].u;
2513 int parameter_index = sorted_uniforms[i].pos;
2514 const glsl_type *type = uniform->Type;
2515 unsigned int size;
2516
2517 if (type->is_vector() ||
2518 type->is_scalar()) {
2519 size = type->vector_elements;
2520 } else {
2521 size = type_size(type) * 4;
2522 }
2523
2524 gl_register_file file;
2525 if (type->is_sampler() ||
2526 (type->is_array() && type->fields.array->is_sampler())) {
2527 file = PROGRAM_SAMPLER;
2528 } else {
2529 file = PROGRAM_UNIFORM;
2530 }
2531
2532 GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
2533 uniform->Name);
2534
2535 if (index < 0) {
2536 index = _mesa_add_parameter(prog->Parameters, file,
2537 uniform->Name, size, type->gl_type,
2538 NULL, NULL, 0x0);
2539
2540 /* Sampler uniform values are stored in prog->SamplerUnits,
2541 * and the entry in that array is selected by this index we
2542 * store in ParameterValues[].
2543 */
2544 if (file == PROGRAM_SAMPLER) {
2545 for (unsigned int j = 0; j < size / 4; j++)
2546 prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
2547 }
2548
2549 /* The location chosen in the Parameters list here (returned
2550 * from _mesa_add_uniform) has to match what the linker chose.
2551 */
2552 if (index != parameter_index) {
2553 fail_link(shader_program, "Allocation of uniform `%s' to target "
2554 "failed (%d vs %d)\n",
2555 uniform->Name, index, parameter_index);
2556 }
2557 }
2558 }
2559
2560 ralloc_free(sorted_uniforms);
2561 }
2562
2563 static void
2564 set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
2565 struct gl_shader_program *shader_program,
2566 const char *name, const glsl_type *type,
2567 ir_constant *val)
2568 {
2569 if (type->is_record()) {
2570 ir_constant *field_constant;
2571
2572 field_constant = (ir_constant *)val->components.get_head();
2573
2574 for (unsigned int i = 0; i < type->length; i++) {
2575 const glsl_type *field_type = type->fields.structure[i].type;
2576 const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
2577 type->fields.structure[i].name);
2578 set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
2579 field_type, field_constant);
2580 field_constant = (ir_constant *)field_constant->next;
2581 }
2582 return;
2583 }
2584
2585 int loc = _mesa_get_uniform_location(ctx, shader_program, name);
2586
2587 if (loc == -1) {
2588 fail_link(shader_program,
2589 "Couldn't find uniform for initializer %s\n", name);
2590 return;
2591 }
2592
2593 for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
2594 ir_constant *element;
2595 const glsl_type *element_type;
2596 if (type->is_array()) {
2597 element = val->array_elements[i];
2598 element_type = type->fields.array;
2599 } else {
2600 element = val;
2601 element_type = type;
2602 }
2603
2604 void *values;
2605
2606 if (element_type->base_type == GLSL_TYPE_BOOL) {
2607 int *conv = ralloc_array(mem_ctx, int, element_type->components());
2608 for (unsigned int j = 0; j < element_type->components(); j++) {
2609 conv[j] = element->value.b[j];
2610 }
2611 values = (void *)conv;
2612 element_type = glsl_type::get_instance(GLSL_TYPE_INT,
2613 element_type->vector_elements,
2614 1);
2615 } else {
2616 values = &element->value;
2617 }
2618
2619 if (element_type->is_matrix()) {
2620 _mesa_uniform_matrix(ctx, shader_program,
2621 element_type->matrix_columns,
2622 element_type->vector_elements,
2623 loc, 1, GL_FALSE, (GLfloat *)values);
2624 loc += element_type->matrix_columns;
2625 } else {
2626 _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
2627 values, element_type->gl_type);
2628 loc += type_size(element_type);
2629 }
2630 }
2631 }
2632
2633 static void
2634 set_uniform_initializers(struct gl_context *ctx,
2635 struct gl_shader_program *shader_program)
2636 {
2637 void *mem_ctx = NULL;
2638
2639 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2640 struct gl_shader *shader = shader_program->_LinkedShaders[i];
2641
2642 if (shader == NULL)
2643 continue;
2644
2645 foreach_iter(exec_list_iterator, iter, *shader->ir) {
2646 ir_instruction *ir = (ir_instruction *)iter.get();
2647 ir_variable *var = ir->as_variable();
2648
2649 if (!var || var->mode != ir_var_uniform || !var->constant_value)
2650 continue;
2651
2652 if (!mem_ctx)
2653 mem_ctx = ralloc_context(NULL);
2654
2655 set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
2656 var->type, var->constant_value);
2657 }
2658 }
2659
2660 ralloc_free(mem_ctx);
2661 }
2662
2663 /*
2664 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
2665 * channels for copy propagation and updates following instructions to
2666 * use the original versions.
2667 *
2668 * The ir_to_mesa_visitor lazily produces code assuming that this pass
2669 * will occur. As an example, a TXP production before this pass:
2670 *
2671 * 0: MOV TEMP[1], INPUT[4].xyyy;
2672 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2673 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
2674 *
2675 * and after:
2676 *
2677 * 0: MOV TEMP[1], INPUT[4].xyyy;
2678 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2679 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
2680 *
2681 * which allows for dead code elimination on TEMP[1]'s writes.
2682 */
2683 void
2684 ir_to_mesa_visitor::copy_propagate(void)
2685 {
2686 ir_to_mesa_instruction **acp = rzalloc_array(mem_ctx,
2687 ir_to_mesa_instruction *,
2688 this->next_temp * 4);
2689 int *acp_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
2690 int level = 0;
2691
2692 foreach_iter(exec_list_iterator, iter, this->instructions) {
2693 ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2694
2695 assert(inst->dst.file != PROGRAM_TEMPORARY
2696 || inst->dst.index < this->next_temp);
2697
2698 /* First, do any copy propagation possible into the src regs. */
2699 for (int r = 0; r < 3; r++) {
2700 ir_to_mesa_instruction *first = NULL;
2701 bool good = true;
2702 int acp_base = inst->src[r].index * 4;
2703
2704 if (inst->src[r].file != PROGRAM_TEMPORARY ||
2705 inst->src[r].reladdr)
2706 continue;
2707
2708 /* See if we can find entries in the ACP consisting of MOVs
2709 * from the same src register for all the swizzled channels
2710 * of this src register reference.
2711 */
2712 for (int i = 0; i < 4; i++) {
2713 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
2714 ir_to_mesa_instruction *copy_chan = acp[acp_base + src_chan];
2715
2716 if (!copy_chan) {
2717 good = false;
2718 break;
2719 }
2720
2721 assert(acp_level[acp_base + src_chan] <= level);
2722
2723 if (!first) {
2724 first = copy_chan;
2725 } else {
2726 if (first->src[0].file != copy_chan->src[0].file ||
2727 first->src[0].index != copy_chan->src[0].index) {
2728 good = false;
2729 break;
2730 }
2731 }
2732 }
2733
2734 if (good) {
2735 /* We've now validated that we can copy-propagate to
2736 * replace this src register reference. Do it.
2737 */
2738 inst->src[r].file = first->src[0].file;
2739 inst->src[r].index = first->src[0].index;
2740
2741 int swizzle = 0;
2742 for (int i = 0; i < 4; i++) {
2743 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
2744 ir_to_mesa_instruction *copy_inst = acp[acp_base + src_chan];
2745 swizzle |= (GET_SWZ(copy_inst->src[0].swizzle, src_chan) <<
2746 (3 * i));
2747 }
2748 inst->src[r].swizzle = swizzle;
2749 }
2750 }
2751
2752 switch (inst->op) {
2753 case OPCODE_BGNLOOP:
2754 case OPCODE_ENDLOOP:
2755 /* End of a basic block, clear the ACP entirely. */
2756 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
2757 break;
2758
2759 case OPCODE_IF:
2760 ++level;
2761 break;
2762
2763 case OPCODE_ENDIF:
2764 case OPCODE_ELSE:
2765 /* Clear all channels written inside the block from the ACP, but
2766 * leaving those that were not touched.
2767 */
2768 for (int r = 0; r < this->next_temp; r++) {
2769 for (int c = 0; c < 4; c++) {
2770 if (!acp[4 * r + c])
2771 continue;
2772
2773 if (acp_level[4 * r + c] >= level)
2774 acp[4 * r + c] = NULL;
2775 }
2776 }
2777 if (inst->op == OPCODE_ENDIF)
2778 --level;
2779 break;
2780
2781 default:
2782 /* Continuing the block, clear any written channels from
2783 * the ACP.
2784 */
2785 if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.reladdr) {
2786 /* Any temporary might be written, so no copy propagation
2787 * across this instruction.
2788 */
2789 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
2790 } else if (inst->dst.file == PROGRAM_OUTPUT &&
2791 inst->dst.reladdr) {
2792 /* Any output might be written, so no copy propagation
2793 * from outputs across this instruction.
2794 */
2795 for (int r = 0; r < this->next_temp; r++) {
2796 for (int c = 0; c < 4; c++) {
2797 if (!acp[4 * r + c])
2798 continue;
2799
2800 if (acp[4 * r + c]->src[0].file == PROGRAM_OUTPUT)
2801 acp[4 * r + c] = NULL;
2802 }
2803 }
2804 } else if (inst->dst.file == PROGRAM_TEMPORARY ||
2805 inst->dst.file == PROGRAM_OUTPUT) {
2806 /* Clear where it's used as dst. */
2807 if (inst->dst.file == PROGRAM_TEMPORARY) {
2808 for (int c = 0; c < 4; c++) {
2809 if (inst->dst.writemask & (1 << c)) {
2810 acp[4 * inst->dst.index + c] = NULL;
2811 }
2812 }
2813 }
2814
2815 /* Clear where it's used as src. */
2816 for (int r = 0; r < this->next_temp; r++) {
2817 for (int c = 0; c < 4; c++) {
2818 if (!acp[4 * r + c])
2819 continue;
2820
2821 int src_chan = GET_SWZ(acp[4 * r + c]->src[0].swizzle, c);
2822
2823 if (acp[4 * r + c]->src[0].file == inst->dst.file &&
2824 acp[4 * r + c]->src[0].index == inst->dst.index &&
2825 inst->dst.writemask & (1 << src_chan))
2826 {
2827 acp[4 * r + c] = NULL;
2828 }
2829 }
2830 }
2831 }
2832 break;
2833 }
2834
2835 /* If this is a copy, add it to the ACP. */
2836 if (inst->op == OPCODE_MOV &&
2837 inst->dst.file == PROGRAM_TEMPORARY &&
2838 !inst->dst.reladdr &&
2839 !inst->saturate &&
2840 !inst->src[0].reladdr &&
2841 !inst->src[0].negate) {
2842 for (int i = 0; i < 4; i++) {
2843 if (inst->dst.writemask & (1 << i)) {
2844 acp[4 * inst->dst.index + i] = inst;
2845 acp_level[4 * inst->dst.index + i] = level;
2846 }
2847 }
2848 }
2849 }
2850
2851 ralloc_free(acp_level);
2852 ralloc_free(acp);
2853 }
2854
2855
2856 /**
2857 * Convert a shader's GLSL IR into a Mesa gl_program.
2858 */
2859 static struct gl_program *
2860 get_mesa_program(struct gl_context *ctx,
2861 struct gl_shader_program *shader_program,
2862 struct gl_shader *shader)
2863 {
2864 ir_to_mesa_visitor v;
2865 struct prog_instruction *mesa_instructions, *mesa_inst;
2866 ir_instruction **mesa_instruction_annotation;
2867 int i;
2868 struct gl_program *prog;
2869 GLenum target;
2870 const char *target_string;
2871 GLboolean progress;
2872 struct gl_shader_compiler_options *options =
2873 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
2874
2875 switch (shader->Type) {
2876 case GL_VERTEX_SHADER:
2877 target = GL_VERTEX_PROGRAM_ARB;
2878 target_string = "vertex";
2879 break;
2880 case GL_FRAGMENT_SHADER:
2881 target = GL_FRAGMENT_PROGRAM_ARB;
2882 target_string = "fragment";
2883 break;
2884 case GL_GEOMETRY_SHADER:
2885 target = GL_GEOMETRY_PROGRAM_NV;
2886 target_string = "geometry";
2887 break;
2888 default:
2889 assert(!"should not be reached");
2890 return NULL;
2891 }
2892
2893 validate_ir_tree(shader->ir);
2894
2895 prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
2896 if (!prog)
2897 return NULL;
2898 prog->Parameters = _mesa_new_parameter_list();
2899 prog->Varying = _mesa_new_parameter_list();
2900 prog->Attributes = _mesa_new_parameter_list();
2901 v.ctx = ctx;
2902 v.prog = prog;
2903 v.shader_program = shader_program;
2904 v.options = options;
2905
2906 add_uniforms_to_parameters_list(shader_program, shader, prog);
2907
2908 /* Emit Mesa IR for main(). */
2909 visit_exec_list(shader->ir, &v);
2910 v.emit(NULL, OPCODE_END);
2911
2912 /* Now emit bodies for any functions that were used. */
2913 do {
2914 progress = GL_FALSE;
2915
2916 foreach_iter(exec_list_iterator, iter, v.function_signatures) {
2917 function_entry *entry = (function_entry *)iter.get();
2918
2919 if (!entry->bgn_inst) {
2920 v.current_function = entry;
2921
2922 entry->bgn_inst = v.emit(NULL, OPCODE_BGNSUB);
2923 entry->bgn_inst->function = entry;
2924
2925 visit_exec_list(&entry->sig->body, &v);
2926
2927 ir_to_mesa_instruction *last;
2928 last = (ir_to_mesa_instruction *)v.instructions.get_tail();
2929 if (last->op != OPCODE_RET)
2930 v.emit(NULL, OPCODE_RET);
2931
2932 ir_to_mesa_instruction *end;
2933 end = v.emit(NULL, OPCODE_ENDSUB);
2934 end->function = entry;
2935
2936 progress = GL_TRUE;
2937 }
2938 }
2939 } while (progress);
2940
2941 prog->NumTemporaries = v.next_temp;
2942
2943 int num_instructions = 0;
2944 foreach_iter(exec_list_iterator, iter, v.instructions) {
2945 num_instructions++;
2946 }
2947
2948 mesa_instructions =
2949 (struct prog_instruction *)calloc(num_instructions,
2950 sizeof(*mesa_instructions));
2951 mesa_instruction_annotation = ralloc_array(v.mem_ctx, ir_instruction *,
2952 num_instructions);
2953
2954 v.copy_propagate();
2955
2956 /* Convert ir_mesa_instructions into prog_instructions.
2957 */
2958 mesa_inst = mesa_instructions;
2959 i = 0;
2960 foreach_iter(exec_list_iterator, iter, v.instructions) {
2961 const ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2962
2963 mesa_inst->Opcode = inst->op;
2964 mesa_inst->CondUpdate = inst->cond_update;
2965 if (inst->saturate)
2966 mesa_inst->SaturateMode = SATURATE_ZERO_ONE;
2967 mesa_inst->DstReg.File = inst->dst.file;
2968 mesa_inst->DstReg.Index = inst->dst.index;
2969 mesa_inst->DstReg.CondMask = inst->dst.cond_mask;
2970 mesa_inst->DstReg.WriteMask = inst->dst.writemask;
2971 mesa_inst->DstReg.RelAddr = inst->dst.reladdr != NULL;
2972 mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src[0]);
2973 mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src[1]);
2974 mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src[2]);
2975 mesa_inst->TexSrcUnit = inst->sampler;
2976 mesa_inst->TexSrcTarget = inst->tex_target;
2977 mesa_inst->TexShadow = inst->tex_shadow;
2978 mesa_instruction_annotation[i] = inst->ir;
2979
2980 /* Set IndirectRegisterFiles. */
2981 if (mesa_inst->DstReg.RelAddr)
2982 prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
2983
2984 /* Update program's bitmask of indirectly accessed register files */
2985 for (unsigned src = 0; src < 3; src++)
2986 if (mesa_inst->SrcReg[src].RelAddr)
2987 prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
2988
2989 if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
2990 fail_link(shader_program, "Couldn't flatten if statement\n");
2991 }
2992
2993 switch (mesa_inst->Opcode) {
2994 case OPCODE_BGNSUB:
2995 inst->function->inst = i;
2996 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2997 break;
2998 case OPCODE_ENDSUB:
2999 mesa_inst->Comment = strdup(inst->function->sig->function_name());
3000 break;
3001 case OPCODE_CAL:
3002 mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
3003 break;
3004 case OPCODE_ARL:
3005 prog->NumAddressRegs = 1;
3006 break;
3007 default:
3008 break;
3009 }
3010
3011 mesa_inst++;
3012 i++;
3013
3014 if (!shader_program->LinkStatus)
3015 break;
3016 }
3017
3018 if (!shader_program->LinkStatus) {
3019 free(mesa_instructions);
3020 _mesa_reference_program(ctx, &shader->Program, NULL);
3021 return NULL;
3022 }
3023
3024 set_branchtargets(&v, mesa_instructions, num_instructions);
3025
3026 if (ctx->Shader.Flags & GLSL_DUMP) {
3027 printf("\n");
3028 printf("GLSL IR for linked %s program %d:\n", target_string,
3029 shader_program->Name);
3030 _mesa_print_ir(shader->ir, NULL);
3031 printf("\n");
3032 printf("\n");
3033 printf("Mesa IR for linked %s program %d:\n", target_string,
3034 shader_program->Name);
3035 print_program(mesa_instructions, mesa_instruction_annotation,
3036 num_instructions);
3037 }
3038
3039 prog->Instructions = mesa_instructions;
3040 prog->NumInstructions = num_instructions;
3041
3042 do_set_program_inouts(shader->ir, prog);
3043 count_resources(prog);
3044
3045 check_resources(ctx, shader_program, prog);
3046
3047 _mesa_reference_program(ctx, &shader->Program, prog);
3048
3049 if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
3050 _mesa_optimize_program(ctx, prog);
3051 }
3052
3053 return prog;
3054 }
3055
3056 extern "C" {
3057
3058 /**
3059 * Link a shader.
3060 * Called via ctx->Driver.LinkShader()
3061 * This actually involves converting GLSL IR into Mesa gl_programs with
3062 * code lowering and other optimizations.
3063 */
3064 GLboolean
3065 _mesa_ir_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
3066 {
3067 assert(prog->LinkStatus);
3068
3069 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
3070 if (prog->_LinkedShaders[i] == NULL)
3071 continue;
3072
3073 bool progress;
3074 exec_list *ir = prog->_LinkedShaders[i]->ir;
3075 const struct gl_shader_compiler_options *options =
3076 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
3077
3078 do {
3079 progress = false;
3080
3081 /* Lowering */
3082 do_mat_op_to_vec(ir);
3083 lower_instructions(ir, (MOD_TO_FRACT | DIV_TO_MUL_RCP | EXP_TO_EXP2
3084 | LOG_TO_LOG2
3085 | ((options->EmitNoPow) ? POW_TO_EXP2 : 0)));
3086
3087 progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
3088
3089 progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
3090
3091 progress = lower_quadop_vector(ir, true) || progress;
3092
3093 if (options->EmitNoIfs) {
3094 progress = lower_discard(ir) || progress;
3095 progress = lower_if_to_cond_assign(ir) || progress;
3096 }
3097
3098 if (options->EmitNoNoise)
3099 progress = lower_noise(ir) || progress;
3100
3101 /* If there are forms of indirect addressing that the driver
3102 * cannot handle, perform the lowering pass.
3103 */
3104 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
3105 || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
3106 progress =
3107 lower_variable_index_to_cond_assign(ir,
3108 options->EmitNoIndirectInput,
3109 options->EmitNoIndirectOutput,
3110 options->EmitNoIndirectTemp,
3111 options->EmitNoIndirectUniform)
3112 || progress;
3113
3114 progress = do_vec_index_to_cond_assign(ir) || progress;
3115 } while (progress);
3116
3117 validate_ir_tree(ir);
3118 }
3119
3120 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
3121 struct gl_program *linked_prog;
3122
3123 if (prog->_LinkedShaders[i] == NULL)
3124 continue;
3125
3126 linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
3127
3128 if (linked_prog) {
3129 bool ok = true;
3130
3131 switch (prog->_LinkedShaders[i]->Type) {
3132 case GL_VERTEX_SHADER:
3133 _mesa_reference_vertprog(ctx, &prog->VertexProgram,
3134 (struct gl_vertex_program *)linked_prog);
3135 ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
3136 linked_prog);
3137 break;
3138 case GL_FRAGMENT_SHADER:
3139 _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
3140 (struct gl_fragment_program *)linked_prog);
3141 ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
3142 linked_prog);
3143 break;
3144 case GL_GEOMETRY_SHADER:
3145 _mesa_reference_geomprog(ctx, &prog->GeometryProgram,
3146 (struct gl_geometry_program *)linked_prog);
3147 ok = ctx->Driver.ProgramStringNotify(ctx, GL_GEOMETRY_PROGRAM_NV,
3148 linked_prog);
3149 break;
3150 }
3151 if (!ok) {
3152 return GL_FALSE;
3153 }
3154 }
3155
3156 _mesa_reference_program(ctx, &linked_prog, NULL);
3157 }
3158
3159 return GL_TRUE;
3160 }
3161
3162
3163 /**
3164 * Compile a GLSL shader. Called via glCompileShader().
3165 */
3166 void
3167 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
3168 {
3169 struct _mesa_glsl_parse_state *state =
3170 new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
3171
3172 const char *source = shader->Source;
3173 /* Check if the user called glCompileShader without first calling
3174 * glShaderSource. This should fail to compile, but not raise a GL_ERROR.
3175 */
3176 if (source == NULL) {
3177 shader->CompileStatus = GL_FALSE;
3178 return;
3179 }
3180
3181 state->error = preprocess(state, &source, &state->info_log,
3182 &ctx->Extensions, ctx->API);
3183
3184 if (ctx->Shader.Flags & GLSL_DUMP) {
3185 printf("GLSL source for %s shader %d:\n",
3186 _mesa_glsl_shader_target_name(state->target), shader->Name);
3187 printf("%s\n", shader->Source);
3188 }
3189
3190 if (!state->error) {
3191 _mesa_glsl_lexer_ctor(state, source);
3192 _mesa_glsl_parse(state);
3193 _mesa_glsl_lexer_dtor(state);
3194 }
3195
3196 ralloc_free(shader->ir);
3197 shader->ir = new(shader) exec_list;
3198 if (!state->error && !state->translation_unit.is_empty())
3199 _mesa_ast_to_hir(shader->ir, state);
3200
3201 if (!state->error && !shader->ir->is_empty()) {
3202 validate_ir_tree(shader->ir);
3203
3204 /* Do some optimization at compile time to reduce shader IR size
3205 * and reduce later work if the same shader is linked multiple times
3206 */
3207 while (do_common_optimization(shader->ir, false, 32))
3208 ;
3209
3210 validate_ir_tree(shader->ir);
3211 }
3212
3213 shader->symbols = state->symbols;
3214
3215 shader->CompileStatus = !state->error;
3216 shader->InfoLog = state->info_log;
3217 shader->Version = state->language_version;
3218 memcpy(shader->builtins_to_link, state->builtins_to_link,
3219 sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
3220 shader->num_builtins_to_link = state->num_builtins_to_link;
3221
3222 if (ctx->Shader.Flags & GLSL_LOG) {
3223 _mesa_write_shader_to_file(shader);
3224 }
3225
3226 if (ctx->Shader.Flags & GLSL_DUMP) {
3227 if (shader->CompileStatus) {
3228 printf("GLSL IR for shader %d:\n", shader->Name);
3229 _mesa_print_ir(shader->ir, NULL);
3230 printf("\n\n");
3231 } else {
3232 printf("GLSL shader %d failed to compile.\n", shader->Name);
3233 }
3234 if (shader->InfoLog && shader->InfoLog[0] != 0) {
3235 printf("GLSL shader %d info log:\n", shader->Name);
3236 printf("%s\n", shader->InfoLog);
3237 }
3238 }
3239
3240 /* Retain any live IR, but trash the rest. */
3241 reparent_ir(shader->ir, shader->ir);
3242
3243 ralloc_free(state);
3244 }
3245
3246
3247 /**
3248 * Link a GLSL shader program. Called via glLinkProgram().
3249 */
3250 void
3251 _mesa_glsl_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
3252 {
3253 unsigned int i;
3254
3255 _mesa_clear_shader_program_data(ctx, prog);
3256
3257 prog->LinkStatus = GL_TRUE;
3258
3259 for (i = 0; i < prog->NumShaders; i++) {
3260 if (!prog->Shaders[i]->CompileStatus) {
3261 fail_link(prog, "linking with uncompiled shader");
3262 prog->LinkStatus = GL_FALSE;
3263 }
3264 }
3265
3266 prog->Varying = _mesa_new_parameter_list();
3267 _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
3268 _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
3269 _mesa_reference_geomprog(ctx, &prog->GeometryProgram, NULL);
3270
3271 if (prog->LinkStatus) {
3272 link_shaders(ctx, prog);
3273 }
3274
3275 if (prog->LinkStatus) {
3276 if (!ctx->Driver.LinkShader(ctx, prog)) {
3277 prog->LinkStatus = GL_FALSE;
3278 }
3279 }
3280
3281 set_uniform_initializers(ctx, prog);
3282
3283 if (ctx->Shader.Flags & GLSL_DUMP) {
3284 if (!prog->LinkStatus) {
3285 printf("GLSL shader program %d failed to link\n", prog->Name);
3286 }
3287
3288 if (prog->InfoLog && prog->InfoLog[0] != 0) {
3289 printf("GLSL shader program %d info log:\n", prog->Name);
3290 printf("%s\n", prog->InfoLog);
3291 }
3292 }
3293 }
3294
3295 } /* extern "C" */