mesa: Add channel-wise copy propagation to ir_to_mesa.
[mesa.git] / src / mesa / program / ir_to_mesa.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 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 * DEALINGS IN THE SOFTWARE.
24 */
25
26 /**
27 * \file ir_to_mesa.cpp
28 *
29 * Translate GLSL IR to Mesa's gl_program representation.
30 */
31
32 #include <stdio.h>
33 #include "main/compiler.h"
34 #include "ir.h"
35 #include "ir_visitor.h"
36 #include "ir_print_visitor.h"
37 #include "ir_expression_flattening.h"
38 #include "glsl_types.h"
39 #include "glsl_parser_extras.h"
40 #include "../glsl/program.h"
41 #include "ir_optimization.h"
42 #include "ast.h"
43
44 extern "C" {
45 #include "main/mtypes.h"
46 #include "main/shaderapi.h"
47 #include "main/shaderobj.h"
48 #include "main/uniforms.h"
49 #include "program/hash_table.h"
50 #include "program/prog_instruction.h"
51 #include "program/prog_optimize.h"
52 #include "program/prog_print.h"
53 #include "program/program.h"
54 #include "program/prog_uniform.h"
55 #include "program/prog_parameter.h"
56 #include "program/sampler.h"
57 }
58
59 static int swizzle_for_size(int size);
60
61 /**
62 * This struct is a corresponding struct to Mesa prog_src_register, with
63 * wider fields.
64 */
65 typedef struct ir_to_mesa_src_reg {
66 ir_to_mesa_src_reg(int file, int index, const glsl_type *type)
67 {
68 this->file = (gl_register_file) file;
69 this->index = index;
70 if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
71 this->swizzle = swizzle_for_size(type->vector_elements);
72 else
73 this->swizzle = SWIZZLE_XYZW;
74 this->negate = 0;
75 this->reladdr = NULL;
76 }
77
78 ir_to_mesa_src_reg()
79 {
80 this->file = PROGRAM_UNDEFINED;
81 this->index = 0;
82 this->swizzle = 0;
83 this->negate = 0;
84 this->reladdr = NULL;
85 }
86
87 gl_register_file file; /**< PROGRAM_* from Mesa */
88 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
89 GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
90 int negate; /**< NEGATE_XYZW mask from mesa */
91 /** Register index should be offset by the integer in this reg. */
92 ir_to_mesa_src_reg *reladdr;
93 } ir_to_mesa_src_reg;
94
95 typedef struct ir_to_mesa_dst_reg {
96 int file; /**< PROGRAM_* from Mesa */
97 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
98 int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
99 GLuint cond_mask:4;
100 /** Register index should be offset by the integer in this reg. */
101 ir_to_mesa_src_reg *reladdr;
102 } ir_to_mesa_dst_reg;
103
104 extern ir_to_mesa_src_reg ir_to_mesa_undef;
105
106 class ir_to_mesa_instruction : public exec_node {
107 public:
108 /* Callers of this talloc-based new need not call delete. It's
109 * easier to just talloc_free 'ctx' (or any of its ancestors). */
110 static void* operator new(size_t size, void *ctx)
111 {
112 void *node;
113
114 node = talloc_zero_size(ctx, size);
115 assert(node != NULL);
116
117 return node;
118 }
119
120 enum prog_opcode op;
121 ir_to_mesa_dst_reg dst_reg;
122 ir_to_mesa_src_reg src_reg[3];
123 /** Pointer to the ir source this tree came from for debugging */
124 ir_instruction *ir;
125 GLboolean cond_update;
126 bool saturate;
127 int sampler; /**< sampler index */
128 int tex_target; /**< One of TEXTURE_*_INDEX */
129 GLboolean tex_shadow;
130
131 class function_entry *function; /* Set on OPCODE_CAL or OPCODE_BGNSUB */
132 };
133
134 class variable_storage : public exec_node {
135 public:
136 variable_storage(ir_variable *var, gl_register_file file, int index)
137 : file(file), index(index), var(var)
138 {
139 /* empty */
140 }
141
142 gl_register_file file;
143 int index;
144 ir_variable *var; /* variable that maps to this, if any */
145 };
146
147 class function_entry : public exec_node {
148 public:
149 ir_function_signature *sig;
150
151 /**
152 * identifier of this function signature used by the program.
153 *
154 * At the point that Mesa instructions for function calls are
155 * generated, we don't know the address of the first instruction of
156 * the function body. So we make the BranchTarget that is called a
157 * small integer and rewrite them during set_branchtargets().
158 */
159 int sig_id;
160
161 /**
162 * Pointer to first instruction of the function body.
163 *
164 * Set during function body emits after main() is processed.
165 */
166 ir_to_mesa_instruction *bgn_inst;
167
168 /**
169 * Index of the first instruction of the function body in actual
170 * Mesa IR.
171 *
172 * Set after convertion from ir_to_mesa_instruction to prog_instruction.
173 */
174 int inst;
175
176 /** Storage for the return value. */
177 ir_to_mesa_src_reg return_reg;
178 };
179
180 class ir_to_mesa_visitor : public ir_visitor {
181 public:
182 ir_to_mesa_visitor();
183 ~ir_to_mesa_visitor();
184
185 function_entry *current_function;
186
187 struct gl_context *ctx;
188 struct gl_program *prog;
189 struct gl_shader_program *shader_program;
190 struct gl_shader_compiler_options *options;
191
192 int next_temp;
193
194 variable_storage *find_variable_storage(ir_variable *var);
195
196 function_entry *get_function_signature(ir_function_signature *sig);
197
198 ir_to_mesa_src_reg get_temp(const glsl_type *type);
199 void reladdr_to_temp(ir_instruction *ir,
200 ir_to_mesa_src_reg *reg, int *num_reladdr);
201
202 struct ir_to_mesa_src_reg src_reg_for_float(float val);
203
204 /**
205 * \name Visit methods
206 *
207 * As typical for the visitor pattern, there must be one \c visit method for
208 * each concrete subclass of \c ir_instruction. Virtual base classes within
209 * the hierarchy should not have \c visit methods.
210 */
211 /*@{*/
212 virtual void visit(ir_variable *);
213 virtual void visit(ir_loop *);
214 virtual void visit(ir_loop_jump *);
215 virtual void visit(ir_function_signature *);
216 virtual void visit(ir_function *);
217 virtual void visit(ir_expression *);
218 virtual void visit(ir_swizzle *);
219 virtual void visit(ir_dereference_variable *);
220 virtual void visit(ir_dereference_array *);
221 virtual void visit(ir_dereference_record *);
222 virtual void visit(ir_assignment *);
223 virtual void visit(ir_constant *);
224 virtual void visit(ir_call *);
225 virtual void visit(ir_return *);
226 virtual void visit(ir_discard *);
227 virtual void visit(ir_texture *);
228 virtual void visit(ir_if *);
229 /*@}*/
230
231 struct ir_to_mesa_src_reg result;
232
233 /** List of variable_storage */
234 exec_list variables;
235
236 /** List of function_entry */
237 exec_list function_signatures;
238 int next_signature_id;
239
240 /** List of ir_to_mesa_instruction */
241 exec_list instructions;
242
243 ir_to_mesa_instruction *ir_to_mesa_emit_op0(ir_instruction *ir,
244 enum prog_opcode op);
245
246 ir_to_mesa_instruction *ir_to_mesa_emit_op1(ir_instruction *ir,
247 enum prog_opcode op,
248 ir_to_mesa_dst_reg dst,
249 ir_to_mesa_src_reg src0);
250
251 ir_to_mesa_instruction *ir_to_mesa_emit_op2(ir_instruction *ir,
252 enum prog_opcode op,
253 ir_to_mesa_dst_reg dst,
254 ir_to_mesa_src_reg src0,
255 ir_to_mesa_src_reg src1);
256
257 ir_to_mesa_instruction *ir_to_mesa_emit_op3(ir_instruction *ir,
258 enum prog_opcode op,
259 ir_to_mesa_dst_reg dst,
260 ir_to_mesa_src_reg src0,
261 ir_to_mesa_src_reg src1,
262 ir_to_mesa_src_reg src2);
263
264 /**
265 * Emit the correct dot-product instruction for the type of arguments
266 *
267 * \sa ir_to_mesa_emit_op2
268 */
269 void ir_to_mesa_emit_dp(ir_instruction *ir,
270 ir_to_mesa_dst_reg dst,
271 ir_to_mesa_src_reg src0,
272 ir_to_mesa_src_reg src1,
273 unsigned elements);
274
275 void ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
276 enum prog_opcode op,
277 ir_to_mesa_dst_reg dst,
278 ir_to_mesa_src_reg src0);
279
280 void ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
281 enum prog_opcode op,
282 ir_to_mesa_dst_reg dst,
283 ir_to_mesa_src_reg src0,
284 ir_to_mesa_src_reg src1);
285
286 void emit_scs(ir_instruction *ir, enum prog_opcode op,
287 ir_to_mesa_dst_reg dst,
288 const ir_to_mesa_src_reg &src);
289
290 GLboolean try_emit_mad(ir_expression *ir,
291 int mul_operand);
292 GLboolean try_emit_sat(ir_expression *ir);
293
294 void emit_swz(ir_expression *ir);
295
296 bool process_move_condition(ir_rvalue *ir);
297
298 void copy_propagate(void);
299
300 void *mem_ctx;
301 };
302
303 ir_to_mesa_src_reg ir_to_mesa_undef = ir_to_mesa_src_reg(PROGRAM_UNDEFINED, 0, NULL);
304
305 ir_to_mesa_dst_reg ir_to_mesa_undef_dst = {
306 PROGRAM_UNDEFINED, 0, SWIZZLE_NOOP, COND_TR, NULL,
307 };
308
309 ir_to_mesa_dst_reg ir_to_mesa_address_reg = {
310 PROGRAM_ADDRESS, 0, WRITEMASK_X, COND_TR, NULL
311 };
312
313 static void
314 fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
315
316 static void
317 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
318 {
319 va_list args;
320 va_start(args, fmt);
321 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, args);
322 va_end(args);
323
324 prog->LinkStatus = GL_FALSE;
325 }
326
327 static int
328 swizzle_for_size(int size)
329 {
330 int size_swizzles[4] = {
331 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
332 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
333 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
334 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
335 };
336
337 assert((size >= 1) && (size <= 4));
338 return size_swizzles[size - 1];
339 }
340
341 ir_to_mesa_instruction *
342 ir_to_mesa_visitor::ir_to_mesa_emit_op3(ir_instruction *ir,
343 enum prog_opcode op,
344 ir_to_mesa_dst_reg dst,
345 ir_to_mesa_src_reg src0,
346 ir_to_mesa_src_reg src1,
347 ir_to_mesa_src_reg src2)
348 {
349 ir_to_mesa_instruction *inst = new(mem_ctx) ir_to_mesa_instruction();
350 int num_reladdr = 0;
351
352 /* If we have to do relative addressing, we want to load the ARL
353 * reg directly for one of the regs, and preload the other reladdr
354 * sources into temps.
355 */
356 num_reladdr += dst.reladdr != NULL;
357 num_reladdr += src0.reladdr != NULL;
358 num_reladdr += src1.reladdr != NULL;
359 num_reladdr += src2.reladdr != NULL;
360
361 reladdr_to_temp(ir, &src2, &num_reladdr);
362 reladdr_to_temp(ir, &src1, &num_reladdr);
363 reladdr_to_temp(ir, &src0, &num_reladdr);
364
365 if (dst.reladdr) {
366 ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg,
367 *dst.reladdr);
368
369 num_reladdr--;
370 }
371 assert(num_reladdr == 0);
372
373 inst->op = op;
374 inst->dst_reg = dst;
375 inst->src_reg[0] = src0;
376 inst->src_reg[1] = src1;
377 inst->src_reg[2] = src2;
378 inst->ir = ir;
379
380 inst->function = NULL;
381
382 this->instructions.push_tail(inst);
383
384 return inst;
385 }
386
387
388 ir_to_mesa_instruction *
389 ir_to_mesa_visitor::ir_to_mesa_emit_op2(ir_instruction *ir,
390 enum prog_opcode op,
391 ir_to_mesa_dst_reg dst,
392 ir_to_mesa_src_reg src0,
393 ir_to_mesa_src_reg src1)
394 {
395 return ir_to_mesa_emit_op3(ir, op, dst, src0, src1, ir_to_mesa_undef);
396 }
397
398 ir_to_mesa_instruction *
399 ir_to_mesa_visitor::ir_to_mesa_emit_op1(ir_instruction *ir,
400 enum prog_opcode op,
401 ir_to_mesa_dst_reg dst,
402 ir_to_mesa_src_reg src0)
403 {
404 assert(dst.writemask != 0);
405 return ir_to_mesa_emit_op3(ir, op, dst,
406 src0, ir_to_mesa_undef, ir_to_mesa_undef);
407 }
408
409 ir_to_mesa_instruction *
410 ir_to_mesa_visitor::ir_to_mesa_emit_op0(ir_instruction *ir,
411 enum prog_opcode op)
412 {
413 return ir_to_mesa_emit_op3(ir, op, ir_to_mesa_undef_dst,
414 ir_to_mesa_undef,
415 ir_to_mesa_undef,
416 ir_to_mesa_undef);
417 }
418
419 void
420 ir_to_mesa_visitor::ir_to_mesa_emit_dp(ir_instruction *ir,
421 ir_to_mesa_dst_reg dst,
422 ir_to_mesa_src_reg src0,
423 ir_to_mesa_src_reg src1,
424 unsigned elements)
425 {
426 static const gl_inst_opcode dot_opcodes[] = {
427 OPCODE_DP2, OPCODE_DP3, OPCODE_DP4
428 };
429
430 ir_to_mesa_emit_op3(ir, dot_opcodes[elements - 2],
431 dst, src0, src1, ir_to_mesa_undef);
432 }
433
434 inline ir_to_mesa_dst_reg
435 ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg reg)
436 {
437 ir_to_mesa_dst_reg dst_reg;
438
439 dst_reg.file = reg.file;
440 dst_reg.index = reg.index;
441 dst_reg.writemask = WRITEMASK_XYZW;
442 dst_reg.cond_mask = COND_TR;
443 dst_reg.reladdr = reg.reladdr;
444
445 return dst_reg;
446 }
447
448 inline ir_to_mesa_src_reg
449 ir_to_mesa_src_reg_from_dst(ir_to_mesa_dst_reg reg)
450 {
451 return ir_to_mesa_src_reg(reg.file, reg.index, NULL);
452 }
453
454 /**
455 * Emits Mesa scalar opcodes to produce unique answers across channels.
456 *
457 * Some Mesa opcodes are scalar-only, like ARB_fp/vp. The src X
458 * channel determines the result across all channels. So to do a vec4
459 * of this operation, we want to emit a scalar per source channel used
460 * to produce dest channels.
461 */
462 void
463 ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
464 enum prog_opcode op,
465 ir_to_mesa_dst_reg dst,
466 ir_to_mesa_src_reg orig_src0,
467 ir_to_mesa_src_reg orig_src1)
468 {
469 int i, j;
470 int done_mask = ~dst.writemask;
471
472 /* Mesa RCP is a scalar operation splatting results to all channels,
473 * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
474 * dst channels.
475 */
476 for (i = 0; i < 4; i++) {
477 GLuint this_mask = (1 << i);
478 ir_to_mesa_instruction *inst;
479 ir_to_mesa_src_reg src0 = orig_src0;
480 ir_to_mesa_src_reg src1 = orig_src1;
481
482 if (done_mask & this_mask)
483 continue;
484
485 GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
486 GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
487 for (j = i + 1; j < 4; j++) {
488 /* If there is another enabled component in the destination that is
489 * derived from the same inputs, generate its value on this pass as
490 * well.
491 */
492 if (!(done_mask & (1 << j)) &&
493 GET_SWZ(src0.swizzle, j) == src0_swiz &&
494 GET_SWZ(src1.swizzle, j) == src1_swiz) {
495 this_mask |= (1 << j);
496 }
497 }
498 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
499 src0_swiz, src0_swiz);
500 src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
501 src1_swiz, src1_swiz);
502
503 inst = ir_to_mesa_emit_op2(ir, op,
504 dst,
505 src0,
506 src1);
507 inst->dst_reg.writemask = this_mask;
508 done_mask |= this_mask;
509 }
510 }
511
512 void
513 ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
514 enum prog_opcode op,
515 ir_to_mesa_dst_reg dst,
516 ir_to_mesa_src_reg src0)
517 {
518 ir_to_mesa_src_reg undef = ir_to_mesa_undef;
519
520 undef.swizzle = SWIZZLE_XXXX;
521
522 ir_to_mesa_emit_scalar_op2(ir, op, dst, src0, undef);
523 }
524
525 /**
526 * Emit an OPCODE_SCS instruction
527 *
528 * The \c SCS opcode functions a bit differently than the other Mesa (or
529 * ARB_fragment_program) opcodes. Instead of splatting its result across all
530 * four components of the destination, it writes one value to the \c x
531 * component and another value to the \c y component.
532 *
533 * \param ir IR instruction being processed
534 * \param op Either \c OPCODE_SIN or \c OPCODE_COS depending on which
535 * value is desired.
536 * \param dst Destination register
537 * \param src Source register
538 */
539 void
540 ir_to_mesa_visitor::emit_scs(ir_instruction *ir, enum prog_opcode op,
541 ir_to_mesa_dst_reg dst,
542 const ir_to_mesa_src_reg &src)
543 {
544 /* Vertex programs cannot use the SCS opcode.
545 */
546 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
547 ir_to_mesa_emit_scalar_op1(ir, op, dst, src);
548 return;
549 }
550
551 const unsigned component = (op == OPCODE_SIN) ? 0 : 1;
552 const unsigned scs_mask = (1U << component);
553 int done_mask = ~dst.writemask;
554 ir_to_mesa_src_reg tmp;
555
556 assert(op == OPCODE_SIN || op == OPCODE_COS);
557
558 /* If there are compnents in the destination that differ from the component
559 * that will be written by the SCS instrution, we'll need a temporary.
560 */
561 if (scs_mask != unsigned(dst.writemask)) {
562 tmp = get_temp(glsl_type::vec4_type);
563 }
564
565 for (unsigned i = 0; i < 4; i++) {
566 unsigned this_mask = (1U << i);
567 ir_to_mesa_src_reg src0 = src;
568
569 if ((done_mask & this_mask) != 0)
570 continue;
571
572 /* The source swizzle specified which component of the source generates
573 * sine / cosine for the current component in the destination. The SCS
574 * instruction requires that this value be swizzle to the X component.
575 * Replace the current swizzle with a swizzle that puts the source in
576 * the X component.
577 */
578 unsigned src0_swiz = GET_SWZ(src.swizzle, i);
579
580 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
581 src0_swiz, src0_swiz);
582 for (unsigned j = i + 1; j < 4; j++) {
583 /* If there is another enabled component in the destination that is
584 * derived from the same inputs, generate its value on this pass as
585 * well.
586 */
587 if (!(done_mask & (1 << j)) &&
588 GET_SWZ(src0.swizzle, j) == src0_swiz) {
589 this_mask |= (1 << j);
590 }
591 }
592
593 if (this_mask != scs_mask) {
594 ir_to_mesa_instruction *inst;
595 ir_to_mesa_dst_reg tmp_dst = ir_to_mesa_dst_reg_from_src(tmp);
596
597 /* Emit the SCS instruction.
598 */
599 inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, tmp_dst, src0);
600 inst->dst_reg.writemask = scs_mask;
601
602 /* Move the result of the SCS instruction to the desired location in
603 * the destination.
604 */
605 tmp.swizzle = MAKE_SWIZZLE4(component, component,
606 component, component);
607 inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, tmp);
608 inst->dst_reg.writemask = this_mask;
609 } else {
610 /* Emit the SCS instruction to write directly to the destination.
611 */
612 ir_to_mesa_instruction *inst =
613 ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, src0);
614 inst->dst_reg.writemask = scs_mask;
615 }
616
617 done_mask |= this_mask;
618 }
619 }
620
621 struct ir_to_mesa_src_reg
622 ir_to_mesa_visitor::src_reg_for_float(float val)
623 {
624 ir_to_mesa_src_reg src_reg(PROGRAM_CONSTANT, -1, NULL);
625
626 src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
627 &val, 1, &src_reg.swizzle);
628
629 return src_reg;
630 }
631
632 static int
633 type_size(const struct glsl_type *type)
634 {
635 unsigned int i;
636 int size;
637
638 switch (type->base_type) {
639 case GLSL_TYPE_UINT:
640 case GLSL_TYPE_INT:
641 case GLSL_TYPE_FLOAT:
642 case GLSL_TYPE_BOOL:
643 if (type->is_matrix()) {
644 return type->matrix_columns;
645 } else {
646 /* Regardless of size of vector, it gets a vec4. This is bad
647 * packing for things like floats, but otherwise arrays become a
648 * mess. Hopefully a later pass over the code can pack scalars
649 * down if appropriate.
650 */
651 return 1;
652 }
653 case GLSL_TYPE_ARRAY:
654 return type_size(type->fields.array) * type->length;
655 case GLSL_TYPE_STRUCT:
656 size = 0;
657 for (i = 0; i < type->length; i++) {
658 size += type_size(type->fields.structure[i].type);
659 }
660 return size;
661 case GLSL_TYPE_SAMPLER:
662 /* Samplers take up one slot in UNIFORMS[], but they're baked in
663 * at link time.
664 */
665 return 1;
666 default:
667 assert(0);
668 return 0;
669 }
670 }
671
672 /**
673 * In the initial pass of codegen, we assign temporary numbers to
674 * intermediate results. (not SSA -- variable assignments will reuse
675 * storage). Actual register allocation for the Mesa VM occurs in a
676 * pass over the Mesa IR later.
677 */
678 ir_to_mesa_src_reg
679 ir_to_mesa_visitor::get_temp(const glsl_type *type)
680 {
681 ir_to_mesa_src_reg src_reg;
682 int swizzle[4];
683 int i;
684
685 src_reg.file = PROGRAM_TEMPORARY;
686 src_reg.index = next_temp;
687 src_reg.reladdr = NULL;
688 next_temp += type_size(type);
689
690 if (type->is_array() || type->is_record()) {
691 src_reg.swizzle = SWIZZLE_NOOP;
692 } else {
693 for (i = 0; i < type->vector_elements; i++)
694 swizzle[i] = i;
695 for (; i < 4; i++)
696 swizzle[i] = type->vector_elements - 1;
697 src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1],
698 swizzle[2], swizzle[3]);
699 }
700 src_reg.negate = 0;
701
702 return src_reg;
703 }
704
705 variable_storage *
706 ir_to_mesa_visitor::find_variable_storage(ir_variable *var)
707 {
708
709 variable_storage *entry;
710
711 foreach_iter(exec_list_iterator, iter, this->variables) {
712 entry = (variable_storage *)iter.get();
713
714 if (entry->var == var)
715 return entry;
716 }
717
718 return NULL;
719 }
720
721 void
722 ir_to_mesa_visitor::visit(ir_variable *ir)
723 {
724 if (strcmp(ir->name, "gl_FragCoord") == 0) {
725 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
726
727 fp->OriginUpperLeft = ir->origin_upper_left;
728 fp->PixelCenterInteger = ir->pixel_center_integer;
729 }
730
731 if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
732 unsigned int i;
733 const struct gl_builtin_uniform_desc *statevar;
734
735 for (i = 0; _mesa_builtin_uniform_desc[i].name; i++) {
736 if (strcmp(ir->name, _mesa_builtin_uniform_desc[i].name) == 0)
737 break;
738 }
739
740 if (!_mesa_builtin_uniform_desc[i].name) {
741 fail_link(this->shader_program,
742 "Failed to find builtin uniform `%s'\n", ir->name);
743 return;
744 }
745
746 statevar = &_mesa_builtin_uniform_desc[i];
747
748 int array_count;
749 if (ir->type->is_array()) {
750 array_count = ir->type->length;
751 } else {
752 array_count = 1;
753 }
754
755 /* Check if this statevar's setup in the STATE file exactly
756 * matches how we'll want to reference it as a
757 * struct/array/whatever. If not, then we need to move it into
758 * temporary storage and hope that it'll get copy-propagated
759 * out.
760 */
761 for (i = 0; i < statevar->num_elements; i++) {
762 if (statevar->elements[i].swizzle != SWIZZLE_XYZW) {
763 break;
764 }
765 }
766
767 struct variable_storage *storage;
768 ir_to_mesa_dst_reg dst;
769 if (i == statevar->num_elements) {
770 /* We'll set the index later. */
771 storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
772 this->variables.push_tail(storage);
773
774 dst = ir_to_mesa_undef_dst;
775 } else {
776 storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
777 this->next_temp);
778 this->variables.push_tail(storage);
779 this->next_temp += type_size(ir->type);
780
781 dst = ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg(PROGRAM_TEMPORARY,
782 storage->index,
783 NULL));
784 }
785
786
787 for (int a = 0; a < array_count; a++) {
788 for (unsigned int i = 0; i < statevar->num_elements; i++) {
789 struct gl_builtin_uniform_element *element = &statevar->elements[i];
790 int tokens[STATE_LENGTH];
791
792 memcpy(tokens, element->tokens, sizeof(element->tokens));
793 if (ir->type->is_array()) {
794 tokens[1] = a;
795 }
796
797 int index = _mesa_add_state_reference(this->prog->Parameters,
798 (gl_state_index *)tokens);
799
800 if (storage->file == PROGRAM_STATE_VAR) {
801 if (storage->index == -1) {
802 storage->index = index;
803 } else {
804 assert(index ==
805 (int)(storage->index + a * statevar->num_elements + i));
806 }
807 } else {
808 ir_to_mesa_src_reg src(PROGRAM_STATE_VAR, index, NULL);
809 src.swizzle = element->swizzle;
810 ir_to_mesa_emit_op1(ir, OPCODE_MOV, dst, src);
811 /* even a float takes up a whole vec4 reg in a struct/array. */
812 dst.index++;
813 }
814 }
815 }
816 if (storage->file == PROGRAM_TEMPORARY &&
817 dst.index != storage->index + type_size(ir->type)) {
818 fail_link(this->shader_program,
819 "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
820 ir->name, dst.index - storage->index,
821 type_size(ir->type));
822 }
823 }
824 }
825
826 void
827 ir_to_mesa_visitor::visit(ir_loop *ir)
828 {
829 ir_dereference_variable *counter = NULL;
830
831 if (ir->counter != NULL)
832 counter = new(ir) ir_dereference_variable(ir->counter);
833
834 if (ir->from != NULL) {
835 assert(ir->counter != NULL);
836
837 ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
838
839 a->accept(this);
840 delete a;
841 }
842
843 ir_to_mesa_emit_op0(NULL, OPCODE_BGNLOOP);
844
845 if (ir->to) {
846 ir_expression *e =
847 new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
848 counter, ir->to);
849 ir_if *if_stmt = new(ir) ir_if(e);
850
851 ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
852
853 if_stmt->then_instructions.push_tail(brk);
854
855 if_stmt->accept(this);
856
857 delete if_stmt;
858 delete e;
859 delete brk;
860 }
861
862 visit_exec_list(&ir->body_instructions, this);
863
864 if (ir->increment) {
865 ir_expression *e =
866 new(ir) ir_expression(ir_binop_add, counter->type,
867 counter, ir->increment);
868
869 ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
870
871 a->accept(this);
872 delete a;
873 delete e;
874 }
875
876 ir_to_mesa_emit_op0(NULL, OPCODE_ENDLOOP);
877 }
878
879 void
880 ir_to_mesa_visitor::visit(ir_loop_jump *ir)
881 {
882 switch (ir->mode) {
883 case ir_loop_jump::jump_break:
884 ir_to_mesa_emit_op0(NULL, OPCODE_BRK);
885 break;
886 case ir_loop_jump::jump_continue:
887 ir_to_mesa_emit_op0(NULL, OPCODE_CONT);
888 break;
889 }
890 }
891
892
893 void
894 ir_to_mesa_visitor::visit(ir_function_signature *ir)
895 {
896 assert(0);
897 (void)ir;
898 }
899
900 void
901 ir_to_mesa_visitor::visit(ir_function *ir)
902 {
903 /* Ignore function bodies other than main() -- we shouldn't see calls to
904 * them since they should all be inlined before we get to ir_to_mesa.
905 */
906 if (strcmp(ir->name, "main") == 0) {
907 const ir_function_signature *sig;
908 exec_list empty;
909
910 sig = ir->matching_signature(&empty);
911
912 assert(sig);
913
914 foreach_iter(exec_list_iterator, iter, sig->body) {
915 ir_instruction *ir = (ir_instruction *)iter.get();
916
917 ir->accept(this);
918 }
919 }
920 }
921
922 GLboolean
923 ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
924 {
925 int nonmul_operand = 1 - mul_operand;
926 ir_to_mesa_src_reg a, b, c;
927
928 ir_expression *expr = ir->operands[mul_operand]->as_expression();
929 if (!expr || expr->operation != ir_binop_mul)
930 return false;
931
932 expr->operands[0]->accept(this);
933 a = this->result;
934 expr->operands[1]->accept(this);
935 b = this->result;
936 ir->operands[nonmul_operand]->accept(this);
937 c = this->result;
938
939 this->result = get_temp(ir->type);
940 ir_to_mesa_emit_op3(ir, OPCODE_MAD,
941 ir_to_mesa_dst_reg_from_src(this->result), a, b, c);
942
943 return true;
944 }
945
946 GLboolean
947 ir_to_mesa_visitor::try_emit_sat(ir_expression *ir)
948 {
949 /* Saturates were only introduced to vertex programs in
950 * NV_vertex_program3, so don't give them to drivers in the VP.
951 */
952 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
953 return false;
954
955 ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
956 if (!sat_src)
957 return false;
958
959 sat_src->accept(this);
960 ir_to_mesa_src_reg src = this->result;
961
962 this->result = get_temp(ir->type);
963 ir_to_mesa_instruction *inst;
964 inst = ir_to_mesa_emit_op1(ir, OPCODE_MOV,
965 ir_to_mesa_dst_reg_from_src(this->result),
966 src);
967 inst->saturate = true;
968
969 return true;
970 }
971
972 void
973 ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
974 ir_to_mesa_src_reg *reg, int *num_reladdr)
975 {
976 if (!reg->reladdr)
977 return;
978
979 ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg, *reg->reladdr);
980
981 if (*num_reladdr != 1) {
982 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
983
984 ir_to_mesa_emit_op1(ir, OPCODE_MOV,
985 ir_to_mesa_dst_reg_from_src(temp), *reg);
986 *reg = temp;
987 }
988
989 (*num_reladdr)--;
990 }
991
992 void
993 ir_to_mesa_visitor::emit_swz(ir_expression *ir)
994 {
995 /* Assume that the vector operator is in a form compatible with OPCODE_SWZ.
996 * This means that each of the operands is either an immediate value of -1,
997 * 0, or 1, or is a component from one source register (possibly with
998 * negation).
999 */
1000 uint8_t components[4] = { 0 };
1001 bool negate[4] = { false };
1002 ir_variable *var = NULL;
1003
1004 for (unsigned i = 0; i < ir->type->vector_elements; i++) {
1005 ir_rvalue *op = ir->operands[i];
1006
1007 assert(op->type->is_scalar());
1008
1009 while (op != NULL) {
1010 switch (op->ir_type) {
1011 case ir_type_constant: {
1012
1013 assert(op->type->is_scalar());
1014
1015 const ir_constant *const c = op->as_constant();
1016 if (c->is_one()) {
1017 components[i] = SWIZZLE_ONE;
1018 } else if (c->is_zero()) {
1019 components[i] = SWIZZLE_ZERO;
1020 } else if (c->is_negative_one()) {
1021 components[i] = SWIZZLE_ONE;
1022 negate[i] = true;
1023 } else {
1024 assert(!"SWZ constant must be 0.0 or 1.0.");
1025 }
1026
1027 op = NULL;
1028 break;
1029 }
1030
1031 case ir_type_dereference_variable: {
1032 ir_dereference_variable *const deref =
1033 (ir_dereference_variable *) op;
1034
1035 assert((var == NULL) || (deref->var == var));
1036 components[i] = SWIZZLE_X;
1037 var = deref->var;
1038 op = NULL;
1039 break;
1040 }
1041
1042 case ir_type_expression: {
1043 ir_expression *const expr = (ir_expression *) op;
1044
1045 assert(expr->operation == ir_unop_neg);
1046 negate[i] = true;
1047
1048 op = expr->operands[0];
1049 break;
1050 }
1051
1052 case ir_type_swizzle: {
1053 ir_swizzle *const swiz = (ir_swizzle *) op;
1054
1055 components[i] = swiz->mask.x;
1056 op = swiz->val;
1057 break;
1058 }
1059
1060 default:
1061 assert(!"Should not get here.");
1062 return;
1063 }
1064 }
1065 }
1066
1067 assert(var != NULL);
1068
1069 ir_dereference_variable *const deref =
1070 new(mem_ctx) ir_dereference_variable(var);
1071
1072 this->result.file = PROGRAM_UNDEFINED;
1073 deref->accept(this);
1074 if (this->result.file == PROGRAM_UNDEFINED) {
1075 ir_print_visitor v;
1076 printf("Failed to get tree for expression operand:\n");
1077 deref->accept(&v);
1078 exit(1);
1079 }
1080
1081 ir_to_mesa_src_reg src;
1082
1083 src = this->result;
1084 src.swizzle = MAKE_SWIZZLE4(components[0],
1085 components[1],
1086 components[2],
1087 components[3]);
1088 src.negate = ((unsigned(negate[0]) << 0)
1089 | (unsigned(negate[1]) << 1)
1090 | (unsigned(negate[2]) << 2)
1091 | (unsigned(negate[3]) << 3));
1092
1093 /* Storage for our result. Ideally for an assignment we'd be using the
1094 * actual storage for the result here, instead.
1095 */
1096 const ir_to_mesa_src_reg result_src = get_temp(ir->type);
1097 ir_to_mesa_dst_reg result_dst = ir_to_mesa_dst_reg_from_src(result_src);
1098
1099 /* Limit writes to the channels that will be used by result_src later.
1100 * This does limit this temp's use as a temporary for multi-instruction
1101 * sequences.
1102 */
1103 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1104
1105 ir_to_mesa_emit_op1(ir, OPCODE_SWZ, result_dst, src);
1106 this->result = result_src;
1107 }
1108
1109 void
1110 ir_to_mesa_visitor::visit(ir_expression *ir)
1111 {
1112 unsigned int operand;
1113 struct ir_to_mesa_src_reg op[Elements(ir->operands)];
1114 struct ir_to_mesa_src_reg result_src;
1115 struct ir_to_mesa_dst_reg result_dst;
1116
1117 /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
1118 */
1119 if (ir->operation == ir_binop_add) {
1120 if (try_emit_mad(ir, 1))
1121 return;
1122 if (try_emit_mad(ir, 0))
1123 return;
1124 }
1125 if (try_emit_sat(ir))
1126 return;
1127
1128 if (ir->operation == ir_quadop_vector) {
1129 this->emit_swz(ir);
1130 return;
1131 }
1132
1133 for (operand = 0; operand < ir->get_num_operands(); operand++) {
1134 this->result.file = PROGRAM_UNDEFINED;
1135 ir->operands[operand]->accept(this);
1136 if (this->result.file == PROGRAM_UNDEFINED) {
1137 ir_print_visitor v;
1138 printf("Failed to get tree for expression operand:\n");
1139 ir->operands[operand]->accept(&v);
1140 exit(1);
1141 }
1142 op[operand] = this->result;
1143
1144 /* Matrix expression operands should have been broken down to vector
1145 * operations already.
1146 */
1147 assert(!ir->operands[operand]->type->is_matrix());
1148 }
1149
1150 int vector_elements = ir->operands[0]->type->vector_elements;
1151 if (ir->operands[1]) {
1152 vector_elements = MAX2(vector_elements,
1153 ir->operands[1]->type->vector_elements);
1154 }
1155
1156 this->result.file = PROGRAM_UNDEFINED;
1157
1158 /* Storage for our result. Ideally for an assignment we'd be using
1159 * the actual storage for the result here, instead.
1160 */
1161 result_src = get_temp(ir->type);
1162 /* convenience for the emit functions below. */
1163 result_dst = ir_to_mesa_dst_reg_from_src(result_src);
1164 /* Limit writes to the channels that will be used by result_src later.
1165 * This does limit this temp's use as a temporary for multi-instruction
1166 * sequences.
1167 */
1168 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1169
1170 switch (ir->operation) {
1171 case ir_unop_logic_not:
1172 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst,
1173 op[0], src_reg_for_float(0.0));
1174 break;
1175 case ir_unop_neg:
1176 op[0].negate = ~op[0].negate;
1177 result_src = op[0];
1178 break;
1179 case ir_unop_abs:
1180 ir_to_mesa_emit_op1(ir, OPCODE_ABS, result_dst, op[0]);
1181 break;
1182 case ir_unop_sign:
1183 ir_to_mesa_emit_op1(ir, OPCODE_SSG, result_dst, op[0]);
1184 break;
1185 case ir_unop_rcp:
1186 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RCP, result_dst, op[0]);
1187 break;
1188
1189 case ir_unop_exp2:
1190 ir_to_mesa_emit_scalar_op1(ir, OPCODE_EX2, result_dst, op[0]);
1191 break;
1192 case ir_unop_exp:
1193 case ir_unop_log:
1194 assert(!"not reached: should be handled by ir_explog_to_explog2");
1195 break;
1196 case ir_unop_log2:
1197 ir_to_mesa_emit_scalar_op1(ir, OPCODE_LG2, result_dst, op[0]);
1198 break;
1199 case ir_unop_sin:
1200 ir_to_mesa_emit_scalar_op1(ir, OPCODE_SIN, result_dst, op[0]);
1201 break;
1202 case ir_unop_cos:
1203 ir_to_mesa_emit_scalar_op1(ir, OPCODE_COS, result_dst, op[0]);
1204 break;
1205 case ir_unop_sin_reduced:
1206 emit_scs(ir, OPCODE_SIN, result_dst, op[0]);
1207 break;
1208 case ir_unop_cos_reduced:
1209 emit_scs(ir, OPCODE_COS, result_dst, op[0]);
1210 break;
1211
1212 case ir_unop_dFdx:
1213 ir_to_mesa_emit_op1(ir, OPCODE_DDX, result_dst, op[0]);
1214 break;
1215 case ir_unop_dFdy:
1216 ir_to_mesa_emit_op1(ir, OPCODE_DDY, result_dst, op[0]);
1217 break;
1218
1219 case ir_unop_noise: {
1220 const enum prog_opcode opcode =
1221 prog_opcode(OPCODE_NOISE1
1222 + (ir->operands[0]->type->vector_elements) - 1);
1223 assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
1224
1225 ir_to_mesa_emit_op1(ir, opcode, result_dst, op[0]);
1226 break;
1227 }
1228
1229 case ir_binop_add:
1230 ir_to_mesa_emit_op2(ir, OPCODE_ADD, result_dst, op[0], op[1]);
1231 break;
1232 case ir_binop_sub:
1233 ir_to_mesa_emit_op2(ir, OPCODE_SUB, result_dst, op[0], op[1]);
1234 break;
1235
1236 case ir_binop_mul:
1237 ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, op[0], op[1]);
1238 break;
1239 case ir_binop_div:
1240 assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1241 case ir_binop_mod:
1242 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1243 break;
1244
1245 case ir_binop_less:
1246 ir_to_mesa_emit_op2(ir, OPCODE_SLT, result_dst, op[0], op[1]);
1247 break;
1248 case ir_binop_greater:
1249 ir_to_mesa_emit_op2(ir, OPCODE_SGT, result_dst, op[0], op[1]);
1250 break;
1251 case ir_binop_lequal:
1252 ir_to_mesa_emit_op2(ir, OPCODE_SLE, result_dst, op[0], op[1]);
1253 break;
1254 case ir_binop_gequal:
1255 ir_to_mesa_emit_op2(ir, OPCODE_SGE, result_dst, op[0], op[1]);
1256 break;
1257 case ir_binop_equal:
1258 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1259 break;
1260 case ir_binop_nequal:
1261 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1262 break;
1263 case ir_binop_all_equal:
1264 /* "==" operator producing a scalar boolean. */
1265 if (ir->operands[0]->type->is_vector() ||
1266 ir->operands[1]->type->is_vector()) {
1267 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
1268 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1269 ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
1270 ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
1271 ir_to_mesa_emit_op2(ir, OPCODE_SEQ,
1272 result_dst, result_src, src_reg_for_float(0.0));
1273 } else {
1274 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1275 }
1276 break;
1277 case ir_binop_any_nequal:
1278 /* "!=" operator producing a scalar boolean. */
1279 if (ir->operands[0]->type->is_vector() ||
1280 ir->operands[1]->type->is_vector()) {
1281 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
1282 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1283 ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
1284 ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
1285 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1286 result_dst, result_src, src_reg_for_float(0.0));
1287 } else {
1288 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1289 }
1290 break;
1291
1292 case ir_unop_any:
1293 assert(ir->operands[0]->type->is_vector());
1294 ir_to_mesa_emit_dp(ir, result_dst, op[0], op[0],
1295 ir->operands[0]->type->vector_elements);
1296 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1297 result_dst, result_src, src_reg_for_float(0.0));
1298 break;
1299
1300 case ir_binop_logic_xor:
1301 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1302 break;
1303
1304 case ir_binop_logic_or:
1305 /* This could be a saturated add and skip the SNE. */
1306 ir_to_mesa_emit_op2(ir, OPCODE_ADD,
1307 result_dst,
1308 op[0], op[1]);
1309
1310 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1311 result_dst,
1312 result_src, src_reg_for_float(0.0));
1313 break;
1314
1315 case ir_binop_logic_and:
1316 /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
1317 ir_to_mesa_emit_op2(ir, OPCODE_MUL,
1318 result_dst,
1319 op[0], op[1]);
1320 break;
1321
1322 case ir_binop_dot:
1323 assert(ir->operands[0]->type->is_vector());
1324 assert(ir->operands[0]->type == ir->operands[1]->type);
1325 ir_to_mesa_emit_dp(ir, result_dst, op[0], op[1],
1326 ir->operands[0]->type->vector_elements);
1327 break;
1328
1329 case ir_unop_sqrt:
1330 /* sqrt(x) = x * rsq(x). */
1331 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
1332 ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, result_src, op[0]);
1333 /* For incoming channels <= 0, set the result to 0. */
1334 op[0].negate = ~op[0].negate;
1335 ir_to_mesa_emit_op3(ir, OPCODE_CMP, result_dst,
1336 op[0], result_src, src_reg_for_float(0.0));
1337 break;
1338 case ir_unop_rsq:
1339 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
1340 break;
1341 case ir_unop_i2f:
1342 case ir_unop_b2f:
1343 case ir_unop_b2i:
1344 /* Mesa IR lacks types, ints are stored as truncated floats. */
1345 result_src = op[0];
1346 break;
1347 case ir_unop_f2i:
1348 ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
1349 break;
1350 case ir_unop_f2b:
1351 case ir_unop_i2b:
1352 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst,
1353 op[0], src_reg_for_float(0.0));
1354 break;
1355 case ir_unop_trunc:
1356 ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
1357 break;
1358 case ir_unop_ceil:
1359 op[0].negate = ~op[0].negate;
1360 ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
1361 result_src.negate = ~result_src.negate;
1362 break;
1363 case ir_unop_floor:
1364 ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
1365 break;
1366 case ir_unop_fract:
1367 ir_to_mesa_emit_op1(ir, OPCODE_FRC, result_dst, op[0]);
1368 break;
1369
1370 case ir_binop_min:
1371 ir_to_mesa_emit_op2(ir, OPCODE_MIN, result_dst, op[0], op[1]);
1372 break;
1373 case ir_binop_max:
1374 ir_to_mesa_emit_op2(ir, OPCODE_MAX, result_dst, op[0], op[1]);
1375 break;
1376 case ir_binop_pow:
1377 ir_to_mesa_emit_scalar_op2(ir, OPCODE_POW, result_dst, op[0], op[1]);
1378 break;
1379
1380 case ir_unop_bit_not:
1381 case ir_unop_u2f:
1382 case ir_binop_lshift:
1383 case ir_binop_rshift:
1384 case ir_binop_bit_and:
1385 case ir_binop_bit_xor:
1386 case ir_binop_bit_or:
1387 case ir_unop_round_even:
1388 assert(!"GLSL 1.30 features unsupported");
1389 break;
1390
1391 case ir_quadop_vector:
1392 /* This operation should have already been handled.
1393 */
1394 assert(!"Should not get here.");
1395 break;
1396 }
1397
1398 this->result = result_src;
1399 }
1400
1401
1402 void
1403 ir_to_mesa_visitor::visit(ir_swizzle *ir)
1404 {
1405 ir_to_mesa_src_reg src_reg;
1406 int i;
1407 int swizzle[4];
1408
1409 /* Note that this is only swizzles in expressions, not those on the left
1410 * hand side of an assignment, which do write masking. See ir_assignment
1411 * for that.
1412 */
1413
1414 ir->val->accept(this);
1415 src_reg = this->result;
1416 assert(src_reg.file != PROGRAM_UNDEFINED);
1417
1418 for (i = 0; i < 4; i++) {
1419 if (i < ir->type->vector_elements) {
1420 switch (i) {
1421 case 0:
1422 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.x);
1423 break;
1424 case 1:
1425 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.y);
1426 break;
1427 case 2:
1428 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.z);
1429 break;
1430 case 3:
1431 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.w);
1432 break;
1433 }
1434 } else {
1435 /* If the type is smaller than a vec4, replicate the last
1436 * channel out.
1437 */
1438 swizzle[i] = swizzle[ir->type->vector_elements - 1];
1439 }
1440 }
1441
1442 src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0],
1443 swizzle[1],
1444 swizzle[2],
1445 swizzle[3]);
1446
1447 this->result = src_reg;
1448 }
1449
1450 void
1451 ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
1452 {
1453 variable_storage *entry = find_variable_storage(ir->var);
1454
1455 if (!entry) {
1456 switch (ir->var->mode) {
1457 case ir_var_uniform:
1458 entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_UNIFORM,
1459 ir->var->location);
1460 this->variables.push_tail(entry);
1461 break;
1462 case ir_var_in:
1463 case ir_var_out:
1464 case ir_var_inout:
1465 /* The linker assigns locations for varyings and attributes,
1466 * including deprecated builtins (like gl_Color), user-assign
1467 * generic attributes (glBindVertexLocation), and
1468 * user-defined varyings.
1469 *
1470 * FINISHME: We would hit this path for function arguments. Fix!
1471 */
1472 assert(ir->var->location != -1);
1473 if (ir->var->mode == ir_var_in ||
1474 ir->var->mode == ir_var_inout) {
1475 entry = new(mem_ctx) variable_storage(ir->var,
1476 PROGRAM_INPUT,
1477 ir->var->location);
1478
1479 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
1480 ir->var->location >= VERT_ATTRIB_GENERIC0) {
1481 _mesa_add_attribute(prog->Attributes,
1482 ir->var->name,
1483 _mesa_sizeof_glsl_type(ir->var->type->gl_type),
1484 ir->var->type->gl_type,
1485 ir->var->location - VERT_ATTRIB_GENERIC0);
1486 }
1487 } else {
1488 entry = new(mem_ctx) variable_storage(ir->var,
1489 PROGRAM_OUTPUT,
1490 ir->var->location);
1491 }
1492
1493 break;
1494 case ir_var_auto:
1495 case ir_var_temporary:
1496 entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_TEMPORARY,
1497 this->next_temp);
1498 this->variables.push_tail(entry);
1499
1500 next_temp += type_size(ir->var->type);
1501 break;
1502 }
1503
1504 if (!entry) {
1505 printf("Failed to make storage for %s\n", ir->var->name);
1506 exit(1);
1507 }
1508 }
1509
1510 this->result = ir_to_mesa_src_reg(entry->file, entry->index, ir->var->type);
1511 }
1512
1513 void
1514 ir_to_mesa_visitor::visit(ir_dereference_array *ir)
1515 {
1516 ir_constant *index;
1517 ir_to_mesa_src_reg src_reg;
1518 int element_size = type_size(ir->type);
1519
1520 index = ir->array_index->constant_expression_value();
1521
1522 ir->array->accept(this);
1523 src_reg = this->result;
1524
1525 if (index) {
1526 src_reg.index += index->value.i[0] * element_size;
1527 } else {
1528 ir_to_mesa_src_reg array_base = this->result;
1529 /* Variable index array dereference. It eats the "vec4" of the
1530 * base of the array and an index that offsets the Mesa register
1531 * index.
1532 */
1533 ir->array_index->accept(this);
1534
1535 ir_to_mesa_src_reg index_reg;
1536
1537 if (element_size == 1) {
1538 index_reg = this->result;
1539 } else {
1540 index_reg = get_temp(glsl_type::float_type);
1541
1542 ir_to_mesa_emit_op2(ir, OPCODE_MUL,
1543 ir_to_mesa_dst_reg_from_src(index_reg),
1544 this->result, src_reg_for_float(element_size));
1545 }
1546
1547 src_reg.reladdr = talloc(mem_ctx, ir_to_mesa_src_reg);
1548 memcpy(src_reg.reladdr, &index_reg, sizeof(index_reg));
1549 }
1550
1551 /* If the type is smaller than a vec4, replicate the last channel out. */
1552 if (ir->type->is_scalar() || ir->type->is_vector())
1553 src_reg.swizzle = swizzle_for_size(ir->type->vector_elements);
1554 else
1555 src_reg.swizzle = SWIZZLE_NOOP;
1556
1557 this->result = src_reg;
1558 }
1559
1560 void
1561 ir_to_mesa_visitor::visit(ir_dereference_record *ir)
1562 {
1563 unsigned int i;
1564 const glsl_type *struct_type = ir->record->type;
1565 int offset = 0;
1566
1567 ir->record->accept(this);
1568
1569 for (i = 0; i < struct_type->length; i++) {
1570 if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
1571 break;
1572 offset += type_size(struct_type->fields.structure[i].type);
1573 }
1574
1575 /* If the type is smaller than a vec4, replicate the last channel out. */
1576 if (ir->type->is_scalar() || ir->type->is_vector())
1577 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
1578 else
1579 this->result.swizzle = SWIZZLE_NOOP;
1580
1581 this->result.index += offset;
1582 }
1583
1584 /**
1585 * We want to be careful in assignment setup to hit the actual storage
1586 * instead of potentially using a temporary like we might with the
1587 * ir_dereference handler.
1588 */
1589 static struct ir_to_mesa_dst_reg
1590 get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
1591 {
1592 /* The LHS must be a dereference. If the LHS is a variable indexed array
1593 * access of a vector, it must be separated into a series conditional moves
1594 * before reaching this point (see ir_vec_index_to_cond_assign).
1595 */
1596 assert(ir->as_dereference());
1597 ir_dereference_array *deref_array = ir->as_dereference_array();
1598 if (deref_array) {
1599 assert(!deref_array->array->type->is_vector());
1600 }
1601
1602 /* Use the rvalue deref handler for the most part. We'll ignore
1603 * swizzles in it and write swizzles using writemask, though.
1604 */
1605 ir->accept(v);
1606 return ir_to_mesa_dst_reg_from_src(v->result);
1607 }
1608
1609 /**
1610 * Process the condition of a conditional assignment
1611 *
1612 * Examines the condition of a conditional assignment to generate the optimal
1613 * first operand of a \c CMP instruction. If the condition is a relational
1614 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
1615 * used as the source for the \c CMP instruction. Otherwise the comparison
1616 * is processed to a boolean result, and the boolean result is used as the
1617 * operand to the CMP instruction.
1618 */
1619 bool
1620 ir_to_mesa_visitor::process_move_condition(ir_rvalue *ir)
1621 {
1622 ir_rvalue *src_ir = ir;
1623 bool negate = true;
1624 bool switch_order = false;
1625
1626 ir_expression *const expr = ir->as_expression();
1627 if ((expr != NULL) && (expr->get_num_operands() == 2)) {
1628 bool zero_on_left = false;
1629
1630 if (expr->operands[0]->is_zero()) {
1631 src_ir = expr->operands[1];
1632 zero_on_left = true;
1633 } else if (expr->operands[1]->is_zero()) {
1634 src_ir = expr->operands[0];
1635 zero_on_left = false;
1636 }
1637
1638 /* a is - 0 + - 0 +
1639 * (a < 0) T F F ( a < 0) T F F
1640 * (0 < a) F F T (-a < 0) F F T
1641 * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
1642 * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
1643 * (a > 0) F F T (-a < 0) F F T
1644 * (0 > a) T F F ( a < 0) T F F
1645 * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
1646 * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
1647 *
1648 * Note that exchanging the order of 0 and 'a' in the comparison simply
1649 * means that the value of 'a' should be negated.
1650 */
1651 if (src_ir != ir) {
1652 switch (expr->operation) {
1653 case ir_binop_less:
1654 switch_order = false;
1655 negate = zero_on_left;
1656 break;
1657
1658 case ir_binop_greater:
1659 switch_order = false;
1660 negate = !zero_on_left;
1661 break;
1662
1663 case ir_binop_lequal:
1664 switch_order = true;
1665 negate = !zero_on_left;
1666 break;
1667
1668 case ir_binop_gequal:
1669 switch_order = true;
1670 negate = zero_on_left;
1671 break;
1672
1673 default:
1674 /* This isn't the right kind of comparison afterall, so make sure
1675 * the whole condition is visited.
1676 */
1677 src_ir = ir;
1678 break;
1679 }
1680 }
1681 }
1682
1683 src_ir->accept(this);
1684
1685 /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
1686 * condition we produced is 0.0 or 1.0. By flipping the sign, we can
1687 * choose which value OPCODE_CMP produces without an extra instruction
1688 * computing the condition.
1689 */
1690 if (negate)
1691 this->result.negate = ~this->result.negate;
1692
1693 return switch_order;
1694 }
1695
1696 void
1697 ir_to_mesa_visitor::visit(ir_assignment *ir)
1698 {
1699 struct ir_to_mesa_dst_reg l;
1700 struct ir_to_mesa_src_reg r;
1701 int i;
1702
1703 ir->rhs->accept(this);
1704 r = this->result;
1705
1706 l = get_assignment_lhs(ir->lhs, this);
1707
1708 /* FINISHME: This should really set to the correct maximal writemask for each
1709 * FINISHME: component written (in the loops below). This case can only
1710 * FINISHME: occur for matrices, arrays, and structures.
1711 */
1712 if (ir->write_mask == 0) {
1713 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
1714 l.writemask = WRITEMASK_XYZW;
1715 } else if (ir->lhs->type->is_scalar()) {
1716 /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
1717 * FINISHME: W component of fragment shader output zero, work correctly.
1718 */
1719 l.writemask = WRITEMASK_XYZW;
1720 } else {
1721 int swizzles[4];
1722 int first_enabled_chan = 0;
1723 int rhs_chan = 0;
1724
1725 assert(ir->lhs->type->is_vector());
1726 l.writemask = ir->write_mask;
1727
1728 for (int i = 0; i < 4; i++) {
1729 if (l.writemask & (1 << i)) {
1730 first_enabled_chan = GET_SWZ(r.swizzle, i);
1731 break;
1732 }
1733 }
1734
1735 /* Swizzle a small RHS vector into the channels being written.
1736 *
1737 * glsl ir treats write_mask as dictating how many channels are
1738 * present on the RHS while Mesa IR treats write_mask as just
1739 * showing which channels of the vec4 RHS get written.
1740 */
1741 for (int i = 0; i < 4; i++) {
1742 if (l.writemask & (1 << i))
1743 swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
1744 else
1745 swizzles[i] = first_enabled_chan;
1746 }
1747 r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
1748 swizzles[2], swizzles[3]);
1749 }
1750
1751 assert(l.file != PROGRAM_UNDEFINED);
1752 assert(r.file != PROGRAM_UNDEFINED);
1753
1754 if (ir->condition) {
1755 const bool switch_order = this->process_move_condition(ir->condition);
1756 ir_to_mesa_src_reg condition = this->result;
1757
1758 for (i = 0; i < type_size(ir->lhs->type); i++) {
1759 if (switch_order) {
1760 ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
1761 condition, ir_to_mesa_src_reg_from_dst(l), r);
1762 } else {
1763 ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
1764 condition, r, ir_to_mesa_src_reg_from_dst(l));
1765 }
1766
1767 l.index++;
1768 r.index++;
1769 }
1770 } else {
1771 for (i = 0; i < type_size(ir->lhs->type); i++) {
1772 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
1773 l.index++;
1774 r.index++;
1775 }
1776 }
1777 }
1778
1779
1780 void
1781 ir_to_mesa_visitor::visit(ir_constant *ir)
1782 {
1783 ir_to_mesa_src_reg src_reg;
1784 GLfloat stack_vals[4] = { 0 };
1785 GLfloat *values = stack_vals;
1786 unsigned int i;
1787
1788 /* Unfortunately, 4 floats is all we can get into
1789 * _mesa_add_unnamed_constant. So, make a temp to store an
1790 * aggregate constant and move each constant value into it. If we
1791 * get lucky, copy propagation will eliminate the extra moves.
1792 */
1793
1794 if (ir->type->base_type == GLSL_TYPE_STRUCT) {
1795 ir_to_mesa_src_reg temp_base = get_temp(ir->type);
1796 ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
1797
1798 foreach_iter(exec_list_iterator, iter, ir->components) {
1799 ir_constant *field_value = (ir_constant *)iter.get();
1800 int size = type_size(field_value->type);
1801
1802 assert(size > 0);
1803
1804 field_value->accept(this);
1805 src_reg = this->result;
1806
1807 for (i = 0; i < (unsigned int)size; i++) {
1808 ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
1809
1810 src_reg.index++;
1811 temp.index++;
1812 }
1813 }
1814 this->result = temp_base;
1815 return;
1816 }
1817
1818 if (ir->type->is_array()) {
1819 ir_to_mesa_src_reg temp_base = get_temp(ir->type);
1820 ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
1821 int size = type_size(ir->type->fields.array);
1822
1823 assert(size > 0);
1824
1825 for (i = 0; i < ir->type->length; i++) {
1826 ir->array_elements[i]->accept(this);
1827 src_reg = this->result;
1828 for (int j = 0; j < size; j++) {
1829 ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
1830
1831 src_reg.index++;
1832 temp.index++;
1833 }
1834 }
1835 this->result = temp_base;
1836 return;
1837 }
1838
1839 if (ir->type->is_matrix()) {
1840 ir_to_mesa_src_reg mat = get_temp(ir->type);
1841 ir_to_mesa_dst_reg mat_column = ir_to_mesa_dst_reg_from_src(mat);
1842
1843 for (i = 0; i < ir->type->matrix_columns; i++) {
1844 assert(ir->type->base_type == GLSL_TYPE_FLOAT);
1845 values = &ir->value.f[i * ir->type->vector_elements];
1846
1847 src_reg = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, NULL);
1848 src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1849 values,
1850 ir->type->vector_elements,
1851 &src_reg.swizzle);
1852 ir_to_mesa_emit_op1(ir, OPCODE_MOV, mat_column, src_reg);
1853
1854 mat_column.index++;
1855 }
1856
1857 this->result = mat;
1858 return;
1859 }
1860
1861 src_reg.file = PROGRAM_CONSTANT;
1862 switch (ir->type->base_type) {
1863 case GLSL_TYPE_FLOAT:
1864 values = &ir->value.f[0];
1865 break;
1866 case GLSL_TYPE_UINT:
1867 for (i = 0; i < ir->type->vector_elements; i++) {
1868 values[i] = ir->value.u[i];
1869 }
1870 break;
1871 case GLSL_TYPE_INT:
1872 for (i = 0; i < ir->type->vector_elements; i++) {
1873 values[i] = ir->value.i[i];
1874 }
1875 break;
1876 case GLSL_TYPE_BOOL:
1877 for (i = 0; i < ir->type->vector_elements; i++) {
1878 values[i] = ir->value.b[i];
1879 }
1880 break;
1881 default:
1882 assert(!"Non-float/uint/int/bool constant");
1883 }
1884
1885 this->result = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, ir->type);
1886 this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1887 values,
1888 ir->type->vector_elements,
1889 &this->result.swizzle);
1890 }
1891
1892 function_entry *
1893 ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
1894 {
1895 function_entry *entry;
1896
1897 foreach_iter(exec_list_iterator, iter, this->function_signatures) {
1898 entry = (function_entry *)iter.get();
1899
1900 if (entry->sig == sig)
1901 return entry;
1902 }
1903
1904 entry = talloc(mem_ctx, function_entry);
1905 entry->sig = sig;
1906 entry->sig_id = this->next_signature_id++;
1907 entry->bgn_inst = NULL;
1908
1909 /* Allocate storage for all the parameters. */
1910 foreach_iter(exec_list_iterator, iter, sig->parameters) {
1911 ir_variable *param = (ir_variable *)iter.get();
1912 variable_storage *storage;
1913
1914 storage = find_variable_storage(param);
1915 assert(!storage);
1916
1917 storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
1918 this->next_temp);
1919 this->variables.push_tail(storage);
1920
1921 this->next_temp += type_size(param->type);
1922 }
1923
1924 if (!sig->return_type->is_void()) {
1925 entry->return_reg = get_temp(sig->return_type);
1926 } else {
1927 entry->return_reg = ir_to_mesa_undef;
1928 }
1929
1930 this->function_signatures.push_tail(entry);
1931 return entry;
1932 }
1933
1934 void
1935 ir_to_mesa_visitor::visit(ir_call *ir)
1936 {
1937 ir_to_mesa_instruction *call_inst;
1938 ir_function_signature *sig = ir->get_callee();
1939 function_entry *entry = get_function_signature(sig);
1940 int i;
1941
1942 /* Process in parameters. */
1943 exec_list_iterator sig_iter = sig->parameters.iterator();
1944 foreach_iter(exec_list_iterator, iter, *ir) {
1945 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1946 ir_variable *param = (ir_variable *)sig_iter.get();
1947
1948 if (param->mode == ir_var_in ||
1949 param->mode == ir_var_inout) {
1950 variable_storage *storage = find_variable_storage(param);
1951 assert(storage);
1952
1953 param_rval->accept(this);
1954 ir_to_mesa_src_reg r = this->result;
1955
1956 ir_to_mesa_dst_reg l;
1957 l.file = storage->file;
1958 l.index = storage->index;
1959 l.reladdr = NULL;
1960 l.writemask = WRITEMASK_XYZW;
1961 l.cond_mask = COND_TR;
1962
1963 for (i = 0; i < type_size(param->type); i++) {
1964 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
1965 l.index++;
1966 r.index++;
1967 }
1968 }
1969
1970 sig_iter.next();
1971 }
1972 assert(!sig_iter.has_next());
1973
1974 /* Emit call instruction */
1975 call_inst = ir_to_mesa_emit_op1(ir, OPCODE_CAL,
1976 ir_to_mesa_undef_dst, ir_to_mesa_undef);
1977 call_inst->function = entry;
1978
1979 /* Process out parameters. */
1980 sig_iter = sig->parameters.iterator();
1981 foreach_iter(exec_list_iterator, iter, *ir) {
1982 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1983 ir_variable *param = (ir_variable *)sig_iter.get();
1984
1985 if (param->mode == ir_var_out ||
1986 param->mode == ir_var_inout) {
1987 variable_storage *storage = find_variable_storage(param);
1988 assert(storage);
1989
1990 ir_to_mesa_src_reg r;
1991 r.file = storage->file;
1992 r.index = storage->index;
1993 r.reladdr = NULL;
1994 r.swizzle = SWIZZLE_NOOP;
1995 r.negate = 0;
1996
1997 param_rval->accept(this);
1998 ir_to_mesa_dst_reg l = ir_to_mesa_dst_reg_from_src(this->result);
1999
2000 for (i = 0; i < type_size(param->type); i++) {
2001 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
2002 l.index++;
2003 r.index++;
2004 }
2005 }
2006
2007 sig_iter.next();
2008 }
2009 assert(!sig_iter.has_next());
2010
2011 /* Process return value. */
2012 this->result = entry->return_reg;
2013 }
2014
2015 void
2016 ir_to_mesa_visitor::visit(ir_texture *ir)
2017 {
2018 ir_to_mesa_src_reg result_src, coord, lod_info, projector;
2019 ir_to_mesa_dst_reg result_dst, coord_dst;
2020 ir_to_mesa_instruction *inst = NULL;
2021 prog_opcode opcode = OPCODE_NOP;
2022
2023 ir->coordinate->accept(this);
2024
2025 /* Put our coords in a temp. We'll need to modify them for shadow,
2026 * projection, or LOD, so the only case we'd use it as is is if
2027 * we're doing plain old texturing. Mesa IR optimization should
2028 * handle cleaning up our mess in that case.
2029 */
2030 coord = get_temp(glsl_type::vec4_type);
2031 coord_dst = ir_to_mesa_dst_reg_from_src(coord);
2032 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst,
2033 this->result);
2034
2035 if (ir->projector) {
2036 ir->projector->accept(this);
2037 projector = this->result;
2038 }
2039
2040 /* Storage for our result. Ideally for an assignment we'd be using
2041 * the actual storage for the result here, instead.
2042 */
2043 result_src = get_temp(glsl_type::vec4_type);
2044 result_dst = ir_to_mesa_dst_reg_from_src(result_src);
2045
2046 switch (ir->op) {
2047 case ir_tex:
2048 opcode = OPCODE_TEX;
2049 break;
2050 case ir_txb:
2051 opcode = OPCODE_TXB;
2052 ir->lod_info.bias->accept(this);
2053 lod_info = this->result;
2054 break;
2055 case ir_txl:
2056 opcode = OPCODE_TXL;
2057 ir->lod_info.lod->accept(this);
2058 lod_info = this->result;
2059 break;
2060 case ir_txd:
2061 case ir_txf:
2062 assert(!"GLSL 1.30 features unsupported");
2063 break;
2064 }
2065
2066 if (ir->projector) {
2067 if (opcode == OPCODE_TEX) {
2068 /* Slot the projector in as the last component of the coord. */
2069 coord_dst.writemask = WRITEMASK_W;
2070 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, projector);
2071 coord_dst.writemask = WRITEMASK_XYZW;
2072 opcode = OPCODE_TXP;
2073 } else {
2074 ir_to_mesa_src_reg coord_w = coord;
2075 coord_w.swizzle = SWIZZLE_WWWW;
2076
2077 /* For the other TEX opcodes there's no projective version
2078 * since the last slot is taken up by lod info. Do the
2079 * projective divide now.
2080 */
2081 coord_dst.writemask = WRITEMASK_W;
2082 ir_to_mesa_emit_op1(ir, OPCODE_RCP, coord_dst, projector);
2083
2084 coord_dst.writemask = WRITEMASK_XYZ;
2085 ir_to_mesa_emit_op2(ir, OPCODE_MUL, coord_dst, coord, coord_w);
2086
2087 coord_dst.writemask = WRITEMASK_XYZW;
2088 coord.swizzle = SWIZZLE_XYZW;
2089 }
2090 }
2091
2092 if (ir->shadow_comparitor) {
2093 /* Slot the shadow value in as the second to last component of the
2094 * coord.
2095 */
2096 ir->shadow_comparitor->accept(this);
2097 coord_dst.writemask = WRITEMASK_Z;
2098 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, this->result);
2099 coord_dst.writemask = WRITEMASK_XYZW;
2100 }
2101
2102 if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
2103 /* Mesa IR stores lod or lod bias in the last channel of the coords. */
2104 coord_dst.writemask = WRITEMASK_W;
2105 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, lod_info);
2106 coord_dst.writemask = WRITEMASK_XYZW;
2107 }
2108
2109 inst = ir_to_mesa_emit_op1(ir, opcode, result_dst, coord);
2110
2111 if (ir->shadow_comparitor)
2112 inst->tex_shadow = GL_TRUE;
2113
2114 inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
2115 this->shader_program,
2116 this->prog);
2117
2118 const glsl_type *sampler_type = ir->sampler->type;
2119
2120 switch (sampler_type->sampler_dimensionality) {
2121 case GLSL_SAMPLER_DIM_1D:
2122 inst->tex_target = (sampler_type->sampler_array)
2123 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
2124 break;
2125 case GLSL_SAMPLER_DIM_2D:
2126 inst->tex_target = (sampler_type->sampler_array)
2127 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
2128 break;
2129 case GLSL_SAMPLER_DIM_3D:
2130 inst->tex_target = TEXTURE_3D_INDEX;
2131 break;
2132 case GLSL_SAMPLER_DIM_CUBE:
2133 inst->tex_target = TEXTURE_CUBE_INDEX;
2134 break;
2135 case GLSL_SAMPLER_DIM_RECT:
2136 inst->tex_target = TEXTURE_RECT_INDEX;
2137 break;
2138 case GLSL_SAMPLER_DIM_BUF:
2139 assert(!"FINISHME: Implement ARB_texture_buffer_object");
2140 break;
2141 default:
2142 assert(!"Should not get here.");
2143 }
2144
2145 this->result = result_src;
2146 }
2147
2148 void
2149 ir_to_mesa_visitor::visit(ir_return *ir)
2150 {
2151 if (ir->get_value()) {
2152 ir_to_mesa_dst_reg l;
2153 int i;
2154
2155 assert(current_function);
2156
2157 ir->get_value()->accept(this);
2158 ir_to_mesa_src_reg r = this->result;
2159
2160 l = ir_to_mesa_dst_reg_from_src(current_function->return_reg);
2161
2162 for (i = 0; i < type_size(current_function->sig->return_type); i++) {
2163 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
2164 l.index++;
2165 r.index++;
2166 }
2167 }
2168
2169 ir_to_mesa_emit_op0(ir, OPCODE_RET);
2170 }
2171
2172 void
2173 ir_to_mesa_visitor::visit(ir_discard *ir)
2174 {
2175 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
2176
2177 if (ir->condition) {
2178 ir->condition->accept(this);
2179 this->result.negate = ~this->result.negate;
2180 ir_to_mesa_emit_op1(ir, OPCODE_KIL, ir_to_mesa_undef_dst, this->result);
2181 } else {
2182 ir_to_mesa_emit_op0(ir, OPCODE_KIL_NV);
2183 }
2184
2185 fp->UsesKill = GL_TRUE;
2186 }
2187
2188 void
2189 ir_to_mesa_visitor::visit(ir_if *ir)
2190 {
2191 ir_to_mesa_instruction *cond_inst, *if_inst, *else_inst = NULL;
2192 ir_to_mesa_instruction *prev_inst;
2193
2194 prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2195
2196 ir->condition->accept(this);
2197 assert(this->result.file != PROGRAM_UNDEFINED);
2198
2199 if (this->options->EmitCondCodes) {
2200 cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2201
2202 /* See if we actually generated any instruction for generating
2203 * the condition. If not, then cook up a move to a temp so we
2204 * have something to set cond_update on.
2205 */
2206 if (cond_inst == prev_inst) {
2207 ir_to_mesa_src_reg temp = get_temp(glsl_type::bool_type);
2208 cond_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_MOV,
2209 ir_to_mesa_dst_reg_from_src(temp),
2210 result);
2211 }
2212 cond_inst->cond_update = GL_TRUE;
2213
2214 if_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_IF);
2215 if_inst->dst_reg.cond_mask = COND_NE;
2216 } else {
2217 if_inst = ir_to_mesa_emit_op1(ir->condition,
2218 OPCODE_IF, ir_to_mesa_undef_dst,
2219 this->result);
2220 }
2221
2222 this->instructions.push_tail(if_inst);
2223
2224 visit_exec_list(&ir->then_instructions, this);
2225
2226 if (!ir->else_instructions.is_empty()) {
2227 else_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_ELSE);
2228 visit_exec_list(&ir->else_instructions, this);
2229 }
2230
2231 if_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_ENDIF,
2232 ir_to_mesa_undef_dst, ir_to_mesa_undef);
2233 }
2234
2235 ir_to_mesa_visitor::ir_to_mesa_visitor()
2236 {
2237 result.file = PROGRAM_UNDEFINED;
2238 next_temp = 1;
2239 next_signature_id = 1;
2240 current_function = NULL;
2241 mem_ctx = talloc_new(NULL);
2242 }
2243
2244 ir_to_mesa_visitor::~ir_to_mesa_visitor()
2245 {
2246 talloc_free(mem_ctx);
2247 }
2248
2249 static struct prog_src_register
2250 mesa_src_reg_from_ir_src_reg(ir_to_mesa_src_reg reg)
2251 {
2252 struct prog_src_register mesa_reg;
2253
2254 mesa_reg.File = reg.file;
2255 assert(reg.index < (1 << INST_INDEX_BITS));
2256 mesa_reg.Index = reg.index;
2257 mesa_reg.Swizzle = reg.swizzle;
2258 mesa_reg.RelAddr = reg.reladdr != NULL;
2259 mesa_reg.Negate = reg.negate;
2260 mesa_reg.Abs = 0;
2261 mesa_reg.HasIndex2 = GL_FALSE;
2262 mesa_reg.RelAddr2 = 0;
2263 mesa_reg.Index2 = 0;
2264
2265 return mesa_reg;
2266 }
2267
2268 static void
2269 set_branchtargets(ir_to_mesa_visitor *v,
2270 struct prog_instruction *mesa_instructions,
2271 int num_instructions)
2272 {
2273 int if_count = 0, loop_count = 0;
2274 int *if_stack, *loop_stack;
2275 int if_stack_pos = 0, loop_stack_pos = 0;
2276 int i, j;
2277
2278 for (i = 0; i < num_instructions; i++) {
2279 switch (mesa_instructions[i].Opcode) {
2280 case OPCODE_IF:
2281 if_count++;
2282 break;
2283 case OPCODE_BGNLOOP:
2284 loop_count++;
2285 break;
2286 case OPCODE_BRK:
2287 case OPCODE_CONT:
2288 mesa_instructions[i].BranchTarget = -1;
2289 break;
2290 default:
2291 break;
2292 }
2293 }
2294
2295 if_stack = talloc_zero_array(v->mem_ctx, int, if_count);
2296 loop_stack = talloc_zero_array(v->mem_ctx, int, loop_count);
2297
2298 for (i = 0; i < num_instructions; i++) {
2299 switch (mesa_instructions[i].Opcode) {
2300 case OPCODE_IF:
2301 if_stack[if_stack_pos] = i;
2302 if_stack_pos++;
2303 break;
2304 case OPCODE_ELSE:
2305 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2306 if_stack[if_stack_pos - 1] = i;
2307 break;
2308 case OPCODE_ENDIF:
2309 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2310 if_stack_pos--;
2311 break;
2312 case OPCODE_BGNLOOP:
2313 loop_stack[loop_stack_pos] = i;
2314 loop_stack_pos++;
2315 break;
2316 case OPCODE_ENDLOOP:
2317 loop_stack_pos--;
2318 /* Rewrite any breaks/conts at this nesting level (haven't
2319 * already had a BranchTarget assigned) to point to the end
2320 * of the loop.
2321 */
2322 for (j = loop_stack[loop_stack_pos]; j < i; j++) {
2323 if (mesa_instructions[j].Opcode == OPCODE_BRK ||
2324 mesa_instructions[j].Opcode == OPCODE_CONT) {
2325 if (mesa_instructions[j].BranchTarget == -1) {
2326 mesa_instructions[j].BranchTarget = i;
2327 }
2328 }
2329 }
2330 /* The loop ends point at each other. */
2331 mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
2332 mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
2333 break;
2334 case OPCODE_CAL:
2335 foreach_iter(exec_list_iterator, iter, v->function_signatures) {
2336 function_entry *entry = (function_entry *)iter.get();
2337
2338 if (entry->sig_id == mesa_instructions[i].BranchTarget) {
2339 mesa_instructions[i].BranchTarget = entry->inst;
2340 break;
2341 }
2342 }
2343 break;
2344 default:
2345 break;
2346 }
2347 }
2348 }
2349
2350 static void
2351 print_program(struct prog_instruction *mesa_instructions,
2352 ir_instruction **mesa_instruction_annotation,
2353 int num_instructions)
2354 {
2355 ir_instruction *last_ir = NULL;
2356 int i;
2357 int indent = 0;
2358
2359 for (i = 0; i < num_instructions; i++) {
2360 struct prog_instruction *mesa_inst = mesa_instructions + i;
2361 ir_instruction *ir = mesa_instruction_annotation[i];
2362
2363 fprintf(stdout, "%3d: ", i);
2364
2365 if (last_ir != ir && ir) {
2366 int j;
2367
2368 for (j = 0; j < indent; j++) {
2369 fprintf(stdout, " ");
2370 }
2371 ir->print();
2372 printf("\n");
2373 last_ir = ir;
2374
2375 fprintf(stdout, " "); /* line number spacing. */
2376 }
2377
2378 indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
2379 PROG_PRINT_DEBUG, NULL);
2380 }
2381 }
2382
2383 static void
2384 count_resources(struct gl_program *prog)
2385 {
2386 unsigned int i;
2387
2388 prog->SamplersUsed = 0;
2389
2390 for (i = 0; i < prog->NumInstructions; i++) {
2391 struct prog_instruction *inst = &prog->Instructions[i];
2392
2393 if (_mesa_is_tex_instruction(inst->Opcode)) {
2394 prog->SamplerTargets[inst->TexSrcUnit] =
2395 (gl_texture_index)inst->TexSrcTarget;
2396 prog->SamplersUsed |= 1 << inst->TexSrcUnit;
2397 if (inst->TexShadow) {
2398 prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
2399 }
2400 }
2401 }
2402
2403 _mesa_update_shader_textures_used(prog);
2404 }
2405
2406 struct uniform_sort {
2407 struct gl_uniform *u;
2408 int pos;
2409 };
2410
2411 /* The shader_program->Uniforms list is almost sorted in increasing
2412 * uniform->{Frag,Vert}Pos locations, but not quite when there are
2413 * uniforms shared between targets. We need to add parameters in
2414 * increasing order for the targets.
2415 */
2416 static int
2417 sort_uniforms(const void *a, const void *b)
2418 {
2419 struct uniform_sort *u1 = (struct uniform_sort *)a;
2420 struct uniform_sort *u2 = (struct uniform_sort *)b;
2421
2422 return u1->pos - u2->pos;
2423 }
2424
2425 /* Add the uniforms to the parameters. The linker chose locations
2426 * in our parameters lists (which weren't created yet), which the
2427 * uniforms code will use to poke values into our parameters list
2428 * when uniforms are updated.
2429 */
2430 static void
2431 add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
2432 struct gl_shader *shader,
2433 struct gl_program *prog)
2434 {
2435 unsigned int i;
2436 unsigned int next_sampler = 0, num_uniforms = 0;
2437 struct uniform_sort *sorted_uniforms;
2438
2439 sorted_uniforms = talloc_array(NULL, struct uniform_sort,
2440 shader_program->Uniforms->NumUniforms);
2441
2442 for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
2443 struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
2444 int parameter_index = -1;
2445
2446 switch (shader->Type) {
2447 case GL_VERTEX_SHADER:
2448 parameter_index = uniform->VertPos;
2449 break;
2450 case GL_FRAGMENT_SHADER:
2451 parameter_index = uniform->FragPos;
2452 break;
2453 case GL_GEOMETRY_SHADER:
2454 parameter_index = uniform->GeomPos;
2455 break;
2456 }
2457
2458 /* Only add uniforms used in our target. */
2459 if (parameter_index != -1) {
2460 sorted_uniforms[num_uniforms].pos = parameter_index;
2461 sorted_uniforms[num_uniforms].u = uniform;
2462 num_uniforms++;
2463 }
2464 }
2465
2466 qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
2467 sort_uniforms);
2468
2469 for (i = 0; i < num_uniforms; i++) {
2470 struct gl_uniform *uniform = sorted_uniforms[i].u;
2471 int parameter_index = sorted_uniforms[i].pos;
2472 const glsl_type *type = uniform->Type;
2473 unsigned int size;
2474
2475 if (type->is_vector() ||
2476 type->is_scalar()) {
2477 size = type->vector_elements;
2478 } else {
2479 size = type_size(type) * 4;
2480 }
2481
2482 gl_register_file file;
2483 if (type->is_sampler() ||
2484 (type->is_array() && type->fields.array->is_sampler())) {
2485 file = PROGRAM_SAMPLER;
2486 } else {
2487 file = PROGRAM_UNIFORM;
2488 }
2489
2490 GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
2491 uniform->Name);
2492
2493 if (index < 0) {
2494 index = _mesa_add_parameter(prog->Parameters, file,
2495 uniform->Name, size, type->gl_type,
2496 NULL, NULL, 0x0);
2497
2498 /* Sampler uniform values are stored in prog->SamplerUnits,
2499 * and the entry in that array is selected by this index we
2500 * store in ParameterValues[].
2501 */
2502 if (file == PROGRAM_SAMPLER) {
2503 for (unsigned int j = 0; j < size / 4; j++)
2504 prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
2505 }
2506
2507 /* The location chosen in the Parameters list here (returned
2508 * from _mesa_add_uniform) has to match what the linker chose.
2509 */
2510 if (index != parameter_index) {
2511 fail_link(shader_program, "Allocation of uniform `%s' to target "
2512 "failed (%d vs %d)\n",
2513 uniform->Name, index, parameter_index);
2514 }
2515 }
2516 }
2517
2518 talloc_free(sorted_uniforms);
2519 }
2520
2521 static void
2522 set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
2523 struct gl_shader_program *shader_program,
2524 const char *name, const glsl_type *type,
2525 ir_constant *val)
2526 {
2527 if (type->is_record()) {
2528 ir_constant *field_constant;
2529
2530 field_constant = (ir_constant *)val->components.get_head();
2531
2532 for (unsigned int i = 0; i < type->length; i++) {
2533 const glsl_type *field_type = type->fields.structure[i].type;
2534 const char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
2535 type->fields.structure[i].name);
2536 set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
2537 field_type, field_constant);
2538 field_constant = (ir_constant *)field_constant->next;
2539 }
2540 return;
2541 }
2542
2543 int loc = _mesa_get_uniform_location(ctx, shader_program, name);
2544
2545 if (loc == -1) {
2546 fail_link(shader_program,
2547 "Couldn't find uniform for initializer %s\n", name);
2548 return;
2549 }
2550
2551 for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
2552 ir_constant *element;
2553 const glsl_type *element_type;
2554 if (type->is_array()) {
2555 element = val->array_elements[i];
2556 element_type = type->fields.array;
2557 } else {
2558 element = val;
2559 element_type = type;
2560 }
2561
2562 void *values;
2563
2564 if (element_type->base_type == GLSL_TYPE_BOOL) {
2565 int *conv = talloc_array(mem_ctx, int, element_type->components());
2566 for (unsigned int j = 0; j < element_type->components(); j++) {
2567 conv[j] = element->value.b[j];
2568 }
2569 values = (void *)conv;
2570 element_type = glsl_type::get_instance(GLSL_TYPE_INT,
2571 element_type->vector_elements,
2572 1);
2573 } else {
2574 values = &element->value;
2575 }
2576
2577 if (element_type->is_matrix()) {
2578 _mesa_uniform_matrix(ctx, shader_program,
2579 element_type->matrix_columns,
2580 element_type->vector_elements,
2581 loc, 1, GL_FALSE, (GLfloat *)values);
2582 loc += element_type->matrix_columns;
2583 } else {
2584 _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
2585 values, element_type->gl_type);
2586 loc += type_size(element_type);
2587 }
2588 }
2589 }
2590
2591 static void
2592 set_uniform_initializers(struct gl_context *ctx,
2593 struct gl_shader_program *shader_program)
2594 {
2595 void *mem_ctx = NULL;
2596
2597 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2598 struct gl_shader *shader = shader_program->_LinkedShaders[i];
2599
2600 if (shader == NULL)
2601 continue;
2602
2603 foreach_iter(exec_list_iterator, iter, *shader->ir) {
2604 ir_instruction *ir = (ir_instruction *)iter.get();
2605 ir_variable *var = ir->as_variable();
2606
2607 if (!var || var->mode != ir_var_uniform || !var->constant_value)
2608 continue;
2609
2610 if (!mem_ctx)
2611 mem_ctx = talloc_new(NULL);
2612
2613 set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
2614 var->type, var->constant_value);
2615 }
2616 }
2617
2618 talloc_free(mem_ctx);
2619 }
2620
2621 /*
2622 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
2623 * channels for copy propagation and updates following instructions to
2624 * use the original versions.
2625 *
2626 * The ir_to_mesa_visitor lazily produces code assuming that this pass
2627 * will occur. As an example, a TXP production before this pass:
2628 *
2629 * 0: MOV TEMP[1], INPUT[4].xyyy;
2630 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2631 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
2632 *
2633 * and after:
2634 *
2635 * 0: MOV TEMP[1], INPUT[4].xyyy;
2636 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2637 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
2638 *
2639 * which allows for dead code elimination on TEMP[1]'s writes.
2640 */
2641 void
2642 ir_to_mesa_visitor::copy_propagate(void)
2643 {
2644 ir_to_mesa_instruction *acp[this->next_temp * 4];
2645
2646 memset(&acp, 0, sizeof(acp));
2647
2648 foreach_iter(exec_list_iterator, iter, this->instructions) {
2649 ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2650
2651 /* First, do any copy propagation possible into the src regs. */
2652 for (int r = 0; r < 3; r++) {
2653 ir_to_mesa_instruction *first = NULL;
2654 bool good = true;
2655 int acp_base = inst->src_reg[r].index * 4;
2656
2657 if (inst->src_reg[r].file != PROGRAM_TEMPORARY ||
2658 inst->src_reg[r].reladdr)
2659 continue;
2660
2661 /* See if we can find entries in the ACP consisting of MOVs
2662 * from the same src register for all the swizzled channels
2663 * of this src register reference.
2664 */
2665 for (int i = 0; i < 4; i++) {
2666 int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
2667 ir_to_mesa_instruction *copy_chan = acp[acp_base + src_chan];
2668
2669 if (!copy_chan) {
2670 good = false;
2671 break;
2672 }
2673
2674 if (!first) {
2675 first = copy_chan;
2676 } else {
2677 if (first->src_reg[0].file != copy_chan->src_reg[0].file ||
2678 first->src_reg[0].index != copy_chan->src_reg[0].index) {
2679 good = false;
2680 break;
2681 }
2682 }
2683 }
2684
2685 if (good) {
2686 /* We've now validated that we can copy-propagate to
2687 * replace this src register reference. Do it.
2688 */
2689 inst->src_reg[r].file = first->src_reg[0].file;
2690 inst->src_reg[r].index = first->src_reg[0].index;
2691
2692 int swizzle = 0;
2693 for (int i = 0; i < 4; i++) {
2694 int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
2695 ir_to_mesa_instruction *copy_inst = acp[acp_base + src_chan];
2696 swizzle |= (GET_SWZ(copy_inst->src_reg[0].swizzle, src_chan) <<
2697 (3 * i));
2698 }
2699 inst->src_reg[r].swizzle = swizzle;
2700 }
2701 }
2702
2703 switch (inst->op) {
2704 case OPCODE_BGNLOOP:
2705 case OPCODE_ENDLOOP:
2706 case OPCODE_ELSE:
2707 case OPCODE_ENDIF:
2708 /* End of a basic block, clear the ACP entirely. */
2709 memset(&acp, 0, sizeof(acp));
2710 break;
2711
2712 default:
2713 /* Continuing the block, clear any written channels from
2714 * the ACP.
2715 */
2716 if (inst->dst_reg.file == PROGRAM_TEMPORARY) {
2717 if (inst->dst_reg.reladdr) {
2718 memset(&acp, 0, sizeof(acp));
2719 } else {
2720 for (int i = 0; i < 4; i++) {
2721 if (inst->dst_reg.writemask & (1 << i)) {
2722 acp[4 * inst->dst_reg.index + i] = NULL;
2723 }
2724 }
2725 }
2726 }
2727 break;
2728 }
2729
2730 /* If this is a copy, add it to the ACP. */
2731 if (inst->op == OPCODE_MOV &&
2732 inst->dst_reg.file == PROGRAM_TEMPORARY &&
2733 !inst->dst_reg.reladdr &&
2734 !inst->saturate &&
2735 !inst->src_reg[0].reladdr &&
2736 !inst->src_reg[0].negate) {
2737 for (int i = 0; i < 4; i++) {
2738 if (inst->dst_reg.writemask & (1 << i)) {
2739 acp[4 * inst->dst_reg.index + i] = inst;
2740 }
2741 }
2742 }
2743 }
2744 }
2745
2746
2747 /**
2748 * Convert a shader's GLSL IR into a Mesa gl_program.
2749 */
2750 static struct gl_program *
2751 get_mesa_program(struct gl_context *ctx,
2752 struct gl_shader_program *shader_program,
2753 struct gl_shader *shader)
2754 {
2755 ir_to_mesa_visitor v;
2756 struct prog_instruction *mesa_instructions, *mesa_inst;
2757 ir_instruction **mesa_instruction_annotation;
2758 int i;
2759 struct gl_program *prog;
2760 GLenum target;
2761 const char *target_string;
2762 GLboolean progress;
2763 struct gl_shader_compiler_options *options =
2764 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
2765
2766 switch (shader->Type) {
2767 case GL_VERTEX_SHADER:
2768 target = GL_VERTEX_PROGRAM_ARB;
2769 target_string = "vertex";
2770 break;
2771 case GL_FRAGMENT_SHADER:
2772 target = GL_FRAGMENT_PROGRAM_ARB;
2773 target_string = "fragment";
2774 break;
2775 case GL_GEOMETRY_SHADER:
2776 target = GL_GEOMETRY_PROGRAM_NV;
2777 target_string = "geometry";
2778 break;
2779 default:
2780 assert(!"should not be reached");
2781 return NULL;
2782 }
2783
2784 validate_ir_tree(shader->ir);
2785
2786 prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
2787 if (!prog)
2788 return NULL;
2789 prog->Parameters = _mesa_new_parameter_list();
2790 prog->Varying = _mesa_new_parameter_list();
2791 prog->Attributes = _mesa_new_parameter_list();
2792 v.ctx = ctx;
2793 v.prog = prog;
2794 v.shader_program = shader_program;
2795 v.options = options;
2796
2797 add_uniforms_to_parameters_list(shader_program, shader, prog);
2798
2799 /* Emit Mesa IR for main(). */
2800 visit_exec_list(shader->ir, &v);
2801 v.ir_to_mesa_emit_op0(NULL, OPCODE_END);
2802
2803 /* Now emit bodies for any functions that were used. */
2804 do {
2805 progress = GL_FALSE;
2806
2807 foreach_iter(exec_list_iterator, iter, v.function_signatures) {
2808 function_entry *entry = (function_entry *)iter.get();
2809
2810 if (!entry->bgn_inst) {
2811 v.current_function = entry;
2812
2813 entry->bgn_inst = v.ir_to_mesa_emit_op0(NULL, OPCODE_BGNSUB);
2814 entry->bgn_inst->function = entry;
2815
2816 visit_exec_list(&entry->sig->body, &v);
2817
2818 ir_to_mesa_instruction *last;
2819 last = (ir_to_mesa_instruction *)v.instructions.get_tail();
2820 if (last->op != OPCODE_RET)
2821 v.ir_to_mesa_emit_op0(NULL, OPCODE_RET);
2822
2823 ir_to_mesa_instruction *end;
2824 end = v.ir_to_mesa_emit_op0(NULL, OPCODE_ENDSUB);
2825 end->function = entry;
2826
2827 progress = GL_TRUE;
2828 }
2829 }
2830 } while (progress);
2831
2832 prog->NumTemporaries = v.next_temp;
2833
2834 int num_instructions = 0;
2835 foreach_iter(exec_list_iterator, iter, v.instructions) {
2836 num_instructions++;
2837 }
2838
2839 mesa_instructions =
2840 (struct prog_instruction *)calloc(num_instructions,
2841 sizeof(*mesa_instructions));
2842 mesa_instruction_annotation = talloc_array(v.mem_ctx, ir_instruction *,
2843 num_instructions);
2844
2845 v.copy_propagate();
2846
2847 /* Convert ir_mesa_instructions into prog_instructions.
2848 */
2849 mesa_inst = mesa_instructions;
2850 i = 0;
2851 foreach_iter(exec_list_iterator, iter, v.instructions) {
2852 const ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2853
2854 mesa_inst->Opcode = inst->op;
2855 mesa_inst->CondUpdate = inst->cond_update;
2856 if (inst->saturate)
2857 mesa_inst->SaturateMode = SATURATE_ZERO_ONE;
2858 mesa_inst->DstReg.File = inst->dst_reg.file;
2859 mesa_inst->DstReg.Index = inst->dst_reg.index;
2860 mesa_inst->DstReg.CondMask = inst->dst_reg.cond_mask;
2861 mesa_inst->DstReg.WriteMask = inst->dst_reg.writemask;
2862 mesa_inst->DstReg.RelAddr = inst->dst_reg.reladdr != NULL;
2863 mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src_reg[0]);
2864 mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src_reg[1]);
2865 mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src_reg[2]);
2866 mesa_inst->TexSrcUnit = inst->sampler;
2867 mesa_inst->TexSrcTarget = inst->tex_target;
2868 mesa_inst->TexShadow = inst->tex_shadow;
2869 mesa_instruction_annotation[i] = inst->ir;
2870
2871 /* Set IndirectRegisterFiles. */
2872 if (mesa_inst->DstReg.RelAddr)
2873 prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
2874
2875 /* Update program's bitmask of indirectly accessed register files */
2876 for (unsigned src = 0; src < 3; src++)
2877 if (mesa_inst->SrcReg[src].RelAddr)
2878 prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
2879
2880 if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
2881 fail_link(shader_program, "Couldn't flatten if statement\n");
2882 }
2883
2884 switch (mesa_inst->Opcode) {
2885 case OPCODE_BGNSUB:
2886 inst->function->inst = i;
2887 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2888 break;
2889 case OPCODE_ENDSUB:
2890 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2891 break;
2892 case OPCODE_CAL:
2893 mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
2894 break;
2895 case OPCODE_ARL:
2896 prog->NumAddressRegs = 1;
2897 break;
2898 default:
2899 break;
2900 }
2901
2902 mesa_inst++;
2903 i++;
2904
2905 if (!shader_program->LinkStatus)
2906 break;
2907 }
2908
2909 if (!shader_program->LinkStatus) {
2910 free(mesa_instructions);
2911 _mesa_reference_program(ctx, &shader->Program, NULL);
2912 return NULL;
2913 }
2914
2915 set_branchtargets(&v, mesa_instructions, num_instructions);
2916
2917 if (ctx->Shader.Flags & GLSL_DUMP) {
2918 printf("\n");
2919 printf("GLSL IR for linked %s program %d:\n", target_string,
2920 shader_program->Name);
2921 _mesa_print_ir(shader->ir, NULL);
2922 printf("\n");
2923 printf("\n");
2924 printf("Mesa IR for linked %s program %d:\n", target_string,
2925 shader_program->Name);
2926 print_program(mesa_instructions, mesa_instruction_annotation,
2927 num_instructions);
2928 }
2929
2930 prog->Instructions = mesa_instructions;
2931 prog->NumInstructions = num_instructions;
2932
2933 do_set_program_inouts(shader->ir, prog);
2934 count_resources(prog);
2935
2936 _mesa_reference_program(ctx, &shader->Program, prog);
2937
2938 if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
2939 _mesa_optimize_program(ctx, prog);
2940 }
2941
2942 return prog;
2943 }
2944
2945 extern "C" {
2946
2947 /**
2948 * Called via ctx->Driver.CompilerShader().
2949 * This is a no-op.
2950 * XXX can we remove the ctx->Driver.CompileShader() hook?
2951 */
2952 GLboolean
2953 _mesa_ir_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
2954 {
2955 assert(shader->CompileStatus);
2956 (void) ctx;
2957
2958 return GL_TRUE;
2959 }
2960
2961
2962 /**
2963 * Link a shader.
2964 * Called via ctx->Driver.LinkShader()
2965 * This actually involves converting GLSL IR into Mesa gl_programs with
2966 * code lowering and other optimizations.
2967 */
2968 GLboolean
2969 _mesa_ir_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
2970 {
2971 assert(prog->LinkStatus);
2972
2973 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2974 if (prog->_LinkedShaders[i] == NULL)
2975 continue;
2976
2977 bool progress;
2978 exec_list *ir = prog->_LinkedShaders[i]->ir;
2979 const struct gl_shader_compiler_options *options =
2980 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
2981
2982 do {
2983 progress = false;
2984
2985 /* Lowering */
2986 do_mat_op_to_vec(ir);
2987 lower_instructions(ir, (MOD_TO_FRACT | DIV_TO_MUL_RCP | EXP_TO_EXP2
2988 | LOG_TO_LOG2
2989 | ((options->EmitNoPow) ? POW_TO_EXP2 : 0)));
2990
2991 progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
2992
2993 progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
2994
2995 progress = lower_quadop_vector(ir, true) || progress;
2996
2997 if (options->EmitNoIfs) {
2998 progress = lower_discard(ir) || progress;
2999 progress = lower_if_to_cond_assign(ir) || progress;
3000 }
3001
3002 if (options->EmitNoNoise)
3003 progress = lower_noise(ir) || progress;
3004
3005 /* If there are forms of indirect addressing that the driver
3006 * cannot handle, perform the lowering pass.
3007 */
3008 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
3009 || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
3010 progress =
3011 lower_variable_index_to_cond_assign(ir,
3012 options->EmitNoIndirectInput,
3013 options->EmitNoIndirectOutput,
3014 options->EmitNoIndirectTemp,
3015 options->EmitNoIndirectUniform)
3016 || progress;
3017
3018 progress = do_vec_index_to_cond_assign(ir) || progress;
3019 } while (progress);
3020
3021 validate_ir_tree(ir);
3022 }
3023
3024 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
3025 struct gl_program *linked_prog;
3026
3027 if (prog->_LinkedShaders[i] == NULL)
3028 continue;
3029
3030 linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
3031
3032 if (linked_prog) {
3033 bool ok = true;
3034
3035 switch (prog->_LinkedShaders[i]->Type) {
3036 case GL_VERTEX_SHADER:
3037 _mesa_reference_vertprog(ctx, &prog->VertexProgram,
3038 (struct gl_vertex_program *)linked_prog);
3039 ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
3040 linked_prog);
3041 break;
3042 case GL_FRAGMENT_SHADER:
3043 _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
3044 (struct gl_fragment_program *)linked_prog);
3045 ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
3046 linked_prog);
3047 break;
3048 case GL_GEOMETRY_SHADER:
3049 _mesa_reference_geomprog(ctx, &prog->GeometryProgram,
3050 (struct gl_geometry_program *)linked_prog);
3051 ok = ctx->Driver.ProgramStringNotify(ctx, GL_GEOMETRY_PROGRAM_NV,
3052 linked_prog);
3053 break;
3054 }
3055 if (!ok) {
3056 return GL_FALSE;
3057 }
3058 }
3059
3060 _mesa_reference_program(ctx, &linked_prog, NULL);
3061 }
3062
3063 return GL_TRUE;
3064 }
3065
3066
3067 /**
3068 * Compile a GLSL shader. Called via glCompileShader().
3069 */
3070 void
3071 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
3072 {
3073 struct _mesa_glsl_parse_state *state =
3074 new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
3075
3076 const char *source = shader->Source;
3077 /* Check if the user called glCompileShader without first calling
3078 * glShaderSource. This should fail to compile, but not raise a GL_ERROR.
3079 */
3080 if (source == NULL) {
3081 shader->CompileStatus = GL_FALSE;
3082 return;
3083 }
3084
3085 state->error = preprocess(state, &source, &state->info_log,
3086 &ctx->Extensions, ctx->API);
3087
3088 if (ctx->Shader.Flags & GLSL_DUMP) {
3089 printf("GLSL source for shader %d:\n", shader->Name);
3090 printf("%s\n", shader->Source);
3091 }
3092
3093 if (!state->error) {
3094 _mesa_glsl_lexer_ctor(state, source);
3095 _mesa_glsl_parse(state);
3096 _mesa_glsl_lexer_dtor(state);
3097 }
3098
3099 talloc_free(shader->ir);
3100 shader->ir = new(shader) exec_list;
3101 if (!state->error && !state->translation_unit.is_empty())
3102 _mesa_ast_to_hir(shader->ir, state);
3103
3104 if (!state->error && !shader->ir->is_empty()) {
3105 validate_ir_tree(shader->ir);
3106
3107 /* Do some optimization at compile time to reduce shader IR size
3108 * and reduce later work if the same shader is linked multiple times
3109 */
3110 while (do_common_optimization(shader->ir, false, 32))
3111 ;
3112
3113 validate_ir_tree(shader->ir);
3114 }
3115
3116 shader->symbols = state->symbols;
3117
3118 shader->CompileStatus = !state->error;
3119 shader->InfoLog = state->info_log;
3120 shader->Version = state->language_version;
3121 memcpy(shader->builtins_to_link, state->builtins_to_link,
3122 sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
3123 shader->num_builtins_to_link = state->num_builtins_to_link;
3124
3125 if (ctx->Shader.Flags & GLSL_LOG) {
3126 _mesa_write_shader_to_file(shader);
3127 }
3128
3129 if (ctx->Shader.Flags & GLSL_DUMP) {
3130 if (shader->CompileStatus) {
3131 printf("GLSL IR for shader %d:\n", shader->Name);
3132 _mesa_print_ir(shader->ir, NULL);
3133 printf("\n\n");
3134 } else {
3135 printf("GLSL shader %d failed to compile.\n", shader->Name);
3136 }
3137 if (shader->InfoLog && shader->InfoLog[0] != 0) {
3138 printf("GLSL shader %d info log:\n", shader->Name);
3139 printf("%s\n", shader->InfoLog);
3140 }
3141 }
3142
3143 /* Retain any live IR, but trash the rest. */
3144 reparent_ir(shader->ir, shader->ir);
3145
3146 talloc_free(state);
3147
3148 if (shader->CompileStatus) {
3149 if (!ctx->Driver.CompileShader(ctx, shader))
3150 shader->CompileStatus = GL_FALSE;
3151 }
3152 }
3153
3154
3155 /**
3156 * Link a GLSL shader program. Called via glLinkProgram().
3157 */
3158 void
3159 _mesa_glsl_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
3160 {
3161 unsigned int i;
3162
3163 _mesa_clear_shader_program_data(ctx, prog);
3164
3165 prog->LinkStatus = GL_TRUE;
3166
3167 for (i = 0; i < prog->NumShaders; i++) {
3168 if (!prog->Shaders[i]->CompileStatus) {
3169 fail_link(prog, "linking with uncompiled shader");
3170 prog->LinkStatus = GL_FALSE;
3171 }
3172 }
3173
3174 prog->Varying = _mesa_new_parameter_list();
3175 _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
3176 _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
3177 _mesa_reference_geomprog(ctx, &prog->GeometryProgram, NULL);
3178
3179 if (prog->LinkStatus) {
3180 link_shaders(ctx, prog);
3181 }
3182
3183 if (prog->LinkStatus) {
3184 if (!ctx->Driver.LinkShader(ctx, prog)) {
3185 prog->LinkStatus = GL_FALSE;
3186 }
3187 }
3188
3189 set_uniform_initializers(ctx, prog);
3190
3191 if (ctx->Shader.Flags & GLSL_DUMP) {
3192 if (!prog->LinkStatus) {
3193 printf("GLSL shader program %d failed to link\n", prog->Name);
3194 }
3195
3196 if (prog->InfoLog && prog->InfoLog[0] != 0) {
3197 printf("GLSL shader program %d info log:\n", prog->Name);
3198 printf("%s\n", prog->InfoLog);
3199 }
3200 }
3201 }
3202
3203 } /* extern "C" */