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