OSDN Git Service

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