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