brw_fs.cpp revision b8e80941
1/*
2 * Copyright © 2010 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24/** @file brw_fs.cpp
25 *
26 * This file drives the GLSL IR -> LIR translation, contains the
27 * optimizations on the LIR, and drives the generation of native code
28 * from the LIR.
29 */
30
31#include "main/macros.h"
32#include "brw_eu.h"
33#include "brw_fs.h"
34#include "brw_nir.h"
35#include "brw_vec4_gs_visitor.h"
36#include "brw_cfg.h"
37#include "brw_dead_control_flow.h"
38#include "dev/gen_debug.h"
39#include "compiler/glsl_types.h"
40#include "compiler/nir/nir_builder.h"
41#include "program/prog_parameter.h"
42#include "util/u_math.h"
43
44using namespace brw;
45
46static unsigned get_lowered_simd_width(const struct gen_device_info *devinfo,
47                                       const fs_inst *inst);
48
49void
50fs_inst::init(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
51              const fs_reg *src, unsigned sources)
52{
53   memset((void*)this, 0, sizeof(*this));
54
55   this->src = new fs_reg[MAX2(sources, 3)];
56   for (unsigned i = 0; i < sources; i++)
57      this->src[i] = src[i];
58
59   this->opcode = opcode;
60   this->dst = dst;
61   this->sources = sources;
62   this->exec_size = exec_size;
63   this->base_mrf = -1;
64
65   assert(dst.file != IMM && dst.file != UNIFORM);
66
67   assert(this->exec_size != 0);
68
69   this->conditional_mod = BRW_CONDITIONAL_NONE;
70
71   /* This will be the case for almost all instructions. */
72   switch (dst.file) {
73   case VGRF:
74   case ARF:
75   case FIXED_GRF:
76   case MRF:
77   case ATTR:
78      this->size_written = dst.component_size(exec_size);
79      break;
80   case BAD_FILE:
81      this->size_written = 0;
82      break;
83   case IMM:
84   case UNIFORM:
85      unreachable("Invalid destination register file");
86   }
87
88   this->writes_accumulator = false;
89}
90
91fs_inst::fs_inst()
92{
93   init(BRW_OPCODE_NOP, 8, dst, NULL, 0);
94}
95
96fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size)
97{
98   init(opcode, exec_size, reg_undef, NULL, 0);
99}
100
101fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst)
102{
103   init(opcode, exec_size, dst, NULL, 0);
104}
105
106fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
107                 const fs_reg &src0)
108{
109   const fs_reg src[1] = { src0 };
110   init(opcode, exec_size, dst, src, 1);
111}
112
113fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
114                 const fs_reg &src0, const fs_reg &src1)
115{
116   const fs_reg src[2] = { src0, src1 };
117   init(opcode, exec_size, dst, src, 2);
118}
119
120fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
121                 const fs_reg &src0, const fs_reg &src1, const fs_reg &src2)
122{
123   const fs_reg src[3] = { src0, src1, src2 };
124   init(opcode, exec_size, dst, src, 3);
125}
126
127fs_inst::fs_inst(enum opcode opcode, uint8_t exec_width, const fs_reg &dst,
128                 const fs_reg src[], unsigned sources)
129{
130   init(opcode, exec_width, dst, src, sources);
131}
132
133fs_inst::fs_inst(const fs_inst &that)
134{
135   memcpy((void*)this, &that, sizeof(that));
136
137   this->src = new fs_reg[MAX2(that.sources, 3)];
138
139   for (unsigned i = 0; i < that.sources; i++)
140      this->src[i] = that.src[i];
141}
142
143fs_inst::~fs_inst()
144{
145   delete[] this->src;
146}
147
148void
149fs_inst::resize_sources(uint8_t num_sources)
150{
151   if (this->sources != num_sources) {
152      fs_reg *src = new fs_reg[MAX2(num_sources, 3)];
153
154      for (unsigned i = 0; i < MIN2(this->sources, num_sources); ++i)
155         src[i] = this->src[i];
156
157      delete[] this->src;
158      this->src = src;
159      this->sources = num_sources;
160   }
161}
162
163void
164fs_visitor::VARYING_PULL_CONSTANT_LOAD(const fs_builder &bld,
165                                       const fs_reg &dst,
166                                       const fs_reg &surf_index,
167                                       const fs_reg &varying_offset,
168                                       uint32_t const_offset)
169{
170   /* We have our constant surface use a pitch of 4 bytes, so our index can
171    * be any component of a vector, and then we load 4 contiguous
172    * components starting from that.
173    *
174    * We break down the const_offset to a portion added to the variable offset
175    * and a portion done using fs_reg::offset, which means that if you have
176    * GLSL using something like "uniform vec4 a[20]; gl_FragColor = a[i]",
177    * we'll temporarily generate 4 vec4 loads from offset i * 4, and CSE can
178    * later notice that those loads are all the same and eliminate the
179    * redundant ones.
180    */
181   fs_reg vec4_offset = vgrf(glsl_type::uint_type);
182   bld.ADD(vec4_offset, varying_offset, brw_imm_ud(const_offset & ~0xf));
183
184   /* The pull load message will load a vec4 (16 bytes). If we are loading
185    * a double this means we are only loading 2 elements worth of data.
186    * We also want to use a 32-bit data type for the dst of the load operation
187    * so other parts of the driver don't get confused about the size of the
188    * result.
189    */
190   fs_reg vec4_result = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
191   fs_inst *inst = bld.emit(FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL,
192                            vec4_result, surf_index, vec4_offset);
193   inst->size_written = 4 * vec4_result.component_size(inst->exec_size);
194
195   shuffle_from_32bit_read(bld, dst, vec4_result,
196                           (const_offset & 0xf) / type_sz(dst.type), 1);
197}
198
199/**
200 * A helper for MOV generation for fixing up broken hardware SEND dependency
201 * handling.
202 */
203void
204fs_visitor::DEP_RESOLVE_MOV(const fs_builder &bld, int grf)
205{
206   /* The caller always wants uncompressed to emit the minimal extra
207    * dependencies, and to avoid having to deal with aligning its regs to 2.
208    */
209   const fs_builder ubld = bld.annotate("send dependency resolve")
210                              .half(0);
211
212   ubld.MOV(ubld.null_reg_f(), fs_reg(VGRF, grf, BRW_REGISTER_TYPE_F));
213}
214
215bool
216fs_inst::is_send_from_grf() const
217{
218   switch (opcode) {
219   case SHADER_OPCODE_SEND:
220   case SHADER_OPCODE_SHADER_TIME_ADD:
221   case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
222   case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
223   case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
224   case SHADER_OPCODE_URB_WRITE_SIMD8:
225   case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
226   case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
227   case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
228   case SHADER_OPCODE_URB_READ_SIMD8:
229   case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
230      return true;
231   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
232      return src[1].file == VGRF;
233   case FS_OPCODE_FB_WRITE:
234   case FS_OPCODE_FB_READ:
235      return src[0].file == VGRF;
236   default:
237      if (is_tex())
238         return src[0].file == VGRF;
239
240      return false;
241   }
242}
243
244bool
245fs_inst::is_control_source(unsigned arg) const
246{
247   switch (opcode) {
248   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
249   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7:
250   case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4:
251      return arg == 0;
252
253   case SHADER_OPCODE_BROADCAST:
254   case SHADER_OPCODE_SHUFFLE:
255   case SHADER_OPCODE_QUAD_SWIZZLE:
256   case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
257   case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
258   case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
259   case SHADER_OPCODE_GET_BUFFER_SIZE:
260      return arg == 1;
261
262   case SHADER_OPCODE_MOV_INDIRECT:
263   case SHADER_OPCODE_CLUSTER_BROADCAST:
264   case SHADER_OPCODE_TEX:
265   case FS_OPCODE_TXB:
266   case SHADER_OPCODE_TXD:
267   case SHADER_OPCODE_TXF:
268   case SHADER_OPCODE_TXF_LZ:
269   case SHADER_OPCODE_TXF_CMS:
270   case SHADER_OPCODE_TXF_CMS_W:
271   case SHADER_OPCODE_TXF_UMS:
272   case SHADER_OPCODE_TXF_MCS:
273   case SHADER_OPCODE_TXL:
274   case SHADER_OPCODE_TXL_LZ:
275   case SHADER_OPCODE_TXS:
276   case SHADER_OPCODE_LOD:
277   case SHADER_OPCODE_TG4:
278   case SHADER_OPCODE_TG4_OFFSET:
279   case SHADER_OPCODE_SAMPLEINFO:
280      return arg == 1 || arg == 2;
281
282   case SHADER_OPCODE_SEND:
283      return arg == 0 || arg == 1;
284
285   default:
286      return false;
287   }
288}
289
290/**
291 * Returns true if this instruction's sources and destinations cannot
292 * safely be the same register.
293 *
294 * In most cases, a register can be written over safely by the same
295 * instruction that is its last use.  For a single instruction, the
296 * sources are dereferenced before writing of the destination starts
297 * (naturally).
298 *
299 * However, there are a few cases where this can be problematic:
300 *
301 * - Virtual opcodes that translate to multiple instructions in the
302 *   code generator: if src == dst and one instruction writes the
303 *   destination before a later instruction reads the source, then
304 *   src will have been clobbered.
305 *
306 * - SIMD16 compressed instructions with certain regioning (see below).
307 *
308 * The register allocator uses this information to set up conflicts between
309 * GRF sources and the destination.
310 */
311bool
312fs_inst::has_source_and_destination_hazard() const
313{
314   switch (opcode) {
315   case FS_OPCODE_PACK_HALF_2x16_SPLIT:
316      /* Multiple partial writes to the destination */
317      return true;
318   case SHADER_OPCODE_SHUFFLE:
319      /* This instruction returns an arbitrary channel from the source and
320       * gets split into smaller instructions in the generator.  It's possible
321       * that one of the instructions will read from a channel corresponding
322       * to an earlier instruction.
323       */
324   case SHADER_OPCODE_SEL_EXEC:
325      /* This is implemented as
326       *
327       * mov(16)      g4<1>D      0D            { align1 WE_all 1H };
328       * mov(16)      g4<1>D      g5<8,8,1>D    { align1 1H }
329       *
330       * Because the source is only read in the second instruction, the first
331       * may stomp all over it.
332       */
333      return true;
334   case SHADER_OPCODE_QUAD_SWIZZLE:
335      switch (src[1].ud) {
336      case BRW_SWIZZLE_XXXX:
337      case BRW_SWIZZLE_YYYY:
338      case BRW_SWIZZLE_ZZZZ:
339      case BRW_SWIZZLE_WWWW:
340      case BRW_SWIZZLE_XXZZ:
341      case BRW_SWIZZLE_YYWW:
342      case BRW_SWIZZLE_XYXY:
343      case BRW_SWIZZLE_ZWZW:
344         /* These can be implemented as a single Align1 region on all
345          * platforms, so there's never a hazard between source and
346          * destination.  C.f. fs_generator::generate_quad_swizzle().
347          */
348         return false;
349      default:
350         return !is_uniform(src[0]);
351      }
352   default:
353      /* The SIMD16 compressed instruction
354       *
355       * add(16)      g4<1>F      g4<8,8,1>F   g6<8,8,1>F
356       *
357       * is actually decoded in hardware as:
358       *
359       * add(8)       g4<1>F      g4<8,8,1>F   g6<8,8,1>F
360       * add(8)       g5<1>F      g5<8,8,1>F   g7<8,8,1>F
361       *
362       * Which is safe.  However, if we have uniform accesses
363       * happening, we get into trouble:
364       *
365       * add(8)       g4<1>F      g4<0,1,0>F   g6<8,8,1>F
366       * add(8)       g5<1>F      g4<0,1,0>F   g7<8,8,1>F
367       *
368       * Now our destination for the first instruction overwrote the
369       * second instruction's src0, and we get garbage for those 8
370       * pixels.  There's a similar issue for the pre-gen6
371       * pixel_x/pixel_y, which are registers of 16-bit values and thus
372       * would get stomped by the first decode as well.
373       */
374      if (exec_size == 16) {
375         for (int i = 0; i < sources; i++) {
376            if (src[i].file == VGRF && (src[i].stride == 0 ||
377                                        src[i].type == BRW_REGISTER_TYPE_UW ||
378                                        src[i].type == BRW_REGISTER_TYPE_W ||
379                                        src[i].type == BRW_REGISTER_TYPE_UB ||
380                                        src[i].type == BRW_REGISTER_TYPE_B)) {
381               return true;
382            }
383         }
384      }
385      return false;
386   }
387}
388
389bool
390fs_inst::is_copy_payload(const brw::simple_allocator &grf_alloc) const
391{
392   if (this->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
393      return false;
394
395   fs_reg reg = this->src[0];
396   if (reg.file != VGRF || reg.offset != 0 || reg.stride != 1)
397      return false;
398
399   if (grf_alloc.sizes[reg.nr] * REG_SIZE != this->size_written)
400      return false;
401
402   for (int i = 0; i < this->sources; i++) {
403      reg.type = this->src[i].type;
404      if (!this->src[i].equals(reg))
405         return false;
406
407      if (i < this->header_size) {
408         reg.offset += REG_SIZE;
409      } else {
410         reg = horiz_offset(reg, this->exec_size);
411      }
412   }
413
414   return true;
415}
416
417bool
418fs_inst::can_do_source_mods(const struct gen_device_info *devinfo) const
419{
420   if (devinfo->gen == 6 && is_math())
421      return false;
422
423   if (is_send_from_grf())
424      return false;
425
426   if (!backend_instruction::can_do_source_mods())
427      return false;
428
429   return true;
430}
431
432bool
433fs_inst::can_do_cmod()
434{
435   if (!backend_instruction::can_do_cmod())
436      return false;
437
438   /* The accumulator result appears to get used for the conditional modifier
439    * generation.  When negating a UD value, there is a 33rd bit generated for
440    * the sign in the accumulator value, so now you can't check, for example,
441    * equality with a 32-bit value.  See piglit fs-op-neg-uvec4.
442    */
443   for (unsigned i = 0; i < sources; i++) {
444      if (type_is_unsigned_int(src[i].type) && src[i].negate)
445         return false;
446   }
447
448   return true;
449}
450
451bool
452fs_inst::can_change_types() const
453{
454   return dst.type == src[0].type &&
455          !src[0].abs && !src[0].negate && !saturate &&
456          (opcode == BRW_OPCODE_MOV ||
457           (opcode == BRW_OPCODE_SEL &&
458            dst.type == src[1].type &&
459            predicate != BRW_PREDICATE_NONE &&
460            !src[1].abs && !src[1].negate));
461}
462
463void
464fs_reg::init()
465{
466   memset((void*)this, 0, sizeof(*this));
467   type = BRW_REGISTER_TYPE_UD;
468   stride = 1;
469}
470
471/** Generic unset register constructor. */
472fs_reg::fs_reg()
473{
474   init();
475   this->file = BAD_FILE;
476}
477
478fs_reg::fs_reg(struct ::brw_reg reg) :
479   backend_reg(reg)
480{
481   this->offset = 0;
482   this->stride = 1;
483   if (this->file == IMM &&
484       (this->type != BRW_REGISTER_TYPE_V &&
485        this->type != BRW_REGISTER_TYPE_UV &&
486        this->type != BRW_REGISTER_TYPE_VF)) {
487      this->stride = 0;
488   }
489}
490
491bool
492fs_reg::equals(const fs_reg &r) const
493{
494   return (this->backend_reg::equals(r) &&
495           stride == r.stride);
496}
497
498bool
499fs_reg::negative_equals(const fs_reg &r) const
500{
501   return (this->backend_reg::negative_equals(r) &&
502           stride == r.stride);
503}
504
505bool
506fs_reg::is_contiguous() const
507{
508   return stride == 1;
509}
510
511unsigned
512fs_reg::component_size(unsigned width) const
513{
514   const unsigned stride = ((file != ARF && file != FIXED_GRF) ? this->stride :
515                            hstride == 0 ? 0 :
516                            1 << (hstride - 1));
517   return MAX2(width * stride, 1) * type_sz(type);
518}
519
520extern "C" int
521type_size_scalar(const struct glsl_type *type, bool bindless)
522{
523   unsigned int size, i;
524
525   switch (type->base_type) {
526   case GLSL_TYPE_UINT:
527   case GLSL_TYPE_INT:
528   case GLSL_TYPE_FLOAT:
529   case GLSL_TYPE_BOOL:
530      return type->components();
531   case GLSL_TYPE_UINT16:
532   case GLSL_TYPE_INT16:
533   case GLSL_TYPE_FLOAT16:
534      return DIV_ROUND_UP(type->components(), 2);
535   case GLSL_TYPE_UINT8:
536   case GLSL_TYPE_INT8:
537      return DIV_ROUND_UP(type->components(), 4);
538   case GLSL_TYPE_DOUBLE:
539   case GLSL_TYPE_UINT64:
540   case GLSL_TYPE_INT64:
541      return type->components() * 2;
542   case GLSL_TYPE_ARRAY:
543      return type_size_scalar(type->fields.array, bindless) * type->length;
544   case GLSL_TYPE_STRUCT:
545   case GLSL_TYPE_INTERFACE:
546      size = 0;
547      for (i = 0; i < type->length; i++) {
548	 size += type_size_scalar(type->fields.structure[i].type, bindless);
549      }
550      return size;
551   case GLSL_TYPE_SAMPLER:
552   case GLSL_TYPE_IMAGE:
553      if (bindless)
554         return type->components() * 2;
555   case GLSL_TYPE_ATOMIC_UINT:
556      /* Samplers, atomics, and images take up no register space, since
557       * they're baked in at link time.
558       */
559      return 0;
560   case GLSL_TYPE_SUBROUTINE:
561      return 1;
562   case GLSL_TYPE_VOID:
563   case GLSL_TYPE_ERROR:
564   case GLSL_TYPE_FUNCTION:
565      unreachable("not reached");
566   }
567
568   return 0;
569}
570
571/**
572 * Create a MOV to read the timestamp register.
573 *
574 * The caller is responsible for emitting the MOV.  The return value is
575 * the destination of the MOV, with extra parameters set.
576 */
577fs_reg
578fs_visitor::get_timestamp(const fs_builder &bld)
579{
580   assert(devinfo->gen >= 7);
581
582   fs_reg ts = fs_reg(retype(brw_vec4_reg(BRW_ARCHITECTURE_REGISTER_FILE,
583                                          BRW_ARF_TIMESTAMP,
584                                          0),
585                             BRW_REGISTER_TYPE_UD));
586
587   fs_reg dst = fs_reg(VGRF, alloc.allocate(1), BRW_REGISTER_TYPE_UD);
588
589   /* We want to read the 3 fields we care about even if it's not enabled in
590    * the dispatch.
591    */
592   bld.group(4, 0).exec_all().MOV(dst, ts);
593
594   return dst;
595}
596
597void
598fs_visitor::emit_shader_time_begin()
599{
600   /* We want only the low 32 bits of the timestamp.  Since it's running
601    * at the GPU clock rate of ~1.2ghz, it will roll over every ~3 seconds,
602    * which is plenty of time for our purposes.  It is identical across the
603    * EUs, but since it's tracking GPU core speed it will increment at a
604    * varying rate as render P-states change.
605    */
606   shader_start_time = component(
607      get_timestamp(bld.annotate("shader time start")), 0);
608}
609
610void
611fs_visitor::emit_shader_time_end()
612{
613   /* Insert our code just before the final SEND with EOT. */
614   exec_node *end = this->instructions.get_tail();
615   assert(end && ((fs_inst *) end)->eot);
616   const fs_builder ibld = bld.annotate("shader time end")
617                              .exec_all().at(NULL, end);
618   const fs_reg timestamp = get_timestamp(ibld);
619
620   /* We only use the low 32 bits of the timestamp - see
621    * emit_shader_time_begin()).
622    *
623    * We could also check if render P-states have changed (or anything
624    * else that might disrupt timing) by setting smear to 2 and checking if
625    * that field is != 0.
626    */
627   const fs_reg shader_end_time = component(timestamp, 0);
628
629   /* Check that there weren't any timestamp reset events (assuming these
630    * were the only two timestamp reads that happened).
631    */
632   const fs_reg reset = component(timestamp, 2);
633   set_condmod(BRW_CONDITIONAL_Z,
634               ibld.AND(ibld.null_reg_ud(), reset, brw_imm_ud(1u)));
635   ibld.IF(BRW_PREDICATE_NORMAL);
636
637   fs_reg start = shader_start_time;
638   start.negate = true;
639   const fs_reg diff = component(fs_reg(VGRF, alloc.allocate(1),
640                                        BRW_REGISTER_TYPE_UD),
641                                 0);
642   const fs_builder cbld = ibld.group(1, 0);
643   cbld.group(1, 0).ADD(diff, start, shader_end_time);
644
645   /* If there were no instructions between the two timestamp gets, the diff
646    * is 2 cycles.  Remove that overhead, so I can forget about that when
647    * trying to determine the time taken for single instructions.
648    */
649   cbld.ADD(diff, diff, brw_imm_ud(-2u));
650   SHADER_TIME_ADD(cbld, 0, diff);
651   SHADER_TIME_ADD(cbld, 1, brw_imm_ud(1u));
652   ibld.emit(BRW_OPCODE_ELSE);
653   SHADER_TIME_ADD(cbld, 2, brw_imm_ud(1u));
654   ibld.emit(BRW_OPCODE_ENDIF);
655}
656
657void
658fs_visitor::SHADER_TIME_ADD(const fs_builder &bld,
659                            int shader_time_subindex,
660                            fs_reg value)
661{
662   int index = shader_time_index * 3 + shader_time_subindex;
663   struct brw_reg offset = brw_imm_d(index * BRW_SHADER_TIME_STRIDE);
664
665   fs_reg payload;
666   if (dispatch_width == 8)
667      payload = vgrf(glsl_type::uvec2_type);
668   else
669      payload = vgrf(glsl_type::uint_type);
670
671   bld.emit(SHADER_OPCODE_SHADER_TIME_ADD, fs_reg(), payload, offset, value);
672}
673
674void
675fs_visitor::vfail(const char *format, va_list va)
676{
677   char *msg;
678
679   if (failed)
680      return;
681
682   failed = true;
683
684   msg = ralloc_vasprintf(mem_ctx, format, va);
685   msg = ralloc_asprintf(mem_ctx, "%s compile failed: %s\n", stage_abbrev, msg);
686
687   this->fail_msg = msg;
688
689   if (debug_enabled) {
690      fprintf(stderr, "%s",  msg);
691   }
692}
693
694void
695fs_visitor::fail(const char *format, ...)
696{
697   va_list va;
698
699   va_start(va, format);
700   vfail(format, va);
701   va_end(va);
702}
703
704/**
705 * Mark this program as impossible to compile with dispatch width greater
706 * than n.
707 *
708 * During the SIMD8 compile (which happens first), we can detect and flag
709 * things that are unsupported in SIMD16+ mode, so the compiler can skip the
710 * SIMD16+ compile altogether.
711 *
712 * During a compile of dispatch width greater than n (if one happens anyway),
713 * this just calls fail().
714 */
715void
716fs_visitor::limit_dispatch_width(unsigned n, const char *msg)
717{
718   if (dispatch_width > n) {
719      fail("%s", msg);
720   } else {
721      max_dispatch_width = n;
722      compiler->shader_perf_log(log_data,
723                                "Shader dispatch width limited to SIMD%d: %s",
724                                n, msg);
725   }
726}
727
728/**
729 * Returns true if the instruction has a flag that means it won't
730 * update an entire destination register.
731 *
732 * For example, dead code elimination and live variable analysis want to know
733 * when a write to a variable screens off any preceding values that were in
734 * it.
735 */
736bool
737fs_inst::is_partial_write() const
738{
739   return ((this->predicate && this->opcode != BRW_OPCODE_SEL) ||
740           (this->exec_size * type_sz(this->dst.type)) < 32 ||
741           !this->dst.is_contiguous() ||
742           this->dst.offset % REG_SIZE != 0);
743}
744
745unsigned
746fs_inst::components_read(unsigned i) const
747{
748   /* Return zero if the source is not present. */
749   if (src[i].file == BAD_FILE)
750      return 0;
751
752   switch (opcode) {
753   case FS_OPCODE_LINTERP:
754      if (i == 0)
755         return 2;
756      else
757         return 1;
758
759   case FS_OPCODE_PIXEL_X:
760   case FS_OPCODE_PIXEL_Y:
761      assert(i == 0);
762      return 2;
763
764   case FS_OPCODE_FB_WRITE_LOGICAL:
765      assert(src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
766      /* First/second FB write color. */
767      if (i < 2)
768         return src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
769      else
770         return 1;
771
772   case SHADER_OPCODE_TEX_LOGICAL:
773   case SHADER_OPCODE_TXD_LOGICAL:
774   case SHADER_OPCODE_TXF_LOGICAL:
775   case SHADER_OPCODE_TXL_LOGICAL:
776   case SHADER_OPCODE_TXS_LOGICAL:
777   case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
778   case FS_OPCODE_TXB_LOGICAL:
779   case SHADER_OPCODE_TXF_CMS_LOGICAL:
780   case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
781   case SHADER_OPCODE_TXF_UMS_LOGICAL:
782   case SHADER_OPCODE_TXF_MCS_LOGICAL:
783   case SHADER_OPCODE_LOD_LOGICAL:
784   case SHADER_OPCODE_TG4_LOGICAL:
785   case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
786   case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
787      assert(src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM &&
788             src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
789      /* Texture coordinates. */
790      if (i == TEX_LOGICAL_SRC_COORDINATE)
791         return src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
792      /* Texture derivatives. */
793      else if ((i == TEX_LOGICAL_SRC_LOD || i == TEX_LOGICAL_SRC_LOD2) &&
794               opcode == SHADER_OPCODE_TXD_LOGICAL)
795         return src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
796      /* Texture offset. */
797      else if (i == TEX_LOGICAL_SRC_TG4_OFFSET)
798         return 2;
799      /* MCS */
800      else if (i == TEX_LOGICAL_SRC_MCS && opcode == SHADER_OPCODE_TXF_CMS_W_LOGICAL)
801         return 2;
802      else
803         return 1;
804
805   case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
806   case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
807      assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM);
808      /* Surface coordinates. */
809      if (i == SURFACE_LOGICAL_SRC_ADDRESS)
810         return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
811      /* Surface operation source (ignored for reads). */
812      else if (i == SURFACE_LOGICAL_SRC_DATA)
813         return 0;
814      else
815         return 1;
816
817   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
818   case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
819      assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
820             src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
821      /* Surface coordinates. */
822      if (i == SURFACE_LOGICAL_SRC_ADDRESS)
823         return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
824      /* Surface operation source. */
825      else if (i == SURFACE_LOGICAL_SRC_DATA)
826         return src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
827      else
828         return 1;
829
830   case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
831      assert(src[2].file == IMM);
832      return 1;
833
834   case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
835      assert(src[2].file == IMM);
836      return i == 1 ? src[2].ud : 1;
837
838   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
839   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
840      assert(src[2].file == IMM);
841      if (i == 1) {
842         /* Data source */
843         const unsigned op = src[2].ud;
844         switch (op) {
845         case BRW_AOP_INC:
846         case BRW_AOP_DEC:
847         case BRW_AOP_PREDEC:
848            return 0;
849         case BRW_AOP_CMPWR:
850            return 2;
851         default:
852            return 1;
853         }
854      } else {
855         return 1;
856      }
857
858   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
859      assert(src[2].file == IMM);
860      if (i == 1) {
861         /* Data source */
862         const unsigned op = src[2].ud;
863         return op == BRW_AOP_FCMPWR ? 2 : 1;
864      } else {
865         return 1;
866      }
867
868   case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
869      /* Scattered logical opcodes use the following params:
870       * src[0] Surface coordinates
871       * src[1] Surface operation source (ignored for reads)
872       * src[2] Surface
873       * src[3] IMM with always 1 dimension.
874       * src[4] IMM with arg bitsize for scattered read/write 8, 16, 32
875       */
876      assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
877             src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
878      return i == SURFACE_LOGICAL_SRC_DATA ? 0 : 1;
879
880   case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
881      assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
882             src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
883      return 1;
884
885   case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
886   case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL: {
887      assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
888             src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
889      const unsigned op = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
890      /* Surface coordinates. */
891      if (i == SURFACE_LOGICAL_SRC_ADDRESS)
892         return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
893      /* Surface operation source. */
894      else if (i == SURFACE_LOGICAL_SRC_DATA && op == BRW_AOP_CMPWR)
895         return 2;
896      else if (i == SURFACE_LOGICAL_SRC_DATA &&
897               (op == BRW_AOP_INC || op == BRW_AOP_DEC || op == BRW_AOP_PREDEC))
898         return 0;
899      else
900         return 1;
901   }
902   case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
903      return (i == 0 ? 2 : 1);
904
905   case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL: {
906      assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
907             src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
908      const unsigned op = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
909      /* Surface coordinates. */
910      if (i == SURFACE_LOGICAL_SRC_ADDRESS)
911         return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
912      /* Surface operation source. */
913      else if (i == SURFACE_LOGICAL_SRC_DATA && op == BRW_AOP_FCMPWR)
914         return 2;
915      else
916         return 1;
917   }
918
919   default:
920      return 1;
921   }
922}
923
924unsigned
925fs_inst::size_read(int arg) const
926{
927   switch (opcode) {
928   case SHADER_OPCODE_SEND:
929      if (arg == 2) {
930         return mlen * REG_SIZE;
931      } else if (arg == 3) {
932         return ex_mlen * REG_SIZE;
933      }
934      break;
935
936   case FS_OPCODE_FB_WRITE:
937   case FS_OPCODE_REP_FB_WRITE:
938      if (arg == 0) {
939         if (base_mrf >= 0)
940            return src[0].file == BAD_FILE ? 0 : 2 * REG_SIZE;
941         else
942            return mlen * REG_SIZE;
943      }
944      break;
945
946   case FS_OPCODE_FB_READ:
947   case SHADER_OPCODE_URB_WRITE_SIMD8:
948   case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
949   case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
950   case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
951   case SHADER_OPCODE_URB_READ_SIMD8:
952   case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
953   case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
954   case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
955      if (arg == 0)
956         return mlen * REG_SIZE;
957      break;
958
959   case FS_OPCODE_SET_SAMPLE_ID:
960      if (arg == 1)
961         return 1;
962      break;
963
964   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7:
965      /* The payload is actually stored in src1 */
966      if (arg == 1)
967         return mlen * REG_SIZE;
968      break;
969
970   case FS_OPCODE_LINTERP:
971      if (arg == 1)
972         return 16;
973      break;
974
975   case SHADER_OPCODE_LOAD_PAYLOAD:
976      if (arg < this->header_size)
977         return REG_SIZE;
978      break;
979
980   case CS_OPCODE_CS_TERMINATE:
981   case SHADER_OPCODE_BARRIER:
982      return REG_SIZE;
983
984   case SHADER_OPCODE_MOV_INDIRECT:
985      if (arg == 0) {
986         assert(src[2].file == IMM);
987         return src[2].ud;
988      }
989      break;
990
991   default:
992      if (is_tex() && arg == 0 && src[0].file == VGRF)
993         return mlen * REG_SIZE;
994      break;
995   }
996
997   switch (src[arg].file) {
998   case UNIFORM:
999   case IMM:
1000      return components_read(arg) * type_sz(src[arg].type);
1001   case BAD_FILE:
1002   case ARF:
1003   case FIXED_GRF:
1004   case VGRF:
1005   case ATTR:
1006      return components_read(arg) * src[arg].component_size(exec_size);
1007   case MRF:
1008      unreachable("MRF registers are not allowed as sources");
1009   }
1010   return 0;
1011}
1012
1013namespace {
1014   /* Return the subset of flag registers that an instruction could
1015    * potentially read or write based on the execution controls and flag
1016    * subregister number of the instruction.
1017    */
1018   unsigned
1019   flag_mask(const fs_inst *inst)
1020   {
1021      const unsigned start = inst->flag_subreg * 16 + inst->group;
1022      const unsigned end = start + inst->exec_size;
1023      return ((1 << DIV_ROUND_UP(end, 8)) - 1) & ~((1 << (start / 8)) - 1);
1024   }
1025
1026   unsigned
1027   bit_mask(unsigned n)
1028   {
1029      return (n >= CHAR_BIT * sizeof(bit_mask(n)) ? ~0u : (1u << n) - 1);
1030   }
1031
1032   unsigned
1033   flag_mask(const fs_reg &r, unsigned sz)
1034   {
1035      if (r.file == ARF) {
1036         const unsigned start = (r.nr - BRW_ARF_FLAG) * 4 + r.subnr;
1037         const unsigned end = start + sz;
1038         return bit_mask(end) & ~bit_mask(start);
1039      } else {
1040         return 0;
1041      }
1042   }
1043}
1044
1045unsigned
1046fs_inst::flags_read(const gen_device_info *devinfo) const
1047{
1048   if (predicate == BRW_PREDICATE_ALIGN1_ANYV ||
1049       predicate == BRW_PREDICATE_ALIGN1_ALLV) {
1050      /* The vertical predication modes combine corresponding bits from
1051       * f0.0 and f1.0 on Gen7+, and f0.0 and f0.1 on older hardware.
1052       */
1053      const unsigned shift = devinfo->gen >= 7 ? 4 : 2;
1054      return flag_mask(this) << shift | flag_mask(this);
1055   } else if (predicate) {
1056      return flag_mask(this);
1057   } else {
1058      unsigned mask = 0;
1059      for (int i = 0; i < sources; i++) {
1060         mask |= flag_mask(src[i], size_read(i));
1061      }
1062      return mask;
1063   }
1064}
1065
1066unsigned
1067fs_inst::flags_written() const
1068{
1069   if ((conditional_mod && (opcode != BRW_OPCODE_SEL &&
1070                            opcode != BRW_OPCODE_CSEL &&
1071                            opcode != BRW_OPCODE_IF &&
1072                            opcode != BRW_OPCODE_WHILE)) ||
1073       opcode == SHADER_OPCODE_FIND_LIVE_CHANNEL ||
1074       opcode == FS_OPCODE_FB_WRITE) {
1075      return flag_mask(this);
1076   } else {
1077      return flag_mask(dst, size_written);
1078   }
1079}
1080
1081/**
1082 * Returns how many MRFs an FS opcode will write over.
1083 *
1084 * Note that this is not the 0 or 1 implied writes in an actual gen
1085 * instruction -- the FS opcodes often generate MOVs in addition.
1086 */
1087int
1088fs_visitor::implied_mrf_writes(fs_inst *inst) const
1089{
1090   if (inst->mlen == 0)
1091      return 0;
1092
1093   if (inst->base_mrf == -1)
1094      return 0;
1095
1096   switch (inst->opcode) {
1097   case SHADER_OPCODE_RCP:
1098   case SHADER_OPCODE_RSQ:
1099   case SHADER_OPCODE_SQRT:
1100   case SHADER_OPCODE_EXP2:
1101   case SHADER_OPCODE_LOG2:
1102   case SHADER_OPCODE_SIN:
1103   case SHADER_OPCODE_COS:
1104      return 1 * dispatch_width / 8;
1105   case SHADER_OPCODE_POW:
1106   case SHADER_OPCODE_INT_QUOTIENT:
1107   case SHADER_OPCODE_INT_REMAINDER:
1108      return 2 * dispatch_width / 8;
1109   case SHADER_OPCODE_TEX:
1110   case FS_OPCODE_TXB:
1111   case SHADER_OPCODE_TXD:
1112   case SHADER_OPCODE_TXF:
1113   case SHADER_OPCODE_TXF_CMS:
1114   case SHADER_OPCODE_TXF_MCS:
1115   case SHADER_OPCODE_TG4:
1116   case SHADER_OPCODE_TG4_OFFSET:
1117   case SHADER_OPCODE_TXL:
1118   case SHADER_OPCODE_TXS:
1119   case SHADER_OPCODE_LOD:
1120   case SHADER_OPCODE_SAMPLEINFO:
1121      return 1;
1122   case FS_OPCODE_FB_WRITE:
1123   case FS_OPCODE_REP_FB_WRITE:
1124      return inst->src[0].file == BAD_FILE ? 0 : 2;
1125   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
1126   case SHADER_OPCODE_GEN4_SCRATCH_READ:
1127      return 1;
1128   case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4:
1129      return inst->mlen;
1130   case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
1131      return inst->mlen;
1132   default:
1133      unreachable("not reached");
1134   }
1135}
1136
1137fs_reg
1138fs_visitor::vgrf(const glsl_type *const type)
1139{
1140   int reg_width = dispatch_width / 8;
1141   return fs_reg(VGRF,
1142                 alloc.allocate(type_size_scalar(type, false) * reg_width),
1143                 brw_type_for_base_type(type));
1144}
1145
1146fs_reg::fs_reg(enum brw_reg_file file, int nr)
1147{
1148   init();
1149   this->file = file;
1150   this->nr = nr;
1151   this->type = BRW_REGISTER_TYPE_F;
1152   this->stride = (file == UNIFORM ? 0 : 1);
1153}
1154
1155fs_reg::fs_reg(enum brw_reg_file file, int nr, enum brw_reg_type type)
1156{
1157   init();
1158   this->file = file;
1159   this->nr = nr;
1160   this->type = type;
1161   this->stride = (file == UNIFORM ? 0 : 1);
1162}
1163
1164/* For SIMD16, we need to follow from the uniform setup of SIMD8 dispatch.
1165 * This brings in those uniform definitions
1166 */
1167void
1168fs_visitor::import_uniforms(fs_visitor *v)
1169{
1170   this->push_constant_loc = v->push_constant_loc;
1171   this->pull_constant_loc = v->pull_constant_loc;
1172   this->uniforms = v->uniforms;
1173   this->subgroup_id = v->subgroup_id;
1174}
1175
1176void
1177fs_visitor::emit_fragcoord_interpolation(fs_reg wpos)
1178{
1179   assert(stage == MESA_SHADER_FRAGMENT);
1180
1181   /* gl_FragCoord.x */
1182   bld.MOV(wpos, this->pixel_x);
1183   wpos = offset(wpos, bld, 1);
1184
1185   /* gl_FragCoord.y */
1186   bld.MOV(wpos, this->pixel_y);
1187   wpos = offset(wpos, bld, 1);
1188
1189   /* gl_FragCoord.z */
1190   if (devinfo->gen >= 6) {
1191      bld.MOV(wpos, fetch_payload_reg(bld, payload.source_depth_reg));
1192   } else {
1193      bld.emit(FS_OPCODE_LINTERP, wpos,
1194               this->delta_xy[BRW_BARYCENTRIC_PERSPECTIVE_PIXEL],
1195               component(interp_reg(VARYING_SLOT_POS, 2), 0));
1196   }
1197   wpos = offset(wpos, bld, 1);
1198
1199   /* gl_FragCoord.w: Already set up in emit_interpolation */
1200   bld.MOV(wpos, this->wpos_w);
1201}
1202
1203enum brw_barycentric_mode
1204brw_barycentric_mode(enum glsl_interp_mode mode, nir_intrinsic_op op)
1205{
1206   /* Barycentric modes don't make sense for flat inputs. */
1207   assert(mode != INTERP_MODE_FLAT);
1208
1209   unsigned bary;
1210   switch (op) {
1211   case nir_intrinsic_load_barycentric_pixel:
1212   case nir_intrinsic_load_barycentric_at_offset:
1213      bary = BRW_BARYCENTRIC_PERSPECTIVE_PIXEL;
1214      break;
1215   case nir_intrinsic_load_barycentric_centroid:
1216      bary = BRW_BARYCENTRIC_PERSPECTIVE_CENTROID;
1217      break;
1218   case nir_intrinsic_load_barycentric_sample:
1219   case nir_intrinsic_load_barycentric_at_sample:
1220      bary = BRW_BARYCENTRIC_PERSPECTIVE_SAMPLE;
1221      break;
1222   default:
1223      unreachable("invalid intrinsic");
1224   }
1225
1226   if (mode == INTERP_MODE_NOPERSPECTIVE)
1227      bary += 3;
1228
1229   return (enum brw_barycentric_mode) bary;
1230}
1231
1232/**
1233 * Turn one of the two CENTROID barycentric modes into PIXEL mode.
1234 */
1235static enum brw_barycentric_mode
1236centroid_to_pixel(enum brw_barycentric_mode bary)
1237{
1238   assert(bary == BRW_BARYCENTRIC_PERSPECTIVE_CENTROID ||
1239          bary == BRW_BARYCENTRIC_NONPERSPECTIVE_CENTROID);
1240   return (enum brw_barycentric_mode) ((unsigned) bary - 1);
1241}
1242
1243fs_reg *
1244fs_visitor::emit_frontfacing_interpolation()
1245{
1246   fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::bool_type));
1247
1248   if (devinfo->gen >= 6) {
1249      /* Bit 15 of g0.0 is 0 if the polygon is front facing. We want to create
1250       * a boolean result from this (~0/true or 0/false).
1251       *
1252       * We can use the fact that bit 15 is the MSB of g0.0:W to accomplish
1253       * this task in only one instruction:
1254       *    - a negation source modifier will flip the bit; and
1255       *    - a W -> D type conversion will sign extend the bit into the high
1256       *      word of the destination.
1257       *
1258       * An ASR 15 fills the low word of the destination.
1259       */
1260      fs_reg g0 = fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_W));
1261      g0.negate = true;
1262
1263      bld.ASR(*reg, g0, brw_imm_d(15));
1264   } else {
1265      /* Bit 31 of g1.6 is 0 if the polygon is front facing. We want to create
1266       * a boolean result from this (1/true or 0/false).
1267       *
1268       * Like in the above case, since the bit is the MSB of g1.6:UD we can use
1269       * the negation source modifier to flip it. Unfortunately the SHR
1270       * instruction only operates on UD (or D with an abs source modifier)
1271       * sources without negation.
1272       *
1273       * Instead, use ASR (which will give ~0/true or 0/false).
1274       */
1275      fs_reg g1_6 = fs_reg(retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_D));
1276      g1_6.negate = true;
1277
1278      bld.ASR(*reg, g1_6, brw_imm_d(31));
1279   }
1280
1281   return reg;
1282}
1283
1284void
1285fs_visitor::compute_sample_position(fs_reg dst, fs_reg int_sample_pos)
1286{
1287   assert(stage == MESA_SHADER_FRAGMENT);
1288   struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1289   assert(dst.type == BRW_REGISTER_TYPE_F);
1290
1291   if (wm_prog_data->persample_dispatch) {
1292      /* Convert int_sample_pos to floating point */
1293      bld.MOV(dst, int_sample_pos);
1294      /* Scale to the range [0, 1] */
1295      bld.MUL(dst, dst, brw_imm_f(1 / 16.0f));
1296   }
1297   else {
1298      /* From ARB_sample_shading specification:
1299       * "When rendering to a non-multisample buffer, or if multisample
1300       *  rasterization is disabled, gl_SamplePosition will always be
1301       *  (0.5, 0.5).
1302       */
1303      bld.MOV(dst, brw_imm_f(0.5f));
1304   }
1305}
1306
1307fs_reg *
1308fs_visitor::emit_samplepos_setup()
1309{
1310   assert(devinfo->gen >= 6);
1311
1312   const fs_builder abld = bld.annotate("compute sample position");
1313   fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::vec2_type));
1314   fs_reg pos = *reg;
1315   fs_reg int_sample_x = vgrf(glsl_type::int_type);
1316   fs_reg int_sample_y = vgrf(glsl_type::int_type);
1317
1318   /* WM will be run in MSDISPMODE_PERSAMPLE. So, only one of SIMD8 or SIMD16
1319    * mode will be enabled.
1320    *
1321    * From the Ivy Bridge PRM, volume 2 part 1, page 344:
1322    * R31.1:0         Position Offset X/Y for Slot[3:0]
1323    * R31.3:2         Position Offset X/Y for Slot[7:4]
1324    * .....
1325    *
1326    * The X, Y sample positions come in as bytes in  thread payload. So, read
1327    * the positions using vstride=16, width=8, hstride=2.
1328    */
1329   const fs_reg sample_pos_reg =
1330      fetch_payload_reg(abld, payload.sample_pos_reg, BRW_REGISTER_TYPE_W);
1331
1332   /* Compute gl_SamplePosition.x */
1333   abld.MOV(int_sample_x, subscript(sample_pos_reg, BRW_REGISTER_TYPE_B, 0));
1334   compute_sample_position(offset(pos, abld, 0), int_sample_x);
1335
1336   /* Compute gl_SamplePosition.y */
1337   abld.MOV(int_sample_y, subscript(sample_pos_reg, BRW_REGISTER_TYPE_B, 1));
1338   compute_sample_position(offset(pos, abld, 1), int_sample_y);
1339   return reg;
1340}
1341
1342fs_reg *
1343fs_visitor::emit_sampleid_setup()
1344{
1345   assert(stage == MESA_SHADER_FRAGMENT);
1346   brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1347   assert(devinfo->gen >= 6);
1348
1349   const fs_builder abld = bld.annotate("compute sample id");
1350   fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uint_type));
1351
1352   if (!key->multisample_fbo) {
1353      /* As per GL_ARB_sample_shading specification:
1354       * "When rendering to a non-multisample buffer, or if multisample
1355       *  rasterization is disabled, gl_SampleID will always be zero."
1356       */
1357      abld.MOV(*reg, brw_imm_d(0));
1358   } else if (devinfo->gen >= 8) {
1359      /* Sample ID comes in as 4-bit numbers in g1.0:
1360       *
1361       *    15:12 Slot 3 SampleID (only used in SIMD16)
1362       *     11:8 Slot 2 SampleID (only used in SIMD16)
1363       *      7:4 Slot 1 SampleID
1364       *      3:0 Slot 0 SampleID
1365       *
1366       * Each slot corresponds to four channels, so we want to replicate each
1367       * half-byte value to 4 channels in a row:
1368       *
1369       *    dst+0:    .7    .6    .5    .4    .3    .2    .1    .0
1370       *             7:4   7:4   7:4   7:4   3:0   3:0   3:0   3:0
1371       *
1372       *    dst+1:    .7    .6    .5    .4    .3    .2    .1    .0  (if SIMD16)
1373       *           15:12 15:12 15:12 15:12  11:8  11:8  11:8  11:8
1374       *
1375       * First, we read g1.0 with a <1,8,0>UB region, causing the first 8
1376       * channels to read the first byte (7:0), and the second group of 8
1377       * channels to read the second byte (15:8).  Then, we shift right by
1378       * a vector immediate of <4, 4, 4, 4, 0, 0, 0, 0>, moving the slot 1 / 3
1379       * values into place.  Finally, we AND with 0xf to keep the low nibble.
1380       *
1381       *    shr(16) tmp<1>W g1.0<1,8,0>B 0x44440000:V
1382       *    and(16) dst<1>D tmp<8,8,1>W  0xf:W
1383       *
1384       * TODO: These payload bits exist on Gen7 too, but they appear to always
1385       *       be zero, so this code fails to work.  We should find out why.
1386       */
1387      const fs_reg tmp = abld.vgrf(BRW_REGISTER_TYPE_UW);
1388
1389      for (unsigned i = 0; i < DIV_ROUND_UP(dispatch_width, 16); i++) {
1390         const fs_builder hbld = abld.group(MIN2(16, dispatch_width), i);
1391         hbld.SHR(offset(tmp, hbld, i),
1392                  stride(retype(brw_vec1_grf(1 + i, 0), BRW_REGISTER_TYPE_UB),
1393                         1, 8, 0),
1394                  brw_imm_v(0x44440000));
1395      }
1396
1397      abld.AND(*reg, tmp, brw_imm_w(0xf));
1398   } else {
1399      const fs_reg t1 = component(abld.vgrf(BRW_REGISTER_TYPE_UD), 0);
1400      const fs_reg t2 = abld.vgrf(BRW_REGISTER_TYPE_UW);
1401
1402      /* The PS will be run in MSDISPMODE_PERSAMPLE. For example with
1403       * 8x multisampling, subspan 0 will represent sample N (where N
1404       * is 0, 2, 4 or 6), subspan 1 will represent sample 1, 3, 5 or
1405       * 7. We can find the value of N by looking at R0.0 bits 7:6
1406       * ("Starting Sample Pair Index (SSPI)") and multiplying by two
1407       * (since samples are always delivered in pairs). That is, we
1408       * compute 2*((R0.0 & 0xc0) >> 6) == (R0.0 & 0xc0) >> 5. Then
1409       * we need to add N to the sequence (0, 0, 0, 0, 1, 1, 1, 1) in
1410       * case of SIMD8 and sequence (0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2,
1411       * 2, 3, 3, 3, 3) in case of SIMD16. We compute this sequence by
1412       * populating a temporary variable with the sequence (0, 1, 2, 3),
1413       * and then reading from it using vstride=1, width=4, hstride=0.
1414       * These computations hold good for 4x multisampling as well.
1415       *
1416       * For 2x MSAA and SIMD16, we want to use the sequence (0, 1, 0, 1):
1417       * the first four slots are sample 0 of subspan 0; the next four
1418       * are sample 1 of subspan 0; the third group is sample 0 of
1419       * subspan 1, and finally sample 1 of subspan 1.
1420       */
1421
1422      /* SKL+ has an extra bit for the Starting Sample Pair Index to
1423       * accomodate 16x MSAA.
1424       */
1425      abld.exec_all().group(1, 0)
1426          .AND(t1, fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
1427               brw_imm_ud(0xc0));
1428      abld.exec_all().group(1, 0).SHR(t1, t1, brw_imm_d(5));
1429
1430      /* This works for SIMD8-SIMD16.  It also works for SIMD32 but only if we
1431       * can assume 4x MSAA.  Disallow it on IVB+
1432       *
1433       * FINISHME: One day, we could come up with a way to do this that
1434       * actually works on gen7.
1435       */
1436      if (devinfo->gen >= 7)
1437         limit_dispatch_width(16, "gl_SampleId is unsupported in SIMD32 on gen7");
1438      abld.exec_all().group(8, 0).MOV(t2, brw_imm_v(0x32103210));
1439
1440      /* This special instruction takes care of setting vstride=1,
1441       * width=4, hstride=0 of t2 during an ADD instruction.
1442       */
1443      abld.emit(FS_OPCODE_SET_SAMPLE_ID, *reg, t1, t2);
1444   }
1445
1446   return reg;
1447}
1448
1449fs_reg *
1450fs_visitor::emit_samplemaskin_setup()
1451{
1452   assert(stage == MESA_SHADER_FRAGMENT);
1453   struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1454   assert(devinfo->gen >= 6);
1455
1456   fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::int_type));
1457
1458   fs_reg coverage_mask =
1459      fetch_payload_reg(bld, payload.sample_mask_in_reg, BRW_REGISTER_TYPE_D);
1460
1461   if (wm_prog_data->persample_dispatch) {
1462      /* gl_SampleMaskIn[] comes from two sources: the input coverage mask,
1463       * and a mask representing which sample is being processed by the
1464       * current shader invocation.
1465       *
1466       * From the OES_sample_variables specification:
1467       * "When per-sample shading is active due to the use of a fragment input
1468       *  qualified by "sample" or due to the use of the gl_SampleID or
1469       *  gl_SamplePosition variables, only the bit for the current sample is
1470       *  set in gl_SampleMaskIn."
1471       */
1472      const fs_builder abld = bld.annotate("compute gl_SampleMaskIn");
1473
1474      if (nir_system_values[SYSTEM_VALUE_SAMPLE_ID].file == BAD_FILE)
1475         nir_system_values[SYSTEM_VALUE_SAMPLE_ID] = *emit_sampleid_setup();
1476
1477      fs_reg one = vgrf(glsl_type::int_type);
1478      fs_reg enabled_mask = vgrf(glsl_type::int_type);
1479      abld.MOV(one, brw_imm_d(1));
1480      abld.SHL(enabled_mask, one, nir_system_values[SYSTEM_VALUE_SAMPLE_ID]);
1481      abld.AND(*reg, enabled_mask, coverage_mask);
1482   } else {
1483      /* In per-pixel mode, the coverage mask is sufficient. */
1484      *reg = coverage_mask;
1485   }
1486   return reg;
1487}
1488
1489fs_reg
1490fs_visitor::resolve_source_modifiers(const fs_reg &src)
1491{
1492   if (!src.abs && !src.negate)
1493      return src;
1494
1495   fs_reg temp = bld.vgrf(src.type);
1496   bld.MOV(temp, src);
1497
1498   return temp;
1499}
1500
1501void
1502fs_visitor::emit_discard_jump()
1503{
1504   assert(brw_wm_prog_data(this->prog_data)->uses_kill);
1505
1506   /* For performance, after a discard, jump to the end of the
1507    * shader if all relevant channels have been discarded.
1508    */
1509   fs_inst *discard_jump = bld.emit(FS_OPCODE_DISCARD_JUMP);
1510   discard_jump->flag_subreg = 1;
1511
1512   discard_jump->predicate = BRW_PREDICATE_ALIGN1_ANY4H;
1513   discard_jump->predicate_inverse = true;
1514}
1515
1516void
1517fs_visitor::emit_gs_thread_end()
1518{
1519   assert(stage == MESA_SHADER_GEOMETRY);
1520
1521   struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1522
1523   if (gs_compile->control_data_header_size_bits > 0) {
1524      emit_gs_control_data_bits(this->final_gs_vertex_count);
1525   }
1526
1527   const fs_builder abld = bld.annotate("thread end");
1528   fs_inst *inst;
1529
1530   if (gs_prog_data->static_vertex_count != -1) {
1531      foreach_in_list_reverse(fs_inst, prev, &this->instructions) {
1532         if (prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8 ||
1533             prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_MASKED ||
1534             prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT ||
1535             prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT) {
1536            prev->eot = true;
1537
1538            /* Delete now dead instructions. */
1539            foreach_in_list_reverse_safe(exec_node, dead, &this->instructions) {
1540               if (dead == prev)
1541                  break;
1542               dead->remove();
1543            }
1544            return;
1545         } else if (prev->is_control_flow() || prev->has_side_effects()) {
1546            break;
1547         }
1548      }
1549      fs_reg hdr = abld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1550      abld.MOV(hdr, fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD)));
1551      inst = abld.emit(SHADER_OPCODE_URB_WRITE_SIMD8, reg_undef, hdr);
1552      inst->mlen = 1;
1553   } else {
1554      fs_reg payload = abld.vgrf(BRW_REGISTER_TYPE_UD, 2);
1555      fs_reg *sources = ralloc_array(mem_ctx, fs_reg, 2);
1556      sources[0] = fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
1557      sources[1] = this->final_gs_vertex_count;
1558      abld.LOAD_PAYLOAD(payload, sources, 2, 2);
1559      inst = abld.emit(SHADER_OPCODE_URB_WRITE_SIMD8, reg_undef, payload);
1560      inst->mlen = 2;
1561   }
1562   inst->eot = true;
1563   inst->offset = 0;
1564}
1565
1566void
1567fs_visitor::assign_curb_setup()
1568{
1569   unsigned uniform_push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
1570
1571   unsigned ubo_push_length = 0;
1572   unsigned ubo_push_start[4];
1573   for (int i = 0; i < 4; i++) {
1574      ubo_push_start[i] = 8 * (ubo_push_length + uniform_push_length);
1575      ubo_push_length += stage_prog_data->ubo_ranges[i].length;
1576   }
1577
1578   prog_data->curb_read_length = uniform_push_length + ubo_push_length;
1579
1580   /* Map the offsets in the UNIFORM file to fixed HW regs. */
1581   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1582      for (unsigned int i = 0; i < inst->sources; i++) {
1583	 if (inst->src[i].file == UNIFORM) {
1584            int uniform_nr = inst->src[i].nr + inst->src[i].offset / 4;
1585            int constant_nr;
1586            if (inst->src[i].nr >= UBO_START) {
1587               /* constant_nr is in 32-bit units, the rest are in bytes */
1588               constant_nr = ubo_push_start[inst->src[i].nr - UBO_START] +
1589                             inst->src[i].offset / 4;
1590            } else if (uniform_nr >= 0 && uniform_nr < (int) uniforms) {
1591               constant_nr = push_constant_loc[uniform_nr];
1592            } else {
1593               /* Section 5.11 of the OpenGL 4.1 spec says:
1594                * "Out-of-bounds reads return undefined values, which include
1595                *  values from other variables of the active program or zero."
1596                * Just return the first push constant.
1597                */
1598               constant_nr = 0;
1599            }
1600
1601	    struct brw_reg brw_reg = brw_vec1_grf(payload.num_regs +
1602						  constant_nr / 8,
1603						  constant_nr % 8);
1604            brw_reg.abs = inst->src[i].abs;
1605            brw_reg.negate = inst->src[i].negate;
1606
1607            assert(inst->src[i].stride == 0);
1608            inst->src[i] = byte_offset(
1609               retype(brw_reg, inst->src[i].type),
1610               inst->src[i].offset % 4);
1611	 }
1612      }
1613   }
1614
1615   /* This may be updated in assign_urb_setup or assign_vs_urb_setup. */
1616   this->first_non_payload_grf = payload.num_regs + prog_data->curb_read_length;
1617}
1618
1619void
1620fs_visitor::calculate_urb_setup()
1621{
1622   assert(stage == MESA_SHADER_FRAGMENT);
1623   struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
1624   brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1625
1626   memset(prog_data->urb_setup, -1,
1627          sizeof(prog_data->urb_setup[0]) * VARYING_SLOT_MAX);
1628
1629   int urb_next = 0;
1630   /* Figure out where each of the incoming setup attributes lands. */
1631   if (devinfo->gen >= 6) {
1632      if (util_bitcount64(nir->info.inputs_read &
1633                            BRW_FS_VARYING_INPUT_MASK) <= 16) {
1634         /* The SF/SBE pipeline stage can do arbitrary rearrangement of the
1635          * first 16 varying inputs, so we can put them wherever we want.
1636          * Just put them in order.
1637          *
1638          * This is useful because it means that (a) inputs not used by the
1639          * fragment shader won't take up valuable register space, and (b) we
1640          * won't have to recompile the fragment shader if it gets paired with
1641          * a different vertex (or geometry) shader.
1642          */
1643         for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1644            if (nir->info.inputs_read & BRW_FS_VARYING_INPUT_MASK &
1645                BITFIELD64_BIT(i)) {
1646               prog_data->urb_setup[i] = urb_next++;
1647            }
1648         }
1649      } else {
1650         /* We have enough input varyings that the SF/SBE pipeline stage can't
1651          * arbitrarily rearrange them to suit our whim; we have to put them
1652          * in an order that matches the output of the previous pipeline stage
1653          * (geometry or vertex shader).
1654          */
1655         struct brw_vue_map prev_stage_vue_map;
1656         brw_compute_vue_map(devinfo, &prev_stage_vue_map,
1657                             key->input_slots_valid,
1658                             nir->info.separate_shader);
1659
1660         int first_slot =
1661            brw_compute_first_urb_slot_required(nir->info.inputs_read,
1662                                                &prev_stage_vue_map);
1663
1664         assert(prev_stage_vue_map.num_slots <= first_slot + 32);
1665         for (int slot = first_slot; slot < prev_stage_vue_map.num_slots;
1666              slot++) {
1667            int varying = prev_stage_vue_map.slot_to_varying[slot];
1668            if (varying != BRW_VARYING_SLOT_PAD &&
1669                (nir->info.inputs_read & BRW_FS_VARYING_INPUT_MASK &
1670                 BITFIELD64_BIT(varying))) {
1671               prog_data->urb_setup[varying] = slot - first_slot;
1672            }
1673         }
1674         urb_next = prev_stage_vue_map.num_slots - first_slot;
1675      }
1676   } else {
1677      /* FINISHME: The sf doesn't map VS->FS inputs for us very well. */
1678      for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1679         /* Point size is packed into the header, not as a general attribute */
1680         if (i == VARYING_SLOT_PSIZ)
1681            continue;
1682
1683	 if (key->input_slots_valid & BITFIELD64_BIT(i)) {
1684	    /* The back color slot is skipped when the front color is
1685	     * also written to.  In addition, some slots can be
1686	     * written in the vertex shader and not read in the
1687	     * fragment shader.  So the register number must always be
1688	     * incremented, mapped or not.
1689	     */
1690	    if (_mesa_varying_slot_in_fs((gl_varying_slot) i))
1691	       prog_data->urb_setup[i] = urb_next;
1692            urb_next++;
1693	 }
1694      }
1695
1696      /*
1697       * It's a FS only attribute, and we did interpolation for this attribute
1698       * in SF thread. So, count it here, too.
1699       *
1700       * See compile_sf_prog() for more info.
1701       */
1702      if (nir->info.inputs_read & BITFIELD64_BIT(VARYING_SLOT_PNTC))
1703         prog_data->urb_setup[VARYING_SLOT_PNTC] = urb_next++;
1704   }
1705
1706   prog_data->num_varying_inputs = urb_next;
1707}
1708
1709void
1710fs_visitor::assign_urb_setup()
1711{
1712   assert(stage == MESA_SHADER_FRAGMENT);
1713   struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
1714
1715   int urb_start = payload.num_regs + prog_data->base.curb_read_length;
1716
1717   /* Offset all the urb_setup[] index by the actual position of the
1718    * setup regs, now that the location of the constants has been chosen.
1719    */
1720   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1721      for (int i = 0; i < inst->sources; i++) {
1722         if (inst->src[i].file == ATTR) {
1723            /* ATTR regs in the FS are in units of logical scalar inputs each
1724             * of which consumes half of a GRF register.
1725             */
1726            assert(inst->src[i].offset < REG_SIZE / 2);
1727            const unsigned grf = urb_start + inst->src[i].nr / 2;
1728            const unsigned offset = (inst->src[i].nr % 2) * (REG_SIZE / 2) +
1729                                    inst->src[i].offset;
1730            const unsigned width = inst->src[i].stride == 0 ?
1731                                   1 : MIN2(inst->exec_size, 8);
1732            struct brw_reg reg = stride(
1733               byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
1734                           offset),
1735               width * inst->src[i].stride,
1736               width, inst->src[i].stride);
1737            reg.abs = inst->src[i].abs;
1738            reg.negate = inst->src[i].negate;
1739            inst->src[i] = reg;
1740         }
1741      }
1742   }
1743
1744   /* Each attribute is 4 setup channels, each of which is half a reg. */
1745   this->first_non_payload_grf += prog_data->num_varying_inputs * 2;
1746}
1747
1748void
1749fs_visitor::convert_attr_sources_to_hw_regs(fs_inst *inst)
1750{
1751   for (int i = 0; i < inst->sources; i++) {
1752      if (inst->src[i].file == ATTR) {
1753         int grf = payload.num_regs +
1754                   prog_data->curb_read_length +
1755                   inst->src[i].nr +
1756                   inst->src[i].offset / REG_SIZE;
1757
1758         /* As explained at brw_reg_from_fs_reg, From the Haswell PRM:
1759          *
1760          * VertStride must be used to cross GRF register boundaries. This
1761          * rule implies that elements within a 'Width' cannot cross GRF
1762          * boundaries.
1763          *
1764          * So, for registers that are large enough, we have to split the exec
1765          * size in two and trust the compression state to sort it out.
1766          */
1767         unsigned total_size = inst->exec_size *
1768                               inst->src[i].stride *
1769                               type_sz(inst->src[i].type);
1770
1771         assert(total_size <= 2 * REG_SIZE);
1772         const unsigned exec_size =
1773            (total_size <= REG_SIZE) ? inst->exec_size : inst->exec_size / 2;
1774
1775         unsigned width = inst->src[i].stride == 0 ? 1 : exec_size;
1776         struct brw_reg reg =
1777            stride(byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
1778                               inst->src[i].offset % REG_SIZE),
1779                   exec_size * inst->src[i].stride,
1780                   width, inst->src[i].stride);
1781         reg.abs = inst->src[i].abs;
1782         reg.negate = inst->src[i].negate;
1783
1784         inst->src[i] = reg;
1785      }
1786   }
1787}
1788
1789void
1790fs_visitor::assign_vs_urb_setup()
1791{
1792   struct brw_vs_prog_data *vs_prog_data = brw_vs_prog_data(prog_data);
1793
1794   assert(stage == MESA_SHADER_VERTEX);
1795
1796   /* Each attribute is 4 regs. */
1797   this->first_non_payload_grf += 4 * vs_prog_data->nr_attribute_slots;
1798
1799   assert(vs_prog_data->base.urb_read_length <= 15);
1800
1801   /* Rewrite all ATTR file references to the hw grf that they land in. */
1802   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1803      convert_attr_sources_to_hw_regs(inst);
1804   }
1805}
1806
1807void
1808fs_visitor::assign_tcs_single_patch_urb_setup()
1809{
1810   assert(stage == MESA_SHADER_TESS_CTRL);
1811
1812   /* Rewrite all ATTR file references to HW_REGs. */
1813   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1814      convert_attr_sources_to_hw_regs(inst);
1815   }
1816}
1817
1818void
1819fs_visitor::assign_tes_urb_setup()
1820{
1821   assert(stage == MESA_SHADER_TESS_EVAL);
1822
1823   struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
1824
1825   first_non_payload_grf += 8 * vue_prog_data->urb_read_length;
1826
1827   /* Rewrite all ATTR file references to HW_REGs. */
1828   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1829      convert_attr_sources_to_hw_regs(inst);
1830   }
1831}
1832
1833void
1834fs_visitor::assign_gs_urb_setup()
1835{
1836   assert(stage == MESA_SHADER_GEOMETRY);
1837
1838   struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
1839
1840   first_non_payload_grf +=
1841      8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in;
1842
1843   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1844      /* Rewrite all ATTR file references to GRFs. */
1845      convert_attr_sources_to_hw_regs(inst);
1846   }
1847}
1848
1849
1850/**
1851 * Split large virtual GRFs into separate components if we can.
1852 *
1853 * This is mostly duplicated with what brw_fs_vector_splitting does,
1854 * but that's really conservative because it's afraid of doing
1855 * splitting that doesn't result in real progress after the rest of
1856 * the optimization phases, which would cause infinite looping in
1857 * optimization.  We can do it once here, safely.  This also has the
1858 * opportunity to split interpolated values, or maybe even uniforms,
1859 * which we don't have at the IR level.
1860 *
1861 * We want to split, because virtual GRFs are what we register
1862 * allocate and spill (due to contiguousness requirements for some
1863 * instructions), and they're what we naturally generate in the
1864 * codegen process, but most virtual GRFs don't actually need to be
1865 * contiguous sets of GRFs.  If we split, we'll end up with reduced
1866 * live intervals and better dead code elimination and coalescing.
1867 */
1868void
1869fs_visitor::split_virtual_grfs()
1870{
1871   /* Compact the register file so we eliminate dead vgrfs.  This
1872    * only defines split points for live registers, so if we have
1873    * too large dead registers they will hit assertions later.
1874    */
1875   compact_virtual_grfs();
1876
1877   int num_vars = this->alloc.count;
1878
1879   /* Count the total number of registers */
1880   int reg_count = 0;
1881   int vgrf_to_reg[num_vars];
1882   for (int i = 0; i < num_vars; i++) {
1883      vgrf_to_reg[i] = reg_count;
1884      reg_count += alloc.sizes[i];
1885   }
1886
1887   /* An array of "split points".  For each register slot, this indicates
1888    * if this slot can be separated from the previous slot.  Every time an
1889    * instruction uses multiple elements of a register (as a source or
1890    * destination), we mark the used slots as inseparable.  Then we go
1891    * through and split the registers into the smallest pieces we can.
1892    */
1893   bool *split_points = new bool[reg_count];
1894   memset(split_points, 0, reg_count * sizeof(*split_points));
1895
1896   /* Mark all used registers as fully splittable */
1897   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1898      if (inst->dst.file == VGRF) {
1899         int reg = vgrf_to_reg[inst->dst.nr];
1900         for (unsigned j = 1; j < this->alloc.sizes[inst->dst.nr]; j++)
1901            split_points[reg + j] = true;
1902      }
1903
1904      for (int i = 0; i < inst->sources; i++) {
1905         if (inst->src[i].file == VGRF) {
1906            int reg = vgrf_to_reg[inst->src[i].nr];
1907            for (unsigned j = 1; j < this->alloc.sizes[inst->src[i].nr]; j++)
1908               split_points[reg + j] = true;
1909         }
1910      }
1911   }
1912
1913   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1914      if (inst->dst.file == VGRF) {
1915         int reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
1916         for (unsigned j = 1; j < regs_written(inst); j++)
1917            split_points[reg + j] = false;
1918      }
1919      for (int i = 0; i < inst->sources; i++) {
1920         if (inst->src[i].file == VGRF) {
1921            int reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
1922            for (unsigned j = 1; j < regs_read(inst, i); j++)
1923               split_points[reg + j] = false;
1924         }
1925      }
1926   }
1927
1928   int *new_virtual_grf = new int[reg_count];
1929   int *new_reg_offset = new int[reg_count];
1930
1931   int reg = 0;
1932   for (int i = 0; i < num_vars; i++) {
1933      /* The first one should always be 0 as a quick sanity check. */
1934      assert(split_points[reg] == false);
1935
1936      /* j = 0 case */
1937      new_reg_offset[reg] = 0;
1938      reg++;
1939      int offset = 1;
1940
1941      /* j > 0 case */
1942      for (unsigned j = 1; j < alloc.sizes[i]; j++) {
1943         /* If this is a split point, reset the offset to 0 and allocate a
1944          * new virtual GRF for the previous offset many registers
1945          */
1946         if (split_points[reg]) {
1947            assert(offset <= MAX_VGRF_SIZE);
1948            int grf = alloc.allocate(offset);
1949            for (int k = reg - offset; k < reg; k++)
1950               new_virtual_grf[k] = grf;
1951            offset = 0;
1952         }
1953         new_reg_offset[reg] = offset;
1954         offset++;
1955         reg++;
1956      }
1957
1958      /* The last one gets the original register number */
1959      assert(offset <= MAX_VGRF_SIZE);
1960      alloc.sizes[i] = offset;
1961      for (int k = reg - offset; k < reg; k++)
1962         new_virtual_grf[k] = i;
1963   }
1964   assert(reg == reg_count);
1965
1966   foreach_block_and_inst(block, fs_inst, inst, cfg) {
1967      if (inst->dst.file == VGRF) {
1968         reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
1969         inst->dst.nr = new_virtual_grf[reg];
1970         inst->dst.offset = new_reg_offset[reg] * REG_SIZE +
1971                            inst->dst.offset % REG_SIZE;
1972         assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1973      }
1974      for (int i = 0; i < inst->sources; i++) {
1975	 if (inst->src[i].file == VGRF) {
1976            reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
1977            inst->src[i].nr = new_virtual_grf[reg];
1978            inst->src[i].offset = new_reg_offset[reg] * REG_SIZE +
1979                                  inst->src[i].offset % REG_SIZE;
1980            assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1981         }
1982      }
1983   }
1984   invalidate_live_intervals();
1985
1986   delete[] split_points;
1987   delete[] new_virtual_grf;
1988   delete[] new_reg_offset;
1989}
1990
1991/**
1992 * Remove unused virtual GRFs and compact the virtual_grf_* arrays.
1993 *
1994 * During code generation, we create tons of temporary variables, many of
1995 * which get immediately killed and are never used again.  Yet, in later
1996 * optimization and analysis passes, such as compute_live_intervals, we need
1997 * to loop over all the virtual GRFs.  Compacting them can save a lot of
1998 * overhead.
1999 */
2000bool
2001fs_visitor::compact_virtual_grfs()
2002{
2003   bool progress = false;
2004   int *remap_table = new int[this->alloc.count];
2005   memset(remap_table, -1, this->alloc.count * sizeof(int));
2006
2007   /* Mark which virtual GRFs are used. */
2008   foreach_block_and_inst(block, const fs_inst, inst, cfg) {
2009      if (inst->dst.file == VGRF)
2010         remap_table[inst->dst.nr] = 0;
2011
2012      for (int i = 0; i < inst->sources; i++) {
2013         if (inst->src[i].file == VGRF)
2014            remap_table[inst->src[i].nr] = 0;
2015      }
2016   }
2017
2018   /* Compact the GRF arrays. */
2019   int new_index = 0;
2020   for (unsigned i = 0; i < this->alloc.count; i++) {
2021      if (remap_table[i] == -1) {
2022         /* We just found an unused register.  This means that we are
2023          * actually going to compact something.
2024          */
2025         progress = true;
2026      } else {
2027         remap_table[i] = new_index;
2028         alloc.sizes[new_index] = alloc.sizes[i];
2029         invalidate_live_intervals();
2030         ++new_index;
2031      }
2032   }
2033
2034   this->alloc.count = new_index;
2035
2036   /* Patch all the instructions to use the newly renumbered registers */
2037   foreach_block_and_inst(block, fs_inst, inst, cfg) {
2038      if (inst->dst.file == VGRF)
2039         inst->dst.nr = remap_table[inst->dst.nr];
2040
2041      for (int i = 0; i < inst->sources; i++) {
2042         if (inst->src[i].file == VGRF)
2043            inst->src[i].nr = remap_table[inst->src[i].nr];
2044      }
2045   }
2046
2047   /* Patch all the references to delta_xy, since they're used in register
2048    * allocation.  If they're unused, switch them to BAD_FILE so we don't
2049    * think some random VGRF is delta_xy.
2050    */
2051   for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2052      if (delta_xy[i].file == VGRF) {
2053         if (remap_table[delta_xy[i].nr] != -1) {
2054            delta_xy[i].nr = remap_table[delta_xy[i].nr];
2055         } else {
2056            delta_xy[i].file = BAD_FILE;
2057         }
2058      }
2059   }
2060
2061   delete[] remap_table;
2062
2063   return progress;
2064}
2065
2066static int
2067get_subgroup_id_param_index(const brw_stage_prog_data *prog_data)
2068{
2069   if (prog_data->nr_params == 0)
2070      return -1;
2071
2072   /* The local thread id is always the last parameter in the list */
2073   uint32_t last_param = prog_data->param[prog_data->nr_params - 1];
2074   if (last_param == BRW_PARAM_BUILTIN_SUBGROUP_ID)
2075      return prog_data->nr_params - 1;
2076
2077   return -1;
2078}
2079
2080/**
2081 * Struct for handling complex alignments.
2082 *
2083 * A complex alignment is stored as multiplier and an offset.  A value is
2084 * considered to be aligned if it is {offset} larger than a multiple of {mul}.
2085 * For instance, with an alignment of {8, 2}, cplx_align_apply would do the
2086 * following:
2087 *
2088 *  N  | cplx_align_apply({8, 2}, N)
2089 * ----+-----------------------------
2090 *  4  | 6
2091 *  6  | 6
2092 *  8  | 14
2093 *  10 | 14
2094 *  12 | 14
2095 *  14 | 14
2096 *  16 | 22
2097 */
2098struct cplx_align {
2099   unsigned mul:4;
2100   unsigned offset:4;
2101};
2102
2103#define CPLX_ALIGN_MAX_MUL 8
2104
2105static void
2106cplx_align_assert_sane(struct cplx_align a)
2107{
2108   assert(a.mul > 0 && util_is_power_of_two_nonzero(a.mul));
2109   assert(a.offset < a.mul);
2110}
2111
2112/**
2113 * Combines two alignments to produce a least multiple of sorts.
2114 *
2115 * The returned alignment is the smallest (in terms of multiplier) such that
2116 * anything aligned to both a and b will be aligned to the new alignment.
2117 * This function will assert-fail if a and b are not compatible, i.e. if the
2118 * offset parameters are such that no common alignment is possible.
2119 */
2120static struct cplx_align
2121cplx_align_combine(struct cplx_align a, struct cplx_align b)
2122{
2123   cplx_align_assert_sane(a);
2124   cplx_align_assert_sane(b);
2125
2126   /* Assert that the alignments agree. */
2127   assert((a.offset & (b.mul - 1)) == (b.offset & (a.mul - 1)));
2128
2129   return a.mul > b.mul ? a : b;
2130}
2131
2132/**
2133 * Apply a complex alignment
2134 *
2135 * This function will return the smallest number greater than or equal to
2136 * offset that is aligned to align.
2137 */
2138static unsigned
2139cplx_align_apply(struct cplx_align align, unsigned offset)
2140{
2141   return ALIGN(offset - align.offset, align.mul) + align.offset;
2142}
2143
2144#define UNIFORM_SLOT_SIZE 4
2145
2146struct uniform_slot_info {
2147   /** True if the given uniform slot is live */
2148   unsigned is_live:1;
2149
2150   /** True if this slot and the next slot must remain contiguous */
2151   unsigned contiguous:1;
2152
2153   struct cplx_align align;
2154};
2155
2156static void
2157mark_uniform_slots_read(struct uniform_slot_info *slots,
2158                        unsigned num_slots, unsigned alignment)
2159{
2160   assert(alignment > 0 && util_is_power_of_two_nonzero(alignment));
2161   assert(alignment <= CPLX_ALIGN_MAX_MUL);
2162
2163   /* We can't align a slot to anything less than the slot size */
2164   alignment = MAX2(alignment, UNIFORM_SLOT_SIZE);
2165
2166   struct cplx_align align = {alignment, 0};
2167   cplx_align_assert_sane(align);
2168
2169   for (unsigned i = 0; i < num_slots; i++) {
2170      slots[i].is_live = true;
2171      if (i < num_slots - 1)
2172         slots[i].contiguous = true;
2173
2174      align.offset = (i * UNIFORM_SLOT_SIZE) & (align.mul - 1);
2175      if (slots[i].align.mul == 0) {
2176         slots[i].align = align;
2177      } else {
2178         slots[i].align = cplx_align_combine(slots[i].align, align);
2179      }
2180   }
2181}
2182
2183/**
2184 * Assign UNIFORM file registers to either push constants or pull constants.
2185 *
2186 * We allow a fragment shader to have more than the specified minimum
2187 * maximum number of fragment shader uniform components (64).  If
2188 * there are too many of these, they'd fill up all of register space.
2189 * So, this will push some of them out to the pull constant buffer and
2190 * update the program to load them.
2191 */
2192void
2193fs_visitor::assign_constant_locations()
2194{
2195   /* Only the first compile gets to decide on locations. */
2196   if (push_constant_loc) {
2197      assert(pull_constant_loc);
2198      return;
2199   }
2200
2201   struct uniform_slot_info slots[uniforms];
2202   memset(slots, 0, sizeof(slots));
2203
2204   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2205      for (int i = 0 ; i < inst->sources; i++) {
2206         if (inst->src[i].file != UNIFORM)
2207            continue;
2208
2209         /* NIR tightly packs things so the uniform number might not be
2210          * aligned (if we have a double right after a float, for instance).
2211          * This is fine because the process of re-arranging them will ensure
2212          * that things are properly aligned.  The offset into that uniform,
2213          * however, must be aligned.
2214          *
2215          * In Vulkan, we have explicit offsets but everything is crammed
2216          * into a single "variable" so inst->src[i].nr will always be 0.
2217          * Everything will be properly aligned relative to that one base.
2218          */
2219         assert(inst->src[i].offset % type_sz(inst->src[i].type) == 0);
2220
2221         unsigned u = inst->src[i].nr +
2222                      inst->src[i].offset / UNIFORM_SLOT_SIZE;
2223
2224         if (u >= uniforms)
2225            continue;
2226
2227         unsigned slots_read;
2228         if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0) {
2229            slots_read = DIV_ROUND_UP(inst->src[2].ud, UNIFORM_SLOT_SIZE);
2230         } else {
2231            unsigned bytes_read = inst->components_read(i) *
2232                                  type_sz(inst->src[i].type);
2233            slots_read = DIV_ROUND_UP(bytes_read, UNIFORM_SLOT_SIZE);
2234         }
2235
2236         assert(u + slots_read <= uniforms);
2237         mark_uniform_slots_read(&slots[u], slots_read,
2238                                 type_sz(inst->src[i].type));
2239      }
2240   }
2241
2242   int subgroup_id_index = get_subgroup_id_param_index(stage_prog_data);
2243
2244   /* Only allow 16 registers (128 uniform components) as push constants.
2245    *
2246    * Just demote the end of the list.  We could probably do better
2247    * here, demoting things that are rarely used in the program first.
2248    *
2249    * If changing this value, note the limitation about total_regs in
2250    * brw_curbe.c.
2251    */
2252   unsigned int max_push_components = 16 * 8;
2253   if (subgroup_id_index >= 0)
2254      max_push_components--; /* Save a slot for the thread ID */
2255
2256   /* We push small arrays, but no bigger than 16 floats.  This is big enough
2257    * for a vec4 but hopefully not large enough to push out other stuff.  We
2258    * should probably use a better heuristic at some point.
2259    */
2260   const unsigned int max_chunk_size = 16;
2261
2262   unsigned int num_push_constants = 0;
2263   unsigned int num_pull_constants = 0;
2264
2265   push_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2266   pull_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2267
2268   /* Default to -1 meaning no location */
2269   memset(push_constant_loc, -1, uniforms * sizeof(*push_constant_loc));
2270   memset(pull_constant_loc, -1, uniforms * sizeof(*pull_constant_loc));
2271
2272   int chunk_start = -1;
2273   struct cplx_align align;
2274   for (unsigned u = 0; u < uniforms; u++) {
2275      if (!slots[u].is_live) {
2276         assert(chunk_start == -1);
2277         continue;
2278      }
2279
2280      /* Skip subgroup_id_index to put it in the last push register. */
2281      if (subgroup_id_index == (int)u)
2282         continue;
2283
2284      if (chunk_start == -1) {
2285         chunk_start = u;
2286         align = slots[u].align;
2287      } else {
2288         /* Offset into the chunk */
2289         unsigned chunk_offset = (u - chunk_start) * UNIFORM_SLOT_SIZE;
2290
2291         /* Shift the slot alignment down by the chunk offset so it is
2292          * comparable with the base chunk alignment.
2293          */
2294         struct cplx_align slot_align = slots[u].align;
2295         slot_align.offset =
2296            (slot_align.offset - chunk_offset) & (align.mul - 1);
2297
2298         align = cplx_align_combine(align, slot_align);
2299      }
2300
2301      /* Sanity check the alignment */
2302      cplx_align_assert_sane(align);
2303
2304      if (slots[u].contiguous)
2305         continue;
2306
2307      /* Adjust the alignment to be in terms of slots, not bytes */
2308      assert((align.mul & (UNIFORM_SLOT_SIZE - 1)) == 0);
2309      assert((align.offset & (UNIFORM_SLOT_SIZE - 1)) == 0);
2310      align.mul /= UNIFORM_SLOT_SIZE;
2311      align.offset /= UNIFORM_SLOT_SIZE;
2312
2313      unsigned push_start_align = cplx_align_apply(align, num_push_constants);
2314      unsigned chunk_size = u - chunk_start + 1;
2315      if ((!compiler->supports_pull_constants && u < UBO_START) ||
2316          (chunk_size < max_chunk_size &&
2317           push_start_align + chunk_size <= max_push_components)) {
2318         /* Align up the number of push constants */
2319         num_push_constants = push_start_align;
2320         for (unsigned i = 0; i < chunk_size; i++)
2321            push_constant_loc[chunk_start + i] = num_push_constants++;
2322      } else {
2323         /* We need to pull this one */
2324         num_pull_constants = cplx_align_apply(align, num_pull_constants);
2325         for (unsigned i = 0; i < chunk_size; i++)
2326            pull_constant_loc[chunk_start + i] = num_pull_constants++;
2327      }
2328
2329      /* Reset the chunk and start again */
2330      chunk_start = -1;
2331   }
2332
2333   /* Add the CS local thread ID uniform at the end of the push constants */
2334   if (subgroup_id_index >= 0)
2335      push_constant_loc[subgroup_id_index] = num_push_constants++;
2336
2337   /* As the uniforms are going to be reordered, stash the old array and
2338    * create two new arrays for push/pull params.
2339    */
2340   uint32_t *param = stage_prog_data->param;
2341   stage_prog_data->nr_params = num_push_constants;
2342   if (num_push_constants) {
2343      stage_prog_data->param = rzalloc_array(mem_ctx, uint32_t,
2344                                             num_push_constants);
2345   } else {
2346      stage_prog_data->param = NULL;
2347   }
2348   assert(stage_prog_data->nr_pull_params == 0);
2349   assert(stage_prog_data->pull_param == NULL);
2350   if (num_pull_constants > 0) {
2351      stage_prog_data->nr_pull_params = num_pull_constants;
2352      stage_prog_data->pull_param = rzalloc_array(mem_ctx, uint32_t,
2353                                                  num_pull_constants);
2354   }
2355
2356   /* Now that we know how many regular uniforms we'll push, reduce the
2357    * UBO push ranges so we don't exceed the 3DSTATE_CONSTANT limits.
2358    */
2359   unsigned push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
2360   for (int i = 0; i < 4; i++) {
2361      struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2362
2363      if (push_length + range->length > 64)
2364         range->length = 64 - push_length;
2365
2366      push_length += range->length;
2367   }
2368   assert(push_length <= 64);
2369
2370   /* Up until now, the param[] array has been indexed by reg + offset
2371    * of UNIFORM registers.  Move pull constants into pull_param[] and
2372    * condense param[] to only contain the uniforms we chose to push.
2373    *
2374    * NOTE: Because we are condensing the params[] array, we know that
2375    * push_constant_loc[i] <= i and we can do it in one smooth loop without
2376    * having to make a copy.
2377    */
2378   for (unsigned int i = 0; i < uniforms; i++) {
2379      uint32_t value = param[i];
2380      if (pull_constant_loc[i] != -1) {
2381         stage_prog_data->pull_param[pull_constant_loc[i]] = value;
2382      } else if (push_constant_loc[i] != -1) {
2383         stage_prog_data->param[push_constant_loc[i]] = value;
2384      }
2385   }
2386   ralloc_free(param);
2387}
2388
2389bool
2390fs_visitor::get_pull_locs(const fs_reg &src,
2391                          unsigned *out_surf_index,
2392                          unsigned *out_pull_index)
2393{
2394   assert(src.file == UNIFORM);
2395
2396   if (src.nr >= UBO_START) {
2397      const struct brw_ubo_range *range =
2398         &prog_data->ubo_ranges[src.nr - UBO_START];
2399
2400      /* If this access is in our (reduced) range, use the push data. */
2401      if (src.offset / 32 < range->length)
2402         return false;
2403
2404      *out_surf_index = prog_data->binding_table.ubo_start + range->block;
2405      *out_pull_index = (32 * range->start + src.offset) / 4;
2406      return true;
2407   }
2408
2409   const unsigned location = src.nr + src.offset / 4;
2410
2411   if (location < uniforms && pull_constant_loc[location] != -1) {
2412      /* A regular uniform push constant */
2413      *out_surf_index = stage_prog_data->binding_table.pull_constants_start;
2414      *out_pull_index = pull_constant_loc[location];
2415      return true;
2416   }
2417
2418   return false;
2419}
2420
2421/**
2422 * Replace UNIFORM register file access with either UNIFORM_PULL_CONSTANT_LOAD
2423 * or VARYING_PULL_CONSTANT_LOAD instructions which load values into VGRFs.
2424 */
2425void
2426fs_visitor::lower_constant_loads()
2427{
2428   unsigned index, pull_index;
2429
2430   foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2431      /* Set up the annotation tracking for new generated instructions. */
2432      const fs_builder ibld(this, block, inst);
2433
2434      for (int i = 0; i < inst->sources; i++) {
2435	 if (inst->src[i].file != UNIFORM)
2436	    continue;
2437
2438         /* We'll handle this case later */
2439         if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0)
2440            continue;
2441
2442         if (!get_pull_locs(inst->src[i], &index, &pull_index))
2443	    continue;
2444
2445         assert(inst->src[i].stride == 0);
2446
2447         const unsigned block_sz = 64; /* Fetch one cacheline at a time. */
2448         const fs_builder ubld = ibld.exec_all().group(block_sz / 4, 0);
2449         const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
2450         const unsigned base = pull_index * 4;
2451
2452         ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
2453                   dst, brw_imm_ud(index), brw_imm_ud(base & ~(block_sz - 1)));
2454
2455         /* Rewrite the instruction to use the temporary VGRF. */
2456         inst->src[i].file = VGRF;
2457         inst->src[i].nr = dst.nr;
2458         inst->src[i].offset = (base & (block_sz - 1)) +
2459                               inst->src[i].offset % 4;
2460      }
2461
2462      if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
2463          inst->src[0].file == UNIFORM) {
2464
2465         if (!get_pull_locs(inst->src[0], &index, &pull_index))
2466            continue;
2467
2468         VARYING_PULL_CONSTANT_LOAD(ibld, inst->dst,
2469                                    brw_imm_ud(index),
2470                                    inst->src[1],
2471                                    pull_index * 4);
2472         inst->remove(block);
2473      }
2474   }
2475   invalidate_live_intervals();
2476}
2477
2478bool
2479fs_visitor::opt_algebraic()
2480{
2481   bool progress = false;
2482
2483   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2484      switch (inst->opcode) {
2485      case BRW_OPCODE_MOV:
2486         if (!devinfo->has_64bit_types &&
2487             (inst->dst.type == BRW_REGISTER_TYPE_DF ||
2488              inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2489              inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2490            assert(inst->dst.type == inst->src[0].type);
2491            assert(!inst->saturate);
2492            assert(!inst->src[0].abs);
2493            assert(!inst->src[0].negate);
2494            const brw::fs_builder ibld(this, block, inst);
2495
2496            if (inst->src[0].file == IMM) {
2497               ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2498                        brw_imm_ud(inst->src[0].u64 >> 32));
2499               ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2500                        brw_imm_ud(inst->src[0].u64));
2501            } else {
2502               ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2503                        subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1));
2504               ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2505                        subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0));
2506            }
2507
2508            inst->remove(block);
2509            progress = true;
2510         }
2511
2512         if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2513              inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2514             inst->dst.is_null() &&
2515             (inst->src[0].abs || inst->src[0].negate)) {
2516            inst->src[0].abs = false;
2517            inst->src[0].negate = false;
2518            progress = true;
2519            break;
2520         }
2521
2522         if (inst->src[0].file != IMM)
2523            break;
2524
2525         if (inst->saturate) {
2526            /* Full mixed-type saturates don't happen.  However, we can end up
2527             * with things like:
2528             *
2529             *    mov.sat(8) g21<1>DF       -1F
2530             *
2531             * Other mixed-size-but-same-base-type cases may also be possible.
2532             */
2533            if (inst->dst.type != inst->src[0].type &&
2534                inst->dst.type != BRW_REGISTER_TYPE_DF &&
2535                inst->src[0].type != BRW_REGISTER_TYPE_F)
2536               assert(!"unimplemented: saturate mixed types");
2537
2538            if (brw_saturate_immediate(inst->src[0].type,
2539                                       &inst->src[0].as_brw_reg())) {
2540               inst->saturate = false;
2541               progress = true;
2542            }
2543         }
2544         break;
2545
2546      case BRW_OPCODE_MUL:
2547         if (inst->src[1].file != IMM)
2548            continue;
2549
2550         /* a * 1.0 = a */
2551         if (inst->src[1].is_one()) {
2552            inst->opcode = BRW_OPCODE_MOV;
2553            inst->src[1] = reg_undef;
2554            progress = true;
2555            break;
2556         }
2557
2558         /* a * -1.0 = -a */
2559         if (inst->src[1].is_negative_one()) {
2560            inst->opcode = BRW_OPCODE_MOV;
2561            inst->src[0].negate = !inst->src[0].negate;
2562            inst->src[1] = reg_undef;
2563            progress = true;
2564            break;
2565         }
2566
2567         if (inst->src[0].file == IMM) {
2568            assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2569            inst->opcode = BRW_OPCODE_MOV;
2570            inst->src[0].f *= inst->src[1].f;
2571            inst->src[1] = reg_undef;
2572            progress = true;
2573            break;
2574         }
2575         break;
2576      case BRW_OPCODE_ADD:
2577         if (inst->src[1].file != IMM)
2578            continue;
2579
2580         if (inst->src[0].file == IMM) {
2581            assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2582            inst->opcode = BRW_OPCODE_MOV;
2583            inst->src[0].f += inst->src[1].f;
2584            inst->src[1] = reg_undef;
2585            progress = true;
2586            break;
2587         }
2588         break;
2589      case BRW_OPCODE_OR:
2590         if (inst->src[0].equals(inst->src[1]) ||
2591             inst->src[1].is_zero()) {
2592            /* On Gen8+, the OR instruction can have a source modifier that
2593             * performs logical not on the operand.  Cases of 'OR r0, ~r1, 0'
2594             * or 'OR r0, ~r1, ~r1' should become a NOT instead of a MOV.
2595             */
2596            if (inst->src[0].negate) {
2597               inst->opcode = BRW_OPCODE_NOT;
2598               inst->src[0].negate = false;
2599            } else {
2600               inst->opcode = BRW_OPCODE_MOV;
2601            }
2602            inst->src[1] = reg_undef;
2603            progress = true;
2604            break;
2605         }
2606         break;
2607      case BRW_OPCODE_CMP:
2608         if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2609              inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2610             inst->src[1].is_zero() &&
2611             (inst->src[0].abs || inst->src[0].negate)) {
2612            inst->src[0].abs = false;
2613            inst->src[0].negate = false;
2614            progress = true;
2615            break;
2616         }
2617         break;
2618      case BRW_OPCODE_SEL:
2619         if (!devinfo->has_64bit_types &&
2620             (inst->dst.type == BRW_REGISTER_TYPE_DF ||
2621              inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2622              inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2623            assert(inst->dst.type == inst->src[0].type);
2624            assert(!inst->saturate);
2625            assert(!inst->src[0].abs && !inst->src[0].negate);
2626            assert(!inst->src[1].abs && !inst->src[1].negate);
2627            const brw::fs_builder ibld(this, block, inst);
2628
2629            set_predicate(inst->predicate,
2630                          ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2631                                   subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
2632                                   subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0)));
2633            set_predicate(inst->predicate,
2634                          ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2635                                   subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1),
2636                                   subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 1)));
2637
2638            inst->remove(block);
2639            progress = true;
2640         }
2641         if (inst->src[0].equals(inst->src[1])) {
2642            inst->opcode = BRW_OPCODE_MOV;
2643            inst->src[1] = reg_undef;
2644            inst->predicate = BRW_PREDICATE_NONE;
2645            inst->predicate_inverse = false;
2646            progress = true;
2647         } else if (inst->saturate && inst->src[1].file == IMM) {
2648            switch (inst->conditional_mod) {
2649            case BRW_CONDITIONAL_LE:
2650            case BRW_CONDITIONAL_L:
2651               switch (inst->src[1].type) {
2652               case BRW_REGISTER_TYPE_F:
2653                  if (inst->src[1].f >= 1.0f) {
2654                     inst->opcode = BRW_OPCODE_MOV;
2655                     inst->src[1] = reg_undef;
2656                     inst->conditional_mod = BRW_CONDITIONAL_NONE;
2657                     progress = true;
2658                  }
2659                  break;
2660               default:
2661                  break;
2662               }
2663               break;
2664            case BRW_CONDITIONAL_GE:
2665            case BRW_CONDITIONAL_G:
2666               switch (inst->src[1].type) {
2667               case BRW_REGISTER_TYPE_F:
2668                  if (inst->src[1].f <= 0.0f) {
2669                     inst->opcode = BRW_OPCODE_MOV;
2670                     inst->src[1] = reg_undef;
2671                     inst->conditional_mod = BRW_CONDITIONAL_NONE;
2672                     progress = true;
2673                  }
2674                  break;
2675               default:
2676                  break;
2677               }
2678            default:
2679               break;
2680            }
2681         }
2682         break;
2683      case BRW_OPCODE_MAD:
2684         if (inst->src[0].type != BRW_REGISTER_TYPE_F ||
2685             inst->src[1].type != BRW_REGISTER_TYPE_F ||
2686             inst->src[2].type != BRW_REGISTER_TYPE_F)
2687            break;
2688         if (inst->src[1].is_one()) {
2689            inst->opcode = BRW_OPCODE_ADD;
2690            inst->src[1] = inst->src[2];
2691            inst->src[2] = reg_undef;
2692            progress = true;
2693         } else if (inst->src[2].is_one()) {
2694            inst->opcode = BRW_OPCODE_ADD;
2695            inst->src[2] = reg_undef;
2696            progress = true;
2697         }
2698         break;
2699      case SHADER_OPCODE_BROADCAST:
2700         if (is_uniform(inst->src[0])) {
2701            inst->opcode = BRW_OPCODE_MOV;
2702            inst->sources = 1;
2703            inst->force_writemask_all = true;
2704            progress = true;
2705         } else if (inst->src[1].file == IMM) {
2706            inst->opcode = BRW_OPCODE_MOV;
2707            /* It's possible that the selected component will be too large and
2708             * overflow the register.  This can happen if someone does a
2709             * readInvocation() from GLSL or SPIR-V and provides an OOB
2710             * invocationIndex.  If this happens and we some how manage
2711             * to constant fold it in and get here, then component() may cause
2712             * us to start reading outside of the VGRF which will lead to an
2713             * assert later.  Instead, just let it wrap around if it goes over
2714             * exec_size.
2715             */
2716            const unsigned comp = inst->src[1].ud & (inst->exec_size - 1);
2717            inst->src[0] = component(inst->src[0], comp);
2718            inst->sources = 1;
2719            inst->force_writemask_all = true;
2720            progress = true;
2721         }
2722         break;
2723
2724      case SHADER_OPCODE_SHUFFLE:
2725         if (is_uniform(inst->src[0])) {
2726            inst->opcode = BRW_OPCODE_MOV;
2727            inst->sources = 1;
2728            progress = true;
2729         } else if (inst->src[1].file == IMM) {
2730            inst->opcode = BRW_OPCODE_MOV;
2731            inst->src[0] = component(inst->src[0],
2732                                     inst->src[1].ud);
2733            inst->sources = 1;
2734            progress = true;
2735         }
2736         break;
2737
2738      default:
2739	 break;
2740      }
2741
2742      /* Swap if src[0] is immediate. */
2743      if (progress && inst->is_commutative()) {
2744         if (inst->src[0].file == IMM) {
2745            fs_reg tmp = inst->src[1];
2746            inst->src[1] = inst->src[0];
2747            inst->src[0] = tmp;
2748         }
2749      }
2750   }
2751   return progress;
2752}
2753
2754/**
2755 * Optimize sample messages that have constant zero values for the trailing
2756 * texture coordinates. We can just reduce the message length for these
2757 * instructions instead of reserving a register for it. Trailing parameters
2758 * that aren't sent default to zero anyway. This will cause the dead code
2759 * eliminator to remove the MOV instruction that would otherwise be emitted to
2760 * set up the zero value.
2761 */
2762bool
2763fs_visitor::opt_zero_samples()
2764{
2765   /* Gen4 infers the texturing opcode based on the message length so we can't
2766    * change it.
2767    */
2768   if (devinfo->gen < 5)
2769      return false;
2770
2771   bool progress = false;
2772
2773   foreach_block_and_inst(block, fs_inst, inst, cfg) {
2774      if (!inst->is_tex())
2775         continue;
2776
2777      fs_inst *load_payload = (fs_inst *) inst->prev;
2778
2779      if (load_payload->is_head_sentinel() ||
2780          load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2781         continue;
2782
2783      /* We don't want to remove the message header or the first parameter.
2784       * Removing the first parameter is not allowed, see the Haswell PRM
2785       * volume 7, page 149:
2786       *
2787       *     "Parameter 0 is required except for the sampleinfo message, which
2788       *      has no parameter 0"
2789       */
2790      while (inst->mlen > inst->header_size + inst->exec_size / 8 &&
2791             load_payload->src[(inst->mlen - inst->header_size) /
2792                               (inst->exec_size / 8) +
2793                               inst->header_size - 1].is_zero()) {
2794         inst->mlen -= inst->exec_size / 8;
2795         progress = true;
2796      }
2797   }
2798
2799   if (progress)
2800      invalidate_live_intervals();
2801
2802   return progress;
2803}
2804
2805/**
2806 * Optimize sample messages which are followed by the final RT write.
2807 *
2808 * CHV, and GEN9+ can mark a texturing SEND instruction with EOT to have its
2809 * results sent directly to the framebuffer, bypassing the EU.  Recognize the
2810 * final texturing results copied to the framebuffer write payload and modify
2811 * them to write to the framebuffer directly.
2812 */
2813bool
2814fs_visitor::opt_sampler_eot()
2815{
2816   brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
2817
2818   if (stage != MESA_SHADER_FRAGMENT || dispatch_width > 16)
2819      return false;
2820
2821   if (devinfo->gen != 9 && !devinfo->is_cherryview)
2822      return false;
2823
2824   /* FINISHME: It should be possible to implement this optimization when there
2825    * are multiple drawbuffers.
2826    */
2827   if (key->nr_color_regions != 1)
2828      return false;
2829
2830   /* Requires emitting a bunch of saturating MOV instructions during logical
2831    * send lowering to clamp the color payload, which the sampler unit isn't
2832    * going to do for us.
2833    */
2834   if (key->clamp_fragment_color)
2835      return false;
2836
2837   /* Look for a texturing instruction immediately before the final FB_WRITE. */
2838   bblock_t *block = cfg->blocks[cfg->num_blocks - 1];
2839   fs_inst *fb_write = (fs_inst *)block->end();
2840   assert(fb_write->eot);
2841   assert(fb_write->opcode == FS_OPCODE_FB_WRITE_LOGICAL);
2842
2843   /* There wasn't one; nothing to do. */
2844   if (unlikely(fb_write->prev->is_head_sentinel()))
2845      return false;
2846
2847   fs_inst *tex_inst = (fs_inst *) fb_write->prev;
2848
2849   /* 3D Sampler » Messages » Message Format
2850    *
2851    * “Response Length of zero is allowed on all SIMD8* and SIMD16* sampler
2852    *  messages except sample+killpix, resinfo, sampleinfo, LOD, and gather4*”
2853    */
2854   if (tex_inst->opcode != SHADER_OPCODE_TEX_LOGICAL &&
2855       tex_inst->opcode != SHADER_OPCODE_TXD_LOGICAL &&
2856       tex_inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
2857       tex_inst->opcode != SHADER_OPCODE_TXL_LOGICAL &&
2858       tex_inst->opcode != FS_OPCODE_TXB_LOGICAL &&
2859       tex_inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL &&
2860       tex_inst->opcode != SHADER_OPCODE_TXF_CMS_W_LOGICAL &&
2861       tex_inst->opcode != SHADER_OPCODE_TXF_UMS_LOGICAL)
2862      return false;
2863
2864   /* XXX - This shouldn't be necessary. */
2865   if (tex_inst->prev->is_head_sentinel())
2866      return false;
2867
2868   /* Check that the FB write sources are fully initialized by the single
2869    * texturing instruction.
2870    */
2871   for (unsigned i = 0; i < FB_WRITE_LOGICAL_NUM_SRCS; i++) {
2872      if (i == FB_WRITE_LOGICAL_SRC_COLOR0) {
2873         if (!fb_write->src[i].equals(tex_inst->dst) ||
2874             fb_write->size_read(i) != tex_inst->size_written)
2875         return false;
2876      } else if (i != FB_WRITE_LOGICAL_SRC_COMPONENTS) {
2877         if (fb_write->src[i].file != BAD_FILE)
2878            return false;
2879      }
2880   }
2881
2882   assert(!tex_inst->eot); /* We can't get here twice */
2883   assert((tex_inst->offset & (0xff << 24)) == 0);
2884
2885   const fs_builder ibld(this, block, tex_inst);
2886
2887   tex_inst->offset |= fb_write->target << 24;
2888   tex_inst->eot = true;
2889   tex_inst->dst = ibld.null_reg_ud();
2890   tex_inst->size_written = 0;
2891   fb_write->remove(cfg->blocks[cfg->num_blocks - 1]);
2892
2893   /* Marking EOT is sufficient, lower_logical_sends() will notice the EOT
2894    * flag and submit a header together with the sampler message as required
2895    * by the hardware.
2896    */
2897   invalidate_live_intervals();
2898   return true;
2899}
2900
2901bool
2902fs_visitor::opt_register_renaming()
2903{
2904   bool progress = false;
2905   int depth = 0;
2906
2907   unsigned remap[alloc.count];
2908   memset(remap, ~0u, sizeof(unsigned) * alloc.count);
2909
2910   foreach_block_and_inst(block, fs_inst, inst, cfg) {
2911      if (inst->opcode == BRW_OPCODE_IF || inst->opcode == BRW_OPCODE_DO) {
2912         depth++;
2913      } else if (inst->opcode == BRW_OPCODE_ENDIF ||
2914                 inst->opcode == BRW_OPCODE_WHILE) {
2915         depth--;
2916      }
2917
2918      /* Rewrite instruction sources. */
2919      for (int i = 0; i < inst->sources; i++) {
2920         if (inst->src[i].file == VGRF &&
2921             remap[inst->src[i].nr] != ~0u &&
2922             remap[inst->src[i].nr] != inst->src[i].nr) {
2923            inst->src[i].nr = remap[inst->src[i].nr];
2924            progress = true;
2925         }
2926      }
2927
2928      const unsigned dst = inst->dst.nr;
2929
2930      if (depth == 0 &&
2931          inst->dst.file == VGRF &&
2932          alloc.sizes[inst->dst.nr] * REG_SIZE == inst->size_written &&
2933          !inst->is_partial_write()) {
2934         if (remap[dst] == ~0u) {
2935            remap[dst] = dst;
2936         } else {
2937            remap[dst] = alloc.allocate(regs_written(inst));
2938            inst->dst.nr = remap[dst];
2939            progress = true;
2940         }
2941      } else if (inst->dst.file == VGRF &&
2942                 remap[dst] != ~0u &&
2943                 remap[dst] != dst) {
2944         inst->dst.nr = remap[dst];
2945         progress = true;
2946      }
2947   }
2948
2949   if (progress) {
2950      invalidate_live_intervals();
2951
2952      for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2953         if (delta_xy[i].file == VGRF && remap[delta_xy[i].nr] != ~0u) {
2954            delta_xy[i].nr = remap[delta_xy[i].nr];
2955         }
2956      }
2957   }
2958
2959   return progress;
2960}
2961
2962/**
2963 * Remove redundant or useless discard jumps.
2964 *
2965 * For example, we can eliminate jumps in the following sequence:
2966 *
2967 * discard-jump       (redundant with the next jump)
2968 * discard-jump       (useless; jumps to the next instruction)
2969 * placeholder-halt
2970 */
2971bool
2972fs_visitor::opt_redundant_discard_jumps()
2973{
2974   bool progress = false;
2975
2976   bblock_t *last_bblock = cfg->blocks[cfg->num_blocks - 1];
2977
2978   fs_inst *placeholder_halt = NULL;
2979   foreach_inst_in_block_reverse(fs_inst, inst, last_bblock) {
2980      if (inst->opcode == FS_OPCODE_PLACEHOLDER_HALT) {
2981         placeholder_halt = inst;
2982         break;
2983      }
2984   }
2985
2986   if (!placeholder_halt)
2987      return false;
2988
2989   /* Delete any HALTs immediately before the placeholder halt. */
2990   for (fs_inst *prev = (fs_inst *) placeholder_halt->prev;
2991        !prev->is_head_sentinel() && prev->opcode == FS_OPCODE_DISCARD_JUMP;
2992        prev = (fs_inst *) placeholder_halt->prev) {
2993      prev->remove(last_bblock);
2994      progress = true;
2995   }
2996
2997   if (progress)
2998      invalidate_live_intervals();
2999
3000   return progress;
3001}
3002
3003/**
3004 * Compute a bitmask with GRF granularity with a bit set for each GRF starting
3005 * from \p r.offset which overlaps the region starting at \p s.offset and
3006 * spanning \p ds bytes.
3007 */
3008static inline unsigned
3009mask_relative_to(const fs_reg &r, const fs_reg &s, unsigned ds)
3010{
3011   const int rel_offset = reg_offset(s) - reg_offset(r);
3012   const int shift = rel_offset / REG_SIZE;
3013   const unsigned n = DIV_ROUND_UP(rel_offset % REG_SIZE + ds, REG_SIZE);
3014   assert(reg_space(r) == reg_space(s) &&
3015          shift >= 0 && shift < int(8 * sizeof(unsigned)));
3016   return ((1 << n) - 1) << shift;
3017}
3018
3019bool
3020fs_visitor::opt_peephole_csel()
3021{
3022   if (devinfo->gen < 8)
3023      return false;
3024
3025   bool progress = false;
3026
3027   foreach_block_reverse(block, cfg) {
3028      int ip = block->end_ip + 1;
3029
3030      foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
3031         ip--;
3032
3033         if (inst->opcode != BRW_OPCODE_SEL ||
3034             inst->predicate != BRW_PREDICATE_NORMAL ||
3035             (inst->dst.type != BRW_REGISTER_TYPE_F &&
3036              inst->dst.type != BRW_REGISTER_TYPE_D &&
3037              inst->dst.type != BRW_REGISTER_TYPE_UD))
3038            continue;
3039
3040         /* Because it is a 3-src instruction, CSEL cannot have an immediate
3041          * value as a source, but we can sometimes handle zero.
3042          */
3043         if ((inst->src[0].file != VGRF && inst->src[0].file != ATTR &&
3044              inst->src[0].file != UNIFORM) ||
3045             (inst->src[1].file != VGRF && inst->src[1].file != ATTR &&
3046              inst->src[1].file != UNIFORM && !inst->src[1].is_zero()))
3047            continue;
3048
3049         foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3050            if (!scan_inst->flags_written())
3051               continue;
3052
3053            if ((scan_inst->opcode != BRW_OPCODE_CMP &&
3054                 scan_inst->opcode != BRW_OPCODE_MOV) ||
3055                scan_inst->predicate != BRW_PREDICATE_NONE ||
3056                (scan_inst->src[0].file != VGRF &&
3057                 scan_inst->src[0].file != ATTR &&
3058                 scan_inst->src[0].file != UNIFORM) ||
3059                scan_inst->src[0].type != BRW_REGISTER_TYPE_F)
3060               break;
3061
3062            if (scan_inst->opcode == BRW_OPCODE_CMP && !scan_inst->src[1].is_zero())
3063               break;
3064
3065            const brw::fs_builder ibld(this, block, inst);
3066
3067            const enum brw_conditional_mod cond =
3068               inst->predicate_inverse
3069               ? brw_negate_cmod(scan_inst->conditional_mod)
3070               : scan_inst->conditional_mod;
3071
3072            fs_inst *csel_inst = NULL;
3073
3074            if (inst->src[1].file != IMM) {
3075               csel_inst = ibld.CSEL(inst->dst,
3076                                     inst->src[0],
3077                                     inst->src[1],
3078                                     scan_inst->src[0],
3079                                     cond);
3080            } else if (cond == BRW_CONDITIONAL_NZ) {
3081               /* Consider the sequence
3082                *
3083                * cmp.nz.f0  null<1>F   g3<8,8,1>F   0F
3084                * (+f0) sel  g124<1>UD  g2<8,8,1>UD  0x00000000UD
3085                *
3086                * The sel will pick the immediate value 0 if r0 is ±0.0.
3087                * Therefore, this sequence is equivalent:
3088                *
3089                * cmp.nz.f0  null<1>F   g3<8,8,1>F   0F
3090                * (+f0) sel  g124<1>F   g2<8,8,1>F   (abs)g3<8,8,1>F
3091                *
3092                * The abs is ensures that the result is 0UD when g3 is -0.0F.
3093                * By normal cmp-sel merging, this is also equivalent:
3094                *
3095                * csel.nz    g124<1>F   g2<4,4,1>F   (abs)g3<4,4,1>F  g3<4,4,1>F
3096                */
3097               csel_inst = ibld.CSEL(inst->dst,
3098                                     inst->src[0],
3099                                     scan_inst->src[0],
3100                                     scan_inst->src[0],
3101                                     cond);
3102
3103               csel_inst->src[1].abs = true;
3104            }
3105
3106            if (csel_inst != NULL) {
3107               progress = true;
3108               csel_inst->saturate = inst->saturate;
3109               inst->remove(block);
3110            }
3111
3112            break;
3113         }
3114      }
3115   }
3116
3117   return progress;
3118}
3119
3120bool
3121fs_visitor::compute_to_mrf()
3122{
3123   bool progress = false;
3124   int next_ip = 0;
3125
3126   /* No MRFs on Gen >= 7. */
3127   if (devinfo->gen >= 7)
3128      return false;
3129
3130   calculate_live_intervals();
3131
3132   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3133      int ip = next_ip;
3134      next_ip++;
3135
3136      if (inst->opcode != BRW_OPCODE_MOV ||
3137	  inst->is_partial_write() ||
3138	  inst->dst.file != MRF || inst->src[0].file != VGRF ||
3139	  inst->dst.type != inst->src[0].type ||
3140	  inst->src[0].abs || inst->src[0].negate ||
3141          !inst->src[0].is_contiguous() ||
3142          inst->src[0].offset % REG_SIZE != 0)
3143	 continue;
3144
3145      /* Can't compute-to-MRF this GRF if someone else was going to
3146       * read it later.
3147       */
3148      if (this->virtual_grf_end[inst->src[0].nr] > ip)
3149	 continue;
3150
3151      /* Found a move of a GRF to a MRF.  Let's see if we can go rewrite the
3152       * things that computed the value of all GRFs of the source region.  The
3153       * regs_left bitset keeps track of the registers we haven't yet found a
3154       * generating instruction for.
3155       */
3156      unsigned regs_left = (1 << regs_read(inst, 0)) - 1;
3157
3158      foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3159         if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3160                             inst->src[0], inst->size_read(0))) {
3161	    /* Found the last thing to write our reg we want to turn
3162	     * into a compute-to-MRF.
3163	     */
3164
3165	    /* If this one instruction didn't populate all the
3166	     * channels, bail.  We might be able to rewrite everything
3167	     * that writes that reg, but it would require smarter
3168	     * tracking.
3169	     */
3170	    if (scan_inst->is_partial_write())
3171	       break;
3172
3173            /* Handling things not fully contained in the source of the copy
3174             * would need us to understand coalescing out more than one MOV at
3175             * a time.
3176             */
3177            if (!region_contained_in(scan_inst->dst, scan_inst->size_written,
3178                                     inst->src[0], inst->size_read(0)))
3179               break;
3180
3181	    /* SEND instructions can't have MRF as a destination. */
3182	    if (scan_inst->mlen)
3183	       break;
3184
3185	    if (devinfo->gen == 6) {
3186	       /* gen6 math instructions must have the destination be
3187		* GRF, so no compute-to-MRF for them.
3188		*/
3189	       if (scan_inst->is_math()) {
3190		  break;
3191	       }
3192	    }
3193
3194            /* Clear the bits for any registers this instruction overwrites. */
3195            regs_left &= ~mask_relative_to(
3196               inst->src[0], scan_inst->dst, scan_inst->size_written);
3197            if (!regs_left)
3198               break;
3199	 }
3200
3201	 /* We don't handle control flow here.  Most computation of
3202	  * values that end up in MRFs are shortly before the MRF
3203	  * write anyway.
3204	  */
3205	 if (block->start() == scan_inst)
3206	    break;
3207
3208	 /* You can't read from an MRF, so if someone else reads our
3209	  * MRF's source GRF that we wanted to rewrite, that stops us.
3210	  */
3211	 bool interfered = false;
3212	 for (int i = 0; i < scan_inst->sources; i++) {
3213            if (regions_overlap(scan_inst->src[i], scan_inst->size_read(i),
3214                                inst->src[0], inst->size_read(0))) {
3215	       interfered = true;
3216	    }
3217	 }
3218	 if (interfered)
3219	    break;
3220
3221         if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3222                             inst->dst, inst->size_written)) {
3223	    /* If somebody else writes our MRF here, we can't
3224	     * compute-to-MRF before that.
3225	     */
3226            break;
3227         }
3228
3229         if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1 &&
3230             regions_overlap(fs_reg(MRF, scan_inst->base_mrf), scan_inst->mlen * REG_SIZE,
3231                             inst->dst, inst->size_written)) {
3232	    /* Found a SEND instruction, which means that there are
3233	     * live values in MRFs from base_mrf to base_mrf +
3234	     * scan_inst->mlen - 1.  Don't go pushing our MRF write up
3235	     * above it.
3236	     */
3237            break;
3238         }
3239      }
3240
3241      if (regs_left)
3242         continue;
3243
3244      /* Found all generating instructions of our MRF's source value, so it
3245       * should be safe to rewrite them to point to the MRF directly.
3246       */
3247      regs_left = (1 << regs_read(inst, 0)) - 1;
3248
3249      foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3250         if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3251                             inst->src[0], inst->size_read(0))) {
3252            /* Clear the bits for any registers this instruction overwrites. */
3253            regs_left &= ~mask_relative_to(
3254               inst->src[0], scan_inst->dst, scan_inst->size_written);
3255
3256            const unsigned rel_offset = reg_offset(scan_inst->dst) -
3257                                        reg_offset(inst->src[0]);
3258
3259            if (inst->dst.nr & BRW_MRF_COMPR4) {
3260               /* Apply the same address transformation done by the hardware
3261                * for COMPR4 MRF writes.
3262                */
3263               assert(rel_offset < 2 * REG_SIZE);
3264               scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE * 4;
3265
3266               /* Clear the COMPR4 bit if the generating instruction is not
3267                * compressed.
3268                */
3269               if (scan_inst->size_written < 2 * REG_SIZE)
3270                  scan_inst->dst.nr &= ~BRW_MRF_COMPR4;
3271
3272            } else {
3273               /* Calculate the MRF number the result of this instruction is
3274                * ultimately written to.
3275                */
3276               scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE;
3277            }
3278
3279            scan_inst->dst.file = MRF;
3280            scan_inst->dst.offset = inst->dst.offset + rel_offset % REG_SIZE;
3281            scan_inst->saturate |= inst->saturate;
3282            if (!regs_left)
3283               break;
3284         }
3285      }
3286
3287      assert(!regs_left);
3288      inst->remove(block);
3289      progress = true;
3290   }
3291
3292   if (progress)
3293      invalidate_live_intervals();
3294
3295   return progress;
3296}
3297
3298/**
3299 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
3300 * flow.  We could probably do better here with some form of divergence
3301 * analysis.
3302 */
3303bool
3304fs_visitor::eliminate_find_live_channel()
3305{
3306   bool progress = false;
3307   unsigned depth = 0;
3308
3309   if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
3310      /* The optimization below assumes that channel zero is live on thread
3311       * dispatch, which may not be the case if the fixed function dispatches
3312       * threads sparsely.
3313       */
3314      return false;
3315   }
3316
3317   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3318      switch (inst->opcode) {
3319      case BRW_OPCODE_IF:
3320      case BRW_OPCODE_DO:
3321         depth++;
3322         break;
3323
3324      case BRW_OPCODE_ENDIF:
3325      case BRW_OPCODE_WHILE:
3326         depth--;
3327         break;
3328
3329      case FS_OPCODE_DISCARD_JUMP:
3330         /* This can potentially make control flow non-uniform until the end
3331          * of the program.
3332          */
3333         return progress;
3334
3335      case SHADER_OPCODE_FIND_LIVE_CHANNEL:
3336         if (depth == 0) {
3337            inst->opcode = BRW_OPCODE_MOV;
3338            inst->src[0] = brw_imm_ud(0u);
3339            inst->sources = 1;
3340            inst->force_writemask_all = true;
3341            progress = true;
3342         }
3343         break;
3344
3345      default:
3346         break;
3347      }
3348   }
3349
3350   return progress;
3351}
3352
3353/**
3354 * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
3355 * instructions to FS_OPCODE_REP_FB_WRITE.
3356 */
3357void
3358fs_visitor::emit_repclear_shader()
3359{
3360   brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3361   int base_mrf = 0;
3362   int color_mrf = base_mrf + 2;
3363   fs_inst *mov;
3364
3365   if (uniforms > 0) {
3366      mov = bld.exec_all().group(4, 0)
3367               .MOV(brw_message_reg(color_mrf),
3368                    fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
3369   } else {
3370      struct brw_reg reg =
3371         brw_reg(BRW_GENERAL_REGISTER_FILE, 2, 3, 0, 0, BRW_REGISTER_TYPE_F,
3372                 BRW_VERTICAL_STRIDE_8, BRW_WIDTH_2, BRW_HORIZONTAL_STRIDE_4,
3373                 BRW_SWIZZLE_XYZW, WRITEMASK_XYZW);
3374
3375      mov = bld.exec_all().group(4, 0)
3376               .MOV(vec4(brw_message_reg(color_mrf)), fs_reg(reg));
3377   }
3378
3379   fs_inst *write = NULL;
3380   if (key->nr_color_regions == 1) {
3381      write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3382      write->saturate = key->clamp_fragment_color;
3383      write->base_mrf = color_mrf;
3384      write->target = 0;
3385      write->header_size = 0;
3386      write->mlen = 1;
3387   } else {
3388      assume(key->nr_color_regions > 0);
3389
3390      struct brw_reg header =
3391         retype(brw_message_reg(base_mrf), BRW_REGISTER_TYPE_UD);
3392      bld.exec_all().group(16, 0)
3393         .MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3394
3395      for (int i = 0; i < key->nr_color_regions; ++i) {
3396         if (i > 0) {
3397            bld.exec_all().group(1, 0)
3398               .MOV(component(header, 2), brw_imm_ud(i));
3399         }
3400
3401         write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3402         write->saturate = key->clamp_fragment_color;
3403         write->base_mrf = base_mrf;
3404         write->target = i;
3405         write->header_size = 2;
3406         write->mlen = 3;
3407      }
3408   }
3409   write->eot = true;
3410   write->last_rt = true;
3411
3412   calculate_cfg();
3413
3414   assign_constant_locations();
3415   assign_curb_setup();
3416
3417   /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
3418   if (uniforms > 0) {
3419      assert(mov->src[0].file == FIXED_GRF);
3420      mov->src[0] = brw_vec4_grf(mov->src[0].nr, 0);
3421   }
3422}
3423
3424/**
3425 * Walks through basic blocks, looking for repeated MRF writes and
3426 * removing the later ones.
3427 */
3428bool
3429fs_visitor::remove_duplicate_mrf_writes()
3430{
3431   fs_inst *last_mrf_move[BRW_MAX_MRF(devinfo->gen)];
3432   bool progress = false;
3433
3434   /* Need to update the MRF tracking for compressed instructions. */
3435   if (dispatch_width >= 16)
3436      return false;
3437
3438   memset(last_mrf_move, 0, sizeof(last_mrf_move));
3439
3440   foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3441      if (inst->is_control_flow()) {
3442	 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3443      }
3444
3445      if (inst->opcode == BRW_OPCODE_MOV &&
3446	  inst->dst.file == MRF) {
3447         fs_inst *prev_inst = last_mrf_move[inst->dst.nr];
3448	 if (prev_inst && prev_inst->opcode == BRW_OPCODE_MOV &&
3449             inst->dst.equals(prev_inst->dst) &&
3450             inst->src[0].equals(prev_inst->src[0]) &&
3451             inst->saturate == prev_inst->saturate &&
3452             inst->predicate == prev_inst->predicate &&
3453             inst->conditional_mod == prev_inst->conditional_mod &&
3454             inst->exec_size == prev_inst->exec_size) {
3455	    inst->remove(block);
3456	    progress = true;
3457	    continue;
3458	 }
3459      }
3460
3461      /* Clear out the last-write records for MRFs that were overwritten. */
3462      if (inst->dst.file == MRF) {
3463         last_mrf_move[inst->dst.nr] = NULL;
3464      }
3465
3466      if (inst->mlen > 0 && inst->base_mrf != -1) {
3467	 /* Found a SEND instruction, which will include two or fewer
3468	  * implied MRF writes.  We could do better here.
3469	  */
3470	 for (int i = 0; i < implied_mrf_writes(inst); i++) {
3471	    last_mrf_move[inst->base_mrf + i] = NULL;
3472	 }
3473      }
3474
3475      /* Clear out any MRF move records whose sources got overwritten. */
3476      for (unsigned i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
3477         if (last_mrf_move[i] &&
3478             regions_overlap(inst->dst, inst->size_written,
3479                             last_mrf_move[i]->src[0],
3480                             last_mrf_move[i]->size_read(0))) {
3481            last_mrf_move[i] = NULL;
3482         }
3483      }
3484
3485      if (inst->opcode == BRW_OPCODE_MOV &&
3486	  inst->dst.file == MRF &&
3487	  inst->src[0].file != ARF &&
3488	  !inst->is_partial_write()) {
3489         last_mrf_move[inst->dst.nr] = inst;
3490      }
3491   }
3492
3493   if (progress)
3494      invalidate_live_intervals();
3495
3496   return progress;
3497}
3498
3499/**
3500 * Rounding modes for conversion instructions are included for each
3501 * conversion, but right now it is a state. So once it is set,
3502 * we don't need to call it again for subsequent calls.
3503 *
3504 * This is useful for vector/matrices conversions, as setting the
3505 * mode once is enough for the full vector/matrix
3506 */
3507bool
3508fs_visitor::remove_extra_rounding_modes()
3509{
3510   bool progress = false;
3511
3512   foreach_block (block, cfg) {
3513      brw_rnd_mode prev_mode = BRW_RND_MODE_UNSPECIFIED;
3514
3515      foreach_inst_in_block_safe (fs_inst, inst, block) {
3516         if (inst->opcode == SHADER_OPCODE_RND_MODE) {
3517            assert(inst->src[0].file == BRW_IMMEDIATE_VALUE);
3518            const brw_rnd_mode mode = (brw_rnd_mode) inst->src[0].d;
3519            if (mode == prev_mode) {
3520               inst->remove(block);
3521               progress = true;
3522            } else {
3523               prev_mode = mode;
3524            }
3525         }
3526      }
3527   }
3528
3529   if (progress)
3530      invalidate_live_intervals();
3531
3532   return progress;
3533}
3534
3535static void
3536clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
3537{
3538   /* Clear the flag for registers that actually got read (as expected). */
3539   for (int i = 0; i < inst->sources; i++) {
3540      int grf;
3541      if (inst->src[i].file == VGRF || inst->src[i].file == FIXED_GRF) {
3542         grf = inst->src[i].nr;
3543      } else {
3544         continue;
3545      }
3546
3547      if (grf >= first_grf &&
3548          grf < first_grf + grf_len) {
3549         deps[grf - first_grf] = false;
3550         if (inst->exec_size == 16)
3551            deps[grf - first_grf + 1] = false;
3552      }
3553   }
3554}
3555
3556/**
3557 * Implements this workaround for the original 965:
3558 *
3559 *     "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
3560 *      check for post destination dependencies on this instruction, software
3561 *      must ensure that there is no destination hazard for the case of ‘write
3562 *      followed by a posted write’ shown in the following example.
3563 *
3564 *      1. mov r3 0
3565 *      2. send r3.xy <rest of send instruction>
3566 *      3. mov r2 r3
3567 *
3568 *      Due to no post-destination dependency check on the ‘send’, the above
3569 *      code sequence could have two instructions (1 and 2) in flight at the
3570 *      same time that both consider ‘r3’ as the target of their final writes.
3571 */
3572void
3573fs_visitor::insert_gen4_pre_send_dependency_workarounds(bblock_t *block,
3574                                                        fs_inst *inst)
3575{
3576   int write_len = regs_written(inst);
3577   int first_write_grf = inst->dst.nr;
3578   bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3579   assert(write_len < (int)sizeof(needs_dep) - 1);
3580
3581   memset(needs_dep, false, sizeof(needs_dep));
3582   memset(needs_dep, true, write_len);
3583
3584   clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
3585
3586   /* Walk backwards looking for writes to registers we're writing which
3587    * aren't read since being written.  If we hit the start of the program,
3588    * we assume that there are no outstanding dependencies on entry to the
3589    * program.
3590    */
3591   foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3592      /* If we hit control flow, assume that there *are* outstanding
3593       * dependencies, and force their cleanup before our instruction.
3594       */
3595      if (block->start() == scan_inst && block->num != 0) {
3596         for (int i = 0; i < write_len; i++) {
3597            if (needs_dep[i])
3598               DEP_RESOLVE_MOV(fs_builder(this, block, inst),
3599                               first_write_grf + i);
3600         }
3601         return;
3602      }
3603
3604      /* We insert our reads as late as possible on the assumption that any
3605       * instruction but a MOV that might have left us an outstanding
3606       * dependency has more latency than a MOV.
3607       */
3608      if (scan_inst->dst.file == VGRF) {
3609         for (unsigned i = 0; i < regs_written(scan_inst); i++) {
3610            int reg = scan_inst->dst.nr + i;
3611
3612            if (reg >= first_write_grf &&
3613                reg < first_write_grf + write_len &&
3614                needs_dep[reg - first_write_grf]) {
3615               DEP_RESOLVE_MOV(fs_builder(this, block, inst), reg);
3616               needs_dep[reg - first_write_grf] = false;
3617               if (scan_inst->exec_size == 16)
3618                  needs_dep[reg - first_write_grf + 1] = false;
3619            }
3620         }
3621      }
3622
3623      /* Clear the flag for registers that actually got read (as expected). */
3624      clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3625
3626      /* Continue the loop only if we haven't resolved all the dependencies */
3627      int i;
3628      for (i = 0; i < write_len; i++) {
3629         if (needs_dep[i])
3630            break;
3631      }
3632      if (i == write_len)
3633         return;
3634   }
3635}
3636
3637/**
3638 * Implements this workaround for the original 965:
3639 *
3640 *     "[DevBW, DevCL] Errata: A destination register from a send can not be
3641 *      used as a destination register until after it has been sourced by an
3642 *      instruction with a different destination register.
3643 */
3644void
3645fs_visitor::insert_gen4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
3646{
3647   int write_len = regs_written(inst);
3648   unsigned first_write_grf = inst->dst.nr;
3649   bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3650   assert(write_len < (int)sizeof(needs_dep) - 1);
3651
3652   memset(needs_dep, false, sizeof(needs_dep));
3653   memset(needs_dep, true, write_len);
3654   /* Walk forwards looking for writes to registers we're writing which aren't
3655    * read before being written.
3656    */
3657   foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst) {
3658      /* If we hit control flow, force resolve all remaining dependencies. */
3659      if (block->end() == scan_inst && block->num != cfg->num_blocks - 1) {
3660         for (int i = 0; i < write_len; i++) {
3661            if (needs_dep[i])
3662               DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3663                               first_write_grf + i);
3664         }
3665         return;
3666      }
3667
3668      /* Clear the flag for registers that actually got read (as expected). */
3669      clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3670
3671      /* We insert our reads as late as possible since they're reading the
3672       * result of a SEND, which has massive latency.
3673       */
3674      if (scan_inst->dst.file == VGRF &&
3675          scan_inst->dst.nr >= first_write_grf &&
3676          scan_inst->dst.nr < first_write_grf + write_len &&
3677          needs_dep[scan_inst->dst.nr - first_write_grf]) {
3678         DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3679                         scan_inst->dst.nr);
3680         needs_dep[scan_inst->dst.nr - first_write_grf] = false;
3681      }
3682
3683      /* Continue the loop only if we haven't resolved all the dependencies */
3684      int i;
3685      for (i = 0; i < write_len; i++) {
3686         if (needs_dep[i])
3687            break;
3688      }
3689      if (i == write_len)
3690         return;
3691   }
3692}
3693
3694void
3695fs_visitor::insert_gen4_send_dependency_workarounds()
3696{
3697   if (devinfo->gen != 4 || devinfo->is_g4x)
3698      return;
3699
3700   bool progress = false;
3701
3702   foreach_block_and_inst(block, fs_inst, inst, cfg) {
3703      if (inst->mlen != 0 && inst->dst.file == VGRF) {
3704         insert_gen4_pre_send_dependency_workarounds(block, inst);
3705         insert_gen4_post_send_dependency_workarounds(block, inst);
3706         progress = true;
3707      }
3708   }
3709
3710   if (progress)
3711      invalidate_live_intervals();
3712}
3713
3714/**
3715 * Turns the generic expression-style uniform pull constant load instruction
3716 * into a hardware-specific series of instructions for loading a pull
3717 * constant.
3718 *
3719 * The expression style allows the CSE pass before this to optimize out
3720 * repeated loads from the same offset, and gives the pre-register-allocation
3721 * scheduling full flexibility, while the conversion to native instructions
3722 * allows the post-register-allocation scheduler the best information
3723 * possible.
3724 *
3725 * Note that execution masking for setting up pull constant loads is special:
3726 * the channels that need to be written are unrelated to the current execution
3727 * mask, since a later instruction will use one of the result channels as a
3728 * source operand for all 8 or 16 of its channels.
3729 */
3730void
3731fs_visitor::lower_uniform_pull_constant_loads()
3732{
3733   foreach_block_and_inst (block, fs_inst, inst, cfg) {
3734      if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
3735         continue;
3736
3737      if (devinfo->gen >= 7) {
3738         const fs_builder ubld = fs_builder(this, block, inst).exec_all();
3739         const fs_reg payload = ubld.group(8, 0).vgrf(BRW_REGISTER_TYPE_UD);
3740
3741         ubld.group(8, 0).MOV(payload,
3742                              retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3743         ubld.group(1, 0).MOV(component(payload, 2),
3744                              brw_imm_ud(inst->src[1].ud / 16));
3745
3746         inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7;
3747         inst->src[1] = payload;
3748         inst->header_size = 1;
3749         inst->mlen = 1;
3750
3751         invalidate_live_intervals();
3752      } else {
3753         /* Before register allocation, we didn't tell the scheduler about the
3754          * MRF we use.  We know it's safe to use this MRF because nothing
3755          * else does except for register spill/unspill, which generates and
3756          * uses its MRF within a single IR instruction.
3757          */
3758         inst->base_mrf = FIRST_PULL_LOAD_MRF(devinfo->gen) + 1;
3759         inst->mlen = 1;
3760      }
3761   }
3762}
3763
3764bool
3765fs_visitor::lower_load_payload()
3766{
3767   bool progress = false;
3768
3769   foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3770      if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3771         continue;
3772
3773      assert(inst->dst.file == MRF || inst->dst.file == VGRF);
3774      assert(inst->saturate == false);
3775      fs_reg dst = inst->dst;
3776
3777      /* Get rid of COMPR4.  We'll add it back in if we need it */
3778      if (dst.file == MRF)
3779         dst.nr = dst.nr & ~BRW_MRF_COMPR4;
3780
3781      const fs_builder ibld(this, block, inst);
3782      const fs_builder hbld = ibld.exec_all().group(8, 0);
3783
3784      for (uint8_t i = 0; i < inst->header_size; i++) {
3785         if (inst->src[i].file != BAD_FILE) {
3786            fs_reg mov_dst = retype(dst, BRW_REGISTER_TYPE_UD);
3787            fs_reg mov_src = retype(inst->src[i], BRW_REGISTER_TYPE_UD);
3788            hbld.MOV(mov_dst, mov_src);
3789         }
3790         dst = offset(dst, hbld, 1);
3791      }
3792
3793      if (inst->dst.file == MRF && (inst->dst.nr & BRW_MRF_COMPR4) &&
3794          inst->exec_size > 8) {
3795         /* In this case, the payload portion of the LOAD_PAYLOAD isn't
3796          * a straightforward copy.  Instead, the result of the
3797          * LOAD_PAYLOAD is treated as interleaved and the first four
3798          * non-header sources are unpacked as:
3799          *
3800          * m + 0: r0
3801          * m + 1: g0
3802          * m + 2: b0
3803          * m + 3: a0
3804          * m + 4: r1
3805          * m + 5: g1
3806          * m + 6: b1
3807          * m + 7: a1
3808          *
3809          * This is used for gen <= 5 fb writes.
3810          */
3811         assert(inst->exec_size == 16);
3812         assert(inst->header_size + 4 <= inst->sources);
3813         for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
3814            if (inst->src[i].file != BAD_FILE) {
3815               if (devinfo->has_compr4) {
3816                  fs_reg compr4_dst = retype(dst, inst->src[i].type);
3817                  compr4_dst.nr |= BRW_MRF_COMPR4;
3818                  ibld.MOV(compr4_dst, inst->src[i]);
3819               } else {
3820                  /* Platform doesn't have COMPR4.  We have to fake it */
3821                  fs_reg mov_dst = retype(dst, inst->src[i].type);
3822                  ibld.half(0).MOV(mov_dst, half(inst->src[i], 0));
3823                  mov_dst.nr += 4;
3824                  ibld.half(1).MOV(mov_dst, half(inst->src[i], 1));
3825               }
3826            }
3827
3828            dst.nr++;
3829         }
3830
3831         /* The loop above only ever incremented us through the first set
3832          * of 4 registers.  However, thanks to the magic of COMPR4, we
3833          * actually wrote to the first 8 registers, so we need to take
3834          * that into account now.
3835          */
3836         dst.nr += 4;
3837
3838         /* The COMPR4 code took care of the first 4 sources.  We'll let
3839          * the regular path handle any remaining sources.  Yes, we are
3840          * modifying the instruction but we're about to delete it so
3841          * this really doesn't hurt anything.
3842          */
3843         inst->header_size += 4;
3844      }
3845
3846      for (uint8_t i = inst->header_size; i < inst->sources; i++) {
3847         if (inst->src[i].file != BAD_FILE) {
3848            dst.type = inst->src[i].type;
3849            ibld.MOV(dst, inst->src[i]);
3850         } else {
3851            dst.type = BRW_REGISTER_TYPE_UD;
3852         }
3853         dst = offset(dst, ibld, 1);
3854      }
3855
3856      inst->remove(block);
3857      progress = true;
3858   }
3859
3860   if (progress)
3861      invalidate_live_intervals();
3862
3863   return progress;
3864}
3865
3866bool
3867fs_visitor::lower_linterp()
3868{
3869   bool progress = false;
3870
3871   if (devinfo->gen < 11)
3872      return false;
3873
3874   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3875      const fs_builder ibld(this, block, inst);
3876
3877      if (inst->opcode != FS_OPCODE_LINTERP)
3878         continue;
3879
3880      fs_reg dwP = component(inst->src[1], 0);
3881      fs_reg dwQ = component(inst->src[1], 1);
3882      fs_reg dwR = component(inst->src[1], 3);
3883      for (unsigned i = 0; i < DIV_ROUND_UP(dispatch_width, 8); i++) {
3884         const fs_builder hbld(ibld.half(i));
3885         fs_reg dst = half(inst->dst, i);
3886         fs_reg delta_xy = offset(inst->src[0], ibld, i);
3887         hbld.MAD(dst, dwR, half(delta_xy, 0), dwP);
3888         fs_inst *mad = hbld.MAD(dst, dst, half(delta_xy, 1), dwQ);
3889
3890         /* Propagate conditional mod and saturate from the original
3891          * instruction to the second MAD instruction.
3892          */
3893         set_saturate(inst->saturate, mad);
3894         set_condmod(inst->conditional_mod, mad);
3895      }
3896
3897      inst->remove(block);
3898      progress = true;
3899   }
3900
3901   if (progress)
3902      invalidate_live_intervals();
3903
3904   return progress;
3905}
3906
3907bool
3908fs_visitor::lower_integer_multiplication()
3909{
3910   bool progress = false;
3911
3912   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3913      const fs_builder ibld(this, block, inst);
3914
3915      if (inst->opcode == BRW_OPCODE_MUL) {
3916         if (inst->dst.is_accumulator() ||
3917             (inst->dst.type != BRW_REGISTER_TYPE_D &&
3918              inst->dst.type != BRW_REGISTER_TYPE_UD))
3919            continue;
3920
3921         if (devinfo->has_integer_dword_mul)
3922            continue;
3923
3924         if (inst->src[1].file == IMM &&
3925             inst->src[1].ud < (1 << 16)) {
3926            /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3927             * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3928             * src1 are used.
3929             *
3930             * If multiplying by an immediate value that fits in 16-bits, do a
3931             * single MUL instruction with that value in the proper location.
3932             */
3933            if (devinfo->gen < 7) {
3934               fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8),
3935                          inst->dst.type);
3936               ibld.MOV(imm, inst->src[1]);
3937               ibld.MUL(inst->dst, imm, inst->src[0]);
3938            } else {
3939               const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
3940               ibld.MUL(inst->dst, inst->src[0],
3941                        ud ? brw_imm_uw(inst->src[1].ud)
3942                           : brw_imm_w(inst->src[1].d));
3943            }
3944         } else {
3945            /* Gen < 8 (and some Gen8+ low-power parts like Cherryview) cannot
3946             * do 32-bit integer multiplication in one instruction, but instead
3947             * must do a sequence (which actually calculates a 64-bit result):
3948             *
3949             *    mul(8)  acc0<1>D   g3<8,8,1>D      g4<8,8,1>D
3950             *    mach(8) null       g3<8,8,1>D      g4<8,8,1>D
3951             *    mov(8)  g2<1>D     acc0<8,8,1>D
3952             *
3953             * But on Gen > 6, the ability to use second accumulator register
3954             * (acc1) for non-float data types was removed, preventing a simple
3955             * implementation in SIMD16. A 16-channel result can be calculated by
3956             * executing the three instructions twice in SIMD8, once with quarter
3957             * control of 1Q for the first eight channels and again with 2Q for
3958             * the second eight channels.
3959             *
3960             * Which accumulator register is implicitly accessed (by AccWrEnable
3961             * for instance) is determined by the quarter control. Unfortunately
3962             * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3963             * implicit accumulator access by an instruction with 2Q will access
3964             * acc1 regardless of whether the data type is usable in acc1.
3965             *
3966             * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3967             * integer data types.
3968             *
3969             * Since we only want the low 32-bits of the result, we can do two
3970             * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3971             * adjust the high result and add them (like the mach is doing):
3972             *
3973             *    mul(8)  g7<1>D     g3<8,8,1>D      g4.0<8,8,1>UW
3974             *    mul(8)  g8<1>D     g3<8,8,1>D      g4.1<8,8,1>UW
3975             *    shl(8)  g9<1>D     g8<8,8,1>D      16D
3976             *    add(8)  g2<1>D     g7<8,8,1>D      g8<8,8,1>D
3977             *
3978             * We avoid the shl instruction by realizing that we only want to add
3979             * the low 16-bits of the "high" result to the high 16-bits of the
3980             * "low" result and using proper regioning on the add:
3981             *
3982             *    mul(8)  g7<1>D     g3<8,8,1>D      g4.0<16,8,2>UW
3983             *    mul(8)  g8<1>D     g3<8,8,1>D      g4.1<16,8,2>UW
3984             *    add(8)  g7.1<2>UW  g7.1<16,8,2>UW  g8<16,8,2>UW
3985             *
3986             * Since it does not use the (single) accumulator register, we can
3987             * schedule multi-component multiplications much better.
3988             */
3989
3990            bool needs_mov = false;
3991            fs_reg orig_dst = inst->dst;
3992
3993            /* Get a new VGRF for the "low" 32x16-bit multiplication result if
3994             * reusing the original destination is impossible due to hardware
3995             * restrictions, source/destination overlap, or it being the null
3996             * register.
3997             */
3998            fs_reg low = inst->dst;
3999            if (orig_dst.is_null() || orig_dst.file == MRF ||
4000                regions_overlap(inst->dst, inst->size_written,
4001                                inst->src[0], inst->size_read(0)) ||
4002                regions_overlap(inst->dst, inst->size_written,
4003                                inst->src[1], inst->size_read(1)) ||
4004                inst->dst.stride >= 4) {
4005               needs_mov = true;
4006               low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
4007                            inst->dst.type);
4008            }
4009
4010            /* Get a new VGRF but keep the same stride as inst->dst */
4011            fs_reg high(VGRF, alloc.allocate(regs_written(inst)),
4012                        inst->dst.type);
4013            high.stride = inst->dst.stride;
4014            high.offset = inst->dst.offset % REG_SIZE;
4015
4016            if (devinfo->gen >= 7) {
4017               if (inst->src[1].abs)
4018                  lower_src_modifiers(this, block, inst, 1);
4019
4020               if (inst->src[1].file == IMM) {
4021                  ibld.MUL(low, inst->src[0],
4022                           brw_imm_uw(inst->src[1].ud & 0xffff));
4023                  ibld.MUL(high, inst->src[0],
4024                           brw_imm_uw(inst->src[1].ud >> 16));
4025               } else {
4026                  ibld.MUL(low, inst->src[0],
4027                           subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4028                  ibld.MUL(high, inst->src[0],
4029                           subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
4030               }
4031            } else {
4032               if (inst->src[0].abs)
4033                  lower_src_modifiers(this, block, inst, 0);
4034
4035               ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
4036                        inst->src[1]);
4037               ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
4038                        inst->src[1]);
4039            }
4040
4041            ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
4042                     subscript(low, BRW_REGISTER_TYPE_UW, 1),
4043                     subscript(high, BRW_REGISTER_TYPE_UW, 0));
4044
4045            if (needs_mov || inst->conditional_mod) {
4046               set_condmod(inst->conditional_mod,
4047                           ibld.MOV(orig_dst, low));
4048            }
4049         }
4050
4051      } else if (inst->opcode == SHADER_OPCODE_MULH) {
4052         /* According to the BDW+ BSpec page for the "Multiply Accumulate
4053          * High" instruction:
4054          *
4055          *  "An added preliminary mov is required for source modification on
4056          *   src1:
4057          *      mov (8) r3.0<1>:d -r3<8;8,1>:d
4058          *      mul (8) acc0:d r2.0<8;8,1>:d r3.0<16;8,2>:uw
4059          *      mach (8) r5.0<1>:d r2.0<8;8,1>:d r3.0<8;8,1>:d"
4060          */
4061         if (devinfo->gen >= 8 && (inst->src[1].negate || inst->src[1].abs))
4062            lower_src_modifiers(this, block, inst, 1);
4063
4064         /* Should have been lowered to 8-wide. */
4065         assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
4066         const fs_reg acc = retype(brw_acc_reg(inst->exec_size),
4067                                   inst->dst.type);
4068         fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
4069         fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
4070
4071         if (devinfo->gen >= 8) {
4072            /* Until Gen8, integer multiplies read 32-bits from one source,
4073             * and 16-bits from the other, and relying on the MACH instruction
4074             * to generate the high bits of the result.
4075             *
4076             * On Gen8, the multiply instruction does a full 32x32-bit
4077             * multiply, but in order to do a 64-bit multiply we can simulate
4078             * the previous behavior and then use a MACH instruction.
4079             */
4080            assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
4081                   mul->src[1].type == BRW_REGISTER_TYPE_UD);
4082            mul->src[1].type = BRW_REGISTER_TYPE_UW;
4083            mul->src[1].stride *= 2;
4084
4085         } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
4086                    inst->group > 0) {
4087            /* Among other things the quarter control bits influence which
4088             * accumulator register is used by the hardware for instructions
4089             * that access the accumulator implicitly (e.g. MACH).  A
4090             * second-half instruction would normally map to acc1, which
4091             * doesn't exist on Gen7 and up (the hardware does emulate it for
4092             * floating-point instructions *only* by taking advantage of the
4093             * extra precision of acc0 not normally used for floating point
4094             * arithmetic).
4095             *
4096             * HSW and up are careful enough not to try to access an
4097             * accumulator register that doesn't exist, but on earlier Gen7
4098             * hardware we need to make sure that the quarter control bits are
4099             * zero to avoid non-deterministic behaviour and emit an extra MOV
4100             * to get the result masked correctly according to the current
4101             * channel enables.
4102             */
4103            mach->group = 0;
4104            mach->force_writemask_all = true;
4105            mach->dst = ibld.vgrf(inst->dst.type);
4106            ibld.MOV(inst->dst, mach->dst);
4107         }
4108      } else {
4109         continue;
4110      }
4111
4112      inst->remove(block);
4113      progress = true;
4114   }
4115
4116   if (progress)
4117      invalidate_live_intervals();
4118
4119   return progress;
4120}
4121
4122bool
4123fs_visitor::lower_minmax()
4124{
4125   assert(devinfo->gen < 6);
4126
4127   bool progress = false;
4128
4129   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4130      const fs_builder ibld(this, block, inst);
4131
4132      if (inst->opcode == BRW_OPCODE_SEL &&
4133          inst->predicate == BRW_PREDICATE_NONE) {
4134         /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
4135          *        the original SEL.L/GE instruction
4136          */
4137         ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4138                  inst->conditional_mod);
4139         inst->predicate = BRW_PREDICATE_NORMAL;
4140         inst->conditional_mod = BRW_CONDITIONAL_NONE;
4141
4142         progress = true;
4143      }
4144   }
4145
4146   if (progress)
4147      invalidate_live_intervals();
4148
4149   return progress;
4150}
4151
4152static void
4153setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
4154                    fs_reg *dst, fs_reg color, unsigned components)
4155{
4156   if (key->clamp_fragment_color) {
4157      fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
4158      assert(color.type == BRW_REGISTER_TYPE_F);
4159
4160      for (unsigned i = 0; i < components; i++)
4161         set_saturate(true,
4162                      bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
4163
4164      color = tmp;
4165   }
4166
4167   for (unsigned i = 0; i < components; i++)
4168      dst[i] = offset(color, bld, i);
4169}
4170
4171static void
4172lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
4173                            const struct brw_wm_prog_data *prog_data,
4174                            const brw_wm_prog_key *key,
4175                            const fs_visitor::thread_payload &payload)
4176{
4177   assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
4178   const gen_device_info *devinfo = bld.shader->devinfo;
4179   const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
4180   const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
4181   const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
4182   const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
4183   const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
4184   const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
4185   fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
4186   const unsigned components =
4187      inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
4188
4189   /* We can potentially have a message length of up to 15, so we have to set
4190    * base_mrf to either 0 or 1 in order to fit in m0..m15.
4191    */
4192   fs_reg sources[15];
4193   int header_size = 2, payload_header_size;
4194   unsigned length = 0;
4195
4196   if (devinfo->gen < 6) {
4197      /* TODO: Support SIMD32 on gen4-5 */
4198      assert(bld.group() < 16);
4199
4200      /* For gen4-5, we always have a header consisting of g0 and g1.  We have
4201       * an implied MOV from g0,g1 to the start of the message.  The MOV from
4202       * g0 is handled by the hardware and the MOV from g1 is provided by the
4203       * generator.  This is required because, on gen4-5, the generator may
4204       * generate two write messages with different message lengths in order
4205       * to handle AA data properly.
4206       *
4207       * Also, since the pixel mask goes in the g0 portion of the message and
4208       * since render target writes are the last thing in the shader, we write
4209       * the pixel mask directly into g0 and it will get copied as part of the
4210       * implied write.
4211       */
4212      if (prog_data->uses_kill) {
4213         bld.exec_all().group(1, 0)
4214            .MOV(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW),
4215                 brw_flag_reg(0, 1));
4216      }
4217
4218      assert(length == 0);
4219      length = 2;
4220   } else if ((devinfo->gen <= 7 && !devinfo->is_haswell &&
4221               prog_data->uses_kill) ||
4222              color1.file != BAD_FILE ||
4223              key->nr_color_regions > 1) {
4224      /* From the Sandy Bridge PRM, volume 4, page 198:
4225       *
4226       *     "Dispatched Pixel Enables. One bit per pixel indicating
4227       *      which pixels were originally enabled when the thread was
4228       *      dispatched. This field is only required for the end-of-
4229       *      thread message and on all dual-source messages."
4230       */
4231      const fs_builder ubld = bld.exec_all().group(8, 0);
4232
4233      fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
4234      if (bld.group() < 16) {
4235         /* The header starts off as g0 and g1 for the first half */
4236         ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4237                                              BRW_REGISTER_TYPE_UD));
4238      } else {
4239         /* The header starts off as g0 and g2 for the second half */
4240         assert(bld.group() < 32);
4241         const fs_reg header_sources[2] = {
4242            retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4243            retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD),
4244         };
4245         ubld.LOAD_PAYLOAD(header, header_sources, 2, 0);
4246      }
4247
4248      uint32_t g00_bits = 0;
4249
4250      /* Set "Source0 Alpha Present to RenderTarget" bit in message
4251       * header.
4252       */
4253      if (inst->target > 0 && prog_data->replicate_alpha)
4254         g00_bits |= 1 << 11;
4255
4256      /* Set computes stencil to render target */
4257      if (prog_data->computed_stencil)
4258         g00_bits |= 1 << 14;
4259
4260      if (g00_bits) {
4261         /* OR extra bits into g0.0 */
4262         ubld.group(1, 0).OR(component(header, 0),
4263                             retype(brw_vec1_grf(0, 0),
4264                                    BRW_REGISTER_TYPE_UD),
4265                             brw_imm_ud(g00_bits));
4266      }
4267
4268      /* Set the render target index for choosing BLEND_STATE. */
4269      if (inst->target > 0) {
4270         ubld.group(1, 0).MOV(component(header, 2), brw_imm_ud(inst->target));
4271      }
4272
4273      if (prog_data->uses_kill) {
4274         assert(bld.group() < 16);
4275         ubld.group(1, 0).MOV(retype(component(header, 15),
4276                                     BRW_REGISTER_TYPE_UW),
4277                              brw_flag_reg(0, 1));
4278      }
4279
4280      assert(length == 0);
4281      sources[0] = header;
4282      sources[1] = horiz_offset(header, 8);
4283      length = 2;
4284   }
4285   assert(length == 0 || length == 2);
4286   header_size = length;
4287
4288   if (payload.aa_dest_stencil_reg[0]) {
4289      assert(inst->group < 16);
4290      sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
4291      bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
4292         .MOV(sources[length],
4293              fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg[0], 0)));
4294      length++;
4295   }
4296
4297   if (src0_alpha.file != BAD_FILE) {
4298      for (unsigned i = 0; i < bld.dispatch_width() / 8; i++) {
4299         const fs_builder &ubld = bld.exec_all().group(8, i)
4300                                    .annotate("FB write src0 alpha");
4301         const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_F);
4302         ubld.MOV(tmp, horiz_offset(src0_alpha, i * 8));
4303         setup_color_payload(ubld, key, &sources[length], tmp, 1);
4304         length++;
4305      }
4306   } else if (prog_data->replicate_alpha && inst->target != 0) {
4307      /* Handle the case when fragment shader doesn't write to draw buffer
4308       * zero. No need to call setup_color_payload() for src0_alpha because
4309       * alpha value will be undefined.
4310       */
4311      length += bld.dispatch_width() / 8;
4312   }
4313
4314   if (sample_mask.file != BAD_FILE) {
4315      sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
4316                               BRW_REGISTER_TYPE_UD);
4317
4318      /* Hand over gl_SampleMask.  Only the lower 16 bits of each channel are
4319       * relevant.  Since it's unsigned single words one vgrf is always
4320       * 16-wide, but only the lower or higher 8 channels will be used by the
4321       * hardware when doing a SIMD8 write depending on whether we have
4322       * selected the subspans for the first or second half respectively.
4323       */
4324      assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
4325      sample_mask.type = BRW_REGISTER_TYPE_UW;
4326      sample_mask.stride *= 2;
4327
4328      bld.exec_all().annotate("FB write oMask")
4329         .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
4330                           inst->group % 16),
4331              sample_mask);
4332      length++;
4333   }
4334
4335   payload_header_size = length;
4336
4337   setup_color_payload(bld, key, &sources[length], color0, components);
4338   length += 4;
4339
4340   if (color1.file != BAD_FILE) {
4341      setup_color_payload(bld, key, &sources[length], color1, components);
4342      length += 4;
4343   }
4344
4345   if (src_depth.file != BAD_FILE) {
4346      sources[length] = src_depth;
4347      length++;
4348   }
4349
4350   if (dst_depth.file != BAD_FILE) {
4351      sources[length] = dst_depth;
4352      length++;
4353   }
4354
4355   if (src_stencil.file != BAD_FILE) {
4356      assert(devinfo->gen >= 9);
4357      assert(bld.dispatch_width() == 8);
4358
4359      /* XXX: src_stencil is only available on gen9+. dst_depth is never
4360       * available on gen9+. As such it's impossible to have both enabled at the
4361       * same time and therefore length cannot overrun the array.
4362       */
4363      assert(length < 15);
4364
4365      sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
4366      bld.exec_all().annotate("FB write OS")
4367         .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
4368              subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
4369      length++;
4370   }
4371
4372   fs_inst *load;
4373   if (devinfo->gen >= 7) {
4374      /* Send from the GRF */
4375      fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
4376      load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
4377      payload.nr = bld.shader->alloc.allocate(regs_written(load));
4378      load->dst = payload;
4379
4380      inst->src[0] = payload;
4381      inst->resize_sources(1);
4382   } else {
4383      /* Send from the MRF */
4384      load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
4385                              sources, length, payload_header_size);
4386
4387      /* On pre-SNB, we have to interlace the color values.  LOAD_PAYLOAD
4388       * will do this for us if we just give it a COMPR4 destination.
4389       */
4390      if (devinfo->gen < 6 && bld.dispatch_width() == 16)
4391         load->dst.nr |= BRW_MRF_COMPR4;
4392
4393      if (devinfo->gen < 6) {
4394         /* Set up src[0] for the implied MOV from grf0-1 */
4395         inst->resize_sources(1);
4396         inst->src[0] = brw_vec8_grf(0, 0);
4397      } else {
4398         inst->resize_sources(0);
4399      }
4400      inst->base_mrf = 1;
4401   }
4402
4403   inst->opcode = FS_OPCODE_FB_WRITE;
4404   inst->mlen = regs_written(load);
4405   inst->header_size = header_size;
4406}
4407
4408static void
4409lower_fb_read_logical_send(const fs_builder &bld, fs_inst *inst)
4410{
4411   const fs_builder &ubld = bld.exec_all().group(8, 0);
4412   const unsigned length = 2;
4413   const fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, length);
4414
4415   if (bld.group() < 16) {
4416      ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4417                                           BRW_REGISTER_TYPE_UD));
4418   } else {
4419      assert(bld.group() < 32);
4420      const fs_reg header_sources[] = {
4421         retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4422         retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD)
4423      };
4424      ubld.LOAD_PAYLOAD(header, header_sources, ARRAY_SIZE(header_sources), 0);
4425   }
4426
4427   inst->resize_sources(1);
4428   inst->src[0] = header;
4429   inst->opcode = FS_OPCODE_FB_READ;
4430   inst->mlen = length;
4431   inst->header_size = length;
4432}
4433
4434static void
4435lower_sampler_logical_send_gen4(const fs_builder &bld, fs_inst *inst, opcode op,
4436                                const fs_reg &coordinate,
4437                                const fs_reg &shadow_c,
4438                                const fs_reg &lod, const fs_reg &lod2,
4439                                const fs_reg &surface,
4440                                const fs_reg &sampler,
4441                                unsigned coord_components,
4442                                unsigned grad_components)
4443{
4444   const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
4445                         op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
4446   fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
4447   fs_reg msg_end = msg_begin;
4448
4449   /* g0 header. */
4450   msg_end = offset(msg_end, bld.group(8, 0), 1);
4451
4452   for (unsigned i = 0; i < coord_components; i++)
4453      bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
4454              offset(coordinate, bld, i));
4455
4456   msg_end = offset(msg_end, bld, coord_components);
4457
4458   /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
4459    * require all three components to be present and zero if they are unused.
4460    */
4461   if (coord_components > 0 &&
4462       (has_lod || shadow_c.file != BAD_FILE ||
4463        (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
4464      for (unsigned i = coord_components; i < 3; i++)
4465         bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
4466
4467      msg_end = offset(msg_end, bld, 3 - coord_components);
4468   }
4469
4470   if (op == SHADER_OPCODE_TXD) {
4471      /* TXD unsupported in SIMD16 mode. */
4472      assert(bld.dispatch_width() == 8);
4473
4474      /* the slots for u and v are always present, but r is optional */
4475      if (coord_components < 2)
4476         msg_end = offset(msg_end, bld, 2 - coord_components);
4477
4478      /*  P   = u, v, r
4479       * dPdx = dudx, dvdx, drdx
4480       * dPdy = dudy, dvdy, drdy
4481       *
4482       * 1-arg: Does not exist.
4483       *
4484       * 2-arg: dudx   dvdx   dudy   dvdy
4485       *        dPdx.x dPdx.y dPdy.x dPdy.y
4486       *        m4     m5     m6     m7
4487       *
4488       * 3-arg: dudx   dvdx   drdx   dudy   dvdy   drdy
4489       *        dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
4490       *        m5     m6     m7     m8     m9     m10
4491       */
4492      for (unsigned i = 0; i < grad_components; i++)
4493         bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
4494
4495      msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4496
4497      for (unsigned i = 0; i < grad_components; i++)
4498         bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
4499
4500      msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4501   }
4502
4503   if (has_lod) {
4504      /* Bias/LOD with shadow comparator is unsupported in SIMD16 -- *Without*
4505       * shadow comparator (including RESINFO) it's unsupported in SIMD8 mode.
4506       */
4507      assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
4508             bld.dispatch_width() == 16);
4509
4510      const brw_reg_type type =
4511         (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
4512          BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
4513      bld.MOV(retype(msg_end, type), lod);
4514      msg_end = offset(msg_end, bld, 1);
4515   }
4516
4517   if (shadow_c.file != BAD_FILE) {
4518      if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
4519         /* There's no plain shadow compare message, so we use shadow
4520          * compare with a bias of 0.0.
4521          */
4522         bld.MOV(msg_end, brw_imm_f(0.0f));
4523         msg_end = offset(msg_end, bld, 1);
4524      }
4525
4526      bld.MOV(msg_end, shadow_c);
4527      msg_end = offset(msg_end, bld, 1);
4528   }
4529
4530   inst->opcode = op;
4531   inst->src[0] = reg_undef;
4532   inst->src[1] = surface;
4533   inst->src[2] = sampler;
4534   inst->resize_sources(3);
4535   inst->base_mrf = msg_begin.nr;
4536   inst->mlen = msg_end.nr - msg_begin.nr;
4537   inst->header_size = 1;
4538}
4539
4540static void
4541lower_sampler_logical_send_gen5(const fs_builder &bld, fs_inst *inst, opcode op,
4542                                const fs_reg &coordinate,
4543                                const fs_reg &shadow_c,
4544                                const fs_reg &lod, const fs_reg &lod2,
4545                                const fs_reg &sample_index,
4546                                const fs_reg &surface,
4547                                const fs_reg &sampler,
4548                                unsigned coord_components,
4549                                unsigned grad_components)
4550{
4551   fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
4552   fs_reg msg_coords = message;
4553   unsigned header_size = 0;
4554
4555   if (inst->offset != 0) {
4556      /* The offsets set up by the visitor are in the m1 header, so we can't
4557       * go headerless.
4558       */
4559      header_size = 1;
4560      message.nr--;
4561   }
4562
4563   for (unsigned i = 0; i < coord_components; i++)
4564      bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
4565              offset(coordinate, bld, i));
4566
4567   fs_reg msg_end = offset(msg_coords, bld, coord_components);
4568   fs_reg msg_lod = offset(msg_coords, bld, 4);
4569
4570   if (shadow_c.file != BAD_FILE) {
4571      fs_reg msg_shadow = msg_lod;
4572      bld.MOV(msg_shadow, shadow_c);
4573      msg_lod = offset(msg_shadow, bld, 1);
4574      msg_end = msg_lod;
4575   }
4576
4577   switch (op) {
4578   case SHADER_OPCODE_TXL:
4579   case FS_OPCODE_TXB:
4580      bld.MOV(msg_lod, lod);
4581      msg_end = offset(msg_lod, bld, 1);
4582      break;
4583   case SHADER_OPCODE_TXD:
4584      /**
4585       *  P   =  u,    v,    r
4586       * dPdx = dudx, dvdx, drdx
4587       * dPdy = dudy, dvdy, drdy
4588       *
4589       * Load up these values:
4590       * - dudx   dudy   dvdx   dvdy   drdx   drdy
4591       * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
4592       */
4593      msg_end = msg_lod;
4594      for (unsigned i = 0; i < grad_components; i++) {
4595         bld.MOV(msg_end, offset(lod, bld, i));
4596         msg_end = offset(msg_end, bld, 1);
4597
4598         bld.MOV(msg_end, offset(lod2, bld, i));
4599         msg_end = offset(msg_end, bld, 1);
4600      }
4601      break;
4602   case SHADER_OPCODE_TXS:
4603      msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
4604      bld.MOV(msg_lod, lod);
4605      msg_end = offset(msg_lod, bld, 1);
4606      break;
4607   case SHADER_OPCODE_TXF:
4608      msg_lod = offset(msg_coords, bld, 3);
4609      bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
4610      msg_end = offset(msg_lod, bld, 1);
4611      break;
4612   case SHADER_OPCODE_TXF_CMS:
4613      msg_lod = offset(msg_coords, bld, 3);
4614      /* lod */
4615      bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
4616      /* sample index */
4617      bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
4618      msg_end = offset(msg_lod, bld, 2);
4619      break;
4620   default:
4621      break;
4622   }
4623
4624   inst->opcode = op;
4625   inst->src[0] = reg_undef;
4626   inst->src[1] = surface;
4627   inst->src[2] = sampler;
4628   inst->resize_sources(3);
4629   inst->base_mrf = message.nr;
4630   inst->mlen = msg_end.nr - message.nr;
4631   inst->header_size = header_size;
4632
4633   /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4634   assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4635}
4636
4637static bool
4638is_high_sampler(const struct gen_device_info *devinfo, const fs_reg &sampler)
4639{
4640   if (devinfo->gen < 8 && !devinfo->is_haswell)
4641      return false;
4642
4643   return sampler.file != IMM || sampler.ud >= 16;
4644}
4645
4646static unsigned
4647sampler_msg_type(const gen_device_info *devinfo,
4648                 opcode opcode, bool shadow_compare)
4649{
4650   assert(devinfo->gen >= 5);
4651   switch (opcode) {
4652   case SHADER_OPCODE_TEX:
4653      return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_COMPARE :
4654                              GEN5_SAMPLER_MESSAGE_SAMPLE;
4655   case FS_OPCODE_TXB:
4656      return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS_COMPARE :
4657                              GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS;
4658   case SHADER_OPCODE_TXL:
4659      return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_LOD_COMPARE :
4660                              GEN5_SAMPLER_MESSAGE_SAMPLE_LOD;
4661   case SHADER_OPCODE_TXL_LZ:
4662      return shadow_compare ? GEN9_SAMPLER_MESSAGE_SAMPLE_C_LZ :
4663                              GEN9_SAMPLER_MESSAGE_SAMPLE_LZ;
4664   case SHADER_OPCODE_TXS:
4665   case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4666      return GEN5_SAMPLER_MESSAGE_SAMPLE_RESINFO;
4667   case SHADER_OPCODE_TXD:
4668      assert(!shadow_compare || devinfo->gen >= 8 || devinfo->is_haswell);
4669      return shadow_compare ? HSW_SAMPLER_MESSAGE_SAMPLE_DERIV_COMPARE :
4670                              GEN5_SAMPLER_MESSAGE_SAMPLE_DERIVS;
4671   case SHADER_OPCODE_TXF:
4672      return GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4673   case SHADER_OPCODE_TXF_LZ:
4674      assert(devinfo->gen >= 9);
4675      return GEN9_SAMPLER_MESSAGE_SAMPLE_LD_LZ;
4676   case SHADER_OPCODE_TXF_CMS_W:
4677      assert(devinfo->gen >= 9);
4678      return GEN9_SAMPLER_MESSAGE_SAMPLE_LD2DMS_W;
4679   case SHADER_OPCODE_TXF_CMS:
4680      return devinfo->gen >= 7 ? GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DMS :
4681                                 GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4682   case SHADER_OPCODE_TXF_UMS:
4683      assert(devinfo->gen >= 7);
4684      return GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DSS;
4685   case SHADER_OPCODE_TXF_MCS:
4686      assert(devinfo->gen >= 7);
4687      return GEN7_SAMPLER_MESSAGE_SAMPLE_LD_MCS;
4688   case SHADER_OPCODE_LOD:
4689      return GEN5_SAMPLER_MESSAGE_LOD;
4690   case SHADER_OPCODE_TG4:
4691      assert(devinfo->gen >= 7);
4692      return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_C :
4693                              GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4;
4694      break;
4695   case SHADER_OPCODE_TG4_OFFSET:
4696      assert(devinfo->gen >= 7);
4697      return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO_C :
4698                              GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO;
4699   case SHADER_OPCODE_SAMPLEINFO:
4700      return GEN6_SAMPLER_MESSAGE_SAMPLE_SAMPLEINFO;
4701   default:
4702      unreachable("not reached");
4703   }
4704}
4705
4706static void
4707lower_sampler_logical_send_gen7(const fs_builder &bld, fs_inst *inst, opcode op,
4708                                const fs_reg &coordinate,
4709                                const fs_reg &shadow_c,
4710                                fs_reg lod, const fs_reg &lod2,
4711                                const fs_reg &min_lod,
4712                                const fs_reg &sample_index,
4713                                const fs_reg &mcs,
4714                                const fs_reg &surface,
4715                                const fs_reg &sampler,
4716                                const fs_reg &surface_handle,
4717                                const fs_reg &sampler_handle,
4718                                const fs_reg &tg4_offset,
4719                                unsigned coord_components,
4720                                unsigned grad_components)
4721{
4722   const gen_device_info *devinfo = bld.shader->devinfo;
4723   const brw_stage_prog_data *prog_data = bld.shader->stage_prog_data;
4724   unsigned reg_width = bld.dispatch_width() / 8;
4725   unsigned header_size = 0, length = 0;
4726   fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
4727   for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
4728      sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
4729
4730   /* We must have exactly one of surface/sampler and surface/sampler_handle */
4731   assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
4732   assert((sampler.file == BAD_FILE) != (sampler_handle.file == BAD_FILE));
4733
4734   if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
4735       inst->offset != 0 || inst->eot ||
4736       op == SHADER_OPCODE_SAMPLEINFO ||
4737       sampler_handle.file != BAD_FILE ||
4738       is_high_sampler(devinfo, sampler)) {
4739      /* For general texture offsets (no txf workaround), we need a header to
4740       * put them in.
4741       *
4742       * TG4 needs to place its channel select in the header, for interaction
4743       * with ARB_texture_swizzle.  The sampler index is only 4-bits, so for
4744       * larger sampler numbers we need to offset the Sampler State Pointer in
4745       * the header.
4746       */
4747      fs_reg header = retype(sources[0], BRW_REGISTER_TYPE_UD);
4748      header_size = 1;
4749      length++;
4750
4751      /* If we're requesting fewer than four channels worth of response,
4752       * and we have an explicit header, we need to set up the sampler
4753       * writemask.  It's reversed from normal: 1 means "don't write".
4754       */
4755      if (!inst->eot && regs_written(inst) != 4 * reg_width) {
4756         assert(regs_written(inst) % reg_width == 0);
4757         unsigned mask = ~((1 << (regs_written(inst) / reg_width)) - 1) & 0xf;
4758         inst->offset |= mask << 12;
4759      }
4760
4761      /* Build the actual header */
4762      const fs_builder ubld = bld.exec_all().group(8, 0);
4763      const fs_builder ubld1 = ubld.group(1, 0);
4764      ubld.MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
4765      if (inst->offset) {
4766         ubld1.MOV(component(header, 2), brw_imm_ud(inst->offset));
4767      } else if (bld.shader->stage != MESA_SHADER_VERTEX &&
4768                 bld.shader->stage != MESA_SHADER_FRAGMENT) {
4769         /* The vertex and fragment stages have g0.2 set to 0, so
4770          * header0.2 is 0 when g0 is copied. Other stages may not, so we
4771          * must set it to 0 to avoid setting undesirable bits in the
4772          * message.
4773          */
4774         ubld1.MOV(component(header, 2), brw_imm_ud(0));
4775      }
4776
4777      if (sampler_handle.file != BAD_FILE) {
4778         /* Bindless sampler handles aren't relative to the sampler state
4779          * pointer passed into the shader through SAMPLER_STATE_POINTERS_*.
4780          * Instead, it's an absolute pointer relative to dynamic state base
4781          * address.
4782          *
4783          * Sampler states are 16 bytes each and the pointer we give here has
4784          * to be 32-byte aligned.  In order to avoid more indirect messages
4785          * than required, we assume that all bindless sampler states are
4786          * 32-byte aligned.  This sacrifices a bit of general state base
4787          * address space but means we can do something more efficient in the
4788          * shader.
4789          */
4790         ubld1.MOV(component(header, 3), sampler_handle);
4791      } else if (is_high_sampler(devinfo, sampler)) {
4792         if (sampler.file == BRW_IMMEDIATE_VALUE) {
4793            assert(sampler.ud >= 16);
4794            const int sampler_state_size = 16; /* 16 bytes */
4795
4796            ubld1.ADD(component(header, 3),
4797                      retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4798                      brw_imm_ud(16 * (sampler.ud / 16) * sampler_state_size));
4799         } else {
4800            fs_reg tmp = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
4801            ubld1.AND(tmp, sampler, brw_imm_ud(0x0f0));
4802            ubld1.SHL(tmp, tmp, brw_imm_ud(4));
4803            ubld1.ADD(component(header, 3),
4804                      retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4805                      tmp);
4806         }
4807      }
4808   }
4809
4810   if (shadow_c.file != BAD_FILE) {
4811      bld.MOV(sources[length], shadow_c);
4812      length++;
4813   }
4814
4815   bool coordinate_done = false;
4816
4817   /* Set up the LOD info */
4818   switch (op) {
4819   case FS_OPCODE_TXB:
4820   case SHADER_OPCODE_TXL:
4821      if (devinfo->gen >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
4822         op = SHADER_OPCODE_TXL_LZ;
4823         break;
4824      }
4825      bld.MOV(sources[length], lod);
4826      length++;
4827      break;
4828   case SHADER_OPCODE_TXD:
4829      /* TXD should have been lowered in SIMD16 mode. */
4830      assert(bld.dispatch_width() == 8);
4831
4832      /* Load dPdx and the coordinate together:
4833       * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
4834       */
4835      for (unsigned i = 0; i < coord_components; i++) {
4836         bld.MOV(sources[length++], offset(coordinate, bld, i));
4837
4838         /* For cube map array, the coordinate is (u,v,r,ai) but there are
4839          * only derivatives for (u, v, r).
4840          */
4841         if (i < grad_components) {
4842            bld.MOV(sources[length++], offset(lod, bld, i));
4843            bld.MOV(sources[length++], offset(lod2, bld, i));
4844         }
4845      }
4846
4847      coordinate_done = true;
4848      break;
4849   case SHADER_OPCODE_TXS:
4850      bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
4851      length++;
4852      break;
4853   case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4854      /* We need an LOD; just use 0 */
4855      bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), brw_imm_ud(0));
4856      length++;
4857      break;
4858   case SHADER_OPCODE_TXF:
4859      /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
4860       * On Gen9 they are u, v, lod, r
4861       */
4862      bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
4863
4864      if (devinfo->gen >= 9) {
4865         if (coord_components >= 2) {
4866            bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
4867                    offset(coordinate, bld, 1));
4868         } else {
4869            sources[length] = brw_imm_d(0);
4870         }
4871         length++;
4872      }
4873
4874      if (devinfo->gen >= 9 && lod.is_zero()) {
4875         op = SHADER_OPCODE_TXF_LZ;
4876      } else {
4877         bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
4878         length++;
4879      }
4880
4881      for (unsigned i = devinfo->gen >= 9 ? 2 : 1; i < coord_components; i++)
4882         bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4883                 offset(coordinate, bld, i));
4884
4885      coordinate_done = true;
4886      break;
4887
4888   case SHADER_OPCODE_TXF_CMS:
4889   case SHADER_OPCODE_TXF_CMS_W:
4890   case SHADER_OPCODE_TXF_UMS:
4891   case SHADER_OPCODE_TXF_MCS:
4892      if (op == SHADER_OPCODE_TXF_UMS ||
4893          op == SHADER_OPCODE_TXF_CMS ||
4894          op == SHADER_OPCODE_TXF_CMS_W) {
4895         bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
4896         length++;
4897      }
4898
4899      if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
4900         /* Data from the multisample control surface. */
4901         bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
4902         length++;
4903
4904         /* On Gen9+ we'll use ld2dms_w instead which has two registers for
4905          * the MCS data.
4906          */
4907         if (op == SHADER_OPCODE_TXF_CMS_W) {
4908            bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
4909                    mcs.file == IMM ?
4910                    mcs :
4911                    offset(mcs, bld, 1));
4912            length++;
4913         }
4914      }
4915
4916      /* There is no offsetting for this message; just copy in the integer
4917       * texture coordinates.
4918       */
4919      for (unsigned i = 0; i < coord_components; i++)
4920         bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4921                 offset(coordinate, bld, i));
4922
4923      coordinate_done = true;
4924      break;
4925   case SHADER_OPCODE_TG4_OFFSET:
4926      /* More crazy intermixing */
4927      for (unsigned i = 0; i < 2; i++) /* u, v */
4928         bld.MOV(sources[length++], offset(coordinate, bld, i));
4929
4930      for (unsigned i = 0; i < 2; i++) /* offu, offv */
4931         bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4932                 offset(tg4_offset, bld, i));
4933
4934      if (coord_components == 3) /* r if present */
4935         bld.MOV(sources[length++], offset(coordinate, bld, 2));
4936
4937      coordinate_done = true;
4938      break;
4939   default:
4940      break;
4941   }
4942
4943   /* Set up the coordinate (except for cases where it was done above) */
4944   if (!coordinate_done) {
4945      for (unsigned i = 0; i < coord_components; i++)
4946         bld.MOV(sources[length++], offset(coordinate, bld, i));
4947   }
4948
4949   if (min_lod.file != BAD_FILE) {
4950      /* Account for all of the missing coordinate sources */
4951      length += 4 - coord_components;
4952      if (op == SHADER_OPCODE_TXD)
4953         length += (3 - grad_components) * 2;
4954
4955      bld.MOV(sources[length++], min_lod);
4956   }
4957
4958   unsigned mlen;
4959   if (reg_width == 2)
4960      mlen = length * reg_width - header_size;
4961   else
4962      mlen = length * reg_width;
4963
4964   const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
4965                                     BRW_REGISTER_TYPE_F);
4966   bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
4967
4968   /* Generate the SEND. */
4969   inst->opcode = SHADER_OPCODE_SEND;
4970   inst->mlen = mlen;
4971   inst->header_size = header_size;
4972
4973   const unsigned msg_type =
4974      sampler_msg_type(devinfo, op, inst->shadow_compare);
4975   const unsigned simd_mode =
4976      inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
4977                             BRW_SAMPLER_SIMD_MODE_SIMD16;
4978
4979   uint32_t base_binding_table_index;
4980   switch (op) {
4981   case SHADER_OPCODE_TG4:
4982   case SHADER_OPCODE_TG4_OFFSET:
4983      base_binding_table_index = prog_data->binding_table.gather_texture_start;
4984      break;
4985   case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4986      base_binding_table_index = prog_data->binding_table.image_start;
4987      break;
4988   default:
4989      base_binding_table_index = prog_data->binding_table.texture_start;
4990      break;
4991   }
4992
4993   inst->sfid = BRW_SFID_SAMPLER;
4994   if (surface.file == IMM &&
4995       (sampler.file == IMM || sampler_handle.file != BAD_FILE)) {
4996      inst->desc = brw_sampler_desc(devinfo,
4997                                    surface.ud + base_binding_table_index,
4998                                    sampler.file == IMM ? sampler.ud % 16 : 0,
4999                                    msg_type,
5000                                    simd_mode,
5001                                    0 /* return_format unused on gen7+ */);
5002      inst->src[0] = brw_imm_ud(0);
5003      inst->src[1] = brw_imm_ud(0); /* ex_desc */
5004   } else if (surface_handle.file != BAD_FILE) {
5005      /* Bindless surface */
5006      assert(devinfo->gen >= 9);
5007      inst->desc = brw_sampler_desc(devinfo,
5008                                    GEN9_BTI_BINDLESS,
5009                                    sampler.file == IMM ? sampler.ud % 16 : 0,
5010                                    msg_type,
5011                                    simd_mode,
5012                                    0 /* return_format unused on gen7+ */);
5013
5014      /* For bindless samplers, the entire address is included in the message
5015       * header so we can leave the portion in the message descriptor 0.
5016       */
5017      if (sampler_handle.file != BAD_FILE || sampler.file == IMM) {
5018         inst->src[0] = brw_imm_ud(0);
5019      } else {
5020         const fs_builder ubld = bld.group(1, 0).exec_all();
5021         fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5022         ubld.SHL(desc, sampler, brw_imm_ud(8));
5023         inst->src[0] = desc;
5024      }
5025
5026      /* We assume that the driver provided the handle in the top 20 bits so
5027       * we can use the surface handle directly as the extended descriptor.
5028       */
5029      inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5030   } else {
5031      /* Immediate portion of the descriptor */
5032      inst->desc = brw_sampler_desc(devinfo,
5033                                    0, /* surface */
5034                                    0, /* sampler */
5035                                    msg_type,
5036                                    simd_mode,
5037                                    0 /* return_format unused on gen7+ */);
5038      const fs_builder ubld = bld.group(1, 0).exec_all();
5039      fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5040      if (surface.equals(sampler)) {
5041         /* This case is common in GL */
5042         ubld.MUL(desc, surface, brw_imm_ud(0x101));
5043      } else {
5044         if (sampler_handle.file != BAD_FILE) {
5045            ubld.MOV(desc, surface);
5046         } else if (sampler.file == IMM) {
5047            ubld.OR(desc, surface, brw_imm_ud(sampler.ud << 8));
5048         } else {
5049            ubld.SHL(desc, sampler, brw_imm_ud(8));
5050            ubld.OR(desc, desc, surface);
5051         }
5052      }
5053      if (base_binding_table_index)
5054         ubld.ADD(desc, desc, brw_imm_ud(base_binding_table_index));
5055      ubld.AND(desc, desc, brw_imm_ud(0xfff));
5056
5057      inst->src[0] = component(desc, 0);
5058      inst->src[1] = brw_imm_ud(0); /* ex_desc */
5059   }
5060
5061   inst->src[2] = src_payload;
5062   inst->resize_sources(3);
5063
5064   if (inst->eot) {
5065      /* EOT sampler messages don't make sense to split because it would
5066       * involve ending half of the thread early.
5067       */
5068      assert(inst->group == 0);
5069      /* We need to use SENDC for EOT sampler messages */
5070      inst->check_tdr = true;
5071      inst->send_has_side_effects = true;
5072   }
5073
5074   /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
5075   assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
5076}
5077
5078static void
5079lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
5080{
5081   const gen_device_info *devinfo = bld.shader->devinfo;
5082   const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
5083   const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
5084   const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
5085   const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
5086   const fs_reg &min_lod = inst->src[TEX_LOGICAL_SRC_MIN_LOD];
5087   const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
5088   const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
5089   const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
5090   const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
5091   const fs_reg &surface_handle = inst->src[TEX_LOGICAL_SRC_SURFACE_HANDLE];
5092   const fs_reg &sampler_handle = inst->src[TEX_LOGICAL_SRC_SAMPLER_HANDLE];
5093   const fs_reg &tg4_offset = inst->src[TEX_LOGICAL_SRC_TG4_OFFSET];
5094   assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
5095   const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
5096   assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
5097   const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
5098
5099   if (devinfo->gen >= 7) {
5100      lower_sampler_logical_send_gen7(bld, inst, op, coordinate,
5101                                      shadow_c, lod, lod2, min_lod,
5102                                      sample_index,
5103                                      mcs, surface, sampler,
5104                                      surface_handle, sampler_handle,
5105                                      tg4_offset,
5106                                      coord_components, grad_components);
5107   } else if (devinfo->gen >= 5) {
5108      lower_sampler_logical_send_gen5(bld, inst, op, coordinate,
5109                                      shadow_c, lod, lod2, sample_index,
5110                                      surface, sampler,
5111                                      coord_components, grad_components);
5112   } else {
5113      lower_sampler_logical_send_gen4(bld, inst, op, coordinate,
5114                                      shadow_c, lod, lod2,
5115                                      surface, sampler,
5116                                      coord_components, grad_components);
5117   }
5118}
5119
5120/**
5121 * Initialize the header present in some typed and untyped surface
5122 * messages.
5123 */
5124static fs_reg
5125emit_surface_header(const fs_builder &bld, const fs_reg &sample_mask)
5126{
5127   fs_builder ubld = bld.exec_all().group(8, 0);
5128   const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5129   ubld.MOV(dst, brw_imm_d(0));
5130   ubld.group(1, 0).MOV(component(dst, 7), sample_mask);
5131   return dst;
5132}
5133
5134static void
5135lower_surface_logical_send(const fs_builder &bld, fs_inst *inst)
5136{
5137   const gen_device_info *devinfo = bld.shader->devinfo;
5138
5139   /* Get the logical send arguments. */
5140   const fs_reg &addr = inst->src[SURFACE_LOGICAL_SRC_ADDRESS];
5141   const fs_reg &src = inst->src[SURFACE_LOGICAL_SRC_DATA];
5142   const fs_reg &surface = inst->src[SURFACE_LOGICAL_SRC_SURFACE];
5143   const fs_reg &surface_handle = inst->src[SURFACE_LOGICAL_SRC_SURFACE_HANDLE];
5144   const UNUSED fs_reg &dims = inst->src[SURFACE_LOGICAL_SRC_IMM_DIMS];
5145   const fs_reg &arg = inst->src[SURFACE_LOGICAL_SRC_IMM_ARG];
5146   assert(arg.file == IMM);
5147
5148   /* We must have exactly one of surface and surface_handle */
5149   assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
5150
5151   /* Calculate the total number of components of the payload. */
5152   const unsigned addr_sz = inst->components_read(SURFACE_LOGICAL_SRC_ADDRESS);
5153   const unsigned src_sz = inst->components_read(SURFACE_LOGICAL_SRC_DATA);
5154
5155   const bool is_typed_access =
5156      inst->opcode == SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL ||
5157      inst->opcode == SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL ||
5158      inst->opcode == SHADER_OPCODE_TYPED_ATOMIC_LOGICAL;
5159
5160   /* From the BDW PRM Volume 7, page 147:
5161    *
5162    *  "For the Data Cache Data Port*, the header must be present for the
5163    *   following message types: [...] Typed read/write/atomics"
5164    *
5165    * Earlier generations have a similar wording.  Because of this restriction
5166    * we don't attempt to implement sample masks via predication for such
5167    * messages prior to Gen9, since we have to provide a header anyway.  On
5168    * Gen11+ the header has been removed so we can only use predication.
5169    */
5170   const unsigned header_sz = devinfo->gen < 9 && is_typed_access ? 1 : 0;
5171
5172   const bool has_side_effects = inst->has_side_effects();
5173   fs_reg sample_mask = has_side_effects ? bld.sample_mask_reg() :
5174                                           fs_reg(brw_imm_d(0xffff));
5175
5176   fs_reg payload, payload2;
5177   unsigned mlen, ex_mlen = 0;
5178   if (devinfo->gen >= 9) {
5179      /* We have split sends on gen9 and above */
5180      assert(header_sz == 0);
5181      payload = bld.move_to_vgrf(addr, addr_sz);
5182      payload2 = bld.move_to_vgrf(src, src_sz);
5183      mlen = addr_sz * (inst->exec_size / 8);
5184      ex_mlen = src_sz * (inst->exec_size / 8);
5185   } else {
5186      /* Allocate space for the payload. */
5187      const unsigned sz = header_sz + addr_sz + src_sz;
5188      payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
5189      fs_reg *const components = new fs_reg[sz];
5190      unsigned n = 0;
5191
5192      /* Construct the payload. */
5193      if (header_sz)
5194         components[n++] = emit_surface_header(bld, sample_mask);
5195
5196      for (unsigned i = 0; i < addr_sz; i++)
5197         components[n++] = offset(addr, bld, i);
5198
5199      for (unsigned i = 0; i < src_sz; i++)
5200         components[n++] = offset(src, bld, i);
5201
5202      bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
5203      mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
5204
5205      delete[] components;
5206   }
5207
5208   /* Predicate the instruction on the sample mask if no header is
5209    * provided.
5210    */
5211   if (!header_sz && sample_mask.file != BAD_FILE &&
5212       sample_mask.file != IMM) {
5213      const fs_builder ubld = bld.group(1, 0).exec_all();
5214      if (inst->predicate) {
5215         assert(inst->predicate == BRW_PREDICATE_NORMAL);
5216         assert(!inst->predicate_inverse);
5217         assert(inst->flag_subreg < 2);
5218         /* Combine the sample mask with the existing predicate by using a
5219          * vertical predication mode.
5220          */
5221         inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
5222         ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg + 2),
5223                         sample_mask.type),
5224                  sample_mask);
5225      } else {
5226         inst->flag_subreg = 2;
5227         inst->predicate = BRW_PREDICATE_NORMAL;
5228         inst->predicate_inverse = false;
5229         ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5230                  sample_mask);
5231      }
5232   }
5233
5234   uint32_t sfid;
5235   switch (inst->opcode) {
5236   case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5237   case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5238      /* Byte scattered opcodes go through the normal data cache */
5239      sfid = GEN7_SFID_DATAPORT_DATA_CACHE;
5240      break;
5241
5242   case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5243   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5244   case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5245   case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5246      /* Untyped Surface messages go through the data cache but the SFID value
5247       * changed on Haswell.
5248       */
5249      sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5250              HSW_SFID_DATAPORT_DATA_CACHE_1 :
5251              GEN7_SFID_DATAPORT_DATA_CACHE);
5252      break;
5253
5254   case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5255   case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5256   case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5257      /* Typed surface messages go through the render cache on IVB and the
5258       * data cache on HSW+.
5259       */
5260      sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5261              HSW_SFID_DATAPORT_DATA_CACHE_1 :
5262              GEN6_SFID_DATAPORT_RENDER_CACHE);
5263      break;
5264
5265   default:
5266      unreachable("Unsupported surface opcode");
5267   }
5268
5269   uint32_t desc;
5270   switch (inst->opcode) {
5271   case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5272      desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5273                                            arg.ud, /* num_channels */
5274                                            false   /* write */);
5275      break;
5276
5277   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5278      desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5279                                            arg.ud, /* num_channels */
5280                                            true    /* write */);
5281      break;
5282
5283   case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5284      desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5285                                           arg.ud, /* bit_size */
5286                                           false   /* write */);
5287      break;
5288
5289   case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5290      desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5291                                           arg.ud, /* bit_size */
5292                                           true    /* write */);
5293      break;
5294
5295   case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5296      desc = brw_dp_untyped_atomic_desc(devinfo, inst->exec_size,
5297                                        arg.ud, /* atomic_op */
5298                                        !inst->dst.is_null());
5299      break;
5300
5301   case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5302      desc = brw_dp_untyped_atomic_float_desc(devinfo, inst->exec_size,
5303                                              arg.ud, /* atomic_op */
5304                                              !inst->dst.is_null());
5305      break;
5306
5307   case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5308      desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5309                                          arg.ud, /* num_channels */
5310                                          false   /* write */);
5311      break;
5312
5313   case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5314      desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5315                                          arg.ud, /* num_channels */
5316                                          true    /* write */);
5317      break;
5318
5319   case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5320      desc = brw_dp_typed_atomic_desc(devinfo, inst->exec_size, inst->group,
5321                                      arg.ud, /* atomic_op */
5322                                      !inst->dst.is_null());
5323      break;
5324
5325   default:
5326      unreachable("Unknown surface logical instruction");
5327   }
5328
5329   /* Update the original instruction. */
5330   inst->opcode = SHADER_OPCODE_SEND;
5331   inst->mlen = mlen;
5332   inst->ex_mlen = ex_mlen;
5333   inst->header_size = header_sz;
5334   inst->send_has_side_effects = has_side_effects;
5335   inst->send_is_volatile = !has_side_effects;
5336
5337   /* Set up SFID and descriptors */
5338   inst->sfid = sfid;
5339   inst->desc = desc;
5340   if (surface.file == IMM) {
5341      inst->desc |= surface.ud & 0xff;
5342      inst->src[0] = brw_imm_ud(0);
5343      inst->src[1] = brw_imm_ud(0); /* ex_desc */
5344   } else if (surface_handle.file != BAD_FILE) {
5345      /* Bindless surface */
5346      assert(devinfo->gen >= 9);
5347      inst->desc |= GEN9_BTI_BINDLESS;
5348      inst->src[0] = brw_imm_ud(0);
5349
5350      /* We assume that the driver provided the handle in the top 20 bits so
5351       * we can use the surface handle directly as the extended descriptor.
5352       */
5353      inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5354   } else {
5355      const fs_builder ubld = bld.exec_all().group(1, 0);
5356      fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5357      ubld.AND(tmp, surface, brw_imm_ud(0xff));
5358      inst->src[0] = component(tmp, 0);
5359      inst->src[1] = brw_imm_ud(0); /* ex_desc */
5360   }
5361
5362   /* Finally, the payload */
5363   inst->src[2] = payload;
5364   inst->src[3] = payload2;
5365
5366   inst->resize_sources(4);
5367}
5368
5369static void
5370lower_a64_logical_send(const fs_builder &bld, fs_inst *inst)
5371{
5372   const gen_device_info *devinfo = bld.shader->devinfo;
5373
5374   const fs_reg &addr = inst->src[0];
5375   const fs_reg &src = inst->src[1];
5376   const unsigned src_comps = inst->components_read(1);
5377   assert(inst->src[2].file == IMM);
5378   const unsigned arg = inst->src[2].ud;
5379   const bool has_side_effects = inst->has_side_effects();
5380
5381   /* If the surface message has side effects and we're a fragment shader, we
5382    * have to predicate with the sample mask to avoid helper invocations.
5383    */
5384   if (has_side_effects && bld.shader->stage == MESA_SHADER_FRAGMENT) {
5385      inst->flag_subreg = 2;
5386      inst->predicate = BRW_PREDICATE_NORMAL;
5387      inst->predicate_inverse = false;
5388
5389      fs_reg sample_mask = bld.sample_mask_reg();
5390      const fs_builder ubld = bld.group(1, 0).exec_all();
5391      ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5392               sample_mask);
5393   }
5394
5395   fs_reg payload, payload2;
5396   unsigned mlen, ex_mlen = 0;
5397   if (devinfo->gen >= 9) {
5398      /* On Skylake and above, we have SENDS */
5399      mlen = 2 * (inst->exec_size / 8);
5400      ex_mlen = src_comps * type_sz(src.type) * inst->exec_size / REG_SIZE;
5401      payload = retype(bld.move_to_vgrf(addr, 1), BRW_REGISTER_TYPE_UD);
5402      payload2 = retype(bld.move_to_vgrf(src, src_comps),
5403                        BRW_REGISTER_TYPE_UD);
5404   } else {
5405      /* Add two because the address is 64-bit */
5406      const unsigned dwords = 2 + src_comps;
5407      mlen = dwords * (inst->exec_size / 8);
5408
5409      fs_reg sources[5];
5410
5411      sources[0] = addr;
5412
5413      for (unsigned i = 0; i < src_comps; i++)
5414         sources[1 + i] = offset(src, bld, i);
5415
5416      payload = bld.vgrf(BRW_REGISTER_TYPE_UD, dwords);
5417      bld.LOAD_PAYLOAD(payload, sources, 1 + src_comps, 0);
5418   }
5419
5420   uint32_t desc;
5421   switch (inst->opcode) {
5422   case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5423      desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5424                                                arg,   /* num_channels */
5425                                                false  /* write */);
5426      break;
5427
5428   case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5429      desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5430                                                arg,   /* num_channels */
5431                                                true   /* write */);
5432      break;
5433
5434   case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5435      desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5436                                               arg,   /* bit_size */
5437                                               false  /* write */);
5438      break;
5439
5440   case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5441      desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5442                                               arg,   /* bit_size */
5443                                               true   /* write */);
5444      break;
5445
5446   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5447      desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 32,
5448                                            arg,   /* atomic_op */
5449                                            !inst->dst.is_null());
5450      break;
5451
5452   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
5453      desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 64,
5454                                            arg,   /* atomic_op */
5455                                            !inst->dst.is_null());
5456      break;
5457
5458
5459   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5460      desc = brw_dp_a64_untyped_atomic_float_desc(devinfo, inst->exec_size,
5461                                                  arg,   /* atomic_op */
5462                                                  !inst->dst.is_null());
5463      break;
5464
5465   default:
5466      unreachable("Unknown A64 logical instruction");
5467   }
5468
5469   /* Update the original instruction. */
5470   inst->opcode = SHADER_OPCODE_SEND;
5471   inst->mlen = mlen;
5472   inst->ex_mlen = ex_mlen;
5473   inst->header_size = 0;
5474   inst->send_has_side_effects = has_side_effects;
5475   inst->send_is_volatile = !has_side_effects;
5476
5477   /* Set up SFID and descriptors */
5478   inst->sfid = HSW_SFID_DATAPORT_DATA_CACHE_1;
5479   inst->desc = desc;
5480   inst->resize_sources(4);
5481   inst->src[0] = brw_imm_ud(0); /* desc */
5482   inst->src[1] = brw_imm_ud(0); /* ex_desc */
5483   inst->src[2] = payload;
5484   inst->src[3] = payload2;
5485}
5486
5487static void
5488lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
5489{
5490   const gen_device_info *devinfo = bld.shader->devinfo;
5491
5492   if (devinfo->gen >= 7) {
5493      fs_reg index = inst->src[0];
5494      /* We are switching the instruction from an ALU-like instruction to a
5495       * send-from-grf instruction.  Since sends can't handle strides or
5496       * source modifiers, we have to make a copy of the offset source.
5497       */
5498      fs_reg offset = bld.vgrf(BRW_REGISTER_TYPE_UD);
5499      bld.MOV(offset, inst->src[1]);
5500
5501      const unsigned simd_mode =
5502         inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
5503                                BRW_SAMPLER_SIMD_MODE_SIMD16;
5504
5505      inst->opcode = SHADER_OPCODE_SEND;
5506      inst->mlen = inst->exec_size / 8;
5507      inst->resize_sources(3);
5508
5509      inst->sfid = BRW_SFID_SAMPLER;
5510      inst->desc = brw_sampler_desc(devinfo, 0, 0,
5511                                    GEN5_SAMPLER_MESSAGE_SAMPLE_LD,
5512                                    simd_mode, 0);
5513      if (index.file == IMM) {
5514         inst->desc |= index.ud & 0xff;
5515         inst->src[0] = brw_imm_ud(0);
5516      } else {
5517         const fs_builder ubld = bld.exec_all().group(1, 0);
5518         fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5519         ubld.AND(tmp, index, brw_imm_ud(0xff));
5520         inst->src[0] = component(tmp, 0);
5521      }
5522      inst->src[1] = brw_imm_ud(0); /* ex_desc */
5523      inst->src[2] = offset; /* payload */
5524   } else {
5525      const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->gen),
5526                           BRW_REGISTER_TYPE_UD);
5527
5528      bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
5529
5530      inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4;
5531      inst->resize_sources(1);
5532      inst->base_mrf = payload.nr;
5533      inst->header_size = 1;
5534      inst->mlen = 1 + inst->exec_size / 8;
5535   }
5536}
5537
5538static void
5539lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
5540{
5541   assert(bld.shader->devinfo->gen < 6);
5542
5543   inst->base_mrf = 2;
5544   inst->mlen = inst->sources * inst->exec_size / 8;
5545
5546   if (inst->sources > 1) {
5547      /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
5548       * "Message Payload":
5549       *
5550       * "Operand0[7].  For the INT DIV functions, this operand is the
5551       *  denominator."
5552       *  ...
5553       * "Operand1[7].  For the INT DIV functions, this operand is the
5554       *  numerator."
5555       */
5556      const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
5557      const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
5558      const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
5559
5560      inst->resize_sources(1);
5561      inst->src[0] = src0;
5562
5563      assert(inst->exec_size == 8);
5564      bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
5565   }
5566}
5567
5568bool
5569fs_visitor::lower_logical_sends()
5570{
5571   bool progress = false;
5572
5573   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5574      const fs_builder ibld(this, block, inst);
5575
5576      switch (inst->opcode) {
5577      case FS_OPCODE_FB_WRITE_LOGICAL:
5578         assert(stage == MESA_SHADER_FRAGMENT);
5579         lower_fb_write_logical_send(ibld, inst,
5580                                     brw_wm_prog_data(prog_data),
5581                                     (const brw_wm_prog_key *)key,
5582                                     payload);
5583         break;
5584
5585      case FS_OPCODE_FB_READ_LOGICAL:
5586         lower_fb_read_logical_send(ibld, inst);
5587         break;
5588
5589      case SHADER_OPCODE_TEX_LOGICAL:
5590         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
5591         break;
5592
5593      case SHADER_OPCODE_TXD_LOGICAL:
5594         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
5595         break;
5596
5597      case SHADER_OPCODE_TXF_LOGICAL:
5598         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
5599         break;
5600
5601      case SHADER_OPCODE_TXL_LOGICAL:
5602         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
5603         break;
5604
5605      case SHADER_OPCODE_TXS_LOGICAL:
5606         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
5607         break;
5608
5609      case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5610         lower_sampler_logical_send(ibld, inst,
5611                                    SHADER_OPCODE_IMAGE_SIZE_LOGICAL);
5612         break;
5613
5614      case FS_OPCODE_TXB_LOGICAL:
5615         lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
5616         break;
5617
5618      case SHADER_OPCODE_TXF_CMS_LOGICAL:
5619         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
5620         break;
5621
5622      case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
5623         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
5624         break;
5625
5626      case SHADER_OPCODE_TXF_UMS_LOGICAL:
5627         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
5628         break;
5629
5630      case SHADER_OPCODE_TXF_MCS_LOGICAL:
5631         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
5632         break;
5633
5634      case SHADER_OPCODE_LOD_LOGICAL:
5635         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
5636         break;
5637
5638      case SHADER_OPCODE_TG4_LOGICAL:
5639         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
5640         break;
5641
5642      case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
5643         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
5644         break;
5645
5646      case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
5647         lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
5648         break;
5649
5650      case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5651      case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5652      case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5653      case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5654      case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5655      case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5656      case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5657      case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5658      case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5659         lower_surface_logical_send(ibld, inst);
5660         break;
5661
5662      case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5663      case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5664      case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5665      case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5666      case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5667      case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
5668      case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5669         lower_a64_logical_send(ibld, inst);
5670         break;
5671
5672      case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
5673         lower_varying_pull_constant_logical_send(ibld, inst);
5674         break;
5675
5676      case SHADER_OPCODE_RCP:
5677      case SHADER_OPCODE_RSQ:
5678      case SHADER_OPCODE_SQRT:
5679      case SHADER_OPCODE_EXP2:
5680      case SHADER_OPCODE_LOG2:
5681      case SHADER_OPCODE_SIN:
5682      case SHADER_OPCODE_COS:
5683      case SHADER_OPCODE_POW:
5684      case SHADER_OPCODE_INT_QUOTIENT:
5685      case SHADER_OPCODE_INT_REMAINDER:
5686         /* The math opcodes are overloaded for the send-like and
5687          * expression-like instructions which seems kind of icky.  Gen6+ has
5688          * a native (but rather quirky) MATH instruction so we don't need to
5689          * do anything here.  On Gen4-5 we'll have to lower the Gen6-like
5690          * logical instructions (which we can easily recognize because they
5691          * have mlen = 0) into send-like virtual instructions.
5692          */
5693         if (devinfo->gen < 6 && inst->mlen == 0) {
5694            lower_math_logical_send(ibld, inst);
5695            break;
5696
5697         } else {
5698            continue;
5699         }
5700
5701      default:
5702         continue;
5703      }
5704
5705      progress = true;
5706   }
5707
5708   if (progress)
5709      invalidate_live_intervals();
5710
5711   return progress;
5712}
5713
5714static bool
5715is_mixed_float_with_fp32_dst(const fs_inst *inst)
5716{
5717   /* This opcode sometimes uses :W type on the source even if the operand is
5718    * a :HF, because in gen7 there is no support for :HF, and thus it uses :W.
5719    */
5720   if (inst->opcode == BRW_OPCODE_F16TO32)
5721      return true;
5722
5723   if (inst->dst.type != BRW_REGISTER_TYPE_F)
5724      return false;
5725
5726   for (int i = 0; i < inst->sources; i++) {
5727      if (inst->src[i].type == BRW_REGISTER_TYPE_HF)
5728         return true;
5729   }
5730
5731   return false;
5732}
5733
5734static bool
5735is_mixed_float_with_packed_fp16_dst(const fs_inst *inst)
5736{
5737   /* This opcode sometimes uses :W type on the destination even if the
5738    * destination is a :HF, because in gen7 there is no support for :HF, and
5739    * thus it uses :W.
5740    */
5741   if (inst->opcode == BRW_OPCODE_F32TO16 &&
5742       inst->dst.stride == 1)
5743      return true;
5744
5745   if (inst->dst.type != BRW_REGISTER_TYPE_HF ||
5746       inst->dst.stride != 1)
5747      return false;
5748
5749   for (int i = 0; i < inst->sources; i++) {
5750      if (inst->src[i].type == BRW_REGISTER_TYPE_F)
5751         return true;
5752   }
5753
5754   return false;
5755}
5756
5757/**
5758 * Get the closest allowed SIMD width for instruction \p inst accounting for
5759 * some common regioning and execution control restrictions that apply to FPU
5760 * instructions.  These restrictions don't necessarily have any relevance to
5761 * instructions not executed by the FPU pipeline like extended math, control
5762 * flow or send message instructions.
5763 *
5764 * For virtual opcodes it's really up to the instruction -- In some cases
5765 * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
5766 * instructions) it may simplify virtual instruction lowering if we can
5767 * enforce FPU-like regioning restrictions already on the virtual instruction,
5768 * in other cases (e.g. virtual send-like instructions) this may be
5769 * excessively restrictive.
5770 */
5771static unsigned
5772get_fpu_lowered_simd_width(const struct gen_device_info *devinfo,
5773                           const fs_inst *inst)
5774{
5775   /* Maximum execution size representable in the instruction controls. */
5776   unsigned max_width = MIN2(32, inst->exec_size);
5777
5778   /* According to the PRMs:
5779    *  "A. In Direct Addressing mode, a source cannot span more than 2
5780    *      adjacent GRF registers.
5781    *   B. A destination cannot span more than 2 adjacent GRF registers."
5782    *
5783    * Look for the source or destination with the largest register region
5784    * which is the one that is going to limit the overall execution size of
5785    * the instruction due to this rule.
5786    */
5787   unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5788
5789   for (unsigned i = 0; i < inst->sources; i++)
5790      reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
5791
5792   /* Calculate the maximum execution size of the instruction based on the
5793    * factor by which it goes over the hardware limit of 2 GRFs.
5794    */
5795   if (reg_count > 2)
5796      max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
5797
5798   /* According to the IVB PRMs:
5799    *  "When destination spans two registers, the source MUST span two
5800    *   registers. The exception to the above rule:
5801    *
5802    *    - When source is scalar, the source registers are not incremented.
5803    *    - When source is packed integer Word and destination is packed
5804    *      integer DWord, the source register is not incremented but the
5805    *      source sub register is incremented."
5806    *
5807    * The hardware specs from Gen4 to Gen7.5 mention similar regioning
5808    * restrictions.  The code below intentionally doesn't check whether the
5809    * destination type is integer because empirically the hardware doesn't
5810    * seem to care what the actual type is as long as it's dword-aligned.
5811    */
5812   if (devinfo->gen < 8) {
5813      for (unsigned i = 0; i < inst->sources; i++) {
5814         /* IVB implements DF scalars as <0;2,1> regions. */
5815         const bool is_scalar_exception = is_uniform(inst->src[i]) &&
5816            (devinfo->is_haswell || type_sz(inst->src[i].type) != 8);
5817         const bool is_packed_word_exception =
5818            type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
5819            type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
5820
5821         /* We check size_read(i) against size_written instead of REG_SIZE
5822          * because we want to properly handle SIMD32.  In SIMD32, you can end
5823          * up with writes to 4 registers and a source that reads 2 registers
5824          * and we may still need to lower all the way to SIMD8 in that case.
5825          */
5826         if (inst->size_written > REG_SIZE &&
5827             inst->size_read(i) != 0 &&
5828             inst->size_read(i) < inst->size_written &&
5829             !is_scalar_exception && !is_packed_word_exception) {
5830            const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5831            max_width = MIN2(max_width, inst->exec_size / reg_count);
5832         }
5833      }
5834   }
5835
5836   if (devinfo->gen < 6) {
5837      /* From the G45 PRM, Volume 4 Page 361:
5838       *
5839       *    "Operand Alignment Rule: With the exceptions listed below, a
5840       *     source/destination operand in general should be aligned to even
5841       *     256-bit physical register with a region size equal to two 256-bit
5842       *     physical registers."
5843       *
5844       * Normally we enforce this by allocating virtual registers to the
5845       * even-aligned class.  But we need to handle payload registers.
5846       */
5847      for (unsigned i = 0; i < inst->sources; i++) {
5848         if (inst->src[i].file == FIXED_GRF && (inst->src[i].nr & 1) &&
5849             inst->size_read(i) > REG_SIZE) {
5850            max_width = MIN2(max_width, 8);
5851         }
5852      }
5853   }
5854
5855   /* From the IVB PRMs:
5856    *  "When an instruction is SIMD32, the low 16 bits of the execution mask
5857    *   are applied for both halves of the SIMD32 instruction. If different
5858    *   execution mask channels are required, split the instruction into two
5859    *   SIMD16 instructions."
5860    *
5861    * There is similar text in the HSW PRMs.  Gen4-6 don't even implement
5862    * 32-wide control flow support in hardware and will behave similarly.
5863    */
5864   if (devinfo->gen < 8 && !inst->force_writemask_all)
5865      max_width = MIN2(max_width, 16);
5866
5867   /* From the IVB PRMs (applies to HSW too):
5868    *  "Instructions with condition modifiers must not use SIMD32."
5869    *
5870    * From the BDW PRMs (applies to later hardware too):
5871    *  "Ternary instruction with condition modifiers must not use SIMD32."
5872    */
5873   if (inst->conditional_mod && (devinfo->gen < 8 || inst->is_3src(devinfo)))
5874      max_width = MIN2(max_width, 16);
5875
5876   /* From the IVB PRMs (applies to other devices that don't have the
5877    * gen_device_info::supports_simd16_3src flag set):
5878    *  "In Align16 access mode, SIMD16 is not allowed for DW operations and
5879    *   SIMD8 is not allowed for DF operations."
5880    */
5881   if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
5882      max_width = MIN2(max_width, inst->exec_size / reg_count);
5883
5884   /* Pre-Gen8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
5885    * the 8-bit quarter of the execution mask signals specified in the
5886    * instruction control fields) for the second compressed half of any
5887    * single-precision instruction (for double-precision instructions
5888    * it's hardwired to use NibCtrl+1, at least on HSW), which means that
5889    * the EU will apply the wrong execution controls for the second
5890    * sequential GRF write if the number of channels per GRF is not exactly
5891    * eight in single-precision mode (or four in double-float mode).
5892    *
5893    * In this situation we calculate the maximum size of the split
5894    * instructions so they only ever write to a single register.
5895    */
5896   if (devinfo->gen < 8 && inst->size_written > REG_SIZE &&
5897       !inst->force_writemask_all) {
5898      const unsigned channels_per_grf = inst->exec_size /
5899         DIV_ROUND_UP(inst->size_written, REG_SIZE);
5900      const unsigned exec_type_size = get_exec_type_size(inst);
5901      assert(exec_type_size);
5902
5903      /* The hardware shifts exactly 8 channels per compressed half of the
5904       * instruction in single-precision mode and exactly 4 in double-precision.
5905       */
5906      if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
5907         max_width = MIN2(max_width, channels_per_grf);
5908
5909      /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
5910       * because HW applies the same channel enable signals to both halves of
5911       * the compressed instruction which will be just wrong under
5912       * non-uniform control flow.
5913       */
5914      if (devinfo->gen == 7 && !devinfo->is_haswell &&
5915          (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
5916         max_width = MIN2(max_width, 4);
5917   }
5918
5919   /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
5920    * Float Operations:
5921    *
5922    *    "No SIMD16 in mixed mode when destination is f32. Instruction
5923    *     execution size must be no more than 8."
5924    *
5925    * FIXME: the simulator doesn't seem to complain if we don't do this and
5926    * empirical testing with existing CTS tests show that they pass just fine
5927    * without implementing this, however, since our interpretation of the PRM
5928    * is that conversion MOVs between HF and F are still mixed-float
5929    * instructions (and therefore subject to this restriction) we decided to
5930    * split them to be safe. Might be useful to do additional investigation to
5931    * lift the restriction if we can ensure that it is safe though, since these
5932    * conversions are common when half-float types are involved since many
5933    * instructions do not support HF types and conversions from/to F are
5934    * required.
5935    */
5936   if (is_mixed_float_with_fp32_dst(inst))
5937      max_width = MIN2(max_width, 8);
5938
5939   /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
5940    * Float Operations:
5941    *
5942    *    "No SIMD16 in mixed mode when destination is packed f16 for both
5943    *     Align1 and Align16."
5944    */
5945   if (is_mixed_float_with_packed_fp16_dst(inst))
5946      max_width = MIN2(max_width, 8);
5947
5948   /* Only power-of-two execution sizes are representable in the instruction
5949    * control fields.
5950    */
5951   return 1 << _mesa_logbase2(max_width);
5952}
5953
5954/**
5955 * Get the maximum allowed SIMD width for instruction \p inst accounting for
5956 * various payload size restrictions that apply to sampler message
5957 * instructions.
5958 *
5959 * This is only intended to provide a maximum theoretical bound for the
5960 * execution size of the message based on the number of argument components
5961 * alone, which in most cases will determine whether the SIMD8 or SIMD16
5962 * variant of the message can be used, though some messages may have
5963 * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
5964 * the message length to determine the exact SIMD width and argument count,
5965 * which makes a number of sampler message combinations impossible to
5966 * represent).
5967 */
5968static unsigned
5969get_sampler_lowered_simd_width(const struct gen_device_info *devinfo,
5970                               const fs_inst *inst)
5971{
5972   /* If we have a min_lod parameter on anything other than a simple sample
5973    * message, it will push it over 5 arguments and we have to fall back to
5974    * SIMD8.
5975    */
5976   if (inst->opcode != SHADER_OPCODE_TEX &&
5977       inst->components_read(TEX_LOGICAL_SRC_MIN_LOD))
5978      return 8;
5979
5980   /* Calculate the number of coordinate components that have to be present
5981    * assuming that additional arguments follow the texel coordinates in the
5982    * message payload.  On IVB+ there is no need for padding, on ILK-SNB we
5983    * need to pad to four or three components depending on the message,
5984    * pre-ILK we need to pad to at most three components.
5985    */
5986   const unsigned req_coord_components =
5987      (devinfo->gen >= 7 ||
5988       !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
5989      (devinfo->gen >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
5990                            inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
5991      3;
5992
5993   /* On Gen9+ the LOD argument is for free if we're able to use the LZ
5994    * variant of the TXL or TXF message.
5995    */
5996   const bool implicit_lod = devinfo->gen >= 9 &&
5997                             (inst->opcode == SHADER_OPCODE_TXL ||
5998                              inst->opcode == SHADER_OPCODE_TXF) &&
5999                             inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
6000
6001   /* Calculate the total number of argument components that need to be passed
6002    * to the sampler unit.
6003    */
6004   const unsigned num_payload_components =
6005      MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
6006           req_coord_components) +
6007      inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
6008      (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
6009      inst->components_read(TEX_LOGICAL_SRC_LOD2) +
6010      inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
6011      (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
6012       inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
6013      inst->components_read(TEX_LOGICAL_SRC_MCS);
6014
6015   /* SIMD16 messages with more than five arguments exceed the maximum message
6016    * size supported by the sampler, regardless of whether a header is
6017    * provided or not.
6018    */
6019   return MIN2(inst->exec_size,
6020               num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
6021}
6022
6023/**
6024 * Get the closest native SIMD width supported by the hardware for instruction
6025 * \p inst.  The instruction will be left untouched by
6026 * fs_visitor::lower_simd_width() if the returned value is equal to the
6027 * original execution size.
6028 */
6029static unsigned
6030get_lowered_simd_width(const struct gen_device_info *devinfo,
6031                       const fs_inst *inst)
6032{
6033   switch (inst->opcode) {
6034   case BRW_OPCODE_MOV:
6035   case BRW_OPCODE_SEL:
6036   case BRW_OPCODE_NOT:
6037   case BRW_OPCODE_AND:
6038   case BRW_OPCODE_OR:
6039   case BRW_OPCODE_XOR:
6040   case BRW_OPCODE_SHR:
6041   case BRW_OPCODE_SHL:
6042   case BRW_OPCODE_ASR:
6043   case BRW_OPCODE_CMPN:
6044   case BRW_OPCODE_CSEL:
6045   case BRW_OPCODE_F32TO16:
6046   case BRW_OPCODE_F16TO32:
6047   case BRW_OPCODE_BFREV:
6048   case BRW_OPCODE_BFE:
6049   case BRW_OPCODE_ADD:
6050   case BRW_OPCODE_MUL:
6051   case BRW_OPCODE_AVG:
6052   case BRW_OPCODE_FRC:
6053   case BRW_OPCODE_RNDU:
6054   case BRW_OPCODE_RNDD:
6055   case BRW_OPCODE_RNDE:
6056   case BRW_OPCODE_RNDZ:
6057   case BRW_OPCODE_LZD:
6058   case BRW_OPCODE_FBH:
6059   case BRW_OPCODE_FBL:
6060   case BRW_OPCODE_CBIT:
6061   case BRW_OPCODE_SAD2:
6062   case BRW_OPCODE_MAD:
6063   case BRW_OPCODE_LRP:
6064   case FS_OPCODE_PACK:
6065   case SHADER_OPCODE_SEL_EXEC:
6066   case SHADER_OPCODE_CLUSTER_BROADCAST:
6067      return get_fpu_lowered_simd_width(devinfo, inst);
6068
6069   case BRW_OPCODE_CMP: {
6070      /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
6071       * when the destination is a GRF the dependency-clear bit on the flag
6072       * register is cleared early.
6073       *
6074       * Suggested workarounds are to disable coissuing CMP instructions
6075       * or to split CMP(16) instructions into two CMP(8) instructions.
6076       *
6077       * We choose to split into CMP(8) instructions since disabling
6078       * coissuing would affect CMP instructions not otherwise affected by
6079       * the errata.
6080       */
6081      const unsigned max_width = (devinfo->gen == 7 && !devinfo->is_haswell &&
6082                                  !inst->dst.is_null() ? 8 : ~0);
6083      return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
6084   }
6085   case BRW_OPCODE_BFI1:
6086   case BRW_OPCODE_BFI2:
6087      /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
6088       * should
6089       *  "Force BFI instructions to be executed always in SIMD8."
6090       */
6091      return MIN2(devinfo->is_haswell ? 8 : ~0u,
6092                  get_fpu_lowered_simd_width(devinfo, inst));
6093
6094   case BRW_OPCODE_IF:
6095      assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
6096      return inst->exec_size;
6097
6098   case SHADER_OPCODE_RCP:
6099   case SHADER_OPCODE_RSQ:
6100   case SHADER_OPCODE_SQRT:
6101   case SHADER_OPCODE_EXP2:
6102   case SHADER_OPCODE_LOG2:
6103   case SHADER_OPCODE_SIN:
6104   case SHADER_OPCODE_COS: {
6105      /* Unary extended math instructions are limited to SIMD8 on Gen4 and
6106       * Gen6. Extended Math Function is limited to SIMD8 with half-float.
6107       */
6108      if (devinfo->gen == 6 || (devinfo->gen == 4 && !devinfo->is_g4x))
6109         return MIN2(8, inst->exec_size);
6110      if (inst->dst.type == BRW_REGISTER_TYPE_HF)
6111         return MIN2(8, inst->exec_size);
6112      return MIN2(16, inst->exec_size);
6113   }
6114
6115   case SHADER_OPCODE_POW: {
6116      /* SIMD16 is only allowed on Gen7+. Extended Math Function is limited
6117       * to SIMD8 with half-float
6118       */
6119      if (devinfo->gen < 7)
6120         return MIN2(8, inst->exec_size);
6121      if (inst->dst.type == BRW_REGISTER_TYPE_HF)
6122         return MIN2(8, inst->exec_size);
6123      return MIN2(16, inst->exec_size);
6124   }
6125
6126   case SHADER_OPCODE_INT_QUOTIENT:
6127   case SHADER_OPCODE_INT_REMAINDER:
6128      /* Integer division is limited to SIMD8 on all generations. */
6129      return MIN2(8, inst->exec_size);
6130
6131   case FS_OPCODE_LINTERP:
6132   case SHADER_OPCODE_GET_BUFFER_SIZE:
6133   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
6134   case FS_OPCODE_PACK_HALF_2x16_SPLIT:
6135   case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
6136   case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
6137   case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
6138      return MIN2(16, inst->exec_size);
6139
6140   case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
6141      /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
6142       * message used to implement varying pull constant loads, so expand it
6143       * to SIMD16.  An alternative with longer message payload length but
6144       * shorter return payload would be to use the SIMD8 sampler message that
6145       * takes (header, u, v, r) as parameters instead of (header, u).
6146       */
6147      return (devinfo->gen == 4 ? 16 : MIN2(16, inst->exec_size));
6148
6149   case FS_OPCODE_DDX_COARSE:
6150   case FS_OPCODE_DDX_FINE:
6151   case FS_OPCODE_DDY_COARSE:
6152   case FS_OPCODE_DDY_FINE:
6153      /* The implementation of this virtual opcode may require emitting
6154       * compressed Align16 instructions, which are severely limited on some
6155       * generations.
6156       *
6157       * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
6158       * Region Restrictions):
6159       *
6160       *  "In Align16 access mode, SIMD16 is not allowed for DW operations
6161       *   and SIMD8 is not allowed for DF operations."
6162       *
6163       * In this context, "DW operations" means "operations acting on 32-bit
6164       * values", so it includes operations on floats.
6165       *
6166       * Gen4 has a similar restriction.  From the i965 PRM, section 11.5.3
6167       * (Instruction Compression -> Rules and Restrictions):
6168       *
6169       *  "A compressed instruction must be in Align1 access mode. Align16
6170       *   mode instructions cannot be compressed."
6171       *
6172       * Similar text exists in the g45 PRM.
6173       *
6174       * Empirically, compressed align16 instructions using odd register
6175       * numbers don't appear to work on Sandybridge either.
6176       */
6177      return (devinfo->gen == 4 || devinfo->gen == 6 ||
6178              (devinfo->gen == 7 && !devinfo->is_haswell) ?
6179              MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
6180
6181   case SHADER_OPCODE_MULH:
6182      /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
6183       * is 8-wide on Gen7+.
6184       */
6185      return (devinfo->gen >= 7 ? 8 :
6186              get_fpu_lowered_simd_width(devinfo, inst));
6187
6188   case FS_OPCODE_FB_WRITE_LOGICAL:
6189      /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
6190       * here.
6191       */
6192      assert(devinfo->gen != 6 ||
6193             inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
6194             inst->exec_size == 8);
6195      /* Dual-source FB writes are unsupported in SIMD16 mode. */
6196      return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
6197              8 : MIN2(16, inst->exec_size));
6198
6199   case FS_OPCODE_FB_READ_LOGICAL:
6200      return MIN2(16, inst->exec_size);
6201
6202   case SHADER_OPCODE_TEX_LOGICAL:
6203   case SHADER_OPCODE_TXF_CMS_LOGICAL:
6204   case SHADER_OPCODE_TXF_UMS_LOGICAL:
6205   case SHADER_OPCODE_TXF_MCS_LOGICAL:
6206   case SHADER_OPCODE_LOD_LOGICAL:
6207   case SHADER_OPCODE_TG4_LOGICAL:
6208   case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
6209   case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
6210   case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
6211      return get_sampler_lowered_simd_width(devinfo, inst);
6212
6213   case SHADER_OPCODE_TXD_LOGICAL:
6214      /* TXD is unsupported in SIMD16 mode. */
6215      return 8;
6216
6217   case SHADER_OPCODE_TXL_LOGICAL:
6218   case FS_OPCODE_TXB_LOGICAL:
6219      /* Only one execution size is representable pre-ILK depending on whether
6220       * the shadow reference argument is present.
6221       */
6222      if (devinfo->gen == 4)
6223         return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
6224      else
6225         return get_sampler_lowered_simd_width(devinfo, inst);
6226
6227   case SHADER_OPCODE_TXF_LOGICAL:
6228   case SHADER_OPCODE_TXS_LOGICAL:
6229      /* Gen4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
6230       * messages.  Use SIMD16 instead.
6231       */
6232      if (devinfo->gen == 4)
6233         return 16;
6234      else
6235         return get_sampler_lowered_simd_width(devinfo, inst);
6236
6237   case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
6238   case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
6239   case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
6240      return 8;
6241
6242   case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
6243   case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6244   case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
6245   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
6246   case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
6247   case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
6248      return MIN2(16, inst->exec_size);
6249
6250   case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
6251   case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
6252   case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
6253   case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
6254      return devinfo->gen <= 8 ? 8 : MIN2(16, inst->exec_size);
6255
6256   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
6257   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
6258   case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6259      return 8;
6260
6261   case SHADER_OPCODE_URB_READ_SIMD8:
6262   case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
6263   case SHADER_OPCODE_URB_WRITE_SIMD8:
6264   case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
6265   case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
6266   case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
6267      return MIN2(8, inst->exec_size);
6268
6269   case SHADER_OPCODE_QUAD_SWIZZLE: {
6270      const unsigned swiz = inst->src[1].ud;
6271      return (is_uniform(inst->src[0]) ?
6272                 get_fpu_lowered_simd_width(devinfo, inst) :
6273              devinfo->gen < 11 && type_sz(inst->src[0].type) == 4 ? 8 :
6274              swiz == BRW_SWIZZLE_XYXY || swiz == BRW_SWIZZLE_ZWZW ? 4 :
6275              get_fpu_lowered_simd_width(devinfo, inst));
6276   }
6277   case SHADER_OPCODE_MOV_INDIRECT: {
6278      /* From IVB and HSW PRMs:
6279       *
6280       * "2.When the destination requires two registers and the sources are
6281       *  indirect, the sources must use 1x1 regioning mode.
6282       *
6283       * In case of DF instructions in HSW/IVB, the exec_size is limited by
6284       * the EU decompression logic not handling VxH indirect addressing
6285       * correctly.
6286       */
6287      const unsigned max_size = (devinfo->gen >= 8 ? 2 : 1) * REG_SIZE;
6288      /* Prior to Broadwell, we only have 8 address subregisters. */
6289      return MIN3(devinfo->gen >= 8 ? 16 : 8,
6290                  max_size / (inst->dst.stride * type_sz(inst->dst.type)),
6291                  inst->exec_size);
6292   }
6293
6294   case SHADER_OPCODE_LOAD_PAYLOAD: {
6295      const unsigned reg_count =
6296         DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
6297
6298      if (reg_count > 2) {
6299         /* Only LOAD_PAYLOAD instructions with per-channel destination region
6300          * can be easily lowered (which excludes headers and heterogeneous
6301          * types).
6302          */
6303         assert(!inst->header_size);
6304         for (unsigned i = 0; i < inst->sources; i++)
6305            assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
6306                   inst->src[i].file == BAD_FILE);
6307
6308         return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
6309      } else {
6310         return inst->exec_size;
6311      }
6312   }
6313   default:
6314      return inst->exec_size;
6315   }
6316}
6317
6318/**
6319 * Return true if splitting out the group of channels of instruction \p inst
6320 * given by lbld.group() requires allocating a temporary for the i-th source
6321 * of the lowered instruction.
6322 */
6323static inline bool
6324needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
6325{
6326   return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
6327            (inst->components_read(i) == 1 &&
6328             lbld.dispatch_width() <= inst->exec_size)) ||
6329          (inst->flags_written() &
6330           flag_mask(inst->src[i], type_sz(inst->src[i].type)));
6331}
6332
6333/**
6334 * Extract the data that would be consumed by the channel group given by
6335 * lbld.group() from the i-th source region of instruction \p inst and return
6336 * it as result in packed form.
6337 */
6338static fs_reg
6339emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
6340{
6341   assert(lbld.group() >= inst->group);
6342
6343   /* Specified channel group from the source region. */
6344   const fs_reg src = horiz_offset(inst->src[i], lbld.group() - inst->group);
6345
6346   if (needs_src_copy(lbld, inst, i)) {
6347      /* Builder of the right width to perform the copy avoiding uninitialized
6348       * data if the lowered execution size is greater than the original
6349       * execution size of the instruction.
6350       */
6351      const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
6352                                              inst->exec_size), 0);
6353      const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
6354
6355      for (unsigned k = 0; k < inst->components_read(i); ++k)
6356         cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
6357
6358      return tmp;
6359
6360   } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
6361      /* The source is invariant for all dispatch_width-wide groups of the
6362       * original region.
6363       */
6364      return inst->src[i];
6365
6366   } else {
6367      /* We can just point the lowered instruction at the right channel group
6368       * from the original region.
6369       */
6370      return src;
6371   }
6372}
6373
6374/**
6375 * Return true if splitting out the group of channels of instruction \p inst
6376 * given by lbld.group() requires allocating a temporary for the destination
6377 * of the lowered instruction and copying the data back to the original
6378 * destination region.
6379 */
6380static inline bool
6381needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
6382{
6383   /* If the instruction writes more than one component we'll have to shuffle
6384    * the results of multiple lowered instructions in order to make sure that
6385    * they end up arranged correctly in the original destination region.
6386    */
6387   if (inst->size_written > inst->dst.component_size(inst->exec_size))
6388      return true;
6389
6390   /* If the lowered execution size is larger than the original the result of
6391    * the instruction won't fit in the original destination, so we'll have to
6392    * allocate a temporary in any case.
6393    */
6394   if (lbld.dispatch_width() > inst->exec_size)
6395      return true;
6396
6397   for (unsigned i = 0; i < inst->sources; i++) {
6398      /* If we already made a copy of the source for other reasons there won't
6399       * be any overlap with the destination.
6400       */
6401      if (needs_src_copy(lbld, inst, i))
6402         continue;
6403
6404      /* In order to keep the logic simple we emit a copy whenever the
6405       * destination region doesn't exactly match an overlapping source, which
6406       * may point at the source and destination not being aligned group by
6407       * group which could cause one of the lowered instructions to overwrite
6408       * the data read from the same source by other lowered instructions.
6409       */
6410      if (regions_overlap(inst->dst, inst->size_written,
6411                          inst->src[i], inst->size_read(i)) &&
6412          !inst->dst.equals(inst->src[i]))
6413        return true;
6414   }
6415
6416   return false;
6417}
6418
6419/**
6420 * Insert data from a packed temporary into the channel group given by
6421 * lbld.group() of the destination region of instruction \p inst and return
6422 * the temporary as result.  Any copy instructions that are required for
6423 * unzipping the previous value (in the case of partial writes) will be
6424 * inserted using \p lbld_before and any copy instructions required for
6425 * zipping up the destination of \p inst will be inserted using \p lbld_after.
6426 */
6427static fs_reg
6428emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
6429         fs_inst *inst)
6430{
6431   assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
6432   assert(lbld_before.group() == lbld_after.group());
6433   assert(lbld_after.group() >= inst->group);
6434
6435   /* Specified channel group from the destination region. */
6436   const fs_reg dst = horiz_offset(inst->dst, lbld_after.group() - inst->group);
6437   const unsigned dst_size = inst->size_written /
6438      inst->dst.component_size(inst->exec_size);
6439
6440   if (needs_dst_copy(lbld_after, inst)) {
6441      const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
6442
6443      if (inst->predicate) {
6444         /* Handle predication by copying the original contents of
6445          * the destination into the temporary before emitting the
6446          * lowered instruction.
6447          */
6448         const fs_builder gbld_before =
6449            lbld_before.group(MIN2(lbld_before.dispatch_width(),
6450                                   inst->exec_size), 0);
6451         for (unsigned k = 0; k < dst_size; ++k) {
6452            gbld_before.MOV(offset(tmp, lbld_before, k),
6453                            offset(dst, inst->exec_size, k));
6454         }
6455      }
6456
6457      const fs_builder gbld_after =
6458         lbld_after.group(MIN2(lbld_after.dispatch_width(),
6459                               inst->exec_size), 0);
6460      for (unsigned k = 0; k < dst_size; ++k) {
6461         /* Use a builder of the right width to perform the copy avoiding
6462          * uninitialized data if the lowered execution size is greater than
6463          * the original execution size of the instruction.
6464          */
6465         gbld_after.MOV(offset(dst, inst->exec_size, k),
6466                        offset(tmp, lbld_after, k));
6467      }
6468
6469      return tmp;
6470
6471   } else {
6472      /* No need to allocate a temporary for the lowered instruction, just
6473       * take the right group of channels from the original region.
6474       */
6475      return dst;
6476   }
6477}
6478
6479bool
6480fs_visitor::lower_simd_width()
6481{
6482   bool progress = false;
6483
6484   foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
6485      const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
6486
6487      if (lower_width != inst->exec_size) {
6488         /* Builder matching the original instruction.  We may also need to
6489          * emit an instruction of width larger than the original, set the
6490          * execution size of the builder to the highest of both for now so
6491          * we're sure that both cases can be handled.
6492          */
6493         const unsigned max_width = MAX2(inst->exec_size, lower_width);
6494         const fs_builder ibld = bld.at(block, inst)
6495                                    .exec_all(inst->force_writemask_all)
6496                                    .group(max_width, inst->group / max_width);
6497
6498         /* Split the copies in chunks of the execution width of either the
6499          * original or the lowered instruction, whichever is lower.
6500          */
6501         const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
6502         const unsigned dst_size = inst->size_written /
6503            inst->dst.component_size(inst->exec_size);
6504
6505         assert(!inst->writes_accumulator && !inst->mlen);
6506
6507         /* Inserting the zip, unzip, and duplicated instructions in all of
6508          * the right spots is somewhat tricky.  All of the unzip and any
6509          * instructions from the zip which unzip the destination prior to
6510          * writing need to happen before all of the per-group instructions
6511          * and the zip instructions need to happen after.  In order to sort
6512          * this all out, we insert the unzip instructions before \p inst,
6513          * insert the per-group instructions after \p inst (i.e. before
6514          * inst->next), and insert the zip instructions before the
6515          * instruction after \p inst.  Since we are inserting instructions
6516          * after \p inst, inst->next is a moving target and we need to save
6517          * it off here so that we insert the zip instructions in the right
6518          * place.
6519          *
6520          * Since we're inserting split instructions after after_inst, the
6521          * instructions will end up in the reverse order that we insert them.
6522          * However, certain render target writes require that the low group
6523          * instructions come before the high group.  From the Ivy Bridge PRM
6524          * Vol. 4, Pt. 1, Section 3.9.11:
6525          *
6526          *    "If multiple SIMD8 Dual Source messages are delivered by the
6527          *    pixel shader thread, each SIMD8_DUALSRC_LO message must be
6528          *    issued before the SIMD8_DUALSRC_HI message with the same Slot
6529          *    Group Select setting."
6530          *
6531          * And, from Section 3.9.11.1 of the same PRM:
6532          *
6533          *    "When SIMD32 or SIMD16 PS threads send render target writes
6534          *    with multiple SIMD8 and SIMD16 messages, the following must
6535          *    hold:
6536          *
6537          *    All the slots (as described above) must have a corresponding
6538          *    render target write irrespective of the slot's validity. A slot
6539          *    is considered valid when at least one sample is enabled. For
6540          *    example, a SIMD16 PS thread must send two SIMD8 render target
6541          *    writes to cover all the slots.
6542          *
6543          *    PS thread must send SIMD render target write messages with
6544          *    increasing slot numbers. For example, SIMD16 thread has
6545          *    Slot[15:0] and if two SIMD8 render target writes are used, the
6546          *    first SIMD8 render target write must send Slot[7:0] and the
6547          *    next one must send Slot[15:8]."
6548          *
6549          * In order to make low group instructions come before high group
6550          * instructions (this is required for some render target writes), we
6551          * split from the highest group to lowest.
6552          */
6553         exec_node *const after_inst = inst->next;
6554         for (int i = n - 1; i >= 0; i--) {
6555            /* Emit a copy of the original instruction with the lowered width.
6556             * If the EOT flag was set throw it away except for the last
6557             * instruction to avoid killing the thread prematurely.
6558             */
6559            fs_inst split_inst = *inst;
6560            split_inst.exec_size = lower_width;
6561            split_inst.eot = inst->eot && i == int(n - 1);
6562
6563            /* Select the correct channel enables for the i-th group, then
6564             * transform the sources and destination and emit the lowered
6565             * instruction.
6566             */
6567            const fs_builder lbld = ibld.group(lower_width, i);
6568
6569            for (unsigned j = 0; j < inst->sources; j++)
6570               split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
6571
6572            split_inst.dst = emit_zip(lbld.at(block, inst),
6573                                      lbld.at(block, after_inst), inst);
6574            split_inst.size_written =
6575               split_inst.dst.component_size(lower_width) * dst_size;
6576
6577            lbld.at(block, inst->next).emit(split_inst);
6578         }
6579
6580         inst->remove(block);
6581         progress = true;
6582      }
6583   }
6584
6585   if (progress)
6586      invalidate_live_intervals();
6587
6588   return progress;
6589}
6590
6591void
6592fs_visitor::dump_instructions()
6593{
6594   dump_instructions(NULL);
6595}
6596
6597void
6598fs_visitor::dump_instructions(const char *name)
6599{
6600   FILE *file = stderr;
6601   if (name && geteuid() != 0) {
6602      file = fopen(name, "w");
6603      if (!file)
6604         file = stderr;
6605   }
6606
6607   if (cfg) {
6608      calculate_register_pressure();
6609      int ip = 0, max_pressure = 0;
6610      foreach_block_and_inst(block, backend_instruction, inst, cfg) {
6611         max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
6612         fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
6613         dump_instruction(inst, file);
6614         ip++;
6615      }
6616      fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
6617   } else {
6618      int ip = 0;
6619      foreach_in_list(backend_instruction, inst, &instructions) {
6620         fprintf(file, "%4d: ", ip++);
6621         dump_instruction(inst, file);
6622      }
6623   }
6624
6625   if (file != stderr) {
6626      fclose(file);
6627   }
6628}
6629
6630void
6631fs_visitor::dump_instruction(backend_instruction *be_inst)
6632{
6633   dump_instruction(be_inst, stderr);
6634}
6635
6636void
6637fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
6638{
6639   fs_inst *inst = (fs_inst *)be_inst;
6640
6641   if (inst->predicate) {
6642      fprintf(file, "(%cf%d.%d) ",
6643              inst->predicate_inverse ? '-' : '+',
6644              inst->flag_subreg / 2,
6645              inst->flag_subreg % 2);
6646   }
6647
6648   fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
6649   if (inst->saturate)
6650      fprintf(file, ".sat");
6651   if (inst->conditional_mod) {
6652      fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
6653      if (!inst->predicate &&
6654          (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
6655                                inst->opcode != BRW_OPCODE_CSEL &&
6656                                inst->opcode != BRW_OPCODE_IF &&
6657                                inst->opcode != BRW_OPCODE_WHILE))) {
6658         fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
6659                 inst->flag_subreg % 2);
6660      }
6661   }
6662   fprintf(file, "(%d) ", inst->exec_size);
6663
6664   if (inst->mlen) {
6665      fprintf(file, "(mlen: %d) ", inst->mlen);
6666   }
6667
6668   if (inst->ex_mlen) {
6669      fprintf(file, "(ex_mlen: %d) ", inst->ex_mlen);
6670   }
6671
6672   if (inst->eot) {
6673      fprintf(file, "(EOT) ");
6674   }
6675
6676   switch (inst->dst.file) {
6677   case VGRF:
6678      fprintf(file, "vgrf%d", inst->dst.nr);
6679      break;
6680   case FIXED_GRF:
6681      fprintf(file, "g%d", inst->dst.nr);
6682      break;
6683   case MRF:
6684      fprintf(file, "m%d", inst->dst.nr);
6685      break;
6686   case BAD_FILE:
6687      fprintf(file, "(null)");
6688      break;
6689   case UNIFORM:
6690      fprintf(file, "***u%d***", inst->dst.nr);
6691      break;
6692   case ATTR:
6693      fprintf(file, "***attr%d***", inst->dst.nr);
6694      break;
6695   case ARF:
6696      switch (inst->dst.nr) {
6697      case BRW_ARF_NULL:
6698         fprintf(file, "null");
6699         break;
6700      case BRW_ARF_ADDRESS:
6701         fprintf(file, "a0.%d", inst->dst.subnr);
6702         break;
6703      case BRW_ARF_ACCUMULATOR:
6704         fprintf(file, "acc%d", inst->dst.subnr);
6705         break;
6706      case BRW_ARF_FLAG:
6707         fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6708         break;
6709      default:
6710         fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6711         break;
6712      }
6713      break;
6714   case IMM:
6715      unreachable("not reached");
6716   }
6717
6718   if (inst->dst.offset ||
6719       (inst->dst.file == VGRF &&
6720        alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
6721      const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
6722      fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
6723              inst->dst.offset % reg_size);
6724   }
6725
6726   if (inst->dst.stride != 1)
6727      fprintf(file, "<%u>", inst->dst.stride);
6728   fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
6729
6730   for (int i = 0; i < inst->sources; i++) {
6731      if (inst->src[i].negate)
6732         fprintf(file, "-");
6733      if (inst->src[i].abs)
6734         fprintf(file, "|");
6735      switch (inst->src[i].file) {
6736      case VGRF:
6737         fprintf(file, "vgrf%d", inst->src[i].nr);
6738         break;
6739      case FIXED_GRF:
6740         fprintf(file, "g%d", inst->src[i].nr);
6741         break;
6742      case MRF:
6743         fprintf(file, "***m%d***", inst->src[i].nr);
6744         break;
6745      case ATTR:
6746         fprintf(file, "attr%d", inst->src[i].nr);
6747         break;
6748      case UNIFORM:
6749         fprintf(file, "u%d", inst->src[i].nr);
6750         break;
6751      case BAD_FILE:
6752         fprintf(file, "(null)");
6753         break;
6754      case IMM:
6755         switch (inst->src[i].type) {
6756         case BRW_REGISTER_TYPE_F:
6757            fprintf(file, "%-gf", inst->src[i].f);
6758            break;
6759         case BRW_REGISTER_TYPE_DF:
6760            fprintf(file, "%fdf", inst->src[i].df);
6761            break;
6762         case BRW_REGISTER_TYPE_W:
6763         case BRW_REGISTER_TYPE_D:
6764            fprintf(file, "%dd", inst->src[i].d);
6765            break;
6766         case BRW_REGISTER_TYPE_UW:
6767         case BRW_REGISTER_TYPE_UD:
6768            fprintf(file, "%uu", inst->src[i].ud);
6769            break;
6770         case BRW_REGISTER_TYPE_Q:
6771            fprintf(file, "%" PRId64 "q", inst->src[i].d64);
6772            break;
6773         case BRW_REGISTER_TYPE_UQ:
6774            fprintf(file, "%" PRIu64 "uq", inst->src[i].u64);
6775            break;
6776         case BRW_REGISTER_TYPE_VF:
6777            fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
6778                    brw_vf_to_float((inst->src[i].ud >>  0) & 0xff),
6779                    brw_vf_to_float((inst->src[i].ud >>  8) & 0xff),
6780                    brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
6781                    brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
6782            break;
6783         case BRW_REGISTER_TYPE_V:
6784         case BRW_REGISTER_TYPE_UV:
6785            fprintf(file, "%08x%s", inst->src[i].ud,
6786                    inst->src[i].type == BRW_REGISTER_TYPE_V ? "V" : "UV");
6787            break;
6788         default:
6789            fprintf(file, "???");
6790            break;
6791         }
6792         break;
6793      case ARF:
6794         switch (inst->src[i].nr) {
6795         case BRW_ARF_NULL:
6796            fprintf(file, "null");
6797            break;
6798         case BRW_ARF_ADDRESS:
6799            fprintf(file, "a0.%d", inst->src[i].subnr);
6800            break;
6801         case BRW_ARF_ACCUMULATOR:
6802            fprintf(file, "acc%d", inst->src[i].subnr);
6803            break;
6804         case BRW_ARF_FLAG:
6805            fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6806            break;
6807         default:
6808            fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6809            break;
6810         }
6811         break;
6812      }
6813
6814      if (inst->src[i].offset ||
6815          (inst->src[i].file == VGRF &&
6816           alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
6817         const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
6818         fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
6819                 inst->src[i].offset % reg_size);
6820      }
6821
6822      if (inst->src[i].abs)
6823         fprintf(file, "|");
6824
6825      if (inst->src[i].file != IMM) {
6826         unsigned stride;
6827         if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
6828            unsigned hstride = inst->src[i].hstride;
6829            stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
6830         } else {
6831            stride = inst->src[i].stride;
6832         }
6833         if (stride != 1)
6834            fprintf(file, "<%u>", stride);
6835
6836         fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
6837      }
6838
6839      if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
6840         fprintf(file, ", ");
6841   }
6842
6843   fprintf(file, " ");
6844
6845   if (inst->force_writemask_all)
6846      fprintf(file, "NoMask ");
6847
6848   if (inst->exec_size != dispatch_width)
6849      fprintf(file, "group%d ", inst->group);
6850
6851   fprintf(file, "\n");
6852}
6853
6854void
6855fs_visitor::setup_fs_payload_gen6()
6856{
6857   assert(stage == MESA_SHADER_FRAGMENT);
6858   struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
6859   const unsigned payload_width = MIN2(16, dispatch_width);
6860   assert(dispatch_width % payload_width == 0);
6861   assert(devinfo->gen >= 6);
6862
6863   prog_data->uses_src_depth = prog_data->uses_src_w =
6864      (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
6865
6866   prog_data->uses_sample_mask =
6867      (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_MASK_IN) != 0;
6868
6869   /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
6870    *
6871    *    "MSDISPMODE_PERSAMPLE is required in order to select
6872    *    POSOFFSET_SAMPLE"
6873    *
6874    * So we can only really get sample positions if we are doing real
6875    * per-sample dispatch.  If we need gl_SamplePosition and we don't have
6876    * persample dispatch, we hard-code it to 0.5.
6877    */
6878   prog_data->uses_pos_offset = prog_data->persample_dispatch &&
6879      (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_POS);
6880
6881   /* R0: PS thread payload header. */
6882   payload.num_regs++;
6883
6884   for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
6885      /* R1: masks, pixel X/Y coordinates. */
6886      payload.subspan_coord_reg[j] = payload.num_regs++;
6887   }
6888
6889   for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
6890      /* R3-26: barycentric interpolation coordinates.  These appear in the
6891       * same order that they appear in the brw_barycentric_mode enum.  Each
6892       * set of coordinates occupies 2 registers if dispatch width == 8 and 4
6893       * registers if dispatch width == 16.  Coordinates only appear if they
6894       * were enabled using the "Barycentric Interpolation Mode" bits in
6895       * WM_STATE.
6896       */
6897      for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
6898         if (prog_data->barycentric_interp_modes & (1 << i)) {
6899            payload.barycentric_coord_reg[i][j] = payload.num_regs;
6900            payload.num_regs += payload_width / 4;
6901         }
6902      }
6903
6904      /* R27-28: interpolated depth if uses source depth */
6905      if (prog_data->uses_src_depth) {
6906         payload.source_depth_reg[j] = payload.num_regs;
6907         payload.num_regs += payload_width / 8;
6908      }
6909
6910      /* R29-30: interpolated W set if GEN6_WM_USES_SOURCE_W. */
6911      if (prog_data->uses_src_w) {
6912         payload.source_w_reg[j] = payload.num_regs;
6913         payload.num_regs += payload_width / 8;
6914      }
6915
6916      /* R31: MSAA position offsets. */
6917      if (prog_data->uses_pos_offset) {
6918         payload.sample_pos_reg[j] = payload.num_regs;
6919         payload.num_regs++;
6920      }
6921
6922      /* R32-33: MSAA input coverage mask */
6923      if (prog_data->uses_sample_mask) {
6924         assert(devinfo->gen >= 7);
6925         payload.sample_mask_in_reg[j] = payload.num_regs;
6926         payload.num_regs += payload_width / 8;
6927      }
6928   }
6929
6930   if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
6931      source_depth_to_render_target = true;
6932   }
6933}
6934
6935void
6936fs_visitor::setup_vs_payload()
6937{
6938   /* R0: thread header, R1: urb handles */
6939   payload.num_regs = 2;
6940}
6941
6942void
6943fs_visitor::setup_gs_payload()
6944{
6945   assert(stage == MESA_SHADER_GEOMETRY);
6946
6947   struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
6948   struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
6949
6950   /* R0: thread header, R1: output URB handles */
6951   payload.num_regs = 2;
6952
6953   if (gs_prog_data->include_primitive_id) {
6954      /* R2: Primitive ID 0..7 */
6955      payload.num_regs++;
6956   }
6957
6958   /* Always enable VUE handles so we can safely use pull model if needed.
6959    *
6960    * The push model for a GS uses a ton of register space even for trivial
6961    * scenarios with just a few inputs, so just make things easier and a bit
6962    * safer by always having pull model available.
6963    */
6964   gs_prog_data->base.include_vue_handles = true;
6965
6966   /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
6967   payload.num_regs += nir->info.gs.vertices_in;
6968
6969   /* Use a maximum of 24 registers for push-model inputs. */
6970   const unsigned max_push_components = 24;
6971
6972   /* If pushing our inputs would take too many registers, reduce the URB read
6973    * length (which is in HWords, or 8 registers), and resort to pulling.
6974    *
6975    * Note that the GS reads <URB Read Length> HWords for every vertex - so we
6976    * have to multiply by VerticesIn to obtain the total storage requirement.
6977    */
6978   if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
6979       max_push_components) {
6980      vue_prog_data->urb_read_length =
6981         ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
6982   }
6983}
6984
6985void
6986fs_visitor::setup_cs_payload()
6987{
6988   assert(devinfo->gen >= 7);
6989   payload.num_regs = 1;
6990}
6991
6992void
6993fs_visitor::calculate_register_pressure()
6994{
6995   invalidate_live_intervals();
6996   calculate_live_intervals();
6997
6998   unsigned num_instructions = 0;
6999   foreach_block(block, cfg)
7000      num_instructions += block->instructions.length();
7001
7002   regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
7003
7004   for (unsigned reg = 0; reg < alloc.count; reg++) {
7005      for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
7006         regs_live_at_ip[ip] += alloc.sizes[reg];
7007   }
7008}
7009
7010void
7011fs_visitor::optimize()
7012{
7013   /* Start by validating the shader we currently have. */
7014   validate();
7015
7016   /* bld is the common builder object pointing at the end of the program we
7017    * used to translate it into i965 IR.  For the optimization and lowering
7018    * passes coming next, any code added after the end of the program without
7019    * having explicitly called fs_builder::at() clearly points at a mistake.
7020    * Ideally optimization passes wouldn't be part of the visitor so they
7021    * wouldn't have access to bld at all, but they do, so just in case some
7022    * pass forgets to ask for a location explicitly set it to NULL here to
7023    * make it trip.  The dispatch width is initialized to a bogus value to
7024    * make sure that optimizations set the execution controls explicitly to
7025    * match the code they are manipulating instead of relying on the defaults.
7026    */
7027   bld = fs_builder(this, 64);
7028
7029   assign_constant_locations();
7030   lower_constant_loads();
7031
7032   validate();
7033
7034   split_virtual_grfs();
7035   validate();
7036
7037#define OPT(pass, args...) ({                                           \
7038      pass_num++;                                                       \
7039      bool this_progress = pass(args);                                  \
7040                                                                        \
7041      if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) {   \
7042         char filename[64];                                             \
7043         snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass,              \
7044                  stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
7045                                                                        \
7046         backend_shader::dump_instructions(filename);                   \
7047      }                                                                 \
7048                                                                        \
7049      validate();                                                       \
7050                                                                        \
7051      progress = progress || this_progress;                             \
7052      this_progress;                                                    \
7053   })
7054
7055   if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
7056      char filename[64];
7057      snprintf(filename, 64, "%s%d-%s-00-00-start",
7058               stage_abbrev, dispatch_width, nir->info.name);
7059
7060      backend_shader::dump_instructions(filename);
7061   }
7062
7063   bool progress = false;
7064   int iteration = 0;
7065   int pass_num = 0;
7066
7067   /* Before anything else, eliminate dead code.  The results of some NIR
7068    * instructions may effectively be calculated twice.  Once when the
7069    * instruction is encountered, and again when the user of that result is
7070    * encountered.  Wipe those away before algebraic optimizations and
7071    * especially copy propagation can mix things up.
7072    */
7073   OPT(dead_code_eliminate);
7074
7075   OPT(remove_extra_rounding_modes);
7076
7077   do {
7078      progress = false;
7079      pass_num = 0;
7080      iteration++;
7081
7082      OPT(remove_duplicate_mrf_writes);
7083
7084      OPT(opt_algebraic);
7085      OPT(opt_cse);
7086      OPT(opt_copy_propagation);
7087      OPT(opt_predicated_break, this);
7088      OPT(opt_cmod_propagation);
7089      OPT(dead_code_eliminate);
7090      OPT(opt_peephole_sel);
7091      OPT(dead_control_flow_eliminate, this);
7092      OPT(opt_register_renaming);
7093      OPT(opt_saturate_propagation);
7094      OPT(register_coalesce);
7095      OPT(compute_to_mrf);
7096      OPT(eliminate_find_live_channel);
7097
7098      OPT(compact_virtual_grfs);
7099   } while (progress);
7100
7101   if (OPT(lower_linterp)) {
7102      OPT(opt_copy_propagation);
7103      OPT(dead_code_eliminate);
7104   }
7105
7106   /* Do this after cmod propagation has had every possible opportunity to
7107    * propagate results into SEL instructions.
7108    */
7109   if (OPT(opt_peephole_csel))
7110      OPT(dead_code_eliminate);
7111
7112   progress = false;
7113   pass_num = 0;
7114
7115   if (OPT(lower_pack)) {
7116      OPT(register_coalesce);
7117      OPT(dead_code_eliminate);
7118   }
7119
7120   OPT(lower_simd_width);
7121
7122   /* After SIMD lowering just in case we had to unroll the EOT send. */
7123   OPT(opt_sampler_eot);
7124
7125   OPT(lower_logical_sends);
7126
7127   if (progress) {
7128      OPT(opt_copy_propagation);
7129      /* Only run after logical send lowering because it's easier to implement
7130       * in terms of physical sends.
7131       */
7132      if (OPT(opt_zero_samples))
7133         OPT(opt_copy_propagation);
7134      /* Run after logical send lowering to give it a chance to CSE the
7135       * LOAD_PAYLOAD instructions created to construct the payloads of
7136       * e.g. texturing messages in cases where it wasn't possible to CSE the
7137       * whole logical instruction.
7138       */
7139      OPT(opt_cse);
7140      OPT(register_coalesce);
7141      OPT(compute_to_mrf);
7142      OPT(dead_code_eliminate);
7143      OPT(remove_duplicate_mrf_writes);
7144      OPT(opt_peephole_sel);
7145   }
7146
7147   OPT(opt_redundant_discard_jumps);
7148
7149   if (OPT(lower_load_payload)) {
7150      split_virtual_grfs();
7151      OPT(register_coalesce);
7152      OPT(lower_simd_width);
7153      OPT(compute_to_mrf);
7154      OPT(dead_code_eliminate);
7155   }
7156
7157   OPT(opt_combine_constants);
7158   OPT(lower_integer_multiplication);
7159
7160   if (devinfo->gen <= 5 && OPT(lower_minmax)) {
7161      OPT(opt_cmod_propagation);
7162      OPT(opt_cse);
7163      OPT(opt_copy_propagation);
7164      OPT(dead_code_eliminate);
7165   }
7166
7167   if (OPT(lower_regioning)) {
7168      OPT(opt_copy_propagation);
7169      OPT(dead_code_eliminate);
7170      OPT(lower_simd_width);
7171   }
7172
7173   OPT(fixup_sends_duplicate_payload);
7174
7175   lower_uniform_pull_constant_loads();
7176
7177   validate();
7178}
7179
7180/**
7181 * From the Skylake PRM Vol. 2a docs for sends:
7182 *
7183 *    "It is required that the second block of GRFs does not overlap with the
7184 *    first block."
7185 *
7186 * There are plenty of cases where we may accidentally violate this due to
7187 * having, for instance, both sources be the constant 0.  This little pass
7188 * just adds a new vgrf for the second payload and copies it over.
7189 */
7190bool
7191fs_visitor::fixup_sends_duplicate_payload()
7192{
7193   bool progress = false;
7194
7195   foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7196      if (inst->opcode == SHADER_OPCODE_SEND && inst->ex_mlen > 0 &&
7197          regions_overlap(inst->src[2], inst->mlen * REG_SIZE,
7198                          inst->src[3], inst->ex_mlen * REG_SIZE)) {
7199         fs_reg tmp = fs_reg(VGRF, alloc.allocate(inst->ex_mlen),
7200                             BRW_REGISTER_TYPE_UD);
7201         /* Sadly, we've lost all notion of channels and bit sizes at this
7202          * point.  Just WE_all it.
7203          */
7204         const fs_builder ibld = bld.at(block, inst).exec_all().group(16, 0);
7205         fs_reg copy_src = retype(inst->src[3], BRW_REGISTER_TYPE_UD);
7206         fs_reg copy_dst = tmp;
7207         for (unsigned i = 0; i < inst->ex_mlen; i += 2) {
7208            if (inst->ex_mlen == i + 1) {
7209               /* Only one register left; do SIMD8 */
7210               ibld.group(8, 0).MOV(copy_dst, copy_src);
7211            } else {
7212               ibld.MOV(copy_dst, copy_src);
7213            }
7214            copy_src = offset(copy_src, ibld, 1);
7215            copy_dst = offset(copy_dst, ibld, 1);
7216         }
7217         inst->src[3] = tmp;
7218         progress = true;
7219      }
7220   }
7221
7222   if (progress)
7223      invalidate_live_intervals();
7224
7225   return progress;
7226}
7227
7228/**
7229 * Three source instruction must have a GRF/MRF destination register.
7230 * ARF NULL is not allowed.  Fix that up by allocating a temporary GRF.
7231 */
7232void
7233fs_visitor::fixup_3src_null_dest()
7234{
7235   bool progress = false;
7236
7237   foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7238      if (inst->is_3src(devinfo) && inst->dst.is_null()) {
7239         inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
7240                            inst->dst.type);
7241         progress = true;
7242      }
7243   }
7244
7245   if (progress)
7246      invalidate_live_intervals();
7247}
7248
7249void
7250fs_visitor::allocate_registers(unsigned min_dispatch_width, bool allow_spilling)
7251{
7252   bool allocated_without_spills;
7253
7254   static const enum instruction_scheduler_mode pre_modes[] = {
7255      SCHEDULE_PRE,
7256      SCHEDULE_PRE_NON_LIFO,
7257      SCHEDULE_PRE_LIFO,
7258   };
7259
7260   bool spill_all = allow_spilling && (INTEL_DEBUG & DEBUG_SPILL_FS);
7261
7262   /* Try each scheduling heuristic to see if it can successfully register
7263    * allocate without spilling.  They should be ordered by decreasing
7264    * performance but increasing likelihood of allocating.
7265    */
7266   for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
7267      schedule_instructions(pre_modes[i]);
7268
7269      if (0) {
7270         assign_regs_trivial();
7271         allocated_without_spills = true;
7272      } else {
7273         allocated_without_spills = assign_regs(false, spill_all);
7274      }
7275      if (allocated_without_spills)
7276         break;
7277   }
7278
7279   if (!allocated_without_spills) {
7280      if (!allow_spilling)
7281         fail("Failure to register allocate and spilling is not allowed.");
7282
7283      /* We assume that any spilling is worse than just dropping back to
7284       * SIMD8.  There's probably actually some intermediate point where
7285       * SIMD16 with a couple of spills is still better.
7286       */
7287      if (dispatch_width > min_dispatch_width) {
7288         fail("Failure to register allocate.  Reduce number of "
7289              "live scalar values to avoid this.");
7290      } else {
7291         compiler->shader_perf_log(log_data,
7292                                   "%s shader triggered register spilling.  "
7293                                   "Try reducing the number of live scalar "
7294                                   "values to improve performance.\n",
7295                                   stage_name);
7296      }
7297
7298      /* Since we're out of heuristics, just go spill registers until we
7299       * get an allocation.
7300       */
7301      while (!assign_regs(true, spill_all)) {
7302         if (failed)
7303            break;
7304      }
7305   }
7306
7307   /* This must come after all optimization and register allocation, since
7308    * it inserts dead code that happens to have side effects, and it does
7309    * so based on the actual physical registers in use.
7310    */
7311   insert_gen4_send_dependency_workarounds();
7312
7313   if (failed)
7314      return;
7315
7316   opt_bank_conflicts();
7317
7318   schedule_instructions(SCHEDULE_POST);
7319
7320   if (last_scratch > 0) {
7321      MAYBE_UNUSED unsigned max_scratch_size = 2 * 1024 * 1024;
7322
7323      prog_data->total_scratch = brw_get_scratch_size(last_scratch);
7324
7325      if (stage == MESA_SHADER_COMPUTE) {
7326         if (devinfo->is_haswell) {
7327            /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7328             * field documentation, Haswell supports a minimum of 2kB of
7329             * scratch space for compute shaders, unlike every other stage
7330             * and platform.
7331             */
7332            prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
7333         } else if (devinfo->gen <= 7) {
7334            /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7335             * field documentation, platforms prior to Haswell measure scratch
7336             * size linearly with a range of [1kB, 12kB] and 1kB granularity.
7337             */
7338            prog_data->total_scratch = ALIGN(last_scratch, 1024);
7339            max_scratch_size = 12 * 1024;
7340         }
7341      }
7342
7343      /* We currently only support up to 2MB of scratch space.  If we
7344       * need to support more eventually, the documentation suggests
7345       * that we could allocate a larger buffer, and partition it out
7346       * ourselves.  We'd just have to undo the hardware's address
7347       * calculation by subtracting (FFTID * Per Thread Scratch Space)
7348       * and then add FFTID * (Larger Per Thread Scratch Space).
7349       *
7350       * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
7351       * Thread Group Tracking > Local Memory/Scratch Space.
7352       */
7353      assert(prog_data->total_scratch < max_scratch_size);
7354   }
7355}
7356
7357bool
7358fs_visitor::run_vs()
7359{
7360   assert(stage == MESA_SHADER_VERTEX);
7361
7362   setup_vs_payload();
7363
7364   if (shader_time_index >= 0)
7365      emit_shader_time_begin();
7366
7367   emit_nir_code();
7368
7369   if (failed)
7370      return false;
7371
7372   compute_clip_distance();
7373
7374   emit_urb_writes();
7375
7376   if (shader_time_index >= 0)
7377      emit_shader_time_end();
7378
7379   calculate_cfg();
7380
7381   optimize();
7382
7383   assign_curb_setup();
7384   assign_vs_urb_setup();
7385
7386   fixup_3src_null_dest();
7387   allocate_registers(8, true);
7388
7389   return !failed;
7390}
7391
7392bool
7393fs_visitor::run_tcs_single_patch()
7394{
7395   assert(stage == MESA_SHADER_TESS_CTRL);
7396
7397   struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
7398
7399   /* r1-r4 contain the ICP handles. */
7400   payload.num_regs = 5;
7401
7402   if (shader_time_index >= 0)
7403      emit_shader_time_begin();
7404
7405   /* Initialize gl_InvocationID */
7406   fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
7407   fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
7408   bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
7409   bld.MOV(channels_ud, channels_uw);
7410
7411   if (tcs_prog_data->instances == 1) {
7412      invocation_id = channels_ud;
7413   } else {
7414      const unsigned invocation_id_mask = devinfo->gen >= 11 ?
7415         INTEL_MASK(22, 16) : INTEL_MASK(23, 17);
7416      const unsigned invocation_id_shift = devinfo->gen >= 11 ? 16 : 17;
7417
7418      invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
7419
7420      /* Get instance number from g0.2 bits 23:17, and multiply it by 8. */
7421      fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
7422      fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
7423      bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
7424              brw_imm_ud(invocation_id_mask));
7425      bld.SHR(instance_times_8, t, brw_imm_ud(invocation_id_shift - 3));
7426
7427      bld.ADD(invocation_id, instance_times_8, channels_ud);
7428   }
7429
7430   /* Fix the disptach mask */
7431   if (nir->info.tess.tcs_vertices_out % 8) {
7432      bld.CMP(bld.null_reg_ud(), invocation_id,
7433              brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
7434      bld.IF(BRW_PREDICATE_NORMAL);
7435   }
7436
7437   emit_nir_code();
7438
7439   if (nir->info.tess.tcs_vertices_out % 8) {
7440      bld.emit(BRW_OPCODE_ENDIF);
7441   }
7442
7443   /* Emit EOT write; set TR DS Cache bit */
7444   fs_reg srcs[3] = {
7445      fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
7446      fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
7447      fs_reg(brw_imm_ud(0)),
7448   };
7449   fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
7450   bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
7451
7452   fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
7453                            bld.null_reg_ud(), payload);
7454   inst->mlen = 3;
7455   inst->eot = true;
7456
7457   if (shader_time_index >= 0)
7458      emit_shader_time_end();
7459
7460   if (failed)
7461      return false;
7462
7463   calculate_cfg();
7464
7465   optimize();
7466
7467   assign_curb_setup();
7468   assign_tcs_single_patch_urb_setup();
7469
7470   fixup_3src_null_dest();
7471   allocate_registers(8, true);
7472
7473   return !failed;
7474}
7475
7476bool
7477fs_visitor::run_tes()
7478{
7479   assert(stage == MESA_SHADER_TESS_EVAL);
7480
7481   /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
7482   payload.num_regs = 5;
7483
7484   if (shader_time_index >= 0)
7485      emit_shader_time_begin();
7486
7487   emit_nir_code();
7488
7489   if (failed)
7490      return false;
7491
7492   emit_urb_writes();
7493
7494   if (shader_time_index >= 0)
7495      emit_shader_time_end();
7496
7497   calculate_cfg();
7498
7499   optimize();
7500
7501   assign_curb_setup();
7502   assign_tes_urb_setup();
7503
7504   fixup_3src_null_dest();
7505   allocate_registers(8, true);
7506
7507   return !failed;
7508}
7509
7510bool
7511fs_visitor::run_gs()
7512{
7513   assert(stage == MESA_SHADER_GEOMETRY);
7514
7515   setup_gs_payload();
7516
7517   this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
7518
7519   if (gs_compile->control_data_header_size_bits > 0) {
7520      /* Create a VGRF to store accumulated control data bits. */
7521      this->control_data_bits = vgrf(glsl_type::uint_type);
7522
7523      /* If we're outputting more than 32 control data bits, then EmitVertex()
7524       * will set control_data_bits to 0 after emitting the first vertex.
7525       * Otherwise, we need to initialize it to 0 here.
7526       */
7527      if (gs_compile->control_data_header_size_bits <= 32) {
7528         const fs_builder abld = bld.annotate("initialize control data bits");
7529         abld.MOV(this->control_data_bits, brw_imm_ud(0u));
7530      }
7531   }
7532
7533   if (shader_time_index >= 0)
7534      emit_shader_time_begin();
7535
7536   emit_nir_code();
7537
7538   emit_gs_thread_end();
7539
7540   if (shader_time_index >= 0)
7541      emit_shader_time_end();
7542
7543   if (failed)
7544      return false;
7545
7546   calculate_cfg();
7547
7548   optimize();
7549
7550   assign_curb_setup();
7551   assign_gs_urb_setup();
7552
7553   fixup_3src_null_dest();
7554   allocate_registers(8, true);
7555
7556   return !failed;
7557}
7558
7559/* From the SKL PRM, Volume 16, Workarounds:
7560 *
7561 *   0877  3D   Pixel Shader Hang possible when pixel shader dispatched with
7562 *              only header phases (R0-R2)
7563 *
7564 *   WA: Enable a non-header phase (e.g. push constant) when dispatch would
7565 *       have been header only.
7566 *
7567 * Instead of enabling push constants one can alternatively enable one of the
7568 * inputs. Here one simply chooses "layer" which shouldn't impose much
7569 * overhead.
7570 */
7571static void
7572gen9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
7573{
7574   if (wm_prog_data->num_varying_inputs)
7575      return;
7576
7577   if (wm_prog_data->base.curb_read_length)
7578      return;
7579
7580   wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
7581   wm_prog_data->num_varying_inputs = 1;
7582}
7583
7584bool
7585fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
7586{
7587   struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
7588   brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
7589
7590   assert(stage == MESA_SHADER_FRAGMENT);
7591
7592   if (devinfo->gen >= 6)
7593      setup_fs_payload_gen6();
7594   else
7595      setup_fs_payload_gen4();
7596
7597   if (0) {
7598      emit_dummy_fs();
7599   } else if (do_rep_send) {
7600      assert(dispatch_width == 16);
7601      emit_repclear_shader();
7602   } else {
7603      if (shader_time_index >= 0)
7604         emit_shader_time_begin();
7605
7606      calculate_urb_setup();
7607      if (nir->info.inputs_read > 0 ||
7608          (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
7609         if (devinfo->gen < 6)
7610            emit_interpolation_setup_gen4();
7611         else
7612            emit_interpolation_setup_gen6();
7613      }
7614
7615      /* We handle discards by keeping track of the still-live pixels in f0.1.
7616       * Initialize it with the dispatched pixels.
7617       */
7618      if (wm_prog_data->uses_kill) {
7619         const fs_reg dispatch_mask =
7620            devinfo->gen >= 6 ? brw_vec1_grf(1, 7) : brw_vec1_grf(0, 0);
7621         bld.exec_all().group(1, 0)
7622            .MOV(retype(brw_flag_reg(0, 1), BRW_REGISTER_TYPE_UW),
7623                 retype(dispatch_mask, BRW_REGISTER_TYPE_UW));
7624      }
7625
7626      emit_nir_code();
7627
7628      if (failed)
7629	 return false;
7630
7631      if (wm_prog_data->uses_kill)
7632         bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
7633
7634      if (wm_key->alpha_test_func)
7635         emit_alpha_test();
7636
7637      emit_fb_writes();
7638
7639      if (shader_time_index >= 0)
7640         emit_shader_time_end();
7641
7642      calculate_cfg();
7643
7644      optimize();
7645
7646      assign_curb_setup();
7647
7648      if (devinfo->gen >= 9)
7649         gen9_ps_header_only_workaround(wm_prog_data);
7650
7651      assign_urb_setup();
7652
7653      fixup_3src_null_dest();
7654      allocate_registers(8, allow_spilling);
7655
7656      if (failed)
7657         return false;
7658   }
7659
7660   return !failed;
7661}
7662
7663bool
7664fs_visitor::run_cs(unsigned min_dispatch_width)
7665{
7666   assert(stage == MESA_SHADER_COMPUTE);
7667   assert(dispatch_width >= min_dispatch_width);
7668
7669   setup_cs_payload();
7670
7671   if (shader_time_index >= 0)
7672      emit_shader_time_begin();
7673
7674   if (devinfo->is_haswell && prog_data->total_shared > 0) {
7675      /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
7676      const fs_builder abld = bld.exec_all().group(1, 0);
7677      abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
7678               suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
7679   }
7680
7681   emit_nir_code();
7682
7683   if (failed)
7684      return false;
7685
7686   emit_cs_terminate();
7687
7688   if (shader_time_index >= 0)
7689      emit_shader_time_end();
7690
7691   calculate_cfg();
7692
7693   optimize();
7694
7695   assign_curb_setup();
7696
7697   fixup_3src_null_dest();
7698   allocate_registers(min_dispatch_width, true);
7699
7700   if (failed)
7701      return false;
7702
7703   return !failed;
7704}
7705
7706/**
7707 * Return a bitfield where bit n is set if barycentric interpolation mode n
7708 * (see enum brw_barycentric_mode) is needed by the fragment shader.
7709 *
7710 * We examine the load_barycentric intrinsics rather than looking at input
7711 * variables so that we catch interpolateAtCentroid() messages too, which
7712 * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
7713 */
7714static unsigned
7715brw_compute_barycentric_interp_modes(const struct gen_device_info *devinfo,
7716                                     const nir_shader *shader)
7717{
7718   unsigned barycentric_interp_modes = 0;
7719
7720   nir_foreach_function(f, shader) {
7721      if (!f->impl)
7722         continue;
7723
7724      nir_foreach_block(block, f->impl) {
7725         nir_foreach_instr(instr, block) {
7726            if (instr->type != nir_instr_type_intrinsic)
7727               continue;
7728
7729            nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7730            if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
7731               continue;
7732
7733            /* Ignore WPOS; it doesn't require interpolation. */
7734            if (nir_intrinsic_base(intrin) == VARYING_SLOT_POS)
7735               continue;
7736
7737            intrin = nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
7738            enum glsl_interp_mode interp = (enum glsl_interp_mode)
7739               nir_intrinsic_interp_mode(intrin);
7740            nir_intrinsic_op bary_op = intrin->intrinsic;
7741            enum brw_barycentric_mode bary =
7742               brw_barycentric_mode(interp, bary_op);
7743
7744            barycentric_interp_modes |= 1 << bary;
7745
7746            if (devinfo->needs_unlit_centroid_workaround &&
7747                bary_op == nir_intrinsic_load_barycentric_centroid)
7748               barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
7749         }
7750      }
7751   }
7752
7753   return barycentric_interp_modes;
7754}
7755
7756static void
7757brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
7758                        const nir_shader *shader)
7759{
7760   prog_data->flat_inputs = 0;
7761
7762   nir_foreach_variable(var, &shader->inputs) {
7763      unsigned slots = glsl_count_attribute_slots(var->type, false);
7764      for (unsigned s = 0; s < slots; s++) {
7765         int input_index = prog_data->urb_setup[var->data.location + s];
7766
7767         if (input_index < 0)
7768            continue;
7769
7770         /* flat shading */
7771         if (var->data.interpolation == INTERP_MODE_FLAT)
7772            prog_data->flat_inputs |= 1 << input_index;
7773      }
7774   }
7775}
7776
7777static uint8_t
7778computed_depth_mode(const nir_shader *shader)
7779{
7780   if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
7781      switch (shader->info.fs.depth_layout) {
7782      case FRAG_DEPTH_LAYOUT_NONE:
7783      case FRAG_DEPTH_LAYOUT_ANY:
7784         return BRW_PSCDEPTH_ON;
7785      case FRAG_DEPTH_LAYOUT_GREATER:
7786         return BRW_PSCDEPTH_ON_GE;
7787      case FRAG_DEPTH_LAYOUT_LESS:
7788         return BRW_PSCDEPTH_ON_LE;
7789      case FRAG_DEPTH_LAYOUT_UNCHANGED:
7790         return BRW_PSCDEPTH_OFF;
7791      }
7792   }
7793   return BRW_PSCDEPTH_OFF;
7794}
7795
7796/**
7797 * Move load_interpolated_input with simple (payload-based) barycentric modes
7798 * to the top of the program so we don't emit multiple PLNs for the same input.
7799 *
7800 * This works around CSE not being able to handle non-dominating cases
7801 * such as:
7802 *
7803 *    if (...) {
7804 *       interpolate input
7805 *    } else {
7806 *       interpolate the same exact input
7807 *    }
7808 *
7809 * This should be replaced by global value numbering someday.
7810 */
7811static bool
7812move_interpolation_to_top(nir_shader *nir)
7813{
7814   bool progress = false;
7815
7816   nir_foreach_function(f, nir) {
7817      if (!f->impl)
7818         continue;
7819
7820      nir_block *top = nir_start_block(f->impl);
7821      exec_node *cursor_node = NULL;
7822
7823      nir_foreach_block(block, f->impl) {
7824         if (block == top)
7825            continue;
7826
7827         nir_foreach_instr_safe(instr, block) {
7828            if (instr->type != nir_instr_type_intrinsic)
7829               continue;
7830
7831            nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7832            if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
7833               continue;
7834            nir_intrinsic_instr *bary_intrinsic =
7835               nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
7836            nir_intrinsic_op op = bary_intrinsic->intrinsic;
7837
7838            /* Leave interpolateAtSample/Offset() where they are. */
7839            if (op == nir_intrinsic_load_barycentric_at_sample ||
7840                op == nir_intrinsic_load_barycentric_at_offset)
7841               continue;
7842
7843            nir_instr *move[3] = {
7844               &bary_intrinsic->instr,
7845               intrin->src[1].ssa->parent_instr,
7846               instr
7847            };
7848
7849            for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
7850               if (move[i]->block != top) {
7851                  move[i]->block = top;
7852                  exec_node_remove(&move[i]->node);
7853                  if (cursor_node) {
7854                     exec_node_insert_after(cursor_node, &move[i]->node);
7855                  } else {
7856                     exec_list_push_head(&top->instr_list, &move[i]->node);
7857                  }
7858                  cursor_node = &move[i]->node;
7859                  progress = true;
7860               }
7861            }
7862         }
7863      }
7864      nir_metadata_preserve(f->impl, (nir_metadata)
7865                            ((unsigned) nir_metadata_block_index |
7866                             (unsigned) nir_metadata_dominance));
7867   }
7868
7869   return progress;
7870}
7871
7872/**
7873 * Demote per-sample barycentric intrinsics to centroid.
7874 *
7875 * Useful when rendering to a non-multisampled buffer.
7876 */
7877static bool
7878demote_sample_qualifiers(nir_shader *nir)
7879{
7880   bool progress = true;
7881
7882   nir_foreach_function(f, nir) {
7883      if (!f->impl)
7884         continue;
7885
7886      nir_builder b;
7887      nir_builder_init(&b, f->impl);
7888
7889      nir_foreach_block(block, f->impl) {
7890         nir_foreach_instr_safe(instr, block) {
7891            if (instr->type != nir_instr_type_intrinsic)
7892               continue;
7893
7894            nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7895            if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
7896                intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
7897               continue;
7898
7899            b.cursor = nir_before_instr(instr);
7900            nir_ssa_def *centroid =
7901               nir_load_barycentric(&b, nir_intrinsic_load_barycentric_centroid,
7902                                    nir_intrinsic_interp_mode(intrin));
7903            nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
7904                                     nir_src_for_ssa(centroid));
7905            nir_instr_remove(instr);
7906            progress = true;
7907         }
7908      }
7909
7910      nir_metadata_preserve(f->impl, (nir_metadata)
7911                            ((unsigned) nir_metadata_block_index |
7912                             (unsigned) nir_metadata_dominance));
7913   }
7914
7915   return progress;
7916}
7917
7918/**
7919 * Pre-gen6, the register file of the EUs was shared between threads,
7920 * and each thread used some subset allocated on a 16-register block
7921 * granularity.  The unit states wanted these block counts.
7922 */
7923static inline int
7924brw_register_blocks(int reg_count)
7925{
7926   return ALIGN(reg_count, 16) / 16 - 1;
7927}
7928
7929const unsigned *
7930brw_compile_fs(const struct brw_compiler *compiler, void *log_data,
7931               void *mem_ctx,
7932               const struct brw_wm_prog_key *key,
7933               struct brw_wm_prog_data *prog_data,
7934               nir_shader *shader,
7935               struct gl_program *prog,
7936               int shader_time_index8, int shader_time_index16,
7937               int shader_time_index32, bool allow_spilling,
7938               bool use_rep_send, struct brw_vue_map *vue_map,
7939               char **error_str)
7940{
7941   const struct gen_device_info *devinfo = compiler->devinfo;
7942
7943   shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
7944   brw_nir_lower_fs_inputs(shader, devinfo, key);
7945   brw_nir_lower_fs_outputs(shader);
7946
7947   if (devinfo->gen < 6)
7948      brw_setup_vue_interpolation(vue_map, shader, prog_data);
7949
7950   if (!key->multisample_fbo)
7951      NIR_PASS_V(shader, demote_sample_qualifiers);
7952   NIR_PASS_V(shader, move_interpolation_to_top);
7953   shader = brw_postprocess_nir(shader, compiler, true);
7954
7955   /* key->alpha_test_func means simulating alpha testing via discards,
7956    * so the shader definitely kills pixels.
7957    */
7958   prog_data->uses_kill = shader->info.fs.uses_discard ||
7959      key->alpha_test_func;
7960   prog_data->uses_omask = key->multisample_fbo &&
7961      shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
7962   prog_data->computed_depth_mode = computed_depth_mode(shader);
7963   prog_data->computed_stencil =
7964      shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
7965
7966   prog_data->persample_dispatch =
7967      key->multisample_fbo &&
7968      (key->persample_interp ||
7969       (shader->info.system_values_read & (SYSTEM_BIT_SAMPLE_ID |
7970                                            SYSTEM_BIT_SAMPLE_POS)) ||
7971       shader->info.fs.uses_sample_qualifier ||
7972       shader->info.outputs_read);
7973
7974   prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
7975
7976   prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
7977   prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
7978   prog_data->inner_coverage = shader->info.fs.inner_coverage;
7979
7980   prog_data->barycentric_interp_modes =
7981      brw_compute_barycentric_interp_modes(compiler->devinfo, shader);
7982
7983   cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL, *simd32_cfg = NULL;
7984
7985   fs_visitor v8(compiler, log_data, mem_ctx, key,
7986                 &prog_data->base, prog, shader, 8,
7987                 shader_time_index8);
7988   if (!v8.run_fs(allow_spilling, false /* do_rep_send */)) {
7989      if (error_str)
7990         *error_str = ralloc_strdup(mem_ctx, v8.fail_msg);
7991
7992      return NULL;
7993   } else if (likely(!(INTEL_DEBUG & DEBUG_NO8))) {
7994      simd8_cfg = v8.cfg;
7995      prog_data->base.dispatch_grf_start_reg = v8.payload.num_regs;
7996      prog_data->reg_blocks_8 = brw_register_blocks(v8.grf_used);
7997   }
7998
7999   if (v8.max_dispatch_width >= 16 &&
8000       likely(!(INTEL_DEBUG & DEBUG_NO16) || use_rep_send)) {
8001      /* Try a SIMD16 compile */
8002      fs_visitor v16(compiler, log_data, mem_ctx, key,
8003                     &prog_data->base, prog, shader, 16,
8004                     shader_time_index16);
8005      v16.import_uniforms(&v8);
8006      if (!v16.run_fs(allow_spilling, use_rep_send)) {
8007         compiler->shader_perf_log(log_data,
8008                                   "SIMD16 shader failed to compile: %s",
8009                                   v16.fail_msg);
8010      } else {
8011         simd16_cfg = v16.cfg;
8012         prog_data->dispatch_grf_start_reg_16 = v16.payload.num_regs;
8013         prog_data->reg_blocks_16 = brw_register_blocks(v16.grf_used);
8014      }
8015   }
8016
8017   /* Currently, the compiler only supports SIMD32 on SNB+ */
8018   if (v8.max_dispatch_width >= 32 && !use_rep_send &&
8019       compiler->devinfo->gen >= 6 &&
8020       unlikely(INTEL_DEBUG & DEBUG_DO32)) {
8021      /* Try a SIMD32 compile */
8022      fs_visitor v32(compiler, log_data, mem_ctx, key,
8023                     &prog_data->base, prog, shader, 32,
8024                     shader_time_index32);
8025      v32.import_uniforms(&v8);
8026      if (!v32.run_fs(allow_spilling, false)) {
8027         compiler->shader_perf_log(log_data,
8028                                   "SIMD32 shader failed to compile: %s",
8029                                   v32.fail_msg);
8030      } else {
8031         simd32_cfg = v32.cfg;
8032         prog_data->dispatch_grf_start_reg_32 = v32.payload.num_regs;
8033         prog_data->reg_blocks_32 = brw_register_blocks(v32.grf_used);
8034      }
8035   }
8036
8037   /* When the caller requests a repclear shader, they want SIMD16-only */
8038   if (use_rep_send)
8039      simd8_cfg = NULL;
8040
8041   /* Prior to Iron Lake, the PS had a single shader offset with a jump table
8042    * at the top to select the shader.  We've never implemented that.
8043    * Instead, we just give them exactly one shader and we pick the widest one
8044    * available.
8045    */
8046   if (compiler->devinfo->gen < 5) {
8047      if (simd32_cfg || simd16_cfg)
8048         simd8_cfg = NULL;
8049      if (simd32_cfg)
8050         simd16_cfg = NULL;
8051   }
8052
8053   /* If computed depth is enabled SNB only allows SIMD8. */
8054   if (compiler->devinfo->gen == 6 &&
8055       prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF)
8056      assert(simd16_cfg == NULL && simd32_cfg == NULL);
8057
8058   if (compiler->devinfo->gen <= 5 && !simd8_cfg) {
8059      /* Iron lake and earlier only have one Dispatch GRF start field.  Make
8060       * the data available in the base prog data struct for convenience.
8061       */
8062      if (simd16_cfg) {
8063         prog_data->base.dispatch_grf_start_reg =
8064            prog_data->dispatch_grf_start_reg_16;
8065      } else if (simd32_cfg) {
8066         prog_data->base.dispatch_grf_start_reg =
8067            prog_data->dispatch_grf_start_reg_32;
8068      }
8069   }
8070
8071   if (prog_data->persample_dispatch) {
8072      /* Starting with SandyBridge (where we first get MSAA), the different
8073       * pixel dispatch combinations are grouped into classifications A
8074       * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1).  On all hardware
8075       * generations, the only configurations supporting persample dispatch
8076       * are are this in which only one dispatch width is enabled.
8077       */
8078      if (simd32_cfg || simd16_cfg)
8079         simd8_cfg = NULL;
8080      if (simd32_cfg)
8081         simd16_cfg = NULL;
8082   }
8083
8084   /* We have to compute the flat inputs after the visitor is finished running
8085    * because it relies on prog_data->urb_setup which is computed in
8086    * fs_visitor::calculate_urb_setup().
8087    */
8088   brw_compute_flat_inputs(prog_data, shader);
8089
8090   fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
8091                  v8.promoted_constants, v8.runtime_check_aads_emit,
8092                  MESA_SHADER_FRAGMENT);
8093
8094   if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
8095      g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
8096                                     shader->info.label ?
8097                                        shader->info.label : "unnamed",
8098                                     shader->info.name));
8099   }
8100
8101   if (simd8_cfg) {
8102      prog_data->dispatch_8 = true;
8103      g.generate_code(simd8_cfg, 8);
8104   }
8105
8106   if (simd16_cfg) {
8107      prog_data->dispatch_16 = true;
8108      prog_data->prog_offset_16 = g.generate_code(simd16_cfg, 16);
8109   }
8110
8111   if (simd32_cfg) {
8112      prog_data->dispatch_32 = true;
8113      prog_data->prog_offset_32 = g.generate_code(simd32_cfg, 32);
8114   }
8115
8116   return g.get_assembly();
8117}
8118
8119fs_reg *
8120fs_visitor::emit_cs_work_group_id_setup()
8121{
8122   assert(stage == MESA_SHADER_COMPUTE);
8123
8124   fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
8125
8126   struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
8127   struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
8128   struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
8129
8130   bld.MOV(*reg, r0_1);
8131   bld.MOV(offset(*reg, bld, 1), r0_6);
8132   bld.MOV(offset(*reg, bld, 2), r0_7);
8133
8134   return reg;
8135}
8136
8137static void
8138fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
8139{
8140   block->dwords = dwords;
8141   block->regs = DIV_ROUND_UP(dwords, 8);
8142   block->size = block->regs * 32;
8143}
8144
8145static void
8146cs_fill_push_const_info(const struct gen_device_info *devinfo,
8147                        struct brw_cs_prog_data *cs_prog_data)
8148{
8149   const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
8150   int subgroup_id_index = get_subgroup_id_param_index(prog_data);
8151   bool cross_thread_supported = devinfo->gen > 7 || devinfo->is_haswell;
8152
8153   /* The thread ID should be stored in the last param dword */
8154   assert(subgroup_id_index == -1 ||
8155          subgroup_id_index == (int)prog_data->nr_params - 1);
8156
8157   unsigned cross_thread_dwords, per_thread_dwords;
8158   if (!cross_thread_supported) {
8159      cross_thread_dwords = 0u;
8160      per_thread_dwords = prog_data->nr_params;
8161   } else if (subgroup_id_index >= 0) {
8162      /* Fill all but the last register with cross-thread payload */
8163      cross_thread_dwords = 8 * (subgroup_id_index / 8);
8164      per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
8165      assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
8166   } else {
8167      /* Fill all data using cross-thread payload */
8168      cross_thread_dwords = prog_data->nr_params;
8169      per_thread_dwords = 0u;
8170   }
8171
8172   fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
8173   fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
8174
8175   unsigned total_dwords =
8176      (cs_prog_data->push.per_thread.size * cs_prog_data->threads +
8177       cs_prog_data->push.cross_thread.size) / 4;
8178   fill_push_const_block_info(&cs_prog_data->push.total, total_dwords);
8179
8180   assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
8181          cs_prog_data->push.per_thread.size == 0);
8182   assert(cs_prog_data->push.cross_thread.dwords +
8183          cs_prog_data->push.per_thread.dwords ==
8184             prog_data->nr_params);
8185}
8186
8187static void
8188cs_set_simd_size(struct brw_cs_prog_data *cs_prog_data, unsigned size)
8189{
8190   cs_prog_data->simd_size = size;
8191   unsigned group_size = cs_prog_data->local_size[0] *
8192      cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
8193   cs_prog_data->threads = (group_size + size - 1) / size;
8194}
8195
8196static nir_shader *
8197compile_cs_to_nir(const struct brw_compiler *compiler,
8198                  void *mem_ctx,
8199                  const struct brw_cs_prog_key *key,
8200                  const nir_shader *src_shader,
8201                  unsigned dispatch_width)
8202{
8203   nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
8204   shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
8205
8206   NIR_PASS_V(shader, brw_nir_lower_cs_intrinsics, dispatch_width);
8207
8208   /* Clean up after the local index and ID calculations. */
8209   NIR_PASS_V(shader, nir_opt_constant_folding);
8210   NIR_PASS_V(shader, nir_opt_dce);
8211
8212   return brw_postprocess_nir(shader, compiler, true);
8213}
8214
8215const unsigned *
8216brw_compile_cs(const struct brw_compiler *compiler, void *log_data,
8217               void *mem_ctx,
8218               const struct brw_cs_prog_key *key,
8219               struct brw_cs_prog_data *prog_data,
8220               const nir_shader *src_shader,
8221               int shader_time_index,
8222               char **error_str)
8223{
8224   prog_data->local_size[0] = src_shader->info.cs.local_size[0];
8225   prog_data->local_size[1] = src_shader->info.cs.local_size[1];
8226   prog_data->local_size[2] = src_shader->info.cs.local_size[2];
8227   unsigned local_workgroup_size =
8228      src_shader->info.cs.local_size[0] * src_shader->info.cs.local_size[1] *
8229      src_shader->info.cs.local_size[2];
8230
8231   unsigned min_dispatch_width =
8232      DIV_ROUND_UP(local_workgroup_size, compiler->devinfo->max_cs_threads);
8233   min_dispatch_width = MAX2(8, min_dispatch_width);
8234   min_dispatch_width = util_next_power_of_two(min_dispatch_width);
8235   assert(min_dispatch_width <= 32);
8236
8237   fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
8238   cfg_t *cfg = NULL;
8239   const char *fail_msg = NULL;
8240   unsigned promoted_constants = 0;
8241
8242   /* Now the main event: Visit the shader IR and generate our CS IR for it.
8243    */
8244   if (min_dispatch_width <= 8) {
8245      nir_shader *nir8 = compile_cs_to_nir(compiler, mem_ctx, key,
8246                                           src_shader, 8);
8247      v8 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8248                          NULL, /* Never used in core profile */
8249                          nir8, 8, shader_time_index);
8250      if (!v8->run_cs(min_dispatch_width)) {
8251         fail_msg = v8->fail_msg;
8252      } else {
8253         /* We should always be able to do SIMD32 for compute shaders */
8254         assert(v8->max_dispatch_width >= 32);
8255
8256         cfg = v8->cfg;
8257         cs_set_simd_size(prog_data, 8);
8258         cs_fill_push_const_info(compiler->devinfo, prog_data);
8259         promoted_constants = v8->promoted_constants;
8260      }
8261   }
8262
8263   if (likely(!(INTEL_DEBUG & DEBUG_NO16)) &&
8264       !fail_msg && min_dispatch_width <= 16) {
8265      /* Try a SIMD16 compile */
8266      nir_shader *nir16 = compile_cs_to_nir(compiler, mem_ctx, key,
8267                                            src_shader, 16);
8268      v16 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8269                           NULL, /* Never used in core profile */
8270                           nir16, 16, shader_time_index);
8271      if (v8)
8272         v16->import_uniforms(v8);
8273
8274      if (!v16->run_cs(min_dispatch_width)) {
8275         compiler->shader_perf_log(log_data,
8276                                   "SIMD16 shader failed to compile: %s",
8277                                   v16->fail_msg);
8278         if (!cfg) {
8279            fail_msg =
8280               "Couldn't generate SIMD16 program and not "
8281               "enough threads for SIMD8";
8282         }
8283      } else {
8284         /* We should always be able to do SIMD32 for compute shaders */
8285         assert(v16->max_dispatch_width >= 32);
8286
8287         cfg = v16->cfg;
8288         cs_set_simd_size(prog_data, 16);
8289         cs_fill_push_const_info(compiler->devinfo, prog_data);
8290         promoted_constants = v16->promoted_constants;
8291      }
8292   }
8293
8294   /* We should always be able to do SIMD32 for compute shaders */
8295   assert(!v16 || v16->max_dispatch_width >= 32);
8296
8297   if (!fail_msg && (min_dispatch_width > 16 || (INTEL_DEBUG & DEBUG_DO32))) {
8298      /* Try a SIMD32 compile */
8299      nir_shader *nir32 = compile_cs_to_nir(compiler, mem_ctx, key,
8300                                            src_shader, 32);
8301      v32 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8302                           NULL, /* Never used in core profile */
8303                           nir32, 32, shader_time_index);
8304      if (v8)
8305         v32->import_uniforms(v8);
8306      else if (v16)
8307         v32->import_uniforms(v16);
8308
8309      if (!v32->run_cs(min_dispatch_width)) {
8310         compiler->shader_perf_log(log_data,
8311                                   "SIMD32 shader failed to compile: %s",
8312                                   v32->fail_msg);
8313         if (!cfg) {
8314            fail_msg =
8315               "Couldn't generate SIMD32 program and not "
8316               "enough threads for SIMD16";
8317         }
8318      } else {
8319         cfg = v32->cfg;
8320         cs_set_simd_size(prog_data, 32);
8321         cs_fill_push_const_info(compiler->devinfo, prog_data);
8322         promoted_constants = v32->promoted_constants;
8323      }
8324   }
8325
8326   const unsigned *ret = NULL;
8327   if (unlikely(cfg == NULL)) {
8328      assert(fail_msg);
8329      if (error_str)
8330         *error_str = ralloc_strdup(mem_ctx, fail_msg);
8331   } else {
8332      fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
8333                     promoted_constants, false, MESA_SHADER_COMPUTE);
8334      if (INTEL_DEBUG & DEBUG_CS) {
8335         char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
8336                                      src_shader->info.label ?
8337                                         src_shader->info.label : "unnamed",
8338                                      src_shader->info.name);
8339         g.enable_debug(name);
8340      }
8341
8342      g.generate_code(cfg, prog_data->simd_size);
8343
8344      ret = g.get_assembly();
8345   }
8346
8347   delete v8;
8348   delete v16;
8349   delete v32;
8350
8351   return ret;
8352}
8353
8354/**
8355 * Test the dispatch mask packing assumptions of
8356 * brw_stage_has_packed_dispatch().  Call this from e.g. the top of
8357 * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
8358 * executed with an unexpected dispatch mask.
8359 */
8360static UNUSED void
8361brw_fs_test_dispatch_packing(const fs_builder &bld)
8362{
8363   const gl_shader_stage stage = bld.shader->stage;
8364
8365   if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
8366                                     bld.shader->stage_prog_data)) {
8367      const fs_builder ubld = bld.exec_all().group(1, 0);
8368      const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
8369      const fs_reg mask = (stage == MESA_SHADER_FRAGMENT ? brw_vmask_reg() :
8370                           brw_dmask_reg());
8371
8372      ubld.ADD(tmp, mask, brw_imm_ud(1));
8373      ubld.AND(tmp, mask, tmp);
8374
8375      /* This will loop forever if the dispatch mask doesn't have the expected
8376       * form '2^n-1', in which case tmp will be non-zero.
8377       */
8378      bld.emit(BRW_OPCODE_DO);
8379      bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
8380      set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));
8381   }
8382}
8383