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