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