OSDN Git Service

i965/fs: Gen4-5: Implement alpha test in shader for MRT
[android-x86/external-mesa.git] / src / mesa / drivers / dri / i965 / brw_fs_visitor.cpp
1 /*
2  * Copyright © 2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23
24 /** @file brw_fs_visitor.cpp
25  *
26  * This file supports generating the FS LIR from the GLSL IR.  The LIR
27  * makes it easier to do backend-specific optimizations than doing so
28  * in the GLSL IR or in the native code.
29  */
30 extern "C" {
31
32 #include <sys/types.h>
33
34 #include "main/macros.h"
35 #include "main/shaderobj.h"
36 #include "program/prog_parameter.h"
37 #include "program/prog_print.h"
38 #include "program/prog_optimize.h"
39 #include "program/register_allocate.h"
40 #include "program/sampler.h"
41 #include "program/hash_table.h"
42 #include "brw_context.h"
43 #include "brw_eu.h"
44 #include "brw_wm.h"
45 }
46 #include "brw_fs.h"
47 #include "main/uniforms.h"
48 #include "glsl/glsl_types.h"
49 #include "glsl/ir_optimization.h"
50
51 void
52 fs_visitor::visit(ir_variable *ir)
53 {
54    fs_reg *reg = NULL;
55
56    if (variable_storage(ir))
57       return;
58
59    if (ir->mode == ir_var_shader_in) {
60       if (!strcmp(ir->name, "gl_FragCoord")) {
61          reg = emit_fragcoord_interpolation(ir);
62       } else if (!strcmp(ir->name, "gl_FrontFacing")) {
63          reg = emit_frontfacing_interpolation(ir);
64       } else {
65          reg = emit_general_interpolation(ir);
66       }
67       assert(reg);
68       hash_table_insert(this->variable_ht, reg, ir);
69       return;
70    } else if (ir->mode == ir_var_shader_out) {
71       reg = new(this->mem_ctx) fs_reg(this, ir->type);
72
73       if (ir->index > 0) {
74          assert(ir->location == FRAG_RESULT_DATA0);
75          assert(ir->index == 1);
76          this->dual_src_output = *reg;
77       } else if (ir->location == FRAG_RESULT_COLOR) {
78          /* Writing gl_FragColor outputs to all color regions. */
79          for (unsigned int i = 0; i < MAX2(c->key.nr_color_regions, 1); i++) {
80             this->outputs[i] = *reg;
81             this->output_components[i] = 4;
82          }
83       } else if (ir->location == FRAG_RESULT_DEPTH) {
84          this->frag_depth = *reg;
85       } else if (ir->location == FRAG_RESULT_SAMPLE_MASK) {
86          this->sample_mask = *reg;
87       } else {
88          /* gl_FragData or a user-defined FS output */
89          assert(ir->location >= FRAG_RESULT_DATA0 &&
90                 ir->location < FRAG_RESULT_DATA0 + BRW_MAX_DRAW_BUFFERS);
91
92          int vector_elements =
93             ir->type->is_array() ? ir->type->fields.array->vector_elements
94                                  : ir->type->vector_elements;
95
96          /* General color output. */
97          for (unsigned int i = 0; i < MAX2(1, ir->type->length); i++) {
98             int output = ir->location - FRAG_RESULT_DATA0 + i;
99             this->outputs[output] = *reg;
100             this->outputs[output].reg_offset += vector_elements * i;
101             this->output_components[output] = vector_elements;
102          }
103       }
104    } else if (ir->mode == ir_var_uniform) {
105       int param_index = c->prog_data.nr_params;
106
107       /* Thanks to the lower_ubo_reference pass, we will see only
108        * ir_binop_ubo_load expressions and not ir_dereference_variable for UBO
109        * variables, so no need for them to be in variable_ht.
110        *
111        * Atomic counters take no uniform storage, no need to do
112        * anything here.
113        */
114       if (ir->is_in_uniform_block() || ir->type->contains_atomic())
115          return;
116
117       if (dispatch_width == 16) {
118          if (!variable_storage(ir)) {
119             fail("Failed to find uniform '%s' in 16-wide\n", ir->name);
120          }
121          return;
122       }
123
124       param_size[param_index] = type_size(ir->type);
125       if (!strncmp(ir->name, "gl_", 3)) {
126          setup_builtin_uniform_values(ir);
127       } else {
128          setup_uniform_values(ir);
129       }
130
131       reg = new(this->mem_ctx) fs_reg(UNIFORM, param_index);
132       reg->type = brw_type_for_base_type(ir->type);
133
134    } else if (ir->mode == ir_var_system_value) {
135       if (ir->location == SYSTEM_VALUE_SAMPLE_POS) {
136          reg = emit_samplepos_setup(ir);
137       } else if (ir->location == SYSTEM_VALUE_SAMPLE_ID) {
138          reg = emit_sampleid_setup(ir);
139       }
140    }
141
142    if (!reg)
143       reg = new(this->mem_ctx) fs_reg(this, ir->type);
144
145    hash_table_insert(this->variable_ht, reg, ir);
146 }
147
148 void
149 fs_visitor::visit(ir_dereference_variable *ir)
150 {
151    fs_reg *reg = variable_storage(ir->var);
152    this->result = *reg;
153 }
154
155 void
156 fs_visitor::visit(ir_dereference_record *ir)
157 {
158    const glsl_type *struct_type = ir->record->type;
159
160    ir->record->accept(this);
161
162    unsigned int offset = 0;
163    for (unsigned int i = 0; i < struct_type->length; i++) {
164       if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
165          break;
166       offset += type_size(struct_type->fields.structure[i].type);
167    }
168    this->result.reg_offset += offset;
169    this->result.type = brw_type_for_base_type(ir->type);
170 }
171
172 void
173 fs_visitor::visit(ir_dereference_array *ir)
174 {
175    ir_constant *constant_index;
176    fs_reg src;
177    int element_size = type_size(ir->type);
178
179    constant_index = ir->array_index->as_constant();
180
181    ir->array->accept(this);
182    src = this->result;
183    src.type = brw_type_for_base_type(ir->type);
184
185    if (constant_index) {
186       assert(src.file == UNIFORM || src.file == GRF);
187       src.reg_offset += constant_index->value.i[0] * element_size;
188    } else {
189       /* Variable index array dereference.  We attach the variable index
190        * component to the reg as a pointer to a register containing the
191        * offset.  Currently only uniform arrays are supported in this patch,
192        * and that reladdr pointer is resolved by
193        * move_uniform_array_access_to_pull_constants().  All other array types
194        * are lowered by lower_variable_index_to_cond_assign().
195        */
196       ir->array_index->accept(this);
197
198       fs_reg index_reg;
199       index_reg = fs_reg(this, glsl_type::int_type);
200       emit(BRW_OPCODE_MUL, index_reg, this->result, fs_reg(element_size));
201
202       if (src.reladdr) {
203          emit(BRW_OPCODE_ADD, index_reg, *src.reladdr, index_reg);
204       }
205
206       src.reladdr = ralloc(mem_ctx, fs_reg);
207       memcpy(src.reladdr, &index_reg, sizeof(index_reg));
208    }
209    this->result = src;
210 }
211
212 void
213 fs_visitor::emit_lrp(fs_reg dst, fs_reg x, fs_reg y, fs_reg a)
214 {
215    if (brw->gen < 6 ||
216        !x.is_valid_3src() ||
217        !y.is_valid_3src() ||
218        !a.is_valid_3src()) {
219       /* We can't use the LRP instruction.  Emit x*(1-a) + y*a. */
220       fs_reg y_times_a           = fs_reg(this, glsl_type::float_type);
221       fs_reg one_minus_a         = fs_reg(this, glsl_type::float_type);
222       fs_reg x_times_one_minus_a = fs_reg(this, glsl_type::float_type);
223
224       emit(MUL(y_times_a, y, a));
225
226       a.negate = !a.negate;
227       emit(ADD(one_minus_a, a, fs_reg(1.0f)));
228       emit(MUL(x_times_one_minus_a, x, one_minus_a));
229
230       emit(ADD(dst, x_times_one_minus_a, y_times_a));
231    } else {
232       /* The LRP instruction actually does op1 * op0 + op2 * (1 - op0), so
233        * we need to reorder the operands.
234        */
235       emit(LRP(dst, a, y, x));
236    }
237 }
238
239 void
240 fs_visitor::emit_minmax(uint32_t conditionalmod, fs_reg dst,
241                         fs_reg src0, fs_reg src1)
242 {
243    fs_inst *inst;
244
245    if (brw->gen >= 6) {
246       inst = emit(BRW_OPCODE_SEL, dst, src0, src1);
247       inst->conditional_mod = conditionalmod;
248    } else {
249       emit(CMP(reg_null_d, src0, src1, conditionalmod));
250
251       inst = emit(BRW_OPCODE_SEL, dst, src0, src1);
252       inst->predicate = BRW_PREDICATE_NORMAL;
253    }
254 }
255
256 /* Instruction selection: Produce a MOV.sat instead of
257  * MIN(MAX(val, 0), 1) when possible.
258  */
259 bool
260 fs_visitor::try_emit_saturate(ir_expression *ir)
261 {
262    ir_rvalue *sat_val = ir->as_rvalue_to_saturate();
263
264    if (!sat_val)
265       return false;
266
267    fs_inst *pre_inst = (fs_inst *) this->instructions.get_tail();
268
269    sat_val->accept(this);
270    fs_reg src = this->result;
271
272    fs_inst *last_inst = (fs_inst *) this->instructions.get_tail();
273
274    /* If the last instruction from our accept() didn't generate our
275     * src, generate a saturated MOV
276     */
277    fs_inst *modify = get_instruction_generating_reg(pre_inst, last_inst, src);
278    if (!modify || modify->regs_written != 1) {
279       this->result = fs_reg(this, ir->type);
280       fs_inst *inst = emit(MOV(this->result, src));
281       inst->saturate = true;
282    } else {
283       modify->saturate = true;
284       this->result = src;
285    }
286
287
288    return true;
289 }
290
291 bool
292 fs_visitor::try_emit_mad(ir_expression *ir, int mul_arg)
293 {
294    /* 3-src instructions were introduced in gen6. */
295    if (brw->gen < 6)
296       return false;
297
298    /* MAD can only handle floating-point data. */
299    if (ir->type != glsl_type::float_type)
300       return false;
301
302    ir_rvalue *nonmul = ir->operands[1 - mul_arg];
303    ir_expression *mul = ir->operands[mul_arg]->as_expression();
304
305    if (!mul || mul->operation != ir_binop_mul)
306       return false;
307
308    if (nonmul->as_constant() ||
309        mul->operands[0]->as_constant() ||
310        mul->operands[1]->as_constant())
311       return false;
312
313    nonmul->accept(this);
314    fs_reg src0 = this->result;
315
316    mul->operands[0]->accept(this);
317    fs_reg src1 = this->result;
318
319    mul->operands[1]->accept(this);
320    fs_reg src2 = this->result;
321
322    this->result = fs_reg(this, ir->type);
323    emit(BRW_OPCODE_MAD, this->result, src0, src1, src2);
324
325    return true;
326 }
327
328 void
329 fs_visitor::visit(ir_expression *ir)
330 {
331    unsigned int operand;
332    fs_reg op[3], temp;
333    fs_inst *inst;
334
335    assert(ir->get_num_operands() <= 3);
336
337    if (try_emit_saturate(ir))
338       return;
339    if (ir->operation == ir_binop_add) {
340       if (try_emit_mad(ir, 0) || try_emit_mad(ir, 1))
341          return;
342    }
343
344    for (operand = 0; operand < ir->get_num_operands(); operand++) {
345       ir->operands[operand]->accept(this);
346       if (this->result.file == BAD_FILE) {
347          fail("Failed to get tree for expression operand:\n");
348          ir->operands[operand]->print();
349          printf("\n");
350       }
351       assert(this->result.is_valid_3src());
352       op[operand] = this->result;
353
354       /* Matrix expression operands should have been broken down to vector
355        * operations already.
356        */
357       assert(!ir->operands[operand]->type->is_matrix());
358       /* And then those vector operands should have been broken down to scalar.
359        */
360       assert(!ir->operands[operand]->type->is_vector());
361    }
362
363    /* Storage for our result.  If our result goes into an assignment, it will
364     * just get copy-propagated out, so no worries.
365     */
366    this->result = fs_reg(this, ir->type);
367
368    switch (ir->operation) {
369    case ir_unop_logic_not:
370       /* Note that BRW_OPCODE_NOT is not appropriate here, since it is
371        * ones complement of the whole register, not just bit 0.
372        */
373       emit(XOR(this->result, op[0], fs_reg(1)));
374       break;
375    case ir_unop_neg:
376       op[0].negate = !op[0].negate;
377       emit(MOV(this->result, op[0]));
378       break;
379    case ir_unop_abs:
380       op[0].abs = true;
381       op[0].negate = false;
382       emit(MOV(this->result, op[0]));
383       break;
384    case ir_unop_sign:
385       temp = fs_reg(this, ir->type);
386
387       emit(MOV(this->result, fs_reg(0.0f)));
388
389       emit(CMP(reg_null_f, op[0], fs_reg(0.0f), BRW_CONDITIONAL_G));
390       inst = emit(MOV(this->result, fs_reg(1.0f)));
391       inst->predicate = BRW_PREDICATE_NORMAL;
392
393       emit(CMP(reg_null_f, op[0], fs_reg(0.0f), BRW_CONDITIONAL_L));
394       inst = emit(MOV(this->result, fs_reg(-1.0f)));
395       inst->predicate = BRW_PREDICATE_NORMAL;
396
397       break;
398    case ir_unop_rcp:
399       emit_math(SHADER_OPCODE_RCP, this->result, op[0]);
400       break;
401
402    case ir_unop_exp2:
403       emit_math(SHADER_OPCODE_EXP2, this->result, op[0]);
404       break;
405    case ir_unop_log2:
406       emit_math(SHADER_OPCODE_LOG2, this->result, op[0]);
407       break;
408    case ir_unop_exp:
409    case ir_unop_log:
410       assert(!"not reached: should be handled by ir_explog_to_explog2");
411       break;
412    case ir_unop_sin:
413    case ir_unop_sin_reduced:
414       emit_math(SHADER_OPCODE_SIN, this->result, op[0]);
415       break;
416    case ir_unop_cos:
417    case ir_unop_cos_reduced:
418       emit_math(SHADER_OPCODE_COS, this->result, op[0]);
419       break;
420
421    case ir_unop_dFdx:
422       emit(FS_OPCODE_DDX, this->result, op[0]);
423       break;
424    case ir_unop_dFdy:
425       emit(FS_OPCODE_DDY, this->result, op[0]);
426       break;
427
428    case ir_binop_add:
429       emit(ADD(this->result, op[0], op[1]));
430       break;
431    case ir_binop_sub:
432       assert(!"not reached: should be handled by ir_sub_to_add_neg");
433       break;
434
435    case ir_binop_mul:
436       if (ir->type->is_integer()) {
437          /* For integer multiplication, the MUL uses the low 16 bits
438           * of one of the operands (src0 on gen6, src1 on gen7).  The
439           * MACH accumulates in the contribution of the upper 16 bits
440           * of that operand.
441           *
442           * FINISHME: Emit just the MUL if we know an operand is small
443           * enough.
444           */
445          if (brw->gen >= 7 && dispatch_width == 16)
446             fail("16-wide explicit accumulator operands unsupported\n");
447
448          struct brw_reg acc = retype(brw_acc_reg(), this->result.type);
449
450          emit(MUL(acc, op[0], op[1]));
451          emit(MACH(reg_null_d, op[0], op[1]));
452          emit(MOV(this->result, fs_reg(acc)));
453       } else {
454          emit(MUL(this->result, op[0], op[1]));
455       }
456       break;
457    case ir_binop_imul_high: {
458       if (brw->gen >= 7 && dispatch_width == 16)
459          fail("16-wide explicit accumulator operands unsupported\n");
460
461       struct brw_reg acc = retype(brw_acc_reg(), this->result.type);
462
463       emit(MUL(acc, op[0], op[1]));
464       emit(MACH(this->result, op[0], op[1]));
465       break;
466    }
467    case ir_binop_div:
468       /* Floating point should be lowered by DIV_TO_MUL_RCP in the compiler. */
469       assert(ir->type->is_integer());
470       emit_math(SHADER_OPCODE_INT_QUOTIENT, this->result, op[0], op[1]);
471       break;
472    case ir_binop_carry: {
473       if (brw->gen >= 7 && dispatch_width == 16)
474          fail("16-wide explicit accumulator operands unsupported\n");
475
476       struct brw_reg acc = retype(brw_acc_reg(), BRW_REGISTER_TYPE_UD);
477
478       emit(ADDC(reg_null_ud, op[0], op[1]));
479       emit(MOV(this->result, fs_reg(acc)));
480       break;
481    }
482    case ir_binop_borrow: {
483       if (brw->gen >= 7 && dispatch_width == 16)
484          fail("16-wide explicit accumulator operands unsupported\n");
485
486       struct brw_reg acc = retype(brw_acc_reg(), BRW_REGISTER_TYPE_UD);
487
488       emit(SUBB(reg_null_ud, op[0], op[1]));
489       emit(MOV(this->result, fs_reg(acc)));
490       break;
491    }
492    case ir_binop_mod:
493       /* Floating point should be lowered by MOD_TO_FRACT in the compiler. */
494       assert(ir->type->is_integer());
495       emit_math(SHADER_OPCODE_INT_REMAINDER, this->result, op[0], op[1]);
496       break;
497
498    case ir_binop_less:
499    case ir_binop_greater:
500    case ir_binop_lequal:
501    case ir_binop_gequal:
502    case ir_binop_equal:
503    case ir_binop_all_equal:
504    case ir_binop_nequal:
505    case ir_binop_any_nequal:
506       resolve_bool_comparison(ir->operands[0], &op[0]);
507       resolve_bool_comparison(ir->operands[1], &op[1]);
508
509       emit(CMP(this->result, op[0], op[1],
510                brw_conditional_for_comparison(ir->operation)));
511       break;
512
513    case ir_binop_logic_xor:
514       emit(XOR(this->result, op[0], op[1]));
515       break;
516
517    case ir_binop_logic_or:
518       emit(OR(this->result, op[0], op[1]));
519       break;
520
521    case ir_binop_logic_and:
522       emit(AND(this->result, op[0], op[1]));
523       break;
524
525    case ir_binop_dot:
526    case ir_unop_any:
527       assert(!"not reached: should be handled by brw_fs_channel_expressions");
528       break;
529
530    case ir_unop_noise:
531       assert(!"not reached: should be handled by lower_noise");
532       break;
533
534    case ir_quadop_vector:
535       assert(!"not reached: should be handled by lower_quadop_vector");
536       break;
537
538    case ir_binop_vector_extract:
539       assert(!"not reached: should be handled by lower_vec_index_to_cond_assign()");
540       break;
541
542    case ir_triop_vector_insert:
543       assert(!"not reached: should be handled by lower_vector_insert()");
544       break;
545
546    case ir_binop_ldexp:
547       assert(!"not reached: should be handled by ldexp_to_arith()");
548       break;
549
550    case ir_unop_sqrt:
551       emit_math(SHADER_OPCODE_SQRT, this->result, op[0]);
552       break;
553
554    case ir_unop_rsq:
555       emit_math(SHADER_OPCODE_RSQ, this->result, op[0]);
556       break;
557
558    case ir_unop_bitcast_i2f:
559    case ir_unop_bitcast_u2f:
560       op[0].type = BRW_REGISTER_TYPE_F;
561       this->result = op[0];
562       break;
563    case ir_unop_i2u:
564    case ir_unop_bitcast_f2u:
565       op[0].type = BRW_REGISTER_TYPE_UD;
566       this->result = op[0];
567       break;
568    case ir_unop_u2i:
569    case ir_unop_bitcast_f2i:
570       op[0].type = BRW_REGISTER_TYPE_D;
571       this->result = op[0];
572       break;
573    case ir_unop_i2f:
574    case ir_unop_u2f:
575    case ir_unop_f2i:
576    case ir_unop_f2u:
577       emit(MOV(this->result, op[0]));
578       break;
579
580    case ir_unop_b2i:
581       emit(AND(this->result, op[0], fs_reg(1)));
582       break;
583    case ir_unop_b2f:
584       temp = fs_reg(this, glsl_type::int_type);
585       emit(AND(temp, op[0], fs_reg(1)));
586       emit(MOV(this->result, temp));
587       break;
588
589    case ir_unop_f2b:
590       emit(CMP(this->result, op[0], fs_reg(0.0f), BRW_CONDITIONAL_NZ));
591       break;
592    case ir_unop_i2b:
593       emit(CMP(this->result, op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
594       break;
595
596    case ir_unop_trunc:
597       emit(RNDZ(this->result, op[0]));
598       break;
599    case ir_unop_ceil:
600       op[0].negate = !op[0].negate;
601       emit(RNDD(this->result, op[0]));
602       this->result.negate = true;
603       break;
604    case ir_unop_floor:
605       emit(RNDD(this->result, op[0]));
606       break;
607    case ir_unop_fract:
608       emit(FRC(this->result, op[0]));
609       break;
610    case ir_unop_round_even:
611       emit(RNDE(this->result, op[0]));
612       break;
613
614    case ir_binop_min:
615    case ir_binop_max:
616       resolve_ud_negate(&op[0]);
617       resolve_ud_negate(&op[1]);
618       emit_minmax(ir->operation == ir_binop_min ?
619                   BRW_CONDITIONAL_L : BRW_CONDITIONAL_GE,
620                   this->result, op[0], op[1]);
621       break;
622    case ir_unop_pack_snorm_2x16:
623    case ir_unop_pack_snorm_4x8:
624    case ir_unop_pack_unorm_2x16:
625    case ir_unop_pack_unorm_4x8:
626    case ir_unop_unpack_snorm_2x16:
627    case ir_unop_unpack_snorm_4x8:
628    case ir_unop_unpack_unorm_2x16:
629    case ir_unop_unpack_unorm_4x8:
630    case ir_unop_unpack_half_2x16:
631    case ir_unop_pack_half_2x16:
632       assert(!"not reached: should be handled by lower_packing_builtins");
633       break;
634    case ir_unop_unpack_half_2x16_split_x:
635       emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_X, this->result, op[0]);
636       break;
637    case ir_unop_unpack_half_2x16_split_y:
638       emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_Y, this->result, op[0]);
639       break;
640    case ir_binop_pow:
641       emit_math(SHADER_OPCODE_POW, this->result, op[0], op[1]);
642       break;
643
644    case ir_unop_bitfield_reverse:
645       emit(BFREV(this->result, op[0]));
646       break;
647    case ir_unop_bit_count:
648       emit(CBIT(this->result, op[0]));
649       break;
650    case ir_unop_find_msb:
651       temp = fs_reg(this, glsl_type::uint_type);
652       emit(FBH(temp, op[0]));
653
654       /* FBH counts from the MSB side, while GLSL's findMSB() wants the count
655        * from the LSB side. If FBH didn't return an error (0xFFFFFFFF), then
656        * subtract the result from 31 to convert the MSB count into an LSB count.
657        */
658
659       /* FBH only supports UD type for dst, so use a MOV to convert UD to D. */
660       emit(MOV(this->result, temp));
661       emit(CMP(reg_null_d, this->result, fs_reg(-1), BRW_CONDITIONAL_NZ));
662
663       temp.negate = true;
664       inst = emit(ADD(this->result, temp, fs_reg(31)));
665       inst->predicate = BRW_PREDICATE_NORMAL;
666       break;
667    case ir_unop_find_lsb:
668       emit(FBL(this->result, op[0]));
669       break;
670    case ir_triop_bitfield_extract:
671       /* Note that the instruction's argument order is reversed from GLSL
672        * and the IR.
673        */
674       emit(BFE(this->result, op[2], op[1], op[0]));
675       break;
676    case ir_binop_bfm:
677       emit(BFI1(this->result, op[0], op[1]));
678       break;
679    case ir_triop_bfi:
680       emit(BFI2(this->result, op[0], op[1], op[2]));
681       break;
682    case ir_quadop_bitfield_insert:
683       assert(!"not reached: should be handled by "
684               "lower_instructions::bitfield_insert_to_bfm_bfi");
685       break;
686
687    case ir_unop_bit_not:
688       emit(NOT(this->result, op[0]));
689       break;
690    case ir_binop_bit_and:
691       emit(AND(this->result, op[0], op[1]));
692       break;
693    case ir_binop_bit_xor:
694       emit(XOR(this->result, op[0], op[1]));
695       break;
696    case ir_binop_bit_or:
697       emit(OR(this->result, op[0], op[1]));
698       break;
699
700    case ir_binop_lshift:
701       emit(SHL(this->result, op[0], op[1]));
702       break;
703
704    case ir_binop_rshift:
705       if (ir->type->base_type == GLSL_TYPE_INT)
706          emit(ASR(this->result, op[0], op[1]));
707       else
708          emit(SHR(this->result, op[0], op[1]));
709       break;
710    case ir_binop_pack_half_2x16_split:
711       emit(FS_OPCODE_PACK_HALF_2x16_SPLIT, this->result, op[0], op[1]);
712       break;
713    case ir_binop_ubo_load: {
714       /* This IR node takes a constant uniform block and a constant or
715        * variable byte offset within the block and loads a vector from that.
716        */
717       ir_constant *uniform_block = ir->operands[0]->as_constant();
718       ir_constant *const_offset = ir->operands[1]->as_constant();
719       fs_reg surf_index = fs_reg(c->prog_data.base.binding_table.ubo_start +
720                                  uniform_block->value.u[0]);
721       if (const_offset) {
722          fs_reg packed_consts = fs_reg(this, glsl_type::float_type);
723          packed_consts.type = result.type;
724
725          fs_reg const_offset_reg = fs_reg(const_offset->value.u[0] & ~15);
726          emit(fs_inst(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
727                       packed_consts, surf_index, const_offset_reg));
728
729          packed_consts.smear = const_offset->value.u[0] % 16 / 4;
730          for (int i = 0; i < ir->type->vector_elements; i++) {
731             /* UBO bools are any nonzero value.  We consider bools to be
732              * values with the low bit set to 1.  Convert them using CMP.
733              */
734             if (ir->type->base_type == GLSL_TYPE_BOOL) {
735                emit(CMP(result, packed_consts, fs_reg(0u), BRW_CONDITIONAL_NZ));
736             } else {
737                emit(MOV(result, packed_consts));
738             }
739
740             packed_consts.smear++;
741             result.reg_offset++;
742
743             /* The std140 packing rules don't allow vectors to cross 16-byte
744              * boundaries, and a reg is 32 bytes.
745              */
746             assert(packed_consts.smear < 8);
747          }
748       } else {
749          /* Turn the byte offset into a dword offset. */
750          fs_reg base_offset = fs_reg(this, glsl_type::int_type);
751          emit(SHR(base_offset, op[1], fs_reg(2)));
752
753          for (int i = 0; i < ir->type->vector_elements; i++) {
754             emit(VARYING_PULL_CONSTANT_LOAD(result, surf_index,
755                                             base_offset, i));
756
757             if (ir->type->base_type == GLSL_TYPE_BOOL)
758                emit(CMP(result, result, fs_reg(0), BRW_CONDITIONAL_NZ));
759
760             result.reg_offset++;
761          }
762       }
763
764       result.reg_offset = 0;
765       break;
766    }
767
768    case ir_triop_fma:
769       /* Note that the instruction's argument order is reversed from GLSL
770        * and the IR.
771        */
772       emit(MAD(this->result, op[2], op[1], op[0]));
773       break;
774
775    case ir_triop_lrp:
776       emit_lrp(this->result, op[0], op[1], op[2]);
777       break;
778
779    case ir_triop_csel:
780       emit(CMP(reg_null_d, op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
781       inst = emit(BRW_OPCODE_SEL, this->result, op[1], op[2]);
782       inst->predicate = BRW_PREDICATE_NORMAL;
783       break;
784    }
785 }
786
787 void
788 fs_visitor::emit_assignment_writes(fs_reg &l, fs_reg &r,
789                                    const glsl_type *type, bool predicated)
790 {
791    switch (type->base_type) {
792    case GLSL_TYPE_FLOAT:
793    case GLSL_TYPE_UINT:
794    case GLSL_TYPE_INT:
795    case GLSL_TYPE_BOOL:
796       for (unsigned int i = 0; i < type->components(); i++) {
797          l.type = brw_type_for_base_type(type);
798          r.type = brw_type_for_base_type(type);
799
800          if (predicated || !l.equals(r)) {
801             fs_inst *inst = emit(MOV(l, r));
802             inst->predicate = predicated ? BRW_PREDICATE_NORMAL : BRW_PREDICATE_NONE;
803          }
804
805          l.reg_offset++;
806          r.reg_offset++;
807       }
808       break;
809    case GLSL_TYPE_ARRAY:
810       for (unsigned int i = 0; i < type->length; i++) {
811          emit_assignment_writes(l, r, type->fields.array, predicated);
812       }
813       break;
814
815    case GLSL_TYPE_STRUCT:
816       for (unsigned int i = 0; i < type->length; i++) {
817          emit_assignment_writes(l, r, type->fields.structure[i].type,
818                                 predicated);
819       }
820       break;
821
822    case GLSL_TYPE_SAMPLER:
823    case GLSL_TYPE_ATOMIC_UINT:
824       break;
825
826    case GLSL_TYPE_VOID:
827    case GLSL_TYPE_ERROR:
828    case GLSL_TYPE_INTERFACE:
829       assert(!"not reached");
830       break;
831    }
832 }
833
834 /* If the RHS processing resulted in an instruction generating a
835  * temporary value, and it would be easy to rewrite the instruction to
836  * generate its result right into the LHS instead, do so.  This ends
837  * up reliably removing instructions where it can be tricky to do so
838  * later without real UD chain information.
839  */
840 bool
841 fs_visitor::try_rewrite_rhs_to_dst(ir_assignment *ir,
842                                    fs_reg dst,
843                                    fs_reg src,
844                                    fs_inst *pre_rhs_inst,
845                                    fs_inst *last_rhs_inst)
846 {
847    /* Only attempt if we're doing a direct assignment. */
848    if (ir->condition ||
849        !(ir->lhs->type->is_scalar() ||
850         (ir->lhs->type->is_vector() &&
851          ir->write_mask == (1 << ir->lhs->type->vector_elements) - 1)))
852       return false;
853
854    /* Make sure the last instruction generated our source reg. */
855    fs_inst *modify = get_instruction_generating_reg(pre_rhs_inst,
856                                                     last_rhs_inst,
857                                                     src);
858    if (!modify)
859       return false;
860
861    /* If last_rhs_inst wrote a different number of components than our LHS,
862     * we can't safely rewrite it.
863     */
864    if (virtual_grf_sizes[dst.reg] != modify->regs_written)
865       return false;
866
867    /* Success!  Rewrite the instruction. */
868    modify->dst = dst;
869
870    return true;
871 }
872
873 void
874 fs_visitor::visit(ir_assignment *ir)
875 {
876    fs_reg l, r;
877    fs_inst *inst;
878
879    /* FINISHME: arrays on the lhs */
880    ir->lhs->accept(this);
881    l = this->result;
882
883    fs_inst *pre_rhs_inst = (fs_inst *) this->instructions.get_tail();
884
885    ir->rhs->accept(this);
886    r = this->result;
887
888    fs_inst *last_rhs_inst = (fs_inst *) this->instructions.get_tail();
889
890    assert(l.file != BAD_FILE);
891    assert(r.file != BAD_FILE);
892
893    if (try_rewrite_rhs_to_dst(ir, l, r, pre_rhs_inst, last_rhs_inst))
894       return;
895
896    if (ir->condition) {
897       emit_bool_to_cond_code(ir->condition);
898    }
899
900    if (ir->lhs->type->is_scalar() ||
901        ir->lhs->type->is_vector()) {
902       for (int i = 0; i < ir->lhs->type->vector_elements; i++) {
903          if (ir->write_mask & (1 << i)) {
904             inst = emit(MOV(l, r));
905             if (ir->condition)
906                inst->predicate = BRW_PREDICATE_NORMAL;
907             r.reg_offset++;
908          }
909          l.reg_offset++;
910       }
911    } else {
912       emit_assignment_writes(l, r, ir->lhs->type, ir->condition != NULL);
913    }
914 }
915
916 fs_inst *
917 fs_visitor::emit_texture_gen4(ir_texture *ir, fs_reg dst, fs_reg coordinate,
918                               fs_reg shadow_c, fs_reg lod, fs_reg dPdy)
919 {
920    int mlen;
921    int base_mrf = 1;
922    bool simd16 = false;
923    fs_reg orig_dst;
924
925    /* g0 header. */
926    mlen = 1;
927
928    if (ir->shadow_comparitor) {
929       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
930          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), coordinate));
931          coordinate.reg_offset++;
932       }
933
934       /* gen4's SIMD8 sampler always has the slots for u,v,r present.
935        * the unused slots must be zeroed.
936        */
937       for (int i = ir->coordinate->type->vector_elements; i < 3; i++) {
938          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), fs_reg(0.0f)));
939       }
940       mlen += 3;
941
942       if (ir->op == ir_tex) {
943          /* There's no plain shadow compare message, so we use shadow
944           * compare with a bias of 0.0.
945           */
946          emit(MOV(fs_reg(MRF, base_mrf + mlen), fs_reg(0.0f)));
947          mlen++;
948       } else if (ir->op == ir_txb || ir->op == ir_txl) {
949          emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
950          mlen++;
951       } else {
952          assert(!"Should not get here.");
953       }
954
955       emit(MOV(fs_reg(MRF, base_mrf + mlen), shadow_c));
956       mlen++;
957    } else if (ir->op == ir_tex) {
958       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
959          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), coordinate));
960          coordinate.reg_offset++;
961       }
962       /* zero the others. */
963       for (int i = ir->coordinate->type->vector_elements; i<3; i++) {
964          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), fs_reg(0.0f)));
965       }
966       /* gen4's SIMD8 sampler always has the slots for u,v,r present. */
967       mlen += 3;
968    } else if (ir->op == ir_txd) {
969       fs_reg &dPdx = lod;
970
971       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
972          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), coordinate));
973          coordinate.reg_offset++;
974       }
975       /* the slots for u and v are always present, but r is optional */
976       mlen += MAX2(ir->coordinate->type->vector_elements, 2);
977
978       /*  P   = u, v, r
979        * dPdx = dudx, dvdx, drdx
980        * dPdy = dudy, dvdy, drdy
981        *
982        * 1-arg: Does not exist.
983        *
984        * 2-arg: dudx   dvdx   dudy   dvdy
985        *        dPdx.x dPdx.y dPdy.x dPdy.y
986        *        m4     m5     m6     m7
987        *
988        * 3-arg: dudx   dvdx   drdx   dudy   dvdy   drdy
989        *        dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
990        *        m5     m6     m7     m8     m9     m10
991        */
992       for (int i = 0; i < ir->lod_info.grad.dPdx->type->vector_elements; i++) {
993          emit(MOV(fs_reg(MRF, base_mrf + mlen), dPdx));
994          dPdx.reg_offset++;
995       }
996       mlen += MAX2(ir->lod_info.grad.dPdx->type->vector_elements, 2);
997
998       for (int i = 0; i < ir->lod_info.grad.dPdy->type->vector_elements; i++) {
999          emit(MOV(fs_reg(MRF, base_mrf + mlen), dPdy));
1000          dPdy.reg_offset++;
1001       }
1002       mlen += MAX2(ir->lod_info.grad.dPdy->type->vector_elements, 2);
1003    } else if (ir->op == ir_txs) {
1004       /* There's no SIMD8 resinfo message on Gen4.  Use SIMD16 instead. */
1005       simd16 = true;
1006       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), lod));
1007       mlen += 2;
1008    } else {
1009       /* Oh joy.  gen4 doesn't have SIMD8 non-shadow-compare bias/lod
1010        * instructions.  We'll need to do SIMD16 here.
1011        */
1012       simd16 = true;
1013       assert(ir->op == ir_txb || ir->op == ir_txl || ir->op == ir_txf);
1014
1015       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1016          emit(MOV(fs_reg(MRF, base_mrf + mlen + i * 2, coordinate.type),
1017                   coordinate));
1018          coordinate.reg_offset++;
1019       }
1020
1021       /* Initialize the rest of u/v/r with 0.0.  Empirically, this seems to
1022        * be necessary for TXF (ld), but seems wise to do for all messages.
1023        */
1024       for (int i = ir->coordinate->type->vector_elements; i < 3; i++) {
1025          emit(MOV(fs_reg(MRF, base_mrf + mlen + i * 2), fs_reg(0.0f)));
1026       }
1027
1028       /* lod/bias appears after u/v/r. */
1029       mlen += 6;
1030
1031       emit(MOV(fs_reg(MRF, base_mrf + mlen, lod.type), lod));
1032       mlen++;
1033
1034       /* The unused upper half. */
1035       mlen++;
1036    }
1037
1038    if (simd16) {
1039       /* Now, since we're doing simd16, the return is 2 interleaved
1040        * vec4s where the odd-indexed ones are junk. We'll need to move
1041        * this weirdness around to the expected layout.
1042        */
1043       orig_dst = dst;
1044       dst = fs_reg(GRF, virtual_grf_alloc(8),
1045                    (brw->is_g4x ?
1046                     brw_type_for_base_type(ir->type) :
1047                     BRW_REGISTER_TYPE_F));
1048    }
1049
1050    fs_inst *inst = NULL;
1051    switch (ir->op) {
1052    case ir_tex:
1053       inst = emit(SHADER_OPCODE_TEX, dst);
1054       break;
1055    case ir_txb:
1056       inst = emit(FS_OPCODE_TXB, dst);
1057       break;
1058    case ir_txl:
1059       inst = emit(SHADER_OPCODE_TXL, dst);
1060       break;
1061    case ir_txd:
1062       inst = emit(SHADER_OPCODE_TXD, dst);
1063       break;
1064    case ir_txs:
1065       inst = emit(SHADER_OPCODE_TXS, dst);
1066       break;
1067    case ir_txf:
1068       inst = emit(SHADER_OPCODE_TXF, dst);
1069       break;
1070    default:
1071       fail("unrecognized texture opcode");
1072    }
1073    inst->base_mrf = base_mrf;
1074    inst->mlen = mlen;
1075    inst->header_present = true;
1076    inst->regs_written = simd16 ? 8 : 4;
1077
1078    if (simd16) {
1079       for (int i = 0; i < 4; i++) {
1080          emit(MOV(orig_dst, dst));
1081          orig_dst.reg_offset++;
1082          dst.reg_offset += 2;
1083       }
1084    }
1085
1086    return inst;
1087 }
1088
1089 /* gen5's sampler has slots for u, v, r, array index, then optional
1090  * parameters like shadow comparitor or LOD bias.  If optional
1091  * parameters aren't present, those base slots are optional and don't
1092  * need to be included in the message.
1093  *
1094  * We don't fill in the unnecessary slots regardless, which may look
1095  * surprising in the disassembly.
1096  */
1097 fs_inst *
1098 fs_visitor::emit_texture_gen5(ir_texture *ir, fs_reg dst, fs_reg coordinate,
1099                               fs_reg shadow_c, fs_reg lod, fs_reg lod2,
1100                               fs_reg sample_index)
1101 {
1102    int mlen = 0;
1103    int base_mrf = 2;
1104    int reg_width = dispatch_width / 8;
1105    bool header_present = false;
1106    const int vector_elements =
1107       ir->coordinate ? ir->coordinate->type->vector_elements : 0;
1108
1109    if (ir->offset) {
1110       /* The offsets set up by the ir_texture visitor are in the
1111        * m1 header, so we can't go headerless.
1112        */
1113       header_present = true;
1114       mlen++;
1115       base_mrf--;
1116    }
1117
1118    for (int i = 0; i < vector_elements; i++) {
1119       emit(MOV(fs_reg(MRF, base_mrf + mlen + i * reg_width, coordinate.type),
1120                coordinate));
1121       coordinate.reg_offset++;
1122    }
1123    mlen += vector_elements * reg_width;
1124
1125    if (ir->shadow_comparitor) {
1126       mlen = MAX2(mlen, header_present + 4 * reg_width);
1127
1128       emit(MOV(fs_reg(MRF, base_mrf + mlen), shadow_c));
1129       mlen += reg_width;
1130    }
1131
1132    fs_inst *inst = NULL;
1133    switch (ir->op) {
1134    case ir_tex:
1135       inst = emit(SHADER_OPCODE_TEX, dst);
1136       break;
1137    case ir_txb:
1138       mlen = MAX2(mlen, header_present + 4 * reg_width);
1139       emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
1140       mlen += reg_width;
1141
1142       inst = emit(FS_OPCODE_TXB, dst);
1143       break;
1144    case ir_txl:
1145       mlen = MAX2(mlen, header_present + 4 * reg_width);
1146       emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
1147       mlen += reg_width;
1148
1149       inst = emit(SHADER_OPCODE_TXL, dst);
1150       break;
1151    case ir_txd: {
1152       mlen = MAX2(mlen, header_present + 4 * reg_width); /* skip over 'ai' */
1153
1154       /**
1155        *  P   =  u,    v,    r
1156        * dPdx = dudx, dvdx, drdx
1157        * dPdy = dudy, dvdy, drdy
1158        *
1159        * Load up these values:
1160        * - dudx   dudy   dvdx   dvdy   drdx   drdy
1161        * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
1162        */
1163       for (int i = 0; i < ir->lod_info.grad.dPdx->type->vector_elements; i++) {
1164          emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
1165          lod.reg_offset++;
1166          mlen += reg_width;
1167
1168          emit(MOV(fs_reg(MRF, base_mrf + mlen), lod2));
1169          lod2.reg_offset++;
1170          mlen += reg_width;
1171       }
1172
1173       inst = emit(SHADER_OPCODE_TXD, dst);
1174       break;
1175    }
1176    case ir_txs:
1177       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), lod));
1178       mlen += reg_width;
1179       inst = emit(SHADER_OPCODE_TXS, dst);
1180       break;
1181    case ir_query_levels:
1182       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), fs_reg(0u)));
1183       mlen += reg_width;
1184       inst = emit(SHADER_OPCODE_TXS, dst);
1185       break;
1186    case ir_txf:
1187       mlen = header_present + 4 * reg_width;
1188       emit(MOV(fs_reg(MRF, base_mrf + mlen - reg_width, BRW_REGISTER_TYPE_UD), lod));
1189       inst = emit(SHADER_OPCODE_TXF, dst);
1190       break;
1191    case ir_txf_ms:
1192       mlen = header_present + 4 * reg_width;
1193
1194       /* lod */
1195       emit(MOV(fs_reg(MRF, base_mrf + mlen - reg_width, BRW_REGISTER_TYPE_UD), fs_reg(0)));
1196       /* sample index */
1197       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), sample_index));
1198       mlen += reg_width;
1199       inst = emit(SHADER_OPCODE_TXF_MS, dst);
1200       break;
1201    case ir_lod:
1202       inst = emit(SHADER_OPCODE_LOD, dst);
1203       break;
1204    case ir_tg4:
1205       inst = emit(SHADER_OPCODE_TG4, dst);
1206       break;
1207    default:
1208       fail("unrecognized texture opcode");
1209       break;
1210    }
1211    inst->base_mrf = base_mrf;
1212    inst->mlen = mlen;
1213    inst->header_present = header_present;
1214    inst->regs_written = 4;
1215
1216    if (mlen > 11) {
1217       fail("Message length >11 disallowed by hardware\n");
1218    }
1219
1220    return inst;
1221 }
1222
1223 fs_inst *
1224 fs_visitor::emit_texture_gen7(ir_texture *ir, fs_reg dst, fs_reg coordinate,
1225                               fs_reg shadow_c, fs_reg lod, fs_reg lod2,
1226                               fs_reg sample_index)
1227 {
1228    int reg_width = dispatch_width / 8;
1229    bool header_present = false;
1230
1231    fs_reg payload = fs_reg(this, glsl_type::float_type);
1232    fs_reg next = payload;
1233
1234    if (ir->op == ir_tg4 || (ir->offset && ir->op != ir_txf)) {
1235       /* For general texture offsets (no txf workaround), we need a header to
1236        * put them in.  Note that for 16-wide we're making space for two actual
1237        * hardware registers here, so the emit will have to fix up for this.
1238        *
1239        * * ir4_tg4 needs to place its channel select in the header,
1240        * for interaction with ARB_texture_swizzle
1241        */
1242       header_present = true;
1243       next.reg_offset++;
1244    }
1245
1246    if (ir->shadow_comparitor) {
1247       emit(MOV(next, shadow_c));
1248       next.reg_offset++;
1249    }
1250
1251    bool has_nonconstant_offset = ir->offset && !ir->offset->as_constant();
1252    bool coordinate_done = false;
1253
1254    /* Set up the LOD info */
1255    switch (ir->op) {
1256    case ir_tex:
1257    case ir_lod:
1258       break;
1259    case ir_txb:
1260       emit(MOV(next, lod));
1261       next.reg_offset++;
1262       break;
1263    case ir_txl:
1264       emit(MOV(next, lod));
1265       next.reg_offset++;
1266       break;
1267    case ir_txd: {
1268       if (dispatch_width == 16)
1269          fail("Gen7 does not support sample_d/sample_d_c in SIMD16 mode.");
1270
1271       /* Load dPdx and the coordinate together:
1272        * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
1273        */
1274       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1275          emit(MOV(next, coordinate));
1276          coordinate.reg_offset++;
1277          next.reg_offset++;
1278
1279          /* For cube map array, the coordinate is (u,v,r,ai) but there are
1280           * only derivatives for (u, v, r).
1281           */
1282          if (i < ir->lod_info.grad.dPdx->type->vector_elements) {
1283             emit(MOV(next, lod));
1284             lod.reg_offset++;
1285             next.reg_offset++;
1286
1287             emit(MOV(next, lod2));
1288             lod2.reg_offset++;
1289             next.reg_offset++;
1290          }
1291       }
1292
1293       coordinate_done = true;
1294       break;
1295    }
1296    case ir_txs:
1297       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), lod));
1298       next.reg_offset++;
1299       break;
1300    case ir_query_levels:
1301       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), fs_reg(0u)));
1302       next.reg_offset++;
1303       break;
1304    case ir_txf:
1305       /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r. */
1306       emit(MOV(next.retype(BRW_REGISTER_TYPE_D), coordinate));
1307       coordinate.reg_offset++;
1308       next.reg_offset++;
1309
1310       emit(MOV(next.retype(BRW_REGISTER_TYPE_D), lod));
1311       next.reg_offset++;
1312
1313       for (int i = 1; i < ir->coordinate->type->vector_elements; i++) {
1314          emit(MOV(next.retype(BRW_REGISTER_TYPE_D), coordinate));
1315          coordinate.reg_offset++;
1316          next.reg_offset++;
1317       }
1318
1319       coordinate_done = true;
1320       break;
1321    case ir_txf_ms:
1322       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), sample_index));
1323       next.reg_offset++;
1324
1325       /* constant zero MCS; we arrange to never actually have a compressed
1326        * multisample surface here for now. TODO: issue ld_mcs to get this first,
1327        * if we ever support texturing from compressed multisample surfaces
1328        */
1329       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), fs_reg(0u)));
1330       next.reg_offset++;
1331
1332       /* there is no offsetting for this message; just copy in the integer
1333        * texture coordinates
1334        */
1335       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1336          emit(MOV(next.retype(BRW_REGISTER_TYPE_D), coordinate));
1337          coordinate.reg_offset++;
1338          next.reg_offset++;
1339       }
1340
1341       coordinate_done = true;
1342       break;
1343    case ir_tg4:
1344       if (has_nonconstant_offset) {
1345          if (ir->shadow_comparitor && dispatch_width == 16)
1346             fail("Gen7 does not support gather4_po_c in SIMD16 mode.");
1347
1348          /* More crazy intermixing */
1349          ir->offset->accept(this);
1350          fs_reg offset_value = this->result;
1351
1352          for (int i = 0; i < 2; i++) { /* u, v */
1353             emit(MOV(next, coordinate));
1354             coordinate.reg_offset++;
1355             next.reg_offset++;
1356          }
1357
1358          for (int i = 0; i < 2; i++) { /* offu, offv */
1359             emit(MOV(next.retype(BRW_REGISTER_TYPE_D), offset_value));
1360             offset_value.reg_offset++;
1361             next.reg_offset++;
1362          }
1363
1364          if (ir->coordinate->type->vector_elements == 3) { /* r if present */
1365             emit(MOV(next, coordinate));
1366             coordinate.reg_offset++;
1367             next.reg_offset++;
1368          }
1369
1370          coordinate_done = true;
1371       }
1372       break;
1373    }
1374
1375    /* Set up the coordinate (except for cases where it was done above) */
1376    if (ir->coordinate && !coordinate_done) {
1377       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1378          emit(MOV(next, coordinate));
1379          coordinate.reg_offset++;
1380          next.reg_offset++;
1381       }
1382    }
1383
1384    /* Generate the SEND */
1385    fs_inst *inst = NULL;
1386    switch (ir->op) {
1387    case ir_tex: inst = emit(SHADER_OPCODE_TEX, dst, payload); break;
1388    case ir_txb: inst = emit(FS_OPCODE_TXB, dst, payload); break;
1389    case ir_txl: inst = emit(SHADER_OPCODE_TXL, dst, payload); break;
1390    case ir_txd: inst = emit(SHADER_OPCODE_TXD, dst, payload); break;
1391    case ir_txf: inst = emit(SHADER_OPCODE_TXF, dst, payload); break;
1392    case ir_txf_ms: inst = emit(SHADER_OPCODE_TXF_MS, dst, payload); break;
1393    case ir_txs: inst = emit(SHADER_OPCODE_TXS, dst, payload); break;
1394    case ir_query_levels: inst = emit(SHADER_OPCODE_TXS, dst, payload); break;
1395    case ir_lod: inst = emit(SHADER_OPCODE_LOD, dst, payload); break;
1396    case ir_tg4:
1397       if (has_nonconstant_offset)
1398          inst = emit(SHADER_OPCODE_TG4_OFFSET, dst, payload);
1399       else
1400          inst = emit(SHADER_OPCODE_TG4, dst, payload);
1401       break;
1402    }
1403    inst->base_mrf = -1;
1404    if (reg_width == 2)
1405       inst->mlen = next.reg_offset * reg_width - header_present;
1406    else
1407       inst->mlen = next.reg_offset * reg_width;
1408    inst->header_present = header_present;
1409    inst->regs_written = 4;
1410
1411    virtual_grf_sizes[payload.reg] = next.reg_offset;
1412    if (inst->mlen > 11) {
1413       fail("Message length >11 disallowed by hardware\n");
1414    }
1415
1416    return inst;
1417 }
1418
1419 fs_reg
1420 fs_visitor::rescale_texcoord(ir_texture *ir, fs_reg coordinate,
1421                              bool is_rect, int sampler, int texunit)
1422 {
1423    fs_inst *inst = NULL;
1424    bool needs_gl_clamp = true;
1425    fs_reg scale_x, scale_y;
1426
1427    /* The 965 requires the EU to do the normalization of GL rectangle
1428     * texture coordinates.  We use the program parameter state
1429     * tracking to get the scaling factor.
1430     */
1431    if (is_rect &&
1432        (brw->gen < 6 ||
1433         (brw->gen >= 6 && (c->key.tex.gl_clamp_mask[0] & (1 << sampler) ||
1434                              c->key.tex.gl_clamp_mask[1] & (1 << sampler))))) {
1435       struct gl_program_parameter_list *params = prog->Parameters;
1436       int tokens[STATE_LENGTH] = {
1437          STATE_INTERNAL,
1438          STATE_TEXRECT_SCALE,
1439          texunit,
1440          0,
1441          0
1442       };
1443
1444       if (dispatch_width == 16) {
1445          fail("rectangle scale uniform setup not supported on 16-wide\n");
1446          return coordinate;
1447       }
1448
1449       scale_x = fs_reg(UNIFORM, c->prog_data.nr_params);
1450       scale_y = fs_reg(UNIFORM, c->prog_data.nr_params + 1);
1451
1452       GLuint index = _mesa_add_state_reference(params,
1453                                                (gl_state_index *)tokens);
1454       c->prog_data.param[c->prog_data.nr_params++] =
1455          &prog->Parameters->ParameterValues[index][0].f;
1456       c->prog_data.param[c->prog_data.nr_params++] =
1457          &prog->Parameters->ParameterValues[index][1].f;
1458    }
1459
1460    /* The 965 requires the EU to do the normalization of GL rectangle
1461     * texture coordinates.  We use the program parameter state
1462     * tracking to get the scaling factor.
1463     */
1464    if (brw->gen < 6 && is_rect) {
1465       fs_reg dst = fs_reg(this, ir->coordinate->type);
1466       fs_reg src = coordinate;
1467       coordinate = dst;
1468
1469       emit(MUL(dst, src, scale_x));
1470       dst.reg_offset++;
1471       src.reg_offset++;
1472       emit(MUL(dst, src, scale_y));
1473    } else if (is_rect) {
1474       /* On gen6+, the sampler handles the rectangle coordinates
1475        * natively, without needing rescaling.  But that means we have
1476        * to do GL_CLAMP clamping at the [0, width], [0, height] scale,
1477        * not [0, 1] like the default case below.
1478        */
1479       needs_gl_clamp = false;
1480
1481       for (int i = 0; i < 2; i++) {
1482          if (c->key.tex.gl_clamp_mask[i] & (1 << sampler)) {
1483             fs_reg chan = coordinate;
1484             chan.reg_offset += i;
1485
1486             inst = emit(BRW_OPCODE_SEL, chan, chan, brw_imm_f(0.0));
1487             inst->conditional_mod = BRW_CONDITIONAL_G;
1488
1489             /* Our parameter comes in as 1.0/width or 1.0/height,
1490              * because that's what people normally want for doing
1491              * texture rectangle handling.  We need width or height
1492              * for clamping, but we don't care enough to make a new
1493              * parameter type, so just invert back.
1494              */
1495             fs_reg limit = fs_reg(this, glsl_type::float_type);
1496             emit(MOV(limit, i == 0 ? scale_x : scale_y));
1497             emit(SHADER_OPCODE_RCP, limit, limit);
1498
1499             inst = emit(BRW_OPCODE_SEL, chan, chan, limit);
1500             inst->conditional_mod = BRW_CONDITIONAL_L;
1501          }
1502       }
1503    }
1504
1505    if (ir->coordinate && needs_gl_clamp) {
1506       for (unsigned int i = 0;
1507            i < MIN2(ir->coordinate->type->vector_elements, 3); i++) {
1508          if (c->key.tex.gl_clamp_mask[i] & (1 << sampler)) {
1509             fs_reg chan = coordinate;
1510             chan.reg_offset += i;
1511
1512             fs_inst *inst = emit(MOV(chan, chan));
1513             inst->saturate = true;
1514          }
1515       }
1516    }
1517    return coordinate;
1518 }
1519
1520 void
1521 fs_visitor::visit(ir_texture *ir)
1522 {
1523    fs_inst *inst = NULL;
1524
1525    int sampler =
1526       _mesa_get_sampler_uniform_value(ir->sampler, shader_prog, prog);
1527    /* FINISHME: We're failing to recompile our programs when the sampler is
1528     * updated.  This only matters for the texture rectangle scale parameters
1529     * (pre-gen6, or gen6+ with GL_CLAMP).
1530     */
1531    int texunit = prog->SamplerUnits[sampler];
1532
1533    if (ir->op == ir_tg4) {
1534       /* When tg4 is used with the degenerate ZERO/ONE swizzles, don't bother
1535        * emitting anything other than setting up the constant result.
1536        */
1537       ir_constant *chan = ir->lod_info.component->as_constant();
1538       int swiz = GET_SWZ(c->key.tex.swizzles[sampler], chan->value.i[0]);
1539       if (swiz == SWIZZLE_ZERO || swiz == SWIZZLE_ONE) {
1540
1541          fs_reg res = fs_reg(this, glsl_type::vec4_type);
1542          this->result = res;
1543
1544          for (int i=0; i<4; i++) {
1545             emit(MOV(res, fs_reg(swiz == SWIZZLE_ZERO ? 0.0f : 1.0f)));
1546             res.reg_offset++;
1547          }
1548          return;
1549       }
1550    }
1551
1552    /* Should be lowered by do_lower_texture_projection */
1553    assert(!ir->projector);
1554
1555    /* Should be lowered */
1556    assert(!ir->offset || !ir->offset->type->is_array());
1557
1558    /* Generate code to compute all the subexpression trees.  This has to be
1559     * done before loading any values into MRFs for the sampler message since
1560     * generating these values may involve SEND messages that need the MRFs.
1561     */
1562    fs_reg coordinate;
1563    if (ir->coordinate) {
1564       ir->coordinate->accept(this);
1565
1566       coordinate = rescale_texcoord(ir, this->result,
1567                                     ir->sampler->type->sampler_dimensionality ==
1568                                     GLSL_SAMPLER_DIM_RECT,
1569                                     sampler, texunit);
1570    }
1571
1572    fs_reg shadow_comparitor;
1573    if (ir->shadow_comparitor) {
1574       ir->shadow_comparitor->accept(this);
1575       shadow_comparitor = this->result;
1576    }
1577
1578    fs_reg lod, lod2, sample_index;
1579    switch (ir->op) {
1580    case ir_tex:
1581    case ir_lod:
1582    case ir_tg4:
1583    case ir_query_levels:
1584       break;
1585    case ir_txb:
1586       ir->lod_info.bias->accept(this);
1587       lod = this->result;
1588       break;
1589    case ir_txd:
1590       ir->lod_info.grad.dPdx->accept(this);
1591       lod = this->result;
1592
1593       ir->lod_info.grad.dPdy->accept(this);
1594       lod2 = this->result;
1595       break;
1596    case ir_txf:
1597    case ir_txl:
1598    case ir_txs:
1599       ir->lod_info.lod->accept(this);
1600       lod = this->result;
1601       break;
1602    case ir_txf_ms:
1603       ir->lod_info.sample_index->accept(this);
1604       sample_index = this->result;
1605       break;
1606    default:
1607       assert(!"Unrecognized texture opcode");
1608    };
1609
1610    /* Writemasking doesn't eliminate channels on SIMD8 texture
1611     * samples, so don't worry about them.
1612     */
1613    fs_reg dst = fs_reg(this, glsl_type::get_instance(ir->type->base_type, 4, 1));
1614
1615    if (brw->gen >= 7) {
1616       inst = emit_texture_gen7(ir, dst, coordinate, shadow_comparitor,
1617                                lod, lod2, sample_index);
1618    } else if (brw->gen >= 5) {
1619       inst = emit_texture_gen5(ir, dst, coordinate, shadow_comparitor,
1620                                lod, lod2, sample_index);
1621    } else {
1622       inst = emit_texture_gen4(ir, dst, coordinate, shadow_comparitor,
1623                                lod, lod2);
1624    }
1625
1626    if (ir->offset != NULL && ir->op != ir_txf)
1627       inst->texture_offset = brw_texture_offset(ctx, ir->offset->as_constant());
1628
1629    if (ir->op == ir_tg4)
1630       inst->texture_offset |= gather_channel(ir, sampler) << 16; // M0.2:16-17
1631
1632    inst->sampler = sampler;
1633
1634    if (ir->shadow_comparitor)
1635       inst->shadow_compare = true;
1636
1637    /* fixup #layers for cube map arrays */
1638    if (ir->op == ir_txs) {
1639       glsl_type const *type = ir->sampler->type;
1640       if (type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE &&
1641           type->sampler_array) {
1642          fs_reg depth = dst;
1643          depth.reg_offset = 2;
1644          emit_math(SHADER_OPCODE_INT_QUOTIENT, depth, depth, fs_reg(6));
1645       }
1646    }
1647
1648    swizzle_result(ir, dst, sampler);
1649 }
1650
1651 /**
1652  * Set up the gather channel based on the swizzle, for gather4.
1653  */
1654 uint32_t
1655 fs_visitor::gather_channel(ir_texture *ir, int sampler)
1656 {
1657    ir_constant *chan = ir->lod_info.component->as_constant();
1658    int swiz = GET_SWZ(c->key.tex.swizzles[sampler], chan->value.i[0]);
1659    switch (swiz) {
1660       case SWIZZLE_X: return 0;
1661       case SWIZZLE_Y:
1662          /* gather4 sampler is broken for green channel on RG32F --
1663           * we must ask for blue instead.
1664           */
1665          if (c->key.tex.gather_channel_quirk_mask & (1<<sampler))
1666             return 2;
1667          return 1;
1668       case SWIZZLE_Z: return 2;
1669       case SWIZZLE_W: return 3;
1670       default:
1671          assert(!"Not reached"); /* zero, one swizzles handled already */
1672          return 0;
1673    }
1674 }
1675
1676 /**
1677  * Swizzle the result of a texture result.  This is necessary for
1678  * EXT_texture_swizzle as well as DEPTH_TEXTURE_MODE for shadow comparisons.
1679  */
1680 void
1681 fs_visitor::swizzle_result(ir_texture *ir, fs_reg orig_val, int sampler)
1682 {
1683    if (ir->op == ir_query_levels) {
1684       /* # levels is in .w */
1685       orig_val.reg_offset += 3;
1686       this->result = orig_val;
1687       return;
1688    }
1689
1690    this->result = orig_val;
1691
1692    /* txs,lod don't actually sample the texture, so swizzling the result
1693     * makes no sense.
1694     */
1695    if (ir->op == ir_txs || ir->op == ir_lod || ir->op == ir_tg4)
1696       return;
1697
1698    if (ir->type == glsl_type::float_type) {
1699       /* Ignore DEPTH_TEXTURE_MODE swizzling. */
1700       assert(ir->sampler->type->sampler_shadow);
1701    } else if (c->key.tex.swizzles[sampler] != SWIZZLE_NOOP) {
1702       fs_reg swizzled_result = fs_reg(this, glsl_type::vec4_type);
1703
1704       for (int i = 0; i < 4; i++) {
1705          int swiz = GET_SWZ(c->key.tex.swizzles[sampler], i);
1706          fs_reg l = swizzled_result;
1707          l.reg_offset += i;
1708
1709          if (swiz == SWIZZLE_ZERO) {
1710             emit(MOV(l, fs_reg(0.0f)));
1711          } else if (swiz == SWIZZLE_ONE) {
1712             emit(MOV(l, fs_reg(1.0f)));
1713          } else {
1714             fs_reg r = orig_val;
1715             r.reg_offset += GET_SWZ(c->key.tex.swizzles[sampler], i);
1716             emit(MOV(l, r));
1717          }
1718       }
1719       this->result = swizzled_result;
1720    }
1721 }
1722
1723 void
1724 fs_visitor::visit(ir_swizzle *ir)
1725 {
1726    ir->val->accept(this);
1727    fs_reg val = this->result;
1728
1729    if (ir->type->vector_elements == 1) {
1730       this->result.reg_offset += ir->mask.x;
1731       return;
1732    }
1733
1734    fs_reg result = fs_reg(this, ir->type);
1735    this->result = result;
1736
1737    for (unsigned int i = 0; i < ir->type->vector_elements; i++) {
1738       fs_reg channel = val;
1739       int swiz = 0;
1740
1741       switch (i) {
1742       case 0:
1743          swiz = ir->mask.x;
1744          break;
1745       case 1:
1746          swiz = ir->mask.y;
1747          break;
1748       case 2:
1749          swiz = ir->mask.z;
1750          break;
1751       case 3:
1752          swiz = ir->mask.w;
1753          break;
1754       }
1755
1756       channel.reg_offset += swiz;
1757       emit(MOV(result, channel));
1758       result.reg_offset++;
1759    }
1760 }
1761
1762 void
1763 fs_visitor::visit(ir_discard *ir)
1764 {
1765    assert(ir->condition == NULL); /* FINISHME */
1766
1767    /* We track our discarded pixels in f0.1.  By predicating on it, we can
1768     * update just the flag bits that aren't yet discarded.  By emitting a
1769     * CMP of g0 != g0, all our currently executing channels will get turned
1770     * off.
1771     */
1772    fs_reg some_reg = fs_reg(retype(brw_vec8_grf(0, 0),
1773                                    BRW_REGISTER_TYPE_UW));
1774    fs_inst *cmp = emit(CMP(reg_null_f, some_reg, some_reg,
1775                            BRW_CONDITIONAL_NZ));
1776    cmp->predicate = BRW_PREDICATE_NORMAL;
1777    cmp->flag_subreg = 1;
1778
1779    if (brw->gen >= 6) {
1780       /* For performance, after a discard, jump to the end of the shader.
1781        * However, many people will do foliage by discarding based on a
1782        * texture's alpha mask, and then continue on to texture with the
1783        * remaining pixels.  To avoid trashing the derivatives for those
1784        * texture samples, we'll only jump if all of the pixels in the subspan
1785        * have been discarded.
1786        */
1787       fs_inst *discard_jump = emit(FS_OPCODE_DISCARD_JUMP);
1788       discard_jump->flag_subreg = 1;
1789       discard_jump->predicate = BRW_PREDICATE_ALIGN1_ANY4H;
1790       discard_jump->predicate_inverse = true;
1791    }
1792 }
1793
1794 void
1795 fs_visitor::visit(ir_constant *ir)
1796 {
1797    /* Set this->result to reg at the bottom of the function because some code
1798     * paths will cause this visitor to be applied to other fields.  This will
1799     * cause the value stored in this->result to be modified.
1800     *
1801     * Make reg constant so that it doesn't get accidentally modified along the
1802     * way.  Yes, I actually had this problem. :(
1803     */
1804    const fs_reg reg(this, ir->type);
1805    fs_reg dst_reg = reg;
1806
1807    if (ir->type->is_array()) {
1808       const unsigned size = type_size(ir->type->fields.array);
1809
1810       for (unsigned i = 0; i < ir->type->length; i++) {
1811          ir->array_elements[i]->accept(this);
1812          fs_reg src_reg = this->result;
1813
1814          dst_reg.type = src_reg.type;
1815          for (unsigned j = 0; j < size; j++) {
1816             emit(MOV(dst_reg, src_reg));
1817             src_reg.reg_offset++;
1818             dst_reg.reg_offset++;
1819          }
1820       }
1821    } else if (ir->type->is_record()) {
1822       foreach_list(node, &ir->components) {
1823          ir_constant *const field = (ir_constant *) node;
1824          const unsigned size = type_size(field->type);
1825
1826          field->accept(this);
1827          fs_reg src_reg = this->result;
1828
1829          dst_reg.type = src_reg.type;
1830          for (unsigned j = 0; j < size; j++) {
1831             emit(MOV(dst_reg, src_reg));
1832             src_reg.reg_offset++;
1833             dst_reg.reg_offset++;
1834          }
1835       }
1836    } else {
1837       const unsigned size = type_size(ir->type);
1838
1839       for (unsigned i = 0; i < size; i++) {
1840          switch (ir->type->base_type) {
1841          case GLSL_TYPE_FLOAT:
1842             emit(MOV(dst_reg, fs_reg(ir->value.f[i])));
1843             break;
1844          case GLSL_TYPE_UINT:
1845             emit(MOV(dst_reg, fs_reg(ir->value.u[i])));
1846             break;
1847          case GLSL_TYPE_INT:
1848             emit(MOV(dst_reg, fs_reg(ir->value.i[i])));
1849             break;
1850          case GLSL_TYPE_BOOL:
1851             emit(MOV(dst_reg, fs_reg((int)ir->value.b[i])));
1852             break;
1853          default:
1854             assert(!"Non-float/uint/int/bool constant");
1855          }
1856          dst_reg.reg_offset++;
1857       }
1858    }
1859
1860    this->result = reg;
1861 }
1862
1863 void
1864 fs_visitor::emit_bool_to_cond_code(ir_rvalue *ir)
1865 {
1866    ir_expression *expr = ir->as_expression();
1867
1868    if (expr &&
1869        expr->operation != ir_binop_logic_and &&
1870        expr->operation != ir_binop_logic_or &&
1871        expr->operation != ir_binop_logic_xor) {
1872       fs_reg op[2];
1873       fs_inst *inst;
1874
1875       assert(expr->get_num_operands() <= 2);
1876       for (unsigned int i = 0; i < expr->get_num_operands(); i++) {
1877          assert(expr->operands[i]->type->is_scalar());
1878
1879          expr->operands[i]->accept(this);
1880          op[i] = this->result;
1881
1882          resolve_ud_negate(&op[i]);
1883       }
1884
1885       switch (expr->operation) {
1886       case ir_unop_logic_not:
1887          inst = emit(AND(reg_null_d, op[0], fs_reg(1)));
1888          inst->conditional_mod = BRW_CONDITIONAL_Z;
1889          break;
1890
1891       case ir_unop_f2b:
1892          if (brw->gen >= 6) {
1893             emit(CMP(reg_null_d, op[0], fs_reg(0.0f), BRW_CONDITIONAL_NZ));
1894          } else {
1895             inst = emit(MOV(reg_null_f, op[0]));
1896             inst->conditional_mod = BRW_CONDITIONAL_NZ;
1897          }
1898          break;
1899
1900       case ir_unop_i2b:
1901          if (brw->gen >= 6) {
1902             emit(CMP(reg_null_d, op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
1903          } else {
1904             inst = emit(MOV(reg_null_d, op[0]));
1905             inst->conditional_mod = BRW_CONDITIONAL_NZ;
1906          }
1907          break;
1908
1909       case ir_binop_greater:
1910       case ir_binop_gequal:
1911       case ir_binop_less:
1912       case ir_binop_lequal:
1913       case ir_binop_equal:
1914       case ir_binop_all_equal:
1915       case ir_binop_nequal:
1916       case ir_binop_any_nequal:
1917          resolve_bool_comparison(expr->operands[0], &op[0]);
1918          resolve_bool_comparison(expr->operands[1], &op[1]);
1919
1920          emit(CMP(reg_null_d, op[0], op[1],
1921                   brw_conditional_for_comparison(expr->operation)));
1922          break;
1923
1924       default:
1925          assert(!"not reached");
1926          fail("bad cond code\n");
1927          break;
1928       }
1929       return;
1930    }
1931
1932    ir->accept(this);
1933
1934    fs_inst *inst = emit(AND(reg_null_d, this->result, fs_reg(1)));
1935    inst->conditional_mod = BRW_CONDITIONAL_NZ;
1936 }
1937
1938 /**
1939  * Emit a gen6 IF statement with the comparison folded into the IF
1940  * instruction.
1941  */
1942 void
1943 fs_visitor::emit_if_gen6(ir_if *ir)
1944 {
1945    ir_expression *expr = ir->condition->as_expression();
1946
1947    if (expr) {
1948       fs_reg op[2];
1949       fs_inst *inst;
1950       fs_reg temp;
1951
1952       assert(expr->get_num_operands() <= 2);
1953       for (unsigned int i = 0; i < expr->get_num_operands(); i++) {
1954          assert(expr->operands[i]->type->is_scalar());
1955
1956          expr->operands[i]->accept(this);
1957          op[i] = this->result;
1958       }
1959
1960       switch (expr->operation) {
1961       case ir_unop_logic_not:
1962       case ir_binop_logic_xor:
1963       case ir_binop_logic_or:
1964       case ir_binop_logic_and:
1965          /* For operations on bool arguments, only the low bit of the bool is
1966           * valid, and the others are undefined.  Fall back to the condition
1967           * code path.
1968           */
1969          break;
1970
1971       case ir_unop_f2b:
1972          inst = emit(BRW_OPCODE_IF, reg_null_f, op[0], fs_reg(0));
1973          inst->conditional_mod = BRW_CONDITIONAL_NZ;
1974          return;
1975
1976       case ir_unop_i2b:
1977          emit(IF(op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
1978          return;
1979
1980       case ir_binop_greater:
1981       case ir_binop_gequal:
1982       case ir_binop_less:
1983       case ir_binop_lequal:
1984       case ir_binop_equal:
1985       case ir_binop_all_equal:
1986       case ir_binop_nequal:
1987       case ir_binop_any_nequal:
1988          resolve_bool_comparison(expr->operands[0], &op[0]);
1989          resolve_bool_comparison(expr->operands[1], &op[1]);
1990
1991          emit(IF(op[0], op[1],
1992                  brw_conditional_for_comparison(expr->operation)));
1993          return;
1994       default:
1995          assert(!"not reached");
1996          emit(IF(op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
1997          fail("bad condition\n");
1998          return;
1999       }
2000    }
2001
2002    emit_bool_to_cond_code(ir->condition);
2003    fs_inst *inst = emit(BRW_OPCODE_IF);
2004    inst->predicate = BRW_PREDICATE_NORMAL;
2005 }
2006
2007 /**
2008  * Try to replace IF/MOV/ELSE/MOV/ENDIF with SEL.
2009  *
2010  * Many GLSL shaders contain the following pattern:
2011  *
2012  *    x = condition ? foo : bar
2013  *
2014  * The compiler emits an ir_if tree for this, since each subexpression might be
2015  * a complex tree that could have side-effects or short-circuit logic.
2016  *
2017  * However, the common case is to simply select one of two constants or
2018  * variable values---which is exactly what SEL is for.  In this case, the
2019  * assembly looks like:
2020  *
2021  *    (+f0) IF
2022  *    MOV dst src0
2023  *    ELSE
2024  *    MOV dst src1
2025  *    ENDIF
2026  *
2027  * which can be easily translated into:
2028  *
2029  *    (+f0) SEL dst src0 src1
2030  *
2031  * If src0 is an immediate value, we promote it to a temporary GRF.
2032  */
2033 void
2034 fs_visitor::try_replace_with_sel()
2035 {
2036    fs_inst *endif_inst = (fs_inst *) instructions.get_tail();
2037    assert(endif_inst->opcode == BRW_OPCODE_ENDIF);
2038
2039    /* Pattern match in reverse: IF, MOV, ELSE, MOV, ENDIF. */
2040    int opcodes[] = {
2041       BRW_OPCODE_IF, BRW_OPCODE_MOV, BRW_OPCODE_ELSE, BRW_OPCODE_MOV,
2042    };
2043
2044    fs_inst *match = (fs_inst *) endif_inst->prev;
2045    for (int i = 0; i < 4; i++) {
2046       if (match->is_head_sentinel() || match->opcode != opcodes[4-i-1])
2047          return;
2048       match = (fs_inst *) match->prev;
2049    }
2050
2051    /* The opcodes match; it looks like the right sequence of instructions. */
2052    fs_inst *else_mov = (fs_inst *) endif_inst->prev;
2053    fs_inst *then_mov = (fs_inst *) else_mov->prev->prev;
2054    fs_inst *if_inst = (fs_inst *) then_mov->prev;
2055
2056    /* Check that the MOVs are the right form. */
2057    if (then_mov->dst.equals(else_mov->dst) &&
2058        !then_mov->is_partial_write() &&
2059        !else_mov->is_partial_write()) {
2060
2061       /* Remove the matched instructions; we'll emit a SEL to replace them. */
2062       while (!if_inst->next->is_tail_sentinel())
2063          if_inst->next->remove();
2064       if_inst->remove();
2065
2066       /* Only the last source register can be a constant, so if the MOV in
2067        * the "then" clause uses a constant, we need to put it in a temporary.
2068        */
2069       fs_reg src0(then_mov->src[0]);
2070       if (src0.file == IMM) {
2071          src0 = fs_reg(this, glsl_type::float_type);
2072          src0.type = then_mov->src[0].type;
2073          emit(MOV(src0, then_mov->src[0]));
2074       }
2075
2076       fs_inst *sel;
2077       if (if_inst->conditional_mod) {
2078          /* Sandybridge-specific IF with embedded comparison */
2079          emit(CMP(reg_null_d, if_inst->src[0], if_inst->src[1],
2080                   if_inst->conditional_mod));
2081          sel = emit(BRW_OPCODE_SEL, then_mov->dst, src0, else_mov->src[0]);
2082          sel->predicate = BRW_PREDICATE_NORMAL;
2083       } else {
2084          /* Separate CMP and IF instructions */
2085          sel = emit(BRW_OPCODE_SEL, then_mov->dst, src0, else_mov->src[0]);
2086          sel->predicate = if_inst->predicate;
2087          sel->predicate_inverse = if_inst->predicate_inverse;
2088       }
2089    }
2090 }
2091
2092 void
2093 fs_visitor::visit(ir_if *ir)
2094 {
2095    if (brw->gen < 6 && dispatch_width == 16) {
2096       fail("Can't support (non-uniform) control flow on 16-wide\n");
2097    }
2098
2099    /* Don't point the annotation at the if statement, because then it plus
2100     * the then and else blocks get printed.
2101     */
2102    this->base_ir = ir->condition;
2103
2104    if (brw->gen == 6) {
2105       emit_if_gen6(ir);
2106    } else {
2107       emit_bool_to_cond_code(ir->condition);
2108
2109       emit(IF(BRW_PREDICATE_NORMAL));
2110    }
2111
2112    foreach_list(node, &ir->then_instructions) {
2113       ir_instruction *ir = (ir_instruction *)node;
2114       this->base_ir = ir;
2115
2116       ir->accept(this);
2117    }
2118
2119    if (!ir->else_instructions.is_empty()) {
2120       emit(BRW_OPCODE_ELSE);
2121
2122       foreach_list(node, &ir->else_instructions) {
2123          ir_instruction *ir = (ir_instruction *)node;
2124          this->base_ir = ir;
2125
2126          ir->accept(this);
2127       }
2128    }
2129
2130    emit(BRW_OPCODE_ENDIF);
2131
2132    try_replace_with_sel();
2133 }
2134
2135 void
2136 fs_visitor::visit(ir_loop *ir)
2137 {
2138    fs_reg counter = reg_undef;
2139
2140    if (brw->gen < 6 && dispatch_width == 16) {
2141       fail("Can't support (non-uniform) control flow on 16-wide\n");
2142    }
2143
2144    if (ir->counter) {
2145       this->base_ir = ir->counter;
2146       ir->counter->accept(this);
2147       counter = *(variable_storage(ir->counter));
2148
2149       if (ir->from) {
2150          this->base_ir = ir->from;
2151          ir->from->accept(this);
2152
2153          emit(MOV(counter, this->result));
2154       }
2155    }
2156
2157    this->base_ir = NULL;
2158    emit(BRW_OPCODE_DO);
2159
2160    if (ir->to) {
2161       this->base_ir = ir->to;
2162       ir->to->accept(this);
2163
2164       emit(CMP(reg_null_d, counter, this->result,
2165                brw_conditional_for_comparison(ir->cmp)));
2166
2167       fs_inst *inst = emit(BRW_OPCODE_BREAK);
2168       inst->predicate = BRW_PREDICATE_NORMAL;
2169    }
2170
2171    foreach_list(node, &ir->body_instructions) {
2172       ir_instruction *ir = (ir_instruction *)node;
2173
2174       this->base_ir = ir;
2175       ir->accept(this);
2176    }
2177
2178    if (ir->increment) {
2179       this->base_ir = ir->increment;
2180       ir->increment->accept(this);
2181       emit(ADD(counter, counter, this->result));
2182    }
2183
2184    this->base_ir = NULL;
2185    emit(BRW_OPCODE_WHILE);
2186 }
2187
2188 void
2189 fs_visitor::visit(ir_loop_jump *ir)
2190 {
2191    switch (ir->mode) {
2192    case ir_loop_jump::jump_break:
2193       emit(BRW_OPCODE_BREAK);
2194       break;
2195    case ir_loop_jump::jump_continue:
2196       emit(BRW_OPCODE_CONTINUE);
2197       break;
2198    }
2199 }
2200
2201 void
2202 fs_visitor::visit_atomic_counter_intrinsic(ir_call *ir)
2203 {
2204    ir_dereference *deref = static_cast<ir_dereference *>(
2205       ir->actual_parameters.get_head());
2206    ir_variable *location = deref->variable_referenced();
2207    unsigned surf_index = (c->prog_data.base.binding_table.abo_start +
2208                           location->atomic.buffer_index);
2209
2210    /* Calculate the surface offset */
2211    fs_reg offset(this, glsl_type::uint_type);
2212    ir_dereference_array *deref_array = deref->as_dereference_array();
2213
2214    if (deref_array) {
2215       deref_array->array_index->accept(this);
2216
2217       fs_reg tmp(this, glsl_type::uint_type);
2218       emit(MUL(tmp, this->result, ATOMIC_COUNTER_SIZE));
2219       emit(ADD(offset, tmp, location->atomic.offset));
2220    } else {
2221       offset = location->atomic.offset;
2222    }
2223
2224    /* Emit the appropriate machine instruction */
2225    const char *callee = ir->callee->function_name();
2226    ir->return_deref->accept(this);
2227    fs_reg dst = this->result;
2228
2229    if (!strcmp("__intrinsic_atomic_read", callee)) {
2230       emit_untyped_surface_read(surf_index, dst, offset);
2231
2232    } else if (!strcmp("__intrinsic_atomic_increment", callee)) {
2233       emit_untyped_atomic(BRW_AOP_INC, surf_index, dst, offset,
2234                           fs_reg(), fs_reg());
2235
2236    } else if (!strcmp("__intrinsic_atomic_predecrement", callee)) {
2237       emit_untyped_atomic(BRW_AOP_PREDEC, surf_index, dst, offset,
2238                           fs_reg(), fs_reg());
2239    }
2240 }
2241
2242 void
2243 fs_visitor::visit(ir_call *ir)
2244 {
2245    const char *callee = ir->callee->function_name();
2246
2247    if (!strcmp("__intrinsic_atomic_read", callee) ||
2248        !strcmp("__intrinsic_atomic_increment", callee) ||
2249        !strcmp("__intrinsic_atomic_predecrement", callee)) {
2250       visit_atomic_counter_intrinsic(ir);
2251    } else {
2252       assert(!"Unsupported intrinsic.");
2253    }
2254 }
2255
2256 void
2257 fs_visitor::visit(ir_return *ir)
2258 {
2259    assert(!"FINISHME");
2260 }
2261
2262 void
2263 fs_visitor::visit(ir_function *ir)
2264 {
2265    /* Ignore function bodies other than main() -- we shouldn't see calls to
2266     * them since they should all be inlined before we get to ir_to_mesa.
2267     */
2268    if (strcmp(ir->name, "main") == 0) {
2269       const ir_function_signature *sig;
2270       exec_list empty;
2271
2272       sig = ir->matching_signature(NULL, &empty);
2273
2274       assert(sig);
2275
2276       foreach_list(node, &sig->body) {
2277          ir_instruction *ir = (ir_instruction *)node;
2278          this->base_ir = ir;
2279
2280          ir->accept(this);
2281       }
2282    }
2283 }
2284
2285 void
2286 fs_visitor::visit(ir_function_signature *ir)
2287 {
2288    assert(!"not reached");
2289    (void)ir;
2290 }
2291
2292 void
2293 fs_visitor::visit(ir_emit_vertex *)
2294 {
2295    assert(!"not reached");
2296 }
2297
2298 void
2299 fs_visitor::visit(ir_end_primitive *)
2300 {
2301    assert(!"not reached");
2302 }
2303
2304 void
2305 fs_visitor::emit_untyped_atomic(unsigned atomic_op, unsigned surf_index,
2306                                 fs_reg dst, fs_reg offset, fs_reg src0,
2307                                 fs_reg src1)
2308 {
2309    const unsigned operand_len = dispatch_width / 8;
2310    unsigned mlen = 0;
2311
2312    /* Initialize the sample mask in the message header. */
2313    emit(MOV(brw_uvec_mrf(8, mlen, 0), brw_imm_ud(0)))
2314       ->force_writemask_all = true;
2315
2316    if (fp->UsesKill) {
2317       emit(MOV(brw_uvec_mrf(1, mlen, 7), brw_flag_reg(0, 1)))
2318          ->force_writemask_all = true;
2319    } else {
2320       emit(MOV(brw_uvec_mrf(1, mlen, 7),
2321                retype(brw_vec1_grf(1, 7), BRW_REGISTER_TYPE_UD)))
2322          ->force_writemask_all = true;
2323    }
2324
2325    mlen++;
2326
2327    /* Set the atomic operation offset. */
2328    emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), offset));
2329    mlen += operand_len;
2330
2331    /* Set the atomic operation arguments. */
2332    if (src0.file != BAD_FILE) {
2333       emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), src0));
2334       mlen += operand_len;
2335    }
2336
2337    if (src1.file != BAD_FILE) {
2338       emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), src1));
2339       mlen += operand_len;
2340    }
2341
2342    /* Emit the instruction. */
2343    fs_inst inst(SHADER_OPCODE_UNTYPED_ATOMIC, dst, atomic_op, surf_index);
2344    inst.base_mrf = 0;
2345    inst.mlen = mlen;
2346    emit(inst);
2347 }
2348
2349 void
2350 fs_visitor::emit_untyped_surface_read(unsigned surf_index, fs_reg dst,
2351                                       fs_reg offset)
2352 {
2353    const unsigned operand_len = dispatch_width / 8;
2354    unsigned mlen = 0;
2355
2356    /* Initialize the sample mask in the message header. */
2357    emit(MOV(brw_uvec_mrf(8, mlen, 0), brw_imm_ud(0)))
2358       ->force_writemask_all = true;
2359
2360    if (fp->UsesKill) {
2361       emit(MOV(brw_uvec_mrf(1, mlen, 7), brw_flag_reg(0, 1)))
2362          ->force_writemask_all = true;
2363    } else {
2364       emit(MOV(brw_uvec_mrf(1, mlen, 7),
2365                retype(brw_vec1_grf(1, 7), BRW_REGISTER_TYPE_UD)))
2366          ->force_writemask_all = true;
2367    }
2368
2369    mlen++;
2370
2371    /* Set the surface read offset. */
2372    emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), offset));
2373    mlen += operand_len;
2374
2375    /* Emit the instruction. */
2376    fs_inst inst(SHADER_OPCODE_UNTYPED_SURFACE_READ, dst, surf_index);
2377    inst.base_mrf = 0;
2378    inst.mlen = mlen;
2379    emit(inst);
2380 }
2381
2382 fs_inst *
2383 fs_visitor::emit(fs_inst inst)
2384 {
2385    fs_inst *list_inst = new(mem_ctx) fs_inst;
2386    *list_inst = inst;
2387    emit(list_inst);
2388    return list_inst;
2389 }
2390
2391 fs_inst *
2392 fs_visitor::emit(fs_inst *inst)
2393 {
2394    if (force_uncompressed_stack > 0)
2395       inst->force_uncompressed = true;
2396    else if (force_sechalf_stack > 0)
2397       inst->force_sechalf = true;
2398
2399    inst->annotation = this->current_annotation;
2400    inst->ir = this->base_ir;
2401
2402    this->instructions.push_tail(inst);
2403
2404    return inst;
2405 }
2406
2407 void
2408 fs_visitor::emit(exec_list list)
2409 {
2410    foreach_list_safe(node, &list) {
2411       fs_inst *inst = (fs_inst *)node;
2412       inst->remove();
2413       emit(inst);
2414    }
2415 }
2416
2417 /** Emits a dummy fragment shader consisting of magenta for bringup purposes. */
2418 void
2419 fs_visitor::emit_dummy_fs()
2420 {
2421    int reg_width = dispatch_width / 8;
2422
2423    /* Everyone's favorite color. */
2424    emit(MOV(fs_reg(MRF, 2 + 0 * reg_width), fs_reg(1.0f)));
2425    emit(MOV(fs_reg(MRF, 2 + 1 * reg_width), fs_reg(0.0f)));
2426    emit(MOV(fs_reg(MRF, 2 + 2 * reg_width), fs_reg(1.0f)));
2427    emit(MOV(fs_reg(MRF, 2 + 3 * reg_width), fs_reg(0.0f)));
2428
2429    fs_inst *write;
2430    write = emit(FS_OPCODE_FB_WRITE, fs_reg(0), fs_reg(0));
2431    write->base_mrf = 2;
2432    write->mlen = 4 * reg_width;
2433    write->eot = true;
2434 }
2435
2436 /* The register location here is relative to the start of the URB
2437  * data.  It will get adjusted to be a real location before
2438  * generate_code() time.
2439  */
2440 struct brw_reg
2441 fs_visitor::interp_reg(int location, int channel)
2442 {
2443    int regnr = c->prog_data.urb_setup[location] * 2 + channel / 2;
2444    int stride = (channel & 1) * 4;
2445
2446    assert(c->prog_data.urb_setup[location] != -1);
2447
2448    return brw_vec1_grf(regnr, stride);
2449 }
2450
2451 /** Emits the interpolation for the varying inputs. */
2452 void
2453 fs_visitor::emit_interpolation_setup_gen4()
2454 {
2455    this->current_annotation = "compute pixel centers";
2456    this->pixel_x = fs_reg(this, glsl_type::uint_type);
2457    this->pixel_y = fs_reg(this, glsl_type::uint_type);
2458    this->pixel_x.type = BRW_REGISTER_TYPE_UW;
2459    this->pixel_y.type = BRW_REGISTER_TYPE_UW;
2460
2461    emit(FS_OPCODE_PIXEL_X, this->pixel_x);
2462    emit(FS_OPCODE_PIXEL_Y, this->pixel_y);
2463
2464    this->current_annotation = "compute pixel deltas from v0";
2465    if (brw->has_pln) {
2466       this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2467          fs_reg(this, glsl_type::vec2_type);
2468       this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2469          this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC];
2470       this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC].reg_offset++;
2471    } else {
2472       this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2473          fs_reg(this, glsl_type::float_type);
2474       this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2475          fs_reg(this, glsl_type::float_type);
2476    }
2477    emit(ADD(this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2478             this->pixel_x, fs_reg(negate(brw_vec1_grf(1, 0)))));
2479    emit(ADD(this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2480             this->pixel_y, fs_reg(negate(brw_vec1_grf(1, 1)))));
2481
2482    this->current_annotation = "compute pos.w and 1/pos.w";
2483    /* Compute wpos.w.  It's always in our setup, since it's needed to
2484     * interpolate the other attributes.
2485     */
2486    this->wpos_w = fs_reg(this, glsl_type::float_type);
2487    emit(FS_OPCODE_LINTERP, wpos_w,
2488         this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2489         this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2490         interp_reg(VARYING_SLOT_POS, 3));
2491    /* Compute the pixel 1/W value from wpos.w. */
2492    this->pixel_w = fs_reg(this, glsl_type::float_type);
2493    emit_math(SHADER_OPCODE_RCP, this->pixel_w, wpos_w);
2494    this->current_annotation = NULL;
2495 }
2496
2497 /** Emits the interpolation for the varying inputs. */
2498 void
2499 fs_visitor::emit_interpolation_setup_gen6()
2500 {
2501    struct brw_reg g1_uw = retype(brw_vec1_grf(1, 0), BRW_REGISTER_TYPE_UW);
2502
2503    /* If the pixel centers end up used, the setup is the same as for gen4. */
2504    this->current_annotation = "compute pixel centers";
2505    fs_reg int_pixel_x = fs_reg(this, glsl_type::uint_type);
2506    fs_reg int_pixel_y = fs_reg(this, glsl_type::uint_type);
2507    int_pixel_x.type = BRW_REGISTER_TYPE_UW;
2508    int_pixel_y.type = BRW_REGISTER_TYPE_UW;
2509    emit(ADD(int_pixel_x,
2510             fs_reg(stride(suboffset(g1_uw, 4), 2, 4, 0)),
2511             fs_reg(brw_imm_v(0x10101010))));
2512    emit(ADD(int_pixel_y,
2513             fs_reg(stride(suboffset(g1_uw, 5), 2, 4, 0)),
2514             fs_reg(brw_imm_v(0x11001100))));
2515
2516    /* As of gen6, we can no longer mix float and int sources.  We have
2517     * to turn the integer pixel centers into floats for their actual
2518     * use.
2519     */
2520    this->pixel_x = fs_reg(this, glsl_type::float_type);
2521    this->pixel_y = fs_reg(this, glsl_type::float_type);
2522    emit(MOV(this->pixel_x, int_pixel_x));
2523    emit(MOV(this->pixel_y, int_pixel_y));
2524
2525    this->current_annotation = "compute pos.w";
2526    this->pixel_w = fs_reg(brw_vec8_grf(c->source_w_reg, 0));
2527    this->wpos_w = fs_reg(this, glsl_type::float_type);
2528    emit_math(SHADER_OPCODE_RCP, this->wpos_w, this->pixel_w);
2529
2530    for (int i = 0; i < BRW_WM_BARYCENTRIC_INTERP_MODE_COUNT; ++i) {
2531       uint8_t reg = c->barycentric_coord_reg[i];
2532       this->delta_x[i] = fs_reg(brw_vec8_grf(reg, 0));
2533       this->delta_y[i] = fs_reg(brw_vec8_grf(reg + 1, 0));
2534    }
2535
2536    this->current_annotation = NULL;
2537 }
2538
2539 void
2540 fs_visitor::emit_color_write(int target, int index, int first_color_mrf)
2541 {
2542    int reg_width = dispatch_width / 8;
2543    fs_inst *inst;
2544    fs_reg color = outputs[target];
2545    fs_reg mrf;
2546
2547    /* If there's no color data to be written, skip it. */
2548    if (color.file == BAD_FILE)
2549       return;
2550
2551    color.reg_offset += index;
2552
2553    if (dispatch_width == 8 || brw->gen >= 6) {
2554       /* SIMD8 write looks like:
2555        * m + 0: r0
2556        * m + 1: r1
2557        * m + 2: g0
2558        * m + 3: g1
2559        *
2560        * gen6 SIMD16 DP write looks like:
2561        * m + 0: r0
2562        * m + 1: r1
2563        * m + 2: g0
2564        * m + 3: g1
2565        * m + 4: b0
2566        * m + 5: b1
2567        * m + 6: a0
2568        * m + 7: a1
2569        */
2570       inst = emit(MOV(fs_reg(MRF, first_color_mrf + index * reg_width,
2571                              color.type),
2572                       color));
2573       inst->saturate = c->key.clamp_fragment_color;
2574    } else {
2575       /* pre-gen6 SIMD16 single source DP write looks like:
2576        * m + 0: r0
2577        * m + 1: g0
2578        * m + 2: b0
2579        * m + 3: a0
2580        * m + 4: r1
2581        * m + 5: g1
2582        * m + 6: b1
2583        * m + 7: a1
2584        */
2585       if (brw->has_compr4) {
2586          /* By setting the high bit of the MRF register number, we
2587           * indicate that we want COMPR4 mode - instead of doing the
2588           * usual destination + 1 for the second half we get
2589           * destination + 4.
2590           */
2591          inst = emit(MOV(fs_reg(MRF, BRW_MRF_COMPR4 + first_color_mrf + index,
2592                                 color.type),
2593                          color));
2594          inst->saturate = c->key.clamp_fragment_color;
2595       } else {
2596          push_force_uncompressed();
2597          inst = emit(MOV(fs_reg(MRF, first_color_mrf + index, color.type),
2598                          color));
2599          inst->saturate = c->key.clamp_fragment_color;
2600          pop_force_uncompressed();
2601
2602          push_force_sechalf();
2603          color.sechalf = true;
2604          inst = emit(MOV(fs_reg(MRF, first_color_mrf + index + 4, color.type),
2605                          color));
2606          inst->saturate = c->key.clamp_fragment_color;
2607          pop_force_sechalf();
2608          color.sechalf = false;
2609       }
2610    }
2611 }
2612
2613 static int
2614 cond_for_alpha_func(GLenum func)
2615 {
2616    switch(func) {
2617       case GL_GREATER:
2618          return BRW_CONDITIONAL_G;
2619       case GL_GEQUAL:
2620          return BRW_CONDITIONAL_GE;
2621       case GL_LESS:
2622          return BRW_CONDITIONAL_L;
2623       case GL_LEQUAL:
2624          return BRW_CONDITIONAL_LE;
2625       case GL_EQUAL:
2626          return BRW_CONDITIONAL_EQ;
2627       case GL_NOTEQUAL:
2628          return BRW_CONDITIONAL_NEQ;
2629       default:
2630          assert(!"Not reached");
2631          return 0;
2632    }
2633 }
2634
2635 /**
2636  * Alpha test support for when we compile it into the shader instead
2637  * of using the normal fixed-function alpha test.
2638  */
2639 void
2640 fs_visitor::emit_alpha_test()
2641 {
2642    this->current_annotation = "Alpha test";
2643
2644    fs_inst *cmp;
2645    if (c->key.alpha_test_func == GL_ALWAYS)
2646       return;
2647
2648    if (c->key.alpha_test_func == GL_NEVER) {
2649       /* f0.1 = 0 */
2650       fs_reg some_reg = fs_reg(retype(brw_vec8_grf(0, 0),
2651                                       BRW_REGISTER_TYPE_UW));
2652       cmp = emit(CMP(reg_null_f, some_reg, some_reg,
2653                      BRW_CONDITIONAL_NEQ));
2654    } else {
2655       /* RT0 alpha */
2656       fs_reg color = outputs[0];
2657       color.reg_offset += 3;
2658
2659       /* f0.1 &= func(color, ref) */
2660       cmp = emit(CMP(reg_null_f, color, fs_reg(c->key.alpha_test_ref),
2661                      cond_for_alpha_func(c->key.alpha_test_func)));
2662    }
2663    cmp->predicate = BRW_PREDICATE_NORMAL;
2664    cmp->flag_subreg = 1;
2665 }
2666
2667 void
2668 fs_visitor::emit_fb_writes()
2669 {
2670    this->current_annotation = "FB write header";
2671    bool header_present = true;
2672    /* We can potentially have a message length of up to 15, so we have to set
2673     * base_mrf to either 0 or 1 in order to fit in m0..m15.
2674     */
2675    int base_mrf = 1;
2676    int nr = base_mrf;
2677    int reg_width = dispatch_width / 8;
2678    bool do_dual_src = this->dual_src_output.file != BAD_FILE;
2679    bool src0_alpha_to_render_target = false;
2680
2681    if (dispatch_width == 16 && do_dual_src) {
2682       fail("GL_ARB_blend_func_extended not yet supported in 16-wide.");
2683       do_dual_src = false;
2684    }
2685
2686    /* From the Sandy Bridge PRM, volume 4, page 198:
2687     *
2688     *     "Dispatched Pixel Enables. One bit per pixel indicating
2689     *      which pixels were originally enabled when the thread was
2690     *      dispatched. This field is only required for the end-of-
2691     *      thread message and on all dual-source messages."
2692     */
2693    if (brw->gen >= 6 &&
2694        !this->fp->UsesKill &&
2695        !do_dual_src &&
2696        c->key.nr_color_regions == 1) {
2697       header_present = false;
2698    }
2699
2700    if (header_present) {
2701       src0_alpha_to_render_target = brw->gen >= 6 &&
2702                                     !do_dual_src &&
2703                                     c->key.replicate_alpha;
2704       /* m2, m3 header */
2705       nr += 2;
2706    }
2707
2708    if (c->aa_dest_stencil_reg) {
2709       push_force_uncompressed();
2710       emit(MOV(fs_reg(MRF, nr++),
2711                fs_reg(brw_vec8_grf(c->aa_dest_stencil_reg, 0))));
2712       pop_force_uncompressed();
2713    }
2714
2715    c->prog_data.uses_omask =
2716       fp->Base.OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
2717    if(c->prog_data.uses_omask) {
2718       this->current_annotation = "FB write oMask";
2719       assert(this->sample_mask.file != BAD_FILE);
2720       /* Hand over gl_SampleMask. Only lower 16 bits are relevant. */
2721       emit(FS_OPCODE_SET_OMASK, fs_reg(MRF, nr, BRW_REGISTER_TYPE_UW), this->sample_mask);
2722       nr += 1;
2723    }
2724
2725    /* Reserve space for color. It'll be filled in per MRT below. */
2726    int color_mrf = nr;
2727    nr += 4 * reg_width;
2728    if (do_dual_src)
2729       nr += 4;
2730    if (src0_alpha_to_render_target)
2731       nr += reg_width;
2732
2733    if (c->source_depth_to_render_target) {
2734       if (brw->gen == 6 && dispatch_width == 16) {
2735          /* For outputting oDepth on gen6, SIMD8 writes have to be
2736           * used.  This would require 8-wide moves of each half to
2737           * message regs, kind of like pre-gen5 SIMD16 FB writes.
2738           * Just bail on doing so for now.
2739           */
2740          fail("Missing support for simd16 depth writes on gen6\n");
2741       }
2742
2743       if (prog->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
2744          /* Hand over gl_FragDepth. */
2745          assert(this->frag_depth.file != BAD_FILE);
2746          emit(MOV(fs_reg(MRF, nr), this->frag_depth));
2747       } else {
2748          /* Pass through the payload depth. */
2749          emit(MOV(fs_reg(MRF, nr),
2750                   fs_reg(brw_vec8_grf(c->source_depth_reg, 0))));
2751       }
2752       nr += reg_width;
2753    }
2754
2755    if (c->dest_depth_reg) {
2756       emit(MOV(fs_reg(MRF, nr),
2757                fs_reg(brw_vec8_grf(c->dest_depth_reg, 0))));
2758       nr += reg_width;
2759    }
2760
2761    if (do_dual_src) {
2762       fs_reg src0 = this->outputs[0];
2763       fs_reg src1 = this->dual_src_output;
2764
2765       this->current_annotation = ralloc_asprintf(this->mem_ctx,
2766                                                  "FB write src0");
2767       for (int i = 0; i < 4; i++) {
2768          fs_inst *inst = emit(MOV(fs_reg(MRF, color_mrf + i, src0.type), src0));
2769          src0.reg_offset++;
2770          inst->saturate = c->key.clamp_fragment_color;
2771       }
2772
2773       this->current_annotation = ralloc_asprintf(this->mem_ctx,
2774                                                  "FB write src1");
2775       for (int i = 0; i < 4; i++) {
2776          fs_inst *inst = emit(MOV(fs_reg(MRF, color_mrf + 4 + i, src1.type),
2777                                   src1));
2778          src1.reg_offset++;
2779          inst->saturate = c->key.clamp_fragment_color;
2780       }
2781
2782       if (INTEL_DEBUG & DEBUG_SHADER_TIME)
2783          emit_shader_time_end();
2784
2785       fs_inst *inst = emit(FS_OPCODE_FB_WRITE);
2786       inst->target = 0;
2787       inst->base_mrf = base_mrf;
2788       inst->mlen = nr - base_mrf;
2789       inst->eot = true;
2790       inst->header_present = header_present;
2791
2792       c->prog_data.dual_src_blend = true;
2793       this->current_annotation = NULL;
2794       return;
2795    }
2796
2797    for (int target = 0; target < c->key.nr_color_regions; target++) {
2798       this->current_annotation = ralloc_asprintf(this->mem_ctx,
2799                                                  "FB write target %d",
2800                                                  target);
2801       /* If src0_alpha_to_render_target is true, include source zero alpha
2802        * data in RenderTargetWrite message for targets > 0.
2803        */
2804       int write_color_mrf = color_mrf;
2805       if (src0_alpha_to_render_target && target != 0) {
2806          fs_inst *inst;
2807          fs_reg color = outputs[0];
2808          color.reg_offset += 3;
2809
2810          inst = emit(MOV(fs_reg(MRF, write_color_mrf, color.type),
2811                          color));
2812          inst->saturate = c->key.clamp_fragment_color;
2813          write_color_mrf = color_mrf + reg_width;
2814       }
2815
2816       for (unsigned i = 0; i < this->output_components[target]; i++)
2817          emit_color_write(target, i, write_color_mrf);
2818
2819       bool eot = false;
2820       if (target == c->key.nr_color_regions - 1) {
2821          eot = true;
2822
2823          if (INTEL_DEBUG & DEBUG_SHADER_TIME)
2824             emit_shader_time_end();
2825       }
2826
2827       fs_inst *inst = emit(FS_OPCODE_FB_WRITE);
2828       inst->target = target;
2829       inst->base_mrf = base_mrf;
2830       if (src0_alpha_to_render_target && target == 0)
2831          inst->mlen = nr - base_mrf - reg_width;
2832       else
2833          inst->mlen = nr - base_mrf;
2834       inst->eot = eot;
2835       inst->header_present = header_present;
2836    }
2837
2838    if (c->key.nr_color_regions == 0) {
2839       /* Even if there's no color buffers enabled, we still need to send
2840        * alpha out the pipeline to our null renderbuffer to support
2841        * alpha-testing, alpha-to-coverage, and so on.
2842        */
2843       emit_color_write(0, 3, color_mrf);
2844
2845       if (INTEL_DEBUG & DEBUG_SHADER_TIME)
2846          emit_shader_time_end();
2847
2848       fs_inst *inst = emit(FS_OPCODE_FB_WRITE);
2849       inst->base_mrf = base_mrf;
2850       inst->mlen = nr - base_mrf;
2851       inst->eot = true;
2852       inst->header_present = header_present;
2853    }
2854
2855    this->current_annotation = NULL;
2856 }
2857
2858 void
2859 fs_visitor::resolve_ud_negate(fs_reg *reg)
2860 {
2861    if (reg->type != BRW_REGISTER_TYPE_UD ||
2862        !reg->negate)
2863       return;
2864
2865    fs_reg temp = fs_reg(this, glsl_type::uint_type);
2866    emit(MOV(temp, *reg));
2867    *reg = temp;
2868 }
2869
2870 void
2871 fs_visitor::resolve_bool_comparison(ir_rvalue *rvalue, fs_reg *reg)
2872 {
2873    if (rvalue->type != glsl_type::bool_type)
2874       return;
2875
2876    fs_reg temp = fs_reg(this, glsl_type::bool_type);
2877    emit(AND(temp, *reg, fs_reg(1)));
2878    *reg = temp;
2879 }
2880
2881 fs_visitor::fs_visitor(struct brw_context *brw,
2882                        struct brw_wm_compile *c,
2883                        struct gl_shader_program *shader_prog,
2884                        struct gl_fragment_program *fp,
2885                        unsigned dispatch_width)
2886    : dispatch_width(dispatch_width)
2887 {
2888    this->c = c;
2889    this->brw = brw;
2890    this->fp = fp;
2891    this->prog = &fp->Base;
2892    this->shader_prog = shader_prog;
2893    this->prog = &fp->Base;
2894    this->stage_prog_data = &c->prog_data.base;
2895    this->ctx = &brw->ctx;
2896    this->mem_ctx = ralloc_context(NULL);
2897    if (shader_prog)
2898       shader = (struct brw_shader *)
2899          shader_prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2900    else
2901       shader = NULL;
2902    this->failed = false;
2903    this->variable_ht = hash_table_ctor(0,
2904                                        hash_table_pointer_hash,
2905                                        hash_table_pointer_compare);
2906
2907    memset(this->outputs, 0, sizeof(this->outputs));
2908    memset(this->output_components, 0, sizeof(this->output_components));
2909    this->first_non_payload_grf = 0;
2910    this->max_grf = brw->gen >= 7 ? GEN7_MRF_HACK_START : BRW_MAX_GRF;
2911
2912    this->current_annotation = NULL;
2913    this->base_ir = NULL;
2914
2915    this->virtual_grf_sizes = NULL;
2916    this->virtual_grf_count = 0;
2917    this->virtual_grf_array_size = 0;
2918    this->virtual_grf_start = NULL;
2919    this->virtual_grf_end = NULL;
2920    this->live_intervals = NULL;
2921
2922    this->params_remap = NULL;
2923    this->nr_params_remap = 0;
2924
2925    this->force_uncompressed_stack = 0;
2926    this->force_sechalf_stack = 0;
2927
2928    this->spilled_any_registers = false;
2929
2930    memset(&this->param_size, 0, sizeof(this->param_size));
2931 }
2932
2933 fs_visitor::~fs_visitor()
2934 {
2935    ralloc_free(this->mem_ctx);
2936    hash_table_dtor(this->variable_ht);
2937 }