OSDN Git Service

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