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