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