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