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