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