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