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