510aeab82da7d9d4a9535d4ad41f71dbed44ad32
[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(ir) ir_dereference_variable(ir->counter);
807
808 if (ir->from != NULL) {
809 assert(ir->counter != NULL);
810
811 ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
812
813 a->accept(this);
814 delete a;
815 }
816
817 emit(NULL, OPCODE_BGNLOOP);
818
819 if (ir->to) {
820 ir_expression *e =
821 new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
822 counter, ir->to);
823 ir_if *if_stmt = new(ir) ir_if(e);
824
825 ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
826
827 if_stmt->then_instructions.push_tail(brk);
828
829 if_stmt->accept(this);
830
831 delete if_stmt;
832 delete e;
833 delete brk;
834 }
835
836 visit_exec_list(&ir->body_instructions, this);
837
838 if (ir->increment) {
839 ir_expression *e =
840 new(ir) ir_expression(ir_binop_add, counter->type,
841 counter, ir->increment);
842
843 ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
844
845 a->accept(this);
846 delete a;
847 delete e;
848 }
849
850 emit(NULL, OPCODE_ENDLOOP);
851 }
852
853 void
854 ir_to_mesa_visitor::visit(ir_loop_jump *ir)
855 {
856 switch (ir->mode) {
857 case ir_loop_jump::jump_break:
858 emit(NULL, OPCODE_BRK);
859 break;
860 case ir_loop_jump::jump_continue:
861 emit(NULL, OPCODE_CONT);
862 break;
863 }
864 }
865
866
867 void
868 ir_to_mesa_visitor::visit(ir_function_signature *ir)
869 {
870 assert(0);
871 (void)ir;
872 }
873
874 void
875 ir_to_mesa_visitor::visit(ir_function *ir)
876 {
877 /* Ignore function bodies other than main() -- we shouldn't see calls to
878 * them since they should all be inlined before we get to ir_to_mesa.
879 */
880 if (strcmp(ir->name, "main") == 0) {
881 const ir_function_signature *sig;
882 exec_list empty;
883
884 sig = ir->matching_signature(&empty);
885
886 assert(sig);
887
888 foreach_iter(exec_list_iterator, iter, sig->body) {
889 ir_instruction *ir = (ir_instruction *)iter.get();
890
891 ir->accept(this);
892 }
893 }
894 }
895
896 GLboolean
897 ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
898 {
899 int nonmul_operand = 1 - mul_operand;
900 src_reg a, b, c;
901
902 ir_expression *expr = ir->operands[mul_operand]->as_expression();
903 if (!expr || expr->operation != ir_binop_mul)
904 return false;
905
906 expr->operands[0]->accept(this);
907 a = this->result;
908 expr->operands[1]->accept(this);
909 b = this->result;
910 ir->operands[nonmul_operand]->accept(this);
911 c = this->result;
912
913 this->result = get_temp(ir->type);
914 emit(ir, OPCODE_MAD, dst_reg(this->result), a, b, c);
915
916 return true;
917 }
918
919 GLboolean
920 ir_to_mesa_visitor::try_emit_sat(ir_expression *ir)
921 {
922 /* Saturates were only introduced to vertex programs in
923 * NV_vertex_program3, so don't give them to drivers in the VP.
924 */
925 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
926 return false;
927
928 ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
929 if (!sat_src)
930 return false;
931
932 sat_src->accept(this);
933 src_reg src = this->result;
934
935 this->result = get_temp(ir->type);
936 ir_to_mesa_instruction *inst;
937 inst = emit(ir, OPCODE_MOV, dst_reg(this->result), src);
938 inst->saturate = true;
939
940 return true;
941 }
942
943 void
944 ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
945 src_reg *reg, int *num_reladdr)
946 {
947 if (!reg->reladdr)
948 return;
949
950 emit(ir, OPCODE_ARL, address_reg, *reg->reladdr);
951
952 if (*num_reladdr != 1) {
953 src_reg temp = get_temp(glsl_type::vec4_type);
954
955 emit(ir, OPCODE_MOV, dst_reg(temp), *reg);
956 *reg = temp;
957 }
958
959 (*num_reladdr)--;
960 }
961
962 void
963 ir_to_mesa_visitor::emit_swz(ir_expression *ir)
964 {
965 /* Assume that the vector operator is in a form compatible with OPCODE_SWZ.
966 * This means that each of the operands is either an immediate value of -1,
967 * 0, or 1, or is a component from one source register (possibly with
968 * negation).
969 */
970 uint8_t components[4] = { 0 };
971 bool negate[4] = { false };
972 ir_variable *var = NULL;
973
974 for (unsigned i = 0; i < ir->type->vector_elements; i++) {
975 ir_rvalue *op = ir->operands[i];
976
977 assert(op->type->is_scalar());
978
979 while (op != NULL) {
980 switch (op->ir_type) {
981 case ir_type_constant: {
982
983 assert(op->type->is_scalar());
984
985 const ir_constant *const c = op->as_constant();
986 if (c->is_one()) {
987 components[i] = SWIZZLE_ONE;
988 } else if (c->is_zero()) {
989 components[i] = SWIZZLE_ZERO;
990 } else if (c->is_negative_one()) {
991 components[i] = SWIZZLE_ONE;
992 negate[i] = true;
993 } else {
994 assert(!"SWZ constant must be 0.0 or 1.0.");
995 }
996
997 op = NULL;
998 break;
999 }
1000
1001 case ir_type_dereference_variable: {
1002 ir_dereference_variable *const deref =
1003 (ir_dereference_variable *) op;
1004
1005 assert((var == NULL) || (deref->var == var));
1006 components[i] = SWIZZLE_X;
1007 var = deref->var;
1008 op = NULL;
1009 break;
1010 }
1011
1012 case ir_type_expression: {
1013 ir_expression *const expr = (ir_expression *) op;
1014
1015 assert(expr->operation == ir_unop_neg);
1016 negate[i] = true;
1017
1018 op = expr->operands[0];
1019 break;
1020 }
1021
1022 case ir_type_swizzle: {
1023 ir_swizzle *const swiz = (ir_swizzle *) op;
1024
1025 components[i] = swiz->mask.x;
1026 op = swiz->val;
1027 break;
1028 }
1029
1030 default:
1031 assert(!"Should not get here.");
1032 return;
1033 }
1034 }
1035 }
1036
1037 assert(var != NULL);
1038
1039 ir_dereference_variable *const deref =
1040 new(mem_ctx) ir_dereference_variable(var);
1041
1042 this->result.file = PROGRAM_UNDEFINED;
1043 deref->accept(this);
1044 if (this->result.file == PROGRAM_UNDEFINED) {
1045 ir_print_visitor v;
1046 printf("Failed to get tree for expression operand:\n");
1047 deref->accept(&v);
1048 exit(1);
1049 }
1050
1051 src_reg src;
1052
1053 src = this->result;
1054 src.swizzle = MAKE_SWIZZLE4(components[0],
1055 components[1],
1056 components[2],
1057 components[3]);
1058 src.negate = ((unsigned(negate[0]) << 0)
1059 | (unsigned(negate[1]) << 1)
1060 | (unsigned(negate[2]) << 2)
1061 | (unsigned(negate[3]) << 3));
1062
1063 /* Storage for our result. Ideally for an assignment we'd be using the
1064 * actual storage for the result here, instead.
1065 */
1066 const src_reg result_src = get_temp(ir->type);
1067 dst_reg result_dst = dst_reg(result_src);
1068
1069 /* Limit writes to the channels that will be used by result_src later.
1070 * This does limit this temp's use as a temporary for multi-instruction
1071 * sequences.
1072 */
1073 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1074
1075 emit(ir, OPCODE_SWZ, result_dst, src);
1076 this->result = result_src;
1077 }
1078
1079 void
1080 ir_to_mesa_visitor::visit(ir_expression *ir)
1081 {
1082 unsigned int operand;
1083 src_reg op[Elements(ir->operands)];
1084 src_reg result_src;
1085 dst_reg result_dst;
1086
1087 /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
1088 */
1089 if (ir->operation == ir_binop_add) {
1090 if (try_emit_mad(ir, 1))
1091 return;
1092 if (try_emit_mad(ir, 0))
1093 return;
1094 }
1095 if (try_emit_sat(ir))
1096 return;
1097
1098 if (ir->operation == ir_quadop_vector) {
1099 this->emit_swz(ir);
1100 return;
1101 }
1102
1103 for (operand = 0; operand < ir->get_num_operands(); operand++) {
1104 this->result.file = PROGRAM_UNDEFINED;
1105 ir->operands[operand]->accept(this);
1106 if (this->result.file == PROGRAM_UNDEFINED) {
1107 ir_print_visitor v;
1108 printf("Failed to get tree for expression operand:\n");
1109 ir->operands[operand]->accept(&v);
1110 exit(1);
1111 }
1112 op[operand] = this->result;
1113
1114 /* Matrix expression operands should have been broken down to vector
1115 * operations already.
1116 */
1117 assert(!ir->operands[operand]->type->is_matrix());
1118 }
1119
1120 int vector_elements = ir->operands[0]->type->vector_elements;
1121 if (ir->operands[1]) {
1122 vector_elements = MAX2(vector_elements,
1123 ir->operands[1]->type->vector_elements);
1124 }
1125
1126 this->result.file = PROGRAM_UNDEFINED;
1127
1128 /* Storage for our result. Ideally for an assignment we'd be using
1129 * the actual storage for the result here, instead.
1130 */
1131 result_src = get_temp(ir->type);
1132 /* convenience for the emit functions below. */
1133 result_dst = dst_reg(result_src);
1134 /* Limit writes to the channels that will be used by result_src later.
1135 * This does limit this temp's use as a temporary for multi-instruction
1136 * sequences.
1137 */
1138 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1139
1140 switch (ir->operation) {
1141 case ir_unop_logic_not:
1142 emit(ir, OPCODE_SEQ, result_dst, op[0], src_reg_for_float(0.0));
1143 break;
1144 case ir_unop_neg:
1145 op[0].negate = ~op[0].negate;
1146 result_src = op[0];
1147 break;
1148 case ir_unop_abs:
1149 emit(ir, OPCODE_ABS, result_dst, op[0]);
1150 break;
1151 case ir_unop_sign:
1152 emit(ir, OPCODE_SSG, result_dst, op[0]);
1153 break;
1154 case ir_unop_rcp:
1155 emit_scalar(ir, OPCODE_RCP, result_dst, op[0]);
1156 break;
1157
1158 case ir_unop_exp2:
1159 emit_scalar(ir, OPCODE_EX2, result_dst, op[0]);
1160 break;
1161 case ir_unop_exp:
1162 case ir_unop_log:
1163 assert(!"not reached: should be handled by ir_explog_to_explog2");
1164 break;
1165 case ir_unop_log2:
1166 emit_scalar(ir, OPCODE_LG2, result_dst, op[0]);
1167 break;
1168 case ir_unop_sin:
1169 emit_scalar(ir, OPCODE_SIN, result_dst, op[0]);
1170 break;
1171 case ir_unop_cos:
1172 emit_scalar(ir, OPCODE_COS, result_dst, op[0]);
1173 break;
1174 case ir_unop_sin_reduced:
1175 emit_scs(ir, OPCODE_SIN, result_dst, op[0]);
1176 break;
1177 case ir_unop_cos_reduced:
1178 emit_scs(ir, OPCODE_COS, result_dst, op[0]);
1179 break;
1180
1181 case ir_unop_dFdx:
1182 emit(ir, OPCODE_DDX, result_dst, op[0]);
1183 break;
1184 case ir_unop_dFdy:
1185 emit(ir, OPCODE_DDY, result_dst, op[0]);
1186 break;
1187
1188 case ir_unop_noise: {
1189 const enum prog_opcode opcode =
1190 prog_opcode(OPCODE_NOISE1
1191 + (ir->operands[0]->type->vector_elements) - 1);
1192 assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
1193
1194 emit(ir, opcode, result_dst, op[0]);
1195 break;
1196 }
1197
1198 case ir_binop_add:
1199 emit(ir, OPCODE_ADD, result_dst, op[0], op[1]);
1200 break;
1201 case ir_binop_sub:
1202 emit(ir, OPCODE_SUB, result_dst, op[0], op[1]);
1203 break;
1204
1205 case ir_binop_mul:
1206 emit(ir, OPCODE_MUL, result_dst, op[0], op[1]);
1207 break;
1208 case ir_binop_div:
1209 assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1210 case ir_binop_mod:
1211 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1212 break;
1213
1214 case ir_binop_less:
1215 emit(ir, OPCODE_SLT, result_dst, op[0], op[1]);
1216 break;
1217 case ir_binop_greater:
1218 emit(ir, OPCODE_SGT, result_dst, op[0], op[1]);
1219 break;
1220 case ir_binop_lequal:
1221 emit(ir, OPCODE_SLE, result_dst, op[0], op[1]);
1222 break;
1223 case ir_binop_gequal:
1224 emit(ir, OPCODE_SGE, result_dst, op[0], op[1]);
1225 break;
1226 case ir_binop_equal:
1227 emit(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1228 break;
1229 case ir_binop_nequal:
1230 emit(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1231 break;
1232 case ir_binop_all_equal:
1233 /* "==" operator producing a scalar boolean. */
1234 if (ir->operands[0]->type->is_vector() ||
1235 ir->operands[1]->type->is_vector()) {
1236 src_reg temp = get_temp(glsl_type::vec4_type);
1237 emit(ir, OPCODE_SNE, dst_reg(temp), op[0], op[1]);
1238 emit_dp(ir, result_dst, temp, temp, vector_elements);
1239 emit(ir, OPCODE_SEQ, result_dst, result_src, src_reg_for_float(0.0));
1240 } else {
1241 emit(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1242 }
1243 break;
1244 case ir_binop_any_nequal:
1245 /* "!=" operator producing a scalar boolean. */
1246 if (ir->operands[0]->type->is_vector() ||
1247 ir->operands[1]->type->is_vector()) {
1248 src_reg temp = get_temp(glsl_type::vec4_type);
1249 emit(ir, OPCODE_SNE, dst_reg(temp), op[0], op[1]);
1250 emit_dp(ir, result_dst, temp, temp, vector_elements);
1251 emit(ir, OPCODE_SNE, result_dst, result_src, src_reg_for_float(0.0));
1252 } else {
1253 emit(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1254 }
1255 break;
1256
1257 case ir_unop_any:
1258 assert(ir->operands[0]->type->is_vector());
1259 emit_dp(ir, result_dst, op[0], op[0],
1260 ir->operands[0]->type->vector_elements);
1261 emit(ir, OPCODE_SNE, result_dst, result_src, src_reg_for_float(0.0));
1262 break;
1263
1264 case ir_binop_logic_xor:
1265 emit(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1266 break;
1267
1268 case ir_binop_logic_or:
1269 /* This could be a saturated add and skip the SNE. */
1270 emit(ir, OPCODE_ADD, result_dst, op[0], op[1]);
1271 emit(ir, OPCODE_SNE, result_dst, result_src, src_reg_for_float(0.0));
1272 break;
1273
1274 case ir_binop_logic_and:
1275 /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
1276 emit(ir, OPCODE_MUL, result_dst, op[0], op[1]);
1277 break;
1278
1279 case ir_binop_dot:
1280 assert(ir->operands[0]->type->is_vector());
1281 assert(ir->operands[0]->type == ir->operands[1]->type);
1282 emit_dp(ir, result_dst, op[0], op[1],
1283 ir->operands[0]->type->vector_elements);
1284 break;
1285
1286 case ir_unop_sqrt:
1287 /* sqrt(x) = x * rsq(x). */
1288 emit_scalar(ir, OPCODE_RSQ, result_dst, op[0]);
1289 emit(ir, OPCODE_MUL, result_dst, result_src, op[0]);
1290 /* For incoming channels <= 0, set the result to 0. */
1291 op[0].negate = ~op[0].negate;
1292 emit(ir, OPCODE_CMP, result_dst,
1293 op[0], result_src, src_reg_for_float(0.0));
1294 break;
1295 case ir_unop_rsq:
1296 emit_scalar(ir, OPCODE_RSQ, result_dst, op[0]);
1297 break;
1298 case ir_unop_i2f:
1299 case ir_unop_b2f:
1300 case ir_unop_b2i:
1301 /* Mesa IR lacks types, ints are stored as truncated floats. */
1302 result_src = op[0];
1303 break;
1304 case ir_unop_f2i:
1305 emit(ir, OPCODE_TRUNC, result_dst, op[0]);
1306 break;
1307 case ir_unop_f2b:
1308 case ir_unop_i2b:
1309 emit(ir, OPCODE_SNE, result_dst,
1310 op[0], src_reg_for_float(0.0));
1311 break;
1312 case ir_unop_trunc:
1313 emit(ir, OPCODE_TRUNC, result_dst, op[0]);
1314 break;
1315 case ir_unop_ceil:
1316 op[0].negate = ~op[0].negate;
1317 emit(ir, OPCODE_FLR, result_dst, op[0]);
1318 result_src.negate = ~result_src.negate;
1319 break;
1320 case ir_unop_floor:
1321 emit(ir, OPCODE_FLR, result_dst, op[0]);
1322 break;
1323 case ir_unop_fract:
1324 emit(ir, OPCODE_FRC, result_dst, op[0]);
1325 break;
1326
1327 case ir_binop_min:
1328 emit(ir, OPCODE_MIN, result_dst, op[0], op[1]);
1329 break;
1330 case ir_binop_max:
1331 emit(ir, OPCODE_MAX, result_dst, op[0], op[1]);
1332 break;
1333 case ir_binop_pow:
1334 emit_scalar(ir, OPCODE_POW, result_dst, op[0], op[1]);
1335 break;
1336
1337 case ir_unop_bit_not:
1338 case ir_unop_u2f:
1339 case ir_binop_lshift:
1340 case ir_binop_rshift:
1341 case ir_binop_bit_and:
1342 case ir_binop_bit_xor:
1343 case ir_binop_bit_or:
1344 case ir_unop_round_even:
1345 assert(!"GLSL 1.30 features unsupported");
1346 break;
1347
1348 case ir_quadop_vector:
1349 /* This operation should have already been handled.
1350 */
1351 assert(!"Should not get here.");
1352 break;
1353 }
1354
1355 this->result = result_src;
1356 }
1357
1358
1359 void
1360 ir_to_mesa_visitor::visit(ir_swizzle *ir)
1361 {
1362 src_reg src;
1363 int i;
1364 int swizzle[4];
1365
1366 /* Note that this is only swizzles in expressions, not those on the left
1367 * hand side of an assignment, which do write masking. See ir_assignment
1368 * for that.
1369 */
1370
1371 ir->val->accept(this);
1372 src = this->result;
1373 assert(src.file != PROGRAM_UNDEFINED);
1374
1375 for (i = 0; i < 4; i++) {
1376 if (i < ir->type->vector_elements) {
1377 switch (i) {
1378 case 0:
1379 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.x);
1380 break;
1381 case 1:
1382 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.y);
1383 break;
1384 case 2:
1385 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.z);
1386 break;
1387 case 3:
1388 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.w);
1389 break;
1390 }
1391 } else {
1392 /* If the type is smaller than a vec4, replicate the last
1393 * channel out.
1394 */
1395 swizzle[i] = swizzle[ir->type->vector_elements - 1];
1396 }
1397 }
1398
1399 src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
1400
1401 this->result = src;
1402 }
1403
1404 void
1405 ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
1406 {
1407 variable_storage *entry = find_variable_storage(ir->var);
1408 ir_variable *var = ir->var;
1409
1410 if (!entry) {
1411 switch (var->mode) {
1412 case ir_var_uniform:
1413 entry = new(mem_ctx) variable_storage(var, PROGRAM_UNIFORM,
1414 var->location);
1415 this->variables.push_tail(entry);
1416 break;
1417 case ir_var_in:
1418 case ir_var_inout:
1419 /* The linker assigns locations for varyings and attributes,
1420 * including deprecated builtins (like gl_Color), user-assign
1421 * generic attributes (glBindVertexLocation), and
1422 * user-defined varyings.
1423 *
1424 * FINISHME: We would hit this path for function arguments. Fix!
1425 */
1426 assert(var->location != -1);
1427 entry = new(mem_ctx) variable_storage(var,
1428 PROGRAM_INPUT,
1429 var->location);
1430 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
1431 var->location >= VERT_ATTRIB_GENERIC0) {
1432 _mesa_add_attribute(this->prog->Attributes,
1433 var->name,
1434 _mesa_sizeof_glsl_type(var->type->gl_type),
1435 var->type->gl_type,
1436 var->location - VERT_ATTRIB_GENERIC0);
1437 }
1438 break;
1439 case ir_var_out:
1440 assert(var->location != -1);
1441 entry = new(mem_ctx) variable_storage(var,
1442 PROGRAM_OUTPUT,
1443 var->location);
1444 break;
1445 case ir_var_system_value:
1446 entry = new(mem_ctx) variable_storage(var,
1447 PROGRAM_SYSTEM_VALUE,
1448 var->location);
1449 break;
1450 case ir_var_auto:
1451 case ir_var_temporary:
1452 entry = new(mem_ctx) variable_storage(var, PROGRAM_TEMPORARY,
1453 this->next_temp);
1454 this->variables.push_tail(entry);
1455
1456 next_temp += type_size(var->type);
1457 break;
1458 }
1459
1460 if (!entry) {
1461 printf("Failed to make storage for %s\n", var->name);
1462 exit(1);
1463 }
1464 }
1465
1466 this->result = src_reg(entry->file, entry->index, var->type);
1467 }
1468
1469 void
1470 ir_to_mesa_visitor::visit(ir_dereference_array *ir)
1471 {
1472 ir_constant *index;
1473 src_reg src;
1474 int element_size = type_size(ir->type);
1475
1476 index = ir->array_index->constant_expression_value();
1477
1478 ir->array->accept(this);
1479 src = this->result;
1480
1481 if (index) {
1482 src.index += index->value.i[0] * element_size;
1483 } else {
1484 /* Variable index array dereference. It eats the "vec4" of the
1485 * base of the array and an index that offsets the Mesa register
1486 * index.
1487 */
1488 ir->array_index->accept(this);
1489
1490 src_reg index_reg;
1491
1492 if (element_size == 1) {
1493 index_reg = this->result;
1494 } else {
1495 index_reg = get_temp(glsl_type::float_type);
1496
1497 emit(ir, OPCODE_MUL, dst_reg(index_reg),
1498 this->result, src_reg_for_float(element_size));
1499 }
1500
1501 src.reladdr = ralloc(mem_ctx, src_reg);
1502 memcpy(src.reladdr, &index_reg, sizeof(index_reg));
1503 }
1504
1505 /* If the type is smaller than a vec4, replicate the last channel out. */
1506 if (ir->type->is_scalar() || ir->type->is_vector())
1507 src.swizzle = swizzle_for_size(ir->type->vector_elements);
1508 else
1509 src.swizzle = SWIZZLE_NOOP;
1510
1511 this->result = src;
1512 }
1513
1514 void
1515 ir_to_mesa_visitor::visit(ir_dereference_record *ir)
1516 {
1517 unsigned int i;
1518 const glsl_type *struct_type = ir->record->type;
1519 int offset = 0;
1520
1521 ir->record->accept(this);
1522
1523 for (i = 0; i < struct_type->length; i++) {
1524 if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
1525 break;
1526 offset += type_size(struct_type->fields.structure[i].type);
1527 }
1528
1529 /* If the type is smaller than a vec4, replicate the last channel out. */
1530 if (ir->type->is_scalar() || ir->type->is_vector())
1531 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
1532 else
1533 this->result.swizzle = SWIZZLE_NOOP;
1534
1535 this->result.index += offset;
1536 }
1537
1538 /**
1539 * We want to be careful in assignment setup to hit the actual storage
1540 * instead of potentially using a temporary like we might with the
1541 * ir_dereference handler.
1542 */
1543 static dst_reg
1544 get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
1545 {
1546 /* The LHS must be a dereference. If the LHS is a variable indexed array
1547 * access of a vector, it must be separated into a series conditional moves
1548 * before reaching this point (see ir_vec_index_to_cond_assign).
1549 */
1550 assert(ir->as_dereference());
1551 ir_dereference_array *deref_array = ir->as_dereference_array();
1552 if (deref_array) {
1553 assert(!deref_array->array->type->is_vector());
1554 }
1555
1556 /* Use the rvalue deref handler for the most part. We'll ignore
1557 * swizzles in it and write swizzles using writemask, though.
1558 */
1559 ir->accept(v);
1560 return dst_reg(v->result);
1561 }
1562
1563 /**
1564 * Process the condition of a conditional assignment
1565 *
1566 * Examines the condition of a conditional assignment to generate the optimal
1567 * first operand of a \c CMP instruction. If the condition is a relational
1568 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
1569 * used as the source for the \c CMP instruction. Otherwise the comparison
1570 * is processed to a boolean result, and the boolean result is used as the
1571 * operand to the CMP instruction.
1572 */
1573 bool
1574 ir_to_mesa_visitor::process_move_condition(ir_rvalue *ir)
1575 {
1576 ir_rvalue *src_ir = ir;
1577 bool negate = true;
1578 bool switch_order = false;
1579
1580 ir_expression *const expr = ir->as_expression();
1581 if ((expr != NULL) && (expr->get_num_operands() == 2)) {
1582 bool zero_on_left = false;
1583
1584 if (expr->operands[0]->is_zero()) {
1585 src_ir = expr->operands[1];
1586 zero_on_left = true;
1587 } else if (expr->operands[1]->is_zero()) {
1588 src_ir = expr->operands[0];
1589 zero_on_left = false;
1590 }
1591
1592 /* a is - 0 + - 0 +
1593 * (a < 0) T F F ( a < 0) T F F
1594 * (0 < a) F F T (-a < 0) F F T
1595 * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
1596 * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
1597 * (a > 0) F F T (-a < 0) F F T
1598 * (0 > a) T F F ( a < 0) T F F
1599 * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
1600 * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
1601 *
1602 * Note that exchanging the order of 0 and 'a' in the comparison simply
1603 * means that the value of 'a' should be negated.
1604 */
1605 if (src_ir != ir) {
1606 switch (expr->operation) {
1607 case ir_binop_less:
1608 switch_order = false;
1609 negate = zero_on_left;
1610 break;
1611
1612 case ir_binop_greater:
1613 switch_order = false;
1614 negate = !zero_on_left;
1615 break;
1616
1617 case ir_binop_lequal:
1618 switch_order = true;
1619 negate = !zero_on_left;
1620 break;
1621
1622 case ir_binop_gequal:
1623 switch_order = true;
1624 negate = zero_on_left;
1625 break;
1626
1627 default:
1628 /* This isn't the right kind of comparison afterall, so make sure
1629 * the whole condition is visited.
1630 */
1631 src_ir = ir;
1632 break;
1633 }
1634 }
1635 }
1636
1637 src_ir->accept(this);
1638
1639 /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
1640 * condition we produced is 0.0 or 1.0. By flipping the sign, we can
1641 * choose which value OPCODE_CMP produces without an extra instruction
1642 * computing the condition.
1643 */
1644 if (negate)
1645 this->result.negate = ~this->result.negate;
1646
1647 return switch_order;
1648 }
1649
1650 void
1651 ir_to_mesa_visitor::visit(ir_assignment *ir)
1652 {
1653 dst_reg l;
1654 src_reg r;
1655 int i;
1656
1657 ir->rhs->accept(this);
1658 r = this->result;
1659
1660 l = get_assignment_lhs(ir->lhs, this);
1661
1662 /* FINISHME: This should really set to the correct maximal writemask for each
1663 * FINISHME: component written (in the loops below). This case can only
1664 * FINISHME: occur for matrices, arrays, and structures.
1665 */
1666 if (ir->write_mask == 0) {
1667 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
1668 l.writemask = WRITEMASK_XYZW;
1669 } else if (ir->lhs->type->is_scalar()) {
1670 /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
1671 * FINISHME: W component of fragment shader output zero, work correctly.
1672 */
1673 l.writemask = WRITEMASK_XYZW;
1674 } else {
1675 int swizzles[4];
1676 int first_enabled_chan = 0;
1677 int rhs_chan = 0;
1678
1679 assert(ir->lhs->type->is_vector());
1680 l.writemask = ir->write_mask;
1681
1682 for (int i = 0; i < 4; i++) {
1683 if (l.writemask & (1 << i)) {
1684 first_enabled_chan = GET_SWZ(r.swizzle, i);
1685 break;
1686 }
1687 }
1688
1689 /* Swizzle a small RHS vector into the channels being written.
1690 *
1691 * glsl ir treats write_mask as dictating how many channels are
1692 * present on the RHS while Mesa IR treats write_mask as just
1693 * showing which channels of the vec4 RHS get written.
1694 */
1695 for (int i = 0; i < 4; i++) {
1696 if (l.writemask & (1 << i))
1697 swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
1698 else
1699 swizzles[i] = first_enabled_chan;
1700 }
1701 r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
1702 swizzles[2], swizzles[3]);
1703 }
1704
1705 assert(l.file != PROGRAM_UNDEFINED);
1706 assert(r.file != PROGRAM_UNDEFINED);
1707
1708 if (ir->condition) {
1709 const bool switch_order = this->process_move_condition(ir->condition);
1710 src_reg condition = this->result;
1711
1712 for (i = 0; i < type_size(ir->lhs->type); i++) {
1713 if (switch_order) {
1714 emit(ir, OPCODE_CMP, l, condition, src_reg(l), r);
1715 } else {
1716 emit(ir, OPCODE_CMP, l, condition, r, src_reg(l));
1717 }
1718
1719 l.index++;
1720 r.index++;
1721 }
1722 } else {
1723 for (i = 0; i < type_size(ir->lhs->type); i++) {
1724 emit(ir, OPCODE_MOV, l, r);
1725 l.index++;
1726 r.index++;
1727 }
1728 }
1729 }
1730
1731
1732 void
1733 ir_to_mesa_visitor::visit(ir_constant *ir)
1734 {
1735 src_reg src;
1736 GLfloat stack_vals[4] = { 0 };
1737 GLfloat *values = stack_vals;
1738 unsigned int i;
1739
1740 /* Unfortunately, 4 floats is all we can get into
1741 * _mesa_add_unnamed_constant. So, make a temp to store an
1742 * aggregate constant and move each constant value into it. If we
1743 * get lucky, copy propagation will eliminate the extra moves.
1744 */
1745
1746 if (ir->type->base_type == GLSL_TYPE_STRUCT) {
1747 src_reg temp_base = get_temp(ir->type);
1748 dst_reg temp = dst_reg(temp_base);
1749
1750 foreach_iter(exec_list_iterator, iter, ir->components) {
1751 ir_constant *field_value = (ir_constant *)iter.get();
1752 int size = type_size(field_value->type);
1753
1754 assert(size > 0);
1755
1756 field_value->accept(this);
1757 src = this->result;
1758
1759 for (i = 0; i < (unsigned int)size; i++) {
1760 emit(ir, OPCODE_MOV, temp, src);
1761
1762 src.index++;
1763 temp.index++;
1764 }
1765 }
1766 this->result = temp_base;
1767 return;
1768 }
1769
1770 if (ir->type->is_array()) {
1771 src_reg temp_base = get_temp(ir->type);
1772 dst_reg temp = dst_reg(temp_base);
1773 int size = type_size(ir->type->fields.array);
1774
1775 assert(size > 0);
1776
1777 for (i = 0; i < ir->type->length; i++) {
1778 ir->array_elements[i]->accept(this);
1779 src = this->result;
1780 for (int j = 0; j < size; j++) {
1781 emit(ir, OPCODE_MOV, temp, src);
1782
1783 src.index++;
1784 temp.index++;
1785 }
1786 }
1787 this->result = temp_base;
1788 return;
1789 }
1790
1791 if (ir->type->is_matrix()) {
1792 src_reg mat = get_temp(ir->type);
1793 dst_reg mat_column = dst_reg(mat);
1794
1795 for (i = 0; i < ir->type->matrix_columns; i++) {
1796 assert(ir->type->base_type == GLSL_TYPE_FLOAT);
1797 values = &ir->value.f[i * ir->type->vector_elements];
1798
1799 src = src_reg(PROGRAM_CONSTANT, -1, NULL);
1800 src.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1801 values,
1802 ir->type->vector_elements,
1803 &src.swizzle);
1804 emit(ir, OPCODE_MOV, mat_column, src);
1805
1806 mat_column.index++;
1807 }
1808
1809 this->result = mat;
1810 return;
1811 }
1812
1813 src.file = PROGRAM_CONSTANT;
1814 switch (ir->type->base_type) {
1815 case GLSL_TYPE_FLOAT:
1816 values = &ir->value.f[0];
1817 break;
1818 case GLSL_TYPE_UINT:
1819 for (i = 0; i < ir->type->vector_elements; i++) {
1820 values[i] = ir->value.u[i];
1821 }
1822 break;
1823 case GLSL_TYPE_INT:
1824 for (i = 0; i < ir->type->vector_elements; i++) {
1825 values[i] = ir->value.i[i];
1826 }
1827 break;
1828 case GLSL_TYPE_BOOL:
1829 for (i = 0; i < ir->type->vector_elements; i++) {
1830 values[i] = ir->value.b[i];
1831 }
1832 break;
1833 default:
1834 assert(!"Non-float/uint/int/bool constant");
1835 }
1836
1837 this->result = src_reg(PROGRAM_CONSTANT, -1, ir->type);
1838 this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1839 values,
1840 ir->type->vector_elements,
1841 &this->result.swizzle);
1842 }
1843
1844 function_entry *
1845 ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
1846 {
1847 function_entry *entry;
1848
1849 foreach_iter(exec_list_iterator, iter, this->function_signatures) {
1850 entry = (function_entry *)iter.get();
1851
1852 if (entry->sig == sig)
1853 return entry;
1854 }
1855
1856 entry = ralloc(mem_ctx, function_entry);
1857 entry->sig = sig;
1858 entry->sig_id = this->next_signature_id++;
1859 entry->bgn_inst = NULL;
1860
1861 /* Allocate storage for all the parameters. */
1862 foreach_iter(exec_list_iterator, iter, sig->parameters) {
1863 ir_variable *param = (ir_variable *)iter.get();
1864 variable_storage *storage;
1865
1866 storage = find_variable_storage(param);
1867 assert(!storage);
1868
1869 storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
1870 this->next_temp);
1871 this->variables.push_tail(storage);
1872
1873 this->next_temp += type_size(param->type);
1874 }
1875
1876 if (!sig->return_type->is_void()) {
1877 entry->return_reg = get_temp(sig->return_type);
1878 } else {
1879 entry->return_reg = undef_src;
1880 }
1881
1882 this->function_signatures.push_tail(entry);
1883 return entry;
1884 }
1885
1886 void
1887 ir_to_mesa_visitor::visit(ir_call *ir)
1888 {
1889 ir_to_mesa_instruction *call_inst;
1890 ir_function_signature *sig = ir->get_callee();
1891 function_entry *entry = get_function_signature(sig);
1892 int i;
1893
1894 /* Process in parameters. */
1895 exec_list_iterator sig_iter = sig->parameters.iterator();
1896 foreach_iter(exec_list_iterator, iter, *ir) {
1897 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1898 ir_variable *param = (ir_variable *)sig_iter.get();
1899
1900 if (param->mode == ir_var_in ||
1901 param->mode == ir_var_inout) {
1902 variable_storage *storage = find_variable_storage(param);
1903 assert(storage);
1904
1905 param_rval->accept(this);
1906 src_reg r = this->result;
1907
1908 dst_reg l;
1909 l.file = storage->file;
1910 l.index = storage->index;
1911 l.reladdr = NULL;
1912 l.writemask = WRITEMASK_XYZW;
1913 l.cond_mask = COND_TR;
1914
1915 for (i = 0; i < type_size(param->type); i++) {
1916 emit(ir, OPCODE_MOV, l, r);
1917 l.index++;
1918 r.index++;
1919 }
1920 }
1921
1922 sig_iter.next();
1923 }
1924 assert(!sig_iter.has_next());
1925
1926 /* Emit call instruction */
1927 call_inst = emit(ir, OPCODE_CAL);
1928 call_inst->function = entry;
1929
1930 /* Process out parameters. */
1931 sig_iter = sig->parameters.iterator();
1932 foreach_iter(exec_list_iterator, iter, *ir) {
1933 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1934 ir_variable *param = (ir_variable *)sig_iter.get();
1935
1936 if (param->mode == ir_var_out ||
1937 param->mode == ir_var_inout) {
1938 variable_storage *storage = find_variable_storage(param);
1939 assert(storage);
1940
1941 src_reg r;
1942 r.file = storage->file;
1943 r.index = storage->index;
1944 r.reladdr = NULL;
1945 r.swizzle = SWIZZLE_NOOP;
1946 r.negate = 0;
1947
1948 param_rval->accept(this);
1949 dst_reg l = dst_reg(this->result);
1950
1951 for (i = 0; i < type_size(param->type); i++) {
1952 emit(ir, OPCODE_MOV, l, r);
1953 l.index++;
1954 r.index++;
1955 }
1956 }
1957
1958 sig_iter.next();
1959 }
1960 assert(!sig_iter.has_next());
1961
1962 /* Process return value. */
1963 this->result = entry->return_reg;
1964 }
1965
1966 void
1967 ir_to_mesa_visitor::visit(ir_texture *ir)
1968 {
1969 src_reg result_src, coord, lod_info, projector, dx, dy;
1970 dst_reg result_dst, coord_dst;
1971 ir_to_mesa_instruction *inst = NULL;
1972 prog_opcode opcode = OPCODE_NOP;
1973
1974 ir->coordinate->accept(this);
1975
1976 /* Put our coords in a temp. We'll need to modify them for shadow,
1977 * projection, or LOD, so the only case we'd use it as is is if
1978 * we're doing plain old texturing. Mesa IR optimization should
1979 * handle cleaning up our mess in that case.
1980 */
1981 coord = get_temp(glsl_type::vec4_type);
1982 coord_dst = dst_reg(coord);
1983 emit(ir, OPCODE_MOV, coord_dst, this->result);
1984
1985 if (ir->projector) {
1986 ir->projector->accept(this);
1987 projector = this->result;
1988 }
1989
1990 /* Storage for our result. Ideally for an assignment we'd be using
1991 * the actual storage for the result here, instead.
1992 */
1993 result_src = get_temp(glsl_type::vec4_type);
1994 result_dst = dst_reg(result_src);
1995
1996 switch (ir->op) {
1997 case ir_tex:
1998 opcode = OPCODE_TEX;
1999 break;
2000 case ir_txb:
2001 opcode = OPCODE_TXB;
2002 ir->lod_info.bias->accept(this);
2003 lod_info = this->result;
2004 break;
2005 case ir_txl:
2006 opcode = OPCODE_TXL;
2007 ir->lod_info.lod->accept(this);
2008 lod_info = this->result;
2009 break;
2010 case ir_txd:
2011 opcode = OPCODE_TXD;
2012 ir->lod_info.grad.dPdx->accept(this);
2013 dx = this->result;
2014 ir->lod_info.grad.dPdy->accept(this);
2015 dy = this->result;
2016 break;
2017 case ir_txf:
2018 assert(!"GLSL 1.30 features unsupported");
2019 break;
2020 }
2021
2022 if (ir->projector) {
2023 if (opcode == OPCODE_TEX) {
2024 /* Slot the projector in as the last component of the coord. */
2025 coord_dst.writemask = WRITEMASK_W;
2026 emit(ir, OPCODE_MOV, coord_dst, projector);
2027 coord_dst.writemask = WRITEMASK_XYZW;
2028 opcode = OPCODE_TXP;
2029 } else {
2030 src_reg coord_w = coord;
2031 coord_w.swizzle = SWIZZLE_WWWW;
2032
2033 /* For the other TEX opcodes there's no projective version
2034 * since the last slot is taken up by lod info. Do the
2035 * projective divide now.
2036 */
2037 coord_dst.writemask = WRITEMASK_W;
2038 emit(ir, OPCODE_RCP, coord_dst, projector);
2039
2040 /* In the case where we have to project the coordinates "by hand,"
2041 * the shadow comparitor value must also be projected.
2042 */
2043 src_reg tmp_src = coord;
2044 if (ir->shadow_comparitor) {
2045 /* Slot the shadow value in as the second to last component of the
2046 * coord.
2047 */
2048 ir->shadow_comparitor->accept(this);
2049
2050 tmp_src = get_temp(glsl_type::vec4_type);
2051 dst_reg tmp_dst = dst_reg(tmp_src);
2052
2053 tmp_dst.writemask = WRITEMASK_Z;
2054 emit(ir, OPCODE_MOV, tmp_dst, this->result);
2055
2056 tmp_dst.writemask = WRITEMASK_XY;
2057 emit(ir, OPCODE_MOV, tmp_dst, coord);
2058 }
2059
2060 coord_dst.writemask = WRITEMASK_XYZ;
2061 emit(ir, OPCODE_MUL, coord_dst, tmp_src, coord_w);
2062
2063 coord_dst.writemask = WRITEMASK_XYZW;
2064 coord.swizzle = SWIZZLE_XYZW;
2065 }
2066 }
2067
2068 /* If projection is done and the opcode is not OPCODE_TXP, then the shadow
2069 * comparitor was put in the correct place (and projected) by the code,
2070 * above, that handles by-hand projection.
2071 */
2072 if (ir->shadow_comparitor && (!ir->projector || opcode == OPCODE_TXP)) {
2073 /* Slot the shadow value in as the second to last component of the
2074 * coord.
2075 */
2076 ir->shadow_comparitor->accept(this);
2077 coord_dst.writemask = WRITEMASK_Z;
2078 emit(ir, OPCODE_MOV, coord_dst, this->result);
2079 coord_dst.writemask = WRITEMASK_XYZW;
2080 }
2081
2082 if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
2083 /* Mesa IR stores lod or lod bias in the last channel of the coords. */
2084 coord_dst.writemask = WRITEMASK_W;
2085 emit(ir, OPCODE_MOV, coord_dst, lod_info);
2086 coord_dst.writemask = WRITEMASK_XYZW;
2087 }
2088
2089 if (opcode == OPCODE_TXD)
2090 inst = emit(ir, opcode, result_dst, coord, dx, dy);
2091 else
2092 inst = emit(ir, opcode, result_dst, coord);
2093
2094 if (ir->shadow_comparitor)
2095 inst->tex_shadow = GL_TRUE;
2096
2097 inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
2098 this->shader_program,
2099 this->prog);
2100
2101 const glsl_type *sampler_type = ir->sampler->type;
2102
2103 switch (sampler_type->sampler_dimensionality) {
2104 case GLSL_SAMPLER_DIM_1D:
2105 inst->tex_target = (sampler_type->sampler_array)
2106 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
2107 break;
2108 case GLSL_SAMPLER_DIM_2D:
2109 inst->tex_target = (sampler_type->sampler_array)
2110 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
2111 break;
2112 case GLSL_SAMPLER_DIM_3D:
2113 inst->tex_target = TEXTURE_3D_INDEX;
2114 break;
2115 case GLSL_SAMPLER_DIM_CUBE:
2116 inst->tex_target = TEXTURE_CUBE_INDEX;
2117 break;
2118 case GLSL_SAMPLER_DIM_RECT:
2119 inst->tex_target = TEXTURE_RECT_INDEX;
2120 break;
2121 case GLSL_SAMPLER_DIM_BUF:
2122 assert(!"FINISHME: Implement ARB_texture_buffer_object");
2123 break;
2124 default:
2125 assert(!"Should not get here.");
2126 }
2127
2128 this->result = result_src;
2129 }
2130
2131 void
2132 ir_to_mesa_visitor::visit(ir_return *ir)
2133 {
2134 if (ir->get_value()) {
2135 dst_reg l;
2136 int i;
2137
2138 assert(current_function);
2139
2140 ir->get_value()->accept(this);
2141 src_reg r = this->result;
2142
2143 l = dst_reg(current_function->return_reg);
2144
2145 for (i = 0; i < type_size(current_function->sig->return_type); i++) {
2146 emit(ir, OPCODE_MOV, l, r);
2147 l.index++;
2148 r.index++;
2149 }
2150 }
2151
2152 emit(ir, OPCODE_RET);
2153 }
2154
2155 void
2156 ir_to_mesa_visitor::visit(ir_discard *ir)
2157 {
2158 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
2159
2160 if (ir->condition) {
2161 ir->condition->accept(this);
2162 this->result.negate = ~this->result.negate;
2163 emit(ir, OPCODE_KIL, undef_dst, this->result);
2164 } else {
2165 emit(ir, OPCODE_KIL_NV);
2166 }
2167
2168 fp->UsesKill = GL_TRUE;
2169 }
2170
2171 void
2172 ir_to_mesa_visitor::visit(ir_if *ir)
2173 {
2174 ir_to_mesa_instruction *cond_inst, *if_inst;
2175 ir_to_mesa_instruction *prev_inst;
2176
2177 prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2178
2179 ir->condition->accept(this);
2180 assert(this->result.file != PROGRAM_UNDEFINED);
2181
2182 if (this->options->EmitCondCodes) {
2183 cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2184
2185 /* See if we actually generated any instruction for generating
2186 * the condition. If not, then cook up a move to a temp so we
2187 * have something to set cond_update on.
2188 */
2189 if (cond_inst == prev_inst) {
2190 src_reg temp = get_temp(glsl_type::bool_type);
2191 cond_inst = emit(ir->condition, OPCODE_MOV, dst_reg(temp), result);
2192 }
2193 cond_inst->cond_update = GL_TRUE;
2194
2195 if_inst = emit(ir->condition, OPCODE_IF);
2196 if_inst->dst.cond_mask = COND_NE;
2197 } else {
2198 if_inst = emit(ir->condition, OPCODE_IF, undef_dst, this->result);
2199 }
2200
2201 this->instructions.push_tail(if_inst);
2202
2203 visit_exec_list(&ir->then_instructions, this);
2204
2205 if (!ir->else_instructions.is_empty()) {
2206 emit(ir->condition, OPCODE_ELSE);
2207 visit_exec_list(&ir->else_instructions, this);
2208 }
2209
2210 if_inst = emit(ir->condition, OPCODE_ENDIF);
2211 }
2212
2213 ir_to_mesa_visitor::ir_to_mesa_visitor()
2214 {
2215 result.file = PROGRAM_UNDEFINED;
2216 next_temp = 1;
2217 next_signature_id = 1;
2218 current_function = NULL;
2219 mem_ctx = ralloc_context(NULL);
2220 }
2221
2222 ir_to_mesa_visitor::~ir_to_mesa_visitor()
2223 {
2224 ralloc_free(mem_ctx);
2225 }
2226
2227 static struct prog_src_register
2228 mesa_src_reg_from_ir_src_reg(src_reg reg)
2229 {
2230 struct prog_src_register mesa_reg;
2231
2232 mesa_reg.File = reg.file;
2233 assert(reg.index < (1 << INST_INDEX_BITS));
2234 mesa_reg.Index = reg.index;
2235 mesa_reg.Swizzle = reg.swizzle;
2236 mesa_reg.RelAddr = reg.reladdr != NULL;
2237 mesa_reg.Negate = reg.negate;
2238 mesa_reg.Abs = 0;
2239 mesa_reg.HasIndex2 = GL_FALSE;
2240 mesa_reg.RelAddr2 = 0;
2241 mesa_reg.Index2 = 0;
2242
2243 return mesa_reg;
2244 }
2245
2246 static void
2247 set_branchtargets(ir_to_mesa_visitor *v,
2248 struct prog_instruction *mesa_instructions,
2249 int num_instructions)
2250 {
2251 int if_count = 0, loop_count = 0;
2252 int *if_stack, *loop_stack;
2253 int if_stack_pos = 0, loop_stack_pos = 0;
2254 int i, j;
2255
2256 for (i = 0; i < num_instructions; i++) {
2257 switch (mesa_instructions[i].Opcode) {
2258 case OPCODE_IF:
2259 if_count++;
2260 break;
2261 case OPCODE_BGNLOOP:
2262 loop_count++;
2263 break;
2264 case OPCODE_BRK:
2265 case OPCODE_CONT:
2266 mesa_instructions[i].BranchTarget = -1;
2267 break;
2268 default:
2269 break;
2270 }
2271 }
2272
2273 if_stack = rzalloc_array(v->mem_ctx, int, if_count);
2274 loop_stack = rzalloc_array(v->mem_ctx, int, loop_count);
2275
2276 for (i = 0; i < num_instructions; i++) {
2277 switch (mesa_instructions[i].Opcode) {
2278 case OPCODE_IF:
2279 if_stack[if_stack_pos] = i;
2280 if_stack_pos++;
2281 break;
2282 case OPCODE_ELSE:
2283 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2284 if_stack[if_stack_pos - 1] = i;
2285 break;
2286 case OPCODE_ENDIF:
2287 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2288 if_stack_pos--;
2289 break;
2290 case OPCODE_BGNLOOP:
2291 loop_stack[loop_stack_pos] = i;
2292 loop_stack_pos++;
2293 break;
2294 case OPCODE_ENDLOOP:
2295 loop_stack_pos--;
2296 /* Rewrite any breaks/conts at this nesting level (haven't
2297 * already had a BranchTarget assigned) to point to the end
2298 * of the loop.
2299 */
2300 for (j = loop_stack[loop_stack_pos]; j < i; j++) {
2301 if (mesa_instructions[j].Opcode == OPCODE_BRK ||
2302 mesa_instructions[j].Opcode == OPCODE_CONT) {
2303 if (mesa_instructions[j].BranchTarget == -1) {
2304 mesa_instructions[j].BranchTarget = i;
2305 }
2306 }
2307 }
2308 /* The loop ends point at each other. */
2309 mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
2310 mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
2311 break;
2312 case OPCODE_CAL:
2313 foreach_iter(exec_list_iterator, iter, v->function_signatures) {
2314 function_entry *entry = (function_entry *)iter.get();
2315
2316 if (entry->sig_id == mesa_instructions[i].BranchTarget) {
2317 mesa_instructions[i].BranchTarget = entry->inst;
2318 break;
2319 }
2320 }
2321 break;
2322 default:
2323 break;
2324 }
2325 }
2326 }
2327
2328 static void
2329 print_program(struct prog_instruction *mesa_instructions,
2330 ir_instruction **mesa_instruction_annotation,
2331 int num_instructions)
2332 {
2333 ir_instruction *last_ir = NULL;
2334 int i;
2335 int indent = 0;
2336
2337 for (i = 0; i < num_instructions; i++) {
2338 struct prog_instruction *mesa_inst = mesa_instructions + i;
2339 ir_instruction *ir = mesa_instruction_annotation[i];
2340
2341 fprintf(stdout, "%3d: ", i);
2342
2343 if (last_ir != ir && ir) {
2344 int j;
2345
2346 for (j = 0; j < indent; j++) {
2347 fprintf(stdout, " ");
2348 }
2349 ir->print();
2350 printf("\n");
2351 last_ir = ir;
2352
2353 fprintf(stdout, " "); /* line number spacing. */
2354 }
2355
2356 indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
2357 PROG_PRINT_DEBUG, NULL);
2358 }
2359 }
2360
2361
2362 /**
2363 * Count resources used by the given gpu program (number of texture
2364 * samplers, etc).
2365 */
2366 static void
2367 count_resources(struct gl_program *prog)
2368 {
2369 unsigned int i;
2370
2371 prog->SamplersUsed = 0;
2372
2373 for (i = 0; i < prog->NumInstructions; i++) {
2374 struct prog_instruction *inst = &prog->Instructions[i];
2375
2376 if (_mesa_is_tex_instruction(inst->Opcode)) {
2377 prog->SamplerTargets[inst->TexSrcUnit] =
2378 (gl_texture_index)inst->TexSrcTarget;
2379 prog->SamplersUsed |= 1 << inst->TexSrcUnit;
2380 if (inst->TexShadow) {
2381 prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
2382 }
2383 }
2384 }
2385
2386 _mesa_update_shader_textures_used(prog);
2387 }
2388
2389
2390 /**
2391 * Check if the given vertex/fragment/shader program is within the
2392 * resource limits of the context (number of texture units, etc).
2393 * If any of those checks fail, record a linker error.
2394 *
2395 * XXX more checks are needed...
2396 */
2397 static void
2398 check_resources(const struct gl_context *ctx,
2399 struct gl_shader_program *shader_program,
2400 struct gl_program *prog)
2401 {
2402 switch (prog->Target) {
2403 case GL_VERTEX_PROGRAM_ARB:
2404 if (_mesa_bitcount(prog->SamplersUsed) >
2405 ctx->Const.MaxVertexTextureImageUnits) {
2406 fail_link(shader_program, "Too many vertex shader texture samplers");
2407 }
2408 if (prog->Parameters->NumParameters > MAX_UNIFORMS) {
2409 fail_link(shader_program, "Too many vertex shader constants");
2410 }
2411 break;
2412 case MESA_GEOMETRY_PROGRAM:
2413 if (_mesa_bitcount(prog->SamplersUsed) >
2414 ctx->Const.MaxGeometryTextureImageUnits) {
2415 fail_link(shader_program, "Too many geometry shader texture samplers");
2416 }
2417 if (prog->Parameters->NumParameters >
2418 MAX_GEOMETRY_UNIFORM_COMPONENTS / 4) {
2419 fail_link(shader_program, "Too many geometry shader constants");
2420 }
2421 break;
2422 case GL_FRAGMENT_PROGRAM_ARB:
2423 if (_mesa_bitcount(prog->SamplersUsed) >
2424 ctx->Const.MaxTextureImageUnits) {
2425 fail_link(shader_program, "Too many fragment shader texture samplers");
2426 }
2427 if (prog->Parameters->NumParameters > MAX_UNIFORMS) {
2428 fail_link(shader_program, "Too many fragment shader constants");
2429 }
2430 break;
2431 default:
2432 _mesa_problem(ctx, "unexpected program type in check_resources()");
2433 }
2434 }
2435
2436
2437
2438 struct uniform_sort {
2439 struct gl_uniform *u;
2440 int pos;
2441 };
2442
2443 /* The shader_program->Uniforms list is almost sorted in increasing
2444 * uniform->{Frag,Vert}Pos locations, but not quite when there are
2445 * uniforms shared between targets. We need to add parameters in
2446 * increasing order for the targets.
2447 */
2448 static int
2449 sort_uniforms(const void *a, const void *b)
2450 {
2451 struct uniform_sort *u1 = (struct uniform_sort *)a;
2452 struct uniform_sort *u2 = (struct uniform_sort *)b;
2453
2454 return u1->pos - u2->pos;
2455 }
2456
2457 /* Add the uniforms to the parameters. The linker chose locations
2458 * in our parameters lists (which weren't created yet), which the
2459 * uniforms code will use to poke values into our parameters list
2460 * when uniforms are updated.
2461 */
2462 static void
2463 add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
2464 struct gl_shader *shader,
2465 struct gl_program *prog)
2466 {
2467 unsigned int i;
2468 unsigned int next_sampler = 0, num_uniforms = 0;
2469 struct uniform_sort *sorted_uniforms;
2470
2471 sorted_uniforms = ralloc_array(NULL, struct uniform_sort,
2472 shader_program->Uniforms->NumUniforms);
2473
2474 for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
2475 struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
2476 int parameter_index = -1;
2477
2478 switch (shader->Type) {
2479 case GL_VERTEX_SHADER:
2480 parameter_index = uniform->VertPos;
2481 break;
2482 case GL_FRAGMENT_SHADER:
2483 parameter_index = uniform->FragPos;
2484 break;
2485 case GL_GEOMETRY_SHADER:
2486 parameter_index = uniform->GeomPos;
2487 break;
2488 }
2489
2490 /* Only add uniforms used in our target. */
2491 if (parameter_index != -1) {
2492 sorted_uniforms[num_uniforms].pos = parameter_index;
2493 sorted_uniforms[num_uniforms].u = uniform;
2494 num_uniforms++;
2495 }
2496 }
2497
2498 qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
2499 sort_uniforms);
2500
2501 for (i = 0; i < num_uniforms; i++) {
2502 struct gl_uniform *uniform = sorted_uniforms[i].u;
2503 int parameter_index = sorted_uniforms[i].pos;
2504 const glsl_type *type = uniform->Type;
2505 unsigned int size;
2506
2507 if (type->is_vector() ||
2508 type->is_scalar()) {
2509 size = type->vector_elements;
2510 } else {
2511 size = type_size(type) * 4;
2512 }
2513
2514 gl_register_file file;
2515 if (type->is_sampler() ||
2516 (type->is_array() && type->fields.array->is_sampler())) {
2517 file = PROGRAM_SAMPLER;
2518 } else {
2519 file = PROGRAM_UNIFORM;
2520 }
2521
2522 GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
2523 uniform->Name);
2524
2525 if (index < 0) {
2526 index = _mesa_add_parameter(prog->Parameters, file,
2527 uniform->Name, size, type->gl_type,
2528 NULL, NULL, 0x0);
2529
2530 /* Sampler uniform values are stored in prog->SamplerUnits,
2531 * and the entry in that array is selected by this index we
2532 * store in ParameterValues[].
2533 */
2534 if (file == PROGRAM_SAMPLER) {
2535 for (unsigned int j = 0; j < size / 4; j++)
2536 prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
2537 }
2538
2539 /* The location chosen in the Parameters list here (returned
2540 * from _mesa_add_uniform) has to match what the linker chose.
2541 */
2542 if (index != parameter_index) {
2543 fail_link(shader_program, "Allocation of uniform `%s' to target "
2544 "failed (%d vs %d)\n",
2545 uniform->Name, index, parameter_index);
2546 }
2547 }
2548 }
2549
2550 ralloc_free(sorted_uniforms);
2551 }
2552
2553 static void
2554 set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
2555 struct gl_shader_program *shader_program,
2556 const char *name, const glsl_type *type,
2557 ir_constant *val)
2558 {
2559 if (type->is_record()) {
2560 ir_constant *field_constant;
2561
2562 field_constant = (ir_constant *)val->components.get_head();
2563
2564 for (unsigned int i = 0; i < type->length; i++) {
2565 const glsl_type *field_type = type->fields.structure[i].type;
2566 const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
2567 type->fields.structure[i].name);
2568 set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
2569 field_type, field_constant);
2570 field_constant = (ir_constant *)field_constant->next;
2571 }
2572 return;
2573 }
2574
2575 int loc = _mesa_get_uniform_location(ctx, shader_program, name);
2576
2577 if (loc == -1) {
2578 fail_link(shader_program,
2579 "Couldn't find uniform for initializer %s\n", name);
2580 return;
2581 }
2582
2583 for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
2584 ir_constant *element;
2585 const glsl_type *element_type;
2586 if (type->is_array()) {
2587 element = val->array_elements[i];
2588 element_type = type->fields.array;
2589 } else {
2590 element = val;
2591 element_type = type;
2592 }
2593
2594 void *values;
2595
2596 if (element_type->base_type == GLSL_TYPE_BOOL) {
2597 int *conv = ralloc_array(mem_ctx, int, element_type->components());
2598 for (unsigned int j = 0; j < element_type->components(); j++) {
2599 conv[j] = element->value.b[j];
2600 }
2601 values = (void *)conv;
2602 element_type = glsl_type::get_instance(GLSL_TYPE_INT,
2603 element_type->vector_elements,
2604 1);
2605 } else {
2606 values = &element->value;
2607 }
2608
2609 if (element_type->is_matrix()) {
2610 _mesa_uniform_matrix(ctx, shader_program,
2611 element_type->matrix_columns,
2612 element_type->vector_elements,
2613 loc, 1, GL_FALSE, (GLfloat *)values);
2614 loc += element_type->matrix_columns;
2615 } else {
2616 _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
2617 values, element_type->gl_type);
2618 loc += type_size(element_type);
2619 }
2620 }
2621 }
2622
2623 static void
2624 set_uniform_initializers(struct gl_context *ctx,
2625 struct gl_shader_program *shader_program)
2626 {
2627 void *mem_ctx = NULL;
2628
2629 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2630 struct gl_shader *shader = shader_program->_LinkedShaders[i];
2631
2632 if (shader == NULL)
2633 continue;
2634
2635 foreach_iter(exec_list_iterator, iter, *shader->ir) {
2636 ir_instruction *ir = (ir_instruction *)iter.get();
2637 ir_variable *var = ir->as_variable();
2638
2639 if (!var || var->mode != ir_var_uniform || !var->constant_value)
2640 continue;
2641
2642 if (!mem_ctx)
2643 mem_ctx = ralloc_context(NULL);
2644
2645 set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
2646 var->type, var->constant_value);
2647 }
2648 }
2649
2650 ralloc_free(mem_ctx);
2651 }
2652
2653 /*
2654 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
2655 * channels for copy propagation and updates following instructions to
2656 * use the original versions.
2657 *
2658 * The ir_to_mesa_visitor lazily produces code assuming that this pass
2659 * will occur. As an example, a TXP production before this pass:
2660 *
2661 * 0: MOV TEMP[1], INPUT[4].xyyy;
2662 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2663 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
2664 *
2665 * and after:
2666 *
2667 * 0: MOV TEMP[1], INPUT[4].xyyy;
2668 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2669 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
2670 *
2671 * which allows for dead code elimination on TEMP[1]'s writes.
2672 */
2673 void
2674 ir_to_mesa_visitor::copy_propagate(void)
2675 {
2676 ir_to_mesa_instruction **acp = rzalloc_array(mem_ctx,
2677 ir_to_mesa_instruction *,
2678 this->next_temp * 4);
2679 int *acp_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
2680 int level = 0;
2681
2682 foreach_iter(exec_list_iterator, iter, this->instructions) {
2683 ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2684
2685 assert(inst->dst.file != PROGRAM_TEMPORARY
2686 || inst->dst.index < this->next_temp);
2687
2688 /* First, do any copy propagation possible into the src regs. */
2689 for (int r = 0; r < 3; r++) {
2690 ir_to_mesa_instruction *first = NULL;
2691 bool good = true;
2692 int acp_base = inst->src[r].index * 4;
2693
2694 if (inst->src[r].file != PROGRAM_TEMPORARY ||
2695 inst->src[r].reladdr)
2696 continue;
2697
2698 /* See if we can find entries in the ACP consisting of MOVs
2699 * from the same src register for all the swizzled channels
2700 * of this src register reference.
2701 */
2702 for (int i = 0; i < 4; i++) {
2703 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
2704 ir_to_mesa_instruction *copy_chan = acp[acp_base + src_chan];
2705
2706 if (!copy_chan) {
2707 good = false;
2708 break;
2709 }
2710
2711 assert(acp_level[acp_base + src_chan] <= level);
2712
2713 if (!first) {
2714 first = copy_chan;
2715 } else {
2716 if (first->src[0].file != copy_chan->src[0].file ||
2717 first->src[0].index != copy_chan->src[0].index) {
2718 good = false;
2719 break;
2720 }
2721 }
2722 }
2723
2724 if (good) {
2725 /* We've now validated that we can copy-propagate to
2726 * replace this src register reference. Do it.
2727 */
2728 inst->src[r].file = first->src[0].file;
2729 inst->src[r].index = first->src[0].index;
2730
2731 int swizzle = 0;
2732 for (int i = 0; i < 4; i++) {
2733 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
2734 ir_to_mesa_instruction *copy_inst = acp[acp_base + src_chan];
2735 swizzle |= (GET_SWZ(copy_inst->src[0].swizzle, src_chan) <<
2736 (3 * i));
2737 }
2738 inst->src[r].swizzle = swizzle;
2739 }
2740 }
2741
2742 switch (inst->op) {
2743 case OPCODE_BGNLOOP:
2744 case OPCODE_ENDLOOP:
2745 /* End of a basic block, clear the ACP entirely. */
2746 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
2747 break;
2748
2749 case OPCODE_IF:
2750 ++level;
2751 break;
2752
2753 case OPCODE_ENDIF:
2754 case OPCODE_ELSE:
2755 /* Clear all channels written inside the block from the ACP, but
2756 * leaving those that were not touched.
2757 */
2758 for (int r = 0; r < this->next_temp; r++) {
2759 for (int c = 0; c < 4; c++) {
2760 if (!acp[4 * r + c])
2761 continue;
2762
2763 if (acp_level[4 * r + c] >= level)
2764 acp[4 * r + c] = NULL;
2765 }
2766 }
2767 if (inst->op == OPCODE_ENDIF)
2768 --level;
2769 break;
2770
2771 default:
2772 /* Continuing the block, clear any written channels from
2773 * the ACP.
2774 */
2775 if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.reladdr) {
2776 /* Any temporary might be written, so no copy propagation
2777 * across this instruction.
2778 */
2779 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
2780 } else if (inst->dst.file == PROGRAM_OUTPUT &&
2781 inst->dst.reladdr) {
2782 /* Any output might be written, so no copy propagation
2783 * from outputs across this instruction.
2784 */
2785 for (int r = 0; r < this->next_temp; r++) {
2786 for (int c = 0; c < 4; c++) {
2787 if (!acp[4 * r + c])
2788 continue;
2789
2790 if (acp[4 * r + c]->src[0].file == PROGRAM_OUTPUT)
2791 acp[4 * r + c] = NULL;
2792 }
2793 }
2794 } else if (inst->dst.file == PROGRAM_TEMPORARY ||
2795 inst->dst.file == PROGRAM_OUTPUT) {
2796 /* Clear where it's used as dst. */
2797 if (inst->dst.file == PROGRAM_TEMPORARY) {
2798 for (int c = 0; c < 4; c++) {
2799 if (inst->dst.writemask & (1 << c)) {
2800 acp[4 * inst->dst.index + c] = NULL;
2801 }
2802 }
2803 }
2804
2805 /* Clear where it's used as src. */
2806 for (int r = 0; r < this->next_temp; r++) {
2807 for (int c = 0; c < 4; c++) {
2808 if (!acp[4 * r + c])
2809 continue;
2810
2811 int src_chan = GET_SWZ(acp[4 * r + c]->src[0].swizzle, c);
2812
2813 if (acp[4 * r + c]->src[0].file == inst->dst.file &&
2814 acp[4 * r + c]->src[0].index == inst->dst.index &&
2815 inst->dst.writemask & (1 << src_chan))
2816 {
2817 acp[4 * r + c] = NULL;
2818 }
2819 }
2820 }
2821 }
2822 break;
2823 }
2824
2825 /* If this is a copy, add it to the ACP. */
2826 if (inst->op == OPCODE_MOV &&
2827 inst->dst.file == PROGRAM_TEMPORARY &&
2828 !inst->dst.reladdr &&
2829 !inst->saturate &&
2830 !inst->src[0].reladdr &&
2831 !inst->src[0].negate) {
2832 for (int i = 0; i < 4; i++) {
2833 if (inst->dst.writemask & (1 << i)) {
2834 acp[4 * inst->dst.index + i] = inst;
2835 acp_level[4 * inst->dst.index + i] = level;
2836 }
2837 }
2838 }
2839 }
2840
2841 ralloc_free(acp_level);
2842 ralloc_free(acp);
2843 }
2844
2845
2846 /**
2847 * Convert a shader's GLSL IR into a Mesa gl_program.
2848 */
2849 static struct gl_program *
2850 get_mesa_program(struct gl_context *ctx,
2851 struct gl_shader_program *shader_program,
2852 struct gl_shader *shader)
2853 {
2854 ir_to_mesa_visitor v;
2855 struct prog_instruction *mesa_instructions, *mesa_inst;
2856 ir_instruction **mesa_instruction_annotation;
2857 int i;
2858 struct gl_program *prog;
2859 GLenum target;
2860 const char *target_string;
2861 GLboolean progress;
2862 struct gl_shader_compiler_options *options =
2863 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
2864
2865 switch (shader->Type) {
2866 case GL_VERTEX_SHADER:
2867 target = GL_VERTEX_PROGRAM_ARB;
2868 target_string = "vertex";
2869 break;
2870 case GL_FRAGMENT_SHADER:
2871 target = GL_FRAGMENT_PROGRAM_ARB;
2872 target_string = "fragment";
2873 break;
2874 case GL_GEOMETRY_SHADER:
2875 target = GL_GEOMETRY_PROGRAM_NV;
2876 target_string = "geometry";
2877 break;
2878 default:
2879 assert(!"should not be reached");
2880 return NULL;
2881 }
2882
2883 validate_ir_tree(shader->ir);
2884
2885 prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
2886 if (!prog)
2887 return NULL;
2888 prog->Parameters = _mesa_new_parameter_list();
2889 prog->Varying = _mesa_new_parameter_list();
2890 prog->Attributes = _mesa_new_parameter_list();
2891 v.ctx = ctx;
2892 v.prog = prog;
2893 v.shader_program = shader_program;
2894 v.options = options;
2895
2896 add_uniforms_to_parameters_list(shader_program, shader, prog);
2897
2898 /* Emit Mesa IR for main(). */
2899 visit_exec_list(shader->ir, &v);
2900 v.emit(NULL, OPCODE_END);
2901
2902 /* Now emit bodies for any functions that were used. */
2903 do {
2904 progress = GL_FALSE;
2905
2906 foreach_iter(exec_list_iterator, iter, v.function_signatures) {
2907 function_entry *entry = (function_entry *)iter.get();
2908
2909 if (!entry->bgn_inst) {
2910 v.current_function = entry;
2911
2912 entry->bgn_inst = v.emit(NULL, OPCODE_BGNSUB);
2913 entry->bgn_inst->function = entry;
2914
2915 visit_exec_list(&entry->sig->body, &v);
2916
2917 ir_to_mesa_instruction *last;
2918 last = (ir_to_mesa_instruction *)v.instructions.get_tail();
2919 if (last->op != OPCODE_RET)
2920 v.emit(NULL, OPCODE_RET);
2921
2922 ir_to_mesa_instruction *end;
2923 end = v.emit(NULL, OPCODE_ENDSUB);
2924 end->function = entry;
2925
2926 progress = GL_TRUE;
2927 }
2928 }
2929 } while (progress);
2930
2931 prog->NumTemporaries = v.next_temp;
2932
2933 int num_instructions = 0;
2934 foreach_iter(exec_list_iterator, iter, v.instructions) {
2935 num_instructions++;
2936 }
2937
2938 mesa_instructions =
2939 (struct prog_instruction *)calloc(num_instructions,
2940 sizeof(*mesa_instructions));
2941 mesa_instruction_annotation = ralloc_array(v.mem_ctx, ir_instruction *,
2942 num_instructions);
2943
2944 v.copy_propagate();
2945
2946 /* Convert ir_mesa_instructions into prog_instructions.
2947 */
2948 mesa_inst = mesa_instructions;
2949 i = 0;
2950 foreach_iter(exec_list_iterator, iter, v.instructions) {
2951 const ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2952
2953 mesa_inst->Opcode = inst->op;
2954 mesa_inst->CondUpdate = inst->cond_update;
2955 if (inst->saturate)
2956 mesa_inst->SaturateMode = SATURATE_ZERO_ONE;
2957 mesa_inst->DstReg.File = inst->dst.file;
2958 mesa_inst->DstReg.Index = inst->dst.index;
2959 mesa_inst->DstReg.CondMask = inst->dst.cond_mask;
2960 mesa_inst->DstReg.WriteMask = inst->dst.writemask;
2961 mesa_inst->DstReg.RelAddr = inst->dst.reladdr != NULL;
2962 mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src[0]);
2963 mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src[1]);
2964 mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src[2]);
2965 mesa_inst->TexSrcUnit = inst->sampler;
2966 mesa_inst->TexSrcTarget = inst->tex_target;
2967 mesa_inst->TexShadow = inst->tex_shadow;
2968 mesa_instruction_annotation[i] = inst->ir;
2969
2970 /* Set IndirectRegisterFiles. */
2971 if (mesa_inst->DstReg.RelAddr)
2972 prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
2973
2974 /* Update program's bitmask of indirectly accessed register files */
2975 for (unsigned src = 0; src < 3; src++)
2976 if (mesa_inst->SrcReg[src].RelAddr)
2977 prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
2978
2979 if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
2980 fail_link(shader_program, "Couldn't flatten if statement\n");
2981 }
2982
2983 switch (mesa_inst->Opcode) {
2984 case OPCODE_BGNSUB:
2985 inst->function->inst = i;
2986 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2987 break;
2988 case OPCODE_ENDSUB:
2989 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2990 break;
2991 case OPCODE_CAL:
2992 mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
2993 break;
2994 case OPCODE_ARL:
2995 prog->NumAddressRegs = 1;
2996 break;
2997 default:
2998 break;
2999 }
3000
3001 mesa_inst++;
3002 i++;
3003
3004 if (!shader_program->LinkStatus)
3005 break;
3006 }
3007
3008 if (!shader_program->LinkStatus) {
3009 free(mesa_instructions);
3010 _mesa_reference_program(ctx, &shader->Program, NULL);
3011 return NULL;
3012 }
3013
3014 set_branchtargets(&v, mesa_instructions, num_instructions);
3015
3016 if (ctx->Shader.Flags & GLSL_DUMP) {
3017 printf("\n");
3018 printf("GLSL IR for linked %s program %d:\n", target_string,
3019 shader_program->Name);
3020 _mesa_print_ir(shader->ir, NULL);
3021 printf("\n");
3022 printf("\n");
3023 printf("Mesa IR for linked %s program %d:\n", target_string,
3024 shader_program->Name);
3025 print_program(mesa_instructions, mesa_instruction_annotation,
3026 num_instructions);
3027 }
3028
3029 prog->Instructions = mesa_instructions;
3030 prog->NumInstructions = num_instructions;
3031
3032 do_set_program_inouts(shader->ir, prog);
3033 count_resources(prog);
3034
3035 check_resources(ctx, shader_program, prog);
3036
3037 _mesa_reference_program(ctx, &shader->Program, prog);
3038
3039 if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
3040 _mesa_optimize_program(ctx, prog);
3041 }
3042
3043 return prog;
3044 }
3045
3046 extern "C" {
3047
3048 /**
3049 * Link a shader.
3050 * Called via ctx->Driver.LinkShader()
3051 * This actually involves converting GLSL IR into Mesa gl_programs with
3052 * code lowering and other optimizations.
3053 */
3054 GLboolean
3055 _mesa_ir_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
3056 {
3057 assert(prog->LinkStatus);
3058
3059 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
3060 if (prog->_LinkedShaders[i] == NULL)
3061 continue;
3062
3063 bool progress;
3064 exec_list *ir = prog->_LinkedShaders[i]->ir;
3065 const struct gl_shader_compiler_options *options =
3066 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
3067
3068 do {
3069 progress = false;
3070
3071 /* Lowering */
3072 do_mat_op_to_vec(ir);
3073 lower_instructions(ir, (MOD_TO_FRACT | DIV_TO_MUL_RCP | EXP_TO_EXP2
3074 | LOG_TO_LOG2
3075 | ((options->EmitNoPow) ? POW_TO_EXP2 : 0)));
3076
3077 progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
3078
3079 progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
3080
3081 progress = lower_quadop_vector(ir, true) || progress;
3082
3083 if (options->EmitNoIfs) {
3084 progress = lower_discard(ir) || progress;
3085 progress = lower_if_to_cond_assign(ir) || progress;
3086 }
3087
3088 if (options->EmitNoNoise)
3089 progress = lower_noise(ir) || progress;
3090
3091 /* If there are forms of indirect addressing that the driver
3092 * cannot handle, perform the lowering pass.
3093 */
3094 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
3095 || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
3096 progress =
3097 lower_variable_index_to_cond_assign(ir,
3098 options->EmitNoIndirectInput,
3099 options->EmitNoIndirectOutput,
3100 options->EmitNoIndirectTemp,
3101 options->EmitNoIndirectUniform)
3102 || progress;
3103
3104 progress = do_vec_index_to_cond_assign(ir) || progress;
3105 } while (progress);
3106
3107 validate_ir_tree(ir);
3108 }
3109
3110 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
3111 struct gl_program *linked_prog;
3112
3113 if (prog->_LinkedShaders[i] == NULL)
3114 continue;
3115
3116 linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
3117
3118 if (linked_prog) {
3119 bool ok = true;
3120
3121 switch (prog->_LinkedShaders[i]->Type) {
3122 case GL_VERTEX_SHADER:
3123 _mesa_reference_vertprog(ctx, &prog->VertexProgram,
3124 (struct gl_vertex_program *)linked_prog);
3125 ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
3126 linked_prog);
3127 break;
3128 case GL_FRAGMENT_SHADER:
3129 _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
3130 (struct gl_fragment_program *)linked_prog);
3131 ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
3132 linked_prog);
3133 break;
3134 case GL_GEOMETRY_SHADER:
3135 _mesa_reference_geomprog(ctx, &prog->GeometryProgram,
3136 (struct gl_geometry_program *)linked_prog);
3137 ok = ctx->Driver.ProgramStringNotify(ctx, GL_GEOMETRY_PROGRAM_NV,
3138 linked_prog);
3139 break;
3140 }
3141 if (!ok) {
3142 return GL_FALSE;
3143 }
3144 }
3145
3146 _mesa_reference_program(ctx, &linked_prog, NULL);
3147 }
3148
3149 return GL_TRUE;
3150 }
3151
3152
3153 /**
3154 * Compile a GLSL shader. Called via glCompileShader().
3155 */
3156 void
3157 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
3158 {
3159 struct _mesa_glsl_parse_state *state =
3160 new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
3161
3162 const char *source = shader->Source;
3163 /* Check if the user called glCompileShader without first calling
3164 * glShaderSource. This should fail to compile, but not raise a GL_ERROR.
3165 */
3166 if (source == NULL) {
3167 shader->CompileStatus = GL_FALSE;
3168 return;
3169 }
3170
3171 state->error = preprocess(state, &source, &state->info_log,
3172 &ctx->Extensions, ctx->API);
3173
3174 if (ctx->Shader.Flags & GLSL_DUMP) {
3175 printf("GLSL source for shader %d:\n", shader->Name);
3176 printf("%s\n", shader->Source);
3177 }
3178
3179 if (!state->error) {
3180 _mesa_glsl_lexer_ctor(state, source);
3181 _mesa_glsl_parse(state);
3182 _mesa_glsl_lexer_dtor(state);
3183 }
3184
3185 ralloc_free(shader->ir);
3186 shader->ir = new(shader) exec_list;
3187 if (!state->error && !state->translation_unit.is_empty())
3188 _mesa_ast_to_hir(shader->ir, state);
3189
3190 if (!state->error && !shader->ir->is_empty()) {
3191 validate_ir_tree(shader->ir);
3192
3193 /* Do some optimization at compile time to reduce shader IR size
3194 * and reduce later work if the same shader is linked multiple times
3195 */
3196 while (do_common_optimization(shader->ir, false, 32))
3197 ;
3198
3199 validate_ir_tree(shader->ir);
3200 }
3201
3202 shader->symbols = state->symbols;
3203
3204 shader->CompileStatus = !state->error;
3205 shader->InfoLog = state->info_log;
3206 shader->Version = state->language_version;
3207 memcpy(shader->builtins_to_link, state->builtins_to_link,
3208 sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
3209 shader->num_builtins_to_link = state->num_builtins_to_link;
3210
3211 if (ctx->Shader.Flags & GLSL_LOG) {
3212 _mesa_write_shader_to_file(shader);
3213 }
3214
3215 if (ctx->Shader.Flags & GLSL_DUMP) {
3216 if (shader->CompileStatus) {
3217 printf("GLSL IR for shader %d:\n", shader->Name);
3218 _mesa_print_ir(shader->ir, NULL);
3219 printf("\n\n");
3220 } else {
3221 printf("GLSL shader %d failed to compile.\n", shader->Name);
3222 }
3223 if (shader->InfoLog && shader->InfoLog[0] != 0) {
3224 printf("GLSL shader %d info log:\n", shader->Name);
3225 printf("%s\n", shader->InfoLog);
3226 }
3227 }
3228
3229 /* Retain any live IR, but trash the rest. */
3230 reparent_ir(shader->ir, shader->ir);
3231
3232 ralloc_free(state);
3233 }
3234
3235
3236 /**
3237 * Link a GLSL shader program. Called via glLinkProgram().
3238 */
3239 void
3240 _mesa_glsl_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
3241 {
3242 unsigned int i;
3243
3244 _mesa_clear_shader_program_data(ctx, prog);
3245
3246 prog->LinkStatus = GL_TRUE;
3247
3248 for (i = 0; i < prog->NumShaders; i++) {
3249 if (!prog->Shaders[i]->CompileStatus) {
3250 fail_link(prog, "linking with uncompiled shader");
3251 prog->LinkStatus = GL_FALSE;
3252 }
3253 }
3254
3255 prog->Varying = _mesa_new_parameter_list();
3256 _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
3257 _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
3258 _mesa_reference_geomprog(ctx, &prog->GeometryProgram, NULL);
3259
3260 if (prog->LinkStatus) {
3261 link_shaders(ctx, prog);
3262 }
3263
3264 if (prog->LinkStatus) {
3265 if (!ctx->Driver.LinkShader(ctx, prog)) {
3266 prog->LinkStatus = GL_FALSE;
3267 }
3268 }
3269
3270 set_uniform_initializers(ctx, prog);
3271
3272 if (ctx->Shader.Flags & GLSL_DUMP) {
3273 if (!prog->LinkStatus) {
3274 printf("GLSL shader program %d failed to link\n", prog->Name);
3275 }
3276
3277 if (prog->InfoLog && prog->InfoLog[0] != 0) {
3278 printf("GLSL shader program %d info log:\n", prog->Name);
3279 printf("%s\n", prog->InfoLog);
3280 }
3281 }
3282 }
3283
3284 } /* extern "C" */