brw_vec4.cpp revision 01e04c3f
1/*
2 * Copyright © 2011 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24#include "brw_vec4.h"
25#include "brw_fs.h"
26#include "brw_cfg.h"
27#include "brw_nir.h"
28#include "brw_vec4_builder.h"
29#include "brw_vec4_live_variables.h"
30#include "brw_vec4_vs.h"
31#include "brw_dead_control_flow.h"
32#include "common/gen_debug.h"
33#include "program/prog_parameter.h"
34#include "util/u_math.h"
35
36#define MAX_INSTRUCTION (1 << 30)
37
38using namespace brw;
39
40namespace brw {
41
42void
43src_reg::init()
44{
45   memset((void*)this, 0, sizeof(*this));
46   this->file = BAD_FILE;
47   this->type = BRW_REGISTER_TYPE_UD;
48}
49
50src_reg::src_reg(enum brw_reg_file file, int nr, const glsl_type *type)
51{
52   init();
53
54   this->file = file;
55   this->nr = nr;
56   if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
57      this->swizzle = brw_swizzle_for_size(type->vector_elements);
58   else
59      this->swizzle = BRW_SWIZZLE_XYZW;
60   if (type)
61      this->type = brw_type_for_base_type(type);
62}
63
64/** Generic unset register constructor. */
65src_reg::src_reg()
66{
67   init();
68}
69
70src_reg::src_reg(struct ::brw_reg reg) :
71   backend_reg(reg)
72{
73   this->offset = 0;
74   this->reladdr = NULL;
75}
76
77src_reg::src_reg(const dst_reg &reg) :
78   backend_reg(reg)
79{
80   this->reladdr = reg.reladdr;
81   this->swizzle = brw_swizzle_for_mask(reg.writemask);
82}
83
84void
85dst_reg::init()
86{
87   memset((void*)this, 0, sizeof(*this));
88   this->file = BAD_FILE;
89   this->type = BRW_REGISTER_TYPE_UD;
90   this->writemask = WRITEMASK_XYZW;
91}
92
93dst_reg::dst_reg()
94{
95   init();
96}
97
98dst_reg::dst_reg(enum brw_reg_file file, int nr)
99{
100   init();
101
102   this->file = file;
103   this->nr = nr;
104}
105
106dst_reg::dst_reg(enum brw_reg_file file, int nr, const glsl_type *type,
107                 unsigned writemask)
108{
109   init();
110
111   this->file = file;
112   this->nr = nr;
113   this->type = brw_type_for_base_type(type);
114   this->writemask = writemask;
115}
116
117dst_reg::dst_reg(enum brw_reg_file file, int nr, brw_reg_type type,
118                 unsigned writemask)
119{
120   init();
121
122   this->file = file;
123   this->nr = nr;
124   this->type = type;
125   this->writemask = writemask;
126}
127
128dst_reg::dst_reg(struct ::brw_reg reg) :
129   backend_reg(reg)
130{
131   this->offset = 0;
132   this->reladdr = NULL;
133}
134
135dst_reg::dst_reg(const src_reg &reg) :
136   backend_reg(reg)
137{
138   this->writemask = brw_mask_for_swizzle(reg.swizzle);
139   this->reladdr = reg.reladdr;
140}
141
142bool
143dst_reg::equals(const dst_reg &r) const
144{
145   return (this->backend_reg::equals(r) &&
146           (reladdr == r.reladdr ||
147            (reladdr && r.reladdr && reladdr->equals(*r.reladdr))));
148}
149
150bool
151vec4_instruction::is_send_from_grf()
152{
153   switch (opcode) {
154   case SHADER_OPCODE_SHADER_TIME_ADD:
155   case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
156   case SHADER_OPCODE_UNTYPED_ATOMIC:
157   case SHADER_OPCODE_UNTYPED_SURFACE_READ:
158   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
159   case SHADER_OPCODE_TYPED_ATOMIC:
160   case SHADER_OPCODE_TYPED_SURFACE_READ:
161   case SHADER_OPCODE_TYPED_SURFACE_WRITE:
162   case VEC4_OPCODE_URB_READ:
163   case TCS_OPCODE_URB_WRITE:
164   case TCS_OPCODE_RELEASE_INPUT:
165   case SHADER_OPCODE_BARRIER:
166      return true;
167   default:
168      return false;
169   }
170}
171
172/**
173 * Returns true if this instruction's sources and destinations cannot
174 * safely be the same register.
175 *
176 * In most cases, a register can be written over safely by the same
177 * instruction that is its last use.  For a single instruction, the
178 * sources are dereferenced before writing of the destination starts
179 * (naturally).
180 *
181 * However, there are a few cases where this can be problematic:
182 *
183 * - Virtual opcodes that translate to multiple instructions in the
184 *   code generator: if src == dst and one instruction writes the
185 *   destination before a later instruction reads the source, then
186 *   src will have been clobbered.
187 *
188 * The register allocator uses this information to set up conflicts between
189 * GRF sources and the destination.
190 */
191bool
192vec4_instruction::has_source_and_destination_hazard() const
193{
194   switch (opcode) {
195   case TCS_OPCODE_SET_INPUT_URB_OFFSETS:
196   case TCS_OPCODE_SET_OUTPUT_URB_OFFSETS:
197   case TES_OPCODE_ADD_INDIRECT_URB_OFFSET:
198      return true;
199   default:
200      /* 8-wide compressed DF operations are executed as two 4-wide operations,
201       * so we have a src/dst hazard if the first half of the instruction
202       * overwrites the source of the second half. Prevent this by marking
203       * compressed instructions as having src/dst hazards, so the register
204       * allocator assigns safe register regions for dst and srcs.
205       */
206      return size_written > REG_SIZE;
207   }
208}
209
210unsigned
211vec4_instruction::size_read(unsigned arg) const
212{
213   switch (opcode) {
214   case SHADER_OPCODE_SHADER_TIME_ADD:
215   case SHADER_OPCODE_UNTYPED_ATOMIC:
216   case SHADER_OPCODE_UNTYPED_SURFACE_READ:
217   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
218   case SHADER_OPCODE_TYPED_ATOMIC:
219   case SHADER_OPCODE_TYPED_SURFACE_READ:
220   case SHADER_OPCODE_TYPED_SURFACE_WRITE:
221   case TCS_OPCODE_URB_WRITE:
222      if (arg == 0)
223         return mlen * REG_SIZE;
224      break;
225   case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
226      if (arg == 1)
227         return mlen * REG_SIZE;
228      break;
229   default:
230      break;
231   }
232
233   switch (src[arg].file) {
234   case BAD_FILE:
235      return 0;
236   case IMM:
237   case UNIFORM:
238      return 4 * type_sz(src[arg].type);
239   default:
240      /* XXX - Represent actual vertical stride. */
241      return exec_size * type_sz(src[arg].type);
242   }
243}
244
245bool
246vec4_instruction::can_do_source_mods(const struct gen_device_info *devinfo)
247{
248   if (devinfo->gen == 6 && is_math())
249      return false;
250
251   if (is_send_from_grf())
252      return false;
253
254   if (!backend_instruction::can_do_source_mods())
255      return false;
256
257   return true;
258}
259
260bool
261vec4_instruction::can_do_cmod()
262{
263   if (!backend_instruction::can_do_cmod())
264      return false;
265
266   /* The accumulator result appears to get used for the conditional modifier
267    * generation.  When negating a UD value, there is a 33rd bit generated for
268    * the sign in the accumulator value, so now you can't check, for example,
269    * equality with a 32-bit value.  See piglit fs-op-neg-uvec4.
270    */
271   for (unsigned i = 0; i < 3; i++) {
272      if (src[i].file != BAD_FILE &&
273          type_is_unsigned_int(src[i].type) && src[i].negate)
274         return false;
275   }
276
277   return true;
278}
279
280bool
281vec4_instruction::can_do_writemask(const struct gen_device_info *devinfo)
282{
283   switch (opcode) {
284   case SHADER_OPCODE_GEN4_SCRATCH_READ:
285   case VEC4_OPCODE_DOUBLE_TO_F32:
286   case VEC4_OPCODE_DOUBLE_TO_D32:
287   case VEC4_OPCODE_DOUBLE_TO_U32:
288   case VEC4_OPCODE_TO_DOUBLE:
289   case VEC4_OPCODE_PICK_LOW_32BIT:
290   case VEC4_OPCODE_PICK_HIGH_32BIT:
291   case VEC4_OPCODE_SET_LOW_32BIT:
292   case VEC4_OPCODE_SET_HIGH_32BIT:
293   case VS_OPCODE_PULL_CONSTANT_LOAD:
294   case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
295   case VS_OPCODE_SET_SIMD4X2_HEADER_GEN9:
296   case TCS_OPCODE_SET_INPUT_URB_OFFSETS:
297   case TCS_OPCODE_SET_OUTPUT_URB_OFFSETS:
298   case TES_OPCODE_CREATE_INPUT_READ_HEADER:
299   case TES_OPCODE_ADD_INDIRECT_URB_OFFSET:
300   case VEC4_OPCODE_URB_READ:
301   case SHADER_OPCODE_MOV_INDIRECT:
302      return false;
303   default:
304      /* The MATH instruction on Gen6 only executes in align1 mode, which does
305       * not support writemasking.
306       */
307      if (devinfo->gen == 6 && is_math())
308         return false;
309
310      if (is_tex())
311         return false;
312
313      return true;
314   }
315}
316
317bool
318vec4_instruction::can_change_types() const
319{
320   return dst.type == src[0].type &&
321          !src[0].abs && !src[0].negate && !saturate &&
322          (opcode == BRW_OPCODE_MOV ||
323           (opcode == BRW_OPCODE_SEL &&
324            dst.type == src[1].type &&
325            predicate != BRW_PREDICATE_NONE &&
326            !src[1].abs && !src[1].negate));
327}
328
329/**
330 * Returns how many MRFs an opcode will write over.
331 *
332 * Note that this is not the 0 or 1 implied writes in an actual gen
333 * instruction -- the generate_* functions generate additional MOVs
334 * for setup.
335 */
336int
337vec4_visitor::implied_mrf_writes(vec4_instruction *inst)
338{
339   if (inst->mlen == 0 || inst->is_send_from_grf())
340      return 0;
341
342   switch (inst->opcode) {
343   case SHADER_OPCODE_RCP:
344   case SHADER_OPCODE_RSQ:
345   case SHADER_OPCODE_SQRT:
346   case SHADER_OPCODE_EXP2:
347   case SHADER_OPCODE_LOG2:
348   case SHADER_OPCODE_SIN:
349   case SHADER_OPCODE_COS:
350      return 1;
351   case SHADER_OPCODE_INT_QUOTIENT:
352   case SHADER_OPCODE_INT_REMAINDER:
353   case SHADER_OPCODE_POW:
354   case TCS_OPCODE_THREAD_END:
355      return 2;
356   case VS_OPCODE_URB_WRITE:
357      return 1;
358   case VS_OPCODE_PULL_CONSTANT_LOAD:
359      return 2;
360   case SHADER_OPCODE_GEN4_SCRATCH_READ:
361      return 2;
362   case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
363      return 3;
364   case GS_OPCODE_URB_WRITE:
365   case GS_OPCODE_URB_WRITE_ALLOCATE:
366   case GS_OPCODE_THREAD_END:
367      return 0;
368   case GS_OPCODE_FF_SYNC:
369      return 1;
370   case TCS_OPCODE_URB_WRITE:
371      return 0;
372   case SHADER_OPCODE_SHADER_TIME_ADD:
373      return 0;
374   case SHADER_OPCODE_TEX:
375   case SHADER_OPCODE_TXL:
376   case SHADER_OPCODE_TXD:
377   case SHADER_OPCODE_TXF:
378   case SHADER_OPCODE_TXF_CMS:
379   case SHADER_OPCODE_TXF_CMS_W:
380   case SHADER_OPCODE_TXF_MCS:
381   case SHADER_OPCODE_TXS:
382   case SHADER_OPCODE_TG4:
383   case SHADER_OPCODE_TG4_OFFSET:
384   case SHADER_OPCODE_SAMPLEINFO:
385   case SHADER_OPCODE_GET_BUFFER_SIZE:
386      return inst->header_size;
387   default:
388      unreachable("not reached");
389   }
390}
391
392bool
393src_reg::equals(const src_reg &r) const
394{
395   return (this->backend_reg::equals(r) &&
396	   !reladdr && !r.reladdr);
397}
398
399bool
400src_reg::negative_equals(const src_reg &r) const
401{
402   return this->backend_reg::negative_equals(r) &&
403          !reladdr && !r.reladdr;
404}
405
406bool
407vec4_visitor::opt_vector_float()
408{
409   bool progress = false;
410
411   foreach_block(block, cfg) {
412      int last_reg = -1, last_offset = -1;
413      enum brw_reg_file last_reg_file = BAD_FILE;
414
415      uint8_t imm[4] = { 0 };
416      int inst_count = 0;
417      vec4_instruction *imm_inst[4];
418      unsigned writemask = 0;
419      enum brw_reg_type dest_type = BRW_REGISTER_TYPE_F;
420
421      foreach_inst_in_block_safe(vec4_instruction, inst, block) {
422         int vf = -1;
423         enum brw_reg_type need_type;
424
425         /* Look for unconditional MOVs from an immediate with a partial
426          * writemask.  Skip type-conversion MOVs other than integer 0,
427          * where the type doesn't matter.  See if the immediate can be
428          * represented as a VF.
429          */
430         if (inst->opcode == BRW_OPCODE_MOV &&
431             inst->src[0].file == IMM &&
432             inst->predicate == BRW_PREDICATE_NONE &&
433             inst->dst.writemask != WRITEMASK_XYZW &&
434             type_sz(inst->src[0].type) < 8 &&
435             (inst->src[0].type == inst->dst.type || inst->src[0].d == 0)) {
436
437            vf = brw_float_to_vf(inst->src[0].d);
438            need_type = BRW_REGISTER_TYPE_D;
439
440            if (vf == -1) {
441               vf = brw_float_to_vf(inst->src[0].f);
442               need_type = BRW_REGISTER_TYPE_F;
443            }
444         } else {
445            last_reg = -1;
446         }
447
448         /* If this wasn't a MOV, or the destination register doesn't match,
449          * or we have to switch destination types, then this breaks our
450          * sequence.  Combine anything we've accumulated so far.
451          */
452         if (last_reg != inst->dst.nr ||
453             last_offset != inst->dst.offset ||
454             last_reg_file != inst->dst.file ||
455             (vf > 0 && dest_type != need_type)) {
456
457            if (inst_count > 1) {
458               unsigned vf;
459               memcpy(&vf, imm, sizeof(vf));
460               vec4_instruction *mov = MOV(imm_inst[0]->dst, brw_imm_vf(vf));
461               mov->dst.type = dest_type;
462               mov->dst.writemask = writemask;
463               inst->insert_before(block, mov);
464
465               for (int i = 0; i < inst_count; i++) {
466                  imm_inst[i]->remove(block);
467               }
468
469               progress = true;
470            }
471
472            inst_count = 0;
473            last_reg = -1;
474            writemask = 0;
475            dest_type = BRW_REGISTER_TYPE_F;
476
477            for (int i = 0; i < 4; i++) {
478               imm[i] = 0;
479            }
480         }
481
482         /* Record this instruction's value (if it was representable). */
483         if (vf != -1) {
484            if ((inst->dst.writemask & WRITEMASK_X) != 0)
485               imm[0] = vf;
486            if ((inst->dst.writemask & WRITEMASK_Y) != 0)
487               imm[1] = vf;
488            if ((inst->dst.writemask & WRITEMASK_Z) != 0)
489               imm[2] = vf;
490            if ((inst->dst.writemask & WRITEMASK_W) != 0)
491               imm[3] = vf;
492
493            writemask |= inst->dst.writemask;
494            imm_inst[inst_count++] = inst;
495
496            last_reg = inst->dst.nr;
497            last_offset = inst->dst.offset;
498            last_reg_file = inst->dst.file;
499            if (vf > 0)
500               dest_type = need_type;
501         }
502      }
503   }
504
505   if (progress)
506      invalidate_live_intervals();
507
508   return progress;
509}
510
511/* Replaces unused channels of a swizzle with channels that are used.
512 *
513 * For instance, this pass transforms
514 *
515 *    mov vgrf4.yz, vgrf5.wxzy
516 *
517 * into
518 *
519 *    mov vgrf4.yz, vgrf5.xxzx
520 *
521 * This eliminates false uses of some channels, letting dead code elimination
522 * remove the instructions that wrote them.
523 */
524bool
525vec4_visitor::opt_reduce_swizzle()
526{
527   bool progress = false;
528
529   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
530      if (inst->dst.file == BAD_FILE ||
531          inst->dst.file == ARF ||
532          inst->dst.file == FIXED_GRF ||
533          inst->is_send_from_grf())
534         continue;
535
536      unsigned swizzle;
537
538      /* Determine which channels of the sources are read. */
539      switch (inst->opcode) {
540      case VEC4_OPCODE_PACK_BYTES:
541      case BRW_OPCODE_DP4:
542      case BRW_OPCODE_DPH: /* FINISHME: DPH reads only three channels of src0,
543                            *           but all four of src1.
544                            */
545         swizzle = brw_swizzle_for_size(4);
546         break;
547      case BRW_OPCODE_DP3:
548         swizzle = brw_swizzle_for_size(3);
549         break;
550      case BRW_OPCODE_DP2:
551         swizzle = brw_swizzle_for_size(2);
552         break;
553
554      case VEC4_OPCODE_TO_DOUBLE:
555      case VEC4_OPCODE_DOUBLE_TO_F32:
556      case VEC4_OPCODE_DOUBLE_TO_D32:
557      case VEC4_OPCODE_DOUBLE_TO_U32:
558      case VEC4_OPCODE_PICK_LOW_32BIT:
559      case VEC4_OPCODE_PICK_HIGH_32BIT:
560      case VEC4_OPCODE_SET_LOW_32BIT:
561      case VEC4_OPCODE_SET_HIGH_32BIT:
562         swizzle = brw_swizzle_for_size(4);
563         break;
564
565      default:
566         swizzle = brw_swizzle_for_mask(inst->dst.writemask);
567         break;
568      }
569
570      /* Update sources' swizzles. */
571      for (int i = 0; i < 3; i++) {
572         if (inst->src[i].file != VGRF &&
573             inst->src[i].file != ATTR &&
574             inst->src[i].file != UNIFORM)
575            continue;
576
577         const unsigned new_swizzle =
578            brw_compose_swizzle(swizzle, inst->src[i].swizzle);
579         if (inst->src[i].swizzle != new_swizzle) {
580            inst->src[i].swizzle = new_swizzle;
581            progress = true;
582         }
583      }
584   }
585
586   if (progress)
587      invalidate_live_intervals();
588
589   return progress;
590}
591
592void
593vec4_visitor::split_uniform_registers()
594{
595   /* Prior to this, uniforms have been in an array sized according to
596    * the number of vector uniforms present, sparsely filled (so an
597    * aggregate results in reg indices being skipped over).  Now we're
598    * going to cut those aggregates up so each .nr index is one
599    * vector.  The goal is to make elimination of unused uniform
600    * components easier later.
601    */
602   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
603      for (int i = 0 ; i < 3; i++) {
604	 if (inst->src[i].file != UNIFORM)
605	    continue;
606
607	 assert(!inst->src[i].reladdr);
608
609         inst->src[i].nr += inst->src[i].offset / 16;
610	 inst->src[i].offset %= 16;
611      }
612   }
613}
614
615/* This function returns the register number where we placed the uniform */
616static int
617set_push_constant_loc(const int nr_uniforms, int *new_uniform_count,
618                      const int src, const int size, const int channel_size,
619                      int *new_loc, int *new_chan,
620                      int *new_chans_used)
621{
622   int dst;
623   /* Find the lowest place we can slot this uniform in. */
624   for (dst = 0; dst < nr_uniforms; dst++) {
625      if (ALIGN(new_chans_used[dst], channel_size) + size <= 4)
626         break;
627   }
628
629   assert(dst < nr_uniforms);
630
631   new_loc[src] = dst;
632   new_chan[src] = ALIGN(new_chans_used[dst], channel_size);
633   new_chans_used[dst] = ALIGN(new_chans_used[dst], channel_size) + size;
634
635   *new_uniform_count = MAX2(*new_uniform_count, dst + 1);
636   return dst;
637}
638
639void
640vec4_visitor::pack_uniform_registers()
641{
642   uint8_t chans_used[this->uniforms];
643   int new_loc[this->uniforms];
644   int new_chan[this->uniforms];
645   bool is_aligned_to_dvec4[this->uniforms];
646   int new_chans_used[this->uniforms];
647   int channel_sizes[this->uniforms];
648
649   memset(chans_used, 0, sizeof(chans_used));
650   memset(new_loc, 0, sizeof(new_loc));
651   memset(new_chan, 0, sizeof(new_chan));
652   memset(new_chans_used, 0, sizeof(new_chans_used));
653   memset(is_aligned_to_dvec4, 0, sizeof(is_aligned_to_dvec4));
654   memset(channel_sizes, 0, sizeof(channel_sizes));
655
656   /* Find which uniform vectors are actually used by the program.  We
657    * expect unused vector elements when we've moved array access out
658    * to pull constants, and from some GLSL code generators like wine.
659    */
660   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
661      unsigned readmask;
662      switch (inst->opcode) {
663      case VEC4_OPCODE_PACK_BYTES:
664      case BRW_OPCODE_DP4:
665      case BRW_OPCODE_DPH:
666         readmask = 0xf;
667         break;
668      case BRW_OPCODE_DP3:
669         readmask = 0x7;
670         break;
671      case BRW_OPCODE_DP2:
672         readmask = 0x3;
673         break;
674      default:
675         readmask = inst->dst.writemask;
676         break;
677      }
678
679      for (int i = 0 ; i < 3; i++) {
680         if (inst->src[i].file != UNIFORM)
681            continue;
682
683         assert(type_sz(inst->src[i].type) % 4 == 0);
684         int channel_size = type_sz(inst->src[i].type) / 4;
685
686         int reg = inst->src[i].nr;
687         for (int c = 0; c < 4; c++) {
688            if (!(readmask & (1 << c)))
689               continue;
690
691            unsigned channel = BRW_GET_SWZ(inst->src[i].swizzle, c) + 1;
692            unsigned used = MAX2(chans_used[reg], channel * channel_size);
693            if (used <= 4) {
694               chans_used[reg] = used;
695               channel_sizes[reg] = MAX2(channel_sizes[reg], channel_size);
696            } else {
697               is_aligned_to_dvec4[reg] = true;
698               is_aligned_to_dvec4[reg + 1] = true;
699               chans_used[reg + 1] = used - 4;
700               channel_sizes[reg + 1] = MAX2(channel_sizes[reg + 1], channel_size);
701            }
702         }
703      }
704
705      if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
706          inst->src[0].file == UNIFORM) {
707         assert(inst->src[2].file == BRW_IMMEDIATE_VALUE);
708         assert(inst->src[0].subnr == 0);
709
710         unsigned bytes_read = inst->src[2].ud;
711         assert(bytes_read % 4 == 0);
712         unsigned vec4s_read = DIV_ROUND_UP(bytes_read, 16);
713
714         /* We just mark every register touched by a MOV_INDIRECT as being
715          * fully used.  This ensures that it doesn't broken up piecewise by
716          * the next part of our packing algorithm.
717          */
718         int reg = inst->src[0].nr;
719         int channel_size = type_sz(inst->src[0].type) / 4;
720         for (unsigned i = 0; i < vec4s_read; i++) {
721            chans_used[reg + i] = 4;
722            channel_sizes[reg + i] = MAX2(channel_sizes[reg + i], channel_size);
723         }
724      }
725   }
726
727   int new_uniform_count = 0;
728
729   /* As the uniforms are going to be reordered, take the data from a temporary
730    * copy of the original param[].
731    */
732   uint32_t *param = ralloc_array(NULL, uint32_t, stage_prog_data->nr_params);
733   memcpy(param, stage_prog_data->param,
734          sizeof(uint32_t) * stage_prog_data->nr_params);
735
736   /* Now, figure out a packing of the live uniform vectors into our
737    * push constants. Start with dvec{3,4} because they are aligned to
738    * dvec4 size (2 vec4).
739    */
740   for (int src = 0; src < uniforms; src++) {
741      int size = chans_used[src];
742
743      if (size == 0 || !is_aligned_to_dvec4[src])
744         continue;
745
746      /* dvec3 are aligned to dvec4 size, apply the alignment of the size
747       * to 4 to avoid moving last component of a dvec3 to the available
748       * location at the end of a previous dvec3. These available locations
749       * could be filled by smaller variables in next loop.
750       */
751      size = ALIGN(size, 4);
752      int dst = set_push_constant_loc(uniforms, &new_uniform_count,
753                                      src, size, channel_sizes[src],
754                                      new_loc, new_chan,
755                                      new_chans_used);
756      /* Move the references to the data */
757      for (int j = 0; j < size; j++) {
758         stage_prog_data->param[dst * 4 + new_chan[src] + j] =
759            param[src * 4 + j];
760      }
761   }
762
763   /* Continue with the rest of data, which is aligned to vec4. */
764   for (int src = 0; src < uniforms; src++) {
765      int size = chans_used[src];
766
767      if (size == 0 || is_aligned_to_dvec4[src])
768         continue;
769
770      int dst = set_push_constant_loc(uniforms, &new_uniform_count,
771                                      src, size, channel_sizes[src],
772                                      new_loc, new_chan,
773                                      new_chans_used);
774      /* Move the references to the data */
775      for (int j = 0; j < size; j++) {
776         stage_prog_data->param[dst * 4 + new_chan[src] + j] =
777            param[src * 4 + j];
778      }
779   }
780
781   ralloc_free(param);
782   this->uniforms = new_uniform_count;
783
784   /* Now, update the instructions for our repacked uniforms. */
785   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
786      for (int i = 0 ; i < 3; i++) {
787         int src = inst->src[i].nr;
788
789         if (inst->src[i].file != UNIFORM)
790            continue;
791
792         int chan = new_chan[src] / channel_sizes[src];
793         inst->src[i].nr = new_loc[src];
794         inst->src[i].swizzle += BRW_SWIZZLE4(chan, chan, chan, chan);
795      }
796   }
797}
798
799/**
800 * Does algebraic optimizations (0 * a = 0, 1 * a = a, a + 0 = a).
801 *
802 * While GLSL IR also performs this optimization, we end up with it in
803 * our instruction stream for a couple of reasons.  One is that we
804 * sometimes generate silly instructions, for example in array access
805 * where we'll generate "ADD offset, index, base" even if base is 0.
806 * The other is that GLSL IR's constant propagation doesn't track the
807 * components of aggregates, so some VS patterns (initialize matrix to
808 * 0, accumulate in vertex blending factors) end up breaking down to
809 * instructions involving 0.
810 */
811bool
812vec4_visitor::opt_algebraic()
813{
814   bool progress = false;
815
816   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
817      switch (inst->opcode) {
818      case BRW_OPCODE_MOV:
819         if (inst->src[0].file != IMM)
820            break;
821
822         if (inst->saturate) {
823            /* Full mixed-type saturates don't happen.  However, we can end up
824             * with things like:
825             *
826             *    mov.sat(8) g21<1>DF       -1F
827             *
828             * Other mixed-size-but-same-base-type cases may also be possible.
829             */
830            if (inst->dst.type != inst->src[0].type &&
831                inst->dst.type != BRW_REGISTER_TYPE_DF &&
832                inst->src[0].type != BRW_REGISTER_TYPE_F)
833               assert(!"unimplemented: saturate mixed types");
834
835            if (brw_saturate_immediate(inst->src[0].type,
836                                       &inst->src[0].as_brw_reg())) {
837               inst->saturate = false;
838               progress = true;
839            }
840         }
841         break;
842
843      case BRW_OPCODE_OR:
844         if (inst->src[1].is_zero()) {
845            inst->opcode = BRW_OPCODE_MOV;
846            inst->src[1] = src_reg();
847            progress = true;
848         }
849         break;
850
851      case VEC4_OPCODE_UNPACK_UNIFORM:
852         if (inst->src[0].file != UNIFORM) {
853            inst->opcode = BRW_OPCODE_MOV;
854            progress = true;
855         }
856         break;
857
858      case BRW_OPCODE_ADD:
859	 if (inst->src[1].is_zero()) {
860	    inst->opcode = BRW_OPCODE_MOV;
861	    inst->src[1] = src_reg();
862	    progress = true;
863	 }
864	 break;
865
866      case BRW_OPCODE_MUL:
867	 if (inst->src[1].is_zero()) {
868	    inst->opcode = BRW_OPCODE_MOV;
869	    switch (inst->src[0].type) {
870	    case BRW_REGISTER_TYPE_F:
871	       inst->src[0] = brw_imm_f(0.0f);
872	       break;
873	    case BRW_REGISTER_TYPE_D:
874	       inst->src[0] = brw_imm_d(0);
875	       break;
876	    case BRW_REGISTER_TYPE_UD:
877	       inst->src[0] = brw_imm_ud(0u);
878	       break;
879	    default:
880	       unreachable("not reached");
881	    }
882	    inst->src[1] = src_reg();
883	    progress = true;
884	 } else if (inst->src[1].is_one()) {
885	    inst->opcode = BRW_OPCODE_MOV;
886	    inst->src[1] = src_reg();
887	    progress = true;
888         } else if (inst->src[1].is_negative_one()) {
889            inst->opcode = BRW_OPCODE_MOV;
890            inst->src[0].negate = !inst->src[0].negate;
891            inst->src[1] = src_reg();
892            progress = true;
893	 }
894	 break;
895      case BRW_OPCODE_CMP:
896         if (inst->conditional_mod == BRW_CONDITIONAL_GE &&
897             inst->src[0].abs &&
898             inst->src[0].negate &&
899             inst->src[1].is_zero()) {
900            inst->src[0].abs = false;
901            inst->src[0].negate = false;
902            inst->conditional_mod = BRW_CONDITIONAL_Z;
903            progress = true;
904            break;
905         }
906         break;
907      case SHADER_OPCODE_BROADCAST:
908         if (is_uniform(inst->src[0]) ||
909             inst->src[1].is_zero()) {
910            inst->opcode = BRW_OPCODE_MOV;
911            inst->src[1] = src_reg();
912            inst->force_writemask_all = true;
913            progress = true;
914         }
915         break;
916
917      default:
918	 break;
919      }
920   }
921
922   if (progress)
923      invalidate_live_intervals();
924
925   return progress;
926}
927
928/**
929 * Only a limited number of hardware registers may be used for push
930 * constants, so this turns access to the overflowed constants into
931 * pull constants.
932 */
933void
934vec4_visitor::move_push_constants_to_pull_constants()
935{
936   int pull_constant_loc[this->uniforms];
937
938   /* Only allow 32 registers (256 uniform components) as push constants,
939    * which is the limit on gen6.
940    *
941    * If changing this value, note the limitation about total_regs in
942    * brw_curbe.c.
943    */
944   int max_uniform_components = 32 * 8;
945   if (this->uniforms * 4 <= max_uniform_components)
946      return;
947
948   /* Make some sort of choice as to which uniforms get sent to pull
949    * constants.  We could potentially do something clever here like
950    * look for the most infrequently used uniform vec4s, but leave
951    * that for later.
952    */
953   for (int i = 0; i < this->uniforms * 4; i += 4) {
954      pull_constant_loc[i / 4] = -1;
955
956      if (i >= max_uniform_components) {
957         uint32_t *values = &stage_prog_data->param[i];
958
959         /* Try to find an existing copy of this uniform in the pull
960          * constants if it was part of an array access already.
961          */
962         for (unsigned int j = 0; j < stage_prog_data->nr_pull_params; j += 4) {
963            int matches;
964
965            for (matches = 0; matches < 4; matches++) {
966               if (stage_prog_data->pull_param[j + matches] != values[matches])
967                  break;
968            }
969
970            if (matches == 4) {
971               pull_constant_loc[i / 4] = j / 4;
972               break;
973            }
974         }
975
976         if (pull_constant_loc[i / 4] == -1) {
977            assert(stage_prog_data->nr_pull_params % 4 == 0);
978            pull_constant_loc[i / 4] = stage_prog_data->nr_pull_params / 4;
979
980            for (int j = 0; j < 4; j++) {
981               stage_prog_data->pull_param[stage_prog_data->nr_pull_params++] =
982                  values[j];
983            }
984         }
985      }
986   }
987
988   /* Now actually rewrite usage of the things we've moved to pull
989    * constants.
990    */
991   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
992      for (int i = 0 ; i < 3; i++) {
993         if (inst->src[i].file != UNIFORM ||
994             pull_constant_loc[inst->src[i].nr] == -1)
995            continue;
996
997         int uniform = inst->src[i].nr;
998
999         const glsl_type *temp_type = type_sz(inst->src[i].type) == 8 ?
1000            glsl_type::dvec4_type : glsl_type::vec4_type;
1001         dst_reg temp = dst_reg(this, temp_type);
1002
1003         emit_pull_constant_load(block, inst, temp, inst->src[i],
1004                                 pull_constant_loc[uniform], src_reg());
1005
1006         inst->src[i].file = temp.file;
1007         inst->src[i].nr = temp.nr;
1008         inst->src[i].offset %= 16;
1009         inst->src[i].reladdr = NULL;
1010      }
1011   }
1012
1013   /* Repack push constants to remove the now-unused ones. */
1014   pack_uniform_registers();
1015}
1016
1017/* Conditions for which we want to avoid setting the dependency control bits */
1018bool
1019vec4_visitor::is_dep_ctrl_unsafe(const vec4_instruction *inst)
1020{
1021#define IS_DWORD(reg) \
1022   (reg.type == BRW_REGISTER_TYPE_UD || \
1023    reg.type == BRW_REGISTER_TYPE_D)
1024
1025#define IS_64BIT(reg) (reg.file != BAD_FILE && type_sz(reg.type) == 8)
1026
1027   /* From the Cherryview and Broadwell PRMs:
1028    *
1029    * "When source or destination datatype is 64b or operation is integer DWord
1030    * multiply, DepCtrl must not be used."
1031    *
1032    * SKL PRMs don't include this restriction, however, gen7 seems to be
1033    * affected, at least by the 64b restriction, since DepCtrl with double
1034    * precision instructions seems to produce GPU hangs in some cases.
1035    */
1036   if (devinfo->gen == 8 || gen_device_info_is_9lp(devinfo)) {
1037      if (inst->opcode == BRW_OPCODE_MUL &&
1038         IS_DWORD(inst->src[0]) &&
1039         IS_DWORD(inst->src[1]))
1040         return true;
1041   }
1042
1043   if (devinfo->gen >= 7 && devinfo->gen <= 8) {
1044      if (IS_64BIT(inst->dst) || IS_64BIT(inst->src[0]) ||
1045          IS_64BIT(inst->src[1]) || IS_64BIT(inst->src[2]))
1046      return true;
1047   }
1048
1049#undef IS_64BIT
1050#undef IS_DWORD
1051
1052   if (devinfo->gen >= 8) {
1053      if (inst->opcode == BRW_OPCODE_F32TO16)
1054         return true;
1055   }
1056
1057   /*
1058    * mlen:
1059    * In the presence of send messages, totally interrupt dependency
1060    * control. They're long enough that the chance of dependency
1061    * control around them just doesn't matter.
1062    *
1063    * predicate:
1064    * From the Ivy Bridge PRM, volume 4 part 3.7, page 80:
1065    * When a sequence of NoDDChk and NoDDClr are used, the last instruction that
1066    * completes the scoreboard clear must have a non-zero execution mask. This
1067    * means, if any kind of predication can change the execution mask or channel
1068    * enable of the last instruction, the optimization must be avoided. This is
1069    * to avoid instructions being shot down the pipeline when no writes are
1070    * required.
1071    *
1072    * math:
1073    * Dependency control does not work well over math instructions.
1074    * NB: Discovered empirically
1075    */
1076   return (inst->mlen || inst->predicate || inst->is_math());
1077}
1078
1079/**
1080 * Sets the dependency control fields on instructions after register
1081 * allocation and before the generator is run.
1082 *
1083 * When you have a sequence of instructions like:
1084 *
1085 * DP4 temp.x vertex uniform[0]
1086 * DP4 temp.y vertex uniform[0]
1087 * DP4 temp.z vertex uniform[0]
1088 * DP4 temp.w vertex uniform[0]
1089 *
1090 * The hardware doesn't know that it can actually run the later instructions
1091 * while the previous ones are in flight, producing stalls.  However, we have
1092 * manual fields we can set in the instructions that let it do so.
1093 */
1094void
1095vec4_visitor::opt_set_dependency_control()
1096{
1097   vec4_instruction *last_grf_write[BRW_MAX_GRF];
1098   uint8_t grf_channels_written[BRW_MAX_GRF];
1099   vec4_instruction *last_mrf_write[BRW_MAX_GRF];
1100   uint8_t mrf_channels_written[BRW_MAX_GRF];
1101
1102   assert(prog_data->total_grf ||
1103          !"Must be called after register allocation");
1104
1105   foreach_block (block, cfg) {
1106      memset(last_grf_write, 0, sizeof(last_grf_write));
1107      memset(last_mrf_write, 0, sizeof(last_mrf_write));
1108
1109      foreach_inst_in_block (vec4_instruction, inst, block) {
1110         /* If we read from a register that we were doing dependency control
1111          * on, don't do dependency control across the read.
1112          */
1113         for (int i = 0; i < 3; i++) {
1114            int reg = inst->src[i].nr + inst->src[i].offset / REG_SIZE;
1115            if (inst->src[i].file == VGRF) {
1116               last_grf_write[reg] = NULL;
1117            } else if (inst->src[i].file == FIXED_GRF) {
1118               memset(last_grf_write, 0, sizeof(last_grf_write));
1119               break;
1120            }
1121            assert(inst->src[i].file != MRF);
1122         }
1123
1124         if (is_dep_ctrl_unsafe(inst)) {
1125            memset(last_grf_write, 0, sizeof(last_grf_write));
1126            memset(last_mrf_write, 0, sizeof(last_mrf_write));
1127            continue;
1128         }
1129
1130         /* Now, see if we can do dependency control for this instruction
1131          * against a previous one writing to its destination.
1132          */
1133         int reg = inst->dst.nr + inst->dst.offset / REG_SIZE;
1134         if (inst->dst.file == VGRF || inst->dst.file == FIXED_GRF) {
1135            if (last_grf_write[reg] &&
1136                last_grf_write[reg]->dst.offset == inst->dst.offset &&
1137                !(inst->dst.writemask & grf_channels_written[reg])) {
1138               last_grf_write[reg]->no_dd_clear = true;
1139               inst->no_dd_check = true;
1140            } else {
1141               grf_channels_written[reg] = 0;
1142            }
1143
1144            last_grf_write[reg] = inst;
1145            grf_channels_written[reg] |= inst->dst.writemask;
1146         } else if (inst->dst.file == MRF) {
1147            if (last_mrf_write[reg] &&
1148                last_mrf_write[reg]->dst.offset == inst->dst.offset &&
1149                !(inst->dst.writemask & mrf_channels_written[reg])) {
1150               last_mrf_write[reg]->no_dd_clear = true;
1151               inst->no_dd_check = true;
1152            } else {
1153               mrf_channels_written[reg] = 0;
1154            }
1155
1156            last_mrf_write[reg] = inst;
1157            mrf_channels_written[reg] |= inst->dst.writemask;
1158         }
1159      }
1160   }
1161}
1162
1163bool
1164vec4_instruction::can_reswizzle(const struct gen_device_info *devinfo,
1165                                int dst_writemask,
1166                                int swizzle,
1167                                int swizzle_mask)
1168{
1169   /* Gen6 MATH instructions can not execute in align16 mode, so swizzles
1170    * are not allowed.
1171    */
1172   if (devinfo->gen == 6 && is_math() && swizzle != BRW_SWIZZLE_XYZW)
1173      return false;
1174
1175   /* We can't swizzle implicit accumulator access.  We'd have to
1176    * reswizzle the producer of the accumulator value in addition
1177    * to the consumer (i.e. both MUL and MACH).  Just skip this.
1178    */
1179   if (reads_accumulator_implicitly())
1180      return false;
1181
1182   if (!can_do_writemask(devinfo) && dst_writemask != WRITEMASK_XYZW)
1183      return false;
1184
1185   /* If this instruction sets anything not referenced by swizzle, then we'd
1186    * totally break it when we reswizzle.
1187    */
1188   if (dst.writemask & ~swizzle_mask)
1189      return false;
1190
1191   if (mlen > 0)
1192      return false;
1193
1194   for (int i = 0; i < 3; i++) {
1195      if (src[i].is_accumulator())
1196         return false;
1197   }
1198
1199   return true;
1200}
1201
1202/**
1203 * For any channels in the swizzle's source that were populated by this
1204 * instruction, rewrite the instruction to put the appropriate result directly
1205 * in those channels.
1206 *
1207 * e.g. for swizzle=yywx, MUL a.xy b c -> MUL a.yy_x b.yy z.yy_x
1208 */
1209void
1210vec4_instruction::reswizzle(int dst_writemask, int swizzle)
1211{
1212   /* Destination write mask doesn't correspond to source swizzle for the dot
1213    * product and pack_bytes instructions.
1214    */
1215   if (opcode != BRW_OPCODE_DP4 && opcode != BRW_OPCODE_DPH &&
1216       opcode != BRW_OPCODE_DP3 && opcode != BRW_OPCODE_DP2 &&
1217       opcode != VEC4_OPCODE_PACK_BYTES) {
1218      for (int i = 0; i < 3; i++) {
1219         if (src[i].file == BAD_FILE || src[i].file == IMM)
1220            continue;
1221
1222         src[i].swizzle = brw_compose_swizzle(swizzle, src[i].swizzle);
1223      }
1224   }
1225
1226   /* Apply the specified swizzle and writemask to the original mask of
1227    * written components.
1228    */
1229   dst.writemask = dst_writemask &
1230                   brw_apply_swizzle_to_mask(swizzle, dst.writemask);
1231}
1232
1233/*
1234 * Tries to reduce extra MOV instructions by taking temporary GRFs that get
1235 * just written and then MOVed into another reg and making the original write
1236 * of the GRF write directly to the final destination instead.
1237 */
1238bool
1239vec4_visitor::opt_register_coalesce()
1240{
1241   bool progress = false;
1242   int next_ip = 0;
1243
1244   calculate_live_intervals();
1245
1246   foreach_block_and_inst_safe (block, vec4_instruction, inst, cfg) {
1247      int ip = next_ip;
1248      next_ip++;
1249
1250      if (inst->opcode != BRW_OPCODE_MOV ||
1251          (inst->dst.file != VGRF && inst->dst.file != MRF) ||
1252	  inst->predicate ||
1253	  inst->src[0].file != VGRF ||
1254	  inst->dst.type != inst->src[0].type ||
1255	  inst->src[0].abs || inst->src[0].negate || inst->src[0].reladdr)
1256	 continue;
1257
1258      /* Remove no-op MOVs */
1259      if (inst->dst.file == inst->src[0].file &&
1260          inst->dst.nr == inst->src[0].nr &&
1261          inst->dst.offset == inst->src[0].offset) {
1262         bool is_nop_mov = true;
1263
1264         for (unsigned c = 0; c < 4; c++) {
1265            if ((inst->dst.writemask & (1 << c)) == 0)
1266               continue;
1267
1268            if (BRW_GET_SWZ(inst->src[0].swizzle, c) != c) {
1269               is_nop_mov = false;
1270               break;
1271            }
1272         }
1273
1274         if (is_nop_mov) {
1275            inst->remove(block);
1276            progress = true;
1277            continue;
1278         }
1279      }
1280
1281      bool to_mrf = (inst->dst.file == MRF);
1282
1283      /* Can't coalesce this GRF if someone else was going to
1284       * read it later.
1285       */
1286      if (var_range_end(var_from_reg(alloc, dst_reg(inst->src[0])), 8) > ip)
1287	 continue;
1288
1289      /* We need to check interference with the final destination between this
1290       * instruction and the earliest instruction involved in writing the GRF
1291       * we're eliminating.  To do that, keep track of which of our source
1292       * channels we've seen initialized.
1293       */
1294      const unsigned chans_needed =
1295         brw_apply_inv_swizzle_to_mask(inst->src[0].swizzle,
1296                                       inst->dst.writemask);
1297      unsigned chans_remaining = chans_needed;
1298
1299      /* Now walk up the instruction stream trying to see if we can rewrite
1300       * everything writing to the temporary to write into the destination
1301       * instead.
1302       */
1303      vec4_instruction *_scan_inst = (vec4_instruction *)inst->prev;
1304      foreach_inst_in_block_reverse_starting_from(vec4_instruction, scan_inst,
1305                                                  inst) {
1306         _scan_inst = scan_inst;
1307
1308         if (regions_overlap(inst->src[0], inst->size_read(0),
1309                             scan_inst->dst, scan_inst->size_written)) {
1310            /* Found something writing to the reg we want to coalesce away. */
1311            if (to_mrf) {
1312               /* SEND instructions can't have MRF as a destination. */
1313               if (scan_inst->mlen)
1314                  break;
1315
1316               if (devinfo->gen == 6) {
1317                  /* gen6 math instructions must have the destination be
1318                   * VGRF, so no compute-to-MRF for them.
1319                   */
1320                  if (scan_inst->is_math()) {
1321                     break;
1322                  }
1323               }
1324            }
1325
1326            /* VS_OPCODE_UNPACK_FLAGS_SIMD4X2 generates a bunch of mov(1)
1327             * instructions, and this optimization pass is not capable of
1328             * handling that.  Bail on these instructions and hope that some
1329             * later optimization pass can do the right thing after they are
1330             * expanded.
1331             */
1332            if (scan_inst->opcode == VS_OPCODE_UNPACK_FLAGS_SIMD4X2)
1333               break;
1334
1335            /* This doesn't handle saturation on the instruction we
1336             * want to coalesce away if the register types do not match.
1337             * But if scan_inst is a non type-converting 'mov', we can fix
1338             * the types later.
1339             */
1340            if (inst->saturate &&
1341                inst->dst.type != scan_inst->dst.type &&
1342                !(scan_inst->opcode == BRW_OPCODE_MOV &&
1343                  scan_inst->dst.type == scan_inst->src[0].type))
1344               break;
1345
1346            /* Only allow coalescing between registers of the same type size.
1347             * Otherwise we would need to make the pass aware of the fact that
1348             * channel sizes are different for single and double precision.
1349             */
1350            if (type_sz(inst->src[0].type) != type_sz(scan_inst->src[0].type))
1351               break;
1352
1353            /* Check that scan_inst writes the same amount of data as the
1354             * instruction, otherwise coalescing would lead to writing a
1355             * different (larger or smaller) region of the destination
1356             */
1357            if (scan_inst->size_written != inst->size_written)
1358               break;
1359
1360            /* If we can't handle the swizzle, bail. */
1361            if (!scan_inst->can_reswizzle(devinfo, inst->dst.writemask,
1362                                          inst->src[0].swizzle,
1363                                          chans_needed)) {
1364               break;
1365            }
1366
1367            /* This only handles coalescing writes of 8 channels (1 register
1368             * for single-precision and 2 registers for double-precision)
1369             * starting at the source offset of the copy instruction.
1370             */
1371            if (DIV_ROUND_UP(scan_inst->size_written,
1372                             type_sz(scan_inst->dst.type)) > 8 ||
1373                scan_inst->dst.offset != inst->src[0].offset)
1374               break;
1375
1376	    /* Mark which channels we found unconditional writes for. */
1377	    if (!scan_inst->predicate)
1378               chans_remaining &= ~scan_inst->dst.writemask;
1379
1380	    if (chans_remaining == 0)
1381	       break;
1382	 }
1383
1384         /* You can't read from an MRF, so if someone else reads our MRF's
1385          * source GRF that we wanted to rewrite, that stops us.  If it's a
1386          * GRF we're trying to coalesce to, we don't actually handle
1387          * rewriting sources so bail in that case as well.
1388          */
1389	 bool interfered = false;
1390	 for (int i = 0; i < 3; i++) {
1391            if (regions_overlap(inst->src[0], inst->size_read(0),
1392                                scan_inst->src[i], scan_inst->size_read(i)))
1393	       interfered = true;
1394	 }
1395	 if (interfered)
1396	    break;
1397
1398         /* If somebody else writes the same channels of our destination here,
1399          * we can't coalesce before that.
1400          */
1401         if (regions_overlap(inst->dst, inst->size_written,
1402                             scan_inst->dst, scan_inst->size_written) &&
1403             (inst->dst.writemask & scan_inst->dst.writemask) != 0) {
1404            break;
1405         }
1406
1407         /* Check for reads of the register we're trying to coalesce into.  We
1408          * can't go rewriting instructions above that to put some other value
1409          * in the register instead.
1410          */
1411         if (to_mrf && scan_inst->mlen > 0) {
1412            if (inst->dst.nr >= scan_inst->base_mrf &&
1413                inst->dst.nr < scan_inst->base_mrf + scan_inst->mlen) {
1414               break;
1415            }
1416         } else {
1417            for (int i = 0; i < 3; i++) {
1418               if (regions_overlap(inst->dst, inst->size_written,
1419                                   scan_inst->src[i], scan_inst->size_read(i)))
1420                  interfered = true;
1421            }
1422            if (interfered)
1423               break;
1424         }
1425      }
1426
1427      if (chans_remaining == 0) {
1428	 /* If we've made it here, we have an MOV we want to coalesce out, and
1429	  * a scan_inst pointing to the earliest instruction involved in
1430	  * computing the value.  Now go rewrite the instruction stream
1431	  * between the two.
1432	  */
1433         vec4_instruction *scan_inst = _scan_inst;
1434	 while (scan_inst != inst) {
1435	    if (scan_inst->dst.file == VGRF &&
1436                scan_inst->dst.nr == inst->src[0].nr &&
1437		scan_inst->dst.offset == inst->src[0].offset) {
1438               scan_inst->reswizzle(inst->dst.writemask,
1439                                    inst->src[0].swizzle);
1440	       scan_inst->dst.file = inst->dst.file;
1441               scan_inst->dst.nr = inst->dst.nr;
1442	       scan_inst->dst.offset = inst->dst.offset;
1443               if (inst->saturate &&
1444                   inst->dst.type != scan_inst->dst.type) {
1445                  /* If we have reached this point, scan_inst is a non
1446                   * type-converting 'mov' and we can modify its register types
1447                   * to match the ones in inst. Otherwise, we could have an
1448                   * incorrect saturation result.
1449                   */
1450                  scan_inst->dst.type = inst->dst.type;
1451                  scan_inst->src[0].type = inst->src[0].type;
1452               }
1453	       scan_inst->saturate |= inst->saturate;
1454	    }
1455	    scan_inst = (vec4_instruction *)scan_inst->next;
1456	 }
1457	 inst->remove(block);
1458	 progress = true;
1459      }
1460   }
1461
1462   if (progress)
1463      invalidate_live_intervals();
1464
1465   return progress;
1466}
1467
1468/**
1469 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
1470 * flow.  We could probably do better here with some form of divergence
1471 * analysis.
1472 */
1473bool
1474vec4_visitor::eliminate_find_live_channel()
1475{
1476   bool progress = false;
1477   unsigned depth = 0;
1478
1479   if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
1480      /* The optimization below assumes that channel zero is live on thread
1481       * dispatch, which may not be the case if the fixed function dispatches
1482       * threads sparsely.
1483       */
1484      return false;
1485   }
1486
1487   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
1488      switch (inst->opcode) {
1489      case BRW_OPCODE_IF:
1490      case BRW_OPCODE_DO:
1491         depth++;
1492         break;
1493
1494      case BRW_OPCODE_ENDIF:
1495      case BRW_OPCODE_WHILE:
1496         depth--;
1497         break;
1498
1499      case SHADER_OPCODE_FIND_LIVE_CHANNEL:
1500         if (depth == 0) {
1501            inst->opcode = BRW_OPCODE_MOV;
1502            inst->src[0] = brw_imm_d(0);
1503            inst->force_writemask_all = true;
1504            progress = true;
1505         }
1506         break;
1507
1508      default:
1509         break;
1510      }
1511   }
1512
1513   return progress;
1514}
1515
1516/**
1517 * Splits virtual GRFs requesting more than one contiguous physical register.
1518 *
1519 * We initially create large virtual GRFs for temporary structures, arrays,
1520 * and matrices, so that the visitor functions can add offsets to work their
1521 * way down to the actual member being accessed.  But when it comes to
1522 * optimization, we'd like to treat each register as individual storage if
1523 * possible.
1524 *
1525 * So far, the only thing that might prevent splitting is a send message from
1526 * a GRF on IVB.
1527 */
1528void
1529vec4_visitor::split_virtual_grfs()
1530{
1531   int num_vars = this->alloc.count;
1532   int new_virtual_grf[num_vars];
1533   bool split_grf[num_vars];
1534
1535   memset(new_virtual_grf, 0, sizeof(new_virtual_grf));
1536
1537   /* Try to split anything > 0 sized. */
1538   for (int i = 0; i < num_vars; i++) {
1539      split_grf[i] = this->alloc.sizes[i] != 1;
1540   }
1541
1542   /* Check that the instructions are compatible with the registers we're trying
1543    * to split.
1544    */
1545   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1546      if (inst->dst.file == VGRF && regs_written(inst) > 1)
1547         split_grf[inst->dst.nr] = false;
1548
1549      for (int i = 0; i < 3; i++) {
1550         if (inst->src[i].file == VGRF && regs_read(inst, i) > 1)
1551            split_grf[inst->src[i].nr] = false;
1552      }
1553   }
1554
1555   /* Allocate new space for split regs.  Note that the virtual
1556    * numbers will be contiguous.
1557    */
1558   for (int i = 0; i < num_vars; i++) {
1559      if (!split_grf[i])
1560         continue;
1561
1562      new_virtual_grf[i] = alloc.allocate(1);
1563      for (unsigned j = 2; j < this->alloc.sizes[i]; j++) {
1564         unsigned reg = alloc.allocate(1);
1565         assert(reg == new_virtual_grf[i] + j - 1);
1566         (void) reg;
1567      }
1568      this->alloc.sizes[i] = 1;
1569   }
1570
1571   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1572      if (inst->dst.file == VGRF && split_grf[inst->dst.nr] &&
1573          inst->dst.offset / REG_SIZE != 0) {
1574         inst->dst.nr = (new_virtual_grf[inst->dst.nr] +
1575                         inst->dst.offset / REG_SIZE - 1);
1576         inst->dst.offset %= REG_SIZE;
1577      }
1578      for (int i = 0; i < 3; i++) {
1579         if (inst->src[i].file == VGRF && split_grf[inst->src[i].nr] &&
1580             inst->src[i].offset / REG_SIZE != 0) {
1581            inst->src[i].nr = (new_virtual_grf[inst->src[i].nr] +
1582                                inst->src[i].offset / REG_SIZE - 1);
1583            inst->src[i].offset %= REG_SIZE;
1584         }
1585      }
1586   }
1587   invalidate_live_intervals();
1588}
1589
1590void
1591vec4_visitor::dump_instruction(backend_instruction *be_inst)
1592{
1593   dump_instruction(be_inst, stderr);
1594}
1595
1596void
1597vec4_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
1598{
1599   vec4_instruction *inst = (vec4_instruction *)be_inst;
1600
1601   if (inst->predicate) {
1602      fprintf(file, "(%cf%d.%d%s) ",
1603              inst->predicate_inverse ? '-' : '+',
1604              inst->flag_subreg / 2,
1605              inst->flag_subreg % 2,
1606              pred_ctrl_align16[inst->predicate]);
1607   }
1608
1609   fprintf(file, "%s(%d)", brw_instruction_name(devinfo, inst->opcode),
1610           inst->exec_size);
1611   if (inst->saturate)
1612      fprintf(file, ".sat");
1613   if (inst->conditional_mod) {
1614      fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
1615      if (!inst->predicate &&
1616          (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
1617                                inst->opcode != BRW_OPCODE_CSEL &&
1618                                inst->opcode != BRW_OPCODE_IF &&
1619                                inst->opcode != BRW_OPCODE_WHILE))) {
1620         fprintf(file, ".f%d.%d", inst->flag_subreg / 2, inst->flag_subreg % 2);
1621      }
1622   }
1623   fprintf(file, " ");
1624
1625   switch (inst->dst.file) {
1626   case VGRF:
1627      fprintf(file, "vgrf%d", inst->dst.nr);
1628      break;
1629   case FIXED_GRF:
1630      fprintf(file, "g%d", inst->dst.nr);
1631      break;
1632   case MRF:
1633      fprintf(file, "m%d", inst->dst.nr);
1634      break;
1635   case ARF:
1636      switch (inst->dst.nr) {
1637      case BRW_ARF_NULL:
1638         fprintf(file, "null");
1639         break;
1640      case BRW_ARF_ADDRESS:
1641         fprintf(file, "a0.%d", inst->dst.subnr);
1642         break;
1643      case BRW_ARF_ACCUMULATOR:
1644         fprintf(file, "acc%d", inst->dst.subnr);
1645         break;
1646      case BRW_ARF_FLAG:
1647         fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
1648         break;
1649      default:
1650         fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
1651         break;
1652      }
1653      break;
1654   case BAD_FILE:
1655      fprintf(file, "(null)");
1656      break;
1657   case IMM:
1658   case ATTR:
1659   case UNIFORM:
1660      unreachable("not reached");
1661   }
1662   if (inst->dst.offset ||
1663       (inst->dst.file == VGRF &&
1664        alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
1665      const unsigned reg_size = (inst->dst.file == UNIFORM ? 16 : REG_SIZE);
1666      fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
1667              inst->dst.offset % reg_size);
1668   }
1669   if (inst->dst.writemask != WRITEMASK_XYZW) {
1670      fprintf(file, ".");
1671      if (inst->dst.writemask & 1)
1672         fprintf(file, "x");
1673      if (inst->dst.writemask & 2)
1674         fprintf(file, "y");
1675      if (inst->dst.writemask & 4)
1676         fprintf(file, "z");
1677      if (inst->dst.writemask & 8)
1678         fprintf(file, "w");
1679   }
1680   fprintf(file, ":%s", brw_reg_type_to_letters(inst->dst.type));
1681
1682   if (inst->src[0].file != BAD_FILE)
1683      fprintf(file, ", ");
1684
1685   for (int i = 0; i < 3 && inst->src[i].file != BAD_FILE; i++) {
1686      if (inst->src[i].negate)
1687         fprintf(file, "-");
1688      if (inst->src[i].abs)
1689         fprintf(file, "|");
1690      switch (inst->src[i].file) {
1691      case VGRF:
1692         fprintf(file, "vgrf%d", inst->src[i].nr);
1693         break;
1694      case FIXED_GRF:
1695         fprintf(file, "g%d.%d", inst->src[i].nr, inst->src[i].subnr);
1696         break;
1697      case ATTR:
1698         fprintf(file, "attr%d", inst->src[i].nr);
1699         break;
1700      case UNIFORM:
1701         fprintf(file, "u%d", inst->src[i].nr);
1702         break;
1703      case IMM:
1704         switch (inst->src[i].type) {
1705         case BRW_REGISTER_TYPE_F:
1706            fprintf(file, "%fF", inst->src[i].f);
1707            break;
1708         case BRW_REGISTER_TYPE_DF:
1709            fprintf(file, "%fDF", inst->src[i].df);
1710            break;
1711         case BRW_REGISTER_TYPE_D:
1712            fprintf(file, "%dD", inst->src[i].d);
1713            break;
1714         case BRW_REGISTER_TYPE_UD:
1715            fprintf(file, "%uU", inst->src[i].ud);
1716            break;
1717         case BRW_REGISTER_TYPE_VF:
1718            fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
1719                    brw_vf_to_float((inst->src[i].ud >>  0) & 0xff),
1720                    brw_vf_to_float((inst->src[i].ud >>  8) & 0xff),
1721                    brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
1722                    brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
1723            break;
1724         default:
1725            fprintf(file, "???");
1726            break;
1727         }
1728         break;
1729      case ARF:
1730         switch (inst->src[i].nr) {
1731         case BRW_ARF_NULL:
1732            fprintf(file, "null");
1733            break;
1734         case BRW_ARF_ADDRESS:
1735            fprintf(file, "a0.%d", inst->src[i].subnr);
1736            break;
1737         case BRW_ARF_ACCUMULATOR:
1738            fprintf(file, "acc%d", inst->src[i].subnr);
1739            break;
1740         case BRW_ARF_FLAG:
1741            fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
1742            break;
1743         default:
1744            fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
1745            break;
1746         }
1747         break;
1748      case BAD_FILE:
1749         fprintf(file, "(null)");
1750         break;
1751      case MRF:
1752         unreachable("not reached");
1753      }
1754
1755      if (inst->src[i].offset ||
1756          (inst->src[i].file == VGRF &&
1757           alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
1758         const unsigned reg_size = (inst->src[i].file == UNIFORM ? 16 : REG_SIZE);
1759         fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
1760                 inst->src[i].offset % reg_size);
1761      }
1762
1763      if (inst->src[i].file != IMM) {
1764         static const char *chans[4] = {"x", "y", "z", "w"};
1765         fprintf(file, ".");
1766         for (int c = 0; c < 4; c++) {
1767            fprintf(file, "%s", chans[BRW_GET_SWZ(inst->src[i].swizzle, c)]);
1768         }
1769      }
1770
1771      if (inst->src[i].abs)
1772         fprintf(file, "|");
1773
1774      if (inst->src[i].file != IMM) {
1775         fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
1776      }
1777
1778      if (i < 2 && inst->src[i + 1].file != BAD_FILE)
1779         fprintf(file, ", ");
1780   }
1781
1782   if (inst->force_writemask_all)
1783      fprintf(file, " NoMask");
1784
1785   if (inst->exec_size != 8)
1786      fprintf(file, " group%d", inst->group);
1787
1788   fprintf(file, "\n");
1789}
1790
1791
1792int
1793vec4_vs_visitor::setup_attributes(int payload_reg)
1794{
1795   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1796      for (int i = 0; i < 3; i++) {
1797         if (inst->src[i].file == ATTR) {
1798            assert(inst->src[i].offset % REG_SIZE == 0);
1799            int grf = payload_reg + inst->src[i].nr +
1800                      inst->src[i].offset / REG_SIZE;
1801
1802            struct brw_reg reg = brw_vec8_grf(grf, 0);
1803            reg.swizzle = inst->src[i].swizzle;
1804            reg.type = inst->src[i].type;
1805            reg.abs = inst->src[i].abs;
1806            reg.negate = inst->src[i].negate;
1807            inst->src[i] = reg;
1808         }
1809      }
1810   }
1811
1812   return payload_reg + vs_prog_data->nr_attribute_slots;
1813}
1814
1815int
1816vec4_visitor::setup_uniforms(int reg)
1817{
1818   prog_data->base.dispatch_grf_start_reg = reg;
1819
1820   /* The pre-gen6 VS requires that some push constants get loaded no
1821    * matter what, or the GPU would hang.
1822    */
1823   if (devinfo->gen < 6 && this->uniforms == 0) {
1824      brw_stage_prog_data_add_params(stage_prog_data, 4);
1825      for (unsigned int i = 0; i < 4; i++) {
1826	 unsigned int slot = this->uniforms * 4 + i;
1827	 stage_prog_data->param[slot] = BRW_PARAM_BUILTIN_ZERO;
1828      }
1829
1830      this->uniforms++;
1831      reg++;
1832   } else {
1833      reg += ALIGN(uniforms, 2) / 2;
1834   }
1835
1836   for (int i = 0; i < 4; i++)
1837      reg += stage_prog_data->ubo_ranges[i].length;
1838
1839   stage_prog_data->nr_params = this->uniforms * 4;
1840
1841   prog_data->base.curb_read_length =
1842      reg - prog_data->base.dispatch_grf_start_reg;
1843
1844   return reg;
1845}
1846
1847void
1848vec4_vs_visitor::setup_payload(void)
1849{
1850   int reg = 0;
1851
1852   /* The payload always contains important data in g0, which contains
1853    * the URB handles that are passed on to the URB write at the end
1854    * of the thread.  So, we always start push constants at g1.
1855    */
1856   reg++;
1857
1858   reg = setup_uniforms(reg);
1859
1860   reg = setup_attributes(reg);
1861
1862   this->first_non_payload_grf = reg;
1863}
1864
1865bool
1866vec4_visitor::lower_minmax()
1867{
1868   assert(devinfo->gen < 6);
1869
1870   bool progress = false;
1871
1872   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
1873      const vec4_builder ibld(this, block, inst);
1874
1875      if (inst->opcode == BRW_OPCODE_SEL &&
1876          inst->predicate == BRW_PREDICATE_NONE) {
1877         /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
1878          *        the original SEL.L/GE instruction
1879          */
1880         ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
1881                  inst->conditional_mod);
1882         inst->predicate = BRW_PREDICATE_NORMAL;
1883         inst->conditional_mod = BRW_CONDITIONAL_NONE;
1884
1885         progress = true;
1886      }
1887   }
1888
1889   if (progress)
1890      invalidate_live_intervals();
1891
1892   return progress;
1893}
1894
1895src_reg
1896vec4_visitor::get_timestamp()
1897{
1898   assert(devinfo->gen >= 7);
1899
1900   src_reg ts = src_reg(brw_reg(BRW_ARCHITECTURE_REGISTER_FILE,
1901                                BRW_ARF_TIMESTAMP,
1902                                0,
1903                                0,
1904                                0,
1905                                BRW_REGISTER_TYPE_UD,
1906                                BRW_VERTICAL_STRIDE_0,
1907                                BRW_WIDTH_4,
1908                                BRW_HORIZONTAL_STRIDE_4,
1909                                BRW_SWIZZLE_XYZW,
1910                                WRITEMASK_XYZW));
1911
1912   dst_reg dst = dst_reg(this, glsl_type::uvec4_type);
1913
1914   vec4_instruction *mov = emit(MOV(dst, ts));
1915   /* We want to read the 3 fields we care about (mostly field 0, but also 2)
1916    * even if it's not enabled in the dispatch.
1917    */
1918   mov->force_writemask_all = true;
1919
1920   return src_reg(dst);
1921}
1922
1923void
1924vec4_visitor::emit_shader_time_begin()
1925{
1926   current_annotation = "shader time start";
1927   shader_start_time = get_timestamp();
1928}
1929
1930void
1931vec4_visitor::emit_shader_time_end()
1932{
1933   current_annotation = "shader time end";
1934   src_reg shader_end_time = get_timestamp();
1935
1936
1937   /* Check that there weren't any timestamp reset events (assuming these
1938    * were the only two timestamp reads that happened).
1939    */
1940   src_reg reset_end = shader_end_time;
1941   reset_end.swizzle = BRW_SWIZZLE_ZZZZ;
1942   vec4_instruction *test = emit(AND(dst_null_ud(), reset_end, brw_imm_ud(1u)));
1943   test->conditional_mod = BRW_CONDITIONAL_Z;
1944
1945   emit(IF(BRW_PREDICATE_NORMAL));
1946
1947   /* Take the current timestamp and get the delta. */
1948   shader_start_time.negate = true;
1949   dst_reg diff = dst_reg(this, glsl_type::uint_type);
1950   emit(ADD(diff, shader_start_time, shader_end_time));
1951
1952   /* If there were no instructions between the two timestamp gets, the diff
1953    * is 2 cycles.  Remove that overhead, so I can forget about that when
1954    * trying to determine the time taken for single instructions.
1955    */
1956   emit(ADD(diff, src_reg(diff), brw_imm_ud(-2u)));
1957
1958   emit_shader_time_write(0, src_reg(diff));
1959   emit_shader_time_write(1, brw_imm_ud(1u));
1960   emit(BRW_OPCODE_ELSE);
1961   emit_shader_time_write(2, brw_imm_ud(1u));
1962   emit(BRW_OPCODE_ENDIF);
1963}
1964
1965void
1966vec4_visitor::emit_shader_time_write(int shader_time_subindex, src_reg value)
1967{
1968   dst_reg dst =
1969      dst_reg(this, glsl_type::get_array_instance(glsl_type::vec4_type, 2));
1970
1971   dst_reg offset = dst;
1972   dst_reg time = dst;
1973   time.offset += REG_SIZE;
1974
1975   offset.type = BRW_REGISTER_TYPE_UD;
1976   int index = shader_time_index * 3 + shader_time_subindex;
1977   emit(MOV(offset, brw_imm_d(index * BRW_SHADER_TIME_STRIDE)));
1978
1979   time.type = BRW_REGISTER_TYPE_UD;
1980   emit(MOV(time, value));
1981
1982   vec4_instruction *inst =
1983      emit(SHADER_OPCODE_SHADER_TIME_ADD, dst_reg(), src_reg(dst));
1984   inst->mlen = 2;
1985}
1986
1987static bool
1988is_align1_df(vec4_instruction *inst)
1989{
1990   switch (inst->opcode) {
1991   case VEC4_OPCODE_DOUBLE_TO_F32:
1992   case VEC4_OPCODE_DOUBLE_TO_D32:
1993   case VEC4_OPCODE_DOUBLE_TO_U32:
1994   case VEC4_OPCODE_TO_DOUBLE:
1995   case VEC4_OPCODE_PICK_LOW_32BIT:
1996   case VEC4_OPCODE_PICK_HIGH_32BIT:
1997   case VEC4_OPCODE_SET_LOW_32BIT:
1998   case VEC4_OPCODE_SET_HIGH_32BIT:
1999      return true;
2000   default:
2001      return false;
2002   }
2003}
2004
2005/**
2006 * Three source instruction must have a GRF/MRF destination register.
2007 * ARF NULL is not allowed.  Fix that up by allocating a temporary GRF.
2008 */
2009void
2010vec4_visitor::fixup_3src_null_dest()
2011{
2012   bool progress = false;
2013
2014   foreach_block_and_inst_safe (block, vec4_instruction, inst, cfg) {
2015      if (inst->is_3src(devinfo) && inst->dst.is_null()) {
2016         const unsigned size_written = type_sz(inst->dst.type);
2017         const unsigned num_regs = DIV_ROUND_UP(size_written, REG_SIZE);
2018
2019         inst->dst = retype(dst_reg(VGRF, alloc.allocate(num_regs)),
2020                            inst->dst.type);
2021         progress = true;
2022      }
2023   }
2024
2025   if (progress)
2026      invalidate_live_intervals();
2027}
2028
2029void
2030vec4_visitor::convert_to_hw_regs()
2031{
2032   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
2033      for (int i = 0; i < 3; i++) {
2034         class src_reg &src = inst->src[i];
2035         struct brw_reg reg;
2036         switch (src.file) {
2037         case VGRF: {
2038            reg = byte_offset(brw_vecn_grf(4, src.nr, 0), src.offset);
2039            reg.type = src.type;
2040            reg.abs = src.abs;
2041            reg.negate = src.negate;
2042            break;
2043         }
2044
2045         case UNIFORM: {
2046            reg = stride(byte_offset(brw_vec4_grf(
2047                                        prog_data->base.dispatch_grf_start_reg +
2048                                        src.nr / 2, src.nr % 2 * 4),
2049                                     src.offset),
2050                         0, 4, 1);
2051            reg.type = src.type;
2052            reg.abs = src.abs;
2053            reg.negate = src.negate;
2054
2055            /* This should have been moved to pull constants. */
2056            assert(!src.reladdr);
2057            break;
2058         }
2059
2060         case FIXED_GRF:
2061            if (type_sz(src.type) == 8) {
2062               reg = src.as_brw_reg();
2063               break;
2064            }
2065            /* fallthrough */
2066         case ARF:
2067         case IMM:
2068            continue;
2069
2070         case BAD_FILE:
2071            /* Probably unused. */
2072            reg = brw_null_reg();
2073            reg = retype(reg, src.type);
2074            break;
2075
2076         case MRF:
2077         case ATTR:
2078            unreachable("not reached");
2079         }
2080
2081         apply_logical_swizzle(&reg, inst, i);
2082         src = reg;
2083
2084         /* From IVB PRM, vol4, part3, "General Restrictions on Regioning
2085          * Parameters":
2086          *
2087          *   "If ExecSize = Width and HorzStride ≠ 0, VertStride must be set
2088          *    to Width * HorzStride."
2089          *
2090          * We can break this rule with DF sources on DF align1
2091          * instructions, because the exec_size would be 4 and width is 4.
2092          * As we know we are not accessing to next GRF, it is safe to
2093          * set vstride to the formula given by the rule itself.
2094          */
2095         if (is_align1_df(inst) && (cvt(inst->exec_size) - 1) == src.width)
2096            src.vstride = src.width + src.hstride;
2097      }
2098
2099      if (inst->is_3src(devinfo)) {
2100         /* 3-src instructions with scalar sources support arbitrary subnr,
2101          * but don't actually use swizzles.  Convert swizzle into subnr.
2102          * Skip this for double-precision instructions: RepCtrl=1 is not
2103          * allowed for them and needs special handling.
2104          */
2105         for (int i = 0; i < 3; i++) {
2106            if (inst->src[i].vstride == BRW_VERTICAL_STRIDE_0 &&
2107                type_sz(inst->src[i].type) < 8) {
2108               assert(brw_is_single_value_swizzle(inst->src[i].swizzle));
2109               inst->src[i].subnr += 4 * BRW_GET_SWZ(inst->src[i].swizzle, 0);
2110            }
2111         }
2112      }
2113
2114      dst_reg &dst = inst->dst;
2115      struct brw_reg reg;
2116
2117      switch (inst->dst.file) {
2118      case VGRF:
2119         reg = byte_offset(brw_vec8_grf(dst.nr, 0), dst.offset);
2120         reg.type = dst.type;
2121         reg.writemask = dst.writemask;
2122         break;
2123
2124      case MRF:
2125         reg = byte_offset(brw_message_reg(dst.nr), dst.offset);
2126         assert((reg.nr & ~BRW_MRF_COMPR4) < BRW_MAX_MRF(devinfo->gen));
2127         reg.type = dst.type;
2128         reg.writemask = dst.writemask;
2129         break;
2130
2131      case ARF:
2132      case FIXED_GRF:
2133         reg = dst.as_brw_reg();
2134         break;
2135
2136      case BAD_FILE:
2137         reg = brw_null_reg();
2138         reg = retype(reg, dst.type);
2139         break;
2140
2141      case IMM:
2142      case ATTR:
2143      case UNIFORM:
2144         unreachable("not reached");
2145      }
2146
2147      dst = reg;
2148   }
2149}
2150
2151static bool
2152stage_uses_interleaved_attributes(unsigned stage,
2153                                  enum shader_dispatch_mode dispatch_mode)
2154{
2155   switch (stage) {
2156   case MESA_SHADER_TESS_EVAL:
2157      return true;
2158   case MESA_SHADER_GEOMETRY:
2159      return dispatch_mode != DISPATCH_MODE_4X2_DUAL_OBJECT;
2160   default:
2161      return false;
2162   }
2163}
2164
2165/**
2166 * Get the closest native SIMD width supported by the hardware for instruction
2167 * \p inst.  The instruction will be left untouched by
2168 * vec4_visitor::lower_simd_width() if the returned value matches the
2169 * instruction's original execution size.
2170 */
2171static unsigned
2172get_lowered_simd_width(const struct gen_device_info *devinfo,
2173                       enum shader_dispatch_mode dispatch_mode,
2174                       unsigned stage, const vec4_instruction *inst)
2175{
2176   /* Do not split some instructions that require special handling */
2177   switch (inst->opcode) {
2178   case SHADER_OPCODE_GEN4_SCRATCH_READ:
2179   case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
2180      return inst->exec_size;
2181   default:
2182      break;
2183   }
2184
2185   unsigned lowered_width = MIN2(16, inst->exec_size);
2186
2187   /* We need to split some cases of double-precision instructions that write
2188    * 2 registers. We only need to care about this in gen7 because that is the
2189    * only hardware that implements fp64 in Align16.
2190    */
2191   if (devinfo->gen == 7 && inst->size_written > REG_SIZE) {
2192      /* Align16 8-wide double-precision SEL does not work well. Verified
2193       * empirically.
2194       */
2195      if (inst->opcode == BRW_OPCODE_SEL && type_sz(inst->dst.type) == 8)
2196         lowered_width = MIN2(lowered_width, 4);
2197
2198      /* HSW PRM, 3D Media GPGPU Engine, Region Alignment Rules for Direct
2199       * Register Addressing:
2200       *
2201       *    "When destination spans two registers, the source MUST span two
2202       *     registers."
2203       */
2204      for (unsigned i = 0; i < 3; i++) {
2205         if (inst->src[i].file == BAD_FILE)
2206            continue;
2207         if (inst->size_read(i) <= REG_SIZE)
2208            lowered_width = MIN2(lowered_width, 4);
2209
2210         /* Interleaved attribute setups use a vertical stride of 0, which
2211          * makes them hit the associated instruction decompression bug in gen7.
2212          * Split them to prevent this.
2213          */
2214         if (inst->src[i].file == ATTR &&
2215             stage_uses_interleaved_attributes(stage, dispatch_mode))
2216            lowered_width = MIN2(lowered_width, 4);
2217      }
2218   }
2219
2220   /* IvyBridge can manage a maximum of 4 DFs per SIMD4x2 instruction, since
2221    * it doesn't support compression in Align16 mode, no matter if it has
2222    * force_writemask_all enabled or disabled (the latter is affected by the
2223    * compressed instruction bug in gen7, which is another reason to enforce
2224    * this limit).
2225    */
2226   if (devinfo->gen == 7 && !devinfo->is_haswell &&
2227       (get_exec_type_size(inst) == 8 || type_sz(inst->dst.type) == 8))
2228      lowered_width = MIN2(lowered_width, 4);
2229
2230   return lowered_width;
2231}
2232
2233static bool
2234dst_src_regions_overlap(vec4_instruction *inst)
2235{
2236   if (inst->size_written == 0)
2237      return false;
2238
2239   unsigned dst_start = inst->dst.offset;
2240   unsigned dst_end = dst_start + inst->size_written - 1;
2241   for (int i = 0; i < 3; i++) {
2242      if (inst->src[i].file == BAD_FILE)
2243         continue;
2244
2245      if (inst->dst.file != inst->src[i].file ||
2246          inst->dst.nr != inst->src[i].nr)
2247         continue;
2248
2249      unsigned src_start = inst->src[i].offset;
2250      unsigned src_end = src_start + inst->size_read(i) - 1;
2251
2252      if ((dst_start >= src_start && dst_start <= src_end) ||
2253          (dst_end >= src_start && dst_end <= src_end) ||
2254          (dst_start <= src_start && dst_end >= src_end)) {
2255         return true;
2256      }
2257   }
2258
2259   return false;
2260}
2261
2262bool
2263vec4_visitor::lower_simd_width()
2264{
2265   bool progress = false;
2266
2267   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2268      const unsigned lowered_width =
2269         get_lowered_simd_width(devinfo, prog_data->dispatch_mode, stage, inst);
2270      assert(lowered_width <= inst->exec_size);
2271      if (lowered_width == inst->exec_size)
2272         continue;
2273
2274      /* We need to deal with source / destination overlaps when splitting.
2275       * The hardware supports reading from and writing to the same register
2276       * in the same instruction, but we need to be careful that each split
2277       * instruction we produce does not corrupt the source of the next.
2278       *
2279       * The easiest way to handle this is to make the split instructions write
2280       * to temporaries if there is an src/dst overlap and then move from the
2281       * temporaries to the original destination. We also need to consider
2282       * instructions that do partial writes via align1 opcodes, in which case
2283       * we need to make sure that the we initialize the temporary with the
2284       * value of the instruction's dst.
2285       */
2286      bool needs_temp = dst_src_regions_overlap(inst);
2287      for (unsigned n = 0; n < inst->exec_size / lowered_width; n++)  {
2288         unsigned channel_offset = lowered_width * n;
2289
2290         unsigned size_written = lowered_width * type_sz(inst->dst.type);
2291
2292         /* Create the split instruction from the original so that we copy all
2293          * relevant instruction fields, then set the width and calculate the
2294          * new dst/src regions.
2295          */
2296         vec4_instruction *linst = new(mem_ctx) vec4_instruction(*inst);
2297         linst->exec_size = lowered_width;
2298         linst->group = channel_offset;
2299         linst->size_written = size_written;
2300
2301         /* Compute split dst region */
2302         dst_reg dst;
2303         if (needs_temp) {
2304            unsigned num_regs = DIV_ROUND_UP(size_written, REG_SIZE);
2305            dst = retype(dst_reg(VGRF, alloc.allocate(num_regs)),
2306                         inst->dst.type);
2307            if (inst->is_align1_partial_write()) {
2308               vec4_instruction *copy = MOV(dst, src_reg(inst->dst));
2309               copy->exec_size = lowered_width;
2310               copy->group = channel_offset;
2311               copy->size_written = size_written;
2312               inst->insert_before(block, copy);
2313            }
2314         } else {
2315            dst = horiz_offset(inst->dst, channel_offset);
2316         }
2317         linst->dst = dst;
2318
2319         /* Compute split source regions */
2320         for (int i = 0; i < 3; i++) {
2321            if (linst->src[i].file == BAD_FILE)
2322               continue;
2323
2324            bool is_interleaved_attr =
2325               linst->src[i].file == ATTR &&
2326               stage_uses_interleaved_attributes(stage,
2327                                                 prog_data->dispatch_mode);
2328
2329            if (!is_uniform(linst->src[i]) && !is_interleaved_attr)
2330               linst->src[i] = horiz_offset(linst->src[i], channel_offset);
2331         }
2332
2333         inst->insert_before(block, linst);
2334
2335         /* If we used a temporary to store the result of the split
2336          * instruction, copy the result to the original destination
2337          */
2338         if (needs_temp) {
2339            vec4_instruction *mov =
2340               MOV(offset(inst->dst, lowered_width, n), src_reg(dst));
2341            mov->exec_size = lowered_width;
2342            mov->group = channel_offset;
2343            mov->size_written = size_written;
2344            mov->predicate = inst->predicate;
2345            inst->insert_before(block, mov);
2346         }
2347      }
2348
2349      inst->remove(block);
2350      progress = true;
2351   }
2352
2353   if (progress)
2354      invalidate_live_intervals();
2355
2356   return progress;
2357}
2358
2359static brw_predicate
2360scalarize_predicate(brw_predicate predicate, unsigned writemask)
2361{
2362   if (predicate != BRW_PREDICATE_NORMAL)
2363      return predicate;
2364
2365   switch (writemask) {
2366   case WRITEMASK_X:
2367      return BRW_PREDICATE_ALIGN16_REPLICATE_X;
2368   case WRITEMASK_Y:
2369      return BRW_PREDICATE_ALIGN16_REPLICATE_Y;
2370   case WRITEMASK_Z:
2371      return BRW_PREDICATE_ALIGN16_REPLICATE_Z;
2372   case WRITEMASK_W:
2373      return BRW_PREDICATE_ALIGN16_REPLICATE_W;
2374   default:
2375      unreachable("invalid writemask");
2376   }
2377}
2378
2379/* Gen7 has a hardware decompression bug that we can exploit to represent
2380 * handful of additional swizzles natively.
2381 */
2382static bool
2383is_gen7_supported_64bit_swizzle(vec4_instruction *inst, unsigned arg)
2384{
2385   switch (inst->src[arg].swizzle) {
2386   case BRW_SWIZZLE_XXXX:
2387   case BRW_SWIZZLE_YYYY:
2388   case BRW_SWIZZLE_ZZZZ:
2389   case BRW_SWIZZLE_WWWW:
2390   case BRW_SWIZZLE_XYXY:
2391   case BRW_SWIZZLE_YXYX:
2392   case BRW_SWIZZLE_ZWZW:
2393   case BRW_SWIZZLE_WZWZ:
2394      return true;
2395   default:
2396      return false;
2397   }
2398}
2399
2400/* 64-bit sources use regions with a width of 2. These 2 elements in each row
2401 * can be addressed using 32-bit swizzles (which is what the hardware supports)
2402 * but it also means that the swizzle we apply on the first two components of a
2403 * dvec4 is coupled with the swizzle we use for the last 2. In other words,
2404 * only some specific swizzle combinations can be natively supported.
2405 *
2406 * FIXME: we can go an step further and implement even more swizzle
2407 *        variations using only partial scalarization.
2408 *
2409 * For more details see:
2410 * https://bugs.freedesktop.org/show_bug.cgi?id=92760#c82
2411 */
2412bool
2413vec4_visitor::is_supported_64bit_region(vec4_instruction *inst, unsigned arg)
2414{
2415   const src_reg &src = inst->src[arg];
2416   assert(type_sz(src.type) == 8);
2417
2418   /* Uniform regions have a vstride=0. Because we use 2-wide rows with
2419    * 64-bit regions it means that we cannot access components Z/W, so
2420    * return false for any such case. Interleaved attributes will also be
2421    * mapped to GRF registers with a vstride of 0, so apply the same
2422    * treatment.
2423    */
2424   if ((is_uniform(src) ||
2425        (stage_uses_interleaved_attributes(stage, prog_data->dispatch_mode) &&
2426         src.file == ATTR)) &&
2427       (brw_mask_for_swizzle(src.swizzle) & 12))
2428      return false;
2429
2430   switch (src.swizzle) {
2431   case BRW_SWIZZLE_XYZW:
2432   case BRW_SWIZZLE_XXZZ:
2433   case BRW_SWIZZLE_YYWW:
2434   case BRW_SWIZZLE_YXWZ:
2435      return true;
2436   default:
2437      return devinfo->gen == 7 && is_gen7_supported_64bit_swizzle(inst, arg);
2438   }
2439}
2440
2441bool
2442vec4_visitor::scalarize_df()
2443{
2444   bool progress = false;
2445
2446   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2447      /* Skip DF instructions that operate in Align1 mode */
2448      if (is_align1_df(inst))
2449         continue;
2450
2451      /* Check if this is a double-precision instruction */
2452      bool is_double = type_sz(inst->dst.type) == 8;
2453      for (int arg = 0; !is_double && arg < 3; arg++) {
2454         is_double = inst->src[arg].file != BAD_FILE &&
2455                     type_sz(inst->src[arg].type) == 8;
2456      }
2457
2458      if (!is_double)
2459         continue;
2460
2461      /* Skip the lowering for specific regioning scenarios that we can
2462       * support natively.
2463       */
2464      bool skip_lowering = true;
2465
2466      /* XY and ZW writemasks operate in 32-bit, which means that they don't
2467       * have a native 64-bit representation and they should always be split.
2468       */
2469      if (inst->dst.writemask == WRITEMASK_XY ||
2470          inst->dst.writemask == WRITEMASK_ZW) {
2471         skip_lowering = false;
2472      } else {
2473         for (unsigned i = 0; i < 3; i++) {
2474            if (inst->src[i].file == BAD_FILE || type_sz(inst->src[i].type) < 8)
2475               continue;
2476            skip_lowering = skip_lowering && is_supported_64bit_region(inst, i);
2477         }
2478      }
2479
2480      if (skip_lowering)
2481         continue;
2482
2483      /* Generate scalar instructions for each enabled channel */
2484      for (unsigned chan = 0; chan < 4; chan++) {
2485         unsigned chan_mask = 1 << chan;
2486         if (!(inst->dst.writemask & chan_mask))
2487            continue;
2488
2489         vec4_instruction *scalar_inst = new(mem_ctx) vec4_instruction(*inst);
2490
2491         for (unsigned i = 0; i < 3; i++) {
2492            unsigned swz = BRW_GET_SWZ(inst->src[i].swizzle, chan);
2493            scalar_inst->src[i].swizzle = BRW_SWIZZLE4(swz, swz, swz, swz);
2494         }
2495
2496         scalar_inst->dst.writemask = chan_mask;
2497
2498         if (inst->predicate != BRW_PREDICATE_NONE) {
2499            scalar_inst->predicate =
2500               scalarize_predicate(inst->predicate, chan_mask);
2501         }
2502
2503         inst->insert_before(block, scalar_inst);
2504      }
2505
2506      inst->remove(block);
2507      progress = true;
2508   }
2509
2510   if (progress)
2511      invalidate_live_intervals();
2512
2513   return progress;
2514}
2515
2516bool
2517vec4_visitor::lower_64bit_mad_to_mul_add()
2518{
2519   bool progress = false;
2520
2521   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2522      if (inst->opcode != BRW_OPCODE_MAD)
2523         continue;
2524
2525      if (type_sz(inst->dst.type) != 8)
2526         continue;
2527
2528      dst_reg mul_dst = dst_reg(this, glsl_type::dvec4_type);
2529
2530      /* Use the copy constructor so we copy all relevant instruction fields
2531       * from the original mad into the add and mul instructions
2532       */
2533      vec4_instruction *mul = new(mem_ctx) vec4_instruction(*inst);
2534      mul->opcode = BRW_OPCODE_MUL;
2535      mul->dst = mul_dst;
2536      mul->src[0] = inst->src[1];
2537      mul->src[1] = inst->src[2];
2538      mul->src[2].file = BAD_FILE;
2539
2540      vec4_instruction *add = new(mem_ctx) vec4_instruction(*inst);
2541      add->opcode = BRW_OPCODE_ADD;
2542      add->src[0] = src_reg(mul_dst);
2543      add->src[1] = inst->src[0];
2544      add->src[2].file = BAD_FILE;
2545
2546      inst->insert_before(block, mul);
2547      inst->insert_before(block, add);
2548      inst->remove(block);
2549
2550      progress = true;
2551   }
2552
2553   if (progress)
2554      invalidate_live_intervals();
2555
2556   return progress;
2557}
2558
2559/* The align16 hardware can only do 32-bit swizzle channels, so we need to
2560 * translate the logical 64-bit swizzle channels that we use in the Vec4 IR
2561 * to 32-bit swizzle channels in hardware registers.
2562 *
2563 * @inst and @arg identify the original vec4 IR source operand we need to
2564 * translate the swizzle for and @hw_reg is the hardware register where we
2565 * will write the hardware swizzle to use.
2566 *
2567 * This pass assumes that Align16/DF instructions have been fully scalarized
2568 * previously so there is just one 64-bit swizzle channel to deal with for any
2569 * given Vec4 IR source.
2570 */
2571void
2572vec4_visitor::apply_logical_swizzle(struct brw_reg *hw_reg,
2573                                    vec4_instruction *inst, int arg)
2574{
2575   src_reg reg = inst->src[arg];
2576
2577   if (reg.file == BAD_FILE || reg.file == BRW_IMMEDIATE_VALUE)
2578      return;
2579
2580   /* If this is not a 64-bit operand or this is a scalar instruction we don't
2581    * need to do anything about the swizzles.
2582    */
2583   if(type_sz(reg.type) < 8 || is_align1_df(inst)) {
2584      hw_reg->swizzle = reg.swizzle;
2585      return;
2586   }
2587
2588   /* Take the 64-bit logical swizzle channel and translate it to 32-bit */
2589   assert(brw_is_single_value_swizzle(reg.swizzle) ||
2590          is_supported_64bit_region(inst, arg));
2591
2592   /* Apply the region <2, 2, 1> for GRF or <0, 2, 1> for uniforms, as align16
2593    * HW can only do 32-bit swizzle channels.
2594    */
2595   hw_reg->width = BRW_WIDTH_2;
2596
2597   if (is_supported_64bit_region(inst, arg) &&
2598       !is_gen7_supported_64bit_swizzle(inst, arg)) {
2599      /* Supported 64-bit swizzles are those such that their first two
2600       * components, when expanded to 32-bit swizzles, match the semantics
2601       * of the original 64-bit swizzle with 2-wide row regioning.
2602       */
2603      unsigned swizzle0 = BRW_GET_SWZ(reg.swizzle, 0);
2604      unsigned swizzle1 = BRW_GET_SWZ(reg.swizzle, 1);
2605      hw_reg->swizzle = BRW_SWIZZLE4(swizzle0 * 2, swizzle0 * 2 + 1,
2606                                     swizzle1 * 2, swizzle1 * 2 + 1);
2607   } else {
2608      /* If we got here then we have one of the following:
2609       *
2610       * 1. An unsupported swizzle, which should be single-value thanks to the
2611       *    scalarization pass.
2612       *
2613       * 2. A gen7 supported swizzle. These can be single-value or double-value
2614       *    swizzles. If the latter, they are never cross-dvec2 channels. For
2615       *    these we always need to activate the gen7 vstride=0 exploit.
2616       */
2617      unsigned swizzle0 = BRW_GET_SWZ(reg.swizzle, 0);
2618      unsigned swizzle1 = BRW_GET_SWZ(reg.swizzle, 1);
2619      assert((swizzle0 < 2) == (swizzle1 < 2));
2620
2621      /* To gain access to Z/W components we need to select the second half
2622       * of the register and then use a X/Y swizzle to select Z/W respectively.
2623       */
2624      if (swizzle0 >= 2) {
2625         *hw_reg = suboffset(*hw_reg, 2);
2626         swizzle0 -= 2;
2627         swizzle1 -= 2;
2628      }
2629
2630      /* All gen7-specific supported swizzles require the vstride=0 exploit */
2631      if (devinfo->gen == 7 && is_gen7_supported_64bit_swizzle(inst, arg))
2632         hw_reg->vstride = BRW_VERTICAL_STRIDE_0;
2633
2634      /* Any 64-bit source with an offset at 16B is intended to address the
2635       * second half of a register and needs a vertical stride of 0 so we:
2636       *
2637       * 1. Don't violate register region restrictions.
2638       * 2. Activate the gen7 instruction decompresion bug exploit when
2639       *    execsize > 4
2640       */
2641      if (hw_reg->subnr % REG_SIZE == 16) {
2642         assert(devinfo->gen == 7);
2643         hw_reg->vstride = BRW_VERTICAL_STRIDE_0;
2644      }
2645
2646      hw_reg->swizzle = BRW_SWIZZLE4(swizzle0 * 2, swizzle0 * 2 + 1,
2647                                     swizzle1 * 2, swizzle1 * 2 + 1);
2648   }
2649}
2650
2651bool
2652vec4_visitor::run()
2653{
2654   if (shader_time_index >= 0)
2655      emit_shader_time_begin();
2656
2657   emit_prolog();
2658
2659   emit_nir_code();
2660   if (failed)
2661      return false;
2662   base_ir = NULL;
2663
2664   emit_thread_end();
2665
2666   calculate_cfg();
2667
2668   /* Before any optimization, push array accesses out to scratch
2669    * space where we need them to be.  This pass may allocate new
2670    * virtual GRFs, so we want to do it early.  It also makes sure
2671    * that we have reladdr computations available for CSE, since we'll
2672    * often do repeated subexpressions for those.
2673    */
2674   move_grf_array_access_to_scratch();
2675   move_uniform_array_access_to_pull_constants();
2676
2677   pack_uniform_registers();
2678   move_push_constants_to_pull_constants();
2679   split_virtual_grfs();
2680
2681#define OPT(pass, args...) ({                                          \
2682      pass_num++;                                                      \
2683      bool this_progress = pass(args);                                 \
2684                                                                       \
2685      if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) {  \
2686         char filename[64];                                            \
2687         snprintf(filename, 64, "%s-%s-%02d-%02d-" #pass,              \
2688                  stage_abbrev, nir->info.name, iteration, pass_num); \
2689                                                                       \
2690         backend_shader::dump_instructions(filename);                  \
2691      }                                                                \
2692                                                                       \
2693      progress = progress || this_progress;                            \
2694      this_progress;                                                   \
2695   })
2696
2697
2698   if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
2699      char filename[64];
2700      snprintf(filename, 64, "%s-%s-00-00-start",
2701               stage_abbrev, nir->info.name);
2702
2703      backend_shader::dump_instructions(filename);
2704   }
2705
2706   bool progress;
2707   int iteration = 0;
2708   int pass_num = 0;
2709   do {
2710      progress = false;
2711      pass_num = 0;
2712      iteration++;
2713
2714      OPT(opt_predicated_break, this);
2715      OPT(opt_reduce_swizzle);
2716      OPT(dead_code_eliminate);
2717      OPT(dead_control_flow_eliminate, this);
2718      OPT(opt_copy_propagation);
2719      OPT(opt_cmod_propagation);
2720      OPT(opt_cse);
2721      OPT(opt_algebraic);
2722      OPT(opt_register_coalesce);
2723      OPT(eliminate_find_live_channel);
2724   } while (progress);
2725
2726   pass_num = 0;
2727
2728   if (OPT(opt_vector_float)) {
2729      OPT(opt_cse);
2730      OPT(opt_copy_propagation, false);
2731      OPT(opt_copy_propagation, true);
2732      OPT(dead_code_eliminate);
2733   }
2734
2735   if (devinfo->gen <= 5 && OPT(lower_minmax)) {
2736      OPT(opt_cmod_propagation);
2737      OPT(opt_cse);
2738      OPT(opt_copy_propagation);
2739      OPT(dead_code_eliminate);
2740   }
2741
2742   if (OPT(lower_simd_width)) {
2743      OPT(opt_copy_propagation);
2744      OPT(dead_code_eliminate);
2745   }
2746
2747   if (failed)
2748      return false;
2749
2750   OPT(lower_64bit_mad_to_mul_add);
2751
2752   /* Run this before payload setup because tesselation shaders
2753    * rely on it to prevent cross dvec2 regioning on DF attributes
2754    * that are setup so that XY are on the second half of register and
2755    * ZW are in the first half of the next.
2756    */
2757   OPT(scalarize_df);
2758
2759   setup_payload();
2760
2761   if (unlikely(INTEL_DEBUG & DEBUG_SPILL_VEC4)) {
2762      /* Debug of register spilling: Go spill everything. */
2763      const int grf_count = alloc.count;
2764      float spill_costs[alloc.count];
2765      bool no_spill[alloc.count];
2766      evaluate_spill_costs(spill_costs, no_spill);
2767      for (int i = 0; i < grf_count; i++) {
2768         if (no_spill[i])
2769            continue;
2770         spill_reg(i);
2771      }
2772
2773      /* We want to run this after spilling because 64-bit (un)spills need to
2774       * emit code to shuffle 64-bit data for the 32-bit scratch read/write
2775       * messages that can produce unsupported 64-bit swizzle regions.
2776       */
2777      OPT(scalarize_df);
2778   }
2779
2780   fixup_3src_null_dest();
2781
2782   bool allocated_without_spills = reg_allocate();
2783
2784   if (!allocated_without_spills) {
2785      compiler->shader_perf_log(log_data,
2786                                "%s shader triggered register spilling.  "
2787                                "Try reducing the number of live vec4 values "
2788                                "to improve performance.\n",
2789                                stage_name);
2790
2791      while (!reg_allocate()) {
2792         if (failed)
2793            return false;
2794      }
2795
2796      /* We want to run this after spilling because 64-bit (un)spills need to
2797       * emit code to shuffle 64-bit data for the 32-bit scratch read/write
2798       * messages that can produce unsupported 64-bit swizzle regions.
2799       */
2800      OPT(scalarize_df);
2801   }
2802
2803   opt_schedule_instructions();
2804
2805   opt_set_dependency_control();
2806
2807   convert_to_hw_regs();
2808
2809   if (last_scratch > 0) {
2810      prog_data->base.total_scratch =
2811         brw_get_scratch_size(last_scratch * REG_SIZE);
2812   }
2813
2814   return !failed;
2815}
2816
2817} /* namespace brw */
2818
2819extern "C" {
2820
2821/**
2822 * Compile a vertex shader.
2823 *
2824 * Returns the final assembly and the program's size.
2825 */
2826const unsigned *
2827brw_compile_vs(const struct brw_compiler *compiler, void *log_data,
2828               void *mem_ctx,
2829               const struct brw_vs_prog_key *key,
2830               struct brw_vs_prog_data *prog_data,
2831               const nir_shader *src_shader,
2832               int shader_time_index,
2833               char **error_str)
2834{
2835   const bool is_scalar = compiler->scalar_stage[MESA_SHADER_VERTEX];
2836   nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
2837   shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, is_scalar);
2838
2839   const unsigned *assembly = NULL;
2840
2841   if (prog_data->base.vue_map.varying_to_slot[VARYING_SLOT_EDGE] != -1) {
2842      /* If the output VUE map contains VARYING_SLOT_EDGE then we need to copy
2843       * the edge flag from VERT_ATTRIB_EDGEFLAG.  This will be done
2844       * automatically by brw_vec4_visitor::emit_urb_slot but we need to
2845       * ensure that prog_data->inputs_read is accurate.
2846       *
2847       * In order to make late NIR passes aware of the change, we actually
2848       * whack shader->info.inputs_read instead.  This is safe because we just
2849       * made a copy of the shader.
2850       */
2851      assert(!is_scalar);
2852      assert(key->copy_edgeflag);
2853      shader->info.inputs_read |= VERT_BIT_EDGEFLAG;
2854   }
2855
2856   prog_data->inputs_read = shader->info.inputs_read;
2857   prog_data->double_inputs_read = shader->info.vs.double_inputs;
2858
2859   brw_nir_lower_vs_inputs(shader, key->gl_attrib_wa_flags);
2860   brw_nir_lower_vue_outputs(shader);
2861   shader = brw_postprocess_nir(shader, compiler, is_scalar);
2862
2863   prog_data->base.clip_distance_mask =
2864      ((1 << shader->info.clip_distance_array_size) - 1);
2865   prog_data->base.cull_distance_mask =
2866      ((1 << shader->info.cull_distance_array_size) - 1) <<
2867      shader->info.clip_distance_array_size;
2868
2869   unsigned nr_attribute_slots = util_bitcount64(prog_data->inputs_read);
2870
2871   /* gl_VertexID and gl_InstanceID are system values, but arrive via an
2872    * incoming vertex attribute.  So, add an extra slot.
2873    */
2874   if (shader->info.system_values_read &
2875       (BITFIELD64_BIT(SYSTEM_VALUE_FIRST_VERTEX) |
2876        BITFIELD64_BIT(SYSTEM_VALUE_BASE_INSTANCE) |
2877        BITFIELD64_BIT(SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) |
2878        BITFIELD64_BIT(SYSTEM_VALUE_INSTANCE_ID))) {
2879      nr_attribute_slots++;
2880   }
2881
2882   /* gl_DrawID and IsIndexedDraw share its very own vec4 */
2883   if (shader->info.system_values_read &
2884       (BITFIELD64_BIT(SYSTEM_VALUE_DRAW_ID) |
2885        BITFIELD64_BIT(SYSTEM_VALUE_IS_INDEXED_DRAW))) {
2886      nr_attribute_slots++;
2887   }
2888
2889   if (shader->info.system_values_read &
2890       BITFIELD64_BIT(SYSTEM_VALUE_IS_INDEXED_DRAW))
2891      prog_data->uses_is_indexed_draw = true;
2892
2893   if (shader->info.system_values_read &
2894       BITFIELD64_BIT(SYSTEM_VALUE_FIRST_VERTEX))
2895      prog_data->uses_firstvertex = true;
2896
2897   if (shader->info.system_values_read &
2898       BITFIELD64_BIT(SYSTEM_VALUE_BASE_INSTANCE))
2899      prog_data->uses_baseinstance = true;
2900
2901   if (shader->info.system_values_read &
2902       BITFIELD64_BIT(SYSTEM_VALUE_VERTEX_ID_ZERO_BASE))
2903      prog_data->uses_vertexid = true;
2904
2905   if (shader->info.system_values_read &
2906       BITFIELD64_BIT(SYSTEM_VALUE_INSTANCE_ID))
2907      prog_data->uses_instanceid = true;
2908
2909   if (shader->info.system_values_read &
2910       BITFIELD64_BIT(SYSTEM_VALUE_DRAW_ID))
2911          prog_data->uses_drawid = true;
2912
2913   /* The 3DSTATE_VS documentation lists the lower bound on "Vertex URB Entry
2914    * Read Length" as 1 in vec4 mode, and 0 in SIMD8 mode.  Empirically, in
2915    * vec4 mode, the hardware appears to wedge unless we read something.
2916    */
2917   if (is_scalar)
2918      prog_data->base.urb_read_length =
2919         DIV_ROUND_UP(nr_attribute_slots, 2);
2920   else
2921      prog_data->base.urb_read_length =
2922         DIV_ROUND_UP(MAX2(nr_attribute_slots, 1), 2);
2923
2924   prog_data->nr_attribute_slots = nr_attribute_slots;
2925
2926   /* Since vertex shaders reuse the same VUE entry for inputs and outputs
2927    * (overwriting the original contents), we need to make sure the size is
2928    * the larger of the two.
2929    */
2930   const unsigned vue_entries =
2931      MAX2(nr_attribute_slots, (unsigned)prog_data->base.vue_map.num_slots);
2932
2933   if (compiler->devinfo->gen == 6) {
2934      prog_data->base.urb_entry_size = DIV_ROUND_UP(vue_entries, 8);
2935   } else {
2936      prog_data->base.urb_entry_size = DIV_ROUND_UP(vue_entries, 4);
2937      /* On Cannonlake software shall not program an allocation size that
2938       * specifies a size that is a multiple of 3 64B (512-bit) cachelines.
2939       */
2940      if (compiler->devinfo->gen == 10 &&
2941          prog_data->base.urb_entry_size % 3 == 0)
2942         prog_data->base.urb_entry_size++;
2943   }
2944
2945   if (INTEL_DEBUG & DEBUG_VS) {
2946      fprintf(stderr, "VS Output ");
2947      brw_print_vue_map(stderr, &prog_data->base.vue_map);
2948   }
2949
2950   if (is_scalar) {
2951      prog_data->base.dispatch_mode = DISPATCH_MODE_SIMD8;
2952
2953      fs_visitor v(compiler, log_data, mem_ctx, key, &prog_data->base.base,
2954                   NULL, /* prog; Only used for TEXTURE_RECTANGLE on gen < 8 */
2955                   shader, 8, shader_time_index);
2956      if (!v.run_vs()) {
2957         if (error_str)
2958            *error_str = ralloc_strdup(mem_ctx, v.fail_msg);
2959
2960         return NULL;
2961      }
2962
2963      prog_data->base.base.dispatch_grf_start_reg = v.payload.num_regs;
2964
2965      fs_generator g(compiler, log_data, mem_ctx,
2966                     &prog_data->base.base, v.promoted_constants,
2967                     v.runtime_check_aads_emit, MESA_SHADER_VERTEX);
2968      if (INTEL_DEBUG & DEBUG_VS) {
2969         const char *debug_name =
2970            ralloc_asprintf(mem_ctx, "%s vertex shader %s",
2971                            shader->info.label ? shader->info.label :
2972                               "unnamed",
2973                            shader->info.name);
2974
2975         g.enable_debug(debug_name);
2976      }
2977      g.generate_code(v.cfg, 8);
2978      assembly = g.get_assembly();
2979   }
2980
2981   if (!assembly) {
2982      prog_data->base.dispatch_mode = DISPATCH_MODE_4X2_DUAL_OBJECT;
2983
2984      vec4_vs_visitor v(compiler, log_data, key, prog_data,
2985                        shader, mem_ctx, shader_time_index);
2986      if (!v.run()) {
2987         if (error_str)
2988            *error_str = ralloc_strdup(mem_ctx, v.fail_msg);
2989
2990         return NULL;
2991      }
2992
2993      assembly = brw_vec4_generate_assembly(compiler, log_data, mem_ctx,
2994                                            shader, &prog_data->base, v.cfg);
2995   }
2996
2997   return assembly;
2998}
2999
3000} /* extern "C" */
3001