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