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