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