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