OSDN Git Service

st/glsl_to_tgsi: fix st_src_reg_for_double constant.
[android-x86/external-mesa.git] / src / mesa / state_tracker / st_glsl_to_tgsi.cpp
1 /*
2  * Copyright (C) 2005-2007  Brian Paul   All Rights Reserved.
3  * Copyright (C) 2008  VMware, Inc.   All Rights Reserved.
4  * Copyright © 2010 Intel Corporation
5  * Copyright © 2011 Bryan Cain
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the next
15  * paragraph) shall be included in all copies or substantial portions of the
16  * Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24  * DEALINGS IN THE SOFTWARE.
25  */
26
27 /**
28  * \file glsl_to_tgsi.cpp
29  *
30  * Translate GLSL IR to TGSI.
31  */
32
33 #include "st_glsl_to_tgsi.h"
34
35 #include "compiler/glsl/glsl_parser_extras.h"
36 #include "compiler/glsl/ir_optimization.h"
37 #include "compiler/glsl/program.h"
38
39 #include "main/errors.h"
40 #include "main/shaderobj.h"
41 #include "main/uniforms.h"
42 #include "main/shaderapi.h"
43 #include "main/shaderimage.h"
44 #include "program/prog_instruction.h"
45
46 #include "pipe/p_context.h"
47 #include "pipe/p_screen.h"
48 #include "tgsi/tgsi_ureg.h"
49 #include "tgsi/tgsi_info.h"
50 #include "util/u_math.h"
51 #include "util/u_memory.h"
52 #include "st_program.h"
53 #include "st_mesa_to_tgsi.h"
54 #include "st_format.h"
55 #include "st_glsl_types.h"
56 #include "st_nir.h"
57
58
59 #define PROGRAM_ANY_CONST ((1 << PROGRAM_STATE_VAR) |    \
60                            (1 << PROGRAM_CONSTANT) |     \
61                            (1 << PROGRAM_UNIFORM))
62
63 #define MAX_GLSL_TEXTURE_OFFSET 4
64
65 class st_src_reg;
66 class st_dst_reg;
67
68 static int swizzle_for_size(int size);
69
70 /**
71  * This struct is a corresponding struct to TGSI ureg_src.
72  */
73 class st_src_reg {
74 public:
75    st_src_reg(gl_register_file file, int index, const glsl_type *type)
76    {
77       this->file = file;
78       this->index = index;
79       if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
80          this->swizzle = swizzle_for_size(type->vector_elements);
81       else
82          this->swizzle = SWIZZLE_XYZW;
83       this->negate = 0;
84       this->index2D = 0;
85       this->type = type ? type->base_type : GLSL_TYPE_ERROR;
86       this->reladdr = NULL;
87       this->reladdr2 = NULL;
88       this->has_index2 = false;
89       this->double_reg2 = false;
90       this->array_id = 0;
91       this->is_double_vertex_input = false;
92    }
93
94    st_src_reg(gl_register_file file, int index, int type)
95    {
96       this->type = type;
97       this->file = file;
98       this->index = index;
99       this->index2D = 0;
100       this->swizzle = SWIZZLE_XYZW;
101       this->negate = 0;
102       this->reladdr = NULL;
103       this->reladdr2 = NULL;
104       this->has_index2 = false;
105       this->double_reg2 = false;
106       this->array_id = 0;
107       this->is_double_vertex_input = false;
108    }
109
110    st_src_reg(gl_register_file file, int index, int type, int index2D)
111    {
112       this->type = type;
113       this->file = file;
114       this->index = index;
115       this->index2D = index2D;
116       this->swizzle = SWIZZLE_XYZW;
117       this->negate = 0;
118       this->reladdr = NULL;
119       this->reladdr2 = NULL;
120       this->has_index2 = false;
121       this->double_reg2 = false;
122       this->array_id = 0;
123       this->is_double_vertex_input = false;
124    }
125
126    st_src_reg()
127    {
128       this->type = GLSL_TYPE_ERROR;
129       this->file = PROGRAM_UNDEFINED;
130       this->index = 0;
131       this->index2D = 0;
132       this->swizzle = 0;
133       this->negate = 0;
134       this->reladdr = NULL;
135       this->reladdr2 = NULL;
136       this->has_index2 = false;
137       this->double_reg2 = false;
138       this->array_id = 0;
139       this->is_double_vertex_input = false;
140    }
141
142    explicit st_src_reg(st_dst_reg reg);
143
144    gl_register_file file; /**< PROGRAM_* from Mesa */
145    int index; /**< temporary index, VERT_ATTRIB_*, VARYING_SLOT_*, etc. */
146    int index2D;
147    GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
148    int negate; /**< NEGATE_XYZW mask from mesa */
149    int type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
150    /** Register index should be offset by the integer in this reg. */
151    st_src_reg *reladdr;
152    st_src_reg *reladdr2;
153    bool has_index2;
154    /*
155     * Is this the second half of a double register pair?
156     * currently used for input mapping only.
157     */
158    bool double_reg2;
159    unsigned array_id;
160    bool is_double_vertex_input;
161 };
162
163 class st_dst_reg {
164 public:
165    st_dst_reg(gl_register_file file, int writemask, int type, int index)
166    {
167       this->file = file;
168       this->index = index;
169       this->index2D = 0;
170       this->writemask = writemask;
171       this->reladdr = NULL;
172       this->reladdr2 = NULL;
173       this->has_index2 = false;
174       this->type = type;
175       this->array_id = 0;
176    }
177
178    st_dst_reg(gl_register_file file, int writemask, int type)
179    {
180       this->file = file;
181       this->index = 0;
182       this->index2D = 0;
183       this->writemask = writemask;
184       this->reladdr = NULL;
185       this->reladdr2 = NULL;
186       this->has_index2 = false;
187       this->type = type;
188       this->array_id = 0;
189    }
190
191    st_dst_reg()
192    {
193       this->type = GLSL_TYPE_ERROR;
194       this->file = PROGRAM_UNDEFINED;
195       this->index = 0;
196       this->index2D = 0;
197       this->writemask = 0;
198       this->reladdr = NULL;
199       this->reladdr2 = NULL;
200       this->has_index2 = false;
201       this->array_id = 0;
202    }
203
204    explicit st_dst_reg(st_src_reg reg);
205
206    gl_register_file file; /**< PROGRAM_* from Mesa */
207    int index; /**< temporary index, VERT_ATTRIB_*, VARYING_SLOT_*, etc. */
208    int index2D;
209    int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
210    int type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
211    /** Register index should be offset by the integer in this reg. */
212    st_src_reg *reladdr;
213    st_src_reg *reladdr2;
214    bool has_index2;
215    unsigned array_id;
216 };
217
218 st_src_reg::st_src_reg(st_dst_reg reg)
219 {
220    this->type = reg.type;
221    this->file = reg.file;
222    this->index = reg.index;
223    this->swizzle = SWIZZLE_XYZW;
224    this->negate = 0;
225    this->reladdr = reg.reladdr;
226    this->index2D = reg.index2D;
227    this->reladdr2 = reg.reladdr2;
228    this->has_index2 = reg.has_index2;
229    this->double_reg2 = false;
230    this->array_id = reg.array_id;
231    this->is_double_vertex_input = false;
232 }
233
234 st_dst_reg::st_dst_reg(st_src_reg reg)
235 {
236    this->type = reg.type;
237    this->file = reg.file;
238    this->index = reg.index;
239    this->writemask = WRITEMASK_XYZW;
240    this->reladdr = reg.reladdr;
241    this->index2D = reg.index2D;
242    this->reladdr2 = reg.reladdr2;
243    this->has_index2 = reg.has_index2;
244    this->array_id = reg.array_id;
245 }
246
247 class glsl_to_tgsi_instruction : public exec_node {
248 public:
249    DECLARE_RALLOC_CXX_OPERATORS(glsl_to_tgsi_instruction)
250
251    unsigned op;
252    st_dst_reg dst[2];
253    st_src_reg src[4];
254    /** Pointer to the ir source this tree came from for debugging */
255    ir_instruction *ir;
256    GLboolean cond_update;
257    bool saturate;
258    st_src_reg sampler; /**< sampler register */
259    int sampler_base;
260    int sampler_array_size; /**< 1-based size of sampler array, 1 if not array */
261    int tex_target; /**< One of TEXTURE_*_INDEX */
262    glsl_base_type tex_type;
263    GLboolean tex_shadow;
264    unsigned image_format;
265
266    st_src_reg tex_offsets[MAX_GLSL_TEXTURE_OFFSET];
267    unsigned tex_offset_num_offset;
268    int dead_mask; /**< Used in dead code elimination */
269
270    st_src_reg buffer; /**< buffer register */
271    unsigned buffer_access; /**< buffer access type */
272
273    class function_entry *function; /* Set on TGSI_OPCODE_CAL or TGSI_OPCODE_BGNSUB */
274    const struct tgsi_opcode_info *info;
275 };
276
277 class variable_storage : public exec_node {
278 public:
279    variable_storage(ir_variable *var, gl_register_file file, int index,
280                     unsigned array_id = 0)
281       : file(file), index(index), var(var), array_id(array_id)
282    {
283       /* empty */
284    }
285
286    gl_register_file file;
287    int index;
288    ir_variable *var; /* variable that maps to this, if any */
289    unsigned array_id;
290 };
291
292 class immediate_storage : public exec_node {
293 public:
294    immediate_storage(gl_constant_value *values, int size32, int type)
295    {
296       memcpy(this->values, values, size32 * sizeof(gl_constant_value));
297       this->size32 = size32;
298       this->type = type;
299    }
300
301    /* doubles are stored across 2 gl_constant_values */
302    gl_constant_value values[4];
303    int size32; /**< Number of 32-bit components (1-4) */
304    int type; /**< GL_DOUBLE, GL_FLOAT, GL_INT, GL_BOOL, or GL_UNSIGNED_INT */
305 };
306
307 class function_entry : public exec_node {
308 public:
309    ir_function_signature *sig;
310
311    /**
312     * identifier of this function signature used by the program.
313     *
314     * At the point that TGSI instructions for function calls are
315     * generated, we don't know the address of the first instruction of
316     * the function body.  So we make the BranchTarget that is called a
317     * small integer and rewrite them during set_branchtargets().
318     */
319    int sig_id;
320
321    /**
322     * Pointer to first instruction of the function body.
323     *
324     * Set during function body emits after main() is processed.
325     */
326    glsl_to_tgsi_instruction *bgn_inst;
327
328    /**
329     * Index of the first instruction of the function body in actual TGSI.
330     *
331     * Set after conversion from glsl_to_tgsi_instruction to TGSI.
332     */
333    int inst;
334
335    /** Storage for the return value. */
336    st_src_reg return_reg;
337 };
338
339 static st_src_reg undef_src = st_src_reg(PROGRAM_UNDEFINED, 0, GLSL_TYPE_ERROR);
340 static st_dst_reg undef_dst = st_dst_reg(PROGRAM_UNDEFINED, SWIZZLE_NOOP, GLSL_TYPE_ERROR);
341
342 struct array_decl {
343    unsigned mesa_index;
344    unsigned array_id;
345    unsigned array_size;
346    unsigned array_type;
347 };
348
349 static unsigned
350 find_array_type(struct array_decl *arrays, unsigned count, unsigned array_id)
351 {
352    unsigned i;
353
354    for (i = 0; i < count; i++) {
355       struct array_decl *decl = &arrays[i];
356
357       if (array_id == decl->array_id) {
358          return decl->array_type;
359       }
360    }
361    return GLSL_TYPE_ERROR;
362 }
363
364 struct rename_reg_pair {
365    int old_reg;
366    int new_reg;
367 };
368
369 struct glsl_to_tgsi_visitor : public ir_visitor {
370 public:
371    glsl_to_tgsi_visitor();
372    ~glsl_to_tgsi_visitor();
373
374    function_entry *current_function;
375
376    struct gl_context *ctx;
377    struct gl_program *prog;
378    struct gl_shader_program *shader_program;
379    struct gl_shader *shader;
380    struct gl_shader_compiler_options *options;
381
382    int next_temp;
383
384    unsigned *array_sizes;
385    unsigned max_num_arrays;
386    unsigned next_array;
387
388    struct array_decl input_arrays[PIPE_MAX_SHADER_INPUTS];
389    unsigned num_input_arrays;
390    struct array_decl output_arrays[PIPE_MAX_SHADER_OUTPUTS];
391    unsigned num_output_arrays;
392
393    int num_address_regs;
394    uint32_t samplers_used;
395    glsl_base_type sampler_types[PIPE_MAX_SAMPLERS];
396    int sampler_targets[PIPE_MAX_SAMPLERS];   /**< One of TGSI_TEXTURE_* */
397    int buffers_used;
398    int images_used;
399    int image_targets[PIPE_MAX_SHADER_IMAGES];
400    unsigned image_formats[PIPE_MAX_SHADER_IMAGES];
401    bool indirect_addr_consts;
402    int wpos_transform_const;
403
404    int glsl_version;
405    bool native_integers;
406    bool have_sqrt;
407    bool have_fma;
408    bool use_shared_memory;
409
410    variable_storage *find_variable_storage(ir_variable *var);
411
412    int add_constant(gl_register_file file, gl_constant_value values[8],
413                     int size, int datatype, GLuint *swizzle_out);
414
415    function_entry *get_function_signature(ir_function_signature *sig);
416
417    st_src_reg get_temp(const glsl_type *type);
418    void reladdr_to_temp(ir_instruction *ir, st_src_reg *reg, int *num_reladdr);
419
420    st_src_reg st_src_reg_for_double(double val);
421    st_src_reg st_src_reg_for_float(float val);
422    st_src_reg st_src_reg_for_int(int val);
423    st_src_reg st_src_reg_for_type(int type, int val);
424
425    /**
426     * \name Visit methods
427     *
428     * As typical for the visitor pattern, there must be one \c visit method for
429     * each concrete subclass of \c ir_instruction.  Virtual base classes within
430     * the hierarchy should not have \c visit methods.
431     */
432    /*@{*/
433    virtual void visit(ir_variable *);
434    virtual void visit(ir_loop *);
435    virtual void visit(ir_loop_jump *);
436    virtual void visit(ir_function_signature *);
437    virtual void visit(ir_function *);
438    virtual void visit(ir_expression *);
439    virtual void visit(ir_swizzle *);
440    virtual void visit(ir_dereference_variable  *);
441    virtual void visit(ir_dereference_array *);
442    virtual void visit(ir_dereference_record *);
443    virtual void visit(ir_assignment *);
444    virtual void visit(ir_constant *);
445    virtual void visit(ir_call *);
446    virtual void visit(ir_return *);
447    virtual void visit(ir_discard *);
448    virtual void visit(ir_texture *);
449    virtual void visit(ir_if *);
450    virtual void visit(ir_emit_vertex *);
451    virtual void visit(ir_end_primitive *);
452    virtual void visit(ir_barrier *);
453    /*@}*/
454
455    void visit_expression(ir_expression *, st_src_reg *) ATTRIBUTE_NOINLINE;
456
457    void visit_atomic_counter_intrinsic(ir_call *);
458    void visit_ssbo_intrinsic(ir_call *);
459    void visit_membar_intrinsic(ir_call *);
460    void visit_shared_intrinsic(ir_call *);
461    void visit_image_intrinsic(ir_call *);
462
463    st_src_reg result;
464
465    /** List of variable_storage */
466    exec_list variables;
467
468    /** List of immediate_storage */
469    exec_list immediates;
470    unsigned num_immediates;
471
472    /** List of function_entry */
473    exec_list function_signatures;
474    int next_signature_id;
475
476    /** List of glsl_to_tgsi_instruction */
477    exec_list instructions;
478
479    glsl_to_tgsi_instruction *emit_asm(ir_instruction *ir, unsigned op,
480                                       st_dst_reg dst = undef_dst,
481                                       st_src_reg src0 = undef_src,
482                                       st_src_reg src1 = undef_src,
483                                       st_src_reg src2 = undef_src,
484                                       st_src_reg src3 = undef_src);
485
486    glsl_to_tgsi_instruction *emit_asm(ir_instruction *ir, unsigned op,
487                                       st_dst_reg dst, st_dst_reg dst1,
488                                       st_src_reg src0 = undef_src,
489                                       st_src_reg src1 = undef_src,
490                                       st_src_reg src2 = undef_src,
491                                       st_src_reg src3 = undef_src);
492
493    unsigned get_opcode(ir_instruction *ir, unsigned op,
494                     st_dst_reg dst,
495                     st_src_reg src0, st_src_reg src1);
496
497    /**
498     * Emit the correct dot-product instruction for the type of arguments
499     */
500    glsl_to_tgsi_instruction *emit_dp(ir_instruction *ir,
501                                      st_dst_reg dst,
502                                      st_src_reg src0,
503                                      st_src_reg src1,
504                                      unsigned elements);
505
506    void emit_scalar(ir_instruction *ir, unsigned op,
507                     st_dst_reg dst, st_src_reg src0);
508
509    void emit_scalar(ir_instruction *ir, unsigned op,
510                     st_dst_reg dst, st_src_reg src0, st_src_reg src1);
511
512    void emit_arl(ir_instruction *ir, st_dst_reg dst, st_src_reg src0);
513
514    void get_deref_offsets(ir_dereference *ir,
515                           unsigned *array_size,
516                           unsigned *base,
517                           unsigned *index,
518                           st_src_reg *reladdr);
519   void calc_deref_offsets(ir_dereference *head,
520                           ir_dereference *tail,
521                           unsigned *array_elements,
522                           unsigned *base,
523                           unsigned *index,
524                           st_src_reg *indirect,
525                           unsigned *location);
526
527    bool try_emit_mad(ir_expression *ir,
528               int mul_operand);
529    bool try_emit_mad_for_and_not(ir_expression *ir,
530               int mul_operand);
531
532    void emit_swz(ir_expression *ir);
533
534    bool process_move_condition(ir_rvalue *ir);
535
536    void simplify_cmp(void);
537
538    void rename_temp_registers(int num_renames, struct rename_reg_pair *renames);
539    void get_first_temp_read(int *first_reads);
540    void get_last_temp_read_first_temp_write(int *last_reads, int *first_writes);
541    void get_last_temp_write(int *last_writes);
542
543    void copy_propagate(void);
544    int eliminate_dead_code(void);
545
546    void merge_two_dsts(void);
547    void merge_registers(void);
548    void renumber_registers(void);
549
550    void emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
551                        st_dst_reg *l, st_src_reg *r,
552                        st_src_reg *cond, bool cond_swap);
553
554    void *mem_ctx;
555 };
556
557 static st_dst_reg address_reg = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 0);
558 static st_dst_reg address_reg2 = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 1);
559 static st_dst_reg sampler_reladdr = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 2);
560
561 static void
562 fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
563
564 static void
565 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
566 {
567    va_list args;
568    va_start(args, fmt);
569    ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
570    va_end(args);
571
572    prog->LinkStatus = GL_FALSE;
573 }
574
575 static int
576 swizzle_for_size(int size)
577 {
578    static const int size_swizzles[4] = {
579       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
580       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
581       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
582       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
583    };
584
585    assert((size >= 1) && (size <= 4));
586    return size_swizzles[size - 1];
587 }
588
589 static bool
590 is_resource_instruction(unsigned opcode)
591 {
592    switch (opcode) {
593    case TGSI_OPCODE_RESQ:
594    case TGSI_OPCODE_LOAD:
595    case TGSI_OPCODE_ATOMUADD:
596    case TGSI_OPCODE_ATOMXCHG:
597    case TGSI_OPCODE_ATOMCAS:
598    case TGSI_OPCODE_ATOMAND:
599    case TGSI_OPCODE_ATOMOR:
600    case TGSI_OPCODE_ATOMXOR:
601    case TGSI_OPCODE_ATOMUMIN:
602    case TGSI_OPCODE_ATOMUMAX:
603    case TGSI_OPCODE_ATOMIMIN:
604    case TGSI_OPCODE_ATOMIMAX:
605       return true;
606    default:
607       return false;
608    }
609 }
610
611 static unsigned
612 num_inst_dst_regs(const glsl_to_tgsi_instruction *op)
613 {
614    return op->info->num_dst;
615 }
616
617 static unsigned
618 num_inst_src_regs(const glsl_to_tgsi_instruction *op)
619 {
620    return op->info->is_tex || is_resource_instruction(op->op) ?
621       op->info->num_src - 1 : op->info->num_src;
622 }
623
624 glsl_to_tgsi_instruction *
625 glsl_to_tgsi_visitor::emit_asm(ir_instruction *ir, unsigned op,
626                                st_dst_reg dst, st_dst_reg dst1,
627                                st_src_reg src0, st_src_reg src1,
628                                st_src_reg src2, st_src_reg src3)
629 {
630    glsl_to_tgsi_instruction *inst = new(mem_ctx) glsl_to_tgsi_instruction();
631    int num_reladdr = 0, i, j;
632    bool dst_is_double[2];
633
634    op = get_opcode(ir, op, dst, src0, src1);
635
636    /* If we have to do relative addressing, we want to load the ARL
637     * reg directly for one of the regs, and preload the other reladdr
638     * sources into temps.
639     */
640    num_reladdr += dst.reladdr != NULL || dst.reladdr2;
641    num_reladdr += dst1.reladdr != NULL || dst1.reladdr2;
642    num_reladdr += src0.reladdr != NULL || src0.reladdr2 != NULL;
643    num_reladdr += src1.reladdr != NULL || src1.reladdr2 != NULL;
644    num_reladdr += src2.reladdr != NULL || src2.reladdr2 != NULL;
645    num_reladdr += src3.reladdr != NULL || src3.reladdr2 != NULL;
646
647    reladdr_to_temp(ir, &src3, &num_reladdr);
648    reladdr_to_temp(ir, &src2, &num_reladdr);
649    reladdr_to_temp(ir, &src1, &num_reladdr);
650    reladdr_to_temp(ir, &src0, &num_reladdr);
651
652    if (dst.reladdr || dst.reladdr2) {
653       if (dst.reladdr)
654          emit_arl(ir, address_reg, *dst.reladdr);
655       if (dst.reladdr2)
656          emit_arl(ir, address_reg2, *dst.reladdr2);
657       num_reladdr--;
658    }
659    if (dst1.reladdr) {
660       emit_arl(ir, address_reg, *dst1.reladdr);
661       num_reladdr--;
662    }
663    assert(num_reladdr == 0);
664
665    inst->op = op;
666    inst->info = tgsi_get_opcode_info(op);
667    inst->dst[0] = dst;
668    inst->dst[1] = dst1;
669    inst->src[0] = src0;
670    inst->src[1] = src1;
671    inst->src[2] = src2;
672    inst->src[3] = src3;
673    inst->ir = ir;
674    inst->dead_mask = 0;
675    /* default to float, for paths where this is not initialized
676     * (since 0==UINT which is likely wrong):
677     */
678    inst->tex_type = GLSL_TYPE_FLOAT;
679
680    inst->function = NULL;
681
682    /* Update indirect addressing status used by TGSI */
683    if (dst.reladdr || dst.reladdr2) {
684       switch(dst.file) {
685       case PROGRAM_STATE_VAR:
686       case PROGRAM_CONSTANT:
687       case PROGRAM_UNIFORM:
688          this->indirect_addr_consts = true;
689          break;
690       case PROGRAM_IMMEDIATE:
691          assert(!"immediates should not have indirect addressing");
692          break;
693       default:
694          break;
695       }
696    }
697    else {
698       for (i = 0; i < 4; i++) {
699          if(inst->src[i].reladdr) {
700             switch(inst->src[i].file) {
701             case PROGRAM_STATE_VAR:
702             case PROGRAM_CONSTANT:
703             case PROGRAM_UNIFORM:
704                this->indirect_addr_consts = true;
705                break;
706             case PROGRAM_IMMEDIATE:
707                assert(!"immediates should not have indirect addressing");
708                break;
709             default:
710                break;
711             }
712          }
713       }
714    }
715
716    /*
717     * This section contains the double processing.
718     * GLSL just represents doubles as single channel values,
719     * however most HW and TGSI represent doubles as pairs of register channels.
720     *
721     * so we have to fixup destination writemask/index and src swizzle/indexes.
722     * dest writemasks need to translate from single channel write mask
723     * to a dual-channel writemask, but also need to modify the index,
724     * if we are touching the Z,W fields in the pre-translated writemask.
725     *
726     * src channels have similiar index modifications along with swizzle
727     * changes to we pick the XY, ZW pairs from the correct index.
728     *
729     * GLSL [0].x -> TGSI [0].xy
730     * GLSL [0].y -> TGSI [0].zw
731     * GLSL [0].z -> TGSI [1].xy
732     * GLSL [0].w -> TGSI [1].zw
733     */
734    for (j = 0; j < 2; j++) {
735       dst_is_double[j] = false;
736       if (inst->dst[j].type == GLSL_TYPE_DOUBLE)
737          dst_is_double[j] = true;
738       else if (inst->dst[j].file == PROGRAM_OUTPUT && inst->dst[j].type == GLSL_TYPE_ARRAY) {
739          unsigned type = find_array_type(this->output_arrays, this->num_output_arrays, inst->dst[j].array_id);
740          if (type == GLSL_TYPE_DOUBLE)
741             dst_is_double[j] = true;
742       }
743    }
744
745    if (dst_is_double[0] || dst_is_double[1] ||
746        inst->src[0].type == GLSL_TYPE_DOUBLE) {
747       glsl_to_tgsi_instruction *dinst = NULL;
748       int initial_src_swz[4], initial_src_idx[4];
749       int initial_dst_idx[2], initial_dst_writemask[2];
750       /* select the writemask for dst0 or dst1 */
751       unsigned writemask = inst->dst[1].file == PROGRAM_UNDEFINED ? inst->dst[0].writemask : inst->dst[1].writemask;
752
753       /* copy out the writemask, index and swizzles for all src/dsts. */
754       for (j = 0; j < 2; j++) {
755          initial_dst_writemask[j] = inst->dst[j].writemask;
756          initial_dst_idx[j] = inst->dst[j].index;
757       }
758
759       for (j = 0; j < 4; j++) {
760          initial_src_swz[j] = inst->src[j].swizzle;
761          initial_src_idx[j] = inst->src[j].index;
762       }
763
764       /*
765        * scan all the components in the dst writemask
766        * generate an instruction for each of them if required.
767        */
768       st_src_reg addr;
769       while (writemask) {
770
771          int i = u_bit_scan(&writemask);
772
773          /* before emitting the instruction, see if we have to adjust store
774           * address */
775          if (i > 1 && inst->op == TGSI_OPCODE_STORE &&
776              addr.file == PROGRAM_UNDEFINED) {
777             /* We have to advance the buffer address by 16 */
778             addr = get_temp(glsl_type::uint_type);
779             emit_asm(ir, TGSI_OPCODE_UADD, st_dst_reg(addr),
780                      inst->src[0], st_src_reg_for_int(16));
781          }
782
783
784          /* first time use previous instruction */
785          if (dinst == NULL) {
786             dinst = inst;
787          } else {
788             /* create a new instructions for subsequent attempts */
789             dinst = new(mem_ctx) glsl_to_tgsi_instruction();
790             *dinst = *inst;
791             dinst->next = NULL;
792             dinst->prev = NULL;
793          }
794          this->instructions.push_tail(dinst);
795
796          /* modify the destination if we are splitting */
797          for (j = 0; j < 2; j++) {
798             if (dst_is_double[j]) {
799                dinst->dst[j].writemask = (i & 1) ? WRITEMASK_ZW : WRITEMASK_XY;
800                dinst->dst[j].index = initial_dst_idx[j];
801                if (i > 1) {
802                   if (dinst->op == TGSI_OPCODE_STORE) {
803                      dinst->src[0] = addr;
804                   } else {
805                      dinst->dst[j].index++;
806                   }
807                }
808             } else {
809                /* if we aren't writing to a double, just get the bit of the initial writemask
810                   for this channel */
811                dinst->dst[j].writemask = initial_dst_writemask[j] & (1 << i);
812             }
813          }
814
815          /* modify the src registers */
816          for (j = 0; j < 4; j++) {
817             int swz = GET_SWZ(initial_src_swz[j], i);
818
819             if (dinst->src[j].type == GLSL_TYPE_DOUBLE) {
820                dinst->src[j].index = initial_src_idx[j];
821                if (swz > 1) {
822                   dinst->src[j].double_reg2 = true;
823                   dinst->src[j].index++;
824                }
825
826                if (swz & 1)
827                   dinst->src[j].swizzle = MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_Z, SWIZZLE_W);
828                else
829                   dinst->src[j].swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
830
831             } else {
832                /* some opcodes are special case in what they use as sources
833                   - F2D is a float src0, DLDEXP is integer src1 */
834                if (op == TGSI_OPCODE_F2D ||
835                    op == TGSI_OPCODE_DLDEXP ||
836                    (op == TGSI_OPCODE_UCMP && dst_is_double[0])) {
837                   dinst->src[j].swizzle = MAKE_SWIZZLE4(swz, swz, swz, swz);
838                }
839             }
840          }
841       }
842       inst = dinst;
843    } else {
844       this->instructions.push_tail(inst);
845    }
846
847
848    return inst;
849 }
850
851 glsl_to_tgsi_instruction *
852 glsl_to_tgsi_visitor::emit_asm(ir_instruction *ir, unsigned op,
853                                st_dst_reg dst,
854                                st_src_reg src0, st_src_reg src1,
855                                st_src_reg src2, st_src_reg src3)
856 {
857    return emit_asm(ir, op, dst, undef_dst, src0, src1, src2, src3);
858 }
859
860 /**
861  * Determines whether to use an integer, unsigned integer, or float opcode
862  * based on the operands and input opcode, then emits the result.
863  */
864 unsigned
865 glsl_to_tgsi_visitor::get_opcode(ir_instruction *ir, unsigned op,
866                                  st_dst_reg dst,
867                                  st_src_reg src0, st_src_reg src1)
868 {
869    int type = GLSL_TYPE_FLOAT;
870
871    if (op == TGSI_OPCODE_MOV)
872        return op;
873
874    assert(src0.type != GLSL_TYPE_ARRAY);
875    assert(src0.type != GLSL_TYPE_STRUCT);
876    assert(src1.type != GLSL_TYPE_ARRAY);
877    assert(src1.type != GLSL_TYPE_STRUCT);
878
879    if (is_resource_instruction(op))
880       type = src1.type;
881    else if (src0.type == GLSL_TYPE_DOUBLE || src1.type == GLSL_TYPE_DOUBLE)
882       type = GLSL_TYPE_DOUBLE;
883    else if (src0.type == GLSL_TYPE_FLOAT || src1.type == GLSL_TYPE_FLOAT)
884       type = GLSL_TYPE_FLOAT;
885    else if (native_integers)
886       type = src0.type == GLSL_TYPE_BOOL ? GLSL_TYPE_INT : src0.type;
887
888 #define case5(c, f, i, u, d)                    \
889    case TGSI_OPCODE_##c: \
890       if (type == GLSL_TYPE_DOUBLE)           \
891          op = TGSI_OPCODE_##d; \
892       else if (type == GLSL_TYPE_INT)       \
893          op = TGSI_OPCODE_##i; \
894       else if (type == GLSL_TYPE_UINT) \
895          op = TGSI_OPCODE_##u; \
896       else \
897          op = TGSI_OPCODE_##f; \
898       break;
899
900 #define case4(c, f, i, u)                    \
901    case TGSI_OPCODE_##c: \
902       if (type == GLSL_TYPE_INT) \
903          op = TGSI_OPCODE_##i; \
904       else if (type == GLSL_TYPE_UINT) \
905          op = TGSI_OPCODE_##u; \
906       else \
907          op = TGSI_OPCODE_##f; \
908       break;
909
910 #define case3(f, i, u)  case4(f, f, i, u)
911 #define case4d(f, i, u, d)  case5(f, f, i, u, d)
912 #define case3fid(f, i, d) case5(f, f, i, i, d)
913 #define case2fi(f, i)   case4(f, f, i, i)
914 #define case2iu(i, u)   case4(i, LAST, i, u)
915
916 #define casecomp(c, f, i, u, d)                   \
917    case TGSI_OPCODE_##c: \
918       if (type == GLSL_TYPE_DOUBLE) \
919          op = TGSI_OPCODE_##d; \
920       else if (type == GLSL_TYPE_INT || type == GLSL_TYPE_SUBROUTINE)       \
921          op = TGSI_OPCODE_##i; \
922       else if (type == GLSL_TYPE_UINT) \
923          op = TGSI_OPCODE_##u; \
924       else if (native_integers) \
925          op = TGSI_OPCODE_##f; \
926       else \
927          op = TGSI_OPCODE_##c; \
928       break;
929
930    switch(op) {
931       case3fid(ADD, UADD, DADD);
932       case3fid(MUL, UMUL, DMUL);
933       case3fid(MAD, UMAD, DMAD);
934       case3fid(FMA, UMAD, DFMA);
935       case3(DIV, IDIV, UDIV);
936       case4d(MAX, IMAX, UMAX, DMAX);
937       case4d(MIN, IMIN, UMIN, DMIN);
938       case2iu(MOD, UMOD);
939
940       casecomp(SEQ, FSEQ, USEQ, USEQ, DSEQ);
941       casecomp(SNE, FSNE, USNE, USNE, DSNE);
942       casecomp(SGE, FSGE, ISGE, USGE, DSGE);
943       casecomp(SLT, FSLT, ISLT, USLT, DSLT);
944
945       case2iu(ISHR, USHR);
946
947       case3fid(SSG, ISSG, DSSG);
948       case3fid(ABS, IABS, DABS);
949
950       case2iu(IBFE, UBFE);
951       case2iu(IMSB, UMSB);
952       case2iu(IMUL_HI, UMUL_HI);
953
954       case3fid(SQRT, SQRT, DSQRT);
955
956       case3fid(RCP, RCP, DRCP);
957       case3fid(RSQ, RSQ, DRSQ);
958
959       case3fid(FRC, FRC, DFRAC);
960       case3fid(TRUNC, TRUNC, DTRUNC);
961       case3fid(CEIL, CEIL, DCEIL);
962       case3fid(FLR, FLR, DFLR);
963       case3fid(ROUND, ROUND, DROUND);
964
965       case2iu(ATOMIMAX, ATOMUMAX);
966       case2iu(ATOMIMIN, ATOMUMIN);
967
968       default: break;
969    }
970
971    assert(op != TGSI_OPCODE_LAST);
972    return op;
973 }
974
975 glsl_to_tgsi_instruction *
976 glsl_to_tgsi_visitor::emit_dp(ir_instruction *ir,
977                               st_dst_reg dst, st_src_reg src0, st_src_reg src1,
978                               unsigned elements)
979 {
980    static const unsigned dot_opcodes[] = {
981       TGSI_OPCODE_DP2, TGSI_OPCODE_DP3, TGSI_OPCODE_DP4
982    };
983
984    return emit_asm(ir, dot_opcodes[elements - 2], dst, src0, src1);
985 }
986
987 /**
988  * Emits TGSI scalar opcodes to produce unique answers across channels.
989  *
990  * Some TGSI opcodes are scalar-only, like ARB_fp/vp.  The src X
991  * channel determines the result across all channels.  So to do a vec4
992  * of this operation, we want to emit a scalar per source channel used
993  * to produce dest channels.
994  */
995 void
996 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
997                                   st_dst_reg dst,
998                                   st_src_reg orig_src0, st_src_reg orig_src1)
999 {
1000    int i, j;
1001    int done_mask = ~dst.writemask;
1002
1003    /* TGSI RCP is a scalar operation splatting results to all channels,
1004     * like ARB_fp/vp.  So emit as many RCPs as necessary to cover our
1005     * dst channels.
1006     */
1007    for (i = 0; i < 4; i++) {
1008       GLuint this_mask = (1 << i);
1009       st_src_reg src0 = orig_src0;
1010       st_src_reg src1 = orig_src1;
1011
1012       if (done_mask & this_mask)
1013          continue;
1014
1015       GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
1016       GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
1017       for (j = i + 1; j < 4; j++) {
1018          /* If there is another enabled component in the destination that is
1019           * derived from the same inputs, generate its value on this pass as
1020           * well.
1021           */
1022          if (!(done_mask & (1 << j)) &&
1023              GET_SWZ(src0.swizzle, j) == src0_swiz &&
1024              GET_SWZ(src1.swizzle, j) == src1_swiz) {
1025             this_mask |= (1 << j);
1026          }
1027       }
1028       src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
1029                                    src0_swiz, src0_swiz);
1030       src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
1031                                    src1_swiz, src1_swiz);
1032
1033       dst.writemask = this_mask;
1034       emit_asm(ir, op, dst, src0, src1);
1035       done_mask |= this_mask;
1036    }
1037 }
1038
1039 void
1040 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
1041                                   st_dst_reg dst, st_src_reg src0)
1042 {
1043    st_src_reg undef = undef_src;
1044
1045    undef.swizzle = SWIZZLE_XXXX;
1046
1047    emit_scalar(ir, op, dst, src0, undef);
1048 }
1049
1050 void
1051 glsl_to_tgsi_visitor::emit_arl(ir_instruction *ir,
1052                                st_dst_reg dst, st_src_reg src0)
1053 {
1054    int op = TGSI_OPCODE_ARL;
1055
1056    if (src0.type == GLSL_TYPE_INT || src0.type == GLSL_TYPE_UINT)
1057       op = TGSI_OPCODE_UARL;
1058
1059    assert(dst.file == PROGRAM_ADDRESS);
1060    if (dst.index >= this->num_address_regs)
1061       this->num_address_regs = dst.index + 1;
1062
1063    emit_asm(NULL, op, dst, src0);
1064 }
1065
1066 int
1067 glsl_to_tgsi_visitor::add_constant(gl_register_file file,
1068                                    gl_constant_value values[8], int size, int datatype,
1069                                    GLuint *swizzle_out)
1070 {
1071    if (file == PROGRAM_CONSTANT) {
1072       return _mesa_add_typed_unnamed_constant(this->prog->Parameters, values,
1073                                               size, datatype, swizzle_out);
1074    }
1075
1076    assert(file == PROGRAM_IMMEDIATE);
1077
1078    int index = 0;
1079    immediate_storage *entry;
1080    int size32 = size * (datatype == GL_DOUBLE ? 2 : 1);
1081    int i;
1082
1083    /* Search immediate storage to see if we already have an identical
1084     * immediate that we can use instead of adding a duplicate entry.
1085     */
1086    foreach_in_list(immediate_storage, entry, &this->immediates) {
1087       immediate_storage *tmp = entry;
1088
1089       for (i = 0; i * 4 < size32; i++) {
1090          int slot_size = MIN2(size32 - (i * 4), 4);
1091          if (tmp->type != datatype || tmp->size32 != slot_size)
1092             break;
1093          if (memcmp(tmp->values, &values[i * 4],
1094                     slot_size * sizeof(gl_constant_value)))
1095             break;
1096
1097          /* Everything matches, keep going until the full size is matched */
1098          tmp = (immediate_storage *)tmp->next;
1099       }
1100
1101       /* The full value matched */
1102       if (i * 4 >= size32)
1103          return index;
1104
1105       index++;
1106    }
1107
1108    for (i = 0; i * 4 < size32; i++) {
1109       int slot_size = MIN2(size32 - (i * 4), 4);
1110       /* Add this immediate to the list. */
1111       entry = new(mem_ctx) immediate_storage(&values[i * 4], slot_size, datatype);
1112       this->immediates.push_tail(entry);
1113       this->num_immediates++;
1114    }
1115    return index;
1116 }
1117
1118 st_src_reg
1119 glsl_to_tgsi_visitor::st_src_reg_for_float(float val)
1120 {
1121    st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_FLOAT);
1122    union gl_constant_value uval;
1123
1124    uval.f = val;
1125    src.index = add_constant(src.file, &uval, 1, GL_FLOAT, &src.swizzle);
1126
1127    return src;
1128 }
1129
1130 st_src_reg
1131 glsl_to_tgsi_visitor::st_src_reg_for_double(double val)
1132 {
1133    st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_DOUBLE);
1134    union gl_constant_value uval[2];
1135
1136    uval[0].u = *(uint32_t *)&val;
1137    uval[1].u = *(((uint32_t *)&val) + 1);
1138    src.index = add_constant(src.file, uval, 1, GL_DOUBLE, &src.swizzle);
1139    src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
1140    return src;
1141 }
1142
1143 st_src_reg
1144 glsl_to_tgsi_visitor::st_src_reg_for_int(int val)
1145 {
1146    st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_INT);
1147    union gl_constant_value uval;
1148
1149    assert(native_integers);
1150
1151    uval.i = val;
1152    src.index = add_constant(src.file, &uval, 1, GL_INT, &src.swizzle);
1153
1154    return src;
1155 }
1156
1157 st_src_reg
1158 glsl_to_tgsi_visitor::st_src_reg_for_type(int type, int val)
1159 {
1160    if (native_integers)
1161       return type == GLSL_TYPE_FLOAT ? st_src_reg_for_float(val) :
1162                                        st_src_reg_for_int(val);
1163    else
1164       return st_src_reg_for_float(val);
1165 }
1166
1167 static int
1168 attrib_type_size(const struct glsl_type *type, bool is_vs_input)
1169 {
1170    return st_glsl_attrib_type_size(type, is_vs_input);
1171 }
1172
1173 static int
1174 type_size(const struct glsl_type *type)
1175 {
1176    return st_glsl_type_size(type);
1177 }
1178
1179 /**
1180  * If the given GLSL type is an array or matrix or a structure containing
1181  * an array/matrix member, return true.  Else return false.
1182  *
1183  * This is used to determine which kind of temp storage (PROGRAM_TEMPORARY
1184  * or PROGRAM_ARRAY) should be used for variables of this type.  Anytime
1185  * we have an array that might be indexed with a variable, we need to use
1186  * the later storage type.
1187  */
1188 static bool
1189 type_has_array_or_matrix(const glsl_type *type)
1190 {
1191    if (type->is_array() || type->is_matrix())
1192       return true;
1193
1194    if (type->is_record()) {
1195       for (unsigned i = 0; i < type->length; i++) {
1196          if (type_has_array_or_matrix(type->fields.structure[i].type)) {
1197             return true;
1198          }
1199       }
1200    }
1201
1202    return false;
1203 }
1204
1205
1206 /**
1207  * In the initial pass of codegen, we assign temporary numbers to
1208  * intermediate results.  (not SSA -- variable assignments will reuse
1209  * storage).
1210  */
1211 st_src_reg
1212 glsl_to_tgsi_visitor::get_temp(const glsl_type *type)
1213 {
1214    st_src_reg src;
1215
1216    src.type = native_integers ? type->base_type : GLSL_TYPE_FLOAT;
1217    src.reladdr = NULL;
1218    src.negate = 0;
1219
1220    if (!options->EmitNoIndirectTemp && type_has_array_or_matrix(type)) {
1221       if (next_array >= max_num_arrays) {
1222          max_num_arrays += 32;
1223          array_sizes = (unsigned*)
1224             realloc(array_sizes, sizeof(array_sizes[0]) * max_num_arrays);
1225       }
1226
1227       src.file = PROGRAM_ARRAY;
1228       src.index = next_array << 16 | 0x8000;
1229       array_sizes[next_array] = type_size(type);
1230       ++next_array;
1231
1232    } else {
1233       src.file = PROGRAM_TEMPORARY;
1234       src.index = next_temp;
1235       next_temp += type_size(type);
1236    }
1237
1238    if (type->is_array() || type->is_record()) {
1239       src.swizzle = SWIZZLE_NOOP;
1240    } else {
1241       src.swizzle = swizzle_for_size(type->vector_elements);
1242    }
1243
1244    return src;
1245 }
1246
1247 variable_storage *
1248 glsl_to_tgsi_visitor::find_variable_storage(ir_variable *var)
1249 {
1250
1251    foreach_in_list(variable_storage, entry, &this->variables) {
1252       if (entry->var == var)
1253          return entry;
1254    }
1255
1256    return NULL;
1257 }
1258
1259 void
1260 glsl_to_tgsi_visitor::visit(ir_variable *ir)
1261 {
1262    if (strcmp(ir->name, "gl_FragCoord") == 0) {
1263       struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
1264
1265       fp->OriginUpperLeft = ir->data.origin_upper_left;
1266       fp->PixelCenterInteger = ir->data.pixel_center_integer;
1267    }
1268
1269    if (ir->data.mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
1270       unsigned int i;
1271       const ir_state_slot *const slots = ir->get_state_slots();
1272       assert(slots != NULL);
1273
1274       /* Check if this statevar's setup in the STATE file exactly
1275        * matches how we'll want to reference it as a
1276        * struct/array/whatever.  If not, then we need to move it into
1277        * temporary storage and hope that it'll get copy-propagated
1278        * out.
1279        */
1280       for (i = 0; i < ir->get_num_state_slots(); i++) {
1281          if (slots[i].swizzle != SWIZZLE_XYZW) {
1282             break;
1283          }
1284       }
1285
1286       variable_storage *storage;
1287       st_dst_reg dst;
1288       if (i == ir->get_num_state_slots()) {
1289          /* We'll set the index later. */
1290          storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
1291          this->variables.push_tail(storage);
1292
1293          dst = undef_dst;
1294       } else {
1295          /* The variable_storage constructor allocates slots based on the size
1296           * of the type.  However, this had better match the number of state
1297           * elements that we're going to copy into the new temporary.
1298           */
1299          assert((int) ir->get_num_state_slots() == type_size(ir->type));
1300
1301          dst = st_dst_reg(get_temp(ir->type));
1302
1303          storage = new(mem_ctx) variable_storage(ir, dst.file, dst.index);
1304
1305          this->variables.push_tail(storage);
1306       }
1307
1308
1309       for (unsigned int i = 0; i < ir->get_num_state_slots(); i++) {
1310          int index = _mesa_add_state_reference(this->prog->Parameters,
1311                                                (gl_state_index *)slots[i].tokens);
1312
1313          if (storage->file == PROGRAM_STATE_VAR) {
1314             if (storage->index == -1) {
1315                storage->index = index;
1316             } else {
1317                assert(index == storage->index + (int)i);
1318             }
1319          } else {
1320             /* We use GLSL_TYPE_FLOAT here regardless of the actual type of
1321              * the data being moved since MOV does not care about the type of
1322              * data it is moving, and we don't want to declare registers with
1323              * array or struct types.
1324              */
1325             st_src_reg src(PROGRAM_STATE_VAR, index, GLSL_TYPE_FLOAT);
1326             src.swizzle = slots[i].swizzle;
1327             emit_asm(ir, TGSI_OPCODE_MOV, dst, src);
1328             /* even a float takes up a whole vec4 reg in a struct/array. */
1329             dst.index++;
1330          }
1331       }
1332
1333       if (storage->file == PROGRAM_TEMPORARY &&
1334           dst.index != storage->index + (int) ir->get_num_state_slots()) {
1335          fail_link(this->shader_program,
1336                   "failed to load builtin uniform `%s'  (%d/%d regs loaded)\n",
1337                   ir->name, dst.index - storage->index,
1338                   type_size(ir->type));
1339       }
1340    }
1341 }
1342
1343 void
1344 glsl_to_tgsi_visitor::visit(ir_loop *ir)
1345 {
1346    emit_asm(NULL, TGSI_OPCODE_BGNLOOP);
1347
1348    visit_exec_list(&ir->body_instructions, this);
1349
1350    emit_asm(NULL, TGSI_OPCODE_ENDLOOP);
1351 }
1352
1353 void
1354 glsl_to_tgsi_visitor::visit(ir_loop_jump *ir)
1355 {
1356    switch (ir->mode) {
1357    case ir_loop_jump::jump_break:
1358       emit_asm(NULL, TGSI_OPCODE_BRK);
1359       break;
1360    case ir_loop_jump::jump_continue:
1361       emit_asm(NULL, TGSI_OPCODE_CONT);
1362       break;
1363    }
1364 }
1365
1366
1367 void
1368 glsl_to_tgsi_visitor::visit(ir_function_signature *ir)
1369 {
1370    assert(0);
1371    (void)ir;
1372 }
1373
1374 void
1375 glsl_to_tgsi_visitor::visit(ir_function *ir)
1376 {
1377    /* Ignore function bodies other than main() -- we shouldn't see calls to
1378     * them since they should all be inlined before we get to glsl_to_tgsi.
1379     */
1380    if (strcmp(ir->name, "main") == 0) {
1381       const ir_function_signature *sig;
1382       exec_list empty;
1383
1384       sig = ir->matching_signature(NULL, &empty, false);
1385
1386       assert(sig);
1387
1388       foreach_in_list(ir_instruction, ir, &sig->body) {
1389          ir->accept(this);
1390       }
1391    }
1392 }
1393
1394 bool
1395 glsl_to_tgsi_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
1396 {
1397    int nonmul_operand = 1 - mul_operand;
1398    st_src_reg a, b, c;
1399    st_dst_reg result_dst;
1400
1401    ir_expression *expr = ir->operands[mul_operand]->as_expression();
1402    if (!expr || expr->operation != ir_binop_mul)
1403       return false;
1404
1405    expr->operands[0]->accept(this);
1406    a = this->result;
1407    expr->operands[1]->accept(this);
1408    b = this->result;
1409    ir->operands[nonmul_operand]->accept(this);
1410    c = this->result;
1411
1412    this->result = get_temp(ir->type);
1413    result_dst = st_dst_reg(this->result);
1414    result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1415    emit_asm(ir, TGSI_OPCODE_MAD, result_dst, a, b, c);
1416
1417    return true;
1418 }
1419
1420 /**
1421  * Emit MAD(a, -b, a) instead of AND(a, NOT(b))
1422  *
1423  * The logic values are 1.0 for true and 0.0 for false.  Logical-and is
1424  * implemented using multiplication, and logical-or is implemented using
1425  * addition.  Logical-not can be implemented as (true - x), or (1.0 - x).
1426  * As result, the logical expression (a & !b) can be rewritten as:
1427  *
1428  *     - a * !b
1429  *     - a * (1 - b)
1430  *     - (a * 1) - (a * b)
1431  *     - a + -(a * b)
1432  *     - a + (a * -b)
1433  *
1434  * This final expression can be implemented as a single MAD(a, -b, a)
1435  * instruction.
1436  */
1437 bool
1438 glsl_to_tgsi_visitor::try_emit_mad_for_and_not(ir_expression *ir, int try_operand)
1439 {
1440    const int other_operand = 1 - try_operand;
1441    st_src_reg a, b;
1442
1443    ir_expression *expr = ir->operands[try_operand]->as_expression();
1444    if (!expr || expr->operation != ir_unop_logic_not)
1445       return false;
1446
1447    ir->operands[other_operand]->accept(this);
1448    a = this->result;
1449    expr->operands[0]->accept(this);
1450    b = this->result;
1451
1452    b.negate = ~b.negate;
1453
1454    this->result = get_temp(ir->type);
1455    emit_asm(ir, TGSI_OPCODE_MAD, st_dst_reg(this->result), a, b, a);
1456
1457    return true;
1458 }
1459
1460 void
1461 glsl_to_tgsi_visitor::reladdr_to_temp(ir_instruction *ir,
1462                                       st_src_reg *reg, int *num_reladdr)
1463 {
1464    if (!reg->reladdr && !reg->reladdr2)
1465       return;
1466
1467    if (reg->reladdr) emit_arl(ir, address_reg, *reg->reladdr);
1468    if (reg->reladdr2) emit_arl(ir, address_reg2, *reg->reladdr2);
1469
1470    if (*num_reladdr != 1) {
1471       st_src_reg temp = get_temp(reg->type == GLSL_TYPE_DOUBLE ? glsl_type::dvec4_type : glsl_type::vec4_type);
1472
1473       emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), *reg);
1474       *reg = temp;
1475    }
1476
1477    (*num_reladdr)--;
1478 }
1479
1480 void
1481 glsl_to_tgsi_visitor::visit(ir_expression *ir)
1482 {
1483    st_src_reg op[ARRAY_SIZE(ir->operands)];
1484
1485    /* Quick peephole: Emit MAD(a, b, c) instead of ADD(MUL(a, b), c)
1486     */
1487    if (ir->operation == ir_binop_add) {
1488       if (try_emit_mad(ir, 1))
1489          return;
1490       if (try_emit_mad(ir, 0))
1491          return;
1492    }
1493
1494    /* Quick peephole: Emit OPCODE_MAD(-a, -b, a) instead of AND(a, NOT(b))
1495     */
1496    if (!native_integers && ir->operation == ir_binop_logic_and) {
1497       if (try_emit_mad_for_and_not(ir, 1))
1498          return;
1499       if (try_emit_mad_for_and_not(ir, 0))
1500          return;
1501    }
1502
1503    if (ir->operation == ir_quadop_vector)
1504       assert(!"ir_quadop_vector should have been lowered");
1505
1506    for (unsigned int operand = 0; operand < ir->get_num_operands(); operand++) {
1507       this->result.file = PROGRAM_UNDEFINED;
1508       ir->operands[operand]->accept(this);
1509       if (this->result.file == PROGRAM_UNDEFINED) {
1510          printf("Failed to get tree for expression operand:\n");
1511          ir->operands[operand]->print();
1512          printf("\n");
1513          exit(1);
1514       }
1515       op[operand] = this->result;
1516
1517       /* Matrix expression operands should have been broken down to vector
1518        * operations already.
1519        */
1520       assert(!ir->operands[operand]->type->is_matrix());
1521    }
1522
1523    visit_expression(ir, op);
1524 }
1525
1526 /* The non-recursive part of the expression visitor lives in a separate
1527  * function and should be prevented from being inlined, to avoid a stack
1528  * explosion when deeply nested expressions are visited.
1529  */
1530 void
1531 glsl_to_tgsi_visitor::visit_expression(ir_expression* ir, st_src_reg *op)
1532 {
1533    st_src_reg result_src;
1534    st_dst_reg result_dst;
1535
1536    int vector_elements = ir->operands[0]->type->vector_elements;
1537    if (ir->operands[1]) {
1538       vector_elements = MAX2(vector_elements,
1539                              ir->operands[1]->type->vector_elements);
1540    }
1541
1542    this->result.file = PROGRAM_UNDEFINED;
1543
1544    /* Storage for our result.  Ideally for an assignment we'd be using
1545     * the actual storage for the result here, instead.
1546     */
1547    result_src = get_temp(ir->type);
1548    /* convenience for the emit functions below. */
1549    result_dst = st_dst_reg(result_src);
1550    /* Limit writes to the channels that will be used by result_src later.
1551     * This does limit this temp's use as a temporary for multi-instruction
1552     * sequences.
1553     */
1554    result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1555
1556    switch (ir->operation) {
1557    case ir_unop_logic_not:
1558       if (result_dst.type != GLSL_TYPE_FLOAT)
1559          emit_asm(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1560       else {
1561          /* Previously 'SEQ dst, src, 0.0' was used for this.  However, many
1562           * older GPUs implement SEQ using multiple instructions (i915 uses two
1563           * SGE instructions and a MUL instruction).  Since our logic values are
1564           * 0.0 and 1.0, 1-x also implements !x.
1565           */
1566          op[0].negate = ~op[0].negate;
1567          emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], st_src_reg_for_float(1.0));
1568       }
1569       break;
1570    case ir_unop_neg:
1571       if (result_dst.type == GLSL_TYPE_INT || result_dst.type == GLSL_TYPE_UINT)
1572          emit_asm(ir, TGSI_OPCODE_INEG, result_dst, op[0]);
1573       else if (result_dst.type == GLSL_TYPE_DOUBLE)
1574          emit_asm(ir, TGSI_OPCODE_DNEG, result_dst, op[0]);
1575       else {
1576          op[0].negate = ~op[0].negate;
1577          result_src = op[0];
1578       }
1579       break;
1580    case ir_unop_subroutine_to_int:
1581       emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1582       break;
1583    case ir_unop_abs:
1584       emit_asm(ir, TGSI_OPCODE_ABS, result_dst, op[0]);
1585       break;
1586    case ir_unop_sign:
1587       emit_asm(ir, TGSI_OPCODE_SSG, result_dst, op[0]);
1588       break;
1589    case ir_unop_rcp:
1590       emit_scalar(ir, TGSI_OPCODE_RCP, result_dst, op[0]);
1591       break;
1592
1593    case ir_unop_exp2:
1594       emit_scalar(ir, TGSI_OPCODE_EX2, result_dst, op[0]);
1595       break;
1596    case ir_unop_exp:
1597    case ir_unop_log:
1598       assert(!"not reached: should be handled by ir_explog_to_explog2");
1599       break;
1600    case ir_unop_log2:
1601       emit_scalar(ir, TGSI_OPCODE_LG2, result_dst, op[0]);
1602       break;
1603    case ir_unop_sin:
1604       emit_scalar(ir, TGSI_OPCODE_SIN, result_dst, op[0]);
1605       break;
1606    case ir_unop_cos:
1607       emit_scalar(ir, TGSI_OPCODE_COS, result_dst, op[0]);
1608       break;
1609    case ir_unop_saturate: {
1610       glsl_to_tgsi_instruction *inst;
1611       inst = emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1612       inst->saturate = true;
1613       break;
1614    }
1615
1616    case ir_unop_dFdx:
1617    case ir_unop_dFdx_coarse:
1618       emit_asm(ir, TGSI_OPCODE_DDX, result_dst, op[0]);
1619       break;
1620    case ir_unop_dFdx_fine:
1621       emit_asm(ir, TGSI_OPCODE_DDX_FINE, result_dst, op[0]);
1622       break;
1623    case ir_unop_dFdy:
1624    case ir_unop_dFdy_coarse:
1625    case ir_unop_dFdy_fine:
1626    {
1627       /* The X component contains 1 or -1 depending on whether the framebuffer
1628        * is a FBO or the window system buffer, respectively.
1629        * It is then multiplied with the source operand of DDY.
1630        */
1631       static const gl_state_index transform_y_state[STATE_LENGTH]
1632          = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM };
1633
1634       unsigned transform_y_index =
1635          _mesa_add_state_reference(this->prog->Parameters,
1636                                    transform_y_state);
1637
1638       st_src_reg transform_y = st_src_reg(PROGRAM_STATE_VAR,
1639                                           transform_y_index,
1640                                           glsl_type::vec4_type);
1641       transform_y.swizzle = SWIZZLE_XXXX;
1642
1643       st_src_reg temp = get_temp(glsl_type::vec4_type);
1644
1645       emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(temp), transform_y, op[0]);
1646       emit_asm(ir, ir->operation == ir_unop_dFdy_fine ?
1647            TGSI_OPCODE_DDY_FINE : TGSI_OPCODE_DDY, result_dst, temp);
1648       break;
1649    }
1650
1651    case ir_unop_frexp_sig:
1652       emit_asm(ir, TGSI_OPCODE_DFRACEXP, result_dst, undef_dst, op[0]);
1653       break;
1654
1655    case ir_unop_frexp_exp:
1656       emit_asm(ir, TGSI_OPCODE_DFRACEXP, undef_dst, result_dst, op[0]);
1657       break;
1658
1659    case ir_unop_noise: {
1660       /* At some point, a motivated person could add a better
1661        * implementation of noise.  Currently not even the nvidia
1662        * binary drivers do anything more than this.  In any case, the
1663        * place to do this is in the GL state tracker, not the poor
1664        * driver.
1665        */
1666       emit_asm(ir, TGSI_OPCODE_MOV, result_dst, st_src_reg_for_float(0.5));
1667       break;
1668    }
1669
1670    case ir_binop_add:
1671       emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1672       break;
1673    case ir_binop_sub:
1674       emit_asm(ir, TGSI_OPCODE_SUB, result_dst, op[0], op[1]);
1675       break;
1676
1677    case ir_binop_mul:
1678       emit_asm(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1679       break;
1680    case ir_binop_div:
1681       if (result_dst.type == GLSL_TYPE_FLOAT || result_dst.type == GLSL_TYPE_DOUBLE)
1682          assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1683       else
1684          emit_asm(ir, TGSI_OPCODE_DIV, result_dst, op[0], op[1]);
1685       break;
1686    case ir_binop_mod:
1687       if (result_dst.type == GLSL_TYPE_FLOAT)
1688          assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1689       else
1690          emit_asm(ir, TGSI_OPCODE_MOD, result_dst, op[0], op[1]);
1691       break;
1692
1693    case ir_binop_less:
1694       emit_asm(ir, TGSI_OPCODE_SLT, result_dst, op[0], op[1]);
1695       break;
1696    case ir_binop_greater:
1697       emit_asm(ir, TGSI_OPCODE_SLT, result_dst, op[1], op[0]);
1698       break;
1699    case ir_binop_lequal:
1700       emit_asm(ir, TGSI_OPCODE_SGE, result_dst, op[1], op[0]);
1701       break;
1702    case ir_binop_gequal:
1703       emit_asm(ir, TGSI_OPCODE_SGE, result_dst, op[0], op[1]);
1704       break;
1705    case ir_binop_equal:
1706       emit_asm(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1707       break;
1708    case ir_binop_nequal:
1709       emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1710       break;
1711    case ir_binop_all_equal:
1712       /* "==" operator producing a scalar boolean. */
1713       if (ir->operands[0]->type->is_vector() ||
1714           ir->operands[1]->type->is_vector()) {
1715          st_src_reg temp = get_temp(native_integers ?
1716                                     glsl_type::uvec4_type :
1717                                     glsl_type::vec4_type);
1718
1719          if (native_integers) {
1720             st_dst_reg temp_dst = st_dst_reg(temp);
1721             st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1722
1723             if (ir->operands[0]->type->is_boolean() &&
1724                 ir->operands[1]->as_constant() &&
1725                 ir->operands[1]->as_constant()->is_one()) {
1726                emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), op[0]);
1727             } else {
1728                emit_asm(ir, TGSI_OPCODE_SEQ, st_dst_reg(temp), op[0], op[1]);
1729             }
1730
1731             /* Emit 1-3 AND operations to combine the SEQ results. */
1732             switch (ir->operands[0]->type->vector_elements) {
1733             case 2:
1734                break;
1735             case 3:
1736                temp_dst.writemask = WRITEMASK_Y;
1737                temp1.swizzle = SWIZZLE_YYYY;
1738                temp2.swizzle = SWIZZLE_ZZZZ;
1739                emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1740                break;
1741             case 4:
1742                temp_dst.writemask = WRITEMASK_X;
1743                temp1.swizzle = SWIZZLE_XXXX;
1744                temp2.swizzle = SWIZZLE_YYYY;
1745                emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1746                temp_dst.writemask = WRITEMASK_Y;
1747                temp1.swizzle = SWIZZLE_ZZZZ;
1748                temp2.swizzle = SWIZZLE_WWWW;
1749                emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1750             }
1751
1752             temp1.swizzle = SWIZZLE_XXXX;
1753             temp2.swizzle = SWIZZLE_YYYY;
1754             emit_asm(ir, TGSI_OPCODE_AND, result_dst, temp1, temp2);
1755          } else {
1756             emit_asm(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1757
1758             /* After the dot-product, the value will be an integer on the
1759              * range [0,4].  Zero becomes 1.0, and positive values become zero.
1760              */
1761             emit_dp(ir, result_dst, temp, temp, vector_elements);
1762
1763             /* Negating the result of the dot-product gives values on the range
1764              * [-4, 0].  Zero becomes 1.0, and negative values become zero.
1765              * This is achieved using SGE.
1766              */
1767             st_src_reg sge_src = result_src;
1768             sge_src.negate = ~sge_src.negate;
1769             emit_asm(ir, TGSI_OPCODE_SGE, result_dst, sge_src, st_src_reg_for_float(0.0));
1770          }
1771       } else {
1772          emit_asm(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1773       }
1774       break;
1775    case ir_binop_any_nequal:
1776       /* "!=" operator producing a scalar boolean. */
1777       if (ir->operands[0]->type->is_vector() ||
1778           ir->operands[1]->type->is_vector()) {
1779          st_src_reg temp = get_temp(native_integers ?
1780                                     glsl_type::uvec4_type :
1781                                     glsl_type::vec4_type);
1782          if (ir->operands[0]->type->is_boolean() &&
1783              ir->operands[1]->as_constant() &&
1784              ir->operands[1]->as_constant()->is_zero()) {
1785             emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), op[0]);
1786          } else {
1787             emit_asm(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1788          }
1789
1790          if (native_integers) {
1791             st_dst_reg temp_dst = st_dst_reg(temp);
1792             st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1793
1794             /* Emit 1-3 OR operations to combine the SNE results. */
1795             switch (ir->operands[0]->type->vector_elements) {
1796             case 2:
1797                break;
1798             case 3:
1799                temp_dst.writemask = WRITEMASK_Y;
1800                temp1.swizzle = SWIZZLE_YYYY;
1801                temp2.swizzle = SWIZZLE_ZZZZ;
1802                emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1803                break;
1804             case 4:
1805                temp_dst.writemask = WRITEMASK_X;
1806                temp1.swizzle = SWIZZLE_XXXX;
1807                temp2.swizzle = SWIZZLE_YYYY;
1808                emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1809                temp_dst.writemask = WRITEMASK_Y;
1810                temp1.swizzle = SWIZZLE_ZZZZ;
1811                temp2.swizzle = SWIZZLE_WWWW;
1812                emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1813             }
1814
1815             temp1.swizzle = SWIZZLE_XXXX;
1816             temp2.swizzle = SWIZZLE_YYYY;
1817             emit_asm(ir, TGSI_OPCODE_OR, result_dst, temp1, temp2);
1818          } else {
1819             /* After the dot-product, the value will be an integer on the
1820              * range [0,4].  Zero stays zero, and positive values become 1.0.
1821              */
1822             glsl_to_tgsi_instruction *const dp =
1823                   emit_dp(ir, result_dst, temp, temp, vector_elements);
1824             if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1825                /* The clamping to [0,1] can be done for free in the fragment
1826                 * shader with a saturate.
1827                 */
1828                dp->saturate = true;
1829             } else {
1830                /* Negating the result of the dot-product gives values on the range
1831                 * [-4, 0].  Zero stays zero, and negative values become 1.0.  This
1832                 * achieved using SLT.
1833                 */
1834                st_src_reg slt_src = result_src;
1835                slt_src.negate = ~slt_src.negate;
1836                emit_asm(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1837             }
1838          }
1839       } else {
1840          emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1841       }
1842       break;
1843
1844    case ir_binop_logic_xor:
1845       if (native_integers)
1846          emit_asm(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1847       else
1848          emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1849       break;
1850
1851    case ir_binop_logic_or: {
1852       if (native_integers) {
1853          /* If integers are used as booleans, we can use an actual "or"
1854           * instruction.
1855           */
1856          assert(native_integers);
1857          emit_asm(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1858       } else {
1859          /* After the addition, the value will be an integer on the
1860           * range [0,2].  Zero stays zero, and positive values become 1.0.
1861           */
1862          glsl_to_tgsi_instruction *add =
1863             emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1864          if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1865             /* The clamping to [0,1] can be done for free in the fragment
1866              * shader with a saturate if floats are being used as boolean values.
1867              */
1868             add->saturate = true;
1869          } else {
1870             /* Negating the result of the addition gives values on the range
1871              * [-2, 0].  Zero stays zero, and negative values become 1.0.  This
1872              * is achieved using SLT.
1873              */
1874             st_src_reg slt_src = result_src;
1875             slt_src.negate = ~slt_src.negate;
1876             emit_asm(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1877          }
1878       }
1879       break;
1880    }
1881
1882    case ir_binop_logic_and:
1883       /* If native integers are disabled, the bool args are stored as float 0.0
1884        * or 1.0, so "mul" gives us "and".  If they're enabled, just use the
1885        * actual AND opcode.
1886        */
1887       if (native_integers)
1888          emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1889       else
1890          emit_asm(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1891       break;
1892
1893    case ir_binop_dot:
1894       assert(ir->operands[0]->type->is_vector());
1895       assert(ir->operands[0]->type == ir->operands[1]->type);
1896       emit_dp(ir, result_dst, op[0], op[1],
1897               ir->operands[0]->type->vector_elements);
1898       break;
1899
1900    case ir_unop_sqrt:
1901       if (have_sqrt) {
1902          emit_scalar(ir, TGSI_OPCODE_SQRT, result_dst, op[0]);
1903       } else {
1904          /* sqrt(x) = x * rsq(x). */
1905          emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1906          emit_asm(ir, TGSI_OPCODE_MUL, result_dst, result_src, op[0]);
1907          /* For incoming channels <= 0, set the result to 0. */
1908          op[0].negate = ~op[0].negate;
1909          emit_asm(ir, TGSI_OPCODE_CMP, result_dst,
1910               op[0], result_src, st_src_reg_for_float(0.0));
1911       }
1912       break;
1913    case ir_unop_rsq:
1914       emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1915       break;
1916    case ir_unop_i2f:
1917       if (native_integers) {
1918          emit_asm(ir, TGSI_OPCODE_I2F, result_dst, op[0]);
1919          break;
1920       }
1921       /* fallthrough to next case otherwise */
1922    case ir_unop_b2f:
1923       if (native_integers) {
1924          emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_float(1.0));
1925          break;
1926       }
1927       /* fallthrough to next case otherwise */
1928    case ir_unop_i2u:
1929    case ir_unop_u2i:
1930       /* Converting between signed and unsigned integers is a no-op. */
1931       result_src = op[0];
1932       result_src.type = result_dst.type;
1933       break;
1934    case ir_unop_b2i:
1935       if (native_integers) {
1936          /* Booleans are stored as integers using ~0 for true and 0 for false.
1937           * GLSL requires that int(bool) return 1 for true and 0 for false.
1938           * This conversion is done with AND, but it could be done with NEG.
1939           */
1940          emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_int(1));
1941       } else {
1942          /* Booleans and integers are both stored as floats when native
1943           * integers are disabled.
1944           */
1945          result_src = op[0];
1946       }
1947       break;
1948    case ir_unop_f2i:
1949       if (native_integers)
1950          emit_asm(ir, TGSI_OPCODE_F2I, result_dst, op[0]);
1951       else
1952          emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1953       break;
1954    case ir_unop_f2u:
1955       if (native_integers)
1956          emit_asm(ir, TGSI_OPCODE_F2U, result_dst, op[0]);
1957       else
1958          emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1959       break;
1960    case ir_unop_bitcast_f2i:
1961    case ir_unop_bitcast_f2u:
1962       /* Make sure we don't propagate the negate modifier to integer opcodes. */
1963       if (op[0].negate)
1964          emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1965       else
1966          result_src = op[0];
1967       result_src.type = ir->operation == ir_unop_bitcast_f2i ? GLSL_TYPE_INT :
1968                                                                GLSL_TYPE_UINT;
1969       break;
1970    case ir_unop_bitcast_i2f:
1971    case ir_unop_bitcast_u2f:
1972       result_src = op[0];
1973       result_src.type = GLSL_TYPE_FLOAT;
1974       break;
1975    case ir_unop_f2b:
1976       emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1977       break;
1978    case ir_unop_d2b:
1979       emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_double(0.0));
1980       break;
1981    case ir_unop_i2b:
1982       if (native_integers)
1983          emit_asm(ir, TGSI_OPCODE_USNE, result_dst, op[0], st_src_reg_for_int(0));
1984       else
1985          emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1986       break;
1987    case ir_unop_trunc:
1988       emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1989       break;
1990    case ir_unop_ceil:
1991       emit_asm(ir, TGSI_OPCODE_CEIL, result_dst, op[0]);
1992       break;
1993    case ir_unop_floor:
1994       emit_asm(ir, TGSI_OPCODE_FLR, result_dst, op[0]);
1995       break;
1996    case ir_unop_round_even:
1997       emit_asm(ir, TGSI_OPCODE_ROUND, result_dst, op[0]);
1998       break;
1999    case ir_unop_fract:
2000       emit_asm(ir, TGSI_OPCODE_FRC, result_dst, op[0]);
2001       break;
2002
2003    case ir_binop_min:
2004       emit_asm(ir, TGSI_OPCODE_MIN, result_dst, op[0], op[1]);
2005       break;
2006    case ir_binop_max:
2007       emit_asm(ir, TGSI_OPCODE_MAX, result_dst, op[0], op[1]);
2008       break;
2009    case ir_binop_pow:
2010       emit_scalar(ir, TGSI_OPCODE_POW, result_dst, op[0], op[1]);
2011       break;
2012
2013    case ir_unop_bit_not:
2014       if (native_integers) {
2015          emit_asm(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
2016          break;
2017       }
2018    case ir_unop_u2f:
2019       if (native_integers) {
2020          emit_asm(ir, TGSI_OPCODE_U2F, result_dst, op[0]);
2021          break;
2022       }
2023    case ir_binop_lshift:
2024       if (native_integers) {
2025          emit_asm(ir, TGSI_OPCODE_SHL, result_dst, op[0], op[1]);
2026          break;
2027       }
2028    case ir_binop_rshift:
2029       if (native_integers) {
2030          emit_asm(ir, TGSI_OPCODE_ISHR, result_dst, op[0], op[1]);
2031          break;
2032       }
2033    case ir_binop_bit_and:
2034       if (native_integers) {
2035          emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
2036          break;
2037       }
2038    case ir_binop_bit_xor:
2039       if (native_integers) {
2040          emit_asm(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
2041          break;
2042       }
2043    case ir_binop_bit_or:
2044       if (native_integers) {
2045          emit_asm(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
2046          break;
2047       }
2048
2049       assert(!"GLSL 1.30 features unsupported");
2050       break;
2051
2052    case ir_binop_ubo_load: {
2053       ir_constant *const_uniform_block = ir->operands[0]->as_constant();
2054       ir_constant *const_offset_ir = ir->operands[1]->as_constant();
2055       unsigned const_offset = const_offset_ir ? const_offset_ir->value.u[0] : 0;
2056       unsigned const_block = const_uniform_block ? const_uniform_block->value.u[0] + 1 : 0;
2057       st_src_reg index_reg = get_temp(glsl_type::uint_type);
2058       st_src_reg cbuf;
2059
2060       cbuf.type = ir->type->base_type;
2061       cbuf.file = PROGRAM_CONSTANT;
2062       cbuf.index = 0;
2063       cbuf.reladdr = NULL;
2064       cbuf.negate = 0;
2065
2066       assert(ir->type->is_vector() || ir->type->is_scalar());
2067
2068       if (const_offset_ir) {
2069          /* Constant index into constant buffer */
2070          cbuf.reladdr = NULL;
2071          cbuf.index = const_offset / 16;
2072       }
2073       else {
2074          /* Relative/variable index into constant buffer */
2075          emit_asm(ir, TGSI_OPCODE_USHR, st_dst_reg(index_reg), op[1],
2076               st_src_reg_for_int(4));
2077          cbuf.reladdr = ralloc(mem_ctx, st_src_reg);
2078          memcpy(cbuf.reladdr, &index_reg, sizeof(index_reg));
2079       }
2080
2081       if (const_uniform_block) {
2082          /* Constant constant buffer */
2083          cbuf.reladdr2 = NULL;
2084          cbuf.index2D = const_block;
2085          cbuf.has_index2 = true;
2086       }
2087       else {
2088          /* Relative/variable constant buffer */
2089          cbuf.reladdr2 = ralloc(mem_ctx, st_src_reg);
2090          cbuf.index2D = 1;
2091          memcpy(cbuf.reladdr2, &op[0], sizeof(st_src_reg));
2092          cbuf.has_index2 = true;
2093       }
2094
2095       cbuf.swizzle = swizzle_for_size(ir->type->vector_elements);
2096       if (cbuf.type == GLSL_TYPE_DOUBLE)
2097          cbuf.swizzle += MAKE_SWIZZLE4(const_offset % 16 / 8,
2098                                        const_offset % 16 / 8,
2099                                        const_offset % 16 / 8,
2100                                        const_offset % 16 / 8);
2101       else
2102          cbuf.swizzle += MAKE_SWIZZLE4(const_offset % 16 / 4,
2103                                        const_offset % 16 / 4,
2104                                        const_offset % 16 / 4,
2105                                        const_offset % 16 / 4);
2106
2107       if (ir->type->base_type == GLSL_TYPE_BOOL) {
2108          emit_asm(ir, TGSI_OPCODE_USNE, result_dst, cbuf, st_src_reg_for_int(0));
2109       } else {
2110          emit_asm(ir, TGSI_OPCODE_MOV, result_dst, cbuf);
2111       }
2112       break;
2113    }
2114    case ir_triop_lrp:
2115       /* note: we have to reorder the three args here */
2116       emit_asm(ir, TGSI_OPCODE_LRP, result_dst, op[2], op[1], op[0]);
2117       break;
2118    case ir_triop_csel:
2119       if (this->ctx->Const.NativeIntegers)
2120          emit_asm(ir, TGSI_OPCODE_UCMP, result_dst, op[0], op[1], op[2]);
2121       else {
2122          op[0].negate = ~op[0].negate;
2123          emit_asm(ir, TGSI_OPCODE_CMP, result_dst, op[0], op[1], op[2]);
2124       }
2125       break;
2126    case ir_triop_bitfield_extract:
2127       emit_asm(ir, TGSI_OPCODE_IBFE, result_dst, op[0], op[1], op[2]);
2128       break;
2129    case ir_quadop_bitfield_insert:
2130       emit_asm(ir, TGSI_OPCODE_BFI, result_dst, op[0], op[1], op[2], op[3]);
2131       break;
2132    case ir_unop_bitfield_reverse:
2133       emit_asm(ir, TGSI_OPCODE_BREV, result_dst, op[0]);
2134       break;
2135    case ir_unop_bit_count:
2136       emit_asm(ir, TGSI_OPCODE_POPC, result_dst, op[0]);
2137       break;
2138    case ir_unop_find_msb:
2139       emit_asm(ir, TGSI_OPCODE_IMSB, result_dst, op[0]);
2140       break;
2141    case ir_unop_find_lsb:
2142       emit_asm(ir, TGSI_OPCODE_LSB, result_dst, op[0]);
2143       break;
2144    case ir_binop_imul_high:
2145       emit_asm(ir, TGSI_OPCODE_IMUL_HI, result_dst, op[0], op[1]);
2146       break;
2147    case ir_triop_fma:
2148       /* In theory, MAD is incorrect here. */
2149       if (have_fma)
2150          emit_asm(ir, TGSI_OPCODE_FMA, result_dst, op[0], op[1], op[2]);
2151       else
2152          emit_asm(ir, TGSI_OPCODE_MAD, result_dst, op[0], op[1], op[2]);
2153       break;
2154    case ir_unop_interpolate_at_centroid:
2155       emit_asm(ir, TGSI_OPCODE_INTERP_CENTROID, result_dst, op[0]);
2156       break;
2157    case ir_binop_interpolate_at_offset: {
2158       /* The y coordinate needs to be flipped for the default fb */
2159       static const gl_state_index transform_y_state[STATE_LENGTH]
2160          = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM };
2161
2162       unsigned transform_y_index =
2163          _mesa_add_state_reference(this->prog->Parameters,
2164                                    transform_y_state);
2165
2166       st_src_reg transform_y = st_src_reg(PROGRAM_STATE_VAR,
2167                                           transform_y_index,
2168                                           glsl_type::vec4_type);
2169       transform_y.swizzle = SWIZZLE_XXXX;
2170
2171       st_src_reg temp = get_temp(glsl_type::vec2_type);
2172       st_dst_reg temp_dst = st_dst_reg(temp);
2173
2174       emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, op[1]);
2175       temp_dst.writemask = WRITEMASK_Y;
2176       emit_asm(ir, TGSI_OPCODE_MUL, temp_dst, transform_y, op[1]);
2177       emit_asm(ir, TGSI_OPCODE_INTERP_OFFSET, result_dst, op[0], temp);
2178       break;
2179    }
2180    case ir_binop_interpolate_at_sample:
2181       emit_asm(ir, TGSI_OPCODE_INTERP_SAMPLE, result_dst, op[0], op[1]);
2182       break;
2183
2184    case ir_unop_d2f:
2185       emit_asm(ir, TGSI_OPCODE_D2F, result_dst, op[0]);
2186       break;
2187    case ir_unop_f2d:
2188       emit_asm(ir, TGSI_OPCODE_F2D, result_dst, op[0]);
2189       break;
2190    case ir_unop_d2i:
2191       emit_asm(ir, TGSI_OPCODE_D2I, result_dst, op[0]);
2192       break;
2193    case ir_unop_i2d:
2194       emit_asm(ir, TGSI_OPCODE_I2D, result_dst, op[0]);
2195       break;
2196    case ir_unop_d2u:
2197       emit_asm(ir, TGSI_OPCODE_D2U, result_dst, op[0]);
2198       break;
2199    case ir_unop_u2d:
2200       emit_asm(ir, TGSI_OPCODE_U2D, result_dst, op[0]);
2201       break;
2202    case ir_unop_unpack_double_2x32:
2203    case ir_unop_pack_double_2x32:
2204       emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
2205       break;
2206
2207    case ir_binop_ldexp:
2208       if (ir->operands[0]->type->base_type == GLSL_TYPE_DOUBLE) {
2209          emit_asm(ir, TGSI_OPCODE_DLDEXP, result_dst, op[0], op[1]);
2210       } else {
2211          assert(!"Invalid ldexp for non-double opcode in glsl_to_tgsi_visitor::visit()");
2212       }
2213       break;
2214
2215    case ir_unop_pack_half_2x16:
2216       emit_asm(ir, TGSI_OPCODE_PK2H, result_dst, op[0]);
2217       break;
2218    case ir_unop_unpack_half_2x16:
2219       emit_asm(ir, TGSI_OPCODE_UP2H, result_dst, op[0]);
2220       break;
2221
2222    case ir_unop_get_buffer_size: {
2223       ir_constant *const_offset = ir->operands[0]->as_constant();
2224       st_src_reg buffer(
2225             PROGRAM_BUFFER,
2226             ctx->Const.Program[shader->Stage].MaxAtomicBuffers +
2227             (const_offset ? const_offset->value.u[0] : 0),
2228             GLSL_TYPE_UINT);
2229       if (!const_offset) {
2230          buffer.reladdr = ralloc(mem_ctx, st_src_reg);
2231          memcpy(buffer.reladdr, &sampler_reladdr, sizeof(sampler_reladdr));
2232          emit_arl(ir, sampler_reladdr, op[0]);
2233       }
2234       emit_asm(ir, TGSI_OPCODE_RESQ, result_dst)->buffer = buffer;
2235       break;
2236    }
2237
2238    case ir_unop_pack_snorm_2x16:
2239    case ir_unop_pack_unorm_2x16:
2240    case ir_unop_pack_snorm_4x8:
2241    case ir_unop_pack_unorm_4x8:
2242
2243    case ir_unop_unpack_snorm_2x16:
2244    case ir_unop_unpack_unorm_2x16:
2245    case ir_unop_unpack_snorm_4x8:
2246    case ir_unop_unpack_unorm_4x8:
2247
2248    case ir_quadop_vector:
2249    case ir_binop_vector_extract:
2250    case ir_triop_vector_insert:
2251    case ir_binop_carry:
2252    case ir_binop_borrow:
2253    case ir_unop_ssbo_unsized_array_length:
2254       /* This operation is not supported, or should have already been handled.
2255        */
2256       assert(!"Invalid ir opcode in glsl_to_tgsi_visitor::visit()");
2257       break;
2258    }
2259
2260    this->result = result_src;
2261 }
2262
2263
2264 void
2265 glsl_to_tgsi_visitor::visit(ir_swizzle *ir)
2266 {
2267    st_src_reg src;
2268    int i;
2269    int swizzle[4];
2270
2271    /* Note that this is only swizzles in expressions, not those on the left
2272     * hand side of an assignment, which do write masking.  See ir_assignment
2273     * for that.
2274     */
2275
2276    ir->val->accept(this);
2277    src = this->result;
2278    assert(src.file != PROGRAM_UNDEFINED);
2279    assert(ir->type->vector_elements > 0);
2280
2281    for (i = 0; i < 4; i++) {
2282       if (i < ir->type->vector_elements) {
2283          switch (i) {
2284          case 0:
2285             swizzle[i] = GET_SWZ(src.swizzle, ir->mask.x);
2286             break;
2287          case 1:
2288             swizzle[i] = GET_SWZ(src.swizzle, ir->mask.y);
2289             break;
2290          case 2:
2291             swizzle[i] = GET_SWZ(src.swizzle, ir->mask.z);
2292             break;
2293          case 3:
2294             swizzle[i] = GET_SWZ(src.swizzle, ir->mask.w);
2295             break;
2296          }
2297       } else {
2298          /* If the type is smaller than a vec4, replicate the last
2299           * channel out.
2300           */
2301          swizzle[i] = swizzle[ir->type->vector_elements - 1];
2302       }
2303    }
2304
2305    src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
2306
2307    this->result = src;
2308 }
2309
2310 /* Test if the variable is an array. Note that geometry and
2311  * tessellation shader inputs are outputs are always arrays (except
2312  * for patch inputs), so only the array element type is considered.
2313  */
2314 static bool
2315 is_inout_array(unsigned stage, ir_variable *var, bool *is_2d)
2316 {
2317    const glsl_type *type = var->type;
2318
2319    if ((stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
2320        (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out))
2321       return false;
2322
2323    *is_2d = false;
2324
2325    if (((stage == MESA_SHADER_GEOMETRY && var->data.mode == ir_var_shader_in) ||
2326         (stage == MESA_SHADER_TESS_EVAL && var->data.mode == ir_var_shader_in) ||
2327         stage == MESA_SHADER_TESS_CTRL) &&
2328        !var->data.patch) {
2329       if (!var->type->is_array())
2330          return false; /* a system value probably */
2331
2332       type = var->type->fields.array;
2333       *is_2d = true;
2334    }
2335
2336    return type->is_array() || type->is_matrix();
2337 }
2338
2339 void
2340 glsl_to_tgsi_visitor::visit(ir_dereference_variable *ir)
2341 {
2342    variable_storage *entry = find_variable_storage(ir->var);
2343    ir_variable *var = ir->var;
2344    bool is_2d;
2345
2346    if (!entry) {
2347       switch (var->data.mode) {
2348       case ir_var_uniform:
2349          entry = new(mem_ctx) variable_storage(var, PROGRAM_UNIFORM,
2350                                                var->data.param_index);
2351          this->variables.push_tail(entry);
2352          break;
2353       case ir_var_shader_in:
2354          /* The linker assigns locations for varyings and attributes,
2355           * including deprecated builtins (like gl_Color), user-assign
2356           * generic attributes (glBindVertexLocation), and
2357           * user-defined varyings.
2358           */
2359          assert(var->data.location != -1);
2360
2361          if (is_inout_array(shader->Stage, var, &is_2d)) {
2362             struct array_decl *decl = &input_arrays[num_input_arrays];
2363
2364             decl->mesa_index = var->data.location;
2365             decl->array_id = num_input_arrays + 1;
2366             if (is_2d) {
2367                decl->array_size = type_size(var->type->fields.array);
2368                decl->array_type = var->type->fields.array->without_array()->base_type;
2369             } else {
2370                decl->array_size = type_size(var->type);
2371                decl->array_type = var->type->without_array()->base_type;
2372             }
2373             num_input_arrays++;
2374
2375             entry = new(mem_ctx) variable_storage(var,
2376                                                   PROGRAM_INPUT,
2377                                                   var->data.location,
2378                                                   decl->array_id);
2379          }
2380          else {
2381             entry = new(mem_ctx) variable_storage(var,
2382                                                   PROGRAM_INPUT,
2383                                                   var->data.location);
2384          }
2385          this->variables.push_tail(entry);
2386          break;
2387       case ir_var_shader_out:
2388          assert(var->data.location != -1);
2389
2390          if (is_inout_array(shader->Stage, var, &is_2d)) {
2391             struct array_decl *decl = &output_arrays[num_output_arrays];
2392
2393             decl->mesa_index = var->data.location;
2394             decl->array_id = num_output_arrays + 1;
2395             if (is_2d) {
2396                decl->array_size = type_size(var->type->fields.array);
2397                decl->array_type = var->type->fields.array->without_array()->base_type;
2398             } else {
2399                decl->array_size = type_size(var->type);
2400                decl->array_type = var->type->without_array()->base_type;
2401             }
2402             num_output_arrays++;
2403
2404             entry = new(mem_ctx) variable_storage(var,
2405                                                   PROGRAM_OUTPUT,
2406                                                   var->data.location,
2407                                                   decl->array_id);
2408          }
2409          else {
2410             entry = new(mem_ctx) variable_storage(var,
2411                                                   PROGRAM_OUTPUT,
2412                                                   var->data.location
2413                                                   + var->data.index);
2414          }
2415          this->variables.push_tail(entry);
2416          break;
2417       case ir_var_system_value:
2418          entry = new(mem_ctx) variable_storage(var,
2419                                                PROGRAM_SYSTEM_VALUE,
2420                                                var->data.location);
2421          break;
2422       case ir_var_auto:
2423       case ir_var_temporary:
2424          st_src_reg src = get_temp(var->type);
2425
2426          entry = new(mem_ctx) variable_storage(var, src.file, src.index);
2427          this->variables.push_tail(entry);
2428
2429          break;
2430       }
2431
2432       if (!entry) {
2433          printf("Failed to make storage for %s\n", var->name);
2434          exit(1);
2435       }
2436    }
2437
2438    this->result = st_src_reg(entry->file, entry->index, var->type);
2439    this->result.array_id = entry->array_id;
2440    if (this->shader->Stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in && var->type->is_double())
2441       this->result.is_double_vertex_input = true;
2442    if (!native_integers)
2443       this->result.type = GLSL_TYPE_FLOAT;
2444 }
2445
2446 static void
2447 shrink_array_declarations(struct array_decl *arrays, unsigned count,
2448                           GLbitfield64 usage_mask,
2449                           GLbitfield64 double_usage_mask,
2450                           GLbitfield patch_usage_mask)
2451 {
2452    unsigned i, j;
2453
2454    /* Fix array declarations by removing unused array elements at both ends
2455     * of the arrays. For example, mat4[3] where only mat[1] is used.
2456     */
2457    for (i = 0; i < count; i++) {
2458       struct array_decl *decl = &arrays[i];
2459
2460       /* Shrink the beginning. */
2461       for (j = 0; j < decl->array_size; j++) {
2462          if (decl->mesa_index >= VARYING_SLOT_PATCH0) {
2463             if (patch_usage_mask &
2464                 BITFIELD64_BIT(decl->mesa_index - VARYING_SLOT_PATCH0 + j))
2465                break;
2466          }
2467          else {
2468             if (usage_mask & BITFIELD64_BIT(decl->mesa_index+j))
2469                break;
2470             if (double_usage_mask & BITFIELD64_BIT(decl->mesa_index+j-1))
2471                break;
2472          }
2473
2474          decl->mesa_index++;
2475          decl->array_size--;
2476          j--;
2477       }
2478
2479       /* Shrink the end. */
2480       for (j = decl->array_size-1; j >= 0; j--) {
2481          if (decl->mesa_index >= VARYING_SLOT_PATCH0) {
2482             if (patch_usage_mask &
2483                 BITFIELD64_BIT(decl->mesa_index - VARYING_SLOT_PATCH0 + j))
2484                break;
2485          }
2486          else {
2487             if (usage_mask & BITFIELD64_BIT(decl->mesa_index+j))
2488                break;
2489             if (double_usage_mask & BITFIELD64_BIT(decl->mesa_index+j-1))
2490                break;
2491          }
2492
2493          decl->array_size--;
2494       }
2495    }
2496 }
2497
2498 void
2499 glsl_to_tgsi_visitor::visit(ir_dereference_array *ir)
2500 {
2501    ir_constant *index;
2502    st_src_reg src;
2503    int element_size = type_size(ir->type);
2504    bool is_2D = false;
2505
2506    index = ir->array_index->constant_expression_value();
2507
2508    ir->array->accept(this);
2509    src = this->result;
2510
2511    if (ir->array->ir_type != ir_type_dereference_array) {
2512       switch (this->prog->Target) {
2513       case GL_TESS_CONTROL_PROGRAM_NV:
2514          is_2D = (src.file == PROGRAM_INPUT || src.file == PROGRAM_OUTPUT) &&
2515                  !ir->variable_referenced()->data.patch;
2516          break;
2517       case GL_TESS_EVALUATION_PROGRAM_NV:
2518          is_2D = src.file == PROGRAM_INPUT &&
2519                  !ir->variable_referenced()->data.patch;
2520          break;
2521       case GL_GEOMETRY_PROGRAM_NV:
2522          is_2D = src.file == PROGRAM_INPUT;
2523          break;
2524       }
2525    }
2526
2527    if (is_2D)
2528       element_size = 1;
2529
2530    if (index) {
2531
2532       if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
2533           src.file == PROGRAM_INPUT)
2534          element_size = attrib_type_size(ir->type, true);
2535       if (is_2D) {
2536          src.index2D = index->value.i[0];
2537          src.has_index2 = true;
2538       } else
2539          src.index += index->value.i[0] * element_size;
2540    } else {
2541       /* Variable index array dereference.  It eats the "vec4" of the
2542        * base of the array and an index that offsets the TGSI register
2543        * index.
2544        */
2545       ir->array_index->accept(this);
2546
2547       st_src_reg index_reg;
2548
2549       if (element_size == 1) {
2550          index_reg = this->result;
2551       } else {
2552          index_reg = get_temp(native_integers ?
2553                               glsl_type::int_type : glsl_type::float_type);
2554
2555          emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(index_reg),
2556               this->result, st_src_reg_for_type(index_reg.type, element_size));
2557       }
2558
2559       /* If there was already a relative address register involved, add the
2560        * new and the old together to get the new offset.
2561        */
2562       if (!is_2D && src.reladdr != NULL) {
2563          st_src_reg accum_reg = get_temp(native_integers ?
2564                                 glsl_type::int_type : glsl_type::float_type);
2565
2566          emit_asm(ir, TGSI_OPCODE_ADD, st_dst_reg(accum_reg),
2567               index_reg, *src.reladdr);
2568
2569          index_reg = accum_reg;
2570       }
2571
2572       if (is_2D) {
2573          src.reladdr2 = ralloc(mem_ctx, st_src_reg);
2574          memcpy(src.reladdr2, &index_reg, sizeof(index_reg));
2575          src.index2D = 0;
2576          src.has_index2 = true;
2577       } else {
2578          src.reladdr = ralloc(mem_ctx, st_src_reg);
2579          memcpy(src.reladdr, &index_reg, sizeof(index_reg));
2580       }
2581    }
2582
2583    /* If the type is smaller than a vec4, replicate the last channel out. */
2584    if (ir->type->is_scalar() || ir->type->is_vector())
2585       src.swizzle = swizzle_for_size(ir->type->vector_elements);
2586    else
2587       src.swizzle = SWIZZLE_NOOP;
2588
2589    /* Change the register type to the element type of the array. */
2590    src.type = ir->type->base_type;
2591
2592    this->result = src;
2593 }
2594
2595 void
2596 glsl_to_tgsi_visitor::visit(ir_dereference_record *ir)
2597 {
2598    unsigned int i;
2599    const glsl_type *struct_type = ir->record->type;
2600    int offset = 0;
2601
2602    ir->record->accept(this);
2603
2604    for (i = 0; i < struct_type->length; i++) {
2605       if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
2606          break;
2607       offset += type_size(struct_type->fields.structure[i].type);
2608    }
2609
2610    /* If the type is smaller than a vec4, replicate the last channel out. */
2611    if (ir->type->is_scalar() || ir->type->is_vector())
2612       this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
2613    else
2614       this->result.swizzle = SWIZZLE_NOOP;
2615
2616    this->result.index += offset;
2617    this->result.type = ir->type->base_type;
2618 }
2619
2620 /**
2621  * We want to be careful in assignment setup to hit the actual storage
2622  * instead of potentially using a temporary like we might with the
2623  * ir_dereference handler.
2624  */
2625 static st_dst_reg
2626 get_assignment_lhs(ir_dereference *ir, glsl_to_tgsi_visitor *v)
2627 {
2628    /* The LHS must be a dereference.  If the LHS is a variable indexed array
2629     * access of a vector, it must be separated into a series conditional moves
2630     * before reaching this point (see ir_vec_index_to_cond_assign).
2631     */
2632    assert(ir->as_dereference());
2633    ir_dereference_array *deref_array = ir->as_dereference_array();
2634    if (deref_array) {
2635       assert(!deref_array->array->type->is_vector());
2636    }
2637
2638    /* Use the rvalue deref handler for the most part.  We'll ignore
2639     * swizzles in it and write swizzles using writemask, though.
2640     */
2641    ir->accept(v);
2642    return st_dst_reg(v->result);
2643 }
2644
2645 /**
2646  * Process the condition of a conditional assignment
2647  *
2648  * Examines the condition of a conditional assignment to generate the optimal
2649  * first operand of a \c CMP instruction.  If the condition is a relational
2650  * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
2651  * used as the source for the \c CMP instruction.  Otherwise the comparison
2652  * is processed to a boolean result, and the boolean result is used as the
2653  * operand to the CMP instruction.
2654  */
2655 bool
2656 glsl_to_tgsi_visitor::process_move_condition(ir_rvalue *ir)
2657 {
2658    ir_rvalue *src_ir = ir;
2659    bool negate = true;
2660    bool switch_order = false;
2661
2662    ir_expression *const expr = ir->as_expression();
2663
2664    if (native_integers) {
2665       if ((expr != NULL) && (expr->get_num_operands() == 2)) {
2666          enum glsl_base_type type = expr->operands[0]->type->base_type;
2667          if (type == GLSL_TYPE_INT || type == GLSL_TYPE_UINT ||
2668              type == GLSL_TYPE_BOOL) {
2669             if (expr->operation == ir_binop_equal) {
2670                if (expr->operands[0]->is_zero()) {
2671                   src_ir = expr->operands[1];
2672                   switch_order = true;
2673                }
2674                else if (expr->operands[1]->is_zero()) {
2675                   src_ir = expr->operands[0];
2676                   switch_order = true;
2677                }
2678             }
2679             else if (expr->operation == ir_binop_nequal) {
2680                if (expr->operands[0]->is_zero()) {
2681                   src_ir = expr->operands[1];
2682                }
2683                else if (expr->operands[1]->is_zero()) {
2684                   src_ir = expr->operands[0];
2685                }
2686             }
2687          }
2688       }
2689
2690       src_ir->accept(this);
2691       return switch_order;
2692    }
2693
2694    if ((expr != NULL) && (expr->get_num_operands() == 2)) {
2695       bool zero_on_left = false;
2696
2697       if (expr->operands[0]->is_zero()) {
2698          src_ir = expr->operands[1];
2699          zero_on_left = true;
2700       } else if (expr->operands[1]->is_zero()) {
2701          src_ir = expr->operands[0];
2702          zero_on_left = false;
2703       }
2704
2705       /*      a is -  0  +            -  0  +
2706        * (a <  0)  T  F  F  ( a < 0)  T  F  F
2707        * (0 <  a)  F  F  T  (-a < 0)  F  F  T
2708        * (a <= 0)  T  T  F  (-a < 0)  F  F  T  (swap order of other operands)
2709        * (0 <= a)  F  T  T  ( a < 0)  T  F  F  (swap order of other operands)
2710        * (a >  0)  F  F  T  (-a < 0)  F  F  T
2711        * (0 >  a)  T  F  F  ( a < 0)  T  F  F
2712        * (a >= 0)  F  T  T  ( a < 0)  T  F  F  (swap order of other operands)
2713        * (0 >= a)  T  T  F  (-a < 0)  F  F  T  (swap order of other operands)
2714        *
2715        * Note that exchanging the order of 0 and 'a' in the comparison simply
2716        * means that the value of 'a' should be negated.
2717        */
2718       if (src_ir != ir) {
2719          switch (expr->operation) {
2720          case ir_binop_less:
2721             switch_order = false;
2722             negate = zero_on_left;
2723             break;
2724
2725          case ir_binop_greater:
2726             switch_order = false;
2727             negate = !zero_on_left;
2728             break;
2729
2730          case ir_binop_lequal:
2731             switch_order = true;
2732             negate = !zero_on_left;
2733             break;
2734
2735          case ir_binop_gequal:
2736             switch_order = true;
2737             negate = zero_on_left;
2738             break;
2739
2740          default:
2741             /* This isn't the right kind of comparison afterall, so make sure
2742              * the whole condition is visited.
2743              */
2744             src_ir = ir;
2745             break;
2746          }
2747       }
2748    }
2749
2750    src_ir->accept(this);
2751
2752    /* We use the TGSI_OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
2753     * condition we produced is 0.0 or 1.0.  By flipping the sign, we can
2754     * choose which value TGSI_OPCODE_CMP produces without an extra instruction
2755     * computing the condition.
2756     */
2757    if (negate)
2758       this->result.negate = ~this->result.negate;
2759
2760    return switch_order;
2761 }
2762
2763 void
2764 glsl_to_tgsi_visitor::emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
2765                                      st_dst_reg *l, st_src_reg *r,
2766                                      st_src_reg *cond, bool cond_swap)
2767 {
2768    if (type->base_type == GLSL_TYPE_STRUCT) {
2769       for (unsigned int i = 0; i < type->length; i++) {
2770          emit_block_mov(ir, type->fields.structure[i].type, l, r,
2771                         cond, cond_swap);
2772       }
2773       return;
2774    }
2775
2776    if (type->is_array()) {
2777       for (unsigned int i = 0; i < type->length; i++) {
2778          emit_block_mov(ir, type->fields.array, l, r, cond, cond_swap);
2779       }
2780       return;
2781    }
2782
2783    if (type->is_matrix()) {
2784       const struct glsl_type *vec_type;
2785
2786       vec_type = glsl_type::get_instance(type->is_double() ? GLSL_TYPE_DOUBLE : GLSL_TYPE_FLOAT,
2787                                          type->vector_elements, 1);
2788
2789       for (int i = 0; i < type->matrix_columns; i++) {
2790          emit_block_mov(ir, vec_type, l, r, cond, cond_swap);
2791       }
2792       return;
2793    }
2794
2795    assert(type->is_scalar() || type->is_vector());
2796
2797    r->type = type->base_type;
2798    if (cond) {
2799       st_src_reg l_src = st_src_reg(*l);
2800       l_src.swizzle = swizzle_for_size(type->vector_elements);
2801
2802       if (native_integers) {
2803          emit_asm(ir, TGSI_OPCODE_UCMP, *l, *cond,
2804               cond_swap ? l_src : *r,
2805               cond_swap ? *r : l_src);
2806       } else {
2807          emit_asm(ir, TGSI_OPCODE_CMP, *l, *cond,
2808               cond_swap ? l_src : *r,
2809               cond_swap ? *r : l_src);
2810       }
2811    } else {
2812       emit_asm(ir, TGSI_OPCODE_MOV, *l, *r);
2813    }
2814    l->index++;
2815    r->index++;
2816    if (type->is_dual_slot_double()) {
2817       l->index++;
2818       if (r->is_double_vertex_input == false)
2819          r->index++;
2820    }
2821 }
2822
2823 void
2824 glsl_to_tgsi_visitor::visit(ir_assignment *ir)
2825 {
2826    st_dst_reg l;
2827    st_src_reg r;
2828
2829    ir->rhs->accept(this);
2830    r = this->result;
2831
2832    l = get_assignment_lhs(ir->lhs, this);
2833
2834    /* FINISHME: This should really set to the correct maximal writemask for each
2835     * FINISHME: component written (in the loops below).  This case can only
2836     * FINISHME: occur for matrices, arrays, and structures.
2837     */
2838    if (ir->write_mask == 0) {
2839       assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
2840
2841       if (ir->lhs->type->is_array() || ir->lhs->type->without_array()->is_matrix()) {
2842          if (ir->lhs->type->without_array()->is_double()) {
2843             switch (ir->lhs->type->without_array()->vector_elements) {
2844             case 1:
2845                l.writemask = WRITEMASK_X;
2846                break;
2847             case 2:
2848                l.writemask = WRITEMASK_XY;
2849                break;
2850             case 3:
2851                l.writemask = WRITEMASK_XYZ;
2852                break;
2853             case 4:
2854                l.writemask = WRITEMASK_XYZW;
2855                break;
2856             }
2857          } else
2858             l.writemask = WRITEMASK_XYZW;
2859       }
2860    } else if (ir->lhs->type->is_scalar() &&
2861               !ir->lhs->type->is_double() &&
2862               ir->lhs->variable_referenced()->data.mode == ir_var_shader_out) {
2863       /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
2864        * FINISHME: W component of fragment shader output zero, work correctly.
2865        */
2866       l.writemask = WRITEMASK_XYZW;
2867    } else {
2868       int swizzles[4];
2869       int first_enabled_chan = 0;
2870       int rhs_chan = 0;
2871
2872       l.writemask = ir->write_mask;
2873
2874       for (int i = 0; i < 4; i++) {
2875          if (l.writemask & (1 << i)) {
2876             first_enabled_chan = GET_SWZ(r.swizzle, i);
2877             break;
2878          }
2879       }
2880
2881       /* Swizzle a small RHS vector into the channels being written.
2882        *
2883        * glsl ir treats write_mask as dictating how many channels are
2884        * present on the RHS while TGSI treats write_mask as just
2885        * showing which channels of the vec4 RHS get written.
2886        */
2887       for (int i = 0; i < 4; i++) {
2888          if (l.writemask & (1 << i))
2889             swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
2890          else
2891             swizzles[i] = first_enabled_chan;
2892       }
2893       r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
2894                                 swizzles[2], swizzles[3]);
2895    }
2896
2897    assert(l.file != PROGRAM_UNDEFINED);
2898    assert(r.file != PROGRAM_UNDEFINED);
2899
2900    if (ir->condition) {
2901       const bool switch_order = this->process_move_condition(ir->condition);
2902       st_src_reg condition = this->result;
2903
2904       emit_block_mov(ir, ir->lhs->type, &l, &r, &condition, switch_order);
2905    } else if (ir->rhs->as_expression() &&
2906               this->instructions.get_tail() &&
2907               ir->rhs == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->ir &&
2908               type_size(ir->lhs->type) == 1 &&
2909               l.writemask == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->dst[0].writemask) {
2910       /* To avoid emitting an extra MOV when assigning an expression to a
2911        * variable, emit the last instruction of the expression again, but
2912        * replace the destination register with the target of the assignment.
2913        * Dead code elimination will remove the original instruction.
2914        */
2915       glsl_to_tgsi_instruction *inst, *new_inst;
2916       inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
2917       new_inst = emit_asm(ir, inst->op, l, inst->src[0], inst->src[1], inst->src[2], inst->src[3]);
2918       new_inst->saturate = inst->saturate;
2919       inst->dead_mask = inst->dst[0].writemask;
2920    } else {
2921       emit_block_mov(ir, ir->rhs->type, &l, &r, NULL, false);
2922    }
2923 }
2924
2925
2926 void
2927 glsl_to_tgsi_visitor::visit(ir_constant *ir)
2928 {
2929    st_src_reg src;
2930    GLdouble stack_vals[4] = { 0 };
2931    gl_constant_value *values = (gl_constant_value *) stack_vals;
2932    GLenum gl_type = GL_NONE;
2933    unsigned int i;
2934    static int in_array = 0;
2935    gl_register_file file = in_array ? PROGRAM_CONSTANT : PROGRAM_IMMEDIATE;
2936
2937    /* Unfortunately, 4 floats is all we can get into
2938     * _mesa_add_typed_unnamed_constant.  So, make a temp to store an
2939     * aggregate constant and move each constant value into it.  If we
2940     * get lucky, copy propagation will eliminate the extra moves.
2941     */
2942    if (ir->type->base_type == GLSL_TYPE_STRUCT) {
2943       st_src_reg temp_base = get_temp(ir->type);
2944       st_dst_reg temp = st_dst_reg(temp_base);
2945
2946       foreach_in_list(ir_constant, field_value, &ir->components) {
2947          int size = type_size(field_value->type);
2948
2949          assert(size > 0);
2950
2951          field_value->accept(this);
2952          src = this->result;
2953
2954          for (i = 0; i < (unsigned int)size; i++) {
2955             emit_asm(ir, TGSI_OPCODE_MOV, temp, src);
2956
2957             src.index++;
2958             temp.index++;
2959          }
2960       }
2961       this->result = temp_base;
2962       return;
2963    }
2964
2965    if (ir->type->is_array()) {
2966       st_src_reg temp_base = get_temp(ir->type);
2967       st_dst_reg temp = st_dst_reg(temp_base);
2968       int size = type_size(ir->type->fields.array);
2969
2970       assert(size > 0);
2971       in_array++;
2972
2973       for (i = 0; i < ir->type->length; i++) {
2974          ir->array_elements[i]->accept(this);
2975          src = this->result;
2976          for (int j = 0; j < size; j++) {
2977             emit_asm(ir, TGSI_OPCODE_MOV, temp, src);
2978
2979             src.index++;
2980             temp.index++;
2981          }
2982       }
2983       this->result = temp_base;
2984       in_array--;
2985       return;
2986    }
2987
2988    if (ir->type->is_matrix()) {
2989       st_src_reg mat = get_temp(ir->type);
2990       st_dst_reg mat_column = st_dst_reg(mat);
2991
2992       for (i = 0; i < ir->type->matrix_columns; i++) {
2993          switch (ir->type->base_type) {
2994          case GLSL_TYPE_FLOAT:
2995             values = (gl_constant_value *) &ir->value.f[i * ir->type->vector_elements];
2996
2997             src = st_src_reg(file, -1, ir->type->base_type);
2998             src.index = add_constant(file,
2999                                      values,
3000                                      ir->type->vector_elements,
3001                                      GL_FLOAT,
3002                                      &src.swizzle);
3003             emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3004             break;
3005          case GLSL_TYPE_DOUBLE:
3006             values = (gl_constant_value *) &ir->value.d[i * ir->type->vector_elements];
3007             src = st_src_reg(file, -1, ir->type->base_type);
3008             src.index = add_constant(file,
3009                                      values,
3010                                      ir->type->vector_elements,
3011                                      GL_DOUBLE,
3012                                      &src.swizzle);
3013             if (ir->type->vector_elements >= 2) {
3014                mat_column.writemask = WRITEMASK_XY;
3015                src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
3016                emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3017             } else {
3018                mat_column.writemask = WRITEMASK_X;
3019                src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X);
3020                emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3021             }
3022             src.index++;
3023             if (ir->type->vector_elements > 2) {
3024                if (ir->type->vector_elements == 4) {
3025                   mat_column.writemask = WRITEMASK_ZW;
3026                   src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
3027                   emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3028                } else {
3029                   mat_column.writemask = WRITEMASK_Z;
3030                   src.swizzle = MAKE_SWIZZLE4(SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y);
3031                   emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3032                   mat_column.writemask = WRITEMASK_XYZW;
3033                   src.swizzle = SWIZZLE_XYZW;
3034                }
3035                mat_column.index++;
3036             }
3037             break;
3038          default:
3039             unreachable("Illegal matrix constant type.\n");
3040             break;
3041          }
3042          mat_column.index++;
3043       }
3044       this->result = mat;
3045       return;
3046    }
3047
3048    switch (ir->type->base_type) {
3049    case GLSL_TYPE_FLOAT:
3050       gl_type = GL_FLOAT;
3051       for (i = 0; i < ir->type->vector_elements; i++) {
3052          values[i].f = ir->value.f[i];
3053       }
3054       break;
3055    case GLSL_TYPE_DOUBLE:
3056       gl_type = GL_DOUBLE;
3057       for (i = 0; i < ir->type->vector_elements; i++) {
3058          values[i * 2].i = *(uint32_t *)&ir->value.d[i];
3059          values[i * 2 + 1].i = *(((uint32_t *)&ir->value.d[i]) + 1);
3060       }
3061       break;
3062    case GLSL_TYPE_UINT:
3063       gl_type = native_integers ? GL_UNSIGNED_INT : GL_FLOAT;
3064       for (i = 0; i < ir->type->vector_elements; i++) {
3065          if (native_integers)
3066             values[i].u = ir->value.u[i];
3067          else
3068             values[i].f = ir->value.u[i];
3069       }
3070       break;
3071    case GLSL_TYPE_INT:
3072       gl_type = native_integers ? GL_INT : GL_FLOAT;
3073       for (i = 0; i < ir->type->vector_elements; i++) {
3074          if (native_integers)
3075             values[i].i = ir->value.i[i];
3076          else
3077             values[i].f = ir->value.i[i];
3078       }
3079       break;
3080    case GLSL_TYPE_BOOL:
3081       gl_type = native_integers ? GL_BOOL : GL_FLOAT;
3082       for (i = 0; i < ir->type->vector_elements; i++) {
3083          values[i].u = ir->value.b[i] ? ctx->Const.UniformBooleanTrue : 0;
3084       }
3085       break;
3086    default:
3087       assert(!"Non-float/uint/int/bool constant");
3088    }
3089
3090    this->result = st_src_reg(file, -1, ir->type);
3091    this->result.index = add_constant(file,
3092                                      values,
3093                                      ir->type->vector_elements,
3094                                      gl_type,
3095                                      &this->result.swizzle);
3096 }
3097
3098 function_entry *
3099 glsl_to_tgsi_visitor::get_function_signature(ir_function_signature *sig)
3100 {
3101    foreach_in_list_use_after(function_entry, entry, &this->function_signatures) {
3102       if (entry->sig == sig)
3103          return entry;
3104    }
3105
3106    entry = ralloc(mem_ctx, function_entry);
3107    entry->sig = sig;
3108    entry->sig_id = this->next_signature_id++;
3109    entry->bgn_inst = NULL;
3110
3111    /* Allocate storage for all the parameters. */
3112    foreach_in_list(ir_variable, param, &sig->parameters) {
3113       variable_storage *storage;
3114
3115       storage = find_variable_storage(param);
3116       assert(!storage);
3117
3118       st_src_reg src = get_temp(param->type);
3119
3120       storage = new(mem_ctx) variable_storage(param, src.file, src.index);
3121       this->variables.push_tail(storage);
3122    }
3123
3124    if (!sig->return_type->is_void()) {
3125       entry->return_reg = get_temp(sig->return_type);
3126    } else {
3127       entry->return_reg = undef_src;
3128    }
3129
3130    this->function_signatures.push_tail(entry);
3131    return entry;
3132 }
3133
3134 void
3135 glsl_to_tgsi_visitor::visit_atomic_counter_intrinsic(ir_call *ir)
3136 {
3137    const char *callee = ir->callee->function_name();
3138    exec_node *param = ir->actual_parameters.get_head();
3139    ir_dereference *deref = static_cast<ir_dereference *>(param);
3140    ir_variable *location = deref->variable_referenced();
3141
3142    st_src_reg buffer(
3143          PROGRAM_BUFFER, location->data.binding, GLSL_TYPE_ATOMIC_UINT);
3144
3145    /* Calculate the surface offset */
3146    st_src_reg offset;
3147    unsigned array_size = 0, base = 0, index = 0;
3148
3149    get_deref_offsets(deref, &array_size, &base, &index, &offset);
3150
3151    if (offset.file != PROGRAM_UNDEFINED) {
3152       emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(offset),
3153                offset, st_src_reg_for_int(ATOMIC_COUNTER_SIZE));
3154       emit_asm(ir, TGSI_OPCODE_ADD, st_dst_reg(offset),
3155                offset, st_src_reg_for_int(location->data.offset + index * ATOMIC_COUNTER_SIZE));
3156    } else {
3157       offset = st_src_reg_for_int(location->data.offset + index * ATOMIC_COUNTER_SIZE);
3158    }
3159
3160    ir->return_deref->accept(this);
3161    st_dst_reg dst(this->result);
3162    dst.writemask = WRITEMASK_X;
3163
3164    glsl_to_tgsi_instruction *inst;
3165
3166    if (!strcmp("__intrinsic_atomic_read", callee)) {
3167       inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, offset);
3168    } else if (!strcmp("__intrinsic_atomic_increment", callee)) {
3169       inst = emit_asm(ir, TGSI_OPCODE_ATOMUADD, dst, offset,
3170                       st_src_reg_for_int(1));
3171    } else if (!strcmp("__intrinsic_atomic_predecrement", callee)) {
3172       inst = emit_asm(ir, TGSI_OPCODE_ATOMUADD, dst, offset,
3173                       st_src_reg_for_int(-1));
3174       emit_asm(ir, TGSI_OPCODE_ADD, dst, this->result, st_src_reg_for_int(-1));
3175    } else {
3176       param = param->get_next();
3177       ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3178       val->accept(this);
3179
3180       st_src_reg data = this->result, data2 = undef_src;
3181       unsigned opcode;
3182       if (!strcmp("__intrinsic_atomic_add", callee))
3183          opcode = TGSI_OPCODE_ATOMUADD;
3184       else if (!strcmp("__intrinsic_atomic_min", callee))
3185          opcode = TGSI_OPCODE_ATOMIMIN;
3186       else if (!strcmp("__intrinsic_atomic_max", callee))
3187          opcode = TGSI_OPCODE_ATOMIMAX;
3188       else if (!strcmp("__intrinsic_atomic_and", callee))
3189          opcode = TGSI_OPCODE_ATOMAND;
3190       else if (!strcmp("__intrinsic_atomic_or", callee))
3191          opcode = TGSI_OPCODE_ATOMOR;
3192       else if (!strcmp("__intrinsic_atomic_xor", callee))
3193          opcode = TGSI_OPCODE_ATOMXOR;
3194       else if (!strcmp("__intrinsic_atomic_exchange", callee))
3195          opcode = TGSI_OPCODE_ATOMXCHG;
3196       else if (!strcmp("__intrinsic_atomic_comp_swap", callee)) {
3197          opcode = TGSI_OPCODE_ATOMCAS;
3198          param = param->get_next();
3199          val = ((ir_instruction *)param)->as_rvalue();
3200          val->accept(this);
3201          data2 = this->result;
3202       } else if (!strcmp("__intrinsic_atomic_sub", callee)) {
3203          opcode = TGSI_OPCODE_ATOMUADD;
3204          st_src_reg res = get_temp(glsl_type::uvec4_type);
3205          st_dst_reg dstres = st_dst_reg(res);
3206          dstres.writemask = dst.writemask;
3207          emit_asm(ir, TGSI_OPCODE_INEG, dstres, data);
3208          data = res;
3209       } else {
3210          assert(!"Unexpected intrinsic");
3211          return;
3212       }
3213
3214       inst = emit_asm(ir, opcode, dst, offset, data, data2);
3215    }
3216
3217    inst->buffer = buffer;
3218 }
3219
3220 void
3221 glsl_to_tgsi_visitor::visit_ssbo_intrinsic(ir_call *ir)
3222 {
3223    const char *callee = ir->callee->function_name();
3224    exec_node *param = ir->actual_parameters.get_head();
3225
3226    ir_rvalue *block = ((ir_instruction *)param)->as_rvalue();
3227
3228    param = param->get_next();
3229    ir_rvalue *offset = ((ir_instruction *)param)->as_rvalue();
3230
3231    ir_constant *const_block = block->as_constant();
3232
3233    st_src_reg buffer(
3234          PROGRAM_BUFFER,
3235          ctx->Const.Program[shader->Stage].MaxAtomicBuffers +
3236          (const_block ? const_block->value.u[0] : 0),
3237          GLSL_TYPE_UINT);
3238
3239    if (!const_block) {
3240       block->accept(this);
3241       emit_arl(ir, sampler_reladdr, this->result);
3242       buffer.reladdr = ralloc(mem_ctx, st_src_reg);
3243       memcpy(buffer.reladdr, &sampler_reladdr, sizeof(sampler_reladdr));
3244    }
3245
3246    /* Calculate the surface offset */
3247    offset->accept(this);
3248    st_src_reg off = this->result;
3249
3250    st_dst_reg dst = undef_dst;
3251    if (ir->return_deref) {
3252       ir->return_deref->accept(this);
3253       dst = st_dst_reg(this->result);
3254       dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3255    }
3256
3257    glsl_to_tgsi_instruction *inst;
3258
3259    if (!strcmp("__intrinsic_load_ssbo", callee)) {
3260       inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, off);
3261       if (dst.type == GLSL_TYPE_BOOL)
3262          emit_asm(ir, TGSI_OPCODE_USNE, dst, st_src_reg(dst), st_src_reg_for_int(0));
3263    } else if (!strcmp("__intrinsic_store_ssbo", callee)) {
3264       param = param->get_next();
3265       ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3266       val->accept(this);
3267
3268       param = param->get_next();
3269       ir_constant *write_mask = ((ir_instruction *)param)->as_constant();
3270       assert(write_mask);
3271       dst.writemask = write_mask->value.u[0];
3272
3273       dst.type = this->result.type;
3274       inst = emit_asm(ir, TGSI_OPCODE_STORE, dst, off, this->result);
3275    } else {
3276       param = param->get_next();
3277       ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3278       val->accept(this);
3279
3280       st_src_reg data = this->result, data2 = undef_src;
3281       unsigned opcode;
3282       if (!strcmp("__intrinsic_atomic_add_ssbo", callee))
3283          opcode = TGSI_OPCODE_ATOMUADD;
3284       else if (!strcmp("__intrinsic_atomic_min_ssbo", callee))
3285          opcode = TGSI_OPCODE_ATOMIMIN;
3286       else if (!strcmp("__intrinsic_atomic_max_ssbo", callee))
3287          opcode = TGSI_OPCODE_ATOMIMAX;
3288       else if (!strcmp("__intrinsic_atomic_and_ssbo", callee))
3289          opcode = TGSI_OPCODE_ATOMAND;
3290       else if (!strcmp("__intrinsic_atomic_or_ssbo", callee))
3291          opcode = TGSI_OPCODE_ATOMOR;
3292       else if (!strcmp("__intrinsic_atomic_xor_ssbo", callee))
3293          opcode = TGSI_OPCODE_ATOMXOR;
3294       else if (!strcmp("__intrinsic_atomic_exchange_ssbo", callee))
3295          opcode = TGSI_OPCODE_ATOMXCHG;
3296       else if (!strcmp("__intrinsic_atomic_comp_swap_ssbo", callee)) {
3297          opcode = TGSI_OPCODE_ATOMCAS;
3298          param = param->get_next();
3299          val = ((ir_instruction *)param)->as_rvalue();
3300          val->accept(this);
3301          data2 = this->result;
3302       } else {
3303          assert(!"Unexpected intrinsic");
3304          return;
3305       }
3306
3307       inst = emit_asm(ir, opcode, dst, off, data, data2);
3308    }
3309
3310    param = param->get_next();
3311    ir_constant *access = NULL;
3312    if (!param->is_tail_sentinel()) {
3313       access = ((ir_instruction *)param)->as_constant();
3314       assert(access);
3315    }
3316
3317    /* The emit_asm() might have actually split the op into pieces, e.g. for
3318     * double stores. We have to go back and fix up all the generated ops.
3319     */
3320    unsigned op = inst->op;
3321    do {
3322       inst->buffer = buffer;
3323       if (access)
3324          inst->buffer_access = access->value.u[0];
3325       inst = (glsl_to_tgsi_instruction *)inst->get_prev();
3326       if (inst->op == TGSI_OPCODE_UADD)
3327          inst = (glsl_to_tgsi_instruction *)inst->get_prev();
3328    } while (inst && inst->buffer.file == PROGRAM_UNDEFINED && inst->op == op);
3329 }
3330
3331 void
3332 glsl_to_tgsi_visitor::visit_membar_intrinsic(ir_call *ir)
3333 {
3334    const char *callee = ir->callee->function_name();
3335
3336    if (!strcmp("__intrinsic_memory_barrier", callee))
3337       emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3338                st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER |
3339                                   TGSI_MEMBAR_ATOMIC_BUFFER |
3340                                   TGSI_MEMBAR_SHADER_IMAGE |
3341                                   TGSI_MEMBAR_SHARED));
3342    else if (!strcmp("__intrinsic_memory_barrier_atomic_counter", callee))
3343       emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3344                st_src_reg_for_int(TGSI_MEMBAR_ATOMIC_BUFFER));
3345    else if (!strcmp("__intrinsic_memory_barrier_buffer", callee))
3346       emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3347                st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER));
3348    else if (!strcmp("__intrinsic_memory_barrier_image", callee))
3349       emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3350                st_src_reg_for_int(TGSI_MEMBAR_SHADER_IMAGE));
3351    else if (!strcmp("__intrinsic_memory_barrier_shared", callee))
3352       emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3353                st_src_reg_for_int(TGSI_MEMBAR_SHARED));
3354    else if (!strcmp("__intrinsic_group_memory_barrier", callee))
3355       emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3356                st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER |
3357                                   TGSI_MEMBAR_ATOMIC_BUFFER |
3358                                   TGSI_MEMBAR_SHADER_IMAGE |
3359                                   TGSI_MEMBAR_SHARED |
3360                                   TGSI_MEMBAR_THREAD_GROUP));
3361    else
3362       assert(!"Unexpected memory barrier intrinsic");
3363 }
3364
3365 void
3366 glsl_to_tgsi_visitor::visit_shared_intrinsic(ir_call *ir)
3367 {
3368    const char *callee = ir->callee->function_name();
3369    exec_node *param = ir->actual_parameters.get_head();
3370
3371    ir_rvalue *offset = ((ir_instruction *)param)->as_rvalue();
3372
3373    st_src_reg buffer(PROGRAM_MEMORY, 0, GLSL_TYPE_UINT);
3374
3375    /* Calculate the surface offset */
3376    offset->accept(this);
3377    st_src_reg off = this->result;
3378
3379    st_dst_reg dst = undef_dst;
3380    if (ir->return_deref) {
3381       ir->return_deref->accept(this);
3382       dst = st_dst_reg(this->result);
3383       dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3384    }
3385
3386    glsl_to_tgsi_instruction *inst;
3387
3388    if (!strcmp("__intrinsic_load_shared", callee)) {
3389       inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, off);
3390       inst->buffer = buffer;
3391    } else if (!strcmp("__intrinsic_store_shared", callee)) {
3392       param = param->get_next();
3393       ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3394       val->accept(this);
3395
3396       param = param->get_next();
3397       ir_constant *write_mask = ((ir_instruction *)param)->as_constant();
3398       assert(write_mask);
3399       dst.writemask = write_mask->value.u[0];
3400
3401       dst.type = this->result.type;
3402       inst = emit_asm(ir, TGSI_OPCODE_STORE, dst, off, this->result);
3403       inst->buffer = buffer;
3404    } else {
3405       param = param->get_next();
3406       ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3407       val->accept(this);
3408
3409       st_src_reg data = this->result, data2 = undef_src;
3410       unsigned opcode;
3411       if (!strcmp("__intrinsic_atomic_add_shared", callee))
3412          opcode = TGSI_OPCODE_ATOMUADD;
3413       else if (!strcmp("__intrinsic_atomic_min_shared", callee))
3414          opcode = TGSI_OPCODE_ATOMIMIN;
3415       else if (!strcmp("__intrinsic_atomic_max_shared", callee))
3416          opcode = TGSI_OPCODE_ATOMIMAX;
3417       else if (!strcmp("__intrinsic_atomic_and_shared", callee))
3418          opcode = TGSI_OPCODE_ATOMAND;
3419       else if (!strcmp("__intrinsic_atomic_or_shared", callee))
3420          opcode = TGSI_OPCODE_ATOMOR;
3421       else if (!strcmp("__intrinsic_atomic_xor_shared", callee))
3422          opcode = TGSI_OPCODE_ATOMXOR;
3423       else if (!strcmp("__intrinsic_atomic_exchange_shared", callee))
3424          opcode = TGSI_OPCODE_ATOMXCHG;
3425       else if (!strcmp("__intrinsic_atomic_comp_swap_shared", callee)) {
3426          opcode = TGSI_OPCODE_ATOMCAS;
3427          param = param->get_next();
3428          val = ((ir_instruction *)param)->as_rvalue();
3429          val->accept(this);
3430          data2 = this->result;
3431       } else {
3432          assert(!"Unexpected intrinsic");
3433          return;
3434       }
3435
3436       inst = emit_asm(ir, opcode, dst, off, data, data2);
3437       inst->buffer = buffer;
3438    }
3439 }
3440
3441 void
3442 glsl_to_tgsi_visitor::visit_image_intrinsic(ir_call *ir)
3443 {
3444    const char *callee = ir->callee->function_name();
3445    exec_node *param = ir->actual_parameters.get_head();
3446
3447    ir_dereference *img = (ir_dereference *)param;
3448    const ir_variable *imgvar = img->variable_referenced();
3449    const glsl_type *type = imgvar->type->without_array();
3450    unsigned sampler_array_size = 1, sampler_base = 0;
3451
3452    st_src_reg reladdr;
3453    st_src_reg image(PROGRAM_IMAGE, 0, GLSL_TYPE_UINT);
3454
3455    get_deref_offsets(img, &sampler_array_size, &sampler_base,
3456                      (unsigned int *)&image.index, &reladdr);
3457    if (reladdr.file != PROGRAM_UNDEFINED) {
3458       emit_arl(ir, sampler_reladdr, reladdr);
3459       image.reladdr = ralloc(mem_ctx, st_src_reg);
3460       memcpy(image.reladdr, &sampler_reladdr, sizeof(reladdr));
3461    }
3462
3463    st_dst_reg dst = undef_dst;
3464    if (ir->return_deref) {
3465       ir->return_deref->accept(this);
3466       dst = st_dst_reg(this->result);
3467       dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3468    }
3469
3470    glsl_to_tgsi_instruction *inst;
3471
3472    if (!strcmp("__intrinsic_image_size", callee)) {
3473       dst.writemask = WRITEMASK_XYZ;
3474       inst = emit_asm(ir, TGSI_OPCODE_RESQ, dst);
3475    } else if (!strcmp("__intrinsic_image_samples", callee)) {
3476       st_src_reg res = get_temp(glsl_type::ivec4_type);
3477       st_dst_reg dstres = st_dst_reg(res);
3478       dstres.writemask = WRITEMASK_W;
3479       inst = emit_asm(ir, TGSI_OPCODE_RESQ, dstres);
3480       res.swizzle = SWIZZLE_WWWW;
3481       emit_asm(ir, TGSI_OPCODE_MOV, dst, res);
3482    } else {
3483       st_src_reg arg1 = undef_src, arg2 = undef_src;
3484       st_src_reg coord;
3485       st_dst_reg coord_dst;
3486       coord = get_temp(glsl_type::ivec4_type);
3487       coord_dst = st_dst_reg(coord);
3488       coord_dst.writemask = (1 << type->coordinate_components()) - 1;
3489       param = param->get_next();
3490       ((ir_dereference *)param)->accept(this);
3491       emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
3492       coord.swizzle = SWIZZLE_XXXX;
3493       switch (type->coordinate_components()) {
3494       case 4: assert(!"unexpected coord count");
3495       /* fallthrough */
3496       case 3: coord.swizzle |= SWIZZLE_Z << 6;
3497       /* fallthrough */
3498       case 2: coord.swizzle |= SWIZZLE_Y << 3;
3499       }
3500
3501       if (type->sampler_dimensionality == GLSL_SAMPLER_DIM_MS) {
3502          param = param->get_next();
3503          ((ir_dereference *)param)->accept(this);
3504          st_src_reg sample = this->result;
3505          sample.swizzle = SWIZZLE_XXXX;
3506          coord_dst.writemask = WRITEMASK_W;
3507          emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, sample);
3508          coord.swizzle |= SWIZZLE_W << 9;
3509       }
3510
3511       param = param->get_next();
3512       if (!param->is_tail_sentinel()) {
3513          ((ir_dereference *)param)->accept(this);
3514          arg1 = this->result;
3515          param = param->get_next();
3516       }
3517
3518       if (!param->is_tail_sentinel()) {
3519          ((ir_dereference *)param)->accept(this);
3520          arg2 = this->result;
3521          param = param->get_next();
3522       }
3523
3524       assert(param->is_tail_sentinel());
3525
3526       unsigned opcode;
3527       if (!strcmp("__intrinsic_image_load", callee))
3528          opcode = TGSI_OPCODE_LOAD;
3529       else if (!strcmp("__intrinsic_image_store", callee))
3530          opcode = TGSI_OPCODE_STORE;
3531       else if (!strcmp("__intrinsic_image_atomic_add", callee))
3532          opcode = TGSI_OPCODE_ATOMUADD;
3533       else if (!strcmp("__intrinsic_image_atomic_min", callee))
3534          opcode = TGSI_OPCODE_ATOMIMIN;
3535       else if (!strcmp("__intrinsic_image_atomic_max", callee))
3536          opcode = TGSI_OPCODE_ATOMIMAX;
3537       else if (!strcmp("__intrinsic_image_atomic_and", callee))
3538          opcode = TGSI_OPCODE_ATOMAND;
3539       else if (!strcmp("__intrinsic_image_atomic_or", callee))
3540          opcode = TGSI_OPCODE_ATOMOR;
3541       else if (!strcmp("__intrinsic_image_atomic_xor", callee))
3542          opcode = TGSI_OPCODE_ATOMXOR;
3543       else if (!strcmp("__intrinsic_image_atomic_exchange", callee))
3544          opcode = TGSI_OPCODE_ATOMXCHG;
3545       else if (!strcmp("__intrinsic_image_atomic_comp_swap", callee))
3546          opcode = TGSI_OPCODE_ATOMCAS;
3547       else {
3548          assert(!"Unexpected intrinsic");
3549          return;
3550       }
3551
3552       inst = emit_asm(ir, opcode, dst, coord, arg1, arg2);
3553       if (opcode == TGSI_OPCODE_STORE)
3554          inst->dst[0].writemask = WRITEMASK_XYZW;
3555    }
3556
3557    inst->buffer = image;
3558    inst->sampler_array_size = sampler_array_size;
3559    inst->sampler_base = sampler_base;
3560
3561    switch (type->sampler_dimensionality) {
3562    case GLSL_SAMPLER_DIM_1D:
3563       inst->tex_target = (type->sampler_array)
3564          ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
3565       break;
3566    case GLSL_SAMPLER_DIM_2D:
3567       inst->tex_target = (type->sampler_array)
3568          ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
3569       break;
3570    case GLSL_SAMPLER_DIM_3D:
3571       inst->tex_target = TEXTURE_3D_INDEX;
3572       break;
3573    case GLSL_SAMPLER_DIM_CUBE:
3574       inst->tex_target = (type->sampler_array)
3575          ? TEXTURE_CUBE_ARRAY_INDEX : TEXTURE_CUBE_INDEX;
3576       break;
3577    case GLSL_SAMPLER_DIM_RECT:
3578       inst->tex_target = TEXTURE_RECT_INDEX;
3579       break;
3580    case GLSL_SAMPLER_DIM_BUF:
3581       inst->tex_target = TEXTURE_BUFFER_INDEX;
3582       break;
3583    case GLSL_SAMPLER_DIM_EXTERNAL:
3584       inst->tex_target = TEXTURE_EXTERNAL_INDEX;
3585       break;
3586    case GLSL_SAMPLER_DIM_MS:
3587       inst->tex_target = (type->sampler_array)
3588          ? TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX : TEXTURE_2D_MULTISAMPLE_INDEX;
3589       break;
3590    default:
3591       assert(!"Should not get here.");
3592    }
3593
3594    inst->image_format = st_mesa_format_to_pipe_format(st_context(ctx),
3595          _mesa_get_shader_image_format(imgvar->data.image_format));
3596
3597    if (imgvar->data.image_coherent)
3598       inst->buffer_access |= TGSI_MEMORY_COHERENT;
3599    if (imgvar->data.image_restrict)
3600       inst->buffer_access |= TGSI_MEMORY_RESTRICT;
3601    if (imgvar->data.image_volatile)
3602       inst->buffer_access |= TGSI_MEMORY_VOLATILE;
3603 }
3604
3605 void
3606 glsl_to_tgsi_visitor::visit(ir_call *ir)
3607 {
3608    glsl_to_tgsi_instruction *call_inst;
3609    ir_function_signature *sig = ir->callee;
3610    const char *callee = sig->function_name();
3611    function_entry *entry;
3612    int i;
3613
3614    /* Filter out intrinsics */
3615    if (!strcmp("__intrinsic_atomic_read", callee) ||
3616        !strcmp("__intrinsic_atomic_increment", callee) ||
3617        !strcmp("__intrinsic_atomic_predecrement", callee) ||
3618        !strcmp("__intrinsic_atomic_add", callee) ||
3619        !strcmp("__intrinsic_atomic_sub", callee) ||
3620        !strcmp("__intrinsic_atomic_min", callee) ||
3621        !strcmp("__intrinsic_atomic_max", callee) ||
3622        !strcmp("__intrinsic_atomic_and", callee) ||
3623        !strcmp("__intrinsic_atomic_or", callee) ||
3624        !strcmp("__intrinsic_atomic_xor", callee) ||
3625        !strcmp("__intrinsic_atomic_exchange", callee) ||
3626        !strcmp("__intrinsic_atomic_comp_swap", callee)) {
3627       visit_atomic_counter_intrinsic(ir);
3628       return;
3629    }
3630
3631    if (!strcmp("__intrinsic_load_ssbo", callee) ||
3632        !strcmp("__intrinsic_store_ssbo", callee) ||
3633        !strcmp("__intrinsic_atomic_add_ssbo", callee) ||
3634        !strcmp("__intrinsic_atomic_min_ssbo", callee) ||
3635        !strcmp("__intrinsic_atomic_max_ssbo", callee) ||
3636        !strcmp("__intrinsic_atomic_and_ssbo", callee) ||
3637        !strcmp("__intrinsic_atomic_or_ssbo", callee) ||
3638        !strcmp("__intrinsic_atomic_xor_ssbo", callee) ||
3639        !strcmp("__intrinsic_atomic_exchange_ssbo", callee) ||
3640        !strcmp("__intrinsic_atomic_comp_swap_ssbo", callee)) {
3641       visit_ssbo_intrinsic(ir);
3642       return;
3643    }
3644
3645    if (!strcmp("__intrinsic_memory_barrier", callee) ||
3646        !strcmp("__intrinsic_memory_barrier_atomic_counter", callee) ||
3647        !strcmp("__intrinsic_memory_barrier_buffer", callee) ||
3648        !strcmp("__intrinsic_memory_barrier_image", callee) ||
3649        !strcmp("__intrinsic_memory_barrier_shared", callee) ||
3650        !strcmp("__intrinsic_group_memory_barrier", callee)) {
3651       visit_membar_intrinsic(ir);
3652       return;
3653    }
3654
3655    if (!strcmp("__intrinsic_load_shared", callee) ||
3656        !strcmp("__intrinsic_store_shared", callee) ||
3657        !strcmp("__intrinsic_atomic_add_shared", callee) ||
3658        !strcmp("__intrinsic_atomic_min_shared", callee) ||
3659        !strcmp("__intrinsic_atomic_max_shared", callee) ||
3660        !strcmp("__intrinsic_atomic_and_shared", callee) ||
3661        !strcmp("__intrinsic_atomic_or_shared", callee) ||
3662        !strcmp("__intrinsic_atomic_xor_shared", callee) ||
3663        !strcmp("__intrinsic_atomic_exchange_shared", callee) ||
3664        !strcmp("__intrinsic_atomic_comp_swap_shared", callee)) {
3665       visit_shared_intrinsic(ir);
3666       return;
3667    }
3668
3669    if (!strcmp("__intrinsic_image_load", callee) ||
3670        !strcmp("__intrinsic_image_store", callee) ||
3671        !strcmp("__intrinsic_image_atomic_add", callee) ||
3672        !strcmp("__intrinsic_image_atomic_min", callee) ||
3673        !strcmp("__intrinsic_image_atomic_max", callee) ||
3674        !strcmp("__intrinsic_image_atomic_and", callee) ||
3675        !strcmp("__intrinsic_image_atomic_or", callee) ||
3676        !strcmp("__intrinsic_image_atomic_xor", callee) ||
3677        !strcmp("__intrinsic_image_atomic_exchange", callee) ||
3678        !strcmp("__intrinsic_image_atomic_comp_swap", callee) ||
3679        !strcmp("__intrinsic_image_size", callee) ||
3680        !strcmp("__intrinsic_image_samples", callee)) {
3681       visit_image_intrinsic(ir);
3682       return;
3683    }
3684
3685    entry = get_function_signature(sig);
3686    /* Process in parameters. */
3687    foreach_two_lists(formal_node, &sig->parameters,
3688                      actual_node, &ir->actual_parameters) {
3689       ir_rvalue *param_rval = (ir_rvalue *) actual_node;
3690       ir_variable *param = (ir_variable *) formal_node;
3691
3692       if (param->data.mode == ir_var_function_in ||
3693           param->data.mode == ir_var_function_inout) {
3694          variable_storage *storage = find_variable_storage(param);
3695          assert(storage);
3696
3697          param_rval->accept(this);
3698          st_src_reg r = this->result;
3699
3700          st_dst_reg l;
3701          l.file = storage->file;
3702          l.index = storage->index;
3703          l.reladdr = NULL;
3704          l.writemask = WRITEMASK_XYZW;
3705
3706          for (i = 0; i < type_size(param->type); i++) {
3707             emit_asm(ir, TGSI_OPCODE_MOV, l, r);
3708             l.index++;
3709             r.index++;
3710          }
3711       }
3712    }
3713
3714    /* Emit call instruction */
3715    call_inst = emit_asm(ir, TGSI_OPCODE_CAL);
3716    call_inst->function = entry;
3717
3718    /* Process out parameters. */
3719    foreach_two_lists(formal_node, &sig->parameters,
3720                      actual_node, &ir->actual_parameters) {
3721       ir_rvalue *param_rval = (ir_rvalue *) actual_node;
3722       ir_variable *param = (ir_variable *) formal_node;
3723
3724       if (param->data.mode == ir_var_function_out ||
3725           param->data.mode == ir_var_function_inout) {
3726          variable_storage *storage = find_variable_storage(param);
3727          assert(storage);
3728
3729          st_src_reg r;
3730          r.file = storage->file;
3731          r.index = storage->index;
3732          r.reladdr = NULL;
3733          r.swizzle = SWIZZLE_NOOP;
3734          r.negate = 0;
3735
3736          param_rval->accept(this);
3737          st_dst_reg l = st_dst_reg(this->result);
3738
3739          for (i = 0; i < type_size(param->type); i++) {
3740             emit_asm(ir, TGSI_OPCODE_MOV, l, r);
3741             l.index++;
3742             r.index++;
3743          }
3744       }
3745    }
3746
3747    /* Process return value. */
3748    this->result = entry->return_reg;
3749 }
3750
3751 void
3752 glsl_to_tgsi_visitor::calc_deref_offsets(ir_dereference *head,
3753                                          ir_dereference *tail,
3754                                          unsigned *array_elements,
3755                                          unsigned *base,
3756                                          unsigned *index,
3757                                          st_src_reg *indirect,
3758                                          unsigned *location)
3759 {
3760    switch (tail->ir_type) {
3761    case ir_type_dereference_record: {
3762       ir_dereference_record *deref_record = tail->as_dereference_record();
3763       const glsl_type *struct_type = deref_record->record->type;
3764       int field_index = deref_record->record->type->field_index(deref_record->field);
3765
3766       calc_deref_offsets(head, deref_record->record->as_dereference(), array_elements, base, index, indirect, location);
3767
3768       assert(field_index >= 0);
3769       *location += struct_type->record_location_offset(field_index);
3770       break;
3771    }
3772
3773    case ir_type_dereference_array: {
3774       ir_dereference_array *deref_arr = tail->as_dereference_array();
3775       ir_constant *array_index = deref_arr->array_index->constant_expression_value();
3776
3777       if (!array_index) {
3778          st_src_reg temp_reg;
3779          st_dst_reg temp_dst;
3780
3781          temp_reg = get_temp(glsl_type::uint_type);
3782          temp_dst = st_dst_reg(temp_reg);
3783          temp_dst.writemask = 1;
3784
3785          deref_arr->array_index->accept(this);
3786          if (*array_elements != 1)
3787             emit_asm(NULL, TGSI_OPCODE_MUL, temp_dst, this->result, st_src_reg_for_int(*array_elements));
3788          else
3789             emit_asm(NULL, TGSI_OPCODE_MOV, temp_dst, this->result);
3790
3791          if (indirect->file == PROGRAM_UNDEFINED)
3792             *indirect = temp_reg;
3793          else {
3794             temp_dst = st_dst_reg(*indirect);
3795             temp_dst.writemask = 1;
3796             emit_asm(NULL, TGSI_OPCODE_ADD, temp_dst, *indirect, temp_reg);
3797          }
3798       } else
3799          *index += array_index->value.u[0] * *array_elements;
3800
3801       *array_elements *= deref_arr->array->type->length;
3802
3803       calc_deref_offsets(head, deref_arr->array->as_dereference(), array_elements, base, index, indirect, location);
3804       break;
3805    }
3806    default:
3807       break;
3808    }
3809 }
3810
3811 void
3812 glsl_to_tgsi_visitor::get_deref_offsets(ir_dereference *ir,
3813                                         unsigned *array_size,
3814                                         unsigned *base,
3815                                         unsigned *index,
3816                                         st_src_reg *reladdr)
3817 {
3818    GLuint shader = _mesa_program_enum_to_shader_stage(this->prog->Target);
3819    unsigned location = 0;
3820    ir_variable *var = ir->variable_referenced();
3821
3822    memset(reladdr, 0, sizeof(*reladdr));
3823    reladdr->file = PROGRAM_UNDEFINED;
3824
3825    *base = 0;
3826    *array_size = 1;
3827
3828    assert(var);
3829    location = var->data.location;
3830    calc_deref_offsets(ir, ir, array_size, base, index, reladdr, &location);
3831
3832    /*
3833     * If we end up with no indirect then adjust the base to the index,
3834     * and set the array size to 1.
3835     */
3836    if (reladdr->file == PROGRAM_UNDEFINED) {
3837       *base = *index;
3838       *array_size = 1;
3839    }
3840
3841    if (location != 0xffffffff) {
3842       *base += this->shader_program->UniformStorage[location].opaque[shader].index;
3843       *index += this->shader_program->UniformStorage[location].opaque[shader].index;
3844    }
3845 }
3846
3847 void
3848 glsl_to_tgsi_visitor::visit(ir_texture *ir)
3849 {
3850    st_src_reg result_src, coord, cube_sc, lod_info, projector, dx, dy;
3851    st_src_reg offset[MAX_GLSL_TEXTURE_OFFSET], sample_index, component;
3852    st_src_reg levels_src, reladdr;
3853    st_dst_reg result_dst, coord_dst, cube_sc_dst;
3854    glsl_to_tgsi_instruction *inst = NULL;
3855    unsigned opcode = TGSI_OPCODE_NOP;
3856    const glsl_type *sampler_type = ir->sampler->type;
3857    unsigned sampler_array_size = 1, sampler_index = 0, sampler_base = 0;
3858    bool is_cube_array = false;
3859    unsigned i;
3860
3861    /* if we are a cube array sampler */
3862    if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE &&
3863         sampler_type->sampler_array)) {
3864       is_cube_array = true;
3865    }
3866
3867    if (ir->coordinate) {
3868       ir->coordinate->accept(this);
3869
3870       /* Put our coords in a temp.  We'll need to modify them for shadow,
3871        * projection, or LOD, so the only case we'd use it as is is if
3872        * we're doing plain old texturing.  The optimization passes on
3873        * glsl_to_tgsi_visitor should handle cleaning up our mess in that case.
3874        */
3875       coord = get_temp(glsl_type::vec4_type);
3876       coord_dst = st_dst_reg(coord);
3877       coord_dst.writemask = (1 << ir->coordinate->type->vector_elements) - 1;
3878       emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
3879    }
3880
3881    if (ir->projector) {
3882       ir->projector->accept(this);
3883       projector = this->result;
3884    }
3885
3886    /* Storage for our result.  Ideally for an assignment we'd be using
3887     * the actual storage for the result here, instead.
3888     */
3889    result_src = get_temp(ir->type);
3890    result_dst = st_dst_reg(result_src);
3891
3892    switch (ir->op) {
3893    case ir_tex:
3894       opcode = (is_cube_array && ir->shadow_comparitor) ? TGSI_OPCODE_TEX2 : TGSI_OPCODE_TEX;
3895       if (ir->offset) {
3896          ir->offset->accept(this);
3897          offset[0] = this->result;
3898       }
3899       break;
3900    case ir_txb:
3901       if (is_cube_array ||
3902           sampler_type == glsl_type::samplerCubeShadow_type) {
3903          opcode = TGSI_OPCODE_TXB2;
3904       }
3905       else {
3906          opcode = TGSI_OPCODE_TXB;
3907       }
3908       ir->lod_info.bias->accept(this);
3909       lod_info = this->result;
3910       if (ir->offset) {
3911          ir->offset->accept(this);
3912          offset[0] = this->result;
3913       }
3914       break;
3915    case ir_txl:
3916       opcode = is_cube_array ? TGSI_OPCODE_TXL2 : TGSI_OPCODE_TXL;
3917       ir->lod_info.lod->accept(this);
3918       lod_info = this->result;
3919       if (ir->offset) {
3920          ir->offset->accept(this);
3921          offset[0] = this->result;
3922       }
3923       break;
3924    case ir_txd:
3925       opcode = TGSI_OPCODE_TXD;
3926       ir->lod_info.grad.dPdx->accept(this);
3927       dx = this->result;
3928       ir->lod_info.grad.dPdy->accept(this);
3929       dy = this->result;
3930       if (ir->offset) {
3931          ir->offset->accept(this);
3932          offset[0] = this->result;
3933       }
3934       break;
3935    case ir_txs:
3936       opcode = TGSI_OPCODE_TXQ;
3937       ir->lod_info.lod->accept(this);
3938       lod_info = this->result;
3939       break;
3940    case ir_query_levels:
3941       opcode = TGSI_OPCODE_TXQ;
3942       lod_info = undef_src;
3943       levels_src = get_temp(ir->type);
3944       break;
3945    case ir_txf:
3946       opcode = TGSI_OPCODE_TXF;
3947       ir->lod_info.lod->accept(this);
3948       lod_info = this->result;
3949       if (ir->offset) {
3950          ir->offset->accept(this);
3951          offset[0] = this->result;
3952       }
3953       break;
3954    case ir_txf_ms:
3955       opcode = TGSI_OPCODE_TXF;
3956       ir->lod_info.sample_index->accept(this);
3957       sample_index = this->result;
3958       break;
3959    case ir_tg4:
3960       opcode = TGSI_OPCODE_TG4;
3961       ir->lod_info.component->accept(this);
3962       component = this->result;
3963       if (ir->offset) {
3964          ir->offset->accept(this);
3965          if (ir->offset->type->base_type == GLSL_TYPE_ARRAY) {
3966             const glsl_type *elt_type = ir->offset->type->fields.array;
3967             for (i = 0; i < ir->offset->type->length; i++) {
3968                offset[i] = this->result;
3969                offset[i].index += i * type_size(elt_type);
3970                offset[i].type = elt_type->base_type;
3971                offset[i].swizzle = swizzle_for_size(elt_type->vector_elements);
3972             }
3973          } else {
3974             offset[0] = this->result;
3975          }
3976       }
3977       break;
3978    case ir_lod:
3979       opcode = TGSI_OPCODE_LODQ;
3980       break;
3981    case ir_texture_samples:
3982       opcode = TGSI_OPCODE_TXQS;
3983       break;
3984    case ir_samples_identical:
3985       unreachable("Unexpected ir_samples_identical opcode");
3986    }
3987
3988    if (ir->projector) {
3989       if (opcode == TGSI_OPCODE_TEX) {
3990          /* Slot the projector in as the last component of the coord. */
3991          coord_dst.writemask = WRITEMASK_W;
3992          emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, projector);
3993          coord_dst.writemask = WRITEMASK_XYZW;
3994          opcode = TGSI_OPCODE_TXP;
3995       } else {
3996          st_src_reg coord_w = coord;
3997          coord_w.swizzle = SWIZZLE_WWWW;
3998
3999          /* For the other TEX opcodes there's no projective version
4000           * since the last slot is taken up by LOD info.  Do the
4001           * projective divide now.
4002           */
4003          coord_dst.writemask = WRITEMASK_W;
4004          emit_asm(ir, TGSI_OPCODE_RCP, coord_dst, projector);
4005
4006          /* In the case where we have to project the coordinates "by hand,"
4007           * the shadow comparator value must also be projected.
4008           */
4009          st_src_reg tmp_src = coord;
4010          if (ir->shadow_comparitor) {
4011             /* Slot the shadow value in as the second to last component of the
4012              * coord.
4013              */
4014             ir->shadow_comparitor->accept(this);
4015
4016             tmp_src = get_temp(glsl_type::vec4_type);
4017             st_dst_reg tmp_dst = st_dst_reg(tmp_src);
4018
4019             /* Projective division not allowed for array samplers. */
4020             assert(!sampler_type->sampler_array);
4021
4022             tmp_dst.writemask = WRITEMASK_Z;
4023             emit_asm(ir, TGSI_OPCODE_MOV, tmp_dst, this->result);
4024
4025             tmp_dst.writemask = WRITEMASK_XY;
4026             emit_asm(ir, TGSI_OPCODE_MOV, tmp_dst, coord);
4027          }
4028
4029          coord_dst.writemask = WRITEMASK_XYZ;
4030          emit_asm(ir, TGSI_OPCODE_MUL, coord_dst, tmp_src, coord_w);
4031
4032          coord_dst.writemask = WRITEMASK_XYZW;
4033          coord.swizzle = SWIZZLE_XYZW;
4034       }
4035    }
4036
4037    /* If projection is done and the opcode is not TGSI_OPCODE_TXP, then the shadow
4038     * comparator was put in the correct place (and projected) by the code,
4039     * above, that handles by-hand projection.
4040     */
4041    if (ir->shadow_comparitor && (!ir->projector || opcode == TGSI_OPCODE_TXP)) {
4042       /* Slot the shadow value in as the second to last component of the
4043        * coord.
4044        */
4045       ir->shadow_comparitor->accept(this);
4046
4047       if (is_cube_array) {
4048          cube_sc = get_temp(glsl_type::float_type);
4049          cube_sc_dst = st_dst_reg(cube_sc);
4050          cube_sc_dst.writemask = WRITEMASK_X;
4051          emit_asm(ir, TGSI_OPCODE_MOV, cube_sc_dst, this->result);
4052          cube_sc_dst.writemask = WRITEMASK_X;
4053       }
4054       else {
4055          if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_2D &&
4056               sampler_type->sampler_array) ||
4057              sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE) {
4058             coord_dst.writemask = WRITEMASK_W;
4059          } else {
4060             coord_dst.writemask = WRITEMASK_Z;
4061          }
4062          emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
4063          coord_dst.writemask = WRITEMASK_XYZW;
4064       }
4065    }
4066
4067    if (ir->op == ir_txf_ms) {
4068       coord_dst.writemask = WRITEMASK_W;
4069       emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, sample_index);
4070       coord_dst.writemask = WRITEMASK_XYZW;
4071    } else if (opcode == TGSI_OPCODE_TXL || opcode == TGSI_OPCODE_TXB ||
4072        opcode == TGSI_OPCODE_TXF) {
4073       /* TGSI stores LOD or LOD bias in the last channel of the coords. */
4074       coord_dst.writemask = WRITEMASK_W;
4075       emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, lod_info);
4076       coord_dst.writemask = WRITEMASK_XYZW;
4077    }
4078
4079    get_deref_offsets(ir->sampler, &sampler_array_size, &sampler_base,
4080                      &sampler_index, &reladdr);
4081    if (reladdr.file != PROGRAM_UNDEFINED)
4082       emit_arl(ir, sampler_reladdr, reladdr);
4083
4084    if (opcode == TGSI_OPCODE_TXD)
4085       inst = emit_asm(ir, opcode, result_dst, coord, dx, dy);
4086    else if (opcode == TGSI_OPCODE_TXQ) {
4087       if (ir->op == ir_query_levels) {
4088          /* the level is stored in W */
4089          inst = emit_asm(ir, opcode, st_dst_reg(levels_src), lod_info);
4090          result_dst.writemask = WRITEMASK_X;
4091          levels_src.swizzle = SWIZZLE_WWWW;
4092          emit_asm(ir, TGSI_OPCODE_MOV, result_dst, levels_src);
4093       } else
4094          inst = emit_asm(ir, opcode, result_dst, lod_info);
4095    } else if (opcode == TGSI_OPCODE_TXQS) {
4096       inst = emit_asm(ir, opcode, result_dst);
4097    } else if (opcode == TGSI_OPCODE_TXF) {
4098       inst = emit_asm(ir, opcode, result_dst, coord);
4099    } else if (opcode == TGSI_OPCODE_TXL2 || opcode == TGSI_OPCODE_TXB2) {
4100       inst = emit_asm(ir, opcode, result_dst, coord, lod_info);
4101    } else if (opcode == TGSI_OPCODE_TEX2) {
4102       inst = emit_asm(ir, opcode, result_dst, coord, cube_sc);
4103    } else if (opcode == TGSI_OPCODE_TG4) {
4104       if (is_cube_array && ir->shadow_comparitor) {
4105          inst = emit_asm(ir, opcode, result_dst, coord, cube_sc);
4106       } else {
4107          inst = emit_asm(ir, opcode, result_dst, coord, component);
4108       }
4109    } else
4110       inst = emit_asm(ir, opcode, result_dst, coord);
4111
4112    if (ir->shadow_comparitor)
4113       inst->tex_shadow = GL_TRUE;
4114
4115    inst->sampler.index = sampler_index;
4116    inst->sampler_array_size = sampler_array_size;
4117    inst->sampler_base = sampler_base;
4118
4119    if (reladdr.file != PROGRAM_UNDEFINED) {
4120       inst->sampler.reladdr = ralloc(mem_ctx, st_src_reg);
4121       memcpy(inst->sampler.reladdr, &reladdr, sizeof(reladdr));
4122    }
4123
4124    if (ir->offset) {
4125       for (i = 0; i < MAX_GLSL_TEXTURE_OFFSET && offset[i].file != PROGRAM_UNDEFINED; i++)
4126          inst->tex_offsets[i] = offset[i];
4127       inst->tex_offset_num_offset = i;
4128    }
4129
4130    switch (sampler_type->sampler_dimensionality) {
4131    case GLSL_SAMPLER_DIM_1D:
4132       inst->tex_target = (sampler_type->sampler_array)
4133          ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
4134       break;
4135    case GLSL_SAMPLER_DIM_2D:
4136       inst->tex_target = (sampler_type->sampler_array)
4137          ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
4138       break;
4139    case GLSL_SAMPLER_DIM_3D:
4140       inst->tex_target = TEXTURE_3D_INDEX;
4141       break;
4142    case GLSL_SAMPLER_DIM_CUBE:
4143       inst->tex_target = (sampler_type->sampler_array)
4144          ? TEXTURE_CUBE_ARRAY_INDEX : TEXTURE_CUBE_INDEX;
4145       break;
4146    case GLSL_SAMPLER_DIM_RECT:
4147       inst->tex_target = TEXTURE_RECT_INDEX;
4148       break;
4149    case GLSL_SAMPLER_DIM_BUF:
4150       inst->tex_target = TEXTURE_BUFFER_INDEX;
4151       break;
4152    case GLSL_SAMPLER_DIM_EXTERNAL:
4153       inst->tex_target = TEXTURE_EXTERNAL_INDEX;
4154       break;
4155    case GLSL_SAMPLER_DIM_MS:
4156       inst->tex_target = (sampler_type->sampler_array)
4157          ? TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX : TEXTURE_2D_MULTISAMPLE_INDEX;
4158       break;
4159    default:
4160       assert(!"Should not get here.");
4161    }
4162
4163    inst->tex_type = ir->type->base_type;
4164
4165    this->result = result_src;
4166 }
4167
4168 void
4169 glsl_to_tgsi_visitor::visit(ir_return *ir)
4170 {
4171    if (ir->get_value()) {
4172       st_dst_reg l;
4173       int i;
4174
4175       assert(current_function);
4176
4177       ir->get_value()->accept(this);
4178       st_src_reg r = this->result;
4179
4180       l = st_dst_reg(current_function->return_reg);
4181
4182       for (i = 0; i < type_size(current_function->sig->return_type); i++) {
4183          emit_asm(ir, TGSI_OPCODE_MOV, l, r);
4184          l.index++;
4185          r.index++;
4186       }
4187    }
4188
4189    emit_asm(ir, TGSI_OPCODE_RET);
4190 }
4191
4192 void
4193 glsl_to_tgsi_visitor::visit(ir_discard *ir)
4194 {
4195    if (ir->condition) {
4196       ir->condition->accept(this);
4197       st_src_reg condition = this->result;
4198
4199       /* Convert the bool condition to a float so we can negate. */
4200       if (native_integers) {
4201          st_src_reg temp = get_temp(ir->condition->type);
4202          emit_asm(ir, TGSI_OPCODE_AND, st_dst_reg(temp),
4203               condition, st_src_reg_for_float(1.0));
4204          condition = temp;
4205       }
4206
4207       condition.negate = ~condition.negate;
4208       emit_asm(ir, TGSI_OPCODE_KILL_IF, undef_dst, condition);
4209    } else {
4210       /* unconditional kil */
4211       emit_asm(ir, TGSI_OPCODE_KILL);
4212    }
4213 }
4214
4215 void
4216 glsl_to_tgsi_visitor::visit(ir_if *ir)
4217 {
4218    unsigned if_opcode;
4219    glsl_to_tgsi_instruction *if_inst;
4220
4221    ir->condition->accept(this);
4222    assert(this->result.file != PROGRAM_UNDEFINED);
4223
4224    if_opcode = native_integers ? TGSI_OPCODE_UIF : TGSI_OPCODE_IF;
4225
4226    if_inst = emit_asm(ir->condition, if_opcode, undef_dst, this->result);
4227
4228    this->instructions.push_tail(if_inst);
4229
4230    visit_exec_list(&ir->then_instructions, this);
4231
4232    if (!ir->else_instructions.is_empty()) {
4233       emit_asm(ir->condition, TGSI_OPCODE_ELSE);
4234       visit_exec_list(&ir->else_instructions, this);
4235    }
4236
4237    if_inst = emit_asm(ir->condition, TGSI_OPCODE_ENDIF);
4238 }
4239
4240
4241 void
4242 glsl_to_tgsi_visitor::visit(ir_emit_vertex *ir)
4243 {
4244    assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
4245
4246    ir->stream->accept(this);
4247    emit_asm(ir, TGSI_OPCODE_EMIT, undef_dst, this->result);
4248 }
4249
4250 void
4251 glsl_to_tgsi_visitor::visit(ir_end_primitive *ir)
4252 {
4253    assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
4254
4255    ir->stream->accept(this);
4256    emit_asm(ir, TGSI_OPCODE_ENDPRIM, undef_dst, this->result);
4257 }
4258
4259 void
4260 glsl_to_tgsi_visitor::visit(ir_barrier *ir)
4261 {
4262    assert(this->prog->Target == GL_TESS_CONTROL_PROGRAM_NV ||
4263           this->prog->Target == GL_COMPUTE_PROGRAM_NV);
4264
4265    emit_asm(ir, TGSI_OPCODE_BARRIER);
4266 }
4267
4268 glsl_to_tgsi_visitor::glsl_to_tgsi_visitor()
4269 {
4270    STATIC_ASSERT(sizeof(samplers_used) * 8 >= PIPE_MAX_SAMPLERS);
4271
4272    result.file = PROGRAM_UNDEFINED;
4273    next_temp = 1;
4274    array_sizes = NULL;
4275    max_num_arrays = 0;
4276    next_array = 0;
4277    num_input_arrays = 0;
4278    num_output_arrays = 0;
4279    next_signature_id = 1;
4280    num_immediates = 0;
4281    current_function = NULL;
4282    num_address_regs = 0;
4283    samplers_used = 0;
4284    buffers_used = 0;
4285    images_used = 0;
4286    indirect_addr_consts = false;
4287    wpos_transform_const = -1;
4288    glsl_version = 0;
4289    native_integers = false;
4290    mem_ctx = ralloc_context(NULL);
4291    ctx = NULL;
4292    prog = NULL;
4293    shader_program = NULL;
4294    shader = NULL;
4295    options = NULL;
4296    have_sqrt = false;
4297    have_fma = false;
4298    use_shared_memory = false;
4299 }
4300
4301 glsl_to_tgsi_visitor::~glsl_to_tgsi_visitor()
4302 {
4303    free(array_sizes);
4304    ralloc_free(mem_ctx);
4305 }
4306
4307 extern "C" void free_glsl_to_tgsi_visitor(glsl_to_tgsi_visitor *v)
4308 {
4309    delete v;
4310 }
4311
4312
4313 /**
4314  * Count resources used by the given gpu program (number of texture
4315  * samplers, etc).
4316  */
4317 static void
4318 count_resources(glsl_to_tgsi_visitor *v, gl_program *prog)
4319 {
4320    v->samplers_used = 0;
4321    v->buffers_used = 0;
4322    v->images_used = 0;
4323
4324    foreach_in_list(glsl_to_tgsi_instruction, inst, &v->instructions) {
4325       if (inst->info->is_tex) {
4326          for (int i = 0; i < inst->sampler_array_size; i++) {
4327             unsigned idx = inst->sampler_base + i;
4328             v->samplers_used |= 1u << idx;
4329
4330             debug_assert(idx < (int)ARRAY_SIZE(v->sampler_types));
4331             v->sampler_types[idx] = inst->tex_type;
4332             v->sampler_targets[idx] =
4333                st_translate_texture_target(inst->tex_target, inst->tex_shadow);
4334
4335             if (inst->tex_shadow) {
4336                prog->ShadowSamplers |= 1 << (inst->sampler.index + i);
4337             }
4338          }
4339       }
4340       if (inst->buffer.file != PROGRAM_UNDEFINED && (
4341                 is_resource_instruction(inst->op) ||
4342                 inst->op == TGSI_OPCODE_STORE)) {
4343          if (inst->buffer.file == PROGRAM_BUFFER) {
4344             v->buffers_used |= 1 << inst->buffer.index;
4345          } else if (inst->buffer.file == PROGRAM_MEMORY) {
4346             v->use_shared_memory = true;
4347          } else {
4348             assert(inst->buffer.file == PROGRAM_IMAGE);
4349             for (int i = 0; i < inst->sampler_array_size; i++) {
4350                unsigned idx = inst->sampler_base + i;
4351                v->images_used |= 1 << idx;
4352                v->image_targets[idx] =
4353                   st_translate_texture_target(inst->tex_target, false);
4354                v->image_formats[idx] = inst->image_format;
4355             }
4356          }
4357       }
4358    }
4359    prog->SamplersUsed = v->samplers_used;
4360
4361    if (v->shader_program != NULL)
4362       _mesa_update_shader_textures_used(v->shader_program, prog);
4363 }
4364
4365 /**
4366  * Returns the mask of channels (bitmask of WRITEMASK_X,Y,Z,W) which
4367  * are read from the given src in this instruction
4368  */
4369 static int
4370 get_src_arg_mask(st_dst_reg dst, st_src_reg src)
4371 {
4372    int read_mask = 0, comp;
4373
4374    /* Now, given the src swizzle and the written channels, find which
4375     * components are actually read
4376     */
4377    for (comp = 0; comp < 4; ++comp) {
4378       const unsigned coord = GET_SWZ(src.swizzle, comp);
4379       assert(coord < 4);
4380       if (dst.writemask & (1 << comp) && coord <= SWIZZLE_W)
4381          read_mask |= 1 << coord;
4382    }
4383
4384    return read_mask;
4385 }
4386
4387 /**
4388  * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
4389  * instruction is the first instruction to write to register T0.  There are
4390  * several lowering passes done in GLSL IR (e.g. branches and
4391  * relative addressing) that create a large number of conditional assignments
4392  * that ir_to_mesa converts to CMP instructions like the one mentioned above.
4393  *
4394  * Here is why this conversion is safe:
4395  * CMP T0, T1 T2 T0 can be expanded to:
4396  * if (T1 < 0.0)
4397  *   MOV T0, T2;
4398  * else
4399  *   MOV T0, T0;
4400  *
4401  * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
4402  * as the original program.  If (T1 < 0.0) evaluates to false, executing
4403  * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
4404  * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
4405  * because any instruction that was going to read from T0 after this was going
4406  * to read a garbage value anyway.
4407  */
4408 void
4409 glsl_to_tgsi_visitor::simplify_cmp(void)
4410 {
4411    int tempWritesSize = 0;
4412    unsigned *tempWrites = NULL;
4413    unsigned outputWrites[VARYING_SLOT_TESS_MAX];
4414
4415    memset(outputWrites, 0, sizeof(outputWrites));
4416
4417    foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4418       unsigned prevWriteMask = 0;
4419
4420       /* Give up if we encounter relative addressing or flow control. */
4421       if (inst->dst[0].reladdr || inst->dst[0].reladdr2 ||
4422           inst->dst[1].reladdr || inst->dst[1].reladdr2 ||
4423           tgsi_get_opcode_info(inst->op)->is_branch ||
4424           inst->op == TGSI_OPCODE_BGNSUB ||
4425           inst->op == TGSI_OPCODE_CONT ||
4426           inst->op == TGSI_OPCODE_END ||
4427           inst->op == TGSI_OPCODE_ENDSUB ||
4428           inst->op == TGSI_OPCODE_RET) {
4429          break;
4430       }
4431
4432       if (inst->dst[0].file == PROGRAM_OUTPUT) {
4433          assert(inst->dst[0].index < (signed)ARRAY_SIZE(outputWrites));
4434          prevWriteMask = outputWrites[inst->dst[0].index];
4435          outputWrites[inst->dst[0].index] |= inst->dst[0].writemask;
4436       } else if (inst->dst[0].file == PROGRAM_TEMPORARY) {
4437          if (inst->dst[0].index >= tempWritesSize) {
4438             const int inc = 4096;
4439
4440             tempWrites = (unsigned*)
4441                          realloc(tempWrites,
4442                                  (tempWritesSize + inc) * sizeof(unsigned));
4443             if (!tempWrites)
4444                return;
4445
4446             memset(tempWrites + tempWritesSize, 0, inc * sizeof(unsigned));
4447             tempWritesSize += inc;
4448          }
4449
4450          prevWriteMask = tempWrites[inst->dst[0].index];
4451          tempWrites[inst->dst[0].index] |= inst->dst[0].writemask;
4452       } else
4453          continue;
4454
4455       /* For a CMP to be considered a conditional write, the destination
4456        * register and source register two must be the same. */
4457       if (inst->op == TGSI_OPCODE_CMP
4458           && !(inst->dst[0].writemask & prevWriteMask)
4459           && inst->src[2].file == inst->dst[0].file
4460           && inst->src[2].index == inst->dst[0].index
4461           && inst->dst[0].writemask == get_src_arg_mask(inst->dst[0], inst->src[2])) {
4462
4463          inst->op = TGSI_OPCODE_MOV;
4464          inst->info = tgsi_get_opcode_info(inst->op);
4465          inst->src[0] = inst->src[1];
4466       }
4467    }
4468
4469    free(tempWrites);
4470 }
4471
4472 /* Replaces all references to a temporary register index with another index. */
4473 void
4474 glsl_to_tgsi_visitor::rename_temp_registers(int num_renames, struct rename_reg_pair *renames)
4475 {
4476    foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4477       unsigned j;
4478       int k;
4479       for (j = 0; j < num_inst_src_regs(inst); j++) {
4480          if (inst->src[j].file == PROGRAM_TEMPORARY)
4481             for (k = 0; k < num_renames; k++)
4482                if (inst->src[j].index == renames[k].old_reg)
4483                   inst->src[j].index = renames[k].new_reg;
4484       }
4485
4486       for (j = 0; j < inst->tex_offset_num_offset; j++) {
4487          if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY)
4488             for (k = 0; k < num_renames; k++)
4489                if (inst->tex_offsets[j].index == renames[k].old_reg)
4490                   inst->tex_offsets[j].index = renames[k].new_reg;
4491       }
4492
4493       for (j = 0; j < num_inst_dst_regs(inst); j++) {
4494          if (inst->dst[j].file == PROGRAM_TEMPORARY)
4495              for (k = 0; k < num_renames; k++)
4496                 if (inst->dst[j].index == renames[k].old_reg)
4497                    inst->dst[j].index = renames[k].new_reg;
4498       }
4499    }
4500 }
4501
4502 void
4503 glsl_to_tgsi_visitor::get_first_temp_read(int *first_reads)
4504 {
4505    int depth = 0; /* loop depth */
4506    int loop_start = -1; /* index of the first active BGNLOOP (if any) */
4507    unsigned i = 0, j;
4508
4509    foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4510       for (j = 0; j < num_inst_src_regs(inst); j++) {
4511          if (inst->src[j].file == PROGRAM_TEMPORARY) {
4512             if (first_reads[inst->src[j].index] == -1)
4513                 first_reads[inst->src[j].index] = (depth == 0) ? i : loop_start;
4514          }
4515       }
4516       for (j = 0; j < inst->tex_offset_num_offset; j++) {
4517          if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY) {
4518             if (first_reads[inst->tex_offsets[j].index] == -1)
4519                first_reads[inst->tex_offsets[j].index] = (depth == 0) ? i : loop_start;
4520          }
4521       }
4522       if (inst->op == TGSI_OPCODE_BGNLOOP) {
4523          if(depth++ == 0)
4524             loop_start = i;
4525       } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
4526          if (--depth == 0)
4527             loop_start = -1;
4528       }
4529       assert(depth >= 0);
4530       i++;
4531    }
4532 }
4533
4534 void
4535 glsl_to_tgsi_visitor::get_last_temp_read_first_temp_write(int *last_reads, int *first_writes)
4536 {
4537    int depth = 0; /* loop depth */
4538    int loop_start = -1; /* index of the first active BGNLOOP (if any) */
4539    unsigned i = 0, j;
4540    int k;
4541    foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4542       for (j = 0; j < num_inst_src_regs(inst); j++) {
4543          if (inst->src[j].file == PROGRAM_TEMPORARY)
4544             last_reads[inst->src[j].index] = (depth == 0) ? i : -2;
4545       }
4546       for (j = 0; j < num_inst_dst_regs(inst); j++) {
4547          if (inst->dst[j].file == PROGRAM_TEMPORARY) {
4548             if (first_writes[inst->dst[j].index] == -1)
4549                first_writes[inst->dst[j].index] = (depth == 0) ? i : loop_start;
4550             last_reads[inst->dst[j].index] = (depth == 0) ? i : -2;
4551          }
4552       }
4553       for (j = 0; j < inst->tex_offset_num_offset; j++) {
4554          if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY)
4555             last_reads[inst->tex_offsets[j].index] = (depth == 0) ? i : -2;
4556       }
4557       if (inst->op == TGSI_OPCODE_BGNLOOP) {
4558          if(depth++ == 0)
4559             loop_start = i;
4560       } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
4561          if (--depth == 0) {
4562             loop_start = -1;
4563             for (k = 0; k < this->next_temp; k++) {
4564                if (last_reads[k] == -2) {
4565                   last_reads[k] = i;
4566                }
4567             }
4568          }
4569       }
4570       assert(depth >= 0);
4571       i++;
4572    }
4573 }
4574
4575 void
4576 glsl_to_tgsi_visitor::get_last_temp_write(int *last_writes)
4577 {
4578    int depth = 0; /* loop depth */
4579    int i = 0, k;
4580    unsigned j;
4581
4582    foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4583       for (j = 0; j < num_inst_dst_regs(inst); j++) {
4584          if (inst->dst[j].file == PROGRAM_TEMPORARY)
4585             last_writes[inst->dst[j].index] = (depth == 0) ? i : -2;
4586       }
4587
4588       if (inst->op == TGSI_OPCODE_BGNLOOP)
4589          depth++;
4590       else if (inst->op == TGSI_OPCODE_ENDLOOP)
4591          if (--depth == 0) {
4592             for (k = 0; k < this->next_temp; k++) {
4593                if (last_writes[k] == -2) {
4594                   last_writes[k] = i;
4595                }
4596             }
4597          }
4598       assert(depth >= 0);
4599       i++;
4600    }
4601 }
4602
4603 /*
4604  * On a basic block basis, tracks available PROGRAM_TEMPORARY register
4605  * channels for copy propagation and updates following instructions to
4606  * use the original versions.
4607  *
4608  * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
4609  * will occur.  As an example, a TXP production before this pass:
4610  *
4611  * 0: MOV TEMP[1], INPUT[4].xyyy;
4612  * 1: MOV TEMP[1].w, INPUT[4].wwww;
4613  * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
4614  *
4615  * and after:
4616  *
4617  * 0: MOV TEMP[1], INPUT[4].xyyy;
4618  * 1: MOV TEMP[1].w, INPUT[4].wwww;
4619  * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
4620  *
4621  * which allows for dead code elimination on TEMP[1]'s writes.
4622  */
4623 void
4624 glsl_to_tgsi_visitor::copy_propagate(void)
4625 {
4626    glsl_to_tgsi_instruction **acp = rzalloc_array(mem_ctx,
4627                                                   glsl_to_tgsi_instruction *,
4628                                                   this->next_temp * 4);
4629    int *acp_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
4630    int level = 0;
4631
4632    foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4633       assert(inst->dst[0].file != PROGRAM_TEMPORARY
4634              || inst->dst[0].index < this->next_temp);
4635
4636       /* First, do any copy propagation possible into the src regs. */
4637       for (int r = 0; r < 3; r++) {
4638          glsl_to_tgsi_instruction *first = NULL;
4639          bool good = true;
4640          int acp_base = inst->src[r].index * 4;
4641
4642          if (inst->src[r].file != PROGRAM_TEMPORARY ||
4643              inst->src[r].reladdr ||
4644              inst->src[r].reladdr2)
4645             continue;
4646
4647          /* See if we can find entries in the ACP consisting of MOVs
4648           * from the same src register for all the swizzled channels
4649           * of this src register reference.
4650           */
4651          for (int i = 0; i < 4; i++) {
4652             int src_chan = GET_SWZ(inst->src[r].swizzle, i);
4653             glsl_to_tgsi_instruction *copy_chan = acp[acp_base + src_chan];
4654
4655             if (!copy_chan) {
4656                good = false;
4657                break;
4658             }
4659
4660             assert(acp_level[acp_base + src_chan] <= level);
4661
4662             if (!first) {
4663                first = copy_chan;
4664             } else {
4665                if (first->src[0].file != copy_chan->src[0].file ||
4666                    first->src[0].index != copy_chan->src[0].index ||
4667                    first->src[0].double_reg2 != copy_chan->src[0].double_reg2 ||
4668                    first->src[0].index2D != copy_chan->src[0].index2D) {
4669                   good = false;
4670                   break;
4671                }
4672             }
4673          }
4674
4675          if (good) {
4676             /* We've now validated that we can copy-propagate to
4677              * replace this src register reference.  Do it.
4678              */
4679             inst->src[r].file = first->src[0].file;
4680             inst->src[r].index = first->src[0].index;
4681             inst->src[r].index2D = first->src[0].index2D;
4682             inst->src[r].has_index2 = first->src[0].has_index2;
4683             inst->src[r].double_reg2 = first->src[0].double_reg2;
4684             inst->src[r].array_id = first->src[0].array_id;
4685
4686             int swizzle = 0;
4687             for (int i = 0; i < 4; i++) {
4688                int src_chan = GET_SWZ(inst->src[r].swizzle, i);
4689                glsl_to_tgsi_instruction *copy_inst = acp[acp_base + src_chan];
4690                swizzle |= (GET_SWZ(copy_inst->src[0].swizzle, src_chan) << (3 * i));
4691             }
4692             inst->src[r].swizzle = swizzle;
4693          }
4694       }
4695
4696       switch (inst->op) {
4697       case TGSI_OPCODE_BGNLOOP:
4698       case TGSI_OPCODE_ENDLOOP:
4699          /* End of a basic block, clear the ACP entirely. */
4700          memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
4701          break;
4702
4703       case TGSI_OPCODE_IF:
4704       case TGSI_OPCODE_UIF:
4705          ++level;
4706          break;
4707
4708       case TGSI_OPCODE_ENDIF:
4709       case TGSI_OPCODE_ELSE:
4710          /* Clear all channels written inside the block from the ACP, but
4711           * leaving those that were not touched.
4712           */
4713          for (int r = 0; r < this->next_temp; r++) {
4714             for (int c = 0; c < 4; c++) {
4715                if (!acp[4 * r + c])
4716                   continue;
4717
4718                if (acp_level[4 * r + c] >= level)
4719                   acp[4 * r + c] = NULL;
4720             }
4721          }
4722          if (inst->op == TGSI_OPCODE_ENDIF)
4723             --level;
4724          break;
4725
4726       default:
4727          /* Continuing the block, clear any written channels from
4728           * the ACP.
4729           */
4730          for (int d = 0; d < 2; d++) {
4731             if (inst->dst[d].file == PROGRAM_TEMPORARY && inst->dst[d].reladdr) {
4732                /* Any temporary might be written, so no copy propagation
4733                 * across this instruction.
4734                 */
4735                memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
4736             } else if (inst->dst[d].file == PROGRAM_OUTPUT &&
4737                        inst->dst[d].reladdr) {
4738                /* Any output might be written, so no copy propagation
4739                 * from outputs across this instruction.
4740                 */
4741                for (int r = 0; r < this->next_temp; r++) {
4742                   for (int c = 0; c < 4; c++) {
4743                      if (!acp[4 * r + c])
4744                         continue;
4745
4746                      if (acp[4 * r + c]->src[0].file == PROGRAM_OUTPUT)
4747                         acp[4 * r + c] = NULL;
4748                   }
4749                }
4750             } else if (inst->dst[d].file == PROGRAM_TEMPORARY ||
4751                        inst->dst[d].file == PROGRAM_OUTPUT) {
4752                /* Clear where it's used as dst. */
4753                if (inst->dst[d].file == PROGRAM_TEMPORARY) {
4754                   for (int c = 0; c < 4; c++) {
4755                      if (inst->dst[d].writemask & (1 << c))
4756                         acp[4 * inst->dst[d].index + c] = NULL;
4757                   }
4758                }
4759
4760                /* Clear where it's used as src. */
4761                for (int r = 0; r < this->next_temp; r++) {
4762                   for (int c = 0; c < 4; c++) {
4763                      if (!acp[4 * r + c])
4764                         continue;
4765
4766                      int src_chan = GET_SWZ(acp[4 * r + c]->src[0].swizzle, c);
4767
4768                      if (acp[4 * r + c]->src[0].file == inst->dst[d].file &&
4769                          acp[4 * r + c]->src[0].index == inst->dst[d].index &&
4770                          inst->dst[d].writemask & (1 << src_chan)) {
4771                         acp[4 * r + c] = NULL;
4772                      }
4773                   }
4774                }
4775             }
4776          }
4777          break;
4778       }
4779
4780       /* If this is a copy, add it to the ACP. */
4781       if (inst->op == TGSI_OPCODE_MOV &&
4782           inst->dst[0].file == PROGRAM_TEMPORARY &&
4783           !(inst->dst[0].file == inst->src[0].file &&
4784              inst->dst[0].index == inst->src[0].index) &&
4785           !inst->dst[0].reladdr &&
4786           !inst->dst[0].reladdr2 &&
4787           !inst->saturate &&
4788           inst->src[0].file != PROGRAM_ARRAY &&
4789           !inst->src[0].reladdr &&
4790           !inst->src[0].reladdr2 &&
4791           !inst->src[0].negate) {
4792          for (int i = 0; i < 4; i++) {
4793             if (inst->dst[0].writemask & (1 << i)) {
4794                acp[4 * inst->dst[0].index + i] = inst;
4795                acp_level[4 * inst->dst[0].index + i] = level;
4796             }
4797          }
4798       }
4799    }
4800
4801    ralloc_free(acp_level);
4802    ralloc_free(acp);
4803 }
4804
4805 /*
4806  * On a basic block basis, tracks available PROGRAM_TEMPORARY registers for dead
4807  * code elimination.
4808  *
4809  * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
4810  * will occur.  As an example, a TXP production after copy propagation but
4811  * before this pass:
4812  *
4813  * 0: MOV TEMP[1], INPUT[4].xyyy;
4814  * 1: MOV TEMP[1].w, INPUT[4].wwww;
4815  * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
4816  *
4817  * and after this pass:
4818  *
4819  * 0: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
4820  */
4821 int
4822 glsl_to_tgsi_visitor::eliminate_dead_code(void)
4823 {
4824    glsl_to_tgsi_instruction **writes = rzalloc_array(mem_ctx,
4825                                                      glsl_to_tgsi_instruction *,
4826                                                      this->next_temp * 4);
4827    int *write_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
4828    int level = 0;
4829    int removed = 0;
4830
4831    foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4832       assert(inst->dst[0].file != PROGRAM_TEMPORARY
4833              || inst->dst[0].index < this->next_temp);
4834
4835       switch (inst->op) {
4836       case TGSI_OPCODE_BGNLOOP:
4837       case TGSI_OPCODE_ENDLOOP:
4838       case TGSI_OPCODE_CONT:
4839       case TGSI_OPCODE_BRK:
4840          /* End of a basic block, clear the write array entirely.
4841           *
4842           * This keeps us from killing dead code when the writes are
4843           * on either side of a loop, even when the register isn't touched
4844           * inside the loop.  However, glsl_to_tgsi_visitor doesn't seem to emit
4845           * dead code of this type, so it shouldn't make a difference as long as
4846           * the dead code elimination pass in the GLSL compiler does its job.
4847           */
4848          memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
4849          break;
4850
4851       case TGSI_OPCODE_ENDIF:
4852       case TGSI_OPCODE_ELSE:
4853          /* Promote the recorded level of all channels written inside the
4854           * preceding if or else block to the level above the if/else block.
4855           */
4856          for (int r = 0; r < this->next_temp; r++) {
4857             for (int c = 0; c < 4; c++) {
4858                if (!writes[4 * r + c])
4859                   continue;
4860
4861                if (write_level[4 * r + c] == level)
4862                   write_level[4 * r + c] = level-1;
4863             }
4864          }
4865          if(inst->op == TGSI_OPCODE_ENDIF)
4866             --level;
4867          break;
4868
4869       case TGSI_OPCODE_IF:
4870       case TGSI_OPCODE_UIF:
4871          ++level;
4872          /* fallthrough to default case to mark the condition as read */
4873       default:
4874          /* Continuing the block, clear any channels from the write array that
4875           * are read by this instruction.
4876           */
4877          for (unsigned i = 0; i < ARRAY_SIZE(inst->src); i++) {
4878             if (inst->src[i].file == PROGRAM_TEMPORARY && inst->src[i].reladdr){
4879                /* Any temporary might be read, so no dead code elimination
4880                 * across this instruction.
4881                 */
4882                memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
4883             } else if (inst->src[i].file == PROGRAM_TEMPORARY) {
4884                /* Clear where it's used as src. */
4885                int src_chans = 1 << GET_SWZ(inst->src[i].swizzle, 0);
4886                src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 1);
4887                src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 2);
4888                src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 3);
4889
4890                for (int c = 0; c < 4; c++) {
4891                   if (src_chans & (1 << c))
4892                      writes[4 * inst->src[i].index + c] = NULL;
4893                }
4894             }
4895          }
4896          for (unsigned i = 0; i < inst->tex_offset_num_offset; i++) {
4897             if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY && inst->tex_offsets[i].reladdr){
4898                /* Any temporary might be read, so no dead code elimination
4899                 * across this instruction.
4900                 */
4901                memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
4902             } else if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY) {
4903                /* Clear where it's used as src. */
4904                int src_chans = 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 0);
4905                src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 1);
4906                src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 2);
4907                src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 3);
4908
4909                for (int c = 0; c < 4; c++) {
4910                   if (src_chans & (1 << c))
4911                      writes[4 * inst->tex_offsets[i].index + c] = NULL;
4912                }
4913             }
4914          }
4915          break;
4916       }
4917
4918       /* If this instruction writes to a temporary, add it to the write array.
4919        * If there is already an instruction in the write array for one or more
4920        * of the channels, flag that channel write as dead.
4921        */
4922       for (unsigned i = 0; i < ARRAY_SIZE(inst->dst); i++) {
4923          if (inst->dst[i].file == PROGRAM_TEMPORARY &&
4924              !inst->dst[i].reladdr) {
4925             for (int c = 0; c < 4; c++) {
4926                if (inst->dst[i].writemask & (1 << c)) {
4927                   if (writes[4 * inst->dst[i].index + c]) {
4928                      if (write_level[4 * inst->dst[i].index + c] < level)
4929                         continue;
4930                      else
4931                         writes[4 * inst->dst[i].index + c]->dead_mask |= (1 << c);
4932                   }
4933                   writes[4 * inst->dst[i].index + c] = inst;
4934                   write_level[4 * inst->dst[i].index + c] = level;
4935                }
4936             }
4937          }
4938       }
4939    }
4940
4941    /* Anything still in the write array at this point is dead code. */
4942    for (int r = 0; r < this->next_temp; r++) {
4943       for (int c = 0; c < 4; c++) {
4944          glsl_to_tgsi_instruction *inst = writes[4 * r + c];
4945          if (inst)
4946             inst->dead_mask |= (1 << c);
4947       }
4948    }
4949
4950    /* Now actually remove the instructions that are completely dead and update
4951     * the writemask of other instructions with dead channels.
4952     */
4953    foreach_in_list_safe(glsl_to_tgsi_instruction, inst, &this->instructions) {
4954       if (!inst->dead_mask || !inst->dst[0].writemask)
4955          continue;
4956       /* No amount of dead masks should remove memory stores */
4957       if (inst->info->is_store)
4958          continue;
4959
4960       if ((inst->dst[0].writemask & ~inst->dead_mask) == 0) {
4961          inst->remove();
4962          delete inst;
4963          removed++;
4964       } else {
4965          if (inst->dst[0].type == GLSL_TYPE_DOUBLE) {
4966             if (inst->dead_mask == WRITEMASK_XY ||
4967                 inst->dead_mask == WRITEMASK_ZW)
4968                inst->dst[0].writemask &= ~(inst->dead_mask);
4969          } else
4970             inst->dst[0].writemask &= ~(inst->dead_mask);
4971       }
4972    }
4973
4974    ralloc_free(write_level);
4975    ralloc_free(writes);
4976
4977    return removed;
4978 }
4979
4980 /* merge DFRACEXP instructions into one. */
4981 void
4982 glsl_to_tgsi_visitor::merge_two_dsts(void)
4983 {
4984    foreach_in_list_safe(glsl_to_tgsi_instruction, inst, &this->instructions) {
4985       glsl_to_tgsi_instruction *inst2;
4986       bool merged;
4987       if (num_inst_dst_regs(inst) != 2)
4988          continue;
4989
4990       if (inst->dst[0].file != PROGRAM_UNDEFINED &&
4991           inst->dst[1].file != PROGRAM_UNDEFINED)
4992          continue;
4993
4994       inst2 = (glsl_to_tgsi_instruction *) inst->next;
4995       do {
4996
4997          if (inst->src[0].file == inst2->src[0].file &&
4998              inst->src[0].index == inst2->src[0].index &&
4999              inst->src[0].type == inst2->src[0].type &&
5000              inst->src[0].swizzle == inst2->src[0].swizzle)
5001             break;
5002          inst2 = (glsl_to_tgsi_instruction *) inst2->next;
5003       } while (inst2);
5004
5005       if (!inst2)
5006          continue;
5007       merged = false;
5008       if (inst->dst[0].file == PROGRAM_UNDEFINED) {
5009          merged = true;
5010          inst->dst[0] = inst2->dst[0];
5011       } else if (inst->dst[1].file == PROGRAM_UNDEFINED) {
5012          inst->dst[1] = inst2->dst[1];
5013          merged = true;
5014       }
5015
5016       if (merged) {
5017          inst2->remove();
5018          delete inst2;
5019       }
5020    }
5021 }
5022
5023 /* Merges temporary registers together where possible to reduce the number of
5024  * registers needed to run a program.
5025  *
5026  * Produces optimal code only after copy propagation and dead code elimination
5027  * have been run. */
5028 void
5029 glsl_to_tgsi_visitor::merge_registers(void)
5030 {
5031    int *last_reads = rzalloc_array(mem_ctx, int, this->next_temp);
5032    int *first_writes = rzalloc_array(mem_ctx, int, this->next_temp);
5033    struct rename_reg_pair *renames = rzalloc_array(mem_ctx, struct rename_reg_pair, this->next_temp);
5034    int i, j;
5035    int num_renames = 0;
5036
5037    /* Read the indices of the last read and first write to each temp register
5038     * into an array so that we don't have to traverse the instruction list as
5039     * much. */
5040    for (i = 0; i < this->next_temp; i++) {
5041       last_reads[i] = -1;
5042       first_writes[i] = -1;
5043    }
5044    get_last_temp_read_first_temp_write(last_reads, first_writes);
5045
5046    /* Start looking for registers with non-overlapping usages that can be
5047     * merged together. */
5048    for (i = 0; i < this->next_temp; i++) {
5049       /* Don't touch unused registers. */
5050       if (last_reads[i] < 0 || first_writes[i] < 0) continue;
5051
5052       for (j = 0; j < this->next_temp; j++) {
5053          /* Don't touch unused registers. */
5054          if (last_reads[j] < 0 || first_writes[j] < 0) continue;
5055
5056          /* We can merge the two registers if the first write to j is after or
5057           * in the same instruction as the last read from i.  Note that the
5058           * register at index i will always be used earlier or at the same time
5059           * as the register at index j. */
5060          if (first_writes[i] <= first_writes[j] &&
5061              last_reads[i] <= first_writes[j]) {
5062             renames[num_renames].old_reg = j;
5063             renames[num_renames].new_reg = i;
5064             num_renames++;
5065
5066             /* Update the first_writes and last_reads arrays with the new
5067              * values for the merged register index, and mark the newly unused
5068              * register index as such. */
5069             assert(last_reads[j] >= last_reads[i]);
5070             last_reads[i] = last_reads[j];
5071             first_writes[j] = -1;
5072             last_reads[j] = -1;
5073          }
5074       }
5075    }
5076
5077    rename_temp_registers(num_renames, renames);
5078    ralloc_free(renames);
5079    ralloc_free(last_reads);
5080    ralloc_free(first_writes);
5081 }
5082
5083 /* Reassign indices to temporary registers by reusing unused indices created
5084  * by optimization passes. */
5085 void
5086 glsl_to_tgsi_visitor::renumber_registers(void)
5087 {
5088    int i = 0;
5089    int new_index = 0;
5090    int *first_reads = rzalloc_array(mem_ctx, int, this->next_temp);
5091    struct rename_reg_pair *renames = rzalloc_array(mem_ctx, struct rename_reg_pair, this->next_temp);
5092    int num_renames = 0;
5093    for (i = 0; i < this->next_temp; i++) {
5094       first_reads[i] = -1;
5095    }
5096    get_first_temp_read(first_reads);
5097
5098    for (i = 0; i < this->next_temp; i++) {
5099       if (first_reads[i] < 0) continue;
5100       if (i != new_index) {
5101          renames[num_renames].old_reg = i;
5102          renames[num_renames].new_reg = new_index;
5103          num_renames++;
5104       }
5105       new_index++;
5106    }
5107
5108    rename_temp_registers(num_renames, renames);
5109    this->next_temp = new_index;
5110    ralloc_free(renames);
5111    ralloc_free(first_reads);
5112 }
5113
5114 /* ------------------------- TGSI conversion stuff -------------------------- */
5115 struct label {
5116    unsigned branch_target;
5117    unsigned token;
5118 };
5119
5120 /**
5121  * Intermediate state used during shader translation.
5122  */
5123 struct st_translate {
5124    struct ureg_program *ureg;
5125
5126    unsigned temps_size;
5127    struct ureg_dst *temps;
5128
5129    struct ureg_dst *arrays;
5130    unsigned num_temp_arrays;
5131    struct ureg_src *constants;
5132    int num_constants;
5133    struct ureg_src *immediates;
5134    int num_immediates;
5135    struct ureg_dst outputs[PIPE_MAX_SHADER_OUTPUTS];
5136    struct ureg_src inputs[PIPE_MAX_SHADER_INPUTS];
5137    struct ureg_dst address[3];
5138    struct ureg_src samplers[PIPE_MAX_SAMPLERS];
5139    struct ureg_src buffers[PIPE_MAX_SHADER_BUFFERS];
5140    struct ureg_src images[PIPE_MAX_SHADER_IMAGES];
5141    struct ureg_src systemValues[SYSTEM_VALUE_MAX];
5142    struct ureg_src shared_memory;
5143    struct tgsi_texture_offset tex_offsets[MAX_GLSL_TEXTURE_OFFSET];
5144    unsigned *array_sizes;
5145    struct array_decl *input_arrays;
5146    struct array_decl *output_arrays;
5147
5148    const GLuint *inputMapping;
5149    const GLuint *outputMapping;
5150
5151    /* For every instruction that contains a label (eg CALL), keep
5152     * details so that we can go back afterwards and emit the correct
5153     * tgsi instruction number for each label.
5154     */
5155    struct label *labels;
5156    unsigned labels_size;
5157    unsigned labels_count;
5158
5159    /* Keep a record of the tgsi instruction number that each mesa
5160     * instruction starts at, will be used to fix up labels after
5161     * translation.
5162     */
5163    unsigned *insn;
5164    unsigned insn_size;
5165    unsigned insn_count;
5166
5167    unsigned procType;  /**< PIPE_SHADER_VERTEX/FRAGMENT */
5168
5169    boolean error;
5170 };
5171
5172 /** Map Mesa's SYSTEM_VALUE_x to TGSI_SEMANTIC_x */
5173 unsigned
5174 _mesa_sysval_to_semantic(unsigned sysval)
5175 {
5176    switch (sysval) {
5177    /* Vertex shader */
5178    case SYSTEM_VALUE_VERTEX_ID:
5179       return TGSI_SEMANTIC_VERTEXID;
5180    case SYSTEM_VALUE_INSTANCE_ID:
5181       return TGSI_SEMANTIC_INSTANCEID;
5182    case SYSTEM_VALUE_VERTEX_ID_ZERO_BASE:
5183       return TGSI_SEMANTIC_VERTEXID_NOBASE;
5184    case SYSTEM_VALUE_BASE_VERTEX:
5185       return TGSI_SEMANTIC_BASEVERTEX;
5186    case SYSTEM_VALUE_BASE_INSTANCE:
5187       return TGSI_SEMANTIC_BASEINSTANCE;
5188    case SYSTEM_VALUE_DRAW_ID:
5189       return TGSI_SEMANTIC_DRAWID;
5190
5191    /* Geometry shader */
5192    case SYSTEM_VALUE_INVOCATION_ID:
5193       return TGSI_SEMANTIC_INVOCATIONID;
5194
5195    /* Fragment shader */
5196    case SYSTEM_VALUE_FRAG_COORD:
5197       return TGSI_SEMANTIC_POSITION;
5198    case SYSTEM_VALUE_FRONT_FACE:
5199       return TGSI_SEMANTIC_FACE;
5200    case SYSTEM_VALUE_SAMPLE_ID:
5201       return TGSI_SEMANTIC_SAMPLEID;
5202    case SYSTEM_VALUE_SAMPLE_POS:
5203       return TGSI_SEMANTIC_SAMPLEPOS;
5204    case SYSTEM_VALUE_SAMPLE_MASK_IN:
5205       return TGSI_SEMANTIC_SAMPLEMASK;
5206    case SYSTEM_VALUE_HELPER_INVOCATION:
5207       return TGSI_SEMANTIC_HELPER_INVOCATION;
5208
5209    /* Tessellation shader */
5210    case SYSTEM_VALUE_TESS_COORD:
5211       return TGSI_SEMANTIC_TESSCOORD;
5212    case SYSTEM_VALUE_VERTICES_IN:
5213       return TGSI_SEMANTIC_VERTICESIN;
5214    case SYSTEM_VALUE_PRIMITIVE_ID:
5215       return TGSI_SEMANTIC_PRIMID;
5216    case SYSTEM_VALUE_TESS_LEVEL_OUTER:
5217       return TGSI_SEMANTIC_TESSOUTER;
5218    case SYSTEM_VALUE_TESS_LEVEL_INNER:
5219       return TGSI_SEMANTIC_TESSINNER;
5220
5221    /* Compute shader */
5222    case SYSTEM_VALUE_LOCAL_INVOCATION_ID:
5223       return TGSI_SEMANTIC_THREAD_ID;
5224    case SYSTEM_VALUE_WORK_GROUP_ID:
5225       return TGSI_SEMANTIC_BLOCK_ID;
5226    case SYSTEM_VALUE_NUM_WORK_GROUPS:
5227       return TGSI_SEMANTIC_GRID_SIZE;
5228
5229    /* Unhandled */
5230    case SYSTEM_VALUE_LOCAL_INVOCATION_INDEX:
5231    case SYSTEM_VALUE_GLOBAL_INVOCATION_ID:
5232    case SYSTEM_VALUE_VERTEX_CNT:
5233    default:
5234       assert(!"Unexpected SYSTEM_VALUE_ enum");
5235       return TGSI_SEMANTIC_COUNT;
5236    }
5237 }
5238
5239
5240 /**
5241  * Make note of a branch to a label in the TGSI code.
5242  * After we've emitted all instructions, we'll go over the list
5243  * of labels built here and patch the TGSI code with the actual
5244  * location of each label.
5245  */
5246 static unsigned *get_label(struct st_translate *t, unsigned branch_target)
5247 {
5248    unsigned i;
5249
5250    if (t->labels_count + 1 >= t->labels_size) {
5251       t->labels_size = 1 << (util_logbase2(t->labels_size) + 1);
5252       t->labels = (struct label *)realloc(t->labels,
5253                                           t->labels_size * sizeof(struct label));
5254       if (t->labels == NULL) {
5255          static unsigned dummy;
5256          t->error = TRUE;
5257          return &dummy;
5258       }
5259    }
5260
5261    i = t->labels_count++;
5262    t->labels[i].branch_target = branch_target;
5263    return &t->labels[i].token;
5264 }
5265
5266 /**
5267  * Called prior to emitting the TGSI code for each instruction.
5268  * Allocate additional space for instructions if needed.
5269  * Update the insn[] array so the next glsl_to_tgsi_instruction points to
5270  * the next TGSI instruction.
5271  */
5272 static void set_insn_start(struct st_translate *t, unsigned start)
5273 {
5274    if (t->insn_count + 1 >= t->insn_size) {
5275       t->insn_size = 1 << (util_logbase2(t->insn_size) + 1);
5276       t->insn = (unsigned *)realloc(t->insn, t->insn_size * sizeof(t->insn[0]));
5277       if (t->insn == NULL) {
5278          t->error = TRUE;
5279          return;
5280       }
5281    }
5282
5283    t->insn[t->insn_count++] = start;
5284 }
5285
5286 /**
5287  * Map a glsl_to_tgsi constant/immediate to a TGSI immediate.
5288  */
5289 static struct ureg_src
5290 emit_immediate(struct st_translate *t,
5291                gl_constant_value values[4],
5292                int type, int size)
5293 {
5294    struct ureg_program *ureg = t->ureg;
5295
5296    switch(type)
5297    {
5298    case GL_FLOAT:
5299       return ureg_DECL_immediate(ureg, &values[0].f, size);
5300    case GL_DOUBLE:
5301       return ureg_DECL_immediate_f64(ureg, (double *)&values[0].f, size);
5302    case GL_INT:
5303       return ureg_DECL_immediate_int(ureg, &values[0].i, size);
5304    case GL_UNSIGNED_INT:
5305    case GL_BOOL:
5306       return ureg_DECL_immediate_uint(ureg, &values[0].u, size);
5307    default:
5308       assert(!"should not get here - type must be float, int, uint, or bool");
5309       return ureg_src_undef();
5310    }
5311 }
5312
5313 /**
5314  * Map a glsl_to_tgsi dst register to a TGSI ureg_dst register.
5315  */
5316 static struct ureg_dst
5317 dst_register(struct st_translate *t, gl_register_file file, unsigned index,
5318              unsigned array_id)
5319 {
5320    unsigned array;
5321
5322    switch(file) {
5323    case PROGRAM_UNDEFINED:
5324       return ureg_dst_undef();
5325
5326    case PROGRAM_TEMPORARY:
5327       /* Allocate space for temporaries on demand. */
5328       if (index >= t->temps_size) {
5329          const int inc = align(index - t->temps_size + 1, 4096);
5330
5331          t->temps = (struct ureg_dst*)
5332                     realloc(t->temps,
5333                             (t->temps_size + inc) * sizeof(struct ureg_dst));
5334          if (!t->temps)
5335             return ureg_dst_undef();
5336
5337          memset(t->temps + t->temps_size, 0, inc * sizeof(struct ureg_dst));
5338          t->temps_size += inc;
5339       }
5340
5341       if (ureg_dst_is_undef(t->temps[index]))
5342          t->temps[index] = ureg_DECL_local_temporary(t->ureg);
5343
5344       return t->temps[index];
5345
5346    case PROGRAM_ARRAY:
5347       array = index >> 16;
5348
5349       assert(array < t->num_temp_arrays);
5350
5351       if (ureg_dst_is_undef(t->arrays[array]))
5352          t->arrays[array] = ureg_DECL_array_temporary(
5353             t->ureg, t->array_sizes[array], TRUE);
5354
5355       return ureg_dst_array_offset(t->arrays[array],
5356                                    (int)(index & 0xFFFF) - 0x8000);
5357
5358    case PROGRAM_OUTPUT:
5359       if (!array_id) {
5360          if (t->procType == PIPE_SHADER_FRAGMENT)
5361             assert(index < FRAG_RESULT_MAX);
5362          else if (t->procType == PIPE_SHADER_TESS_CTRL ||
5363                   t->procType == PIPE_SHADER_TESS_EVAL)
5364             assert(index < VARYING_SLOT_TESS_MAX);
5365          else
5366             assert(index < VARYING_SLOT_MAX);
5367
5368          assert(t->outputMapping[index] < ARRAY_SIZE(t->outputs));
5369          assert(t->outputs[t->outputMapping[index]].File != TGSI_FILE_NULL);
5370          return t->outputs[t->outputMapping[index]];
5371       }
5372       else {
5373          struct array_decl *decl = &t->output_arrays[array_id-1];
5374          unsigned mesa_index = decl->mesa_index;
5375          int slot = t->outputMapping[mesa_index];
5376
5377          assert(slot != -1 && t->outputs[slot].File == TGSI_FILE_OUTPUT);
5378          assert(t->outputs[slot].ArrayID == array_id);
5379          return ureg_dst_array_offset(t->outputs[slot], index - mesa_index);
5380       }
5381
5382    case PROGRAM_ADDRESS:
5383       return t->address[index];
5384
5385    default:
5386       assert(!"unknown dst register file");
5387       return ureg_dst_undef();
5388    }
5389 }
5390
5391 /**
5392  * Map a glsl_to_tgsi src register to a TGSI ureg_src register.
5393  */
5394 static struct ureg_src
5395 src_register(struct st_translate *t, const st_src_reg *reg)
5396 {
5397    int index = reg->index;
5398    int double_reg2 = reg->double_reg2 ? 1 : 0;
5399
5400    switch(reg->file) {
5401    case PROGRAM_UNDEFINED:
5402       return ureg_imm4f(t->ureg, 0, 0, 0, 0);
5403
5404    case PROGRAM_TEMPORARY:
5405    case PROGRAM_ARRAY:
5406    case PROGRAM_OUTPUT:
5407       return ureg_src(dst_register(t, reg->file, reg->index, reg->array_id));
5408
5409    case PROGRAM_UNIFORM:
5410       assert(reg->index >= 0);
5411       return reg->index < t->num_constants ?
5412                t->constants[reg->index] : ureg_imm4f(t->ureg, 0, 0, 0, 0);
5413    case PROGRAM_STATE_VAR:
5414    case PROGRAM_CONSTANT:       /* ie, immediate */
5415       if (reg->has_index2)
5416          return ureg_src_register(TGSI_FILE_CONSTANT, reg->index);
5417       else
5418          return reg->index >= 0 && reg->index < t->num_constants ?
5419                   t->constants[reg->index] : ureg_imm4f(t->ureg, 0, 0, 0, 0);
5420
5421    case PROGRAM_IMMEDIATE:
5422       assert(reg->index >= 0 && reg->index < t->num_immediates);
5423       return t->immediates[reg->index];
5424
5425    case PROGRAM_INPUT:
5426       /* GLSL inputs are 64-bit containers, so we have to
5427        * map back to the original index and add the offset after
5428        * mapping. */
5429       index -= double_reg2;
5430       if (!reg->array_id) {
5431          assert(t->inputMapping[index] < ARRAY_SIZE(t->inputs));
5432          assert(t->inputs[t->inputMapping[index]].File != TGSI_FILE_NULL);
5433          return t->inputs[t->inputMapping[index] + double_reg2];
5434       }
5435       else {
5436          struct array_decl *decl = &t->input_arrays[reg->array_id-1];
5437          unsigned mesa_index = decl->mesa_index;
5438          int slot = t->inputMapping[mesa_index];
5439
5440          assert(slot != -1 && t->inputs[slot].File == TGSI_FILE_INPUT);
5441          assert(t->inputs[slot].ArrayID == reg->array_id);
5442          return ureg_src_array_offset(t->inputs[slot], index + double_reg2 - mesa_index);
5443       }
5444
5445    case PROGRAM_ADDRESS:
5446       return ureg_src(t->address[reg->index]);
5447
5448    case PROGRAM_SYSTEM_VALUE:
5449       assert(reg->index < (int) ARRAY_SIZE(t->systemValues));
5450       return t->systemValues[reg->index];
5451
5452    default:
5453       assert(!"unknown src register file");
5454       return ureg_src_undef();
5455    }
5456 }
5457
5458 /**
5459  * Create a TGSI ureg_dst register from an st_dst_reg.
5460  */
5461 static struct ureg_dst
5462 translate_dst(struct st_translate *t,
5463               const st_dst_reg *dst_reg,
5464               bool saturate)
5465 {
5466    struct ureg_dst dst = dst_register(t, dst_reg->file, dst_reg->index,
5467                                       dst_reg->array_id);
5468
5469    if (dst.File == TGSI_FILE_NULL)
5470       return dst;
5471
5472    dst = ureg_writemask(dst, dst_reg->writemask);
5473
5474    if (saturate)
5475       dst = ureg_saturate(dst);
5476
5477    if (dst_reg->reladdr != NULL) {
5478       assert(dst_reg->file != PROGRAM_TEMPORARY);
5479       dst = ureg_dst_indirect(dst, ureg_src(t->address[0]));
5480    }
5481
5482    if (dst_reg->has_index2) {
5483       if (dst_reg->reladdr2)
5484          dst = ureg_dst_dimension_indirect(dst, ureg_src(t->address[1]),
5485                                            dst_reg->index2D);
5486       else
5487          dst = ureg_dst_dimension(dst, dst_reg->index2D);
5488    }
5489
5490    return dst;
5491 }
5492
5493 /**
5494  * Create a TGSI ureg_src register from an st_src_reg.
5495  */
5496 static struct ureg_src
5497 translate_src(struct st_translate *t, const st_src_reg *src_reg)
5498 {
5499    struct ureg_src src = src_register(t, src_reg);
5500
5501    if (src_reg->has_index2) {
5502       /* 2D indexes occur with geometry shader inputs (attrib, vertex)
5503        * and UBO constant buffers (buffer, position).
5504        */
5505       if (src_reg->reladdr2)
5506          src = ureg_src_dimension_indirect(src, ureg_src(t->address[1]),
5507                                            src_reg->index2D);
5508       else
5509          src = ureg_src_dimension(src, src_reg->index2D);
5510    }
5511
5512    src = ureg_swizzle(src,
5513                       GET_SWZ(src_reg->swizzle, 0) & 0x3,
5514                       GET_SWZ(src_reg->swizzle, 1) & 0x3,
5515                       GET_SWZ(src_reg->swizzle, 2) & 0x3,
5516                       GET_SWZ(src_reg->swizzle, 3) & 0x3);
5517
5518    if ((src_reg->negate & 0xf) == NEGATE_XYZW)
5519       src = ureg_negate(src);
5520
5521    if (src_reg->reladdr != NULL) {
5522       assert(src_reg->file != PROGRAM_TEMPORARY);
5523       src = ureg_src_indirect(src, ureg_src(t->address[0]));
5524    }
5525
5526    return src;
5527 }
5528
5529 static struct tgsi_texture_offset
5530 translate_tex_offset(struct st_translate *t,
5531                      const st_src_reg *in_offset, int idx)
5532 {
5533    struct tgsi_texture_offset offset;
5534    struct ureg_src imm_src;
5535    struct ureg_dst dst;
5536    int array;
5537
5538    switch (in_offset->file) {
5539    case PROGRAM_IMMEDIATE:
5540       assert(in_offset->index >= 0 && in_offset->index < t->num_immediates);
5541       imm_src = t->immediates[in_offset->index];
5542
5543       offset.File = imm_src.File;
5544       offset.Index = imm_src.Index;
5545       offset.SwizzleX = imm_src.SwizzleX;
5546       offset.SwizzleY = imm_src.SwizzleY;
5547       offset.SwizzleZ = imm_src.SwizzleZ;
5548       offset.Padding = 0;
5549       break;
5550    case PROGRAM_INPUT:
5551       imm_src = t->inputs[t->inputMapping[in_offset->index]];
5552       offset.File = imm_src.File;
5553       offset.Index = imm_src.Index;
5554       offset.SwizzleX = GET_SWZ(in_offset->swizzle, 0);
5555       offset.SwizzleY = GET_SWZ(in_offset->swizzle, 1);
5556       offset.SwizzleZ = GET_SWZ(in_offset->swizzle, 2);
5557       offset.Padding = 0;
5558       break;
5559    case PROGRAM_TEMPORARY:
5560       imm_src = ureg_src(t->temps[in_offset->index]);
5561       offset.File = imm_src.File;
5562       offset.Index = imm_src.Index;
5563       offset.SwizzleX = GET_SWZ(in_offset->swizzle, 0);
5564       offset.SwizzleY = GET_SWZ(in_offset->swizzle, 1);
5565       offset.SwizzleZ = GET_SWZ(in_offset->swizzle, 2);
5566       offset.Padding = 0;
5567       break;
5568    case PROGRAM_ARRAY:
5569       array = in_offset->index >> 16;
5570
5571       assert(array >= 0);
5572       assert(array < (int)t->num_temp_arrays);
5573
5574       dst = t->arrays[array];
5575       offset.File = dst.File;
5576       offset.Index = dst.Index + (in_offset->index & 0xFFFF) - 0x8000;
5577       offset.SwizzleX = GET_SWZ(in_offset->swizzle, 0);
5578       offset.SwizzleY = GET_SWZ(in_offset->swizzle, 1);
5579       offset.SwizzleZ = GET_SWZ(in_offset->swizzle, 2);
5580       offset.Padding = 0;
5581       break;
5582    default:
5583       break;
5584    }
5585    return offset;
5586 }
5587
5588 static void
5589 compile_tgsi_instruction(struct st_translate *t,
5590                          const glsl_to_tgsi_instruction *inst)
5591 {
5592    struct ureg_program *ureg = t->ureg;
5593    int i;
5594    struct ureg_dst dst[2];
5595    struct ureg_src src[4];
5596    struct tgsi_texture_offset texoffsets[MAX_GLSL_TEXTURE_OFFSET];
5597
5598    int num_dst;
5599    int num_src;
5600    unsigned tex_target = 0;
5601
5602    num_dst = num_inst_dst_regs(inst);
5603    num_src = num_inst_src_regs(inst);
5604
5605    for (i = 0; i < num_dst; i++)
5606       dst[i] = translate_dst(t,
5607                              &inst->dst[i],
5608                              inst->saturate);
5609
5610    for (i = 0; i < num_src; i++)
5611       src[i] = translate_src(t, &inst->src[i]);
5612
5613    switch(inst->op) {
5614    case TGSI_OPCODE_BGNLOOP:
5615    case TGSI_OPCODE_CAL:
5616    case TGSI_OPCODE_ELSE:
5617    case TGSI_OPCODE_ENDLOOP:
5618    case TGSI_OPCODE_IF:
5619    case TGSI_OPCODE_UIF:
5620       assert(num_dst == 0);
5621       ureg_label_insn(ureg,
5622                       inst->op,
5623                       src, num_src,
5624                       get_label(t,
5625                                 inst->op == TGSI_OPCODE_CAL ? inst->function->sig_id : 0));
5626       return;
5627
5628    case TGSI_OPCODE_TEX:
5629    case TGSI_OPCODE_TXB:
5630    case TGSI_OPCODE_TXD:
5631    case TGSI_OPCODE_TXL:
5632    case TGSI_OPCODE_TXP:
5633    case TGSI_OPCODE_TXQ:
5634    case TGSI_OPCODE_TXQS:
5635    case TGSI_OPCODE_TXF:
5636    case TGSI_OPCODE_TEX2:
5637    case TGSI_OPCODE_TXB2:
5638    case TGSI_OPCODE_TXL2:
5639    case TGSI_OPCODE_TG4:
5640    case TGSI_OPCODE_LODQ:
5641       src[num_src] = t->samplers[inst->sampler.index];
5642       assert(src[num_src].File != TGSI_FILE_NULL);
5643       if (inst->sampler.reladdr)
5644          src[num_src] =
5645             ureg_src_indirect(src[num_src], ureg_src(t->address[2]));
5646       num_src++;
5647       for (i = 0; i < (int)inst->tex_offset_num_offset; i++) {
5648          texoffsets[i] = translate_tex_offset(t, &inst->tex_offsets[i], i);
5649       }
5650       tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
5651
5652       ureg_tex_insn(ureg,
5653                     inst->op,
5654                     dst, num_dst,
5655                     tex_target,
5656                     texoffsets, inst->tex_offset_num_offset,
5657                     src, num_src);
5658       return;
5659
5660    case TGSI_OPCODE_RESQ:
5661    case TGSI_OPCODE_LOAD:
5662    case TGSI_OPCODE_ATOMUADD:
5663    case TGSI_OPCODE_ATOMXCHG:
5664    case TGSI_OPCODE_ATOMCAS:
5665    case TGSI_OPCODE_ATOMAND:
5666    case TGSI_OPCODE_ATOMOR:
5667    case TGSI_OPCODE_ATOMXOR:
5668    case TGSI_OPCODE_ATOMUMIN:
5669    case TGSI_OPCODE_ATOMUMAX:
5670    case TGSI_OPCODE_ATOMIMIN:
5671    case TGSI_OPCODE_ATOMIMAX:
5672       for (i = num_src - 1; i >= 0; i--)
5673          src[i + 1] = src[i];
5674       num_src++;
5675       if (inst->buffer.file == PROGRAM_MEMORY) {
5676          src[0] = t->shared_memory;
5677       } else if (inst->buffer.file == PROGRAM_BUFFER) {
5678          src[0] = t->buffers[inst->buffer.index];
5679       } else {
5680          src[0] = t->images[inst->buffer.index];
5681          tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
5682       }
5683       if (inst->buffer.reladdr)
5684          src[0] = ureg_src_indirect(src[0], ureg_src(t->address[2]));
5685       assert(src[0].File != TGSI_FILE_NULL);
5686       ureg_memory_insn(ureg, inst->op, dst, num_dst, src, num_src,
5687                        inst->buffer_access,
5688                        tex_target, inst->image_format);
5689       break;
5690
5691    case TGSI_OPCODE_STORE:
5692       if (inst->buffer.file == PROGRAM_MEMORY) {
5693          dst[0] = ureg_dst(t->shared_memory);
5694       } else if (inst->buffer.file == PROGRAM_BUFFER) {
5695          dst[0] = ureg_dst(t->buffers[inst->buffer.index]);
5696       } else {
5697          dst[0] = ureg_dst(t->images[inst->buffer.index]);
5698          tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
5699       }
5700       dst[0] = ureg_writemask(dst[0], inst->dst[0].writemask);
5701       if (inst->buffer.reladdr)
5702          dst[0] = ureg_dst_indirect(dst[0], ureg_src(t->address[2]));
5703       assert(dst[0].File != TGSI_FILE_NULL);
5704       ureg_memory_insn(ureg, inst->op, dst, num_dst, src, num_src,
5705                        inst->buffer_access,
5706                        tex_target, inst->image_format);
5707       break;
5708
5709    case TGSI_OPCODE_SCS:
5710       dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XY);
5711       ureg_insn(ureg, inst->op, dst, num_dst, src, num_src);
5712       break;
5713
5714    default:
5715       ureg_insn(ureg,
5716                 inst->op,
5717                 dst, num_dst,
5718                 src, num_src);
5719       break;
5720    }
5721 }
5722
5723 /**
5724  * Emit the TGSI instructions for inverting and adjusting WPOS.
5725  * This code is unavoidable because it also depends on whether
5726  * a FBO is bound (STATE_FB_WPOS_Y_TRANSFORM).
5727  */
5728 static void
5729 emit_wpos_adjustment(struct gl_context *ctx,
5730                      struct st_translate *t,
5731                      int wpos_transform_const,
5732                      boolean invert,
5733                      GLfloat adjX, GLfloat adjY[2])
5734 {
5735    struct ureg_program *ureg = t->ureg;
5736
5737    assert(wpos_transform_const >= 0);
5738
5739    /* Fragment program uses fragment position input.
5740     * Need to replace instances of INPUT[WPOS] with temp T
5741     * where T = INPUT[WPOS] is inverted by Y.
5742     */
5743    struct ureg_src wpostrans = ureg_DECL_constant(ureg, wpos_transform_const);
5744    struct ureg_dst wpos_temp = ureg_DECL_temporary( ureg );
5745    struct ureg_src *wpos =
5746       ctx->Const.GLSLFragCoordIsSysVal ?
5747          &t->systemValues[SYSTEM_VALUE_FRAG_COORD] :
5748          &t->inputs[t->inputMapping[VARYING_SLOT_POS]];
5749    struct ureg_src wpos_input = *wpos;
5750
5751    /* First, apply the coordinate shift: */
5752    if (adjX || adjY[0] || adjY[1]) {
5753       if (adjY[0] != adjY[1]) {
5754          /* Adjust the y coordinate by adjY[1] or adjY[0] respectively
5755           * depending on whether inversion is actually going to be applied
5756           * or not, which is determined by testing against the inversion
5757           * state variable used below, which will be either +1 or -1.
5758           */
5759          struct ureg_dst adj_temp = ureg_DECL_local_temporary(ureg);
5760
5761          ureg_CMP(ureg, adj_temp,
5762                   ureg_scalar(wpostrans, invert ? 2 : 0),
5763                   ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f),
5764                   ureg_imm4f(ureg, adjX, adjY[1], 0.0f, 0.0f));
5765          ureg_ADD(ureg, wpos_temp, wpos_input, ureg_src(adj_temp));
5766       } else {
5767          ureg_ADD(ureg, wpos_temp, wpos_input,
5768                   ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f));
5769       }
5770       wpos_input = ureg_src(wpos_temp);
5771    } else {
5772       /* MOV wpos_temp, input[wpos]
5773        */
5774       ureg_MOV( ureg, wpos_temp, wpos_input );
5775    }
5776
5777    /* Now the conditional y flip: STATE_FB_WPOS_Y_TRANSFORM.xy/zw will be
5778     * inversion/identity, or the other way around if we're drawing to an FBO.
5779     */
5780    if (invert) {
5781       /* MAD wpos_temp.y, wpos_input, wpostrans.xxxx, wpostrans.yyyy
5782        */
5783       ureg_MAD( ureg,
5784                 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
5785                 wpos_input,
5786                 ureg_scalar(wpostrans, 0),
5787                 ureg_scalar(wpostrans, 1));
5788    } else {
5789       /* MAD wpos_temp.y, wpos_input, wpostrans.zzzz, wpostrans.wwww
5790        */
5791       ureg_MAD( ureg,
5792                 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
5793                 wpos_input,
5794                 ureg_scalar(wpostrans, 2),
5795                 ureg_scalar(wpostrans, 3));
5796    }
5797
5798    /* Use wpos_temp as position input from here on:
5799     */
5800    *wpos = ureg_src(wpos_temp);
5801 }
5802
5803
5804 /**
5805  * Emit fragment position/ooordinate code.
5806  */
5807 static void
5808 emit_wpos(struct st_context *st,
5809           struct st_translate *t,
5810           const struct gl_program *program,
5811           struct ureg_program *ureg,
5812           int wpos_transform_const)
5813 {
5814    const struct gl_fragment_program *fp =
5815       (const struct gl_fragment_program *) program;
5816    struct pipe_screen *pscreen = st->pipe->screen;
5817    GLfloat adjX = 0.0f;
5818    GLfloat adjY[2] = { 0.0f, 0.0f };
5819    boolean invert = FALSE;
5820
5821    /* Query the pixel center conventions supported by the pipe driver and set
5822     * adjX, adjY to help out if it cannot handle the requested one internally.
5823     *
5824     * The bias of the y-coordinate depends on whether y-inversion takes place
5825     * (adjY[1]) or not (adjY[0]), which is in turn dependent on whether we are
5826     * drawing to an FBO (causes additional inversion), and whether the the pipe
5827     * driver origin and the requested origin differ (the latter condition is
5828     * stored in the 'invert' variable).
5829     *
5830     * For height = 100 (i = integer, h = half-integer, l = lower, u = upper):
5831     *
5832     * center shift only:
5833     * i -> h: +0.5
5834     * h -> i: -0.5
5835     *
5836     * inversion only:
5837     * l,i -> u,i: ( 0.0 + 1.0) * -1 + 100 = 99
5838     * l,h -> u,h: ( 0.5 + 0.0) * -1 + 100 = 99.5
5839     * u,i -> l,i: (99.0 + 1.0) * -1 + 100 = 0
5840     * u,h -> l,h: (99.5 + 0.0) * -1 + 100 = 0.5
5841     *
5842     * inversion and center shift:
5843     * l,i -> u,h: ( 0.0 + 0.5) * -1 + 100 = 99.5
5844     * l,h -> u,i: ( 0.5 + 0.5) * -1 + 100 = 99
5845     * u,i -> l,h: (99.0 + 0.5) * -1 + 100 = 0.5
5846     * u,h -> l,i: (99.5 + 0.5) * -1 + 100 = 0
5847     */
5848    if (fp->OriginUpperLeft) {
5849       /* Fragment shader wants origin in upper-left */
5850       if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT)) {
5851          /* the driver supports upper-left origin */
5852       }
5853       else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT)) {
5854          /* the driver supports lower-left origin, need to invert Y */
5855          ureg_property(ureg, TGSI_PROPERTY_FS_COORD_ORIGIN,
5856                        TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
5857          invert = TRUE;
5858       }
5859       else
5860          assert(0);
5861    }
5862    else {
5863       /* Fragment shader wants origin in lower-left */
5864       if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT))
5865          /* the driver supports lower-left origin */
5866          ureg_property(ureg, TGSI_PROPERTY_FS_COORD_ORIGIN,
5867                        TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
5868       else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT))
5869          /* the driver supports upper-left origin, need to invert Y */
5870          invert = TRUE;
5871       else
5872          assert(0);
5873    }
5874
5875    if (fp->PixelCenterInteger) {
5876       /* Fragment shader wants pixel center integer */
5877       if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
5878          /* the driver supports pixel center integer */
5879          adjY[1] = 1.0f;
5880          ureg_property(ureg, TGSI_PROPERTY_FS_COORD_PIXEL_CENTER,
5881                        TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
5882       }
5883       else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
5884          /* the driver supports pixel center half integer, need to bias X,Y */
5885          adjX = -0.5f;
5886          adjY[0] = -0.5f;
5887          adjY[1] = 0.5f;
5888       }
5889       else
5890          assert(0);
5891    }
5892    else {
5893       /* Fragment shader wants pixel center half integer */
5894       if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
5895          /* the driver supports pixel center half integer */
5896       }
5897       else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
5898          /* the driver supports pixel center integer, need to bias X,Y */
5899          adjX = adjY[0] = adjY[1] = 0.5f;
5900          ureg_property(ureg, TGSI_PROPERTY_FS_COORD_PIXEL_CENTER,
5901                        TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
5902       }
5903       else
5904          assert(0);
5905    }
5906
5907    /* we invert after adjustment so that we avoid the MOV to temporary,
5908     * and reuse the adjustment ADD instead */
5909    emit_wpos_adjustment(st->ctx, t, wpos_transform_const, invert, adjX, adjY);
5910 }
5911
5912 /**
5913  * OpenGL's fragment gl_FrontFace input is 1 for front-facing, 0 for back.
5914  * TGSI uses +1 for front, -1 for back.
5915  * This function converts the TGSI value to the GL value.  Simply clamping/
5916  * saturating the value to [0,1] does the job.
5917  */
5918 static void
5919 emit_face_var(struct gl_context *ctx, struct st_translate *t)
5920 {
5921    struct ureg_program *ureg = t->ureg;
5922    struct ureg_dst face_temp = ureg_DECL_temporary(ureg);
5923    struct ureg_src face_input = t->inputs[t->inputMapping[VARYING_SLOT_FACE]];
5924
5925    if (ctx->Const.NativeIntegers) {
5926       ureg_FSGE(ureg, face_temp, face_input, ureg_imm1f(ureg, 0));
5927    }
5928    else {
5929       /* MOV_SAT face_temp, input[face] */
5930       ureg_MOV(ureg, ureg_saturate(face_temp), face_input);
5931    }
5932
5933    /* Use face_temp as face input from here on: */
5934    t->inputs[t->inputMapping[VARYING_SLOT_FACE]] = ureg_src(face_temp);
5935 }
5936
5937 static bool
5938 find_array(unsigned attr, struct array_decl *arrays, unsigned count,
5939            unsigned *array_id, unsigned *array_size)
5940 {
5941    unsigned i;
5942
5943    for (i = 0; i < count; i++) {
5944       struct array_decl *decl = &arrays[i];
5945
5946       if (attr == decl->mesa_index) {
5947          *array_id = decl->array_id;
5948          *array_size = decl->array_size;
5949          assert(*array_size);
5950          return true;
5951       }
5952    }
5953    return false;
5954 }
5955
5956 static void
5957 emit_compute_block_size(const struct gl_program *program,
5958                         struct ureg_program *ureg) {
5959    const struct gl_compute_program *cp =
5960       (const struct gl_compute_program *)program;
5961
5962    ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH,
5963                        cp->LocalSize[0]);
5964    ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT,
5965                        cp->LocalSize[1]);
5966    ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH,
5967                        cp->LocalSize[2]);
5968 }
5969
5970 /**
5971  * Translate intermediate IR (glsl_to_tgsi_instruction) to TGSI format.
5972  * \param program  the program to translate
5973  * \param numInputs  number of input registers used
5974  * \param inputMapping  maps Mesa fragment program inputs to TGSI generic
5975  *                      input indexes
5976  * \param inputSemanticName  the TGSI_SEMANTIC flag for each input
5977  * \param inputSemanticIndex  the semantic index (ex: which texcoord) for
5978  *                            each input
5979  * \param interpMode  the TGSI_INTERPOLATE_LINEAR/PERSP mode for each input
5980  * \param interpLocation the TGSI_INTERPOLATE_LOC_* location for each input
5981  * \param numOutputs  number of output registers used
5982  * \param outputMapping  maps Mesa fragment program outputs to TGSI
5983  *                       generic outputs
5984  * \param outputSemanticName  the TGSI_SEMANTIC flag for each output
5985  * \param outputSemanticIndex  the semantic index (ex: which texcoord) for
5986  *                             each output
5987  *
5988  * \return  PIPE_OK or PIPE_ERROR_OUT_OF_MEMORY
5989  */
5990 extern "C" enum pipe_error
5991 st_translate_program(
5992    struct gl_context *ctx,
5993    uint procType,
5994    struct ureg_program *ureg,
5995    glsl_to_tgsi_visitor *program,
5996    const struct gl_program *proginfo,
5997    GLuint numInputs,
5998    const GLuint inputMapping[],
5999    const GLuint inputSlotToAttr[],
6000    const ubyte inputSemanticName[],
6001    const ubyte inputSemanticIndex[],
6002    const GLuint interpMode[],
6003    const GLuint interpLocation[],
6004    GLuint numOutputs,
6005    const GLuint outputMapping[],
6006    const GLuint outputSlotToAttr[],
6007    const ubyte outputSemanticName[],
6008    const ubyte outputSemanticIndex[])
6009 {
6010    struct st_translate *t;
6011    unsigned i;
6012    struct gl_program_constants *frag_const =
6013       &ctx->Const.Program[MESA_SHADER_FRAGMENT];
6014    enum pipe_error ret = PIPE_OK;
6015
6016    assert(numInputs <= ARRAY_SIZE(t->inputs));
6017    assert(numOutputs <= ARRAY_SIZE(t->outputs));
6018
6019    t = CALLOC_STRUCT(st_translate);
6020    if (!t) {
6021       ret = PIPE_ERROR_OUT_OF_MEMORY;
6022       goto out;
6023    }
6024
6025    t->procType = procType;
6026    t->inputMapping = inputMapping;
6027    t->outputMapping = outputMapping;
6028    t->ureg = ureg;
6029    t->num_temp_arrays = program->next_array;
6030    if (t->num_temp_arrays)
6031       t->arrays = (struct ureg_dst*)
6032                   calloc(1, sizeof(t->arrays[0]) * t->num_temp_arrays);
6033
6034    /*
6035     * Declare input attributes.
6036     */
6037    switch (procType) {
6038    case PIPE_SHADER_FRAGMENT:
6039       for (i = 0; i < numInputs; i++) {
6040          unsigned array_id = 0;
6041          unsigned array_size;
6042
6043          if (find_array(inputSlotToAttr[i], program->input_arrays,
6044                         program->num_input_arrays, &array_id, &array_size)) {
6045             /* We've found an array. Declare it so. */
6046             t->inputs[i] = ureg_DECL_fs_input_cyl_centroid(ureg,
6047                               inputSemanticName[i], inputSemanticIndex[i],
6048                               interpMode[i], 0, interpLocation[i],
6049                               array_id, array_size);
6050
6051             GLuint base_attr = inputSlotToAttr[i];
6052             while (i + 1 < numInputs &&
6053                    inputSlotToAttr[i + 1] < base_attr + array_size)
6054                ++i;
6055          }
6056          else {
6057             t->inputs[i] = ureg_DECL_fs_input_cyl_centroid(ureg,
6058                               inputSemanticName[i], inputSemanticIndex[i],
6059                               interpMode[i], 0, interpLocation[i], 0, 1);
6060          }
6061       }
6062       break;
6063    case PIPE_SHADER_GEOMETRY:
6064    case PIPE_SHADER_TESS_EVAL:
6065    case PIPE_SHADER_TESS_CTRL:
6066       for (i = 0; i < numInputs; i++) {
6067          unsigned array_id = 0;
6068          unsigned array_size;
6069
6070          if (find_array(inputSlotToAttr[i], program->input_arrays,
6071                         program->num_input_arrays, &array_id, &array_size)) {
6072             /* We've found an array. Declare it so. */
6073             t->inputs[i] = ureg_DECL_input(ureg, inputSemanticName[i],
6074                                            inputSemanticIndex[i],
6075                                            array_id, array_size);
6076             i += array_size - 1;
6077          }
6078          else {
6079             t->inputs[i] = ureg_DECL_input(ureg, inputSemanticName[i],
6080                                            inputSemanticIndex[i], 0, 1);
6081          }
6082       }
6083       break;
6084    case PIPE_SHADER_VERTEX:
6085       for (i = 0; i < numInputs; i++) {
6086          t->inputs[i] = ureg_DECL_vs_input(ureg, i);
6087       }
6088       break;
6089    case PIPE_SHADER_COMPUTE:
6090       break;
6091    default:
6092       assert(0);
6093    }
6094
6095    /*
6096     * Declare output attributes.
6097     */
6098    switch (procType) {
6099    case PIPE_SHADER_FRAGMENT:
6100    case PIPE_SHADER_COMPUTE:
6101       break;
6102    case PIPE_SHADER_GEOMETRY:
6103    case PIPE_SHADER_TESS_EVAL:
6104    case PIPE_SHADER_TESS_CTRL:
6105    case PIPE_SHADER_VERTEX:
6106       for (i = 0; i < numOutputs; i++) {
6107          unsigned array_id = 0;
6108          unsigned array_size;
6109
6110          if (find_array(outputSlotToAttr[i], program->output_arrays,
6111                         program->num_output_arrays, &array_id, &array_size)) {
6112             /* We've found an array. Declare it so. */
6113             t->outputs[i] = ureg_DECL_output_array(ureg,
6114                                                    outputSemanticName[i],
6115                                                    outputSemanticIndex[i],
6116                                                    array_id, array_size);
6117             i += array_size - 1;
6118          }
6119          else {
6120             t->outputs[i] = ureg_DECL_output(ureg,
6121                                              outputSemanticName[i],
6122                                              outputSemanticIndex[i]);
6123          }
6124       }
6125       break;
6126    default:
6127       assert(0);
6128    }
6129
6130    if (procType == PIPE_SHADER_FRAGMENT) {
6131       if (program->shader->EarlyFragmentTests)
6132          ureg_property(ureg, TGSI_PROPERTY_FS_EARLY_DEPTH_STENCIL, 1);
6133
6134       if (proginfo->InputsRead & VARYING_BIT_POS) {
6135           /* Must do this after setting up t->inputs. */
6136           emit_wpos(st_context(ctx), t, proginfo, ureg,
6137                     program->wpos_transform_const);
6138       }
6139
6140       if (proginfo->InputsRead & VARYING_BIT_FACE)
6141          emit_face_var(ctx, t);
6142
6143       for (i = 0; i < numOutputs; i++) {
6144          switch (outputSemanticName[i]) {
6145          case TGSI_SEMANTIC_POSITION:
6146             t->outputs[i] = ureg_DECL_output(ureg,
6147                                              TGSI_SEMANTIC_POSITION, /* Z/Depth */
6148                                              outputSemanticIndex[i]);
6149             t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Z);
6150             break;
6151          case TGSI_SEMANTIC_STENCIL:
6152             t->outputs[i] = ureg_DECL_output(ureg,
6153                                              TGSI_SEMANTIC_STENCIL, /* Stencil */
6154                                              outputSemanticIndex[i]);
6155             t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Y);
6156             break;
6157          case TGSI_SEMANTIC_COLOR:
6158             t->outputs[i] = ureg_DECL_output(ureg,
6159                                              TGSI_SEMANTIC_COLOR,
6160                                              outputSemanticIndex[i]);
6161             break;
6162          case TGSI_SEMANTIC_SAMPLEMASK:
6163             t->outputs[i] = ureg_DECL_output(ureg,
6164                                              TGSI_SEMANTIC_SAMPLEMASK,
6165                                              outputSemanticIndex[i]);
6166             /* TODO: If we ever support more than 32 samples, this will have
6167              * to become an array.
6168              */
6169             t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_X);
6170             break;
6171          default:
6172             assert(!"fragment shader outputs must be POSITION/STENCIL/COLOR");
6173             ret = PIPE_ERROR_BAD_INPUT;
6174             goto out;
6175          }
6176       }
6177    }
6178    else if (procType == PIPE_SHADER_VERTEX) {
6179       for (i = 0; i < numOutputs; i++) {
6180          if (outputSemanticName[i] == TGSI_SEMANTIC_FOG) {
6181             /* force register to contain a fog coordinate in the form (F, 0, 0, 1). */
6182             ureg_MOV(ureg,
6183                      ureg_writemask(t->outputs[i], TGSI_WRITEMASK_YZW),
6184                      ureg_imm4f(ureg, 0.0f, 0.0f, 0.0f, 1.0f));
6185             t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_X);
6186          }
6187       }
6188    }
6189
6190    if (procType == PIPE_SHADER_COMPUTE) {
6191       emit_compute_block_size(proginfo, ureg);
6192    }
6193
6194    /* Declare address register.
6195     */
6196    if (program->num_address_regs > 0) {
6197       assert(program->num_address_regs <= 3);
6198       for (int i = 0; i < program->num_address_regs; i++)
6199          t->address[i] = ureg_DECL_address(ureg);
6200    }
6201
6202    /* Declare misc input registers
6203     */
6204    {
6205       GLbitfield sysInputs = proginfo->SystemValuesRead;
6206
6207       for (i = 0; sysInputs; i++) {
6208          if (sysInputs & (1 << i)) {
6209             unsigned semName = _mesa_sysval_to_semantic(i);
6210
6211             t->systemValues[i] = ureg_DECL_system_value(ureg, semName, 0);
6212
6213             if (semName == TGSI_SEMANTIC_INSTANCEID ||
6214                 semName == TGSI_SEMANTIC_VERTEXID) {
6215                /* From Gallium perspective, these system values are always
6216                 * integer, and require native integer support.  However, if
6217                 * native integer is supported on the vertex stage but not the
6218                 * pixel stage (e.g, i915g + draw), Mesa will generate IR that
6219                 * assumes these system values are floats. To resolve the
6220                 * inconsistency, we insert a U2F.
6221                 */
6222                struct st_context *st = st_context(ctx);
6223                struct pipe_screen *pscreen = st->pipe->screen;
6224                assert(procType == PIPE_SHADER_VERTEX);
6225                assert(pscreen->get_shader_param(pscreen, PIPE_SHADER_VERTEX, PIPE_SHADER_CAP_INTEGERS));
6226                (void) pscreen;
6227                if (!ctx->Const.NativeIntegers) {
6228                   struct ureg_dst temp = ureg_DECL_local_temporary(t->ureg);
6229                   ureg_U2F( t->ureg, ureg_writemask(temp, TGSI_WRITEMASK_X), t->systemValues[i]);
6230                   t->systemValues[i] = ureg_scalar(ureg_src(temp), 0);
6231                }
6232             }
6233
6234             if (procType == PIPE_SHADER_FRAGMENT &&
6235                 semName == TGSI_SEMANTIC_POSITION)
6236                emit_wpos(st_context(ctx), t, proginfo, ureg,
6237                          program->wpos_transform_const);
6238
6239             sysInputs &= ~(1 << i);
6240          }
6241       }
6242    }
6243
6244    t->array_sizes = program->array_sizes;
6245    t->input_arrays = program->input_arrays;
6246    t->output_arrays = program->output_arrays;
6247
6248    /* Emit constants and uniforms.  TGSI uses a single index space for these,
6249     * so we put all the translated regs in t->constants.
6250     */
6251    if (proginfo->Parameters) {
6252       t->constants = (struct ureg_src *)
6253          calloc(proginfo->Parameters->NumParameters, sizeof(t->constants[0]));
6254       if (t->constants == NULL) {
6255          ret = PIPE_ERROR_OUT_OF_MEMORY;
6256          goto out;
6257       }
6258       t->num_constants = proginfo->Parameters->NumParameters;
6259
6260       for (i = 0; i < proginfo->Parameters->NumParameters; i++) {
6261          switch (proginfo->Parameters->Parameters[i].Type) {
6262          case PROGRAM_STATE_VAR:
6263          case PROGRAM_UNIFORM:
6264             t->constants[i] = ureg_DECL_constant(ureg, i);
6265             break;
6266
6267          /* Emit immediates for PROGRAM_CONSTANT only when there's no indirect
6268           * addressing of the const buffer.
6269           * FIXME: Be smarter and recognize param arrays:
6270           * indirect addressing is only valid within the referenced
6271           * array.
6272           */
6273          case PROGRAM_CONSTANT:
6274             if (program->indirect_addr_consts)
6275                t->constants[i] = ureg_DECL_constant(ureg, i);
6276             else
6277                t->constants[i] = emit_immediate(t,
6278                                                 proginfo->Parameters->ParameterValues[i],
6279                                                 proginfo->Parameters->Parameters[i].DataType,
6280                                                 4);
6281             break;
6282          default:
6283             break;
6284          }
6285       }
6286    }
6287
6288    if (program->shader) {
6289       unsigned num_ubos = program->shader->NumUniformBlocks;
6290
6291       for (i = 0; i < num_ubos; i++) {
6292          unsigned size = program->shader->UniformBlocks[i]->UniformBufferSize;
6293          unsigned num_const_vecs = (size + 15) / 16;
6294          unsigned first, last;
6295          assert(num_const_vecs > 0);
6296          first = 0;
6297          last = num_const_vecs > 0 ? num_const_vecs - 1 : 0;
6298          ureg_DECL_constant2D(t->ureg, first, last, i + 1);
6299       }
6300    }
6301
6302    /* Emit immediate values.
6303     */
6304    t->immediates = (struct ureg_src *)
6305       calloc(program->num_immediates, sizeof(struct ureg_src));
6306    if (t->immediates == NULL) {
6307       ret = PIPE_ERROR_OUT_OF_MEMORY;
6308       goto out;
6309    }
6310    t->num_immediates = program->num_immediates;
6311
6312    i = 0;
6313    foreach_in_list(immediate_storage, imm, &program->immediates) {
6314       assert(i < program->num_immediates);
6315       t->immediates[i++] = emit_immediate(t, imm->values, imm->type, imm->size32);
6316    }
6317    assert(i == program->num_immediates);
6318
6319    /* texture samplers */
6320    for (i = 0; i < frag_const->MaxTextureImageUnits; i++) {
6321       if (program->samplers_used & (1u << i)) {
6322          unsigned type;
6323
6324          t->samplers[i] = ureg_DECL_sampler(ureg, i);
6325
6326          switch (program->sampler_types[i]) {
6327          case GLSL_TYPE_INT:
6328             type = TGSI_RETURN_TYPE_SINT;
6329             break;
6330          case GLSL_TYPE_UINT:
6331             type = TGSI_RETURN_TYPE_UINT;
6332             break;
6333          case GLSL_TYPE_FLOAT:
6334             type = TGSI_RETURN_TYPE_FLOAT;
6335             break;
6336          default:
6337             unreachable("not reached");
6338          }
6339
6340          ureg_DECL_sampler_view( ureg, i, program->sampler_targets[i],
6341                                  type, type, type, type );
6342       }
6343    }
6344
6345    for (i = 0; i < frag_const->MaxAtomicBuffers; i++) {
6346       if (program->buffers_used & (1 << i)) {
6347          t->buffers[i] = ureg_DECL_buffer(ureg, i, true);
6348       }
6349    }
6350
6351    for (; i < frag_const->MaxAtomicBuffers + frag_const->MaxShaderStorageBlocks;
6352         i++) {
6353       if (program->buffers_used & (1 << i)) {
6354          t->buffers[i] = ureg_DECL_buffer(ureg, i, false);
6355       }
6356    }
6357
6358    if (program->use_shared_memory)
6359       t->shared_memory = ureg_DECL_memory(ureg, TGSI_MEMORY_TYPE_SHARED);
6360
6361    for (i = 0; i < program->shader->NumImages; i++) {
6362       if (program->images_used & (1 << i)) {
6363          t->images[i] = ureg_DECL_image(ureg, i,
6364                                         program->image_targets[i],
6365                                         program->image_formats[i],
6366                                         true, false);
6367       }
6368    }
6369
6370    /* Emit each instruction in turn:
6371     */
6372    foreach_in_list(glsl_to_tgsi_instruction, inst, &program->instructions) {
6373       set_insn_start(t, ureg_get_instruction_number(ureg));
6374       compile_tgsi_instruction(t, inst);
6375    }
6376
6377    /* Fix up all emitted labels:
6378     */
6379    for (i = 0; i < t->labels_count; i++) {
6380       ureg_fixup_label(ureg, t->labels[i].token,
6381                        t->insn[t->labels[i].branch_target]);
6382    }
6383
6384    /* Set the next shader stage hint for VS and TES. */
6385    switch (procType) {
6386    case PIPE_SHADER_VERTEX:
6387    case PIPE_SHADER_TESS_EVAL:
6388       if (program->shader_program->SeparateShader)
6389          break;
6390
6391       for (i = program->shader->Stage+1; i <= MESA_SHADER_FRAGMENT; i++) {
6392          if (program->shader_program->_LinkedShaders[i]) {
6393             unsigned next;
6394
6395             switch (i) {
6396             case MESA_SHADER_TESS_CTRL:
6397                next = PIPE_SHADER_TESS_CTRL;
6398                break;
6399             case MESA_SHADER_TESS_EVAL:
6400                next = PIPE_SHADER_TESS_EVAL;
6401                break;
6402             case MESA_SHADER_GEOMETRY:
6403                next = PIPE_SHADER_GEOMETRY;
6404                break;
6405             case MESA_SHADER_FRAGMENT:
6406                next = PIPE_SHADER_FRAGMENT;
6407                break;
6408             default:
6409                assert(0);
6410                continue;
6411             }
6412
6413             ureg_set_next_shader_processor(ureg, next);
6414             break;
6415          }
6416       }
6417       break;
6418    }
6419
6420 out:
6421    if (t) {
6422       free(t->arrays);
6423       free(t->temps);
6424       free(t->insn);
6425       free(t->labels);
6426       free(t->constants);
6427       t->num_constants = 0;
6428       free(t->immediates);
6429       t->num_immediates = 0;
6430
6431       if (t->error) {
6432          debug_printf("%s: translate error flag set\n", __func__);
6433       }
6434
6435       FREE(t);
6436    }
6437
6438    return ret;
6439 }
6440 /* ----------------------------- End TGSI code ------------------------------ */
6441
6442
6443 /**
6444  * Convert a shader's GLSL IR into a Mesa gl_program, although without
6445  * generating Mesa IR.
6446  */
6447 static struct gl_program *
6448 get_mesa_program_tgsi(struct gl_context *ctx,
6449                       struct gl_shader_program *shader_program,
6450                       struct gl_shader *shader)
6451 {
6452    glsl_to_tgsi_visitor* v;
6453    struct gl_program *prog;
6454    GLenum target = _mesa_shader_stage_to_program(shader->Stage);
6455    bool progress;
6456    struct gl_shader_compiler_options *options =
6457          &ctx->Const.ShaderCompilerOptions[_mesa_shader_enum_to_shader_stage(shader->Type)];
6458    struct pipe_screen *pscreen = ctx->st->pipe->screen;
6459    unsigned ptarget = st_shader_stage_to_ptarget(shader->Stage);
6460
6461    validate_ir_tree(shader->ir);
6462
6463    prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
6464    if (!prog)
6465       return NULL;
6466    prog->Parameters = _mesa_new_parameter_list();
6467    v = new glsl_to_tgsi_visitor();
6468    v->ctx = ctx;
6469    v->prog = prog;
6470    v->shader_program = shader_program;
6471    v->shader = shader;
6472    v->options = options;
6473    v->glsl_version = ctx->Const.GLSLVersion;
6474    v->native_integers = ctx->Const.NativeIntegers;
6475
6476    v->have_sqrt = pscreen->get_shader_param(pscreen, ptarget,
6477                                             PIPE_SHADER_CAP_TGSI_SQRT_SUPPORTED);
6478    v->have_fma = pscreen->get_shader_param(pscreen, ptarget,
6479                                            PIPE_SHADER_CAP_TGSI_FMA_SUPPORTED);
6480
6481    _mesa_copy_linked_program_data(shader->Stage, shader_program, prog);
6482    _mesa_generate_parameters_list_for_uniforms(shader_program, shader,
6483                                                prog->Parameters);
6484
6485    /* Remove reads from output registers. */
6486    lower_output_reads(shader->Stage, shader->ir);
6487
6488    /* Emit intermediate IR for main(). */
6489    visit_exec_list(shader->ir, v);
6490
6491    /* Now emit bodies for any functions that were used. */
6492    do {
6493       progress = GL_FALSE;
6494
6495       foreach_in_list(function_entry, entry, &v->function_signatures) {
6496          if (!entry->bgn_inst) {
6497             v->current_function = entry;
6498
6499             entry->bgn_inst = v->emit_asm(NULL, TGSI_OPCODE_BGNSUB);
6500             entry->bgn_inst->function = entry;
6501
6502             visit_exec_list(&entry->sig->body, v);
6503
6504             glsl_to_tgsi_instruction *last;
6505             last = (glsl_to_tgsi_instruction *)v->instructions.get_tail();
6506             if (last->op != TGSI_OPCODE_RET)
6507                v->emit_asm(NULL, TGSI_OPCODE_RET);
6508
6509             glsl_to_tgsi_instruction *end;
6510             end = v->emit_asm(NULL, TGSI_OPCODE_ENDSUB);
6511             end->function = entry;
6512
6513             progress = GL_TRUE;
6514          }
6515       }
6516    } while (progress);
6517
6518 #if 0
6519    /* Print out some information (for debugging purposes) used by the
6520     * optimization passes. */
6521    {
6522       int i;
6523       int *first_writes = rzalloc_array(v->mem_ctx, int, v->next_temp);
6524       int *first_reads = rzalloc_array(v->mem_ctx, int, v->next_temp);
6525       int *last_writes = rzalloc_array(v->mem_ctx, int, v->next_temp);
6526       int *last_reads = rzalloc_array(v->mem_ctx, int, v->next_temp);
6527
6528       for (i = 0; i < v->next_temp; i++) {
6529          first_writes[i] = -1;
6530          first_reads[i] = -1;
6531          last_writes[i] = -1;
6532          last_reads[i] = -1;
6533       }
6534       v->get_first_temp_read(first_reads);
6535       v->get_last_temp_read_first_temp_write(last_reads, first_writes);
6536       v->get_last_temp_write(last_writes);
6537       for (i = 0; i < v->next_temp; i++)
6538          printf("Temp %d: FR=%3d FW=%3d LR=%3d LW=%3d\n", i, first_reads[i],
6539                 first_writes[i],
6540                 last_reads[i],
6541                 last_writes[i]);
6542       ralloc_free(first_writes);
6543       ralloc_free(first_reads);
6544       ralloc_free(last_writes);
6545       ralloc_free(last_reads);
6546    }
6547 #endif
6548
6549    /* Perform optimizations on the instructions in the glsl_to_tgsi_visitor. */
6550    v->simplify_cmp();
6551
6552    if (shader->Type != GL_TESS_CONTROL_SHADER &&
6553        shader->Type != GL_TESS_EVALUATION_SHADER)
6554       v->copy_propagate();
6555
6556    while (v->eliminate_dead_code());
6557
6558    v->merge_two_dsts();
6559    v->merge_registers();
6560    v->renumber_registers();
6561
6562    /* Write the END instruction. */
6563    v->emit_asm(NULL, TGSI_OPCODE_END);
6564
6565    if (ctx->_Shader->Flags & GLSL_DUMP) {
6566       _mesa_log("\n");
6567       _mesa_log("GLSL IR for linked %s program %d:\n",
6568              _mesa_shader_stage_to_string(shader->Stage),
6569              shader_program->Name);
6570       _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
6571       _mesa_log("\n\n");
6572    }
6573
6574    prog->Instructions = NULL;
6575    prog->NumInstructions = 0;
6576
6577    do_set_program_inouts(shader->ir, prog, shader->Stage);
6578    shrink_array_declarations(v->input_arrays, v->num_input_arrays,
6579                              prog->InputsRead, prog->DoubleInputsRead, prog->PatchInputsRead);
6580    shrink_array_declarations(v->output_arrays, v->num_output_arrays,
6581                              prog->OutputsWritten, 0ULL, prog->PatchOutputsWritten);
6582    count_resources(v, prog);
6583
6584    /* The GLSL IR won't be needed anymore. */
6585    ralloc_free(shader->ir);
6586    shader->ir = NULL;
6587
6588    /* This must be done before the uniform storage is associated. */
6589    if (shader->Type == GL_FRAGMENT_SHADER &&
6590        (prog->InputsRead & VARYING_BIT_POS ||
6591         prog->SystemValuesRead & (1 << SYSTEM_VALUE_FRAG_COORD))) {
6592       static const gl_state_index wposTransformState[STATE_LENGTH] = {
6593          STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
6594       };
6595
6596       v->wpos_transform_const = _mesa_add_state_reference(prog->Parameters,
6597                                                           wposTransformState);
6598    }
6599
6600    _mesa_reference_program(ctx, &shader->Program, prog);
6601
6602    /* Avoid reallocation of the program parameter list, because the uniform
6603     * storage is only associated with the original parameter list.
6604     * This should be enough for Bitmap and DrawPixels constants.
6605     */
6606    _mesa_reserve_parameter_storage(prog->Parameters, 8);
6607
6608    /* This has to be done last.  Any operation the can cause
6609     * prog->ParameterValues to get reallocated (e.g., anything that adds a
6610     * program constant) has to happen before creating this linkage.
6611     */
6612    _mesa_associate_uniform_storage(ctx, shader_program, prog->Parameters);
6613    if (!shader_program->LinkStatus) {
6614       free_glsl_to_tgsi_visitor(v);
6615       return NULL;
6616    }
6617
6618    struct st_vertex_program *stvp;
6619    struct st_fragment_program *stfp;
6620    struct st_geometry_program *stgp;
6621    struct st_tessctrl_program *sttcp;
6622    struct st_tesseval_program *sttep;
6623    struct st_compute_program *stcp;
6624
6625    switch (shader->Type) {
6626    case GL_VERTEX_SHADER:
6627       stvp = (struct st_vertex_program *)prog;
6628       stvp->glsl_to_tgsi = v;
6629       break;
6630    case GL_FRAGMENT_SHADER:
6631       stfp = (struct st_fragment_program *)prog;
6632       stfp->glsl_to_tgsi = v;
6633       break;
6634    case GL_GEOMETRY_SHADER:
6635       stgp = (struct st_geometry_program *)prog;
6636       stgp->glsl_to_tgsi = v;
6637       break;
6638    case GL_TESS_CONTROL_SHADER:
6639       sttcp = (struct st_tessctrl_program *)prog;
6640       sttcp->glsl_to_tgsi = v;
6641       break;
6642    case GL_TESS_EVALUATION_SHADER:
6643       sttep = (struct st_tesseval_program *)prog;
6644       sttep->glsl_to_tgsi = v;
6645       break;
6646    case GL_COMPUTE_SHADER:
6647       stcp = (struct st_compute_program *)prog;
6648       stcp->glsl_to_tgsi = v;
6649       break;
6650    default:
6651       assert(!"should not be reached");
6652       return NULL;
6653    }
6654
6655    return prog;
6656 }
6657
6658 static struct gl_program *
6659 get_mesa_program(struct gl_context *ctx,
6660                  struct gl_shader_program *shader_program,
6661                  struct gl_shader *shader)
6662 {
6663    struct pipe_screen *pscreen = ctx->st->pipe->screen;
6664    unsigned ptarget = st_shader_stage_to_ptarget(shader->Stage);
6665    enum pipe_shader_ir preferred_ir = (enum pipe_shader_ir)
6666       pscreen->get_shader_param(pscreen, ptarget, PIPE_SHADER_CAP_PREFERRED_IR);
6667    if (preferred_ir == PIPE_SHADER_IR_NIR) {
6668       /* TODO only for GLSL VS/FS for now: */
6669       switch (shader->Type) {
6670       case GL_VERTEX_SHADER:
6671       case GL_FRAGMENT_SHADER:
6672          return st_nir_get_mesa_program(ctx, shader_program, shader);
6673       default:
6674          break;
6675       }
6676    }
6677    return get_mesa_program_tgsi(ctx, shader_program, shader);
6678 }
6679
6680
6681 extern "C" {
6682
6683 static void
6684 st_dump_program_for_shader_db(struct gl_context *ctx,
6685                               struct gl_shader_program *prog)
6686 {
6687    /* Dump only successfully compiled and linked shaders to the specified
6688     * file. This is for shader-db.
6689     *
6690     * These options allow some pre-processing of shaders while dumping,
6691     * because some apps have ill-formed shaders.
6692     */
6693    const char *dump_filename = os_get_option("ST_DUMP_SHADERS");
6694    const char *insert_directives = os_get_option("ST_DUMP_INSERT");
6695
6696    if (dump_filename && prog->Name != 0) {
6697       FILE *f = fopen(dump_filename, "a");
6698
6699       if (f) {
6700          for (unsigned i = 0; i < prog->NumShaders; i++) {
6701             const struct gl_shader *sh = prog->Shaders[i];
6702             const char *source;
6703             bool skip_version = false;
6704
6705             if (!sh)
6706                continue;
6707
6708             source = sh->Source;
6709
6710             /* This string mustn't be changed. shader-db uses it to find
6711              * where the shader begins.
6712              */
6713             fprintf(f, "GLSL %s shader %d source for linked program %d:\n",
6714                     _mesa_shader_stage_to_string(sh->Stage),
6715                     i, prog->Name);
6716
6717             /* Dump the forced version if set. */
6718             if (ctx->Const.ForceGLSLVersion) {
6719                fprintf(f, "#version %i\n", ctx->Const.ForceGLSLVersion);
6720                skip_version = true;
6721             }
6722
6723             /* Insert directives (optional). */
6724             if (insert_directives) {
6725                if (!ctx->Const.ForceGLSLVersion && prog->Version)
6726                   fprintf(f, "#version %i\n", prog->Version);
6727                fprintf(f, "%s\n", insert_directives);
6728                skip_version = true;
6729             }
6730
6731             if (skip_version && strncmp(source, "#version ", 9) == 0) {
6732                const char *next_line = strstr(source, "\n");
6733
6734                if (next_line)
6735                   source = next_line + 1;
6736                else
6737                   continue;
6738             }
6739
6740             fprintf(f, "%s", source);
6741             fprintf(f, "\n");
6742          }
6743          fclose(f);
6744       }
6745    }
6746 }
6747
6748 /**
6749  * Link a shader.
6750  * Called via ctx->Driver.LinkShader()
6751  * This actually involves converting GLSL IR into an intermediate TGSI-like IR
6752  * with code lowering and other optimizations.
6753  */
6754 GLboolean
6755 st_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
6756 {
6757    struct pipe_screen *pscreen = ctx->st->pipe->screen;
6758    assert(prog->LinkStatus);
6759
6760    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
6761       if (prog->_LinkedShaders[i] == NULL)
6762          continue;
6763
6764       bool progress;
6765       exec_list *ir = prog->_LinkedShaders[i]->ir;
6766       gl_shader_stage stage = _mesa_shader_enum_to_shader_stage(prog->_LinkedShaders[i]->Type);
6767       const struct gl_shader_compiler_options *options =
6768             &ctx->Const.ShaderCompilerOptions[stage];
6769       unsigned ptarget = st_shader_stage_to_ptarget(stage);
6770       bool have_dround = pscreen->get_shader_param(pscreen, ptarget,
6771                                                    PIPE_SHADER_CAP_TGSI_DROUND_SUPPORTED);
6772       bool have_dfrexp = pscreen->get_shader_param(pscreen, ptarget,
6773                                                    PIPE_SHADER_CAP_TGSI_DFRACEXP_DLDEXP_SUPPORTED);
6774
6775       /* If there are forms of indirect addressing that the driver
6776        * cannot handle, perform the lowering pass.
6777        */
6778       if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput ||
6779           options->EmitNoIndirectTemp || options->EmitNoIndirectUniform) {
6780          lower_variable_index_to_cond_assign(prog->_LinkedShaders[i]->Stage, ir,
6781                                              options->EmitNoIndirectInput,
6782                                              options->EmitNoIndirectOutput,
6783                                              options->EmitNoIndirectTemp,
6784                                              options->EmitNoIndirectUniform);
6785       }
6786
6787       if (ctx->Extensions.ARB_shading_language_packing) {
6788          unsigned lower_inst = LOWER_PACK_SNORM_2x16 |
6789                                LOWER_UNPACK_SNORM_2x16 |
6790                                LOWER_PACK_UNORM_2x16 |
6791                                LOWER_UNPACK_UNORM_2x16 |
6792                                LOWER_PACK_SNORM_4x8 |
6793                                LOWER_UNPACK_SNORM_4x8 |
6794                                LOWER_UNPACK_UNORM_4x8 |
6795                                LOWER_PACK_UNORM_4x8;
6796
6797          if (ctx->Extensions.ARB_gpu_shader5)
6798             lower_inst |= LOWER_PACK_USE_BFI |
6799                           LOWER_PACK_USE_BFE;
6800          if (!ctx->st->has_half_float_packing)
6801             lower_inst |= LOWER_PACK_HALF_2x16 |
6802                           LOWER_UNPACK_HALF_2x16;
6803
6804          lower_packing_builtins(ir, lower_inst);
6805       }
6806
6807       if (!pscreen->get_param(pscreen, PIPE_CAP_TEXTURE_GATHER_OFFSETS))
6808          lower_offset_arrays(ir);
6809       do_mat_op_to_vec(ir);
6810       lower_instructions(ir,
6811                          MOD_TO_FLOOR |
6812                          DIV_TO_MUL_RCP |
6813                          EXP_TO_EXP2 |
6814                          LOG_TO_LOG2 |
6815                          LDEXP_TO_ARITH |
6816                          (have_dfrexp ? 0 : DFREXP_DLDEXP_TO_ARITH) |
6817                          CARRY_TO_ARITH |
6818                          BORROW_TO_ARITH |
6819                          (have_dround ? 0 : DOPS_TO_DFRAC) |
6820                          (options->EmitNoPow ? POW_TO_EXP2 : 0) |
6821                          (!ctx->Const.NativeIntegers ? INT_DIV_TO_MUL_RCP : 0) |
6822                          (options->EmitNoSat ? SAT_TO_CLAMP : 0));
6823
6824       do_vec_index_to_cond_assign(ir);
6825       lower_vector_insert(ir, true);
6826       lower_quadop_vector(ir, false);
6827       lower_noise(ir);
6828       if (options->MaxIfDepth == 0) {
6829          lower_discard(ir);
6830       }
6831
6832       do {
6833          progress = false;
6834
6835          progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
6836
6837          progress = do_common_optimization(ir, true, true, options,
6838                                            ctx->Const.NativeIntegers)
6839            || progress;
6840
6841          progress = lower_if_to_cond_assign(ir, options->MaxIfDepth) || progress;
6842
6843       } while (progress);
6844
6845       validate_ir_tree(ir);
6846    }
6847
6848    build_program_resource_list(ctx, prog);
6849
6850    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
6851       struct gl_program *linked_prog;
6852
6853       if (prog->_LinkedShaders[i] == NULL)
6854          continue;
6855
6856       linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
6857
6858       if (linked_prog) {
6859          _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
6860                                  linked_prog);
6861          if (!ctx->Driver.ProgramStringNotify(ctx,
6862                                               _mesa_shader_stage_to_program(i),
6863                                               linked_prog)) {
6864             _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
6865                                     NULL);
6866             _mesa_reference_program(ctx, &linked_prog, NULL);
6867             return GL_FALSE;
6868          }
6869       }
6870
6871       _mesa_reference_program(ctx, &linked_prog, NULL);
6872    }
6873
6874    st_dump_program_for_shader_db(ctx, prog);
6875    return GL_TRUE;
6876 }
6877
6878 void
6879 st_translate_stream_output_info(glsl_to_tgsi_visitor *glsl_to_tgsi,
6880                                 const GLuint outputMapping[],
6881                                 struct pipe_stream_output_info *so)
6882 {
6883    struct gl_transform_feedback_info *info =
6884       &glsl_to_tgsi->shader_program->LinkedTransformFeedback;
6885    st_translate_stream_output_info2(info, outputMapping, so);
6886 }
6887
6888 void
6889 st_translate_stream_output_info2(struct gl_transform_feedback_info *info,
6890                                 const GLuint outputMapping[],
6891                                 struct pipe_stream_output_info *so)
6892 {
6893    unsigned i;
6894
6895    for (i = 0; i < info->NumOutputs; i++) {
6896       so->output[i].register_index =
6897          outputMapping[info->Outputs[i].OutputRegister];
6898       so->output[i].start_component = info->Outputs[i].ComponentOffset;
6899       so->output[i].num_components = info->Outputs[i].NumComponents;
6900       so->output[i].output_buffer = info->Outputs[i].OutputBuffer;
6901       so->output[i].dst_offset = info->Outputs[i].DstOffset;
6902       so->output[i].stream = info->Outputs[i].StreamId;
6903    }
6904
6905    for (i = 0; i < PIPE_MAX_SO_BUFFERS; i++) {
6906       so->stride[i] = info->Buffers[i].Stride;
6907    }
6908    so->num_outputs = info->NumOutputs;
6909 }
6910
6911 } /* extern "C" */