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