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