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