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