1/*
2 * Copyright © 2015 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 "brw_nir.h"
25#include "brw_vec4.h"
26#include "brw_vec4_builder.h"
27#include "brw_vec4_surface_builder.h"
28#include "brw_eu.h"
29
30using namespace brw;
31using namespace brw::surface_access;
32
33namespace brw {
34
35void
36vec4_visitor::emit_nir_code()
37{
38   if (nir->num_uniforms > 0)
39      nir_setup_uniforms();
40
41   nir_emit_impl(nir_shader_get_entrypoint((nir_shader *)nir));
42}
43
44void
45vec4_visitor::nir_setup_uniforms()
46{
47   uniforms = nir->num_uniforms / 16;
48}
49
50void
51vec4_visitor::nir_emit_impl(nir_function_impl *impl)
52{
53   nir_locals = ralloc_array(mem_ctx, dst_reg, impl->reg_alloc);
54   for (unsigned i = 0; i < impl->reg_alloc; i++) {
55      nir_locals[i] = dst_reg();
56   }
57
58   foreach_list_typed(nir_register, reg, node, &impl->registers) {
59      unsigned array_elems =
60         reg->num_array_elems == 0 ? 1 : reg->num_array_elems;
61      const unsigned num_regs = array_elems * DIV_ROUND_UP(reg->bit_size, 32);
62      nir_locals[reg->index] = dst_reg(VGRF, alloc.allocate(num_regs));
63
64      if (reg->bit_size == 64)
65         nir_locals[reg->index].type = BRW_REGISTER_TYPE_DF;
66   }
67
68   nir_ssa_values = ralloc_array(mem_ctx, dst_reg, impl->ssa_alloc);
69
70   nir_emit_cf_list(&impl->body);
71}
72
73void
74vec4_visitor::nir_emit_cf_list(exec_list *list)
75{
76   exec_list_validate(list);
77   foreach_list_typed(nir_cf_node, node, node, list) {
78      switch (node->type) {
79      case nir_cf_node_if:
80         nir_emit_if(nir_cf_node_as_if(node));
81         break;
82
83      case nir_cf_node_loop:
84         nir_emit_loop(nir_cf_node_as_loop(node));
85         break;
86
87      case nir_cf_node_block:
88         nir_emit_block(nir_cf_node_as_block(node));
89         break;
90
91      default:
92         unreachable("Invalid CFG node block");
93      }
94   }
95}
96
97void
98vec4_visitor::nir_emit_if(nir_if *if_stmt)
99{
100   /* First, put the condition in f0 */
101   src_reg condition = get_nir_src(if_stmt->condition, BRW_REGISTER_TYPE_D, 1);
102   vec4_instruction *inst = emit(MOV(dst_null_d(), condition));
103   inst->conditional_mod = BRW_CONDITIONAL_NZ;
104
105   /* We can just predicate based on the X channel, as the condition only
106    * goes on its own line */
107   emit(IF(BRW_PREDICATE_ALIGN16_REPLICATE_X));
108
109   nir_emit_cf_list(&if_stmt->then_list);
110
111   /* note: if the else is empty, dead CF elimination will remove it */
112   emit(BRW_OPCODE_ELSE);
113
114   nir_emit_cf_list(&if_stmt->else_list);
115
116   emit(BRW_OPCODE_ENDIF);
117}
118
119void
120vec4_visitor::nir_emit_loop(nir_loop *loop)
121{
122   emit(BRW_OPCODE_DO);
123
124   nir_emit_cf_list(&loop->body);
125
126   emit(BRW_OPCODE_WHILE);
127}
128
129void
130vec4_visitor::nir_emit_block(nir_block *block)
131{
132   nir_foreach_instr(instr, block) {
133      nir_emit_instr(instr);
134   }
135}
136
137void
138vec4_visitor::nir_emit_instr(nir_instr *instr)
139{
140   base_ir = instr;
141
142   switch (instr->type) {
143   case nir_instr_type_load_const:
144      nir_emit_load_const(nir_instr_as_load_const(instr));
145      break;
146
147   case nir_instr_type_intrinsic:
148      nir_emit_intrinsic(nir_instr_as_intrinsic(instr));
149      break;
150
151   case nir_instr_type_alu:
152      nir_emit_alu(nir_instr_as_alu(instr));
153      break;
154
155   case nir_instr_type_jump:
156      nir_emit_jump(nir_instr_as_jump(instr));
157      break;
158
159   case nir_instr_type_tex:
160      nir_emit_texture(nir_instr_as_tex(instr));
161      break;
162
163   case nir_instr_type_ssa_undef:
164      nir_emit_undef(nir_instr_as_ssa_undef(instr));
165      break;
166
167   default:
168      unreachable("VS instruction not yet implemented by NIR->vec4");
169   }
170}
171
172static dst_reg
173dst_reg_for_nir_reg(vec4_visitor *v, nir_register *nir_reg,
174                    unsigned base_offset, nir_src *indirect)
175{
176   dst_reg reg;
177
178   reg = v->nir_locals[nir_reg->index];
179   if (nir_reg->bit_size == 64)
180      reg.type = BRW_REGISTER_TYPE_DF;
181   reg = offset(reg, 8, base_offset);
182   if (indirect) {
183      reg.reladdr =
184         new(v->mem_ctx) src_reg(v->get_nir_src(*indirect,
185                                                BRW_REGISTER_TYPE_D,
186                                                1));
187   }
188   return reg;
189}
190
191dst_reg
192vec4_visitor::get_nir_dest(const nir_dest &dest)
193{
194   if (dest.is_ssa) {
195      dst_reg dst =
196         dst_reg(VGRF, alloc.allocate(DIV_ROUND_UP(dest.ssa.bit_size, 32)));
197      if (dest.ssa.bit_size == 64)
198         dst.type = BRW_REGISTER_TYPE_DF;
199      nir_ssa_values[dest.ssa.index] = dst;
200      return dst;
201   } else {
202      return dst_reg_for_nir_reg(this, dest.reg.reg, dest.reg.base_offset,
203                                 dest.reg.indirect);
204   }
205}
206
207dst_reg
208vec4_visitor::get_nir_dest(const nir_dest &dest, enum brw_reg_type type)
209{
210   return retype(get_nir_dest(dest), type);
211}
212
213dst_reg
214vec4_visitor::get_nir_dest(const nir_dest &dest, nir_alu_type type)
215{
216   return get_nir_dest(dest, brw_type_for_nir_type(devinfo, type));
217}
218
219src_reg
220vec4_visitor::get_nir_src(const nir_src &src, enum brw_reg_type type,
221                          unsigned num_components)
222{
223   dst_reg reg;
224
225   if (src.is_ssa) {
226      assert(src.ssa != NULL);
227      reg = nir_ssa_values[src.ssa->index];
228   }
229   else {
230      reg = dst_reg_for_nir_reg(this, src.reg.reg, src.reg.base_offset,
231                                src.reg.indirect);
232   }
233
234   reg = retype(reg, type);
235
236   src_reg reg_as_src = src_reg(reg);
237   reg_as_src.swizzle = brw_swizzle_for_size(num_components);
238   return reg_as_src;
239}
240
241src_reg
242vec4_visitor::get_nir_src(const nir_src &src, nir_alu_type type,
243                          unsigned num_components)
244{
245   return get_nir_src(src, brw_type_for_nir_type(devinfo, type),
246                      num_components);
247}
248
249src_reg
250vec4_visitor::get_nir_src(const nir_src &src, unsigned num_components)
251{
252   /* if type is not specified, default to signed int */
253   return get_nir_src(src, nir_type_int32, num_components);
254}
255
256src_reg
257vec4_visitor::get_nir_src_imm(const nir_src &src)
258{
259   assert(nir_src_num_components(src) == 1);
260   assert(nir_src_bit_size(src) == 32);
261   return nir_src_is_const(src) ? src_reg(brw_imm_d(nir_src_as_int(src))) :
262                                  get_nir_src(src, 1);
263}
264
265src_reg
266vec4_visitor::get_indirect_offset(nir_intrinsic_instr *instr)
267{
268   nir_src *offset_src = nir_get_io_offset_src(instr);
269
270   if (nir_src_is_const(*offset_src)) {
271      /* The only constant offset we should find is 0.  brw_nir.c's
272       * add_const_offset_to_base() will fold other constant offsets
273       * into instr->const_index[0].
274       */
275      assert(nir_src_as_uint(*offset_src) == 0);
276      return src_reg();
277   }
278
279   return get_nir_src(*offset_src, BRW_REGISTER_TYPE_UD, 1);
280}
281
282static src_reg
283setup_imm_df(const vec4_builder &bld, double v)
284{
285   const intel_device_info *devinfo = bld.shader->devinfo;
286   assert(devinfo->ver == 7);
287
288   /* gfx7.5 does not support DF immediates straighforward but the DIM
289    * instruction allows to set the 64-bit immediate value.
290    */
291   if (devinfo->is_haswell) {
292      const vec4_builder ubld = bld.exec_all();
293      const dst_reg dst = bld.vgrf(BRW_REGISTER_TYPE_DF);
294      ubld.DIM(dst, brw_imm_df(v));
295      return swizzle(src_reg(dst), BRW_SWIZZLE_XXXX);
296   }
297
298   /* gfx7 does not support DF immediates */
299   union {
300      double d;
301      struct {
302         uint32_t i1;
303         uint32_t i2;
304      };
305   } di;
306
307   di.d = v;
308
309   /* Write the low 32-bit of the constant to the X:UD channel and the
310    * high 32-bit to the Y:UD channel to build the constant in a VGRF.
311    * We have to do this twice (offset 0 and offset 1), since a DF VGRF takes
312    * two SIMD8 registers in SIMD4x2 execution. Finally, return a swizzle
313    * XXXX so any access to the VGRF only reads the constant data in these
314    * channels.
315    */
316   const dst_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
317   for (unsigned n = 0; n < 2; n++) {
318      const vec4_builder ubld = bld.exec_all().group(4, n);
319      ubld.MOV(writemask(offset(tmp, 8, n), WRITEMASK_X), brw_imm_ud(di.i1));
320      ubld.MOV(writemask(offset(tmp, 8, n), WRITEMASK_Y), brw_imm_ud(di.i2));
321   }
322
323   return swizzle(src_reg(retype(tmp, BRW_REGISTER_TYPE_DF)), BRW_SWIZZLE_XXXX);
324}
325
326void
327vec4_visitor::nir_emit_load_const(nir_load_const_instr *instr)
328{
329   dst_reg reg;
330
331   if (instr->def.bit_size == 64) {
332      reg = dst_reg(VGRF, alloc.allocate(2));
333      reg.type = BRW_REGISTER_TYPE_DF;
334   } else {
335      reg = dst_reg(VGRF, alloc.allocate(1));
336      reg.type = BRW_REGISTER_TYPE_D;
337   }
338
339   const vec4_builder ibld = vec4_builder(this).at_end();
340   unsigned remaining = brw_writemask_for_size(instr->def.num_components);
341
342   /* @FIXME: consider emitting vector operations to save some MOVs in
343    * cases where the components are representable in 8 bits.
344    * For now, we emit a MOV for each distinct value.
345    */
346   for (unsigned i = 0; i < instr->def.num_components; i++) {
347      unsigned writemask = 1 << i;
348
349      if ((remaining & writemask) == 0)
350         continue;
351
352      for (unsigned j = i; j < instr->def.num_components; j++) {
353         if ((instr->def.bit_size == 32 &&
354              instr->value[i].u32 == instr->value[j].u32) ||
355             (instr->def.bit_size == 64 &&
356              instr->value[i].f64 == instr->value[j].f64)) {
357            writemask |= 1 << j;
358         }
359      }
360
361      reg.writemask = writemask;
362      if (instr->def.bit_size == 64) {
363         emit(MOV(reg, setup_imm_df(ibld, instr->value[i].f64)));
364      } else {
365         emit(MOV(reg, brw_imm_d(instr->value[i].i32)));
366      }
367
368      remaining &= ~writemask;
369   }
370
371   /* Set final writemask */
372   reg.writemask = brw_writemask_for_size(instr->def.num_components);
373
374   nir_ssa_values[instr->def.index] = reg;
375}
376
377src_reg
378vec4_visitor::get_nir_ssbo_intrinsic_index(nir_intrinsic_instr *instr)
379{
380   /* SSBO stores are weird in that their index is in src[1] */
381   const unsigned src = instr->intrinsic == nir_intrinsic_store_ssbo ? 1 : 0;
382
383   src_reg surf_index;
384   if (nir_src_is_const(instr->src[src])) {
385      unsigned index = prog_data->base.binding_table.ssbo_start +
386                       nir_src_as_uint(instr->src[src]);
387      surf_index = brw_imm_ud(index);
388   } else {
389      surf_index = src_reg(this, glsl_type::uint_type);
390      emit(ADD(dst_reg(surf_index), get_nir_src(instr->src[src], 1),
391               brw_imm_ud(prog_data->base.binding_table.ssbo_start)));
392      surf_index = emit_uniformize(surf_index);
393   }
394
395   return surf_index;
396}
397
398void
399vec4_visitor::nir_emit_intrinsic(nir_intrinsic_instr *instr)
400{
401   dst_reg dest;
402   src_reg src;
403
404   switch (instr->intrinsic) {
405
406   case nir_intrinsic_load_input: {
407      assert(nir_dest_bit_size(instr->dest) == 32);
408      /* We set EmitNoIndirectInput for VS */
409      unsigned load_offset = nir_src_as_uint(instr->src[0]);
410
411      dest = get_nir_dest(instr->dest);
412      dest.writemask = brw_writemask_for_size(instr->num_components);
413
414      src = src_reg(ATTR, instr->const_index[0] + load_offset,
415                    glsl_type::uvec4_type);
416      src = retype(src, dest.type);
417
418      /* Swizzle source based on component layout qualifier */
419      src.swizzle = BRW_SWZ_COMP_INPUT(nir_intrinsic_component(instr));
420      emit(MOV(dest, src));
421      break;
422   }
423
424   case nir_intrinsic_store_output: {
425      assert(nir_src_bit_size(instr->src[0]) == 32);
426      unsigned store_offset = nir_src_as_uint(instr->src[1]);
427      int varying = instr->const_index[0] + store_offset;
428      src = get_nir_src(instr->src[0], BRW_REGISTER_TYPE_F,
429                        instr->num_components);
430
431      unsigned c = nir_intrinsic_component(instr);
432      output_reg[varying][c] = dst_reg(src);
433      output_num_components[varying][c] = instr->num_components;
434      break;
435   }
436
437   case nir_intrinsic_get_ssbo_size: {
438      assert(nir_src_num_components(instr->src[0]) == 1);
439      unsigned ssbo_index = nir_src_is_const(instr->src[0]) ?
440                            nir_src_as_uint(instr->src[0]) : 0;
441
442      const unsigned index =
443         prog_data->base.binding_table.ssbo_start + ssbo_index;
444      dst_reg result_dst = get_nir_dest(instr->dest);
445      vec4_instruction *inst = new(mem_ctx)
446         vec4_instruction(SHADER_OPCODE_GET_BUFFER_SIZE, result_dst);
447
448      inst->base_mrf = 2;
449      inst->mlen = 1; /* always at least one */
450      inst->src[1] = brw_imm_ud(index);
451
452      /* MRF for the first parameter */
453      src_reg lod = brw_imm_d(0);
454      int param_base = inst->base_mrf;
455      int writemask = WRITEMASK_X;
456      emit(MOV(dst_reg(MRF, param_base, glsl_type::int_type, writemask), lod));
457
458      emit(inst);
459      break;
460   }
461
462   case nir_intrinsic_store_ssbo: {
463      assert(devinfo->ver == 7);
464
465      /* brw_nir_lower_mem_access_bit_sizes takes care of this */
466      assert(nir_src_bit_size(instr->src[0]) == 32);
467      assert(nir_intrinsic_write_mask(instr) ==
468             (1u << instr->num_components) - 1);
469
470      src_reg surf_index = get_nir_ssbo_intrinsic_index(instr);
471      src_reg offset_reg = retype(get_nir_src_imm(instr->src[2]),
472                                  BRW_REGISTER_TYPE_UD);
473
474      /* Value */
475      src_reg val_reg = get_nir_src(instr->src[0], BRW_REGISTER_TYPE_F, 4);
476
477      /* IvyBridge does not have a native SIMD4x2 untyped write message so untyped
478       * writes will use SIMD8 mode. In order to hide this and keep symmetry across
479       * typed and untyped messages and across hardware platforms, the
480       * current implementation of the untyped messages will transparently convert
481       * the SIMD4x2 payload into an equivalent SIMD8 payload by transposing it
482       * and enabling only channel X on the SEND instruction.
483       *
484       * The above, works well for full vector writes, but not for partial writes
485       * where we want to write some channels and not others, like when we have
486       * code such as v.xyw = vec3(1,2,4). Because the untyped write messages are
487       * quite restrictive with regards to the channel enables we can configure in
488       * the message descriptor (not all combinations are allowed) we cannot simply
489       * implement these scenarios with a single message while keeping the
490       * aforementioned symmetry in the implementation. For now we de decided that
491       * it is better to keep the symmetry to reduce complexity, so in situations
492       * such as the one described we end up emitting two untyped write messages
493       * (one for xy and another for w).
494       *
495       * The code below packs consecutive channels into a single write message,
496       * detects gaps in the vector write and if needed, sends a second message
497       * with the remaining channels. If in the future we decide that we want to
498       * emit a single message at the expense of losing the symmetry in the
499       * implementation we can:
500       *
501       * 1) For IvyBridge: Only use the red channel of the untyped write SIMD8
502       *    message payload. In this mode we can write up to 8 offsets and dwords
503       *    to the red channel only (for the two vec4s in the SIMD4x2 execution)
504       *    and select which of the 8 channels carry data to write by setting the
505       *    appropriate writemask in the dst register of the SEND instruction.
506       *    It would require to write a new generator opcode specifically for
507       *    IvyBridge since we would need to prepare a SIMD8 payload that could
508       *    use any channel, not just X.
509       *
510       * 2) For Haswell+: Simply send a single write message but set the writemask
511       *    on the dst of the SEND instruction to select the channels we want to
512       *    write. It would require to modify the current messages to receive
513       *    and honor the writemask provided.
514       */
515      const vec4_builder bld = vec4_builder(this).at_end()
516                               .annotate(current_annotation, base_ir);
517
518      emit_untyped_write(bld, surf_index, offset_reg, val_reg,
519                         1 /* dims */, instr->num_components /* size */,
520                         BRW_PREDICATE_NONE);
521      break;
522   }
523
524   case nir_intrinsic_load_ssbo: {
525      assert(devinfo->ver == 7);
526
527      /* brw_nir_lower_mem_access_bit_sizes takes care of this */
528      assert(nir_dest_bit_size(instr->dest) == 32);
529
530      src_reg surf_index = get_nir_ssbo_intrinsic_index(instr);
531      src_reg offset_reg = retype(get_nir_src_imm(instr->src[1]),
532                                  BRW_REGISTER_TYPE_UD);
533
534      /* Read the vector */
535      const vec4_builder bld = vec4_builder(this).at_end()
536         .annotate(current_annotation, base_ir);
537
538      src_reg read_result = emit_untyped_read(bld, surf_index, offset_reg,
539                                              1 /* dims */, 4 /* size*/,
540                                              BRW_PREDICATE_NONE);
541      dst_reg dest = get_nir_dest(instr->dest);
542      read_result.type = dest.type;
543      read_result.swizzle = brw_swizzle_for_size(instr->num_components);
544      emit(MOV(dest, read_result));
545      break;
546   }
547
548   case nir_intrinsic_ssbo_atomic_add:
549   case nir_intrinsic_ssbo_atomic_imin:
550   case nir_intrinsic_ssbo_atomic_umin:
551   case nir_intrinsic_ssbo_atomic_imax:
552   case nir_intrinsic_ssbo_atomic_umax:
553   case nir_intrinsic_ssbo_atomic_and:
554   case nir_intrinsic_ssbo_atomic_or:
555   case nir_intrinsic_ssbo_atomic_xor:
556   case nir_intrinsic_ssbo_atomic_exchange:
557   case nir_intrinsic_ssbo_atomic_comp_swap:
558      nir_emit_ssbo_atomic(brw_aop_for_nir_intrinsic(instr), instr);
559      break;
560
561   case nir_intrinsic_load_vertex_id:
562      unreachable("should be lowered by lower_vertex_id()");
563
564   case nir_intrinsic_load_vertex_id_zero_base:
565   case nir_intrinsic_load_base_vertex:
566   case nir_intrinsic_load_instance_id:
567   case nir_intrinsic_load_base_instance:
568   case nir_intrinsic_load_draw_id:
569   case nir_intrinsic_load_invocation_id:
570      unreachable("should be lowered by brw_nir_lower_vs_inputs()");
571
572   case nir_intrinsic_load_uniform: {
573      /* Offsets are in bytes but they should always be multiples of 4 */
574      assert(nir_intrinsic_base(instr) % 4 == 0);
575
576      dest = get_nir_dest(instr->dest);
577
578      src = src_reg(dst_reg(UNIFORM, nir_intrinsic_base(instr) / 16));
579      src.type = dest.type;
580
581      /* Uniforms don't actually have to be vec4 aligned.  In the case that
582       * it isn't, we have to use a swizzle to shift things around.  They
583       * do still have the std140 alignment requirement that vec2's have to
584       * be vec2-aligned and vec3's and vec4's have to be vec4-aligned.
585       *
586       * The swizzle also works in the indirect case as the generator adds
587       * the swizzle to the offset for us.
588       */
589      const int type_size = type_sz(src.type);
590      unsigned shift = (nir_intrinsic_base(instr) % 16) / type_size;
591      assert(shift + instr->num_components <= 4);
592
593      if (nir_src_is_const(instr->src[0])) {
594         const unsigned load_offset = nir_src_as_uint(instr->src[0]);
595         /* Offsets are in bytes but they should always be multiples of 4 */
596         assert(load_offset % 4 == 0);
597
598         src.swizzle = brw_swizzle_for_size(instr->num_components);
599         dest.writemask = brw_writemask_for_size(instr->num_components);
600         unsigned offset = load_offset + shift * type_size;
601         src.offset = ROUND_DOWN_TO(offset, 16);
602         shift = (offset % 16) / type_size;
603         assert(shift + instr->num_components <= 4);
604         src.swizzle += BRW_SWIZZLE4(shift, shift, shift, shift);
605
606         emit(MOV(dest, src));
607      } else {
608         /* Uniform arrays are vec4 aligned, because of std140 alignment
609          * rules.
610          */
611         assert(shift == 0);
612
613         src_reg indirect = get_nir_src(instr->src[0], BRW_REGISTER_TYPE_UD, 1);
614
615         /* MOV_INDIRECT is going to stomp the whole thing anyway */
616         dest.writemask = WRITEMASK_XYZW;
617
618         emit(SHADER_OPCODE_MOV_INDIRECT, dest, src,
619              indirect, brw_imm_ud(instr->const_index[1]));
620      }
621      break;
622   }
623
624   case nir_intrinsic_load_ubo: {
625      src_reg surf_index;
626
627      dest = get_nir_dest(instr->dest);
628
629      if (nir_src_is_const(instr->src[0])) {
630         /* The block index is a constant, so just emit the binding table entry
631          * as an immediate.
632          */
633         const unsigned index = prog_data->base.binding_table.ubo_start +
634                                nir_src_as_uint(instr->src[0]);
635         surf_index = brw_imm_ud(index);
636      } else {
637         /* The block index is not a constant. Evaluate the index expression
638          * per-channel and add the base UBO index; we have to select a value
639          * from any live channel.
640          */
641         surf_index = src_reg(this, glsl_type::uint_type);
642         emit(ADD(dst_reg(surf_index), get_nir_src(instr->src[0], nir_type_int32,
643                                                   instr->num_components),
644                  brw_imm_ud(prog_data->base.binding_table.ubo_start)));
645         surf_index = emit_uniformize(surf_index);
646      }
647
648      src_reg push_reg;
649      src_reg offset_reg;
650      if (nir_src_is_const(instr->src[1])) {
651         unsigned load_offset = nir_src_as_uint(instr->src[1]);
652         unsigned aligned_offset = load_offset & ~15;
653         offset_reg = brw_imm_ud(aligned_offset);
654
655         /* See if we've selected this as a push constant candidate */
656         if (nir_src_is_const(instr->src[0])) {
657            const unsigned ubo_block = nir_src_as_uint(instr->src[0]);
658            const unsigned offset_256b = aligned_offset / 32;
659
660            for (int i = 0; i < 4; i++) {
661               const struct brw_ubo_range *range = &prog_data->base.ubo_ranges[i];
662               if (range->block == ubo_block &&
663                   offset_256b >= range->start &&
664                   offset_256b < range->start + range->length) {
665
666                  push_reg = src_reg(dst_reg(UNIFORM, UBO_START + i));
667                  push_reg.type = dest.type;
668                  push_reg.offset = aligned_offset - 32 * range->start;
669                  break;
670               }
671            }
672         }
673      } else {
674         offset_reg = src_reg(this, glsl_type::uint_type);
675         emit(MOV(dst_reg(offset_reg),
676                  get_nir_src(instr->src[1], nir_type_uint32, 1)));
677      }
678
679      src_reg packed_consts;
680      if (push_reg.file != BAD_FILE) {
681         packed_consts = push_reg;
682      } else if (nir_dest_bit_size(instr->dest) == 32) {
683         packed_consts = src_reg(this, glsl_type::vec4_type);
684         emit_pull_constant_load_reg(dst_reg(packed_consts),
685                                     surf_index,
686                                     offset_reg,
687                                     NULL, NULL /* before_block/inst */);
688         prog_data->base.has_ubo_pull = true;
689      } else {
690         src_reg temp = src_reg(this, glsl_type::dvec4_type);
691         src_reg temp_float = retype(temp, BRW_REGISTER_TYPE_F);
692
693         emit_pull_constant_load_reg(dst_reg(temp_float),
694                                     surf_index, offset_reg, NULL, NULL);
695         if (offset_reg.file == IMM)
696            offset_reg.ud += 16;
697         else
698            emit(ADD(dst_reg(offset_reg), offset_reg, brw_imm_ud(16u)));
699         emit_pull_constant_load_reg(dst_reg(byte_offset(temp_float, REG_SIZE)),
700                                     surf_index, offset_reg, NULL, NULL);
701         prog_data->base.has_ubo_pull = true;
702
703         packed_consts = src_reg(this, glsl_type::dvec4_type);
704         shuffle_64bit_data(dst_reg(packed_consts), temp, false);
705      }
706
707      packed_consts.swizzle = brw_swizzle_for_size(instr->num_components);
708      if (nir_src_is_const(instr->src[1])) {
709         unsigned load_offset = nir_src_as_uint(instr->src[1]);
710         unsigned type_size = type_sz(dest.type);
711         packed_consts.swizzle +=
712            BRW_SWIZZLE4(load_offset % 16 / type_size,
713                         load_offset % 16 / type_size,
714                         load_offset % 16 / type_size,
715                         load_offset % 16 / type_size);
716      }
717
718      emit(MOV(dest, retype(packed_consts, dest.type)));
719
720      break;
721   }
722
723   case nir_intrinsic_scoped_barrier:
724      assert(nir_intrinsic_execution_scope(instr) == NIR_SCOPE_NONE);
725      FALLTHROUGH;
726   case nir_intrinsic_memory_barrier: {
727      const vec4_builder bld =
728         vec4_builder(this).at_end().annotate(current_annotation, base_ir);
729      const dst_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD);
730      vec4_instruction *fence =
731         bld.emit(SHADER_OPCODE_MEMORY_FENCE, tmp, brw_vec8_grf(0, 0));
732      fence->sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
733      break;
734   }
735
736   case nir_intrinsic_shader_clock: {
737      /* We cannot do anything if there is an event, so ignore it for now */
738      const src_reg shader_clock = get_timestamp();
739      const enum brw_reg_type type = brw_type_for_base_type(glsl_type::uvec2_type);
740
741      dest = get_nir_dest(instr->dest, type);
742      emit(MOV(dest, shader_clock));
743      break;
744   }
745
746   default:
747      unreachable("Unknown intrinsic");
748   }
749}
750
751void
752vec4_visitor::nir_emit_ssbo_atomic(int op, nir_intrinsic_instr *instr)
753{
754   dst_reg dest;
755   if (nir_intrinsic_infos[instr->intrinsic].has_dest)
756      dest = get_nir_dest(instr->dest);
757
758   src_reg surface = get_nir_ssbo_intrinsic_index(instr);
759   src_reg offset = get_nir_src(instr->src[1], 1);
760   src_reg data1;
761   if (op != BRW_AOP_INC && op != BRW_AOP_DEC && op != BRW_AOP_PREDEC)
762      data1 = get_nir_src(instr->src[2], 1);
763   src_reg data2;
764   if (op == BRW_AOP_CMPWR)
765      data2 = get_nir_src(instr->src[3], 1);
766
767   /* Emit the actual atomic operation operation */
768   const vec4_builder bld =
769      vec4_builder(this).at_end().annotate(current_annotation, base_ir);
770
771   src_reg atomic_result = emit_untyped_atomic(bld, surface, offset,
772                                               data1, data2,
773                                               1 /* dims */, 1 /* rsize */,
774                                               op,
775                                               BRW_PREDICATE_NONE);
776   dest.type = atomic_result.type;
777   bld.MOV(dest, atomic_result);
778}
779
780static unsigned
781brw_swizzle_for_nir_swizzle(uint8_t swizzle[4])
782{
783   return BRW_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
784}
785
786bool
787vec4_visitor::optimize_predicate(nir_alu_instr *instr,
788                                 enum brw_predicate *predicate)
789{
790   if (!instr->src[0].src.is_ssa ||
791       instr->src[0].src.ssa->parent_instr->type != nir_instr_type_alu)
792      return false;
793
794   nir_alu_instr *cmp_instr =
795      nir_instr_as_alu(instr->src[0].src.ssa->parent_instr);
796
797   switch (cmp_instr->op) {
798   case nir_op_b32any_fnequal2:
799   case nir_op_b32any_inequal2:
800   case nir_op_b32any_fnequal3:
801   case nir_op_b32any_inequal3:
802   case nir_op_b32any_fnequal4:
803   case nir_op_b32any_inequal4:
804      *predicate = BRW_PREDICATE_ALIGN16_ANY4H;
805      break;
806   case nir_op_b32all_fequal2:
807   case nir_op_b32all_iequal2:
808   case nir_op_b32all_fequal3:
809   case nir_op_b32all_iequal3:
810   case nir_op_b32all_fequal4:
811   case nir_op_b32all_iequal4:
812      *predicate = BRW_PREDICATE_ALIGN16_ALL4H;
813      break;
814   default:
815      return false;
816   }
817
818   unsigned size_swizzle =
819      brw_swizzle_for_size(nir_op_infos[cmp_instr->op].input_sizes[0]);
820
821   src_reg op[2];
822   assert(nir_op_infos[cmp_instr->op].num_inputs == 2);
823   for (unsigned i = 0; i < 2; i++) {
824      nir_alu_type type = nir_op_infos[cmp_instr->op].input_types[i];
825      unsigned bit_size = nir_src_bit_size(cmp_instr->src[i].src);
826      type = (nir_alu_type) (((unsigned) type) | bit_size);
827      op[i] = get_nir_src(cmp_instr->src[i].src, type, 4);
828      unsigned base_swizzle =
829         brw_swizzle_for_nir_swizzle(cmp_instr->src[i].swizzle);
830      op[i].swizzle = brw_compose_swizzle(size_swizzle, base_swizzle);
831   }
832
833   emit(CMP(dst_null_d(), op[0], op[1],
834            brw_cmod_for_nir_comparison(cmp_instr->op)));
835
836   return true;
837}
838
839static void
840emit_find_msb_using_lzd(const vec4_builder &bld,
841                        const dst_reg &dst,
842                        const src_reg &src,
843                        bool is_signed)
844{
845   vec4_instruction *inst;
846   src_reg temp = src;
847
848   if (is_signed) {
849      /* LZD of an absolute value source almost always does the right
850       * thing.  There are two problem values:
851       *
852       * * 0x80000000.  Since abs(0x80000000) == 0x80000000, LZD returns
853       *   0.  However, findMSB(int(0x80000000)) == 30.
854       *
855       * * 0xffffffff.  Since abs(0xffffffff) == 1, LZD returns
856       *   31.  Section 8.8 (Integer Functions) of the GLSL 4.50 spec says:
857       *
858       *    For a value of zero or negative one, -1 will be returned.
859       *
860       * * Negative powers of two.  LZD(abs(-(1<<x))) returns x, but
861       *   findMSB(-(1<<x)) should return x-1.
862       *
863       * For all negative number cases, including 0x80000000 and
864       * 0xffffffff, the correct value is obtained from LZD if instead of
865       * negating the (already negative) value the logical-not is used.  A
866       * conditonal logical-not can be achieved in two instructions.
867       */
868      temp = src_reg(bld.vgrf(BRW_REGISTER_TYPE_D));
869
870      bld.ASR(dst_reg(temp), src, brw_imm_d(31));
871      bld.XOR(dst_reg(temp), temp, src);
872   }
873
874   bld.LZD(retype(dst, BRW_REGISTER_TYPE_UD),
875           retype(temp, BRW_REGISTER_TYPE_UD));
876
877   /* LZD counts from the MSB side, while GLSL's findMSB() wants the count
878    * from the LSB side. Subtract the result from 31 to convert the MSB count
879    * into an LSB count.  If no bits are set, LZD will return 32.  31-32 = -1,
880    * which is exactly what findMSB() is supposed to return.
881    */
882   inst = bld.ADD(dst, retype(src_reg(dst), BRW_REGISTER_TYPE_D),
883                  brw_imm_d(31));
884   inst->src[0].negate = true;
885}
886
887void
888vec4_visitor::emit_conversion_from_double(dst_reg dst, src_reg src)
889{
890   enum opcode op;
891   switch (dst.type) {
892   case BRW_REGISTER_TYPE_D:
893      op = VEC4_OPCODE_DOUBLE_TO_D32;
894      break;
895   case BRW_REGISTER_TYPE_UD:
896      op = VEC4_OPCODE_DOUBLE_TO_U32;
897      break;
898   case BRW_REGISTER_TYPE_F:
899      op = VEC4_OPCODE_DOUBLE_TO_F32;
900      break;
901   default:
902      unreachable("Unknown conversion");
903   }
904
905   dst_reg temp = dst_reg(this, glsl_type::dvec4_type);
906   emit(MOV(temp, src));
907   dst_reg temp2 = dst_reg(this, glsl_type::dvec4_type);
908   emit(op, temp2, src_reg(temp));
909
910   emit(VEC4_OPCODE_PICK_LOW_32BIT, retype(temp2, dst.type), src_reg(temp2));
911   emit(MOV(dst, src_reg(retype(temp2, dst.type))));
912}
913
914void
915vec4_visitor::emit_conversion_to_double(dst_reg dst, src_reg src)
916{
917   dst_reg tmp_dst = dst_reg(src_reg(this, glsl_type::dvec4_type));
918   src_reg tmp_src = retype(src_reg(this, glsl_type::vec4_type), src.type);
919   emit(MOV(dst_reg(tmp_src), src));
920   emit(VEC4_OPCODE_TO_DOUBLE, tmp_dst, tmp_src);
921   emit(MOV(dst, src_reg(tmp_dst)));
922}
923
924/**
925 * Try to use an immediate value for a source
926 *
927 * In cases of flow control, constant propagation is sometimes unable to
928 * determine that a register contains a constant value.  To work around this,
929 * try to emit a literal as one of the sources.  If \c try_src0_also is set,
930 * \c op[0] will also be tried for an immediate value.
931 *
932 * If \c op[0] is modified, the operands will be exchanged so that \c op[1]
933 * will always be the immediate value.
934 *
935 * \return The index of the source that was modified, 0 or 1, if successful.
936 * Otherwise, -1.
937 *
938 * \param op - Operands to the instruction
939 * \param try_src0_also - True if \c op[0] should also be a candidate for
940 *                        getting an immediate value.  This should only be set
941 *                        for commutative operations.
942 */
943static int
944try_immediate_source(const nir_alu_instr *instr, src_reg *op,
945                     bool try_src0_also)
946{
947   unsigned idx;
948
949   /* MOV should be the only single-source instruction passed to this
950    * function.  Any other unary instruction with a constant source should
951    * have been constant-folded away!
952    */
953   assert(nir_op_infos[instr->op].num_inputs > 1 ||
954          instr->op == nir_op_mov);
955
956   if (instr->op != nir_op_mov &&
957       nir_src_bit_size(instr->src[1].src) == 32 &&
958       nir_src_is_const(instr->src[1].src)) {
959      idx = 1;
960   } else if (try_src0_also &&
961         nir_src_bit_size(instr->src[0].src) == 32 &&
962         nir_src_is_const(instr->src[0].src)) {
963      idx = 0;
964   } else {
965      return -1;
966   }
967
968   const enum brw_reg_type old_type = op[idx].type;
969
970   switch (old_type) {
971   case BRW_REGISTER_TYPE_D:
972   case BRW_REGISTER_TYPE_UD: {
973      int first_comp = -1;
974      int d = 0;
975
976      for (unsigned i = 0; i < NIR_MAX_VEC_COMPONENTS; i++) {
977         if (nir_alu_instr_channel_used(instr, idx, i)) {
978            if (first_comp < 0) {
979               first_comp = i;
980               d = nir_src_comp_as_int(instr->src[idx].src,
981                                       instr->src[idx].swizzle[i]);
982            } else if (d != nir_src_comp_as_int(instr->src[idx].src,
983                                                instr->src[idx].swizzle[i])) {
984               return -1;
985            }
986         }
987      }
988
989      assert(first_comp >= 0);
990
991      if (op[idx].abs)
992         d = MAX2(-d, d);
993
994      if (op[idx].negate)
995         d = -d;
996
997      op[idx] = retype(src_reg(brw_imm_d(d)), old_type);
998      break;
999   }
1000
1001   case BRW_REGISTER_TYPE_F: {
1002      int first_comp = -1;
1003      float f[NIR_MAX_VEC_COMPONENTS] = { 0.0f };
1004      bool is_scalar = true;
1005
1006      for (unsigned i = 0; i < NIR_MAX_VEC_COMPONENTS; i++) {
1007         if (nir_alu_instr_channel_used(instr, idx, i)) {
1008            f[i] = nir_src_comp_as_float(instr->src[idx].src,
1009                                         instr->src[idx].swizzle[i]);
1010            if (first_comp < 0) {
1011               first_comp = i;
1012            } else if (f[first_comp] != f[i]) {
1013               is_scalar = false;
1014            }
1015         }
1016      }
1017
1018      if (is_scalar) {
1019         if (op[idx].abs)
1020            f[first_comp] = fabs(f[first_comp]);
1021
1022         if (op[idx].negate)
1023            f[first_comp] = -f[first_comp];
1024
1025         op[idx] = src_reg(brw_imm_f(f[first_comp]));
1026         assert(op[idx].type == old_type);
1027      } else {
1028         uint8_t vf_values[4] = { 0, 0, 0, 0 };
1029
1030         for (unsigned i = 0; i < ARRAY_SIZE(vf_values); i++) {
1031
1032            if (op[idx].abs)
1033               f[i] = fabs(f[i]);
1034
1035            if (op[idx].negate)
1036               f[i] = -f[i];
1037
1038            const int vf = brw_float_to_vf(f[i]);
1039            if (vf == -1)
1040               return -1;
1041
1042            vf_values[i] = vf;
1043         }
1044
1045         op[idx] = src_reg(brw_imm_vf4(vf_values[0], vf_values[1],
1046                                       vf_values[2], vf_values[3]));
1047      }
1048      break;
1049   }
1050
1051   default:
1052      unreachable("Non-32bit type.");
1053   }
1054
1055   /* If the instruction has more than one source, the instruction format only
1056    * allows source 1 to be an immediate value.  If the immediate value was
1057    * source 0, then the sources must be exchanged.
1058    */
1059   if (idx == 0 && instr->op != nir_op_mov) {
1060      src_reg tmp = op[0];
1061      op[0] = op[1];
1062      op[1] = tmp;
1063   }
1064
1065   return idx;
1066}
1067
1068void
1069vec4_visitor::fix_float_operands(src_reg op[3], nir_alu_instr *instr)
1070{
1071   bool fixed[3] = { false, false, false };
1072
1073   for (unsigned i = 0; i < 2; i++) {
1074      if (!nir_src_is_const(instr->src[i].src))
1075         continue;
1076
1077      for (unsigned j = i + 1; j < 3; j++) {
1078         if (fixed[j])
1079            continue;
1080
1081         if (!nir_src_is_const(instr->src[j].src))
1082            continue;
1083
1084         if (nir_alu_srcs_equal(instr, instr, i, j)) {
1085            if (!fixed[i])
1086               op[i] = fix_3src_operand(op[i]);
1087
1088            op[j] = op[i];
1089
1090            fixed[i] = true;
1091            fixed[j] = true;
1092         } else if (nir_alu_srcs_negative_equal(instr, instr, i, j)) {
1093            if (!fixed[i])
1094               op[i] = fix_3src_operand(op[i]);
1095
1096            op[j] = op[i];
1097            op[j].negate = !op[j].negate;
1098
1099            fixed[i] = true;
1100            fixed[j] = true;
1101         }
1102      }
1103   }
1104
1105   for (unsigned i = 0; i < 3; i++) {
1106      if (!fixed[i])
1107         op[i] = fix_3src_operand(op[i]);
1108   }
1109}
1110
1111static bool
1112const_src_fits_in_16_bits(const nir_src &src, brw_reg_type type)
1113{
1114   assert(nir_src_is_const(src));
1115   if (brw_reg_type_is_unsigned_integer(type)) {
1116      return nir_src_comp_as_uint(src, 0) <= UINT16_MAX;
1117   } else {
1118      const int64_t c = nir_src_comp_as_int(src, 0);
1119      return c <= INT16_MAX && c >= INT16_MIN;
1120   }
1121}
1122
1123void
1124vec4_visitor::nir_emit_alu(nir_alu_instr *instr)
1125{
1126   vec4_instruction *inst;
1127
1128   nir_alu_type dst_type = (nir_alu_type) (nir_op_infos[instr->op].output_type |
1129                                           nir_dest_bit_size(instr->dest.dest));
1130   dst_reg dst = get_nir_dest(instr->dest.dest, dst_type);
1131   dst.writemask = instr->dest.write_mask;
1132
1133   assert(!instr->dest.saturate);
1134
1135   src_reg op[4];
1136   for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
1137      /* We don't lower to source modifiers, so they shouldn't exist. */
1138      assert(!instr->src[i].abs);
1139      assert(!instr->src[i].negate);
1140
1141      nir_alu_type src_type = (nir_alu_type)
1142         (nir_op_infos[instr->op].input_types[i] |
1143          nir_src_bit_size(instr->src[i].src));
1144      op[i] = get_nir_src(instr->src[i].src, src_type, 4);
1145      op[i].swizzle = brw_swizzle_for_nir_swizzle(instr->src[i].swizzle);
1146   }
1147
1148#ifndef NDEBUG
1149   /* On Gen7 and earlier, no functionality is exposed that should allow 8-bit
1150    * integer types to ever exist.
1151    */
1152   for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
1153      assert(type_sz(op[i].type) > 1);
1154#endif
1155
1156   switch (instr->op) {
1157   case nir_op_mov:
1158      try_immediate_source(instr, &op[0], true);
1159      inst = emit(MOV(dst, op[0]));
1160      break;
1161
1162   case nir_op_vec2:
1163   case nir_op_vec3:
1164   case nir_op_vec4:
1165      unreachable("not reached: should be handled by lower_vec_to_movs()");
1166
1167   case nir_op_i2f32:
1168   case nir_op_u2f32:
1169      inst = emit(MOV(dst, op[0]));
1170      break;
1171
1172   case nir_op_f2f32:
1173   case nir_op_f2i32:
1174   case nir_op_f2u32:
1175      if (nir_src_bit_size(instr->src[0].src) == 64)
1176         emit_conversion_from_double(dst, op[0]);
1177      else
1178         inst = emit(MOV(dst, op[0]));
1179      break;
1180
1181   case nir_op_f2f64:
1182   case nir_op_i2f64:
1183   case nir_op_u2f64:
1184      emit_conversion_to_double(dst, op[0]);
1185      break;
1186
1187   case nir_op_fsat:
1188      inst = emit(MOV(dst, op[0]));
1189      inst->saturate = true;
1190      break;
1191
1192   case nir_op_fneg:
1193   case nir_op_ineg:
1194      op[0].negate = true;
1195      inst = emit(MOV(dst, op[0]));
1196      break;
1197
1198   case nir_op_fabs:
1199   case nir_op_iabs:
1200      op[0].negate = false;
1201      op[0].abs = true;
1202      inst = emit(MOV(dst, op[0]));
1203      break;
1204
1205   case nir_op_iadd:
1206      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1207      FALLTHROUGH;
1208   case nir_op_fadd:
1209      try_immediate_source(instr, op, true);
1210      inst = emit(ADD(dst, op[0], op[1]));
1211      break;
1212
1213   case nir_op_uadd_sat:
1214      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1215      inst = emit(ADD(dst, op[0], op[1]));
1216      inst->saturate = true;
1217      break;
1218
1219   case nir_op_fmul:
1220      try_immediate_source(instr, op, true);
1221      inst = emit(MUL(dst, op[0], op[1]));
1222      break;
1223
1224   case nir_op_imul: {
1225      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1226
1227      /* For integer multiplication, the MUL uses the low 16 bits of one of
1228       * the operands (src0 through SNB, src1 on IVB and later). The MACH
1229       * accumulates in the contribution of the upper 16 bits of that
1230       * operand. If we can determine that one of the args is in the low
1231       * 16 bits, though, we can just emit a single MUL.
1232       */
1233      if (nir_src_is_const(instr->src[0].src) &&
1234          nir_alu_instr_src_read_mask(instr, 0) == 1 &&
1235          const_src_fits_in_16_bits(instr->src[0].src, op[0].type)) {
1236         if (devinfo->ver < 7)
1237            emit(MUL(dst, op[0], op[1]));
1238         else
1239            emit(MUL(dst, op[1], op[0]));
1240      } else if (nir_src_is_const(instr->src[1].src) &&
1241                 nir_alu_instr_src_read_mask(instr, 1) == 1 &&
1242                 const_src_fits_in_16_bits(instr->src[1].src, op[1].type)) {
1243         if (devinfo->ver < 7)
1244            emit(MUL(dst, op[1], op[0]));
1245         else
1246            emit(MUL(dst, op[0], op[1]));
1247      } else {
1248         struct brw_reg acc = retype(brw_acc_reg(8), dst.type);
1249
1250         emit(MUL(acc, op[0], op[1]));
1251         emit(MACH(dst_null_d(), op[0], op[1]));
1252         emit(MOV(dst, src_reg(acc)));
1253      }
1254      break;
1255   }
1256
1257   case nir_op_imul_high:
1258   case nir_op_umul_high: {
1259      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1260      struct brw_reg acc = retype(brw_acc_reg(8), dst.type);
1261
1262      emit(MUL(acc, op[0], op[1]));
1263      emit(MACH(dst, op[0], op[1]));
1264      break;
1265   }
1266
1267   case nir_op_frcp:
1268      inst = emit_math(SHADER_OPCODE_RCP, dst, op[0]);
1269      break;
1270
1271   case nir_op_fexp2:
1272      inst = emit_math(SHADER_OPCODE_EXP2, dst, op[0]);
1273      break;
1274
1275   case nir_op_flog2:
1276      inst = emit_math(SHADER_OPCODE_LOG2, dst, op[0]);
1277      break;
1278
1279   case nir_op_fsin:
1280      inst = emit_math(SHADER_OPCODE_SIN, dst, op[0]);
1281      break;
1282
1283   case nir_op_fcos:
1284      inst = emit_math(SHADER_OPCODE_COS, dst, op[0]);
1285      break;
1286
1287   case nir_op_idiv:
1288   case nir_op_udiv:
1289      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1290      emit_math(SHADER_OPCODE_INT_QUOTIENT, dst, op[0], op[1]);
1291      break;
1292
1293   case nir_op_umod:
1294   case nir_op_irem:
1295      /* According to the sign table for INT DIV in the Ivy Bridge PRM, it
1296       * appears that our hardware just does the right thing for signed
1297       * remainder.
1298       */
1299      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1300      emit_math(SHADER_OPCODE_INT_REMAINDER, dst, op[0], op[1]);
1301      break;
1302
1303   case nir_op_imod: {
1304      /* Get a regular C-style remainder.  If a % b == 0, set the predicate. */
1305      inst = emit_math(SHADER_OPCODE_INT_REMAINDER, dst, op[0], op[1]);
1306
1307      /* Math instructions don't support conditional mod */
1308      inst = emit(MOV(dst_null_d(), src_reg(dst)));
1309      inst->conditional_mod = BRW_CONDITIONAL_NZ;
1310
1311      /* Now, we need to determine if signs of the sources are different.
1312       * When we XOR the sources, the top bit is 0 if they are the same and 1
1313       * if they are different.  We can then use a conditional modifier to
1314       * turn that into a predicate.  This leads us to an XOR.l instruction.
1315       *
1316       * Technically, according to the PRM, you're not allowed to use .l on a
1317       * XOR instruction.  However, emperical experiments and Curro's reading
1318       * of the simulator source both indicate that it's safe.
1319       */
1320      src_reg tmp = src_reg(this, glsl_type::ivec4_type);
1321      inst = emit(XOR(dst_reg(tmp), op[0], op[1]));
1322      inst->predicate = BRW_PREDICATE_NORMAL;
1323      inst->conditional_mod = BRW_CONDITIONAL_L;
1324
1325      /* If the result of the initial remainder operation is non-zero and the
1326       * two sources have different signs, add in a copy of op[1] to get the
1327       * final integer modulus value.
1328       */
1329      inst = emit(ADD(dst, src_reg(dst), op[1]));
1330      inst->predicate = BRW_PREDICATE_NORMAL;
1331      break;
1332   }
1333
1334   case nir_op_ldexp:
1335      unreachable("not reached: should be handled by ldexp_to_arith()");
1336
1337   case nir_op_fsqrt:
1338      inst = emit_math(SHADER_OPCODE_SQRT, dst, op[0]);
1339      break;
1340
1341   case nir_op_frsq:
1342      inst = emit_math(SHADER_OPCODE_RSQ, dst, op[0]);
1343      break;
1344
1345   case nir_op_fpow:
1346      inst = emit_math(SHADER_OPCODE_POW, dst, op[0], op[1]);
1347      break;
1348
1349   case nir_op_uadd_carry: {
1350      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1351      struct brw_reg acc = retype(brw_acc_reg(8), BRW_REGISTER_TYPE_UD);
1352
1353      emit(ADDC(dst_null_ud(), op[0], op[1]));
1354      emit(MOV(dst, src_reg(acc)));
1355      break;
1356   }
1357
1358   case nir_op_usub_borrow: {
1359      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1360      struct brw_reg acc = retype(brw_acc_reg(8), BRW_REGISTER_TYPE_UD);
1361
1362      emit(SUBB(dst_null_ud(), op[0], op[1]));
1363      emit(MOV(dst, src_reg(acc)));
1364      break;
1365   }
1366
1367   case nir_op_ftrunc:
1368      inst = emit(RNDZ(dst, op[0]));
1369      if (devinfo->ver < 6) {
1370         inst->conditional_mod = BRW_CONDITIONAL_R;
1371         inst = emit(ADD(dst, src_reg(dst), brw_imm_f(1.0f)));
1372         inst->predicate = BRW_PREDICATE_NORMAL;
1373         inst = emit(MOV(dst, src_reg(dst))); /* for potential saturation */
1374      }
1375      break;
1376
1377   case nir_op_fceil: {
1378      src_reg tmp = src_reg(this, glsl_type::float_type);
1379      tmp.swizzle =
1380         brw_swizzle_for_size(instr->src[0].src.is_ssa ?
1381                              instr->src[0].src.ssa->num_components :
1382                              instr->src[0].src.reg.reg->num_components);
1383
1384      op[0].negate = !op[0].negate;
1385      emit(RNDD(dst_reg(tmp), op[0]));
1386      tmp.negate = true;
1387      inst = emit(MOV(dst, tmp));
1388      break;
1389   }
1390
1391   case nir_op_ffloor:
1392      inst = emit(RNDD(dst, op[0]));
1393      break;
1394
1395   case nir_op_ffract:
1396      inst = emit(FRC(dst, op[0]));
1397      break;
1398
1399   case nir_op_fround_even:
1400      inst = emit(RNDE(dst, op[0]));
1401      if (devinfo->ver < 6) {
1402         inst->conditional_mod = BRW_CONDITIONAL_R;
1403         inst = emit(ADD(dst, src_reg(dst), brw_imm_f(1.0f)));
1404         inst->predicate = BRW_PREDICATE_NORMAL;
1405         inst = emit(MOV(dst, src_reg(dst))); /* for potential saturation */
1406      }
1407      break;
1408
1409   case nir_op_fquantize2f16: {
1410      /* See also vec4_visitor::emit_pack_half_2x16() */
1411      src_reg tmp16 = src_reg(this, glsl_type::uvec4_type);
1412      src_reg tmp32 = src_reg(this, glsl_type::vec4_type);
1413      src_reg zero = src_reg(this, glsl_type::vec4_type);
1414
1415      /* Check for denormal */
1416      src_reg abs_src0 = op[0];
1417      abs_src0.abs = true;
1418      emit(CMP(dst_null_f(), abs_src0, brw_imm_f(ldexpf(1.0, -14)),
1419               BRW_CONDITIONAL_L));
1420      /* Get the appropriately signed zero */
1421      emit(AND(retype(dst_reg(zero), BRW_REGISTER_TYPE_UD),
1422               retype(op[0], BRW_REGISTER_TYPE_UD),
1423               brw_imm_ud(0x80000000)));
1424      /* Do the actual F32 -> F16 -> F32 conversion */
1425      emit(F32TO16(dst_reg(tmp16), op[0]));
1426      emit(F16TO32(dst_reg(tmp32), tmp16));
1427      /* Select that or zero based on normal status */
1428      inst = emit(BRW_OPCODE_SEL, dst, zero, tmp32);
1429      inst->predicate = BRW_PREDICATE_NORMAL;
1430      break;
1431   }
1432
1433   case nir_op_imin:
1434   case nir_op_umin:
1435      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1436      FALLTHROUGH;
1437   case nir_op_fmin:
1438      try_immediate_source(instr, op, true);
1439      inst = emit_minmax(BRW_CONDITIONAL_L, dst, op[0], op[1]);
1440      break;
1441
1442   case nir_op_imax:
1443   case nir_op_umax:
1444      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1445      FALLTHROUGH;
1446   case nir_op_fmax:
1447      try_immediate_source(instr, op, true);
1448      inst = emit_minmax(BRW_CONDITIONAL_GE, dst, op[0], op[1]);
1449      break;
1450
1451   case nir_op_fddx:
1452   case nir_op_fddx_coarse:
1453   case nir_op_fddx_fine:
1454   case nir_op_fddy:
1455   case nir_op_fddy_coarse:
1456   case nir_op_fddy_fine:
1457      unreachable("derivatives are not valid in vertex shaders");
1458
1459   case nir_op_ilt32:
1460   case nir_op_ult32:
1461   case nir_op_ige32:
1462   case nir_op_uge32:
1463   case nir_op_ieq32:
1464   case nir_op_ine32:
1465      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1466      FALLTHROUGH;
1467   case nir_op_flt32:
1468   case nir_op_fge32:
1469   case nir_op_feq32:
1470   case nir_op_fneu32: {
1471      enum brw_conditional_mod conditional_mod =
1472         brw_cmod_for_nir_comparison(instr->op);
1473
1474      if (nir_src_bit_size(instr->src[0].src) < 64) {
1475         /* If the order of the sources is changed due to an immediate value,
1476          * then the condition must also be changed.
1477          */
1478         if (try_immediate_source(instr, op, true) == 0)
1479            conditional_mod = brw_swap_cmod(conditional_mod);
1480
1481         emit(CMP(dst, op[0], op[1], conditional_mod));
1482      } else {
1483         /* Produce a 32-bit boolean result from the DF comparison by selecting
1484          * only the low 32-bit in each DF produced. Do this in a temporary
1485          * so we can then move from there to the result using align16 again
1486          * to honor the original writemask.
1487          */
1488         dst_reg temp = dst_reg(this, glsl_type::dvec4_type);
1489         emit(CMP(temp, op[0], op[1], conditional_mod));
1490         dst_reg result = dst_reg(this, glsl_type::bvec4_type);
1491         emit(VEC4_OPCODE_PICK_LOW_32BIT, result, src_reg(temp));
1492         emit(MOV(dst, src_reg(result)));
1493      }
1494      break;
1495   }
1496
1497   case nir_op_b32all_iequal2:
1498   case nir_op_b32all_iequal3:
1499   case nir_op_b32all_iequal4:
1500      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1501      FALLTHROUGH;
1502   case nir_op_b32all_fequal2:
1503   case nir_op_b32all_fequal3:
1504   case nir_op_b32all_fequal4: {
1505      unsigned swiz =
1506         brw_swizzle_for_size(nir_op_infos[instr->op].input_sizes[0]);
1507
1508      emit(CMP(dst_null_d(), swizzle(op[0], swiz), swizzle(op[1], swiz),
1509               brw_cmod_for_nir_comparison(instr->op)));
1510      emit(MOV(dst, brw_imm_d(0)));
1511      inst = emit(MOV(dst, brw_imm_d(~0)));
1512      inst->predicate = BRW_PREDICATE_ALIGN16_ALL4H;
1513      break;
1514   }
1515
1516   case nir_op_b32any_inequal2:
1517   case nir_op_b32any_inequal3:
1518   case nir_op_b32any_inequal4:
1519      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1520      FALLTHROUGH;
1521   case nir_op_b32any_fnequal2:
1522   case nir_op_b32any_fnequal3:
1523   case nir_op_b32any_fnequal4: {
1524      unsigned swiz =
1525         brw_swizzle_for_size(nir_op_infos[instr->op].input_sizes[0]);
1526
1527      emit(CMP(dst_null_d(), swizzle(op[0], swiz), swizzle(op[1], swiz),
1528               brw_cmod_for_nir_comparison(instr->op)));
1529
1530      emit(MOV(dst, brw_imm_d(0)));
1531      inst = emit(MOV(dst, brw_imm_d(~0)));
1532      inst->predicate = BRW_PREDICATE_ALIGN16_ANY4H;
1533      break;
1534   }
1535
1536   case nir_op_inot:
1537      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1538      emit(NOT(dst, op[0]));
1539      break;
1540
1541   case nir_op_ixor:
1542      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1543      try_immediate_source(instr, op, true);
1544      emit(XOR(dst, op[0], op[1]));
1545      break;
1546
1547   case nir_op_ior:
1548      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1549      try_immediate_source(instr, op, true);
1550      emit(OR(dst, op[0], op[1]));
1551      break;
1552
1553   case nir_op_iand:
1554      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1555      try_immediate_source(instr, op, true);
1556      emit(AND(dst, op[0], op[1]));
1557      break;
1558
1559   case nir_op_b2i32:
1560   case nir_op_b2f32:
1561   case nir_op_b2f64:
1562      if (nir_dest_bit_size(instr->dest.dest) > 32) {
1563         assert(dst.type == BRW_REGISTER_TYPE_DF);
1564         emit_conversion_to_double(dst, negate(op[0]));
1565      } else {
1566         emit(MOV(dst, negate(op[0])));
1567      }
1568      break;
1569
1570   case nir_op_f2b32:
1571      if (nir_src_bit_size(instr->src[0].src) == 64) {
1572         /* We use a MOV with conditional_mod to check if the provided value is
1573          * 0.0. We want this to flush denormalized numbers to zero, so we set a
1574          * source modifier on the source operand to trigger this, as source
1575          * modifiers don't affect the result of the testing against 0.0.
1576          */
1577         src_reg value = op[0];
1578         value.abs = true;
1579         vec4_instruction *inst = emit(MOV(dst_null_df(), value));
1580         inst->conditional_mod = BRW_CONDITIONAL_NZ;
1581
1582         src_reg one = src_reg(this, glsl_type::ivec4_type);
1583         emit(MOV(dst_reg(one), brw_imm_d(~0)));
1584         inst = emit(BRW_OPCODE_SEL, dst, one, brw_imm_d(0));
1585         inst->predicate = BRW_PREDICATE_NORMAL;
1586      } else {
1587         emit(CMP(dst, op[0], brw_imm_f(0.0f), BRW_CONDITIONAL_NZ));
1588      }
1589      break;
1590
1591   case nir_op_i2b32:
1592      emit(CMP(dst, op[0], brw_imm_d(0), BRW_CONDITIONAL_NZ));
1593      break;
1594
1595   case nir_op_unpack_half_2x16_split_x:
1596   case nir_op_unpack_half_2x16_split_y:
1597   case nir_op_pack_half_2x16_split:
1598      unreachable("not reached: should not occur in vertex shader");
1599
1600   case nir_op_unpack_snorm_2x16:
1601   case nir_op_unpack_unorm_2x16:
1602   case nir_op_pack_snorm_2x16:
1603   case nir_op_pack_unorm_2x16:
1604      unreachable("not reached: should be handled by lower_packing_builtins");
1605
1606   case nir_op_pack_uvec4_to_uint:
1607      unreachable("not reached");
1608
1609   case nir_op_pack_uvec2_to_uint: {
1610      dst_reg tmp1 = dst_reg(this, glsl_type::uint_type);
1611      tmp1.writemask = WRITEMASK_X;
1612      op[0].swizzle = BRW_SWIZZLE_YYYY;
1613      emit(SHL(tmp1, op[0], src_reg(brw_imm_ud(16u))));
1614
1615      dst_reg tmp2 = dst_reg(this, glsl_type::uint_type);
1616      tmp2.writemask = WRITEMASK_X;
1617      op[0].swizzle = BRW_SWIZZLE_XXXX;
1618      emit(AND(tmp2, op[0], src_reg(brw_imm_ud(0xffffu))));
1619
1620      emit(OR(dst, src_reg(tmp1), src_reg(tmp2)));
1621      break;
1622   }
1623
1624   case nir_op_pack_64_2x32_split: {
1625      dst_reg result = dst_reg(this, glsl_type::dvec4_type);
1626      dst_reg tmp = dst_reg(this, glsl_type::uvec4_type);
1627      emit(MOV(tmp, retype(op[0], BRW_REGISTER_TYPE_UD)));
1628      emit(VEC4_OPCODE_SET_LOW_32BIT, result, src_reg(tmp));
1629      emit(MOV(tmp, retype(op[1], BRW_REGISTER_TYPE_UD)));
1630      emit(VEC4_OPCODE_SET_HIGH_32BIT, result, src_reg(tmp));
1631      emit(MOV(dst, src_reg(result)));
1632      break;
1633   }
1634
1635   case nir_op_unpack_64_2x32_split_x:
1636   case nir_op_unpack_64_2x32_split_y: {
1637      enum opcode oper = (instr->op == nir_op_unpack_64_2x32_split_x) ?
1638         VEC4_OPCODE_PICK_LOW_32BIT : VEC4_OPCODE_PICK_HIGH_32BIT;
1639      dst_reg tmp = dst_reg(this, glsl_type::dvec4_type);
1640      emit(MOV(tmp, op[0]));
1641      dst_reg tmp2 = dst_reg(this, glsl_type::uvec4_type);
1642      emit(oper, tmp2, src_reg(tmp));
1643      emit(MOV(dst, src_reg(tmp2)));
1644      break;
1645   }
1646
1647   case nir_op_unpack_half_2x16:
1648      /* As NIR does not guarantee that we have a correct swizzle outside the
1649       * boundaries of a vector, and the implementation of emit_unpack_half_2x16
1650       * uses the source operand in an operation with WRITEMASK_Y while our
1651       * source operand has only size 1, it accessed incorrect data producing
1652       * regressions in Piglit. We repeat the swizzle of the first component on the
1653       * rest of components to avoid regressions. In the vec4_visitor IR code path
1654       * this is not needed because the operand has already the correct swizzle.
1655       */
1656      op[0].swizzle = brw_compose_swizzle(BRW_SWIZZLE_XXXX, op[0].swizzle);
1657      emit_unpack_half_2x16(dst, op[0]);
1658      break;
1659
1660   case nir_op_pack_half_2x16:
1661      emit_pack_half_2x16(dst, op[0]);
1662      break;
1663
1664   case nir_op_unpack_unorm_4x8:
1665      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1666      emit_unpack_unorm_4x8(dst, op[0]);
1667      break;
1668
1669   case nir_op_pack_unorm_4x8:
1670      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1671      emit_pack_unorm_4x8(dst, op[0]);
1672      break;
1673
1674   case nir_op_unpack_snorm_4x8:
1675      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1676      emit_unpack_snorm_4x8(dst, op[0]);
1677      break;
1678
1679   case nir_op_pack_snorm_4x8:
1680      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1681      emit_pack_snorm_4x8(dst, op[0]);
1682      break;
1683
1684   case nir_op_bitfield_reverse:
1685      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1686      emit(BFREV(dst, op[0]));
1687      break;
1688
1689   case nir_op_bit_count:
1690      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1691      emit(CBIT(dst, op[0]));
1692      break;
1693
1694   case nir_op_ufind_msb:
1695      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1696      emit_find_msb_using_lzd(vec4_builder(this).at_end(), dst, op[0], false);
1697      break;
1698
1699   case nir_op_ifind_msb: {
1700      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1701      vec4_builder bld = vec4_builder(this).at_end();
1702      src_reg src(dst);
1703
1704      if (devinfo->ver < 7) {
1705         emit_find_msb_using_lzd(bld, dst, op[0], true);
1706      } else {
1707         emit(FBH(retype(dst, BRW_REGISTER_TYPE_UD), op[0]));
1708
1709         /* FBH counts from the MSB side, while GLSL's findMSB() wants the
1710          * count from the LSB side. If FBH didn't return an error
1711          * (0xFFFFFFFF), then subtract the result from 31 to convert the MSB
1712          * count into an LSB count.
1713          */
1714         bld.CMP(dst_null_d(), src, brw_imm_d(-1), BRW_CONDITIONAL_NZ);
1715
1716         inst = bld.ADD(dst, src, brw_imm_d(31));
1717         inst->predicate = BRW_PREDICATE_NORMAL;
1718         inst->src[0].negate = true;
1719      }
1720      break;
1721   }
1722
1723   case nir_op_find_lsb: {
1724      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1725      vec4_builder bld = vec4_builder(this).at_end();
1726
1727      if (devinfo->ver < 7) {
1728         dst_reg temp = bld.vgrf(BRW_REGISTER_TYPE_D);
1729
1730         /* (x & -x) generates a value that consists of only the LSB of x.
1731          * For all powers of 2, findMSB(y) == findLSB(y).
1732          */
1733         src_reg src = src_reg(retype(op[0], BRW_REGISTER_TYPE_D));
1734         src_reg negated_src = src;
1735
1736         /* One must be negated, and the other must be non-negated.  It
1737          * doesn't matter which is which.
1738          */
1739         negated_src.negate = true;
1740         src.negate = false;
1741
1742         bld.AND(temp, src, negated_src);
1743         emit_find_msb_using_lzd(bld, dst, src_reg(temp), false);
1744      } else {
1745         bld.FBL(dst, op[0]);
1746      }
1747      break;
1748   }
1749
1750   case nir_op_ubitfield_extract:
1751   case nir_op_ibitfield_extract:
1752      unreachable("should have been lowered");
1753   case nir_op_ubfe:
1754   case nir_op_ibfe:
1755      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1756      op[0] = fix_3src_operand(op[0]);
1757      op[1] = fix_3src_operand(op[1]);
1758      op[2] = fix_3src_operand(op[2]);
1759
1760      emit(BFE(dst, op[2], op[1], op[0]));
1761      break;
1762
1763   case nir_op_bfm:
1764      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1765      emit(BFI1(dst, op[0], op[1]));
1766      break;
1767
1768   case nir_op_bfi:
1769      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1770      op[0] = fix_3src_operand(op[0]);
1771      op[1] = fix_3src_operand(op[1]);
1772      op[2] = fix_3src_operand(op[2]);
1773
1774      emit(BFI2(dst, op[0], op[1], op[2]));
1775      break;
1776
1777   case nir_op_bitfield_insert:
1778      unreachable("not reached: should have been lowered");
1779
1780   case nir_op_fsign:
1781       if (type_sz(op[0].type) < 8) {
1782         /* AND(val, 0x80000000) gives the sign bit.
1783          *
1784          * Predicated OR ORs 1.0 (0x3f800000) with the sign bit if val is not
1785          * zero.
1786          */
1787         emit(CMP(dst_null_f(), op[0], brw_imm_f(0.0f), BRW_CONDITIONAL_NZ));
1788
1789         op[0].type = BRW_REGISTER_TYPE_UD;
1790         dst.type = BRW_REGISTER_TYPE_UD;
1791         emit(AND(dst, op[0], brw_imm_ud(0x80000000u)));
1792
1793         inst = emit(OR(dst, src_reg(dst), brw_imm_ud(0x3f800000u)));
1794         inst->predicate = BRW_PREDICATE_NORMAL;
1795         dst.type = BRW_REGISTER_TYPE_F;
1796      } else {
1797         /* For doubles we do the same but we need to consider:
1798          *
1799          * - We use a MOV with conditional_mod instead of a CMP so that we can
1800          *   skip loading a 0.0 immediate. We use a source modifier on the
1801          *   source of the MOV so that we flush denormalized values to 0.
1802          *   Since we want to compare against 0, this won't alter the result.
1803          * - We need to extract the high 32-bit of each DF where the sign
1804          *   is stored.
1805          * - We need to produce a DF result.
1806          */
1807
1808         /* Check for zero */
1809         src_reg value = op[0];
1810         value.abs = true;
1811         inst = emit(MOV(dst_null_df(), value));
1812         inst->conditional_mod = BRW_CONDITIONAL_NZ;
1813
1814         /* AND each high 32-bit channel with 0x80000000u */
1815         dst_reg tmp = dst_reg(this, glsl_type::uvec4_type);
1816         emit(VEC4_OPCODE_PICK_HIGH_32BIT, tmp, op[0]);
1817         emit(AND(tmp, src_reg(tmp), brw_imm_ud(0x80000000u)));
1818
1819         /* Add 1.0 to each channel, predicated to skip the cases where the
1820          * channel's value was 0
1821          */
1822         inst = emit(OR(tmp, src_reg(tmp), brw_imm_ud(0x3f800000u)));
1823         inst->predicate = BRW_PREDICATE_NORMAL;
1824
1825         /* Now convert the result from float to double */
1826         emit_conversion_to_double(dst, retype(src_reg(tmp),
1827                                               BRW_REGISTER_TYPE_F));
1828      }
1829      break;
1830
1831   case nir_op_ishl:
1832      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1833      try_immediate_source(instr, op, false);
1834      emit(SHL(dst, op[0], op[1]));
1835      break;
1836
1837   case nir_op_ishr:
1838      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1839      try_immediate_source(instr, op, false);
1840      emit(ASR(dst, op[0], op[1]));
1841      break;
1842
1843   case nir_op_ushr:
1844      assert(nir_dest_bit_size(instr->dest.dest) < 64);
1845      try_immediate_source(instr, op, false);
1846      emit(SHR(dst, op[0], op[1]));
1847      break;
1848
1849   case nir_op_ffma:
1850      if (type_sz(dst.type) == 8) {
1851         dst_reg mul_dst = dst_reg(this, glsl_type::dvec4_type);
1852         emit(MUL(mul_dst, op[1], op[0]));
1853         inst = emit(ADD(dst, src_reg(mul_dst), op[2]));
1854      } else {
1855         fix_float_operands(op, instr);
1856         inst = emit(MAD(dst, op[2], op[1], op[0]));
1857      }
1858      break;
1859
1860   case nir_op_flrp:
1861      fix_float_operands(op, instr);
1862      inst = emit(LRP(dst, op[2], op[1], op[0]));
1863      break;
1864
1865   case nir_op_b32csel:
1866      enum brw_predicate predicate;
1867      if (!optimize_predicate(instr, &predicate)) {
1868         emit(CMP(dst_null_d(), op[0], brw_imm_d(0), BRW_CONDITIONAL_NZ));
1869         switch (dst.writemask) {
1870         case WRITEMASK_X:
1871            predicate = BRW_PREDICATE_ALIGN16_REPLICATE_X;
1872            break;
1873         case WRITEMASK_Y:
1874            predicate = BRW_PREDICATE_ALIGN16_REPLICATE_Y;
1875            break;
1876         case WRITEMASK_Z:
1877            predicate = BRW_PREDICATE_ALIGN16_REPLICATE_Z;
1878            break;
1879         case WRITEMASK_W:
1880            predicate = BRW_PREDICATE_ALIGN16_REPLICATE_W;
1881            break;
1882         default:
1883            predicate = BRW_PREDICATE_NORMAL;
1884            break;
1885         }
1886      }
1887      inst = emit(BRW_OPCODE_SEL, dst, op[1], op[2]);
1888      inst->predicate = predicate;
1889      break;
1890
1891   case nir_op_fdot2_replicated:
1892      try_immediate_source(instr, op, true);
1893      inst = emit(BRW_OPCODE_DP2, dst, op[0], op[1]);
1894      break;
1895
1896   case nir_op_fdot3_replicated:
1897      try_immediate_source(instr, op, true);
1898      inst = emit(BRW_OPCODE_DP3, dst, op[0], op[1]);
1899      break;
1900
1901   case nir_op_fdot4_replicated:
1902      try_immediate_source(instr, op, true);
1903      inst = emit(BRW_OPCODE_DP4, dst, op[0], op[1]);
1904      break;
1905
1906   case nir_op_fdph_replicated:
1907      try_immediate_source(instr, op, false);
1908      inst = emit(BRW_OPCODE_DPH, dst, op[0], op[1]);
1909      break;
1910
1911   case nir_op_fdiv:
1912      unreachable("not reached: should be lowered by DIV_TO_MUL_RCP in the compiler");
1913
1914   case nir_op_fmod:
1915      unreachable("not reached: should be lowered by MOD_TO_FLOOR in the compiler");
1916
1917   case nir_op_fsub:
1918   case nir_op_isub:
1919      unreachable("not reached: should be handled by ir_sub_to_add_neg");
1920
1921   default:
1922      unreachable("Unimplemented ALU operation");
1923   }
1924
1925   /* If we need to do a boolean resolve, replace the result with -(x & 1)
1926    * to sign extend the low bit to 0/~0
1927    */
1928   if (devinfo->ver <= 5 &&
1929       (instr->instr.pass_flags & BRW_NIR_BOOLEAN_MASK) ==
1930       BRW_NIR_BOOLEAN_NEEDS_RESOLVE) {
1931      dst_reg masked = dst_reg(this, glsl_type::int_type);
1932      masked.writemask = dst.writemask;
1933      emit(AND(masked, src_reg(dst), brw_imm_d(1)));
1934      src_reg masked_neg = src_reg(masked);
1935      masked_neg.negate = true;
1936      emit(MOV(retype(dst, BRW_REGISTER_TYPE_D), masked_neg));
1937   }
1938}
1939
1940void
1941vec4_visitor::nir_emit_jump(nir_jump_instr *instr)
1942{
1943   switch (instr->type) {
1944   case nir_jump_break:
1945      emit(BRW_OPCODE_BREAK);
1946      break;
1947
1948   case nir_jump_continue:
1949      emit(BRW_OPCODE_CONTINUE);
1950      break;
1951
1952   case nir_jump_return:
1953      FALLTHROUGH;
1954   default:
1955      unreachable("unknown jump");
1956   }
1957}
1958
1959static enum ir_texture_opcode
1960ir_texture_opcode_for_nir_texop(nir_texop texop)
1961{
1962   enum ir_texture_opcode op;
1963
1964   switch (texop) {
1965   case nir_texop_lod: op = ir_lod; break;
1966   case nir_texop_query_levels: op = ir_query_levels; break;
1967   case nir_texop_texture_samples: op = ir_texture_samples; break;
1968   case nir_texop_tex: op = ir_tex; break;
1969   case nir_texop_tg4: op = ir_tg4; break;
1970   case nir_texop_txb: op = ir_txb; break;
1971   case nir_texop_txd: op = ir_txd; break;
1972   case nir_texop_txf: op = ir_txf; break;
1973   case nir_texop_txf_ms: op = ir_txf_ms; break;
1974   case nir_texop_txl: op = ir_txl; break;
1975   case nir_texop_txs: op = ir_txs; break;
1976   case nir_texop_samples_identical: op = ir_samples_identical; break;
1977   default:
1978      unreachable("unknown texture opcode");
1979   }
1980
1981   return op;
1982}
1983
1984void
1985vec4_visitor::nir_emit_texture(nir_tex_instr *instr)
1986{
1987   unsigned texture = instr->texture_index;
1988   unsigned sampler = instr->sampler_index;
1989   src_reg texture_reg = brw_imm_ud(texture);
1990   src_reg sampler_reg = brw_imm_ud(sampler);
1991   src_reg coordinate;
1992   const glsl_type *coord_type = NULL;
1993   src_reg shadow_comparator;
1994   src_reg offset_value;
1995   src_reg lod, lod2;
1996   src_reg sample_index;
1997   src_reg mcs;
1998
1999   dst_reg dest = get_nir_dest(instr->dest, instr->dest_type);
2000
2001   /* The hardware requires a LOD for buffer textures */
2002   if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF)
2003      lod = brw_imm_d(0);
2004
2005   /* Load the texture operation sources */
2006   uint32_t constant_offset = 0;
2007   for (unsigned i = 0; i < instr->num_srcs; i++) {
2008      switch (instr->src[i].src_type) {
2009      case nir_tex_src_comparator:
2010         shadow_comparator = get_nir_src(instr->src[i].src,
2011                                         BRW_REGISTER_TYPE_F, 1);
2012         break;
2013
2014      case nir_tex_src_coord: {
2015         unsigned src_size = nir_tex_instr_src_size(instr, i);
2016
2017         switch (instr->op) {
2018         case nir_texop_txf:
2019         case nir_texop_txf_ms:
2020         case nir_texop_samples_identical:
2021            coordinate = get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_D,
2022                                     src_size);
2023            coord_type = glsl_type::ivec(src_size);
2024            break;
2025
2026         default:
2027            coordinate = get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_F,
2028                                     src_size);
2029            coord_type = glsl_type::vec(src_size);
2030            break;
2031         }
2032         break;
2033      }
2034
2035      case nir_tex_src_ddx:
2036         lod = get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_F,
2037                           nir_tex_instr_src_size(instr, i));
2038         break;
2039
2040      case nir_tex_src_ddy:
2041         lod2 = get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_F,
2042                           nir_tex_instr_src_size(instr, i));
2043         break;
2044
2045      case nir_tex_src_lod:
2046         switch (instr->op) {
2047         case nir_texop_txs:
2048         case nir_texop_txf:
2049            lod = get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_D, 1);
2050            break;
2051
2052         default:
2053            lod = get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_F, 1);
2054            break;
2055         }
2056         break;
2057
2058      case nir_tex_src_ms_index: {
2059         sample_index = get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_D, 1);
2060         break;
2061      }
2062
2063      case nir_tex_src_offset:
2064         if (!brw_texture_offset(instr, i, &constant_offset)) {
2065            offset_value =
2066               get_nir_src(instr->src[i].src, BRW_REGISTER_TYPE_D, 2);
2067         }
2068         break;
2069
2070      case nir_tex_src_texture_offset: {
2071         /* Emit code to evaluate the actual indexing expression */
2072         src_reg src = get_nir_src(instr->src[i].src, 1);
2073         src_reg temp(this, glsl_type::uint_type);
2074         emit(ADD(dst_reg(temp), src, brw_imm_ud(texture)));
2075         texture_reg = emit_uniformize(temp);
2076         break;
2077      }
2078
2079      case nir_tex_src_sampler_offset: {
2080         /* Emit code to evaluate the actual indexing expression */
2081         src_reg src = get_nir_src(instr->src[i].src, 1);
2082         src_reg temp(this, glsl_type::uint_type);
2083         emit(ADD(dst_reg(temp), src, brw_imm_ud(sampler)));
2084         sampler_reg = emit_uniformize(temp);
2085         break;
2086      }
2087
2088      case nir_tex_src_projector:
2089         unreachable("Should be lowered by nir_lower_tex");
2090
2091      case nir_tex_src_bias:
2092         unreachable("LOD bias is not valid for vertex shaders.\n");
2093
2094      default:
2095         unreachable("unknown texture source");
2096      }
2097   }
2098
2099   if (instr->op == nir_texop_txf_ms ||
2100       instr->op == nir_texop_samples_identical) {
2101      assert(coord_type != NULL);
2102      if (devinfo->ver >= 7 &&
2103          key_tex->compressed_multisample_layout_mask & (1 << texture)) {
2104         mcs = emit_mcs_fetch(coord_type, coordinate, texture_reg);
2105      } else {
2106         mcs = brw_imm_ud(0u);
2107      }
2108   }
2109
2110   /* Stuff the channel select bits in the top of the texture offset */
2111   if (instr->op == nir_texop_tg4) {
2112      if (instr->component == 1 &&
2113          (key_tex->gather_channel_quirk_mask & (1 << texture))) {
2114         /* gather4 sampler is broken for green channel on RG32F --
2115          * we must ask for blue instead.
2116          */
2117         constant_offset |= 2 << 16;
2118      } else {
2119         constant_offset |= instr->component << 16;
2120      }
2121   }
2122
2123   ir_texture_opcode op = ir_texture_opcode_for_nir_texop(instr->op);
2124
2125   emit_texture(op, dest, nir_tex_instr_dest_size(instr),
2126                coordinate, instr->coord_components,
2127                shadow_comparator,
2128                lod, lod2, sample_index,
2129                constant_offset, offset_value, mcs,
2130                texture, texture_reg, sampler_reg);
2131}
2132
2133void
2134vec4_visitor::nir_emit_undef(nir_ssa_undef_instr *instr)
2135{
2136   nir_ssa_values[instr->def.index] =
2137      dst_reg(VGRF, alloc.allocate(DIV_ROUND_UP(instr->def.bit_size, 32)));
2138}
2139
2140/* SIMD4x2 64bit data is stored in register space like this:
2141 *
2142 * r0.0:DF  x0 y0 z0 w0
2143 * r1.0:DF  x1 y1 z1 w1
2144 *
2145 * When we need to write data such as this to memory using 32-bit write
2146 * messages we need to shuffle it in this fashion:
2147 *
2148 * r0.0:DF  x0 y0 x1 y1 (to be written at base offset)
2149 * r0.0:DF  z0 w0 z1 w1 (to be written at base offset + 16)
2150 *
2151 * We need to do the inverse operation when we read using 32-bit messages,
2152 * which we can do by applying the same exact shuffling on the 64-bit data
2153 * read, only that because the data for each vertex is positioned differently
2154 * we need to apply different channel enables.
2155 *
2156 * This function takes 64bit data and shuffles it as explained above.
2157 *
2158 * The @for_write parameter is used to specify if the shuffling is being done
2159 * for proper SIMD4x2 64-bit data that needs to be shuffled prior to a 32-bit
2160 * write message (for_write = true), or instead we are doing the inverse
2161 * operation and we have just read 64-bit data using a 32-bit messages that we
2162 * need to shuffle to create valid SIMD4x2 64-bit data (for_write = false).
2163 *
2164 * If @block and @ref are non-NULL, then the shuffling is done after @ref,
2165 * otherwise the instructions are emitted normally at the end. The function
2166 * returns the last instruction inserted.
2167 *
2168 * Notice that @src and @dst cannot be the same register.
2169 */
2170vec4_instruction *
2171vec4_visitor::shuffle_64bit_data(dst_reg dst, src_reg src, bool for_write,
2172                                 bool for_scratch,
2173                                 bblock_t *block, vec4_instruction *ref)
2174{
2175   assert(type_sz(src.type) == 8);
2176   assert(type_sz(dst.type) == 8);
2177   assert(!regions_overlap(dst, 2 * REG_SIZE, src, 2 * REG_SIZE));
2178   assert(!ref == !block);
2179
2180   opcode mov_op = for_scratch ? VEC4_OPCODE_MOV_FOR_SCRATCH : BRW_OPCODE_MOV;
2181
2182   const vec4_builder bld = !ref ? vec4_builder(this).at_end() :
2183                                   vec4_builder(this).at(block, ref->next);
2184
2185   /* Resolve swizzle in src */
2186   if (src.swizzle != BRW_SWIZZLE_XYZW) {
2187      dst_reg data = dst_reg(this, glsl_type::dvec4_type);
2188      bld.emit(mov_op, data, src);
2189      src = src_reg(data);
2190   }
2191
2192   /* dst+0.XY = src+0.XY */
2193   bld.group(4, 0).emit(mov_op, writemask(dst, WRITEMASK_XY), src);
2194
2195   /* dst+0.ZW = src+1.XY */
2196   bld.group(4, for_write ? 1 : 0)
2197            .emit(mov_op, writemask(dst, WRITEMASK_ZW),
2198                  swizzle(byte_offset(src, REG_SIZE), BRW_SWIZZLE_XYXY));
2199
2200   /* dst+1.XY = src+0.ZW */
2201   bld.group(4, for_write ? 0 : 1)
2202            .emit(mov_op, writemask(byte_offset(dst, REG_SIZE), WRITEMASK_XY),
2203                  swizzle(src, BRW_SWIZZLE_ZWZW));
2204
2205   /* dst+1.ZW = src+1.ZW */
2206   return bld.group(4, 1)
2207            .emit(mov_op, writemask(byte_offset(dst, REG_SIZE), WRITEMASK_ZW),
2208                  byte_offset(src, REG_SIZE));
2209}
2210
2211}
2212