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