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