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