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