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