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