OSDN Git Service

intel/fs: Use new shuffle_32bit_write for all 64-bit storage writes
[android-x86/external-mesa.git] / src / intel / compiler / brw_fs_nir.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 #include "compiler/glsl/ir.h"
25 #include "brw_fs.h"
26 #include "brw_fs_surface_builder.h"
27 #include "brw_nir.h"
28
29 using namespace brw;
30 using namespace brw::surface_access;
31
32 void
33 fs_visitor::emit_nir_code()
34 {
35    /* emit the arrays used for inputs and outputs - load/store intrinsics will
36     * be converted to reads/writes of these arrays
37     */
38    nir_setup_outputs();
39    nir_setup_uniforms();
40    nir_emit_system_values();
41
42    /* get the main function and emit it */
43    nir_foreach_function(function, nir) {
44       assert(strcmp(function->name, "main") == 0);
45       assert(function->impl);
46       nir_emit_impl(function->impl);
47    }
48 }
49
50 void
51 fs_visitor::nir_setup_outputs()
52 {
53    if (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_FRAGMENT)
54       return;
55
56    unsigned vec4s[VARYING_SLOT_TESS_MAX] = { 0, };
57
58    /* Calculate the size of output registers in a separate pass, before
59     * allocating them.  With ARB_enhanced_layouts, multiple output variables
60     * may occupy the same slot, but have different type sizes.
61     */
62    nir_foreach_variable(var, &nir->outputs) {
63       const int loc = var->data.driver_location;
64       const unsigned var_vec4s =
65          var->data.compact ? DIV_ROUND_UP(glsl_get_length(var->type), 4)
66                            : type_size_vec4(var->type);
67       vec4s[loc] = MAX2(vec4s[loc], var_vec4s);
68    }
69
70    nir_foreach_variable(var, &nir->outputs) {
71       const int loc = var->data.driver_location;
72       if (outputs[loc].file == BAD_FILE) {
73          fs_reg reg = bld.vgrf(BRW_REGISTER_TYPE_F, 4 * vec4s[loc]);
74          for (unsigned i = 0; i < vec4s[loc]; i++) {
75             outputs[loc + i] = offset(reg, bld, 4 * i);
76          }
77       }
78    }
79 }
80
81 void
82 fs_visitor::nir_setup_uniforms()
83 {
84    /* Only the first compile gets to set up uniforms. */
85    if (push_constant_loc) {
86       assert(pull_constant_loc);
87       return;
88    }
89
90    uniforms = nir->num_uniforms / 4;
91
92    if (stage == MESA_SHADER_COMPUTE) {
93       /* Add a uniform for the thread local id.  It must be the last uniform
94        * on the list.
95        */
96       assert(uniforms == prog_data->nr_params);
97       uint32_t *param = brw_stage_prog_data_add_params(prog_data, 1);
98       *param = BRW_PARAM_BUILTIN_SUBGROUP_ID;
99       subgroup_id = fs_reg(UNIFORM, uniforms++, BRW_REGISTER_TYPE_UD);
100    }
101 }
102
103 static bool
104 emit_system_values_block(nir_block *block, fs_visitor *v)
105 {
106    fs_reg *reg;
107
108    nir_foreach_instr(instr, block) {
109       if (instr->type != nir_instr_type_intrinsic)
110          continue;
111
112       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
113       switch (intrin->intrinsic) {
114       case nir_intrinsic_load_vertex_id:
115       case nir_intrinsic_load_base_vertex:
116          unreachable("should be lowered by nir_lower_system_values().");
117
118       case nir_intrinsic_load_vertex_id_zero_base:
119       case nir_intrinsic_load_is_indexed_draw:
120       case nir_intrinsic_load_first_vertex:
121       case nir_intrinsic_load_instance_id:
122       case nir_intrinsic_load_base_instance:
123       case nir_intrinsic_load_draw_id:
124          unreachable("should be lowered by brw_nir_lower_vs_inputs().");
125
126       case nir_intrinsic_load_invocation_id:
127          if (v->stage == MESA_SHADER_TESS_CTRL)
128             break;
129          assert(v->stage == MESA_SHADER_GEOMETRY);
130          reg = &v->nir_system_values[SYSTEM_VALUE_INVOCATION_ID];
131          if (reg->file == BAD_FILE) {
132             const fs_builder abld = v->bld.annotate("gl_InvocationID", NULL);
133             fs_reg g1(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
134             fs_reg iid = abld.vgrf(BRW_REGISTER_TYPE_UD, 1);
135             abld.SHR(iid, g1, brw_imm_ud(27u));
136             *reg = iid;
137          }
138          break;
139
140       case nir_intrinsic_load_sample_pos:
141          assert(v->stage == MESA_SHADER_FRAGMENT);
142          reg = &v->nir_system_values[SYSTEM_VALUE_SAMPLE_POS];
143          if (reg->file == BAD_FILE)
144             *reg = *v->emit_samplepos_setup();
145          break;
146
147       case nir_intrinsic_load_sample_id:
148          assert(v->stage == MESA_SHADER_FRAGMENT);
149          reg = &v->nir_system_values[SYSTEM_VALUE_SAMPLE_ID];
150          if (reg->file == BAD_FILE)
151             *reg = *v->emit_sampleid_setup();
152          break;
153
154       case nir_intrinsic_load_sample_mask_in:
155          assert(v->stage == MESA_SHADER_FRAGMENT);
156          assert(v->devinfo->gen >= 7);
157          reg = &v->nir_system_values[SYSTEM_VALUE_SAMPLE_MASK_IN];
158          if (reg->file == BAD_FILE)
159             *reg = *v->emit_samplemaskin_setup();
160          break;
161
162       case nir_intrinsic_load_work_group_id:
163          assert(v->stage == MESA_SHADER_COMPUTE);
164          reg = &v->nir_system_values[SYSTEM_VALUE_WORK_GROUP_ID];
165          if (reg->file == BAD_FILE)
166             *reg = *v->emit_cs_work_group_id_setup();
167          break;
168
169       case nir_intrinsic_load_helper_invocation:
170          assert(v->stage == MESA_SHADER_FRAGMENT);
171          reg = &v->nir_system_values[SYSTEM_VALUE_HELPER_INVOCATION];
172          if (reg->file == BAD_FILE) {
173             const fs_builder abld =
174                v->bld.annotate("gl_HelperInvocation", NULL);
175
176             /* On Gen6+ (gl_HelperInvocation is only exposed on Gen7+) the
177              * pixel mask is in g1.7 of the thread payload.
178              *
179              * We move the per-channel pixel enable bit to the low bit of each
180              * channel by shifting the byte containing the pixel mask by the
181              * vector immediate 0x76543210UV.
182              *
183              * The region of <1,8,0> reads only 1 byte (the pixel masks for
184              * subspans 0 and 1) in SIMD8 and an additional byte (the pixel
185              * masks for 2 and 3) in SIMD16.
186              */
187             fs_reg shifted = abld.vgrf(BRW_REGISTER_TYPE_UW, 1);
188             abld.SHR(shifted,
189                      stride(byte_offset(retype(brw_vec1_grf(1, 0),
190                                                BRW_REGISTER_TYPE_UB), 28),
191                             1, 8, 0),
192                      brw_imm_v(0x76543210));
193
194             /* A set bit in the pixel mask means the channel is enabled, but
195              * that is the opposite of gl_HelperInvocation so we need to invert
196              * the mask.
197              *
198              * The negate source-modifier bit of logical instructions on Gen8+
199              * performs 1's complement negation, so we can use that instead of
200              * a NOT instruction.
201              */
202             fs_reg inverted = negate(shifted);
203             if (v->devinfo->gen < 8) {
204                inverted = abld.vgrf(BRW_REGISTER_TYPE_UW);
205                abld.NOT(inverted, shifted);
206             }
207
208             /* We then resolve the 0/1 result to 0/~0 boolean values by ANDing
209              * with 1 and negating.
210              */
211             fs_reg anded = abld.vgrf(BRW_REGISTER_TYPE_UD, 1);
212             abld.AND(anded, inverted, brw_imm_uw(1));
213
214             fs_reg dst = abld.vgrf(BRW_REGISTER_TYPE_D, 1);
215             abld.MOV(dst, negate(retype(anded, BRW_REGISTER_TYPE_D)));
216             *reg = dst;
217          }
218          break;
219
220       default:
221          break;
222       }
223    }
224
225    return true;
226 }
227
228 void
229 fs_visitor::nir_emit_system_values()
230 {
231    nir_system_values = ralloc_array(mem_ctx, fs_reg, SYSTEM_VALUE_MAX);
232    for (unsigned i = 0; i < SYSTEM_VALUE_MAX; i++) {
233       nir_system_values[i] = fs_reg();
234    }
235
236    /* Always emit SUBGROUP_INVOCATION.  Dead code will clean it up if we
237     * never end up using it.
238     */
239    {
240       const fs_builder abld = bld.annotate("gl_SubgroupInvocation", NULL);
241       fs_reg &reg = nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION];
242       reg = abld.vgrf(BRW_REGISTER_TYPE_UW);
243
244       const fs_builder allbld8 = abld.group(8, 0).exec_all();
245       allbld8.MOV(reg, brw_imm_v(0x76543210));
246       if (dispatch_width > 8)
247          allbld8.ADD(byte_offset(reg, 16), reg, brw_imm_uw(8u));
248       if (dispatch_width > 16) {
249          const fs_builder allbld16 = abld.group(16, 0).exec_all();
250          allbld16.ADD(byte_offset(reg, 32), reg, brw_imm_uw(16u));
251       }
252    }
253
254    nir_foreach_function(function, nir) {
255       assert(strcmp(function->name, "main") == 0);
256       assert(function->impl);
257       nir_foreach_block(block, function->impl) {
258          emit_system_values_block(block, this);
259       }
260    }
261 }
262
263 /*
264  * Returns a type based on a reference_type (word, float, half-float) and a
265  * given bit_size.
266  *
267  * Reference BRW_REGISTER_TYPE are HF,F,DF,W,D,UW,UD.
268  *
269  * @FIXME: 64-bit return types are always DF on integer types to maintain
270  * compability with uses of DF previously to the introduction of int64
271  * support.
272  */
273 static brw_reg_type
274 brw_reg_type_from_bit_size(const unsigned bit_size,
275                            const brw_reg_type reference_type)
276 {
277    switch(reference_type) {
278    case BRW_REGISTER_TYPE_HF:
279    case BRW_REGISTER_TYPE_F:
280    case BRW_REGISTER_TYPE_DF:
281       switch(bit_size) {
282       case 16:
283          return BRW_REGISTER_TYPE_HF;
284       case 32:
285          return BRW_REGISTER_TYPE_F;
286       case 64:
287          return BRW_REGISTER_TYPE_DF;
288       default:
289          unreachable("Invalid bit size");
290       }
291    case BRW_REGISTER_TYPE_W:
292    case BRW_REGISTER_TYPE_D:
293    case BRW_REGISTER_TYPE_Q:
294       switch(bit_size) {
295       case 16:
296          return BRW_REGISTER_TYPE_W;
297       case 32:
298          return BRW_REGISTER_TYPE_D;
299       case 64:
300          return BRW_REGISTER_TYPE_Q;
301       default:
302          unreachable("Invalid bit size");
303       }
304    case BRW_REGISTER_TYPE_UW:
305    case BRW_REGISTER_TYPE_UD:
306    case BRW_REGISTER_TYPE_UQ:
307       switch(bit_size) {
308       case 16:
309          return BRW_REGISTER_TYPE_UW;
310       case 32:
311          return BRW_REGISTER_TYPE_UD;
312       case 64:
313          return BRW_REGISTER_TYPE_UQ;
314       default:
315          unreachable("Invalid bit size");
316       }
317    default:
318       unreachable("Unknown type");
319    }
320 }
321
322 void
323 fs_visitor::nir_emit_impl(nir_function_impl *impl)
324 {
325    nir_locals = ralloc_array(mem_ctx, fs_reg, impl->reg_alloc);
326    for (unsigned i = 0; i < impl->reg_alloc; i++) {
327       nir_locals[i] = fs_reg();
328    }
329
330    foreach_list_typed(nir_register, reg, node, &impl->registers) {
331       unsigned array_elems =
332          reg->num_array_elems == 0 ? 1 : reg->num_array_elems;
333       unsigned size = array_elems * reg->num_components;
334       const brw_reg_type reg_type =
335          brw_reg_type_from_bit_size(reg->bit_size, BRW_REGISTER_TYPE_F);
336       nir_locals[reg->index] = bld.vgrf(reg_type, size);
337    }
338
339    nir_ssa_values = reralloc(mem_ctx, nir_ssa_values, fs_reg,
340                              impl->ssa_alloc);
341
342    nir_emit_cf_list(&impl->body);
343 }
344
345 void
346 fs_visitor::nir_emit_cf_list(exec_list *list)
347 {
348    exec_list_validate(list);
349    foreach_list_typed(nir_cf_node, node, node, list) {
350       switch (node->type) {
351       case nir_cf_node_if:
352          nir_emit_if(nir_cf_node_as_if(node));
353          break;
354
355       case nir_cf_node_loop:
356          nir_emit_loop(nir_cf_node_as_loop(node));
357          break;
358
359       case nir_cf_node_block:
360          nir_emit_block(nir_cf_node_as_block(node));
361          break;
362
363       default:
364          unreachable("Invalid CFG node block");
365       }
366    }
367 }
368
369 void
370 fs_visitor::nir_emit_if(nir_if *if_stmt)
371 {
372    /* first, put the condition into f0 */
373    fs_inst *inst = bld.MOV(bld.null_reg_d(),
374                             retype(get_nir_src(if_stmt->condition),
375                                    BRW_REGISTER_TYPE_D));
376    inst->conditional_mod = BRW_CONDITIONAL_NZ;
377
378    bld.IF(BRW_PREDICATE_NORMAL);
379
380    nir_emit_cf_list(&if_stmt->then_list);
381
382    /* note: if the else is empty, dead CF elimination will remove it */
383    bld.emit(BRW_OPCODE_ELSE);
384
385    nir_emit_cf_list(&if_stmt->else_list);
386
387    bld.emit(BRW_OPCODE_ENDIF);
388 }
389
390 void
391 fs_visitor::nir_emit_loop(nir_loop *loop)
392 {
393    bld.emit(BRW_OPCODE_DO);
394
395    nir_emit_cf_list(&loop->body);
396
397    bld.emit(BRW_OPCODE_WHILE);
398 }
399
400 void
401 fs_visitor::nir_emit_block(nir_block *block)
402 {
403    nir_foreach_instr(instr, block) {
404       nir_emit_instr(instr);
405    }
406 }
407
408 void
409 fs_visitor::nir_emit_instr(nir_instr *instr)
410 {
411    const fs_builder abld = bld.annotate(NULL, instr);
412
413    switch (instr->type) {
414    case nir_instr_type_alu:
415       nir_emit_alu(abld, nir_instr_as_alu(instr));
416       break;
417
418    case nir_instr_type_intrinsic:
419       switch (stage) {
420       case MESA_SHADER_VERTEX:
421          nir_emit_vs_intrinsic(abld, nir_instr_as_intrinsic(instr));
422          break;
423       case MESA_SHADER_TESS_CTRL:
424          nir_emit_tcs_intrinsic(abld, nir_instr_as_intrinsic(instr));
425          break;
426       case MESA_SHADER_TESS_EVAL:
427          nir_emit_tes_intrinsic(abld, nir_instr_as_intrinsic(instr));
428          break;
429       case MESA_SHADER_GEOMETRY:
430          nir_emit_gs_intrinsic(abld, nir_instr_as_intrinsic(instr));
431          break;
432       case MESA_SHADER_FRAGMENT:
433          nir_emit_fs_intrinsic(abld, nir_instr_as_intrinsic(instr));
434          break;
435       case MESA_SHADER_COMPUTE:
436          nir_emit_cs_intrinsic(abld, nir_instr_as_intrinsic(instr));
437          break;
438       default:
439          unreachable("unsupported shader stage");
440       }
441       break;
442
443    case nir_instr_type_tex:
444       nir_emit_texture(abld, nir_instr_as_tex(instr));
445       break;
446
447    case nir_instr_type_load_const:
448       nir_emit_load_const(abld, nir_instr_as_load_const(instr));
449       break;
450
451    case nir_instr_type_ssa_undef:
452       /* We create a new VGRF for undefs on every use (by handling
453        * them in get_nir_src()), rather than for each definition.
454        * This helps register coalescing eliminate MOVs from undef.
455        */
456       break;
457
458    case nir_instr_type_jump:
459       nir_emit_jump(abld, nir_instr_as_jump(instr));
460       break;
461
462    default:
463       unreachable("unknown instruction type");
464    }
465 }
466
467 /**
468  * Recognizes a parent instruction of nir_op_extract_* and changes the type to
469  * match instr.
470  */
471 bool
472 fs_visitor::optimize_extract_to_float(nir_alu_instr *instr,
473                                       const fs_reg &result)
474 {
475    if (!instr->src[0].src.is_ssa ||
476        !instr->src[0].src.ssa->parent_instr)
477       return false;
478
479    if (instr->src[0].src.ssa->parent_instr->type != nir_instr_type_alu)
480       return false;
481
482    nir_alu_instr *src0 =
483       nir_instr_as_alu(instr->src[0].src.ssa->parent_instr);
484
485    if (src0->op != nir_op_extract_u8 && src0->op != nir_op_extract_u16 &&
486        src0->op != nir_op_extract_i8 && src0->op != nir_op_extract_i16)
487       return false;
488
489    nir_const_value *element = nir_src_as_const_value(src0->src[1].src);
490    assert(element != NULL);
491
492    /* Element type to extract.*/
493    const brw_reg_type type = brw_int_type(
494       src0->op == nir_op_extract_u16 || src0->op == nir_op_extract_i16 ? 2 : 1,
495       src0->op == nir_op_extract_i16 || src0->op == nir_op_extract_i8);
496
497    fs_reg op0 = get_nir_src(src0->src[0].src);
498    op0.type = brw_type_for_nir_type(devinfo,
499       (nir_alu_type)(nir_op_infos[src0->op].input_types[0] |
500                      nir_src_bit_size(src0->src[0].src)));
501    op0 = offset(op0, bld, src0->src[0].swizzle[0]);
502
503    set_saturate(instr->dest.saturate,
504                 bld.MOV(result, subscript(op0, type, element->u32[0])));
505    return true;
506 }
507
508 bool
509 fs_visitor::optimize_frontfacing_ternary(nir_alu_instr *instr,
510                                          const fs_reg &result)
511 {
512    if (!instr->src[0].src.is_ssa ||
513        instr->src[0].src.ssa->parent_instr->type != nir_instr_type_intrinsic)
514       return false;
515
516    nir_intrinsic_instr *src0 =
517       nir_instr_as_intrinsic(instr->src[0].src.ssa->parent_instr);
518
519    if (src0->intrinsic != nir_intrinsic_load_front_face)
520       return false;
521
522    nir_const_value *value1 = nir_src_as_const_value(instr->src[1].src);
523    if (!value1 || fabsf(value1->f32[0]) != 1.0f)
524       return false;
525
526    nir_const_value *value2 = nir_src_as_const_value(instr->src[2].src);
527    if (!value2 || fabsf(value2->f32[0]) != 1.0f)
528       return false;
529
530    fs_reg tmp = vgrf(glsl_type::int_type);
531
532    if (devinfo->gen >= 6) {
533       /* Bit 15 of g0.0 is 0 if the polygon is front facing. */
534       fs_reg g0 = fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_W));
535
536       /* For (gl_FrontFacing ? 1.0 : -1.0), emit:
537        *
538        *    or(8)  tmp.1<2>W  g0.0<0,1,0>W  0x00003f80W
539        *    and(8) dst<1>D    tmp<8,8,1>D   0xbf800000D
540        *
541        * and negate g0.0<0,1,0>W for (gl_FrontFacing ? -1.0 : 1.0).
542        *
543        * This negation looks like it's safe in practice, because bits 0:4 will
544        * surely be TRIANGLES
545        */
546
547       if (value1->f32[0] == -1.0f) {
548          g0.negate = true;
549       }
550
551       bld.OR(subscript(tmp, BRW_REGISTER_TYPE_W, 1),
552              g0, brw_imm_uw(0x3f80));
553    } else {
554       /* Bit 31 of g1.6 is 0 if the polygon is front facing. */
555       fs_reg g1_6 = fs_reg(retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_D));
556
557       /* For (gl_FrontFacing ? 1.0 : -1.0), emit:
558        *
559        *    or(8)  tmp<1>D  g1.6<0,1,0>D  0x3f800000D
560        *    and(8) dst<1>D  tmp<8,8,1>D   0xbf800000D
561        *
562        * and negate g1.6<0,1,0>D for (gl_FrontFacing ? -1.0 : 1.0).
563        *
564        * This negation looks like it's safe in practice, because bits 0:4 will
565        * surely be TRIANGLES
566        */
567
568       if (value1->f32[0] == -1.0f) {
569          g1_6.negate = true;
570       }
571
572       bld.OR(tmp, g1_6, brw_imm_d(0x3f800000));
573    }
574    bld.AND(retype(result, BRW_REGISTER_TYPE_D), tmp, brw_imm_d(0xbf800000));
575
576    return true;
577 }
578
579 static void
580 emit_find_msb_using_lzd(const fs_builder &bld,
581                         const fs_reg &result,
582                         const fs_reg &src,
583                         bool is_signed)
584 {
585    fs_inst *inst;
586    fs_reg temp = src;
587
588    if (is_signed) {
589       /* LZD of an absolute value source almost always does the right
590        * thing.  There are two problem values:
591        *
592        * * 0x80000000.  Since abs(0x80000000) == 0x80000000, LZD returns
593        *   0.  However, findMSB(int(0x80000000)) == 30.
594        *
595        * * 0xffffffff.  Since abs(0xffffffff) == 1, LZD returns
596        *   31.  Section 8.8 (Integer Functions) of the GLSL 4.50 spec says:
597        *
598        *    For a value of zero or negative one, -1 will be returned.
599        *
600        * * Negative powers of two.  LZD(abs(-(1<<x))) returns x, but
601        *   findMSB(-(1<<x)) should return x-1.
602        *
603        * For all negative number cases, including 0x80000000 and
604        * 0xffffffff, the correct value is obtained from LZD if instead of
605        * negating the (already negative) value the logical-not is used.  A
606        * conditonal logical-not can be achieved in two instructions.
607        */
608       temp = bld.vgrf(BRW_REGISTER_TYPE_D);
609
610       bld.ASR(temp, src, brw_imm_d(31));
611       bld.XOR(temp, temp, src);
612    }
613
614    bld.LZD(retype(result, BRW_REGISTER_TYPE_UD),
615            retype(temp, BRW_REGISTER_TYPE_UD));
616
617    /* LZD counts from the MSB side, while GLSL's findMSB() wants the count
618     * from the LSB side. Subtract the result from 31 to convert the MSB
619     * count into an LSB count.  If no bits are set, LZD will return 32.
620     * 31-32 = -1, which is exactly what findMSB() is supposed to return.
621     */
622    inst = bld.ADD(result, retype(result, BRW_REGISTER_TYPE_D), brw_imm_d(31));
623    inst->src[0].negate = true;
624 }
625
626 static brw_rnd_mode
627 brw_rnd_mode_from_nir_op (const nir_op op) {
628    switch (op) {
629    case nir_op_f2f16_rtz:
630       return BRW_RND_MODE_RTZ;
631    case nir_op_f2f16_rtne:
632       return BRW_RND_MODE_RTNE;
633    default:
634       unreachable("Operation doesn't support rounding mode");
635    }
636 }
637
638 void
639 fs_visitor::nir_emit_alu(const fs_builder &bld, nir_alu_instr *instr)
640 {
641    struct brw_wm_prog_key *fs_key = (struct brw_wm_prog_key *) this->key;
642    fs_inst *inst;
643
644    fs_reg result = get_nir_dest(instr->dest.dest);
645    result.type = brw_type_for_nir_type(devinfo,
646       (nir_alu_type)(nir_op_infos[instr->op].output_type |
647                      nir_dest_bit_size(instr->dest.dest)));
648
649    fs_reg op[4];
650    for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
651       op[i] = get_nir_src(instr->src[i].src);
652       op[i].type = brw_type_for_nir_type(devinfo,
653          (nir_alu_type)(nir_op_infos[instr->op].input_types[i] |
654                         nir_src_bit_size(instr->src[i].src)));
655       op[i].abs = instr->src[i].abs;
656       op[i].negate = instr->src[i].negate;
657    }
658
659    /* We get a bunch of mov's out of the from_ssa pass and they may still
660     * be vectorized.  We'll handle them as a special-case.  We'll also
661     * handle vecN here because it's basically the same thing.
662     */
663    switch (instr->op) {
664    case nir_op_imov:
665    case nir_op_fmov:
666    case nir_op_vec2:
667    case nir_op_vec3:
668    case nir_op_vec4: {
669       fs_reg temp = result;
670       bool need_extra_copy = false;
671       for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
672          if (!instr->src[i].src.is_ssa &&
673              instr->dest.dest.reg.reg == instr->src[i].src.reg.reg) {
674             need_extra_copy = true;
675             temp = bld.vgrf(result.type, 4);
676             break;
677          }
678       }
679
680       for (unsigned i = 0; i < 4; i++) {
681          if (!(instr->dest.write_mask & (1 << i)))
682             continue;
683
684          if (instr->op == nir_op_imov || instr->op == nir_op_fmov) {
685             inst = bld.MOV(offset(temp, bld, i),
686                            offset(op[0], bld, instr->src[0].swizzle[i]));
687          } else {
688             inst = bld.MOV(offset(temp, bld, i),
689                            offset(op[i], bld, instr->src[i].swizzle[0]));
690          }
691          inst->saturate = instr->dest.saturate;
692       }
693
694       /* In this case the source and destination registers were the same,
695        * so we need to insert an extra set of moves in order to deal with
696        * any swizzling.
697        */
698       if (need_extra_copy) {
699          for (unsigned i = 0; i < 4; i++) {
700             if (!(instr->dest.write_mask & (1 << i)))
701                continue;
702
703             bld.MOV(offset(result, bld, i), offset(temp, bld, i));
704          }
705       }
706       return;
707    }
708    default:
709       break;
710    }
711
712    /* At this point, we have dealt with any instruction that operates on
713     * more than a single channel.  Therefore, we can just adjust the source
714     * and destination registers for that channel and emit the instruction.
715     */
716    unsigned channel = 0;
717    if (nir_op_infos[instr->op].output_size == 0) {
718       /* Since NIR is doing the scalarizing for us, we should only ever see
719        * vectorized operations with a single channel.
720        */
721       assert(_mesa_bitcount(instr->dest.write_mask) == 1);
722       channel = ffs(instr->dest.write_mask) - 1;
723
724       result = offset(result, bld, channel);
725    }
726
727    for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
728       assert(nir_op_infos[instr->op].input_sizes[i] < 2);
729       op[i] = offset(op[i], bld, instr->src[i].swizzle[channel]);
730    }
731
732    switch (instr->op) {
733    case nir_op_i2f32:
734    case nir_op_u2f32:
735       if (optimize_extract_to_float(instr, result))
736          return;
737       inst = bld.MOV(result, op[0]);
738       inst->saturate = instr->dest.saturate;
739       break;
740
741    case nir_op_f2f16_rtne:
742    case nir_op_f2f16_rtz:
743       bld.emit(SHADER_OPCODE_RND_MODE, bld.null_reg_ud(),
744                brw_imm_d(brw_rnd_mode_from_nir_op(instr->op)));
745       /* fallthrough */
746
747       /* In theory, it would be better to use BRW_OPCODE_F32TO16. Depending
748        * on the HW gen, it is a special hw opcode or just a MOV, and
749        * brw_F32TO16 (at brw_eu_emit) would do the work to chose.
750        *
751        * But if we want to use that opcode, we need to provide support on
752        * different optimizations and lowerings. As right now HF support is
753        * only for gen8+, it will be better to use directly the MOV, and use
754        * BRW_OPCODE_F32TO16 when/if we work for HF support on gen7.
755        */
756
757    case nir_op_f2f16_undef:
758       inst = bld.MOV(result, op[0]);
759       inst->saturate = instr->dest.saturate;
760       break;
761
762    case nir_op_f2f64:
763    case nir_op_f2i64:
764    case nir_op_f2u64:
765    case nir_op_i2f64:
766    case nir_op_i2i64:
767    case nir_op_u2f64:
768    case nir_op_u2u64:
769       /* CHV PRM, vol07, 3D Media GPGPU Engine, Register Region Restrictions:
770        *
771        *    "When source or destination is 64b (...), regioning in Align1
772        *     must follow these rules:
773        *
774        *     1. Source and destination horizontal stride must be aligned to
775        *        the same qword.
776        *     (...)"
777        *
778        * This means that conversions from bit-sizes smaller than 64-bit to
779        * 64-bit need to have the source data elements aligned to 64-bit.
780        * This restriction does not apply to BDW and later.
781        */
782       if (nir_dest_bit_size(instr->dest.dest) == 64 &&
783           nir_src_bit_size(instr->src[0].src) < 64 &&
784           (devinfo->is_cherryview || gen_device_info_is_9lp(devinfo))) {
785          fs_reg tmp = bld.vgrf(result.type, 1);
786          tmp = subscript(tmp, op[0].type, 0);
787          inst = bld.MOV(tmp, op[0]);
788          inst = bld.MOV(result, tmp);
789          inst->saturate = instr->dest.saturate;
790          break;
791       }
792       /* fallthrough */
793    case nir_op_f2f32:
794    case nir_op_f2i32:
795    case nir_op_f2u32:
796    case nir_op_f2i16:
797    case nir_op_f2u16:
798    case nir_op_i2i32:
799    case nir_op_u2u32:
800    case nir_op_i2i16:
801    case nir_op_u2u16:
802    case nir_op_i2f16:
803    case nir_op_u2f16:
804       inst = bld.MOV(result, op[0]);
805       inst->saturate = instr->dest.saturate;
806       break;
807
808    case nir_op_fsign: {
809       if (op[0].abs) {
810          /* Straightforward since the source can be assumed to be
811           * non-negative.
812           */
813          set_condmod(BRW_CONDITIONAL_NZ, bld.MOV(result, op[0]));
814          set_predicate(BRW_PREDICATE_NORMAL, bld.MOV(result, brw_imm_f(1.0f)));
815
816       } else if (type_sz(op[0].type) < 8) {
817          /* AND(val, 0x80000000) gives the sign bit.
818           *
819           * Predicated OR ORs 1.0 (0x3f800000) with the sign bit if val is not
820           * zero.
821           */
822          bld.CMP(bld.null_reg_f(), op[0], brw_imm_f(0.0f), BRW_CONDITIONAL_NZ);
823
824          fs_reg result_int = retype(result, BRW_REGISTER_TYPE_UD);
825          op[0].type = BRW_REGISTER_TYPE_UD;
826          result.type = BRW_REGISTER_TYPE_UD;
827          bld.AND(result_int, op[0], brw_imm_ud(0x80000000u));
828
829          inst = bld.OR(result_int, result_int, brw_imm_ud(0x3f800000u));
830          inst->predicate = BRW_PREDICATE_NORMAL;
831          if (instr->dest.saturate) {
832             inst = bld.MOV(result, result);
833             inst->saturate = true;
834          }
835       } else {
836          /* For doubles we do the same but we need to consider:
837           *
838           * - 2-src instructions can't operate with 64-bit immediates
839           * - The sign is encoded in the high 32-bit of each DF
840           * - We need to produce a DF result.
841           */
842
843          fs_reg zero = vgrf(glsl_type::double_type);
844          bld.MOV(zero, setup_imm_df(bld, 0.0));
845          bld.CMP(bld.null_reg_df(), op[0], zero, BRW_CONDITIONAL_NZ);
846
847          bld.MOV(result, zero);
848
849          fs_reg r = subscript(result, BRW_REGISTER_TYPE_UD, 1);
850          bld.AND(r, subscript(op[0], BRW_REGISTER_TYPE_UD, 1),
851                  brw_imm_ud(0x80000000u));
852
853          set_predicate(BRW_PREDICATE_NORMAL,
854                        bld.OR(r, r, brw_imm_ud(0x3ff00000u)));
855
856          if (instr->dest.saturate) {
857             inst = bld.MOV(result, result);
858             inst->saturate = true;
859          }
860       }
861       break;
862    }
863
864    case nir_op_isign: {
865       /*  ASR(val, 31) -> negative val generates 0xffffffff (signed -1).
866        *               -> non-negative val generates 0x00000000.
867        *  Predicated OR sets 1 if val is positive.
868        */
869       uint32_t bit_size = nir_dest_bit_size(instr->dest.dest);
870       assert(bit_size == 32 || bit_size == 16);
871
872       fs_reg zero = bit_size == 32 ? brw_imm_d(0) : brw_imm_w(0);
873       fs_reg one = bit_size == 32 ? brw_imm_d(1) : brw_imm_w(1);
874       fs_reg shift = bit_size == 32 ? brw_imm_d(31) : brw_imm_w(15);
875
876       bld.CMP(bld.null_reg_d(), op[0], zero, BRW_CONDITIONAL_G);
877       bld.ASR(result, op[0], shift);
878       inst = bld.OR(result, result, one);
879       inst->predicate = BRW_PREDICATE_NORMAL;
880       break;
881    }
882
883    case nir_op_frcp:
884       inst = bld.emit(SHADER_OPCODE_RCP, result, op[0]);
885       inst->saturate = instr->dest.saturate;
886       break;
887
888    case nir_op_fexp2:
889       inst = bld.emit(SHADER_OPCODE_EXP2, result, op[0]);
890       inst->saturate = instr->dest.saturate;
891       break;
892
893    case nir_op_flog2:
894       inst = bld.emit(SHADER_OPCODE_LOG2, result, op[0]);
895       inst->saturate = instr->dest.saturate;
896       break;
897
898    case nir_op_fsin:
899       inst = bld.emit(SHADER_OPCODE_SIN, result, op[0]);
900       inst->saturate = instr->dest.saturate;
901       break;
902
903    case nir_op_fcos:
904       inst = bld.emit(SHADER_OPCODE_COS, result, op[0]);
905       inst->saturate = instr->dest.saturate;
906       break;
907
908    case nir_op_fddx:
909       if (fs_key->high_quality_derivatives) {
910          inst = bld.emit(FS_OPCODE_DDX_FINE, result, op[0]);
911       } else {
912          inst = bld.emit(FS_OPCODE_DDX_COARSE, result, op[0]);
913       }
914       inst->saturate = instr->dest.saturate;
915       break;
916    case nir_op_fddx_fine:
917       inst = bld.emit(FS_OPCODE_DDX_FINE, result, op[0]);
918       inst->saturate = instr->dest.saturate;
919       break;
920    case nir_op_fddx_coarse:
921       inst = bld.emit(FS_OPCODE_DDX_COARSE, result, op[0]);
922       inst->saturate = instr->dest.saturate;
923       break;
924    case nir_op_fddy:
925       if (fs_key->high_quality_derivatives) {
926          inst = bld.emit(FS_OPCODE_DDY_FINE, result, op[0]);
927       } else {
928          inst = bld.emit(FS_OPCODE_DDY_COARSE, result, op[0]);
929       }
930       inst->saturate = instr->dest.saturate;
931       break;
932    case nir_op_fddy_fine:
933       inst = bld.emit(FS_OPCODE_DDY_FINE, result, op[0]);
934       inst->saturate = instr->dest.saturate;
935       break;
936    case nir_op_fddy_coarse:
937       inst = bld.emit(FS_OPCODE_DDY_COARSE, result, op[0]);
938       inst->saturate = instr->dest.saturate;
939       break;
940
941    case nir_op_iadd:
942    case nir_op_fadd:
943       inst = bld.ADD(result, op[0], op[1]);
944       inst->saturate = instr->dest.saturate;
945       break;
946
947    case nir_op_fmul:
948       inst = bld.MUL(result, op[0], op[1]);
949       inst->saturate = instr->dest.saturate;
950       break;
951
952    case nir_op_imul:
953       assert(nir_dest_bit_size(instr->dest.dest) < 64);
954       bld.MUL(result, op[0], op[1]);
955       break;
956
957    case nir_op_imul_high:
958    case nir_op_umul_high:
959       assert(nir_dest_bit_size(instr->dest.dest) < 64);
960       bld.emit(SHADER_OPCODE_MULH, result, op[0], op[1]);
961       break;
962
963    case nir_op_idiv:
964    case nir_op_udiv:
965       assert(nir_dest_bit_size(instr->dest.dest) < 64);
966       bld.emit(SHADER_OPCODE_INT_QUOTIENT, result, op[0], op[1]);
967       break;
968
969    case nir_op_uadd_carry:
970       unreachable("Should have been lowered by carry_to_arith().");
971
972    case nir_op_usub_borrow:
973       unreachable("Should have been lowered by borrow_to_arith().");
974
975    case nir_op_umod:
976    case nir_op_irem:
977       /* According to the sign table for INT DIV in the Ivy Bridge PRM, it
978        * appears that our hardware just does the right thing for signed
979        * remainder.
980        */
981       assert(nir_dest_bit_size(instr->dest.dest) < 64);
982       bld.emit(SHADER_OPCODE_INT_REMAINDER, result, op[0], op[1]);
983       break;
984
985    case nir_op_imod: {
986       /* Get a regular C-style remainder.  If a % b == 0, set the predicate. */
987       bld.emit(SHADER_OPCODE_INT_REMAINDER, result, op[0], op[1]);
988
989       /* Math instructions don't support conditional mod */
990       inst = bld.MOV(bld.null_reg_d(), result);
991       inst->conditional_mod = BRW_CONDITIONAL_NZ;
992
993       /* Now, we need to determine if signs of the sources are different.
994        * When we XOR the sources, the top bit is 0 if they are the same and 1
995        * if they are different.  We can then use a conditional modifier to
996        * turn that into a predicate.  This leads us to an XOR.l instruction.
997        *
998        * Technically, according to the PRM, you're not allowed to use .l on a
999        * XOR instruction.  However, emperical experiments and Curro's reading
1000        * of the simulator source both indicate that it's safe.
1001        */
1002       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_D);
1003       inst = bld.XOR(tmp, op[0], op[1]);
1004       inst->predicate = BRW_PREDICATE_NORMAL;
1005       inst->conditional_mod = BRW_CONDITIONAL_L;
1006
1007       /* If the result of the initial remainder operation is non-zero and the
1008        * two sources have different signs, add in a copy of op[1] to get the
1009        * final integer modulus value.
1010        */
1011       inst = bld.ADD(result, result, op[1]);
1012       inst->predicate = BRW_PREDICATE_NORMAL;
1013       break;
1014    }
1015
1016    case nir_op_flt:
1017    case nir_op_fge:
1018    case nir_op_feq:
1019    case nir_op_fne: {
1020       fs_reg dest = result;
1021
1022       const uint32_t bit_size =  nir_src_bit_size(instr->src[0].src);
1023       if (bit_size != 32)
1024          dest = bld.vgrf(op[0].type, 1);
1025
1026       brw_conditional_mod cond;
1027       switch (instr->op) {
1028       case nir_op_flt:
1029          cond = BRW_CONDITIONAL_L;
1030          break;
1031       case nir_op_fge:
1032          cond = BRW_CONDITIONAL_GE;
1033          break;
1034       case nir_op_feq:
1035          cond = BRW_CONDITIONAL_Z;
1036          break;
1037       case nir_op_fne:
1038          cond = BRW_CONDITIONAL_NZ;
1039          break;
1040       default:
1041          unreachable("bad opcode");
1042       }
1043
1044       bld.CMP(dest, op[0], op[1], cond);
1045
1046       if (bit_size > 32) {
1047          bld.MOV(result, subscript(dest, BRW_REGISTER_TYPE_UD, 0));
1048       } else if(bit_size < 32) {
1049          /* When we convert the result to 32-bit we need to be careful and do
1050           * it as a signed conversion to get sign extension (for 32-bit true)
1051           */
1052          const brw_reg_type src_type =
1053             brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_D);
1054
1055          bld.MOV(retype(result, BRW_REGISTER_TYPE_D), retype(dest, src_type));
1056       }
1057       break;
1058    }
1059
1060    case nir_op_ilt:
1061    case nir_op_ult:
1062    case nir_op_ige:
1063    case nir_op_uge:
1064    case nir_op_ieq:
1065    case nir_op_ine: {
1066       fs_reg dest = result;
1067
1068       const uint32_t bit_size = nir_src_bit_size(instr->src[0].src);
1069       if (bit_size != 32)
1070          dest = bld.vgrf(op[0].type, 1);
1071
1072       brw_conditional_mod cond;
1073       switch (instr->op) {
1074       case nir_op_ilt:
1075       case nir_op_ult:
1076          cond = BRW_CONDITIONAL_L;
1077          break;
1078       case nir_op_ige:
1079       case nir_op_uge:
1080          cond = BRW_CONDITIONAL_GE;
1081          break;
1082       case nir_op_ieq:
1083          cond = BRW_CONDITIONAL_Z;
1084          break;
1085       case nir_op_ine:
1086          cond = BRW_CONDITIONAL_NZ;
1087          break;
1088       default:
1089          unreachable("bad opcode");
1090       }
1091       bld.CMP(dest, op[0], op[1], cond);
1092
1093       if (bit_size > 32) {
1094          bld.MOV(result, subscript(dest, BRW_REGISTER_TYPE_UD, 0));
1095       } else if (bit_size < 32) {
1096          /* When we convert the result to 32-bit we need to be careful and do
1097           * it as a signed conversion to get sign extension (for 32-bit true)
1098           */
1099          const brw_reg_type src_type =
1100             brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_D);
1101
1102          bld.MOV(retype(result, BRW_REGISTER_TYPE_D), retype(dest, src_type));
1103       }
1104       break;
1105    }
1106
1107    case nir_op_inot:
1108       if (devinfo->gen >= 8) {
1109          op[0] = resolve_source_modifiers(op[0]);
1110       }
1111       bld.NOT(result, op[0]);
1112       break;
1113    case nir_op_ixor:
1114       if (devinfo->gen >= 8) {
1115          op[0] = resolve_source_modifiers(op[0]);
1116          op[1] = resolve_source_modifiers(op[1]);
1117       }
1118       bld.XOR(result, op[0], op[1]);
1119       break;
1120    case nir_op_ior:
1121       if (devinfo->gen >= 8) {
1122          op[0] = resolve_source_modifiers(op[0]);
1123          op[1] = resolve_source_modifiers(op[1]);
1124       }
1125       bld.OR(result, op[0], op[1]);
1126       break;
1127    case nir_op_iand:
1128       if (devinfo->gen >= 8) {
1129          op[0] = resolve_source_modifiers(op[0]);
1130          op[1] = resolve_source_modifiers(op[1]);
1131       }
1132       bld.AND(result, op[0], op[1]);
1133       break;
1134
1135    case nir_op_fdot2:
1136    case nir_op_fdot3:
1137    case nir_op_fdot4:
1138    case nir_op_ball_fequal2:
1139    case nir_op_ball_iequal2:
1140    case nir_op_ball_fequal3:
1141    case nir_op_ball_iequal3:
1142    case nir_op_ball_fequal4:
1143    case nir_op_ball_iequal4:
1144    case nir_op_bany_fnequal2:
1145    case nir_op_bany_inequal2:
1146    case nir_op_bany_fnequal3:
1147    case nir_op_bany_inequal3:
1148    case nir_op_bany_fnequal4:
1149    case nir_op_bany_inequal4:
1150       unreachable("Lowered by nir_lower_alu_reductions");
1151
1152    case nir_op_fnoise1_1:
1153    case nir_op_fnoise1_2:
1154    case nir_op_fnoise1_3:
1155    case nir_op_fnoise1_4:
1156    case nir_op_fnoise2_1:
1157    case nir_op_fnoise2_2:
1158    case nir_op_fnoise2_3:
1159    case nir_op_fnoise2_4:
1160    case nir_op_fnoise3_1:
1161    case nir_op_fnoise3_2:
1162    case nir_op_fnoise3_3:
1163    case nir_op_fnoise3_4:
1164    case nir_op_fnoise4_1:
1165    case nir_op_fnoise4_2:
1166    case nir_op_fnoise4_3:
1167    case nir_op_fnoise4_4:
1168       unreachable("not reached: should be handled by lower_noise");
1169
1170    case nir_op_ldexp:
1171       unreachable("not reached: should be handled by ldexp_to_arith()");
1172
1173    case nir_op_fsqrt:
1174       inst = bld.emit(SHADER_OPCODE_SQRT, result, op[0]);
1175       inst->saturate = instr->dest.saturate;
1176       break;
1177
1178    case nir_op_frsq:
1179       inst = bld.emit(SHADER_OPCODE_RSQ, result, op[0]);
1180       inst->saturate = instr->dest.saturate;
1181       break;
1182
1183    case nir_op_b2i:
1184    case nir_op_b2f:
1185       bld.MOV(result, negate(op[0]));
1186       break;
1187
1188    case nir_op_i2b:
1189    case nir_op_f2b: {
1190       uint32_t bit_size = nir_src_bit_size(instr->src[0].src);
1191       if (bit_size == 64) {
1192          /* two-argument instructions can't take 64-bit immediates */
1193          fs_reg zero;
1194          fs_reg tmp;
1195
1196          if (instr->op == nir_op_f2b) {
1197             zero = vgrf(glsl_type::double_type);
1198             tmp = vgrf(glsl_type::double_type);
1199             bld.MOV(zero, setup_imm_df(bld, 0.0));
1200          } else {
1201             zero = vgrf(glsl_type::int64_t_type);
1202             tmp = vgrf(glsl_type::int64_t_type);
1203             bld.MOV(zero, brw_imm_q(0));
1204          }
1205
1206          /* A SIMD16 execution needs to be split in two instructions, so use
1207           * a vgrf instead of the flag register as dst so instruction splitting
1208           * works
1209           */
1210          bld.CMP(tmp, op[0], zero, BRW_CONDITIONAL_NZ);
1211          bld.MOV(result, subscript(tmp, BRW_REGISTER_TYPE_UD, 0));
1212       } else {
1213          fs_reg zero;
1214          if (bit_size == 32) {
1215             zero = instr->op == nir_op_f2b ? brw_imm_f(0.0f) : brw_imm_d(0);
1216          } else {
1217             assert(bit_size == 16);
1218             zero = instr->op == nir_op_f2b ?
1219                retype(brw_imm_w(0), BRW_REGISTER_TYPE_HF) : brw_imm_w(0);
1220          }
1221          bld.CMP(result, op[0], zero, BRW_CONDITIONAL_NZ);
1222       }
1223       break;
1224    }
1225
1226    case nir_op_ftrunc:
1227       inst = bld.RNDZ(result, op[0]);
1228       inst->saturate = instr->dest.saturate;
1229       break;
1230
1231    case nir_op_fceil: {
1232       op[0].negate = !op[0].negate;
1233       fs_reg temp = vgrf(glsl_type::float_type);
1234       bld.RNDD(temp, op[0]);
1235       temp.negate = true;
1236       inst = bld.MOV(result, temp);
1237       inst->saturate = instr->dest.saturate;
1238       break;
1239    }
1240    case nir_op_ffloor:
1241       inst = bld.RNDD(result, op[0]);
1242       inst->saturate = instr->dest.saturate;
1243       break;
1244    case nir_op_ffract:
1245       inst = bld.FRC(result, op[0]);
1246       inst->saturate = instr->dest.saturate;
1247       break;
1248    case nir_op_fround_even:
1249       inst = bld.RNDE(result, op[0]);
1250       inst->saturate = instr->dest.saturate;
1251       break;
1252
1253    case nir_op_fquantize2f16: {
1254       fs_reg tmp16 = bld.vgrf(BRW_REGISTER_TYPE_D);
1255       fs_reg tmp32 = bld.vgrf(BRW_REGISTER_TYPE_F);
1256       fs_reg zero = bld.vgrf(BRW_REGISTER_TYPE_F);
1257
1258       /* The destination stride must be at least as big as the source stride. */
1259       tmp16.type = BRW_REGISTER_TYPE_W;
1260       tmp16.stride = 2;
1261
1262       /* Check for denormal */
1263       fs_reg abs_src0 = op[0];
1264       abs_src0.abs = true;
1265       bld.CMP(bld.null_reg_f(), abs_src0, brw_imm_f(ldexpf(1.0, -14)),
1266               BRW_CONDITIONAL_L);
1267       /* Get the appropriately signed zero */
1268       bld.AND(retype(zero, BRW_REGISTER_TYPE_UD),
1269               retype(op[0], BRW_REGISTER_TYPE_UD),
1270               brw_imm_ud(0x80000000));
1271       /* Do the actual F32 -> F16 -> F32 conversion */
1272       bld.emit(BRW_OPCODE_F32TO16, tmp16, op[0]);
1273       bld.emit(BRW_OPCODE_F16TO32, tmp32, tmp16);
1274       /* Select that or zero based on normal status */
1275       inst = bld.SEL(result, zero, tmp32);
1276       inst->predicate = BRW_PREDICATE_NORMAL;
1277       inst->saturate = instr->dest.saturate;
1278       break;
1279    }
1280
1281    case nir_op_imin:
1282    case nir_op_umin:
1283    case nir_op_fmin:
1284       inst = bld.emit_minmax(result, op[0], op[1], BRW_CONDITIONAL_L);
1285       inst->saturate = instr->dest.saturate;
1286       break;
1287
1288    case nir_op_imax:
1289    case nir_op_umax:
1290    case nir_op_fmax:
1291       inst = bld.emit_minmax(result, op[0], op[1], BRW_CONDITIONAL_GE);
1292       inst->saturate = instr->dest.saturate;
1293       break;
1294
1295    case nir_op_pack_snorm_2x16:
1296    case nir_op_pack_snorm_4x8:
1297    case nir_op_pack_unorm_2x16:
1298    case nir_op_pack_unorm_4x8:
1299    case nir_op_unpack_snorm_2x16:
1300    case nir_op_unpack_snorm_4x8:
1301    case nir_op_unpack_unorm_2x16:
1302    case nir_op_unpack_unorm_4x8:
1303    case nir_op_unpack_half_2x16:
1304    case nir_op_pack_half_2x16:
1305       unreachable("not reached: should be handled by lower_packing_builtins");
1306
1307    case nir_op_unpack_half_2x16_split_x:
1308       inst = bld.emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_X, result, op[0]);
1309       inst->saturate = instr->dest.saturate;
1310       break;
1311    case nir_op_unpack_half_2x16_split_y:
1312       inst = bld.emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_Y, result, op[0]);
1313       inst->saturate = instr->dest.saturate;
1314       break;
1315
1316    case nir_op_pack_64_2x32_split:
1317    case nir_op_pack_32_2x16_split:
1318       bld.emit(FS_OPCODE_PACK, result, op[0], op[1]);
1319       break;
1320
1321    case nir_op_unpack_64_2x32_split_x:
1322    case nir_op_unpack_64_2x32_split_y: {
1323       if (instr->op == nir_op_unpack_64_2x32_split_x)
1324          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UD, 0));
1325       else
1326          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UD, 1));
1327       break;
1328    }
1329
1330    case nir_op_unpack_32_2x16_split_x:
1331    case nir_op_unpack_32_2x16_split_y: {
1332       if (instr->op == nir_op_unpack_32_2x16_split_x)
1333          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UW, 0));
1334       else
1335          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UW, 1));
1336       break;
1337    }
1338
1339    case nir_op_fpow:
1340       inst = bld.emit(SHADER_OPCODE_POW, result, op[0], op[1]);
1341       inst->saturate = instr->dest.saturate;
1342       break;
1343
1344    case nir_op_bitfield_reverse:
1345       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1346       bld.BFREV(result, op[0]);
1347       break;
1348
1349    case nir_op_bit_count:
1350       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1351       bld.CBIT(result, op[0]);
1352       break;
1353
1354    case nir_op_ufind_msb: {
1355       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1356       emit_find_msb_using_lzd(bld, result, op[0], false);
1357       break;
1358    }
1359
1360    case nir_op_ifind_msb: {
1361       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1362
1363       if (devinfo->gen < 7) {
1364          emit_find_msb_using_lzd(bld, result, op[0], true);
1365       } else {
1366          bld.FBH(retype(result, BRW_REGISTER_TYPE_UD), op[0]);
1367
1368          /* FBH counts from the MSB side, while GLSL's findMSB() wants the
1369           * count from the LSB side. If FBH didn't return an error
1370           * (0xFFFFFFFF), then subtract the result from 31 to convert the MSB
1371           * count into an LSB count.
1372           */
1373          bld.CMP(bld.null_reg_d(), result, brw_imm_d(-1), BRW_CONDITIONAL_NZ);
1374
1375          inst = bld.ADD(result, result, brw_imm_d(31));
1376          inst->predicate = BRW_PREDICATE_NORMAL;
1377          inst->src[0].negate = true;
1378       }
1379       break;
1380    }
1381
1382    case nir_op_find_lsb:
1383       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1384
1385       if (devinfo->gen < 7) {
1386          fs_reg temp = vgrf(glsl_type::int_type);
1387
1388          /* (x & -x) generates a value that consists of only the LSB of x.
1389           * For all powers of 2, findMSB(y) == findLSB(y).
1390           */
1391          fs_reg src = retype(op[0], BRW_REGISTER_TYPE_D);
1392          fs_reg negated_src = src;
1393
1394          /* One must be negated, and the other must be non-negated.  It
1395           * doesn't matter which is which.
1396           */
1397          negated_src.negate = true;
1398          src.negate = false;
1399
1400          bld.AND(temp, src, negated_src);
1401          emit_find_msb_using_lzd(bld, result, temp, false);
1402       } else {
1403          bld.FBL(result, op[0]);
1404       }
1405       break;
1406
1407    case nir_op_ubitfield_extract:
1408    case nir_op_ibitfield_extract:
1409       unreachable("should have been lowered");
1410    case nir_op_ubfe:
1411    case nir_op_ibfe:
1412       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1413       bld.BFE(result, op[2], op[1], op[0]);
1414       break;
1415    case nir_op_bfm:
1416       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1417       bld.BFI1(result, op[0], op[1]);
1418       break;
1419    case nir_op_bfi:
1420       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1421       bld.BFI2(result, op[0], op[1], op[2]);
1422       break;
1423
1424    case nir_op_bitfield_insert:
1425       unreachable("not reached: should have been lowered");
1426
1427    case nir_op_ishl:
1428    case nir_op_ishr:
1429    case nir_op_ushr: {
1430       fs_reg shift_count = op[1];
1431
1432       if (devinfo->is_cherryview || gen_device_info_is_9lp(devinfo)) {
1433          if (op[1].file == VGRF &&
1434              (result.type == BRW_REGISTER_TYPE_Q ||
1435               result.type == BRW_REGISTER_TYPE_UQ)) {
1436             shift_count = fs_reg(VGRF, alloc.allocate(dispatch_width / 4),
1437                                  BRW_REGISTER_TYPE_UD);
1438             shift_count.stride = 2;
1439             bld.MOV(shift_count, op[1]);
1440          }
1441       }
1442
1443       switch (instr->op) {
1444       case nir_op_ishl:
1445          bld.SHL(result, op[0], shift_count);
1446          break;
1447       case nir_op_ishr:
1448          bld.ASR(result, op[0], shift_count);
1449          break;
1450       case nir_op_ushr:
1451          bld.SHR(result, op[0], shift_count);
1452          break;
1453       default:
1454          unreachable("not reached");
1455       }
1456       break;
1457    }
1458
1459    case nir_op_pack_half_2x16_split:
1460       bld.emit(FS_OPCODE_PACK_HALF_2x16_SPLIT, result, op[0], op[1]);
1461       break;
1462
1463    case nir_op_ffma:
1464       inst = bld.MAD(result, op[2], op[1], op[0]);
1465       inst->saturate = instr->dest.saturate;
1466       break;
1467
1468    case nir_op_flrp:
1469       inst = bld.LRP(result, op[0], op[1], op[2]);
1470       inst->saturate = instr->dest.saturate;
1471       break;
1472
1473    case nir_op_bcsel:
1474       if (optimize_frontfacing_ternary(instr, result))
1475          return;
1476
1477       bld.CMP(bld.null_reg_d(), op[0], brw_imm_d(0), BRW_CONDITIONAL_NZ);
1478       inst = bld.SEL(result, op[1], op[2]);
1479       inst->predicate = BRW_PREDICATE_NORMAL;
1480       break;
1481
1482    case nir_op_extract_u8:
1483    case nir_op_extract_i8: {
1484       nir_const_value *byte = nir_src_as_const_value(instr->src[1].src);
1485       assert(byte != NULL);
1486
1487       /* The PRMs say:
1488        *
1489        *    BDW+
1490        *    There is no direct conversion from B/UB to Q/UQ or Q/UQ to B/UB.
1491        *    Use two instructions and a word or DWord intermediate integer type.
1492        */
1493       if (nir_dest_bit_size(instr->dest.dest) == 64) {
1494          const brw_reg_type type = brw_int_type(2, instr->op == nir_op_extract_i8);
1495
1496          if (instr->op == nir_op_extract_i8) {
1497             /* If we need to sign extend, extract to a word first */
1498             fs_reg w_temp = bld.vgrf(BRW_REGISTER_TYPE_W);
1499             bld.MOV(w_temp, subscript(op[0], type, byte->u32[0]));
1500             bld.MOV(result, w_temp);
1501          } else {
1502             /* Otherwise use an AND with 0xff and a word type */
1503             bld.AND(result, subscript(op[0], type, byte->u32[0] / 2), brw_imm_uw(0xff));
1504          }
1505       } else {
1506          const brw_reg_type type = brw_int_type(1, instr->op == nir_op_extract_i8);
1507          bld.MOV(result, subscript(op[0], type, byte->u32[0]));
1508       }
1509       break;
1510    }
1511
1512    case nir_op_extract_u16:
1513    case nir_op_extract_i16: {
1514       const brw_reg_type type = brw_int_type(2, instr->op == nir_op_extract_i16);
1515       nir_const_value *word = nir_src_as_const_value(instr->src[1].src);
1516       assert(word != NULL);
1517       bld.MOV(result, subscript(op[0], type, word->u32[0]));
1518       break;
1519    }
1520
1521    default:
1522       unreachable("unhandled instruction");
1523    }
1524
1525    /* If we need to do a boolean resolve, replace the result with -(x & 1)
1526     * to sign extend the low bit to 0/~0
1527     */
1528    if (devinfo->gen <= 5 &&
1529        (instr->instr.pass_flags & BRW_NIR_BOOLEAN_MASK) == BRW_NIR_BOOLEAN_NEEDS_RESOLVE) {
1530       fs_reg masked = vgrf(glsl_type::int_type);
1531       bld.AND(masked, result, brw_imm_d(1));
1532       masked.negate = true;
1533       bld.MOV(retype(result, BRW_REGISTER_TYPE_D), masked);
1534    }
1535 }
1536
1537 void
1538 fs_visitor::nir_emit_load_const(const fs_builder &bld,
1539                                 nir_load_const_instr *instr)
1540 {
1541    const brw_reg_type reg_type =
1542       brw_reg_type_from_bit_size(instr->def.bit_size, BRW_REGISTER_TYPE_D);
1543    fs_reg reg = bld.vgrf(reg_type, instr->def.num_components);
1544
1545    switch (instr->def.bit_size) {
1546    case 16:
1547       for (unsigned i = 0; i < instr->def.num_components; i++)
1548          bld.MOV(offset(reg, bld, i), brw_imm_w(instr->value.i16[i]));
1549       break;
1550
1551    case 32:
1552       for (unsigned i = 0; i < instr->def.num_components; i++)
1553          bld.MOV(offset(reg, bld, i), brw_imm_d(instr->value.i32[i]));
1554       break;
1555
1556    case 64:
1557       assert(devinfo->gen >= 7);
1558       if (devinfo->gen == 7) {
1559          /* We don't get 64-bit integer types until gen8 */
1560          for (unsigned i = 0; i < instr->def.num_components; i++) {
1561             bld.MOV(retype(offset(reg, bld, i), BRW_REGISTER_TYPE_DF),
1562                     setup_imm_df(bld, instr->value.f64[i]));
1563          }
1564       } else {
1565          for (unsigned i = 0; i < instr->def.num_components; i++)
1566             bld.MOV(offset(reg, bld, i), brw_imm_q(instr->value.i64[i]));
1567       }
1568       break;
1569
1570    default:
1571       unreachable("Invalid bit size");
1572    }
1573
1574    nir_ssa_values[instr->def.index] = reg;
1575 }
1576
1577 fs_reg
1578 fs_visitor::get_nir_src(const nir_src &src)
1579 {
1580    fs_reg reg;
1581    if (src.is_ssa) {
1582       if (src.ssa->parent_instr->type == nir_instr_type_ssa_undef) {
1583          const brw_reg_type reg_type =
1584             brw_reg_type_from_bit_size(src.ssa->bit_size, BRW_REGISTER_TYPE_D);
1585          reg = bld.vgrf(reg_type, src.ssa->num_components);
1586       } else {
1587          reg = nir_ssa_values[src.ssa->index];
1588       }
1589    } else {
1590       /* We don't handle indirects on locals */
1591       assert(src.reg.indirect == NULL);
1592       reg = offset(nir_locals[src.reg.reg->index], bld,
1593                    src.reg.base_offset * src.reg.reg->num_components);
1594    }
1595
1596    if (nir_src_bit_size(src) == 64 && devinfo->gen == 7) {
1597       /* The only 64-bit type available on gen7 is DF, so use that. */
1598       reg.type = BRW_REGISTER_TYPE_DF;
1599    } else {
1600       /* To avoid floating-point denorm flushing problems, set the type by
1601        * default to an integer type - instructions that need floating point
1602        * semantics will set this to F if they need to
1603        */
1604       reg.type = brw_reg_type_from_bit_size(nir_src_bit_size(src),
1605                                             BRW_REGISTER_TYPE_D);
1606    }
1607
1608    return reg;
1609 }
1610
1611 /**
1612  * Return an IMM for constants; otherwise call get_nir_src() as normal.
1613  *
1614  * This function should not be called on any value which may be 64 bits.
1615  * We could theoretically support 64-bit on gen8+ but we choose not to
1616  * because it wouldn't work in general (no gen7 support) and there are
1617  * enough restrictions in 64-bit immediates that you can't take the return
1618  * value and treat it the same as the result of get_nir_src().
1619  */
1620 fs_reg
1621 fs_visitor::get_nir_src_imm(const nir_src &src)
1622 {
1623    nir_const_value *val = nir_src_as_const_value(src);
1624    assert(nir_src_bit_size(src) == 32);
1625    return val ? fs_reg(brw_imm_d(val->i32[0])) : get_nir_src(src);
1626 }
1627
1628 fs_reg
1629 fs_visitor::get_nir_dest(const nir_dest &dest)
1630 {
1631    if (dest.is_ssa) {
1632       const brw_reg_type reg_type =
1633          brw_reg_type_from_bit_size(dest.ssa.bit_size, BRW_REGISTER_TYPE_F);
1634       nir_ssa_values[dest.ssa.index] =
1635          bld.vgrf(reg_type, dest.ssa.num_components);
1636       return nir_ssa_values[dest.ssa.index];
1637    } else {
1638       /* We don't handle indirects on locals */
1639       assert(dest.reg.indirect == NULL);
1640       return offset(nir_locals[dest.reg.reg->index], bld,
1641                     dest.reg.base_offset * dest.reg.reg->num_components);
1642    }
1643 }
1644
1645 fs_reg
1646 fs_visitor::get_nir_image_deref(const nir_deref_var *deref)
1647 {
1648    fs_reg image(UNIFORM, deref->var->data.driver_location / 4,
1649                 BRW_REGISTER_TYPE_UD);
1650    fs_reg indirect;
1651    unsigned indirect_max = 0;
1652
1653    for (const nir_deref *tail = &deref->deref; tail->child;
1654         tail = tail->child) {
1655       const nir_deref_array *deref_array = nir_deref_as_array(tail->child);
1656       assert(tail->child->deref_type == nir_deref_type_array);
1657       const unsigned size = glsl_get_length(tail->type);
1658       const unsigned element_size = type_size_scalar(deref_array->deref.type);
1659       const unsigned base = MIN2(deref_array->base_offset, size - 1);
1660       image = offset(image, bld, base * element_size);
1661
1662       if (deref_array->deref_array_type == nir_deref_array_type_indirect) {
1663          fs_reg tmp = vgrf(glsl_type::uint_type);
1664
1665          /* Accessing an invalid surface index with the dataport can result
1666           * in a hang.  According to the spec "if the index used to
1667           * select an individual element is negative or greater than or
1668           * equal to the size of the array, the results of the operation
1669           * are undefined but may not lead to termination" -- which is one
1670           * of the possible outcomes of the hang.  Clamp the index to
1671           * prevent access outside of the array bounds.
1672           */
1673          bld.emit_minmax(tmp, retype(get_nir_src(deref_array->indirect),
1674                                      BRW_REGISTER_TYPE_UD),
1675                          brw_imm_ud(size - base - 1), BRW_CONDITIONAL_L);
1676
1677          indirect_max += element_size * (tail->type->length - 1);
1678
1679          bld.MUL(tmp, tmp, brw_imm_ud(element_size * 4));
1680          if (indirect.file == BAD_FILE) {
1681             indirect = tmp;
1682          } else {
1683             bld.ADD(indirect, indirect, tmp);
1684          }
1685       }
1686    }
1687
1688    if (indirect.file == BAD_FILE) {
1689       return image;
1690    } else {
1691       /* Emit a pile of MOVs to load the uniform into a temporary.  The
1692        * dead-code elimination pass will get rid of what we don't use.
1693        */
1694       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD, BRW_IMAGE_PARAM_SIZE);
1695       for (unsigned j = 0; j < BRW_IMAGE_PARAM_SIZE; j++) {
1696          bld.emit(SHADER_OPCODE_MOV_INDIRECT,
1697                   offset(tmp, bld, j), offset(image, bld, j),
1698                   indirect, brw_imm_ud((indirect_max + 1) * 4));
1699       }
1700       return tmp;
1701    }
1702 }
1703
1704 void
1705 fs_visitor::emit_percomp(const fs_builder &bld, const fs_inst &inst,
1706                          unsigned wr_mask)
1707 {
1708    for (unsigned i = 0; i < 4; i++) {
1709       if (!((wr_mask >> i) & 1))
1710          continue;
1711
1712       fs_inst *new_inst = new(mem_ctx) fs_inst(inst);
1713       new_inst->dst = offset(new_inst->dst, bld, i);
1714       for (unsigned j = 0; j < new_inst->sources; j++)
1715          if (new_inst->src[j].file == VGRF)
1716             new_inst->src[j] = offset(new_inst->src[j], bld, i);
1717
1718       bld.emit(new_inst);
1719    }
1720 }
1721
1722 /**
1723  * Get the matching channel register datatype for an image intrinsic of the
1724  * specified GLSL image type.
1725  */
1726 static brw_reg_type
1727 get_image_base_type(const glsl_type *type)
1728 {
1729    switch ((glsl_base_type)type->sampled_type) {
1730    case GLSL_TYPE_UINT:
1731       return BRW_REGISTER_TYPE_UD;
1732    case GLSL_TYPE_INT:
1733       return BRW_REGISTER_TYPE_D;
1734    case GLSL_TYPE_FLOAT:
1735       return BRW_REGISTER_TYPE_F;
1736    default:
1737       unreachable("Not reached.");
1738    }
1739 }
1740
1741 /**
1742  * Get the appropriate atomic op for an image atomic intrinsic.
1743  */
1744 static unsigned
1745 get_image_atomic_op(nir_intrinsic_op op, const glsl_type *type)
1746 {
1747    switch (op) {
1748    case nir_intrinsic_image_var_atomic_add:
1749       return BRW_AOP_ADD;
1750    case nir_intrinsic_image_var_atomic_min:
1751       return (get_image_base_type(type) == BRW_REGISTER_TYPE_D ?
1752               BRW_AOP_IMIN : BRW_AOP_UMIN);
1753    case nir_intrinsic_image_var_atomic_max:
1754       return (get_image_base_type(type) == BRW_REGISTER_TYPE_D ?
1755               BRW_AOP_IMAX : BRW_AOP_UMAX);
1756    case nir_intrinsic_image_var_atomic_and:
1757       return BRW_AOP_AND;
1758    case nir_intrinsic_image_var_atomic_or:
1759       return BRW_AOP_OR;
1760    case nir_intrinsic_image_var_atomic_xor:
1761       return BRW_AOP_XOR;
1762    case nir_intrinsic_image_var_atomic_exchange:
1763       return BRW_AOP_MOV;
1764    case nir_intrinsic_image_var_atomic_comp_swap:
1765       return BRW_AOP_CMPWR;
1766    default:
1767       unreachable("Not reachable.");
1768    }
1769 }
1770
1771 static fs_inst *
1772 emit_pixel_interpolater_send(const fs_builder &bld,
1773                              enum opcode opcode,
1774                              const fs_reg &dst,
1775                              const fs_reg &src,
1776                              const fs_reg &desc,
1777                              glsl_interp_mode interpolation)
1778 {
1779    struct brw_wm_prog_data *wm_prog_data =
1780       brw_wm_prog_data(bld.shader->stage_prog_data);
1781    fs_inst *inst;
1782    fs_reg payload;
1783    int mlen;
1784
1785    if (src.file == BAD_FILE) {
1786       /* Dummy payload */
1787       payload = bld.vgrf(BRW_REGISTER_TYPE_F, 1);
1788       mlen = 1;
1789    } else {
1790       payload = src;
1791       mlen = 2 * bld.dispatch_width() / 8;
1792    }
1793
1794    inst = bld.emit(opcode, dst, payload, desc);
1795    inst->mlen = mlen;
1796    /* 2 floats per slot returned */
1797    inst->size_written = 2 * dst.component_size(inst->exec_size);
1798    inst->pi_noperspective = interpolation == INTERP_MODE_NOPERSPECTIVE;
1799
1800    wm_prog_data->pulls_bary = true;
1801
1802    return inst;
1803 }
1804
1805 /**
1806  * Computes 1 << x, given a D/UD register containing some value x.
1807  */
1808 static fs_reg
1809 intexp2(const fs_builder &bld, const fs_reg &x)
1810 {
1811    assert(x.type == BRW_REGISTER_TYPE_UD || x.type == BRW_REGISTER_TYPE_D);
1812
1813    fs_reg result = bld.vgrf(x.type, 1);
1814    fs_reg one = bld.vgrf(x.type, 1);
1815
1816    bld.MOV(one, retype(brw_imm_d(1), one.type));
1817    bld.SHL(result, one, x);
1818    return result;
1819 }
1820
1821 void
1822 fs_visitor::emit_gs_end_primitive(const nir_src &vertex_count_nir_src)
1823 {
1824    assert(stage == MESA_SHADER_GEOMETRY);
1825
1826    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1827
1828    if (gs_compile->control_data_header_size_bits == 0)
1829       return;
1830
1831    /* We can only do EndPrimitive() functionality when the control data
1832     * consists of cut bits.  Fortunately, the only time it isn't is when the
1833     * output type is points, in which case EndPrimitive() is a no-op.
1834     */
1835    if (gs_prog_data->control_data_format !=
1836        GEN7_GS_CONTROL_DATA_FORMAT_GSCTL_CUT) {
1837       return;
1838    }
1839
1840    /* Cut bits use one bit per vertex. */
1841    assert(gs_compile->control_data_bits_per_vertex == 1);
1842
1843    fs_reg vertex_count = get_nir_src(vertex_count_nir_src);
1844    vertex_count.type = BRW_REGISTER_TYPE_UD;
1845
1846    /* Cut bit n should be set to 1 if EndPrimitive() was called after emitting
1847     * vertex n, 0 otherwise.  So all we need to do here is mark bit
1848     * (vertex_count - 1) % 32 in the cut_bits register to indicate that
1849     * EndPrimitive() was called after emitting vertex (vertex_count - 1);
1850     * vec4_gs_visitor::emit_control_data_bits() will take care of the rest.
1851     *
1852     * Note that if EndPrimitive() is called before emitting any vertices, this
1853     * will cause us to set bit 31 of the control_data_bits register to 1.
1854     * That's fine because:
1855     *
1856     * - If max_vertices < 32, then vertex number 31 (zero-based) will never be
1857     *   output, so the hardware will ignore cut bit 31.
1858     *
1859     * - If max_vertices == 32, then vertex number 31 is guaranteed to be the
1860     *   last vertex, so setting cut bit 31 has no effect (since the primitive
1861     *   is automatically ended when the GS terminates).
1862     *
1863     * - If max_vertices > 32, then the ir_emit_vertex visitor will reset the
1864     *   control_data_bits register to 0 when the first vertex is emitted.
1865     */
1866
1867    const fs_builder abld = bld.annotate("end primitive");
1868
1869    /* control_data_bits |= 1 << ((vertex_count - 1) % 32) */
1870    fs_reg prev_count = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1871    abld.ADD(prev_count, vertex_count, brw_imm_ud(0xffffffffu));
1872    fs_reg mask = intexp2(abld, prev_count);
1873    /* Note: we're relying on the fact that the GEN SHL instruction only pays
1874     * attention to the lower 5 bits of its second source argument, so on this
1875     * architecture, 1 << (vertex_count - 1) is equivalent to 1 <<
1876     * ((vertex_count - 1) % 32).
1877     */
1878    abld.OR(this->control_data_bits, this->control_data_bits, mask);
1879 }
1880
1881 void
1882 fs_visitor::emit_gs_control_data_bits(const fs_reg &vertex_count)
1883 {
1884    assert(stage == MESA_SHADER_GEOMETRY);
1885    assert(gs_compile->control_data_bits_per_vertex != 0);
1886
1887    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1888
1889    const fs_builder abld = bld.annotate("emit control data bits");
1890    const fs_builder fwa_bld = bld.exec_all();
1891
1892    /* We use a single UD register to accumulate control data bits (32 bits
1893     * for each of the SIMD8 channels).  So we need to write a DWord (32 bits)
1894     * at a time.
1895     *
1896     * Unfortunately, the URB_WRITE_SIMD8 message uses 128-bit (OWord) offsets.
1897     * We have select a 128-bit group via the Global and Per-Slot Offsets, then
1898     * use the Channel Mask phase to enable/disable which DWord within that
1899     * group to write.  (Remember, different SIMD8 channels may have emitted
1900     * different numbers of vertices, so we may need per-slot offsets.)
1901     *
1902     * Channel masking presents an annoying problem: we may have to replicate
1903     * the data up to 4 times:
1904     *
1905     * Msg = Handles, Per-Slot Offsets, Channel Masks, Data, Data, Data, Data.
1906     *
1907     * To avoid penalizing shaders that emit a small number of vertices, we
1908     * can avoid these sometimes: if the size of the control data header is
1909     * <= 128 bits, then there is only 1 OWord.  All SIMD8 channels will land
1910     * land in the same 128-bit group, so we can skip per-slot offsets.
1911     *
1912     * Similarly, if the control data header is <= 32 bits, there is only one
1913     * DWord, so we can skip channel masks.
1914     */
1915    enum opcode opcode = SHADER_OPCODE_URB_WRITE_SIMD8;
1916
1917    fs_reg channel_mask, per_slot_offset;
1918
1919    if (gs_compile->control_data_header_size_bits > 32) {
1920       opcode = SHADER_OPCODE_URB_WRITE_SIMD8_MASKED;
1921       channel_mask = vgrf(glsl_type::uint_type);
1922    }
1923
1924    if (gs_compile->control_data_header_size_bits > 128) {
1925       opcode = SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT;
1926       per_slot_offset = vgrf(glsl_type::uint_type);
1927    }
1928
1929    /* Figure out which DWord we're trying to write to using the formula:
1930     *
1931     *    dword_index = (vertex_count - 1) * bits_per_vertex / 32
1932     *
1933     * Since bits_per_vertex is a power of two, and is known at compile
1934     * time, this can be optimized to:
1935     *
1936     *    dword_index = (vertex_count - 1) >> (6 - log2(bits_per_vertex))
1937     */
1938    if (opcode != SHADER_OPCODE_URB_WRITE_SIMD8) {
1939       fs_reg dword_index = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1940       fs_reg prev_count = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1941       abld.ADD(prev_count, vertex_count, brw_imm_ud(0xffffffffu));
1942       unsigned log2_bits_per_vertex =
1943          util_last_bit(gs_compile->control_data_bits_per_vertex);
1944       abld.SHR(dword_index, prev_count, brw_imm_ud(6u - log2_bits_per_vertex));
1945
1946       if (per_slot_offset.file != BAD_FILE) {
1947          /* Set the per-slot offset to dword_index / 4, so that we'll write to
1948           * the appropriate OWord within the control data header.
1949           */
1950          abld.SHR(per_slot_offset, dword_index, brw_imm_ud(2u));
1951       }
1952
1953       /* Set the channel masks to 1 << (dword_index % 4), so that we'll
1954        * write to the appropriate DWORD within the OWORD.
1955        */
1956       fs_reg channel = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1957       fwa_bld.AND(channel, dword_index, brw_imm_ud(3u));
1958       channel_mask = intexp2(fwa_bld, channel);
1959       /* Then the channel masks need to be in bits 23:16. */
1960       fwa_bld.SHL(channel_mask, channel_mask, brw_imm_ud(16u));
1961    }
1962
1963    /* Store the control data bits in the message payload and send it. */
1964    int mlen = 2;
1965    if (channel_mask.file != BAD_FILE)
1966       mlen += 4; /* channel masks, plus 3 extra copies of the data */
1967    if (per_slot_offset.file != BAD_FILE)
1968       mlen++;
1969
1970    fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, mlen);
1971    fs_reg *sources = ralloc_array(mem_ctx, fs_reg, mlen);
1972    int i = 0;
1973    sources[i++] = fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
1974    if (per_slot_offset.file != BAD_FILE)
1975       sources[i++] = per_slot_offset;
1976    if (channel_mask.file != BAD_FILE)
1977       sources[i++] = channel_mask;
1978    while (i < mlen) {
1979       sources[i++] = this->control_data_bits;
1980    }
1981
1982    abld.LOAD_PAYLOAD(payload, sources, mlen, mlen);
1983    fs_inst *inst = abld.emit(opcode, reg_undef, payload);
1984    inst->mlen = mlen;
1985    /* We need to increment Global Offset by 256-bits to make room for
1986     * Broadwell's extra "Vertex Count" payload at the beginning of the
1987     * URB entry.  Since this is an OWord message, Global Offset is counted
1988     * in 128-bit units, so we must set it to 2.
1989     */
1990    if (gs_prog_data->static_vertex_count == -1)
1991       inst->offset = 2;
1992 }
1993
1994 void
1995 fs_visitor::set_gs_stream_control_data_bits(const fs_reg &vertex_count,
1996                                             unsigned stream_id)
1997 {
1998    /* control_data_bits |= stream_id << ((2 * (vertex_count - 1)) % 32) */
1999
2000    /* Note: we are calling this *before* increasing vertex_count, so
2001     * this->vertex_count == vertex_count - 1 in the formula above.
2002     */
2003
2004    /* Stream mode uses 2 bits per vertex */
2005    assert(gs_compile->control_data_bits_per_vertex == 2);
2006
2007    /* Must be a valid stream */
2008    assert(stream_id < MAX_VERTEX_STREAMS);
2009
2010    /* Control data bits are initialized to 0 so we don't have to set any
2011     * bits when sending vertices to stream 0.
2012     */
2013    if (stream_id == 0)
2014       return;
2015
2016    const fs_builder abld = bld.annotate("set stream control data bits", NULL);
2017
2018    /* reg::sid = stream_id */
2019    fs_reg sid = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2020    abld.MOV(sid, brw_imm_ud(stream_id));
2021
2022    /* reg:shift_count = 2 * (vertex_count - 1) */
2023    fs_reg shift_count = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2024    abld.SHL(shift_count, vertex_count, brw_imm_ud(1u));
2025
2026    /* Note: we're relying on the fact that the GEN SHL instruction only pays
2027     * attention to the lower 5 bits of its second source argument, so on this
2028     * architecture, stream_id << 2 * (vertex_count - 1) is equivalent to
2029     * stream_id << ((2 * (vertex_count - 1)) % 32).
2030     */
2031    fs_reg mask = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2032    abld.SHL(mask, sid, shift_count);
2033    abld.OR(this->control_data_bits, this->control_data_bits, mask);
2034 }
2035
2036 void
2037 fs_visitor::emit_gs_vertex(const nir_src &vertex_count_nir_src,
2038                            unsigned stream_id)
2039 {
2040    assert(stage == MESA_SHADER_GEOMETRY);
2041
2042    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
2043
2044    fs_reg vertex_count = get_nir_src(vertex_count_nir_src);
2045    vertex_count.type = BRW_REGISTER_TYPE_UD;
2046
2047    /* Haswell and later hardware ignores the "Render Stream Select" bits
2048     * from the 3DSTATE_STREAMOUT packet when the SOL stage is disabled,
2049     * and instead sends all primitives down the pipeline for rasterization.
2050     * If the SOL stage is enabled, "Render Stream Select" is honored and
2051     * primitives bound to non-zero streams are discarded after stream output.
2052     *
2053     * Since the only purpose of primives sent to non-zero streams is to
2054     * be recorded by transform feedback, we can simply discard all geometry
2055     * bound to these streams when transform feedback is disabled.
2056     */
2057    if (stream_id > 0 && !nir->info.has_transform_feedback_varyings)
2058       return;
2059
2060    /* If we're outputting 32 control data bits or less, then we can wait
2061     * until the shader is over to output them all.  Otherwise we need to
2062     * output them as we go.  Now is the time to do it, since we're about to
2063     * output the vertex_count'th vertex, so it's guaranteed that the
2064     * control data bits associated with the (vertex_count - 1)th vertex are
2065     * correct.
2066     */
2067    if (gs_compile->control_data_header_size_bits > 32) {
2068       const fs_builder abld =
2069          bld.annotate("emit vertex: emit control data bits");
2070
2071       /* Only emit control data bits if we've finished accumulating a batch
2072        * of 32 bits.  This is the case when:
2073        *
2074        *     (vertex_count * bits_per_vertex) % 32 == 0
2075        *
2076        * (in other words, when the last 5 bits of vertex_count *
2077        * bits_per_vertex are 0).  Assuming bits_per_vertex == 2^n for some
2078        * integer n (which is always the case, since bits_per_vertex is
2079        * always 1 or 2), this is equivalent to requiring that the last 5-n
2080        * bits of vertex_count are 0:
2081        *
2082        *     vertex_count & (2^(5-n) - 1) == 0
2083        *
2084        * 2^(5-n) == 2^5 / 2^n == 32 / bits_per_vertex, so this is
2085        * equivalent to:
2086        *
2087        *     vertex_count & (32 / bits_per_vertex - 1) == 0
2088        *
2089        * TODO: If vertex_count is an immediate, we could do some of this math
2090        *       at compile time...
2091        */
2092       fs_inst *inst =
2093          abld.AND(bld.null_reg_d(), vertex_count,
2094                   brw_imm_ud(32u / gs_compile->control_data_bits_per_vertex - 1u));
2095       inst->conditional_mod = BRW_CONDITIONAL_Z;
2096
2097       abld.IF(BRW_PREDICATE_NORMAL);
2098       /* If vertex_count is 0, then no control data bits have been
2099        * accumulated yet, so we can skip emitting them.
2100        */
2101       abld.CMP(bld.null_reg_d(), vertex_count, brw_imm_ud(0u),
2102                BRW_CONDITIONAL_NEQ);
2103       abld.IF(BRW_PREDICATE_NORMAL);
2104       emit_gs_control_data_bits(vertex_count);
2105       abld.emit(BRW_OPCODE_ENDIF);
2106
2107       /* Reset control_data_bits to 0 so we can start accumulating a new
2108        * batch.
2109        *
2110        * Note: in the case where vertex_count == 0, this neutralizes the
2111        * effect of any call to EndPrimitive() that the shader may have
2112        * made before outputting its first vertex.
2113        */
2114       inst = abld.MOV(this->control_data_bits, brw_imm_ud(0u));
2115       inst->force_writemask_all = true;
2116       abld.emit(BRW_OPCODE_ENDIF);
2117    }
2118
2119    emit_urb_writes(vertex_count);
2120
2121    /* In stream mode we have to set control data bits for all vertices
2122     * unless we have disabled control data bits completely (which we do
2123     * do for GL_POINTS outputs that don't use streams).
2124     */
2125    if (gs_compile->control_data_header_size_bits > 0 &&
2126        gs_prog_data->control_data_format ==
2127           GEN7_GS_CONTROL_DATA_FORMAT_GSCTL_SID) {
2128       set_gs_stream_control_data_bits(vertex_count, stream_id);
2129    }
2130 }
2131
2132 void
2133 fs_visitor::emit_gs_input_load(const fs_reg &dst,
2134                                const nir_src &vertex_src,
2135                                unsigned base_offset,
2136                                const nir_src &offset_src,
2137                                unsigned num_components,
2138                                unsigned first_component)
2139 {
2140    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
2141
2142    nir_const_value *vertex_const = nir_src_as_const_value(vertex_src);
2143    nir_const_value *offset_const = nir_src_as_const_value(offset_src);
2144    const unsigned push_reg_count = gs_prog_data->base.urb_read_length * 8;
2145
2146    /* TODO: figure out push input layout for invocations == 1 */
2147    /* TODO: make this work with 64-bit inputs */
2148    if (gs_prog_data->invocations == 1 &&
2149        type_sz(dst.type) <= 4 &&
2150        offset_const != NULL && vertex_const != NULL &&
2151        4 * (base_offset + offset_const->u32[0]) < push_reg_count) {
2152       int imm_offset = (base_offset + offset_const->u32[0]) * 4 +
2153                        vertex_const->u32[0] * push_reg_count;
2154       for (unsigned i = 0; i < num_components; i++) {
2155          bld.MOV(offset(dst, bld, i),
2156                  fs_reg(ATTR, imm_offset + i + first_component, dst.type));
2157       }
2158       return;
2159    }
2160
2161    /* Resort to the pull model.  Ensure the VUE handles are provided. */
2162    assert(gs_prog_data->base.include_vue_handles);
2163
2164    unsigned first_icp_handle = gs_prog_data->include_primitive_id ? 3 : 2;
2165    fs_reg icp_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2166
2167    if (gs_prog_data->invocations == 1) {
2168       if (vertex_const) {
2169          /* The vertex index is constant; just select the proper URB handle. */
2170          icp_handle =
2171             retype(brw_vec8_grf(first_icp_handle + vertex_const->i32[0], 0),
2172                    BRW_REGISTER_TYPE_UD);
2173       } else {
2174          /* The vertex index is non-constant.  We need to use indirect
2175           * addressing to fetch the proper URB handle.
2176           *
2177           * First, we start with the sequence <7, 6, 5, 4, 3, 2, 1, 0>
2178           * indicating that channel <n> should read the handle from
2179           * DWord <n>.  We convert that to bytes by multiplying by 4.
2180           *
2181           * Next, we convert the vertex index to bytes by multiplying
2182           * by 32 (shifting by 5), and add the two together.  This is
2183           * the final indirect byte offset.
2184           */
2185          fs_reg sequence = bld.vgrf(BRW_REGISTER_TYPE_UW, 1);
2186          fs_reg channel_offsets = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2187          fs_reg vertex_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2188          fs_reg icp_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2189
2190          /* sequence = <7, 6, 5, 4, 3, 2, 1, 0> */
2191          bld.MOV(sequence, fs_reg(brw_imm_v(0x76543210)));
2192          /* channel_offsets = 4 * sequence = <28, 24, 20, 16, 12, 8, 4, 0> */
2193          bld.SHL(channel_offsets, sequence, brw_imm_ud(2u));
2194          /* Convert vertex_index to bytes (multiply by 32) */
2195          bld.SHL(vertex_offset_bytes,
2196                  retype(get_nir_src(vertex_src), BRW_REGISTER_TYPE_UD),
2197                  brw_imm_ud(5u));
2198          bld.ADD(icp_offset_bytes, vertex_offset_bytes, channel_offsets);
2199
2200          /* Use first_icp_handle as the base offset.  There is one register
2201           * of URB handles per vertex, so inform the register allocator that
2202           * we might read up to nir->info.gs.vertices_in registers.
2203           */
2204          bld.emit(SHADER_OPCODE_MOV_INDIRECT, icp_handle,
2205                   retype(brw_vec8_grf(first_icp_handle, 0), icp_handle.type),
2206                   fs_reg(icp_offset_bytes),
2207                   brw_imm_ud(nir->info.gs.vertices_in * REG_SIZE));
2208       }
2209    } else {
2210       assert(gs_prog_data->invocations > 1);
2211
2212       if (vertex_const) {
2213          assert(devinfo->gen >= 9 || vertex_const->i32[0] <= 5);
2214          bld.MOV(icp_handle,
2215                  retype(brw_vec1_grf(first_icp_handle +
2216                                      vertex_const->i32[0] / 8,
2217                                      vertex_const->i32[0] % 8),
2218                         BRW_REGISTER_TYPE_UD));
2219       } else {
2220          /* The vertex index is non-constant.  We need to use indirect
2221           * addressing to fetch the proper URB handle.
2222           *
2223           */
2224          fs_reg icp_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2225
2226          /* Convert vertex_index to bytes (multiply by 4) */
2227          bld.SHL(icp_offset_bytes,
2228                  retype(get_nir_src(vertex_src), BRW_REGISTER_TYPE_UD),
2229                  brw_imm_ud(2u));
2230
2231          /* Use first_icp_handle as the base offset.  There is one DWord
2232           * of URB handles per vertex, so inform the register allocator that
2233           * we might read up to ceil(nir->info.gs.vertices_in / 8) registers.
2234           */
2235          bld.emit(SHADER_OPCODE_MOV_INDIRECT, icp_handle,
2236                   retype(brw_vec8_grf(first_icp_handle, 0), icp_handle.type),
2237                   fs_reg(icp_offset_bytes),
2238                   brw_imm_ud(DIV_ROUND_UP(nir->info.gs.vertices_in, 8) *
2239                              REG_SIZE));
2240       }
2241    }
2242
2243    fs_inst *inst;
2244
2245    fs_reg tmp_dst = dst;
2246    fs_reg indirect_offset = get_nir_src(offset_src);
2247    unsigned num_iterations = 1;
2248    unsigned orig_num_components = num_components;
2249
2250    if (type_sz(dst.type) == 8) {
2251       if (num_components > 2) {
2252          num_iterations = 2;
2253          num_components = 2;
2254       }
2255       fs_reg tmp = fs_reg(VGRF, alloc.allocate(4), dst.type);
2256       tmp_dst = tmp;
2257       first_component = first_component / 2;
2258    }
2259
2260    for (unsigned iter = 0; iter < num_iterations; iter++) {
2261       if (offset_const) {
2262          /* Constant indexing - use global offset. */
2263          if (first_component != 0) {
2264             unsigned read_components = num_components + first_component;
2265             fs_reg tmp = bld.vgrf(dst.type, read_components);
2266             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp, icp_handle);
2267             inst->size_written = read_components *
2268                                  tmp.component_size(inst->exec_size);
2269             for (unsigned i = 0; i < num_components; i++) {
2270                bld.MOV(offset(tmp_dst, bld, i),
2271                        offset(tmp, bld, i + first_component));
2272             }
2273          } else {
2274             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp_dst,
2275                             icp_handle);
2276             inst->size_written = num_components *
2277                                  tmp_dst.component_size(inst->exec_size);
2278          }
2279          inst->offset = base_offset + offset_const->u32[0];
2280          inst->mlen = 1;
2281       } else {
2282          /* Indirect indexing - use per-slot offsets as well. */
2283          const fs_reg srcs[] = { icp_handle, indirect_offset };
2284          unsigned read_components = num_components + first_component;
2285          fs_reg tmp = bld.vgrf(dst.type, read_components);
2286          fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2287          bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2288          if (first_component != 0) {
2289             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2290                             payload);
2291             inst->size_written = read_components *
2292                                  tmp.component_size(inst->exec_size);
2293             for (unsigned i = 0; i < num_components; i++) {
2294                bld.MOV(offset(tmp_dst, bld, i),
2295                        offset(tmp, bld, i + first_component));
2296             }
2297          } else {
2298             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp_dst,
2299                          payload);
2300             inst->size_written = num_components *
2301                                  tmp_dst.component_size(inst->exec_size);
2302          }
2303          inst->offset = base_offset;
2304          inst->mlen = 2;
2305       }
2306
2307       if (type_sz(dst.type) == 8) {
2308          shuffle_from_32bit_read(bld,
2309                                  offset(dst, bld, iter * 2),
2310                                  retype(tmp_dst, BRW_REGISTER_TYPE_D),
2311                                  0,
2312                                  num_components);
2313       }
2314
2315       if (num_iterations > 1) {
2316          num_components = orig_num_components - 2;
2317          if(offset_const) {
2318             base_offset++;
2319          } else {
2320             fs_reg new_indirect = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2321             bld.ADD(new_indirect, indirect_offset, brw_imm_ud(1u));
2322             indirect_offset = new_indirect;
2323          }
2324       }
2325    }
2326 }
2327
2328 fs_reg
2329 fs_visitor::get_indirect_offset(nir_intrinsic_instr *instr)
2330 {
2331    nir_src *offset_src = nir_get_io_offset_src(instr);
2332    nir_const_value *const_value = nir_src_as_const_value(*offset_src);
2333
2334    if (const_value) {
2335       /* The only constant offset we should find is 0.  brw_nir.c's
2336        * add_const_offset_to_base() will fold other constant offsets
2337        * into instr->const_index[0].
2338        */
2339       assert(const_value->u32[0] == 0);
2340       return fs_reg();
2341    }
2342
2343    return get_nir_src(*offset_src);
2344 }
2345
2346 static void
2347 do_untyped_vector_read(const fs_builder &bld,
2348                        const fs_reg dest,
2349                        const fs_reg surf_index,
2350                        const fs_reg offset_reg,
2351                        unsigned num_components)
2352 {
2353    if (type_sz(dest.type) <= 2) {
2354       assert(dest.stride == 1);
2355       boolean is_const_offset = offset_reg.file == BRW_IMMEDIATE_VALUE;
2356
2357       if (is_const_offset) {
2358          uint32_t start = offset_reg.ud & ~3;
2359          uint32_t end = offset_reg.ud + num_components * type_sz(dest.type);
2360          end = ALIGN(end, 4);
2361          assert (end - start <= 16);
2362
2363          /* At this point we have 16-bit component/s that have constant
2364           * offset aligned to 4-bytes that can be read with untyped_reads.
2365           * untyped_read message requires 32-bit aligned offsets.
2366           */
2367          unsigned first_component = (offset_reg.ud & 3) / type_sz(dest.type);
2368          unsigned num_components_32bit = (end - start) / 4;
2369
2370          fs_reg read_result =
2371             emit_untyped_read(bld, surf_index, brw_imm_ud(start),
2372                               1 /* dims */,
2373                               num_components_32bit,
2374                               BRW_PREDICATE_NONE);
2375          shuffle_from_32bit_read(bld, dest, read_result, first_component,
2376                                  num_components);
2377       } else {
2378          fs_reg read_offset = bld.vgrf(BRW_REGISTER_TYPE_UD);
2379          for (unsigned i = 0; i < num_components; i++) {
2380             if (i == 0) {
2381                bld.MOV(read_offset, offset_reg);
2382             } else {
2383                bld.ADD(read_offset, offset_reg,
2384                        brw_imm_ud(i * type_sz(dest.type)));
2385             }
2386             /* Non constant offsets are not guaranteed to be aligned 32-bits
2387              * so they are read using one byte_scattered_read message
2388              * for each component.
2389              */
2390             fs_reg read_result =
2391                emit_byte_scattered_read(bld, surf_index, read_offset,
2392                                         1 /* dims */, 1,
2393                                         type_sz(dest.type) * 8 /* bit_size */,
2394                                         BRW_PREDICATE_NONE);
2395             bld.MOV(offset(dest, bld, i),
2396                     subscript (read_result, dest.type, 0));
2397          }
2398       }
2399    } else if (type_sz(dest.type) == 4) {
2400       fs_reg read_result = emit_untyped_read(bld, surf_index, offset_reg,
2401                                              1 /* dims */,
2402                                              num_components,
2403                                              BRW_PREDICATE_NONE);
2404       read_result.type = dest.type;
2405       for (unsigned i = 0; i < num_components; i++)
2406          bld.MOV(offset(dest, bld, i), offset(read_result, bld, i));
2407    } else if (type_sz(dest.type) == 8) {
2408       /* Reading a dvec, so we need to:
2409        *
2410        * 1. Multiply num_components by 2, to account for the fact that we
2411        *    need to read 64-bit components.
2412        * 2. Shuffle the result of the load to form valid 64-bit elements
2413        * 3. Emit a second load (for components z/w) if needed.
2414        */
2415       fs_reg read_offset = bld.vgrf(BRW_REGISTER_TYPE_UD);
2416       bld.MOV(read_offset, offset_reg);
2417
2418       int iters = num_components <= 2 ? 1 : 2;
2419
2420       /* Load the dvec, the first iteration loads components x/y, the second
2421        * iteration, if needed, loads components z/w
2422        */
2423       for (int it = 0; it < iters; it++) {
2424          /* Compute number of components to read in this iteration */
2425          int iter_components = MIN2(2, num_components);
2426          num_components -= iter_components;
2427
2428          /* Read. Since this message reads 32-bit components, we need to
2429           * read twice as many components.
2430           */
2431          fs_reg read_result = emit_untyped_read(bld, surf_index, read_offset,
2432                                                 1 /* dims */,
2433                                                 iter_components * 2,
2434                                                 BRW_PREDICATE_NONE);
2435
2436          /* Shuffle the 32-bit load result into valid 64-bit data */
2437          shuffle_from_32bit_read(bld, offset(dest, bld, it * 2),
2438                                  read_result, 0, iter_components);
2439
2440          bld.ADD(read_offset, read_offset, brw_imm_ud(16));
2441       }
2442    } else {
2443       unreachable("Unsupported type");
2444    }
2445 }
2446
2447 void
2448 fs_visitor::nir_emit_vs_intrinsic(const fs_builder &bld,
2449                                   nir_intrinsic_instr *instr)
2450 {
2451    assert(stage == MESA_SHADER_VERTEX);
2452
2453    fs_reg dest;
2454    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
2455       dest = get_nir_dest(instr->dest);
2456
2457    switch (instr->intrinsic) {
2458    case nir_intrinsic_load_vertex_id:
2459    case nir_intrinsic_load_base_vertex:
2460       unreachable("should be lowered by nir_lower_system_values()");
2461
2462    case nir_intrinsic_load_vertex_id_zero_base:
2463    case nir_intrinsic_load_instance_id:
2464    case nir_intrinsic_load_base_instance:
2465    case nir_intrinsic_load_draw_id: {
2466       gl_system_value sv = nir_system_value_from_intrinsic(instr->intrinsic);
2467       fs_reg val = nir_system_values[sv];
2468       assert(val.file != BAD_FILE);
2469       dest.type = val.type;
2470       bld.MOV(dest, val);
2471       break;
2472    }
2473
2474    case nir_intrinsic_load_input: {
2475       fs_reg src = fs_reg(ATTR, nir_intrinsic_base(instr) * 4, dest.type);
2476       unsigned first_component = nir_intrinsic_component(instr);
2477       unsigned num_components = instr->num_components;
2478
2479       nir_const_value *const_offset = nir_src_as_const_value(instr->src[0]);
2480       assert(const_offset && "Indirect input loads not allowed");
2481       src = offset(src, bld, const_offset->u32[0]);
2482
2483       if (type_sz(dest.type) == 8)
2484          first_component /= 2;
2485
2486       /* For 16-bit support maybe a temporary will be needed to copy from
2487        * the ATTR file.
2488        */
2489       shuffle_from_32bit_read(bld, dest, retype(src, BRW_REGISTER_TYPE_D),
2490                               first_component, num_components);
2491       break;
2492    }
2493
2494    case nir_intrinsic_load_first_vertex:
2495    case nir_intrinsic_load_is_indexed_draw:
2496       unreachable("lowered by brw_nir_lower_vs_inputs");
2497
2498    default:
2499       nir_emit_intrinsic(bld, instr);
2500       break;
2501    }
2502 }
2503
2504 void
2505 fs_visitor::nir_emit_tcs_intrinsic(const fs_builder &bld,
2506                                    nir_intrinsic_instr *instr)
2507 {
2508    assert(stage == MESA_SHADER_TESS_CTRL);
2509    struct brw_tcs_prog_key *tcs_key = (struct brw_tcs_prog_key *) key;
2510    struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
2511
2512    fs_reg dst;
2513    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
2514       dst = get_nir_dest(instr->dest);
2515
2516    switch (instr->intrinsic) {
2517    case nir_intrinsic_load_primitive_id:
2518       bld.MOV(dst, fs_reg(brw_vec1_grf(0, 1)));
2519       break;
2520    case nir_intrinsic_load_invocation_id:
2521       bld.MOV(retype(dst, invocation_id.type), invocation_id);
2522       break;
2523    case nir_intrinsic_load_patch_vertices_in:
2524       bld.MOV(retype(dst, BRW_REGISTER_TYPE_D),
2525               brw_imm_d(tcs_key->input_vertices));
2526       break;
2527
2528    case nir_intrinsic_barrier: {
2529       if (tcs_prog_data->instances == 1)
2530          break;
2531
2532       fs_reg m0 = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2533       fs_reg m0_2 = component(m0, 2);
2534
2535       const fs_builder chanbld = bld.exec_all().group(1, 0);
2536
2537       /* Zero the message header */
2538       bld.exec_all().MOV(m0, brw_imm_ud(0u));
2539
2540       /* Copy "Barrier ID" from r0.2, bits 16:13 */
2541       chanbld.AND(m0_2, retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD),
2542                   brw_imm_ud(INTEL_MASK(16, 13)));
2543
2544       /* Shift it up to bits 27:24. */
2545       chanbld.SHL(m0_2, m0_2, brw_imm_ud(11));
2546
2547       /* Set the Barrier Count and the enable bit */
2548       chanbld.OR(m0_2, m0_2,
2549                  brw_imm_ud(tcs_prog_data->instances << 9 | (1 << 15)));
2550
2551       bld.emit(SHADER_OPCODE_BARRIER, bld.null_reg_ud(), m0);
2552       break;
2553    }
2554
2555    case nir_intrinsic_load_input:
2556       unreachable("nir_lower_io should never give us these.");
2557       break;
2558
2559    case nir_intrinsic_load_per_vertex_input: {
2560       fs_reg indirect_offset = get_indirect_offset(instr);
2561       unsigned imm_offset = instr->const_index[0];
2562
2563       const nir_src &vertex_src = instr->src[0];
2564       nir_const_value *vertex_const = nir_src_as_const_value(vertex_src);
2565
2566       fs_inst *inst;
2567
2568       fs_reg icp_handle;
2569
2570       if (vertex_const) {
2571          /* Emit a MOV to resolve <0,1,0> regioning. */
2572          icp_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2573          bld.MOV(icp_handle,
2574                  retype(brw_vec1_grf(1 + (vertex_const->i32[0] >> 3),
2575                                      vertex_const->i32[0] & 7),
2576                         BRW_REGISTER_TYPE_UD));
2577       } else if (tcs_prog_data->instances == 1 &&
2578                  vertex_src.is_ssa &&
2579                  vertex_src.ssa->parent_instr->type == nir_instr_type_intrinsic &&
2580                  nir_instr_as_intrinsic(vertex_src.ssa->parent_instr)->intrinsic == nir_intrinsic_load_invocation_id) {
2581          /* For the common case of only 1 instance, an array index of
2582           * gl_InvocationID means reading g1.  Skip all the indirect work.
2583           */
2584          icp_handle = retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD);
2585       } else {
2586          /* The vertex index is non-constant.  We need to use indirect
2587           * addressing to fetch the proper URB handle.
2588           */
2589          icp_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2590
2591          /* Each ICP handle is a single DWord (4 bytes) */
2592          fs_reg vertex_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2593          bld.SHL(vertex_offset_bytes,
2594                  retype(get_nir_src(vertex_src), BRW_REGISTER_TYPE_UD),
2595                  brw_imm_ud(2u));
2596
2597          /* Start at g1.  We might read up to 4 registers. */
2598          bld.emit(SHADER_OPCODE_MOV_INDIRECT, icp_handle,
2599                   retype(brw_vec8_grf(1, 0), icp_handle.type), vertex_offset_bytes,
2600                   brw_imm_ud(4 * REG_SIZE));
2601       }
2602
2603       /* We can only read two double components with each URB read, so
2604        * we send two read messages in that case, each one loading up to
2605        * two double components.
2606        */
2607       unsigned num_iterations = 1;
2608       unsigned num_components = instr->num_components;
2609       unsigned first_component = nir_intrinsic_component(instr);
2610       fs_reg orig_dst = dst;
2611       if (type_sz(dst.type) == 8) {
2612          first_component = first_component / 2;
2613          if (instr->num_components > 2) {
2614             num_iterations = 2;
2615             num_components = 2;
2616          }
2617
2618          fs_reg tmp = fs_reg(VGRF, alloc.allocate(4), dst.type);
2619          dst = tmp;
2620       }
2621
2622       for (unsigned iter = 0; iter < num_iterations; iter++) {
2623          if (indirect_offset.file == BAD_FILE) {
2624             /* Constant indexing - use global offset. */
2625             if (first_component != 0) {
2626                unsigned read_components = num_components + first_component;
2627                fs_reg tmp = bld.vgrf(dst.type, read_components);
2628                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp, icp_handle);
2629                for (unsigned i = 0; i < num_components; i++) {
2630                   bld.MOV(offset(dst, bld, i),
2631                           offset(tmp, bld, i + first_component));
2632                }
2633             } else {
2634                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, dst, icp_handle);
2635             }
2636             inst->offset = imm_offset;
2637             inst->mlen = 1;
2638          } else {
2639             /* Indirect indexing - use per-slot offsets as well. */
2640             const fs_reg srcs[] = { icp_handle, indirect_offset };
2641             fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2642             bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2643             if (first_component != 0) {
2644                unsigned read_components = num_components + first_component;
2645                fs_reg tmp = bld.vgrf(dst.type, read_components);
2646                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2647                                payload);
2648                for (unsigned i = 0; i < num_components; i++) {
2649                   bld.MOV(offset(dst, bld, i),
2650                           offset(tmp, bld, i + first_component));
2651                }
2652             } else {
2653                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, dst,
2654                                payload);
2655             }
2656             inst->offset = imm_offset;
2657             inst->mlen = 2;
2658          }
2659          inst->size_written = (num_components + first_component) *
2660                               inst->dst.component_size(inst->exec_size);
2661
2662          /* If we are reading 64-bit data using 32-bit read messages we need
2663           * build proper 64-bit data elements by shuffling the low and high
2664           * 32-bit components around like we do for other things like UBOs
2665           * or SSBOs.
2666           */
2667          if (type_sz(dst.type) == 8) {
2668             shuffle_from_32bit_read(bld,
2669                                     offset(orig_dst, bld, iter * 2),
2670                                     retype(dst, BRW_REGISTER_TYPE_D),
2671                                     0, num_components);
2672          }
2673
2674          /* Copy the temporary to the destination to deal with writemasking.
2675           *
2676           * Also attempt to deal with gl_PointSize being in the .w component.
2677           */
2678          if (inst->offset == 0 && indirect_offset.file == BAD_FILE) {
2679             assert(type_sz(dst.type) < 8);
2680             inst->dst = bld.vgrf(dst.type, 4);
2681             inst->size_written = 4 * REG_SIZE;
2682             bld.MOV(dst, offset(inst->dst, bld, 3));
2683          }
2684
2685          /* If we are loading double data and we need a second read message
2686           * adjust the write offset
2687           */
2688          if (num_iterations > 1) {
2689             num_components = instr->num_components - 2;
2690             imm_offset++;
2691          }
2692       }
2693       break;
2694    }
2695
2696    case nir_intrinsic_load_output:
2697    case nir_intrinsic_load_per_vertex_output: {
2698       fs_reg indirect_offset = get_indirect_offset(instr);
2699       unsigned imm_offset = instr->const_index[0];
2700       unsigned first_component = nir_intrinsic_component(instr);
2701
2702       fs_inst *inst;
2703       if (indirect_offset.file == BAD_FILE) {
2704          /* Replicate the patch handle to all enabled channels */
2705          fs_reg patch_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2706          bld.MOV(patch_handle,
2707                  retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD));
2708
2709          {
2710             if (first_component != 0) {
2711                unsigned read_components =
2712                   instr->num_components + first_component;
2713                fs_reg tmp = bld.vgrf(dst.type, read_components);
2714                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp,
2715                                patch_handle);
2716                inst->size_written = read_components * REG_SIZE;
2717                for (unsigned i = 0; i < instr->num_components; i++) {
2718                   bld.MOV(offset(dst, bld, i),
2719                           offset(tmp, bld, i + first_component));
2720                }
2721             } else {
2722                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, dst,
2723                                patch_handle);
2724                inst->size_written = instr->num_components * REG_SIZE;
2725             }
2726             inst->offset = imm_offset;
2727             inst->mlen = 1;
2728          }
2729       } else {
2730          /* Indirect indexing - use per-slot offsets as well. */
2731          const fs_reg srcs[] = {
2732             retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD),
2733             indirect_offset
2734          };
2735          fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2736          bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2737          if (first_component != 0) {
2738             unsigned read_components =
2739                instr->num_components + first_component;
2740             fs_reg tmp = bld.vgrf(dst.type, read_components);
2741             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2742                             payload);
2743             inst->size_written = read_components * REG_SIZE;
2744             for (unsigned i = 0; i < instr->num_components; i++) {
2745                bld.MOV(offset(dst, bld, i),
2746                        offset(tmp, bld, i + first_component));
2747             }
2748          } else {
2749             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, dst,
2750                             payload);
2751             inst->size_written = instr->num_components * REG_SIZE;
2752          }
2753          inst->offset = imm_offset;
2754          inst->mlen = 2;
2755       }
2756       break;
2757    }
2758
2759    case nir_intrinsic_store_output:
2760    case nir_intrinsic_store_per_vertex_output: {
2761       fs_reg value = get_nir_src(instr->src[0]);
2762       bool is_64bit = (instr->src[0].is_ssa ?
2763          instr->src[0].ssa->bit_size : instr->src[0].reg.reg->bit_size) == 64;
2764       fs_reg indirect_offset = get_indirect_offset(instr);
2765       unsigned imm_offset = instr->const_index[0];
2766       unsigned mask = instr->const_index[1];
2767       unsigned header_regs = 0;
2768       fs_reg srcs[7];
2769       srcs[header_regs++] = retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD);
2770
2771       if (indirect_offset.file != BAD_FILE) {
2772          srcs[header_regs++] = indirect_offset;
2773       }
2774
2775       if (mask == 0)
2776          break;
2777
2778       unsigned num_components = util_last_bit(mask);
2779       enum opcode opcode;
2780
2781       /* We can only pack two 64-bit components in a single message, so send
2782        * 2 messages if we have more components
2783        */
2784       unsigned num_iterations = 1;
2785       unsigned iter_components = num_components;
2786       unsigned first_component = nir_intrinsic_component(instr);
2787       if (is_64bit) {
2788          first_component = first_component / 2;
2789          if (instr->num_components > 2) {
2790             num_iterations = 2;
2791             iter_components = 2;
2792          }
2793       }
2794
2795       mask = mask << first_component;
2796
2797       for (unsigned iter = 0; iter < num_iterations; iter++) {
2798          if (!is_64bit && mask != WRITEMASK_XYZW) {
2799             srcs[header_regs++] = brw_imm_ud(mask << 16);
2800             opcode = indirect_offset.file != BAD_FILE ?
2801                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT :
2802                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED;
2803          } else if (is_64bit && ((mask & WRITEMASK_XY) != WRITEMASK_XY)) {
2804             /* Expand the 64-bit mask to 32-bit channels. We only handle
2805              * two channels in each iteration, so we only care about X/Y.
2806              */
2807             unsigned mask32 = 0;
2808             if (mask & WRITEMASK_X)
2809                mask32 |= WRITEMASK_XY;
2810             if (mask & WRITEMASK_Y)
2811                mask32 |= WRITEMASK_ZW;
2812
2813             /* If the mask does not include any of the channels X or Y there
2814              * is nothing to do in this iteration. Move on to the next couple
2815              * of 64-bit channels.
2816              */
2817             if (!mask32) {
2818                mask >>= 2;
2819                imm_offset++;
2820                continue;
2821             }
2822
2823             srcs[header_regs++] = brw_imm_ud(mask32 << 16);
2824             opcode = indirect_offset.file != BAD_FILE ?
2825                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT :
2826                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED;
2827          } else {
2828             opcode = indirect_offset.file != BAD_FILE ?
2829                SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT :
2830                SHADER_OPCODE_URB_WRITE_SIMD8;
2831          }
2832
2833          for (unsigned i = 0; i < iter_components; i++) {
2834             if (!(mask & (1 << (i + first_component))))
2835                continue;
2836
2837             if (!is_64bit) {
2838                srcs[header_regs + i + first_component] = offset(value, bld, i);
2839             } else {
2840                /* We need to shuffle the 64-bit data to match the layout
2841                 * expected by our 32-bit URB write messages. We use a temporary
2842                 * for that.
2843                 */
2844                unsigned channel = iter * 2 + i;
2845                fs_reg dest = shuffle_for_32bit_write(bld, value, channel, 1);
2846
2847                srcs[header_regs + (i + first_component) * 2] = dest;
2848                srcs[header_regs + (i + first_component) * 2 + 1] =
2849                   offset(dest, bld, 1);
2850             }
2851          }
2852
2853          unsigned mlen =
2854             header_regs + (is_64bit ? 2 * iter_components : iter_components) +
2855             (is_64bit ? 2 * first_component : first_component);
2856          fs_reg payload =
2857             bld.vgrf(BRW_REGISTER_TYPE_UD, mlen);
2858          bld.LOAD_PAYLOAD(payload, srcs, mlen, header_regs);
2859
2860          fs_inst *inst = bld.emit(opcode, bld.null_reg_ud(), payload);
2861          inst->offset = imm_offset;
2862          inst->mlen = mlen;
2863
2864          /* If this is a 64-bit attribute, select the next two 64-bit channels
2865           * to be handled in the next iteration.
2866           */
2867          if (is_64bit) {
2868             mask >>= 2;
2869             imm_offset++;
2870          }
2871       }
2872       break;
2873    }
2874
2875    default:
2876       nir_emit_intrinsic(bld, instr);
2877       break;
2878    }
2879 }
2880
2881 void
2882 fs_visitor::nir_emit_tes_intrinsic(const fs_builder &bld,
2883                                    nir_intrinsic_instr *instr)
2884 {
2885    assert(stage == MESA_SHADER_TESS_EVAL);
2886    struct brw_tes_prog_data *tes_prog_data = brw_tes_prog_data(prog_data);
2887
2888    fs_reg dest;
2889    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
2890       dest = get_nir_dest(instr->dest);
2891
2892    switch (instr->intrinsic) {
2893    case nir_intrinsic_load_primitive_id:
2894       bld.MOV(dest, fs_reg(brw_vec1_grf(0, 1)));
2895       break;
2896    case nir_intrinsic_load_tess_coord:
2897       /* gl_TessCoord is part of the payload in g1-3 */
2898       for (unsigned i = 0; i < 3; i++) {
2899          bld.MOV(offset(dest, bld, i), fs_reg(brw_vec8_grf(1 + i, 0)));
2900       }
2901       break;
2902
2903    case nir_intrinsic_load_input:
2904    case nir_intrinsic_load_per_vertex_input: {
2905       fs_reg indirect_offset = get_indirect_offset(instr);
2906       unsigned imm_offset = instr->const_index[0];
2907       unsigned first_component = nir_intrinsic_component(instr);
2908
2909       if (type_sz(dest.type) == 8) {
2910          first_component = first_component / 2;
2911       }
2912
2913       fs_inst *inst;
2914       if (indirect_offset.file == BAD_FILE) {
2915          /* Arbitrarily only push up to 32 vec4 slots worth of data,
2916           * which is 16 registers (since each holds 2 vec4 slots).
2917           */
2918          unsigned slot_count = 1;
2919          if (type_sz(dest.type) == 8 && instr->num_components > 2)
2920             slot_count++;
2921
2922          const unsigned max_push_slots = 32;
2923          if (imm_offset + slot_count <= max_push_slots) {
2924             fs_reg src = fs_reg(ATTR, imm_offset / 2, dest.type);
2925             for (int i = 0; i < instr->num_components; i++) {
2926                unsigned comp = 16 / type_sz(dest.type) * (imm_offset % 2) +
2927                   i + first_component;
2928                bld.MOV(offset(dest, bld, i), component(src, comp));
2929             }
2930
2931             tes_prog_data->base.urb_read_length =
2932                MAX2(tes_prog_data->base.urb_read_length,
2933                     DIV_ROUND_UP(imm_offset + slot_count, 2));
2934          } else {
2935             /* Replicate the patch handle to all enabled channels */
2936             const fs_reg srcs[] = {
2937                retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)
2938             };
2939             fs_reg patch_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2940             bld.LOAD_PAYLOAD(patch_handle, srcs, ARRAY_SIZE(srcs), 0);
2941
2942             if (first_component != 0) {
2943                unsigned read_components =
2944                   instr->num_components + first_component;
2945                fs_reg tmp = bld.vgrf(dest.type, read_components);
2946                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp,
2947                                patch_handle);
2948                inst->size_written = read_components * REG_SIZE;
2949                for (unsigned i = 0; i < instr->num_components; i++) {
2950                   bld.MOV(offset(dest, bld, i),
2951                           offset(tmp, bld, i + first_component));
2952                }
2953             } else {
2954                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, dest,
2955                                patch_handle);
2956                inst->size_written = instr->num_components * REG_SIZE;
2957             }
2958             inst->mlen = 1;
2959             inst->offset = imm_offset;
2960          }
2961       } else {
2962          /* Indirect indexing - use per-slot offsets as well. */
2963
2964          /* We can only read two double components with each URB read, so
2965           * we send two read messages in that case, each one loading up to
2966           * two double components.
2967           */
2968          unsigned num_iterations = 1;
2969          unsigned num_components = instr->num_components;
2970          fs_reg orig_dest = dest;
2971          if (type_sz(dest.type) == 8) {
2972             if (instr->num_components > 2) {
2973                num_iterations = 2;
2974                num_components = 2;
2975             }
2976             fs_reg tmp = fs_reg(VGRF, alloc.allocate(4), dest.type);
2977             dest = tmp;
2978          }
2979
2980          for (unsigned iter = 0; iter < num_iterations; iter++) {
2981             const fs_reg srcs[] = {
2982                retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD),
2983                indirect_offset
2984             };
2985             fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2986             bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2987
2988             if (first_component != 0) {
2989                unsigned read_components =
2990                    num_components + first_component;
2991                fs_reg tmp = bld.vgrf(dest.type, read_components);
2992                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2993                                payload);
2994                for (unsigned i = 0; i < num_components; i++) {
2995                   bld.MOV(offset(dest, bld, i),
2996                           offset(tmp, bld, i + first_component));
2997                }
2998             } else {
2999                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, dest,
3000                                payload);
3001             }
3002             inst->mlen = 2;
3003             inst->offset = imm_offset;
3004             inst->size_written = (num_components + first_component) *
3005                                  inst->dst.component_size(inst->exec_size);
3006
3007             /* If we are reading 64-bit data using 32-bit read messages we need
3008              * build proper 64-bit data elements by shuffling the low and high
3009              * 32-bit components around like we do for other things like UBOs
3010              * or SSBOs.
3011              */
3012             if (type_sz(dest.type) == 8) {
3013                shuffle_from_32bit_read(bld,
3014                                        offset(orig_dest, bld, iter * 2),
3015                                        retype(dest, BRW_REGISTER_TYPE_D),
3016                                        0, num_components);
3017             }
3018
3019             /* If we are loading double data and we need a second read message
3020              * adjust the offset
3021              */
3022             if (num_iterations > 1) {
3023                num_components = instr->num_components - 2;
3024                imm_offset++;
3025             }
3026          }
3027       }
3028       break;
3029    }
3030    default:
3031       nir_emit_intrinsic(bld, instr);
3032       break;
3033    }
3034 }
3035
3036 void
3037 fs_visitor::nir_emit_gs_intrinsic(const fs_builder &bld,
3038                                   nir_intrinsic_instr *instr)
3039 {
3040    assert(stage == MESA_SHADER_GEOMETRY);
3041    fs_reg indirect_offset;
3042
3043    fs_reg dest;
3044    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
3045       dest = get_nir_dest(instr->dest);
3046
3047    switch (instr->intrinsic) {
3048    case nir_intrinsic_load_primitive_id:
3049       assert(stage == MESA_SHADER_GEOMETRY);
3050       assert(brw_gs_prog_data(prog_data)->include_primitive_id);
3051       bld.MOV(retype(dest, BRW_REGISTER_TYPE_UD),
3052               retype(fs_reg(brw_vec8_grf(2, 0)), BRW_REGISTER_TYPE_UD));
3053       break;
3054
3055    case nir_intrinsic_load_input:
3056       unreachable("load_input intrinsics are invalid for the GS stage");
3057
3058    case nir_intrinsic_load_per_vertex_input:
3059       emit_gs_input_load(dest, instr->src[0], instr->const_index[0],
3060                          instr->src[1], instr->num_components,
3061                          nir_intrinsic_component(instr));
3062       break;
3063
3064    case nir_intrinsic_emit_vertex_with_counter:
3065       emit_gs_vertex(instr->src[0], instr->const_index[0]);
3066       break;
3067
3068    case nir_intrinsic_end_primitive_with_counter:
3069       emit_gs_end_primitive(instr->src[0]);
3070       break;
3071
3072    case nir_intrinsic_set_vertex_count:
3073       bld.MOV(this->final_gs_vertex_count, get_nir_src(instr->src[0]));
3074       break;
3075
3076    case nir_intrinsic_load_invocation_id: {
3077       fs_reg val = nir_system_values[SYSTEM_VALUE_INVOCATION_ID];
3078       assert(val.file != BAD_FILE);
3079       dest.type = val.type;
3080       bld.MOV(dest, val);
3081       break;
3082    }
3083
3084    default:
3085       nir_emit_intrinsic(bld, instr);
3086       break;
3087    }
3088 }
3089
3090 /**
3091  * Fetch the current render target layer index.
3092  */
3093 static fs_reg
3094 fetch_render_target_array_index(const fs_builder &bld)
3095 {
3096    if (bld.shader->devinfo->gen >= 6) {
3097       /* The render target array index is provided in the thread payload as
3098        * bits 26:16 of r0.0.
3099        */
3100       const fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_UD);
3101       bld.AND(idx, brw_uw1_reg(BRW_GENERAL_REGISTER_FILE, 0, 1),
3102               brw_imm_uw(0x7ff));
3103       return idx;
3104    } else {
3105       /* Pre-SNB we only ever render into the first layer of the framebuffer
3106        * since layered rendering is not implemented.
3107        */
3108       return brw_imm_ud(0);
3109    }
3110 }
3111
3112 /**
3113  * Fake non-coherent framebuffer read implemented using TXF to fetch from the
3114  * framebuffer at the current fragment coordinates and sample index.
3115  */
3116 fs_inst *
3117 fs_visitor::emit_non_coherent_fb_read(const fs_builder &bld, const fs_reg &dst,
3118                                       unsigned target)
3119 {
3120    const struct gen_device_info *devinfo = bld.shader->devinfo;
3121
3122    assert(bld.shader->stage == MESA_SHADER_FRAGMENT);
3123    const brw_wm_prog_key *wm_key =
3124       reinterpret_cast<const brw_wm_prog_key *>(key);
3125    assert(!wm_key->coherent_fb_fetch);
3126    const struct brw_wm_prog_data *wm_prog_data =
3127       brw_wm_prog_data(stage_prog_data);
3128
3129    /* Calculate the surface index relative to the start of the texture binding
3130     * table block, since that's what the texturing messages expect.
3131     */
3132    const unsigned surface = target +
3133       wm_prog_data->binding_table.render_target_read_start -
3134       wm_prog_data->base.binding_table.texture_start;
3135
3136    brw_mark_surface_used(
3137       bld.shader->stage_prog_data,
3138       wm_prog_data->binding_table.render_target_read_start + target);
3139
3140    /* Calculate the fragment coordinates. */
3141    const fs_reg coords = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
3142    bld.MOV(offset(coords, bld, 0), pixel_x);
3143    bld.MOV(offset(coords, bld, 1), pixel_y);
3144    bld.MOV(offset(coords, bld, 2), fetch_render_target_array_index(bld));
3145
3146    /* Calculate the sample index and MCS payload when multisampling.  Luckily
3147     * the MCS fetch message behaves deterministically for UMS surfaces, so it
3148     * shouldn't be necessary to recompile based on whether the framebuffer is
3149     * CMS or UMS.
3150     */
3151    if (wm_key->multisample_fbo &&
3152        nir_system_values[SYSTEM_VALUE_SAMPLE_ID].file == BAD_FILE)
3153       nir_system_values[SYSTEM_VALUE_SAMPLE_ID] = *emit_sampleid_setup();
3154
3155    const fs_reg sample = nir_system_values[SYSTEM_VALUE_SAMPLE_ID];
3156    const fs_reg mcs = wm_key->multisample_fbo ?
3157       emit_mcs_fetch(coords, 3, brw_imm_ud(surface)) : fs_reg();
3158
3159    /* Use either a normal or a CMS texel fetch message depending on whether
3160     * the framebuffer is single or multisample.  On SKL+ use the wide CMS
3161     * message just in case the framebuffer uses 16x multisampling, it should
3162     * be equivalent to the normal CMS fetch for lower multisampling modes.
3163     */
3164    const opcode op = !wm_key->multisample_fbo ? SHADER_OPCODE_TXF_LOGICAL :
3165                      devinfo->gen >= 9 ? SHADER_OPCODE_TXF_CMS_W_LOGICAL :
3166                      SHADER_OPCODE_TXF_CMS_LOGICAL;
3167
3168    /* Emit the instruction. */
3169    const fs_reg srcs[] = { coords, fs_reg(), brw_imm_ud(0), fs_reg(),
3170                            sample, mcs,
3171                            brw_imm_ud(surface), brw_imm_ud(0),
3172                            fs_reg(), brw_imm_ud(3), brw_imm_ud(0) };
3173    STATIC_ASSERT(ARRAY_SIZE(srcs) == TEX_LOGICAL_NUM_SRCS);
3174
3175    fs_inst *inst = bld.emit(op, dst, srcs, ARRAY_SIZE(srcs));
3176    inst->size_written = 4 * inst->dst.component_size(inst->exec_size);
3177
3178    return inst;
3179 }
3180
3181 /**
3182  * Actual coherent framebuffer read implemented using the native render target
3183  * read message.  Requires SKL+.
3184  */
3185 static fs_inst *
3186 emit_coherent_fb_read(const fs_builder &bld, const fs_reg &dst, unsigned target)
3187 {
3188    assert(bld.shader->devinfo->gen >= 9);
3189    fs_inst *inst = bld.emit(FS_OPCODE_FB_READ_LOGICAL, dst);
3190    inst->target = target;
3191    inst->size_written = 4 * inst->dst.component_size(inst->exec_size);
3192
3193    return inst;
3194 }
3195
3196 static fs_reg
3197 alloc_temporary(const fs_builder &bld, unsigned size, fs_reg *regs, unsigned n)
3198 {
3199    if (n && regs[0].file != BAD_FILE) {
3200       return regs[0];
3201
3202    } else {
3203       const fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, size);
3204
3205       for (unsigned i = 0; i < n; i++)
3206          regs[i] = tmp;
3207
3208       return tmp;
3209    }
3210 }
3211
3212 static fs_reg
3213 alloc_frag_output(fs_visitor *v, unsigned location)
3214 {
3215    assert(v->stage == MESA_SHADER_FRAGMENT);
3216    const brw_wm_prog_key *const key =
3217       reinterpret_cast<const brw_wm_prog_key *>(v->key);
3218    const unsigned l = GET_FIELD(location, BRW_NIR_FRAG_OUTPUT_LOCATION);
3219    const unsigned i = GET_FIELD(location, BRW_NIR_FRAG_OUTPUT_INDEX);
3220
3221    if (i > 0 || (key->force_dual_color_blend && l == FRAG_RESULT_DATA1))
3222       return alloc_temporary(v->bld, 4, &v->dual_src_output, 1);
3223
3224    else if (l == FRAG_RESULT_COLOR)
3225       return alloc_temporary(v->bld, 4, v->outputs,
3226                              MAX2(key->nr_color_regions, 1));
3227
3228    else if (l == FRAG_RESULT_DEPTH)
3229       return alloc_temporary(v->bld, 1, &v->frag_depth, 1);
3230
3231    else if (l == FRAG_RESULT_STENCIL)
3232       return alloc_temporary(v->bld, 1, &v->frag_stencil, 1);
3233
3234    else if (l == FRAG_RESULT_SAMPLE_MASK)
3235       return alloc_temporary(v->bld, 1, &v->sample_mask, 1);
3236
3237    else if (l >= FRAG_RESULT_DATA0 &&
3238             l < FRAG_RESULT_DATA0 + BRW_MAX_DRAW_BUFFERS)
3239       return alloc_temporary(v->bld, 4,
3240                              &v->outputs[l - FRAG_RESULT_DATA0], 1);
3241
3242    else
3243       unreachable("Invalid location");
3244 }
3245
3246 void
3247 fs_visitor::nir_emit_fs_intrinsic(const fs_builder &bld,
3248                                   nir_intrinsic_instr *instr)
3249 {
3250    assert(stage == MESA_SHADER_FRAGMENT);
3251
3252    fs_reg dest;
3253    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
3254       dest = get_nir_dest(instr->dest);
3255
3256    switch (instr->intrinsic) {
3257    case nir_intrinsic_load_front_face:
3258       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D),
3259               *emit_frontfacing_interpolation());
3260       break;
3261
3262    case nir_intrinsic_load_sample_pos: {
3263       fs_reg sample_pos = nir_system_values[SYSTEM_VALUE_SAMPLE_POS];
3264       assert(sample_pos.file != BAD_FILE);
3265       dest.type = sample_pos.type;
3266       bld.MOV(dest, sample_pos);
3267       bld.MOV(offset(dest, bld, 1), offset(sample_pos, bld, 1));
3268       break;
3269    }
3270
3271    case nir_intrinsic_load_layer_id:
3272       dest.type = BRW_REGISTER_TYPE_UD;
3273       bld.MOV(dest, fetch_render_target_array_index(bld));
3274       break;
3275
3276    case nir_intrinsic_load_helper_invocation:
3277    case nir_intrinsic_load_sample_mask_in:
3278    case nir_intrinsic_load_sample_id: {
3279       gl_system_value sv = nir_system_value_from_intrinsic(instr->intrinsic);
3280       fs_reg val = nir_system_values[sv];
3281       assert(val.file != BAD_FILE);
3282       dest.type = val.type;
3283       bld.MOV(dest, val);
3284       break;
3285    }
3286
3287    case nir_intrinsic_store_output: {
3288       const fs_reg src = get_nir_src(instr->src[0]);
3289       const nir_const_value *const_offset = nir_src_as_const_value(instr->src[1]);
3290       assert(const_offset && "Indirect output stores not allowed");
3291       const unsigned location = nir_intrinsic_base(instr) +
3292          SET_FIELD(const_offset->u32[0], BRW_NIR_FRAG_OUTPUT_LOCATION);
3293       const fs_reg new_dest = retype(alloc_frag_output(this, location),
3294                                      src.type);
3295
3296       for (unsigned j = 0; j < instr->num_components; j++)
3297          bld.MOV(offset(new_dest, bld, nir_intrinsic_component(instr) + j),
3298                  offset(src, bld, j));
3299
3300       break;
3301    }
3302
3303    case nir_intrinsic_load_output: {
3304       const unsigned l = GET_FIELD(nir_intrinsic_base(instr),
3305                                    BRW_NIR_FRAG_OUTPUT_LOCATION);
3306       assert(l >= FRAG_RESULT_DATA0);
3307       nir_const_value *const_offset = nir_src_as_const_value(instr->src[0]);
3308       assert(const_offset && "Indirect output loads not allowed");
3309       const unsigned target = l - FRAG_RESULT_DATA0 + const_offset->u32[0];
3310       const fs_reg tmp = bld.vgrf(dest.type, 4);
3311
3312       if (reinterpret_cast<const brw_wm_prog_key *>(key)->coherent_fb_fetch)
3313          emit_coherent_fb_read(bld, tmp, target);
3314       else
3315          emit_non_coherent_fb_read(bld, tmp, target);
3316
3317       for (unsigned j = 0; j < instr->num_components; j++) {
3318          bld.MOV(offset(dest, bld, j),
3319                  offset(tmp, bld, nir_intrinsic_component(instr) + j));
3320       }
3321
3322       break;
3323    }
3324
3325    case nir_intrinsic_discard:
3326    case nir_intrinsic_discard_if: {
3327       /* We track our discarded pixels in f0.1.  By predicating on it, we can
3328        * update just the flag bits that aren't yet discarded.  If there's no
3329        * condition, we emit a CMP of g0 != g0, so all currently executing
3330        * channels will get turned off.
3331        */
3332       fs_inst *cmp;
3333       if (instr->intrinsic == nir_intrinsic_discard_if) {
3334          cmp = bld.CMP(bld.null_reg_f(), get_nir_src(instr->src[0]),
3335                        brw_imm_d(0), BRW_CONDITIONAL_Z);
3336       } else {
3337          fs_reg some_reg = fs_reg(retype(brw_vec8_grf(0, 0),
3338                                        BRW_REGISTER_TYPE_UW));
3339          cmp = bld.CMP(bld.null_reg_f(), some_reg, some_reg, BRW_CONDITIONAL_NZ);
3340       }
3341       cmp->predicate = BRW_PREDICATE_NORMAL;
3342       cmp->flag_subreg = 1;
3343
3344       if (devinfo->gen >= 6) {
3345          emit_discard_jump();
3346       }
3347       break;
3348    }
3349
3350    case nir_intrinsic_load_input: {
3351       /* load_input is only used for flat inputs */
3352       unsigned base = nir_intrinsic_base(instr);
3353       unsigned comp = nir_intrinsic_component(instr);
3354       unsigned num_components = instr->num_components;
3355       fs_reg orig_dest = dest;
3356       enum brw_reg_type type = dest.type;
3357
3358       /* Special case fields in the VUE header */
3359       if (base == VARYING_SLOT_LAYER)
3360          comp = 1;
3361       else if (base == VARYING_SLOT_VIEWPORT)
3362          comp = 2;
3363
3364       if (nir_dest_bit_size(instr->dest) == 64) {
3365          /* const_index is in 32-bit type size units that could not be aligned
3366           * with DF. We need to read the double vector as if it was a float
3367           * vector of twice the number of components to fetch the right data.
3368           */
3369          type = BRW_REGISTER_TYPE_F;
3370          num_components *= 2;
3371          dest = bld.vgrf(type, num_components);
3372       }
3373
3374       for (unsigned int i = 0; i < num_components; i++) {
3375          bld.MOV(offset(retype(dest, type), bld, i),
3376                  retype(component(interp_reg(base, comp + i), 3), type));
3377       }
3378
3379       if (nir_dest_bit_size(instr->dest) == 64) {
3380          shuffle_from_32bit_read(bld, orig_dest, dest, 0,
3381                                  instr->num_components);
3382       }
3383       break;
3384    }
3385
3386    case nir_intrinsic_load_barycentric_pixel:
3387    case nir_intrinsic_load_barycentric_centroid:
3388    case nir_intrinsic_load_barycentric_sample:
3389       /* Do nothing - load_interpolated_input handling will handle it later. */
3390       break;
3391
3392    case nir_intrinsic_load_barycentric_at_sample: {
3393       const glsl_interp_mode interpolation =
3394          (enum glsl_interp_mode) nir_intrinsic_interp_mode(instr);
3395
3396       nir_const_value *const_sample = nir_src_as_const_value(instr->src[0]);
3397
3398       if (const_sample) {
3399          unsigned msg_data = const_sample->i32[0] << 4;
3400
3401          emit_pixel_interpolater_send(bld,
3402                                       FS_OPCODE_INTERPOLATE_AT_SAMPLE,
3403                                       dest,
3404                                       fs_reg(), /* src */
3405                                       brw_imm_ud(msg_data),
3406                                       interpolation);
3407       } else {
3408          const fs_reg sample_src = retype(get_nir_src(instr->src[0]),
3409                                           BRW_REGISTER_TYPE_UD);
3410
3411          if (nir_src_is_dynamically_uniform(instr->src[0])) {
3412             const fs_reg sample_id = bld.emit_uniformize(sample_src);
3413             const fs_reg msg_data = vgrf(glsl_type::uint_type);
3414             bld.exec_all().group(1, 0)
3415                .SHL(msg_data, sample_id, brw_imm_ud(4u));
3416             emit_pixel_interpolater_send(bld,
3417                                          FS_OPCODE_INTERPOLATE_AT_SAMPLE,
3418                                          dest,
3419                                          fs_reg(), /* src */
3420                                          msg_data,
3421                                          interpolation);
3422          } else {
3423             /* Make a loop that sends a message to the pixel interpolater
3424              * for the sample number in each live channel. If there are
3425              * multiple channels with the same sample number then these
3426              * will be handled simultaneously with a single interation of
3427              * the loop.
3428              */
3429             bld.emit(BRW_OPCODE_DO);
3430
3431             /* Get the next live sample number into sample_id_reg */
3432             const fs_reg sample_id = bld.emit_uniformize(sample_src);
3433
3434             /* Set the flag register so that we can perform the send
3435              * message on all channels that have the same sample number
3436              */
3437             bld.CMP(bld.null_reg_ud(),
3438                     sample_src, sample_id,
3439                     BRW_CONDITIONAL_EQ);
3440             const fs_reg msg_data = vgrf(glsl_type::uint_type);
3441             bld.exec_all().group(1, 0)
3442                .SHL(msg_data, sample_id, brw_imm_ud(4u));
3443             fs_inst *inst =
3444                emit_pixel_interpolater_send(bld,
3445                                             FS_OPCODE_INTERPOLATE_AT_SAMPLE,
3446                                             dest,
3447                                             fs_reg(), /* src */
3448                                             msg_data,
3449                                             interpolation);
3450             set_predicate(BRW_PREDICATE_NORMAL, inst);
3451
3452             /* Continue the loop if there are any live channels left */
3453             set_predicate_inv(BRW_PREDICATE_NORMAL,
3454                               true, /* inverse */
3455                               bld.emit(BRW_OPCODE_WHILE));
3456          }
3457       }
3458       break;
3459    }
3460
3461    case nir_intrinsic_load_barycentric_at_offset: {
3462       const glsl_interp_mode interpolation =
3463          (enum glsl_interp_mode) nir_intrinsic_interp_mode(instr);
3464
3465       nir_const_value *const_offset = nir_src_as_const_value(instr->src[0]);
3466
3467       if (const_offset) {
3468          unsigned off_x = MIN2((int)(const_offset->f32[0] * 16), 7) & 0xf;
3469          unsigned off_y = MIN2((int)(const_offset->f32[1] * 16), 7) & 0xf;
3470
3471          emit_pixel_interpolater_send(bld,
3472                                       FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET,
3473                                       dest,
3474                                       fs_reg(), /* src */
3475                                       brw_imm_ud(off_x | (off_y << 4)),
3476                                       interpolation);
3477       } else {
3478          fs_reg src = vgrf(glsl_type::ivec2_type);
3479          fs_reg offset_src = retype(get_nir_src(instr->src[0]),
3480                                     BRW_REGISTER_TYPE_F);
3481          for (int i = 0; i < 2; i++) {
3482             fs_reg temp = vgrf(glsl_type::float_type);
3483             bld.MUL(temp, offset(offset_src, bld, i), brw_imm_f(16.0f));
3484             fs_reg itemp = vgrf(glsl_type::int_type);
3485             /* float to int */
3486             bld.MOV(itemp, temp);
3487
3488             /* Clamp the upper end of the range to +7/16.
3489              * ARB_gpu_shader5 requires that we support a maximum offset
3490              * of +0.5, which isn't representable in a S0.4 value -- if
3491              * we didn't clamp it, we'd end up with -8/16, which is the
3492              * opposite of what the shader author wanted.
3493              *
3494              * This is legal due to ARB_gpu_shader5's quantization
3495              * rules:
3496              *
3497              * "Not all values of <offset> may be supported; x and y
3498              * offsets may be rounded to fixed-point values with the
3499              * number of fraction bits given by the
3500              * implementation-dependent constant
3501              * FRAGMENT_INTERPOLATION_OFFSET_BITS"
3502              */
3503             set_condmod(BRW_CONDITIONAL_L,
3504                         bld.SEL(offset(src, bld, i), itemp, brw_imm_d(7)));
3505          }
3506
3507          const enum opcode opcode = FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET;
3508          emit_pixel_interpolater_send(bld,
3509                                       opcode,
3510                                       dest,
3511                                       src,
3512                                       brw_imm_ud(0u),
3513                                       interpolation);
3514       }
3515       break;
3516    }
3517
3518    case nir_intrinsic_load_interpolated_input: {
3519       if (nir_intrinsic_base(instr) == VARYING_SLOT_POS) {
3520          emit_fragcoord_interpolation(dest);
3521          break;
3522       }
3523
3524       assert(instr->src[0].ssa &&
3525              instr->src[0].ssa->parent_instr->type == nir_instr_type_intrinsic);
3526       nir_intrinsic_instr *bary_intrinsic =
3527          nir_instr_as_intrinsic(instr->src[0].ssa->parent_instr);
3528       nir_intrinsic_op bary_intrin = bary_intrinsic->intrinsic;
3529       enum glsl_interp_mode interp_mode =
3530          (enum glsl_interp_mode) nir_intrinsic_interp_mode(bary_intrinsic);
3531       fs_reg dst_xy;
3532
3533       if (bary_intrin == nir_intrinsic_load_barycentric_at_offset ||
3534           bary_intrin == nir_intrinsic_load_barycentric_at_sample) {
3535          /* Use the result of the PI message */
3536          dst_xy = retype(get_nir_src(instr->src[0]), BRW_REGISTER_TYPE_F);
3537       } else {
3538          /* Use the delta_xy values computed from the payload */
3539          enum brw_barycentric_mode bary =
3540             brw_barycentric_mode(interp_mode, bary_intrin);
3541
3542          dst_xy = this->delta_xy[bary];
3543       }
3544
3545       for (unsigned int i = 0; i < instr->num_components; i++) {
3546          fs_reg interp =
3547             component(interp_reg(nir_intrinsic_base(instr),
3548                                  nir_intrinsic_component(instr) + i), 0);
3549          interp.type = BRW_REGISTER_TYPE_F;
3550          dest.type = BRW_REGISTER_TYPE_F;
3551
3552          if (devinfo->gen < 6 && interp_mode == INTERP_MODE_SMOOTH) {
3553             fs_reg tmp = vgrf(glsl_type::float_type);
3554             bld.emit(FS_OPCODE_LINTERP, tmp, dst_xy, interp);
3555             bld.MUL(offset(dest, bld, i), tmp, this->pixel_w);
3556          } else {
3557             bld.emit(FS_OPCODE_LINTERP, offset(dest, bld, i), dst_xy, interp);
3558          }
3559       }
3560       break;
3561    }
3562
3563    default:
3564       nir_emit_intrinsic(bld, instr);
3565       break;
3566    }
3567 }
3568
3569 void
3570 fs_visitor::nir_emit_cs_intrinsic(const fs_builder &bld,
3571                                   nir_intrinsic_instr *instr)
3572 {
3573    assert(stage == MESA_SHADER_COMPUTE);
3574    struct brw_cs_prog_data *cs_prog_data = brw_cs_prog_data(prog_data);
3575
3576    fs_reg dest;
3577    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
3578       dest = get_nir_dest(instr->dest);
3579
3580    switch (instr->intrinsic) {
3581    case nir_intrinsic_barrier:
3582       emit_barrier();
3583       cs_prog_data->uses_barrier = true;
3584       break;
3585
3586    case nir_intrinsic_load_subgroup_id:
3587       bld.MOV(retype(dest, BRW_REGISTER_TYPE_UD), subgroup_id);
3588       break;
3589
3590    case nir_intrinsic_load_local_invocation_id:
3591    case nir_intrinsic_load_work_group_id: {
3592       gl_system_value sv = nir_system_value_from_intrinsic(instr->intrinsic);
3593       fs_reg val = nir_system_values[sv];
3594       assert(val.file != BAD_FILE);
3595       dest.type = val.type;
3596       for (unsigned i = 0; i < 3; i++)
3597          bld.MOV(offset(dest, bld, i), offset(val, bld, i));
3598       break;
3599    }
3600
3601    case nir_intrinsic_load_num_work_groups: {
3602       const unsigned surface =
3603          cs_prog_data->binding_table.work_groups_start;
3604
3605       cs_prog_data->uses_num_work_groups = true;
3606
3607       fs_reg surf_index = brw_imm_ud(surface);
3608       brw_mark_surface_used(prog_data, surface);
3609
3610       /* Read the 3 GLuint components of gl_NumWorkGroups */
3611       for (unsigned i = 0; i < 3; i++) {
3612          fs_reg read_result =
3613             emit_untyped_read(bld, surf_index,
3614                               brw_imm_ud(i << 2),
3615                               1 /* dims */, 1 /* size */,
3616                               BRW_PREDICATE_NONE);
3617          read_result.type = dest.type;
3618          bld.MOV(dest, read_result);
3619          dest = offset(dest, bld, 1);
3620       }
3621       break;
3622    }
3623
3624    case nir_intrinsic_shared_atomic_add:
3625       nir_emit_shared_atomic(bld, BRW_AOP_ADD, instr);
3626       break;
3627    case nir_intrinsic_shared_atomic_imin:
3628       nir_emit_shared_atomic(bld, BRW_AOP_IMIN, instr);
3629       break;
3630    case nir_intrinsic_shared_atomic_umin:
3631       nir_emit_shared_atomic(bld, BRW_AOP_UMIN, instr);
3632       break;
3633    case nir_intrinsic_shared_atomic_imax:
3634       nir_emit_shared_atomic(bld, BRW_AOP_IMAX, instr);
3635       break;
3636    case nir_intrinsic_shared_atomic_umax:
3637       nir_emit_shared_atomic(bld, BRW_AOP_UMAX, instr);
3638       break;
3639    case nir_intrinsic_shared_atomic_and:
3640       nir_emit_shared_atomic(bld, BRW_AOP_AND, instr);
3641       break;
3642    case nir_intrinsic_shared_atomic_or:
3643       nir_emit_shared_atomic(bld, BRW_AOP_OR, instr);
3644       break;
3645    case nir_intrinsic_shared_atomic_xor:
3646       nir_emit_shared_atomic(bld, BRW_AOP_XOR, instr);
3647       break;
3648    case nir_intrinsic_shared_atomic_exchange:
3649       nir_emit_shared_atomic(bld, BRW_AOP_MOV, instr);
3650       break;
3651    case nir_intrinsic_shared_atomic_comp_swap:
3652       nir_emit_shared_atomic(bld, BRW_AOP_CMPWR, instr);
3653       break;
3654
3655    case nir_intrinsic_load_shared: {
3656       assert(devinfo->gen >= 7);
3657
3658       fs_reg surf_index = brw_imm_ud(GEN7_BTI_SLM);
3659
3660       /* Get the offset to read from */
3661       fs_reg offset_reg;
3662       nir_const_value *const_offset = nir_src_as_const_value(instr->src[0]);
3663       if (const_offset) {
3664          offset_reg = brw_imm_ud(instr->const_index[0] + const_offset->u32[0]);
3665       } else {
3666          offset_reg = vgrf(glsl_type::uint_type);
3667          bld.ADD(offset_reg,
3668                  retype(get_nir_src(instr->src[0]), BRW_REGISTER_TYPE_UD),
3669                  brw_imm_ud(instr->const_index[0]));
3670       }
3671
3672       /* Read the vector */
3673       do_untyped_vector_read(bld, dest, surf_index, offset_reg,
3674                              instr->num_components);
3675       break;
3676    }
3677
3678    case nir_intrinsic_store_shared: {
3679       assert(devinfo->gen >= 7);
3680
3681       /* Block index */
3682       fs_reg surf_index = brw_imm_ud(GEN7_BTI_SLM);
3683
3684       /* Value */
3685       fs_reg val_reg = get_nir_src(instr->src[0]);
3686
3687       /* Writemask */
3688       unsigned writemask = instr->const_index[1];
3689
3690       /* get_nir_src() retypes to integer. Be wary of 64-bit types though
3691        * since the untyped writes below operate in units of 32-bits, which
3692        * means that we need to write twice as many components each time.
3693        * Also, we have to suffle 64-bit data to be in the appropriate layout
3694        * expected by our 32-bit write messages.
3695        */
3696       unsigned type_size = 4;
3697       if (nir_src_bit_size(instr->src[0]) == 64) {
3698          type_size = 8;
3699          val_reg = shuffle_for_32bit_write(bld, val_reg, 0,
3700                                            instr->num_components);
3701       }
3702
3703       unsigned type_slots = type_size / 4;
3704
3705       /* Combine groups of consecutive enabled channels in one write
3706        * message. We use ffs to find the first enabled channel and then ffs on
3707        * the bit-inverse, down-shifted writemask to determine the length of
3708        * the block of enabled bits.
3709        */
3710       while (writemask) {
3711          unsigned first_component = ffs(writemask) - 1;
3712          unsigned length = ffs(~(writemask >> first_component)) - 1;
3713
3714          /* We can't write more than 2 64-bit components at once. Limit the
3715           * length of the write to what we can do and let the next iteration
3716           * handle the rest
3717           */
3718          if (type_size > 4)
3719             length = MIN2(2, length);
3720
3721          fs_reg offset_reg;
3722          nir_const_value *const_offset = nir_src_as_const_value(instr->src[1]);
3723          if (const_offset) {
3724             offset_reg = brw_imm_ud(instr->const_index[0] + const_offset->u32[0] +
3725                                     type_size * first_component);
3726          } else {
3727             offset_reg = vgrf(glsl_type::uint_type);
3728             bld.ADD(offset_reg,
3729                     retype(get_nir_src(instr->src[1]), BRW_REGISTER_TYPE_UD),
3730                     brw_imm_ud(instr->const_index[0] + type_size * first_component));
3731          }
3732
3733          emit_untyped_write(bld, surf_index, offset_reg,
3734                             offset(val_reg, bld, first_component * type_slots),
3735                             1 /* dims */, length * type_slots,
3736                             BRW_PREDICATE_NONE);
3737
3738          /* Clear the bits in the writemask that we just wrote, then try
3739           * again to see if more channels are left.
3740           */
3741          writemask &= (15 << (first_component + length));
3742       }
3743
3744       break;
3745    }
3746
3747    default:
3748       nir_emit_intrinsic(bld, instr);
3749       break;
3750    }
3751 }
3752
3753 static fs_reg
3754 brw_nir_reduction_op_identity(const fs_builder &bld,
3755                               nir_op op, brw_reg_type type)
3756 {
3757    nir_const_value value = nir_alu_binop_identity(op, type_sz(type) * 8);
3758    switch (type_sz(type)) {
3759    case 2:
3760       assert(type != BRW_REGISTER_TYPE_HF);
3761       return retype(brw_imm_uw(value.u16[0]), type);
3762    case 4:
3763       return retype(brw_imm_ud(value.u32[0]), type);
3764    case 8:
3765       if (type == BRW_REGISTER_TYPE_DF)
3766          return setup_imm_df(bld, value.f64[0]);
3767       else
3768          return retype(brw_imm_u64(value.u64[0]), type);
3769    default:
3770       unreachable("Invalid type size");
3771    }
3772 }
3773
3774 static opcode
3775 brw_op_for_nir_reduction_op(nir_op op)
3776 {
3777    switch (op) {
3778    case nir_op_iadd: return BRW_OPCODE_ADD;
3779    case nir_op_fadd: return BRW_OPCODE_ADD;
3780    case nir_op_imul: return BRW_OPCODE_MUL;
3781    case nir_op_fmul: return BRW_OPCODE_MUL;
3782    case nir_op_imin: return BRW_OPCODE_SEL;
3783    case nir_op_umin: return BRW_OPCODE_SEL;
3784    case nir_op_fmin: return BRW_OPCODE_SEL;
3785    case nir_op_imax: return BRW_OPCODE_SEL;
3786    case nir_op_umax: return BRW_OPCODE_SEL;
3787    case nir_op_fmax: return BRW_OPCODE_SEL;
3788    case nir_op_iand: return BRW_OPCODE_AND;
3789    case nir_op_ior:  return BRW_OPCODE_OR;
3790    case nir_op_ixor: return BRW_OPCODE_XOR;
3791    default:
3792       unreachable("Invalid reduction operation");
3793    }
3794 }
3795
3796 static brw_conditional_mod
3797 brw_cond_mod_for_nir_reduction_op(nir_op op)
3798 {
3799    switch (op) {
3800    case nir_op_iadd: return BRW_CONDITIONAL_NONE;
3801    case nir_op_fadd: return BRW_CONDITIONAL_NONE;
3802    case nir_op_imul: return BRW_CONDITIONAL_NONE;
3803    case nir_op_fmul: return BRW_CONDITIONAL_NONE;
3804    case nir_op_imin: return BRW_CONDITIONAL_L;
3805    case nir_op_umin: return BRW_CONDITIONAL_L;
3806    case nir_op_fmin: return BRW_CONDITIONAL_L;
3807    case nir_op_imax: return BRW_CONDITIONAL_GE;
3808    case nir_op_umax: return BRW_CONDITIONAL_GE;
3809    case nir_op_fmax: return BRW_CONDITIONAL_GE;
3810    case nir_op_iand: return BRW_CONDITIONAL_NONE;
3811    case nir_op_ior:  return BRW_CONDITIONAL_NONE;
3812    case nir_op_ixor: return BRW_CONDITIONAL_NONE;
3813    default:
3814       unreachable("Invalid reduction operation");
3815    }
3816 }
3817
3818 void
3819 fs_visitor::nir_emit_intrinsic(const fs_builder &bld, nir_intrinsic_instr *instr)
3820 {
3821    fs_reg dest;
3822    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
3823       dest = get_nir_dest(instr->dest);
3824
3825    switch (instr->intrinsic) {
3826    case nir_intrinsic_image_var_load:
3827    case nir_intrinsic_image_var_store:
3828    case nir_intrinsic_image_var_atomic_add:
3829    case nir_intrinsic_image_var_atomic_min:
3830    case nir_intrinsic_image_var_atomic_max:
3831    case nir_intrinsic_image_var_atomic_and:
3832    case nir_intrinsic_image_var_atomic_or:
3833    case nir_intrinsic_image_var_atomic_xor:
3834    case nir_intrinsic_image_var_atomic_exchange:
3835    case nir_intrinsic_image_var_atomic_comp_swap: {
3836       using namespace image_access;
3837
3838       if (stage == MESA_SHADER_FRAGMENT &&
3839           instr->intrinsic != nir_intrinsic_image_var_load)
3840          brw_wm_prog_data(prog_data)->has_side_effects = true;
3841
3842       /* Get the referenced image variable and type. */
3843       const nir_variable *var = instr->variables[0]->var;
3844       const glsl_type *type = var->type->without_array();
3845       const brw_reg_type base_type = get_image_base_type(type);
3846
3847       /* Get some metadata from the image intrinsic. */
3848       const nir_intrinsic_info *info = &nir_intrinsic_infos[instr->intrinsic];
3849       const unsigned arr_dims = type->sampler_array ? 1 : 0;
3850       const unsigned surf_dims = type->coordinate_components() - arr_dims;
3851       const unsigned format = var->data.image.format;
3852       const unsigned dest_components = nir_intrinsic_dest_components(instr);
3853
3854       /* Get the arguments of the image intrinsic. */
3855       const fs_reg image = get_nir_image_deref(instr->variables[0]);
3856       const fs_reg addr = retype(get_nir_src(instr->src[0]),
3857                                  BRW_REGISTER_TYPE_UD);
3858       const fs_reg src0 = (info->num_srcs >= 3 ?
3859                            retype(get_nir_src(instr->src[2]), base_type) :
3860                            fs_reg());
3861       const fs_reg src1 = (info->num_srcs >= 4 ?
3862                            retype(get_nir_src(instr->src[3]), base_type) :
3863                            fs_reg());
3864       fs_reg tmp;
3865
3866       /* Emit an image load, store or atomic op. */
3867       if (instr->intrinsic == nir_intrinsic_image_var_load)
3868          tmp = emit_image_load(bld, image, addr, surf_dims, arr_dims, format);
3869
3870       else if (instr->intrinsic == nir_intrinsic_image_var_store)
3871          emit_image_store(bld, image, addr, src0, surf_dims, arr_dims,
3872                           var->data.image.write_only ? GL_NONE : format);
3873
3874       else
3875          tmp = emit_image_atomic(bld, image, addr, src0, src1,
3876                                  surf_dims, arr_dims, dest_components,
3877                                  get_image_atomic_op(instr->intrinsic, type));
3878
3879       /* Assign the result. */
3880       for (unsigned c = 0; c < dest_components; ++c) {
3881          bld.MOV(offset(retype(dest, base_type), bld, c),
3882                offset(tmp, bld, c));
3883       }
3884       break;
3885    }
3886
3887    case nir_intrinsic_memory_barrier_atomic_counter:
3888    case nir_intrinsic_memory_barrier_buffer:
3889    case nir_intrinsic_memory_barrier_image:
3890    case nir_intrinsic_memory_barrier: {
3891       const fs_builder ubld = bld.group(8, 0);
3892       const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
3893       ubld.emit(SHADER_OPCODE_MEMORY_FENCE, tmp)
3894          ->size_written = 2 * REG_SIZE;
3895       break;
3896    }
3897
3898    case nir_intrinsic_group_memory_barrier:
3899    case nir_intrinsic_memory_barrier_shared:
3900       /* We treat these workgroup-level barriers as no-ops.  This should be
3901        * safe at present and as long as:
3902        *
3903        *  - Memory access instructions are not subsequently reordered by the
3904        *    compiler back-end.
3905        *
3906        *  - All threads from a given compute shader workgroup fit within a
3907        *    single subslice and therefore talk to the same HDC shared unit
3908        *    what supposedly guarantees ordering and coherency between threads
3909        *    from the same workgroup.  This may change in the future when we
3910        *    start splitting workgroups across multiple subslices.
3911        *
3912        *  - The context is not in fault-and-stream mode, which could cause
3913        *    memory transactions (including to SLM) prior to the barrier to be
3914        *    replayed after the barrier if a pagefault occurs.  This shouldn't
3915        *    be a problem up to and including SKL because fault-and-stream is
3916        *    not usable due to hardware issues, but that's likely to change in
3917        *    the future.
3918        */
3919       break;
3920
3921    case nir_intrinsic_shader_clock: {
3922       /* We cannot do anything if there is an event, so ignore it for now */
3923       const fs_reg shader_clock = get_timestamp(bld);
3924       const fs_reg srcs[] = { component(shader_clock, 0),
3925                               component(shader_clock, 1) };
3926       bld.LOAD_PAYLOAD(dest, srcs, ARRAY_SIZE(srcs), 0);
3927       break;
3928    }
3929
3930    case nir_intrinsic_image_var_size: {
3931       /* Get the referenced image variable and type. */
3932       const nir_variable *var = instr->variables[0]->var;
3933       const glsl_type *type = var->type->without_array();
3934
3935       /* Get the size of the image. */
3936       const fs_reg image = get_nir_image_deref(instr->variables[0]);
3937       const fs_reg size = offset(image, bld, BRW_IMAGE_PARAM_SIZE_OFFSET);
3938
3939       /* For 1DArray image types, the array index is stored in the Z component.
3940        * Fix this by swizzling the Z component to the Y component.
3941        */
3942       const bool is_1d_array_image =
3943                   type->sampler_dimensionality == GLSL_SAMPLER_DIM_1D &&
3944                   type->sampler_array;
3945
3946       /* For CubeArray images, we should count the number of cubes instead
3947        * of the number of faces. Fix it by dividing the (Z component) by 6.
3948        */
3949       const bool is_cube_array_image =
3950                   type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE &&
3951                   type->sampler_array;
3952
3953       /* Copy all the components. */
3954       for (unsigned c = 0; c < instr->dest.ssa.num_components; ++c) {
3955          if ((int)c >= type->coordinate_components()) {
3956              bld.MOV(offset(retype(dest, BRW_REGISTER_TYPE_D), bld, c),
3957                      brw_imm_d(1));
3958          } else if (c == 1 && is_1d_array_image) {
3959             bld.MOV(offset(retype(dest, BRW_REGISTER_TYPE_D), bld, c),
3960                     offset(size, bld, 2));
3961          } else if (c == 2 && is_cube_array_image) {
3962             bld.emit(SHADER_OPCODE_INT_QUOTIENT,
3963                      offset(retype(dest, BRW_REGISTER_TYPE_D), bld, c),
3964                      offset(size, bld, c), brw_imm_d(6));
3965          } else {
3966             bld.MOV(offset(retype(dest, BRW_REGISTER_TYPE_D), bld, c),
3967                     offset(size, bld, c));
3968          }
3969        }
3970
3971       break;
3972    }
3973
3974    case nir_intrinsic_image_var_samples:
3975       /* The driver does not support multi-sampled images. */
3976       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), brw_imm_d(1));
3977       break;
3978
3979    case nir_intrinsic_load_uniform: {
3980       /* Offsets are in bytes but they should always aligned to
3981        * the type size
3982        */
3983       assert(instr->const_index[0] % 4 == 0 ||
3984              instr->const_index[0] % type_sz(dest.type) == 0);
3985
3986       fs_reg src(UNIFORM, instr->const_index[0] / 4, dest.type);
3987
3988       nir_const_value *const_offset = nir_src_as_const_value(instr->src[0]);
3989       if (const_offset) {
3990          assert(const_offset->u32[0] % type_sz(dest.type) == 0);
3991          /* For 16-bit types we add the module of the const_index[0]
3992           * offset to access to not 32-bit aligned element
3993           */
3994          src.offset = const_offset->u32[0] + instr->const_index[0] % 4;
3995
3996          for (unsigned j = 0; j < instr->num_components; j++) {
3997             bld.MOV(offset(dest, bld, j), offset(src, bld, j));
3998          }
3999       } else {
4000          fs_reg indirect = retype(get_nir_src(instr->src[0]),
4001                                   BRW_REGISTER_TYPE_UD);
4002
4003          /* We need to pass a size to the MOV_INDIRECT but we don't want it to
4004           * go past the end of the uniform.  In order to keep the n'th
4005           * component from running past, we subtract off the size of all but
4006           * one component of the vector.
4007           */
4008          assert(instr->const_index[1] >=
4009                 instr->num_components * (int) type_sz(dest.type));
4010          unsigned read_size = instr->const_index[1] -
4011             (instr->num_components - 1) * type_sz(dest.type);
4012
4013          bool supports_64bit_indirects =
4014             !devinfo->is_cherryview && !gen_device_info_is_9lp(devinfo);
4015
4016          if (type_sz(dest.type) != 8 || supports_64bit_indirects) {
4017             for (unsigned j = 0; j < instr->num_components; j++) {
4018                bld.emit(SHADER_OPCODE_MOV_INDIRECT,
4019                         offset(dest, bld, j), offset(src, bld, j),
4020                         indirect, brw_imm_ud(read_size));
4021             }
4022          } else {
4023             const unsigned num_mov_indirects =
4024                type_sz(dest.type) / type_sz(BRW_REGISTER_TYPE_UD);
4025             /* We read a little bit less per MOV INDIRECT, as they are now
4026              * 32-bits ones instead of 64-bit. Fix read_size then.
4027              */
4028             const unsigned read_size_32bit = read_size -
4029                 (num_mov_indirects - 1) * type_sz(BRW_REGISTER_TYPE_UD);
4030             for (unsigned j = 0; j < instr->num_components; j++) {
4031                for (unsigned i = 0; i < num_mov_indirects; i++) {
4032                   bld.emit(SHADER_OPCODE_MOV_INDIRECT,
4033                            subscript(offset(dest, bld, j), BRW_REGISTER_TYPE_UD, i),
4034                            subscript(offset(src, bld, j), BRW_REGISTER_TYPE_UD, i),
4035                            indirect, brw_imm_ud(read_size_32bit));
4036                }
4037             }
4038          }
4039       }
4040       break;
4041    }
4042
4043    case nir_intrinsic_load_ubo: {
4044       nir_const_value *const_index = nir_src_as_const_value(instr->src[0]);
4045       fs_reg surf_index;
4046
4047       if (const_index) {
4048          const unsigned index = stage_prog_data->binding_table.ubo_start +
4049                                 const_index->u32[0];
4050          surf_index = brw_imm_ud(index);
4051          brw_mark_surface_used(prog_data, index);
4052       } else {
4053          /* The block index is not a constant. Evaluate the index expression
4054           * per-channel and add the base UBO index; we have to select a value
4055           * from any live channel.
4056           */
4057          surf_index = vgrf(glsl_type::uint_type);
4058          bld.ADD(surf_index, get_nir_src(instr->src[0]),
4059                  brw_imm_ud(stage_prog_data->binding_table.ubo_start));
4060          surf_index = bld.emit_uniformize(surf_index);
4061
4062          /* Assume this may touch any UBO. It would be nice to provide
4063           * a tighter bound, but the array information is already lowered away.
4064           */
4065          brw_mark_surface_used(prog_data,
4066                                stage_prog_data->binding_table.ubo_start +
4067                                nir->info.num_ubos - 1);
4068       }
4069
4070       nir_const_value *const_offset = nir_src_as_const_value(instr->src[1]);
4071       if (const_offset == NULL) {
4072          fs_reg base_offset = retype(get_nir_src(instr->src[1]),
4073                                      BRW_REGISTER_TYPE_UD);
4074
4075          for (int i = 0; i < instr->num_components; i++)
4076             VARYING_PULL_CONSTANT_LOAD(bld, offset(dest, bld, i), surf_index,
4077                                        base_offset, i * type_sz(dest.type));
4078       } else {
4079          /* Even if we are loading doubles, a pull constant load will load
4080           * a 32-bit vec4, so should only reserve vgrf space for that. If we
4081           * need to load a full dvec4 we will have to emit 2 loads. This is
4082           * similar to demote_pull_constants(), except that in that case we
4083           * see individual accesses to each component of the vector and then
4084           * we let CSE deal with duplicate loads. Here we see a vector access
4085           * and we have to split it if necessary.
4086           */
4087          const unsigned type_size = type_sz(dest.type);
4088
4089          /* See if we've selected this as a push constant candidate */
4090          if (const_index) {
4091             const unsigned ubo_block = const_index->u32[0];
4092             const unsigned offset_256b = const_offset->u32[0] / 32;
4093
4094             fs_reg push_reg;
4095             for (int i = 0; i < 4; i++) {
4096                const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
4097                if (range->block == ubo_block &&
4098                    offset_256b >= range->start &&
4099                    offset_256b < range->start + range->length) {
4100
4101                   push_reg = fs_reg(UNIFORM, UBO_START + i, dest.type);
4102                   push_reg.offset = const_offset->u32[0] - 32 * range->start;
4103                   break;
4104                }
4105             }
4106
4107             if (push_reg.file != BAD_FILE) {
4108                for (unsigned i = 0; i < instr->num_components; i++) {
4109                   bld.MOV(offset(dest, bld, i),
4110                           byte_offset(push_reg, i * type_size));
4111                }
4112                break;
4113             }
4114          }
4115
4116          const unsigned block_sz = 64; /* Fetch one cacheline at a time. */
4117          const fs_builder ubld = bld.exec_all().group(block_sz / 4, 0);
4118          const fs_reg packed_consts = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4119
4120          for (unsigned c = 0; c < instr->num_components;) {
4121             const unsigned base = const_offset->u32[0] + c * type_size;
4122             /* Number of usable components in the next block-aligned load. */
4123             const unsigned count = MIN2(instr->num_components - c,
4124                                         (block_sz - base % block_sz) / type_size);
4125
4126             ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
4127                       packed_consts, surf_index,
4128                       brw_imm_ud(base & ~(block_sz - 1)));
4129
4130             const fs_reg consts =
4131                retype(byte_offset(packed_consts, base & (block_sz - 1)),
4132                       dest.type);
4133
4134             for (unsigned d = 0; d < count; d++)
4135                bld.MOV(offset(dest, bld, c + d), component(consts, d));
4136
4137             c += count;
4138          }
4139       }
4140       break;
4141    }
4142
4143    case nir_intrinsic_load_ssbo: {
4144       assert(devinfo->gen >= 7);
4145
4146       nir_const_value *const_uniform_block =
4147          nir_src_as_const_value(instr->src[0]);
4148
4149       fs_reg surf_index;
4150       if (const_uniform_block) {
4151          unsigned index = stage_prog_data->binding_table.ssbo_start +
4152                           const_uniform_block->u32[0];
4153          surf_index = brw_imm_ud(index);
4154          brw_mark_surface_used(prog_data, index);
4155       } else {
4156          surf_index = vgrf(glsl_type::uint_type);
4157          bld.ADD(surf_index, get_nir_src(instr->src[0]),
4158                  brw_imm_ud(stage_prog_data->binding_table.ssbo_start));
4159
4160          /* Assume this may touch any UBO. It would be nice to provide
4161           * a tighter bound, but the array information is already lowered away.
4162           */
4163          brw_mark_surface_used(prog_data,
4164                                stage_prog_data->binding_table.ssbo_start +
4165                                nir->info.num_ssbos - 1);
4166       }
4167
4168       fs_reg offset_reg;
4169       nir_const_value *const_offset = nir_src_as_const_value(instr->src[1]);
4170       if (const_offset) {
4171          offset_reg = brw_imm_ud(const_offset->u32[0]);
4172       } else {
4173          offset_reg = retype(get_nir_src(instr->src[1]), BRW_REGISTER_TYPE_UD);
4174       }
4175
4176       /* Read the vector */
4177       do_untyped_vector_read(bld, dest, surf_index, offset_reg,
4178                              instr->num_components);
4179
4180       break;
4181    }
4182
4183    case nir_intrinsic_store_ssbo: {
4184       assert(devinfo->gen >= 7);
4185
4186       if (stage == MESA_SHADER_FRAGMENT)
4187          brw_wm_prog_data(prog_data)->has_side_effects = true;
4188
4189       /* Block index */
4190       fs_reg surf_index;
4191       nir_const_value *const_uniform_block =
4192          nir_src_as_const_value(instr->src[1]);
4193       if (const_uniform_block) {
4194          unsigned index = stage_prog_data->binding_table.ssbo_start +
4195                           const_uniform_block->u32[0];
4196          surf_index = brw_imm_ud(index);
4197          brw_mark_surface_used(prog_data, index);
4198       } else {
4199          surf_index = vgrf(glsl_type::uint_type);
4200          bld.ADD(surf_index, get_nir_src(instr->src[1]),
4201                   brw_imm_ud(stage_prog_data->binding_table.ssbo_start));
4202
4203          brw_mark_surface_used(prog_data,
4204                                stage_prog_data->binding_table.ssbo_start +
4205                                nir->info.num_ssbos - 1);
4206       }
4207
4208       /* Value */
4209       fs_reg val_reg = get_nir_src(instr->src[0]);
4210
4211       /* Writemask */
4212       unsigned writemask = instr->const_index[0];
4213
4214       /* get_nir_src() retypes to integer. Be wary of 64-bit types though
4215        * since the untyped writes below operate in units of 32-bits, which
4216        * means that we need to write twice as many components each time.
4217        * Also, we have to suffle 64-bit data to be in the appropriate layout
4218        * expected by our 32-bit write messages.
4219        */
4220       unsigned bit_size = nir_src_bit_size(instr->src[0]);
4221       unsigned type_size = bit_size / 8;
4222
4223       /* Combine groups of consecutive enabled channels in one write
4224        * message. We use ffs to find the first enabled channel and then ffs on
4225        * the bit-inverse, down-shifted writemask to determine the num_components
4226        * of the block of enabled bits.
4227        */
4228       while (writemask) {
4229          unsigned first_component = ffs(writemask) - 1;
4230          unsigned num_components = ffs(~(writemask >> first_component)) - 1;
4231          fs_reg write_src = offset(val_reg, bld, first_component);
4232
4233          nir_const_value *const_offset = nir_src_as_const_value(instr->src[2]);
4234
4235          if (type_size > 4) {
4236             /* We can't write more than 2 64-bit components at once. Limit
4237              * the num_components of the write to what we can do and let the next
4238              * iteration handle the rest.
4239              */
4240             num_components = MIN2(2, num_components);
4241             write_src = shuffle_for_32bit_write(bld, write_src, 0,
4242                                                 num_components);
4243          } else if (type_size < 4) {
4244             assert(type_size == 2);
4245             /* For 16-bit types we pack two consecutive values into a 32-bit
4246              * word and use an untyped write message. For single values or not
4247              * 32-bit-aligned we need to use byte-scattered writes because
4248              * untyped writes works with 32-bit components with 32-bit
4249              * alignment. byte_scattered_write messages only support one
4250              * 16-bit component at a time. As VK_KHR_relaxed_block_layout
4251              * could be enabled we can not guarantee that not constant offsets
4252              * to be 32-bit aligned for 16-bit types. For example an array, of
4253              * 16-bit vec3 with array element stride of 6.
4254              *
4255              * In the case of 32-bit aligned constant offsets if there is
4256              * a 3-components vector we submit one untyped-write message
4257              * of 32-bit (first two components), and one byte-scattered
4258              * write message (the last component).
4259              */
4260
4261             if ( !const_offset || ((const_offset->u32[0] +
4262                                    type_size * first_component) % 4)) {
4263                /* If we use a .yz writemask we also need to emit 2
4264                 * byte-scattered write messages because of y-component not
4265                 * being aligned to 32-bit.
4266                 */
4267                num_components = 1;
4268             } else if (num_components > 2 && (num_components % 2)) {
4269                /* If there is an odd number of consecutive components we left
4270                 * the not paired component for a following emit of length == 1
4271                 * with byte_scattered_write.
4272                 */
4273                num_components --;
4274             }
4275             /* For num_components == 1 we are also shuffling the component
4276              * because byte scattered writes of 16-bit need values to be dword
4277              * aligned. Shuffling only one component would be the same as
4278              * striding it.
4279              */
4280             write_src = shuffle_for_32bit_write(bld, write_src, 0,
4281                                                 num_components);
4282          }
4283
4284          fs_reg offset_reg;
4285
4286          if (const_offset) {
4287             offset_reg = brw_imm_ud(const_offset->u32[0] +
4288                                     type_size * first_component);
4289          } else {
4290             offset_reg = vgrf(glsl_type::uint_type);
4291             bld.ADD(offset_reg,
4292                     retype(get_nir_src(instr->src[2]), BRW_REGISTER_TYPE_UD),
4293                     brw_imm_ud(type_size * first_component));
4294          }
4295
4296          if (type_size < 4 && num_components == 1) {
4297             assert(type_size == 2);
4298             /* Untyped Surface messages have a fixed 32-bit size, so we need
4299              * to rely on byte scattered in order to write 16-bit elements.
4300              * The byte_scattered_write message needs that every written 16-bit
4301              * type to be aligned 32-bits (stride=2).
4302              */
4303             emit_byte_scattered_write(bld, surf_index, offset_reg,
4304                                       write_src,
4305                                       1 /* dims */, 1,
4306                                       bit_size,
4307                                       BRW_PREDICATE_NONE);
4308          } else {
4309             assert(num_components * type_size <= 16);
4310             assert((num_components * type_size) % 4 == 0);
4311             assert(offset_reg.file != BRW_IMMEDIATE_VALUE ||
4312                    offset_reg.ud % 4 == 0);
4313             unsigned num_slots = (num_components * type_size) / 4;
4314
4315             emit_untyped_write(bld, surf_index, offset_reg,
4316                                write_src,
4317                                1 /* dims */, num_slots,
4318                                BRW_PREDICATE_NONE);
4319          }
4320
4321          /* Clear the bits in the writemask that we just wrote, then try
4322           * again to see if more channels are left.
4323           */
4324          writemask &= (15 << (first_component + num_components));
4325       }
4326       break;
4327    }
4328
4329    case nir_intrinsic_store_output: {
4330       fs_reg src = get_nir_src(instr->src[0]);
4331
4332       nir_const_value *const_offset = nir_src_as_const_value(instr->src[1]);
4333       assert(const_offset && "Indirect output stores not allowed");
4334
4335       unsigned num_components = instr->num_components;
4336       unsigned first_component = nir_intrinsic_component(instr);
4337       if (nir_src_bit_size(instr->src[0]) == 64) {
4338          src = shuffle_for_32bit_write(bld, src, 0, num_components);
4339          num_components *= 2;
4340       }
4341
4342       fs_reg new_dest = retype(offset(outputs[instr->const_index[0]], bld,
4343                                       4 * const_offset->u32[0]), src.type);
4344       for (unsigned j = 0; j < num_components; j++) {
4345          bld.MOV(offset(new_dest, bld, j + first_component),
4346                  offset(src, bld, j));
4347       }
4348       break;
4349    }
4350
4351    case nir_intrinsic_ssbo_atomic_add:
4352       nir_emit_ssbo_atomic(bld, BRW_AOP_ADD, instr);
4353       break;
4354    case nir_intrinsic_ssbo_atomic_imin:
4355       nir_emit_ssbo_atomic(bld, BRW_AOP_IMIN, instr);
4356       break;
4357    case nir_intrinsic_ssbo_atomic_umin:
4358       nir_emit_ssbo_atomic(bld, BRW_AOP_UMIN, instr);
4359       break;
4360    case nir_intrinsic_ssbo_atomic_imax:
4361       nir_emit_ssbo_atomic(bld, BRW_AOP_IMAX, instr);
4362       break;
4363    case nir_intrinsic_ssbo_atomic_umax:
4364       nir_emit_ssbo_atomic(bld, BRW_AOP_UMAX, instr);
4365       break;
4366    case nir_intrinsic_ssbo_atomic_and:
4367       nir_emit_ssbo_atomic(bld, BRW_AOP_AND, instr);
4368       break;
4369    case nir_intrinsic_ssbo_atomic_or:
4370       nir_emit_ssbo_atomic(bld, BRW_AOP_OR, instr);
4371       break;
4372    case nir_intrinsic_ssbo_atomic_xor:
4373       nir_emit_ssbo_atomic(bld, BRW_AOP_XOR, instr);
4374       break;
4375    case nir_intrinsic_ssbo_atomic_exchange:
4376       nir_emit_ssbo_atomic(bld, BRW_AOP_MOV, instr);
4377       break;
4378    case nir_intrinsic_ssbo_atomic_comp_swap:
4379       nir_emit_ssbo_atomic(bld, BRW_AOP_CMPWR, instr);
4380       break;
4381
4382    case nir_intrinsic_get_buffer_size: {
4383       nir_const_value *const_uniform_block = nir_src_as_const_value(instr->src[0]);
4384       unsigned ssbo_index = const_uniform_block ? const_uniform_block->u32[0] : 0;
4385
4386       /* A resinfo's sampler message is used to get the buffer size.  The
4387        * SIMD8's writeback message consists of four registers and SIMD16's
4388        * writeback message consists of 8 destination registers (two per each
4389        * component).  Because we are only interested on the first channel of
4390        * the first returned component, where resinfo returns the buffer size
4391        * for SURFTYPE_BUFFER, we can just use the SIMD8 variant regardless of
4392        * the dispatch width.
4393        */
4394       const fs_builder ubld = bld.exec_all().group(8, 0);
4395       fs_reg src_payload = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4396       fs_reg ret_payload = ubld.vgrf(BRW_REGISTER_TYPE_UD, 4);
4397
4398       /* Set LOD = 0 */
4399       ubld.MOV(src_payload, brw_imm_d(0));
4400
4401       const unsigned index = prog_data->binding_table.ssbo_start + ssbo_index;
4402       fs_inst *inst = ubld.emit(SHADER_OPCODE_GET_BUFFER_SIZE, ret_payload,
4403                                 src_payload, brw_imm_ud(index));
4404       inst->header_size = 0;
4405       inst->mlen = 1;
4406       inst->size_written = 4 * REG_SIZE;
4407
4408       /* SKL PRM, vol07, 3D Media GPGPU Engine, Bounds Checking and Faulting:
4409        *
4410        * "Out-of-bounds checking is always performed at a DWord granularity. If
4411        * any part of the DWord is out-of-bounds then the whole DWord is
4412        * considered out-of-bounds."
4413        *
4414        * This implies that types with size smaller than 4-bytes need to be
4415        * padded if they don't complete the last dword of the buffer. But as we
4416        * need to maintain the original size we need to reverse the padding
4417        * calculation to return the correct size to know the number of elements
4418        * of an unsized array. As we stored in the last two bits of the surface
4419        * size the needed padding for the buffer, we calculate here the
4420        * original buffer_size reversing the surface_size calculation:
4421        *
4422        * surface_size = isl_align(buffer_size, 4) +
4423        *                (isl_align(buffer_size) - buffer_size)
4424        *
4425        * buffer_size = surface_size & ~3 - surface_size & 3
4426        */
4427
4428       fs_reg size_aligned4 = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4429       fs_reg size_padding = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4430       fs_reg buffer_size = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4431
4432       ubld.AND(size_padding, ret_payload, brw_imm_ud(3));
4433       ubld.AND(size_aligned4, ret_payload, brw_imm_ud(~3));
4434       ubld.ADD(buffer_size, size_aligned4, negate(size_padding));
4435
4436       bld.MOV(retype(dest, ret_payload.type), component(buffer_size, 0));
4437
4438       brw_mark_surface_used(prog_data, index);
4439       break;
4440    }
4441
4442    case nir_intrinsic_load_subgroup_invocation:
4443       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D),
4444               nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION]);
4445       break;
4446
4447    case nir_intrinsic_load_subgroup_eq_mask:
4448    case nir_intrinsic_load_subgroup_ge_mask:
4449    case nir_intrinsic_load_subgroup_gt_mask:
4450    case nir_intrinsic_load_subgroup_le_mask:
4451    case nir_intrinsic_load_subgroup_lt_mask:
4452       unreachable("not reached");
4453
4454    case nir_intrinsic_vote_any: {
4455       const fs_builder ubld = bld.exec_all().group(1, 0);
4456
4457       /* The any/all predicates do not consider channel enables. To prevent
4458        * dead channels from affecting the result, we initialize the flag with
4459        * with the identity value for the logical operation.
4460        */
4461       if (dispatch_width == 32) {
4462          /* For SIMD32, we use a UD type so we fill both f0.0 and f0.1. */
4463          ubld.MOV(retype(brw_flag_reg(0, 0), BRW_REGISTER_TYPE_UD),
4464                          brw_imm_ud(0));
4465       } else {
4466          ubld.MOV(brw_flag_reg(0, 0), brw_imm_uw(0));
4467       }
4468       bld.CMP(bld.null_reg_d(), get_nir_src(instr->src[0]), brw_imm_d(0), BRW_CONDITIONAL_NZ);
4469
4470       /* For some reason, the any/all predicates don't work properly with
4471        * SIMD32.  In particular, it appears that a SEL with a QtrCtrl of 2H
4472        * doesn't read the correct subset of the flag register and you end up
4473        * getting garbage in the second half.  Work around this by using a pair
4474        * of 1-wide MOVs and scattering the result.
4475        */
4476       fs_reg res1 = ubld.vgrf(BRW_REGISTER_TYPE_D);
4477       ubld.MOV(res1, brw_imm_d(0));
4478       set_predicate(dispatch_width == 8  ? BRW_PREDICATE_ALIGN1_ANY8H :
4479                     dispatch_width == 16 ? BRW_PREDICATE_ALIGN1_ANY16H :
4480                                            BRW_PREDICATE_ALIGN1_ANY32H,
4481                     ubld.MOV(res1, brw_imm_d(-1)));
4482
4483       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), component(res1, 0));
4484       break;
4485    }
4486    case nir_intrinsic_vote_all: {
4487       const fs_builder ubld = bld.exec_all().group(1, 0);
4488
4489       /* The any/all predicates do not consider channel enables. To prevent
4490        * dead channels from affecting the result, we initialize the flag with
4491        * with the identity value for the logical operation.
4492        */
4493       if (dispatch_width == 32) {
4494          /* For SIMD32, we use a UD type so we fill both f0.0 and f0.1. */
4495          ubld.MOV(retype(brw_flag_reg(0, 0), BRW_REGISTER_TYPE_UD),
4496                          brw_imm_ud(0xffffffff));
4497       } else {
4498          ubld.MOV(brw_flag_reg(0, 0), brw_imm_uw(0xffff));
4499       }
4500       bld.CMP(bld.null_reg_d(), get_nir_src(instr->src[0]), brw_imm_d(0), BRW_CONDITIONAL_NZ);
4501
4502       /* For some reason, the any/all predicates don't work properly with
4503        * SIMD32.  In particular, it appears that a SEL with a QtrCtrl of 2H
4504        * doesn't read the correct subset of the flag register and you end up
4505        * getting garbage in the second half.  Work around this by using a pair
4506        * of 1-wide MOVs and scattering the result.
4507        */
4508       fs_reg res1 = ubld.vgrf(BRW_REGISTER_TYPE_D);
4509       ubld.MOV(res1, brw_imm_d(0));
4510       set_predicate(dispatch_width == 8  ? BRW_PREDICATE_ALIGN1_ALL8H :
4511                     dispatch_width == 16 ? BRW_PREDICATE_ALIGN1_ALL16H :
4512                                            BRW_PREDICATE_ALIGN1_ALL32H,
4513                     ubld.MOV(res1, brw_imm_d(-1)));
4514
4515       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), component(res1, 0));
4516       break;
4517    }
4518    case nir_intrinsic_vote_feq:
4519    case nir_intrinsic_vote_ieq: {
4520       fs_reg value = get_nir_src(instr->src[0]);
4521       if (instr->intrinsic == nir_intrinsic_vote_feq) {
4522          const unsigned bit_size = nir_src_bit_size(instr->src[0]);
4523          value.type = brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_F);
4524       }
4525
4526       fs_reg uniformized = bld.emit_uniformize(value);
4527       const fs_builder ubld = bld.exec_all().group(1, 0);
4528
4529       /* The any/all predicates do not consider channel enables. To prevent
4530        * dead channels from affecting the result, we initialize the flag with
4531        * with the identity value for the logical operation.
4532        */
4533       if (dispatch_width == 32) {
4534          /* For SIMD32, we use a UD type so we fill both f0.0 and f0.1. */
4535          ubld.MOV(retype(brw_flag_reg(0, 0), BRW_REGISTER_TYPE_UD),
4536                          brw_imm_ud(0xffffffff));
4537       } else {
4538          ubld.MOV(brw_flag_reg(0, 0), brw_imm_uw(0xffff));
4539       }
4540       bld.CMP(bld.null_reg_d(), value, uniformized, BRW_CONDITIONAL_Z);
4541
4542       /* For some reason, the any/all predicates don't work properly with
4543        * SIMD32.  In particular, it appears that a SEL with a QtrCtrl of 2H
4544        * doesn't read the correct subset of the flag register and you end up
4545        * getting garbage in the second half.  Work around this by using a pair
4546        * of 1-wide MOVs and scattering the result.
4547        */
4548       fs_reg res1 = ubld.vgrf(BRW_REGISTER_TYPE_D);
4549       ubld.MOV(res1, brw_imm_d(0));
4550       set_predicate(dispatch_width == 8  ? BRW_PREDICATE_ALIGN1_ALL8H :
4551                     dispatch_width == 16 ? BRW_PREDICATE_ALIGN1_ALL16H :
4552                                            BRW_PREDICATE_ALIGN1_ALL32H,
4553                     ubld.MOV(res1, brw_imm_d(-1)));
4554
4555       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), component(res1, 0));
4556       break;
4557    }
4558
4559    case nir_intrinsic_ballot: {
4560       const fs_reg value = retype(get_nir_src(instr->src[0]),
4561                                   BRW_REGISTER_TYPE_UD);
4562       struct brw_reg flag = brw_flag_reg(0, 0);
4563       /* FIXME: For SIMD32 programs, this causes us to stomp on f0.1 as well
4564        * as f0.0.  This is a problem for fragment programs as we currently use
4565        * f0.1 for discards.  Fortunately, we don't support SIMD32 fragment
4566        * programs yet so this isn't a problem.  When we do, something will
4567        * have to change.
4568        */
4569       if (dispatch_width == 32)
4570          flag.type = BRW_REGISTER_TYPE_UD;
4571
4572       bld.exec_all().group(1, 0).MOV(flag, brw_imm_ud(0u));
4573       bld.CMP(bld.null_reg_ud(), value, brw_imm_ud(0u), BRW_CONDITIONAL_NZ);
4574
4575       if (instr->dest.ssa.bit_size > 32) {
4576          dest.type = BRW_REGISTER_TYPE_UQ;
4577       } else {
4578          dest.type = BRW_REGISTER_TYPE_UD;
4579       }
4580       bld.MOV(dest, flag);
4581       break;
4582    }
4583
4584    case nir_intrinsic_read_invocation: {
4585       const fs_reg value = get_nir_src(instr->src[0]);
4586       const fs_reg invocation = get_nir_src(instr->src[1]);
4587       fs_reg tmp = bld.vgrf(value.type);
4588
4589       bld.exec_all().emit(SHADER_OPCODE_BROADCAST, tmp, value,
4590                           bld.emit_uniformize(invocation));
4591
4592       bld.MOV(retype(dest, value.type), fs_reg(component(tmp, 0)));
4593       break;
4594    }
4595
4596    case nir_intrinsic_read_first_invocation: {
4597       const fs_reg value = get_nir_src(instr->src[0]);
4598       bld.MOV(retype(dest, value.type), bld.emit_uniformize(value));
4599       break;
4600    }
4601
4602    case nir_intrinsic_shuffle: {
4603       const fs_reg value = get_nir_src(instr->src[0]);
4604       const fs_reg index = get_nir_src(instr->src[1]);
4605
4606       bld.emit(SHADER_OPCODE_SHUFFLE, retype(dest, value.type), value, index);
4607       break;
4608    }
4609
4610    case nir_intrinsic_first_invocation: {
4611       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD);
4612       bld.exec_all().emit(SHADER_OPCODE_FIND_LIVE_CHANNEL, tmp);
4613       bld.MOV(retype(dest, BRW_REGISTER_TYPE_UD),
4614               fs_reg(component(tmp, 0)));
4615       break;
4616    }
4617
4618    case nir_intrinsic_quad_broadcast: {
4619       const fs_reg value = get_nir_src(instr->src[0]);
4620       nir_const_value *index = nir_src_as_const_value(instr->src[1]);
4621       assert(nir_src_bit_size(instr->src[1]) == 32);
4622
4623       bld.emit(SHADER_OPCODE_CLUSTER_BROADCAST, retype(dest, value.type),
4624                value, brw_imm_ud(index->u32[0]), brw_imm_ud(4));
4625       break;
4626    }
4627
4628    case nir_intrinsic_quad_swap_horizontal: {
4629       const fs_reg value = get_nir_src(instr->src[0]);
4630       const fs_reg tmp = bld.vgrf(value.type);
4631       const fs_builder ubld = bld.exec_all().group(dispatch_width / 2, 0);
4632
4633       const fs_reg src_left = horiz_stride(value, 2);
4634       const fs_reg src_right = horiz_stride(horiz_offset(value, 1), 2);
4635       const fs_reg tmp_left = horiz_stride(tmp, 2);
4636       const fs_reg tmp_right = horiz_stride(horiz_offset(tmp, 1), 2);
4637
4638       /* From the Cherryview PRM Vol. 7, "Register Region Restrictiosn":
4639        *
4640        *    "When source or destination datatype is 64b or operation is
4641        *    integer DWord multiply, regioning in Align1 must follow
4642        *    these rules:
4643        *
4644        *    [...]
4645        *
4646        *    3. Source and Destination offset must be the same, except
4647        *       the case of scalar source."
4648        *
4649        * In order to work around this, we have to emit two 32-bit MOVs instead
4650        * of a single 64-bit MOV to do the shuffle.
4651        */
4652       if (type_sz(value.type) > 4 &&
4653           (devinfo->is_cherryview || gen_device_info_is_9lp(devinfo))) {
4654          ubld.MOV(subscript(tmp_left, BRW_REGISTER_TYPE_D, 0),
4655                   subscript(src_right, BRW_REGISTER_TYPE_D, 0));
4656          ubld.MOV(subscript(tmp_left, BRW_REGISTER_TYPE_D, 1),
4657                   subscript(src_right, BRW_REGISTER_TYPE_D, 1));
4658          ubld.MOV(subscript(tmp_right, BRW_REGISTER_TYPE_D, 0),
4659                   subscript(src_left, BRW_REGISTER_TYPE_D, 0));
4660          ubld.MOV(subscript(tmp_right, BRW_REGISTER_TYPE_D, 1),
4661                   subscript(src_left, BRW_REGISTER_TYPE_D, 1));
4662       } else {
4663          ubld.MOV(tmp_left, src_right);
4664          ubld.MOV(tmp_right, src_left);
4665       }
4666       bld.MOV(retype(dest, value.type), tmp);
4667       break;
4668    }
4669
4670    case nir_intrinsic_quad_swap_vertical: {
4671       const fs_reg value = get_nir_src(instr->src[0]);
4672       if (nir_src_bit_size(instr->src[0]) == 32) {
4673          /* For 32-bit, we can use a SIMD4x2 instruction to do this easily */
4674          const fs_reg tmp = bld.vgrf(value.type);
4675          const fs_builder ubld = bld.exec_all();
4676          ubld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp, value,
4677                    brw_imm_ud(BRW_SWIZZLE4(2,3,0,1)));
4678          bld.MOV(retype(dest, value.type), tmp);
4679       } else {
4680          /* For larger data types, we have to either emit dispatch_width many
4681           * MOVs or else fall back to doing indirects.
4682           */
4683          fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_W);
4684          bld.XOR(idx, nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION],
4685                       brw_imm_w(0x2));
4686          bld.emit(SHADER_OPCODE_SHUFFLE, retype(dest, value.type), value, idx);
4687       }
4688       break;
4689    }
4690
4691    case nir_intrinsic_quad_swap_diagonal: {
4692       const fs_reg value = get_nir_src(instr->src[0]);
4693       if (nir_src_bit_size(instr->src[0]) == 32) {
4694          /* For 32-bit, we can use a SIMD4x2 instruction to do this easily */
4695          const fs_reg tmp = bld.vgrf(value.type);
4696          const fs_builder ubld = bld.exec_all();
4697          ubld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp, value,
4698                    brw_imm_ud(BRW_SWIZZLE4(3,2,1,0)));
4699          bld.MOV(retype(dest, value.type), tmp);
4700       } else {
4701          /* For larger data types, we have to either emit dispatch_width many
4702           * MOVs or else fall back to doing indirects.
4703           */
4704          fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_W);
4705          bld.XOR(idx, nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION],
4706                       brw_imm_w(0x3));
4707          bld.emit(SHADER_OPCODE_SHUFFLE, retype(dest, value.type), value, idx);
4708       }
4709       break;
4710    }
4711
4712    case nir_intrinsic_reduce: {
4713       fs_reg src = get_nir_src(instr->src[0]);
4714       nir_op redop = (nir_op)nir_intrinsic_reduction_op(instr);
4715       unsigned cluster_size = nir_intrinsic_cluster_size(instr);
4716       if (cluster_size == 0 || cluster_size > dispatch_width)
4717          cluster_size = dispatch_width;
4718
4719       /* Figure out the source type */
4720       src.type = brw_type_for_nir_type(devinfo,
4721          (nir_alu_type)(nir_op_infos[redop].input_types[0] |
4722                         nir_src_bit_size(instr->src[0])));
4723
4724       fs_reg identity = brw_nir_reduction_op_identity(bld, redop, src.type);
4725       opcode brw_op = brw_op_for_nir_reduction_op(redop);
4726       brw_conditional_mod cond_mod = brw_cond_mod_for_nir_reduction_op(redop);
4727
4728       /* Set up a register for all of our scratching around and initialize it
4729        * to reduction operation's identity value.
4730        */
4731       fs_reg scan = bld.vgrf(src.type);
4732       bld.exec_all().emit(SHADER_OPCODE_SEL_EXEC, scan, src, identity);
4733
4734       bld.emit_scan(brw_op, scan, cluster_size, cond_mod);
4735
4736       dest.type = src.type;
4737       if (cluster_size * type_sz(src.type) >= REG_SIZE * 2) {
4738          /* In this case, CLUSTER_BROADCAST instruction isn't needed because
4739           * the distance between clusters is at least 2 GRFs.  In this case,
4740           * we don't need the weird striding of the CLUSTER_BROADCAST
4741           * instruction and can just do regular MOVs.
4742           */
4743          assert((cluster_size * type_sz(src.type)) % (REG_SIZE * 2) == 0);
4744          const unsigned groups =
4745             (dispatch_width * type_sz(src.type)) / (REG_SIZE * 2);
4746          const unsigned group_size = dispatch_width / groups;
4747          for (unsigned i = 0; i < groups; i++) {
4748             const unsigned cluster = (i * group_size) / cluster_size;
4749             const unsigned comp = cluster * cluster_size + (cluster_size - 1);
4750             bld.group(group_size, i).MOV(horiz_offset(dest, i * group_size),
4751                                          component(scan, comp));
4752          }
4753       } else {
4754          bld.emit(SHADER_OPCODE_CLUSTER_BROADCAST, dest, scan,
4755                   brw_imm_ud(cluster_size - 1), brw_imm_ud(cluster_size));
4756       }
4757       break;
4758    }
4759
4760    case nir_intrinsic_inclusive_scan:
4761    case nir_intrinsic_exclusive_scan: {
4762       fs_reg src = get_nir_src(instr->src[0]);
4763       nir_op redop = (nir_op)nir_intrinsic_reduction_op(instr);
4764
4765       /* Figure out the source type */
4766       src.type = brw_type_for_nir_type(devinfo,
4767          (nir_alu_type)(nir_op_infos[redop].input_types[0] |
4768                         nir_src_bit_size(instr->src[0])));
4769
4770       fs_reg identity = brw_nir_reduction_op_identity(bld, redop, src.type);
4771       opcode brw_op = brw_op_for_nir_reduction_op(redop);
4772       brw_conditional_mod cond_mod = brw_cond_mod_for_nir_reduction_op(redop);
4773
4774       /* Set up a register for all of our scratching around and initialize it
4775        * to reduction operation's identity value.
4776        */
4777       fs_reg scan = bld.vgrf(src.type);
4778       const fs_builder allbld = bld.exec_all();
4779       allbld.emit(SHADER_OPCODE_SEL_EXEC, scan, src, identity);
4780
4781       if (instr->intrinsic == nir_intrinsic_exclusive_scan) {
4782          /* Exclusive scan is a bit harder because we have to do an annoying
4783           * shift of the contents before we can begin.  To make things worse,
4784           * we can't do this with a normal stride; we have to use indirects.
4785           */
4786          fs_reg shifted = bld.vgrf(src.type);
4787          fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_W);
4788          allbld.ADD(idx, nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION],
4789                          brw_imm_w(-1));
4790          allbld.emit(SHADER_OPCODE_SHUFFLE, shifted, scan, idx);
4791          allbld.group(1, 0).MOV(component(shifted, 0), identity);
4792          scan = shifted;
4793       }
4794
4795       bld.emit_scan(brw_op, scan, dispatch_width, cond_mod);
4796
4797       bld.MOV(retype(dest, src.type), scan);
4798       break;
4799    }
4800
4801    case nir_intrinsic_begin_invocation_interlock: {
4802       const fs_builder ubld = bld.group(8, 0);
4803       const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
4804
4805       ubld.emit(SHADER_OPCODE_INTERLOCK, tmp)->size_written = 2 *
4806          REG_SIZE;
4807
4808       break;
4809    }
4810
4811    case nir_intrinsic_end_invocation_interlock: {
4812       /* We don't need to do anything here */
4813       break;
4814    }
4815
4816    default:
4817       unreachable("unknown intrinsic");
4818    }
4819 }
4820
4821 void
4822 fs_visitor::nir_emit_ssbo_atomic(const fs_builder &bld,
4823                                  int op, nir_intrinsic_instr *instr)
4824 {
4825    if (stage == MESA_SHADER_FRAGMENT)
4826       brw_wm_prog_data(prog_data)->has_side_effects = true;
4827
4828    fs_reg dest;
4829    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
4830       dest = get_nir_dest(instr->dest);
4831
4832    fs_reg surface;
4833    nir_const_value *const_surface = nir_src_as_const_value(instr->src[0]);
4834    if (const_surface) {
4835       unsigned surf_index = stage_prog_data->binding_table.ssbo_start +
4836                             const_surface->u32[0];
4837       surface = brw_imm_ud(surf_index);
4838       brw_mark_surface_used(prog_data, surf_index);
4839    } else {
4840       surface = vgrf(glsl_type::uint_type);
4841       bld.ADD(surface, get_nir_src(instr->src[0]),
4842               brw_imm_ud(stage_prog_data->binding_table.ssbo_start));
4843
4844       /* Assume this may touch any SSBO. This is the same we do for other
4845        * UBO/SSBO accesses with non-constant surface.
4846        */
4847       brw_mark_surface_used(prog_data,
4848                             stage_prog_data->binding_table.ssbo_start +
4849                             nir->info.num_ssbos - 1);
4850    }
4851
4852    fs_reg offset = get_nir_src(instr->src[1]);
4853    fs_reg data1 = get_nir_src(instr->src[2]);
4854    fs_reg data2;
4855    if (op == BRW_AOP_CMPWR)
4856       data2 = get_nir_src(instr->src[3]);
4857
4858    /* Emit the actual atomic operation */
4859
4860    fs_reg atomic_result = emit_untyped_atomic(bld, surface, offset,
4861                                               data1, data2,
4862                                               1 /* dims */, 1 /* rsize */,
4863                                               op,
4864                                               BRW_PREDICATE_NONE);
4865    dest.type = atomic_result.type;
4866    bld.MOV(dest, atomic_result);
4867 }
4868
4869 void
4870 fs_visitor::nir_emit_shared_atomic(const fs_builder &bld,
4871                                    int op, nir_intrinsic_instr *instr)
4872 {
4873    fs_reg dest;
4874    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
4875       dest = get_nir_dest(instr->dest);
4876
4877    fs_reg surface = brw_imm_ud(GEN7_BTI_SLM);
4878    fs_reg offset;
4879    fs_reg data1 = get_nir_src(instr->src[1]);
4880    fs_reg data2;
4881    if (op == BRW_AOP_CMPWR)
4882       data2 = get_nir_src(instr->src[2]);
4883
4884    /* Get the offset */
4885    nir_const_value *const_offset = nir_src_as_const_value(instr->src[0]);
4886    if (const_offset) {
4887       offset = brw_imm_ud(instr->const_index[0] + const_offset->u32[0]);
4888    } else {
4889       offset = vgrf(glsl_type::uint_type);
4890       bld.ADD(offset,
4891               retype(get_nir_src(instr->src[0]), BRW_REGISTER_TYPE_UD),
4892               brw_imm_ud(instr->const_index[0]));
4893    }
4894
4895    /* Emit the actual atomic operation operation */
4896
4897    fs_reg atomic_result = emit_untyped_atomic(bld, surface, offset,
4898                                               data1, data2,
4899                                               1 /* dims */, 1 /* rsize */,
4900                                               op,
4901                                               BRW_PREDICATE_NONE);
4902    dest.type = atomic_result.type;
4903    bld.MOV(dest, atomic_result);
4904 }
4905
4906 void
4907 fs_visitor::nir_emit_texture(const fs_builder &bld, nir_tex_instr *instr)
4908 {
4909    unsigned texture = instr->texture_index;
4910    unsigned sampler = instr->sampler_index;
4911
4912    fs_reg srcs[TEX_LOGICAL_NUM_SRCS];
4913
4914    srcs[TEX_LOGICAL_SRC_SURFACE] = brw_imm_ud(texture);
4915    srcs[TEX_LOGICAL_SRC_SAMPLER] = brw_imm_ud(sampler);
4916
4917    int lod_components = 0;
4918
4919    /* The hardware requires a LOD for buffer textures */
4920    if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF)
4921       srcs[TEX_LOGICAL_SRC_LOD] = brw_imm_d(0);
4922
4923    uint32_t header_bits = 0;
4924    for (unsigned i = 0; i < instr->num_srcs; i++) {
4925       fs_reg src = get_nir_src(instr->src[i].src);
4926       switch (instr->src[i].src_type) {
4927       case nir_tex_src_bias:
4928          srcs[TEX_LOGICAL_SRC_LOD] =
4929             retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_F);
4930          break;
4931       case nir_tex_src_comparator:
4932          srcs[TEX_LOGICAL_SRC_SHADOW_C] = retype(src, BRW_REGISTER_TYPE_F);
4933          break;
4934       case nir_tex_src_coord:
4935          switch (instr->op) {
4936          case nir_texop_txf:
4937          case nir_texop_txf_ms:
4938          case nir_texop_txf_ms_mcs:
4939          case nir_texop_samples_identical:
4940             srcs[TEX_LOGICAL_SRC_COORDINATE] = retype(src, BRW_REGISTER_TYPE_D);
4941             break;
4942          default:
4943             srcs[TEX_LOGICAL_SRC_COORDINATE] = retype(src, BRW_REGISTER_TYPE_F);
4944             break;
4945          }
4946          break;
4947       case nir_tex_src_ddx:
4948          srcs[TEX_LOGICAL_SRC_LOD] = retype(src, BRW_REGISTER_TYPE_F);
4949          lod_components = nir_tex_instr_src_size(instr, i);
4950          break;
4951       case nir_tex_src_ddy:
4952          srcs[TEX_LOGICAL_SRC_LOD2] = retype(src, BRW_REGISTER_TYPE_F);
4953          break;
4954       case nir_tex_src_lod:
4955          switch (instr->op) {
4956          case nir_texop_txs:
4957             srcs[TEX_LOGICAL_SRC_LOD] =
4958                retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_UD);
4959             break;
4960          case nir_texop_txf:
4961             srcs[TEX_LOGICAL_SRC_LOD] =
4962                retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_D);
4963             break;
4964          default:
4965             srcs[TEX_LOGICAL_SRC_LOD] =
4966                retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_F);
4967             break;
4968          }
4969          break;
4970       case nir_tex_src_ms_index:
4971          srcs[TEX_LOGICAL_SRC_SAMPLE_INDEX] = retype(src, BRW_REGISTER_TYPE_UD);
4972          break;
4973
4974       case nir_tex_src_offset: {
4975          nir_const_value *const_offset =
4976             nir_src_as_const_value(instr->src[i].src);
4977          unsigned offset_bits = 0;
4978          if (const_offset &&
4979              brw_texture_offset(const_offset->i32,
4980                                 nir_tex_instr_src_size(instr, i),
4981                                 &offset_bits)) {
4982             header_bits |= offset_bits;
4983          } else {
4984             srcs[TEX_LOGICAL_SRC_TG4_OFFSET] =
4985                retype(src, BRW_REGISTER_TYPE_D);
4986          }
4987          break;
4988       }
4989
4990       case nir_tex_src_projector:
4991          unreachable("should be lowered");
4992
4993       case nir_tex_src_texture_offset: {
4994          /* Figure out the highest possible texture index and mark it as used */
4995          uint32_t max_used = texture + instr->texture_array_size - 1;
4996          if (instr->op == nir_texop_tg4 && devinfo->gen < 8) {
4997             max_used += stage_prog_data->binding_table.gather_texture_start;
4998          } else {
4999             max_used += stage_prog_data->binding_table.texture_start;
5000          }
5001          brw_mark_surface_used(prog_data, max_used);
5002
5003          /* Emit code to evaluate the actual indexing expression */
5004          fs_reg tmp = vgrf(glsl_type::uint_type);
5005          bld.ADD(tmp, src, brw_imm_ud(texture));
5006          srcs[TEX_LOGICAL_SRC_SURFACE] = bld.emit_uniformize(tmp);
5007          break;
5008       }
5009
5010       case nir_tex_src_sampler_offset: {
5011          /* Emit code to evaluate the actual indexing expression */
5012          fs_reg tmp = vgrf(glsl_type::uint_type);
5013          bld.ADD(tmp, src, brw_imm_ud(sampler));
5014          srcs[TEX_LOGICAL_SRC_SAMPLER] = bld.emit_uniformize(tmp);
5015          break;
5016       }
5017
5018       case nir_tex_src_ms_mcs:
5019          assert(instr->op == nir_texop_txf_ms);
5020          srcs[TEX_LOGICAL_SRC_MCS] = retype(src, BRW_REGISTER_TYPE_D);
5021          break;
5022
5023       case nir_tex_src_plane: {
5024          nir_const_value *const_plane =
5025             nir_src_as_const_value(instr->src[i].src);
5026          const uint32_t plane = const_plane->u32[0];
5027          const uint32_t texture_index =
5028             instr->texture_index +
5029             stage_prog_data->binding_table.plane_start[plane] -
5030             stage_prog_data->binding_table.texture_start;
5031
5032          srcs[TEX_LOGICAL_SRC_SURFACE] = brw_imm_ud(texture_index);
5033          break;
5034       }
5035
5036       default:
5037          unreachable("unknown texture source");
5038       }
5039    }
5040
5041    if (srcs[TEX_LOGICAL_SRC_MCS].file == BAD_FILE &&
5042        (instr->op == nir_texop_txf_ms ||
5043         instr->op == nir_texop_samples_identical)) {
5044       if (devinfo->gen >= 7 &&
5045           key_tex->compressed_multisample_layout_mask & (1 << texture)) {
5046          srcs[TEX_LOGICAL_SRC_MCS] =
5047             emit_mcs_fetch(srcs[TEX_LOGICAL_SRC_COORDINATE],
5048                            instr->coord_components,
5049                            srcs[TEX_LOGICAL_SRC_SURFACE]);
5050       } else {
5051          srcs[TEX_LOGICAL_SRC_MCS] = brw_imm_ud(0u);
5052       }
5053    }
5054
5055    srcs[TEX_LOGICAL_SRC_COORD_COMPONENTS] = brw_imm_d(instr->coord_components);
5056    srcs[TEX_LOGICAL_SRC_GRAD_COMPONENTS] = brw_imm_d(lod_components);
5057
5058    enum opcode opcode;
5059    switch (instr->op) {
5060    case nir_texop_tex:
5061       opcode = (stage == MESA_SHADER_FRAGMENT ? SHADER_OPCODE_TEX_LOGICAL :
5062                 SHADER_OPCODE_TXL_LOGICAL);
5063       break;
5064    case nir_texop_txb:
5065       opcode = FS_OPCODE_TXB_LOGICAL;
5066       break;
5067    case nir_texop_txl:
5068       opcode = SHADER_OPCODE_TXL_LOGICAL;
5069       break;
5070    case nir_texop_txd:
5071       opcode = SHADER_OPCODE_TXD_LOGICAL;
5072       break;
5073    case nir_texop_txf:
5074       opcode = SHADER_OPCODE_TXF_LOGICAL;
5075       break;
5076    case nir_texop_txf_ms:
5077       if ((key_tex->msaa_16 & (1 << sampler)))
5078          opcode = SHADER_OPCODE_TXF_CMS_W_LOGICAL;
5079       else
5080          opcode = SHADER_OPCODE_TXF_CMS_LOGICAL;
5081       break;
5082    case nir_texop_txf_ms_mcs:
5083       opcode = SHADER_OPCODE_TXF_MCS_LOGICAL;
5084       break;
5085    case nir_texop_query_levels:
5086    case nir_texop_txs:
5087       opcode = SHADER_OPCODE_TXS_LOGICAL;
5088       break;
5089    case nir_texop_lod:
5090       opcode = SHADER_OPCODE_LOD_LOGICAL;
5091       break;
5092    case nir_texop_tg4:
5093       if (srcs[TEX_LOGICAL_SRC_TG4_OFFSET].file != BAD_FILE)
5094          opcode = SHADER_OPCODE_TG4_OFFSET_LOGICAL;
5095       else
5096          opcode = SHADER_OPCODE_TG4_LOGICAL;
5097       break;
5098    case nir_texop_texture_samples:
5099       opcode = SHADER_OPCODE_SAMPLEINFO_LOGICAL;
5100       break;
5101    case nir_texop_samples_identical: {
5102       fs_reg dst = retype(get_nir_dest(instr->dest), BRW_REGISTER_TYPE_D);
5103
5104       /* If mcs is an immediate value, it means there is no MCS.  In that case
5105        * just return false.
5106        */
5107       if (srcs[TEX_LOGICAL_SRC_MCS].file == BRW_IMMEDIATE_VALUE) {
5108          bld.MOV(dst, brw_imm_ud(0u));
5109       } else if ((key_tex->msaa_16 & (1 << sampler))) {
5110          fs_reg tmp = vgrf(glsl_type::uint_type);
5111          bld.OR(tmp, srcs[TEX_LOGICAL_SRC_MCS],
5112                 offset(srcs[TEX_LOGICAL_SRC_MCS], bld, 1));
5113          bld.CMP(dst, tmp, brw_imm_ud(0u), BRW_CONDITIONAL_EQ);
5114       } else {
5115          bld.CMP(dst, srcs[TEX_LOGICAL_SRC_MCS], brw_imm_ud(0u),
5116                  BRW_CONDITIONAL_EQ);
5117       }
5118       return;
5119    }
5120    default:
5121       unreachable("unknown texture opcode");
5122    }
5123
5124    if (instr->op == nir_texop_tg4) {
5125       if (instr->component == 1 &&
5126           key_tex->gather_channel_quirk_mask & (1 << texture)) {
5127          /* gather4 sampler is broken for green channel on RG32F --
5128           * we must ask for blue instead.
5129           */
5130          header_bits |= 2 << 16;
5131       } else {
5132          header_bits |= instr->component << 16;
5133       }
5134    }
5135
5136    fs_reg dst = bld.vgrf(brw_type_for_nir_type(devinfo, instr->dest_type), 4);
5137    fs_inst *inst = bld.emit(opcode, dst, srcs, ARRAY_SIZE(srcs));
5138    inst->offset = header_bits;
5139
5140    const unsigned dest_size = nir_tex_instr_dest_size(instr);
5141    if (devinfo->gen >= 9 &&
5142        instr->op != nir_texop_tg4 && instr->op != nir_texop_query_levels) {
5143       unsigned write_mask = instr->dest.is_ssa ?
5144                             nir_ssa_def_components_read(&instr->dest.ssa):
5145                             (1 << dest_size) - 1;
5146       assert(write_mask != 0); /* dead code should have been eliminated */
5147       inst->size_written = util_last_bit(write_mask) *
5148                            inst->dst.component_size(inst->exec_size);
5149    } else {
5150       inst->size_written = 4 * inst->dst.component_size(inst->exec_size);
5151    }
5152
5153    if (srcs[TEX_LOGICAL_SRC_SHADOW_C].file != BAD_FILE)
5154       inst->shadow_compare = true;
5155
5156    if (instr->op == nir_texop_tg4 && devinfo->gen == 6)
5157       emit_gen6_gather_wa(key_tex->gen6_gather_wa[texture], dst);
5158
5159    fs_reg nir_dest[4];
5160    for (unsigned i = 0; i < dest_size; i++)
5161       nir_dest[i] = offset(dst, bld, i);
5162
5163    if (instr->op == nir_texop_query_levels) {
5164       /* # levels is in .w */
5165       nir_dest[0] = offset(dst, bld, 3);
5166    } else if (instr->op == nir_texop_txs &&
5167               dest_size >= 3 && devinfo->gen < 7) {
5168       /* Gen4-6 return 0 instead of 1 for single layer surfaces. */
5169       fs_reg depth = offset(dst, bld, 2);
5170       nir_dest[2] = vgrf(glsl_type::int_type);
5171       bld.emit_minmax(nir_dest[2], depth, brw_imm_d(1), BRW_CONDITIONAL_GE);
5172    }
5173
5174    bld.LOAD_PAYLOAD(get_nir_dest(instr->dest), nir_dest, dest_size, 0);
5175 }
5176
5177 void
5178 fs_visitor::nir_emit_jump(const fs_builder &bld, nir_jump_instr *instr)
5179 {
5180    switch (instr->type) {
5181    case nir_jump_break:
5182       bld.emit(BRW_OPCODE_BREAK);
5183       break;
5184    case nir_jump_continue:
5185       bld.emit(BRW_OPCODE_CONTINUE);
5186       break;
5187    case nir_jump_return:
5188    default:
5189       unreachable("unknown jump");
5190    }
5191 }
5192
5193 /**
5194  * This helper does the inverse operation of
5195  * SHUFFLE_32BIT_LOAD_RESULT_TO_64BIT_DATA.
5196  *
5197  * We need to do this when we are going to use untyped write messsages that
5198  * operate with 32-bit components in order to arrange our 64-bit data to be
5199  * in the expected layout.
5200  *
5201  * Notice that callers of this function, unlike in the case of the inverse
5202  * operation, would typically need to call this with dst and src being
5203  * different registers, since they would otherwise corrupt the original
5204  * 64-bit data they are about to write. Because of this the function checks
5205  * that the src and dst regions involved in the operation do not overlap.
5206  */
5207 fs_reg
5208 shuffle_64bit_data_for_32bit_write(const fs_builder &bld,
5209                                    const fs_reg &src,
5210                                    uint32_t components)
5211 {
5212    assert(type_sz(src.type) == 8);
5213
5214    fs_reg dst = bld.vgrf(BRW_REGISTER_TYPE_D, 2 * components);
5215
5216    for (unsigned i = 0; i < components; i++) {
5217       const fs_reg component_i = offset(src, bld, i);
5218       bld.MOV(offset(dst, bld, 2 * i), subscript(component_i, dst.type, 0));
5219       bld.MOV(offset(dst, bld, 2 * i + 1), subscript(component_i, dst.type, 1));
5220    }
5221
5222    return dst;
5223 }
5224
5225 /*
5226  * This helper takes a source register and un/shuffles it into the destination
5227  * register.
5228  *
5229  * If source type size is smaller than destination type size the operation
5230  * needed is a component shuffle. The opposite case would be an unshuffle. If
5231  * source/destination type size is equal a shuffle is done that would be
5232  * equivalent to a simple MOV.
5233  *
5234  * For example, if source is a 16-bit type and destination is 32-bit. A 3
5235  * components .xyz 16-bit vector on SIMD8 would be.
5236  *
5237  *    |x1|x2|x3|x4|x5|x6|x7|x8|y1|y2|y3|y4|y5|y6|y7|y8|
5238  *    |z1|z2|z3|z4|z5|z6|z7|z8|  |  |  |  |  |  |  |  |
5239  *
5240  * This helper will return the following 2 32-bit components with the 16-bit
5241  * values shuffled:
5242  *
5243  *    |x1 y1|x2 y2|x3 y3|x4 y4|x5 y5|x6 y6|x7 y7|x8 y8|
5244  *    |z1   |z2   |z3   |z4   |z5   |z6   |z7   |z8   |
5245  *
5246  * For unshuffle, the example would be the opposite, a 64-bit type source
5247  * and a 32-bit destination. A 2 component .xy 64-bit vector on SIMD8
5248  * would be:
5249  *
5250  *    | x1l   x1h | x2l   x2h | x3l   x3h | x4l   x4h |
5251  *    | x5l   x5h | x6l   x6h | x7l   x7h | x8l   x8h |
5252  *    | y1l   y1h | y2l   y2h | y3l   y3h | y4l   y4h |
5253  *    | y5l   y5h | y6l   y6h | y7l   y7h | y8l   y8h |
5254  *
5255  * The returned result would be the following 4 32-bit components unshuffled:
5256  *
5257  *    | x1l | x2l | x3l | x4l | x5l | x6l | x7l | x8l |
5258  *    | x1h | x2h | x3h | x4h | x5h | x6h | x7h | x8h |
5259  *    | y1l | y2l | y3l | y4l | y5l | y6l | y7l | y8l |
5260  *    | y1h | y2h | y3h | y4h | y5h | y6h | y7h | y8h |
5261  *
5262  * - Source and destination register must not be overlapped.
5263  * - components units are measured in terms of the smaller type between
5264  *   source and destination because we are un/shuffling the smaller
5265  *   components from/into the bigger ones.
5266  * - first_component parameter allows skipping source components.
5267  */
5268 void
5269 shuffle_src_to_dst(const fs_builder &bld,
5270                    const fs_reg &dst,
5271                    const fs_reg &src,
5272                    uint32_t first_component,
5273                    uint32_t components)
5274 {
5275    if (type_sz(src.type) == type_sz(dst.type)) {
5276       assert(!regions_overlap(dst,
5277          type_sz(dst.type) * bld.dispatch_width() * components,
5278          offset(src, bld, first_component),
5279          type_sz(src.type) * bld.dispatch_width() * components));
5280       for (unsigned i = 0; i < components; i++) {
5281          bld.MOV(retype(offset(dst, bld, i), src.type),
5282                  offset(src, bld, i + first_component));
5283       }
5284    } else if (type_sz(src.type) < type_sz(dst.type)) {
5285       /* Source is shuffled into destination */
5286       unsigned size_ratio = type_sz(dst.type) / type_sz(src.type);
5287       assert(!regions_overlap(dst,
5288          type_sz(dst.type) * bld.dispatch_width() *
5289          DIV_ROUND_UP(components, size_ratio),
5290          offset(src, bld, first_component),
5291          type_sz(src.type) * bld.dispatch_width() * components));
5292
5293       brw_reg_type shuffle_type =
5294          brw_reg_type_from_bit_size(8 * type_sz(src.type),
5295                                     BRW_REGISTER_TYPE_D);
5296       for (unsigned i = 0; i < components; i++) {
5297          fs_reg shuffle_component_i =
5298             subscript(offset(dst, bld, i / size_ratio),
5299                       shuffle_type, i % size_ratio);
5300          bld.MOV(shuffle_component_i,
5301                  retype(offset(src, bld, i + first_component), shuffle_type));
5302       }
5303    } else {
5304       /* Source is unshuffled into destination */
5305       unsigned size_ratio = type_sz(src.type) / type_sz(dst.type);
5306       assert(!regions_overlap(dst,
5307          type_sz(dst.type) * bld.dispatch_width() * components,
5308          offset(src, bld, first_component / size_ratio),
5309          type_sz(src.type) * bld.dispatch_width() *
5310          DIV_ROUND_UP(components + (first_component % size_ratio),
5311                       size_ratio)));
5312
5313       brw_reg_type shuffle_type =
5314          brw_reg_type_from_bit_size(8 * type_sz(dst.type),
5315                                     BRW_REGISTER_TYPE_D);
5316       for (unsigned i = 0; i < components; i++) {
5317          fs_reg shuffle_component_i =
5318             subscript(offset(src, bld, (first_component + i) / size_ratio),
5319                       shuffle_type, (first_component + i) % size_ratio);
5320          bld.MOV(retype(offset(dst, bld, i), shuffle_type),
5321                  shuffle_component_i);
5322       }
5323    }
5324 }
5325
5326 void
5327 shuffle_from_32bit_read(const fs_builder &bld,
5328                         const fs_reg &dst,
5329                         const fs_reg &src,
5330                         uint32_t first_component,
5331                         uint32_t components)
5332 {
5333    assert(type_sz(src.type) == 4);
5334
5335    /* This function takes components in units of the destination type while
5336     * shuffle_src_to_dst takes components in units of the smallest type
5337     */
5338    if (type_sz(dst.type) > 4) {
5339       assert(type_sz(dst.type) == 8);
5340       first_component *= 2;
5341       components *= 2;
5342    }
5343
5344    shuffle_src_to_dst(bld, dst, src, first_component, components);
5345 }
5346
5347 fs_reg
5348 shuffle_for_32bit_write(const fs_builder &bld,
5349                         const fs_reg &src,
5350                         uint32_t first_component,
5351                         uint32_t components)
5352 {
5353    fs_reg dst = bld.vgrf(BRW_REGISTER_TYPE_D,
5354                          DIV_ROUND_UP (components * type_sz(src.type), 4));
5355    /* This function takes components in units of the source type while
5356     * shuffle_src_to_dst takes components in units of the smallest type
5357     */
5358    if (type_sz(src.type) > 4) {
5359       assert(type_sz(src.type) == 8);
5360       first_component *= 2;
5361       components *= 2;
5362    }
5363
5364    shuffle_src_to_dst(bld, dst, src, first_component, components);
5365
5366    return dst;
5367 }
5368
5369 fs_reg
5370 setup_imm_df(const fs_builder &bld, double v)
5371 {
5372    const struct gen_device_info *devinfo = bld.shader->devinfo;
5373    assert(devinfo->gen >= 7);
5374
5375    if (devinfo->gen >= 8)
5376       return brw_imm_df(v);
5377
5378    /* gen7.5 does not support DF immediates straighforward but the DIM
5379     * instruction allows to set the 64-bit immediate value.
5380     */
5381    if (devinfo->is_haswell) {
5382       const fs_builder ubld = bld.exec_all().group(1, 0);
5383       fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_DF, 1);
5384       ubld.DIM(dst, brw_imm_df(v));
5385       return component(dst, 0);
5386    }
5387
5388    /* gen7 does not support DF immediates, so we generate a 64-bit constant by
5389     * writing the low 32-bit of the constant to suboffset 0 of a VGRF and
5390     * the high 32-bit to suboffset 4 and then applying a stride of 0.
5391     *
5392     * Alternatively, we could also produce a normal VGRF (without stride 0)
5393     * by writing to all the channels in the VGRF, however, that would hit the
5394     * gen7 bug where we have to split writes that span more than 1 register
5395     * into instructions with a width of 4 (otherwise the write to the second
5396     * register written runs into an execmask hardware bug) which isn't very
5397     * nice.
5398     */
5399    union {
5400       double d;
5401       struct {
5402          uint32_t i1;
5403          uint32_t i2;
5404       };
5405    } di;
5406
5407    di.d = v;
5408
5409    const fs_builder ubld = bld.exec_all().group(1, 0);
5410    const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
5411    ubld.MOV(tmp, brw_imm_ud(di.i1));
5412    ubld.MOV(horiz_offset(tmp, 1), brw_imm_ud(di.i2));
5413
5414    return component(retype(tmp, BRW_REGISTER_TYPE_DF), 0);
5415 }