gallium glsl: Fix crash with piglit fs-deref-literal-array-of-structs.shader_test
[mesa.git] / src / mesa / state_tracker / st_glsl_to_tgsi.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 * Copyright © 2011 Bryan Cain
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the next
15 * paragraph) shall be included in all copies or substantial portions of the
16 * Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
25 */
26
27 /**
28 * \file glsl_to_tgsi.cpp
29 *
30 * Translate GLSL IR to TGSI.
31 */
32
33 #include <stdio.h>
34 #include "main/compiler.h"
35 #include "ir.h"
36 #include "ir_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 "main/uniforms.h"
47 #include "program/hash_table.h"
48
49 extern "C" {
50 #include "main/shaderapi.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 #include "pipe/p_compiler.h"
59 #include "pipe/p_context.h"
60 #include "pipe/p_screen.h"
61 #include "pipe/p_shader_tokens.h"
62 #include "pipe/p_state.h"
63 #include "util/u_math.h"
64 #include "tgsi/tgsi_ureg.h"
65 #include "tgsi/tgsi_info.h"
66 #include "st_context.h"
67 #include "st_program.h"
68 #include "st_glsl_to_tgsi.h"
69 #include "st_mesa_to_tgsi.h"
70 }
71
72 #define PROGRAM_IMMEDIATE PROGRAM_FILE_MAX
73 #define PROGRAM_ANY_CONST ((1 << PROGRAM_STATE_VAR) | \
74 (1 << PROGRAM_CONSTANT) | \
75 (1 << PROGRAM_UNIFORM))
76
77 /**
78 * Maximum number of temporary registers.
79 *
80 * It is too big for stack allocated arrays -- it will cause stack overflow on
81 * Windows and likely Mac OS X.
82 */
83 #define MAX_TEMPS 4096
84
85 /**
86 * Maximum number of arrays
87 */
88 #define MAX_ARRAYS 256
89
90 /* if we support a native gallium TG4 with the ability to take 4 texoffsets then bump this */
91 #define MAX_GLSL_TEXTURE_OFFSET 1
92
93 class st_src_reg;
94 class st_dst_reg;
95
96 static int swizzle_for_size(int size);
97
98 /**
99 * This struct is a corresponding struct to TGSI ureg_src.
100 */
101 class st_src_reg {
102 public:
103 st_src_reg(gl_register_file file, int index, const glsl_type *type)
104 {
105 this->file = file;
106 this->index = index;
107 if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
108 this->swizzle = swizzle_for_size(type->vector_elements);
109 else
110 this->swizzle = SWIZZLE_XYZW;
111 this->negate = 0;
112 this->index2D = 0;
113 this->type = type ? type->base_type : GLSL_TYPE_ERROR;
114 this->reladdr = NULL;
115 this->reladdr2 = NULL;
116 this->has_index2 = false;
117 }
118
119 st_src_reg(gl_register_file file, int index, int type)
120 {
121 this->type = type;
122 this->file = file;
123 this->index = index;
124 this->index2D = 0;
125 this->swizzle = SWIZZLE_XYZW;
126 this->negate = 0;
127 this->reladdr = NULL;
128 this->reladdr2 = NULL;
129 this->has_index2 = false;
130 }
131
132 st_src_reg(gl_register_file file, int index, int type, int index2D)
133 {
134 this->type = type;
135 this->file = file;
136 this->index = index;
137 this->index2D = index2D;
138 this->swizzle = SWIZZLE_XYZW;
139 this->negate = 0;
140 this->reladdr = NULL;
141 this->reladdr2 = NULL;
142 this->has_index2 = false;
143 }
144
145 st_src_reg()
146 {
147 this->type = GLSL_TYPE_ERROR;
148 this->file = PROGRAM_UNDEFINED;
149 this->index = 0;
150 this->index2D = 0;
151 this->swizzle = 0;
152 this->negate = 0;
153 this->reladdr = NULL;
154 this->reladdr2 = NULL;
155 this->has_index2 = false;
156 }
157
158 explicit st_src_reg(st_dst_reg reg);
159
160 gl_register_file file; /**< PROGRAM_* from Mesa */
161 int index; /**< temporary index, VERT_ATTRIB_*, VARYING_SLOT_*, etc. */
162 int index2D;
163 GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
164 int negate; /**< NEGATE_XYZW mask from mesa */
165 int type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
166 /** Register index should be offset by the integer in this reg. */
167 st_src_reg *reladdr;
168 st_src_reg *reladdr2;
169 bool has_index2;
170 };
171
172 class st_dst_reg {
173 public:
174 st_dst_reg(gl_register_file file, int writemask, int type, int index)
175 {
176 this->file = file;
177 this->index = index;
178 this->writemask = writemask;
179 this->cond_mask = COND_TR;
180 this->reladdr = NULL;
181 this->type = type;
182 }
183
184 st_dst_reg(gl_register_file file, int writemask, int type)
185 {
186 this->file = file;
187 this->index = 0;
188 this->writemask = writemask;
189 this->cond_mask = COND_TR;
190 this->reladdr = NULL;
191 this->type = type;
192 }
193
194 st_dst_reg()
195 {
196 this->type = GLSL_TYPE_ERROR;
197 this->file = PROGRAM_UNDEFINED;
198 this->index = 0;
199 this->writemask = 0;
200 this->cond_mask = COND_TR;
201 this->reladdr = NULL;
202 }
203
204 explicit st_dst_reg(st_src_reg reg);
205
206 gl_register_file file; /**< PROGRAM_* from Mesa */
207 int index; /**< temporary index, VERT_ATTRIB_*, VARYING_SLOT_*, etc. */
208 int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
209 GLuint cond_mask:4;
210 int type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
211 /** Register index should be offset by the integer in this reg. */
212 st_src_reg *reladdr;
213 };
214
215 st_src_reg::st_src_reg(st_dst_reg reg)
216 {
217 this->type = reg.type;
218 this->file = reg.file;
219 this->index = reg.index;
220 this->swizzle = SWIZZLE_XYZW;
221 this->negate = 0;
222 this->reladdr = reg.reladdr;
223 this->index2D = 0;
224 this->reladdr2 = NULL;
225 this->has_index2 = false;
226 }
227
228 st_dst_reg::st_dst_reg(st_src_reg reg)
229 {
230 this->type = reg.type;
231 this->file = reg.file;
232 this->index = reg.index;
233 this->writemask = WRITEMASK_XYZW;
234 this->cond_mask = COND_TR;
235 this->reladdr = reg.reladdr;
236 }
237
238 class glsl_to_tgsi_instruction : public exec_node {
239 public:
240 DECLARE_RALLOC_CXX_OPERATORS(glsl_to_tgsi_instruction)
241
242 unsigned op;
243 st_dst_reg dst;
244 st_src_reg src[3];
245 /** Pointer to the ir source this tree came from for debugging */
246 ir_instruction *ir;
247 GLboolean cond_update;
248 bool saturate;
249 int sampler; /**< sampler index */
250 int tex_target; /**< One of TEXTURE_*_INDEX */
251 GLboolean tex_shadow;
252
253 st_src_reg tex_offsets[MAX_GLSL_TEXTURE_OFFSET];
254 unsigned tex_offset_num_offset;
255 int dead_mask; /**< Used in dead code elimination */
256
257 class function_entry *function; /* Set on TGSI_OPCODE_CAL or TGSI_OPCODE_BGNSUB */
258 };
259
260 class variable_storage : public exec_node {
261 public:
262 variable_storage(ir_variable *var, gl_register_file file, int index)
263 : file(file), index(index), var(var)
264 {
265 /* empty */
266 }
267
268 gl_register_file file;
269 int index;
270 ir_variable *var; /* variable that maps to this, if any */
271 };
272
273 class immediate_storage : public exec_node {
274 public:
275 immediate_storage(gl_constant_value *values, int size, int type)
276 {
277 memcpy(this->values, values, size * sizeof(gl_constant_value));
278 this->size = size;
279 this->type = type;
280 }
281
282 gl_constant_value values[4];
283 int size; /**< Number of components (1-4) */
284 int type; /**< GL_FLOAT, GL_INT, GL_BOOL, or GL_UNSIGNED_INT */
285 };
286
287 class function_entry : public exec_node {
288 public:
289 ir_function_signature *sig;
290
291 /**
292 * identifier of this function signature used by the program.
293 *
294 * At the point that TGSI instructions for function calls are
295 * generated, we don't know the address of the first instruction of
296 * the function body. So we make the BranchTarget that is called a
297 * small integer and rewrite them during set_branchtargets().
298 */
299 int sig_id;
300
301 /**
302 * Pointer to first instruction of the function body.
303 *
304 * Set during function body emits after main() is processed.
305 */
306 glsl_to_tgsi_instruction *bgn_inst;
307
308 /**
309 * Index of the first instruction of the function body in actual TGSI.
310 *
311 * Set after conversion from glsl_to_tgsi_instruction to TGSI.
312 */
313 int inst;
314
315 /** Storage for the return value. */
316 st_src_reg return_reg;
317 };
318
319 struct glsl_to_tgsi_visitor : public ir_visitor {
320 public:
321 glsl_to_tgsi_visitor();
322 ~glsl_to_tgsi_visitor();
323
324 function_entry *current_function;
325
326 struct gl_context *ctx;
327 struct gl_program *prog;
328 struct gl_shader_program *shader_program;
329 struct gl_shader_compiler_options *options;
330
331 int next_temp;
332
333 unsigned array_sizes[MAX_ARRAYS];
334 unsigned next_array;
335
336 int num_address_regs;
337 int samplers_used;
338 bool indirect_addr_consts;
339
340 int glsl_version;
341 bool native_integers;
342 bool have_sqrt;
343
344 variable_storage *find_variable_storage(ir_variable *var);
345
346 int add_constant(gl_register_file file, gl_constant_value values[4],
347 int size, int datatype, GLuint *swizzle_out);
348
349 function_entry *get_function_signature(ir_function_signature *sig);
350
351 st_src_reg get_temp(const glsl_type *type);
352 void reladdr_to_temp(ir_instruction *ir, st_src_reg *reg, int *num_reladdr);
353
354 st_src_reg st_src_reg_for_float(float val);
355 st_src_reg st_src_reg_for_int(int val);
356 st_src_reg st_src_reg_for_type(int type, int val);
357
358 /**
359 * \name Visit methods
360 *
361 * As typical for the visitor pattern, there must be one \c visit method for
362 * each concrete subclass of \c ir_instruction. Virtual base classes within
363 * the hierarchy should not have \c visit methods.
364 */
365 /*@{*/
366 virtual void visit(ir_variable *);
367 virtual void visit(ir_loop *);
368 virtual void visit(ir_loop_jump *);
369 virtual void visit(ir_function_signature *);
370 virtual void visit(ir_function *);
371 virtual void visit(ir_expression *);
372 virtual void visit(ir_swizzle *);
373 virtual void visit(ir_dereference_variable *);
374 virtual void visit(ir_dereference_array *);
375 virtual void visit(ir_dereference_record *);
376 virtual void visit(ir_assignment *);
377 virtual void visit(ir_constant *);
378 virtual void visit(ir_call *);
379 virtual void visit(ir_return *);
380 virtual void visit(ir_discard *);
381 virtual void visit(ir_texture *);
382 virtual void visit(ir_if *);
383 virtual void visit(ir_emit_vertex *);
384 virtual void visit(ir_end_primitive *);
385 /*@}*/
386
387 st_src_reg result;
388
389 /** List of variable_storage */
390 exec_list variables;
391
392 /** List of immediate_storage */
393 exec_list immediates;
394 unsigned num_immediates;
395
396 /** List of function_entry */
397 exec_list function_signatures;
398 int next_signature_id;
399
400 /** List of glsl_to_tgsi_instruction */
401 exec_list instructions;
402
403 glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op);
404
405 glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op,
406 st_dst_reg dst, st_src_reg src0);
407
408 glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op,
409 st_dst_reg dst, st_src_reg src0, st_src_reg src1);
410
411 glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op,
412 st_dst_reg dst,
413 st_src_reg src0, st_src_reg src1, st_src_reg src2);
414
415 unsigned get_opcode(ir_instruction *ir, unsigned op,
416 st_dst_reg dst,
417 st_src_reg src0, st_src_reg src1);
418
419 /**
420 * Emit the correct dot-product instruction for the type of arguments
421 */
422 glsl_to_tgsi_instruction *emit_dp(ir_instruction *ir,
423 st_dst_reg dst,
424 st_src_reg src0,
425 st_src_reg src1,
426 unsigned elements);
427
428 void emit_scalar(ir_instruction *ir, unsigned op,
429 st_dst_reg dst, st_src_reg src0);
430
431 void emit_scalar(ir_instruction *ir, unsigned op,
432 st_dst_reg dst, st_src_reg src0, st_src_reg src1);
433
434 void emit_arl(ir_instruction *ir, st_dst_reg dst, st_src_reg src0);
435
436 void emit_scs(ir_instruction *ir, unsigned op,
437 st_dst_reg dst, const st_src_reg &src);
438
439 bool try_emit_mad(ir_expression *ir,
440 int mul_operand);
441 bool try_emit_mad_for_and_not(ir_expression *ir,
442 int mul_operand);
443 bool try_emit_sat(ir_expression *ir);
444
445 void emit_swz(ir_expression *ir);
446
447 bool process_move_condition(ir_rvalue *ir);
448
449 void simplify_cmp(void);
450
451 void rename_temp_register(int index, int new_index);
452 int get_first_temp_read(int index);
453 int get_first_temp_write(int index);
454 int get_last_temp_read(int index);
455 int get_last_temp_write(int index);
456
457 void copy_propagate(void);
458 void eliminate_dead_code(void);
459 int eliminate_dead_code_advanced(void);
460 void merge_registers(void);
461 void renumber_registers(void);
462
463 void emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
464 st_dst_reg *l, st_src_reg *r);
465
466 void *mem_ctx;
467 };
468
469 static st_src_reg undef_src = st_src_reg(PROGRAM_UNDEFINED, 0, GLSL_TYPE_ERROR);
470
471 static st_dst_reg undef_dst = st_dst_reg(PROGRAM_UNDEFINED, SWIZZLE_NOOP, GLSL_TYPE_ERROR);
472
473 static st_dst_reg address_reg = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 0);
474 static st_dst_reg address_reg2 = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 1);
475
476 static void
477 fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
478
479 static void
480 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
481 {
482 va_list args;
483 va_start(args, fmt);
484 ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
485 va_end(args);
486
487 prog->LinkStatus = GL_FALSE;
488 }
489
490 static int
491 swizzle_for_size(int size)
492 {
493 int size_swizzles[4] = {
494 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
495 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
496 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
497 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
498 };
499
500 assert((size >= 1) && (size <= 4));
501 return size_swizzles[size - 1];
502 }
503
504 static bool
505 is_tex_instruction(unsigned opcode)
506 {
507 const tgsi_opcode_info* info = tgsi_get_opcode_info(opcode);
508 return info->is_tex;
509 }
510
511 static unsigned
512 num_inst_dst_regs(unsigned opcode)
513 {
514 const tgsi_opcode_info* info = tgsi_get_opcode_info(opcode);
515 return info->num_dst;
516 }
517
518 static unsigned
519 num_inst_src_regs(unsigned opcode)
520 {
521 const tgsi_opcode_info* info = tgsi_get_opcode_info(opcode);
522 return info->is_tex ? info->num_src - 1 : info->num_src;
523 }
524
525 glsl_to_tgsi_instruction *
526 glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op,
527 st_dst_reg dst,
528 st_src_reg src0, st_src_reg src1, st_src_reg src2)
529 {
530 glsl_to_tgsi_instruction *inst = new(mem_ctx) glsl_to_tgsi_instruction();
531 int num_reladdr = 0, i;
532
533 op = get_opcode(ir, op, dst, src0, src1);
534
535 /* If we have to do relative addressing, we want to load the ARL
536 * reg directly for one of the regs, and preload the other reladdr
537 * sources into temps.
538 */
539 num_reladdr += dst.reladdr != NULL;
540 num_reladdr += src0.reladdr != NULL || src0.reladdr2 != NULL;
541 num_reladdr += src1.reladdr != NULL || src1.reladdr2 != NULL;
542 num_reladdr += src2.reladdr != NULL || src2.reladdr2 != NULL;
543
544 reladdr_to_temp(ir, &src2, &num_reladdr);
545 reladdr_to_temp(ir, &src1, &num_reladdr);
546 reladdr_to_temp(ir, &src0, &num_reladdr);
547
548 if (dst.reladdr) {
549 emit_arl(ir, address_reg, *dst.reladdr);
550 num_reladdr--;
551 }
552 assert(num_reladdr == 0);
553
554 inst->op = op;
555 inst->dst = dst;
556 inst->src[0] = src0;
557 inst->src[1] = src1;
558 inst->src[2] = src2;
559 inst->ir = ir;
560 inst->dead_mask = 0;
561
562 inst->function = NULL;
563
564 /* Update indirect addressing status used by TGSI */
565 if (dst.reladdr) {
566 switch(dst.file) {
567 case PROGRAM_STATE_VAR:
568 case PROGRAM_CONSTANT:
569 case PROGRAM_UNIFORM:
570 this->indirect_addr_consts = true;
571 break;
572 case PROGRAM_IMMEDIATE:
573 assert(!"immediates should not have indirect addressing");
574 break;
575 default:
576 break;
577 }
578 }
579 else {
580 for (i=0; i<3; i++) {
581 if(inst->src[i].reladdr) {
582 switch(inst->src[i].file) {
583 case PROGRAM_STATE_VAR:
584 case PROGRAM_CONSTANT:
585 case PROGRAM_UNIFORM:
586 this->indirect_addr_consts = true;
587 break;
588 case PROGRAM_IMMEDIATE:
589 assert(!"immediates should not have indirect addressing");
590 break;
591 default:
592 break;
593 }
594 }
595 }
596 }
597
598 this->instructions.push_tail(inst);
599
600 return inst;
601 }
602
603
604 glsl_to_tgsi_instruction *
605 glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op,
606 st_dst_reg dst, st_src_reg src0, st_src_reg src1)
607 {
608 return emit(ir, op, dst, src0, src1, undef_src);
609 }
610
611 glsl_to_tgsi_instruction *
612 glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op,
613 st_dst_reg dst, st_src_reg src0)
614 {
615 assert(dst.writemask != 0);
616 return emit(ir, op, dst, src0, undef_src, undef_src);
617 }
618
619 glsl_to_tgsi_instruction *
620 glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op)
621 {
622 return emit(ir, op, undef_dst, undef_src, undef_src, undef_src);
623 }
624
625 /**
626 * Determines whether to use an integer, unsigned integer, or float opcode
627 * based on the operands and input opcode, then emits the result.
628 */
629 unsigned
630 glsl_to_tgsi_visitor::get_opcode(ir_instruction *ir, unsigned op,
631 st_dst_reg dst,
632 st_src_reg src0, st_src_reg src1)
633 {
634 int type = GLSL_TYPE_FLOAT;
635
636 if (op == TGSI_OPCODE_MOV)
637 return op;
638
639 assert(src0.type != GLSL_TYPE_ARRAY);
640 assert(src0.type != GLSL_TYPE_STRUCT);
641 assert(src1.type != GLSL_TYPE_ARRAY);
642 assert(src1.type != GLSL_TYPE_STRUCT);
643
644 if (src0.type == GLSL_TYPE_FLOAT || src1.type == GLSL_TYPE_FLOAT)
645 type = GLSL_TYPE_FLOAT;
646 else if (native_integers)
647 type = src0.type == GLSL_TYPE_BOOL ? GLSL_TYPE_INT : src0.type;
648
649 #define case4(c, f, i, u) \
650 case TGSI_OPCODE_##c: \
651 if (type == GLSL_TYPE_INT) \
652 op = TGSI_OPCODE_##i; \
653 else if (type == GLSL_TYPE_UINT) \
654 op = TGSI_OPCODE_##u; \
655 else \
656 op = TGSI_OPCODE_##f; \
657 break;
658
659 #define case3(f, i, u) case4(f, f, i, u)
660 #define case2fi(f, i) case4(f, f, i, i)
661 #define case2iu(i, u) case4(i, LAST, i, u)
662
663 #define casecomp(c, f, i, u) \
664 case TGSI_OPCODE_##c: \
665 if (type == GLSL_TYPE_INT) \
666 op = TGSI_OPCODE_##i; \
667 else if (type == GLSL_TYPE_UINT) \
668 op = TGSI_OPCODE_##u; \
669 else if (native_integers) \
670 op = TGSI_OPCODE_##f; \
671 else \
672 op = TGSI_OPCODE_##c; \
673 break;
674
675 switch(op) {
676 case2fi(ADD, UADD);
677 case2fi(MUL, UMUL);
678 case2fi(MAD, UMAD);
679 case3(DIV, IDIV, UDIV);
680 case3(MAX, IMAX, UMAX);
681 case3(MIN, IMIN, UMIN);
682 case2iu(MOD, UMOD);
683
684 casecomp(SEQ, FSEQ, USEQ, USEQ);
685 casecomp(SNE, FSNE, USNE, USNE);
686 casecomp(SGE, FSGE, ISGE, USGE);
687 casecomp(SLT, FSLT, ISLT, USLT);
688
689 case2iu(ISHR, USHR);
690
691 case2fi(SSG, ISSG);
692 case3(ABS, IABS, IABS);
693
694 default: break;
695 }
696
697 assert(op != TGSI_OPCODE_LAST);
698 return op;
699 }
700
701 glsl_to_tgsi_instruction *
702 glsl_to_tgsi_visitor::emit_dp(ir_instruction *ir,
703 st_dst_reg dst, st_src_reg src0, st_src_reg src1,
704 unsigned elements)
705 {
706 static const unsigned dot_opcodes[] = {
707 TGSI_OPCODE_DP2, TGSI_OPCODE_DP3, TGSI_OPCODE_DP4
708 };
709
710 return emit(ir, dot_opcodes[elements - 2], dst, src0, src1);
711 }
712
713 /**
714 * Emits TGSI scalar opcodes to produce unique answers across channels.
715 *
716 * Some TGSI opcodes are scalar-only, like ARB_fp/vp. The src X
717 * channel determines the result across all channels. So to do a vec4
718 * of this operation, we want to emit a scalar per source channel used
719 * to produce dest channels.
720 */
721 void
722 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
723 st_dst_reg dst,
724 st_src_reg orig_src0, st_src_reg orig_src1)
725 {
726 int i, j;
727 int done_mask = ~dst.writemask;
728
729 /* TGSI RCP is a scalar operation splatting results to all channels,
730 * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
731 * dst channels.
732 */
733 for (i = 0; i < 4; i++) {
734 GLuint this_mask = (1 << i);
735 glsl_to_tgsi_instruction *inst;
736 st_src_reg src0 = orig_src0;
737 st_src_reg src1 = orig_src1;
738
739 if (done_mask & this_mask)
740 continue;
741
742 GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
743 GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
744 for (j = i + 1; j < 4; j++) {
745 /* If there is another enabled component in the destination that is
746 * derived from the same inputs, generate its value on this pass as
747 * well.
748 */
749 if (!(done_mask & (1 << j)) &&
750 GET_SWZ(src0.swizzle, j) == src0_swiz &&
751 GET_SWZ(src1.swizzle, j) == src1_swiz) {
752 this_mask |= (1 << j);
753 }
754 }
755 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
756 src0_swiz, src0_swiz);
757 src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
758 src1_swiz, src1_swiz);
759
760 inst = emit(ir, op, dst, src0, src1);
761 inst->dst.writemask = this_mask;
762 done_mask |= this_mask;
763 }
764 }
765
766 void
767 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
768 st_dst_reg dst, st_src_reg src0)
769 {
770 st_src_reg undef = undef_src;
771
772 undef.swizzle = SWIZZLE_XXXX;
773
774 emit_scalar(ir, op, dst, src0, undef);
775 }
776
777 void
778 glsl_to_tgsi_visitor::emit_arl(ir_instruction *ir,
779 st_dst_reg dst, st_src_reg src0)
780 {
781 int op = TGSI_OPCODE_ARL;
782
783 if (src0.type == GLSL_TYPE_INT || src0.type == GLSL_TYPE_UINT)
784 op = TGSI_OPCODE_UARL;
785
786 assert(dst.file == PROGRAM_ADDRESS);
787 if (dst.index >= this->num_address_regs)
788 this->num_address_regs = dst.index + 1;
789
790 emit(NULL, op, dst, src0);
791 }
792
793 /**
794 * Emit an TGSI_OPCODE_SCS instruction
795 *
796 * The \c SCS opcode functions a bit differently than the other TGSI opcodes.
797 * Instead of splatting its result across all four components of the
798 * destination, it writes one value to the \c x component and another value to
799 * the \c y component.
800 *
801 * \param ir IR instruction being processed
802 * \param op Either \c TGSI_OPCODE_SIN or \c TGSI_OPCODE_COS depending
803 * on which value is desired.
804 * \param dst Destination register
805 * \param src Source register
806 */
807 void
808 glsl_to_tgsi_visitor::emit_scs(ir_instruction *ir, unsigned op,
809 st_dst_reg dst,
810 const st_src_reg &src)
811 {
812 /* Vertex programs cannot use the SCS opcode.
813 */
814 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
815 emit_scalar(ir, op, dst, src);
816 return;
817 }
818
819 const unsigned component = (op == TGSI_OPCODE_SIN) ? 0 : 1;
820 const unsigned scs_mask = (1U << component);
821 int done_mask = ~dst.writemask;
822 st_src_reg tmp;
823
824 assert(op == TGSI_OPCODE_SIN || op == TGSI_OPCODE_COS);
825
826 /* If there are compnents in the destination that differ from the component
827 * that will be written by the SCS instrution, we'll need a temporary.
828 */
829 if (scs_mask != unsigned(dst.writemask)) {
830 tmp = get_temp(glsl_type::vec4_type);
831 }
832
833 for (unsigned i = 0; i < 4; i++) {
834 unsigned this_mask = (1U << i);
835 st_src_reg src0 = src;
836
837 if ((done_mask & this_mask) != 0)
838 continue;
839
840 /* The source swizzle specified which component of the source generates
841 * sine / cosine for the current component in the destination. The SCS
842 * instruction requires that this value be swizzle to the X component.
843 * Replace the current swizzle with a swizzle that puts the source in
844 * the X component.
845 */
846 unsigned src0_swiz = GET_SWZ(src.swizzle, i);
847
848 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
849 src0_swiz, src0_swiz);
850 for (unsigned j = i + 1; j < 4; j++) {
851 /* If there is another enabled component in the destination that is
852 * derived from the same inputs, generate its value on this pass as
853 * well.
854 */
855 if (!(done_mask & (1 << j)) &&
856 GET_SWZ(src0.swizzle, j) == src0_swiz) {
857 this_mask |= (1 << j);
858 }
859 }
860
861 if (this_mask != scs_mask) {
862 glsl_to_tgsi_instruction *inst;
863 st_dst_reg tmp_dst = st_dst_reg(tmp);
864
865 /* Emit the SCS instruction.
866 */
867 inst = emit(ir, TGSI_OPCODE_SCS, tmp_dst, src0);
868 inst->dst.writemask = scs_mask;
869
870 /* Move the result of the SCS instruction to the desired location in
871 * the destination.
872 */
873 tmp.swizzle = MAKE_SWIZZLE4(component, component,
874 component, component);
875 inst = emit(ir, TGSI_OPCODE_SCS, dst, tmp);
876 inst->dst.writemask = this_mask;
877 } else {
878 /* Emit the SCS instruction to write directly to the destination.
879 */
880 glsl_to_tgsi_instruction *inst = emit(ir, TGSI_OPCODE_SCS, dst, src0);
881 inst->dst.writemask = scs_mask;
882 }
883
884 done_mask |= this_mask;
885 }
886 }
887
888 int
889 glsl_to_tgsi_visitor::add_constant(gl_register_file file,
890 gl_constant_value values[4], int size, int datatype,
891 GLuint *swizzle_out)
892 {
893 if (file == PROGRAM_CONSTANT) {
894 return _mesa_add_typed_unnamed_constant(this->prog->Parameters, values,
895 size, datatype, swizzle_out);
896 } else {
897 int index = 0;
898 immediate_storage *entry;
899 assert(file == PROGRAM_IMMEDIATE);
900
901 /* Search immediate storage to see if we already have an identical
902 * immediate that we can use instead of adding a duplicate entry.
903 */
904 foreach_list(node, &this->immediates) {
905 entry = (immediate_storage *) node;
906
907 if (entry->size == size &&
908 entry->type == datatype &&
909 !memcmp(entry->values, values, size * sizeof(gl_constant_value))) {
910 return index;
911 }
912 index++;
913 }
914
915 /* Add this immediate to the list. */
916 entry = new(mem_ctx) immediate_storage(values, size, datatype);
917 this->immediates.push_tail(entry);
918 this->num_immediates++;
919 return index;
920 }
921 }
922
923 st_src_reg
924 glsl_to_tgsi_visitor::st_src_reg_for_float(float val)
925 {
926 st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_FLOAT);
927 union gl_constant_value uval;
928
929 uval.f = val;
930 src.index = add_constant(src.file, &uval, 1, GL_FLOAT, &src.swizzle);
931
932 return src;
933 }
934
935 st_src_reg
936 glsl_to_tgsi_visitor::st_src_reg_for_int(int val)
937 {
938 st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_INT);
939 union gl_constant_value uval;
940
941 assert(native_integers);
942
943 uval.i = val;
944 src.index = add_constant(src.file, &uval, 1, GL_INT, &src.swizzle);
945
946 return src;
947 }
948
949 st_src_reg
950 glsl_to_tgsi_visitor::st_src_reg_for_type(int type, int val)
951 {
952 if (native_integers)
953 return type == GLSL_TYPE_FLOAT ? st_src_reg_for_float(val) :
954 st_src_reg_for_int(val);
955 else
956 return st_src_reg_for_float(val);
957 }
958
959 static int
960 type_size(const struct glsl_type *type)
961 {
962 unsigned int i;
963 int size;
964
965 switch (type->base_type) {
966 case GLSL_TYPE_UINT:
967 case GLSL_TYPE_INT:
968 case GLSL_TYPE_FLOAT:
969 case GLSL_TYPE_BOOL:
970 if (type->is_matrix()) {
971 return type->matrix_columns;
972 } else {
973 /* Regardless of size of vector, it gets a vec4. This is bad
974 * packing for things like floats, but otherwise arrays become a
975 * mess. Hopefully a later pass over the code can pack scalars
976 * down if appropriate.
977 */
978 return 1;
979 }
980 case GLSL_TYPE_ARRAY:
981 assert(type->length > 0);
982 return type_size(type->fields.array) * type->length;
983 case GLSL_TYPE_STRUCT:
984 size = 0;
985 for (i = 0; i < type->length; i++) {
986 size += type_size(type->fields.structure[i].type);
987 }
988 return size;
989 case GLSL_TYPE_SAMPLER:
990 case GLSL_TYPE_IMAGE:
991 /* Samplers take up one slot in UNIFORMS[], but they're baked in
992 * at link time.
993 */
994 return 1;
995 case GLSL_TYPE_ATOMIC_UINT:
996 case GLSL_TYPE_INTERFACE:
997 case GLSL_TYPE_VOID:
998 case GLSL_TYPE_ERROR:
999 assert(!"Invalid type in type_size");
1000 break;
1001 }
1002 return 0;
1003 }
1004
1005 /**
1006 * In the initial pass of codegen, we assign temporary numbers to
1007 * intermediate results. (not SSA -- variable assignments will reuse
1008 * storage).
1009 */
1010 st_src_reg
1011 glsl_to_tgsi_visitor::get_temp(const glsl_type *type)
1012 {
1013 st_src_reg src;
1014
1015 src.type = native_integers ? type->base_type : GLSL_TYPE_FLOAT;
1016 src.reladdr = NULL;
1017 src.negate = 0;
1018
1019 if (!options->EmitNoIndirectTemp &&
1020 (type->is_array() || type->is_matrix())) {
1021
1022 src.file = PROGRAM_ARRAY;
1023 src.index = next_array << 16 | 0x8000;
1024 array_sizes[next_array] = type_size(type);
1025 ++next_array;
1026
1027 } else {
1028 src.file = PROGRAM_TEMPORARY;
1029 src.index = next_temp;
1030 next_temp += type_size(type);
1031 }
1032
1033 if (type->is_array() || type->is_record()) {
1034 src.swizzle = SWIZZLE_NOOP;
1035 } else {
1036 src.swizzle = swizzle_for_size(type->vector_elements);
1037 }
1038
1039 return src;
1040 }
1041
1042 variable_storage *
1043 glsl_to_tgsi_visitor::find_variable_storage(ir_variable *var)
1044 {
1045
1046 variable_storage *entry;
1047
1048 foreach_list(node, &this->variables) {
1049 entry = (variable_storage *) node;
1050
1051 if (entry->var == var)
1052 return entry;
1053 }
1054
1055 return NULL;
1056 }
1057
1058 void
1059 glsl_to_tgsi_visitor::visit(ir_variable *ir)
1060 {
1061 if (strcmp(ir->name, "gl_FragCoord") == 0) {
1062 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
1063
1064 fp->OriginUpperLeft = ir->data.origin_upper_left;
1065 fp->PixelCenterInteger = ir->data.pixel_center_integer;
1066 }
1067
1068 if (ir->data.mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
1069 unsigned int i;
1070 const ir_state_slot *const slots = ir->state_slots;
1071 assert(ir->state_slots != NULL);
1072
1073 /* Check if this statevar's setup in the STATE file exactly
1074 * matches how we'll want to reference it as a
1075 * struct/array/whatever. If not, then we need to move it into
1076 * temporary storage and hope that it'll get copy-propagated
1077 * out.
1078 */
1079 for (i = 0; i < ir->num_state_slots; i++) {
1080 if (slots[i].swizzle != SWIZZLE_XYZW) {
1081 break;
1082 }
1083 }
1084
1085 variable_storage *storage;
1086 st_dst_reg dst;
1087 if (i == ir->num_state_slots) {
1088 /* We'll set the index later. */
1089 storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
1090 this->variables.push_tail(storage);
1091
1092 dst = undef_dst;
1093 } else {
1094 /* The variable_storage constructor allocates slots based on the size
1095 * of the type. However, this had better match the number of state
1096 * elements that we're going to copy into the new temporary.
1097 */
1098 assert((int) ir->num_state_slots == type_size(ir->type));
1099
1100 dst = st_dst_reg(get_temp(ir->type));
1101
1102 storage = new(mem_ctx) variable_storage(ir, dst.file, dst.index);
1103
1104 this->variables.push_tail(storage);
1105 }
1106
1107
1108 for (unsigned int i = 0; i < ir->num_state_slots; i++) {
1109 int index = _mesa_add_state_reference(this->prog->Parameters,
1110 (gl_state_index *)slots[i].tokens);
1111
1112 if (storage->file == PROGRAM_STATE_VAR) {
1113 if (storage->index == -1) {
1114 storage->index = index;
1115 } else {
1116 assert(index == storage->index + (int)i);
1117 }
1118 } else {
1119 /* We use GLSL_TYPE_FLOAT here regardless of the actual type of
1120 * the data being moved since MOV does not care about the type of
1121 * data it is moving, and we don't want to declare registers with
1122 * array or struct types.
1123 */
1124 st_src_reg src(PROGRAM_STATE_VAR, index, GLSL_TYPE_FLOAT);
1125 src.swizzle = slots[i].swizzle;
1126 emit(ir, TGSI_OPCODE_MOV, dst, src);
1127 /* even a float takes up a whole vec4 reg in a struct/array. */
1128 dst.index++;
1129 }
1130 }
1131
1132 if (storage->file == PROGRAM_TEMPORARY &&
1133 dst.index != storage->index + (int) ir->num_state_slots) {
1134 fail_link(this->shader_program,
1135 "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
1136 ir->name, dst.index - storage->index,
1137 type_size(ir->type));
1138 }
1139 }
1140 }
1141
1142 void
1143 glsl_to_tgsi_visitor::visit(ir_loop *ir)
1144 {
1145 emit(NULL, TGSI_OPCODE_BGNLOOP);
1146
1147 visit_exec_list(&ir->body_instructions, this);
1148
1149 emit(NULL, TGSI_OPCODE_ENDLOOP);
1150 }
1151
1152 void
1153 glsl_to_tgsi_visitor::visit(ir_loop_jump *ir)
1154 {
1155 switch (ir->mode) {
1156 case ir_loop_jump::jump_break:
1157 emit(NULL, TGSI_OPCODE_BRK);
1158 break;
1159 case ir_loop_jump::jump_continue:
1160 emit(NULL, TGSI_OPCODE_CONT);
1161 break;
1162 }
1163 }
1164
1165
1166 void
1167 glsl_to_tgsi_visitor::visit(ir_function_signature *ir)
1168 {
1169 assert(0);
1170 (void)ir;
1171 }
1172
1173 void
1174 glsl_to_tgsi_visitor::visit(ir_function *ir)
1175 {
1176 /* Ignore function bodies other than main() -- we shouldn't see calls to
1177 * them since they should all be inlined before we get to glsl_to_tgsi.
1178 */
1179 if (strcmp(ir->name, "main") == 0) {
1180 const ir_function_signature *sig;
1181 exec_list empty;
1182
1183 sig = ir->matching_signature(NULL, &empty);
1184
1185 assert(sig);
1186
1187 foreach_list(node, &sig->body) {
1188 ir_instruction *ir = (ir_instruction *) node;
1189
1190 ir->accept(this);
1191 }
1192 }
1193 }
1194
1195 bool
1196 glsl_to_tgsi_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
1197 {
1198 int nonmul_operand = 1 - mul_operand;
1199 st_src_reg a, b, c;
1200 st_dst_reg result_dst;
1201
1202 ir_expression *expr = ir->operands[mul_operand]->as_expression();
1203 if (!expr || expr->operation != ir_binop_mul)
1204 return false;
1205
1206 expr->operands[0]->accept(this);
1207 a = this->result;
1208 expr->operands[1]->accept(this);
1209 b = this->result;
1210 ir->operands[nonmul_operand]->accept(this);
1211 c = this->result;
1212
1213 this->result = get_temp(ir->type);
1214 result_dst = st_dst_reg(this->result);
1215 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1216 emit(ir, TGSI_OPCODE_MAD, result_dst, a, b, c);
1217
1218 return true;
1219 }
1220
1221 /**
1222 * Emit MAD(a, -b, a) instead of AND(a, NOT(b))
1223 *
1224 * The logic values are 1.0 for true and 0.0 for false. Logical-and is
1225 * implemented using multiplication, and logical-or is implemented using
1226 * addition. Logical-not can be implemented as (true - x), or (1.0 - x).
1227 * As result, the logical expression (a & !b) can be rewritten as:
1228 *
1229 * - a * !b
1230 * - a * (1 - b)
1231 * - (a * 1) - (a * b)
1232 * - a + -(a * b)
1233 * - a + (a * -b)
1234 *
1235 * This final expression can be implemented as a single MAD(a, -b, a)
1236 * instruction.
1237 */
1238 bool
1239 glsl_to_tgsi_visitor::try_emit_mad_for_and_not(ir_expression *ir, int try_operand)
1240 {
1241 const int other_operand = 1 - try_operand;
1242 st_src_reg a, b;
1243
1244 ir_expression *expr = ir->operands[try_operand]->as_expression();
1245 if (!expr || expr->operation != ir_unop_logic_not)
1246 return false;
1247
1248 ir->operands[other_operand]->accept(this);
1249 a = this->result;
1250 expr->operands[0]->accept(this);
1251 b = this->result;
1252
1253 b.negate = ~b.negate;
1254
1255 this->result = get_temp(ir->type);
1256 emit(ir, TGSI_OPCODE_MAD, st_dst_reg(this->result), a, b, a);
1257
1258 return true;
1259 }
1260
1261 bool
1262 glsl_to_tgsi_visitor::try_emit_sat(ir_expression *ir)
1263 {
1264 /* Emit saturates in the vertex shader only if SM 3.0 is supported.
1265 */
1266 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
1267 !st_context(this->ctx)->has_shader_model3) {
1268 return false;
1269 }
1270
1271 ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
1272 if (!sat_src)
1273 return false;
1274
1275 sat_src->accept(this);
1276 st_src_reg src = this->result;
1277
1278 /* If we generated an expression instruction into a temporary in
1279 * processing the saturate's operand, apply the saturate to that
1280 * instruction. Otherwise, generate a MOV to do the saturate.
1281 *
1282 * Note that we have to be careful to only do this optimization if
1283 * the instruction in question was what generated src->result. For
1284 * example, ir_dereference_array might generate a MUL instruction
1285 * to create the reladdr, and return us a src reg using that
1286 * reladdr. That MUL result is not the value we're trying to
1287 * saturate.
1288 */
1289 ir_expression *sat_src_expr = sat_src->as_expression();
1290 if (sat_src_expr && (sat_src_expr->operation == ir_binop_mul ||
1291 sat_src_expr->operation == ir_binop_add ||
1292 sat_src_expr->operation == ir_binop_dot)) {
1293 glsl_to_tgsi_instruction *new_inst;
1294 new_inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
1295 new_inst->saturate = true;
1296 } else {
1297 this->result = get_temp(ir->type);
1298 st_dst_reg result_dst = st_dst_reg(this->result);
1299 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1300 glsl_to_tgsi_instruction *inst;
1301 inst = emit(ir, TGSI_OPCODE_MOV, result_dst, src);
1302 inst->saturate = true;
1303 }
1304
1305 return true;
1306 }
1307
1308 void
1309 glsl_to_tgsi_visitor::reladdr_to_temp(ir_instruction *ir,
1310 st_src_reg *reg, int *num_reladdr)
1311 {
1312 if (!reg->reladdr && !reg->reladdr2)
1313 return;
1314
1315 if (reg->reladdr) emit_arl(ir, address_reg, *reg->reladdr);
1316 if (reg->reladdr2) emit_arl(ir, address_reg2, *reg->reladdr2);
1317
1318 if (*num_reladdr != 1) {
1319 st_src_reg temp = get_temp(glsl_type::vec4_type);
1320
1321 emit(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), *reg);
1322 *reg = temp;
1323 }
1324
1325 (*num_reladdr)--;
1326 }
1327
1328 void
1329 glsl_to_tgsi_visitor::visit(ir_expression *ir)
1330 {
1331 unsigned int operand;
1332 st_src_reg op[Elements(ir->operands)];
1333 st_src_reg result_src;
1334 st_dst_reg result_dst;
1335
1336 /* Quick peephole: Emit MAD(a, b, c) instead of ADD(MUL(a, b), c)
1337 */
1338 if (ir->operation == ir_binop_add) {
1339 if (try_emit_mad(ir, 1))
1340 return;
1341 if (try_emit_mad(ir, 0))
1342 return;
1343 }
1344
1345 /* Quick peephole: Emit OPCODE_MAD(-a, -b, a) instead of AND(a, NOT(b))
1346 */
1347 if (ir->operation == ir_binop_logic_and) {
1348 if (try_emit_mad_for_and_not(ir, 1))
1349 return;
1350 if (try_emit_mad_for_and_not(ir, 0))
1351 return;
1352 }
1353
1354 if (try_emit_sat(ir))
1355 return;
1356
1357 if (ir->operation == ir_quadop_vector)
1358 assert(!"ir_quadop_vector should have been lowered");
1359
1360 for (operand = 0; operand < ir->get_num_operands(); operand++) {
1361 this->result.file = PROGRAM_UNDEFINED;
1362 ir->operands[operand]->accept(this);
1363 if (this->result.file == PROGRAM_UNDEFINED) {
1364 printf("Failed to get tree for expression operand:\n");
1365 ir->operands[operand]->print();
1366 printf("\n");
1367 exit(1);
1368 }
1369 op[operand] = this->result;
1370
1371 /* Matrix expression operands should have been broken down to vector
1372 * operations already.
1373 */
1374 assert(!ir->operands[operand]->type->is_matrix());
1375 }
1376
1377 int vector_elements = ir->operands[0]->type->vector_elements;
1378 if (ir->operands[1]) {
1379 vector_elements = MAX2(vector_elements,
1380 ir->operands[1]->type->vector_elements);
1381 }
1382
1383 this->result.file = PROGRAM_UNDEFINED;
1384
1385 /* Storage for our result. Ideally for an assignment we'd be using
1386 * the actual storage for the result here, instead.
1387 */
1388 result_src = get_temp(ir->type);
1389 /* convenience for the emit functions below. */
1390 result_dst = st_dst_reg(result_src);
1391 /* Limit writes to the channels that will be used by result_src later.
1392 * This does limit this temp's use as a temporary for multi-instruction
1393 * sequences.
1394 */
1395 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1396
1397 switch (ir->operation) {
1398 case ir_unop_logic_not:
1399 if (result_dst.type != GLSL_TYPE_FLOAT)
1400 emit(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1401 else {
1402 /* Previously 'SEQ dst, src, 0.0' was used for this. However, many
1403 * older GPUs implement SEQ using multiple instructions (i915 uses two
1404 * SGE instructions and a MUL instruction). Since our logic values are
1405 * 0.0 and 1.0, 1-x also implements !x.
1406 */
1407 op[0].negate = ~op[0].negate;
1408 emit(ir, TGSI_OPCODE_ADD, result_dst, op[0], st_src_reg_for_float(1.0));
1409 }
1410 break;
1411 case ir_unop_neg:
1412 if (result_dst.type == GLSL_TYPE_INT || result_dst.type == GLSL_TYPE_UINT)
1413 emit(ir, TGSI_OPCODE_INEG, result_dst, op[0]);
1414 else {
1415 op[0].negate = ~op[0].negate;
1416 result_src = op[0];
1417 }
1418 break;
1419 case ir_unop_abs:
1420 emit(ir, TGSI_OPCODE_ABS, result_dst, op[0]);
1421 break;
1422 case ir_unop_sign:
1423 emit(ir, TGSI_OPCODE_SSG, result_dst, op[0]);
1424 break;
1425 case ir_unop_rcp:
1426 emit_scalar(ir, TGSI_OPCODE_RCP, result_dst, op[0]);
1427 break;
1428
1429 case ir_unop_exp2:
1430 emit_scalar(ir, TGSI_OPCODE_EX2, result_dst, op[0]);
1431 break;
1432 case ir_unop_exp:
1433 case ir_unop_log:
1434 assert(!"not reached: should be handled by ir_explog_to_explog2");
1435 break;
1436 case ir_unop_log2:
1437 emit_scalar(ir, TGSI_OPCODE_LG2, result_dst, op[0]);
1438 break;
1439 case ir_unop_sin:
1440 emit_scalar(ir, TGSI_OPCODE_SIN, result_dst, op[0]);
1441 break;
1442 case ir_unop_cos:
1443 emit_scalar(ir, TGSI_OPCODE_COS, result_dst, op[0]);
1444 break;
1445 case ir_unop_sin_reduced:
1446 emit_scs(ir, TGSI_OPCODE_SIN, result_dst, op[0]);
1447 break;
1448 case ir_unop_cos_reduced:
1449 emit_scs(ir, TGSI_OPCODE_COS, result_dst, op[0]);
1450 break;
1451
1452 case ir_unop_dFdx:
1453 emit(ir, TGSI_OPCODE_DDX, result_dst, op[0]);
1454 break;
1455 case ir_unop_dFdy:
1456 {
1457 /* The X component contains 1 or -1 depending on whether the framebuffer
1458 * is a FBO or the window system buffer, respectively.
1459 * It is then multiplied with the source operand of DDY.
1460 */
1461 static const gl_state_index transform_y_state[STATE_LENGTH]
1462 = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM };
1463
1464 unsigned transform_y_index =
1465 _mesa_add_state_reference(this->prog->Parameters,
1466 transform_y_state);
1467
1468 st_src_reg transform_y = st_src_reg(PROGRAM_STATE_VAR,
1469 transform_y_index,
1470 glsl_type::vec4_type);
1471 transform_y.swizzle = SWIZZLE_XXXX;
1472
1473 st_src_reg temp = get_temp(glsl_type::vec4_type);
1474
1475 emit(ir, TGSI_OPCODE_MUL, st_dst_reg(temp), transform_y, op[0]);
1476 emit(ir, TGSI_OPCODE_DDY, result_dst, temp);
1477 break;
1478 }
1479
1480 case ir_unop_noise: {
1481 /* At some point, a motivated person could add a better
1482 * implementation of noise. Currently not even the nvidia
1483 * binary drivers do anything more than this. In any case, the
1484 * place to do this is in the GL state tracker, not the poor
1485 * driver.
1486 */
1487 emit(ir, TGSI_OPCODE_MOV, result_dst, st_src_reg_for_float(0.5));
1488 break;
1489 }
1490
1491 case ir_binop_add:
1492 emit(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1493 break;
1494 case ir_binop_sub:
1495 emit(ir, TGSI_OPCODE_SUB, result_dst, op[0], op[1]);
1496 break;
1497
1498 case ir_binop_mul:
1499 emit(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1500 break;
1501 case ir_binop_div:
1502 if (result_dst.type == GLSL_TYPE_FLOAT)
1503 assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1504 else
1505 emit(ir, TGSI_OPCODE_DIV, result_dst, op[0], op[1]);
1506 break;
1507 case ir_binop_mod:
1508 if (result_dst.type == GLSL_TYPE_FLOAT)
1509 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1510 else
1511 emit(ir, TGSI_OPCODE_MOD, result_dst, op[0], op[1]);
1512 break;
1513
1514 case ir_binop_less:
1515 emit(ir, TGSI_OPCODE_SLT, result_dst, op[0], op[1]);
1516 break;
1517 case ir_binop_greater:
1518 emit(ir, TGSI_OPCODE_SLT, result_dst, op[1], op[0]);
1519 break;
1520 case ir_binop_lequal:
1521 emit(ir, TGSI_OPCODE_SGE, result_dst, op[1], op[0]);
1522 break;
1523 case ir_binop_gequal:
1524 emit(ir, TGSI_OPCODE_SGE, result_dst, op[0], op[1]);
1525 break;
1526 case ir_binop_equal:
1527 emit(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1528 break;
1529 case ir_binop_nequal:
1530 emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1531 break;
1532 case ir_binop_all_equal:
1533 /* "==" operator producing a scalar boolean. */
1534 if (ir->operands[0]->type->is_vector() ||
1535 ir->operands[1]->type->is_vector()) {
1536 st_src_reg temp = get_temp(native_integers ?
1537 glsl_type::get_instance(ir->operands[0]->type->base_type, 4, 1) :
1538 glsl_type::vec4_type);
1539
1540 if (native_integers) {
1541 st_dst_reg temp_dst = st_dst_reg(temp);
1542 st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1543
1544 emit(ir, TGSI_OPCODE_SEQ, st_dst_reg(temp), op[0], op[1]);
1545
1546 /* Emit 1-3 AND operations to combine the SEQ results. */
1547 switch (ir->operands[0]->type->vector_elements) {
1548 case 2:
1549 break;
1550 case 3:
1551 temp_dst.writemask = WRITEMASK_Y;
1552 temp1.swizzle = SWIZZLE_YYYY;
1553 temp2.swizzle = SWIZZLE_ZZZZ;
1554 emit(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1555 break;
1556 case 4:
1557 temp_dst.writemask = WRITEMASK_X;
1558 temp1.swizzle = SWIZZLE_XXXX;
1559 temp2.swizzle = SWIZZLE_YYYY;
1560 emit(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1561 temp_dst.writemask = WRITEMASK_Y;
1562 temp1.swizzle = SWIZZLE_ZZZZ;
1563 temp2.swizzle = SWIZZLE_WWWW;
1564 emit(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1565 }
1566
1567 temp1.swizzle = SWIZZLE_XXXX;
1568 temp2.swizzle = SWIZZLE_YYYY;
1569 emit(ir, TGSI_OPCODE_AND, result_dst, temp1, temp2);
1570 } else {
1571 emit(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1572
1573 /* After the dot-product, the value will be an integer on the
1574 * range [0,4]. Zero becomes 1.0, and positive values become zero.
1575 */
1576 emit_dp(ir, result_dst, temp, temp, vector_elements);
1577
1578 /* Negating the result of the dot-product gives values on the range
1579 * [-4, 0]. Zero becomes 1.0, and negative values become zero.
1580 * This is achieved using SGE.
1581 */
1582 st_src_reg sge_src = result_src;
1583 sge_src.negate = ~sge_src.negate;
1584 emit(ir, TGSI_OPCODE_SGE, result_dst, sge_src, st_src_reg_for_float(0.0));
1585 }
1586 } else {
1587 emit(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1588 }
1589 break;
1590 case ir_binop_any_nequal:
1591 /* "!=" operator producing a scalar boolean. */
1592 if (ir->operands[0]->type->is_vector() ||
1593 ir->operands[1]->type->is_vector()) {
1594 st_src_reg temp = get_temp(native_integers ?
1595 glsl_type::get_instance(ir->operands[0]->type->base_type, 4, 1) :
1596 glsl_type::vec4_type);
1597 emit(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1598
1599 if (native_integers) {
1600 st_dst_reg temp_dst = st_dst_reg(temp);
1601 st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1602
1603 /* Emit 1-3 OR operations to combine the SNE results. */
1604 switch (ir->operands[0]->type->vector_elements) {
1605 case 2:
1606 break;
1607 case 3:
1608 temp_dst.writemask = WRITEMASK_Y;
1609 temp1.swizzle = SWIZZLE_YYYY;
1610 temp2.swizzle = SWIZZLE_ZZZZ;
1611 emit(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1612 break;
1613 case 4:
1614 temp_dst.writemask = WRITEMASK_X;
1615 temp1.swizzle = SWIZZLE_XXXX;
1616 temp2.swizzle = SWIZZLE_YYYY;
1617 emit(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1618 temp_dst.writemask = WRITEMASK_Y;
1619 temp1.swizzle = SWIZZLE_ZZZZ;
1620 temp2.swizzle = SWIZZLE_WWWW;
1621 emit(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1622 }
1623
1624 temp1.swizzle = SWIZZLE_XXXX;
1625 temp2.swizzle = SWIZZLE_YYYY;
1626 emit(ir, TGSI_OPCODE_OR, result_dst, temp1, temp2);
1627 } else {
1628 /* After the dot-product, the value will be an integer on the
1629 * range [0,4]. Zero stays zero, and positive values become 1.0.
1630 */
1631 glsl_to_tgsi_instruction *const dp =
1632 emit_dp(ir, result_dst, temp, temp, vector_elements);
1633 if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1634 /* The clamping to [0,1] can be done for free in the fragment
1635 * shader with a saturate.
1636 */
1637 dp->saturate = true;
1638 } else {
1639 /* Negating the result of the dot-product gives values on the range
1640 * [-4, 0]. Zero stays zero, and negative values become 1.0. This
1641 * achieved using SLT.
1642 */
1643 st_src_reg slt_src = result_src;
1644 slt_src.negate = ~slt_src.negate;
1645 emit(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1646 }
1647 }
1648 } else {
1649 emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1650 }
1651 break;
1652
1653 case ir_unop_any: {
1654 assert(ir->operands[0]->type->is_vector());
1655
1656 /* After the dot-product, the value will be an integer on the
1657 * range [0,4]. Zero stays zero, and positive values become 1.0.
1658 */
1659 glsl_to_tgsi_instruction *const dp =
1660 emit_dp(ir, result_dst, op[0], op[0],
1661 ir->operands[0]->type->vector_elements);
1662 if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB &&
1663 result_dst.type == GLSL_TYPE_FLOAT) {
1664 /* The clamping to [0,1] can be done for free in the fragment
1665 * shader with a saturate.
1666 */
1667 dp->saturate = true;
1668 } else if (result_dst.type == GLSL_TYPE_FLOAT) {
1669 /* Negating the result of the dot-product gives values on the range
1670 * [-4, 0]. Zero stays zero, and negative values become 1.0. This
1671 * is achieved using SLT.
1672 */
1673 st_src_reg slt_src = result_src;
1674 slt_src.negate = ~slt_src.negate;
1675 emit(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1676 }
1677 else {
1678 /* Use SNE 0 if integers are being used as boolean values. */
1679 emit(ir, TGSI_OPCODE_SNE, result_dst, result_src, st_src_reg_for_int(0));
1680 }
1681 break;
1682 }
1683
1684 case ir_binop_logic_xor:
1685 if (native_integers)
1686 emit(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1687 else
1688 emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1689 break;
1690
1691 case ir_binop_logic_or: {
1692 if (native_integers) {
1693 /* If integers are used as booleans, we can use an actual "or"
1694 * instruction.
1695 */
1696 assert(native_integers);
1697 emit(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1698 } else {
1699 /* After the addition, the value will be an integer on the
1700 * range [0,2]. Zero stays zero, and positive values become 1.0.
1701 */
1702 glsl_to_tgsi_instruction *add =
1703 emit(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1704 if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1705 /* The clamping to [0,1] can be done for free in the fragment
1706 * shader with a saturate if floats are being used as boolean values.
1707 */
1708 add->saturate = true;
1709 } else {
1710 /* Negating the result of the addition gives values on the range
1711 * [-2, 0]. Zero stays zero, and negative values become 1.0. This
1712 * is achieved using SLT.
1713 */
1714 st_src_reg slt_src = result_src;
1715 slt_src.negate = ~slt_src.negate;
1716 emit(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1717 }
1718 }
1719 break;
1720 }
1721
1722 case ir_binop_logic_and:
1723 /* If native integers are disabled, the bool args are stored as float 0.0
1724 * or 1.0, so "mul" gives us "and". If they're enabled, just use the
1725 * actual AND opcode.
1726 */
1727 if (native_integers)
1728 emit(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1729 else
1730 emit(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1731 break;
1732
1733 case ir_binop_dot:
1734 assert(ir->operands[0]->type->is_vector());
1735 assert(ir->operands[0]->type == ir->operands[1]->type);
1736 emit_dp(ir, result_dst, op[0], op[1],
1737 ir->operands[0]->type->vector_elements);
1738 break;
1739
1740 case ir_unop_sqrt:
1741 if (have_sqrt) {
1742 emit_scalar(ir, TGSI_OPCODE_SQRT, result_dst, op[0]);
1743 }
1744 else {
1745 /* sqrt(x) = x * rsq(x). */
1746 emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1747 emit(ir, TGSI_OPCODE_MUL, result_dst, result_src, op[0]);
1748 /* For incoming channels <= 0, set the result to 0. */
1749 op[0].negate = ~op[0].negate;
1750 emit(ir, TGSI_OPCODE_CMP, result_dst,
1751 op[0], result_src, st_src_reg_for_float(0.0));
1752 }
1753 break;
1754 case ir_unop_rsq:
1755 emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1756 break;
1757 case ir_unop_i2f:
1758 if (native_integers) {
1759 emit(ir, TGSI_OPCODE_I2F, result_dst, op[0]);
1760 break;
1761 }
1762 /* fallthrough to next case otherwise */
1763 case ir_unop_b2f:
1764 if (native_integers) {
1765 emit(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_float(1.0));
1766 break;
1767 }
1768 /* fallthrough to next case otherwise */
1769 case ir_unop_i2u:
1770 case ir_unop_u2i:
1771 /* Converting between signed and unsigned integers is a no-op. */
1772 result_src = op[0];
1773 break;
1774 case ir_unop_b2i:
1775 if (native_integers) {
1776 /* Booleans are stored as integers using ~0 for true and 0 for false.
1777 * GLSL requires that int(bool) return 1 for true and 0 for false.
1778 * This conversion is done with AND, but it could be done with NEG.
1779 */
1780 emit(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_int(1));
1781 } else {
1782 /* Booleans and integers are both stored as floats when native
1783 * integers are disabled.
1784 */
1785 result_src = op[0];
1786 }
1787 break;
1788 case ir_unop_f2i:
1789 if (native_integers)
1790 emit(ir, TGSI_OPCODE_F2I, result_dst, op[0]);
1791 else
1792 emit(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1793 break;
1794 case ir_unop_f2u:
1795 if (native_integers)
1796 emit(ir, TGSI_OPCODE_F2U, result_dst, op[0]);
1797 else
1798 emit(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1799 break;
1800 case ir_unop_bitcast_f2i:
1801 result_src = op[0];
1802 result_src.type = GLSL_TYPE_INT;
1803 break;
1804 case ir_unop_bitcast_f2u:
1805 result_src = op[0];
1806 result_src.type = GLSL_TYPE_UINT;
1807 break;
1808 case ir_unop_bitcast_i2f:
1809 case ir_unop_bitcast_u2f:
1810 result_src = op[0];
1811 result_src.type = GLSL_TYPE_FLOAT;
1812 break;
1813 case ir_unop_f2b:
1814 emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1815 break;
1816 case ir_unop_i2b:
1817 if (native_integers)
1818 emit(ir, TGSI_OPCODE_INEG, result_dst, op[0]);
1819 else
1820 emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1821 break;
1822 case ir_unop_trunc:
1823 emit(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1824 break;
1825 case ir_unop_ceil:
1826 emit(ir, TGSI_OPCODE_CEIL, result_dst, op[0]);
1827 break;
1828 case ir_unop_floor:
1829 emit(ir, TGSI_OPCODE_FLR, result_dst, op[0]);
1830 break;
1831 case ir_unop_round_even:
1832 emit(ir, TGSI_OPCODE_ROUND, result_dst, op[0]);
1833 break;
1834 case ir_unop_fract:
1835 emit(ir, TGSI_OPCODE_FRC, result_dst, op[0]);
1836 break;
1837
1838 case ir_binop_min:
1839 emit(ir, TGSI_OPCODE_MIN, result_dst, op[0], op[1]);
1840 break;
1841 case ir_binop_max:
1842 emit(ir, TGSI_OPCODE_MAX, result_dst, op[0], op[1]);
1843 break;
1844 case ir_binop_pow:
1845 emit_scalar(ir, TGSI_OPCODE_POW, result_dst, op[0], op[1]);
1846 break;
1847
1848 case ir_unop_bit_not:
1849 if (native_integers) {
1850 emit(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1851 break;
1852 }
1853 case ir_unop_u2f:
1854 if (native_integers) {
1855 emit(ir, TGSI_OPCODE_U2F, result_dst, op[0]);
1856 break;
1857 }
1858 case ir_binop_lshift:
1859 if (native_integers) {
1860 emit(ir, TGSI_OPCODE_SHL, result_dst, op[0], op[1]);
1861 break;
1862 }
1863 case ir_binop_rshift:
1864 if (native_integers) {
1865 emit(ir, TGSI_OPCODE_ISHR, result_dst, op[0], op[1]);
1866 break;
1867 }
1868 case ir_binop_bit_and:
1869 if (native_integers) {
1870 emit(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1871 break;
1872 }
1873 case ir_binop_bit_xor:
1874 if (native_integers) {
1875 emit(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1876 break;
1877 }
1878 case ir_binop_bit_or:
1879 if (native_integers) {
1880 emit(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1881 break;
1882 }
1883
1884 assert(!"GLSL 1.30 features unsupported");
1885 break;
1886
1887 case ir_binop_ubo_load: {
1888 ir_constant *uniform_block = ir->operands[0]->as_constant();
1889 ir_constant *const_offset_ir = ir->operands[1]->as_constant();
1890 unsigned const_offset = const_offset_ir ? const_offset_ir->value.u[0] : 0;
1891 st_src_reg index_reg = get_temp(glsl_type::uint_type);
1892 st_src_reg cbuf;
1893
1894 cbuf.type = glsl_type::vec4_type->base_type;
1895 cbuf.file = PROGRAM_CONSTANT;
1896 cbuf.index = 0;
1897 cbuf.index2D = uniform_block->value.u[0] + 1;
1898 cbuf.reladdr = NULL;
1899 cbuf.negate = 0;
1900
1901 assert(ir->type->is_vector() || ir->type->is_scalar());
1902
1903 if (const_offset_ir) {
1904 index_reg = st_src_reg_for_int(const_offset / 16);
1905 } else {
1906 emit(ir, TGSI_OPCODE_USHR, st_dst_reg(index_reg), op[1], st_src_reg_for_int(4));
1907 }
1908
1909 cbuf.swizzle = swizzle_for_size(ir->type->vector_elements);
1910 cbuf.swizzle += MAKE_SWIZZLE4(const_offset % 16 / 4,
1911 const_offset % 16 / 4,
1912 const_offset % 16 / 4,
1913 const_offset % 16 / 4);
1914
1915 cbuf.reladdr = ralloc(mem_ctx, st_src_reg);
1916 memcpy(cbuf.reladdr, &index_reg, sizeof(index_reg));
1917
1918 if (ir->type->base_type == GLSL_TYPE_BOOL) {
1919 emit(ir, TGSI_OPCODE_USNE, result_dst, cbuf, st_src_reg_for_int(0));
1920 } else {
1921 emit(ir, TGSI_OPCODE_MOV, result_dst, cbuf);
1922 }
1923 break;
1924 }
1925 case ir_triop_lrp:
1926 /* note: we have to reorder the three args here */
1927 emit(ir, TGSI_OPCODE_LRP, result_dst, op[2], op[1], op[0]);
1928 break;
1929 case ir_triop_csel:
1930 if (this->ctx->Const.NativeIntegers)
1931 emit(ir, TGSI_OPCODE_UCMP, result_dst, op[0], op[1], op[2]);
1932 else {
1933 op[0].negate = ~op[0].negate;
1934 emit(ir, TGSI_OPCODE_CMP, result_dst, op[0], op[1], op[2]);
1935 }
1936 break;
1937 case ir_unop_pack_snorm_2x16:
1938 case ir_unop_pack_unorm_2x16:
1939 case ir_unop_pack_half_2x16:
1940 case ir_unop_pack_snorm_4x8:
1941 case ir_unop_pack_unorm_4x8:
1942 case ir_unop_unpack_snorm_2x16:
1943 case ir_unop_unpack_unorm_2x16:
1944 case ir_unop_unpack_half_2x16:
1945 case ir_unop_unpack_half_2x16_split_x:
1946 case ir_unop_unpack_half_2x16_split_y:
1947 case ir_unop_unpack_snorm_4x8:
1948 case ir_unop_unpack_unorm_4x8:
1949 case ir_binop_pack_half_2x16_split:
1950 case ir_unop_bitfield_reverse:
1951 case ir_unop_bit_count:
1952 case ir_unop_find_msb:
1953 case ir_unop_find_lsb:
1954 case ir_binop_bfm:
1955 case ir_triop_fma:
1956 case ir_triop_bfi:
1957 case ir_triop_bitfield_extract:
1958 case ir_quadop_bitfield_insert:
1959 case ir_quadop_vector:
1960 case ir_binop_vector_extract:
1961 case ir_triop_vector_insert:
1962 case ir_binop_ldexp:
1963 case ir_binop_carry:
1964 case ir_binop_borrow:
1965 case ir_binop_imul_high:
1966 /* This operation is not supported, or should have already been handled.
1967 */
1968 assert(!"Invalid ir opcode in glsl_to_tgsi_visitor::visit()");
1969 break;
1970 }
1971
1972 this->result = result_src;
1973 }
1974
1975
1976 void
1977 glsl_to_tgsi_visitor::visit(ir_swizzle *ir)
1978 {
1979 st_src_reg src;
1980 int i;
1981 int swizzle[4];
1982
1983 /* Note that this is only swizzles in expressions, not those on the left
1984 * hand side of an assignment, which do write masking. See ir_assignment
1985 * for that.
1986 */
1987
1988 ir->val->accept(this);
1989 src = this->result;
1990 assert(src.file != PROGRAM_UNDEFINED);
1991
1992 for (i = 0; i < 4; i++) {
1993 if (i < ir->type->vector_elements) {
1994 switch (i) {
1995 case 0:
1996 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.x);
1997 break;
1998 case 1:
1999 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.y);
2000 break;
2001 case 2:
2002 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.z);
2003 break;
2004 case 3:
2005 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.w);
2006 break;
2007 }
2008 } else {
2009 /* If the type is smaller than a vec4, replicate the last
2010 * channel out.
2011 */
2012 swizzle[i] = swizzle[ir->type->vector_elements - 1];
2013 }
2014 }
2015
2016 src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
2017
2018 this->result = src;
2019 }
2020
2021 void
2022 glsl_to_tgsi_visitor::visit(ir_dereference_variable *ir)
2023 {
2024 variable_storage *entry = find_variable_storage(ir->var);
2025 ir_variable *var = ir->var;
2026
2027 if (!entry) {
2028 switch (var->data.mode) {
2029 case ir_var_uniform:
2030 entry = new(mem_ctx) variable_storage(var, PROGRAM_UNIFORM,
2031 var->data.location);
2032 this->variables.push_tail(entry);
2033 break;
2034 case ir_var_shader_in:
2035 /* The linker assigns locations for varyings and attributes,
2036 * including deprecated builtins (like gl_Color), user-assign
2037 * generic attributes (glBindVertexLocation), and
2038 * user-defined varyings.
2039 */
2040 assert(var->data.location != -1);
2041 entry = new(mem_ctx) variable_storage(var,
2042 PROGRAM_INPUT,
2043 var->data.location);
2044 break;
2045 case ir_var_shader_out:
2046 assert(var->data.location != -1);
2047 entry = new(mem_ctx) variable_storage(var,
2048 PROGRAM_OUTPUT,
2049 var->data.location
2050 + var->data.index);
2051 break;
2052 case ir_var_system_value:
2053 entry = new(mem_ctx) variable_storage(var,
2054 PROGRAM_SYSTEM_VALUE,
2055 var->data.location);
2056 break;
2057 case ir_var_auto:
2058 case ir_var_temporary:
2059 st_src_reg src = get_temp(var->type);
2060
2061 entry = new(mem_ctx) variable_storage(var, src.file, src.index);
2062 this->variables.push_tail(entry);
2063
2064 break;
2065 }
2066
2067 if (!entry) {
2068 printf("Failed to make storage for %s\n", var->name);
2069 exit(1);
2070 }
2071 }
2072
2073 this->result = st_src_reg(entry->file, entry->index, var->type);
2074 if (!native_integers)
2075 this->result.type = GLSL_TYPE_FLOAT;
2076 }
2077
2078 void
2079 glsl_to_tgsi_visitor::visit(ir_dereference_array *ir)
2080 {
2081 ir_constant *index;
2082 st_src_reg src;
2083 int element_size = type_size(ir->type);
2084 bool is_2D_input;
2085
2086 index = ir->array_index->constant_expression_value();
2087
2088 ir->array->accept(this);
2089 src = this->result;
2090
2091 is_2D_input = this->prog->Target == GL_GEOMETRY_PROGRAM_NV &&
2092 src.file == PROGRAM_INPUT &&
2093 ir->array->ir_type != ir_type_dereference_array;
2094
2095 if (is_2D_input)
2096 element_size = 1;
2097
2098 if (index) {
2099 if (is_2D_input) {
2100 src.index2D = index->value.i[0];
2101 src.has_index2 = true;
2102 } else
2103 src.index += index->value.i[0] * element_size;
2104 } else {
2105 /* Variable index array dereference. It eats the "vec4" of the
2106 * base of the array and an index that offsets the TGSI register
2107 * index.
2108 */
2109 ir->array_index->accept(this);
2110
2111 st_src_reg index_reg;
2112
2113 if (element_size == 1) {
2114 index_reg = this->result;
2115 } else {
2116 index_reg = get_temp(native_integers ?
2117 glsl_type::int_type : glsl_type::float_type);
2118
2119 emit(ir, TGSI_OPCODE_MUL, st_dst_reg(index_reg),
2120 this->result, st_src_reg_for_type(index_reg.type, element_size));
2121 }
2122
2123 /* If there was already a relative address register involved, add the
2124 * new and the old together to get the new offset.
2125 */
2126 if (!is_2D_input && src.reladdr != NULL) {
2127 st_src_reg accum_reg = get_temp(native_integers ?
2128 glsl_type::int_type : glsl_type::float_type);
2129
2130 emit(ir, TGSI_OPCODE_ADD, st_dst_reg(accum_reg),
2131 index_reg, *src.reladdr);
2132
2133 index_reg = accum_reg;
2134 }
2135
2136 if (is_2D_input) {
2137 src.reladdr2 = ralloc(mem_ctx, st_src_reg);
2138 memcpy(src.reladdr2, &index_reg, sizeof(index_reg));
2139 src.index2D = 0;
2140 src.has_index2 = true;
2141 } else {
2142 src.reladdr = ralloc(mem_ctx, st_src_reg);
2143 memcpy(src.reladdr, &index_reg, sizeof(index_reg));
2144 }
2145 }
2146
2147 /* If the type is smaller than a vec4, replicate the last channel out. */
2148 if (ir->type->is_scalar() || ir->type->is_vector())
2149 src.swizzle = swizzle_for_size(ir->type->vector_elements);
2150 else
2151 src.swizzle = SWIZZLE_NOOP;
2152
2153 /* Change the register type to the element type of the array. */
2154 src.type = ir->type->base_type;
2155
2156 this->result = src;
2157 }
2158
2159 void
2160 glsl_to_tgsi_visitor::visit(ir_dereference_record *ir)
2161 {
2162 unsigned int i;
2163 const glsl_type *struct_type = ir->record->type;
2164 int offset = 0;
2165
2166 ir->record->accept(this);
2167
2168 for (i = 0; i < struct_type->length; i++) {
2169 if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
2170 break;
2171 offset += type_size(struct_type->fields.structure[i].type);
2172 }
2173
2174 /* If the type is smaller than a vec4, replicate the last channel out. */
2175 if (ir->type->is_scalar() || ir->type->is_vector())
2176 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
2177 else
2178 this->result.swizzle = SWIZZLE_NOOP;
2179
2180 this->result.index += offset;
2181 this->result.type = ir->type->base_type;
2182 }
2183
2184 /**
2185 * We want to be careful in assignment setup to hit the actual storage
2186 * instead of potentially using a temporary like we might with the
2187 * ir_dereference handler.
2188 */
2189 static st_dst_reg
2190 get_assignment_lhs(ir_dereference *ir, glsl_to_tgsi_visitor *v)
2191 {
2192 /* The LHS must be a dereference. If the LHS is a variable indexed array
2193 * access of a vector, it must be separated into a series conditional moves
2194 * before reaching this point (see ir_vec_index_to_cond_assign).
2195 */
2196 assert(ir->as_dereference());
2197 ir_dereference_array *deref_array = ir->as_dereference_array();
2198 if (deref_array) {
2199 assert(!deref_array->array->type->is_vector());
2200 }
2201
2202 /* Use the rvalue deref handler for the most part. We'll ignore
2203 * swizzles in it and write swizzles using writemask, though.
2204 */
2205 ir->accept(v);
2206 return st_dst_reg(v->result);
2207 }
2208
2209 /**
2210 * Process the condition of a conditional assignment
2211 *
2212 * Examines the condition of a conditional assignment to generate the optimal
2213 * first operand of a \c CMP instruction. If the condition is a relational
2214 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
2215 * used as the source for the \c CMP instruction. Otherwise the comparison
2216 * is processed to a boolean result, and the boolean result is used as the
2217 * operand to the CMP instruction.
2218 */
2219 bool
2220 glsl_to_tgsi_visitor::process_move_condition(ir_rvalue *ir)
2221 {
2222 ir_rvalue *src_ir = ir;
2223 bool negate = true;
2224 bool switch_order = false;
2225
2226 ir_expression *const expr = ir->as_expression();
2227 if ((expr != NULL) && (expr->get_num_operands() == 2)) {
2228 bool zero_on_left = false;
2229
2230 if (expr->operands[0]->is_zero()) {
2231 src_ir = expr->operands[1];
2232 zero_on_left = true;
2233 } else if (expr->operands[1]->is_zero()) {
2234 src_ir = expr->operands[0];
2235 zero_on_left = false;
2236 }
2237
2238 /* a is - 0 + - 0 +
2239 * (a < 0) T F F ( a < 0) T F F
2240 * (0 < a) F F T (-a < 0) F F T
2241 * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
2242 * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
2243 * (a > 0) F F T (-a < 0) F F T
2244 * (0 > a) T F F ( a < 0) T F F
2245 * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
2246 * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
2247 *
2248 * Note that exchanging the order of 0 and 'a' in the comparison simply
2249 * means that the value of 'a' should be negated.
2250 */
2251 if (src_ir != ir) {
2252 switch (expr->operation) {
2253 case ir_binop_less:
2254 switch_order = false;
2255 negate = zero_on_left;
2256 break;
2257
2258 case ir_binop_greater:
2259 switch_order = false;
2260 negate = !zero_on_left;
2261 break;
2262
2263 case ir_binop_lequal:
2264 switch_order = true;
2265 negate = !zero_on_left;
2266 break;
2267
2268 case ir_binop_gequal:
2269 switch_order = true;
2270 negate = zero_on_left;
2271 break;
2272
2273 default:
2274 /* This isn't the right kind of comparison afterall, so make sure
2275 * the whole condition is visited.
2276 */
2277 src_ir = ir;
2278 break;
2279 }
2280 }
2281 }
2282
2283 src_ir->accept(this);
2284
2285 /* We use the TGSI_OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
2286 * condition we produced is 0.0 or 1.0. By flipping the sign, we can
2287 * choose which value TGSI_OPCODE_CMP produces without an extra instruction
2288 * computing the condition.
2289 */
2290 if (negate)
2291 this->result.negate = ~this->result.negate;
2292
2293 return switch_order;
2294 }
2295
2296 void
2297 glsl_to_tgsi_visitor::emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
2298 st_dst_reg *l, st_src_reg *r)
2299 {
2300 if (type->base_type == GLSL_TYPE_STRUCT) {
2301 for (unsigned int i = 0; i < type->length; i++) {
2302 emit_block_mov(ir, type->fields.structure[i].type, l, r);
2303 }
2304 return;
2305 }
2306
2307 if (type->is_array()) {
2308 for (unsigned int i = 0; i < type->length; i++) {
2309 emit_block_mov(ir, type->fields.array, l, r);
2310 }
2311 return;
2312 }
2313
2314 if (type->is_matrix()) {
2315 const struct glsl_type *vec_type;
2316
2317 vec_type = glsl_type::get_instance(GLSL_TYPE_FLOAT,
2318 type->vector_elements, 1);
2319
2320 for (int i = 0; i < type->matrix_columns; i++) {
2321 emit_block_mov(ir, vec_type, l, r);
2322 }
2323 return;
2324 }
2325
2326 assert(type->is_scalar() || type->is_vector());
2327
2328 r->type = type->base_type;
2329 emit(ir, TGSI_OPCODE_MOV, *l, *r);
2330 l->index++;
2331 r->index++;
2332 }
2333
2334 void
2335 glsl_to_tgsi_visitor::visit(ir_assignment *ir)
2336 {
2337 st_dst_reg l;
2338 st_src_reg r;
2339 int i;
2340
2341 ir->rhs->accept(this);
2342 r = this->result;
2343
2344 l = get_assignment_lhs(ir->lhs, this);
2345
2346 /* FINISHME: This should really set to the correct maximal writemask for each
2347 * FINISHME: component written (in the loops below). This case can only
2348 * FINISHME: occur for matrices, arrays, and structures.
2349 */
2350 if (ir->write_mask == 0) {
2351 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
2352 l.writemask = WRITEMASK_XYZW;
2353 } else if (ir->lhs->type->is_scalar() &&
2354 ir->lhs->variable_referenced()->data.mode == ir_var_shader_out) {
2355 /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
2356 * FINISHME: W component of fragment shader output zero, work correctly.
2357 */
2358 l.writemask = WRITEMASK_XYZW;
2359 } else {
2360 int swizzles[4];
2361 int first_enabled_chan = 0;
2362 int rhs_chan = 0;
2363
2364 l.writemask = ir->write_mask;
2365
2366 for (int i = 0; i < 4; i++) {
2367 if (l.writemask & (1 << i)) {
2368 first_enabled_chan = GET_SWZ(r.swizzle, i);
2369 break;
2370 }
2371 }
2372
2373 /* Swizzle a small RHS vector into the channels being written.
2374 *
2375 * glsl ir treats write_mask as dictating how many channels are
2376 * present on the RHS while TGSI treats write_mask as just
2377 * showing which channels of the vec4 RHS get written.
2378 */
2379 for (int i = 0; i < 4; i++) {
2380 if (l.writemask & (1 << i))
2381 swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
2382 else
2383 swizzles[i] = first_enabled_chan;
2384 }
2385 r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
2386 swizzles[2], swizzles[3]);
2387 }
2388
2389 assert(l.file != PROGRAM_UNDEFINED);
2390 assert(r.file != PROGRAM_UNDEFINED);
2391
2392 if (ir->condition) {
2393 const bool switch_order = this->process_move_condition(ir->condition);
2394 st_src_reg condition = this->result;
2395
2396 for (i = 0; i < type_size(ir->lhs->type); i++) {
2397 st_src_reg l_src = st_src_reg(l);
2398 st_src_reg condition_temp = condition;
2399 l_src.swizzle = swizzle_for_size(ir->lhs->type->vector_elements);
2400
2401 if (native_integers) {
2402 /* This is necessary because TGSI's CMP instruction expects the
2403 * condition to be a float, and we store booleans as integers.
2404 * TODO: really want to avoid i2f path and use UCMP. Requires
2405 * changes to process_move_condition though too.
2406 */
2407 condition_temp = get_temp(glsl_type::vec4_type);
2408 condition.negate = 0;
2409 emit(ir, TGSI_OPCODE_I2F, st_dst_reg(condition_temp), condition);
2410 condition_temp.swizzle = condition.swizzle;
2411 }
2412
2413 if (switch_order) {
2414 emit(ir, TGSI_OPCODE_CMP, l, condition_temp, l_src, r);
2415 } else {
2416 emit(ir, TGSI_OPCODE_CMP, l, condition_temp, r, l_src);
2417 }
2418
2419 l.index++;
2420 r.index++;
2421 }
2422 } else if (ir->rhs->as_expression() &&
2423 this->instructions.get_tail() &&
2424 ir->rhs == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->ir &&
2425 type_size(ir->lhs->type) == 1 &&
2426 l.writemask == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->dst.writemask) {
2427 /* To avoid emitting an extra MOV when assigning an expression to a
2428 * variable, emit the last instruction of the expression again, but
2429 * replace the destination register with the target of the assignment.
2430 * Dead code elimination will remove the original instruction.
2431 */
2432 glsl_to_tgsi_instruction *inst, *new_inst;
2433 inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
2434 new_inst = emit(ir, inst->op, l, inst->src[0], inst->src[1], inst->src[2]);
2435 new_inst->saturate = inst->saturate;
2436 inst->dead_mask = inst->dst.writemask;
2437 } else {
2438 emit_block_mov(ir, ir->rhs->type, &l, &r);
2439 }
2440 }
2441
2442
2443 void
2444 glsl_to_tgsi_visitor::visit(ir_constant *ir)
2445 {
2446 st_src_reg src;
2447 GLfloat stack_vals[4] = { 0 };
2448 gl_constant_value *values = (gl_constant_value *) stack_vals;
2449 GLenum gl_type = GL_NONE;
2450 unsigned int i;
2451 static int in_array = 0;
2452 gl_register_file file = in_array ? PROGRAM_CONSTANT : PROGRAM_IMMEDIATE;
2453
2454 /* Unfortunately, 4 floats is all we can get into
2455 * _mesa_add_typed_unnamed_constant. So, make a temp to store an
2456 * aggregate constant and move each constant value into it. If we
2457 * get lucky, copy propagation will eliminate the extra moves.
2458 */
2459 if (ir->type->base_type == GLSL_TYPE_STRUCT) {
2460 st_src_reg temp_base = get_temp(ir->type);
2461 st_dst_reg temp = st_dst_reg(temp_base);
2462
2463 foreach_list(node, &ir->components) {
2464 ir_constant *field_value = (ir_constant *) node;
2465 int size = type_size(field_value->type);
2466
2467 assert(size > 0);
2468
2469 field_value->accept(this);
2470 src = this->result;
2471
2472 for (i = 0; i < (unsigned int)size; i++) {
2473 emit(ir, TGSI_OPCODE_MOV, temp, src);
2474
2475 src.index++;
2476 temp.index++;
2477 }
2478 }
2479 this->result = temp_base;
2480 return;
2481 }
2482
2483 if (ir->type->is_array()) {
2484 st_src_reg temp_base = get_temp(ir->type);
2485 st_dst_reg temp = st_dst_reg(temp_base);
2486 int size = type_size(ir->type->fields.array);
2487
2488 assert(size > 0);
2489 in_array++;
2490
2491 for (i = 0; i < ir->type->length; i++) {
2492 ir->array_elements[i]->accept(this);
2493 src = this->result;
2494 for (int j = 0; j < size; j++) {
2495 emit(ir, TGSI_OPCODE_MOV, temp, src);
2496
2497 src.index++;
2498 temp.index++;
2499 }
2500 }
2501 this->result = temp_base;
2502 in_array--;
2503 return;
2504 }
2505
2506 if (ir->type->is_matrix()) {
2507 st_src_reg mat = get_temp(ir->type);
2508 st_dst_reg mat_column = st_dst_reg(mat);
2509
2510 for (i = 0; i < ir->type->matrix_columns; i++) {
2511 assert(ir->type->base_type == GLSL_TYPE_FLOAT);
2512 values = (gl_constant_value *) &ir->value.f[i * ir->type->vector_elements];
2513
2514 src = st_src_reg(file, -1, ir->type->base_type);
2515 src.index = add_constant(file,
2516 values,
2517 ir->type->vector_elements,
2518 GL_FLOAT,
2519 &src.swizzle);
2520 emit(ir, TGSI_OPCODE_MOV, mat_column, src);
2521
2522 mat_column.index++;
2523 }
2524
2525 this->result = mat;
2526 return;
2527 }
2528
2529 switch (ir->type->base_type) {
2530 case GLSL_TYPE_FLOAT:
2531 gl_type = GL_FLOAT;
2532 for (i = 0; i < ir->type->vector_elements; i++) {
2533 values[i].f = ir->value.f[i];
2534 }
2535 break;
2536 case GLSL_TYPE_UINT:
2537 gl_type = native_integers ? GL_UNSIGNED_INT : GL_FLOAT;
2538 for (i = 0; i < ir->type->vector_elements; i++) {
2539 if (native_integers)
2540 values[i].u = ir->value.u[i];
2541 else
2542 values[i].f = ir->value.u[i];
2543 }
2544 break;
2545 case GLSL_TYPE_INT:
2546 gl_type = native_integers ? GL_INT : GL_FLOAT;
2547 for (i = 0; i < ir->type->vector_elements; i++) {
2548 if (native_integers)
2549 values[i].i = ir->value.i[i];
2550 else
2551 values[i].f = ir->value.i[i];
2552 }
2553 break;
2554 case GLSL_TYPE_BOOL:
2555 gl_type = native_integers ? GL_BOOL : GL_FLOAT;
2556 for (i = 0; i < ir->type->vector_elements; i++) {
2557 if (native_integers)
2558 values[i].u = ir->value.b[i] ? ~0 : 0;
2559 else
2560 values[i].f = ir->value.b[i];
2561 }
2562 break;
2563 default:
2564 assert(!"Non-float/uint/int/bool constant");
2565 }
2566
2567 this->result = st_src_reg(file, -1, ir->type);
2568 this->result.index = add_constant(file,
2569 values,
2570 ir->type->vector_elements,
2571 gl_type,
2572 &this->result.swizzle);
2573 }
2574
2575 function_entry *
2576 glsl_to_tgsi_visitor::get_function_signature(ir_function_signature *sig)
2577 {
2578 function_entry *entry;
2579
2580 foreach_list(node, &this->function_signatures) {
2581 entry = (function_entry *) node;
2582
2583 if (entry->sig == sig)
2584 return entry;
2585 }
2586
2587 entry = ralloc(mem_ctx, function_entry);
2588 entry->sig = sig;
2589 entry->sig_id = this->next_signature_id++;
2590 entry->bgn_inst = NULL;
2591
2592 /* Allocate storage for all the parameters. */
2593 foreach_list(node, &sig->parameters) {
2594 ir_variable *param = (ir_variable *) node;
2595 variable_storage *storage;
2596
2597 storage = find_variable_storage(param);
2598 assert(!storage);
2599
2600 st_src_reg src = get_temp(param->type);
2601
2602 storage = new(mem_ctx) variable_storage(param, src.file, src.index);
2603 this->variables.push_tail(storage);
2604 }
2605
2606 if (!sig->return_type->is_void()) {
2607 entry->return_reg = get_temp(sig->return_type);
2608 } else {
2609 entry->return_reg = undef_src;
2610 }
2611
2612 this->function_signatures.push_tail(entry);
2613 return entry;
2614 }
2615
2616 void
2617 glsl_to_tgsi_visitor::visit(ir_call *ir)
2618 {
2619 glsl_to_tgsi_instruction *call_inst;
2620 ir_function_signature *sig = ir->callee;
2621 function_entry *entry = get_function_signature(sig);
2622 int i;
2623
2624 /* Process in parameters. */
2625 foreach_two_lists(formal_node, &sig->parameters,
2626 actual_node, &ir->actual_parameters) {
2627 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
2628 ir_variable *param = (ir_variable *) formal_node;
2629
2630 if (param->data.mode == ir_var_function_in ||
2631 param->data.mode == ir_var_function_inout) {
2632 variable_storage *storage = find_variable_storage(param);
2633 assert(storage);
2634
2635 param_rval->accept(this);
2636 st_src_reg r = this->result;
2637
2638 st_dst_reg l;
2639 l.file = storage->file;
2640 l.index = storage->index;
2641 l.reladdr = NULL;
2642 l.writemask = WRITEMASK_XYZW;
2643 l.cond_mask = COND_TR;
2644
2645 for (i = 0; i < type_size(param->type); i++) {
2646 emit(ir, TGSI_OPCODE_MOV, l, r);
2647 l.index++;
2648 r.index++;
2649 }
2650 }
2651 }
2652
2653 /* Emit call instruction */
2654 call_inst = emit(ir, TGSI_OPCODE_CAL);
2655 call_inst->function = entry;
2656
2657 /* Process out parameters. */
2658 foreach_two_lists(formal_node, &sig->parameters,
2659 actual_node, &ir->actual_parameters) {
2660 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
2661 ir_variable *param = (ir_variable *) formal_node;
2662
2663 if (param->data.mode == ir_var_function_out ||
2664 param->data.mode == ir_var_function_inout) {
2665 variable_storage *storage = find_variable_storage(param);
2666 assert(storage);
2667
2668 st_src_reg r;
2669 r.file = storage->file;
2670 r.index = storage->index;
2671 r.reladdr = NULL;
2672 r.swizzle = SWIZZLE_NOOP;
2673 r.negate = 0;
2674
2675 param_rval->accept(this);
2676 st_dst_reg l = st_dst_reg(this->result);
2677
2678 for (i = 0; i < type_size(param->type); i++) {
2679 emit(ir, TGSI_OPCODE_MOV, l, r);
2680 l.index++;
2681 r.index++;
2682 }
2683 }
2684 }
2685
2686 /* Process return value. */
2687 this->result = entry->return_reg;
2688 }
2689
2690 void
2691 glsl_to_tgsi_visitor::visit(ir_texture *ir)
2692 {
2693 st_src_reg result_src, coord, cube_sc, lod_info, projector, dx, dy, offset, sample_index, component;
2694 st_dst_reg result_dst, coord_dst, cube_sc_dst;
2695 glsl_to_tgsi_instruction *inst = NULL;
2696 unsigned opcode = TGSI_OPCODE_NOP;
2697 const glsl_type *sampler_type = ir->sampler->type;
2698 bool is_cube_array = false;
2699
2700 /* if we are a cube array sampler */
2701 if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE &&
2702 sampler_type->sampler_array)) {
2703 is_cube_array = true;
2704 }
2705
2706 if (ir->coordinate) {
2707 ir->coordinate->accept(this);
2708
2709 /* Put our coords in a temp. We'll need to modify them for shadow,
2710 * projection, or LOD, so the only case we'd use it as is is if
2711 * we're doing plain old texturing. The optimization passes on
2712 * glsl_to_tgsi_visitor should handle cleaning up our mess in that case.
2713 */
2714 coord = get_temp(glsl_type::vec4_type);
2715 coord_dst = st_dst_reg(coord);
2716 coord_dst.writemask = (1 << ir->coordinate->type->vector_elements) - 1;
2717 emit(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
2718 }
2719
2720 if (ir->projector) {
2721 ir->projector->accept(this);
2722 projector = this->result;
2723 }
2724
2725 /* Storage for our result. Ideally for an assignment we'd be using
2726 * the actual storage for the result here, instead.
2727 */
2728 result_src = get_temp(ir->type);
2729 result_dst = st_dst_reg(result_src);
2730
2731 switch (ir->op) {
2732 case ir_tex:
2733 opcode = (is_cube_array && ir->shadow_comparitor) ? TGSI_OPCODE_TEX2 : TGSI_OPCODE_TEX;
2734 if (ir->offset) {
2735 ir->offset->accept(this);
2736 offset = this->result;
2737 }
2738 break;
2739 case ir_txb:
2740 opcode = is_cube_array ? TGSI_OPCODE_TXB2 : TGSI_OPCODE_TXB;
2741 ir->lod_info.bias->accept(this);
2742 lod_info = this->result;
2743 if (ir->offset) {
2744 ir->offset->accept(this);
2745 offset = this->result;
2746 }
2747 break;
2748 case ir_txl:
2749 opcode = is_cube_array ? TGSI_OPCODE_TXL2 : TGSI_OPCODE_TXL;
2750 ir->lod_info.lod->accept(this);
2751 lod_info = this->result;
2752 if (ir->offset) {
2753 ir->offset->accept(this);
2754 offset = this->result;
2755 }
2756 break;
2757 case ir_txd:
2758 opcode = TGSI_OPCODE_TXD;
2759 ir->lod_info.grad.dPdx->accept(this);
2760 dx = this->result;
2761 ir->lod_info.grad.dPdy->accept(this);
2762 dy = this->result;
2763 if (ir->offset) {
2764 ir->offset->accept(this);
2765 offset = this->result;
2766 }
2767 break;
2768 case ir_txs:
2769 opcode = TGSI_OPCODE_TXQ;
2770 ir->lod_info.lod->accept(this);
2771 lod_info = this->result;
2772 break;
2773 case ir_txf:
2774 opcode = TGSI_OPCODE_TXF;
2775 ir->lod_info.lod->accept(this);
2776 lod_info = this->result;
2777 if (ir->offset) {
2778 ir->offset->accept(this);
2779 offset = this->result;
2780 }
2781 break;
2782 case ir_txf_ms:
2783 opcode = TGSI_OPCODE_TXF;
2784 ir->lod_info.sample_index->accept(this);
2785 sample_index = this->result;
2786 break;
2787 case ir_tg4:
2788 opcode = TGSI_OPCODE_TG4;
2789 ir->lod_info.component->accept(this);
2790 component = this->result;
2791 if (ir->offset) {
2792 ir->offset->accept(this);
2793 /* this should have been lowered */
2794 assert(ir->offset->type->base_type != GLSL_TYPE_ARRAY);
2795 offset = this->result;
2796 }
2797 break;
2798 case ir_lod:
2799 opcode = TGSI_OPCODE_LODQ;
2800 break;
2801 case ir_query_levels:
2802 assert(!"Unexpected ir_query_levels opcode");
2803 break;
2804 }
2805
2806 if (ir->projector) {
2807 if (opcode == TGSI_OPCODE_TEX) {
2808 /* Slot the projector in as the last component of the coord. */
2809 coord_dst.writemask = WRITEMASK_W;
2810 emit(ir, TGSI_OPCODE_MOV, coord_dst, projector);
2811 coord_dst.writemask = WRITEMASK_XYZW;
2812 opcode = TGSI_OPCODE_TXP;
2813 } else {
2814 st_src_reg coord_w = coord;
2815 coord_w.swizzle = SWIZZLE_WWWW;
2816
2817 /* For the other TEX opcodes there's no projective version
2818 * since the last slot is taken up by LOD info. Do the
2819 * projective divide now.
2820 */
2821 coord_dst.writemask = WRITEMASK_W;
2822 emit(ir, TGSI_OPCODE_RCP, coord_dst, projector);
2823
2824 /* In the case where we have to project the coordinates "by hand,"
2825 * the shadow comparator value must also be projected.
2826 */
2827 st_src_reg tmp_src = coord;
2828 if (ir->shadow_comparitor) {
2829 /* Slot the shadow value in as the second to last component of the
2830 * coord.
2831 */
2832 ir->shadow_comparitor->accept(this);
2833
2834 tmp_src = get_temp(glsl_type::vec4_type);
2835 st_dst_reg tmp_dst = st_dst_reg(tmp_src);
2836
2837 /* Projective division not allowed for array samplers. */
2838 assert(!sampler_type->sampler_array);
2839
2840 tmp_dst.writemask = WRITEMASK_Z;
2841 emit(ir, TGSI_OPCODE_MOV, tmp_dst, this->result);
2842
2843 tmp_dst.writemask = WRITEMASK_XY;
2844 emit(ir, TGSI_OPCODE_MOV, tmp_dst, coord);
2845 }
2846
2847 coord_dst.writemask = WRITEMASK_XYZ;
2848 emit(ir, TGSI_OPCODE_MUL, coord_dst, tmp_src, coord_w);
2849
2850 coord_dst.writemask = WRITEMASK_XYZW;
2851 coord.swizzle = SWIZZLE_XYZW;
2852 }
2853 }
2854
2855 /* If projection is done and the opcode is not TGSI_OPCODE_TXP, then the shadow
2856 * comparator was put in the correct place (and projected) by the code,
2857 * above, that handles by-hand projection.
2858 */
2859 if (ir->shadow_comparitor && (!ir->projector || opcode == TGSI_OPCODE_TXP)) {
2860 /* Slot the shadow value in as the second to last component of the
2861 * coord.
2862 */
2863 ir->shadow_comparitor->accept(this);
2864
2865 if (is_cube_array) {
2866 cube_sc = get_temp(glsl_type::float_type);
2867 cube_sc_dst = st_dst_reg(cube_sc);
2868 cube_sc_dst.writemask = WRITEMASK_X;
2869 emit(ir, TGSI_OPCODE_MOV, cube_sc_dst, this->result);
2870 cube_sc_dst.writemask = WRITEMASK_X;
2871 }
2872 else {
2873 if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_2D &&
2874 sampler_type->sampler_array) ||
2875 sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE) {
2876 coord_dst.writemask = WRITEMASK_W;
2877 } else {
2878 coord_dst.writemask = WRITEMASK_Z;
2879 }
2880
2881 emit(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
2882 coord_dst.writemask = WRITEMASK_XYZW;
2883 }
2884 }
2885
2886 if (ir->op == ir_txf_ms) {
2887 coord_dst.writemask = WRITEMASK_W;
2888 emit(ir, TGSI_OPCODE_MOV, coord_dst, sample_index);
2889 coord_dst.writemask = WRITEMASK_XYZW;
2890 } else if (opcode == TGSI_OPCODE_TXL || opcode == TGSI_OPCODE_TXB ||
2891 opcode == TGSI_OPCODE_TXF) {
2892 /* TGSI stores LOD or LOD bias in the last channel of the coords. */
2893 coord_dst.writemask = WRITEMASK_W;
2894 emit(ir, TGSI_OPCODE_MOV, coord_dst, lod_info);
2895 coord_dst.writemask = WRITEMASK_XYZW;
2896 }
2897
2898 if (opcode == TGSI_OPCODE_TXD)
2899 inst = emit(ir, opcode, result_dst, coord, dx, dy);
2900 else if (opcode == TGSI_OPCODE_TXQ)
2901 inst = emit(ir, opcode, result_dst, lod_info);
2902 else if (opcode == TGSI_OPCODE_TXF) {
2903 inst = emit(ir, opcode, result_dst, coord);
2904 } else if (opcode == TGSI_OPCODE_TXL2 || opcode == TGSI_OPCODE_TXB2) {
2905 inst = emit(ir, opcode, result_dst, coord, lod_info);
2906 } else if (opcode == TGSI_OPCODE_TEX2) {
2907 inst = emit(ir, opcode, result_dst, coord, cube_sc);
2908 } else if (opcode == TGSI_OPCODE_TG4) {
2909 if (is_cube_array && ir->shadow_comparitor) {
2910 inst = emit(ir, opcode, result_dst, coord, cube_sc);
2911 } else {
2912 inst = emit(ir, opcode, result_dst, coord, component);
2913 }
2914 } else
2915 inst = emit(ir, opcode, result_dst, coord);
2916
2917 if (ir->shadow_comparitor)
2918 inst->tex_shadow = GL_TRUE;
2919
2920 inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
2921 this->shader_program,
2922 this->prog);
2923
2924 if (ir->offset) {
2925 inst->tex_offset_num_offset = 1;
2926 inst->tex_offsets[0] = offset;
2927 }
2928
2929 switch (sampler_type->sampler_dimensionality) {
2930 case GLSL_SAMPLER_DIM_1D:
2931 inst->tex_target = (sampler_type->sampler_array)
2932 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
2933 break;
2934 case GLSL_SAMPLER_DIM_2D:
2935 inst->tex_target = (sampler_type->sampler_array)
2936 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
2937 break;
2938 case GLSL_SAMPLER_DIM_3D:
2939 inst->tex_target = TEXTURE_3D_INDEX;
2940 break;
2941 case GLSL_SAMPLER_DIM_CUBE:
2942 inst->tex_target = (sampler_type->sampler_array)
2943 ? TEXTURE_CUBE_ARRAY_INDEX : TEXTURE_CUBE_INDEX;
2944 break;
2945 case GLSL_SAMPLER_DIM_RECT:
2946 inst->tex_target = TEXTURE_RECT_INDEX;
2947 break;
2948 case GLSL_SAMPLER_DIM_BUF:
2949 inst->tex_target = TEXTURE_BUFFER_INDEX;
2950 break;
2951 case GLSL_SAMPLER_DIM_EXTERNAL:
2952 inst->tex_target = TEXTURE_EXTERNAL_INDEX;
2953 break;
2954 case GLSL_SAMPLER_DIM_MS:
2955 inst->tex_target = (sampler_type->sampler_array)
2956 ? TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX : TEXTURE_2D_MULTISAMPLE_INDEX;
2957 break;
2958 default:
2959 assert(!"Should not get here.");
2960 }
2961
2962 this->result = result_src;
2963 }
2964
2965 void
2966 glsl_to_tgsi_visitor::visit(ir_return *ir)
2967 {
2968 if (ir->get_value()) {
2969 st_dst_reg l;
2970 int i;
2971
2972 assert(current_function);
2973
2974 ir->get_value()->accept(this);
2975 st_src_reg r = this->result;
2976
2977 l = st_dst_reg(current_function->return_reg);
2978
2979 for (i = 0; i < type_size(current_function->sig->return_type); i++) {
2980 emit(ir, TGSI_OPCODE_MOV, l, r);
2981 l.index++;
2982 r.index++;
2983 }
2984 }
2985
2986 emit(ir, TGSI_OPCODE_RET);
2987 }
2988
2989 void
2990 glsl_to_tgsi_visitor::visit(ir_discard *ir)
2991 {
2992 if (ir->condition) {
2993 ir->condition->accept(this);
2994 this->result.negate = ~this->result.negate;
2995 emit(ir, TGSI_OPCODE_KILL_IF, undef_dst, this->result);
2996 } else {
2997 /* unconditional kil */
2998 emit(ir, TGSI_OPCODE_KILL);
2999 }
3000 }
3001
3002 void
3003 glsl_to_tgsi_visitor::visit(ir_if *ir)
3004 {
3005 unsigned if_opcode;
3006 glsl_to_tgsi_instruction *if_inst;
3007
3008 ir->condition->accept(this);
3009 assert(this->result.file != PROGRAM_UNDEFINED);
3010
3011 if_opcode = native_integers ? TGSI_OPCODE_UIF : TGSI_OPCODE_IF;
3012
3013 if_inst = emit(ir->condition, if_opcode, undef_dst, this->result);
3014
3015 this->instructions.push_tail(if_inst);
3016
3017 visit_exec_list(&ir->then_instructions, this);
3018
3019 if (!ir->else_instructions.is_empty()) {
3020 emit(ir->condition, TGSI_OPCODE_ELSE);
3021 visit_exec_list(&ir->else_instructions, this);
3022 }
3023
3024 if_inst = emit(ir->condition, TGSI_OPCODE_ENDIF);
3025 }
3026
3027
3028 void
3029 glsl_to_tgsi_visitor::visit(ir_emit_vertex *ir)
3030 {
3031 assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
3032 emit(ir, TGSI_OPCODE_EMIT);
3033 }
3034
3035 void
3036 glsl_to_tgsi_visitor::visit(ir_end_primitive *ir)
3037 {
3038 assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
3039 emit(ir, TGSI_OPCODE_ENDPRIM);
3040 }
3041
3042 glsl_to_tgsi_visitor::glsl_to_tgsi_visitor()
3043 {
3044 result.file = PROGRAM_UNDEFINED;
3045 next_temp = 1;
3046 next_array = 0;
3047 next_signature_id = 1;
3048 num_immediates = 0;
3049 current_function = NULL;
3050 num_address_regs = 0;
3051 samplers_used = 0;
3052 indirect_addr_consts = false;
3053 glsl_version = 0;
3054 native_integers = false;
3055 mem_ctx = ralloc_context(NULL);
3056 ctx = NULL;
3057 prog = NULL;
3058 shader_program = NULL;
3059 options = NULL;
3060 }
3061
3062 glsl_to_tgsi_visitor::~glsl_to_tgsi_visitor()
3063 {
3064 ralloc_free(mem_ctx);
3065 }
3066
3067 extern "C" void free_glsl_to_tgsi_visitor(glsl_to_tgsi_visitor *v)
3068 {
3069 delete v;
3070 }
3071
3072
3073 /**
3074 * Count resources used by the given gpu program (number of texture
3075 * samplers, etc).
3076 */
3077 static void
3078 count_resources(glsl_to_tgsi_visitor *v, gl_program *prog)
3079 {
3080 v->samplers_used = 0;
3081
3082 foreach_list(node, &v->instructions) {
3083 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3084
3085 if (is_tex_instruction(inst->op)) {
3086 v->samplers_used |= 1 << inst->sampler;
3087
3088 if (inst->tex_shadow) {
3089 prog->ShadowSamplers |= 1 << inst->sampler;
3090 }
3091 }
3092 }
3093
3094 prog->SamplersUsed = v->samplers_used;
3095
3096 if (v->shader_program != NULL)
3097 _mesa_update_shader_textures_used(v->shader_program, prog);
3098 }
3099
3100 static void
3101 set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
3102 struct gl_shader_program *shader_program,
3103 const char *name, const glsl_type *type,
3104 ir_constant *val)
3105 {
3106 if (type->is_record()) {
3107 ir_constant *field_constant;
3108
3109 field_constant = (ir_constant *)val->components.get_head();
3110
3111 for (unsigned int i = 0; i < type->length; i++) {
3112 const glsl_type *field_type = type->fields.structure[i].type;
3113 const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
3114 type->fields.structure[i].name);
3115 set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
3116 field_type, field_constant);
3117 field_constant = (ir_constant *)field_constant->next;
3118 }
3119 return;
3120 }
3121
3122 unsigned offset;
3123 unsigned index = _mesa_get_uniform_location(ctx, shader_program, name,
3124 &offset);
3125 if (offset == GL_INVALID_INDEX) {
3126 fail_link(shader_program,
3127 "Couldn't find uniform for initializer %s\n", name);
3128 return;
3129 }
3130 int loc = _mesa_uniform_merge_location_offset(shader_program, index, offset);
3131
3132 for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
3133 ir_constant *element;
3134 const glsl_type *element_type;
3135 if (type->is_array()) {
3136 element = val->array_elements[i];
3137 element_type = type->fields.array;
3138 } else {
3139 element = val;
3140 element_type = type;
3141 }
3142
3143 void *values;
3144
3145 if (element_type->base_type == GLSL_TYPE_BOOL) {
3146 int *conv = ralloc_array(mem_ctx, int, element_type->components());
3147 for (unsigned int j = 0; j < element_type->components(); j++) {
3148 conv[j] = element->value.b[j];
3149 }
3150 values = (void *)conv;
3151 element_type = glsl_type::get_instance(GLSL_TYPE_INT,
3152 element_type->vector_elements,
3153 1);
3154 } else {
3155 values = &element->value;
3156 }
3157
3158 if (element_type->is_matrix()) {
3159 _mesa_uniform_matrix(ctx, shader_program,
3160 element_type->matrix_columns,
3161 element_type->vector_elements,
3162 loc, 1, GL_FALSE, (GLfloat *)values);
3163 } else {
3164 _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
3165 values, element_type->gl_type);
3166 }
3167
3168 loc++;
3169 }
3170 }
3171
3172 /**
3173 * Returns the mask of channels (bitmask of WRITEMASK_X,Y,Z,W) which
3174 * are read from the given src in this instruction
3175 */
3176 static int
3177 get_src_arg_mask(st_dst_reg dst, st_src_reg src)
3178 {
3179 int read_mask = 0, comp;
3180
3181 /* Now, given the src swizzle and the written channels, find which
3182 * components are actually read
3183 */
3184 for (comp = 0; comp < 4; ++comp) {
3185 const unsigned coord = GET_SWZ(src.swizzle, comp);
3186 ASSERT(coord < 4);
3187 if (dst.writemask & (1 << comp) && coord <= SWIZZLE_W)
3188 read_mask |= 1 << coord;
3189 }
3190
3191 return read_mask;
3192 }
3193
3194 /**
3195 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
3196 * instruction is the first instruction to write to register T0. There are
3197 * several lowering passes done in GLSL IR (e.g. branches and
3198 * relative addressing) that create a large number of conditional assignments
3199 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
3200 *
3201 * Here is why this conversion is safe:
3202 * CMP T0, T1 T2 T0 can be expanded to:
3203 * if (T1 < 0.0)
3204 * MOV T0, T2;
3205 * else
3206 * MOV T0, T0;
3207 *
3208 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
3209 * as the original program. If (T1 < 0.0) evaluates to false, executing
3210 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
3211 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
3212 * because any instruction that was going to read from T0 after this was going
3213 * to read a garbage value anyway.
3214 */
3215 void
3216 glsl_to_tgsi_visitor::simplify_cmp(void)
3217 {
3218 unsigned *tempWrites;
3219 unsigned outputWrites[MAX_PROGRAM_OUTPUTS];
3220
3221 tempWrites = new unsigned[MAX_TEMPS];
3222 if (!tempWrites) {
3223 return;
3224 }
3225 memset(tempWrites, 0, sizeof(unsigned) * MAX_TEMPS);
3226 memset(outputWrites, 0, sizeof(outputWrites));
3227
3228 foreach_list(node, &this->instructions) {
3229 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3230 unsigned prevWriteMask = 0;
3231
3232 /* Give up if we encounter relative addressing or flow control. */
3233 if (inst->dst.reladdr ||
3234 tgsi_get_opcode_info(inst->op)->is_branch ||
3235 inst->op == TGSI_OPCODE_BGNSUB ||
3236 inst->op == TGSI_OPCODE_CONT ||
3237 inst->op == TGSI_OPCODE_END ||
3238 inst->op == TGSI_OPCODE_ENDSUB ||
3239 inst->op == TGSI_OPCODE_RET) {
3240 break;
3241 }
3242
3243 if (inst->dst.file == PROGRAM_OUTPUT) {
3244 assert(inst->dst.index < MAX_PROGRAM_OUTPUTS);
3245 prevWriteMask = outputWrites[inst->dst.index];
3246 outputWrites[inst->dst.index] |= inst->dst.writemask;
3247 } else if (inst->dst.file == PROGRAM_TEMPORARY) {
3248 assert(inst->dst.index < MAX_TEMPS);
3249 prevWriteMask = tempWrites[inst->dst.index];
3250 tempWrites[inst->dst.index] |= inst->dst.writemask;
3251 } else
3252 continue;
3253
3254 /* For a CMP to be considered a conditional write, the destination
3255 * register and source register two must be the same. */
3256 if (inst->op == TGSI_OPCODE_CMP
3257 && !(inst->dst.writemask & prevWriteMask)
3258 && inst->src[2].file == inst->dst.file
3259 && inst->src[2].index == inst->dst.index
3260 && inst->dst.writemask == get_src_arg_mask(inst->dst, inst->src[2])) {
3261
3262 inst->op = TGSI_OPCODE_MOV;
3263 inst->src[0] = inst->src[1];
3264 }
3265 }
3266
3267 delete [] tempWrites;
3268 }
3269
3270 /* Replaces all references to a temporary register index with another index. */
3271 void
3272 glsl_to_tgsi_visitor::rename_temp_register(int index, int new_index)
3273 {
3274 foreach_list(node, &this->instructions) {
3275 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3276 unsigned j;
3277
3278 for (j=0; j < num_inst_src_regs(inst->op); j++) {
3279 if (inst->src[j].file == PROGRAM_TEMPORARY &&
3280 inst->src[j].index == index) {
3281 inst->src[j].index = new_index;
3282 }
3283 }
3284
3285 for (j=0; j < inst->tex_offset_num_offset; j++) {
3286 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY &&
3287 inst->tex_offsets[j].index == index) {
3288 inst->tex_offsets[j].index = new_index;
3289 }
3290 }
3291
3292 if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == index) {
3293 inst->dst.index = new_index;
3294 }
3295 }
3296 }
3297
3298 int
3299 glsl_to_tgsi_visitor::get_first_temp_read(int index)
3300 {
3301 int depth = 0; /* loop depth */
3302 int loop_start = -1; /* index of the first active BGNLOOP (if any) */
3303 unsigned i = 0, j;
3304
3305 foreach_list(node, &this->instructions) {
3306 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3307
3308 for (j=0; j < num_inst_src_regs(inst->op); j++) {
3309 if (inst->src[j].file == PROGRAM_TEMPORARY &&
3310 inst->src[j].index == index) {
3311 return (depth == 0) ? i : loop_start;
3312 }
3313 }
3314 for (j=0; j < inst->tex_offset_num_offset; j++) {
3315 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY &&
3316 inst->tex_offsets[j].index == index) {
3317 return (depth == 0) ? i : loop_start;
3318 }
3319 }
3320
3321 if (inst->op == TGSI_OPCODE_BGNLOOP) {
3322 if(depth++ == 0)
3323 loop_start = i;
3324 } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
3325 if (--depth == 0)
3326 loop_start = -1;
3327 }
3328 assert(depth >= 0);
3329
3330 i++;
3331 }
3332
3333 return -1;
3334 }
3335
3336 int
3337 glsl_to_tgsi_visitor::get_first_temp_write(int index)
3338 {
3339 int depth = 0; /* loop depth */
3340 int loop_start = -1; /* index of the first active BGNLOOP (if any) */
3341 int i = 0;
3342
3343 foreach_list(node, &this->instructions) {
3344 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3345
3346 if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == index) {
3347 return (depth == 0) ? i : loop_start;
3348 }
3349
3350 if (inst->op == TGSI_OPCODE_BGNLOOP) {
3351 if(depth++ == 0)
3352 loop_start = i;
3353 } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
3354 if (--depth == 0)
3355 loop_start = -1;
3356 }
3357 assert(depth >= 0);
3358
3359 i++;
3360 }
3361
3362 return -1;
3363 }
3364
3365 int
3366 glsl_to_tgsi_visitor::get_last_temp_read(int index)
3367 {
3368 int depth = 0; /* loop depth */
3369 int last = -1; /* index of last instruction that reads the temporary */
3370 unsigned i = 0, j;
3371
3372 foreach_list(node, &this->instructions) {
3373 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3374
3375 for (j=0; j < num_inst_src_regs(inst->op); j++) {
3376 if (inst->src[j].file == PROGRAM_TEMPORARY &&
3377 inst->src[j].index == index) {
3378 last = (depth == 0) ? i : -2;
3379 }
3380 }
3381 for (j=0; j < inst->tex_offset_num_offset; j++) {
3382 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY &&
3383 inst->tex_offsets[j].index == index)
3384 last = (depth == 0) ? i : -2;
3385 }
3386
3387 if (inst->op == TGSI_OPCODE_BGNLOOP)
3388 depth++;
3389 else if (inst->op == TGSI_OPCODE_ENDLOOP)
3390 if (--depth == 0 && last == -2)
3391 last = i;
3392 assert(depth >= 0);
3393
3394 i++;
3395 }
3396
3397 assert(last >= -1);
3398 return last;
3399 }
3400
3401 int
3402 glsl_to_tgsi_visitor::get_last_temp_write(int index)
3403 {
3404 int depth = 0; /* loop depth */
3405 int last = -1; /* index of last instruction that writes to the temporary */
3406 int i = 0;
3407
3408 foreach_list(node, &this->instructions) {
3409 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3410
3411 if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == index)
3412 last = (depth == 0) ? i : -2;
3413
3414 if (inst->op == TGSI_OPCODE_BGNLOOP)
3415 depth++;
3416 else if (inst->op == TGSI_OPCODE_ENDLOOP)
3417 if (--depth == 0 && last == -2)
3418 last = i;
3419 assert(depth >= 0);
3420
3421 i++;
3422 }
3423
3424 assert(last >= -1);
3425 return last;
3426 }
3427
3428 /*
3429 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
3430 * channels for copy propagation and updates following instructions to
3431 * use the original versions.
3432 *
3433 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
3434 * will occur. As an example, a TXP production before this pass:
3435 *
3436 * 0: MOV TEMP[1], INPUT[4].xyyy;
3437 * 1: MOV TEMP[1].w, INPUT[4].wwww;
3438 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
3439 *
3440 * and after:
3441 *
3442 * 0: MOV TEMP[1], INPUT[4].xyyy;
3443 * 1: MOV TEMP[1].w, INPUT[4].wwww;
3444 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
3445 *
3446 * which allows for dead code elimination on TEMP[1]'s writes.
3447 */
3448 void
3449 glsl_to_tgsi_visitor::copy_propagate(void)
3450 {
3451 glsl_to_tgsi_instruction **acp = rzalloc_array(mem_ctx,
3452 glsl_to_tgsi_instruction *,
3453 this->next_temp * 4);
3454 int *acp_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
3455 int level = 0;
3456
3457 foreach_list(node, &this->instructions) {
3458 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3459
3460 assert(inst->dst.file != PROGRAM_TEMPORARY
3461 || inst->dst.index < this->next_temp);
3462
3463 /* First, do any copy propagation possible into the src regs. */
3464 for (int r = 0; r < 3; r++) {
3465 glsl_to_tgsi_instruction *first = NULL;
3466 bool good = true;
3467 int acp_base = inst->src[r].index * 4;
3468
3469 if (inst->src[r].file != PROGRAM_TEMPORARY ||
3470 inst->src[r].reladdr ||
3471 inst->src[r].reladdr2)
3472 continue;
3473
3474 /* See if we can find entries in the ACP consisting of MOVs
3475 * from the same src register for all the swizzled channels
3476 * of this src register reference.
3477 */
3478 for (int i = 0; i < 4; i++) {
3479 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
3480 glsl_to_tgsi_instruction *copy_chan = acp[acp_base + src_chan];
3481
3482 if (!copy_chan) {
3483 good = false;
3484 break;
3485 }
3486
3487 assert(acp_level[acp_base + src_chan] <= level);
3488
3489 if (!first) {
3490 first = copy_chan;
3491 } else {
3492 if (first->src[0].file != copy_chan->src[0].file ||
3493 first->src[0].index != copy_chan->src[0].index) {
3494 good = false;
3495 break;
3496 }
3497 }
3498 }
3499
3500 if (good) {
3501 /* We've now validated that we can copy-propagate to
3502 * replace this src register reference. Do it.
3503 */
3504 inst->src[r].file = first->src[0].file;
3505 inst->src[r].index = first->src[0].index;
3506 inst->src[r].index2D = first->src[0].index2D;
3507 inst->src[r].has_index2 = first->src[0].has_index2;
3508
3509 int swizzle = 0;
3510 for (int i = 0; i < 4; i++) {
3511 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
3512 glsl_to_tgsi_instruction *copy_inst = acp[acp_base + src_chan];
3513 swizzle |= (GET_SWZ(copy_inst->src[0].swizzle, src_chan) <<
3514 (3 * i));
3515 }
3516 inst->src[r].swizzle = swizzle;
3517 }
3518 }
3519
3520 switch (inst->op) {
3521 case TGSI_OPCODE_BGNLOOP:
3522 case TGSI_OPCODE_ENDLOOP:
3523 /* End of a basic block, clear the ACP entirely. */
3524 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
3525 break;
3526
3527 case TGSI_OPCODE_IF:
3528 case TGSI_OPCODE_UIF:
3529 ++level;
3530 break;
3531
3532 case TGSI_OPCODE_ENDIF:
3533 case TGSI_OPCODE_ELSE:
3534 /* Clear all channels written inside the block from the ACP, but
3535 * leaving those that were not touched.
3536 */
3537 for (int r = 0; r < this->next_temp; r++) {
3538 for (int c = 0; c < 4; c++) {
3539 if (!acp[4 * r + c])
3540 continue;
3541
3542 if (acp_level[4 * r + c] >= level)
3543 acp[4 * r + c] = NULL;
3544 }
3545 }
3546 if (inst->op == TGSI_OPCODE_ENDIF)
3547 --level;
3548 break;
3549
3550 default:
3551 /* Continuing the block, clear any written channels from
3552 * the ACP.
3553 */
3554 if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.reladdr) {
3555 /* Any temporary might be written, so no copy propagation
3556 * across this instruction.
3557 */
3558 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
3559 } else if (inst->dst.file == PROGRAM_OUTPUT &&
3560 inst->dst.reladdr) {
3561 /* Any output might be written, so no copy propagation
3562 * from outputs across this instruction.
3563 */
3564 for (int r = 0; r < this->next_temp; r++) {
3565 for (int c = 0; c < 4; c++) {
3566 if (!acp[4 * r + c])
3567 continue;
3568
3569 if (acp[4 * r + c]->src[0].file == PROGRAM_OUTPUT)
3570 acp[4 * r + c] = NULL;
3571 }
3572 }
3573 } else if (inst->dst.file == PROGRAM_TEMPORARY ||
3574 inst->dst.file == PROGRAM_OUTPUT) {
3575 /* Clear where it's used as dst. */
3576 if (inst->dst.file == PROGRAM_TEMPORARY) {
3577 for (int c = 0; c < 4; c++) {
3578 if (inst->dst.writemask & (1 << c)) {
3579 acp[4 * inst->dst.index + c] = NULL;
3580 }
3581 }
3582 }
3583
3584 /* Clear where it's used as src. */
3585 for (int r = 0; r < this->next_temp; r++) {
3586 for (int c = 0; c < 4; c++) {
3587 if (!acp[4 * r + c])
3588 continue;
3589
3590 int src_chan = GET_SWZ(acp[4 * r + c]->src[0].swizzle, c);
3591
3592 if (acp[4 * r + c]->src[0].file == inst->dst.file &&
3593 acp[4 * r + c]->src[0].index == inst->dst.index &&
3594 inst->dst.writemask & (1 << src_chan))
3595 {
3596 acp[4 * r + c] = NULL;
3597 }
3598 }
3599 }
3600 }
3601 break;
3602 }
3603
3604 /* If this is a copy, add it to the ACP. */
3605 if (inst->op == TGSI_OPCODE_MOV &&
3606 inst->dst.file == PROGRAM_TEMPORARY &&
3607 !(inst->dst.file == inst->src[0].file &&
3608 inst->dst.index == inst->src[0].index) &&
3609 !inst->dst.reladdr &&
3610 !inst->saturate &&
3611 !inst->src[0].reladdr &&
3612 !inst->src[0].reladdr2 &&
3613 !inst->src[0].negate) {
3614 for (int i = 0; i < 4; i++) {
3615 if (inst->dst.writemask & (1 << i)) {
3616 acp[4 * inst->dst.index + i] = inst;
3617 acp_level[4 * inst->dst.index + i] = level;
3618 }
3619 }
3620 }
3621 }
3622
3623 ralloc_free(acp_level);
3624 ralloc_free(acp);
3625 }
3626
3627 /*
3628 * Tracks available PROGRAM_TEMPORARY registers for dead code elimination.
3629 *
3630 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
3631 * will occur. As an example, a TXP production after copy propagation but
3632 * before this pass:
3633 *
3634 * 0: MOV TEMP[1], INPUT[4].xyyy;
3635 * 1: MOV TEMP[1].w, INPUT[4].wwww;
3636 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
3637 *
3638 * and after this pass:
3639 *
3640 * 0: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
3641 *
3642 * FIXME: assumes that all functions are inlined (no support for BGNSUB/ENDSUB)
3643 * FIXME: doesn't eliminate all dead code inside of loops; it steps around them
3644 */
3645 void
3646 glsl_to_tgsi_visitor::eliminate_dead_code(void)
3647 {
3648 int i;
3649
3650 for (i=0; i < this->next_temp; i++) {
3651 int last_read = get_last_temp_read(i);
3652 int j = 0;
3653
3654 foreach_list_safe(node, &this->instructions) {
3655 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3656
3657 if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == i &&
3658 j > last_read)
3659 {
3660 inst->remove();
3661 delete inst;
3662 }
3663
3664 j++;
3665 }
3666 }
3667 }
3668
3669 /*
3670 * On a basic block basis, tracks available PROGRAM_TEMPORARY registers for dead
3671 * code elimination. This is less primitive than eliminate_dead_code(), as it
3672 * is per-channel and can detect consecutive writes without a read between them
3673 * as dead code. However, there is some dead code that can be eliminated by
3674 * eliminate_dead_code() but not this function - for example, this function
3675 * cannot eliminate an instruction writing to a register that is never read and
3676 * is the only instruction writing to that register.
3677 *
3678 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
3679 * will occur.
3680 */
3681 int
3682 glsl_to_tgsi_visitor::eliminate_dead_code_advanced(void)
3683 {
3684 glsl_to_tgsi_instruction **writes = rzalloc_array(mem_ctx,
3685 glsl_to_tgsi_instruction *,
3686 this->next_temp * 4);
3687 int *write_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
3688 int level = 0;
3689 int removed = 0;
3690
3691 foreach_list(node, &this->instructions) {
3692 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3693
3694 assert(inst->dst.file != PROGRAM_TEMPORARY
3695 || inst->dst.index < this->next_temp);
3696
3697 switch (inst->op) {
3698 case TGSI_OPCODE_BGNLOOP:
3699 case TGSI_OPCODE_ENDLOOP:
3700 case TGSI_OPCODE_CONT:
3701 case TGSI_OPCODE_BRK:
3702 /* End of a basic block, clear the write array entirely.
3703 *
3704 * This keeps us from killing dead code when the writes are
3705 * on either side of a loop, even when the register isn't touched
3706 * inside the loop. However, glsl_to_tgsi_visitor doesn't seem to emit
3707 * dead code of this type, so it shouldn't make a difference as long as
3708 * the dead code elimination pass in the GLSL compiler does its job.
3709 */
3710 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
3711 break;
3712
3713 case TGSI_OPCODE_ENDIF:
3714 case TGSI_OPCODE_ELSE:
3715 /* Promote the recorded level of all channels written inside the
3716 * preceding if or else block to the level above the if/else block.
3717 */
3718 for (int r = 0; r < this->next_temp; r++) {
3719 for (int c = 0; c < 4; c++) {
3720 if (!writes[4 * r + c])
3721 continue;
3722
3723 if (write_level[4 * r + c] == level)
3724 write_level[4 * r + c] = level-1;
3725 }
3726 }
3727
3728 if(inst->op == TGSI_OPCODE_ENDIF)
3729 --level;
3730
3731 break;
3732
3733 case TGSI_OPCODE_IF:
3734 case TGSI_OPCODE_UIF:
3735 ++level;
3736 /* fallthrough to default case to mark the condition as read */
3737
3738 default:
3739 /* Continuing the block, clear any channels from the write array that
3740 * are read by this instruction.
3741 */
3742 for (unsigned i = 0; i < Elements(inst->src); i++) {
3743 if (inst->src[i].file == PROGRAM_TEMPORARY && inst->src[i].reladdr){
3744 /* Any temporary might be read, so no dead code elimination
3745 * across this instruction.
3746 */
3747 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
3748 } else if (inst->src[i].file == PROGRAM_TEMPORARY) {
3749 /* Clear where it's used as src. */
3750 int src_chans = 1 << GET_SWZ(inst->src[i].swizzle, 0);
3751 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 1);
3752 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 2);
3753 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 3);
3754
3755 for (int c = 0; c < 4; c++) {
3756 if (src_chans & (1 << c)) {
3757 writes[4 * inst->src[i].index + c] = NULL;
3758 }
3759 }
3760 }
3761 }
3762 for (unsigned i = 0; i < inst->tex_offset_num_offset; i++) {
3763 if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY && inst->tex_offsets[i].reladdr){
3764 /* Any temporary might be read, so no dead code elimination
3765 * across this instruction.
3766 */
3767 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
3768 } else if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY) {
3769 /* Clear where it's used as src. */
3770 int src_chans = 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 0);
3771 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 1);
3772 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 2);
3773 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 3);
3774
3775 for (int c = 0; c < 4; c++) {
3776 if (src_chans & (1 << c)) {
3777 writes[4 * inst->tex_offsets[i].index + c] = NULL;
3778 }
3779 }
3780 }
3781 }
3782 break;
3783 }
3784
3785 /* If this instruction writes to a temporary, add it to the write array.
3786 * If there is already an instruction in the write array for one or more
3787 * of the channels, flag that channel write as dead.
3788 */
3789 if (inst->dst.file == PROGRAM_TEMPORARY &&
3790 !inst->dst.reladdr &&
3791 !inst->saturate) {
3792 for (int c = 0; c < 4; c++) {
3793 if (inst->dst.writemask & (1 << c)) {
3794 if (writes[4 * inst->dst.index + c]) {
3795 if (write_level[4 * inst->dst.index + c] < level)
3796 continue;
3797 else
3798 writes[4 * inst->dst.index + c]->dead_mask |= (1 << c);
3799 }
3800 writes[4 * inst->dst.index + c] = inst;
3801 write_level[4 * inst->dst.index + c] = level;
3802 }
3803 }
3804 }
3805 }
3806
3807 /* Anything still in the write array at this point is dead code. */
3808 for (int r = 0; r < this->next_temp; r++) {
3809 for (int c = 0; c < 4; c++) {
3810 glsl_to_tgsi_instruction *inst = writes[4 * r + c];
3811 if (inst)
3812 inst->dead_mask |= (1 << c);
3813 }
3814 }
3815
3816 /* Now actually remove the instructions that are completely dead and update
3817 * the writemask of other instructions with dead channels.
3818 */
3819 foreach_list_safe(node, &this->instructions) {
3820 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
3821
3822 if (!inst->dead_mask || !inst->dst.writemask)
3823 continue;
3824 else if ((inst->dst.writemask & ~inst->dead_mask) == 0) {
3825 inst->remove();
3826 delete inst;
3827 removed++;
3828 } else
3829 inst->dst.writemask &= ~(inst->dead_mask);
3830 }
3831
3832 ralloc_free(write_level);
3833 ralloc_free(writes);
3834
3835 return removed;
3836 }
3837
3838 /* Merges temporary registers together where possible to reduce the number of
3839 * registers needed to run a program.
3840 *
3841 * Produces optimal code only after copy propagation and dead code elimination
3842 * have been run. */
3843 void
3844 glsl_to_tgsi_visitor::merge_registers(void)
3845 {
3846 int *last_reads = rzalloc_array(mem_ctx, int, this->next_temp);
3847 int *first_writes = rzalloc_array(mem_ctx, int, this->next_temp);
3848 int i, j;
3849
3850 /* Read the indices of the last read and first write to each temp register
3851 * into an array so that we don't have to traverse the instruction list as
3852 * much. */
3853 for (i=0; i < this->next_temp; i++) {
3854 last_reads[i] = get_last_temp_read(i);
3855 first_writes[i] = get_first_temp_write(i);
3856 }
3857
3858 /* Start looking for registers with non-overlapping usages that can be
3859 * merged together. */
3860 for (i=0; i < this->next_temp; i++) {
3861 /* Don't touch unused registers. */
3862 if (last_reads[i] < 0 || first_writes[i] < 0) continue;
3863
3864 for (j=0; j < this->next_temp; j++) {
3865 /* Don't touch unused registers. */
3866 if (last_reads[j] < 0 || first_writes[j] < 0) continue;
3867
3868 /* We can merge the two registers if the first write to j is after or
3869 * in the same instruction as the last read from i. Note that the
3870 * register at index i will always be used earlier or at the same time
3871 * as the register at index j. */
3872 if (first_writes[i] <= first_writes[j] &&
3873 last_reads[i] <= first_writes[j])
3874 {
3875 rename_temp_register(j, i); /* Replace all references to j with i.*/
3876
3877 /* Update the first_writes and last_reads arrays with the new
3878 * values for the merged register index, and mark the newly unused
3879 * register index as such. */
3880 last_reads[i] = last_reads[j];
3881 first_writes[j] = -1;
3882 last_reads[j] = -1;
3883 }
3884 }
3885 }
3886
3887 ralloc_free(last_reads);
3888 ralloc_free(first_writes);
3889 }
3890
3891 /* Reassign indices to temporary registers by reusing unused indices created
3892 * by optimization passes. */
3893 void
3894 glsl_to_tgsi_visitor::renumber_registers(void)
3895 {
3896 int i = 0;
3897 int new_index = 0;
3898
3899 for (i=0; i < this->next_temp; i++) {
3900 if (get_first_temp_read(i) < 0) continue;
3901 if (i != new_index)
3902 rename_temp_register(i, new_index);
3903 new_index++;
3904 }
3905
3906 this->next_temp = new_index;
3907 }
3908
3909 /**
3910 * Returns a fragment program which implements the current pixel transfer ops.
3911 * Based on get_pixel_transfer_program in st_atom_pixeltransfer.c.
3912 */
3913 extern "C" void
3914 get_pixel_transfer_visitor(struct st_fragment_program *fp,
3915 glsl_to_tgsi_visitor *original,
3916 int scale_and_bias, int pixel_maps)
3917 {
3918 glsl_to_tgsi_visitor *v = new glsl_to_tgsi_visitor();
3919 struct st_context *st = st_context(original->ctx);
3920 struct gl_program *prog = &fp->Base.Base;
3921 struct gl_program_parameter_list *params = _mesa_new_parameter_list();
3922 st_src_reg coord, src0;
3923 st_dst_reg dst0;
3924 glsl_to_tgsi_instruction *inst;
3925
3926 /* Copy attributes of the glsl_to_tgsi_visitor in the original shader. */
3927 v->ctx = original->ctx;
3928 v->prog = prog;
3929 v->shader_program = NULL;
3930 v->glsl_version = original->glsl_version;
3931 v->native_integers = original->native_integers;
3932 v->options = original->options;
3933 v->next_temp = original->next_temp;
3934 v->num_address_regs = original->num_address_regs;
3935 v->samplers_used = prog->SamplersUsed = original->samplers_used;
3936 v->indirect_addr_consts = original->indirect_addr_consts;
3937 memcpy(&v->immediates, &original->immediates, sizeof(v->immediates));
3938 v->num_immediates = original->num_immediates;
3939
3940 /*
3941 * Get initial pixel color from the texture.
3942 * TEX colorTemp, fragment.texcoord[0], texture[0], 2D;
3943 */
3944 coord = st_src_reg(PROGRAM_INPUT, VARYING_SLOT_TEX0, glsl_type::vec2_type);
3945 src0 = v->get_temp(glsl_type::vec4_type);
3946 dst0 = st_dst_reg(src0);
3947 inst = v->emit(NULL, TGSI_OPCODE_TEX, dst0, coord);
3948 inst->sampler = 0;
3949 inst->tex_target = TEXTURE_2D_INDEX;
3950
3951 prog->InputsRead |= VARYING_BIT_TEX0;
3952 prog->SamplersUsed |= (1 << 0); /* mark sampler 0 as used */
3953 v->samplers_used |= (1 << 0);
3954
3955 if (scale_and_bias) {
3956 static const gl_state_index scale_state[STATE_LENGTH] =
3957 { STATE_INTERNAL, STATE_PT_SCALE,
3958 (gl_state_index) 0, (gl_state_index) 0, (gl_state_index) 0 };
3959 static const gl_state_index bias_state[STATE_LENGTH] =
3960 { STATE_INTERNAL, STATE_PT_BIAS,
3961 (gl_state_index) 0, (gl_state_index) 0, (gl_state_index) 0 };
3962 GLint scale_p, bias_p;
3963 st_src_reg scale, bias;
3964
3965 scale_p = _mesa_add_state_reference(params, scale_state);
3966 bias_p = _mesa_add_state_reference(params, bias_state);
3967
3968 /* MAD colorTemp, colorTemp, scale, bias; */
3969 scale = st_src_reg(PROGRAM_STATE_VAR, scale_p, GLSL_TYPE_FLOAT);
3970 bias = st_src_reg(PROGRAM_STATE_VAR, bias_p, GLSL_TYPE_FLOAT);
3971 inst = v->emit(NULL, TGSI_OPCODE_MAD, dst0, src0, scale, bias);
3972 }
3973
3974 if (pixel_maps) {
3975 st_src_reg temp = v->get_temp(glsl_type::vec4_type);
3976 st_dst_reg temp_dst = st_dst_reg(temp);
3977
3978 assert(st->pixel_xfer.pixelmap_texture);
3979
3980 /* With a little effort, we can do four pixel map look-ups with
3981 * two TEX instructions:
3982 */
3983
3984 /* TEX temp.rg, colorTemp.rgba, texture[1], 2D; */
3985 temp_dst.writemask = WRITEMASK_XY; /* write R,G */
3986 inst = v->emit(NULL, TGSI_OPCODE_TEX, temp_dst, src0);
3987 inst->sampler = 1;
3988 inst->tex_target = TEXTURE_2D_INDEX;
3989
3990 /* TEX temp.ba, colorTemp.baba, texture[1], 2D; */
3991 src0.swizzle = MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_Z, SWIZZLE_W);
3992 temp_dst.writemask = WRITEMASK_ZW; /* write B,A */
3993 inst = v->emit(NULL, TGSI_OPCODE_TEX, temp_dst, src0);
3994 inst->sampler = 1;
3995 inst->tex_target = TEXTURE_2D_INDEX;
3996
3997 prog->SamplersUsed |= (1 << 1); /* mark sampler 1 as used */
3998 v->samplers_used |= (1 << 1);
3999
4000 /* MOV colorTemp, temp; */
4001 inst = v->emit(NULL, TGSI_OPCODE_MOV, dst0, temp);
4002 }
4003
4004 /* Now copy the instructions from the original glsl_to_tgsi_visitor into the
4005 * new visitor. */
4006 foreach_list(node, &original->instructions) {
4007 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
4008 glsl_to_tgsi_instruction *newinst;
4009 st_src_reg src_regs[3];
4010
4011 if (inst->dst.file == PROGRAM_OUTPUT)
4012 prog->OutputsWritten |= BITFIELD64_BIT(inst->dst.index);
4013
4014 for (int i=0; i<3; i++) {
4015 src_regs[i] = inst->src[i];
4016 if (src_regs[i].file == PROGRAM_INPUT &&
4017 src_regs[i].index == VARYING_SLOT_COL0)
4018 {
4019 src_regs[i].file = PROGRAM_TEMPORARY;
4020 src_regs[i].index = src0.index;
4021 }
4022 else if (src_regs[i].file == PROGRAM_INPUT)
4023 prog->InputsRead |= BITFIELD64_BIT(src_regs[i].index);
4024 }
4025
4026 newinst = v->emit(NULL, inst->op, inst->dst, src_regs[0], src_regs[1], src_regs[2]);
4027 newinst->tex_target = inst->tex_target;
4028 }
4029
4030 /* Make modifications to fragment program info. */
4031 prog->Parameters = _mesa_combine_parameter_lists(params,
4032 original->prog->Parameters);
4033 _mesa_free_parameter_list(params);
4034 count_resources(v, prog);
4035 fp->glsl_to_tgsi = v;
4036 }
4037
4038 /**
4039 * Make fragment program for glBitmap:
4040 * Sample the texture and kill the fragment if the bit is 0.
4041 * This program will be combined with the user's fragment program.
4042 *
4043 * Based on make_bitmap_fragment_program in st_cb_bitmap.c.
4044 */
4045 extern "C" void
4046 get_bitmap_visitor(struct st_fragment_program *fp,
4047 glsl_to_tgsi_visitor *original, int samplerIndex)
4048 {
4049 glsl_to_tgsi_visitor *v = new glsl_to_tgsi_visitor();
4050 struct st_context *st = st_context(original->ctx);
4051 struct gl_program *prog = &fp->Base.Base;
4052 st_src_reg coord, src0;
4053 st_dst_reg dst0;
4054 glsl_to_tgsi_instruction *inst;
4055
4056 /* Copy attributes of the glsl_to_tgsi_visitor in the original shader. */
4057 v->ctx = original->ctx;
4058 v->prog = prog;
4059 v->shader_program = NULL;
4060 v->glsl_version = original->glsl_version;
4061 v->native_integers = original->native_integers;
4062 v->options = original->options;
4063 v->next_temp = original->next_temp;
4064 v->num_address_regs = original->num_address_regs;
4065 v->samplers_used = prog->SamplersUsed = original->samplers_used;
4066 v->indirect_addr_consts = original->indirect_addr_consts;
4067 memcpy(&v->immediates, &original->immediates, sizeof(v->immediates));
4068 v->num_immediates = original->num_immediates;
4069
4070 /* TEX tmp0, fragment.texcoord[0], texture[0], 2D; */
4071 coord = st_src_reg(PROGRAM_INPUT, VARYING_SLOT_TEX0, glsl_type::vec2_type);
4072 src0 = v->get_temp(glsl_type::vec4_type);
4073 dst0 = st_dst_reg(src0);
4074 inst = v->emit(NULL, TGSI_OPCODE_TEX, dst0, coord);
4075 inst->sampler = samplerIndex;
4076 inst->tex_target = TEXTURE_2D_INDEX;
4077
4078 prog->InputsRead |= VARYING_BIT_TEX0;
4079 prog->SamplersUsed |= (1 << samplerIndex); /* mark sampler as used */
4080 v->samplers_used |= (1 << samplerIndex);
4081
4082 /* KIL if -tmp0 < 0 # texel=0 -> keep / texel=0 -> discard */
4083 src0.negate = NEGATE_XYZW;
4084 if (st->bitmap.tex_format == PIPE_FORMAT_L8_UNORM)
4085 src0.swizzle = SWIZZLE_XXXX;
4086 inst = v->emit(NULL, TGSI_OPCODE_KILL_IF, undef_dst, src0);
4087
4088 /* Now copy the instructions from the original glsl_to_tgsi_visitor into the
4089 * new visitor. */
4090 foreach_list(node, &original->instructions) {
4091 glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *) node;
4092 glsl_to_tgsi_instruction *newinst;
4093 st_src_reg src_regs[3];
4094
4095 if (inst->dst.file == PROGRAM_OUTPUT)
4096 prog->OutputsWritten |= BITFIELD64_BIT(inst->dst.index);
4097
4098 for (int i=0; i<3; i++) {
4099 src_regs[i] = inst->src[i];
4100 if (src_regs[i].file == PROGRAM_INPUT)
4101 prog->InputsRead |= BITFIELD64_BIT(src_regs[i].index);
4102 }
4103
4104 newinst = v->emit(NULL, inst->op, inst->dst, src_regs[0], src_regs[1], src_regs[2]);
4105 newinst->tex_target = inst->tex_target;
4106 }
4107
4108 /* Make modifications to fragment program info. */
4109 prog->Parameters = _mesa_clone_parameter_list(original->prog->Parameters);
4110 count_resources(v, prog);
4111 fp->glsl_to_tgsi = v;
4112 }
4113
4114 /* ------------------------- TGSI conversion stuff -------------------------- */
4115 struct label {
4116 unsigned branch_target;
4117 unsigned token;
4118 };
4119
4120 /**
4121 * Intermediate state used during shader translation.
4122 */
4123 struct st_translate {
4124 struct ureg_program *ureg;
4125
4126 struct ureg_dst temps[MAX_TEMPS];
4127 struct ureg_dst arrays[MAX_ARRAYS];
4128 struct ureg_src *constants;
4129 struct ureg_src *immediates;
4130 struct ureg_dst outputs[PIPE_MAX_SHADER_OUTPUTS];
4131 struct ureg_src inputs[PIPE_MAX_SHADER_INPUTS];
4132 struct ureg_dst address[2];
4133 struct ureg_src samplers[PIPE_MAX_SAMPLERS];
4134 struct ureg_src systemValues[SYSTEM_VALUE_MAX];
4135 struct tgsi_texture_offset tex_offsets[MAX_GLSL_TEXTURE_OFFSET];
4136 unsigned array_sizes[MAX_ARRAYS];
4137
4138 const GLuint *inputMapping;
4139 const GLuint *outputMapping;
4140
4141 /* For every instruction that contains a label (eg CALL), keep
4142 * details so that we can go back afterwards and emit the correct
4143 * tgsi instruction number for each label.
4144 */
4145 struct label *labels;
4146 unsigned labels_size;
4147 unsigned labels_count;
4148
4149 /* Keep a record of the tgsi instruction number that each mesa
4150 * instruction starts at, will be used to fix up labels after
4151 * translation.
4152 */
4153 unsigned *insn;
4154 unsigned insn_size;
4155 unsigned insn_count;
4156
4157 unsigned procType; /**< TGSI_PROCESSOR_VERTEX/FRAGMENT */
4158
4159 boolean error;
4160 };
4161
4162 /** Map Mesa's SYSTEM_VALUE_x to TGSI_SEMANTIC_x */
4163 static unsigned mesa_sysval_to_semantic[SYSTEM_VALUE_MAX] = {
4164 TGSI_SEMANTIC_FACE,
4165 TGSI_SEMANTIC_VERTEXID,
4166 TGSI_SEMANTIC_INSTANCEID
4167 };
4168
4169 /**
4170 * Make note of a branch to a label in the TGSI code.
4171 * After we've emitted all instructions, we'll go over the list
4172 * of labels built here and patch the TGSI code with the actual
4173 * location of each label.
4174 */
4175 static unsigned *get_label(struct st_translate *t, unsigned branch_target)
4176 {
4177 unsigned i;
4178
4179 if (t->labels_count + 1 >= t->labels_size) {
4180 t->labels_size = 1 << (util_logbase2(t->labels_size) + 1);
4181 t->labels = (struct label *)realloc(t->labels,
4182 t->labels_size * sizeof(struct label));
4183 if (t->labels == NULL) {
4184 static unsigned dummy;
4185 t->error = TRUE;
4186 return &dummy;
4187 }
4188 }
4189
4190 i = t->labels_count++;
4191 t->labels[i].branch_target = branch_target;
4192 return &t->labels[i].token;
4193 }
4194
4195 /**
4196 * Called prior to emitting the TGSI code for each instruction.
4197 * Allocate additional space for instructions if needed.
4198 * Update the insn[] array so the next glsl_to_tgsi_instruction points to
4199 * the next TGSI instruction.
4200 */
4201 static void set_insn_start(struct st_translate *t, unsigned start)
4202 {
4203 if (t->insn_count + 1 >= t->insn_size) {
4204 t->insn_size = 1 << (util_logbase2(t->insn_size) + 1);
4205 t->insn = (unsigned *)realloc(t->insn, t->insn_size * sizeof(t->insn[0]));
4206 if (t->insn == NULL) {
4207 t->error = TRUE;
4208 return;
4209 }
4210 }
4211
4212 t->insn[t->insn_count++] = start;
4213 }
4214
4215 /**
4216 * Map a glsl_to_tgsi constant/immediate to a TGSI immediate.
4217 */
4218 static struct ureg_src
4219 emit_immediate(struct st_translate *t,
4220 gl_constant_value values[4],
4221 int type, int size)
4222 {
4223 struct ureg_program *ureg = t->ureg;
4224
4225 switch(type)
4226 {
4227 case GL_FLOAT:
4228 return ureg_DECL_immediate(ureg, &values[0].f, size);
4229 case GL_INT:
4230 return ureg_DECL_immediate_int(ureg, &values[0].i, size);
4231 case GL_UNSIGNED_INT:
4232 case GL_BOOL:
4233 return ureg_DECL_immediate_uint(ureg, &values[0].u, size);
4234 default:
4235 assert(!"should not get here - type must be float, int, uint, or bool");
4236 return ureg_src_undef();
4237 }
4238 }
4239
4240 /**
4241 * Map a glsl_to_tgsi dst register to a TGSI ureg_dst register.
4242 */
4243 static struct ureg_dst
4244 dst_register(struct st_translate *t,
4245 gl_register_file file,
4246 GLuint index)
4247 {
4248 unsigned array;
4249
4250 switch(file) {
4251 case PROGRAM_UNDEFINED:
4252 return ureg_dst_undef();
4253
4254 case PROGRAM_TEMPORARY:
4255 assert(index >= 0);
4256 assert(index < (int) Elements(t->temps));
4257
4258 if (ureg_dst_is_undef(t->temps[index]))
4259 t->temps[index] = ureg_DECL_local_temporary(t->ureg);
4260
4261 return t->temps[index];
4262
4263 case PROGRAM_ARRAY:
4264 array = index >> 16;
4265
4266 assert(array >= 0);
4267 assert(array < (int) Elements(t->arrays));
4268
4269 if (ureg_dst_is_undef(t->arrays[array]))
4270 t->arrays[array] = ureg_DECL_array_temporary(
4271 t->ureg, t->array_sizes[array], TRUE);
4272
4273 return ureg_dst_array_offset(t->arrays[array],
4274 (int)(index & 0xFFFF) - 0x8000);
4275
4276 case PROGRAM_OUTPUT:
4277 if (t->procType == TGSI_PROCESSOR_VERTEX)
4278 assert(index < VARYING_SLOT_MAX);
4279 else if (t->procType == TGSI_PROCESSOR_FRAGMENT)
4280 assert(index < FRAG_RESULT_MAX);
4281 else
4282 assert(index < VARYING_SLOT_MAX);
4283
4284 assert(t->outputMapping[index] < Elements(t->outputs));
4285
4286 return t->outputs[t->outputMapping[index]];
4287
4288 case PROGRAM_ADDRESS:
4289 return t->address[index];
4290
4291 default:
4292 assert(!"unknown dst register file");
4293 return ureg_dst_undef();
4294 }
4295 }
4296
4297 /**
4298 * Map a glsl_to_tgsi src register to a TGSI ureg_src register.
4299 */
4300 static struct ureg_src
4301 src_register(struct st_translate *t,
4302 gl_register_file file,
4303 GLint index, GLint index2D)
4304 {
4305 switch(file) {
4306 case PROGRAM_UNDEFINED:
4307 return ureg_src_undef();
4308
4309 case PROGRAM_TEMPORARY:
4310 case PROGRAM_ARRAY:
4311 return ureg_src(dst_register(t, file, index));
4312
4313 case PROGRAM_UNIFORM:
4314 assert(index >= 0);
4315 return t->constants[index];
4316 case PROGRAM_STATE_VAR:
4317 case PROGRAM_CONSTANT: /* ie, immediate */
4318 if (index2D) {
4319 struct ureg_src src;
4320 src = ureg_src_register(TGSI_FILE_CONSTANT, 0);
4321 src.Dimension = 1;
4322 src.DimensionIndex = index2D;
4323 return src;
4324 } else if (index < 0)
4325 return ureg_DECL_constant(t->ureg, 0);
4326 else
4327 return t->constants[index];
4328
4329 case PROGRAM_IMMEDIATE:
4330 return t->immediates[index];
4331
4332 case PROGRAM_INPUT:
4333 assert(t->inputMapping[index] < Elements(t->inputs));
4334 return t->inputs[t->inputMapping[index]];
4335
4336 case PROGRAM_OUTPUT:
4337 assert(t->outputMapping[index] < Elements(t->outputs));
4338 return ureg_src(t->outputs[t->outputMapping[index]]); /* not needed? */
4339
4340 case PROGRAM_ADDRESS:
4341 return ureg_src(t->address[index]);
4342
4343 case PROGRAM_SYSTEM_VALUE:
4344 assert(index < (int) Elements(t->systemValues));
4345 return t->systemValues[index];
4346
4347 default:
4348 assert(!"unknown src register file");
4349 return ureg_src_undef();
4350 }
4351 }
4352
4353 /**
4354 * Create a TGSI ureg_dst register from an st_dst_reg.
4355 */
4356 static struct ureg_dst
4357 translate_dst(struct st_translate *t,
4358 const st_dst_reg *dst_reg,
4359 bool saturate, bool clamp_color)
4360 {
4361 struct ureg_dst dst = dst_register(t,
4362 dst_reg->file,
4363 dst_reg->index);
4364
4365 dst = ureg_writemask(dst, dst_reg->writemask);
4366
4367 if (saturate)
4368 dst = ureg_saturate(dst);
4369 else if (clamp_color && dst_reg->file == PROGRAM_OUTPUT) {
4370 /* Clamp colors for ARB_color_buffer_float. */
4371 switch (t->procType) {
4372 case TGSI_PROCESSOR_VERTEX:
4373 /* XXX if the geometry shader is present, this must be done there
4374 * instead of here. */
4375 if (dst_reg->index == VARYING_SLOT_COL0 ||
4376 dst_reg->index == VARYING_SLOT_COL1 ||
4377 dst_reg->index == VARYING_SLOT_BFC0 ||
4378 dst_reg->index == VARYING_SLOT_BFC1) {
4379 dst = ureg_saturate(dst);
4380 }
4381 break;
4382
4383 case TGSI_PROCESSOR_FRAGMENT:
4384 if (dst_reg->index >= FRAG_RESULT_COLOR) {
4385 dst = ureg_saturate(dst);
4386 }
4387 break;
4388 }
4389 }
4390
4391 if (dst_reg->reladdr != NULL) {
4392 assert(dst_reg->file != PROGRAM_TEMPORARY);
4393 dst = ureg_dst_indirect(dst, ureg_src(t->address[0]));
4394 }
4395
4396 return dst;
4397 }
4398
4399 /**
4400 * Create a TGSI ureg_src register from an st_src_reg.
4401 */
4402 static struct ureg_src
4403 translate_src(struct st_translate *t, const st_src_reg *src_reg)
4404 {
4405 struct ureg_src src = src_register(t, src_reg->file, src_reg->index, src_reg->index2D);
4406
4407 if (t->procType == TGSI_PROCESSOR_GEOMETRY && src_reg->has_index2) {
4408 src = src_register(t, src_reg->file, src_reg->index, src_reg->index2D);
4409 if (src_reg->reladdr2)
4410 src = ureg_src_dimension_indirect(src, ureg_src(t->address[1]),
4411 src_reg->index2D);
4412 else
4413 src = ureg_src_dimension(src, src_reg->index2D);
4414 }
4415
4416 src = ureg_swizzle(src,
4417 GET_SWZ(src_reg->swizzle, 0) & 0x3,
4418 GET_SWZ(src_reg->swizzle, 1) & 0x3,
4419 GET_SWZ(src_reg->swizzle, 2) & 0x3,
4420 GET_SWZ(src_reg->swizzle, 3) & 0x3);
4421
4422 if ((src_reg->negate & 0xf) == NEGATE_XYZW)
4423 src = ureg_negate(src);
4424
4425 if (src_reg->reladdr != NULL) {
4426 assert(src_reg->file != PROGRAM_TEMPORARY);
4427 src = ureg_src_indirect(src, ureg_src(t->address[0]));
4428 }
4429
4430 return src;
4431 }
4432
4433 static struct tgsi_texture_offset
4434 translate_tex_offset(struct st_translate *t,
4435 const st_src_reg *in_offset, int idx)
4436 {
4437 struct tgsi_texture_offset offset;
4438 struct ureg_src imm_src;
4439
4440 switch (in_offset->file) {
4441 case PROGRAM_IMMEDIATE:
4442 imm_src = t->immediates[in_offset->index];
4443
4444 offset.File = imm_src.File;
4445 offset.Index = imm_src.Index;
4446 offset.SwizzleX = imm_src.SwizzleX;
4447 offset.SwizzleY = imm_src.SwizzleY;
4448 offset.SwizzleZ = imm_src.SwizzleZ;
4449 offset.Padding = 0;
4450 break;
4451 case PROGRAM_TEMPORARY:
4452 imm_src = ureg_src(t->temps[in_offset->index]);
4453 offset.File = imm_src.File;
4454 offset.Index = imm_src.Index;
4455 offset.SwizzleX = GET_SWZ(in_offset->swizzle, 0);
4456 offset.SwizzleY = GET_SWZ(in_offset->swizzle, 1);
4457 offset.SwizzleZ = GET_SWZ(in_offset->swizzle, 2);
4458 offset.Padding = 0;
4459 break;
4460 default:
4461 break;
4462 }
4463 return offset;
4464 }
4465
4466 static void
4467 compile_tgsi_instruction(struct st_translate *t,
4468 const glsl_to_tgsi_instruction *inst,
4469 bool clamp_dst_color_output)
4470 {
4471 struct ureg_program *ureg = t->ureg;
4472 GLuint i;
4473 struct ureg_dst dst[1];
4474 struct ureg_src src[4];
4475 struct tgsi_texture_offset texoffsets[MAX_GLSL_TEXTURE_OFFSET];
4476
4477 unsigned num_dst;
4478 unsigned num_src;
4479 unsigned tex_target;
4480
4481 num_dst = num_inst_dst_regs(inst->op);
4482 num_src = num_inst_src_regs(inst->op);
4483
4484 if (num_dst)
4485 dst[0] = translate_dst(t,
4486 &inst->dst,
4487 inst->saturate,
4488 clamp_dst_color_output);
4489
4490 for (i = 0; i < num_src; i++)
4491 src[i] = translate_src(t, &inst->src[i]);
4492
4493 switch(inst->op) {
4494 case TGSI_OPCODE_BGNLOOP:
4495 case TGSI_OPCODE_CAL:
4496 case TGSI_OPCODE_ELSE:
4497 case TGSI_OPCODE_ENDLOOP:
4498 case TGSI_OPCODE_IF:
4499 case TGSI_OPCODE_UIF:
4500 assert(num_dst == 0);
4501 ureg_label_insn(ureg,
4502 inst->op,
4503 src, num_src,
4504 get_label(t,
4505 inst->op == TGSI_OPCODE_CAL ? inst->function->sig_id : 0));
4506 return;
4507
4508 case TGSI_OPCODE_TEX:
4509 case TGSI_OPCODE_TXB:
4510 case TGSI_OPCODE_TXD:
4511 case TGSI_OPCODE_TXL:
4512 case TGSI_OPCODE_TXP:
4513 case TGSI_OPCODE_TXQ:
4514 case TGSI_OPCODE_TXF:
4515 case TGSI_OPCODE_TEX2:
4516 case TGSI_OPCODE_TXB2:
4517 case TGSI_OPCODE_TXL2:
4518 case TGSI_OPCODE_TG4:
4519 case TGSI_OPCODE_LODQ:
4520 src[num_src++] = t->samplers[inst->sampler];
4521 for (i = 0; i < inst->tex_offset_num_offset; i++) {
4522 texoffsets[i] = translate_tex_offset(t, &inst->tex_offsets[i], i);
4523 }
4524 tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
4525
4526 ureg_tex_insn(ureg,
4527 inst->op,
4528 dst, num_dst,
4529 tex_target,
4530 texoffsets, inst->tex_offset_num_offset,
4531 src, num_src);
4532 return;
4533
4534 case TGSI_OPCODE_SCS:
4535 dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XY);
4536 ureg_insn(ureg, inst->op, dst, num_dst, src, num_src);
4537 break;
4538
4539 default:
4540 ureg_insn(ureg,
4541 inst->op,
4542 dst, num_dst,
4543 src, num_src);
4544 break;
4545 }
4546 }
4547
4548 /**
4549 * Emit the TGSI instructions for inverting and adjusting WPOS.
4550 * This code is unavoidable because it also depends on whether
4551 * a FBO is bound (STATE_FB_WPOS_Y_TRANSFORM).
4552 */
4553 static void
4554 emit_wpos_adjustment( struct st_translate *t,
4555 const struct gl_program *program,
4556 boolean invert,
4557 GLfloat adjX, GLfloat adjY[2])
4558 {
4559 struct ureg_program *ureg = t->ureg;
4560
4561 /* Fragment program uses fragment position input.
4562 * Need to replace instances of INPUT[WPOS] with temp T
4563 * where T = INPUT[WPOS] by y is inverted.
4564 */
4565 static const gl_state_index wposTransformState[STATE_LENGTH]
4566 = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM,
4567 (gl_state_index)0, (gl_state_index)0, (gl_state_index)0 };
4568
4569 /* XXX: note we are modifying the incoming shader here! Need to
4570 * do this before emitting the constant decls below, or this
4571 * will be missed:
4572 */
4573 unsigned wposTransConst = _mesa_add_state_reference(program->Parameters,
4574 wposTransformState);
4575
4576 struct ureg_src wpostrans = ureg_DECL_constant( ureg, wposTransConst );
4577 struct ureg_dst wpos_temp = ureg_DECL_temporary( ureg );
4578 struct ureg_src wpos_input = t->inputs[t->inputMapping[VARYING_SLOT_POS]];
4579
4580 /* First, apply the coordinate shift: */
4581 if (adjX || adjY[0] || adjY[1]) {
4582 if (adjY[0] != adjY[1]) {
4583 /* Adjust the y coordinate by adjY[1] or adjY[0] respectively
4584 * depending on whether inversion is actually going to be applied
4585 * or not, which is determined by testing against the inversion
4586 * state variable used below, which will be either +1 or -1.
4587 */
4588 struct ureg_dst adj_temp = ureg_DECL_local_temporary(ureg);
4589
4590 ureg_CMP(ureg, adj_temp,
4591 ureg_scalar(wpostrans, invert ? 2 : 0),
4592 ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f),
4593 ureg_imm4f(ureg, adjX, adjY[1], 0.0f, 0.0f));
4594 ureg_ADD(ureg, wpos_temp, wpos_input, ureg_src(adj_temp));
4595 } else {
4596 ureg_ADD(ureg, wpos_temp, wpos_input,
4597 ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f));
4598 }
4599 wpos_input = ureg_src(wpos_temp);
4600 } else {
4601 /* MOV wpos_temp, input[wpos]
4602 */
4603 ureg_MOV( ureg, wpos_temp, wpos_input );
4604 }
4605
4606 /* Now the conditional y flip: STATE_FB_WPOS_Y_TRANSFORM.xy/zw will be
4607 * inversion/identity, or the other way around if we're drawing to an FBO.
4608 */
4609 if (invert) {
4610 /* MAD wpos_temp.y, wpos_input, wpostrans.xxxx, wpostrans.yyyy
4611 */
4612 ureg_MAD( ureg,
4613 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
4614 wpos_input,
4615 ureg_scalar(wpostrans, 0),
4616 ureg_scalar(wpostrans, 1));
4617 } else {
4618 /* MAD wpos_temp.y, wpos_input, wpostrans.zzzz, wpostrans.wwww
4619 */
4620 ureg_MAD( ureg,
4621 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
4622 wpos_input,
4623 ureg_scalar(wpostrans, 2),
4624 ureg_scalar(wpostrans, 3));
4625 }
4626
4627 /* Use wpos_temp as position input from here on:
4628 */
4629 t->inputs[t->inputMapping[VARYING_SLOT_POS]] = ureg_src(wpos_temp);
4630 }
4631
4632
4633 /**
4634 * Emit fragment position/ooordinate code.
4635 */
4636 static void
4637 emit_wpos(struct st_context *st,
4638 struct st_translate *t,
4639 const struct gl_program *program,
4640 struct ureg_program *ureg)
4641 {
4642 const struct gl_fragment_program *fp =
4643 (const struct gl_fragment_program *) program;
4644 struct pipe_screen *pscreen = st->pipe->screen;
4645 GLfloat adjX = 0.0f;
4646 GLfloat adjY[2] = { 0.0f, 0.0f };
4647 boolean invert = FALSE;
4648
4649 /* Query the pixel center conventions supported by the pipe driver and set
4650 * adjX, adjY to help out if it cannot handle the requested one internally.
4651 *
4652 * The bias of the y-coordinate depends on whether y-inversion takes place
4653 * (adjY[1]) or not (adjY[0]), which is in turn dependent on whether we are
4654 * drawing to an FBO (causes additional inversion), and whether the the pipe
4655 * driver origin and the requested origin differ (the latter condition is
4656 * stored in the 'invert' variable).
4657 *
4658 * For height = 100 (i = integer, h = half-integer, l = lower, u = upper):
4659 *
4660 * center shift only:
4661 * i -> h: +0.5
4662 * h -> i: -0.5
4663 *
4664 * inversion only:
4665 * l,i -> u,i: ( 0.0 + 1.0) * -1 + 100 = 99
4666 * l,h -> u,h: ( 0.5 + 0.0) * -1 + 100 = 99.5
4667 * u,i -> l,i: (99.0 + 1.0) * -1 + 100 = 0
4668 * u,h -> l,h: (99.5 + 0.0) * -1 + 100 = 0.5
4669 *
4670 * inversion and center shift:
4671 * l,i -> u,h: ( 0.0 + 0.5) * -1 + 100 = 99.5
4672 * l,h -> u,i: ( 0.5 + 0.5) * -1 + 100 = 99
4673 * u,i -> l,h: (99.0 + 0.5) * -1 + 100 = 0.5
4674 * u,h -> l,i: (99.5 + 0.5) * -1 + 100 = 0
4675 */
4676 if (fp->OriginUpperLeft) {
4677 /* Fragment shader wants origin in upper-left */
4678 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT)) {
4679 /* the driver supports upper-left origin */
4680 }
4681 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT)) {
4682 /* the driver supports lower-left origin, need to invert Y */
4683 ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
4684 invert = TRUE;
4685 }
4686 else
4687 assert(0);
4688 }
4689 else {
4690 /* Fragment shader wants origin in lower-left */
4691 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT))
4692 /* the driver supports lower-left origin */
4693 ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
4694 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT))
4695 /* the driver supports upper-left origin, need to invert Y */
4696 invert = TRUE;
4697 else
4698 assert(0);
4699 }
4700
4701 if (fp->PixelCenterInteger) {
4702 /* Fragment shader wants pixel center integer */
4703 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
4704 /* the driver supports pixel center integer */
4705 adjY[1] = 1.0f;
4706 ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
4707 }
4708 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
4709 /* the driver supports pixel center half integer, need to bias X,Y */
4710 adjX = -0.5f;
4711 adjY[0] = -0.5f;
4712 adjY[1] = 0.5f;
4713 }
4714 else
4715 assert(0);
4716 }
4717 else {
4718 /* Fragment shader wants pixel center half integer */
4719 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
4720 /* the driver supports pixel center half integer */
4721 }
4722 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
4723 /* the driver supports pixel center integer, need to bias X,Y */
4724 adjX = adjY[0] = adjY[1] = 0.5f;
4725 ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
4726 }
4727 else
4728 assert(0);
4729 }
4730
4731 /* we invert after adjustment so that we avoid the MOV to temporary,
4732 * and reuse the adjustment ADD instead */
4733 emit_wpos_adjustment(t, program, invert, adjX, adjY);
4734 }
4735
4736 /**
4737 * OpenGL's fragment gl_FrontFace input is 1 for front-facing, 0 for back.
4738 * TGSI uses +1 for front, -1 for back.
4739 * This function converts the TGSI value to the GL value. Simply clamping/
4740 * saturating the value to [0,1] does the job.
4741 */
4742 static void
4743 emit_face_var(struct st_translate *t)
4744 {
4745 struct ureg_program *ureg = t->ureg;
4746 struct ureg_dst face_temp = ureg_DECL_temporary(ureg);
4747 struct ureg_src face_input = t->inputs[t->inputMapping[VARYING_SLOT_FACE]];
4748
4749 /* MOV_SAT face_temp, input[face] */
4750 face_temp = ureg_saturate(face_temp);
4751 ureg_MOV(ureg, face_temp, face_input);
4752
4753 /* Use face_temp as face input from here on: */
4754 t->inputs[t->inputMapping[VARYING_SLOT_FACE]] = ureg_src(face_temp);
4755 }
4756
4757 static void
4758 emit_edgeflags(struct st_translate *t)
4759 {
4760 struct ureg_program *ureg = t->ureg;
4761 struct ureg_dst edge_dst = t->outputs[t->outputMapping[VARYING_SLOT_EDGE]];
4762 struct ureg_src edge_src = t->inputs[t->inputMapping[VERT_ATTRIB_EDGEFLAG]];
4763
4764 ureg_MOV(ureg, edge_dst, edge_src);
4765 }
4766
4767 /**
4768 * Translate intermediate IR (glsl_to_tgsi_instruction) to TGSI format.
4769 * \param program the program to translate
4770 * \param numInputs number of input registers used
4771 * \param inputMapping maps Mesa fragment program inputs to TGSI generic
4772 * input indexes
4773 * \param inputSemanticName the TGSI_SEMANTIC flag for each input
4774 * \param inputSemanticIndex the semantic index (ex: which texcoord) for
4775 * each input
4776 * \param interpMode the TGSI_INTERPOLATE_LINEAR/PERSP mode for each input
4777 * \param numOutputs number of output registers used
4778 * \param outputMapping maps Mesa fragment program outputs to TGSI
4779 * generic outputs
4780 * \param outputSemanticName the TGSI_SEMANTIC flag for each output
4781 * \param outputSemanticIndex the semantic index (ex: which texcoord) for
4782 * each output
4783 *
4784 * \return PIPE_OK or PIPE_ERROR_OUT_OF_MEMORY
4785 */
4786 extern "C" enum pipe_error
4787 st_translate_program(
4788 struct gl_context *ctx,
4789 uint procType,
4790 struct ureg_program *ureg,
4791 glsl_to_tgsi_visitor *program,
4792 const struct gl_program *proginfo,
4793 GLuint numInputs,
4794 const GLuint inputMapping[],
4795 const ubyte inputSemanticName[],
4796 const ubyte inputSemanticIndex[],
4797 const GLuint interpMode[],
4798 const GLboolean is_centroid[],
4799 GLuint numOutputs,
4800 const GLuint outputMapping[],
4801 const ubyte outputSemanticName[],
4802 const ubyte outputSemanticIndex[],
4803 boolean passthrough_edgeflags,
4804 boolean clamp_color)
4805 {
4806 struct st_translate *t;
4807 unsigned i;
4808 enum pipe_error ret = PIPE_OK;
4809
4810 assert(numInputs <= Elements(t->inputs));
4811 assert(numOutputs <= Elements(t->outputs));
4812
4813 t = CALLOC_STRUCT(st_translate);
4814 if (!t) {
4815 ret = PIPE_ERROR_OUT_OF_MEMORY;
4816 goto out;
4817 }
4818
4819 memset(t, 0, sizeof *t);
4820
4821 t->procType = procType;
4822 t->inputMapping = inputMapping;
4823 t->outputMapping = outputMapping;
4824 t->ureg = ureg;
4825
4826 if (program->shader_program) {
4827 for (i = 0; i < program->shader_program->NumUserUniformStorage; i++) {
4828 struct gl_uniform_storage *const storage =
4829 &program->shader_program->UniformStorage[i];
4830
4831 _mesa_uniform_detach_all_driver_storage(storage);
4832 }
4833 }
4834
4835 /*
4836 * Declare input attributes.
4837 */
4838 if (procType == TGSI_PROCESSOR_FRAGMENT) {
4839 for (i = 0; i < numInputs; i++) {
4840 t->inputs[i] = ureg_DECL_fs_input_cyl_centroid(ureg,
4841 inputSemanticName[i],
4842 inputSemanticIndex[i],
4843 interpMode[i], 0,
4844 is_centroid[i]);
4845 }
4846
4847 if (proginfo->InputsRead & VARYING_BIT_POS) {
4848 /* Must do this after setting up t->inputs, and before
4849 * emitting constant references, below:
4850 */
4851 emit_wpos(st_context(ctx), t, proginfo, ureg);
4852 }
4853
4854 if (proginfo->InputsRead & VARYING_BIT_FACE)
4855 emit_face_var(t);
4856
4857 /*
4858 * Declare output attributes.
4859 */
4860 for (i = 0; i < numOutputs; i++) {
4861 switch (outputSemanticName[i]) {
4862 case TGSI_SEMANTIC_POSITION:
4863 t->outputs[i] = ureg_DECL_output(ureg,
4864 TGSI_SEMANTIC_POSITION, /* Z/Depth */
4865 outputSemanticIndex[i]);
4866 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Z);
4867 break;
4868 case TGSI_SEMANTIC_STENCIL:
4869 t->outputs[i] = ureg_DECL_output(ureg,
4870 TGSI_SEMANTIC_STENCIL, /* Stencil */
4871 outputSemanticIndex[i]);
4872 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Y);
4873 break;
4874 case TGSI_SEMANTIC_COLOR:
4875 t->outputs[i] = ureg_DECL_output(ureg,
4876 TGSI_SEMANTIC_COLOR,
4877 outputSemanticIndex[i]);
4878 break;
4879 default:
4880 assert(!"fragment shader outputs must be POSITION/STENCIL/COLOR");
4881 ret = PIPE_ERROR_BAD_INPUT;
4882 goto out;
4883 }
4884 }
4885 }
4886 else if (procType == TGSI_PROCESSOR_GEOMETRY) {
4887 for (i = 0; i < numInputs; i++) {
4888 t->inputs[i] = ureg_DECL_gs_input(ureg,
4889 i,
4890 inputSemanticName[i],
4891 inputSemanticIndex[i]);
4892 }
4893
4894 for (i = 0; i < numOutputs; i++) {
4895 t->outputs[i] = ureg_DECL_output(ureg,
4896 outputSemanticName[i],
4897 outputSemanticIndex[i]);
4898 }
4899 }
4900 else {
4901 assert(procType == TGSI_PROCESSOR_VERTEX);
4902
4903 for (i = 0; i < numInputs; i++) {
4904 t->inputs[i] = ureg_DECL_vs_input(ureg, i);
4905 }
4906
4907 for (i = 0; i < numOutputs; i++) {
4908 t->outputs[i] = ureg_DECL_output(ureg,
4909 outputSemanticName[i],
4910 outputSemanticIndex[i]);
4911 if (outputSemanticName[i] == TGSI_SEMANTIC_FOG) {
4912 /* force register to contain a fog coordinate in the form (F, 0, 0, 1). */
4913 ureg_MOV(ureg,
4914 ureg_writemask(t->outputs[i], TGSI_WRITEMASK_YZW),
4915 ureg_imm4f(ureg, 0.0f, 0.0f, 0.0f, 1.0f));
4916 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_X);
4917 }
4918 }
4919 if (passthrough_edgeflags)
4920 emit_edgeflags(t);
4921 }
4922
4923 /* Declare address register.
4924 */
4925 if (program->num_address_regs > 0) {
4926 assert(program->num_address_regs <= 2);
4927 t->address[0] = ureg_DECL_address(ureg);
4928 if (program->num_address_regs == 2)
4929 t->address[1] = ureg_DECL_address(ureg);
4930 }
4931
4932 /* Declare misc input registers
4933 */
4934 {
4935 GLbitfield sysInputs = proginfo->SystemValuesRead;
4936 unsigned numSys = 0;
4937 for (i = 0; sysInputs; i++) {
4938 if (sysInputs & (1 << i)) {
4939 unsigned semName = mesa_sysval_to_semantic[i];
4940 t->systemValues[i] = ureg_DECL_system_value(ureg, numSys, semName, 0);
4941 if (semName == TGSI_SEMANTIC_INSTANCEID ||
4942 semName == TGSI_SEMANTIC_VERTEXID) {
4943 /* From Gallium perspective, these system values are always
4944 * integer, and require native integer support. However, if
4945 * native integer is supported on the vertex stage but not the
4946 * pixel stage (e.g, i915g + draw), Mesa will generate IR that
4947 * assumes these system values are floats. To resolve the
4948 * inconsistency, we insert a U2F.
4949 */
4950 struct st_context *st = st_context(ctx);
4951 struct pipe_screen *pscreen = st->pipe->screen;
4952 assert(procType == TGSI_PROCESSOR_VERTEX);
4953 assert(pscreen->get_shader_param(pscreen, PIPE_SHADER_VERTEX, PIPE_SHADER_CAP_INTEGERS));
4954 if (!ctx->Const.NativeIntegers) {
4955 struct ureg_dst temp = ureg_DECL_local_temporary(t->ureg);
4956 ureg_U2F( t->ureg, ureg_writemask(temp, TGSI_WRITEMASK_X), t->systemValues[i]);
4957 t->systemValues[i] = ureg_scalar(ureg_src(temp), 0);
4958 }
4959 }
4960 numSys++;
4961 sysInputs &= ~(1 << i);
4962 }
4963 }
4964 }
4965
4966 /* Copy over array sizes
4967 */
4968 memcpy(t->array_sizes, program->array_sizes, sizeof(unsigned) * program->next_array);
4969
4970 /* Emit constants and uniforms. TGSI uses a single index space for these,
4971 * so we put all the translated regs in t->constants.
4972 */
4973 if (proginfo->Parameters) {
4974 t->constants = (struct ureg_src *)
4975 calloc(proginfo->Parameters->NumParameters, sizeof(t->constants[0]));
4976 if (t->constants == NULL) {
4977 ret = PIPE_ERROR_OUT_OF_MEMORY;
4978 goto out;
4979 }
4980
4981 for (i = 0; i < proginfo->Parameters->NumParameters; i++) {
4982 switch (proginfo->Parameters->Parameters[i].Type) {
4983 case PROGRAM_STATE_VAR:
4984 case PROGRAM_UNIFORM:
4985 t->constants[i] = ureg_DECL_constant(ureg, i);
4986 break;
4987
4988 /* Emit immediates for PROGRAM_CONSTANT only when there's no indirect
4989 * addressing of the const buffer.
4990 * FIXME: Be smarter and recognize param arrays:
4991 * indirect addressing is only valid within the referenced
4992 * array.
4993 */
4994 case PROGRAM_CONSTANT:
4995 if (program->indirect_addr_consts)
4996 t->constants[i] = ureg_DECL_constant(ureg, i);
4997 else
4998 t->constants[i] = emit_immediate(t,
4999 proginfo->Parameters->ParameterValues[i],
5000 proginfo->Parameters->Parameters[i].DataType,
5001 4);
5002 break;
5003 default:
5004 break;
5005 }
5006 }
5007 }
5008
5009 if (program->shader_program) {
5010 unsigned num_ubos = program->shader_program->NumUniformBlocks;
5011
5012 for (i = 0; i < num_ubos; i++) {
5013 ureg_DECL_constant2D(t->ureg, 0, program->shader_program->UniformBlocks[i].UniformBufferSize / 4, i + 1);
5014 }
5015 }
5016
5017 /* Emit immediate values.
5018 */
5019 t->immediates = (struct ureg_src *)
5020 calloc(program->num_immediates, sizeof(struct ureg_src));
5021 if (t->immediates == NULL) {
5022 ret = PIPE_ERROR_OUT_OF_MEMORY;
5023 goto out;
5024 }
5025 i = 0;
5026 foreach_list(node, &program->immediates) {
5027 immediate_storage *imm = (immediate_storage *) node;
5028 assert(i < program->num_immediates);
5029 t->immediates[i++] = emit_immediate(t, imm->values, imm->type, imm->size);
5030 }
5031 assert(i == program->num_immediates);
5032
5033 /* texture samplers */
5034 for (i = 0; i < ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits; i++) {
5035 if (program->samplers_used & (1 << i)) {
5036 t->samplers[i] = ureg_DECL_sampler(ureg, i);
5037 }
5038 }
5039
5040 /* Emit each instruction in turn:
5041 */
5042 foreach_list(n, &program->instructions) {
5043 set_insn_start(t, ureg_get_instruction_number(ureg));
5044 compile_tgsi_instruction(t, (glsl_to_tgsi_instruction *) n, clamp_color);
5045 }
5046
5047 /* Fix up all emitted labels:
5048 */
5049 for (i = 0; i < t->labels_count; i++) {
5050 ureg_fixup_label(ureg, t->labels[i].token,
5051 t->insn[t->labels[i].branch_target]);
5052 }
5053
5054 if (program->shader_program) {
5055 /* This has to be done last. Any operation the can cause
5056 * prog->ParameterValues to get reallocated (e.g., anything that adds a
5057 * program constant) has to happen before creating this linkage.
5058 */
5059 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5060 if (program->shader_program->_LinkedShaders[i] == NULL)
5061 continue;
5062
5063 _mesa_associate_uniform_storage(ctx, program->shader_program,
5064 program->shader_program->_LinkedShaders[i]->Program->Parameters);
5065 }
5066 }
5067
5068 out:
5069 if (t) {
5070 free(t->insn);
5071 free(t->labels);
5072 free(t->constants);
5073 free(t->immediates);
5074
5075 if (t->error) {
5076 debug_printf("%s: translate error flag set\n", __FUNCTION__);
5077 }
5078
5079 free(t);
5080 }
5081
5082 return ret;
5083 }
5084 /* ----------------------------- End TGSI code ------------------------------ */
5085
5086
5087 static unsigned
5088 shader_stage_to_ptarget(gl_shader_stage stage)
5089 {
5090 switch (stage) {
5091 case MESA_SHADER_VERTEX:
5092 return PIPE_SHADER_VERTEX;
5093 case MESA_SHADER_FRAGMENT:
5094 return PIPE_SHADER_FRAGMENT;
5095 case MESA_SHADER_GEOMETRY:
5096 return PIPE_SHADER_GEOMETRY;
5097 case MESA_SHADER_COMPUTE:
5098 return PIPE_SHADER_COMPUTE;
5099 }
5100
5101 assert(!"should not be reached");
5102 return PIPE_SHADER_VERTEX;
5103 }
5104
5105
5106 /**
5107 * Convert a shader's GLSL IR into a Mesa gl_program, although without
5108 * generating Mesa IR.
5109 */
5110 static struct gl_program *
5111 get_mesa_program(struct gl_context *ctx,
5112 struct gl_shader_program *shader_program,
5113 struct gl_shader *shader)
5114 {
5115 glsl_to_tgsi_visitor* v;
5116 struct gl_program *prog;
5117 GLenum target = _mesa_shader_stage_to_program(shader->Stage);
5118 bool progress;
5119 struct gl_shader_compiler_options *options =
5120 &ctx->ShaderCompilerOptions[_mesa_shader_enum_to_shader_stage(shader->Type)];
5121 struct pipe_screen *pscreen = ctx->st->pipe->screen;
5122 unsigned ptarget = shader_stage_to_ptarget(shader->Stage);
5123
5124 validate_ir_tree(shader->ir);
5125
5126 prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
5127 if (!prog)
5128 return NULL;
5129 prog->Parameters = _mesa_new_parameter_list();
5130 v = new glsl_to_tgsi_visitor();
5131 v->ctx = ctx;
5132 v->prog = prog;
5133 v->shader_program = shader_program;
5134 v->options = options;
5135 v->glsl_version = ctx->Const.GLSLVersion;
5136 v->native_integers = ctx->Const.NativeIntegers;
5137
5138 v->have_sqrt = pscreen->get_shader_param(pscreen, ptarget,
5139 PIPE_SHADER_CAP_TGSI_SQRT_SUPPORTED);
5140
5141 _mesa_generate_parameters_list_for_uniforms(shader_program, shader,
5142 prog->Parameters);
5143
5144 /* Remove reads from output registers. */
5145 lower_output_reads(shader->ir);
5146
5147 /* Emit intermediate IR for main(). */
5148 visit_exec_list(shader->ir, v);
5149
5150 /* Now emit bodies for any functions that were used. */
5151 do {
5152 progress = GL_FALSE;
5153
5154 foreach_list(node, &v->function_signatures) {
5155 function_entry *entry = (function_entry *) node;
5156
5157 if (!entry->bgn_inst) {
5158 v->current_function = entry;
5159
5160 entry->bgn_inst = v->emit(NULL, TGSI_OPCODE_BGNSUB);
5161 entry->bgn_inst->function = entry;
5162
5163 visit_exec_list(&entry->sig->body, v);
5164
5165 glsl_to_tgsi_instruction *last;
5166 last = (glsl_to_tgsi_instruction *)v->instructions.get_tail();
5167 if (last->op != TGSI_OPCODE_RET)
5168 v->emit(NULL, TGSI_OPCODE_RET);
5169
5170 glsl_to_tgsi_instruction *end;
5171 end = v->emit(NULL, TGSI_OPCODE_ENDSUB);
5172 end->function = entry;
5173
5174 progress = GL_TRUE;
5175 }
5176 }
5177 } while (progress);
5178
5179 #if 0
5180 /* Print out some information (for debugging purposes) used by the
5181 * optimization passes. */
5182 for (i=0; i < v->next_temp; i++) {
5183 int fr = v->get_first_temp_read(i);
5184 int fw = v->get_first_temp_write(i);
5185 int lr = v->get_last_temp_read(i);
5186 int lw = v->get_last_temp_write(i);
5187
5188 printf("Temp %d: FR=%3d FW=%3d LR=%3d LW=%3d\n", i, fr, fw, lr, lw);
5189 assert(fw <= fr);
5190 }
5191 #endif
5192
5193 /* Perform optimizations on the instructions in the glsl_to_tgsi_visitor. */
5194 v->simplify_cmp();
5195 v->copy_propagate();
5196 while (v->eliminate_dead_code_advanced());
5197
5198 v->eliminate_dead_code();
5199 v->merge_registers();
5200 v->renumber_registers();
5201
5202 /* Write the END instruction. */
5203 v->emit(NULL, TGSI_OPCODE_END);
5204
5205 if (ctx->_Shader->Flags & GLSL_DUMP) {
5206 printf("\n");
5207 printf("GLSL IR for linked %s program %d:\n",
5208 _mesa_shader_stage_to_string(shader->Stage),
5209 shader_program->Name);
5210 _mesa_print_ir(stdout, shader->ir, NULL);
5211 printf("\n");
5212 printf("\n");
5213 fflush(stdout);
5214 }
5215
5216 prog->Instructions = NULL;
5217 prog->NumInstructions = 0;
5218
5219 do_set_program_inouts(shader->ir, prog, shader->Stage);
5220 count_resources(v, prog);
5221
5222 _mesa_reference_program(ctx, &shader->Program, prog);
5223
5224 /* This has to be done last. Any operation the can cause
5225 * prog->ParameterValues to get reallocated (e.g., anything that adds a
5226 * program constant) has to happen before creating this linkage.
5227 */
5228 _mesa_associate_uniform_storage(ctx, shader_program, prog->Parameters);
5229 if (!shader_program->LinkStatus) {
5230 return NULL;
5231 }
5232
5233 struct st_vertex_program *stvp;
5234 struct st_fragment_program *stfp;
5235 struct st_geometry_program *stgp;
5236
5237 switch (shader->Type) {
5238 case GL_VERTEX_SHADER:
5239 stvp = (struct st_vertex_program *)prog;
5240 stvp->glsl_to_tgsi = v;
5241 break;
5242 case GL_FRAGMENT_SHADER:
5243 stfp = (struct st_fragment_program *)prog;
5244 stfp->glsl_to_tgsi = v;
5245 break;
5246 case GL_GEOMETRY_SHADER:
5247 stgp = (struct st_geometry_program *)prog;
5248 stgp->glsl_to_tgsi = v;
5249 stgp->Base.InputType = shader_program->Geom.InputType;
5250 stgp->Base.OutputType = shader_program->Geom.OutputType;
5251 stgp->Base.VerticesOut = shader_program->Geom.VerticesOut;
5252 stgp->Base.Invocations = shader_program->Geom.Invocations;
5253 break;
5254 default:
5255 assert(!"should not be reached");
5256 return NULL;
5257 }
5258
5259 return prog;
5260 }
5261
5262 extern "C" {
5263
5264 struct gl_shader *
5265 st_new_shader(struct gl_context *ctx, GLuint name, GLuint type)
5266 {
5267 struct gl_shader *shader;
5268 assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER ||
5269 type == GL_GEOMETRY_SHADER_ARB);
5270 shader = rzalloc(NULL, struct gl_shader);
5271 if (shader) {
5272 shader->Type = type;
5273 shader->Stage = _mesa_shader_enum_to_shader_stage(type);
5274 shader->Name = name;
5275 _mesa_init_shader(ctx, shader);
5276 }
5277 return shader;
5278 }
5279
5280 struct gl_shader_program *
5281 st_new_shader_program(struct gl_context *ctx, GLuint name)
5282 {
5283 struct gl_shader_program *shProg;
5284 shProg = rzalloc(NULL, struct gl_shader_program);
5285 if (shProg) {
5286 shProg->Name = name;
5287 _mesa_init_shader_program(ctx, shProg);
5288 }
5289 return shProg;
5290 }
5291
5292 /**
5293 * Link a shader.
5294 * Called via ctx->Driver.LinkShader()
5295 * This actually involves converting GLSL IR into an intermediate TGSI-like IR
5296 * with code lowering and other optimizations.
5297 */
5298 GLboolean
5299 st_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
5300 {
5301 assert(prog->LinkStatus);
5302
5303 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5304 if (prog->_LinkedShaders[i] == NULL)
5305 continue;
5306
5307 bool progress;
5308 exec_list *ir = prog->_LinkedShaders[i]->ir;
5309 const struct gl_shader_compiler_options *options =
5310 &ctx->ShaderCompilerOptions[_mesa_shader_enum_to_shader_stage(prog->_LinkedShaders[i]->Type)];
5311
5312 /* If there are forms of indirect addressing that the driver
5313 * cannot handle, perform the lowering pass.
5314 */
5315 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput ||
5316 options->EmitNoIndirectTemp || options->EmitNoIndirectUniform) {
5317 lower_variable_index_to_cond_assign(ir,
5318 options->EmitNoIndirectInput,
5319 options->EmitNoIndirectOutput,
5320 options->EmitNoIndirectTemp,
5321 options->EmitNoIndirectUniform);
5322 }
5323
5324 if (ctx->Extensions.ARB_shading_language_packing) {
5325 unsigned lower_inst = LOWER_PACK_SNORM_2x16 |
5326 LOWER_UNPACK_SNORM_2x16 |
5327 LOWER_PACK_UNORM_2x16 |
5328 LOWER_UNPACK_UNORM_2x16 |
5329 LOWER_PACK_SNORM_4x8 |
5330 LOWER_UNPACK_SNORM_4x8 |
5331 LOWER_UNPACK_UNORM_4x8 |
5332 LOWER_PACK_UNORM_4x8 |
5333 LOWER_PACK_HALF_2x16 |
5334 LOWER_UNPACK_HALF_2x16;
5335
5336 lower_packing_builtins(ir, lower_inst);
5337 }
5338
5339 lower_offset_arrays(ir);
5340 do_mat_op_to_vec(ir);
5341 lower_instructions(ir,
5342 MOD_TO_FRACT |
5343 DIV_TO_MUL_RCP |
5344 EXP_TO_EXP2 |
5345 LOG_TO_LOG2 |
5346 (options->EmitNoPow ? POW_TO_EXP2 : 0) |
5347 (!ctx->Const.NativeIntegers ? INT_DIV_TO_MUL_RCP : 0));
5348
5349 lower_ubo_reference(prog->_LinkedShaders[i], ir);
5350 do_vec_index_to_cond_assign(ir);
5351 lower_vector_insert(ir, true);
5352 lower_quadop_vector(ir, false);
5353 lower_noise(ir);
5354 if (options->MaxIfDepth == 0) {
5355 lower_discard(ir);
5356 }
5357
5358 do {
5359 progress = false;
5360
5361 progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
5362
5363 progress = do_common_optimization(ir, true, true, options,
5364 ctx->Const.NativeIntegers)
5365 || progress;
5366
5367 progress = lower_if_to_cond_assign(ir, options->MaxIfDepth) || progress;
5368
5369 } while (progress);
5370
5371 validate_ir_tree(ir);
5372 }
5373
5374 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5375 struct gl_program *linked_prog;
5376
5377 if (prog->_LinkedShaders[i] == NULL)
5378 continue;
5379
5380 linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
5381
5382 if (linked_prog) {
5383 _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
5384 linked_prog);
5385 if (!ctx->Driver.ProgramStringNotify(ctx,
5386 _mesa_shader_stage_to_program(i),
5387 linked_prog)) {
5388 _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
5389 NULL);
5390 _mesa_reference_program(ctx, &linked_prog, NULL);
5391 return GL_FALSE;
5392 }
5393 }
5394
5395 _mesa_reference_program(ctx, &linked_prog, NULL);
5396 }
5397
5398 return GL_TRUE;
5399 }
5400
5401 void
5402 st_translate_stream_output_info(glsl_to_tgsi_visitor *glsl_to_tgsi,
5403 const GLuint outputMapping[],
5404 struct pipe_stream_output_info *so)
5405 {
5406 unsigned i;
5407 struct gl_transform_feedback_info *info =
5408 &glsl_to_tgsi->shader_program->LinkedTransformFeedback;
5409
5410 for (i = 0; i < info->NumOutputs; i++) {
5411 so->output[i].register_index =
5412 outputMapping[info->Outputs[i].OutputRegister];
5413 so->output[i].start_component = info->Outputs[i].ComponentOffset;
5414 so->output[i].num_components = info->Outputs[i].NumComponents;
5415 so->output[i].output_buffer = info->Outputs[i].OutputBuffer;
5416 so->output[i].dst_offset = info->Outputs[i].DstOffset;
5417 }
5418
5419 for (i = 0; i < PIPE_MAX_SO_BUFFERS; i++) {
5420 so->stride[i] = info->BufferStride[i];
5421 }
5422 so->num_outputs = info->NumOutputs;
5423 }
5424
5425 } /* extern "C" */