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