5322903b93a277312579e4df40ff7eb9a82491ae
[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 "compiler/glsl/glsl_parser_extras.h"
36 #include "compiler/glsl/ir_optimization.h"
37 #include "compiler/glsl/program.h"
38
39 #include "main/errors.h"
40 #include "main/shaderobj.h"
41 #include "main/uniforms.h"
42 #include "main/shaderapi.h"
43 #include "main/shaderimage.h"
44 #include "program/prog_instruction.h"
45
46 #include "pipe/p_context.h"
47 #include "pipe/p_screen.h"
48 #include "tgsi/tgsi_ureg.h"
49 #include "tgsi/tgsi_info.h"
50 #include "util/u_math.h"
51 #include "util/u_memory.h"
52 #include "st_glsl_types.h"
53 #include "st_program.h"
54 #include "st_mesa_to_tgsi.h"
55 #include "st_format.h"
56 #include "st_nir.h"
57 #include "st_shader_cache.h"
58 #include "st_glsl_to_tgsi_temprename.h"
59
60 #include "util/hash_table.h"
61 #include <algorithm>
62
63 #define PROGRAM_ANY_CONST ((1 << PROGRAM_STATE_VAR) | \
64 (1 << PROGRAM_CONSTANT) | \
65 (1 << PROGRAM_UNIFORM))
66
67 #define MAX_GLSL_TEXTURE_OFFSET 4
68
69 #ifndef NDEBUG
70 #include "util/u_atomic.h"
71 #include "util/simple_mtx.h"
72 #include <fstream>
73 #include <ios>
74
75 /* Prepare to make it possible to specify log file */
76 static std::ofstream stats_log;
77
78 /* Helper function to check whether we want to write some statistics
79 * of the shader conversion.
80 */
81
82 static simple_mtx_t print_stats_mutex = _SIMPLE_MTX_INITIALIZER_NP;
83
84 static inline bool print_stats_enabled ()
85 {
86 static int stats_enabled = 0;
87
88 if (!stats_enabled) {
89 simple_mtx_lock(&print_stats_mutex);
90 if (!stats_enabled) {
91 const char *stats_filename = getenv("GLSL_TO_TGSI_PRINT_STATS");
92 if (stats_filename) {
93 bool write_header = std::ifstream(stats_filename).fail();
94 stats_log.open(stats_filename, std::ios_base::out | std::ios_base::app);
95 stats_enabled = stats_log.good() ? 1 : -1;
96 if (write_header)
97 stats_log << "arrays,temps,temps in arrays,total,instructions\n";
98 } else {
99 stats_enabled = -1;
100 }
101 }
102 simple_mtx_unlock(&print_stats_mutex);
103 }
104 return stats_enabled > 0;
105 }
106 #define PRINT_STATS(X) if (print_stats_enabled()) do { X; } while (false);
107 #else
108 #define PRINT_STATS(X)
109 #endif
110
111
112 static unsigned is_precise(const ir_variable *ir)
113 {
114 if (!ir)
115 return 0;
116 return ir->data.precise || ir->data.invariant;
117 }
118
119 class variable_storage {
120 DECLARE_RZALLOC_CXX_OPERATORS(variable_storage)
121
122 public:
123 variable_storage(ir_variable *var, gl_register_file file, int index,
124 unsigned array_id = 0)
125 : file(file), index(index), component(0), var(var), array_id(array_id)
126 {
127 assert(file != PROGRAM_ARRAY || array_id != 0);
128 }
129
130 gl_register_file file;
131 int index;
132
133 /* Explicit component location. This is given in terms of the GLSL-style
134 * swizzles where each double is a single component, i.e. for 64-bit types
135 * it can only be 0 or 1.
136 */
137 int component;
138 ir_variable *var; /* variable that maps to this, if any */
139 unsigned array_id;
140 };
141
142 class immediate_storage : public exec_node {
143 public:
144 immediate_storage(gl_constant_value *values, int size32, GLenum type)
145 {
146 memcpy(this->values, values, size32 * sizeof(gl_constant_value));
147 this->size32 = size32;
148 this->type = type;
149 }
150
151 /* doubles are stored across 2 gl_constant_values */
152 gl_constant_value values[4];
153 int size32; /**< Number of 32-bit components (1-4) */
154 GLenum type; /**< GL_DOUBLE, GL_FLOAT, GL_INT, GL_BOOL, or GL_UNSIGNED_INT */
155 };
156
157 static const st_src_reg undef_src = st_src_reg(PROGRAM_UNDEFINED, 0, GLSL_TYPE_ERROR);
158 static const st_dst_reg undef_dst = st_dst_reg(PROGRAM_UNDEFINED, SWIZZLE_NOOP, GLSL_TYPE_ERROR);
159
160 struct inout_decl {
161 unsigned mesa_index;
162 unsigned array_id; /* TGSI ArrayID; 1-based: 0 means not an array */
163 unsigned size;
164 unsigned interp_loc;
165 unsigned gs_out_streams;
166 enum glsl_interp_mode interp;
167 enum glsl_base_type base_type;
168 ubyte usage_mask; /* GLSL-style usage-mask, i.e. single bit per double */
169 bool invariant;
170 };
171
172 static struct inout_decl *
173 find_inout_array(struct inout_decl *decls, unsigned count, unsigned array_id)
174 {
175 assert(array_id != 0);
176
177 for (unsigned i = 0; i < count; i++) {
178 struct inout_decl *decl = &decls[i];
179
180 if (array_id == decl->array_id) {
181 return decl;
182 }
183 }
184
185 return NULL;
186 }
187
188 static enum glsl_base_type
189 find_array_type(struct inout_decl *decls, unsigned count, unsigned array_id)
190 {
191 if (!array_id)
192 return GLSL_TYPE_ERROR;
193 struct inout_decl *decl = find_inout_array(decls, count, array_id);
194 if (decl)
195 return decl->base_type;
196 return GLSL_TYPE_ERROR;
197 }
198
199 struct hwatomic_decl {
200 unsigned location;
201 unsigned binding;
202 unsigned size;
203 unsigned array_id;
204 };
205
206 struct glsl_to_tgsi_visitor : public ir_visitor {
207 public:
208 glsl_to_tgsi_visitor();
209 ~glsl_to_tgsi_visitor();
210
211 struct gl_context *ctx;
212 struct gl_program *prog;
213 struct gl_shader_program *shader_program;
214 struct gl_linked_shader *shader;
215 struct gl_shader_compiler_options *options;
216
217 int next_temp;
218
219 unsigned *array_sizes;
220 unsigned max_num_arrays;
221 unsigned next_array;
222
223 struct inout_decl inputs[4 * PIPE_MAX_SHADER_INPUTS];
224 unsigned num_inputs;
225 unsigned num_input_arrays;
226 struct inout_decl outputs[4 * PIPE_MAX_SHADER_OUTPUTS];
227 unsigned num_outputs;
228 unsigned num_output_arrays;
229
230 struct hwatomic_decl atomic_info[PIPE_MAX_HW_ATOMIC_BUFFERS];
231 unsigned num_atomics;
232 unsigned num_atomic_arrays;
233 int num_address_regs;
234 uint32_t samplers_used;
235 glsl_base_type sampler_types[PIPE_MAX_SAMPLERS];
236 enum tgsi_texture_type sampler_targets[PIPE_MAX_SAMPLERS];
237 int images_used;
238 enum tgsi_texture_type image_targets[PIPE_MAX_SHADER_IMAGES];
239 enum pipe_format image_formats[PIPE_MAX_SHADER_IMAGES];
240 bool image_wr[PIPE_MAX_SHADER_IMAGES];
241 bool indirect_addr_consts;
242 int wpos_transform_const;
243
244 bool native_integers;
245 bool have_sqrt;
246 bool have_fma;
247 bool use_shared_memory;
248 bool has_tex_txf_lz;
249 bool precise;
250 bool need_uarl;
251
252 variable_storage *find_variable_storage(ir_variable *var);
253
254 int add_constant(gl_register_file file, gl_constant_value values[8],
255 int size, GLenum datatype, uint16_t *swizzle_out);
256
257 st_src_reg get_temp(const glsl_type *type);
258 void reladdr_to_temp(ir_instruction *ir, st_src_reg *reg, int *num_reladdr);
259
260 st_src_reg st_src_reg_for_double(double val);
261 st_src_reg st_src_reg_for_float(float val);
262 st_src_reg st_src_reg_for_int(int val);
263 st_src_reg st_src_reg_for_int64(int64_t val);
264 st_src_reg st_src_reg_for_type(enum glsl_base_type type, int val);
265
266 /**
267 * \name Visit methods
268 *
269 * As typical for the visitor pattern, there must be one \c visit method for
270 * each concrete subclass of \c ir_instruction. Virtual base classes within
271 * the hierarchy should not have \c visit methods.
272 */
273 /*@{*/
274 virtual void visit(ir_variable *);
275 virtual void visit(ir_loop *);
276 virtual void visit(ir_loop_jump *);
277 virtual void visit(ir_function_signature *);
278 virtual void visit(ir_function *);
279 virtual void visit(ir_expression *);
280 virtual void visit(ir_swizzle *);
281 virtual void visit(ir_dereference_variable *);
282 virtual void visit(ir_dereference_array *);
283 virtual void visit(ir_dereference_record *);
284 virtual void visit(ir_assignment *);
285 virtual void visit(ir_constant *);
286 virtual void visit(ir_call *);
287 virtual void visit(ir_return *);
288 virtual void visit(ir_discard *);
289 virtual void visit(ir_texture *);
290 virtual void visit(ir_if *);
291 virtual void visit(ir_emit_vertex *);
292 virtual void visit(ir_end_primitive *);
293 virtual void visit(ir_barrier *);
294 /*@}*/
295
296 void visit_expression(ir_expression *, st_src_reg *) ATTRIBUTE_NOINLINE;
297
298 void visit_atomic_counter_intrinsic(ir_call *);
299 void visit_ssbo_intrinsic(ir_call *);
300 void visit_membar_intrinsic(ir_call *);
301 void visit_shared_intrinsic(ir_call *);
302 void visit_image_intrinsic(ir_call *);
303 void visit_generic_intrinsic(ir_call *, enum tgsi_opcode op);
304
305 st_src_reg result;
306
307 /** List of variable_storage */
308 struct hash_table *variables;
309
310 /** List of immediate_storage */
311 exec_list immediates;
312 unsigned num_immediates;
313
314 /** List of glsl_to_tgsi_instruction */
315 exec_list instructions;
316
317 glsl_to_tgsi_instruction *emit_asm(ir_instruction *ir, enum tgsi_opcode op,
318 st_dst_reg dst = undef_dst,
319 st_src_reg src0 = undef_src,
320 st_src_reg src1 = undef_src,
321 st_src_reg src2 = undef_src,
322 st_src_reg src3 = undef_src);
323
324 glsl_to_tgsi_instruction *emit_asm(ir_instruction *ir, enum tgsi_opcode op,
325 st_dst_reg dst, st_dst_reg dst1,
326 st_src_reg src0 = undef_src,
327 st_src_reg src1 = undef_src,
328 st_src_reg src2 = undef_src,
329 st_src_reg src3 = undef_src);
330
331 enum tgsi_opcode get_opcode(enum tgsi_opcode op,
332 st_dst_reg dst,
333 st_src_reg src0, st_src_reg src1);
334
335 /**
336 * Emit the correct dot-product instruction for the type of arguments
337 */
338 glsl_to_tgsi_instruction *emit_dp(ir_instruction *ir,
339 st_dst_reg dst,
340 st_src_reg src0,
341 st_src_reg src1,
342 unsigned elements);
343
344 void emit_scalar(ir_instruction *ir, enum tgsi_opcode op,
345 st_dst_reg dst, st_src_reg src0);
346
347 void emit_scalar(ir_instruction *ir, enum tgsi_opcode op,
348 st_dst_reg dst, st_src_reg src0, st_src_reg src1);
349
350 void emit_arl(ir_instruction *ir, st_dst_reg dst, st_src_reg src0);
351
352 void get_deref_offsets(ir_dereference *ir,
353 unsigned *array_size,
354 unsigned *base,
355 uint16_t *index,
356 st_src_reg *reladdr,
357 bool opaque);
358 void calc_deref_offsets(ir_dereference *tail,
359 unsigned *array_elements,
360 uint16_t *index,
361 st_src_reg *indirect,
362 unsigned *location);
363 st_src_reg canonicalize_gather_offset(st_src_reg offset);
364 bool handle_bound_deref(ir_dereference *ir);
365
366 bool try_emit_mad(ir_expression *ir,
367 int mul_operand);
368 bool try_emit_mad_for_and_not(ir_expression *ir,
369 int mul_operand);
370
371 void emit_swz(ir_expression *ir);
372
373 bool process_move_condition(ir_rvalue *ir);
374
375 void simplify_cmp(void);
376
377 void rename_temp_registers(struct rename_reg_pair *renames);
378 void get_first_temp_read(int *first_reads);
379 void get_first_temp_write(int *first_writes);
380 void get_last_temp_read_first_temp_write(int *last_reads, int *first_writes);
381 void get_last_temp_write(int *last_writes);
382
383 void copy_propagate(void);
384 int eliminate_dead_code(void);
385
386 void split_arrays(void);
387 void merge_two_dsts(void);
388 void merge_registers(void);
389 void renumber_registers(void);
390
391 void emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
392 st_dst_reg *l, st_src_reg *r,
393 st_src_reg *cond, bool cond_swap);
394
395 void print_stats();
396
397 void *mem_ctx;
398 };
399
400 static st_dst_reg address_reg = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X,
401 GLSL_TYPE_FLOAT, 0);
402 static st_dst_reg address_reg2 = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X,
403 GLSL_TYPE_FLOAT, 1);
404 static st_dst_reg sampler_reladdr = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X,
405 GLSL_TYPE_FLOAT, 2);
406
407 static void
408 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
409 PRINTFLIKE(2, 3);
410
411 static void
412 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
413 {
414 va_list args;
415 va_start(args, fmt);
416 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, args);
417 va_end(args);
418
419 prog->data->LinkStatus = LINKING_FAILURE;
420 }
421
422 int
423 swizzle_for_size(int size)
424 {
425 static const int size_swizzles[4] = {
426 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
427 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
428 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
429 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
430 };
431
432 assert((size >= 1) && (size <= 4));
433 return size_swizzles[size - 1];
434 }
435
436
437 glsl_to_tgsi_instruction *
438 glsl_to_tgsi_visitor::emit_asm(ir_instruction *ir, enum tgsi_opcode op,
439 st_dst_reg dst, st_dst_reg dst1,
440 st_src_reg src0, st_src_reg src1,
441 st_src_reg src2, st_src_reg src3)
442 {
443 glsl_to_tgsi_instruction *inst = new(mem_ctx) glsl_to_tgsi_instruction();
444 int num_reladdr = 0, i, j;
445 bool dst_is_64bit[2];
446
447 op = get_opcode(op, dst, src0, src1);
448
449 /* If we have to do relative addressing, we want to load the ARL
450 * reg directly for one of the regs, and preload the other reladdr
451 * sources into temps.
452 */
453 num_reladdr += dst.reladdr != NULL || dst.reladdr2;
454 assert(!dst1.reladdr); /* should be lowered in earlier passes */
455 num_reladdr += src0.reladdr != NULL || src0.reladdr2 != NULL;
456 num_reladdr += src1.reladdr != NULL || src1.reladdr2 != NULL;
457 num_reladdr += src2.reladdr != NULL || src2.reladdr2 != NULL;
458 num_reladdr += src3.reladdr != NULL || src3.reladdr2 != NULL;
459
460 reladdr_to_temp(ir, &src3, &num_reladdr);
461 reladdr_to_temp(ir, &src2, &num_reladdr);
462 reladdr_to_temp(ir, &src1, &num_reladdr);
463 reladdr_to_temp(ir, &src0, &num_reladdr);
464
465 if (dst.reladdr || dst.reladdr2) {
466 if (dst.reladdr)
467 emit_arl(ir, address_reg, *dst.reladdr);
468 if (dst.reladdr2)
469 emit_arl(ir, address_reg2, *dst.reladdr2);
470 num_reladdr--;
471 }
472
473 assert(num_reladdr == 0);
474
475 /* inst->op has only 8 bits. */
476 STATIC_ASSERT(TGSI_OPCODE_LAST <= 255);
477
478 inst->op = op;
479 inst->precise = this->precise;
480 inst->info = tgsi_get_opcode_info(op);
481 inst->dst[0] = dst;
482 inst->dst[1] = dst1;
483 inst->src[0] = src0;
484 inst->src[1] = src1;
485 inst->src[2] = src2;
486 inst->src[3] = src3;
487 inst->is_64bit_expanded = false;
488 inst->ir = ir;
489 inst->dead_mask = 0;
490 inst->tex_offsets = NULL;
491 inst->tex_offset_num_offset = 0;
492 inst->saturate = 0;
493 inst->tex_shadow = 0;
494 /* default to float, for paths where this is not initialized
495 * (since 0==UINT which is likely wrong):
496 */
497 inst->tex_type = GLSL_TYPE_FLOAT;
498
499 /* Update indirect addressing status used by TGSI */
500 if (dst.reladdr || dst.reladdr2) {
501 switch (dst.file) {
502 case PROGRAM_STATE_VAR:
503 case PROGRAM_CONSTANT:
504 case PROGRAM_UNIFORM:
505 this->indirect_addr_consts = true;
506 break;
507 case PROGRAM_IMMEDIATE:
508 assert(!"immediates should not have indirect addressing");
509 break;
510 default:
511 break;
512 }
513 }
514 else {
515 for (i = 0; i < 4; i++) {
516 if (inst->src[i].reladdr) {
517 switch (inst->src[i].file) {
518 case PROGRAM_STATE_VAR:
519 case PROGRAM_CONSTANT:
520 case PROGRAM_UNIFORM:
521 this->indirect_addr_consts = true;
522 break;
523 case PROGRAM_IMMEDIATE:
524 assert(!"immediates should not have indirect addressing");
525 break;
526 default:
527 break;
528 }
529 }
530 }
531 }
532
533 /*
534 * This section contains the double processing.
535 * GLSL just represents doubles as single channel values,
536 * however most HW and TGSI represent doubles as pairs of register channels.
537 *
538 * so we have to fixup destination writemask/index and src swizzle/indexes.
539 * dest writemasks need to translate from single channel write mask
540 * to a dual-channel writemask, but also need to modify the index,
541 * if we are touching the Z,W fields in the pre-translated writemask.
542 *
543 * src channels have similiar index modifications along with swizzle
544 * changes to we pick the XY, ZW pairs from the correct index.
545 *
546 * GLSL [0].x -> TGSI [0].xy
547 * GLSL [0].y -> TGSI [0].zw
548 * GLSL [0].z -> TGSI [1].xy
549 * GLSL [0].w -> TGSI [1].zw
550 */
551 for (j = 0; j < 2; j++) {
552 dst_is_64bit[j] = glsl_base_type_is_64bit(inst->dst[j].type);
553 if (!dst_is_64bit[j] && inst->dst[j].file == PROGRAM_OUTPUT &&
554 inst->dst[j].type == GLSL_TYPE_ARRAY) {
555 enum glsl_base_type type = find_array_type(this->outputs,
556 this->num_outputs,
557 inst->dst[j].array_id);
558 if (glsl_base_type_is_64bit(type))
559 dst_is_64bit[j] = true;
560 }
561 }
562
563 if (dst_is_64bit[0] || dst_is_64bit[1] ||
564 glsl_base_type_is_64bit(inst->src[0].type)) {
565 glsl_to_tgsi_instruction *dinst = NULL;
566 int initial_src_swz[4], initial_src_idx[4];
567 int initial_dst_idx[2], initial_dst_writemask[2];
568 /* select the writemask for dst0 or dst1 */
569 unsigned writemask = inst->dst[1].file == PROGRAM_UNDEFINED
570 ? inst->dst[0].writemask : inst->dst[1].writemask;
571
572 /* copy out the writemask, index and swizzles for all src/dsts. */
573 for (j = 0; j < 2; j++) {
574 initial_dst_writemask[j] = inst->dst[j].writemask;
575 initial_dst_idx[j] = inst->dst[j].index;
576 }
577
578 for (j = 0; j < 4; j++) {
579 initial_src_swz[j] = inst->src[j].swizzle;
580 initial_src_idx[j] = inst->src[j].index;
581 }
582
583 /*
584 * scan all the components in the dst writemask
585 * generate an instruction for each of them if required.
586 */
587 st_src_reg addr;
588 while (writemask) {
589
590 int i = u_bit_scan(&writemask);
591
592 /* before emitting the instruction, see if we have to adjust
593 * load / store address */
594 if (i > 1 && (inst->op == TGSI_OPCODE_LOAD ||
595 inst->op == TGSI_OPCODE_STORE) &&
596 addr.file == PROGRAM_UNDEFINED) {
597 /* We have to advance the buffer address by 16 */
598 addr = get_temp(glsl_type::uint_type);
599 emit_asm(ir, TGSI_OPCODE_UADD, st_dst_reg(addr),
600 inst->src[0], st_src_reg_for_int(16));
601 }
602
603 /* first time use previous instruction */
604 if (dinst == NULL) {
605 dinst = inst;
606 } else {
607 /* create a new instructions for subsequent attempts */
608 dinst = new(mem_ctx) glsl_to_tgsi_instruction();
609 *dinst = *inst;
610 dinst->next = NULL;
611 dinst->prev = NULL;
612 }
613 this->instructions.push_tail(dinst);
614 dinst->is_64bit_expanded = true;
615
616 /* modify the destination if we are splitting */
617 for (j = 0; j < 2; j++) {
618 if (dst_is_64bit[j]) {
619 dinst->dst[j].writemask = (i & 1) ? WRITEMASK_ZW : WRITEMASK_XY;
620 dinst->dst[j].index = initial_dst_idx[j];
621 if (i > 1) {
622 if (dinst->op == TGSI_OPCODE_LOAD ||
623 dinst->op == TGSI_OPCODE_STORE)
624 dinst->src[0] = addr;
625 if (dinst->op != TGSI_OPCODE_STORE)
626 dinst->dst[j].index++;
627 }
628 } else {
629 /* if we aren't writing to a double, just get the bit of the
630 * initial writemask for this channel
631 */
632 dinst->dst[j].writemask = initial_dst_writemask[j] & (1 << i);
633 }
634 }
635
636 /* modify the src registers */
637 for (j = 0; j < 4; j++) {
638 int swz = GET_SWZ(initial_src_swz[j], i);
639
640 if (glsl_base_type_is_64bit(dinst->src[j].type)) {
641 dinst->src[j].index = initial_src_idx[j];
642 if (swz > 1) {
643 dinst->src[j].double_reg2 = true;
644 dinst->src[j].index++;
645 }
646
647 if (swz & 1)
648 dinst->src[j].swizzle = MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W,
649 SWIZZLE_Z, SWIZZLE_W);
650 else
651 dinst->src[j].swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y,
652 SWIZZLE_X, SWIZZLE_Y);
653
654 } else {
655 /* some opcodes are special case in what they use as sources
656 * - [FUI]2D/[UI]2I64 is a float/[u]int src0, (D)LDEXP is
657 * integer src1
658 */
659 if (op == TGSI_OPCODE_F2D || op == TGSI_OPCODE_U2D ||
660 op == TGSI_OPCODE_I2D ||
661 op == TGSI_OPCODE_I2I64 || op == TGSI_OPCODE_U2I64 ||
662 op == TGSI_OPCODE_DLDEXP || op == TGSI_OPCODE_LDEXP ||
663 (op == TGSI_OPCODE_UCMP && dst_is_64bit[0])) {
664 dinst->src[j].swizzle = MAKE_SWIZZLE4(swz, swz, swz, swz);
665 }
666 }
667 }
668 }
669 inst = dinst;
670 } else {
671 this->instructions.push_tail(inst);
672 }
673
674
675 return inst;
676 }
677
678 glsl_to_tgsi_instruction *
679 glsl_to_tgsi_visitor::emit_asm(ir_instruction *ir, enum tgsi_opcode op,
680 st_dst_reg dst,
681 st_src_reg src0, st_src_reg src1,
682 st_src_reg src2, st_src_reg src3)
683 {
684 return emit_asm(ir, op, dst, undef_dst, src0, src1, src2, src3);
685 }
686
687 /**
688 * Determines whether to use an integer, unsigned integer, or float opcode
689 * based on the operands and input opcode, then emits the result.
690 */
691 enum tgsi_opcode
692 glsl_to_tgsi_visitor::get_opcode(enum tgsi_opcode op,
693 st_dst_reg dst,
694 st_src_reg src0, st_src_reg src1)
695 {
696 enum glsl_base_type type = GLSL_TYPE_FLOAT;
697
698 if (op == TGSI_OPCODE_MOV)
699 return op;
700
701 assert(src0.type != GLSL_TYPE_ARRAY);
702 assert(src0.type != GLSL_TYPE_STRUCT);
703 assert(src1.type != GLSL_TYPE_ARRAY);
704 assert(src1.type != GLSL_TYPE_STRUCT);
705
706 if (is_resource_instruction(op))
707 type = src1.type;
708 else if (src0.type == GLSL_TYPE_INT64 || src1.type == GLSL_TYPE_INT64)
709 type = GLSL_TYPE_INT64;
710 else if (src0.type == GLSL_TYPE_UINT64 || src1.type == GLSL_TYPE_UINT64)
711 type = GLSL_TYPE_UINT64;
712 else if (src0.type == GLSL_TYPE_DOUBLE || src1.type == GLSL_TYPE_DOUBLE)
713 type = GLSL_TYPE_DOUBLE;
714 else if (src0.type == GLSL_TYPE_FLOAT || src1.type == GLSL_TYPE_FLOAT)
715 type = GLSL_TYPE_FLOAT;
716 else if (native_integers)
717 type = src0.type == GLSL_TYPE_BOOL ? GLSL_TYPE_INT : src0.type;
718
719 #define case7(c, f, i, u, d, i64, ui64) \
720 case TGSI_OPCODE_##c: \
721 if (type == GLSL_TYPE_UINT64) \
722 op = TGSI_OPCODE_##ui64; \
723 else if (type == GLSL_TYPE_INT64) \
724 op = TGSI_OPCODE_##i64; \
725 else if (type == GLSL_TYPE_DOUBLE) \
726 op = TGSI_OPCODE_##d; \
727 else if (type == GLSL_TYPE_INT) \
728 op = TGSI_OPCODE_##i; \
729 else if (type == GLSL_TYPE_UINT) \
730 op = TGSI_OPCODE_##u; \
731 else \
732 op = TGSI_OPCODE_##f; \
733 break;
734
735 #define casecomp(c, f, i, u, d, i64, ui64) \
736 case TGSI_OPCODE_##c: \
737 if (type == GLSL_TYPE_INT64) \
738 op = TGSI_OPCODE_##i64; \
739 else if (type == GLSL_TYPE_UINT64) \
740 op = TGSI_OPCODE_##ui64; \
741 else if (type == GLSL_TYPE_DOUBLE) \
742 op = TGSI_OPCODE_##d; \
743 else if (type == GLSL_TYPE_INT || type == GLSL_TYPE_SUBROUTINE) \
744 op = TGSI_OPCODE_##i; \
745 else if (type == GLSL_TYPE_UINT) \
746 op = TGSI_OPCODE_##u; \
747 else if (native_integers) \
748 op = TGSI_OPCODE_##f; \
749 else \
750 op = TGSI_OPCODE_##c; \
751 break;
752
753 switch (op) {
754 /* Some instructions are initially selected without considering the type.
755 * This fixes the type:
756 *
757 * INIT FLOAT SINT UINT DOUBLE SINT64 UINT64
758 */
759 case7(ADD, ADD, UADD, UADD, DADD, U64ADD, U64ADD);
760 case7(CEIL, CEIL, LAST, LAST, DCEIL, LAST, LAST);
761 case7(DIV, DIV, IDIV, UDIV, DDIV, I64DIV, U64DIV);
762 case7(FMA, FMA, UMAD, UMAD, DFMA, LAST, LAST);
763 case7(FLR, FLR, LAST, LAST, DFLR, LAST, LAST);
764 case7(FRC, FRC, LAST, LAST, DFRAC, LAST, LAST);
765 case7(MUL, MUL, UMUL, UMUL, DMUL, U64MUL, U64MUL);
766 case7(MAD, MAD, UMAD, UMAD, DMAD, LAST, LAST);
767 case7(MAX, MAX, IMAX, UMAX, DMAX, I64MAX, U64MAX);
768 case7(MIN, MIN, IMIN, UMIN, DMIN, I64MIN, U64MIN);
769 case7(RCP, RCP, LAST, LAST, DRCP, LAST, LAST);
770 case7(ROUND, ROUND,LAST, LAST, DROUND, LAST, LAST);
771 case7(RSQ, RSQ, LAST, LAST, DRSQ, LAST, LAST);
772 case7(SQRT, SQRT, LAST, LAST, DSQRT, LAST, LAST);
773 case7(SSG, SSG, ISSG, ISSG, DSSG, I64SSG, I64SSG);
774 case7(TRUNC, TRUNC,LAST, LAST, DTRUNC, LAST, LAST);
775
776 case7(MOD, LAST, MOD, UMOD, LAST, I64MOD, U64MOD);
777 case7(SHL, LAST, SHL, SHL, LAST, U64SHL, U64SHL);
778 case7(IBFE, LAST, IBFE, UBFE, LAST, LAST, LAST);
779 case7(IMSB, LAST, IMSB, UMSB, LAST, LAST, LAST);
780 case7(IMUL_HI, LAST, IMUL_HI, UMUL_HI, LAST, LAST, LAST);
781 case7(ISHR, LAST, ISHR, USHR, LAST, I64SHR, U64SHR);
782 case7(ATOMIMAX,LAST, ATOMIMAX,ATOMUMAX,LAST, LAST, LAST);
783 case7(ATOMIMIN,LAST, ATOMIMIN,ATOMUMIN,LAST, LAST, LAST);
784
785 casecomp(SEQ, FSEQ, USEQ, USEQ, DSEQ, U64SEQ, U64SEQ);
786 casecomp(SNE, FSNE, USNE, USNE, DSNE, U64SNE, U64SNE);
787 casecomp(SGE, FSGE, ISGE, USGE, DSGE, I64SGE, U64SGE);
788 casecomp(SLT, FSLT, ISLT, USLT, DSLT, I64SLT, U64SLT);
789
790 default:
791 break;
792 }
793
794 assert(op != TGSI_OPCODE_LAST);
795 return op;
796 }
797
798 glsl_to_tgsi_instruction *
799 glsl_to_tgsi_visitor::emit_dp(ir_instruction *ir,
800 st_dst_reg dst, st_src_reg src0, st_src_reg src1,
801 unsigned elements)
802 {
803 static const enum tgsi_opcode dot_opcodes[] = {
804 TGSI_OPCODE_DP2, TGSI_OPCODE_DP3, TGSI_OPCODE_DP4
805 };
806
807 return emit_asm(ir, dot_opcodes[elements - 2], dst, src0, src1);
808 }
809
810 /**
811 * Emits TGSI scalar opcodes to produce unique answers across channels.
812 *
813 * Some TGSI opcodes are scalar-only, like ARB_fp/vp. The src X
814 * channel determines the result across all channels. So to do a vec4
815 * of this operation, we want to emit a scalar per source channel used
816 * to produce dest channels.
817 */
818 void
819 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, enum tgsi_opcode op,
820 st_dst_reg dst,
821 st_src_reg orig_src0, st_src_reg orig_src1)
822 {
823 int i, j;
824 int done_mask = ~dst.writemask;
825
826 /* TGSI RCP is a scalar operation splatting results to all channels,
827 * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
828 * dst channels.
829 */
830 for (i = 0; i < 4; i++) {
831 GLuint this_mask = (1 << i);
832 st_src_reg src0 = orig_src0;
833 st_src_reg src1 = orig_src1;
834
835 if (done_mask & this_mask)
836 continue;
837
838 GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
839 GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
840 for (j = i + 1; j < 4; j++) {
841 /* If there is another enabled component in the destination that is
842 * derived from the same inputs, generate its value on this pass as
843 * well.
844 */
845 if (!(done_mask & (1 << j)) &&
846 GET_SWZ(src0.swizzle, j) == src0_swiz &&
847 GET_SWZ(src1.swizzle, j) == src1_swiz) {
848 this_mask |= (1 << j);
849 }
850 }
851 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
852 src0_swiz, src0_swiz);
853 src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
854 src1_swiz, src1_swiz);
855
856 dst.writemask = this_mask;
857 emit_asm(ir, op, dst, src0, src1);
858 done_mask |= this_mask;
859 }
860 }
861
862 void
863 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, enum tgsi_opcode op,
864 st_dst_reg dst, st_src_reg src0)
865 {
866 st_src_reg undef = undef_src;
867
868 undef.swizzle = SWIZZLE_XXXX;
869
870 emit_scalar(ir, op, dst, src0, undef);
871 }
872
873 void
874 glsl_to_tgsi_visitor::emit_arl(ir_instruction *ir,
875 st_dst_reg dst, st_src_reg src0)
876 {
877 enum tgsi_opcode op = TGSI_OPCODE_ARL;
878
879 if (src0.type == GLSL_TYPE_INT || src0.type == GLSL_TYPE_UINT) {
880 if (!this->need_uarl && src0.is_legal_tgsi_address_operand())
881 return;
882
883 op = TGSI_OPCODE_UARL;
884 }
885
886 assert(dst.file == PROGRAM_ADDRESS);
887 if (dst.index >= this->num_address_regs)
888 this->num_address_regs = dst.index + 1;
889
890 emit_asm(NULL, op, dst, src0);
891 }
892
893 int
894 glsl_to_tgsi_visitor::add_constant(gl_register_file file,
895 gl_constant_value values[8], int size,
896 GLenum datatype,
897 uint16_t *swizzle_out)
898 {
899 if (file == PROGRAM_CONSTANT) {
900 GLuint swizzle = swizzle_out ? *swizzle_out : 0;
901 int result = _mesa_add_typed_unnamed_constant(this->prog->Parameters,
902 values, size, datatype,
903 &swizzle);
904 if (swizzle_out)
905 *swizzle_out = swizzle;
906 return result;
907 }
908
909 assert(file == PROGRAM_IMMEDIATE);
910
911 int index = 0;
912 immediate_storage *entry;
913 int size32 = size * ((datatype == GL_DOUBLE ||
914 datatype == GL_INT64_ARB ||
915 datatype == GL_UNSIGNED_INT64_ARB) ? 2 : 1);
916 int i;
917
918 /* Search immediate storage to see if we already have an identical
919 * immediate that we can use instead of adding a duplicate entry.
920 */
921 foreach_in_list(immediate_storage, entry, &this->immediates) {
922 immediate_storage *tmp = entry;
923
924 for (i = 0; i * 4 < size32; i++) {
925 int slot_size = MIN2(size32 - (i * 4), 4);
926 if (tmp->type != datatype || tmp->size32 != slot_size)
927 break;
928 if (memcmp(tmp->values, &values[i * 4],
929 slot_size * sizeof(gl_constant_value)))
930 break;
931
932 /* Everything matches, keep going until the full size is matched */
933 tmp = (immediate_storage *)tmp->next;
934 }
935
936 /* The full value matched */
937 if (i * 4 >= size32)
938 return index;
939
940 index++;
941 }
942
943 for (i = 0; i * 4 < size32; i++) {
944 int slot_size = MIN2(size32 - (i * 4), 4);
945 /* Add this immediate to the list. */
946 entry = new(mem_ctx) immediate_storage(&values[i * 4],
947 slot_size, datatype);
948 this->immediates.push_tail(entry);
949 this->num_immediates++;
950 }
951 return index;
952 }
953
954 st_src_reg
955 glsl_to_tgsi_visitor::st_src_reg_for_float(float val)
956 {
957 st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_FLOAT);
958 union gl_constant_value uval;
959
960 uval.f = val;
961 src.index = add_constant(src.file, &uval, 1, GL_FLOAT, &src.swizzle);
962
963 return src;
964 }
965
966 st_src_reg
967 glsl_to_tgsi_visitor::st_src_reg_for_double(double val)
968 {
969 st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_DOUBLE);
970 union gl_constant_value uval[2];
971
972 memcpy(uval, &val, sizeof(uval));
973 src.index = add_constant(src.file, uval, 1, GL_DOUBLE, &src.swizzle);
974 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
975 return src;
976 }
977
978 st_src_reg
979 glsl_to_tgsi_visitor::st_src_reg_for_int(int val)
980 {
981 st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_INT);
982 union gl_constant_value uval;
983
984 assert(native_integers);
985
986 uval.i = val;
987 src.index = add_constant(src.file, &uval, 1, GL_INT, &src.swizzle);
988
989 return src;
990 }
991
992 st_src_reg
993 glsl_to_tgsi_visitor::st_src_reg_for_int64(int64_t val)
994 {
995 st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_INT64);
996 union gl_constant_value uval[2];
997
998 memcpy(uval, &val, sizeof(uval));
999 src.index = add_constant(src.file, uval, 1, GL_DOUBLE, &src.swizzle);
1000 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
1001
1002 return src;
1003 }
1004
1005 st_src_reg
1006 glsl_to_tgsi_visitor::st_src_reg_for_type(enum glsl_base_type type, int val)
1007 {
1008 if (native_integers)
1009 return type == GLSL_TYPE_FLOAT ? st_src_reg_for_float(val) :
1010 st_src_reg_for_int(val);
1011 else
1012 return st_src_reg_for_float(val);
1013 }
1014
1015 static int
1016 attrib_type_size(const struct glsl_type *type, bool is_vs_input)
1017 {
1018 return type->count_attribute_slots(is_vs_input);
1019 }
1020
1021 static int
1022 type_size(const struct glsl_type *type)
1023 {
1024 return type->count_attribute_slots(false);
1025 }
1026
1027 static void
1028 add_buffer_to_load_and_stores(glsl_to_tgsi_instruction *inst, st_src_reg *buf,
1029 exec_list *instructions, ir_constant *access)
1030 {
1031 /**
1032 * emit_asm() might have actually split the op into pieces, e.g. for
1033 * double stores. We have to go back and fix up all the generated ops.
1034 */
1035 enum tgsi_opcode op = inst->op;
1036 do {
1037 inst->resource = *buf;
1038 if (access)
1039 inst->buffer_access = access->value.u[0];
1040
1041 if (inst == instructions->get_head_raw())
1042 break;
1043 inst = (glsl_to_tgsi_instruction *)inst->get_prev();
1044
1045 if (inst->op == TGSI_OPCODE_UADD) {
1046 if (inst == instructions->get_head_raw())
1047 break;
1048 inst = (glsl_to_tgsi_instruction *)inst->get_prev();
1049 }
1050 } while (inst->op == op && inst->resource.file == PROGRAM_UNDEFINED);
1051 }
1052
1053 /**
1054 * If the given GLSL type is an array or matrix or a structure containing
1055 * an array/matrix member, return true. Else return false.
1056 *
1057 * This is used to determine which kind of temp storage (PROGRAM_TEMPORARY
1058 * or PROGRAM_ARRAY) should be used for variables of this type. Anytime
1059 * we have an array that might be indexed with a variable, we need to use
1060 * the later storage type.
1061 */
1062 static bool
1063 type_has_array_or_matrix(const glsl_type *type)
1064 {
1065 if (type->is_array() || type->is_matrix())
1066 return true;
1067
1068 if (type->is_record()) {
1069 for (unsigned i = 0; i < type->length; i++) {
1070 if (type_has_array_or_matrix(type->fields.structure[i].type)) {
1071 return true;
1072 }
1073 }
1074 }
1075
1076 return false;
1077 }
1078
1079
1080 /**
1081 * In the initial pass of codegen, we assign temporary numbers to
1082 * intermediate results. (not SSA -- variable assignments will reuse
1083 * storage).
1084 */
1085 st_src_reg
1086 glsl_to_tgsi_visitor::get_temp(const glsl_type *type)
1087 {
1088 st_src_reg src;
1089
1090 src.type = native_integers ? type->base_type : GLSL_TYPE_FLOAT;
1091 src.reladdr = NULL;
1092 src.negate = 0;
1093 src.abs = 0;
1094
1095 if (!options->EmitNoIndirectTemp && type_has_array_or_matrix(type)) {
1096 if (next_array >= max_num_arrays) {
1097 max_num_arrays += 32;
1098 array_sizes = (unsigned*)
1099 realloc(array_sizes, sizeof(array_sizes[0]) * max_num_arrays);
1100 }
1101
1102 src.file = PROGRAM_ARRAY;
1103 src.index = 0;
1104 src.array_id = next_array + 1;
1105 array_sizes[next_array] = type_size(type);
1106 ++next_array;
1107
1108 } else {
1109 src.file = PROGRAM_TEMPORARY;
1110 src.index = next_temp;
1111 next_temp += type_size(type);
1112 }
1113
1114 if (type->is_array() || type->is_record()) {
1115 src.swizzle = SWIZZLE_NOOP;
1116 } else {
1117 src.swizzle = swizzle_for_size(type->vector_elements);
1118 }
1119
1120 return src;
1121 }
1122
1123 variable_storage *
1124 glsl_to_tgsi_visitor::find_variable_storage(ir_variable *var)
1125 {
1126 struct hash_entry *entry;
1127
1128 entry = _mesa_hash_table_search(this->variables, var);
1129 if (!entry)
1130 return NULL;
1131
1132 return (variable_storage *)entry->data;
1133 }
1134
1135 void
1136 glsl_to_tgsi_visitor::visit(ir_variable *ir)
1137 {
1138 if (strcmp(ir->name, "gl_FragCoord") == 0) {
1139 this->prog->OriginUpperLeft = ir->data.origin_upper_left;
1140 this->prog->PixelCenterInteger = ir->data.pixel_center_integer;
1141 }
1142
1143 if (ir->data.mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
1144 unsigned int i;
1145 const ir_state_slot *const slots = ir->get_state_slots();
1146 assert(slots != NULL);
1147
1148 /* Check if this statevar's setup in the STATE file exactly
1149 * matches how we'll want to reference it as a
1150 * struct/array/whatever. If not, then we need to move it into
1151 * temporary storage and hope that it'll get copy-propagated
1152 * out.
1153 */
1154 for (i = 0; i < ir->get_num_state_slots(); i++) {
1155 if (slots[i].swizzle != SWIZZLE_XYZW) {
1156 break;
1157 }
1158 }
1159
1160 variable_storage *storage;
1161 st_dst_reg dst;
1162 if (i == ir->get_num_state_slots()) {
1163 /* We'll set the index later. */
1164 storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
1165
1166 _mesa_hash_table_insert(this->variables, ir, storage);
1167
1168 dst = undef_dst;
1169 } else {
1170 /* The variable_storage constructor allocates slots based on the size
1171 * of the type. However, this had better match the number of state
1172 * elements that we're going to copy into the new temporary.
1173 */
1174 assert((int) ir->get_num_state_slots() == type_size(ir->type));
1175
1176 dst = st_dst_reg(get_temp(ir->type));
1177
1178 storage = new(mem_ctx) variable_storage(ir, dst.file, dst.index,
1179 dst.array_id);
1180
1181 _mesa_hash_table_insert(this->variables, ir, storage);
1182 }
1183
1184
1185 for (unsigned int i = 0; i < ir->get_num_state_slots(); i++) {
1186 int index = _mesa_add_state_reference(this->prog->Parameters,
1187 slots[i].tokens);
1188
1189 if (storage->file == PROGRAM_STATE_VAR) {
1190 if (storage->index == -1) {
1191 storage->index = index;
1192 } else {
1193 assert(index == storage->index + (int)i);
1194 }
1195 } else {
1196 /* We use GLSL_TYPE_FLOAT here regardless of the actual type of
1197 * the data being moved since MOV does not care about the type of
1198 * data it is moving, and we don't want to declare registers with
1199 * array or struct types.
1200 */
1201 st_src_reg src(PROGRAM_STATE_VAR, index, GLSL_TYPE_FLOAT);
1202 src.swizzle = slots[i].swizzle;
1203 emit_asm(ir, TGSI_OPCODE_MOV, dst, src);
1204 /* even a float takes up a whole vec4 reg in a struct/array. */
1205 dst.index++;
1206 }
1207 }
1208
1209 if (storage->file == PROGRAM_TEMPORARY &&
1210 dst.index != storage->index + (int) ir->get_num_state_slots()) {
1211 fail_link(this->shader_program,
1212 "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
1213 ir->name, dst.index - storage->index,
1214 type_size(ir->type));
1215 }
1216 }
1217 }
1218
1219 void
1220 glsl_to_tgsi_visitor::visit(ir_loop *ir)
1221 {
1222 emit_asm(NULL, TGSI_OPCODE_BGNLOOP);
1223
1224 visit_exec_list(&ir->body_instructions, this);
1225
1226 emit_asm(NULL, TGSI_OPCODE_ENDLOOP);
1227 }
1228
1229 void
1230 glsl_to_tgsi_visitor::visit(ir_loop_jump *ir)
1231 {
1232 switch (ir->mode) {
1233 case ir_loop_jump::jump_break:
1234 emit_asm(NULL, TGSI_OPCODE_BRK);
1235 break;
1236 case ir_loop_jump::jump_continue:
1237 emit_asm(NULL, TGSI_OPCODE_CONT);
1238 break;
1239 }
1240 }
1241
1242
1243 void
1244 glsl_to_tgsi_visitor::visit(ir_function_signature *ir)
1245 {
1246 assert(0);
1247 (void)ir;
1248 }
1249
1250 void
1251 glsl_to_tgsi_visitor::visit(ir_function *ir)
1252 {
1253 /* Ignore function bodies other than main() -- we shouldn't see calls to
1254 * them since they should all be inlined before we get to glsl_to_tgsi.
1255 */
1256 if (strcmp(ir->name, "main") == 0) {
1257 const ir_function_signature *sig;
1258 exec_list empty;
1259
1260 sig = ir->matching_signature(NULL, &empty, false);
1261
1262 assert(sig);
1263
1264 foreach_in_list(ir_instruction, ir, &sig->body) {
1265 ir->accept(this);
1266 }
1267 }
1268 }
1269
1270 bool
1271 glsl_to_tgsi_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
1272 {
1273 int nonmul_operand = 1 - mul_operand;
1274 st_src_reg a, b, c;
1275 st_dst_reg result_dst;
1276
1277 // there is no TGSI opcode for this
1278 if (ir->type->is_integer_64())
1279 return false;
1280
1281 ir_expression *expr = ir->operands[mul_operand]->as_expression();
1282 if (!expr || expr->operation != ir_binop_mul)
1283 return false;
1284
1285 expr->operands[0]->accept(this);
1286 a = this->result;
1287 expr->operands[1]->accept(this);
1288 b = this->result;
1289 ir->operands[nonmul_operand]->accept(this);
1290 c = this->result;
1291
1292 this->result = get_temp(ir->type);
1293 result_dst = st_dst_reg(this->result);
1294 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1295 emit_asm(ir, TGSI_OPCODE_MAD, result_dst, a, b, c);
1296
1297 return true;
1298 }
1299
1300 /**
1301 * Emit MAD(a, -b, a) instead of AND(a, NOT(b))
1302 *
1303 * The logic values are 1.0 for true and 0.0 for false. Logical-and is
1304 * implemented using multiplication, and logical-or is implemented using
1305 * addition. Logical-not can be implemented as (true - x), or (1.0 - x).
1306 * As result, the logical expression (a & !b) can be rewritten as:
1307 *
1308 * - a * !b
1309 * - a * (1 - b)
1310 * - (a * 1) - (a * b)
1311 * - a + -(a * b)
1312 * - a + (a * -b)
1313 *
1314 * This final expression can be implemented as a single MAD(a, -b, a)
1315 * instruction.
1316 */
1317 bool
1318 glsl_to_tgsi_visitor::try_emit_mad_for_and_not(ir_expression *ir,
1319 int try_operand)
1320 {
1321 const int other_operand = 1 - try_operand;
1322 st_src_reg a, b;
1323
1324 ir_expression *expr = ir->operands[try_operand]->as_expression();
1325 if (!expr || expr->operation != ir_unop_logic_not)
1326 return false;
1327
1328 ir->operands[other_operand]->accept(this);
1329 a = this->result;
1330 expr->operands[0]->accept(this);
1331 b = this->result;
1332
1333 b.negate = ~b.negate;
1334
1335 this->result = get_temp(ir->type);
1336 emit_asm(ir, TGSI_OPCODE_MAD, st_dst_reg(this->result), a, b, a);
1337
1338 return true;
1339 }
1340
1341 void
1342 glsl_to_tgsi_visitor::reladdr_to_temp(ir_instruction *ir,
1343 st_src_reg *reg, int *num_reladdr)
1344 {
1345 if (!reg->reladdr && !reg->reladdr2)
1346 return;
1347
1348 if (reg->reladdr)
1349 emit_arl(ir, address_reg, *reg->reladdr);
1350 if (reg->reladdr2)
1351 emit_arl(ir, address_reg2, *reg->reladdr2);
1352
1353 if (*num_reladdr != 1) {
1354 st_src_reg temp = get_temp(glsl_type::get_instance(reg->type, 4, 1));
1355
1356 emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), *reg);
1357 *reg = temp;
1358 }
1359
1360 (*num_reladdr)--;
1361 }
1362
1363 void
1364 glsl_to_tgsi_visitor::visit(ir_expression *ir)
1365 {
1366 st_src_reg op[ARRAY_SIZE(ir->operands)];
1367
1368 /* Quick peephole: Emit MAD(a, b, c) instead of ADD(MUL(a, b), c)
1369 */
1370 if (!this->precise && ir->operation == ir_binop_add) {
1371 if (try_emit_mad(ir, 1))
1372 return;
1373 if (try_emit_mad(ir, 0))
1374 return;
1375 }
1376
1377 /* Quick peephole: Emit OPCODE_MAD(-a, -b, a) instead of AND(a, NOT(b))
1378 */
1379 if (!native_integers && ir->operation == ir_binop_logic_and) {
1380 if (try_emit_mad_for_and_not(ir, 1))
1381 return;
1382 if (try_emit_mad_for_and_not(ir, 0))
1383 return;
1384 }
1385
1386 if (ir->operation == ir_quadop_vector)
1387 assert(!"ir_quadop_vector should have been lowered");
1388
1389 for (unsigned int operand = 0; operand < ir->num_operands; operand++) {
1390 this->result.file = PROGRAM_UNDEFINED;
1391 ir->operands[operand]->accept(this);
1392 if (this->result.file == PROGRAM_UNDEFINED) {
1393 printf("Failed to get tree for expression operand:\n");
1394 ir->operands[operand]->print();
1395 printf("\n");
1396 exit(1);
1397 }
1398 op[operand] = this->result;
1399
1400 /* Matrix expression operands should have been broken down to vector
1401 * operations already.
1402 */
1403 assert(!ir->operands[operand]->type->is_matrix());
1404 }
1405
1406 visit_expression(ir, op);
1407 }
1408
1409 /* The non-recursive part of the expression visitor lives in a separate
1410 * function and should be prevented from being inlined, to avoid a stack
1411 * explosion when deeply nested expressions are visited.
1412 */
1413 void
1414 glsl_to_tgsi_visitor::visit_expression(ir_expression* ir, st_src_reg *op)
1415 {
1416 st_src_reg result_src;
1417 st_dst_reg result_dst;
1418
1419 int vector_elements = ir->operands[0]->type->vector_elements;
1420 if (ir->operands[1] &&
1421 ir->operation != ir_binop_interpolate_at_offset &&
1422 ir->operation != ir_binop_interpolate_at_sample) {
1423 st_src_reg *swz_op = NULL;
1424 if (vector_elements > ir->operands[1]->type->vector_elements) {
1425 assert(ir->operands[1]->type->vector_elements == 1);
1426 swz_op = &op[1];
1427 } else if (vector_elements < ir->operands[1]->type->vector_elements) {
1428 assert(ir->operands[0]->type->vector_elements == 1);
1429 swz_op = &op[0];
1430 }
1431 if (swz_op) {
1432 uint16_t swizzle_x = GET_SWZ(swz_op->swizzle, 0);
1433 swz_op->swizzle = MAKE_SWIZZLE4(swizzle_x, swizzle_x,
1434 swizzle_x, swizzle_x);
1435 }
1436 vector_elements = MAX2(vector_elements,
1437 ir->operands[1]->type->vector_elements);
1438 }
1439 if (ir->operands[2] &&
1440 ir->operands[2]->type->vector_elements != vector_elements) {
1441 /* This can happen with ir_triop_lrp, i.e. glsl mix */
1442 assert(ir->operands[2]->type->vector_elements == 1);
1443 uint16_t swizzle_x = GET_SWZ(op[2].swizzle, 0);
1444 op[2].swizzle = MAKE_SWIZZLE4(swizzle_x, swizzle_x,
1445 swizzle_x, swizzle_x);
1446 }
1447
1448 this->result.file = PROGRAM_UNDEFINED;
1449
1450 /* Storage for our result. Ideally for an assignment we'd be using
1451 * the actual storage for the result here, instead.
1452 */
1453 result_src = get_temp(ir->type);
1454 /* convenience for the emit functions below. */
1455 result_dst = st_dst_reg(result_src);
1456 /* Limit writes to the channels that will be used by result_src later.
1457 * This does limit this temp's use as a temporary for multi-instruction
1458 * sequences.
1459 */
1460 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1461
1462 switch (ir->operation) {
1463 case ir_unop_logic_not:
1464 if (result_dst.type != GLSL_TYPE_FLOAT)
1465 emit_asm(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1466 else {
1467 /* Previously 'SEQ dst, src, 0.0' was used for this. However, many
1468 * older GPUs implement SEQ using multiple instructions (i915 uses two
1469 * SGE instructions and a MUL instruction). Since our logic values are
1470 * 0.0 and 1.0, 1-x also implements !x.
1471 */
1472 op[0].negate = ~op[0].negate;
1473 emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0],
1474 st_src_reg_for_float(1.0));
1475 }
1476 break;
1477 case ir_unop_neg:
1478 if (result_dst.type == GLSL_TYPE_INT64 ||
1479 result_dst.type == GLSL_TYPE_UINT64)
1480 emit_asm(ir, TGSI_OPCODE_I64NEG, result_dst, op[0]);
1481 else if (result_dst.type == GLSL_TYPE_INT ||
1482 result_dst.type == GLSL_TYPE_UINT)
1483 emit_asm(ir, TGSI_OPCODE_INEG, result_dst, op[0]);
1484 else if (result_dst.type == GLSL_TYPE_DOUBLE)
1485 emit_asm(ir, TGSI_OPCODE_DNEG, result_dst, op[0]);
1486 else {
1487 op[0].negate = ~op[0].negate;
1488 result_src = op[0];
1489 }
1490 break;
1491 case ir_unop_subroutine_to_int:
1492 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1493 break;
1494 case ir_unop_abs:
1495 if (result_dst.type == GLSL_TYPE_FLOAT)
1496 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0].get_abs());
1497 else if (result_dst.type == GLSL_TYPE_DOUBLE)
1498 emit_asm(ir, TGSI_OPCODE_DABS, result_dst, op[0]);
1499 else if (result_dst.type == GLSL_TYPE_INT64 ||
1500 result_dst.type == GLSL_TYPE_UINT64)
1501 emit_asm(ir, TGSI_OPCODE_I64ABS, result_dst, op[0]);
1502 else
1503 emit_asm(ir, TGSI_OPCODE_IABS, result_dst, op[0]);
1504 break;
1505 case ir_unop_sign:
1506 emit_asm(ir, TGSI_OPCODE_SSG, result_dst, op[0]);
1507 break;
1508 case ir_unop_rcp:
1509 emit_scalar(ir, TGSI_OPCODE_RCP, result_dst, op[0]);
1510 break;
1511
1512 case ir_unop_exp2:
1513 emit_scalar(ir, TGSI_OPCODE_EX2, result_dst, op[0]);
1514 break;
1515 case ir_unop_exp:
1516 assert(!"not reached: should be handled by exp_to_exp2");
1517 break;
1518 case ir_unop_log:
1519 assert(!"not reached: should be handled by log_to_log2");
1520 break;
1521 case ir_unop_log2:
1522 emit_scalar(ir, TGSI_OPCODE_LG2, result_dst, op[0]);
1523 break;
1524 case ir_unop_sin:
1525 emit_scalar(ir, TGSI_OPCODE_SIN, result_dst, op[0]);
1526 break;
1527 case ir_unop_cos:
1528 emit_scalar(ir, TGSI_OPCODE_COS, result_dst, op[0]);
1529 break;
1530 case ir_unop_saturate: {
1531 glsl_to_tgsi_instruction *inst;
1532 inst = emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1533 inst->saturate = true;
1534 break;
1535 }
1536
1537 case ir_unop_dFdx:
1538 case ir_unop_dFdx_coarse:
1539 emit_asm(ir, TGSI_OPCODE_DDX, result_dst, op[0]);
1540 break;
1541 case ir_unop_dFdx_fine:
1542 emit_asm(ir, TGSI_OPCODE_DDX_FINE, result_dst, op[0]);
1543 break;
1544 case ir_unop_dFdy:
1545 case ir_unop_dFdy_coarse:
1546 case ir_unop_dFdy_fine:
1547 {
1548 /* The X component contains 1 or -1 depending on whether the framebuffer
1549 * is a FBO or the window system buffer, respectively.
1550 * It is then multiplied with the source operand of DDY.
1551 */
1552 static const gl_state_index16 transform_y_state[STATE_LENGTH]
1553 = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM };
1554
1555 unsigned transform_y_index =
1556 _mesa_add_state_reference(this->prog->Parameters,
1557 transform_y_state);
1558
1559 st_src_reg transform_y = st_src_reg(PROGRAM_STATE_VAR,
1560 transform_y_index,
1561 glsl_type::vec4_type);
1562 transform_y.swizzle = SWIZZLE_XXXX;
1563
1564 st_src_reg temp = get_temp(glsl_type::vec4_type);
1565
1566 emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(temp), transform_y, op[0]);
1567 emit_asm(ir, ir->operation == ir_unop_dFdy_fine ?
1568 TGSI_OPCODE_DDY_FINE : TGSI_OPCODE_DDY, result_dst, temp);
1569 break;
1570 }
1571
1572 case ir_unop_frexp_sig:
1573 emit_asm(ir, TGSI_OPCODE_DFRACEXP, result_dst, undef_dst, op[0]);
1574 break;
1575
1576 case ir_unop_frexp_exp:
1577 emit_asm(ir, TGSI_OPCODE_DFRACEXP, undef_dst, result_dst, op[0]);
1578 break;
1579
1580 case ir_unop_noise: {
1581 /* At some point, a motivated person could add a better
1582 * implementation of noise. Currently not even the nvidia
1583 * binary drivers do anything more than this. In any case, the
1584 * place to do this is in the GL state tracker, not the poor
1585 * driver.
1586 */
1587 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, st_src_reg_for_float(0.5));
1588 break;
1589 }
1590
1591 case ir_binop_add:
1592 emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1593 break;
1594 case ir_binop_sub:
1595 op[1].negate = ~op[1].negate;
1596 emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1597 break;
1598
1599 case ir_binop_mul:
1600 emit_asm(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1601 break;
1602 case ir_binop_div:
1603 emit_asm(ir, TGSI_OPCODE_DIV, result_dst, op[0], op[1]);
1604 break;
1605 case ir_binop_mod:
1606 if (result_dst.type == GLSL_TYPE_FLOAT)
1607 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1608 else
1609 emit_asm(ir, TGSI_OPCODE_MOD, result_dst, op[0], op[1]);
1610 break;
1611
1612 case ir_binop_less:
1613 emit_asm(ir, TGSI_OPCODE_SLT, result_dst, op[0], op[1]);
1614 break;
1615 case ir_binop_gequal:
1616 emit_asm(ir, TGSI_OPCODE_SGE, result_dst, op[0], op[1]);
1617 break;
1618 case ir_binop_equal:
1619 emit_asm(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1620 break;
1621 case ir_binop_nequal:
1622 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1623 break;
1624 case ir_binop_all_equal:
1625 /* "==" operator producing a scalar boolean. */
1626 if (ir->operands[0]->type->is_vector() ||
1627 ir->operands[1]->type->is_vector()) {
1628 st_src_reg temp = get_temp(native_integers ?
1629 glsl_type::uvec4_type :
1630 glsl_type::vec4_type);
1631
1632 if (native_integers) {
1633 st_dst_reg temp_dst = st_dst_reg(temp);
1634 st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1635
1636 if (ir->operands[0]->type->is_boolean() &&
1637 ir->operands[1]->as_constant() &&
1638 ir->operands[1]->as_constant()->is_one()) {
1639 emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), op[0]);
1640 } else {
1641 emit_asm(ir, TGSI_OPCODE_SEQ, st_dst_reg(temp), op[0], op[1]);
1642 }
1643
1644 /* Emit 1-3 AND operations to combine the SEQ results. */
1645 switch (ir->operands[0]->type->vector_elements) {
1646 case 2:
1647 break;
1648 case 3:
1649 temp_dst.writemask = WRITEMASK_Y;
1650 temp1.swizzle = SWIZZLE_YYYY;
1651 temp2.swizzle = SWIZZLE_ZZZZ;
1652 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1653 break;
1654 case 4:
1655 temp_dst.writemask = WRITEMASK_X;
1656 temp1.swizzle = SWIZZLE_XXXX;
1657 temp2.swizzle = SWIZZLE_YYYY;
1658 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1659 temp_dst.writemask = WRITEMASK_Y;
1660 temp1.swizzle = SWIZZLE_ZZZZ;
1661 temp2.swizzle = SWIZZLE_WWWW;
1662 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1663 }
1664
1665 temp1.swizzle = SWIZZLE_XXXX;
1666 temp2.swizzle = SWIZZLE_YYYY;
1667 emit_asm(ir, TGSI_OPCODE_AND, result_dst, temp1, temp2);
1668 } else {
1669 emit_asm(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1670
1671 /* After the dot-product, the value will be an integer on the
1672 * range [0,4]. Zero becomes 1.0, and positive values become zero.
1673 */
1674 emit_dp(ir, result_dst, temp, temp, vector_elements);
1675
1676 /* Negating the result of the dot-product gives values on the range
1677 * [-4, 0]. Zero becomes 1.0, and negative values become zero.
1678 * This is achieved using SGE.
1679 */
1680 st_src_reg sge_src = result_src;
1681 sge_src.negate = ~sge_src.negate;
1682 emit_asm(ir, TGSI_OPCODE_SGE, result_dst, sge_src,
1683 st_src_reg_for_float(0.0));
1684 }
1685 } else {
1686 emit_asm(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1687 }
1688 break;
1689 case ir_binop_any_nequal:
1690 /* "!=" operator producing a scalar boolean. */
1691 if (ir->operands[0]->type->is_vector() ||
1692 ir->operands[1]->type->is_vector()) {
1693 st_src_reg temp = get_temp(native_integers ?
1694 glsl_type::uvec4_type :
1695 glsl_type::vec4_type);
1696 if (ir->operands[0]->type->is_boolean() &&
1697 ir->operands[1]->as_constant() &&
1698 ir->operands[1]->as_constant()->is_zero()) {
1699 emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), op[0]);
1700 } else {
1701 emit_asm(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1702 }
1703
1704 if (native_integers) {
1705 st_dst_reg temp_dst = st_dst_reg(temp);
1706 st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1707
1708 /* Emit 1-3 OR operations to combine the SNE results. */
1709 switch (ir->operands[0]->type->vector_elements) {
1710 case 2:
1711 break;
1712 case 3:
1713 temp_dst.writemask = WRITEMASK_Y;
1714 temp1.swizzle = SWIZZLE_YYYY;
1715 temp2.swizzle = SWIZZLE_ZZZZ;
1716 emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1717 break;
1718 case 4:
1719 temp_dst.writemask = WRITEMASK_X;
1720 temp1.swizzle = SWIZZLE_XXXX;
1721 temp2.swizzle = SWIZZLE_YYYY;
1722 emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1723 temp_dst.writemask = WRITEMASK_Y;
1724 temp1.swizzle = SWIZZLE_ZZZZ;
1725 temp2.swizzle = SWIZZLE_WWWW;
1726 emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1727 }
1728
1729 temp1.swizzle = SWIZZLE_XXXX;
1730 temp2.swizzle = SWIZZLE_YYYY;
1731 emit_asm(ir, TGSI_OPCODE_OR, result_dst, temp1, temp2);
1732 } else {
1733 /* After the dot-product, the value will be an integer on the
1734 * range [0,4]. Zero stays zero, and positive values become 1.0.
1735 */
1736 glsl_to_tgsi_instruction *const dp =
1737 emit_dp(ir, result_dst, temp, temp, vector_elements);
1738 if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1739 /* The clamping to [0,1] can be done for free in the fragment
1740 * shader with a saturate.
1741 */
1742 dp->saturate = true;
1743 } else {
1744 /* Negating the result of the dot-product gives values on the
1745 * range [-4, 0]. Zero stays zero, and negative values become
1746 * 1.0. This achieved using SLT.
1747 */
1748 st_src_reg slt_src = result_src;
1749 slt_src.negate = ~slt_src.negate;
1750 emit_asm(ir, TGSI_OPCODE_SLT, result_dst, slt_src,
1751 st_src_reg_for_float(0.0));
1752 }
1753 }
1754 } else {
1755 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1756 }
1757 break;
1758
1759 case ir_binop_logic_xor:
1760 if (native_integers)
1761 emit_asm(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1762 else
1763 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1764 break;
1765
1766 case ir_binop_logic_or: {
1767 if (native_integers) {
1768 /* If integers are used as booleans, we can use an actual "or"
1769 * instruction.
1770 */
1771 assert(native_integers);
1772 emit_asm(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1773 } else {
1774 /* After the addition, the value will be an integer on the
1775 * range [0,2]. Zero stays zero, and positive values become 1.0.
1776 */
1777 glsl_to_tgsi_instruction *add =
1778 emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1779 if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1780 /* The clamping to [0,1] can be done for free in the fragment
1781 * shader with a saturate if floats are being used as boolean
1782 * values.
1783 */
1784 add->saturate = true;
1785 } else {
1786 /* Negating the result of the addition gives values on the range
1787 * [-2, 0]. Zero stays zero, and negative values become 1.0
1788 * This is achieved using SLT.
1789 */
1790 st_src_reg slt_src = result_src;
1791 slt_src.negate = ~slt_src.negate;
1792 emit_asm(ir, TGSI_OPCODE_SLT, result_dst, slt_src,
1793 st_src_reg_for_float(0.0));
1794 }
1795 }
1796 break;
1797 }
1798
1799 case ir_binop_logic_and:
1800 /* If native integers are disabled, the bool args are stored as float 0.0
1801 * or 1.0, so "mul" gives us "and". If they're enabled, just use the
1802 * actual AND opcode.
1803 */
1804 if (native_integers)
1805 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1806 else
1807 emit_asm(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1808 break;
1809
1810 case ir_binop_dot:
1811 assert(ir->operands[0]->type->is_vector());
1812 assert(ir->operands[0]->type == ir->operands[1]->type);
1813 emit_dp(ir, result_dst, op[0], op[1],
1814 ir->operands[0]->type->vector_elements);
1815 break;
1816
1817 case ir_unop_sqrt:
1818 if (have_sqrt) {
1819 emit_scalar(ir, TGSI_OPCODE_SQRT, result_dst, op[0]);
1820 } else {
1821 /* This is the only instruction sequence that makes the game "Risen"
1822 * render correctly. ABS is not required for the game, but since GLSL
1823 * declares negative values as "undefined", allowing us to do whatever
1824 * we want, I choose to use ABS to match DX9 and pre-GLSL RSQ
1825 * behavior.
1826 */
1827 emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0].get_abs());
1828 emit_scalar(ir, TGSI_OPCODE_RCP, result_dst, result_src);
1829 }
1830 break;
1831 case ir_unop_rsq:
1832 emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1833 break;
1834 case ir_unop_i2f:
1835 if (native_integers) {
1836 emit_asm(ir, TGSI_OPCODE_I2F, result_dst, op[0]);
1837 break;
1838 }
1839 /* fallthrough to next case otherwise */
1840 case ir_unop_b2f:
1841 if (native_integers) {
1842 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0],
1843 st_src_reg_for_float(1.0));
1844 break;
1845 }
1846 /* fallthrough to next case otherwise */
1847 case ir_unop_i2u:
1848 case ir_unop_u2i:
1849 case ir_unop_i642u64:
1850 case ir_unop_u642i64:
1851 /* Converting between signed and unsigned integers is a no-op. */
1852 result_src = op[0];
1853 result_src.type = result_dst.type;
1854 break;
1855 case ir_unop_b2i:
1856 if (native_integers) {
1857 /* Booleans are stored as integers using ~0 for true and 0 for false.
1858 * GLSL requires that int(bool) return 1 for true and 0 for false.
1859 * This conversion is done with AND, but it could be done with NEG.
1860 */
1861 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0],
1862 st_src_reg_for_int(1));
1863 } else {
1864 /* Booleans and integers are both stored as floats when native
1865 * integers are disabled.
1866 */
1867 result_src = op[0];
1868 }
1869 break;
1870 case ir_unop_f2i:
1871 if (native_integers)
1872 emit_asm(ir, TGSI_OPCODE_F2I, result_dst, op[0]);
1873 else
1874 emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1875 break;
1876 case ir_unop_f2u:
1877 if (native_integers)
1878 emit_asm(ir, TGSI_OPCODE_F2U, result_dst, op[0]);
1879 else
1880 emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1881 break;
1882 case ir_unop_bitcast_f2i:
1883 case ir_unop_bitcast_f2u:
1884 /* Make sure we don't propagate the negate modifier to integer opcodes. */
1885 if (op[0].negate || op[0].abs)
1886 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1887 else
1888 result_src = op[0];
1889 result_src.type = ir->operation == ir_unop_bitcast_f2i ? GLSL_TYPE_INT :
1890 GLSL_TYPE_UINT;
1891 break;
1892 case ir_unop_bitcast_i2f:
1893 case ir_unop_bitcast_u2f:
1894 result_src = op[0];
1895 result_src.type = GLSL_TYPE_FLOAT;
1896 break;
1897 case ir_unop_f2b:
1898 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0],
1899 st_src_reg_for_float(0.0));
1900 break;
1901 case ir_unop_d2b:
1902 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0],
1903 st_src_reg_for_double(0.0));
1904 break;
1905 case ir_unop_i2b:
1906 if (native_integers)
1907 emit_asm(ir, TGSI_OPCODE_USNE, result_dst, op[0],
1908 st_src_reg_for_int(0));
1909 else
1910 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0],
1911 st_src_reg_for_float(0.0));
1912 break;
1913 case ir_unop_bitcast_u642d:
1914 case ir_unop_bitcast_i642d:
1915 result_src = op[0];
1916 result_src.type = GLSL_TYPE_DOUBLE;
1917 break;
1918 case ir_unop_bitcast_d2i64:
1919 result_src = op[0];
1920 result_src.type = GLSL_TYPE_INT64;
1921 break;
1922 case ir_unop_bitcast_d2u64:
1923 result_src = op[0];
1924 result_src.type = GLSL_TYPE_UINT64;
1925 break;
1926 case ir_unop_trunc:
1927 emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1928 break;
1929 case ir_unop_ceil:
1930 emit_asm(ir, TGSI_OPCODE_CEIL, result_dst, op[0]);
1931 break;
1932 case ir_unop_floor:
1933 emit_asm(ir, TGSI_OPCODE_FLR, result_dst, op[0]);
1934 break;
1935 case ir_unop_round_even:
1936 emit_asm(ir, TGSI_OPCODE_ROUND, result_dst, op[0]);
1937 break;
1938 case ir_unop_fract:
1939 emit_asm(ir, TGSI_OPCODE_FRC, result_dst, op[0]);
1940 break;
1941
1942 case ir_binop_min:
1943 emit_asm(ir, TGSI_OPCODE_MIN, result_dst, op[0], op[1]);
1944 break;
1945 case ir_binop_max:
1946 emit_asm(ir, TGSI_OPCODE_MAX, result_dst, op[0], op[1]);
1947 break;
1948 case ir_binop_pow:
1949 emit_scalar(ir, TGSI_OPCODE_POW, result_dst, op[0], op[1]);
1950 break;
1951
1952 case ir_unop_bit_not:
1953 if (native_integers) {
1954 emit_asm(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1955 break;
1956 }
1957 case ir_unop_u2f:
1958 if (native_integers) {
1959 emit_asm(ir, TGSI_OPCODE_U2F, result_dst, op[0]);
1960 break;
1961 }
1962 case ir_binop_lshift:
1963 case ir_binop_rshift:
1964 if (native_integers) {
1965 enum tgsi_opcode opcode = ir->operation == ir_binop_lshift
1966 ? TGSI_OPCODE_SHL : TGSI_OPCODE_ISHR;
1967 st_src_reg count;
1968
1969 if (glsl_base_type_is_64bit(op[0].type)) {
1970 /* GLSL shift operations have 32-bit shift counts, but TGSI uses
1971 * 64 bits.
1972 */
1973 count = get_temp(glsl_type::u64vec(ir->operands[1]
1974 ->type->components()));
1975 emit_asm(ir, TGSI_OPCODE_U2I64, st_dst_reg(count), op[1]);
1976 } else {
1977 count = op[1];
1978 }
1979
1980 emit_asm(ir, opcode, result_dst, op[0], count);
1981 break;
1982 }
1983 case ir_binop_bit_and:
1984 if (native_integers) {
1985 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1986 break;
1987 }
1988 case ir_binop_bit_xor:
1989 if (native_integers) {
1990 emit_asm(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1991 break;
1992 }
1993 case ir_binop_bit_or:
1994 if (native_integers) {
1995 emit_asm(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1996 break;
1997 }
1998
1999 assert(!"GLSL 1.30 features unsupported");
2000 break;
2001
2002 case ir_binop_ubo_load: {
2003 if (ctx->Const.UseSTD430AsDefaultPacking) {
2004 ir_rvalue *block = ir->operands[0];
2005 ir_rvalue *offset = ir->operands[1];
2006 ir_constant *const_block = block->as_constant();
2007
2008 st_src_reg cbuf(PROGRAM_CONSTANT,
2009 (const_block ? const_block->value.u[0] + 1 : 1),
2010 ir->type->base_type);
2011
2012 cbuf.has_index2 = true;
2013
2014 if (!const_block) {
2015 block->accept(this);
2016 cbuf.reladdr = ralloc(mem_ctx, st_src_reg);
2017 *cbuf.reladdr = this->result;
2018 emit_arl(ir, sampler_reladdr, this->result);
2019 }
2020
2021 /* Calculate the surface offset */
2022 offset->accept(this);
2023 st_src_reg off = this->result;
2024
2025 glsl_to_tgsi_instruction *inst =
2026 emit_asm(ir, TGSI_OPCODE_LOAD, result_dst, off);
2027
2028 if (result_dst.type == GLSL_TYPE_BOOL)
2029 emit_asm(ir, TGSI_OPCODE_USNE, result_dst, st_src_reg(result_dst),
2030 st_src_reg_for_int(0));
2031
2032 add_buffer_to_load_and_stores(inst, &cbuf, &this->instructions,
2033 NULL);
2034 } else {
2035 ir_constant *const_uniform_block = ir->operands[0]->as_constant();
2036 ir_constant *const_offset_ir = ir->operands[1]->as_constant();
2037 unsigned const_offset = const_offset_ir ?
2038 const_offset_ir->value.u[0] : 0;
2039 unsigned const_block = const_uniform_block ?
2040 const_uniform_block->value.u[0] + 1 : 1;
2041 st_src_reg index_reg = get_temp(glsl_type::uint_type);
2042 st_src_reg cbuf;
2043
2044 cbuf.type = ir->type->base_type;
2045 cbuf.file = PROGRAM_CONSTANT;
2046 cbuf.index = 0;
2047 cbuf.reladdr = NULL;
2048 cbuf.negate = 0;
2049 cbuf.abs = 0;
2050 cbuf.index2D = const_block;
2051
2052 assert(ir->type->is_vector() || ir->type->is_scalar());
2053
2054 if (const_offset_ir) {
2055 /* Constant index into constant buffer */
2056 cbuf.reladdr = NULL;
2057 cbuf.index = const_offset / 16;
2058 } else {
2059 ir_expression *offset_expr = ir->operands[1]->as_expression();
2060 st_src_reg offset = op[1];
2061
2062 /* The OpenGL spec is written in such a way that accesses with
2063 * non-constant offset are almost always vec4-aligned. The only
2064 * exception to this are members of structs in arrays of structs:
2065 * each struct in an array of structs is at least vec4-aligned,
2066 * but single-element and [ui]vec2 members of the struct may be at
2067 * an offset that is not a multiple of 16 bytes.
2068 *
2069 * Here, we extract that offset, relying on previous passes to
2070 * always generate offset expressions of the form
2071 * (+ expr constant_offset).
2072 *
2073 * Note that the std430 layout, which allows more cases of
2074 * alignment less than vec4 in arrays, is not supported for
2075 * uniform blocks, so we do not have to deal with it here.
2076 */
2077 if (offset_expr && offset_expr->operation == ir_binop_add) {
2078 const_offset_ir = offset_expr->operands[1]->as_constant();
2079 if (const_offset_ir) {
2080 const_offset = const_offset_ir->value.u[0];
2081 cbuf.index = const_offset / 16;
2082 offset_expr->operands[0]->accept(this);
2083 offset = this->result;
2084 }
2085 }
2086
2087 /* Relative/variable index into constant buffer */
2088 emit_asm(ir, TGSI_OPCODE_USHR, st_dst_reg(index_reg), offset,
2089 st_src_reg_for_int(4));
2090 cbuf.reladdr = ralloc(mem_ctx, st_src_reg);
2091 *cbuf.reladdr = index_reg;
2092 }
2093
2094 if (const_uniform_block) {
2095 /* Constant constant buffer */
2096 cbuf.reladdr2 = NULL;
2097 } else {
2098 /* Relative/variable constant buffer */
2099 cbuf.reladdr2 = ralloc(mem_ctx, st_src_reg);
2100 *cbuf.reladdr2 = op[0];
2101 }
2102 cbuf.has_index2 = true;
2103
2104 cbuf.swizzle = swizzle_for_size(ir->type->vector_elements);
2105 if (glsl_base_type_is_64bit(cbuf.type))
2106 cbuf.swizzle += MAKE_SWIZZLE4(const_offset % 16 / 8,
2107 const_offset % 16 / 8,
2108 const_offset % 16 / 8,
2109 const_offset % 16 / 8);
2110 else
2111 cbuf.swizzle += MAKE_SWIZZLE4(const_offset % 16 / 4,
2112 const_offset % 16 / 4,
2113 const_offset % 16 / 4,
2114 const_offset % 16 / 4);
2115
2116 if (ir->type->is_boolean()) {
2117 emit_asm(ir, TGSI_OPCODE_USNE, result_dst, cbuf,
2118 st_src_reg_for_int(0));
2119 } else {
2120 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, cbuf);
2121 }
2122 }
2123 break;
2124 }
2125 case ir_triop_lrp:
2126 /* note: we have to reorder the three args here */
2127 emit_asm(ir, TGSI_OPCODE_LRP, result_dst, op[2], op[1], op[0]);
2128 break;
2129 case ir_triop_csel:
2130 if (this->ctx->Const.NativeIntegers)
2131 emit_asm(ir, TGSI_OPCODE_UCMP, result_dst, op[0], op[1], op[2]);
2132 else {
2133 op[0].negate = ~op[0].negate;
2134 emit_asm(ir, TGSI_OPCODE_CMP, result_dst, op[0], op[1], op[2]);
2135 }
2136 break;
2137 case ir_triop_bitfield_extract:
2138 emit_asm(ir, TGSI_OPCODE_IBFE, result_dst, op[0], op[1], op[2]);
2139 break;
2140 case ir_quadop_bitfield_insert:
2141 emit_asm(ir, TGSI_OPCODE_BFI, result_dst, op[0], op[1], op[2], op[3]);
2142 break;
2143 case ir_unop_bitfield_reverse:
2144 emit_asm(ir, TGSI_OPCODE_BREV, result_dst, op[0]);
2145 break;
2146 case ir_unop_bit_count:
2147 emit_asm(ir, TGSI_OPCODE_POPC, result_dst, op[0]);
2148 break;
2149 case ir_unop_find_msb:
2150 emit_asm(ir, TGSI_OPCODE_IMSB, result_dst, op[0]);
2151 break;
2152 case ir_unop_find_lsb:
2153 emit_asm(ir, TGSI_OPCODE_LSB, result_dst, op[0]);
2154 break;
2155 case ir_binop_imul_high:
2156 emit_asm(ir, TGSI_OPCODE_IMUL_HI, result_dst, op[0], op[1]);
2157 break;
2158 case ir_triop_fma:
2159 /* In theory, MAD is incorrect here. */
2160 if (have_fma)
2161 emit_asm(ir, TGSI_OPCODE_FMA, result_dst, op[0], op[1], op[2]);
2162 else
2163 emit_asm(ir, TGSI_OPCODE_MAD, result_dst, op[0], op[1], op[2]);
2164 break;
2165 case ir_unop_interpolate_at_centroid:
2166 emit_asm(ir, TGSI_OPCODE_INTERP_CENTROID, result_dst, op[0]);
2167 break;
2168 case ir_binop_interpolate_at_offset: {
2169 /* The y coordinate needs to be flipped for the default fb */
2170 static const gl_state_index16 transform_y_state[STATE_LENGTH]
2171 = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM };
2172
2173 unsigned transform_y_index =
2174 _mesa_add_state_reference(this->prog->Parameters,
2175 transform_y_state);
2176
2177 st_src_reg transform_y = st_src_reg(PROGRAM_STATE_VAR,
2178 transform_y_index,
2179 glsl_type::vec4_type);
2180 transform_y.swizzle = SWIZZLE_XXXX;
2181
2182 st_src_reg temp = get_temp(glsl_type::vec2_type);
2183 st_dst_reg temp_dst = st_dst_reg(temp);
2184
2185 emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, op[1]);
2186 temp_dst.writemask = WRITEMASK_Y;
2187 emit_asm(ir, TGSI_OPCODE_MUL, temp_dst, transform_y, op[1]);
2188 emit_asm(ir, TGSI_OPCODE_INTERP_OFFSET, result_dst, op[0], temp);
2189 break;
2190 }
2191 case ir_binop_interpolate_at_sample:
2192 emit_asm(ir, TGSI_OPCODE_INTERP_SAMPLE, result_dst, op[0], op[1]);
2193 break;
2194
2195 case ir_unop_d2f:
2196 emit_asm(ir, TGSI_OPCODE_D2F, result_dst, op[0]);
2197 break;
2198 case ir_unop_f2d:
2199 emit_asm(ir, TGSI_OPCODE_F2D, result_dst, op[0]);
2200 break;
2201 case ir_unop_d2i:
2202 emit_asm(ir, TGSI_OPCODE_D2I, result_dst, op[0]);
2203 break;
2204 case ir_unop_i2d:
2205 emit_asm(ir, TGSI_OPCODE_I2D, result_dst, op[0]);
2206 break;
2207 case ir_unop_d2u:
2208 emit_asm(ir, TGSI_OPCODE_D2U, result_dst, op[0]);
2209 break;
2210 case ir_unop_u2d:
2211 emit_asm(ir, TGSI_OPCODE_U2D, result_dst, op[0]);
2212 break;
2213 case ir_unop_unpack_double_2x32:
2214 case ir_unop_pack_double_2x32:
2215 case ir_unop_unpack_int_2x32:
2216 case ir_unop_pack_int_2x32:
2217 case ir_unop_unpack_uint_2x32:
2218 case ir_unop_pack_uint_2x32:
2219 case ir_unop_unpack_sampler_2x32:
2220 case ir_unop_pack_sampler_2x32:
2221 case ir_unop_unpack_image_2x32:
2222 case ir_unop_pack_image_2x32:
2223 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
2224 break;
2225
2226 case ir_binop_ldexp:
2227 if (ir->operands[0]->type->is_double()) {
2228 emit_asm(ir, TGSI_OPCODE_DLDEXP, result_dst, op[0], op[1]);
2229 } else if (ir->operands[0]->type->is_float()) {
2230 emit_asm(ir, TGSI_OPCODE_LDEXP, result_dst, op[0], op[1]);
2231 } else {
2232 assert(!"Invalid ldexp for non-double opcode in glsl_to_tgsi_visitor::visit()");
2233 }
2234 break;
2235
2236 case ir_unop_pack_half_2x16:
2237 emit_asm(ir, TGSI_OPCODE_PK2H, result_dst, op[0]);
2238 break;
2239 case ir_unop_unpack_half_2x16:
2240 emit_asm(ir, TGSI_OPCODE_UP2H, result_dst, op[0]);
2241 break;
2242
2243 case ir_unop_get_buffer_size: {
2244 ir_constant *const_offset = ir->operands[0]->as_constant();
2245 int buf_base = ctx->st->has_hw_atomics
2246 ? 0 : ctx->Const.Program[shader->Stage].MaxAtomicBuffers;
2247 st_src_reg buffer(
2248 PROGRAM_BUFFER,
2249 buf_base + (const_offset ? const_offset->value.u[0] : 0),
2250 GLSL_TYPE_UINT);
2251 if (!const_offset) {
2252 buffer.reladdr = ralloc(mem_ctx, st_src_reg);
2253 *buffer.reladdr = op[0];
2254 emit_arl(ir, sampler_reladdr, op[0]);
2255 }
2256 emit_asm(ir, TGSI_OPCODE_RESQ, result_dst)->resource = buffer;
2257 break;
2258 }
2259
2260 case ir_unop_u2i64:
2261 case ir_unop_u2u64:
2262 case ir_unop_b2i64: {
2263 st_src_reg temp = get_temp(glsl_type::uvec4_type);
2264 st_dst_reg temp_dst = st_dst_reg(temp);
2265 unsigned orig_swz = op[0].swizzle;
2266 /*
2267 * To convert unsigned to 64-bit:
2268 * zero Y channel, copy X channel.
2269 */
2270 temp_dst.writemask = WRITEMASK_Y;
2271 if (vector_elements > 1)
2272 temp_dst.writemask |= WRITEMASK_W;
2273 emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, st_src_reg_for_int(0));
2274 temp_dst.writemask = WRITEMASK_X;
2275 if (vector_elements > 1)
2276 temp_dst.writemask |= WRITEMASK_Z;
2277 op[0].swizzle = MAKE_SWIZZLE4(GET_SWZ(orig_swz, 0), GET_SWZ(orig_swz, 0),
2278 GET_SWZ(orig_swz, 1), GET_SWZ(orig_swz, 1));
2279 if (ir->operation == ir_unop_u2i64 || ir->operation == ir_unop_u2u64)
2280 emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, op[0]);
2281 else
2282 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, op[0], st_src_reg_for_int(1));
2283 result_src = temp;
2284 result_src.type = GLSL_TYPE_UINT64;
2285 if (vector_elements > 2) {
2286 /* Subtle: We rely on the fact that get_temp here returns the next
2287 * TGSI temporary register directly after the temp register used for
2288 * the first two components, so that the result gets picked up
2289 * automatically.
2290 */
2291 st_src_reg temp = get_temp(glsl_type::uvec4_type);
2292 st_dst_reg temp_dst = st_dst_reg(temp);
2293 temp_dst.writemask = WRITEMASK_Y;
2294 if (vector_elements > 3)
2295 temp_dst.writemask |= WRITEMASK_W;
2296 emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, st_src_reg_for_int(0));
2297
2298 temp_dst.writemask = WRITEMASK_X;
2299 if (vector_elements > 3)
2300 temp_dst.writemask |= WRITEMASK_Z;
2301 op[0].swizzle = MAKE_SWIZZLE4(GET_SWZ(orig_swz, 2),
2302 GET_SWZ(orig_swz, 2),
2303 GET_SWZ(orig_swz, 3),
2304 GET_SWZ(orig_swz, 3));
2305 if (ir->operation == ir_unop_u2i64 || ir->operation == ir_unop_u2u64)
2306 emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, op[0]);
2307 else
2308 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, op[0],
2309 st_src_reg_for_int(1));
2310 }
2311 break;
2312 }
2313 case ir_unop_i642i:
2314 case ir_unop_u642i:
2315 case ir_unop_u642u:
2316 case ir_unop_i642u: {
2317 st_src_reg temp = get_temp(glsl_type::uvec4_type);
2318 st_dst_reg temp_dst = st_dst_reg(temp);
2319 unsigned orig_swz = op[0].swizzle;
2320 unsigned orig_idx = op[0].index;
2321 int el;
2322 temp_dst.writemask = WRITEMASK_X;
2323
2324 for (el = 0; el < vector_elements; el++) {
2325 unsigned swz = GET_SWZ(orig_swz, el);
2326 if (swz & 1)
2327 op[0].swizzle = MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_Z,
2328 SWIZZLE_Z, SWIZZLE_Z);
2329 else
2330 op[0].swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X,
2331 SWIZZLE_X, SWIZZLE_X);
2332 if (swz > 2)
2333 op[0].index = orig_idx + 1;
2334 op[0].type = GLSL_TYPE_UINT;
2335 temp_dst.writemask = WRITEMASK_X << el;
2336 emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, op[0]);
2337 }
2338 result_src = temp;
2339 if (ir->operation == ir_unop_u642u || ir->operation == ir_unop_i642u)
2340 result_src.type = GLSL_TYPE_UINT;
2341 else
2342 result_src.type = GLSL_TYPE_INT;
2343 break;
2344 }
2345 case ir_unop_i642b:
2346 emit_asm(ir, TGSI_OPCODE_U64SNE, result_dst, op[0],
2347 st_src_reg_for_int64(0));
2348 break;
2349 case ir_unop_i642f:
2350 emit_asm(ir, TGSI_OPCODE_I642F, result_dst, op[0]);
2351 break;
2352 case ir_unop_u642f:
2353 emit_asm(ir, TGSI_OPCODE_U642F, result_dst, op[0]);
2354 break;
2355 case ir_unop_i642d:
2356 emit_asm(ir, TGSI_OPCODE_I642D, result_dst, op[0]);
2357 break;
2358 case ir_unop_u642d:
2359 emit_asm(ir, TGSI_OPCODE_U642D, result_dst, op[0]);
2360 break;
2361 case ir_unop_i2i64:
2362 emit_asm(ir, TGSI_OPCODE_I2I64, result_dst, op[0]);
2363 break;
2364 case ir_unop_f2i64:
2365 emit_asm(ir, TGSI_OPCODE_F2I64, result_dst, op[0]);
2366 break;
2367 case ir_unop_d2i64:
2368 emit_asm(ir, TGSI_OPCODE_D2I64, result_dst, op[0]);
2369 break;
2370 case ir_unop_i2u64:
2371 emit_asm(ir, TGSI_OPCODE_I2I64, result_dst, op[0]);
2372 break;
2373 case ir_unop_f2u64:
2374 emit_asm(ir, TGSI_OPCODE_F2U64, result_dst, op[0]);
2375 break;
2376 case ir_unop_d2u64:
2377 emit_asm(ir, TGSI_OPCODE_D2U64, result_dst, op[0]);
2378 break;
2379 /* these might be needed */
2380 case ir_unop_pack_snorm_2x16:
2381 case ir_unop_pack_unorm_2x16:
2382 case ir_unop_pack_snorm_4x8:
2383 case ir_unop_pack_unorm_4x8:
2384
2385 case ir_unop_unpack_snorm_2x16:
2386 case ir_unop_unpack_unorm_2x16:
2387 case ir_unop_unpack_snorm_4x8:
2388 case ir_unop_unpack_unorm_4x8:
2389
2390 case ir_quadop_vector:
2391 case ir_binop_vector_extract:
2392 case ir_triop_vector_insert:
2393 case ir_binop_carry:
2394 case ir_binop_borrow:
2395 case ir_unop_ssbo_unsized_array_length:
2396 /* This operation is not supported, or should have already been handled.
2397 */
2398 assert(!"Invalid ir opcode in glsl_to_tgsi_visitor::visit()");
2399 break;
2400 }
2401
2402 this->result = result_src;
2403 }
2404
2405
2406 void
2407 glsl_to_tgsi_visitor::visit(ir_swizzle *ir)
2408 {
2409 st_src_reg src;
2410 int i;
2411 int swizzle[4];
2412
2413 /* Note that this is only swizzles in expressions, not those on the left
2414 * hand side of an assignment, which do write masking. See ir_assignment
2415 * for that.
2416 */
2417
2418 ir->val->accept(this);
2419 src = this->result;
2420 assert(src.file != PROGRAM_UNDEFINED);
2421 assert(ir->type->vector_elements > 0);
2422
2423 for (i = 0; i < 4; i++) {
2424 if (i < ir->type->vector_elements) {
2425 switch (i) {
2426 case 0:
2427 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.x);
2428 break;
2429 case 1:
2430 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.y);
2431 break;
2432 case 2:
2433 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.z);
2434 break;
2435 case 3:
2436 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.w);
2437 break;
2438 }
2439 } else {
2440 /* If the type is smaller than a vec4, replicate the last
2441 * channel out.
2442 */
2443 swizzle[i] = swizzle[ir->type->vector_elements - 1];
2444 }
2445 }
2446
2447 src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
2448
2449 this->result = src;
2450 }
2451
2452 /* Test if the variable is an array. Note that geometry and
2453 * tessellation shader inputs are outputs are always arrays (except
2454 * for patch inputs), so only the array element type is considered.
2455 */
2456 static bool
2457 is_inout_array(unsigned stage, ir_variable *var, bool *remove_array)
2458 {
2459 const glsl_type *type = var->type;
2460
2461 *remove_array = false;
2462
2463 if ((stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
2464 (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out))
2465 return false;
2466
2467 if (((stage == MESA_SHADER_GEOMETRY && var->data.mode == ir_var_shader_in) ||
2468 (stage == MESA_SHADER_TESS_EVAL && var->data.mode == ir_var_shader_in) ||
2469 stage == MESA_SHADER_TESS_CTRL) &&
2470 !var->data.patch) {
2471 if (!var->type->is_array())
2472 return false; /* a system value probably */
2473
2474 type = var->type->fields.array;
2475 *remove_array = true;
2476 }
2477
2478 return type->is_array() || type->is_matrix();
2479 }
2480
2481 static unsigned
2482 st_translate_interp_loc(ir_variable *var)
2483 {
2484 if (var->data.centroid)
2485 return TGSI_INTERPOLATE_LOC_CENTROID;
2486 else if (var->data.sample)
2487 return TGSI_INTERPOLATE_LOC_SAMPLE;
2488 else
2489 return TGSI_INTERPOLATE_LOC_CENTER;
2490 }
2491
2492 void
2493 glsl_to_tgsi_visitor::visit(ir_dereference_variable *ir)
2494 {
2495 variable_storage *entry;
2496 ir_variable *var = ir->var;
2497 bool remove_array;
2498
2499 if (handle_bound_deref(ir->as_dereference()))
2500 return;
2501
2502 entry = find_variable_storage(ir->var);
2503
2504 if (!entry) {
2505 switch (var->data.mode) {
2506 case ir_var_uniform:
2507 entry = new(mem_ctx) variable_storage(var, PROGRAM_UNIFORM,
2508 var->data.param_index);
2509 _mesa_hash_table_insert(this->variables, var, entry);
2510 break;
2511 case ir_var_shader_in: {
2512 /* The linker assigns locations for varyings and attributes,
2513 * including deprecated builtins (like gl_Color), user-assign
2514 * generic attributes (glBindVertexLocation), and
2515 * user-defined varyings.
2516 */
2517 assert(var->data.location != -1);
2518
2519 const glsl_type *type_without_array = var->type->without_array();
2520 struct inout_decl *decl = &inputs[num_inputs];
2521 unsigned component = var->data.location_frac;
2522 unsigned num_components;
2523 num_inputs++;
2524
2525 if (type_without_array->is_64bit())
2526 component = component / 2;
2527 if (type_without_array->vector_elements)
2528 num_components = type_without_array->vector_elements;
2529 else
2530 num_components = 4;
2531
2532 decl->mesa_index = var->data.location;
2533 decl->interp = (glsl_interp_mode) var->data.interpolation;
2534 decl->interp_loc = st_translate_interp_loc(var);
2535 decl->base_type = type_without_array->base_type;
2536 decl->usage_mask = u_bit_consecutive(component, num_components);
2537
2538 if (is_inout_array(shader->Stage, var, &remove_array)) {
2539 decl->array_id = num_input_arrays + 1;
2540 num_input_arrays++;
2541 } else {
2542 decl->array_id = 0;
2543 }
2544
2545 if (remove_array)
2546 decl->size = type_size(var->type->fields.array);
2547 else
2548 decl->size = type_size(var->type);
2549
2550 entry = new(mem_ctx) variable_storage(var,
2551 PROGRAM_INPUT,
2552 decl->mesa_index,
2553 decl->array_id);
2554 entry->component = component;
2555
2556 _mesa_hash_table_insert(this->variables, var, entry);
2557
2558 break;
2559 }
2560 case ir_var_shader_out: {
2561 assert(var->data.location != -1);
2562
2563 const glsl_type *type_without_array = var->type->without_array();
2564 struct inout_decl *decl = &outputs[num_outputs];
2565 unsigned component = var->data.location_frac;
2566 unsigned num_components;
2567 num_outputs++;
2568
2569 decl->invariant = var->data.invariant;
2570
2571 if (type_without_array->is_64bit())
2572 component = component / 2;
2573 if (type_without_array->vector_elements)
2574 num_components = type_without_array->vector_elements;
2575 else
2576 num_components = 4;
2577
2578 decl->mesa_index = var->data.location + FRAG_RESULT_MAX * var->data.index;
2579 decl->base_type = type_without_array->base_type;
2580 decl->usage_mask = u_bit_consecutive(component, num_components);
2581 if (var->data.stream & (1u << 31)) {
2582 decl->gs_out_streams = var->data.stream & ~(1u << 31);
2583 } else {
2584 assert(var->data.stream < 4);
2585 decl->gs_out_streams = 0;
2586 for (unsigned i = 0; i < num_components; ++i)
2587 decl->gs_out_streams |= var->data.stream << (2 * (component + i));
2588 }
2589
2590 if (is_inout_array(shader->Stage, var, &remove_array)) {
2591 decl->array_id = num_output_arrays + 1;
2592 num_output_arrays++;
2593 } else {
2594 decl->array_id = 0;
2595 }
2596
2597 if (remove_array)
2598 decl->size = type_size(var->type->fields.array);
2599 else
2600 decl->size = type_size(var->type);
2601
2602 if (var->data.fb_fetch_output) {
2603 st_dst_reg dst = st_dst_reg(get_temp(var->type));
2604 st_src_reg src = st_src_reg(PROGRAM_OUTPUT, decl->mesa_index,
2605 var->type, component, decl->array_id);
2606 emit_asm(NULL, TGSI_OPCODE_FBFETCH, dst, src);
2607 entry = new(mem_ctx) variable_storage(var, dst.file, dst.index,
2608 dst.array_id);
2609 } else {
2610 entry = new(mem_ctx) variable_storage(var,
2611 PROGRAM_OUTPUT,
2612 decl->mesa_index,
2613 decl->array_id);
2614 }
2615 entry->component = component;
2616
2617 _mesa_hash_table_insert(this->variables, var, entry);
2618
2619 break;
2620 }
2621 case ir_var_system_value:
2622 entry = new(mem_ctx) variable_storage(var,
2623 PROGRAM_SYSTEM_VALUE,
2624 var->data.location);
2625 break;
2626 case ir_var_auto:
2627 case ir_var_temporary:
2628 st_src_reg src = get_temp(var->type);
2629
2630 entry = new(mem_ctx) variable_storage(var, src.file, src.index,
2631 src.array_id);
2632 _mesa_hash_table_insert(this->variables, var, entry);
2633
2634 break;
2635 }
2636
2637 if (!entry) {
2638 printf("Failed to make storage for %s\n", var->name);
2639 exit(1);
2640 }
2641 }
2642
2643 this->result = st_src_reg(entry->file, entry->index, var->type,
2644 entry->component, entry->array_id);
2645 if (this->shader->Stage == MESA_SHADER_VERTEX &&
2646 var->data.mode == ir_var_shader_in &&
2647 var->type->without_array()->is_double())
2648 this->result.is_double_vertex_input = true;
2649 if (!native_integers)
2650 this->result.type = GLSL_TYPE_FLOAT;
2651 }
2652
2653 static void
2654 shrink_array_declarations(struct inout_decl *decls, unsigned count,
2655 GLbitfield64* usage_mask,
2656 GLbitfield64 double_usage_mask,
2657 GLbitfield* patch_usage_mask)
2658 {
2659 unsigned i;
2660 int j;
2661
2662 /* Fix array declarations by removing unused array elements at both ends
2663 * of the arrays. For example, mat4[3] where only mat[1] is used.
2664 */
2665 for (i = 0; i < count; i++) {
2666 struct inout_decl *decl = &decls[i];
2667 if (!decl->array_id)
2668 continue;
2669
2670 /* Shrink the beginning. */
2671 for (j = 0; j < (int)decl->size; j++) {
2672 if (decl->mesa_index >= VARYING_SLOT_PATCH0) {
2673 if (*patch_usage_mask &
2674 BITFIELD64_BIT(decl->mesa_index - VARYING_SLOT_PATCH0 + j))
2675 break;
2676 }
2677 else {
2678 if (*usage_mask & BITFIELD64_BIT(decl->mesa_index+j))
2679 break;
2680 if (double_usage_mask & BITFIELD64_BIT(decl->mesa_index+j-1))
2681 break;
2682 }
2683
2684 decl->mesa_index++;
2685 decl->size--;
2686 j--;
2687 }
2688
2689 /* Shrink the end. */
2690 for (j = decl->size-1; j >= 0; j--) {
2691 if (decl->mesa_index >= VARYING_SLOT_PATCH0) {
2692 if (*patch_usage_mask &
2693 BITFIELD64_BIT(decl->mesa_index - VARYING_SLOT_PATCH0 + j))
2694 break;
2695 }
2696 else {
2697 if (*usage_mask & BITFIELD64_BIT(decl->mesa_index+j))
2698 break;
2699 if (double_usage_mask & BITFIELD64_BIT(decl->mesa_index+j-1))
2700 break;
2701 }
2702
2703 decl->size--;
2704 }
2705
2706 /* When not all entries of an array are accessed, we mark them as used
2707 * here anyway, to ensure that the input/output mapping logic doesn't get
2708 * confused.
2709 *
2710 * TODO This happens when an array isn't used via indirect access, which
2711 * some game ports do (at least eON-based). There is an optimization
2712 * opportunity here by replacing the array declaration with non-array
2713 * declarations of those slots that are actually used.
2714 */
2715 for (j = 1; j < (int)decl->size; ++j) {
2716 if (decl->mesa_index >= VARYING_SLOT_PATCH0)
2717 *patch_usage_mask |= BITFIELD64_BIT(decl->mesa_index - VARYING_SLOT_PATCH0 + j);
2718 else
2719 *usage_mask |= BITFIELD64_BIT(decl->mesa_index + j);
2720 }
2721 }
2722 }
2723
2724 void
2725 glsl_to_tgsi_visitor::visit(ir_dereference_array *ir)
2726 {
2727 ir_constant *index;
2728 st_src_reg src;
2729 bool is_2D = false;
2730 ir_variable *var = ir->variable_referenced();
2731
2732 if (handle_bound_deref(ir->as_dereference()))
2733 return;
2734
2735 /* We only need the logic provided by st_glsl_storage_type_size()
2736 * for arrays of structs. Indirect sampler and image indexing is handled
2737 * elsewhere.
2738 */
2739 int element_size = ir->type->without_array()->is_record() ?
2740 st_glsl_storage_type_size(ir->type, var->data.bindless) :
2741 type_size(ir->type);
2742
2743 index = ir->array_index->constant_expression_value(ralloc_parent(ir));
2744
2745 ir->array->accept(this);
2746 src = this->result;
2747
2748 if (!src.has_index2) {
2749 switch (this->prog->Target) {
2750 case GL_TESS_CONTROL_PROGRAM_NV:
2751 is_2D = (src.file == PROGRAM_INPUT || src.file == PROGRAM_OUTPUT) &&
2752 !ir->variable_referenced()->data.patch;
2753 break;
2754 case GL_TESS_EVALUATION_PROGRAM_NV:
2755 is_2D = src.file == PROGRAM_INPUT &&
2756 !ir->variable_referenced()->data.patch;
2757 break;
2758 case GL_GEOMETRY_PROGRAM_NV:
2759 is_2D = src.file == PROGRAM_INPUT;
2760 break;
2761 }
2762 }
2763
2764 if (is_2D)
2765 element_size = 1;
2766
2767 if (index) {
2768
2769 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
2770 src.file == PROGRAM_INPUT)
2771 element_size = attrib_type_size(ir->type, true);
2772 if (is_2D) {
2773 src.index2D = index->value.i[0];
2774 src.has_index2 = true;
2775 } else
2776 src.index += index->value.i[0] * element_size;
2777 } else {
2778 /* Variable index array dereference. It eats the "vec4" of the
2779 * base of the array and an index that offsets the TGSI register
2780 * index.
2781 */
2782 ir->array_index->accept(this);
2783
2784 st_src_reg index_reg;
2785
2786 if (element_size == 1) {
2787 index_reg = this->result;
2788 } else {
2789 index_reg = get_temp(native_integers ?
2790 glsl_type::int_type : glsl_type::float_type);
2791
2792 emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(index_reg),
2793 this->result, st_src_reg_for_type(index_reg.type, element_size));
2794 }
2795
2796 /* If there was already a relative address register involved, add the
2797 * new and the old together to get the new offset.
2798 */
2799 if (!is_2D && src.reladdr != NULL) {
2800 st_src_reg accum_reg = get_temp(native_integers ?
2801 glsl_type::int_type : glsl_type::float_type);
2802
2803 emit_asm(ir, TGSI_OPCODE_ADD, st_dst_reg(accum_reg),
2804 index_reg, *src.reladdr);
2805
2806 index_reg = accum_reg;
2807 }
2808
2809 if (is_2D) {
2810 src.reladdr2 = ralloc(mem_ctx, st_src_reg);
2811 *src.reladdr2 = index_reg;
2812 src.index2D = 0;
2813 src.has_index2 = true;
2814 } else {
2815 src.reladdr = ralloc(mem_ctx, st_src_reg);
2816 *src.reladdr = index_reg;
2817 }
2818 }
2819
2820 /* Change the register type to the element type of the array. */
2821 src.type = ir->type->base_type;
2822
2823 this->result = src;
2824 }
2825
2826 void
2827 glsl_to_tgsi_visitor::visit(ir_dereference_record *ir)
2828 {
2829 unsigned int i;
2830 const glsl_type *struct_type = ir->record->type;
2831 ir_variable *var = ir->record->variable_referenced();
2832 int offset = 0;
2833
2834 if (handle_bound_deref(ir->as_dereference()))
2835 return;
2836
2837 ir->record->accept(this);
2838
2839 assert(ir->field_idx >= 0);
2840 assert(var);
2841 for (i = 0; i < struct_type->length; i++) {
2842 if (i == (unsigned) ir->field_idx)
2843 break;
2844 const glsl_type *member_type = struct_type->fields.structure[i].type;
2845 offset += st_glsl_storage_type_size(member_type, var->data.bindless);
2846 }
2847
2848 /* If the type is smaller than a vec4, replicate the last channel out. */
2849 if (ir->type->is_scalar() || ir->type->is_vector())
2850 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
2851 else
2852 this->result.swizzle = SWIZZLE_NOOP;
2853
2854 this->result.index += offset;
2855 this->result.type = ir->type->base_type;
2856 }
2857
2858 /**
2859 * We want to be careful in assignment setup to hit the actual storage
2860 * instead of potentially using a temporary like we might with the
2861 * ir_dereference handler.
2862 */
2863 static st_dst_reg
2864 get_assignment_lhs(ir_dereference *ir, glsl_to_tgsi_visitor *v, int *component)
2865 {
2866 /* The LHS must be a dereference. If the LHS is a variable indexed array
2867 * access of a vector, it must be separated into a series conditional moves
2868 * before reaching this point (see ir_vec_index_to_cond_assign).
2869 */
2870 assert(ir->as_dereference());
2871 ir_dereference_array *deref_array = ir->as_dereference_array();
2872 if (deref_array) {
2873 assert(!deref_array->array->type->is_vector());
2874 }
2875
2876 /* Use the rvalue deref handler for the most part. We write swizzles using
2877 * the writemask, but we do extract the base component for enhanced layouts
2878 * from the source swizzle.
2879 */
2880 ir->accept(v);
2881 *component = GET_SWZ(v->result.swizzle, 0);
2882 return st_dst_reg(v->result);
2883 }
2884
2885 /**
2886 * Process the condition of a conditional assignment
2887 *
2888 * Examines the condition of a conditional assignment to generate the optimal
2889 * first operand of a \c CMP instruction. If the condition is a relational
2890 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
2891 * used as the source for the \c CMP instruction. Otherwise the comparison
2892 * is processed to a boolean result, and the boolean result is used as the
2893 * operand to the CMP instruction.
2894 */
2895 bool
2896 glsl_to_tgsi_visitor::process_move_condition(ir_rvalue *ir)
2897 {
2898 ir_rvalue *src_ir = ir;
2899 bool negate = true;
2900 bool switch_order = false;
2901
2902 ir_expression *const expr = ir->as_expression();
2903
2904 if (native_integers) {
2905 if ((expr != NULL) && (expr->num_operands == 2)) {
2906 enum glsl_base_type type = expr->operands[0]->type->base_type;
2907 if (type == GLSL_TYPE_INT || type == GLSL_TYPE_UINT ||
2908 type == GLSL_TYPE_BOOL) {
2909 if (expr->operation == ir_binop_equal) {
2910 if (expr->operands[0]->is_zero()) {
2911 src_ir = expr->operands[1];
2912 switch_order = true;
2913 }
2914 else if (expr->operands[1]->is_zero()) {
2915 src_ir = expr->operands[0];
2916 switch_order = true;
2917 }
2918 }
2919 else if (expr->operation == ir_binop_nequal) {
2920 if (expr->operands[0]->is_zero()) {
2921 src_ir = expr->operands[1];
2922 }
2923 else if (expr->operands[1]->is_zero()) {
2924 src_ir = expr->operands[0];
2925 }
2926 }
2927 }
2928 }
2929
2930 src_ir->accept(this);
2931 return switch_order;
2932 }
2933
2934 if ((expr != NULL) && (expr->num_operands == 2)) {
2935 bool zero_on_left = false;
2936
2937 if (expr->operands[0]->is_zero()) {
2938 src_ir = expr->operands[1];
2939 zero_on_left = true;
2940 } else if (expr->operands[1]->is_zero()) {
2941 src_ir = expr->operands[0];
2942 zero_on_left = false;
2943 }
2944
2945 /* a is - 0 + - 0 +
2946 * (a < 0) T F F ( a < 0) T F F
2947 * (0 < a) F F T (-a < 0) F F T
2948 * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
2949 * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
2950 *
2951 * Note that exchanging the order of 0 and 'a' in the comparison simply
2952 * means that the value of 'a' should be negated.
2953 */
2954 if (src_ir != ir) {
2955 switch (expr->operation) {
2956 case ir_binop_less:
2957 switch_order = false;
2958 negate = zero_on_left;
2959 break;
2960
2961 case ir_binop_gequal:
2962 switch_order = true;
2963 negate = zero_on_left;
2964 break;
2965
2966 default:
2967 /* This isn't the right kind of comparison afterall, so make sure
2968 * the whole condition is visited.
2969 */
2970 src_ir = ir;
2971 break;
2972 }
2973 }
2974 }
2975
2976 src_ir->accept(this);
2977
2978 /* We use the TGSI_OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
2979 * condition we produced is 0.0 or 1.0. By flipping the sign, we can
2980 * choose which value TGSI_OPCODE_CMP produces without an extra instruction
2981 * computing the condition.
2982 */
2983 if (negate)
2984 this->result.negate = ~this->result.negate;
2985
2986 return switch_order;
2987 }
2988
2989 void
2990 glsl_to_tgsi_visitor::emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
2991 st_dst_reg *l, st_src_reg *r,
2992 st_src_reg *cond, bool cond_swap)
2993 {
2994 if (type->is_record()) {
2995 for (unsigned int i = 0; i < type->length; i++) {
2996 emit_block_mov(ir, type->fields.structure[i].type, l, r,
2997 cond, cond_swap);
2998 }
2999 return;
3000 }
3001
3002 if (type->is_array()) {
3003 for (unsigned int i = 0; i < type->length; i++) {
3004 emit_block_mov(ir, type->fields.array, l, r, cond, cond_swap);
3005 }
3006 return;
3007 }
3008
3009 if (type->is_matrix()) {
3010 const struct glsl_type *vec_type;
3011
3012 vec_type = glsl_type::get_instance(type->is_double()
3013 ? GLSL_TYPE_DOUBLE : GLSL_TYPE_FLOAT,
3014 type->vector_elements, 1);
3015
3016 for (int i = 0; i < type->matrix_columns; i++) {
3017 emit_block_mov(ir, vec_type, l, r, cond, cond_swap);
3018 }
3019 return;
3020 }
3021
3022 assert(type->is_scalar() || type->is_vector());
3023
3024 l->type = type->base_type;
3025 r->type = type->base_type;
3026 if (cond) {
3027 st_src_reg l_src = st_src_reg(*l);
3028
3029 if (l_src.file == PROGRAM_OUTPUT &&
3030 this->prog->Target == GL_FRAGMENT_PROGRAM_ARB &&
3031 (l_src.index == FRAG_RESULT_DEPTH ||
3032 l_src.index == FRAG_RESULT_STENCIL)) {
3033 /* This is a special case because the source swizzles will be shifted
3034 * later to account for the difference between GLSL (where they're
3035 * plain floats) and TGSI (where they're Z and Y components). */
3036 l_src.swizzle = SWIZZLE_XXXX;
3037 }
3038
3039 if (native_integers) {
3040 emit_asm(ir, TGSI_OPCODE_UCMP, *l, *cond,
3041 cond_swap ? l_src : *r,
3042 cond_swap ? *r : l_src);
3043 } else {
3044 emit_asm(ir, TGSI_OPCODE_CMP, *l, *cond,
3045 cond_swap ? l_src : *r,
3046 cond_swap ? *r : l_src);
3047 }
3048 } else {
3049 emit_asm(ir, TGSI_OPCODE_MOV, *l, *r);
3050 }
3051 l->index++;
3052 r->index++;
3053 if (type->is_dual_slot()) {
3054 l->index++;
3055 if (r->is_double_vertex_input == false)
3056 r->index++;
3057 }
3058 }
3059
3060 void
3061 glsl_to_tgsi_visitor::visit(ir_assignment *ir)
3062 {
3063 int dst_component;
3064 st_dst_reg l;
3065 st_src_reg r;
3066
3067 /* all generated instructions need to be flaged as precise */
3068 this->precise = is_precise(ir->lhs->variable_referenced());
3069 ir->rhs->accept(this);
3070 r = this->result;
3071
3072 l = get_assignment_lhs(ir->lhs, this, &dst_component);
3073
3074 {
3075 int swizzles[4];
3076 int first_enabled_chan = 0;
3077 int rhs_chan = 0;
3078 ir_variable *variable = ir->lhs->variable_referenced();
3079
3080 if (shader->Stage == MESA_SHADER_FRAGMENT &&
3081 variable->data.mode == ir_var_shader_out &&
3082 (variable->data.location == FRAG_RESULT_DEPTH ||
3083 variable->data.location == FRAG_RESULT_STENCIL)) {
3084 assert(ir->lhs->type->is_scalar());
3085 assert(ir->write_mask == WRITEMASK_X);
3086
3087 if (variable->data.location == FRAG_RESULT_DEPTH)
3088 l.writemask = WRITEMASK_Z;
3089 else {
3090 assert(variable->data.location == FRAG_RESULT_STENCIL);
3091 l.writemask = WRITEMASK_Y;
3092 }
3093 } else if (ir->write_mask == 0) {
3094 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
3095
3096 unsigned num_elements =
3097 ir->lhs->type->without_array()->vector_elements;
3098
3099 if (num_elements) {
3100 l.writemask = u_bit_consecutive(0, num_elements);
3101 } else {
3102 /* The type is a struct or an array of (array of) structs. */
3103 l.writemask = WRITEMASK_XYZW;
3104 }
3105 } else {
3106 l.writemask = ir->write_mask;
3107 }
3108
3109 for (int i = 0; i < 4; i++) {
3110 if (l.writemask & (1 << i)) {
3111 first_enabled_chan = GET_SWZ(r.swizzle, i);
3112 break;
3113 }
3114 }
3115
3116 l.writemask = l.writemask << dst_component;
3117
3118 /* Swizzle a small RHS vector into the channels being written.
3119 *
3120 * glsl ir treats write_mask as dictating how many channels are
3121 * present on the RHS while TGSI treats write_mask as just
3122 * showing which channels of the vec4 RHS get written.
3123 */
3124 for (int i = 0; i < 4; i++) {
3125 if (l.writemask & (1 << i))
3126 swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
3127 else
3128 swizzles[i] = first_enabled_chan;
3129 }
3130 r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
3131 swizzles[2], swizzles[3]);
3132 }
3133
3134 assert(l.file != PROGRAM_UNDEFINED);
3135 assert(r.file != PROGRAM_UNDEFINED);
3136
3137 if (ir->condition) {
3138 const bool switch_order = this->process_move_condition(ir->condition);
3139 st_src_reg condition = this->result;
3140
3141 emit_block_mov(ir, ir->lhs->type, &l, &r, &condition, switch_order);
3142 } else if (ir->rhs->as_expression() &&
3143 this->instructions.get_tail() &&
3144 ir->rhs == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->ir &&
3145 !((glsl_to_tgsi_instruction *)this->instructions.get_tail())->is_64bit_expanded &&
3146 type_size(ir->lhs->type) == 1 &&
3147 l.writemask == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->dst[0].writemask) {
3148 /* To avoid emitting an extra MOV when assigning an expression to a
3149 * variable, emit the last instruction of the expression again, but
3150 * replace the destination register with the target of the assignment.
3151 * Dead code elimination will remove the original instruction.
3152 */
3153 glsl_to_tgsi_instruction *inst, *new_inst;
3154 inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
3155 new_inst = emit_asm(ir, inst->op, l, inst->src[0], inst->src[1], inst->src[2], inst->src[3]);
3156 new_inst->saturate = inst->saturate;
3157 new_inst->resource = inst->resource;
3158 inst->dead_mask = inst->dst[0].writemask;
3159 } else {
3160 emit_block_mov(ir, ir->rhs->type, &l, &r, NULL, false);
3161 }
3162 this->precise = 0;
3163 }
3164
3165
3166 void
3167 glsl_to_tgsi_visitor::visit(ir_constant *ir)
3168 {
3169 st_src_reg src;
3170 GLdouble stack_vals[4] = { 0 };
3171 gl_constant_value *values = (gl_constant_value *) stack_vals;
3172 GLenum gl_type = GL_NONE;
3173 unsigned int i, elements;
3174 static int in_array = 0;
3175 gl_register_file file = in_array ? PROGRAM_CONSTANT : PROGRAM_IMMEDIATE;
3176
3177 /* Unfortunately, 4 floats is all we can get into
3178 * _mesa_add_typed_unnamed_constant. So, make a temp to store an
3179 * aggregate constant and move each constant value into it. If we
3180 * get lucky, copy propagation will eliminate the extra moves.
3181 */
3182 if (ir->type->is_record()) {
3183 st_src_reg temp_base = get_temp(ir->type);
3184 st_dst_reg temp = st_dst_reg(temp_base);
3185
3186 for (i = 0; i < ir->type->length; i++) {
3187 ir_constant *const field_value = ir->get_record_field(i);
3188 int size = type_size(field_value->type);
3189
3190 assert(size > 0);
3191
3192 field_value->accept(this);
3193 src = this->result;
3194
3195 for (unsigned j = 0; j < (unsigned int)size; j++) {
3196 emit_asm(ir, TGSI_OPCODE_MOV, temp, src);
3197
3198 src.index++;
3199 temp.index++;
3200 }
3201 }
3202 this->result = temp_base;
3203 return;
3204 }
3205
3206 if (ir->type->is_array()) {
3207 st_src_reg temp_base = get_temp(ir->type);
3208 st_dst_reg temp = st_dst_reg(temp_base);
3209 int size = type_size(ir->type->fields.array);
3210
3211 assert(size > 0);
3212 in_array++;
3213
3214 for (i = 0; i < ir->type->length; i++) {
3215 ir->const_elements[i]->accept(this);
3216 src = this->result;
3217 for (int j = 0; j < size; j++) {
3218 emit_asm(ir, TGSI_OPCODE_MOV, temp, src);
3219
3220 src.index++;
3221 temp.index++;
3222 }
3223 }
3224 this->result = temp_base;
3225 in_array--;
3226 return;
3227 }
3228
3229 if (ir->type->is_matrix()) {
3230 st_src_reg mat = get_temp(ir->type);
3231 st_dst_reg mat_column = st_dst_reg(mat);
3232
3233 for (i = 0; i < ir->type->matrix_columns; i++) {
3234 switch (ir->type->base_type) {
3235 case GLSL_TYPE_FLOAT:
3236 values = (gl_constant_value *)
3237 &ir->value.f[i * ir->type->vector_elements];
3238
3239 src = st_src_reg(file, -1, ir->type->base_type);
3240 src.index = add_constant(file,
3241 values,
3242 ir->type->vector_elements,
3243 GL_FLOAT,
3244 &src.swizzle);
3245 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3246 break;
3247 case GLSL_TYPE_DOUBLE:
3248 values = (gl_constant_value *)
3249 &ir->value.d[i * ir->type->vector_elements];
3250 src = st_src_reg(file, -1, ir->type->base_type);
3251 src.index = add_constant(file,
3252 values,
3253 ir->type->vector_elements,
3254 GL_DOUBLE,
3255 &src.swizzle);
3256 if (ir->type->vector_elements >= 2) {
3257 mat_column.writemask = WRITEMASK_XY;
3258 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y,
3259 SWIZZLE_X, SWIZZLE_Y);
3260 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3261 } else {
3262 mat_column.writemask = WRITEMASK_X;
3263 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X,
3264 SWIZZLE_X, SWIZZLE_X);
3265 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3266 }
3267 src.index++;
3268 if (ir->type->vector_elements > 2) {
3269 if (ir->type->vector_elements == 4) {
3270 mat_column.writemask = WRITEMASK_ZW;
3271 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y,
3272 SWIZZLE_X, SWIZZLE_Y);
3273 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3274 } else {
3275 mat_column.writemask = WRITEMASK_Z;
3276 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_Y, SWIZZLE_Y,
3277 SWIZZLE_Y, SWIZZLE_Y);
3278 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3279 mat_column.writemask = WRITEMASK_XYZW;
3280 src.swizzle = SWIZZLE_XYZW;
3281 }
3282 mat_column.index++;
3283 }
3284 break;
3285 default:
3286 unreachable("Illegal matrix constant type.\n");
3287 break;
3288 }
3289 mat_column.index++;
3290 }
3291 this->result = mat;
3292 return;
3293 }
3294
3295 elements = ir->type->vector_elements;
3296 switch (ir->type->base_type) {
3297 case GLSL_TYPE_FLOAT:
3298 gl_type = GL_FLOAT;
3299 for (i = 0; i < ir->type->vector_elements; i++) {
3300 values[i].f = ir->value.f[i];
3301 }
3302 break;
3303 case GLSL_TYPE_DOUBLE:
3304 gl_type = GL_DOUBLE;
3305 for (i = 0; i < ir->type->vector_elements; i++) {
3306 memcpy(&values[i * 2], &ir->value.d[i], sizeof(double));
3307 }
3308 break;
3309 case GLSL_TYPE_INT64:
3310 gl_type = GL_INT64_ARB;
3311 for (i = 0; i < ir->type->vector_elements; i++) {
3312 memcpy(&values[i * 2], &ir->value.d[i], sizeof(int64_t));
3313 }
3314 break;
3315 case GLSL_TYPE_UINT64:
3316 gl_type = GL_UNSIGNED_INT64_ARB;
3317 for (i = 0; i < ir->type->vector_elements; i++) {
3318 memcpy(&values[i * 2], &ir->value.d[i], sizeof(uint64_t));
3319 }
3320 break;
3321 case GLSL_TYPE_UINT:
3322 gl_type = native_integers ? GL_UNSIGNED_INT : GL_FLOAT;
3323 for (i = 0; i < ir->type->vector_elements; i++) {
3324 if (native_integers)
3325 values[i].u = ir->value.u[i];
3326 else
3327 values[i].f = ir->value.u[i];
3328 }
3329 break;
3330 case GLSL_TYPE_INT:
3331 gl_type = native_integers ? GL_INT : GL_FLOAT;
3332 for (i = 0; i < ir->type->vector_elements; i++) {
3333 if (native_integers)
3334 values[i].i = ir->value.i[i];
3335 else
3336 values[i].f = ir->value.i[i];
3337 }
3338 break;
3339 case GLSL_TYPE_BOOL:
3340 gl_type = native_integers ? GL_BOOL : GL_FLOAT;
3341 for (i = 0; i < ir->type->vector_elements; i++) {
3342 values[i].u = ir->value.b[i] ? ctx->Const.UniformBooleanTrue : 0;
3343 }
3344 break;
3345 case GLSL_TYPE_SAMPLER:
3346 case GLSL_TYPE_IMAGE:
3347 gl_type = GL_UNSIGNED_INT;
3348 elements = 2;
3349 values[0].u = ir->value.u64[0] & 0xffffffff;
3350 values[1].u = ir->value.u64[0] >> 32;
3351 break;
3352 default:
3353 assert(!"Non-float/uint/int/bool/sampler/image constant");
3354 }
3355
3356 this->result = st_src_reg(file, -1, ir->type);
3357 this->result.index = add_constant(file,
3358 values,
3359 elements,
3360 gl_type,
3361 &this->result.swizzle);
3362 }
3363
3364 void
3365 glsl_to_tgsi_visitor::visit_atomic_counter_intrinsic(ir_call *ir)
3366 {
3367 exec_node *param = ir->actual_parameters.get_head();
3368 ir_dereference *deref = static_cast<ir_dereference *>(param);
3369 ir_variable *location = deref->variable_referenced();
3370 bool has_hw_atomics = st_context(ctx)->has_hw_atomics;
3371 /* Calculate the surface offset */
3372 st_src_reg offset;
3373 unsigned array_size = 0, base = 0;
3374 uint16_t index = 0;
3375 st_src_reg resource;
3376
3377 get_deref_offsets(deref, &array_size, &base, &index, &offset, false);
3378
3379 if (has_hw_atomics) {
3380 variable_storage *entry = find_variable_storage(location);
3381 st_src_reg buffer(PROGRAM_HW_ATOMIC, 0, GLSL_TYPE_ATOMIC_UINT,
3382 location->data.binding);
3383
3384 if (!entry) {
3385 entry = new(mem_ctx) variable_storage(location, PROGRAM_HW_ATOMIC,
3386 num_atomics);
3387 _mesa_hash_table_insert(this->variables, location, entry);
3388
3389 atomic_info[num_atomics].location = location->data.location;
3390 atomic_info[num_atomics].binding = location->data.binding;
3391 atomic_info[num_atomics].size = location->type->arrays_of_arrays_size();
3392 if (atomic_info[num_atomics].size == 0)
3393 atomic_info[num_atomics].size = 1;
3394 atomic_info[num_atomics].array_id = 0;
3395 num_atomics++;
3396 }
3397
3398 if (offset.file != PROGRAM_UNDEFINED) {
3399 if (atomic_info[entry->index].array_id == 0) {
3400 num_atomic_arrays++;
3401 atomic_info[entry->index].array_id = num_atomic_arrays;
3402 }
3403 buffer.array_id = atomic_info[entry->index].array_id;
3404 }
3405
3406 buffer.index = index;
3407 buffer.index += location->data.offset / ATOMIC_COUNTER_SIZE;
3408 buffer.has_index2 = true;
3409
3410 if (offset.file != PROGRAM_UNDEFINED) {
3411 buffer.reladdr = ralloc(mem_ctx, st_src_reg);
3412 *buffer.reladdr = offset;
3413 emit_arl(ir, sampler_reladdr, offset);
3414 }
3415 offset = st_src_reg_for_int(0);
3416
3417 resource = buffer;
3418 } else {
3419 st_src_reg buffer(PROGRAM_BUFFER, location->data.binding,
3420 GLSL_TYPE_ATOMIC_UINT);
3421
3422 if (offset.file != PROGRAM_UNDEFINED) {
3423 emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(offset),
3424 offset, st_src_reg_for_int(ATOMIC_COUNTER_SIZE));
3425 emit_asm(ir, TGSI_OPCODE_ADD, st_dst_reg(offset),
3426 offset, st_src_reg_for_int(location->data.offset + index * ATOMIC_COUNTER_SIZE));
3427 } else {
3428 offset = st_src_reg_for_int(location->data.offset + index * ATOMIC_COUNTER_SIZE);
3429 }
3430 resource = buffer;
3431 }
3432
3433 ir->return_deref->accept(this);
3434 st_dst_reg dst(this->result);
3435 dst.writemask = WRITEMASK_X;
3436
3437 glsl_to_tgsi_instruction *inst;
3438
3439 if (ir->callee->intrinsic_id == ir_intrinsic_atomic_counter_read) {
3440 inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, offset);
3441 } else if (ir->callee->intrinsic_id == ir_intrinsic_atomic_counter_increment) {
3442 inst = emit_asm(ir, TGSI_OPCODE_ATOMUADD, dst, offset,
3443 st_src_reg_for_int(1));
3444 } else if (ir->callee->intrinsic_id == ir_intrinsic_atomic_counter_predecrement) {
3445 inst = emit_asm(ir, TGSI_OPCODE_ATOMUADD, dst, offset,
3446 st_src_reg_for_int(-1));
3447 emit_asm(ir, TGSI_OPCODE_ADD, dst, this->result, st_src_reg_for_int(-1));
3448 } else {
3449 param = param->get_next();
3450 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3451 val->accept(this);
3452
3453 st_src_reg data = this->result, data2 = undef_src;
3454 enum tgsi_opcode opcode;
3455 switch (ir->callee->intrinsic_id) {
3456 case ir_intrinsic_atomic_counter_add:
3457 opcode = TGSI_OPCODE_ATOMUADD;
3458 break;
3459 case ir_intrinsic_atomic_counter_min:
3460 opcode = TGSI_OPCODE_ATOMIMIN;
3461 break;
3462 case ir_intrinsic_atomic_counter_max:
3463 opcode = TGSI_OPCODE_ATOMIMAX;
3464 break;
3465 case ir_intrinsic_atomic_counter_and:
3466 opcode = TGSI_OPCODE_ATOMAND;
3467 break;
3468 case ir_intrinsic_atomic_counter_or:
3469 opcode = TGSI_OPCODE_ATOMOR;
3470 break;
3471 case ir_intrinsic_atomic_counter_xor:
3472 opcode = TGSI_OPCODE_ATOMXOR;
3473 break;
3474 case ir_intrinsic_atomic_counter_exchange:
3475 opcode = TGSI_OPCODE_ATOMXCHG;
3476 break;
3477 case ir_intrinsic_atomic_counter_comp_swap: {
3478 opcode = TGSI_OPCODE_ATOMCAS;
3479 param = param->get_next();
3480 val = ((ir_instruction *)param)->as_rvalue();
3481 val->accept(this);
3482 data2 = this->result;
3483 break;
3484 }
3485 default:
3486 assert(!"Unexpected intrinsic");
3487 return;
3488 }
3489
3490 inst = emit_asm(ir, opcode, dst, offset, data, data2);
3491 }
3492
3493 inst->resource = resource;
3494 }
3495
3496 void
3497 glsl_to_tgsi_visitor::visit_ssbo_intrinsic(ir_call *ir)
3498 {
3499 exec_node *param = ir->actual_parameters.get_head();
3500
3501 ir_rvalue *block = ((ir_instruction *)param)->as_rvalue();
3502
3503 param = param->get_next();
3504 ir_rvalue *offset = ((ir_instruction *)param)->as_rvalue();
3505
3506 ir_constant *const_block = block->as_constant();
3507 int buf_base = st_context(ctx)->has_hw_atomics
3508 ? 0 : ctx->Const.Program[shader->Stage].MaxAtomicBuffers;
3509 st_src_reg buffer(
3510 PROGRAM_BUFFER,
3511 buf_base + (const_block ? const_block->value.u[0] : 0),
3512 GLSL_TYPE_UINT);
3513
3514 if (!const_block) {
3515 block->accept(this);
3516 buffer.reladdr = ralloc(mem_ctx, st_src_reg);
3517 *buffer.reladdr = this->result;
3518 emit_arl(ir, sampler_reladdr, this->result);
3519 }
3520
3521 /* Calculate the surface offset */
3522 offset->accept(this);
3523 st_src_reg off = this->result;
3524
3525 st_dst_reg dst = undef_dst;
3526 if (ir->return_deref) {
3527 ir->return_deref->accept(this);
3528 dst = st_dst_reg(this->result);
3529 dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3530 }
3531
3532 glsl_to_tgsi_instruction *inst;
3533
3534 if (ir->callee->intrinsic_id == ir_intrinsic_ssbo_load) {
3535 inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, off);
3536 if (dst.type == GLSL_TYPE_BOOL)
3537 emit_asm(ir, TGSI_OPCODE_USNE, dst, st_src_reg(dst),
3538 st_src_reg_for_int(0));
3539 } else if (ir->callee->intrinsic_id == ir_intrinsic_ssbo_store) {
3540 param = param->get_next();
3541 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3542 val->accept(this);
3543
3544 param = param->get_next();
3545 ir_constant *write_mask = ((ir_instruction *)param)->as_constant();
3546 assert(write_mask);
3547 dst.writemask = write_mask->value.u[0];
3548
3549 dst.type = this->result.type;
3550 inst = emit_asm(ir, TGSI_OPCODE_STORE, dst, off, this->result);
3551 } else {
3552 param = param->get_next();
3553 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3554 val->accept(this);
3555
3556 st_src_reg data = this->result, data2 = undef_src;
3557 enum tgsi_opcode opcode;
3558 switch (ir->callee->intrinsic_id) {
3559 case ir_intrinsic_ssbo_atomic_add:
3560 opcode = TGSI_OPCODE_ATOMUADD;
3561 break;
3562 case ir_intrinsic_ssbo_atomic_min:
3563 opcode = TGSI_OPCODE_ATOMIMIN;
3564 break;
3565 case ir_intrinsic_ssbo_atomic_max:
3566 opcode = TGSI_OPCODE_ATOMIMAX;
3567 break;
3568 case ir_intrinsic_ssbo_atomic_and:
3569 opcode = TGSI_OPCODE_ATOMAND;
3570 break;
3571 case ir_intrinsic_ssbo_atomic_or:
3572 opcode = TGSI_OPCODE_ATOMOR;
3573 break;
3574 case ir_intrinsic_ssbo_atomic_xor:
3575 opcode = TGSI_OPCODE_ATOMXOR;
3576 break;
3577 case ir_intrinsic_ssbo_atomic_exchange:
3578 opcode = TGSI_OPCODE_ATOMXCHG;
3579 break;
3580 case ir_intrinsic_ssbo_atomic_comp_swap:
3581 opcode = TGSI_OPCODE_ATOMCAS;
3582 param = param->get_next();
3583 val = ((ir_instruction *)param)->as_rvalue();
3584 val->accept(this);
3585 data2 = this->result;
3586 break;
3587 default:
3588 assert(!"Unexpected intrinsic");
3589 return;
3590 }
3591
3592 inst = emit_asm(ir, opcode, dst, off, data, data2);
3593 }
3594
3595 param = param->get_next();
3596 ir_constant *access = NULL;
3597 if (!param->is_tail_sentinel()) {
3598 access = ((ir_instruction *)param)->as_constant();
3599 assert(access);
3600 }
3601
3602 add_buffer_to_load_and_stores(inst, &buffer, &this->instructions, access);
3603 }
3604
3605 void
3606 glsl_to_tgsi_visitor::visit_membar_intrinsic(ir_call *ir)
3607 {
3608 switch (ir->callee->intrinsic_id) {
3609 case ir_intrinsic_memory_barrier:
3610 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3611 st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER |
3612 TGSI_MEMBAR_ATOMIC_BUFFER |
3613 TGSI_MEMBAR_SHADER_IMAGE |
3614 TGSI_MEMBAR_SHARED));
3615 break;
3616 case ir_intrinsic_memory_barrier_atomic_counter:
3617 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3618 st_src_reg_for_int(TGSI_MEMBAR_ATOMIC_BUFFER));
3619 break;
3620 case ir_intrinsic_memory_barrier_buffer:
3621 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3622 st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER));
3623 break;
3624 case ir_intrinsic_memory_barrier_image:
3625 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3626 st_src_reg_for_int(TGSI_MEMBAR_SHADER_IMAGE));
3627 break;
3628 case ir_intrinsic_memory_barrier_shared:
3629 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3630 st_src_reg_for_int(TGSI_MEMBAR_SHARED));
3631 break;
3632 case ir_intrinsic_group_memory_barrier:
3633 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3634 st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER |
3635 TGSI_MEMBAR_ATOMIC_BUFFER |
3636 TGSI_MEMBAR_SHADER_IMAGE |
3637 TGSI_MEMBAR_SHARED |
3638 TGSI_MEMBAR_THREAD_GROUP));
3639 break;
3640 default:
3641 assert(!"Unexpected memory barrier intrinsic");
3642 }
3643 }
3644
3645 void
3646 glsl_to_tgsi_visitor::visit_shared_intrinsic(ir_call *ir)
3647 {
3648 exec_node *param = ir->actual_parameters.get_head();
3649
3650 ir_rvalue *offset = ((ir_instruction *)param)->as_rvalue();
3651
3652 st_src_reg buffer(PROGRAM_MEMORY, 0, GLSL_TYPE_UINT);
3653
3654 /* Calculate the surface offset */
3655 offset->accept(this);
3656 st_src_reg off = this->result;
3657
3658 st_dst_reg dst = undef_dst;
3659 if (ir->return_deref) {
3660 ir->return_deref->accept(this);
3661 dst = st_dst_reg(this->result);
3662 dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3663 }
3664
3665 glsl_to_tgsi_instruction *inst;
3666
3667 if (ir->callee->intrinsic_id == ir_intrinsic_shared_load) {
3668 inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, off);
3669 inst->resource = buffer;
3670 } else if (ir->callee->intrinsic_id == ir_intrinsic_shared_store) {
3671 param = param->get_next();
3672 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3673 val->accept(this);
3674
3675 param = param->get_next();
3676 ir_constant *write_mask = ((ir_instruction *)param)->as_constant();
3677 assert(write_mask);
3678 dst.writemask = write_mask->value.u[0];
3679
3680 dst.type = this->result.type;
3681 inst = emit_asm(ir, TGSI_OPCODE_STORE, dst, off, this->result);
3682 inst->resource = buffer;
3683 } else {
3684 param = param->get_next();
3685 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3686 val->accept(this);
3687
3688 st_src_reg data = this->result, data2 = undef_src;
3689 enum tgsi_opcode opcode;
3690 switch (ir->callee->intrinsic_id) {
3691 case ir_intrinsic_shared_atomic_add:
3692 opcode = TGSI_OPCODE_ATOMUADD;
3693 break;
3694 case ir_intrinsic_shared_atomic_min:
3695 opcode = TGSI_OPCODE_ATOMIMIN;
3696 break;
3697 case ir_intrinsic_shared_atomic_max:
3698 opcode = TGSI_OPCODE_ATOMIMAX;
3699 break;
3700 case ir_intrinsic_shared_atomic_and:
3701 opcode = TGSI_OPCODE_ATOMAND;
3702 break;
3703 case ir_intrinsic_shared_atomic_or:
3704 opcode = TGSI_OPCODE_ATOMOR;
3705 break;
3706 case ir_intrinsic_shared_atomic_xor:
3707 opcode = TGSI_OPCODE_ATOMXOR;
3708 break;
3709 case ir_intrinsic_shared_atomic_exchange:
3710 opcode = TGSI_OPCODE_ATOMXCHG;
3711 break;
3712 case ir_intrinsic_shared_atomic_comp_swap:
3713 opcode = TGSI_OPCODE_ATOMCAS;
3714 param = param->get_next();
3715 val = ((ir_instruction *)param)->as_rvalue();
3716 val->accept(this);
3717 data2 = this->result;
3718 break;
3719 default:
3720 assert(!"Unexpected intrinsic");
3721 return;
3722 }
3723
3724 inst = emit_asm(ir, opcode, dst, off, data, data2);
3725 inst->resource = buffer;
3726 }
3727 }
3728
3729 static void
3730 get_image_qualifiers(ir_dereference *ir, const glsl_type **type,
3731 bool *memory_coherent, bool *memory_volatile,
3732 bool *memory_restrict, bool *memory_read_only,
3733 unsigned *image_format)
3734 {
3735
3736 switch (ir->ir_type) {
3737 case ir_type_dereference_record: {
3738 ir_dereference_record *deref_record = ir->as_dereference_record();
3739 const glsl_type *struct_type = deref_record->record->type;
3740 int fild_idx = deref_record->field_idx;
3741
3742 *type = struct_type->fields.structure[fild_idx].type->without_array();
3743 *memory_coherent =
3744 struct_type->fields.structure[fild_idx].memory_coherent;
3745 *memory_volatile =
3746 struct_type->fields.structure[fild_idx].memory_volatile;
3747 *memory_restrict =
3748 struct_type->fields.structure[fild_idx].memory_restrict;
3749 *memory_read_only =
3750 struct_type->fields.structure[fild_idx].memory_read_only;
3751 *image_format =
3752 struct_type->fields.structure[fild_idx].image_format;
3753 break;
3754 }
3755
3756 case ir_type_dereference_array: {
3757 ir_dereference_array *deref_arr = ir->as_dereference_array();
3758 get_image_qualifiers((ir_dereference *)deref_arr->array, type,
3759 memory_coherent, memory_volatile, memory_restrict,
3760 memory_read_only, image_format);
3761 break;
3762 }
3763
3764 case ir_type_dereference_variable: {
3765 ir_variable *var = ir->variable_referenced();
3766
3767 *type = var->type->without_array();
3768 *memory_coherent = var->data.memory_coherent;
3769 *memory_volatile = var->data.memory_volatile;
3770 *memory_restrict = var->data.memory_restrict;
3771 *memory_read_only = var->data.memory_read_only;
3772 *image_format = var->data.image_format;
3773 break;
3774 }
3775
3776 default:
3777 break;
3778 }
3779 }
3780
3781 void
3782 glsl_to_tgsi_visitor::visit_image_intrinsic(ir_call *ir)
3783 {
3784 exec_node *param = ir->actual_parameters.get_head();
3785
3786 ir_dereference *img = (ir_dereference *)param;
3787 const ir_variable *imgvar = img->variable_referenced();
3788 unsigned sampler_array_size = 1, sampler_base = 0;
3789 bool memory_coherent = false, memory_volatile = false,
3790 memory_restrict = false, memory_read_only = false;
3791 unsigned image_format = 0;
3792 const glsl_type *type = NULL;
3793
3794 get_image_qualifiers(img, &type, &memory_coherent, &memory_volatile,
3795 &memory_restrict, &memory_read_only, &image_format);
3796
3797 st_src_reg reladdr;
3798 st_src_reg image(PROGRAM_IMAGE, 0, GLSL_TYPE_UINT);
3799 uint16_t index = 0;
3800 get_deref_offsets(img, &sampler_array_size, &sampler_base,
3801 &index, &reladdr, !imgvar->contains_bindless());
3802
3803 image.index = index;
3804 if (reladdr.file != PROGRAM_UNDEFINED) {
3805 image.reladdr = ralloc(mem_ctx, st_src_reg);
3806 *image.reladdr = reladdr;
3807 emit_arl(ir, sampler_reladdr, reladdr);
3808 }
3809
3810 st_dst_reg dst = undef_dst;
3811 if (ir->return_deref) {
3812 ir->return_deref->accept(this);
3813 dst = st_dst_reg(this->result);
3814 dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3815 }
3816
3817 glsl_to_tgsi_instruction *inst;
3818
3819 st_src_reg bindless;
3820 if (imgvar->contains_bindless()) {
3821 img->accept(this);
3822 bindless = this->result;
3823 }
3824
3825 if (ir->callee->intrinsic_id == ir_intrinsic_image_size) {
3826 dst.writemask = WRITEMASK_XYZ;
3827 inst = emit_asm(ir, TGSI_OPCODE_RESQ, dst);
3828 } else if (ir->callee->intrinsic_id == ir_intrinsic_image_samples) {
3829 st_src_reg res = get_temp(glsl_type::ivec4_type);
3830 st_dst_reg dstres = st_dst_reg(res);
3831 dstres.writemask = WRITEMASK_W;
3832 inst = emit_asm(ir, TGSI_OPCODE_RESQ, dstres);
3833 res.swizzle = SWIZZLE_WWWW;
3834 emit_asm(ir, TGSI_OPCODE_MOV, dst, res);
3835 } else {
3836 st_src_reg arg1 = undef_src, arg2 = undef_src;
3837 st_src_reg coord;
3838 st_dst_reg coord_dst;
3839 coord = get_temp(glsl_type::ivec4_type);
3840 coord_dst = st_dst_reg(coord);
3841 coord_dst.writemask = (1 << type->coordinate_components()) - 1;
3842 param = param->get_next();
3843 ((ir_dereference *)param)->accept(this);
3844 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
3845 coord.swizzle = SWIZZLE_XXXX;
3846 switch (type->coordinate_components()) {
3847 case 4: assert(!"unexpected coord count");
3848 /* fallthrough */
3849 case 3: coord.swizzle |= SWIZZLE_Z << 6;
3850 /* fallthrough */
3851 case 2: coord.swizzle |= SWIZZLE_Y << 3;
3852 }
3853
3854 if (type->sampler_dimensionality == GLSL_SAMPLER_DIM_MS) {
3855 param = param->get_next();
3856 ((ir_dereference *)param)->accept(this);
3857 st_src_reg sample = this->result;
3858 sample.swizzle = SWIZZLE_XXXX;
3859 coord_dst.writemask = WRITEMASK_W;
3860 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, sample);
3861 coord.swizzle |= SWIZZLE_W << 9;
3862 }
3863
3864 param = param->get_next();
3865 if (!param->is_tail_sentinel()) {
3866 ((ir_dereference *)param)->accept(this);
3867 arg1 = this->result;
3868 param = param->get_next();
3869 }
3870
3871 if (!param->is_tail_sentinel()) {
3872 ((ir_dereference *)param)->accept(this);
3873 arg2 = this->result;
3874 param = param->get_next();
3875 }
3876
3877 assert(param->is_tail_sentinel());
3878
3879 enum tgsi_opcode opcode;
3880 switch (ir->callee->intrinsic_id) {
3881 case ir_intrinsic_image_load:
3882 opcode = TGSI_OPCODE_LOAD;
3883 break;
3884 case ir_intrinsic_image_store:
3885 opcode = TGSI_OPCODE_STORE;
3886 break;
3887 case ir_intrinsic_image_atomic_add:
3888 opcode = TGSI_OPCODE_ATOMUADD;
3889 break;
3890 case ir_intrinsic_image_atomic_min:
3891 opcode = TGSI_OPCODE_ATOMIMIN;
3892 break;
3893 case ir_intrinsic_image_atomic_max:
3894 opcode = TGSI_OPCODE_ATOMIMAX;
3895 break;
3896 case ir_intrinsic_image_atomic_and:
3897 opcode = TGSI_OPCODE_ATOMAND;
3898 break;
3899 case ir_intrinsic_image_atomic_or:
3900 opcode = TGSI_OPCODE_ATOMOR;
3901 break;
3902 case ir_intrinsic_image_atomic_xor:
3903 opcode = TGSI_OPCODE_ATOMXOR;
3904 break;
3905 case ir_intrinsic_image_atomic_exchange:
3906 opcode = TGSI_OPCODE_ATOMXCHG;
3907 break;
3908 case ir_intrinsic_image_atomic_comp_swap:
3909 opcode = TGSI_OPCODE_ATOMCAS;
3910 break;
3911 default:
3912 assert(!"Unexpected intrinsic");
3913 return;
3914 }
3915
3916 inst = emit_asm(ir, opcode, dst, coord, arg1, arg2);
3917 if (opcode == TGSI_OPCODE_STORE)
3918 inst->dst[0].writemask = WRITEMASK_XYZW;
3919 }
3920
3921 if (imgvar->contains_bindless()) {
3922 inst->resource = bindless;
3923 inst->resource.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y,
3924 SWIZZLE_X, SWIZZLE_Y);
3925 } else {
3926 inst->resource = image;
3927 inst->sampler_array_size = sampler_array_size;
3928 inst->sampler_base = sampler_base;
3929 }
3930
3931 inst->tex_target = type->sampler_index();
3932 inst->image_format = st_mesa_format_to_pipe_format(st_context(ctx),
3933 _mesa_get_shader_image_format(image_format));
3934 inst->read_only = memory_read_only;
3935
3936 if (memory_coherent)
3937 inst->buffer_access |= TGSI_MEMORY_COHERENT;
3938 if (memory_restrict)
3939 inst->buffer_access |= TGSI_MEMORY_RESTRICT;
3940 if (memory_volatile)
3941 inst->buffer_access |= TGSI_MEMORY_VOLATILE;
3942 }
3943
3944 void
3945 glsl_to_tgsi_visitor::visit_generic_intrinsic(ir_call *ir, enum tgsi_opcode op)
3946 {
3947 ir->return_deref->accept(this);
3948 st_dst_reg dst = st_dst_reg(this->result);
3949
3950 dst.writemask = u_bit_consecutive(0, ir->return_deref->var->type->vector_elements);
3951
3952 st_src_reg src[4] = { undef_src, undef_src, undef_src, undef_src };
3953 unsigned num_src = 0;
3954 foreach_in_list(ir_rvalue, param, &ir->actual_parameters) {
3955 assert(num_src < ARRAY_SIZE(src));
3956
3957 this->result.file = PROGRAM_UNDEFINED;
3958 param->accept(this);
3959 assert(this->result.file != PROGRAM_UNDEFINED);
3960
3961 src[num_src] = this->result;
3962 num_src++;
3963 }
3964
3965 emit_asm(ir, op, dst, src[0], src[1], src[2], src[3]);
3966 }
3967
3968 void
3969 glsl_to_tgsi_visitor::visit(ir_call *ir)
3970 {
3971 ir_function_signature *sig = ir->callee;
3972
3973 /* Filter out intrinsics */
3974 switch (sig->intrinsic_id) {
3975 case ir_intrinsic_atomic_counter_read:
3976 case ir_intrinsic_atomic_counter_increment:
3977 case ir_intrinsic_atomic_counter_predecrement:
3978 case ir_intrinsic_atomic_counter_add:
3979 case ir_intrinsic_atomic_counter_min:
3980 case ir_intrinsic_atomic_counter_max:
3981 case ir_intrinsic_atomic_counter_and:
3982 case ir_intrinsic_atomic_counter_or:
3983 case ir_intrinsic_atomic_counter_xor:
3984 case ir_intrinsic_atomic_counter_exchange:
3985 case ir_intrinsic_atomic_counter_comp_swap:
3986 visit_atomic_counter_intrinsic(ir);
3987 return;
3988
3989 case ir_intrinsic_ssbo_load:
3990 case ir_intrinsic_ssbo_store:
3991 case ir_intrinsic_ssbo_atomic_add:
3992 case ir_intrinsic_ssbo_atomic_min:
3993 case ir_intrinsic_ssbo_atomic_max:
3994 case ir_intrinsic_ssbo_atomic_and:
3995 case ir_intrinsic_ssbo_atomic_or:
3996 case ir_intrinsic_ssbo_atomic_xor:
3997 case ir_intrinsic_ssbo_atomic_exchange:
3998 case ir_intrinsic_ssbo_atomic_comp_swap:
3999 visit_ssbo_intrinsic(ir);
4000 return;
4001
4002 case ir_intrinsic_memory_barrier:
4003 case ir_intrinsic_memory_barrier_atomic_counter:
4004 case ir_intrinsic_memory_barrier_buffer:
4005 case ir_intrinsic_memory_barrier_image:
4006 case ir_intrinsic_memory_barrier_shared:
4007 case ir_intrinsic_group_memory_barrier:
4008 visit_membar_intrinsic(ir);
4009 return;
4010
4011 case ir_intrinsic_shared_load:
4012 case ir_intrinsic_shared_store:
4013 case ir_intrinsic_shared_atomic_add:
4014 case ir_intrinsic_shared_atomic_min:
4015 case ir_intrinsic_shared_atomic_max:
4016 case ir_intrinsic_shared_atomic_and:
4017 case ir_intrinsic_shared_atomic_or:
4018 case ir_intrinsic_shared_atomic_xor:
4019 case ir_intrinsic_shared_atomic_exchange:
4020 case ir_intrinsic_shared_atomic_comp_swap:
4021 visit_shared_intrinsic(ir);
4022 return;
4023
4024 case ir_intrinsic_image_load:
4025 case ir_intrinsic_image_store:
4026 case ir_intrinsic_image_atomic_add:
4027 case ir_intrinsic_image_atomic_min:
4028 case ir_intrinsic_image_atomic_max:
4029 case ir_intrinsic_image_atomic_and:
4030 case ir_intrinsic_image_atomic_or:
4031 case ir_intrinsic_image_atomic_xor:
4032 case ir_intrinsic_image_atomic_exchange:
4033 case ir_intrinsic_image_atomic_comp_swap:
4034 case ir_intrinsic_image_size:
4035 case ir_intrinsic_image_samples:
4036 visit_image_intrinsic(ir);
4037 return;
4038
4039 case ir_intrinsic_shader_clock:
4040 visit_generic_intrinsic(ir, TGSI_OPCODE_CLOCK);
4041 return;
4042
4043 case ir_intrinsic_vote_all:
4044 visit_generic_intrinsic(ir, TGSI_OPCODE_VOTE_ALL);
4045 return;
4046 case ir_intrinsic_vote_any:
4047 visit_generic_intrinsic(ir, TGSI_OPCODE_VOTE_ANY);
4048 return;
4049 case ir_intrinsic_vote_eq:
4050 visit_generic_intrinsic(ir, TGSI_OPCODE_VOTE_EQ);
4051 return;
4052 case ir_intrinsic_ballot:
4053 visit_generic_intrinsic(ir, TGSI_OPCODE_BALLOT);
4054 return;
4055 case ir_intrinsic_read_first_invocation:
4056 visit_generic_intrinsic(ir, TGSI_OPCODE_READ_FIRST);
4057 return;
4058 case ir_intrinsic_read_invocation:
4059 visit_generic_intrinsic(ir, TGSI_OPCODE_READ_INVOC);
4060 return;
4061
4062 case ir_intrinsic_invalid:
4063 case ir_intrinsic_generic_load:
4064 case ir_intrinsic_generic_store:
4065 case ir_intrinsic_generic_atomic_add:
4066 case ir_intrinsic_generic_atomic_and:
4067 case ir_intrinsic_generic_atomic_or:
4068 case ir_intrinsic_generic_atomic_xor:
4069 case ir_intrinsic_generic_atomic_min:
4070 case ir_intrinsic_generic_atomic_max:
4071 case ir_intrinsic_generic_atomic_exchange:
4072 case ir_intrinsic_generic_atomic_comp_swap:
4073 case ir_intrinsic_begin_invocation_interlock:
4074 case ir_intrinsic_end_invocation_interlock:
4075 case ir_intrinsic_begin_fragment_shader_ordering:
4076 unreachable("Invalid intrinsic");
4077 }
4078 }
4079
4080 void
4081 glsl_to_tgsi_visitor::calc_deref_offsets(ir_dereference *tail,
4082 unsigned *array_elements,
4083 uint16_t *index,
4084 st_src_reg *indirect,
4085 unsigned *location)
4086 {
4087 switch (tail->ir_type) {
4088 case ir_type_dereference_record: {
4089 ir_dereference_record *deref_record = tail->as_dereference_record();
4090 const glsl_type *struct_type = deref_record->record->type;
4091 int field_index = deref_record->field_idx;
4092
4093 calc_deref_offsets(deref_record->record->as_dereference(), array_elements, index, indirect, location);
4094
4095 assert(field_index >= 0);
4096 *location += struct_type->record_location_offset(field_index);
4097 break;
4098 }
4099
4100 case ir_type_dereference_array: {
4101 ir_dereference_array *deref_arr = tail->as_dereference_array();
4102
4103 void *mem_ctx = ralloc_parent(deref_arr);
4104 ir_constant *array_index =
4105 deref_arr->array_index->constant_expression_value(mem_ctx);
4106
4107 if (!array_index) {
4108 st_src_reg temp_reg;
4109 st_dst_reg temp_dst;
4110
4111 temp_reg = get_temp(glsl_type::uint_type);
4112 temp_dst = st_dst_reg(temp_reg);
4113 temp_dst.writemask = 1;
4114
4115 deref_arr->array_index->accept(this);
4116 if (*array_elements != 1)
4117 emit_asm(NULL, TGSI_OPCODE_MUL, temp_dst, this->result, st_src_reg_for_int(*array_elements));
4118 else
4119 emit_asm(NULL, TGSI_OPCODE_MOV, temp_dst, this->result);
4120
4121 if (indirect->file == PROGRAM_UNDEFINED)
4122 *indirect = temp_reg;
4123 else {
4124 temp_dst = st_dst_reg(*indirect);
4125 temp_dst.writemask = 1;
4126 emit_asm(NULL, TGSI_OPCODE_ADD, temp_dst, *indirect, temp_reg);
4127 }
4128 } else
4129 *index += array_index->value.u[0] * *array_elements;
4130
4131 *array_elements *= deref_arr->array->type->length;
4132
4133 calc_deref_offsets(deref_arr->array->as_dereference(), array_elements, index, indirect, location);
4134 break;
4135 }
4136 default:
4137 break;
4138 }
4139 }
4140
4141 void
4142 glsl_to_tgsi_visitor::get_deref_offsets(ir_dereference *ir,
4143 unsigned *array_size,
4144 unsigned *base,
4145 uint16_t *index,
4146 st_src_reg *reladdr,
4147 bool opaque)
4148 {
4149 GLuint shader = _mesa_program_enum_to_shader_stage(this->prog->Target);
4150 unsigned location = 0;
4151 ir_variable *var = ir->variable_referenced();
4152
4153 reladdr->reset();
4154
4155 *base = 0;
4156 *array_size = 1;
4157
4158 assert(var);
4159 location = var->data.location;
4160 calc_deref_offsets(ir, array_size, index, reladdr, &location);
4161
4162 /*
4163 * If we end up with no indirect then adjust the base to the index,
4164 * and set the array size to 1.
4165 */
4166 if (reladdr->file == PROGRAM_UNDEFINED) {
4167 *base = *index;
4168 *array_size = 1;
4169 }
4170
4171 if (opaque) {
4172 assert(location != 0xffffffff);
4173 *base += this->shader_program->data->UniformStorage[location].opaque[shader].index;
4174 *index += this->shader_program->data->UniformStorage[location].opaque[shader].index;
4175 }
4176 }
4177
4178 st_src_reg
4179 glsl_to_tgsi_visitor::canonicalize_gather_offset(st_src_reg offset)
4180 {
4181 if (offset.reladdr || offset.reladdr2 ||
4182 offset.has_index2 ||
4183 offset.file == PROGRAM_UNIFORM ||
4184 offset.file == PROGRAM_CONSTANT ||
4185 offset.file == PROGRAM_STATE_VAR) {
4186 st_src_reg tmp = get_temp(glsl_type::ivec2_type);
4187 st_dst_reg tmp_dst = st_dst_reg(tmp);
4188 tmp_dst.writemask = WRITEMASK_XY;
4189 emit_asm(NULL, TGSI_OPCODE_MOV, tmp_dst, offset);
4190 return tmp;
4191 }
4192
4193 return offset;
4194 }
4195
4196 bool
4197 glsl_to_tgsi_visitor::handle_bound_deref(ir_dereference *ir)
4198 {
4199 ir_variable *var = ir->variable_referenced();
4200
4201 if (!var || var->data.mode != ir_var_uniform || var->data.bindless ||
4202 !(ir->type->is_image() || ir->type->is_sampler()))
4203 return false;
4204
4205 /* Convert from bound sampler/image to bindless handle. */
4206 bool is_image = ir->type->is_image();
4207 st_src_reg resource(is_image ? PROGRAM_IMAGE : PROGRAM_SAMPLER, 0, GLSL_TYPE_UINT);
4208 uint16_t index = 0;
4209 unsigned array_size = 1, base = 0;
4210 st_src_reg reladdr;
4211 get_deref_offsets(ir, &array_size, &base, &index, &reladdr, true);
4212
4213 resource.index = index;
4214 if (reladdr.file != PROGRAM_UNDEFINED) {
4215 resource.reladdr = ralloc(mem_ctx, st_src_reg);
4216 *resource.reladdr = reladdr;
4217 emit_arl(ir, sampler_reladdr, reladdr);
4218 }
4219
4220 this->result = get_temp(glsl_type::uvec2_type);
4221 st_dst_reg dst(this->result);
4222 dst.writemask = WRITEMASK_XY;
4223
4224 glsl_to_tgsi_instruction *inst = emit_asm(
4225 ir, is_image ? TGSI_OPCODE_IMG2HND : TGSI_OPCODE_SAMP2HND, dst);
4226
4227 inst->tex_target = ir->type->sampler_index();
4228 inst->resource = resource;
4229 inst->sampler_array_size = array_size;
4230 inst->sampler_base = base;
4231
4232 return true;
4233 }
4234
4235 void
4236 glsl_to_tgsi_visitor::visit(ir_texture *ir)
4237 {
4238 st_src_reg result_src, coord, cube_sc, lod_info, projector, dx, dy;
4239 st_src_reg offset[MAX_GLSL_TEXTURE_OFFSET], sample_index, component;
4240 st_src_reg levels_src, reladdr;
4241 st_dst_reg result_dst, coord_dst, cube_sc_dst;
4242 glsl_to_tgsi_instruction *inst = NULL;
4243 enum tgsi_opcode opcode = TGSI_OPCODE_NOP;
4244 const glsl_type *sampler_type = ir->sampler->type;
4245 unsigned sampler_array_size = 1, sampler_base = 0;
4246 bool is_cube_array = false, is_cube_shadow = false;
4247 ir_variable *var = ir->sampler->variable_referenced();
4248 unsigned i;
4249
4250 /* if we are a cube array sampler or a cube shadow */
4251 if (sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE) {
4252 is_cube_array = sampler_type->sampler_array;
4253 is_cube_shadow = sampler_type->sampler_shadow;
4254 }
4255
4256 if (ir->coordinate) {
4257 ir->coordinate->accept(this);
4258
4259 /* Put our coords in a temp. We'll need to modify them for shadow,
4260 * projection, or LOD, so the only case we'd use it as-is is if
4261 * we're doing plain old texturing. The optimization passes on
4262 * glsl_to_tgsi_visitor should handle cleaning up our mess in that case.
4263 */
4264 coord = get_temp(glsl_type::vec4_type);
4265 coord_dst = st_dst_reg(coord);
4266 coord_dst.writemask = (1 << ir->coordinate->type->vector_elements) - 1;
4267 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
4268 }
4269
4270 if (ir->projector) {
4271 ir->projector->accept(this);
4272 projector = this->result;
4273 }
4274
4275 /* Storage for our result. Ideally for an assignment we'd be using
4276 * the actual storage for the result here, instead.
4277 */
4278 result_src = get_temp(ir->type);
4279 result_dst = st_dst_reg(result_src);
4280 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
4281
4282 switch (ir->op) {
4283 case ir_tex:
4284 opcode = (is_cube_array && ir->shadow_comparator) ? TGSI_OPCODE_TEX2 : TGSI_OPCODE_TEX;
4285 if (ir->offset) {
4286 ir->offset->accept(this);
4287 offset[0] = this->result;
4288 }
4289 break;
4290 case ir_txb:
4291 if (is_cube_array || is_cube_shadow) {
4292 opcode = TGSI_OPCODE_TXB2;
4293 }
4294 else {
4295 opcode = TGSI_OPCODE_TXB;
4296 }
4297 ir->lod_info.bias->accept(this);
4298 lod_info = this->result;
4299 if (ir->offset) {
4300 ir->offset->accept(this);
4301 offset[0] = this->result;
4302 }
4303 break;
4304 case ir_txl:
4305 if (this->has_tex_txf_lz && ir->lod_info.lod->is_zero()) {
4306 opcode = TGSI_OPCODE_TEX_LZ;
4307 } else {
4308 opcode = is_cube_array ? TGSI_OPCODE_TXL2 : TGSI_OPCODE_TXL;
4309 ir->lod_info.lod->accept(this);
4310 lod_info = this->result;
4311 }
4312 if (ir->offset) {
4313 ir->offset->accept(this);
4314 offset[0] = this->result;
4315 }
4316 break;
4317 case ir_txd:
4318 opcode = TGSI_OPCODE_TXD;
4319 ir->lod_info.grad.dPdx->accept(this);
4320 dx = this->result;
4321 ir->lod_info.grad.dPdy->accept(this);
4322 dy = this->result;
4323 if (ir->offset) {
4324 ir->offset->accept(this);
4325 offset[0] = this->result;
4326 }
4327 break;
4328 case ir_txs:
4329 opcode = TGSI_OPCODE_TXQ;
4330 ir->lod_info.lod->accept(this);
4331 lod_info = this->result;
4332 break;
4333 case ir_query_levels:
4334 opcode = TGSI_OPCODE_TXQ;
4335 lod_info = undef_src;
4336 levels_src = get_temp(ir->type);
4337 break;
4338 case ir_txf:
4339 if (this->has_tex_txf_lz && ir->lod_info.lod->is_zero()) {
4340 opcode = TGSI_OPCODE_TXF_LZ;
4341 } else {
4342 opcode = TGSI_OPCODE_TXF;
4343 ir->lod_info.lod->accept(this);
4344 lod_info = this->result;
4345 }
4346 if (ir->offset) {
4347 ir->offset->accept(this);
4348 offset[0] = this->result;
4349 }
4350 break;
4351 case ir_txf_ms:
4352 opcode = TGSI_OPCODE_TXF;
4353 ir->lod_info.sample_index->accept(this);
4354 sample_index = this->result;
4355 break;
4356 case ir_tg4:
4357 opcode = TGSI_OPCODE_TG4;
4358 ir->lod_info.component->accept(this);
4359 component = this->result;
4360 if (ir->offset) {
4361 ir->offset->accept(this);
4362 if (ir->offset->type->is_array()) {
4363 const glsl_type *elt_type = ir->offset->type->fields.array;
4364 for (i = 0; i < ir->offset->type->length; i++) {
4365 offset[i] = this->result;
4366 offset[i].index += i * type_size(elt_type);
4367 offset[i].type = elt_type->base_type;
4368 offset[i].swizzle = swizzle_for_size(elt_type->vector_elements);
4369 offset[i] = canonicalize_gather_offset(offset[i]);
4370 }
4371 } else {
4372 offset[0] = canonicalize_gather_offset(this->result);
4373 }
4374 }
4375 break;
4376 case ir_lod:
4377 opcode = TGSI_OPCODE_LODQ;
4378 break;
4379 case ir_texture_samples:
4380 opcode = TGSI_OPCODE_TXQS;
4381 break;
4382 case ir_samples_identical:
4383 unreachable("Unexpected ir_samples_identical opcode");
4384 }
4385
4386 if (ir->projector) {
4387 if (opcode == TGSI_OPCODE_TEX) {
4388 /* Slot the projector in as the last component of the coord. */
4389 coord_dst.writemask = WRITEMASK_W;
4390 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, projector);
4391 coord_dst.writemask = WRITEMASK_XYZW;
4392 opcode = TGSI_OPCODE_TXP;
4393 } else {
4394 st_src_reg coord_w = coord;
4395 coord_w.swizzle = SWIZZLE_WWWW;
4396
4397 /* For the other TEX opcodes there's no projective version
4398 * since the last slot is taken up by LOD info. Do the
4399 * projective divide now.
4400 */
4401 coord_dst.writemask = WRITEMASK_W;
4402 emit_asm(ir, TGSI_OPCODE_RCP, coord_dst, projector);
4403
4404 /* In the case where we have to project the coordinates "by hand,"
4405 * the shadow comparator value must also be projected.
4406 */
4407 st_src_reg tmp_src = coord;
4408 if (ir->shadow_comparator) {
4409 /* Slot the shadow value in as the second to last component of the
4410 * coord.
4411 */
4412 ir->shadow_comparator->accept(this);
4413
4414 tmp_src = get_temp(glsl_type::vec4_type);
4415 st_dst_reg tmp_dst = st_dst_reg(tmp_src);
4416
4417 /* Projective division not allowed for array samplers. */
4418 assert(!sampler_type->sampler_array);
4419
4420 tmp_dst.writemask = WRITEMASK_Z;
4421 emit_asm(ir, TGSI_OPCODE_MOV, tmp_dst, this->result);
4422
4423 tmp_dst.writemask = WRITEMASK_XY;
4424 emit_asm(ir, TGSI_OPCODE_MOV, tmp_dst, coord);
4425 }
4426
4427 coord_dst.writemask = WRITEMASK_XYZ;
4428 emit_asm(ir, TGSI_OPCODE_MUL, coord_dst, tmp_src, coord_w);
4429
4430 coord_dst.writemask = WRITEMASK_XYZW;
4431 coord.swizzle = SWIZZLE_XYZW;
4432 }
4433 }
4434
4435 /* If projection is done and the opcode is not TGSI_OPCODE_TXP, then the
4436 * shadow comparator was put in the correct place (and projected) by the
4437 * code, above, that handles by-hand projection.
4438 */
4439 if (ir->shadow_comparator && (!ir->projector || opcode == TGSI_OPCODE_TXP)) {
4440 /* Slot the shadow value in as the second to last component of the
4441 * coord.
4442 */
4443 ir->shadow_comparator->accept(this);
4444
4445 if (is_cube_array) {
4446 cube_sc = get_temp(glsl_type::float_type);
4447 cube_sc_dst = st_dst_reg(cube_sc);
4448 cube_sc_dst.writemask = WRITEMASK_X;
4449 emit_asm(ir, TGSI_OPCODE_MOV, cube_sc_dst, this->result);
4450 cube_sc_dst.writemask = WRITEMASK_X;
4451 }
4452 else {
4453 if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_2D &&
4454 sampler_type->sampler_array) ||
4455 sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE) {
4456 coord_dst.writemask = WRITEMASK_W;
4457 } else {
4458 coord_dst.writemask = WRITEMASK_Z;
4459 }
4460 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
4461 coord_dst.writemask = WRITEMASK_XYZW;
4462 }
4463 }
4464
4465 if (ir->op == ir_txf_ms) {
4466 coord_dst.writemask = WRITEMASK_W;
4467 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, sample_index);
4468 coord_dst.writemask = WRITEMASK_XYZW;
4469 } else if (opcode == TGSI_OPCODE_TXL || opcode == TGSI_OPCODE_TXB ||
4470 opcode == TGSI_OPCODE_TXF) {
4471 /* TGSI stores LOD or LOD bias in the last channel of the coords. */
4472 coord_dst.writemask = WRITEMASK_W;
4473 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, lod_info);
4474 coord_dst.writemask = WRITEMASK_XYZW;
4475 }
4476
4477 st_src_reg sampler(PROGRAM_SAMPLER, 0, GLSL_TYPE_UINT);
4478
4479 uint16_t index = 0;
4480 get_deref_offsets(ir->sampler, &sampler_array_size, &sampler_base,
4481 &index, &reladdr, !var->contains_bindless());
4482
4483 sampler.index = index;
4484 if (reladdr.file != PROGRAM_UNDEFINED) {
4485 sampler.reladdr = ralloc(mem_ctx, st_src_reg);
4486 *sampler.reladdr = reladdr;
4487 emit_arl(ir, sampler_reladdr, reladdr);
4488 }
4489
4490 st_src_reg bindless;
4491 if (var->contains_bindless()) {
4492 ir->sampler->accept(this);
4493 bindless = this->result;
4494 }
4495
4496 if (opcode == TGSI_OPCODE_TXD)
4497 inst = emit_asm(ir, opcode, result_dst, coord, dx, dy);
4498 else if (opcode == TGSI_OPCODE_TXQ) {
4499 if (ir->op == ir_query_levels) {
4500 /* the level is stored in W */
4501 inst = emit_asm(ir, opcode, st_dst_reg(levels_src), lod_info);
4502 result_dst.writemask = WRITEMASK_X;
4503 levels_src.swizzle = SWIZZLE_WWWW;
4504 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, levels_src);
4505 } else
4506 inst = emit_asm(ir, opcode, result_dst, lod_info);
4507 } else if (opcode == TGSI_OPCODE_TXQS) {
4508 inst = emit_asm(ir, opcode, result_dst);
4509 } else if (opcode == TGSI_OPCODE_TXL2 || opcode == TGSI_OPCODE_TXB2) {
4510 inst = emit_asm(ir, opcode, result_dst, coord, lod_info);
4511 } else if (opcode == TGSI_OPCODE_TEX2) {
4512 inst = emit_asm(ir, opcode, result_dst, coord, cube_sc);
4513 } else if (opcode == TGSI_OPCODE_TG4) {
4514 if (is_cube_array && ir->shadow_comparator) {
4515 inst = emit_asm(ir, opcode, result_dst, coord, cube_sc);
4516 } else {
4517 inst = emit_asm(ir, opcode, result_dst, coord, component);
4518 }
4519 } else
4520 inst = emit_asm(ir, opcode, result_dst, coord);
4521
4522 if (ir->shadow_comparator)
4523 inst->tex_shadow = GL_TRUE;
4524
4525 if (var->contains_bindless()) {
4526 inst->resource = bindless;
4527 inst->resource.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y,
4528 SWIZZLE_X, SWIZZLE_Y);
4529 } else {
4530 inst->resource = sampler;
4531 inst->sampler_array_size = sampler_array_size;
4532 inst->sampler_base = sampler_base;
4533 }
4534
4535 if (ir->offset) {
4536 if (!inst->tex_offsets)
4537 inst->tex_offsets = rzalloc_array(inst, st_src_reg,
4538 MAX_GLSL_TEXTURE_OFFSET);
4539
4540 for (i = 0; i < MAX_GLSL_TEXTURE_OFFSET &&
4541 offset[i].file != PROGRAM_UNDEFINED; i++)
4542 inst->tex_offsets[i] = offset[i];
4543 inst->tex_offset_num_offset = i;
4544 }
4545
4546 inst->tex_target = sampler_type->sampler_index();
4547 inst->tex_type = ir->type->base_type;
4548
4549 this->result = result_src;
4550 }
4551
4552 void
4553 glsl_to_tgsi_visitor::visit(ir_return *ir)
4554 {
4555 assert(!ir->get_value());
4556
4557 emit_asm(ir, TGSI_OPCODE_RET);
4558 }
4559
4560 void
4561 glsl_to_tgsi_visitor::visit(ir_discard *ir)
4562 {
4563 if (ir->condition) {
4564 ir->condition->accept(this);
4565 st_src_reg condition = this->result;
4566
4567 /* Convert the bool condition to a float so we can negate. */
4568 if (native_integers) {
4569 st_src_reg temp = get_temp(ir->condition->type);
4570 emit_asm(ir, TGSI_OPCODE_AND, st_dst_reg(temp),
4571 condition, st_src_reg_for_float(1.0));
4572 condition = temp;
4573 }
4574
4575 condition.negate = ~condition.negate;
4576 emit_asm(ir, TGSI_OPCODE_KILL_IF, undef_dst, condition);
4577 } else {
4578 /* unconditional kil */
4579 emit_asm(ir, TGSI_OPCODE_KILL);
4580 }
4581 }
4582
4583 void
4584 glsl_to_tgsi_visitor::visit(ir_if *ir)
4585 {
4586 enum tgsi_opcode if_opcode;
4587 glsl_to_tgsi_instruction *if_inst;
4588
4589 ir->condition->accept(this);
4590 assert(this->result.file != PROGRAM_UNDEFINED);
4591
4592 if_opcode = native_integers ? TGSI_OPCODE_UIF : TGSI_OPCODE_IF;
4593
4594 if_inst = emit_asm(ir->condition, if_opcode, undef_dst, this->result);
4595
4596 this->instructions.push_tail(if_inst);
4597
4598 visit_exec_list(&ir->then_instructions, this);
4599
4600 if (!ir->else_instructions.is_empty()) {
4601 emit_asm(ir->condition, TGSI_OPCODE_ELSE);
4602 visit_exec_list(&ir->else_instructions, this);
4603 }
4604
4605 if_inst = emit_asm(ir->condition, TGSI_OPCODE_ENDIF);
4606 }
4607
4608
4609 void
4610 glsl_to_tgsi_visitor::visit(ir_emit_vertex *ir)
4611 {
4612 assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
4613
4614 ir->stream->accept(this);
4615 emit_asm(ir, TGSI_OPCODE_EMIT, undef_dst, this->result);
4616 }
4617
4618 void
4619 glsl_to_tgsi_visitor::visit(ir_end_primitive *ir)
4620 {
4621 assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
4622
4623 ir->stream->accept(this);
4624 emit_asm(ir, TGSI_OPCODE_ENDPRIM, undef_dst, this->result);
4625 }
4626
4627 void
4628 glsl_to_tgsi_visitor::visit(ir_barrier *ir)
4629 {
4630 assert(this->prog->Target == GL_TESS_CONTROL_PROGRAM_NV ||
4631 this->prog->Target == GL_COMPUTE_PROGRAM_NV);
4632
4633 emit_asm(ir, TGSI_OPCODE_BARRIER);
4634 }
4635
4636 glsl_to_tgsi_visitor::glsl_to_tgsi_visitor()
4637 {
4638 STATIC_ASSERT(sizeof(samplers_used) * 8 >= PIPE_MAX_SAMPLERS);
4639
4640 result.file = PROGRAM_UNDEFINED;
4641 next_temp = 1;
4642 array_sizes = NULL;
4643 max_num_arrays = 0;
4644 next_array = 0;
4645 num_inputs = 0;
4646 num_outputs = 0;
4647 num_input_arrays = 0;
4648 num_output_arrays = 0;
4649 num_atomics = 0;
4650 num_atomic_arrays = 0;
4651 num_immediates = 0;
4652 num_address_regs = 0;
4653 samplers_used = 0;
4654 images_used = 0;
4655 indirect_addr_consts = false;
4656 wpos_transform_const = -1;
4657 native_integers = false;
4658 mem_ctx = ralloc_context(NULL);
4659 ctx = NULL;
4660 prog = NULL;
4661 precise = 0;
4662 need_uarl = false;
4663 shader_program = NULL;
4664 shader = NULL;
4665 options = NULL;
4666 have_sqrt = false;
4667 have_fma = false;
4668 use_shared_memory = false;
4669 has_tex_txf_lz = false;
4670 variables = NULL;
4671 }
4672
4673 static void var_destroy(struct hash_entry *entry)
4674 {
4675 variable_storage *storage = (variable_storage *)entry->data;
4676
4677 delete storage;
4678 }
4679
4680 glsl_to_tgsi_visitor::~glsl_to_tgsi_visitor()
4681 {
4682 _mesa_hash_table_destroy(variables, var_destroy);
4683 free(array_sizes);
4684 ralloc_free(mem_ctx);
4685 }
4686
4687 extern "C" void free_glsl_to_tgsi_visitor(glsl_to_tgsi_visitor *v)
4688 {
4689 delete v;
4690 }
4691
4692
4693 /**
4694 * Count resources used by the given gpu program (number of texture
4695 * samplers, etc).
4696 */
4697 static void
4698 count_resources(glsl_to_tgsi_visitor *v, gl_program *prog)
4699 {
4700 v->samplers_used = 0;
4701 v->images_used = 0;
4702 prog->info.textures_used_by_txf = 0;
4703
4704 foreach_in_list(glsl_to_tgsi_instruction, inst, &v->instructions) {
4705 if (inst->info->is_tex) {
4706 for (int i = 0; i < inst->sampler_array_size; i++) {
4707 unsigned idx = inst->sampler_base + i;
4708 v->samplers_used |= 1u << idx;
4709
4710 debug_assert(idx < (int)ARRAY_SIZE(v->sampler_types));
4711 v->sampler_types[idx] = inst->tex_type;
4712 v->sampler_targets[idx] =
4713 st_translate_texture_target(inst->tex_target, inst->tex_shadow);
4714
4715 if (inst->op == TGSI_OPCODE_TXF || inst->op == TGSI_OPCODE_TXF_LZ) {
4716 prog->info.textures_used_by_txf |= 1u << idx;
4717 }
4718 }
4719 }
4720
4721 if (inst->tex_target == TEXTURE_EXTERNAL_INDEX)
4722 prog->ExternalSamplersUsed |= 1 << inst->resource.index;
4723
4724 if (inst->resource.file != PROGRAM_UNDEFINED && (
4725 is_resource_instruction(inst->op) ||
4726 inst->op == TGSI_OPCODE_STORE)) {
4727 if (inst->resource.file == PROGRAM_MEMORY) {
4728 v->use_shared_memory = true;
4729 } else if (inst->resource.file == PROGRAM_IMAGE) {
4730 for (int i = 0; i < inst->sampler_array_size; i++) {
4731 unsigned idx = inst->sampler_base + i;
4732 v->images_used |= 1 << idx;
4733 v->image_targets[idx] =
4734 st_translate_texture_target(inst->tex_target, false);
4735 v->image_formats[idx] = inst->image_format;
4736 v->image_wr[idx] = !inst->read_only;
4737 }
4738 }
4739 }
4740 }
4741 prog->SamplersUsed = v->samplers_used;
4742
4743 if (v->shader_program != NULL)
4744 _mesa_update_shader_textures_used(v->shader_program, prog);
4745 }
4746
4747 /**
4748 * Returns the mask of channels (bitmask of WRITEMASK_X,Y,Z,W) which
4749 * are read from the given src in this instruction
4750 */
4751 static int
4752 get_src_arg_mask(st_dst_reg dst, st_src_reg src)
4753 {
4754 int read_mask = 0, comp;
4755
4756 /* Now, given the src swizzle and the written channels, find which
4757 * components are actually read
4758 */
4759 for (comp = 0; comp < 4; ++comp) {
4760 const unsigned coord = GET_SWZ(src.swizzle, comp);
4761 assert(coord < 4);
4762 if (dst.writemask & (1 << comp) && coord <= SWIZZLE_W)
4763 read_mask |= 1 << coord;
4764 }
4765
4766 return read_mask;
4767 }
4768
4769 /**
4770 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
4771 * instruction is the first instruction to write to register T0. There are
4772 * several lowering passes done in GLSL IR (e.g. branches and
4773 * relative addressing) that create a large number of conditional assignments
4774 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
4775 *
4776 * Here is why this conversion is safe:
4777 * CMP T0, T1 T2 T0 can be expanded to:
4778 * if (T1 < 0.0)
4779 * MOV T0, T2;
4780 * else
4781 * MOV T0, T0;
4782 *
4783 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
4784 * as the original program. If (T1 < 0.0) evaluates to false, executing
4785 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
4786 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
4787 * because any instruction that was going to read from T0 after this was going
4788 * to read a garbage value anyway.
4789 */
4790 void
4791 glsl_to_tgsi_visitor::simplify_cmp(void)
4792 {
4793 int tempWritesSize = 0;
4794 unsigned *tempWrites = NULL;
4795 unsigned outputWrites[VARYING_SLOT_TESS_MAX];
4796
4797 memset(outputWrites, 0, sizeof(outputWrites));
4798
4799 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4800 unsigned prevWriteMask = 0;
4801
4802 /* Give up if we encounter relative addressing or flow control. */
4803 if (inst->dst[0].reladdr || inst->dst[0].reladdr2 ||
4804 inst->dst[1].reladdr || inst->dst[1].reladdr2 ||
4805 inst->info->is_branch ||
4806 inst->op == TGSI_OPCODE_CONT ||
4807 inst->op == TGSI_OPCODE_END ||
4808 inst->op == TGSI_OPCODE_RET) {
4809 break;
4810 }
4811
4812 if (inst->dst[0].file == PROGRAM_OUTPUT) {
4813 assert(inst->dst[0].index < (signed)ARRAY_SIZE(outputWrites));
4814 prevWriteMask = outputWrites[inst->dst[0].index];
4815 outputWrites[inst->dst[0].index] |= inst->dst[0].writemask;
4816 } else if (inst->dst[0].file == PROGRAM_TEMPORARY) {
4817 if (inst->dst[0].index >= tempWritesSize) {
4818 const int inc = 4096;
4819
4820 tempWrites = (unsigned*)
4821 realloc(tempWrites,
4822 (tempWritesSize + inc) * sizeof(unsigned));
4823 if (!tempWrites)
4824 return;
4825
4826 memset(tempWrites + tempWritesSize, 0, inc * sizeof(unsigned));
4827 tempWritesSize += inc;
4828 }
4829
4830 prevWriteMask = tempWrites[inst->dst[0].index];
4831 tempWrites[inst->dst[0].index] |= inst->dst[0].writemask;
4832 } else
4833 continue;
4834
4835 /* For a CMP to be considered a conditional write, the destination
4836 * register and source register two must be the same. */
4837 if (inst->op == TGSI_OPCODE_CMP
4838 && !(inst->dst[0].writemask & prevWriteMask)
4839 && inst->src[2].file == inst->dst[0].file
4840 && inst->src[2].index == inst->dst[0].index
4841 && inst->dst[0].writemask ==
4842 get_src_arg_mask(inst->dst[0], inst->src[2])) {
4843
4844 inst->op = TGSI_OPCODE_MOV;
4845 inst->info = tgsi_get_opcode_info(inst->op);
4846 inst->src[0] = inst->src[1];
4847 }
4848 }
4849
4850 free(tempWrites);
4851 }
4852
4853 static void
4854 rename_temp_handle_src(struct rename_reg_pair *renames, st_src_reg *src)
4855 {
4856 if (src && src->file == PROGRAM_TEMPORARY) {
4857 int old_idx = src->index;
4858 if (renames[old_idx].valid)
4859 src->index = renames[old_idx].new_reg;
4860 }
4861 }
4862
4863 /* Replaces all references to a temporary register index with another index. */
4864 void
4865 glsl_to_tgsi_visitor::rename_temp_registers(struct rename_reg_pair *renames)
4866 {
4867 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4868 unsigned j;
4869 for (j = 0; j < num_inst_src_regs(inst); j++) {
4870 rename_temp_handle_src(renames, &inst->src[j]);
4871 rename_temp_handle_src(renames, inst->src[j].reladdr);
4872 rename_temp_handle_src(renames, inst->src[j].reladdr2);
4873 }
4874
4875 for (j = 0; j < inst->tex_offset_num_offset; j++) {
4876 rename_temp_handle_src(renames, &inst->tex_offsets[j]);
4877 rename_temp_handle_src(renames, inst->tex_offsets[j].reladdr);
4878 rename_temp_handle_src(renames, inst->tex_offsets[j].reladdr2);
4879 }
4880
4881 rename_temp_handle_src(renames, &inst->resource);
4882 rename_temp_handle_src(renames, inst->resource.reladdr);
4883 rename_temp_handle_src(renames, inst->resource.reladdr2);
4884
4885 for (j = 0; j < num_inst_dst_regs(inst); j++) {
4886 if (inst->dst[j].file == PROGRAM_TEMPORARY) {
4887 int old_idx = inst->dst[j].index;
4888 if (renames[old_idx].valid)
4889 inst->dst[j].index = renames[old_idx].new_reg;
4890 }
4891 rename_temp_handle_src(renames, inst->dst[j].reladdr);
4892 rename_temp_handle_src(renames, inst->dst[j].reladdr2);
4893 }
4894 }
4895 }
4896
4897 void
4898 glsl_to_tgsi_visitor::get_first_temp_write(int *first_writes)
4899 {
4900 int depth = 0; /* loop depth */
4901 int loop_start = -1; /* index of the first active BGNLOOP (if any) */
4902 unsigned i = 0, j;
4903
4904 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4905 for (j = 0; j < num_inst_dst_regs(inst); j++) {
4906 if (inst->dst[j].file == PROGRAM_TEMPORARY) {
4907 if (first_writes[inst->dst[j].index] == -1)
4908 first_writes[inst->dst[j].index] = (depth == 0) ? i : loop_start;
4909 }
4910 }
4911
4912 if (inst->op == TGSI_OPCODE_BGNLOOP) {
4913 if (depth++ == 0)
4914 loop_start = i;
4915 } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
4916 if (--depth == 0)
4917 loop_start = -1;
4918 }
4919 assert(depth >= 0);
4920 i++;
4921 }
4922 }
4923
4924 void
4925 glsl_to_tgsi_visitor::get_first_temp_read(int *first_reads)
4926 {
4927 int depth = 0; /* loop depth */
4928 int loop_start = -1; /* index of the first active BGNLOOP (if any) */
4929 unsigned i = 0, j;
4930
4931 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4932 for (j = 0; j < num_inst_src_regs(inst); j++) {
4933 if (inst->src[j].file == PROGRAM_TEMPORARY) {
4934 if (first_reads[inst->src[j].index] == -1)
4935 first_reads[inst->src[j].index] = (depth == 0) ? i : loop_start;
4936 }
4937 }
4938 for (j = 0; j < inst->tex_offset_num_offset; j++) {
4939 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY) {
4940 if (first_reads[inst->tex_offsets[j].index] == -1)
4941 first_reads[inst->tex_offsets[j].index] = (depth == 0) ? i : loop_start;
4942 }
4943 }
4944 if (inst->op == TGSI_OPCODE_BGNLOOP) {
4945 if (depth++ == 0)
4946 loop_start = i;
4947 } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
4948 if (--depth == 0)
4949 loop_start = -1;
4950 }
4951 assert(depth >= 0);
4952 i++;
4953 }
4954 }
4955
4956 void
4957 glsl_to_tgsi_visitor::get_last_temp_read_first_temp_write(int *last_reads, int *first_writes)
4958 {
4959 int depth = 0; /* loop depth */
4960 int loop_start = -1; /* index of the first active BGNLOOP (if any) */
4961 unsigned i = 0, j;
4962 int k;
4963 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4964 for (j = 0; j < num_inst_src_regs(inst); j++) {
4965 if (inst->src[j].file == PROGRAM_TEMPORARY)
4966 last_reads[inst->src[j].index] = (depth == 0) ? i : -2;
4967 }
4968 for (j = 0; j < num_inst_dst_regs(inst); j++) {
4969 if (inst->dst[j].file == PROGRAM_TEMPORARY) {
4970 if (first_writes[inst->dst[j].index] == -1)
4971 first_writes[inst->dst[j].index] = (depth == 0) ? i : loop_start;
4972 last_reads[inst->dst[j].index] = (depth == 0) ? i : -2;
4973 }
4974 }
4975 for (j = 0; j < inst->tex_offset_num_offset; j++) {
4976 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY)
4977 last_reads[inst->tex_offsets[j].index] = (depth == 0) ? i : -2;
4978 }
4979 if (inst->op == TGSI_OPCODE_BGNLOOP) {
4980 if (depth++ == 0)
4981 loop_start = i;
4982 } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
4983 if (--depth == 0) {
4984 loop_start = -1;
4985 for (k = 0; k < this->next_temp; k++) {
4986 if (last_reads[k] == -2) {
4987 last_reads[k] = i;
4988 }
4989 }
4990 }
4991 }
4992 assert(depth >= 0);
4993 i++;
4994 }
4995 }
4996
4997 void
4998 glsl_to_tgsi_visitor::get_last_temp_write(int *last_writes)
4999 {
5000 int depth = 0; /* loop depth */
5001 int i = 0, k;
5002 unsigned j;
5003
5004 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
5005 for (j = 0; j < num_inst_dst_regs(inst); j++) {
5006 if (inst->dst[j].file == PROGRAM_TEMPORARY)
5007 last_writes[inst->dst[j].index] = (depth == 0) ? i : -2;
5008 }
5009
5010 if (inst->op == TGSI_OPCODE_BGNLOOP)
5011 depth++;
5012 else if (inst->op == TGSI_OPCODE_ENDLOOP)
5013 if (--depth == 0) {
5014 for (k = 0; k < this->next_temp; k++) {
5015 if (last_writes[k] == -2) {
5016 last_writes[k] = i;
5017 }
5018 }
5019 }
5020 assert(depth >= 0);
5021 i++;
5022 }
5023 }
5024
5025 /*
5026 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
5027 * channels for copy propagation and updates following instructions to
5028 * use the original versions.
5029 *
5030 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
5031 * will occur. As an example, a TXP production before this pass:
5032 *
5033 * 0: MOV TEMP[1], INPUT[4].xyyy;
5034 * 1: MOV TEMP[1].w, INPUT[4].wwww;
5035 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
5036 *
5037 * and after:
5038 *
5039 * 0: MOV TEMP[1], INPUT[4].xyyy;
5040 * 1: MOV TEMP[1].w, INPUT[4].wwww;
5041 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
5042 *
5043 * which allows for dead code elimination on TEMP[1]'s writes.
5044 */
5045 void
5046 glsl_to_tgsi_visitor::copy_propagate(void)
5047 {
5048 glsl_to_tgsi_instruction **acp = rzalloc_array(mem_ctx,
5049 glsl_to_tgsi_instruction *,
5050 this->next_temp * 4);
5051 int *acp_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
5052 int level = 0;
5053
5054 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
5055 assert(inst->dst[0].file != PROGRAM_TEMPORARY
5056 || inst->dst[0].index < this->next_temp);
5057
5058 /* First, do any copy propagation possible into the src regs. */
5059 for (int r = 0; r < 3; r++) {
5060 glsl_to_tgsi_instruction *first = NULL;
5061 bool good = true;
5062 int acp_base = inst->src[r].index * 4;
5063
5064 if (inst->src[r].file != PROGRAM_TEMPORARY ||
5065 inst->src[r].reladdr ||
5066 inst->src[r].reladdr2)
5067 continue;
5068
5069 /* See if we can find entries in the ACP consisting of MOVs
5070 * from the same src register for all the swizzled channels
5071 * of this src register reference.
5072 */
5073 for (int i = 0; i < 4; i++) {
5074 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
5075 glsl_to_tgsi_instruction *copy_chan = acp[acp_base + src_chan];
5076
5077 if (!copy_chan) {
5078 good = false;
5079 break;
5080 }
5081
5082 assert(acp_level[acp_base + src_chan] <= level);
5083
5084 if (!first) {
5085 first = copy_chan;
5086 } else {
5087 if (first->src[0].file != copy_chan->src[0].file ||
5088 first->src[0].index != copy_chan->src[0].index ||
5089 first->src[0].double_reg2 != copy_chan->src[0].double_reg2 ||
5090 first->src[0].index2D != copy_chan->src[0].index2D) {
5091 good = false;
5092 break;
5093 }
5094 }
5095 }
5096
5097 if (good) {
5098 /* We've now validated that we can copy-propagate to
5099 * replace this src register reference. Do it.
5100 */
5101 inst->src[r].file = first->src[0].file;
5102 inst->src[r].index = first->src[0].index;
5103 inst->src[r].index2D = first->src[0].index2D;
5104 inst->src[r].has_index2 = first->src[0].has_index2;
5105 inst->src[r].double_reg2 = first->src[0].double_reg2;
5106 inst->src[r].array_id = first->src[0].array_id;
5107
5108 int swizzle = 0;
5109 for (int i = 0; i < 4; i++) {
5110 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
5111 glsl_to_tgsi_instruction *copy_inst = acp[acp_base + src_chan];
5112 swizzle |= (GET_SWZ(copy_inst->src[0].swizzle, src_chan) << (3 * i));
5113 }
5114 inst->src[r].swizzle = swizzle;
5115 }
5116 }
5117
5118 switch (inst->op) {
5119 case TGSI_OPCODE_BGNLOOP:
5120 case TGSI_OPCODE_ENDLOOP:
5121 /* End of a basic block, clear the ACP entirely. */
5122 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
5123 break;
5124
5125 case TGSI_OPCODE_IF:
5126 case TGSI_OPCODE_UIF:
5127 ++level;
5128 break;
5129
5130 case TGSI_OPCODE_ENDIF:
5131 case TGSI_OPCODE_ELSE:
5132 /* Clear all channels written inside the block from the ACP, but
5133 * leaving those that were not touched.
5134 */
5135 for (int r = 0; r < this->next_temp; r++) {
5136 for (int c = 0; c < 4; c++) {
5137 if (!acp[4 * r + c])
5138 continue;
5139
5140 if (acp_level[4 * r + c] >= level)
5141 acp[4 * r + c] = NULL;
5142 }
5143 }
5144 if (inst->op == TGSI_OPCODE_ENDIF)
5145 --level;
5146 break;
5147
5148 default:
5149 /* Continuing the block, clear any written channels from
5150 * the ACP.
5151 */
5152 for (int d = 0; d < 2; d++) {
5153 if (inst->dst[d].file == PROGRAM_TEMPORARY && inst->dst[d].reladdr) {
5154 /* Any temporary might be written, so no copy propagation
5155 * across this instruction.
5156 */
5157 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
5158 } else if (inst->dst[d].file == PROGRAM_OUTPUT &&
5159 inst->dst[d].reladdr) {
5160 /* Any output might be written, so no copy propagation
5161 * from outputs across this instruction.
5162 */
5163 for (int r = 0; r < this->next_temp; r++) {
5164 for (int c = 0; c < 4; c++) {
5165 if (!acp[4 * r + c])
5166 continue;
5167
5168 if (acp[4 * r + c]->src[0].file == PROGRAM_OUTPUT)
5169 acp[4 * r + c] = NULL;
5170 }
5171 }
5172 } else if (inst->dst[d].file == PROGRAM_TEMPORARY ||
5173 inst->dst[d].file == PROGRAM_OUTPUT) {
5174 /* Clear where it's used as dst. */
5175 if (inst->dst[d].file == PROGRAM_TEMPORARY) {
5176 for (int c = 0; c < 4; c++) {
5177 if (inst->dst[d].writemask & (1 << c))
5178 acp[4 * inst->dst[d].index + c] = NULL;
5179 }
5180 }
5181
5182 /* Clear where it's used as src. */
5183 for (int r = 0; r < this->next_temp; r++) {
5184 for (int c = 0; c < 4; c++) {
5185 if (!acp[4 * r + c])
5186 continue;
5187
5188 int src_chan = GET_SWZ(acp[4 * r + c]->src[0].swizzle, c);
5189
5190 if (acp[4 * r + c]->src[0].file == inst->dst[d].file &&
5191 acp[4 * r + c]->src[0].index == inst->dst[d].index &&
5192 inst->dst[d].writemask & (1 << src_chan)) {
5193 acp[4 * r + c] = NULL;
5194 }
5195 }
5196 }
5197 }
5198 }
5199 break;
5200 }
5201
5202 /* If this is a copy, add it to the ACP. */
5203 if (inst->op == TGSI_OPCODE_MOV &&
5204 inst->dst[0].file == PROGRAM_TEMPORARY &&
5205 !(inst->dst[0].file == inst->src[0].file &&
5206 inst->dst[0].index == inst->src[0].index) &&
5207 !inst->dst[0].reladdr &&
5208 !inst->dst[0].reladdr2 &&
5209 !inst->saturate &&
5210 inst->src[0].file != PROGRAM_ARRAY &&
5211 (inst->src[0].file != PROGRAM_OUTPUT ||
5212 this->shader->Stage != MESA_SHADER_TESS_CTRL) &&
5213 !inst->src[0].reladdr &&
5214 !inst->src[0].reladdr2 &&
5215 !inst->src[0].negate &&
5216 !inst->src[0].abs) {
5217 for (int i = 0; i < 4; i++) {
5218 if (inst->dst[0].writemask & (1 << i)) {
5219 acp[4 * inst->dst[0].index + i] = inst;
5220 acp_level[4 * inst->dst[0].index + i] = level;
5221 }
5222 }
5223 }
5224 }
5225
5226 ralloc_free(acp_level);
5227 ralloc_free(acp);
5228 }
5229
5230 static void
5231 dead_code_handle_reladdr(glsl_to_tgsi_instruction **writes, st_src_reg *reladdr)
5232 {
5233 if (reladdr && reladdr->file == PROGRAM_TEMPORARY) {
5234 /* Clear where it's used as src. */
5235 int swz = GET_SWZ(reladdr->swizzle, 0);
5236 writes[4 * reladdr->index + swz] = NULL;
5237 }
5238 }
5239
5240 /*
5241 * On a basic block basis, tracks available PROGRAM_TEMPORARY registers for dead
5242 * code elimination.
5243 *
5244 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
5245 * will occur. As an example, a TXP production after copy propagation but
5246 * before this pass:
5247 *
5248 * 0: MOV TEMP[1], INPUT[4].xyyy;
5249 * 1: MOV TEMP[1].w, INPUT[4].wwww;
5250 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
5251 *
5252 * and after this pass:
5253 *
5254 * 0: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
5255 */
5256 int
5257 glsl_to_tgsi_visitor::eliminate_dead_code(void)
5258 {
5259 glsl_to_tgsi_instruction **writes = rzalloc_array(mem_ctx,
5260 glsl_to_tgsi_instruction *,
5261 this->next_temp * 4);
5262 int *write_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
5263 int level = 0;
5264 int removed = 0;
5265
5266 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
5267 assert(inst->dst[0].file != PROGRAM_TEMPORARY
5268 || inst->dst[0].index < this->next_temp);
5269
5270 switch (inst->op) {
5271 case TGSI_OPCODE_BGNLOOP:
5272 case TGSI_OPCODE_ENDLOOP:
5273 case TGSI_OPCODE_CONT:
5274 case TGSI_OPCODE_BRK:
5275 /* End of a basic block, clear the write array entirely.
5276 *
5277 * This keeps us from killing dead code when the writes are
5278 * on either side of a loop, even when the register isn't touched
5279 * inside the loop. However, glsl_to_tgsi_visitor doesn't seem to emit
5280 * dead code of this type, so it shouldn't make a difference as long as
5281 * the dead code elimination pass in the GLSL compiler does its job.
5282 */
5283 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
5284 break;
5285
5286 case TGSI_OPCODE_ENDIF:
5287 case TGSI_OPCODE_ELSE:
5288 /* Promote the recorded level of all channels written inside the
5289 * preceding if or else block to the level above the if/else block.
5290 */
5291 for (int r = 0; r < this->next_temp; r++) {
5292 for (int c = 0; c < 4; c++) {
5293 if (!writes[4 * r + c])
5294 continue;
5295
5296 if (write_level[4 * r + c] == level)
5297 write_level[4 * r + c] = level-1;
5298 }
5299 }
5300 if (inst->op == TGSI_OPCODE_ENDIF)
5301 --level;
5302 break;
5303
5304 case TGSI_OPCODE_IF:
5305 case TGSI_OPCODE_UIF:
5306 ++level;
5307 /* fallthrough to default case to mark the condition as read */
5308 default:
5309 /* Continuing the block, clear any channels from the write array that
5310 * are read by this instruction.
5311 */
5312 for (unsigned i = 0; i < ARRAY_SIZE(inst->src); i++) {
5313 if (inst->src[i].file == PROGRAM_TEMPORARY && inst->src[i].reladdr){
5314 /* Any temporary might be read, so no dead code elimination
5315 * across this instruction.
5316 */
5317 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
5318 } else if (inst->src[i].file == PROGRAM_TEMPORARY) {
5319 /* Clear where it's used as src. */
5320 int src_chans = 1 << GET_SWZ(inst->src[i].swizzle, 0);
5321 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 1);
5322 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 2);
5323 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 3);
5324
5325 for (int c = 0; c < 4; c++) {
5326 if (src_chans & (1 << c))
5327 writes[4 * inst->src[i].index + c] = NULL;
5328 }
5329 }
5330 dead_code_handle_reladdr(writes, inst->src[i].reladdr);
5331 dead_code_handle_reladdr(writes, inst->src[i].reladdr2);
5332 }
5333 for (unsigned i = 0; i < inst->tex_offset_num_offset; i++) {
5334 if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY && inst->tex_offsets[i].reladdr){
5335 /* Any temporary might be read, so no dead code elimination
5336 * across this instruction.
5337 */
5338 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
5339 } else if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY) {
5340 /* Clear where it's used as src. */
5341 int src_chans = 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 0);
5342 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 1);
5343 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 2);
5344 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 3);
5345
5346 for (int c = 0; c < 4; c++) {
5347 if (src_chans & (1 << c))
5348 writes[4 * inst->tex_offsets[i].index + c] = NULL;
5349 }
5350 }
5351 dead_code_handle_reladdr(writes, inst->tex_offsets[i].reladdr);
5352 dead_code_handle_reladdr(writes, inst->tex_offsets[i].reladdr2);
5353 }
5354
5355 if (inst->resource.file == PROGRAM_TEMPORARY) {
5356 int src_chans;
5357
5358 src_chans = 1 << GET_SWZ(inst->resource.swizzle, 0);
5359 src_chans |= 1 << GET_SWZ(inst->resource.swizzle, 1);
5360 src_chans |= 1 << GET_SWZ(inst->resource.swizzle, 2);
5361 src_chans |= 1 << GET_SWZ(inst->resource.swizzle, 3);
5362
5363 for (int c = 0; c < 4; c++) {
5364 if (src_chans & (1 << c))
5365 writes[4 * inst->resource.index + c] = NULL;
5366 }
5367 }
5368 dead_code_handle_reladdr(writes, inst->resource.reladdr);
5369 dead_code_handle_reladdr(writes, inst->resource.reladdr2);
5370
5371 for (unsigned i = 0; i < ARRAY_SIZE(inst->dst); i++) {
5372 dead_code_handle_reladdr(writes, inst->dst[i].reladdr);
5373 dead_code_handle_reladdr(writes, inst->dst[i].reladdr2);
5374 }
5375 break;
5376 }
5377
5378 /* If this instruction writes to a temporary, add it to the write array.
5379 * If there is already an instruction in the write array for one or more
5380 * of the channels, flag that channel write as dead.
5381 */
5382 for (unsigned i = 0; i < ARRAY_SIZE(inst->dst); i++) {
5383 if (inst->dst[i].file == PROGRAM_TEMPORARY &&
5384 !inst->dst[i].reladdr) {
5385 for (int c = 0; c < 4; c++) {
5386 if (inst->dst[i].writemask & (1 << c)) {
5387 if (writes[4 * inst->dst[i].index + c]) {
5388 if (write_level[4 * inst->dst[i].index + c] < level)
5389 continue;
5390 else
5391 writes[4 * inst->dst[i].index + c]->dead_mask |= (1 << c);
5392 }
5393 writes[4 * inst->dst[i].index + c] = inst;
5394 write_level[4 * inst->dst[i].index + c] = level;
5395 }
5396 }
5397 }
5398 }
5399 }
5400
5401 /* Anything still in the write array at this point is dead code. */
5402 for (int r = 0; r < this->next_temp; r++) {
5403 for (int c = 0; c < 4; c++) {
5404 glsl_to_tgsi_instruction *inst = writes[4 * r + c];
5405 if (inst)
5406 inst->dead_mask |= (1 << c);
5407 }
5408 }
5409
5410 /* Now actually remove the instructions that are completely dead and update
5411 * the writemask of other instructions with dead channels.
5412 */
5413 foreach_in_list_safe(glsl_to_tgsi_instruction, inst, &this->instructions) {
5414 if (!inst->dead_mask || !inst->dst[0].writemask)
5415 continue;
5416 /* No amount of dead masks should remove memory stores */
5417 if (inst->info->is_store)
5418 continue;
5419
5420 if ((inst->dst[0].writemask & ~inst->dead_mask) == 0) {
5421 inst->remove();
5422 delete inst;
5423 removed++;
5424 } else {
5425 if (glsl_base_type_is_64bit(inst->dst[0].type)) {
5426 if (inst->dead_mask == WRITEMASK_XY ||
5427 inst->dead_mask == WRITEMASK_ZW)
5428 inst->dst[0].writemask &= ~(inst->dead_mask);
5429 } else
5430 inst->dst[0].writemask &= ~(inst->dead_mask);
5431 }
5432 }
5433
5434 ralloc_free(write_level);
5435 ralloc_free(writes);
5436
5437 return removed;
5438 }
5439
5440 /* merge DFRACEXP instructions into one. */
5441 void
5442 glsl_to_tgsi_visitor::merge_two_dsts(void)
5443 {
5444 /* We never delete inst, but we may delete its successor. */
5445 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
5446 glsl_to_tgsi_instruction *inst2;
5447 unsigned defined;
5448
5449 if (num_inst_dst_regs(inst) != 2)
5450 continue;
5451
5452 if (inst->dst[0].file != PROGRAM_UNDEFINED &&
5453 inst->dst[1].file != PROGRAM_UNDEFINED)
5454 continue;
5455
5456 assert(inst->dst[0].file != PROGRAM_UNDEFINED ||
5457 inst->dst[1].file != PROGRAM_UNDEFINED);
5458
5459 if (inst->dst[0].file == PROGRAM_UNDEFINED)
5460 defined = 1;
5461 else
5462 defined = 0;
5463
5464 inst2 = (glsl_to_tgsi_instruction *) inst->next;
5465 while (!inst2->is_tail_sentinel()) {
5466 if (inst->op == inst2->op &&
5467 inst2->dst[defined].file == PROGRAM_UNDEFINED &&
5468 inst->src[0].file == inst2->src[0].file &&
5469 inst->src[0].index == inst2->src[0].index &&
5470 inst->src[0].type == inst2->src[0].type &&
5471 inst->src[0].swizzle == inst2->src[0].swizzle)
5472 break;
5473 inst2 = (glsl_to_tgsi_instruction *) inst2->next;
5474 }
5475
5476 if (inst2->is_tail_sentinel()) {
5477 /* Undefined destinations are not allowed, substitute with an unused
5478 * temporary register.
5479 */
5480 st_src_reg tmp = get_temp(glsl_type::vec4_type);
5481 inst->dst[defined ^ 1] = st_dst_reg(tmp);
5482 inst->dst[defined ^ 1].writemask = 0;
5483 continue;
5484 }
5485
5486 inst->dst[defined ^ 1] = inst2->dst[defined ^ 1];
5487 inst2->remove();
5488 delete inst2;
5489 }
5490 }
5491
5492 template <typename st_reg>
5493 void test_indirect_access(const st_reg& reg, bool *has_indirect_access)
5494 {
5495 if (reg.file == PROGRAM_ARRAY) {
5496 if (reg.reladdr || reg.reladdr2 || reg.has_index2) {
5497 has_indirect_access[reg.array_id] = true;
5498 if (reg.reladdr)
5499 test_indirect_access(*reg.reladdr, has_indirect_access);
5500 if (reg.reladdr2)
5501 test_indirect_access(*reg.reladdr2, has_indirect_access);
5502 }
5503 }
5504 }
5505
5506 template <typename st_reg>
5507 void remap_array(st_reg& reg, const int *array_remap_info,
5508 const bool *has_indirect_access)
5509 {
5510 if (reg.file == PROGRAM_ARRAY) {
5511 if (!has_indirect_access[reg.array_id]) {
5512 reg.file = PROGRAM_TEMPORARY;
5513 reg.index = reg.index + array_remap_info[reg.array_id];
5514 reg.array_id = 0;
5515 } else {
5516 reg.array_id = array_remap_info[reg.array_id];
5517 }
5518
5519 if (reg.reladdr)
5520 remap_array(*reg.reladdr, array_remap_info, has_indirect_access);
5521
5522 if (reg.reladdr2)
5523 remap_array(*reg.reladdr2, array_remap_info, has_indirect_access);
5524 }
5525 }
5526
5527 /* One-dimensional arrays whose elements are only accessed directly are
5528 * replaced by an according set of temporary registers that then can become
5529 * subject to further optimization steps like copy propagation and
5530 * register merging.
5531 */
5532 void
5533 glsl_to_tgsi_visitor::split_arrays(void)
5534 {
5535 if (!next_array)
5536 return;
5537
5538 bool *has_indirect_access = rzalloc_array(mem_ctx, bool, next_array + 1);
5539
5540 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
5541 for (unsigned j = 0; j < num_inst_src_regs(inst); j++)
5542 test_indirect_access(inst->src[j], has_indirect_access);
5543
5544 for (unsigned j = 0; j < inst->tex_offset_num_offset; j++)
5545 test_indirect_access(inst->tex_offsets[j], has_indirect_access);
5546
5547 for (unsigned j = 0; j < num_inst_dst_regs(inst); j++)
5548 test_indirect_access(inst->dst[j], has_indirect_access);
5549
5550 test_indirect_access(inst->resource, has_indirect_access);
5551 }
5552
5553 unsigned array_offset = 0;
5554 unsigned n_remaining_arrays = 0;
5555
5556 /* Double use: For arrays that get split this value will contain
5557 * the base index of the temporary registers this array is replaced
5558 * with. For arrays that remain it contains the new array ID.
5559 */
5560 int *array_remap_info = rzalloc_array(has_indirect_access, int,
5561 next_array + 1);
5562
5563 for (unsigned i = 1; i <= next_array; ++i) {
5564 if (!has_indirect_access[i]) {
5565 array_remap_info[i] = this->next_temp + array_offset;
5566 array_offset += array_sizes[i - 1];
5567 } else {
5568 array_sizes[n_remaining_arrays] = array_sizes[i-1];
5569 array_remap_info[i] = ++n_remaining_arrays;
5570 }
5571 }
5572
5573 if (next_array != n_remaining_arrays) {
5574 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
5575 for (unsigned j = 0; j < num_inst_src_regs(inst); j++)
5576 remap_array(inst->src[j], array_remap_info, has_indirect_access);
5577
5578 for (unsigned j = 0; j < inst->tex_offset_num_offset; j++)
5579 remap_array(inst->tex_offsets[j], array_remap_info, has_indirect_access);
5580
5581 for (unsigned j = 0; j < num_inst_dst_regs(inst); j++) {
5582 remap_array(inst->dst[j], array_remap_info, has_indirect_access);
5583 }
5584 remap_array(inst->resource, array_remap_info, has_indirect_access);
5585 }
5586 }
5587
5588 ralloc_free(has_indirect_access);
5589 this->next_temp += array_offset;
5590 next_array = n_remaining_arrays;
5591 }
5592
5593 /* Merges temporary registers together where possible to reduce the number of
5594 * registers needed to run a program.
5595 *
5596 * Produces optimal code only after copy propagation and dead code elimination
5597 * have been run. */
5598 void
5599 glsl_to_tgsi_visitor::merge_registers(void)
5600 {
5601 class array_live_range *arr_live_ranges = NULL;
5602
5603 struct register_live_range *reg_live_ranges =
5604 rzalloc_array(mem_ctx, struct register_live_range, this->next_temp);
5605
5606 if (this->next_array > 0) {
5607 arr_live_ranges = new array_live_range[this->next_array];
5608 for (unsigned i = 0; i < this->next_array; ++i)
5609 arr_live_ranges[i] = array_live_range(i+1, this->array_sizes[i]);
5610 }
5611
5612
5613 if (get_temp_registers_required_live_ranges(reg_live_ranges, &this->instructions,
5614 this->next_temp, reg_live_ranges,
5615 this->next_array, arr_live_ranges)) {
5616 struct rename_reg_pair *renames =
5617 rzalloc_array(reg_live_ranges, struct rename_reg_pair, this->next_temp);
5618 get_temp_registers_remapping(reg_live_ranges, this->next_temp,
5619 reg_live_ranges, renames);
5620 rename_temp_registers(renames);
5621
5622 this->next_array = merge_arrays(this->next_array, this->array_sizes,
5623 &this->instructions, arr_live_ranges);
5624 }
5625
5626 if (arr_live_ranges)
5627 delete[] arr_live_ranges;
5628
5629 ralloc_free(reg_live_ranges);
5630 }
5631
5632 /* Reassign indices to temporary registers by reusing unused indices created
5633 * by optimization passes. */
5634 void
5635 glsl_to_tgsi_visitor::renumber_registers(void)
5636 {
5637 int i = 0;
5638 int new_index = 0;
5639 int *first_writes = ralloc_array(mem_ctx, int, this->next_temp);
5640 struct rename_reg_pair *renames = rzalloc_array(mem_ctx, struct rename_reg_pair, this->next_temp);
5641
5642 for (i = 0; i < this->next_temp; i++) {
5643 first_writes[i] = -1;
5644 }
5645 get_first_temp_write(first_writes);
5646
5647 for (i = 0; i < this->next_temp; i++) {
5648 if (first_writes[i] < 0) continue;
5649 if (i != new_index) {
5650 renames[i].new_reg = new_index;
5651 renames[i].valid = true;
5652 }
5653 new_index++;
5654 }
5655
5656 rename_temp_registers(renames);
5657 this->next_temp = new_index;
5658 ralloc_free(renames);
5659 ralloc_free(first_writes);
5660 }
5661
5662 #ifndef NDEBUG
5663 void glsl_to_tgsi_visitor::print_stats()
5664 {
5665 int narray_registers = 0;
5666 for (unsigned i = 0; i < this->next_array; ++i)
5667 narray_registers += this->array_sizes[i];
5668
5669 int ninstructions = 0;
5670 foreach_in_list(glsl_to_tgsi_instruction, inst, &instructions) {
5671 ++ninstructions;
5672 }
5673
5674 simple_mtx_lock(&print_stats_mutex);
5675 stats_log << next_array << ", "
5676 << next_temp << ", "
5677 << narray_registers << ", "
5678 << next_temp + narray_registers << ", "
5679 << ninstructions << "\n";
5680 simple_mtx_unlock(&print_stats_mutex);
5681 }
5682 #endif
5683 /* ------------------------- TGSI conversion stuff -------------------------- */
5684
5685 /**
5686 * Intermediate state used during shader translation.
5687 */
5688 struct st_translate {
5689 struct ureg_program *ureg;
5690
5691 unsigned temps_size;
5692 struct ureg_dst *temps;
5693
5694 struct ureg_dst *arrays;
5695 unsigned num_temp_arrays;
5696 struct ureg_src *constants;
5697 int num_constants;
5698 struct ureg_src *immediates;
5699 int num_immediates;
5700 struct ureg_dst outputs[PIPE_MAX_SHADER_OUTPUTS];
5701 struct ureg_src inputs[PIPE_MAX_SHADER_INPUTS];
5702 struct ureg_dst address[3];
5703 struct ureg_src samplers[PIPE_MAX_SAMPLERS];
5704 struct ureg_src buffers[PIPE_MAX_SHADER_BUFFERS];
5705 struct ureg_src images[PIPE_MAX_SHADER_IMAGES];
5706 struct ureg_src systemValues[SYSTEM_VALUE_MAX];
5707 struct ureg_src hw_atomics[PIPE_MAX_HW_ATOMIC_BUFFERS];
5708 struct ureg_src shared_memory;
5709 unsigned *array_sizes;
5710 struct inout_decl *input_decls;
5711 unsigned num_input_decls;
5712 struct inout_decl *output_decls;
5713 unsigned num_output_decls;
5714
5715 const ubyte *inputMapping;
5716 const ubyte *outputMapping;
5717
5718 enum pipe_shader_type procType; /**< PIPE_SHADER_VERTEX/FRAGMENT */
5719 bool need_uarl;
5720 };
5721
5722 /** Map Mesa's SYSTEM_VALUE_x to TGSI_SEMANTIC_x */
5723 enum tgsi_semantic
5724 _mesa_sysval_to_semantic(unsigned sysval)
5725 {
5726 switch (sysval) {
5727 /* Vertex shader */
5728 case SYSTEM_VALUE_VERTEX_ID:
5729 return TGSI_SEMANTIC_VERTEXID;
5730 case SYSTEM_VALUE_INSTANCE_ID:
5731 return TGSI_SEMANTIC_INSTANCEID;
5732 case SYSTEM_VALUE_VERTEX_ID_ZERO_BASE:
5733 return TGSI_SEMANTIC_VERTEXID_NOBASE;
5734 case SYSTEM_VALUE_BASE_VERTEX:
5735 return TGSI_SEMANTIC_BASEVERTEX;
5736 case SYSTEM_VALUE_BASE_INSTANCE:
5737 return TGSI_SEMANTIC_BASEINSTANCE;
5738 case SYSTEM_VALUE_DRAW_ID:
5739 return TGSI_SEMANTIC_DRAWID;
5740
5741 /* Geometry shader */
5742 case SYSTEM_VALUE_INVOCATION_ID:
5743 return TGSI_SEMANTIC_INVOCATIONID;
5744
5745 /* Fragment shader */
5746 case SYSTEM_VALUE_FRAG_COORD:
5747 return TGSI_SEMANTIC_POSITION;
5748 case SYSTEM_VALUE_FRONT_FACE:
5749 return TGSI_SEMANTIC_FACE;
5750 case SYSTEM_VALUE_SAMPLE_ID:
5751 return TGSI_SEMANTIC_SAMPLEID;
5752 case SYSTEM_VALUE_SAMPLE_POS:
5753 return TGSI_SEMANTIC_SAMPLEPOS;
5754 case SYSTEM_VALUE_SAMPLE_MASK_IN:
5755 return TGSI_SEMANTIC_SAMPLEMASK;
5756 case SYSTEM_VALUE_HELPER_INVOCATION:
5757 return TGSI_SEMANTIC_HELPER_INVOCATION;
5758
5759 /* Tessellation shader */
5760 case SYSTEM_VALUE_TESS_COORD:
5761 return TGSI_SEMANTIC_TESSCOORD;
5762 case SYSTEM_VALUE_VERTICES_IN:
5763 return TGSI_SEMANTIC_VERTICESIN;
5764 case SYSTEM_VALUE_PRIMITIVE_ID:
5765 return TGSI_SEMANTIC_PRIMID;
5766 case SYSTEM_VALUE_TESS_LEVEL_OUTER:
5767 return TGSI_SEMANTIC_TESSOUTER;
5768 case SYSTEM_VALUE_TESS_LEVEL_INNER:
5769 return TGSI_SEMANTIC_TESSINNER;
5770
5771 /* Compute shader */
5772 case SYSTEM_VALUE_LOCAL_INVOCATION_ID:
5773 return TGSI_SEMANTIC_THREAD_ID;
5774 case SYSTEM_VALUE_WORK_GROUP_ID:
5775 return TGSI_SEMANTIC_BLOCK_ID;
5776 case SYSTEM_VALUE_NUM_WORK_GROUPS:
5777 return TGSI_SEMANTIC_GRID_SIZE;
5778 case SYSTEM_VALUE_LOCAL_GROUP_SIZE:
5779 return TGSI_SEMANTIC_BLOCK_SIZE;
5780
5781 /* ARB_shader_ballot */
5782 case SYSTEM_VALUE_SUBGROUP_SIZE:
5783 return TGSI_SEMANTIC_SUBGROUP_SIZE;
5784 case SYSTEM_VALUE_SUBGROUP_INVOCATION:
5785 return TGSI_SEMANTIC_SUBGROUP_INVOCATION;
5786 case SYSTEM_VALUE_SUBGROUP_EQ_MASK:
5787 return TGSI_SEMANTIC_SUBGROUP_EQ_MASK;
5788 case SYSTEM_VALUE_SUBGROUP_GE_MASK:
5789 return TGSI_SEMANTIC_SUBGROUP_GE_MASK;
5790 case SYSTEM_VALUE_SUBGROUP_GT_MASK:
5791 return TGSI_SEMANTIC_SUBGROUP_GT_MASK;
5792 case SYSTEM_VALUE_SUBGROUP_LE_MASK:
5793 return TGSI_SEMANTIC_SUBGROUP_LE_MASK;
5794 case SYSTEM_VALUE_SUBGROUP_LT_MASK:
5795 return TGSI_SEMANTIC_SUBGROUP_LT_MASK;
5796
5797 /* Unhandled */
5798 case SYSTEM_VALUE_LOCAL_INVOCATION_INDEX:
5799 case SYSTEM_VALUE_GLOBAL_INVOCATION_ID:
5800 case SYSTEM_VALUE_VERTEX_CNT:
5801 case SYSTEM_VALUE_VARYING_COORD:
5802 default:
5803 assert(!"Unexpected SYSTEM_VALUE_ enum");
5804 return TGSI_SEMANTIC_COUNT;
5805 }
5806 }
5807
5808 /**
5809 * Map a glsl_to_tgsi constant/immediate to a TGSI immediate.
5810 */
5811 static struct ureg_src
5812 emit_immediate(struct st_translate *t,
5813 gl_constant_value values[4],
5814 GLenum type, int size)
5815 {
5816 struct ureg_program *ureg = t->ureg;
5817
5818 switch (type) {
5819 case GL_FLOAT:
5820 return ureg_DECL_immediate(ureg, &values[0].f, size);
5821 case GL_DOUBLE:
5822 return ureg_DECL_immediate_f64(ureg, (double *)&values[0].f, size);
5823 case GL_INT64_ARB:
5824 return ureg_DECL_immediate_int64(ureg, (int64_t *)&values[0].f, size);
5825 case GL_UNSIGNED_INT64_ARB:
5826 return ureg_DECL_immediate_uint64(ureg, (uint64_t *)&values[0].f, size);
5827 case GL_INT:
5828 return ureg_DECL_immediate_int(ureg, &values[0].i, size);
5829 case GL_UNSIGNED_INT:
5830 case GL_BOOL:
5831 return ureg_DECL_immediate_uint(ureg, &values[0].u, size);
5832 default:
5833 assert(!"should not get here - type must be float, int, uint, or bool");
5834 return ureg_src_undef();
5835 }
5836 }
5837
5838 /**
5839 * Map a glsl_to_tgsi dst register to a TGSI ureg_dst register.
5840 */
5841 static struct ureg_dst
5842 dst_register(struct st_translate *t, gl_register_file file, unsigned index,
5843 unsigned array_id)
5844 {
5845 unsigned array;
5846
5847 switch (file) {
5848 case PROGRAM_UNDEFINED:
5849 return ureg_dst_undef();
5850
5851 case PROGRAM_TEMPORARY:
5852 /* Allocate space for temporaries on demand. */
5853 if (index >= t->temps_size) {
5854 const int inc = align(index - t->temps_size + 1, 4096);
5855
5856 t->temps = (struct ureg_dst*)
5857 realloc(t->temps,
5858 (t->temps_size + inc) * sizeof(struct ureg_dst));
5859 if (!t->temps)
5860 return ureg_dst_undef();
5861
5862 memset(t->temps + t->temps_size, 0, inc * sizeof(struct ureg_dst));
5863 t->temps_size += inc;
5864 }
5865
5866 if (ureg_dst_is_undef(t->temps[index]))
5867 t->temps[index] = ureg_DECL_local_temporary(t->ureg);
5868
5869 return t->temps[index];
5870
5871 case PROGRAM_ARRAY:
5872 assert(array_id && array_id <= t->num_temp_arrays);
5873 array = array_id - 1;
5874
5875 if (ureg_dst_is_undef(t->arrays[array]))
5876 t->arrays[array] = ureg_DECL_array_temporary(
5877 t->ureg, t->array_sizes[array], TRUE);
5878
5879 return ureg_dst_array_offset(t->arrays[array], index);
5880
5881 case PROGRAM_OUTPUT:
5882 if (!array_id) {
5883 if (t->procType == PIPE_SHADER_FRAGMENT)
5884 assert(index < 2 * FRAG_RESULT_MAX);
5885 else if (t->procType == PIPE_SHADER_TESS_CTRL ||
5886 t->procType == PIPE_SHADER_TESS_EVAL)
5887 assert(index < VARYING_SLOT_TESS_MAX);
5888 else
5889 assert(index < VARYING_SLOT_MAX);
5890
5891 assert(t->outputMapping[index] < ARRAY_SIZE(t->outputs));
5892 assert(t->outputs[t->outputMapping[index]].File != TGSI_FILE_NULL);
5893 return t->outputs[t->outputMapping[index]];
5894 }
5895 else {
5896 struct inout_decl *decl =
5897 find_inout_array(t->output_decls,
5898 t->num_output_decls, array_id);
5899 unsigned mesa_index = decl->mesa_index;
5900 int slot = t->outputMapping[mesa_index];
5901
5902 assert(slot != -1 && t->outputs[slot].File == TGSI_FILE_OUTPUT);
5903
5904 struct ureg_dst dst = t->outputs[slot];
5905 dst.ArrayID = array_id;
5906 return ureg_dst_array_offset(dst, index - mesa_index);
5907 }
5908
5909 case PROGRAM_ADDRESS:
5910 return t->address[index];
5911
5912 default:
5913 assert(!"unknown dst register file");
5914 return ureg_dst_undef();
5915 }
5916 }
5917
5918 static struct ureg_src
5919 translate_src(struct st_translate *t, const st_src_reg *src_reg);
5920
5921 static struct ureg_src
5922 translate_addr(struct st_translate *t, const st_src_reg *reladdr,
5923 unsigned addr_index)
5924 {
5925 if (t->need_uarl || !reladdr->is_legal_tgsi_address_operand())
5926 return ureg_src(t->address[addr_index]);
5927
5928 return translate_src(t, reladdr);
5929 }
5930
5931 /**
5932 * Create a TGSI ureg_dst register from an st_dst_reg.
5933 */
5934 static struct ureg_dst
5935 translate_dst(struct st_translate *t,
5936 const st_dst_reg *dst_reg,
5937 bool saturate)
5938 {
5939 struct ureg_dst dst = dst_register(t, dst_reg->file, dst_reg->index,
5940 dst_reg->array_id);
5941
5942 if (dst.File == TGSI_FILE_NULL)
5943 return dst;
5944
5945 dst = ureg_writemask(dst, dst_reg->writemask);
5946
5947 if (saturate)
5948 dst = ureg_saturate(dst);
5949
5950 if (dst_reg->reladdr != NULL) {
5951 assert(dst_reg->file != PROGRAM_TEMPORARY);
5952 dst = ureg_dst_indirect(dst, translate_addr(t, dst_reg->reladdr, 0));
5953 }
5954
5955 if (dst_reg->has_index2) {
5956 if (dst_reg->reladdr2)
5957 dst = ureg_dst_dimension_indirect(dst,
5958 translate_addr(t, dst_reg->reladdr2, 1),
5959 dst_reg->index2D);
5960 else
5961 dst = ureg_dst_dimension(dst, dst_reg->index2D);
5962 }
5963
5964 return dst;
5965 }
5966
5967 /**
5968 * Create a TGSI ureg_src register from an st_src_reg.
5969 */
5970 static struct ureg_src
5971 translate_src(struct st_translate *t, const st_src_reg *src_reg)
5972 {
5973 struct ureg_src src;
5974 int index = src_reg->index;
5975 int double_reg2 = src_reg->double_reg2 ? 1 : 0;
5976
5977 switch (src_reg->file) {
5978 case PROGRAM_UNDEFINED:
5979 src = ureg_imm4f(t->ureg, 0, 0, 0, 0);
5980 break;
5981
5982 case PROGRAM_TEMPORARY:
5983 case PROGRAM_ARRAY:
5984 src = ureg_src(dst_register(t, src_reg->file, src_reg->index,
5985 src_reg->array_id));
5986 break;
5987
5988 case PROGRAM_OUTPUT: {
5989 struct ureg_dst dst = dst_register(t, src_reg->file, src_reg->index,
5990 src_reg->array_id);
5991 assert(dst.WriteMask != 0);
5992 unsigned shift = ffs(dst.WriteMask) - 1;
5993 src = ureg_swizzle(ureg_src(dst),
5994 shift,
5995 MIN2(shift + 1, 3),
5996 MIN2(shift + 2, 3),
5997 MIN2(shift + 3, 3));
5998 break;
5999 }
6000
6001 case PROGRAM_UNIFORM:
6002 assert(src_reg->index >= 0);
6003 src = src_reg->index < t->num_constants ?
6004 t->constants[src_reg->index] : ureg_imm4f(t->ureg, 0, 0, 0, 0);
6005 break;
6006 case PROGRAM_STATE_VAR:
6007 case PROGRAM_CONSTANT: /* ie, immediate */
6008 if (src_reg->has_index2)
6009 src = ureg_src_register(TGSI_FILE_CONSTANT, src_reg->index);
6010 else
6011 src = src_reg->index >= 0 && src_reg->index < t->num_constants ?
6012 t->constants[src_reg->index] : ureg_imm4f(t->ureg, 0, 0, 0, 0);
6013 break;
6014
6015 case PROGRAM_IMMEDIATE:
6016 assert(src_reg->index >= 0 && src_reg->index < t->num_immediates);
6017 src = t->immediates[src_reg->index];
6018 break;
6019
6020 case PROGRAM_INPUT:
6021 /* GLSL inputs are 64-bit containers, so we have to
6022 * map back to the original index and add the offset after
6023 * mapping. */
6024 index -= double_reg2;
6025 if (!src_reg->array_id) {
6026 assert(t->inputMapping[index] < ARRAY_SIZE(t->inputs));
6027 assert(t->inputs[t->inputMapping[index]].File != TGSI_FILE_NULL);
6028 src = t->inputs[t->inputMapping[index] + double_reg2];
6029 }
6030 else {
6031 struct inout_decl *decl = find_inout_array(t->input_decls,
6032 t->num_input_decls,
6033 src_reg->array_id);
6034 unsigned mesa_index = decl->mesa_index;
6035 int slot = t->inputMapping[mesa_index];
6036
6037 assert(slot != -1 && t->inputs[slot].File == TGSI_FILE_INPUT);
6038
6039 src = t->inputs[slot];
6040 src.ArrayID = src_reg->array_id;
6041 src = ureg_src_array_offset(src, index + double_reg2 - mesa_index);
6042 }
6043 break;
6044
6045 case PROGRAM_ADDRESS:
6046 src = ureg_src(t->address[src_reg->index]);
6047 break;
6048
6049 case PROGRAM_SYSTEM_VALUE:
6050 assert(src_reg->index < (int) ARRAY_SIZE(t->systemValues));
6051 src = t->systemValues[src_reg->index];
6052 break;
6053
6054 case PROGRAM_HW_ATOMIC:
6055 src = ureg_src_array_register(TGSI_FILE_HW_ATOMIC, src_reg->index,
6056 src_reg->array_id);
6057 break;
6058
6059 default:
6060 assert(!"unknown src register file");
6061 return ureg_src_undef();
6062 }
6063
6064 if (src_reg->has_index2) {
6065 /* 2D indexes occur with geometry shader inputs (attrib, vertex)
6066 * and UBO constant buffers (buffer, position).
6067 */
6068 if (src_reg->reladdr2)
6069 src = ureg_src_dimension_indirect(src,
6070 translate_addr(t, src_reg->reladdr2, 1),
6071 src_reg->index2D);
6072 else
6073 src = ureg_src_dimension(src, src_reg->index2D);
6074 }
6075
6076 src = ureg_swizzle(src,
6077 GET_SWZ(src_reg->swizzle, 0) & 0x3,
6078 GET_SWZ(src_reg->swizzle, 1) & 0x3,
6079 GET_SWZ(src_reg->swizzle, 2) & 0x3,
6080 GET_SWZ(src_reg->swizzle, 3) & 0x3);
6081
6082 if (src_reg->abs)
6083 src = ureg_abs(src);
6084
6085 if ((src_reg->negate & 0xf) == NEGATE_XYZW)
6086 src = ureg_negate(src);
6087
6088 if (src_reg->reladdr != NULL) {
6089 assert(src_reg->file != PROGRAM_TEMPORARY);
6090 src = ureg_src_indirect(src, translate_addr(t, src_reg->reladdr, 0));
6091 }
6092
6093 return src;
6094 }
6095
6096 static struct tgsi_texture_offset
6097 translate_tex_offset(struct st_translate *t,
6098 const st_src_reg *in_offset)
6099 {
6100 struct tgsi_texture_offset offset;
6101 struct ureg_src src = translate_src(t, in_offset);
6102
6103 offset.File = src.File;
6104 offset.Index = src.Index;
6105 offset.SwizzleX = src.SwizzleX;
6106 offset.SwizzleY = src.SwizzleY;
6107 offset.SwizzleZ = src.SwizzleZ;
6108 offset.Padding = 0;
6109
6110 assert(!src.Indirect);
6111 assert(!src.DimIndirect);
6112 assert(!src.Dimension);
6113 assert(!src.Absolute); /* those shouldn't be used with integers anyway */
6114 assert(!src.Negate);
6115
6116 return offset;
6117 }
6118
6119 static void
6120 compile_tgsi_instruction(struct st_translate *t,
6121 const glsl_to_tgsi_instruction *inst)
6122 {
6123 struct ureg_program *ureg = t->ureg;
6124 int i;
6125 struct ureg_dst dst[2];
6126 struct ureg_src src[4];
6127 struct tgsi_texture_offset texoffsets[MAX_GLSL_TEXTURE_OFFSET];
6128
6129 int num_dst;
6130 int num_src;
6131 enum tgsi_texture_type tex_target = TGSI_TEXTURE_BUFFER;
6132
6133 num_dst = num_inst_dst_regs(inst);
6134 num_src = num_inst_src_regs(inst);
6135
6136 for (i = 0; i < num_dst; i++)
6137 dst[i] = translate_dst(t,
6138 &inst->dst[i],
6139 inst->saturate);
6140
6141 for (i = 0; i < num_src; i++)
6142 src[i] = translate_src(t, &inst->src[i]);
6143
6144 switch (inst->op) {
6145 case TGSI_OPCODE_BGNLOOP:
6146 case TGSI_OPCODE_ELSE:
6147 case TGSI_OPCODE_ENDLOOP:
6148 case TGSI_OPCODE_IF:
6149 case TGSI_OPCODE_UIF:
6150 assert(num_dst == 0);
6151 ureg_insn(ureg, inst->op, NULL, 0, src, num_src, inst->precise);
6152 return;
6153
6154 case TGSI_OPCODE_TEX:
6155 case TGSI_OPCODE_TEX_LZ:
6156 case TGSI_OPCODE_TXB:
6157 case TGSI_OPCODE_TXD:
6158 case TGSI_OPCODE_TXL:
6159 case TGSI_OPCODE_TXP:
6160 case TGSI_OPCODE_TXQ:
6161 case TGSI_OPCODE_TXQS:
6162 case TGSI_OPCODE_TXF:
6163 case TGSI_OPCODE_TXF_LZ:
6164 case TGSI_OPCODE_TEX2:
6165 case TGSI_OPCODE_TXB2:
6166 case TGSI_OPCODE_TXL2:
6167 case TGSI_OPCODE_TG4:
6168 case TGSI_OPCODE_LODQ:
6169 case TGSI_OPCODE_SAMP2HND:
6170 if (inst->resource.file == PROGRAM_SAMPLER) {
6171 src[num_src] = t->samplers[inst->resource.index];
6172 } else {
6173 /* Bindless samplers. */
6174 src[num_src] = translate_src(t, &inst->resource);
6175 }
6176 assert(src[num_src].File != TGSI_FILE_NULL);
6177 if (inst->resource.reladdr)
6178 src[num_src] =
6179 ureg_src_indirect(src[num_src],
6180 translate_addr(t, inst->resource.reladdr, 2));
6181 num_src++;
6182 for (i = 0; i < (int)inst->tex_offset_num_offset; i++) {
6183 texoffsets[i] = translate_tex_offset(t, &inst->tex_offsets[i]);
6184 }
6185 tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
6186
6187 ureg_tex_insn(ureg,
6188 inst->op,
6189 dst, num_dst,
6190 tex_target,
6191 st_translate_texture_type(inst->tex_type),
6192 texoffsets, inst->tex_offset_num_offset,
6193 src, num_src);
6194 return;
6195
6196 case TGSI_OPCODE_RESQ:
6197 case TGSI_OPCODE_LOAD:
6198 case TGSI_OPCODE_ATOMUADD:
6199 case TGSI_OPCODE_ATOMXCHG:
6200 case TGSI_OPCODE_ATOMCAS:
6201 case TGSI_OPCODE_ATOMAND:
6202 case TGSI_OPCODE_ATOMOR:
6203 case TGSI_OPCODE_ATOMXOR:
6204 case TGSI_OPCODE_ATOMUMIN:
6205 case TGSI_OPCODE_ATOMUMAX:
6206 case TGSI_OPCODE_ATOMIMIN:
6207 case TGSI_OPCODE_ATOMIMAX:
6208 case TGSI_OPCODE_IMG2HND:
6209 for (i = num_src - 1; i >= 0; i--)
6210 src[i + 1] = src[i];
6211 num_src++;
6212 if (inst->resource.file == PROGRAM_MEMORY) {
6213 src[0] = t->shared_memory;
6214 } else if (inst->resource.file == PROGRAM_BUFFER) {
6215 src[0] = t->buffers[inst->resource.index];
6216 } else if (inst->resource.file == PROGRAM_HW_ATOMIC) {
6217 src[0] = translate_src(t, &inst->resource);
6218 } else if (inst->resource.file == PROGRAM_CONSTANT) {
6219 assert(inst->resource.has_index2);
6220 src[0] = ureg_src_register(TGSI_FILE_CONSTBUF, inst->resource.index);
6221 } else {
6222 assert(inst->resource.file != PROGRAM_UNDEFINED);
6223 if (inst->resource.file == PROGRAM_IMAGE) {
6224 src[0] = t->images[inst->resource.index];
6225 } else {
6226 /* Bindless images. */
6227 src[0] = translate_src(t, &inst->resource);
6228 }
6229 tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
6230 }
6231 if (inst->resource.reladdr)
6232 src[0] = ureg_src_indirect(src[0],
6233 translate_addr(t, inst->resource.reladdr, 2));
6234 assert(src[0].File != TGSI_FILE_NULL);
6235 ureg_memory_insn(ureg, inst->op, dst, num_dst, src, num_src,
6236 inst->buffer_access,
6237 tex_target, inst->image_format);
6238 break;
6239
6240 case TGSI_OPCODE_STORE:
6241 if (inst->resource.file == PROGRAM_MEMORY) {
6242 dst[0] = ureg_dst(t->shared_memory);
6243 } else if (inst->resource.file == PROGRAM_BUFFER) {
6244 dst[0] = ureg_dst(t->buffers[inst->resource.index]);
6245 } else {
6246 if (inst->resource.file == PROGRAM_IMAGE) {
6247 dst[0] = ureg_dst(t->images[inst->resource.index]);
6248 } else {
6249 /* Bindless images. */
6250 dst[0] = ureg_dst(translate_src(t, &inst->resource));
6251 }
6252 tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
6253 }
6254 dst[0] = ureg_writemask(dst[0], inst->dst[0].writemask);
6255 if (inst->resource.reladdr)
6256 dst[0] = ureg_dst_indirect(dst[0],
6257 translate_addr(t, inst->resource.reladdr, 2));
6258 assert(dst[0].File != TGSI_FILE_NULL);
6259 ureg_memory_insn(ureg, inst->op, dst, num_dst, src, num_src,
6260 inst->buffer_access,
6261 tex_target, inst->image_format);
6262 break;
6263
6264 default:
6265 ureg_insn(ureg,
6266 inst->op,
6267 dst, num_dst,
6268 src, num_src, inst->precise);
6269 break;
6270 }
6271 }
6272
6273 /* Invert SamplePos.y when rendering to the default framebuffer. */
6274 static void
6275 emit_samplepos_adjustment(struct st_translate *t, int wpos_y_transform)
6276 {
6277 struct ureg_program *ureg = t->ureg;
6278
6279 assert(wpos_y_transform >= 0);
6280 struct ureg_src trans_const = ureg_DECL_constant(ureg, wpos_y_transform);
6281 struct ureg_src samplepos_sysval = t->systemValues[SYSTEM_VALUE_SAMPLE_POS];
6282 struct ureg_dst samplepos_flipped = ureg_DECL_temporary(ureg);
6283 struct ureg_dst is_fbo = ureg_DECL_temporary(ureg);
6284
6285 ureg_ADD(ureg, ureg_writemask(samplepos_flipped, TGSI_WRITEMASK_Y),
6286 ureg_imm1f(ureg, 1), ureg_negate(samplepos_sysval));
6287
6288 /* If trans.x == 1, use samplepos.y, else use 1 - samplepos.y. */
6289 ureg_FSEQ(ureg, ureg_writemask(is_fbo, TGSI_WRITEMASK_Y),
6290 ureg_scalar(trans_const, TGSI_SWIZZLE_X), ureg_imm1f(ureg, 1));
6291 ureg_UCMP(ureg, ureg_writemask(samplepos_flipped, TGSI_WRITEMASK_Y),
6292 ureg_src(is_fbo), samplepos_sysval, ureg_src(samplepos_flipped));
6293 ureg_MOV(ureg, ureg_writemask(samplepos_flipped, TGSI_WRITEMASK_X),
6294 samplepos_sysval);
6295
6296 /* Use the result in place of the system value. */
6297 t->systemValues[SYSTEM_VALUE_SAMPLE_POS] = ureg_src(samplepos_flipped);
6298 }
6299
6300
6301 /**
6302 * Emit the TGSI instructions for inverting and adjusting WPOS.
6303 * This code is unavoidable because it also depends on whether
6304 * a FBO is bound (STATE_FB_WPOS_Y_TRANSFORM).
6305 */
6306 static void
6307 emit_wpos_adjustment(struct gl_context *ctx,
6308 struct st_translate *t,
6309 int wpos_transform_const,
6310 boolean invert,
6311 GLfloat adjX, GLfloat adjY[2])
6312 {
6313 struct ureg_program *ureg = t->ureg;
6314
6315 assert(wpos_transform_const >= 0);
6316
6317 /* Fragment program uses fragment position input.
6318 * Need to replace instances of INPUT[WPOS] with temp T
6319 * where T = INPUT[WPOS] is inverted by Y.
6320 */
6321 struct ureg_src wpostrans = ureg_DECL_constant(ureg, wpos_transform_const);
6322 struct ureg_dst wpos_temp = ureg_DECL_temporary(ureg);
6323 struct ureg_src *wpos =
6324 ctx->Const.GLSLFragCoordIsSysVal ?
6325 &t->systemValues[SYSTEM_VALUE_FRAG_COORD] :
6326 &t->inputs[t->inputMapping[VARYING_SLOT_POS]];
6327 struct ureg_src wpos_input = *wpos;
6328
6329 /* First, apply the coordinate shift: */
6330 if (adjX || adjY[0] || adjY[1]) {
6331 if (adjY[0] != adjY[1]) {
6332 /* Adjust the y coordinate by adjY[1] or adjY[0] respectively
6333 * depending on whether inversion is actually going to be applied
6334 * or not, which is determined by testing against the inversion
6335 * state variable used below, which will be either +1 or -1.
6336 */
6337 struct ureg_dst adj_temp = ureg_DECL_local_temporary(ureg);
6338
6339 ureg_CMP(ureg, adj_temp,
6340 ureg_scalar(wpostrans, invert ? 2 : 0),
6341 ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f),
6342 ureg_imm4f(ureg, adjX, adjY[1], 0.0f, 0.0f));
6343 ureg_ADD(ureg, wpos_temp, wpos_input, ureg_src(adj_temp));
6344 } else {
6345 ureg_ADD(ureg, wpos_temp, wpos_input,
6346 ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f));
6347 }
6348 wpos_input = ureg_src(wpos_temp);
6349 } else {
6350 /* MOV wpos_temp, input[wpos]
6351 */
6352 ureg_MOV(ureg, wpos_temp, wpos_input);
6353 }
6354
6355 /* Now the conditional y flip: STATE_FB_WPOS_Y_TRANSFORM.xy/zw will be
6356 * inversion/identity, or the other way around if we're drawing to an FBO.
6357 */
6358 if (invert) {
6359 /* MAD wpos_temp.y, wpos_input, wpostrans.xxxx, wpostrans.yyyy
6360 */
6361 ureg_MAD(ureg,
6362 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y),
6363 wpos_input,
6364 ureg_scalar(wpostrans, 0),
6365 ureg_scalar(wpostrans, 1));
6366 } else {
6367 /* MAD wpos_temp.y, wpos_input, wpostrans.zzzz, wpostrans.wwww
6368 */
6369 ureg_MAD(ureg,
6370 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y),
6371 wpos_input,
6372 ureg_scalar(wpostrans, 2),
6373 ureg_scalar(wpostrans, 3));
6374 }
6375
6376 /* Use wpos_temp as position input from here on:
6377 */
6378 *wpos = ureg_src(wpos_temp);
6379 }
6380
6381
6382 /**
6383 * Emit fragment position/ooordinate code.
6384 */
6385 static void
6386 emit_wpos(struct st_context *st,
6387 struct st_translate *t,
6388 const struct gl_program *program,
6389 struct ureg_program *ureg,
6390 int wpos_transform_const)
6391 {
6392 struct pipe_screen *pscreen = st->pipe->screen;
6393 GLfloat adjX = 0.0f;
6394 GLfloat adjY[2] = { 0.0f, 0.0f };
6395 boolean invert = FALSE;
6396
6397 /* Query the pixel center conventions supported by the pipe driver and set
6398 * adjX, adjY to help out if it cannot handle the requested one internally.
6399 *
6400 * The bias of the y-coordinate depends on whether y-inversion takes place
6401 * (adjY[1]) or not (adjY[0]), which is in turn dependent on whether we are
6402 * drawing to an FBO (causes additional inversion), and whether the pipe
6403 * driver origin and the requested origin differ (the latter condition is
6404 * stored in the 'invert' variable).
6405 *
6406 * For height = 100 (i = integer, h = half-integer, l = lower, u = upper):
6407 *
6408 * center shift only:
6409 * i -> h: +0.5
6410 * h -> i: -0.5
6411 *
6412 * inversion only:
6413 * l,i -> u,i: ( 0.0 + 1.0) * -1 + 100 = 99
6414 * l,h -> u,h: ( 0.5 + 0.0) * -1 + 100 = 99.5
6415 * u,i -> l,i: (99.0 + 1.0) * -1 + 100 = 0
6416 * u,h -> l,h: (99.5 + 0.0) * -1 + 100 = 0.5
6417 *
6418 * inversion and center shift:
6419 * l,i -> u,h: ( 0.0 + 0.5) * -1 + 100 = 99.5
6420 * l,h -> u,i: ( 0.5 + 0.5) * -1 + 100 = 99
6421 * u,i -> l,h: (99.0 + 0.5) * -1 + 100 = 0.5
6422 * u,h -> l,i: (99.5 + 0.5) * -1 + 100 = 0
6423 */
6424 if (program->OriginUpperLeft) {
6425 /* Fragment shader wants origin in upper-left */
6426 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT)) {
6427 /* the driver supports upper-left origin */
6428 }
6429 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT)) {
6430 /* the driver supports lower-left origin, need to invert Y */
6431 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_ORIGIN,
6432 TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
6433 invert = TRUE;
6434 }
6435 else
6436 assert(0);
6437 }
6438 else {
6439 /* Fragment shader wants origin in lower-left */
6440 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT))
6441 /* the driver supports lower-left origin */
6442 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_ORIGIN,
6443 TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
6444 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT))
6445 /* the driver supports upper-left origin, need to invert Y */
6446 invert = TRUE;
6447 else
6448 assert(0);
6449 }
6450
6451 if (program->PixelCenterInteger) {
6452 /* Fragment shader wants pixel center integer */
6453 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
6454 /* the driver supports pixel center integer */
6455 adjY[1] = 1.0f;
6456 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_PIXEL_CENTER,
6457 TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
6458 }
6459 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
6460 /* the driver supports pixel center half integer, need to bias X,Y */
6461 adjX = -0.5f;
6462 adjY[0] = -0.5f;
6463 adjY[1] = 0.5f;
6464 }
6465 else
6466 assert(0);
6467 }
6468 else {
6469 /* Fragment shader wants pixel center half integer */
6470 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
6471 /* the driver supports pixel center half integer */
6472 }
6473 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
6474 /* the driver supports pixel center integer, need to bias X,Y */
6475 adjX = adjY[0] = adjY[1] = 0.5f;
6476 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_PIXEL_CENTER,
6477 TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
6478 }
6479 else
6480 assert(0);
6481 }
6482
6483 /* we invert after adjustment so that we avoid the MOV to temporary,
6484 * and reuse the adjustment ADD instead */
6485 emit_wpos_adjustment(st->ctx, t, wpos_transform_const, invert, adjX, adjY);
6486 }
6487
6488 /**
6489 * OpenGL's fragment gl_FrontFace input is 1 for front-facing, 0 for back.
6490 * TGSI uses +1 for front, -1 for back.
6491 * This function converts the TGSI value to the GL value. Simply clamping/
6492 * saturating the value to [0,1] does the job.
6493 */
6494 static void
6495 emit_face_var(struct gl_context *ctx, struct st_translate *t)
6496 {
6497 struct ureg_program *ureg = t->ureg;
6498 struct ureg_dst face_temp = ureg_DECL_temporary(ureg);
6499 struct ureg_src face_input = t->inputs[t->inputMapping[VARYING_SLOT_FACE]];
6500
6501 if (ctx->Const.NativeIntegers) {
6502 ureg_FSGE(ureg, face_temp, face_input, ureg_imm1f(ureg, 0));
6503 }
6504 else {
6505 /* MOV_SAT face_temp, input[face] */
6506 ureg_MOV(ureg, ureg_saturate(face_temp), face_input);
6507 }
6508
6509 /* Use face_temp as face input from here on: */
6510 t->inputs[t->inputMapping[VARYING_SLOT_FACE]] = ureg_src(face_temp);
6511 }
6512
6513 static void
6514 emit_compute_block_size(const struct gl_program *prog,
6515 struct ureg_program *ureg) {
6516 ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH,
6517 prog->info.cs.local_size[0]);
6518 ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT,
6519 prog->info.cs.local_size[1]);
6520 ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH,
6521 prog->info.cs.local_size[2]);
6522 }
6523
6524 struct sort_inout_decls {
6525 bool operator()(const struct inout_decl &a, const struct inout_decl &b) const {
6526 return mapping[a.mesa_index] < mapping[b.mesa_index];
6527 }
6528
6529 const ubyte *mapping;
6530 };
6531
6532 /* Sort the given array of decls by the corresponding slot (TGSI file index).
6533 *
6534 * This is for the benefit of older drivers which are broken when the
6535 * declarations aren't sorted in this way.
6536 */
6537 static void
6538 sort_inout_decls_by_slot(struct inout_decl *decls,
6539 unsigned count,
6540 const ubyte mapping[])
6541 {
6542 sort_inout_decls sorter;
6543 sorter.mapping = mapping;
6544 std::sort(decls, decls + count, sorter);
6545 }
6546
6547 static enum tgsi_interpolate_mode
6548 st_translate_interp(enum glsl_interp_mode glsl_qual, GLuint varying)
6549 {
6550 switch (glsl_qual) {
6551 case INTERP_MODE_NONE:
6552 if (varying == VARYING_SLOT_COL0 || varying == VARYING_SLOT_COL1)
6553 return TGSI_INTERPOLATE_COLOR;
6554 return TGSI_INTERPOLATE_PERSPECTIVE;
6555 case INTERP_MODE_SMOOTH:
6556 return TGSI_INTERPOLATE_PERSPECTIVE;
6557 case INTERP_MODE_FLAT:
6558 return TGSI_INTERPOLATE_CONSTANT;
6559 case INTERP_MODE_NOPERSPECTIVE:
6560 return TGSI_INTERPOLATE_LINEAR;
6561 default:
6562 assert(0 && "unexpected interp mode in st_translate_interp()");
6563 return TGSI_INTERPOLATE_PERSPECTIVE;
6564 }
6565 }
6566
6567 /**
6568 * Translate intermediate IR (glsl_to_tgsi_instruction) to TGSI format.
6569 * \param program the program to translate
6570 * \param numInputs number of input registers used
6571 * \param inputMapping maps Mesa fragment program inputs to TGSI generic
6572 * input indexes
6573 * \param inputSemanticName the TGSI_SEMANTIC flag for each input
6574 * \param inputSemanticIndex the semantic index (ex: which texcoord) for
6575 * each input
6576 * \param interpMode the TGSI_INTERPOLATE_LINEAR/PERSP mode for each input
6577 * \param numOutputs number of output registers used
6578 * \param outputMapping maps Mesa fragment program outputs to TGSI
6579 * generic outputs
6580 * \param outputSemanticName the TGSI_SEMANTIC flag for each output
6581 * \param outputSemanticIndex the semantic index (ex: which texcoord) for
6582 * each output
6583 *
6584 * \return PIPE_OK or PIPE_ERROR_OUT_OF_MEMORY
6585 */
6586 extern "C" enum pipe_error
6587 st_translate_program(
6588 struct gl_context *ctx,
6589 enum pipe_shader_type procType,
6590 struct ureg_program *ureg,
6591 glsl_to_tgsi_visitor *program,
6592 const struct gl_program *proginfo,
6593 GLuint numInputs,
6594 const ubyte inputMapping[],
6595 const ubyte inputSlotToAttr[],
6596 const ubyte inputSemanticName[],
6597 const ubyte inputSemanticIndex[],
6598 const ubyte interpMode[],
6599 GLuint numOutputs,
6600 const ubyte outputMapping[],
6601 const ubyte outputSemanticName[],
6602 const ubyte outputSemanticIndex[])
6603 {
6604 struct pipe_screen *screen = st_context(ctx)->pipe->screen;
6605 struct st_translate *t;
6606 unsigned i;
6607 struct gl_program_constants *frag_const =
6608 &ctx->Const.Program[MESA_SHADER_FRAGMENT];
6609 enum pipe_error ret = PIPE_OK;
6610
6611 assert(numInputs <= ARRAY_SIZE(t->inputs));
6612 assert(numOutputs <= ARRAY_SIZE(t->outputs));
6613
6614 ASSERT_BITFIELD_SIZE(st_src_reg, type, GLSL_TYPE_ERROR);
6615 ASSERT_BITFIELD_SIZE(st_dst_reg, type, GLSL_TYPE_ERROR);
6616 ASSERT_BITFIELD_SIZE(glsl_to_tgsi_instruction, tex_type, GLSL_TYPE_ERROR);
6617 ASSERT_BITFIELD_SIZE(glsl_to_tgsi_instruction, image_format, PIPE_FORMAT_COUNT);
6618 ASSERT_BITFIELD_SIZE(glsl_to_tgsi_instruction, tex_target,
6619 (gl_texture_index) (NUM_TEXTURE_TARGETS - 1));
6620 ASSERT_BITFIELD_SIZE(glsl_to_tgsi_instruction, image_format,
6621 (enum pipe_format) (PIPE_FORMAT_COUNT - 1));
6622 ASSERT_BITFIELD_SIZE(glsl_to_tgsi_instruction, op,
6623 (enum tgsi_opcode) (TGSI_OPCODE_LAST - 1));
6624
6625 t = CALLOC_STRUCT(st_translate);
6626 if (!t) {
6627 ret = PIPE_ERROR_OUT_OF_MEMORY;
6628 goto out;
6629 }
6630
6631 t->procType = procType;
6632 t->need_uarl = !screen->get_param(screen, PIPE_CAP_TGSI_ANY_REG_AS_ADDRESS);
6633 t->inputMapping = inputMapping;
6634 t->outputMapping = outputMapping;
6635 t->ureg = ureg;
6636 t->num_temp_arrays = program->next_array;
6637 if (t->num_temp_arrays)
6638 t->arrays = (struct ureg_dst*)
6639 calloc(t->num_temp_arrays, sizeof(t->arrays[0]));
6640
6641 /*
6642 * Declare input attributes.
6643 */
6644 switch (procType) {
6645 case PIPE_SHADER_FRAGMENT:
6646 case PIPE_SHADER_GEOMETRY:
6647 case PIPE_SHADER_TESS_EVAL:
6648 case PIPE_SHADER_TESS_CTRL:
6649 sort_inout_decls_by_slot(program->inputs, program->num_inputs, inputMapping);
6650
6651 for (i = 0; i < program->num_inputs; ++i) {
6652 struct inout_decl *decl = &program->inputs[i];
6653 unsigned slot = inputMapping[decl->mesa_index];
6654 struct ureg_src src;
6655 ubyte tgsi_usage_mask = decl->usage_mask;
6656
6657 if (glsl_base_type_is_64bit(decl->base_type)) {
6658 if (tgsi_usage_mask == 1)
6659 tgsi_usage_mask = TGSI_WRITEMASK_XY;
6660 else if (tgsi_usage_mask == 2)
6661 tgsi_usage_mask = TGSI_WRITEMASK_ZW;
6662 else
6663 tgsi_usage_mask = TGSI_WRITEMASK_XYZW;
6664 }
6665
6666 enum tgsi_interpolate_mode interp_mode = TGSI_INTERPOLATE_CONSTANT;
6667 enum tgsi_interpolate_loc interp_location = TGSI_INTERPOLATE_LOC_CENTER;
6668 if (procType == PIPE_SHADER_FRAGMENT) {
6669 assert(interpMode);
6670 interp_mode = interpMode[slot] != TGSI_INTERPOLATE_COUNT ?
6671 (enum tgsi_interpolate_mode) interpMode[slot] :
6672 st_translate_interp(decl->interp, inputSlotToAttr[slot]);
6673
6674 interp_location = (enum tgsi_interpolate_loc) decl->interp_loc;
6675 }
6676
6677 src = ureg_DECL_fs_input_cyl_centroid_layout(ureg,
6678 (enum tgsi_semantic) inputSemanticName[slot],
6679 inputSemanticIndex[slot],
6680 interp_mode, 0, interp_location, slot, tgsi_usage_mask,
6681 decl->array_id, decl->size);
6682
6683 for (unsigned j = 0; j < decl->size; ++j) {
6684 if (t->inputs[slot + j].File != TGSI_FILE_INPUT) {
6685 /* The ArrayID is set up in dst_register */
6686 t->inputs[slot + j] = src;
6687 t->inputs[slot + j].ArrayID = 0;
6688 t->inputs[slot + j].Index += j;
6689 }
6690 }
6691 }
6692 break;
6693 case PIPE_SHADER_VERTEX:
6694 for (i = 0; i < numInputs; i++) {
6695 t->inputs[i] = ureg_DECL_vs_input(ureg, i);
6696 }
6697 break;
6698 case PIPE_SHADER_COMPUTE:
6699 break;
6700 default:
6701 assert(0);
6702 }
6703
6704 /*
6705 * Declare output attributes.
6706 */
6707 switch (procType) {
6708 case PIPE_SHADER_FRAGMENT:
6709 case PIPE_SHADER_COMPUTE:
6710 break;
6711 case PIPE_SHADER_GEOMETRY:
6712 case PIPE_SHADER_TESS_EVAL:
6713 case PIPE_SHADER_TESS_CTRL:
6714 case PIPE_SHADER_VERTEX:
6715 sort_inout_decls_by_slot(program->outputs, program->num_outputs, outputMapping);
6716
6717 for (i = 0; i < program->num_outputs; ++i) {
6718 struct inout_decl *decl = &program->outputs[i];
6719 unsigned slot = outputMapping[decl->mesa_index];
6720 struct ureg_dst dst;
6721 ubyte tgsi_usage_mask = decl->usage_mask;
6722
6723 if (glsl_base_type_is_64bit(decl->base_type)) {
6724 if (tgsi_usage_mask == 1)
6725 tgsi_usage_mask = TGSI_WRITEMASK_XY;
6726 else if (tgsi_usage_mask == 2)
6727 tgsi_usage_mask = TGSI_WRITEMASK_ZW;
6728 else
6729 tgsi_usage_mask = TGSI_WRITEMASK_XYZW;
6730 }
6731
6732 dst = ureg_DECL_output_layout(ureg,
6733 (enum tgsi_semantic) outputSemanticName[slot],
6734 outputSemanticIndex[slot],
6735 decl->gs_out_streams,
6736 slot, tgsi_usage_mask, decl->array_id, decl->size, decl->invariant);
6737 dst.Invariant = decl->invariant;
6738 for (unsigned j = 0; j < decl->size; ++j) {
6739 if (t->outputs[slot + j].File != TGSI_FILE_OUTPUT) {
6740 /* The ArrayID is set up in dst_register */
6741 t->outputs[slot + j] = dst;
6742 t->outputs[slot + j].ArrayID = 0;
6743 t->outputs[slot + j].Index += j;
6744 t->outputs[slot + j].Invariant = decl->invariant;
6745 }
6746 }
6747 }
6748 break;
6749 default:
6750 assert(0);
6751 }
6752
6753 if (procType == PIPE_SHADER_FRAGMENT) {
6754 if (program->shader->Program->info.fs.early_fragment_tests ||
6755 program->shader->Program->info.fs.post_depth_coverage) {
6756 ureg_property(ureg, TGSI_PROPERTY_FS_EARLY_DEPTH_STENCIL, 1);
6757
6758 if (program->shader->Program->info.fs.post_depth_coverage)
6759 ureg_property(ureg, TGSI_PROPERTY_FS_POST_DEPTH_COVERAGE, 1);
6760 }
6761
6762 if (proginfo->info.inputs_read & VARYING_BIT_POS) {
6763 /* Must do this after setting up t->inputs. */
6764 emit_wpos(st_context(ctx), t, proginfo, ureg,
6765 program->wpos_transform_const);
6766 }
6767
6768 if (proginfo->info.inputs_read & VARYING_BIT_FACE)
6769 emit_face_var(ctx, t);
6770
6771 for (i = 0; i < numOutputs; i++) {
6772 switch (outputSemanticName[i]) {
6773 case TGSI_SEMANTIC_POSITION:
6774 t->outputs[i] = ureg_DECL_output(ureg,
6775 TGSI_SEMANTIC_POSITION, /* Z/Depth */
6776 outputSemanticIndex[i]);
6777 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Z);
6778 break;
6779 case TGSI_SEMANTIC_STENCIL:
6780 t->outputs[i] = ureg_DECL_output(ureg,
6781 TGSI_SEMANTIC_STENCIL, /* Stencil */
6782 outputSemanticIndex[i]);
6783 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Y);
6784 break;
6785 case TGSI_SEMANTIC_COLOR:
6786 t->outputs[i] = ureg_DECL_output(ureg,
6787 TGSI_SEMANTIC_COLOR,
6788 outputSemanticIndex[i]);
6789 break;
6790 case TGSI_SEMANTIC_SAMPLEMASK:
6791 t->outputs[i] = ureg_DECL_output(ureg,
6792 TGSI_SEMANTIC_SAMPLEMASK,
6793 outputSemanticIndex[i]);
6794 /* TODO: If we ever support more than 32 samples, this will have
6795 * to become an array.
6796 */
6797 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_X);
6798 break;
6799 default:
6800 assert(!"fragment shader outputs must be POSITION/STENCIL/COLOR");
6801 ret = PIPE_ERROR_BAD_INPUT;
6802 goto out;
6803 }
6804 }
6805 }
6806 else if (procType == PIPE_SHADER_VERTEX) {
6807 for (i = 0; i < numOutputs; i++) {
6808 if (outputSemanticName[i] == TGSI_SEMANTIC_FOG) {
6809 /* force register to contain a fog coordinate in the form (F, 0, 0, 1). */
6810 ureg_MOV(ureg,
6811 ureg_writemask(t->outputs[i], TGSI_WRITEMASK_YZW),
6812 ureg_imm4f(ureg, 0.0f, 0.0f, 0.0f, 1.0f));
6813 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_X);
6814 }
6815 }
6816 }
6817
6818 if (procType == PIPE_SHADER_COMPUTE) {
6819 emit_compute_block_size(proginfo, ureg);
6820 }
6821
6822 /* Declare address register.
6823 */
6824 if (program->num_address_regs > 0) {
6825 assert(program->num_address_regs <= 3);
6826 for (int i = 0; i < program->num_address_regs; i++)
6827 t->address[i] = ureg_DECL_address(ureg);
6828 }
6829
6830 /* Declare misc input registers
6831 */
6832 {
6833 GLbitfield64 sysInputs = proginfo->info.system_values_read;
6834
6835 for (i = 0; sysInputs; i++) {
6836 if (sysInputs & (1ull << i)) {
6837 enum tgsi_semantic semName = _mesa_sysval_to_semantic(i);
6838
6839 t->systemValues[i] = ureg_DECL_system_value(ureg, semName, 0);
6840
6841 if (semName == TGSI_SEMANTIC_INSTANCEID ||
6842 semName == TGSI_SEMANTIC_VERTEXID) {
6843 /* From Gallium perspective, these system values are always
6844 * integer, and require native integer support. However, if
6845 * native integer is supported on the vertex stage but not the
6846 * pixel stage (e.g, i915g + draw), Mesa will generate IR that
6847 * assumes these system values are floats. To resolve the
6848 * inconsistency, we insert a U2F.
6849 */
6850 struct st_context *st = st_context(ctx);
6851 struct pipe_screen *pscreen = st->pipe->screen;
6852 assert(procType == PIPE_SHADER_VERTEX);
6853 assert(pscreen->get_shader_param(pscreen, PIPE_SHADER_VERTEX, PIPE_SHADER_CAP_INTEGERS));
6854 (void) pscreen;
6855 if (!ctx->Const.NativeIntegers) {
6856 struct ureg_dst temp = ureg_DECL_local_temporary(t->ureg);
6857 ureg_U2F(t->ureg, ureg_writemask(temp, TGSI_WRITEMASK_X),
6858 t->systemValues[i]);
6859 t->systemValues[i] = ureg_scalar(ureg_src(temp), 0);
6860 }
6861 }
6862
6863 if (procType == PIPE_SHADER_FRAGMENT &&
6864 semName == TGSI_SEMANTIC_POSITION)
6865 emit_wpos(st_context(ctx), t, proginfo, ureg,
6866 program->wpos_transform_const);
6867
6868 if (procType == PIPE_SHADER_FRAGMENT &&
6869 semName == TGSI_SEMANTIC_SAMPLEPOS)
6870 emit_samplepos_adjustment(t, program->wpos_transform_const);
6871
6872 sysInputs &= ~(1ull << i);
6873 }
6874 }
6875 }
6876
6877 t->array_sizes = program->array_sizes;
6878 t->input_decls = program->inputs;
6879 t->num_input_decls = program->num_inputs;
6880 t->output_decls = program->outputs;
6881 t->num_output_decls = program->num_outputs;
6882
6883 /* Emit constants and uniforms. TGSI uses a single index space for these,
6884 * so we put all the translated regs in t->constants.
6885 */
6886 if (proginfo->Parameters) {
6887 t->constants = (struct ureg_src *)
6888 calloc(proginfo->Parameters->NumParameters, sizeof(t->constants[0]));
6889 if (t->constants == NULL) {
6890 ret = PIPE_ERROR_OUT_OF_MEMORY;
6891 goto out;
6892 }
6893 t->num_constants = proginfo->Parameters->NumParameters;
6894
6895 for (i = 0; i < proginfo->Parameters->NumParameters; i++) {
6896 unsigned pvo = proginfo->Parameters->ParameterValueOffset[i];
6897
6898 switch (proginfo->Parameters->Parameters[i].Type) {
6899 case PROGRAM_STATE_VAR:
6900 case PROGRAM_UNIFORM:
6901 t->constants[i] = ureg_DECL_constant(ureg, i);
6902 break;
6903
6904 /* Emit immediates for PROGRAM_CONSTANT only when there's no indirect
6905 * addressing of the const buffer.
6906 * FIXME: Be smarter and recognize param arrays:
6907 * indirect addressing is only valid within the referenced
6908 * array.
6909 */
6910 case PROGRAM_CONSTANT:
6911 if (program->indirect_addr_consts)
6912 t->constants[i] = ureg_DECL_constant(ureg, i);
6913 else
6914 t->constants[i] = emit_immediate(t,
6915 proginfo->Parameters->ParameterValues + pvo,
6916 proginfo->Parameters->Parameters[i].DataType,
6917 4);
6918 break;
6919 default:
6920 break;
6921 }
6922 }
6923 }
6924
6925 for (i = 0; i < proginfo->info.num_ubos; i++) {
6926 unsigned size = proginfo->sh.UniformBlocks[i]->UniformBufferSize;
6927 unsigned num_const_vecs = (size + 15) / 16;
6928 unsigned first, last;
6929 assert(num_const_vecs > 0);
6930 first = 0;
6931 last = num_const_vecs > 0 ? num_const_vecs - 1 : 0;
6932 ureg_DECL_constant2D(t->ureg, first, last, i + 1);
6933 }
6934
6935 /* Emit immediate values.
6936 */
6937 t->immediates = (struct ureg_src *)
6938 calloc(program->num_immediates, sizeof(struct ureg_src));
6939 if (t->immediates == NULL) {
6940 ret = PIPE_ERROR_OUT_OF_MEMORY;
6941 goto out;
6942 }
6943 t->num_immediates = program->num_immediates;
6944
6945 i = 0;
6946 foreach_in_list(immediate_storage, imm, &program->immediates) {
6947 assert(i < program->num_immediates);
6948 t->immediates[i++] = emit_immediate(t, imm->values, imm->type, imm->size32);
6949 }
6950 assert(i == program->num_immediates);
6951
6952 /* texture samplers */
6953 for (i = 0; i < frag_const->MaxTextureImageUnits; i++) {
6954 if (program->samplers_used & (1u << i)) {
6955 enum tgsi_return_type type =
6956 st_translate_texture_type(program->sampler_types[i]);
6957
6958 t->samplers[i] = ureg_DECL_sampler(ureg, i);
6959
6960 ureg_DECL_sampler_view(ureg, i, program->sampler_targets[i],
6961 type, type, type, type);
6962 }
6963 }
6964
6965 /* Declare atomic and shader storage buffers. */
6966 {
6967 struct gl_program *prog = program->prog;
6968
6969 if (!st_context(ctx)->has_hw_atomics) {
6970 for (i = 0; i < prog->info.num_abos; i++) {
6971 unsigned index = prog->sh.AtomicBuffers[i]->Binding;
6972 assert(index < frag_const->MaxAtomicBuffers);
6973 t->buffers[index] = ureg_DECL_buffer(ureg, index, true);
6974 }
6975 } else {
6976 for (i = 0; i < program->num_atomics; i++) {
6977 struct hwatomic_decl *ainfo = &program->atomic_info[i];
6978 gl_uniform_storage *uni_storage = &prog->sh.data->UniformStorage[ainfo->location];
6979 int base = uni_storage->offset / ATOMIC_COUNTER_SIZE;
6980 ureg_DECL_hw_atomic(ureg, base, base + ainfo->size - 1, ainfo->binding,
6981 ainfo->array_id);
6982 }
6983 }
6984
6985 assert(prog->info.num_ssbos <= frag_const->MaxShaderStorageBlocks);
6986 for (i = 0; i < prog->info.num_ssbos; i++) {
6987 unsigned index = i;
6988 if (!st_context(ctx)->has_hw_atomics)
6989 index += frag_const->MaxAtomicBuffers;
6990
6991 t->buffers[index] = ureg_DECL_buffer(ureg, index, false);
6992 }
6993 }
6994
6995 if (program->use_shared_memory)
6996 t->shared_memory = ureg_DECL_memory(ureg, TGSI_MEMORY_TYPE_SHARED);
6997
6998 for (i = 0; i < program->shader->Program->info.num_images; i++) {
6999 if (program->images_used & (1 << i)) {
7000 t->images[i] = ureg_DECL_image(ureg, i,
7001 program->image_targets[i],
7002 program->image_formats[i],
7003 program->image_wr[i],
7004 false);
7005 }
7006 }
7007
7008 /* Emit each instruction in turn:
7009 */
7010 foreach_in_list(glsl_to_tgsi_instruction, inst, &program->instructions)
7011 compile_tgsi_instruction(t, inst);
7012
7013 /* Set the next shader stage hint for VS and TES. */
7014 switch (procType) {
7015 case PIPE_SHADER_VERTEX:
7016 case PIPE_SHADER_TESS_EVAL:
7017 if (program->shader_program->SeparateShader)
7018 break;
7019
7020 for (i = program->shader->Stage+1; i <= MESA_SHADER_FRAGMENT; i++) {
7021 if (program->shader_program->_LinkedShaders[i]) {
7022 ureg_set_next_shader_processor(
7023 ureg, pipe_shader_type_from_mesa((gl_shader_stage)i));
7024 break;
7025 }
7026 }
7027 break;
7028 default:
7029 ; /* nothing - silence compiler warning */
7030 }
7031
7032 out:
7033 if (t) {
7034 free(t->arrays);
7035 free(t->temps);
7036 free(t->constants);
7037 t->num_constants = 0;
7038 free(t->immediates);
7039 t->num_immediates = 0;
7040 FREE(t);
7041 }
7042
7043 return ret;
7044 }
7045 /* ----------------------------- End TGSI code ------------------------------ */
7046
7047
7048 /**
7049 * Convert a shader's GLSL IR into a Mesa gl_program, although without
7050 * generating Mesa IR.
7051 */
7052 static struct gl_program *
7053 get_mesa_program_tgsi(struct gl_context *ctx,
7054 struct gl_shader_program *shader_program,
7055 struct gl_linked_shader *shader)
7056 {
7057 glsl_to_tgsi_visitor* v;
7058 struct gl_program *prog;
7059 struct gl_shader_compiler_options *options =
7060 &ctx->Const.ShaderCompilerOptions[shader->Stage];
7061 struct pipe_screen *pscreen = ctx->st->pipe->screen;
7062 enum pipe_shader_type ptarget = pipe_shader_type_from_mesa(shader->Stage);
7063 unsigned skip_merge_registers;
7064
7065 validate_ir_tree(shader->ir);
7066
7067 prog = shader->Program;
7068
7069 prog->Parameters = _mesa_new_parameter_list();
7070 v = new glsl_to_tgsi_visitor();
7071 v->ctx = ctx;
7072 v->prog = prog;
7073 v->shader_program = shader_program;
7074 v->shader = shader;
7075 v->options = options;
7076 v->native_integers = ctx->Const.NativeIntegers;
7077
7078 v->have_sqrt = pscreen->get_shader_param(pscreen, ptarget,
7079 PIPE_SHADER_CAP_TGSI_SQRT_SUPPORTED);
7080 v->have_fma = pscreen->get_shader_param(pscreen, ptarget,
7081 PIPE_SHADER_CAP_TGSI_FMA_SUPPORTED);
7082 v->has_tex_txf_lz = pscreen->get_param(pscreen,
7083 PIPE_CAP_TGSI_TEX_TXF_LZ);
7084 v->need_uarl = !pscreen->get_param(pscreen, PIPE_CAP_TGSI_ANY_REG_AS_ADDRESS);
7085
7086 v->variables = _mesa_hash_table_create(v->mem_ctx, _mesa_hash_pointer,
7087 _mesa_key_pointer_equal);
7088 skip_merge_registers =
7089 pscreen->get_shader_param(pscreen, ptarget,
7090 PIPE_SHADER_CAP_TGSI_SKIP_MERGE_REGISTERS);
7091
7092 _mesa_generate_parameters_list_for_uniforms(ctx, shader_program, shader,
7093 prog->Parameters);
7094
7095 /* Remove reads from output registers. */
7096 if (!pscreen->get_param(pscreen, PIPE_CAP_TGSI_CAN_READ_OUTPUTS))
7097 lower_output_reads(shader->Stage, shader->ir);
7098
7099 /* Emit intermediate IR for main(). */
7100 visit_exec_list(shader->ir, v);
7101
7102 #if 0
7103 /* Print out some information (for debugging purposes) used by the
7104 * optimization passes. */
7105 {
7106 int i;
7107 int *first_writes = ralloc_array(v->mem_ctx, int, v->next_temp);
7108 int *first_reads = ralloc_array(v->mem_ctx, int, v->next_temp);
7109 int *last_writes = ralloc_array(v->mem_ctx, int, v->next_temp);
7110 int *last_reads = ralloc_array(v->mem_ctx, int, v->next_temp);
7111
7112 for (i = 0; i < v->next_temp; i++) {
7113 first_writes[i] = -1;
7114 first_reads[i] = -1;
7115 last_writes[i] = -1;
7116 last_reads[i] = -1;
7117 }
7118 v->get_first_temp_read(first_reads);
7119 v->get_last_temp_read_first_temp_write(last_reads, first_writes);
7120 v->get_last_temp_write(last_writes);
7121 for (i = 0; i < v->next_temp; i++)
7122 printf("Temp %d: FR=%3d FW=%3d LR=%3d LW=%3d\n", i, first_reads[i],
7123 first_writes[i],
7124 last_reads[i],
7125 last_writes[i]);
7126 ralloc_free(first_writes);
7127 ralloc_free(first_reads);
7128 ralloc_free(last_writes);
7129 ralloc_free(last_reads);
7130 }
7131 #endif
7132
7133 /* Perform optimizations on the instructions in the glsl_to_tgsi_visitor. */
7134 v->simplify_cmp();
7135 v->copy_propagate();
7136
7137 while (v->eliminate_dead_code());
7138
7139 v->merge_two_dsts();
7140
7141 if (!skip_merge_registers) {
7142 v->split_arrays();
7143 v->copy_propagate();
7144 while (v->eliminate_dead_code());
7145
7146 v->merge_registers();
7147 v->copy_propagate();
7148 while (v->eliminate_dead_code());
7149 }
7150
7151 v->renumber_registers();
7152
7153 /* Write the END instruction. */
7154 v->emit_asm(NULL, TGSI_OPCODE_END);
7155
7156 if (ctx->_Shader->Flags & GLSL_DUMP) {
7157 _mesa_log("\n");
7158 _mesa_log("GLSL IR for linked %s program %d:\n",
7159 _mesa_shader_stage_to_string(shader->Stage),
7160 shader_program->Name);
7161 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
7162 _mesa_log("\n\n");
7163 }
7164
7165 do_set_program_inouts(shader->ir, prog, shader->Stage);
7166 _mesa_copy_linked_program_data(shader_program, shader);
7167 shrink_array_declarations(v->inputs, v->num_inputs,
7168 &prog->info.inputs_read,
7169 prog->DualSlotInputs,
7170 &prog->info.patch_inputs_read);
7171 shrink_array_declarations(v->outputs, v->num_outputs,
7172 &prog->info.outputs_written, 0ULL,
7173 &prog->info.patch_outputs_written);
7174 count_resources(v, prog);
7175
7176 /* The GLSL IR won't be needed anymore. */
7177 ralloc_free(shader->ir);
7178 shader->ir = NULL;
7179
7180 /* This must be done before the uniform storage is associated. */
7181 if (shader->Stage == MESA_SHADER_FRAGMENT &&
7182 (prog->info.inputs_read & VARYING_BIT_POS ||
7183 prog->info.system_values_read & (1ull << SYSTEM_VALUE_FRAG_COORD) ||
7184 prog->info.system_values_read & (1ull << SYSTEM_VALUE_SAMPLE_POS))) {
7185 static const gl_state_index16 wposTransformState[STATE_LENGTH] = {
7186 STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
7187 };
7188
7189 v->wpos_transform_const = _mesa_add_state_reference(prog->Parameters,
7190 wposTransformState);
7191 }
7192
7193 /* Avoid reallocation of the program parameter list, because the uniform
7194 * storage is only associated with the original parameter list.
7195 * This should be enough for Bitmap and DrawPixels constants.
7196 */
7197 _mesa_reserve_parameter_storage(prog->Parameters, 8);
7198
7199 /* This has to be done last. Any operation the can cause
7200 * prog->ParameterValues to get reallocated (e.g., anything that adds a
7201 * program constant) has to happen before creating this linkage.
7202 */
7203 _mesa_associate_uniform_storage(ctx, shader_program, prog, true);
7204 if (!shader_program->data->LinkStatus) {
7205 free_glsl_to_tgsi_visitor(v);
7206 _mesa_reference_program(ctx, &shader->Program, NULL);
7207 return NULL;
7208 }
7209
7210 struct st_vertex_program *stvp;
7211 struct st_fragment_program *stfp;
7212 struct st_common_program *stp;
7213 struct st_compute_program *stcp;
7214
7215 switch (shader->Stage) {
7216 case MESA_SHADER_VERTEX:
7217 stvp = (struct st_vertex_program *)prog;
7218 stvp->glsl_to_tgsi = v;
7219 break;
7220 case MESA_SHADER_FRAGMENT:
7221 stfp = (struct st_fragment_program *)prog;
7222 stfp->glsl_to_tgsi = v;
7223 break;
7224 case MESA_SHADER_TESS_CTRL:
7225 case MESA_SHADER_TESS_EVAL:
7226 case MESA_SHADER_GEOMETRY:
7227 stp = st_common_program(prog);
7228 stp->glsl_to_tgsi = v;
7229 break;
7230 case MESA_SHADER_COMPUTE:
7231 stcp = (struct st_compute_program *)prog;
7232 stcp->glsl_to_tgsi = v;
7233 break;
7234 default:
7235 assert(!"should not be reached");
7236 return NULL;
7237 }
7238
7239 PRINT_STATS(v->print_stats());
7240
7241 return prog;
7242 }
7243
7244 /* See if there are unsupported control flow statements. */
7245 class ir_control_flow_info_visitor : public ir_hierarchical_visitor {
7246 private:
7247 const struct gl_shader_compiler_options *options;
7248 public:
7249 ir_control_flow_info_visitor(const struct gl_shader_compiler_options *options)
7250 : options(options),
7251 unsupported(false)
7252 {
7253 }
7254
7255 virtual ir_visitor_status visit_enter(ir_function *ir)
7256 {
7257 /* Other functions are skipped (same as glsl_to_tgsi). */
7258 if (strcmp(ir->name, "main") == 0)
7259 return visit_continue;
7260
7261 return visit_continue_with_parent;
7262 }
7263
7264 virtual ir_visitor_status visit_enter(ir_call *ir)
7265 {
7266 if (!ir->callee->is_intrinsic()) {
7267 unsupported = true; /* it's a function call */
7268 return visit_stop;
7269 }
7270 return visit_continue;
7271 }
7272
7273 virtual ir_visitor_status visit_enter(ir_return *ir)
7274 {
7275 if (options->EmitNoMainReturn) {
7276 unsupported = true;
7277 return visit_stop;
7278 }
7279 return visit_continue;
7280 }
7281
7282 bool unsupported;
7283 };
7284
7285 static bool
7286 has_unsupported_control_flow(exec_list *ir,
7287 const struct gl_shader_compiler_options *options)
7288 {
7289 ir_control_flow_info_visitor visitor(options);
7290 visit_list_elements(&visitor, ir);
7291 return visitor.unsupported;
7292 }
7293
7294 extern "C" {
7295
7296 /**
7297 * Link a shader.
7298 * Called via ctx->Driver.LinkShader()
7299 * This actually involves converting GLSL IR into an intermediate TGSI-like IR
7300 * with code lowering and other optimizations.
7301 */
7302 GLboolean
7303 st_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
7304 {
7305 struct pipe_screen *pscreen = ctx->st->pipe->screen;
7306
7307 enum pipe_shader_ir preferred_ir = (enum pipe_shader_ir)
7308 pscreen->get_shader_param(pscreen, PIPE_SHADER_VERTEX,
7309 PIPE_SHADER_CAP_PREFERRED_IR);
7310 bool use_nir = preferred_ir == PIPE_SHADER_IR_NIR;
7311
7312 /* Return early if we are loading the shader from on-disk cache */
7313 if (st_load_ir_from_disk_cache(ctx, prog, use_nir)) {
7314 return GL_TRUE;
7315 }
7316
7317 assert(prog->data->LinkStatus);
7318
7319 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
7320 if (prog->_LinkedShaders[i] == NULL)
7321 continue;
7322
7323 struct gl_linked_shader *shader = prog->_LinkedShaders[i];
7324 exec_list *ir = shader->ir;
7325 gl_shader_stage stage = shader->Stage;
7326 const struct gl_shader_compiler_options *options =
7327 &ctx->Const.ShaderCompilerOptions[stage];
7328 enum pipe_shader_type ptarget = pipe_shader_type_from_mesa(stage);
7329 bool have_dround = pscreen->get_shader_param(pscreen, ptarget,
7330 PIPE_SHADER_CAP_TGSI_DROUND_SUPPORTED);
7331 bool have_dfrexp = pscreen->get_shader_param(pscreen, ptarget,
7332 PIPE_SHADER_CAP_TGSI_DFRACEXP_DLDEXP_SUPPORTED);
7333 bool have_ldexp = pscreen->get_shader_param(pscreen, ptarget,
7334 PIPE_SHADER_CAP_TGSI_LDEXP_SUPPORTED);
7335 unsigned if_threshold = pscreen->get_shader_param(pscreen, ptarget,
7336 PIPE_SHADER_CAP_LOWER_IF_THRESHOLD);
7337
7338 /* If there are forms of indirect addressing that the driver
7339 * cannot handle, perform the lowering pass.
7340 */
7341 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput ||
7342 options->EmitNoIndirectTemp || options->EmitNoIndirectUniform) {
7343 lower_variable_index_to_cond_assign(stage, ir,
7344 options->EmitNoIndirectInput,
7345 options->EmitNoIndirectOutput,
7346 options->EmitNoIndirectTemp,
7347 options->EmitNoIndirectUniform);
7348 }
7349
7350 if (!pscreen->get_param(pscreen, PIPE_CAP_INT64_DIVMOD))
7351 lower_64bit_integer_instructions(ir, DIV64 | MOD64);
7352
7353 if (ctx->Extensions.ARB_shading_language_packing) {
7354 unsigned lower_inst = LOWER_PACK_SNORM_2x16 |
7355 LOWER_UNPACK_SNORM_2x16 |
7356 LOWER_PACK_UNORM_2x16 |
7357 LOWER_UNPACK_UNORM_2x16 |
7358 LOWER_PACK_SNORM_4x8 |
7359 LOWER_UNPACK_SNORM_4x8 |
7360 LOWER_UNPACK_UNORM_4x8 |
7361 LOWER_PACK_UNORM_4x8;
7362
7363 if (ctx->Extensions.ARB_gpu_shader5)
7364 lower_inst |= LOWER_PACK_USE_BFI |
7365 LOWER_PACK_USE_BFE;
7366 if (!ctx->st->has_half_float_packing)
7367 lower_inst |= LOWER_PACK_HALF_2x16 |
7368 LOWER_UNPACK_HALF_2x16;
7369
7370 lower_packing_builtins(ir, lower_inst);
7371 }
7372
7373 if (!pscreen->get_param(pscreen, PIPE_CAP_TEXTURE_GATHER_OFFSETS))
7374 lower_offset_arrays(ir);
7375 do_mat_op_to_vec(ir);
7376
7377 if (stage == MESA_SHADER_FRAGMENT)
7378 lower_blend_equation_advanced(
7379 shader, ctx->Extensions.KHR_blend_equation_advanced_coherent);
7380
7381 lower_instructions(ir,
7382 MOD_TO_FLOOR |
7383 FDIV_TO_MUL_RCP |
7384 EXP_TO_EXP2 |
7385 LOG_TO_LOG2 |
7386 (have_ldexp ? 0 : LDEXP_TO_ARITH) |
7387 (have_dfrexp ? 0 : DFREXP_DLDEXP_TO_ARITH) |
7388 CARRY_TO_ARITH |
7389 BORROW_TO_ARITH |
7390 (have_dround ? 0 : DOPS_TO_DFRAC) |
7391 (options->EmitNoPow ? POW_TO_EXP2 : 0) |
7392 (!ctx->Const.NativeIntegers ? INT_DIV_TO_MUL_RCP : 0) |
7393 (options->EmitNoSat ? SAT_TO_CLAMP : 0) |
7394 (ctx->Const.ForceGLSLAbsSqrt ? SQRT_TO_ABS_SQRT : 0) |
7395 /* Assume that if ARB_gpu_shader5 is not supported
7396 * then all of the extended integer functions need
7397 * lowering. It may be necessary to add some caps
7398 * for individual instructions.
7399 */
7400 (!ctx->Extensions.ARB_gpu_shader5
7401 ? BIT_COUNT_TO_MATH |
7402 EXTRACT_TO_SHIFTS |
7403 INSERT_TO_SHIFTS |
7404 REVERSE_TO_SHIFTS |
7405 FIND_LSB_TO_FLOAT_CAST |
7406 FIND_MSB_TO_FLOAT_CAST |
7407 IMUL_HIGH_TO_MUL
7408 : 0));
7409
7410 do_vec_index_to_cond_assign(ir);
7411 lower_vector_insert(ir, true);
7412 lower_quadop_vector(ir, false);
7413 lower_noise(ir);
7414 if (options->MaxIfDepth == 0) {
7415 lower_discard(ir);
7416 }
7417
7418 if (ctx->Const.GLSLOptimizeConservatively) {
7419 /* Do it once and repeat only if there's unsupported control flow. */
7420 do {
7421 do_common_optimization(ir, true, true, options,
7422 ctx->Const.NativeIntegers);
7423 lower_if_to_cond_assign((gl_shader_stage)i, ir,
7424 options->MaxIfDepth, if_threshold);
7425 } while (has_unsupported_control_flow(ir, options));
7426 } else {
7427 /* Repeat it until it stops making changes. */
7428 bool progress;
7429 do {
7430 progress = do_common_optimization(ir, true, true, options,
7431 ctx->Const.NativeIntegers);
7432 progress |= lower_if_to_cond_assign((gl_shader_stage)i, ir,
7433 options->MaxIfDepth, if_threshold);
7434 } while (progress);
7435 }
7436
7437 /* Do this again to lower ir_binop_vector_extract introduced
7438 * by optimization passes.
7439 */
7440 do_vec_index_to_cond_assign(ir);
7441
7442 validate_ir_tree(ir);
7443 }
7444
7445 build_program_resource_list(ctx, prog);
7446
7447 if (use_nir)
7448 return st_link_nir(ctx, prog);
7449
7450 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
7451 struct gl_linked_shader *shader = prog->_LinkedShaders[i];
7452 if (shader == NULL)
7453 continue;
7454
7455 struct gl_program *linked_prog =
7456 get_mesa_program_tgsi(ctx, prog, shader);
7457 st_set_prog_affected_state_flags(linked_prog);
7458
7459 if (linked_prog) {
7460 if (!ctx->Driver.ProgramStringNotify(ctx,
7461 _mesa_shader_stage_to_program(i),
7462 linked_prog)) {
7463 _mesa_reference_program(ctx, &shader->Program, NULL);
7464 return GL_FALSE;
7465 }
7466 }
7467 }
7468
7469 return GL_TRUE;
7470 }
7471
7472 void
7473 st_translate_stream_output_info(glsl_to_tgsi_visitor *glsl_to_tgsi,
7474 const ubyte outputMapping[],
7475 struct pipe_stream_output_info *so)
7476 {
7477 if (!glsl_to_tgsi->shader_program->last_vert_prog)
7478 return;
7479
7480 struct gl_transform_feedback_info *info =
7481 glsl_to_tgsi->shader_program->last_vert_prog->sh.LinkedTransformFeedback;
7482 st_translate_stream_output_info2(info, outputMapping, so);
7483 }
7484
7485 void
7486 st_translate_stream_output_info2(struct gl_transform_feedback_info *info,
7487 const ubyte outputMapping[],
7488 struct pipe_stream_output_info *so)
7489 {
7490 unsigned i;
7491
7492 for (i = 0; i < info->NumOutputs; i++) {
7493 so->output[i].register_index =
7494 outputMapping[info->Outputs[i].OutputRegister];
7495 so->output[i].start_component = info->Outputs[i].ComponentOffset;
7496 so->output[i].num_components = info->Outputs[i].NumComponents;
7497 so->output[i].output_buffer = info->Outputs[i].OutputBuffer;
7498 so->output[i].dst_offset = info->Outputs[i].DstOffset;
7499 so->output[i].stream = info->Outputs[i].StreamId;
7500 }
7501
7502 for (i = 0; i < PIPE_MAX_SO_BUFFERS; i++) {
7503 so->stride[i] = info->Buffers[i].Stride;
7504 }
7505 so->num_outputs = info->NumOutputs;
7506 }
7507
7508 } /* extern "C" */