intel/compiler: Record whether any pull constant loads occur
[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
2430 prog_data->has_ubo_pull = true;
2431 return true;
2432 }
2433
2434 const unsigned location = src.nr + src.offset / 4;
2435
2436 if (location < uniforms && pull_constant_loc[location] != -1) {
2437 /* A regular uniform push constant */
2438 *out_surf_index = stage_prog_data->binding_table.pull_constants_start;
2439 *out_pull_index = pull_constant_loc[location];
2440
2441 prog_data->has_ubo_pull = true;
2442 return true;
2443 }
2444
2445 return false;
2446 }
2447
2448 /**
2449 * Replace UNIFORM register file access with either UNIFORM_PULL_CONSTANT_LOAD
2450 * or VARYING_PULL_CONSTANT_LOAD instructions which load values into VGRFs.
2451 */
2452 void
2453 fs_visitor::lower_constant_loads()
2454 {
2455 unsigned index, pull_index;
2456
2457 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2458 /* Set up the annotation tracking for new generated instructions. */
2459 const fs_builder ibld(this, block, inst);
2460
2461 for (int i = 0; i < inst->sources; i++) {
2462 if (inst->src[i].file != UNIFORM)
2463 continue;
2464
2465 /* We'll handle this case later */
2466 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0)
2467 continue;
2468
2469 if (!get_pull_locs(inst->src[i], &index, &pull_index))
2470 continue;
2471
2472 assert(inst->src[i].stride == 0);
2473
2474 const unsigned block_sz = 64; /* Fetch one cacheline at a time. */
2475 const fs_builder ubld = ibld.exec_all().group(block_sz / 4, 0);
2476 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
2477 const unsigned base = pull_index * 4;
2478
2479 ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
2480 dst, brw_imm_ud(index), brw_imm_ud(base & ~(block_sz - 1)));
2481
2482 /* Rewrite the instruction to use the temporary VGRF. */
2483 inst->src[i].file = VGRF;
2484 inst->src[i].nr = dst.nr;
2485 inst->src[i].offset = (base & (block_sz - 1)) +
2486 inst->src[i].offset % 4;
2487 }
2488
2489 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
2490 inst->src[0].file == UNIFORM) {
2491
2492 if (!get_pull_locs(inst->src[0], &index, &pull_index))
2493 continue;
2494
2495 VARYING_PULL_CONSTANT_LOAD(ibld, inst->dst,
2496 brw_imm_ud(index),
2497 inst->src[1],
2498 pull_index * 4);
2499 inst->remove(block);
2500 }
2501 }
2502 invalidate_live_intervals();
2503 }
2504
2505 bool
2506 fs_visitor::opt_algebraic()
2507 {
2508 bool progress = false;
2509
2510 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2511 switch (inst->opcode) {
2512 case BRW_OPCODE_MOV:
2513 if (!devinfo->has_64bit_types &&
2514 (inst->dst.type == BRW_REGISTER_TYPE_DF ||
2515 inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2516 inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2517 assert(inst->dst.type == inst->src[0].type);
2518 assert(!inst->saturate);
2519 assert(!inst->src[0].abs);
2520 assert(!inst->src[0].negate);
2521 const brw::fs_builder ibld(this, block, inst);
2522
2523 if (inst->src[0].file == IMM) {
2524 ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2525 brw_imm_ud(inst->src[0].u64 >> 32));
2526 ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2527 brw_imm_ud(inst->src[0].u64));
2528 } else {
2529 ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2530 subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1));
2531 ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2532 subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0));
2533 }
2534
2535 inst->remove(block);
2536 progress = true;
2537 }
2538
2539 if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2540 inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2541 inst->dst.is_null() &&
2542 (inst->src[0].abs || inst->src[0].negate)) {
2543 inst->src[0].abs = false;
2544 inst->src[0].negate = false;
2545 progress = true;
2546 break;
2547 }
2548
2549 if (inst->src[0].file != IMM)
2550 break;
2551
2552 if (inst->saturate) {
2553 /* Full mixed-type saturates don't happen. However, we can end up
2554 * with things like:
2555 *
2556 * mov.sat(8) g21<1>DF -1F
2557 *
2558 * Other mixed-size-but-same-base-type cases may also be possible.
2559 */
2560 if (inst->dst.type != inst->src[0].type &&
2561 inst->dst.type != BRW_REGISTER_TYPE_DF &&
2562 inst->src[0].type != BRW_REGISTER_TYPE_F)
2563 assert(!"unimplemented: saturate mixed types");
2564
2565 if (brw_saturate_immediate(inst->src[0].type,
2566 &inst->src[0].as_brw_reg())) {
2567 inst->saturate = false;
2568 progress = true;
2569 }
2570 }
2571 break;
2572
2573 case BRW_OPCODE_MUL:
2574 if (inst->src[1].file != IMM)
2575 continue;
2576
2577 /* a * 1.0 = a */
2578 if (inst->src[1].is_one()) {
2579 inst->opcode = BRW_OPCODE_MOV;
2580 inst->src[1] = reg_undef;
2581 progress = true;
2582 break;
2583 }
2584
2585 /* a * -1.0 = -a */
2586 if (inst->src[1].is_negative_one()) {
2587 inst->opcode = BRW_OPCODE_MOV;
2588 inst->src[0].negate = !inst->src[0].negate;
2589 inst->src[1] = reg_undef;
2590 progress = true;
2591 break;
2592 }
2593
2594 if (inst->src[0].file == IMM) {
2595 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2596 inst->opcode = BRW_OPCODE_MOV;
2597 inst->src[0].f *= inst->src[1].f;
2598 inst->src[1] = reg_undef;
2599 progress = true;
2600 break;
2601 }
2602 break;
2603 case BRW_OPCODE_ADD:
2604 if (inst->src[1].file != IMM)
2605 continue;
2606
2607 if (inst->src[0].file == IMM) {
2608 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2609 inst->opcode = BRW_OPCODE_MOV;
2610 inst->src[0].f += inst->src[1].f;
2611 inst->src[1] = reg_undef;
2612 progress = true;
2613 break;
2614 }
2615 break;
2616 case BRW_OPCODE_OR:
2617 if (inst->src[0].equals(inst->src[1]) ||
2618 inst->src[1].is_zero()) {
2619 /* On Gen8+, the OR instruction can have a source modifier that
2620 * performs logical not on the operand. Cases of 'OR r0, ~r1, 0'
2621 * or 'OR r0, ~r1, ~r1' should become a NOT instead of a MOV.
2622 */
2623 if (inst->src[0].negate) {
2624 inst->opcode = BRW_OPCODE_NOT;
2625 inst->src[0].negate = false;
2626 } else {
2627 inst->opcode = BRW_OPCODE_MOV;
2628 }
2629 inst->src[1] = reg_undef;
2630 progress = true;
2631 break;
2632 }
2633 break;
2634 case BRW_OPCODE_CMP:
2635 if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2636 inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2637 inst->src[1].is_zero() &&
2638 (inst->src[0].abs || inst->src[0].negate)) {
2639 inst->src[0].abs = false;
2640 inst->src[0].negate = false;
2641 progress = true;
2642 break;
2643 }
2644 break;
2645 case BRW_OPCODE_SEL:
2646 if (!devinfo->has_64bit_types &&
2647 (inst->dst.type == BRW_REGISTER_TYPE_DF ||
2648 inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2649 inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2650 assert(inst->dst.type == inst->src[0].type);
2651 assert(!inst->saturate);
2652 assert(!inst->src[0].abs && !inst->src[0].negate);
2653 assert(!inst->src[1].abs && !inst->src[1].negate);
2654 const brw::fs_builder ibld(this, block, inst);
2655
2656 set_predicate(inst->predicate,
2657 ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2658 subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
2659 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0)));
2660 set_predicate(inst->predicate,
2661 ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2662 subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1),
2663 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 1)));
2664
2665 inst->remove(block);
2666 progress = true;
2667 }
2668 if (inst->src[0].equals(inst->src[1])) {
2669 inst->opcode = BRW_OPCODE_MOV;
2670 inst->src[1] = reg_undef;
2671 inst->predicate = BRW_PREDICATE_NONE;
2672 inst->predicate_inverse = false;
2673 progress = true;
2674 } else if (inst->saturate && inst->src[1].file == IMM) {
2675 switch (inst->conditional_mod) {
2676 case BRW_CONDITIONAL_LE:
2677 case BRW_CONDITIONAL_L:
2678 switch (inst->src[1].type) {
2679 case BRW_REGISTER_TYPE_F:
2680 if (inst->src[1].f >= 1.0f) {
2681 inst->opcode = BRW_OPCODE_MOV;
2682 inst->src[1] = reg_undef;
2683 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2684 progress = true;
2685 }
2686 break;
2687 default:
2688 break;
2689 }
2690 break;
2691 case BRW_CONDITIONAL_GE:
2692 case BRW_CONDITIONAL_G:
2693 switch (inst->src[1].type) {
2694 case BRW_REGISTER_TYPE_F:
2695 if (inst->src[1].f <= 0.0f) {
2696 inst->opcode = BRW_OPCODE_MOV;
2697 inst->src[1] = reg_undef;
2698 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2699 progress = true;
2700 }
2701 break;
2702 default:
2703 break;
2704 }
2705 default:
2706 break;
2707 }
2708 }
2709 break;
2710 case BRW_OPCODE_MAD:
2711 if (inst->src[0].type != BRW_REGISTER_TYPE_F ||
2712 inst->src[1].type != BRW_REGISTER_TYPE_F ||
2713 inst->src[2].type != BRW_REGISTER_TYPE_F)
2714 break;
2715 if (inst->src[1].is_one()) {
2716 inst->opcode = BRW_OPCODE_ADD;
2717 inst->src[1] = inst->src[2];
2718 inst->src[2] = reg_undef;
2719 progress = true;
2720 } else if (inst->src[2].is_one()) {
2721 inst->opcode = BRW_OPCODE_ADD;
2722 inst->src[2] = reg_undef;
2723 progress = true;
2724 }
2725 break;
2726 case SHADER_OPCODE_BROADCAST:
2727 if (is_uniform(inst->src[0])) {
2728 inst->opcode = BRW_OPCODE_MOV;
2729 inst->sources = 1;
2730 inst->force_writemask_all = true;
2731 progress = true;
2732 } else if (inst->src[1].file == IMM) {
2733 inst->opcode = BRW_OPCODE_MOV;
2734 /* It's possible that the selected component will be too large and
2735 * overflow the register. This can happen if someone does a
2736 * readInvocation() from GLSL or SPIR-V and provides an OOB
2737 * invocationIndex. If this happens and we some how manage
2738 * to constant fold it in and get here, then component() may cause
2739 * us to start reading outside of the VGRF which will lead to an
2740 * assert later. Instead, just let it wrap around if it goes over
2741 * exec_size.
2742 */
2743 const unsigned comp = inst->src[1].ud & (inst->exec_size - 1);
2744 inst->src[0] = component(inst->src[0], comp);
2745 inst->sources = 1;
2746 inst->force_writemask_all = true;
2747 progress = true;
2748 }
2749 break;
2750
2751 case SHADER_OPCODE_SHUFFLE:
2752 if (is_uniform(inst->src[0])) {
2753 inst->opcode = BRW_OPCODE_MOV;
2754 inst->sources = 1;
2755 progress = true;
2756 } else if (inst->src[1].file == IMM) {
2757 inst->opcode = BRW_OPCODE_MOV;
2758 inst->src[0] = component(inst->src[0],
2759 inst->src[1].ud);
2760 inst->sources = 1;
2761 progress = true;
2762 }
2763 break;
2764
2765 default:
2766 break;
2767 }
2768
2769 /* Swap if src[0] is immediate. */
2770 if (progress && inst->is_commutative()) {
2771 if (inst->src[0].file == IMM) {
2772 fs_reg tmp = inst->src[1];
2773 inst->src[1] = inst->src[0];
2774 inst->src[0] = tmp;
2775 }
2776 }
2777 }
2778 return progress;
2779 }
2780
2781 /**
2782 * Optimize sample messages that have constant zero values for the trailing
2783 * texture coordinates. We can just reduce the message length for these
2784 * instructions instead of reserving a register for it. Trailing parameters
2785 * that aren't sent default to zero anyway. This will cause the dead code
2786 * eliminator to remove the MOV instruction that would otherwise be emitted to
2787 * set up the zero value.
2788 */
2789 bool
2790 fs_visitor::opt_zero_samples()
2791 {
2792 /* Gen4 infers the texturing opcode based on the message length so we can't
2793 * change it.
2794 */
2795 if (devinfo->gen < 5)
2796 return false;
2797
2798 bool progress = false;
2799
2800 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2801 if (!inst->is_tex())
2802 continue;
2803
2804 fs_inst *load_payload = (fs_inst *) inst->prev;
2805
2806 if (load_payload->is_head_sentinel() ||
2807 load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2808 continue;
2809
2810 /* We don't want to remove the message header or the first parameter.
2811 * Removing the first parameter is not allowed, see the Haswell PRM
2812 * volume 7, page 149:
2813 *
2814 * "Parameter 0 is required except for the sampleinfo message, which
2815 * has no parameter 0"
2816 */
2817 while (inst->mlen > inst->header_size + inst->exec_size / 8 &&
2818 load_payload->src[(inst->mlen - inst->header_size) /
2819 (inst->exec_size / 8) +
2820 inst->header_size - 1].is_zero()) {
2821 inst->mlen -= inst->exec_size / 8;
2822 progress = true;
2823 }
2824 }
2825
2826 if (progress)
2827 invalidate_live_intervals();
2828
2829 return progress;
2830 }
2831
2832 /**
2833 * Optimize sample messages which are followed by the final RT write.
2834 *
2835 * CHV, and GEN9+ can mark a texturing SEND instruction with EOT to have its
2836 * results sent directly to the framebuffer, bypassing the EU. Recognize the
2837 * final texturing results copied to the framebuffer write payload and modify
2838 * them to write to the framebuffer directly.
2839 */
2840 bool
2841 fs_visitor::opt_sampler_eot()
2842 {
2843 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
2844
2845 if (stage != MESA_SHADER_FRAGMENT || dispatch_width > 16)
2846 return false;
2847
2848 if (devinfo->gen != 9 && !devinfo->is_cherryview)
2849 return false;
2850
2851 /* FINISHME: It should be possible to implement this optimization when there
2852 * are multiple drawbuffers.
2853 */
2854 if (key->nr_color_regions != 1)
2855 return false;
2856
2857 /* Requires emitting a bunch of saturating MOV instructions during logical
2858 * send lowering to clamp the color payload, which the sampler unit isn't
2859 * going to do for us.
2860 */
2861 if (key->clamp_fragment_color)
2862 return false;
2863
2864 /* Look for a texturing instruction immediately before the final FB_WRITE. */
2865 bblock_t *block = cfg->blocks[cfg->num_blocks - 1];
2866 fs_inst *fb_write = (fs_inst *)block->end();
2867 assert(fb_write->eot);
2868 assert(fb_write->opcode == FS_OPCODE_FB_WRITE_LOGICAL);
2869
2870 /* There wasn't one; nothing to do. */
2871 if (unlikely(fb_write->prev->is_head_sentinel()))
2872 return false;
2873
2874 fs_inst *tex_inst = (fs_inst *) fb_write->prev;
2875
2876 /* 3D Sampler » Messages » Message Format
2877 *
2878 * “Response Length of zero is allowed on all SIMD8* and SIMD16* sampler
2879 * messages except sample+killpix, resinfo, sampleinfo, LOD, and gather4*”
2880 */
2881 if (tex_inst->opcode != SHADER_OPCODE_TEX_LOGICAL &&
2882 tex_inst->opcode != SHADER_OPCODE_TXD_LOGICAL &&
2883 tex_inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
2884 tex_inst->opcode != SHADER_OPCODE_TXL_LOGICAL &&
2885 tex_inst->opcode != FS_OPCODE_TXB_LOGICAL &&
2886 tex_inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL &&
2887 tex_inst->opcode != SHADER_OPCODE_TXF_CMS_W_LOGICAL &&
2888 tex_inst->opcode != SHADER_OPCODE_TXF_UMS_LOGICAL)
2889 return false;
2890
2891 /* XXX - This shouldn't be necessary. */
2892 if (tex_inst->prev->is_head_sentinel())
2893 return false;
2894
2895 /* Check that the FB write sources are fully initialized by the single
2896 * texturing instruction.
2897 */
2898 for (unsigned i = 0; i < FB_WRITE_LOGICAL_NUM_SRCS; i++) {
2899 if (i == FB_WRITE_LOGICAL_SRC_COLOR0) {
2900 if (!fb_write->src[i].equals(tex_inst->dst) ||
2901 fb_write->size_read(i) != tex_inst->size_written)
2902 return false;
2903 } else if (i != FB_WRITE_LOGICAL_SRC_COMPONENTS) {
2904 if (fb_write->src[i].file != BAD_FILE)
2905 return false;
2906 }
2907 }
2908
2909 assert(!tex_inst->eot); /* We can't get here twice */
2910 assert((tex_inst->offset & (0xff << 24)) == 0);
2911
2912 const fs_builder ibld(this, block, tex_inst);
2913
2914 tex_inst->offset |= fb_write->target << 24;
2915 tex_inst->eot = true;
2916 tex_inst->dst = ibld.null_reg_ud();
2917 tex_inst->size_written = 0;
2918 fb_write->remove(cfg->blocks[cfg->num_blocks - 1]);
2919
2920 /* Marking EOT is sufficient, lower_logical_sends() will notice the EOT
2921 * flag and submit a header together with the sampler message as required
2922 * by the hardware.
2923 */
2924 invalidate_live_intervals();
2925 return true;
2926 }
2927
2928 bool
2929 fs_visitor::opt_register_renaming()
2930 {
2931 bool progress = false;
2932 int depth = 0;
2933
2934 unsigned remap[alloc.count];
2935 memset(remap, ~0u, sizeof(unsigned) * alloc.count);
2936
2937 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2938 if (inst->opcode == BRW_OPCODE_IF || inst->opcode == BRW_OPCODE_DO) {
2939 depth++;
2940 } else if (inst->opcode == BRW_OPCODE_ENDIF ||
2941 inst->opcode == BRW_OPCODE_WHILE) {
2942 depth--;
2943 }
2944
2945 /* Rewrite instruction sources. */
2946 for (int i = 0; i < inst->sources; i++) {
2947 if (inst->src[i].file == VGRF &&
2948 remap[inst->src[i].nr] != ~0u &&
2949 remap[inst->src[i].nr] != inst->src[i].nr) {
2950 inst->src[i].nr = remap[inst->src[i].nr];
2951 progress = true;
2952 }
2953 }
2954
2955 const unsigned dst = inst->dst.nr;
2956
2957 if (depth == 0 &&
2958 inst->dst.file == VGRF &&
2959 alloc.sizes[inst->dst.nr] * REG_SIZE == inst->size_written &&
2960 !inst->is_partial_write()) {
2961 if (remap[dst] == ~0u) {
2962 remap[dst] = dst;
2963 } else {
2964 remap[dst] = alloc.allocate(regs_written(inst));
2965 inst->dst.nr = remap[dst];
2966 progress = true;
2967 }
2968 } else if (inst->dst.file == VGRF &&
2969 remap[dst] != ~0u &&
2970 remap[dst] != dst) {
2971 inst->dst.nr = remap[dst];
2972 progress = true;
2973 }
2974 }
2975
2976 if (progress) {
2977 invalidate_live_intervals();
2978
2979 for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2980 if (delta_xy[i].file == VGRF && remap[delta_xy[i].nr] != ~0u) {
2981 delta_xy[i].nr = remap[delta_xy[i].nr];
2982 }
2983 }
2984 }
2985
2986 return progress;
2987 }
2988
2989 /**
2990 * Remove redundant or useless discard jumps.
2991 *
2992 * For example, we can eliminate jumps in the following sequence:
2993 *
2994 * discard-jump (redundant with the next jump)
2995 * discard-jump (useless; jumps to the next instruction)
2996 * placeholder-halt
2997 */
2998 bool
2999 fs_visitor::opt_redundant_discard_jumps()
3000 {
3001 bool progress = false;
3002
3003 bblock_t *last_bblock = cfg->blocks[cfg->num_blocks - 1];
3004
3005 fs_inst *placeholder_halt = NULL;
3006 foreach_inst_in_block_reverse(fs_inst, inst, last_bblock) {
3007 if (inst->opcode == FS_OPCODE_PLACEHOLDER_HALT) {
3008 placeholder_halt = inst;
3009 break;
3010 }
3011 }
3012
3013 if (!placeholder_halt)
3014 return false;
3015
3016 /* Delete any HALTs immediately before the placeholder halt. */
3017 for (fs_inst *prev = (fs_inst *) placeholder_halt->prev;
3018 !prev->is_head_sentinel() && prev->opcode == FS_OPCODE_DISCARD_JUMP;
3019 prev = (fs_inst *) placeholder_halt->prev) {
3020 prev->remove(last_bblock);
3021 progress = true;
3022 }
3023
3024 if (progress)
3025 invalidate_live_intervals();
3026
3027 return progress;
3028 }
3029
3030 /**
3031 * Compute a bitmask with GRF granularity with a bit set for each GRF starting
3032 * from \p r.offset which overlaps the region starting at \p s.offset and
3033 * spanning \p ds bytes.
3034 */
3035 static inline unsigned
3036 mask_relative_to(const fs_reg &r, const fs_reg &s, unsigned ds)
3037 {
3038 const int rel_offset = reg_offset(s) - reg_offset(r);
3039 const int shift = rel_offset / REG_SIZE;
3040 const unsigned n = DIV_ROUND_UP(rel_offset % REG_SIZE + ds, REG_SIZE);
3041 assert(reg_space(r) == reg_space(s) &&
3042 shift >= 0 && shift < int(8 * sizeof(unsigned)));
3043 return ((1 << n) - 1) << shift;
3044 }
3045
3046 bool
3047 fs_visitor::opt_peephole_csel()
3048 {
3049 if (devinfo->gen < 8)
3050 return false;
3051
3052 bool progress = false;
3053
3054 foreach_block_reverse(block, cfg) {
3055 int ip = block->end_ip + 1;
3056
3057 foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
3058 ip--;
3059
3060 if (inst->opcode != BRW_OPCODE_SEL ||
3061 inst->predicate != BRW_PREDICATE_NORMAL ||
3062 (inst->dst.type != BRW_REGISTER_TYPE_F &&
3063 inst->dst.type != BRW_REGISTER_TYPE_D &&
3064 inst->dst.type != BRW_REGISTER_TYPE_UD))
3065 continue;
3066
3067 /* Because it is a 3-src instruction, CSEL cannot have an immediate
3068 * value as a source, but we can sometimes handle zero.
3069 */
3070 if ((inst->src[0].file != VGRF && inst->src[0].file != ATTR &&
3071 inst->src[0].file != UNIFORM) ||
3072 (inst->src[1].file != VGRF && inst->src[1].file != ATTR &&
3073 inst->src[1].file != UNIFORM && !inst->src[1].is_zero()))
3074 continue;
3075
3076 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3077 if (!scan_inst->flags_written())
3078 continue;
3079
3080 if ((scan_inst->opcode != BRW_OPCODE_CMP &&
3081 scan_inst->opcode != BRW_OPCODE_MOV) ||
3082 scan_inst->predicate != BRW_PREDICATE_NONE ||
3083 (scan_inst->src[0].file != VGRF &&
3084 scan_inst->src[0].file != ATTR &&
3085 scan_inst->src[0].file != UNIFORM) ||
3086 scan_inst->src[0].type != BRW_REGISTER_TYPE_F)
3087 break;
3088
3089 if (scan_inst->opcode == BRW_OPCODE_CMP && !scan_inst->src[1].is_zero())
3090 break;
3091
3092 const brw::fs_builder ibld(this, block, inst);
3093
3094 const enum brw_conditional_mod cond =
3095 inst->predicate_inverse
3096 ? brw_negate_cmod(scan_inst->conditional_mod)
3097 : scan_inst->conditional_mod;
3098
3099 fs_inst *csel_inst = NULL;
3100
3101 if (inst->src[1].file != IMM) {
3102 csel_inst = ibld.CSEL(inst->dst,
3103 inst->src[0],
3104 inst->src[1],
3105 scan_inst->src[0],
3106 cond);
3107 } else if (cond == BRW_CONDITIONAL_NZ) {
3108 /* Consider the sequence
3109 *
3110 * cmp.nz.f0 null<1>F g3<8,8,1>F 0F
3111 * (+f0) sel g124<1>UD g2<8,8,1>UD 0x00000000UD
3112 *
3113 * The sel will pick the immediate value 0 if r0 is ±0.0.
3114 * Therefore, this sequence is equivalent:
3115 *
3116 * cmp.nz.f0 null<1>F g3<8,8,1>F 0F
3117 * (+f0) sel g124<1>F g2<8,8,1>F (abs)g3<8,8,1>F
3118 *
3119 * The abs is ensures that the result is 0UD when g3 is -0.0F.
3120 * By normal cmp-sel merging, this is also equivalent:
3121 *
3122 * csel.nz g124<1>F g2<4,4,1>F (abs)g3<4,4,1>F g3<4,4,1>F
3123 */
3124 csel_inst = ibld.CSEL(inst->dst,
3125 inst->src[0],
3126 scan_inst->src[0],
3127 scan_inst->src[0],
3128 cond);
3129
3130 csel_inst->src[1].abs = true;
3131 }
3132
3133 if (csel_inst != NULL) {
3134 progress = true;
3135 csel_inst->saturate = inst->saturate;
3136 inst->remove(block);
3137 }
3138
3139 break;
3140 }
3141 }
3142 }
3143
3144 return progress;
3145 }
3146
3147 bool
3148 fs_visitor::compute_to_mrf()
3149 {
3150 bool progress = false;
3151 int next_ip = 0;
3152
3153 /* No MRFs on Gen >= 7. */
3154 if (devinfo->gen >= 7)
3155 return false;
3156
3157 calculate_live_intervals();
3158
3159 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3160 int ip = next_ip;
3161 next_ip++;
3162
3163 if (inst->opcode != BRW_OPCODE_MOV ||
3164 inst->is_partial_write() ||
3165 inst->dst.file != MRF || inst->src[0].file != VGRF ||
3166 inst->dst.type != inst->src[0].type ||
3167 inst->src[0].abs || inst->src[0].negate ||
3168 !inst->src[0].is_contiguous() ||
3169 inst->src[0].offset % REG_SIZE != 0)
3170 continue;
3171
3172 /* Can't compute-to-MRF this GRF if someone else was going to
3173 * read it later.
3174 */
3175 if (this->virtual_grf_end[inst->src[0].nr] > ip)
3176 continue;
3177
3178 /* Found a move of a GRF to a MRF. Let's see if we can go rewrite the
3179 * things that computed the value of all GRFs of the source region. The
3180 * regs_left bitset keeps track of the registers we haven't yet found a
3181 * generating instruction for.
3182 */
3183 unsigned regs_left = (1 << regs_read(inst, 0)) - 1;
3184
3185 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3186 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3187 inst->src[0], inst->size_read(0))) {
3188 /* Found the last thing to write our reg we want to turn
3189 * into a compute-to-MRF.
3190 */
3191
3192 /* If this one instruction didn't populate all the
3193 * channels, bail. We might be able to rewrite everything
3194 * that writes that reg, but it would require smarter
3195 * tracking.
3196 */
3197 if (scan_inst->is_partial_write())
3198 break;
3199
3200 /* Handling things not fully contained in the source of the copy
3201 * would need us to understand coalescing out more than one MOV at
3202 * a time.
3203 */
3204 if (!region_contained_in(scan_inst->dst, scan_inst->size_written,
3205 inst->src[0], inst->size_read(0)))
3206 break;
3207
3208 /* SEND instructions can't have MRF as a destination. */
3209 if (scan_inst->mlen)
3210 break;
3211
3212 if (devinfo->gen == 6) {
3213 /* gen6 math instructions must have the destination be
3214 * GRF, so no compute-to-MRF for them.
3215 */
3216 if (scan_inst->is_math()) {
3217 break;
3218 }
3219 }
3220
3221 /* Clear the bits for any registers this instruction overwrites. */
3222 regs_left &= ~mask_relative_to(
3223 inst->src[0], scan_inst->dst, scan_inst->size_written);
3224 if (!regs_left)
3225 break;
3226 }
3227
3228 /* We don't handle control flow here. Most computation of
3229 * values that end up in MRFs are shortly before the MRF
3230 * write anyway.
3231 */
3232 if (block->start() == scan_inst)
3233 break;
3234
3235 /* You can't read from an MRF, so if someone else reads our
3236 * MRF's source GRF that we wanted to rewrite, that stops us.
3237 */
3238 bool interfered = false;
3239 for (int i = 0; i < scan_inst->sources; i++) {
3240 if (regions_overlap(scan_inst->src[i], scan_inst->size_read(i),
3241 inst->src[0], inst->size_read(0))) {
3242 interfered = true;
3243 }
3244 }
3245 if (interfered)
3246 break;
3247
3248 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3249 inst->dst, inst->size_written)) {
3250 /* If somebody else writes our MRF here, we can't
3251 * compute-to-MRF before that.
3252 */
3253 break;
3254 }
3255
3256 if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1 &&
3257 regions_overlap(fs_reg(MRF, scan_inst->base_mrf), scan_inst->mlen * REG_SIZE,
3258 inst->dst, inst->size_written)) {
3259 /* Found a SEND instruction, which means that there are
3260 * live values in MRFs from base_mrf to base_mrf +
3261 * scan_inst->mlen - 1. Don't go pushing our MRF write up
3262 * above it.
3263 */
3264 break;
3265 }
3266 }
3267
3268 if (regs_left)
3269 continue;
3270
3271 /* Found all generating instructions of our MRF's source value, so it
3272 * should be safe to rewrite them to point to the MRF directly.
3273 */
3274 regs_left = (1 << regs_read(inst, 0)) - 1;
3275
3276 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3277 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3278 inst->src[0], inst->size_read(0))) {
3279 /* Clear the bits for any registers this instruction overwrites. */
3280 regs_left &= ~mask_relative_to(
3281 inst->src[0], scan_inst->dst, scan_inst->size_written);
3282
3283 const unsigned rel_offset = reg_offset(scan_inst->dst) -
3284 reg_offset(inst->src[0]);
3285
3286 if (inst->dst.nr & BRW_MRF_COMPR4) {
3287 /* Apply the same address transformation done by the hardware
3288 * for COMPR4 MRF writes.
3289 */
3290 assert(rel_offset < 2 * REG_SIZE);
3291 scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE * 4;
3292
3293 /* Clear the COMPR4 bit if the generating instruction is not
3294 * compressed.
3295 */
3296 if (scan_inst->size_written < 2 * REG_SIZE)
3297 scan_inst->dst.nr &= ~BRW_MRF_COMPR4;
3298
3299 } else {
3300 /* Calculate the MRF number the result of this instruction is
3301 * ultimately written to.
3302 */
3303 scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE;
3304 }
3305
3306 scan_inst->dst.file = MRF;
3307 scan_inst->dst.offset = inst->dst.offset + rel_offset % REG_SIZE;
3308 scan_inst->saturate |= inst->saturate;
3309 if (!regs_left)
3310 break;
3311 }
3312 }
3313
3314 assert(!regs_left);
3315 inst->remove(block);
3316 progress = true;
3317 }
3318
3319 if (progress)
3320 invalidate_live_intervals();
3321
3322 return progress;
3323 }
3324
3325 /**
3326 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
3327 * flow. We could probably do better here with some form of divergence
3328 * analysis.
3329 */
3330 bool
3331 fs_visitor::eliminate_find_live_channel()
3332 {
3333 bool progress = false;
3334 unsigned depth = 0;
3335
3336 if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
3337 /* The optimization below assumes that channel zero is live on thread
3338 * dispatch, which may not be the case if the fixed function dispatches
3339 * threads sparsely.
3340 */
3341 return false;
3342 }
3343
3344 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3345 switch (inst->opcode) {
3346 case BRW_OPCODE_IF:
3347 case BRW_OPCODE_DO:
3348 depth++;
3349 break;
3350
3351 case BRW_OPCODE_ENDIF:
3352 case BRW_OPCODE_WHILE:
3353 depth--;
3354 break;
3355
3356 case FS_OPCODE_DISCARD_JUMP:
3357 /* This can potentially make control flow non-uniform until the end
3358 * of the program.
3359 */
3360 return progress;
3361
3362 case SHADER_OPCODE_FIND_LIVE_CHANNEL:
3363 if (depth == 0) {
3364 inst->opcode = BRW_OPCODE_MOV;
3365 inst->src[0] = brw_imm_ud(0u);
3366 inst->sources = 1;
3367 inst->force_writemask_all = true;
3368 progress = true;
3369 }
3370 break;
3371
3372 default:
3373 break;
3374 }
3375 }
3376
3377 return progress;
3378 }
3379
3380 /**
3381 * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
3382 * instructions to FS_OPCODE_REP_FB_WRITE.
3383 */
3384 void
3385 fs_visitor::emit_repclear_shader()
3386 {
3387 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3388 int base_mrf = 0;
3389 int color_mrf = base_mrf + 2;
3390 fs_inst *mov;
3391
3392 if (uniforms > 0) {
3393 mov = bld.exec_all().group(4, 0)
3394 .MOV(brw_message_reg(color_mrf),
3395 fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
3396 } else {
3397 struct brw_reg reg =
3398 brw_reg(BRW_GENERAL_REGISTER_FILE, 2, 3, 0, 0, BRW_REGISTER_TYPE_F,
3399 BRW_VERTICAL_STRIDE_8, BRW_WIDTH_2, BRW_HORIZONTAL_STRIDE_4,
3400 BRW_SWIZZLE_XYZW, WRITEMASK_XYZW);
3401
3402 mov = bld.exec_all().group(4, 0)
3403 .MOV(vec4(brw_message_reg(color_mrf)), fs_reg(reg));
3404 }
3405
3406 fs_inst *write = NULL;
3407 if (key->nr_color_regions == 1) {
3408 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3409 write->saturate = key->clamp_fragment_color;
3410 write->base_mrf = color_mrf;
3411 write->target = 0;
3412 write->header_size = 0;
3413 write->mlen = 1;
3414 } else {
3415 assume(key->nr_color_regions > 0);
3416
3417 struct brw_reg header =
3418 retype(brw_message_reg(base_mrf), BRW_REGISTER_TYPE_UD);
3419 bld.exec_all().group(16, 0)
3420 .MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3421
3422 for (int i = 0; i < key->nr_color_regions; ++i) {
3423 if (i > 0) {
3424 bld.exec_all().group(1, 0)
3425 .MOV(component(header, 2), brw_imm_ud(i));
3426 }
3427
3428 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3429 write->saturate = key->clamp_fragment_color;
3430 write->base_mrf = base_mrf;
3431 write->target = i;
3432 write->header_size = 2;
3433 write->mlen = 3;
3434 }
3435 }
3436 write->eot = true;
3437 write->last_rt = true;
3438
3439 calculate_cfg();
3440
3441 assign_constant_locations();
3442 assign_curb_setup();
3443
3444 /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
3445 if (uniforms > 0) {
3446 assert(mov->src[0].file == FIXED_GRF);
3447 mov->src[0] = brw_vec4_grf(mov->src[0].nr, 0);
3448 }
3449 }
3450
3451 /**
3452 * Walks through basic blocks, looking for repeated MRF writes and
3453 * removing the later ones.
3454 */
3455 bool
3456 fs_visitor::remove_duplicate_mrf_writes()
3457 {
3458 fs_inst *last_mrf_move[BRW_MAX_MRF(devinfo->gen)];
3459 bool progress = false;
3460
3461 /* Need to update the MRF tracking for compressed instructions. */
3462 if (dispatch_width >= 16)
3463 return false;
3464
3465 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3466
3467 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3468 if (inst->is_control_flow()) {
3469 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3470 }
3471
3472 if (inst->opcode == BRW_OPCODE_MOV &&
3473 inst->dst.file == MRF) {
3474 fs_inst *prev_inst = last_mrf_move[inst->dst.nr];
3475 if (prev_inst && prev_inst->opcode == BRW_OPCODE_MOV &&
3476 inst->dst.equals(prev_inst->dst) &&
3477 inst->src[0].equals(prev_inst->src[0]) &&
3478 inst->saturate == prev_inst->saturate &&
3479 inst->predicate == prev_inst->predicate &&
3480 inst->conditional_mod == prev_inst->conditional_mod &&
3481 inst->exec_size == prev_inst->exec_size) {
3482 inst->remove(block);
3483 progress = true;
3484 continue;
3485 }
3486 }
3487
3488 /* Clear out the last-write records for MRFs that were overwritten. */
3489 if (inst->dst.file == MRF) {
3490 last_mrf_move[inst->dst.nr] = NULL;
3491 }
3492
3493 if (inst->mlen > 0 && inst->base_mrf != -1) {
3494 /* Found a SEND instruction, which will include two or fewer
3495 * implied MRF writes. We could do better here.
3496 */
3497 for (int i = 0; i < implied_mrf_writes(inst); i++) {
3498 last_mrf_move[inst->base_mrf + i] = NULL;
3499 }
3500 }
3501
3502 /* Clear out any MRF move records whose sources got overwritten. */
3503 for (unsigned i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
3504 if (last_mrf_move[i] &&
3505 regions_overlap(inst->dst, inst->size_written,
3506 last_mrf_move[i]->src[0],
3507 last_mrf_move[i]->size_read(0))) {
3508 last_mrf_move[i] = NULL;
3509 }
3510 }
3511
3512 if (inst->opcode == BRW_OPCODE_MOV &&
3513 inst->dst.file == MRF &&
3514 inst->src[0].file != ARF &&
3515 !inst->is_partial_write()) {
3516 last_mrf_move[inst->dst.nr] = inst;
3517 }
3518 }
3519
3520 if (progress)
3521 invalidate_live_intervals();
3522
3523 return progress;
3524 }
3525
3526 /**
3527 * Rounding modes for conversion instructions are included for each
3528 * conversion, but right now it is a state. So once it is set,
3529 * we don't need to call it again for subsequent calls.
3530 *
3531 * This is useful for vector/matrices conversions, as setting the
3532 * mode once is enough for the full vector/matrix
3533 */
3534 bool
3535 fs_visitor::remove_extra_rounding_modes()
3536 {
3537 bool progress = false;
3538 unsigned execution_mode = this->nir->info.float_controls_execution_mode;
3539
3540 brw_rnd_mode base_mode = BRW_RND_MODE_UNSPECIFIED;
3541 if ((FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16 |
3542 FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32 |
3543 FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64) &
3544 execution_mode)
3545 base_mode = BRW_RND_MODE_RTNE;
3546 if ((FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16 |
3547 FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32 |
3548 FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64) &
3549 execution_mode)
3550 base_mode = BRW_RND_MODE_RTZ;
3551
3552 foreach_block (block, cfg) {
3553 brw_rnd_mode prev_mode = base_mode;
3554
3555 foreach_inst_in_block_safe (fs_inst, inst, block) {
3556 if (inst->opcode == SHADER_OPCODE_RND_MODE) {
3557 assert(inst->src[0].file == BRW_IMMEDIATE_VALUE);
3558 const brw_rnd_mode mode = (brw_rnd_mode) inst->src[0].d;
3559 if (mode == prev_mode) {
3560 inst->remove(block);
3561 progress = true;
3562 } else {
3563 prev_mode = mode;
3564 }
3565 }
3566 }
3567 }
3568
3569 if (progress)
3570 invalidate_live_intervals();
3571
3572 return progress;
3573 }
3574
3575 static void
3576 clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
3577 {
3578 /* Clear the flag for registers that actually got read (as expected). */
3579 for (int i = 0; i < inst->sources; i++) {
3580 int grf;
3581 if (inst->src[i].file == VGRF || inst->src[i].file == FIXED_GRF) {
3582 grf = inst->src[i].nr;
3583 } else {
3584 continue;
3585 }
3586
3587 if (grf >= first_grf &&
3588 grf < first_grf + grf_len) {
3589 deps[grf - first_grf] = false;
3590 if (inst->exec_size == 16)
3591 deps[grf - first_grf + 1] = false;
3592 }
3593 }
3594 }
3595
3596 /**
3597 * Implements this workaround for the original 965:
3598 *
3599 * "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
3600 * check for post destination dependencies on this instruction, software
3601 * must ensure that there is no destination hazard for the case of ‘write
3602 * followed by a posted write’ shown in the following example.
3603 *
3604 * 1. mov r3 0
3605 * 2. send r3.xy <rest of send instruction>
3606 * 3. mov r2 r3
3607 *
3608 * Due to no post-destination dependency check on the ‘send’, the above
3609 * code sequence could have two instructions (1 and 2) in flight at the
3610 * same time that both consider ‘r3’ as the target of their final writes.
3611 */
3612 void
3613 fs_visitor::insert_gen4_pre_send_dependency_workarounds(bblock_t *block,
3614 fs_inst *inst)
3615 {
3616 int write_len = regs_written(inst);
3617 int first_write_grf = inst->dst.nr;
3618 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3619 assert(write_len < (int)sizeof(needs_dep) - 1);
3620
3621 memset(needs_dep, false, sizeof(needs_dep));
3622 memset(needs_dep, true, write_len);
3623
3624 clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
3625
3626 /* Walk backwards looking for writes to registers we're writing which
3627 * aren't read since being written. If we hit the start of the program,
3628 * we assume that there are no outstanding dependencies on entry to the
3629 * program.
3630 */
3631 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3632 /* If we hit control flow, assume that there *are* outstanding
3633 * dependencies, and force their cleanup before our instruction.
3634 */
3635 if (block->start() == scan_inst && block->num != 0) {
3636 for (int i = 0; i < write_len; i++) {
3637 if (needs_dep[i])
3638 DEP_RESOLVE_MOV(fs_builder(this, block, inst),
3639 first_write_grf + i);
3640 }
3641 return;
3642 }
3643
3644 /* We insert our reads as late as possible on the assumption that any
3645 * instruction but a MOV that might have left us an outstanding
3646 * dependency has more latency than a MOV.
3647 */
3648 if (scan_inst->dst.file == VGRF) {
3649 for (unsigned i = 0; i < regs_written(scan_inst); i++) {
3650 int reg = scan_inst->dst.nr + i;
3651
3652 if (reg >= first_write_grf &&
3653 reg < first_write_grf + write_len &&
3654 needs_dep[reg - first_write_grf]) {
3655 DEP_RESOLVE_MOV(fs_builder(this, block, inst), reg);
3656 needs_dep[reg - first_write_grf] = false;
3657 if (scan_inst->exec_size == 16)
3658 needs_dep[reg - first_write_grf + 1] = false;
3659 }
3660 }
3661 }
3662
3663 /* Clear the flag for registers that actually got read (as expected). */
3664 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3665
3666 /* Continue the loop only if we haven't resolved all the dependencies */
3667 int i;
3668 for (i = 0; i < write_len; i++) {
3669 if (needs_dep[i])
3670 break;
3671 }
3672 if (i == write_len)
3673 return;
3674 }
3675 }
3676
3677 /**
3678 * Implements this workaround for the original 965:
3679 *
3680 * "[DevBW, DevCL] Errata: A destination register from a send can not be
3681 * used as a destination register until after it has been sourced by an
3682 * instruction with a different destination register.
3683 */
3684 void
3685 fs_visitor::insert_gen4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
3686 {
3687 int write_len = regs_written(inst);
3688 unsigned first_write_grf = inst->dst.nr;
3689 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3690 assert(write_len < (int)sizeof(needs_dep) - 1);
3691
3692 memset(needs_dep, false, sizeof(needs_dep));
3693 memset(needs_dep, true, write_len);
3694 /* Walk forwards looking for writes to registers we're writing which aren't
3695 * read before being written.
3696 */
3697 foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst) {
3698 /* If we hit control flow, force resolve all remaining dependencies. */
3699 if (block->end() == scan_inst && block->num != cfg->num_blocks - 1) {
3700 for (int i = 0; i < write_len; i++) {
3701 if (needs_dep[i])
3702 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3703 first_write_grf + i);
3704 }
3705 return;
3706 }
3707
3708 /* Clear the flag for registers that actually got read (as expected). */
3709 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3710
3711 /* We insert our reads as late as possible since they're reading the
3712 * result of a SEND, which has massive latency.
3713 */
3714 if (scan_inst->dst.file == VGRF &&
3715 scan_inst->dst.nr >= first_write_grf &&
3716 scan_inst->dst.nr < first_write_grf + write_len &&
3717 needs_dep[scan_inst->dst.nr - first_write_grf]) {
3718 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3719 scan_inst->dst.nr);
3720 needs_dep[scan_inst->dst.nr - first_write_grf] = false;
3721 }
3722
3723 /* Continue the loop only if we haven't resolved all the dependencies */
3724 int i;
3725 for (i = 0; i < write_len; i++) {
3726 if (needs_dep[i])
3727 break;
3728 }
3729 if (i == write_len)
3730 return;
3731 }
3732 }
3733
3734 void
3735 fs_visitor::insert_gen4_send_dependency_workarounds()
3736 {
3737 if (devinfo->gen != 4 || devinfo->is_g4x)
3738 return;
3739
3740 bool progress = false;
3741
3742 foreach_block_and_inst(block, fs_inst, inst, cfg) {
3743 if (inst->mlen != 0 && inst->dst.file == VGRF) {
3744 insert_gen4_pre_send_dependency_workarounds(block, inst);
3745 insert_gen4_post_send_dependency_workarounds(block, inst);
3746 progress = true;
3747 }
3748 }
3749
3750 if (progress)
3751 invalidate_live_intervals();
3752 }
3753
3754 /**
3755 * Turns the generic expression-style uniform pull constant load instruction
3756 * into a hardware-specific series of instructions for loading a pull
3757 * constant.
3758 *
3759 * The expression style allows the CSE pass before this to optimize out
3760 * repeated loads from the same offset, and gives the pre-register-allocation
3761 * scheduling full flexibility, while the conversion to native instructions
3762 * allows the post-register-allocation scheduler the best information
3763 * possible.
3764 *
3765 * Note that execution masking for setting up pull constant loads is special:
3766 * the channels that need to be written are unrelated to the current execution
3767 * mask, since a later instruction will use one of the result channels as a
3768 * source operand for all 8 or 16 of its channels.
3769 */
3770 void
3771 fs_visitor::lower_uniform_pull_constant_loads()
3772 {
3773 foreach_block_and_inst (block, fs_inst, inst, cfg) {
3774 if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
3775 continue;
3776
3777 if (devinfo->gen >= 7) {
3778 const fs_builder ubld = fs_builder(this, block, inst).exec_all();
3779 const fs_reg payload = ubld.group(8, 0).vgrf(BRW_REGISTER_TYPE_UD);
3780
3781 ubld.group(8, 0).MOV(payload,
3782 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3783 ubld.group(1, 0).MOV(component(payload, 2),
3784 brw_imm_ud(inst->src[1].ud / 16));
3785
3786 inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7;
3787 inst->src[1] = payload;
3788 inst->header_size = 1;
3789 inst->mlen = 1;
3790
3791 invalidate_live_intervals();
3792 } else {
3793 /* Before register allocation, we didn't tell the scheduler about the
3794 * MRF we use. We know it's safe to use this MRF because nothing
3795 * else does except for register spill/unspill, which generates and
3796 * uses its MRF within a single IR instruction.
3797 */
3798 inst->base_mrf = FIRST_PULL_LOAD_MRF(devinfo->gen) + 1;
3799 inst->mlen = 1;
3800 }
3801 }
3802 }
3803
3804 bool
3805 fs_visitor::lower_load_payload()
3806 {
3807 bool progress = false;
3808
3809 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3810 if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3811 continue;
3812
3813 assert(inst->dst.file == MRF || inst->dst.file == VGRF);
3814 assert(inst->saturate == false);
3815 fs_reg dst = inst->dst;
3816
3817 /* Get rid of COMPR4. We'll add it back in if we need it */
3818 if (dst.file == MRF)
3819 dst.nr = dst.nr & ~BRW_MRF_COMPR4;
3820
3821 const fs_builder ibld(this, block, inst);
3822 const fs_builder hbld = ibld.exec_all().group(8, 0);
3823
3824 for (uint8_t i = 0; i < inst->header_size; i++) {
3825 if (inst->src[i].file != BAD_FILE) {
3826 fs_reg mov_dst = retype(dst, BRW_REGISTER_TYPE_UD);
3827 fs_reg mov_src = retype(inst->src[i], BRW_REGISTER_TYPE_UD);
3828 hbld.MOV(mov_dst, mov_src);
3829 }
3830 dst = offset(dst, hbld, 1);
3831 }
3832
3833 if (inst->dst.file == MRF && (inst->dst.nr & BRW_MRF_COMPR4) &&
3834 inst->exec_size > 8) {
3835 /* In this case, the payload portion of the LOAD_PAYLOAD isn't
3836 * a straightforward copy. Instead, the result of the
3837 * LOAD_PAYLOAD is treated as interleaved and the first four
3838 * non-header sources are unpacked as:
3839 *
3840 * m + 0: r0
3841 * m + 1: g0
3842 * m + 2: b0
3843 * m + 3: a0
3844 * m + 4: r1
3845 * m + 5: g1
3846 * m + 6: b1
3847 * m + 7: a1
3848 *
3849 * This is used for gen <= 5 fb writes.
3850 */
3851 assert(inst->exec_size == 16);
3852 assert(inst->header_size + 4 <= inst->sources);
3853 for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
3854 if (inst->src[i].file != BAD_FILE) {
3855 if (devinfo->has_compr4) {
3856 fs_reg compr4_dst = retype(dst, inst->src[i].type);
3857 compr4_dst.nr |= BRW_MRF_COMPR4;
3858 ibld.MOV(compr4_dst, inst->src[i]);
3859 } else {
3860 /* Platform doesn't have COMPR4. We have to fake it */
3861 fs_reg mov_dst = retype(dst, inst->src[i].type);
3862 ibld.half(0).MOV(mov_dst, half(inst->src[i], 0));
3863 mov_dst.nr += 4;
3864 ibld.half(1).MOV(mov_dst, half(inst->src[i], 1));
3865 }
3866 }
3867
3868 dst.nr++;
3869 }
3870
3871 /* The loop above only ever incremented us through the first set
3872 * of 4 registers. However, thanks to the magic of COMPR4, we
3873 * actually wrote to the first 8 registers, so we need to take
3874 * that into account now.
3875 */
3876 dst.nr += 4;
3877
3878 /* The COMPR4 code took care of the first 4 sources. We'll let
3879 * the regular path handle any remaining sources. Yes, we are
3880 * modifying the instruction but we're about to delete it so
3881 * this really doesn't hurt anything.
3882 */
3883 inst->header_size += 4;
3884 }
3885
3886 for (uint8_t i = inst->header_size; i < inst->sources; i++) {
3887 if (inst->src[i].file != BAD_FILE) {
3888 dst.type = inst->src[i].type;
3889 ibld.MOV(dst, inst->src[i]);
3890 } else {
3891 dst.type = BRW_REGISTER_TYPE_UD;
3892 }
3893 dst = offset(dst, ibld, 1);
3894 }
3895
3896 inst->remove(block);
3897 progress = true;
3898 }
3899
3900 if (progress)
3901 invalidate_live_intervals();
3902
3903 return progress;
3904 }
3905
3906 void
3907 fs_visitor::lower_mul_dword_inst(fs_inst *inst, bblock_t *block)
3908 {
3909 const fs_builder ibld(this, block, inst);
3910
3911 if (inst->src[1].file == IMM && inst->src[1].ud < (1 << 16)) {
3912 /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3913 * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3914 * src1 are used.
3915 *
3916 * If multiplying by an immediate value that fits in 16-bits, do a
3917 * single MUL instruction with that value in the proper location.
3918 */
3919 if (devinfo->gen < 7) {
3920 fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8), inst->dst.type);
3921 ibld.MOV(imm, inst->src[1]);
3922 ibld.MUL(inst->dst, imm, inst->src[0]);
3923 } else {
3924 const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
3925 ibld.MUL(inst->dst, inst->src[0],
3926 ud ? brw_imm_uw(inst->src[1].ud)
3927 : brw_imm_w(inst->src[1].d));
3928 }
3929 } else {
3930 /* Gen < 8 (and some Gen8+ low-power parts like Cherryview) cannot
3931 * do 32-bit integer multiplication in one instruction, but instead
3932 * must do a sequence (which actually calculates a 64-bit result):
3933 *
3934 * mul(8) acc0<1>D g3<8,8,1>D g4<8,8,1>D
3935 * mach(8) null g3<8,8,1>D g4<8,8,1>D
3936 * mov(8) g2<1>D acc0<8,8,1>D
3937 *
3938 * But on Gen > 6, the ability to use second accumulator register
3939 * (acc1) for non-float data types was removed, preventing a simple
3940 * implementation in SIMD16. A 16-channel result can be calculated by
3941 * executing the three instructions twice in SIMD8, once with quarter
3942 * control of 1Q for the first eight channels and again with 2Q for
3943 * the second eight channels.
3944 *
3945 * Which accumulator register is implicitly accessed (by AccWrEnable
3946 * for instance) is determined by the quarter control. Unfortunately
3947 * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3948 * implicit accumulator access by an instruction with 2Q will access
3949 * acc1 regardless of whether the data type is usable in acc1.
3950 *
3951 * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3952 * integer data types.
3953 *
3954 * Since we only want the low 32-bits of the result, we can do two
3955 * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3956 * adjust the high result and add them (like the mach is doing):
3957 *
3958 * mul(8) g7<1>D g3<8,8,1>D g4.0<8,8,1>UW
3959 * mul(8) g8<1>D g3<8,8,1>D g4.1<8,8,1>UW
3960 * shl(8) g9<1>D g8<8,8,1>D 16D
3961 * add(8) g2<1>D g7<8,8,1>D g8<8,8,1>D
3962 *
3963 * We avoid the shl instruction by realizing that we only want to add
3964 * the low 16-bits of the "high" result to the high 16-bits of the
3965 * "low" result and using proper regioning on the add:
3966 *
3967 * mul(8) g7<1>D g3<8,8,1>D g4.0<16,8,2>UW
3968 * mul(8) g8<1>D g3<8,8,1>D g4.1<16,8,2>UW
3969 * add(8) g7.1<2>UW g7.1<16,8,2>UW g8<16,8,2>UW
3970 *
3971 * Since it does not use the (single) accumulator register, we can
3972 * schedule multi-component multiplications much better.
3973 */
3974
3975 bool needs_mov = false;
3976 fs_reg orig_dst = inst->dst;
3977
3978 /* Get a new VGRF for the "low" 32x16-bit multiplication result if
3979 * reusing the original destination is impossible due to hardware
3980 * restrictions, source/destination overlap, or it being the null
3981 * register.
3982 */
3983 fs_reg low = inst->dst;
3984 if (orig_dst.is_null() || orig_dst.file == MRF ||
3985 regions_overlap(inst->dst, inst->size_written,
3986 inst->src[0], inst->size_read(0)) ||
3987 regions_overlap(inst->dst, inst->size_written,
3988 inst->src[1], inst->size_read(1)) ||
3989 inst->dst.stride >= 4) {
3990 needs_mov = true;
3991 low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
3992 inst->dst.type);
3993 }
3994
3995 /* Get a new VGRF but keep the same stride as inst->dst */
3996 fs_reg high(VGRF, alloc.allocate(regs_written(inst)), inst->dst.type);
3997 high.stride = inst->dst.stride;
3998 high.offset = inst->dst.offset % REG_SIZE;
3999
4000 if (devinfo->gen >= 7) {
4001 if (inst->src[1].abs)
4002 lower_src_modifiers(this, block, inst, 1);
4003
4004 if (inst->src[1].file == IMM) {
4005 ibld.MUL(low, inst->src[0],
4006 brw_imm_uw(inst->src[1].ud & 0xffff));
4007 ibld.MUL(high, inst->src[0],
4008 brw_imm_uw(inst->src[1].ud >> 16));
4009 } else {
4010 ibld.MUL(low, inst->src[0],
4011 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4012 ibld.MUL(high, inst->src[0],
4013 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
4014 }
4015 } else {
4016 if (inst->src[0].abs)
4017 lower_src_modifiers(this, block, inst, 0);
4018
4019 ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
4020 inst->src[1]);
4021 ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
4022 inst->src[1]);
4023 }
4024
4025 ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
4026 subscript(low, BRW_REGISTER_TYPE_UW, 1),
4027 subscript(high, BRW_REGISTER_TYPE_UW, 0));
4028
4029 if (needs_mov || inst->conditional_mod)
4030 set_condmod(inst->conditional_mod, ibld.MOV(orig_dst, low));
4031 }
4032 }
4033
4034 void
4035 fs_visitor::lower_mul_qword_inst(fs_inst *inst, bblock_t *block)
4036 {
4037 const fs_builder ibld(this, block, inst);
4038
4039 /* Considering two 64-bit integers ab and cd where each letter ab
4040 * corresponds to 32 bits, we get a 128-bit result WXYZ. We * cd
4041 * only need to provide the YZ part of the result. -------
4042 * BD
4043 * Only BD needs to be 64 bits. For AD and BC we only care + AD
4044 * about the lower 32 bits (since they are part of the upper + BC
4045 * 32 bits of our result). AC is not needed since it starts + AC
4046 * on the 65th bit of the result. -------
4047 * WXYZ
4048 */
4049 unsigned int q_regs = regs_written(inst);
4050 unsigned int d_regs = (q_regs + 1) / 2;
4051
4052 fs_reg bd(VGRF, alloc.allocate(q_regs), BRW_REGISTER_TYPE_UQ);
4053 fs_reg ad(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4054 fs_reg bc(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4055
4056 /* Here we need the full 64 bit result for 32b * 32b. */
4057 if (devinfo->has_integer_dword_mul) {
4058 ibld.MUL(bd, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4059 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4060 } else {
4061 fs_reg bd_high(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4062 fs_reg bd_low(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4063 fs_reg acc = retype(brw_acc_reg(inst->exec_size), BRW_REGISTER_TYPE_UD);
4064
4065 fs_inst *mul = ibld.MUL(acc,
4066 subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4067 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4068 mul->writes_accumulator = true;
4069
4070 ibld.MACH(bd_high, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4071 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4072 ibld.MOV(bd_low, acc);
4073
4074 ibld.MOV(subscript(bd, BRW_REGISTER_TYPE_UD, 0), bd_low);
4075 ibld.MOV(subscript(bd, BRW_REGISTER_TYPE_UD, 1), bd_high);
4076 }
4077
4078 ibld.MUL(ad, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1),
4079 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4080 ibld.MUL(bc, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4081 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 1));
4082
4083 ibld.ADD(ad, ad, bc);
4084 ibld.ADD(subscript(bd, BRW_REGISTER_TYPE_UD, 1),
4085 subscript(bd, BRW_REGISTER_TYPE_UD, 1), ad);
4086
4087 ibld.MOV(inst->dst, bd);
4088 }
4089
4090 void
4091 fs_visitor::lower_mulh_inst(fs_inst *inst, bblock_t *block)
4092 {
4093 const fs_builder ibld(this, block, inst);
4094
4095 /* According to the BDW+ BSpec page for the "Multiply Accumulate
4096 * High" instruction:
4097 *
4098 * "An added preliminary mov is required for source modification on
4099 * src1:
4100 * mov (8) r3.0<1>:d -r3<8;8,1>:d
4101 * mul (8) acc0:d r2.0<8;8,1>:d r3.0<16;8,2>:uw
4102 * mach (8) r5.0<1>:d r2.0<8;8,1>:d r3.0<8;8,1>:d"
4103 */
4104 if (devinfo->gen >= 8 && (inst->src[1].negate || inst->src[1].abs))
4105 lower_src_modifiers(this, block, inst, 1);
4106
4107 /* Should have been lowered to 8-wide. */
4108 assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
4109 const fs_reg acc = retype(brw_acc_reg(inst->exec_size), inst->dst.type);
4110 fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
4111 fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
4112
4113 if (devinfo->gen >= 8) {
4114 /* Until Gen8, integer multiplies read 32-bits from one source,
4115 * and 16-bits from the other, and relying on the MACH instruction
4116 * to generate the high bits of the result.
4117 *
4118 * On Gen8, the multiply instruction does a full 32x32-bit
4119 * multiply, but in order to do a 64-bit multiply we can simulate
4120 * the previous behavior and then use a MACH instruction.
4121 */
4122 assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
4123 mul->src[1].type == BRW_REGISTER_TYPE_UD);
4124 mul->src[1].type = BRW_REGISTER_TYPE_UW;
4125 mul->src[1].stride *= 2;
4126
4127 if (mul->src[1].file == IMM) {
4128 mul->src[1] = brw_imm_uw(mul->src[1].ud);
4129 }
4130 } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
4131 inst->group > 0) {
4132 /* Among other things the quarter control bits influence which
4133 * accumulator register is used by the hardware for instructions
4134 * that access the accumulator implicitly (e.g. MACH). A
4135 * second-half instruction would normally map to acc1, which
4136 * doesn't exist on Gen7 and up (the hardware does emulate it for
4137 * floating-point instructions *only* by taking advantage of the
4138 * extra precision of acc0 not normally used for floating point
4139 * arithmetic).
4140 *
4141 * HSW and up are careful enough not to try to access an
4142 * accumulator register that doesn't exist, but on earlier Gen7
4143 * hardware we need to make sure that the quarter control bits are
4144 * zero to avoid non-deterministic behaviour and emit an extra MOV
4145 * to get the result masked correctly according to the current
4146 * channel enables.
4147 */
4148 mach->group = 0;
4149 mach->force_writemask_all = true;
4150 mach->dst = ibld.vgrf(inst->dst.type);
4151 ibld.MOV(inst->dst, mach->dst);
4152 }
4153 }
4154
4155 bool
4156 fs_visitor::lower_integer_multiplication()
4157 {
4158 bool progress = false;
4159
4160 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4161 if (inst->opcode == BRW_OPCODE_MUL) {
4162 if ((inst->dst.type == BRW_REGISTER_TYPE_Q ||
4163 inst->dst.type == BRW_REGISTER_TYPE_UQ) &&
4164 (inst->src[0].type == BRW_REGISTER_TYPE_Q ||
4165 inst->src[0].type == BRW_REGISTER_TYPE_UQ) &&
4166 (inst->src[1].type == BRW_REGISTER_TYPE_Q ||
4167 inst->src[1].type == BRW_REGISTER_TYPE_UQ)) {
4168 lower_mul_qword_inst(inst, block);
4169 inst->remove(block);
4170 progress = true;
4171 } else if (!inst->dst.is_accumulator() &&
4172 (inst->dst.type == BRW_REGISTER_TYPE_D ||
4173 inst->dst.type == BRW_REGISTER_TYPE_UD) &&
4174 !devinfo->has_integer_dword_mul) {
4175 lower_mul_dword_inst(inst, block);
4176 inst->remove(block);
4177 progress = true;
4178 }
4179 } else if (inst->opcode == SHADER_OPCODE_MULH) {
4180 lower_mulh_inst(inst, block);
4181 inst->remove(block);
4182 progress = true;
4183 }
4184
4185 }
4186
4187 if (progress)
4188 invalidate_live_intervals();
4189
4190 return progress;
4191 }
4192
4193 bool
4194 fs_visitor::lower_minmax()
4195 {
4196 assert(devinfo->gen < 6);
4197
4198 bool progress = false;
4199
4200 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4201 const fs_builder ibld(this, block, inst);
4202
4203 if (inst->opcode == BRW_OPCODE_SEL &&
4204 inst->predicate == BRW_PREDICATE_NONE) {
4205 /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
4206 * the original SEL.L/GE instruction
4207 */
4208 ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4209 inst->conditional_mod);
4210 inst->predicate = BRW_PREDICATE_NORMAL;
4211 inst->conditional_mod = BRW_CONDITIONAL_NONE;
4212
4213 progress = true;
4214 }
4215 }
4216
4217 if (progress)
4218 invalidate_live_intervals();
4219
4220 return progress;
4221 }
4222
4223 static void
4224 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
4225 fs_reg *dst, fs_reg color, unsigned components)
4226 {
4227 if (key->clamp_fragment_color) {
4228 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
4229 assert(color.type == BRW_REGISTER_TYPE_F);
4230
4231 for (unsigned i = 0; i < components; i++)
4232 set_saturate(true,
4233 bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
4234
4235 color = tmp;
4236 }
4237
4238 for (unsigned i = 0; i < components; i++)
4239 dst[i] = offset(color, bld, i);
4240 }
4241
4242 uint32_t
4243 brw_fb_write_msg_control(const fs_inst *inst,
4244 const struct brw_wm_prog_data *prog_data)
4245 {
4246 uint32_t mctl;
4247
4248 if (inst->opcode == FS_OPCODE_REP_FB_WRITE) {
4249 assert(inst->group == 0 && inst->exec_size == 16);
4250 mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE_REPLICATED;
4251 } else if (prog_data->dual_src_blend) {
4252 assert(inst->exec_size == 8);
4253
4254 if (inst->group % 16 == 0)
4255 mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_DUAL_SOURCE_SUBSPAN01;
4256 else if (inst->group % 16 == 8)
4257 mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_DUAL_SOURCE_SUBSPAN23;
4258 else
4259 unreachable("Invalid dual-source FB write instruction group");
4260 } else {
4261 assert(inst->group == 0 || (inst->group == 16 && inst->exec_size == 16));
4262
4263 if (inst->exec_size == 16)
4264 mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE;
4265 else if (inst->exec_size == 8)
4266 mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_SINGLE_SOURCE_SUBSPAN01;
4267 else
4268 unreachable("Invalid FB write execution size");
4269 }
4270
4271 return mctl;
4272 }
4273
4274 static void
4275 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
4276 const struct brw_wm_prog_data *prog_data,
4277 const brw_wm_prog_key *key,
4278 const fs_visitor::thread_payload &payload)
4279 {
4280 assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
4281 const gen_device_info *devinfo = bld.shader->devinfo;
4282 const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
4283 const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
4284 const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
4285 const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
4286 const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
4287 const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
4288 fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
4289 const unsigned components =
4290 inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
4291
4292 /* We can potentially have a message length of up to 15, so we have to set
4293 * base_mrf to either 0 or 1 in order to fit in m0..m15.
4294 */
4295 fs_reg sources[15];
4296 int header_size = 2, payload_header_size;
4297 unsigned length = 0;
4298
4299 if (devinfo->gen < 6) {
4300 /* TODO: Support SIMD32 on gen4-5 */
4301 assert(bld.group() < 16);
4302
4303 /* For gen4-5, we always have a header consisting of g0 and g1. We have
4304 * an implied MOV from g0,g1 to the start of the message. The MOV from
4305 * g0 is handled by the hardware and the MOV from g1 is provided by the
4306 * generator. This is required because, on gen4-5, the generator may
4307 * generate two write messages with different message lengths in order
4308 * to handle AA data properly.
4309 *
4310 * Also, since the pixel mask goes in the g0 portion of the message and
4311 * since render target writes are the last thing in the shader, we write
4312 * the pixel mask directly into g0 and it will get copied as part of the
4313 * implied write.
4314 */
4315 if (prog_data->uses_kill) {
4316 bld.exec_all().group(1, 0)
4317 .MOV(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW),
4318 brw_flag_reg(0, 1));
4319 }
4320
4321 assert(length == 0);
4322 length = 2;
4323 } else if ((devinfo->gen <= 7 && !devinfo->is_haswell &&
4324 prog_data->uses_kill) ||
4325 (devinfo->gen < 11 &&
4326 (color1.file != BAD_FILE || key->nr_color_regions > 1))) {
4327 /* From the Sandy Bridge PRM, volume 4, page 198:
4328 *
4329 * "Dispatched Pixel Enables. One bit per pixel indicating
4330 * which pixels were originally enabled when the thread was
4331 * dispatched. This field is only required for the end-of-
4332 * thread message and on all dual-source messages."
4333 */
4334 const fs_builder ubld = bld.exec_all().group(8, 0);
4335
4336 fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
4337 if (bld.group() < 16) {
4338 /* The header starts off as g0 and g1 for the first half */
4339 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4340 BRW_REGISTER_TYPE_UD));
4341 } else {
4342 /* The header starts off as g0 and g2 for the second half */
4343 assert(bld.group() < 32);
4344 const fs_reg header_sources[2] = {
4345 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4346 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD),
4347 };
4348 ubld.LOAD_PAYLOAD(header, header_sources, 2, 0);
4349 }
4350
4351 uint32_t g00_bits = 0;
4352
4353 /* Set "Source0 Alpha Present to RenderTarget" bit in message
4354 * header.
4355 */
4356 if (inst->target > 0 && prog_data->replicate_alpha)
4357 g00_bits |= 1 << 11;
4358
4359 /* Set computes stencil to render target */
4360 if (prog_data->computed_stencil)
4361 g00_bits |= 1 << 14;
4362
4363 if (g00_bits) {
4364 /* OR extra bits into g0.0 */
4365 ubld.group(1, 0).OR(component(header, 0),
4366 retype(brw_vec1_grf(0, 0),
4367 BRW_REGISTER_TYPE_UD),
4368 brw_imm_ud(g00_bits));
4369 }
4370
4371 /* Set the render target index for choosing BLEND_STATE. */
4372 if (inst->target > 0) {
4373 ubld.group(1, 0).MOV(component(header, 2), brw_imm_ud(inst->target));
4374 }
4375
4376 if (prog_data->uses_kill) {
4377 assert(bld.group() < 16);
4378 ubld.group(1, 0).MOV(retype(component(header, 15),
4379 BRW_REGISTER_TYPE_UW),
4380 brw_flag_reg(0, 1));
4381 }
4382
4383 assert(length == 0);
4384 sources[0] = header;
4385 sources[1] = horiz_offset(header, 8);
4386 length = 2;
4387 }
4388 assert(length == 0 || length == 2);
4389 header_size = length;
4390
4391 if (payload.aa_dest_stencil_reg[0]) {
4392 assert(inst->group < 16);
4393 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
4394 bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
4395 .MOV(sources[length],
4396 fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg[0], 0)));
4397 length++;
4398 }
4399
4400 bool src0_alpha_present = false;
4401
4402 if (src0_alpha.file != BAD_FILE) {
4403 for (unsigned i = 0; i < bld.dispatch_width() / 8; i++) {
4404 const fs_builder &ubld = bld.exec_all().group(8, i)
4405 .annotate("FB write src0 alpha");
4406 const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_F);
4407 ubld.MOV(tmp, horiz_offset(src0_alpha, i * 8));
4408 setup_color_payload(ubld, key, &sources[length], tmp, 1);
4409 length++;
4410 }
4411 src0_alpha_present = true;
4412 } else if (prog_data->replicate_alpha && inst->target != 0) {
4413 /* Handle the case when fragment shader doesn't write to draw buffer
4414 * zero. No need to call setup_color_payload() for src0_alpha because
4415 * alpha value will be undefined.
4416 */
4417 length += bld.dispatch_width() / 8;
4418 src0_alpha_present = true;
4419 }
4420
4421 if (sample_mask.file != BAD_FILE) {
4422 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
4423 BRW_REGISTER_TYPE_UD);
4424
4425 /* Hand over gl_SampleMask. Only the lower 16 bits of each channel are
4426 * relevant. Since it's unsigned single words one vgrf is always
4427 * 16-wide, but only the lower or higher 8 channels will be used by the
4428 * hardware when doing a SIMD8 write depending on whether we have
4429 * selected the subspans for the first or second half respectively.
4430 */
4431 assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
4432 sample_mask.type = BRW_REGISTER_TYPE_UW;
4433 sample_mask.stride *= 2;
4434
4435 bld.exec_all().annotate("FB write oMask")
4436 .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
4437 inst->group % 16),
4438 sample_mask);
4439 length++;
4440 }
4441
4442 payload_header_size = length;
4443
4444 setup_color_payload(bld, key, &sources[length], color0, components);
4445 length += 4;
4446
4447 if (color1.file != BAD_FILE) {
4448 setup_color_payload(bld, key, &sources[length], color1, components);
4449 length += 4;
4450 }
4451
4452 if (src_depth.file != BAD_FILE) {
4453 sources[length] = src_depth;
4454 length++;
4455 }
4456
4457 if (dst_depth.file != BAD_FILE) {
4458 sources[length] = dst_depth;
4459 length++;
4460 }
4461
4462 if (src_stencil.file != BAD_FILE) {
4463 assert(devinfo->gen >= 9);
4464 assert(bld.dispatch_width() == 8);
4465
4466 /* XXX: src_stencil is only available on gen9+. dst_depth is never
4467 * available on gen9+. As such it's impossible to have both enabled at the
4468 * same time and therefore length cannot overrun the array.
4469 */
4470 assert(length < 15);
4471
4472 sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
4473 bld.exec_all().annotate("FB write OS")
4474 .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
4475 subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
4476 length++;
4477 }
4478
4479 fs_inst *load;
4480 if (devinfo->gen >= 7) {
4481 /* Send from the GRF */
4482 fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
4483 load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
4484 payload.nr = bld.shader->alloc.allocate(regs_written(load));
4485 load->dst = payload;
4486
4487 uint32_t msg_ctl = brw_fb_write_msg_control(inst, prog_data);
4488 uint32_t ex_desc = 0;
4489
4490 inst->desc =
4491 (inst->group / 16) << 11 | /* rt slot group */
4492 brw_dp_write_desc(devinfo, inst->target, msg_ctl,
4493 GEN6_DATAPORT_WRITE_MESSAGE_RENDER_TARGET_WRITE,
4494 inst->last_rt, false);
4495
4496 if (devinfo->gen >= 11) {
4497 /* Set the "Render Target Index" and "Src0 Alpha Present" fields
4498 * in the extended message descriptor, in lieu of using a header.
4499 */
4500 ex_desc = inst->target << 12 | src0_alpha_present << 15;
4501
4502 if (key->nr_color_regions == 0)
4503 ex_desc |= 1 << 20; /* Null Render Target */
4504 }
4505
4506 inst->opcode = SHADER_OPCODE_SEND;
4507 inst->resize_sources(3);
4508 inst->sfid = GEN6_SFID_DATAPORT_RENDER_CACHE;
4509 inst->src[0] = brw_imm_ud(inst->desc);
4510 inst->src[1] = brw_imm_ud(ex_desc);
4511 inst->src[2] = payload;
4512 inst->mlen = regs_written(load);
4513 inst->ex_mlen = 0;
4514 inst->header_size = header_size;
4515 inst->check_tdr = true;
4516 inst->send_has_side_effects = true;
4517 } else {
4518 /* Send from the MRF */
4519 load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
4520 sources, length, payload_header_size);
4521
4522 /* On pre-SNB, we have to interlace the color values. LOAD_PAYLOAD
4523 * will do this for us if we just give it a COMPR4 destination.
4524 */
4525 if (devinfo->gen < 6 && bld.dispatch_width() == 16)
4526 load->dst.nr |= BRW_MRF_COMPR4;
4527
4528 if (devinfo->gen < 6) {
4529 /* Set up src[0] for the implied MOV from grf0-1 */
4530 inst->resize_sources(1);
4531 inst->src[0] = brw_vec8_grf(0, 0);
4532 } else {
4533 inst->resize_sources(0);
4534 }
4535 inst->base_mrf = 1;
4536 inst->opcode = FS_OPCODE_FB_WRITE;
4537 inst->mlen = regs_written(load);
4538 inst->header_size = header_size;
4539 }
4540 }
4541
4542 static void
4543 lower_fb_read_logical_send(const fs_builder &bld, fs_inst *inst)
4544 {
4545 const fs_builder &ubld = bld.exec_all().group(8, 0);
4546 const unsigned length = 2;
4547 const fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, length);
4548
4549 if (bld.group() < 16) {
4550 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4551 BRW_REGISTER_TYPE_UD));
4552 } else {
4553 assert(bld.group() < 32);
4554 const fs_reg header_sources[] = {
4555 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4556 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD)
4557 };
4558 ubld.LOAD_PAYLOAD(header, header_sources, ARRAY_SIZE(header_sources), 0);
4559 }
4560
4561 inst->resize_sources(1);
4562 inst->src[0] = header;
4563 inst->opcode = FS_OPCODE_FB_READ;
4564 inst->mlen = length;
4565 inst->header_size = length;
4566 }
4567
4568 static void
4569 lower_sampler_logical_send_gen4(const fs_builder &bld, fs_inst *inst, opcode op,
4570 const fs_reg &coordinate,
4571 const fs_reg &shadow_c,
4572 const fs_reg &lod, const fs_reg &lod2,
4573 const fs_reg &surface,
4574 const fs_reg &sampler,
4575 unsigned coord_components,
4576 unsigned grad_components)
4577 {
4578 const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
4579 op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
4580 fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
4581 fs_reg msg_end = msg_begin;
4582
4583 /* g0 header. */
4584 msg_end = offset(msg_end, bld.group(8, 0), 1);
4585
4586 for (unsigned i = 0; i < coord_components; i++)
4587 bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
4588 offset(coordinate, bld, i));
4589
4590 msg_end = offset(msg_end, bld, coord_components);
4591
4592 /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
4593 * require all three components to be present and zero if they are unused.
4594 */
4595 if (coord_components > 0 &&
4596 (has_lod || shadow_c.file != BAD_FILE ||
4597 (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
4598 for (unsigned i = coord_components; i < 3; i++)
4599 bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
4600
4601 msg_end = offset(msg_end, bld, 3 - coord_components);
4602 }
4603
4604 if (op == SHADER_OPCODE_TXD) {
4605 /* TXD unsupported in SIMD16 mode. */
4606 assert(bld.dispatch_width() == 8);
4607
4608 /* the slots for u and v are always present, but r is optional */
4609 if (coord_components < 2)
4610 msg_end = offset(msg_end, bld, 2 - coord_components);
4611
4612 /* P = u, v, r
4613 * dPdx = dudx, dvdx, drdx
4614 * dPdy = dudy, dvdy, drdy
4615 *
4616 * 1-arg: Does not exist.
4617 *
4618 * 2-arg: dudx dvdx dudy dvdy
4619 * dPdx.x dPdx.y dPdy.x dPdy.y
4620 * m4 m5 m6 m7
4621 *
4622 * 3-arg: dudx dvdx drdx dudy dvdy drdy
4623 * dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
4624 * m5 m6 m7 m8 m9 m10
4625 */
4626 for (unsigned i = 0; i < grad_components; i++)
4627 bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
4628
4629 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4630
4631 for (unsigned i = 0; i < grad_components; i++)
4632 bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
4633
4634 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4635 }
4636
4637 if (has_lod) {
4638 /* Bias/LOD with shadow comparator is unsupported in SIMD16 -- *Without*
4639 * shadow comparator (including RESINFO) it's unsupported in SIMD8 mode.
4640 */
4641 assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
4642 bld.dispatch_width() == 16);
4643
4644 const brw_reg_type type =
4645 (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
4646 BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
4647 bld.MOV(retype(msg_end, type), lod);
4648 msg_end = offset(msg_end, bld, 1);
4649 }
4650
4651 if (shadow_c.file != BAD_FILE) {
4652 if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
4653 /* There's no plain shadow compare message, so we use shadow
4654 * compare with a bias of 0.0.
4655 */
4656 bld.MOV(msg_end, brw_imm_f(0.0f));
4657 msg_end = offset(msg_end, bld, 1);
4658 }
4659
4660 bld.MOV(msg_end, shadow_c);
4661 msg_end = offset(msg_end, bld, 1);
4662 }
4663
4664 inst->opcode = op;
4665 inst->src[0] = reg_undef;
4666 inst->src[1] = surface;
4667 inst->src[2] = sampler;
4668 inst->resize_sources(3);
4669 inst->base_mrf = msg_begin.nr;
4670 inst->mlen = msg_end.nr - msg_begin.nr;
4671 inst->header_size = 1;
4672 }
4673
4674 static void
4675 lower_sampler_logical_send_gen5(const fs_builder &bld, fs_inst *inst, opcode op,
4676 const fs_reg &coordinate,
4677 const fs_reg &shadow_c,
4678 const fs_reg &lod, const fs_reg &lod2,
4679 const fs_reg &sample_index,
4680 const fs_reg &surface,
4681 const fs_reg &sampler,
4682 unsigned coord_components,
4683 unsigned grad_components)
4684 {
4685 fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
4686 fs_reg msg_coords = message;
4687 unsigned header_size = 0;
4688
4689 if (inst->offset != 0) {
4690 /* The offsets set up by the visitor are in the m1 header, so we can't
4691 * go headerless.
4692 */
4693 header_size = 1;
4694 message.nr--;
4695 }
4696
4697 for (unsigned i = 0; i < coord_components; i++)
4698 bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
4699 offset(coordinate, bld, i));
4700
4701 fs_reg msg_end = offset(msg_coords, bld, coord_components);
4702 fs_reg msg_lod = offset(msg_coords, bld, 4);
4703
4704 if (shadow_c.file != BAD_FILE) {
4705 fs_reg msg_shadow = msg_lod;
4706 bld.MOV(msg_shadow, shadow_c);
4707 msg_lod = offset(msg_shadow, bld, 1);
4708 msg_end = msg_lod;
4709 }
4710
4711 switch (op) {
4712 case SHADER_OPCODE_TXL:
4713 case FS_OPCODE_TXB:
4714 bld.MOV(msg_lod, lod);
4715 msg_end = offset(msg_lod, bld, 1);
4716 break;
4717 case SHADER_OPCODE_TXD:
4718 /**
4719 * P = u, v, r
4720 * dPdx = dudx, dvdx, drdx
4721 * dPdy = dudy, dvdy, drdy
4722 *
4723 * Load up these values:
4724 * - dudx dudy dvdx dvdy drdx drdy
4725 * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
4726 */
4727 msg_end = msg_lod;
4728 for (unsigned i = 0; i < grad_components; i++) {
4729 bld.MOV(msg_end, offset(lod, bld, i));
4730 msg_end = offset(msg_end, bld, 1);
4731
4732 bld.MOV(msg_end, offset(lod2, bld, i));
4733 msg_end = offset(msg_end, bld, 1);
4734 }
4735 break;
4736 case SHADER_OPCODE_TXS:
4737 msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
4738 bld.MOV(msg_lod, lod);
4739 msg_end = offset(msg_lod, bld, 1);
4740 break;
4741 case SHADER_OPCODE_TXF:
4742 msg_lod = offset(msg_coords, bld, 3);
4743 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
4744 msg_end = offset(msg_lod, bld, 1);
4745 break;
4746 case SHADER_OPCODE_TXF_CMS:
4747 msg_lod = offset(msg_coords, bld, 3);
4748 /* lod */
4749 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
4750 /* sample index */
4751 bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
4752 msg_end = offset(msg_lod, bld, 2);
4753 break;
4754 default:
4755 break;
4756 }
4757
4758 inst->opcode = op;
4759 inst->src[0] = reg_undef;
4760 inst->src[1] = surface;
4761 inst->src[2] = sampler;
4762 inst->resize_sources(3);
4763 inst->base_mrf = message.nr;
4764 inst->mlen = msg_end.nr - message.nr;
4765 inst->header_size = header_size;
4766
4767 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4768 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4769 }
4770
4771 static bool
4772 is_high_sampler(const struct gen_device_info *devinfo, const fs_reg &sampler)
4773 {
4774 if (devinfo->gen < 8 && !devinfo->is_haswell)
4775 return false;
4776
4777 return sampler.file != IMM || sampler.ud >= 16;
4778 }
4779
4780 static unsigned
4781 sampler_msg_type(const gen_device_info *devinfo,
4782 opcode opcode, bool shadow_compare)
4783 {
4784 assert(devinfo->gen >= 5);
4785 switch (opcode) {
4786 case SHADER_OPCODE_TEX:
4787 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_COMPARE :
4788 GEN5_SAMPLER_MESSAGE_SAMPLE;
4789 case FS_OPCODE_TXB:
4790 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS_COMPARE :
4791 GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS;
4792 case SHADER_OPCODE_TXL:
4793 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_LOD_COMPARE :
4794 GEN5_SAMPLER_MESSAGE_SAMPLE_LOD;
4795 case SHADER_OPCODE_TXL_LZ:
4796 return shadow_compare ? GEN9_SAMPLER_MESSAGE_SAMPLE_C_LZ :
4797 GEN9_SAMPLER_MESSAGE_SAMPLE_LZ;
4798 case SHADER_OPCODE_TXS:
4799 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4800 return GEN5_SAMPLER_MESSAGE_SAMPLE_RESINFO;
4801 case SHADER_OPCODE_TXD:
4802 assert(!shadow_compare || devinfo->gen >= 8 || devinfo->is_haswell);
4803 return shadow_compare ? HSW_SAMPLER_MESSAGE_SAMPLE_DERIV_COMPARE :
4804 GEN5_SAMPLER_MESSAGE_SAMPLE_DERIVS;
4805 case SHADER_OPCODE_TXF:
4806 return GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4807 case SHADER_OPCODE_TXF_LZ:
4808 assert(devinfo->gen >= 9);
4809 return GEN9_SAMPLER_MESSAGE_SAMPLE_LD_LZ;
4810 case SHADER_OPCODE_TXF_CMS_W:
4811 assert(devinfo->gen >= 9);
4812 return GEN9_SAMPLER_MESSAGE_SAMPLE_LD2DMS_W;
4813 case SHADER_OPCODE_TXF_CMS:
4814 return devinfo->gen >= 7 ? GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DMS :
4815 GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4816 case SHADER_OPCODE_TXF_UMS:
4817 assert(devinfo->gen >= 7);
4818 return GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DSS;
4819 case SHADER_OPCODE_TXF_MCS:
4820 assert(devinfo->gen >= 7);
4821 return GEN7_SAMPLER_MESSAGE_SAMPLE_LD_MCS;
4822 case SHADER_OPCODE_LOD:
4823 return GEN5_SAMPLER_MESSAGE_LOD;
4824 case SHADER_OPCODE_TG4:
4825 assert(devinfo->gen >= 7);
4826 return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_C :
4827 GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4;
4828 break;
4829 case SHADER_OPCODE_TG4_OFFSET:
4830 assert(devinfo->gen >= 7);
4831 return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO_C :
4832 GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO;
4833 case SHADER_OPCODE_SAMPLEINFO:
4834 return GEN6_SAMPLER_MESSAGE_SAMPLE_SAMPLEINFO;
4835 default:
4836 unreachable("not reached");
4837 }
4838 }
4839
4840 static void
4841 lower_sampler_logical_send_gen7(const fs_builder &bld, fs_inst *inst, opcode op,
4842 const fs_reg &coordinate,
4843 const fs_reg &shadow_c,
4844 fs_reg lod, const fs_reg &lod2,
4845 const fs_reg &min_lod,
4846 const fs_reg &sample_index,
4847 const fs_reg &mcs,
4848 const fs_reg &surface,
4849 const fs_reg &sampler,
4850 const fs_reg &surface_handle,
4851 const fs_reg &sampler_handle,
4852 const fs_reg &tg4_offset,
4853 unsigned coord_components,
4854 unsigned grad_components)
4855 {
4856 const gen_device_info *devinfo = bld.shader->devinfo;
4857 const brw_stage_prog_data *prog_data = bld.shader->stage_prog_data;
4858 unsigned reg_width = bld.dispatch_width() / 8;
4859 unsigned header_size = 0, length = 0;
4860 fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
4861 for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
4862 sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
4863
4864 /* We must have exactly one of surface/sampler and surface/sampler_handle */
4865 assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
4866 assert((sampler.file == BAD_FILE) != (sampler_handle.file == BAD_FILE));
4867
4868 if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
4869 inst->offset != 0 || inst->eot ||
4870 op == SHADER_OPCODE_SAMPLEINFO ||
4871 sampler_handle.file != BAD_FILE ||
4872 is_high_sampler(devinfo, sampler)) {
4873 /* For general texture offsets (no txf workaround), we need a header to
4874 * put them in.
4875 *
4876 * TG4 needs to place its channel select in the header, for interaction
4877 * with ARB_texture_swizzle. The sampler index is only 4-bits, so for
4878 * larger sampler numbers we need to offset the Sampler State Pointer in
4879 * the header.
4880 */
4881 fs_reg header = retype(sources[0], BRW_REGISTER_TYPE_UD);
4882 header_size = 1;
4883 length++;
4884
4885 /* If we're requesting fewer than four channels worth of response,
4886 * and we have an explicit header, we need to set up the sampler
4887 * writemask. It's reversed from normal: 1 means "don't write".
4888 */
4889 if (!inst->eot && regs_written(inst) != 4 * reg_width) {
4890 assert(regs_written(inst) % reg_width == 0);
4891 unsigned mask = ~((1 << (regs_written(inst) / reg_width)) - 1) & 0xf;
4892 inst->offset |= mask << 12;
4893 }
4894
4895 /* Build the actual header */
4896 const fs_builder ubld = bld.exec_all().group(8, 0);
4897 const fs_builder ubld1 = ubld.group(1, 0);
4898 ubld.MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
4899 if (inst->offset) {
4900 ubld1.MOV(component(header, 2), brw_imm_ud(inst->offset));
4901 } else if (bld.shader->stage != MESA_SHADER_VERTEX &&
4902 bld.shader->stage != MESA_SHADER_FRAGMENT) {
4903 /* The vertex and fragment stages have g0.2 set to 0, so
4904 * header0.2 is 0 when g0 is copied. Other stages may not, so we
4905 * must set it to 0 to avoid setting undesirable bits in the
4906 * message.
4907 */
4908 ubld1.MOV(component(header, 2), brw_imm_ud(0));
4909 }
4910
4911 if (sampler_handle.file != BAD_FILE) {
4912 /* Bindless sampler handles aren't relative to the sampler state
4913 * pointer passed into the shader through SAMPLER_STATE_POINTERS_*.
4914 * Instead, it's an absolute pointer relative to dynamic state base
4915 * address.
4916 *
4917 * Sampler states are 16 bytes each and the pointer we give here has
4918 * to be 32-byte aligned. In order to avoid more indirect messages
4919 * than required, we assume that all bindless sampler states are
4920 * 32-byte aligned. This sacrifices a bit of general state base
4921 * address space but means we can do something more efficient in the
4922 * shader.
4923 */
4924 ubld1.MOV(component(header, 3), sampler_handle);
4925 } else if (is_high_sampler(devinfo, sampler)) {
4926 if (sampler.file == BRW_IMMEDIATE_VALUE) {
4927 assert(sampler.ud >= 16);
4928 const int sampler_state_size = 16; /* 16 bytes */
4929
4930 ubld1.ADD(component(header, 3),
4931 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4932 brw_imm_ud(16 * (sampler.ud / 16) * sampler_state_size));
4933 } else {
4934 fs_reg tmp = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
4935 ubld1.AND(tmp, sampler, brw_imm_ud(0x0f0));
4936 ubld1.SHL(tmp, tmp, brw_imm_ud(4));
4937 ubld1.ADD(component(header, 3),
4938 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4939 tmp);
4940 }
4941 }
4942 }
4943
4944 if (shadow_c.file != BAD_FILE) {
4945 bld.MOV(sources[length], shadow_c);
4946 length++;
4947 }
4948
4949 bool coordinate_done = false;
4950
4951 /* Set up the LOD info */
4952 switch (op) {
4953 case FS_OPCODE_TXB:
4954 case SHADER_OPCODE_TXL:
4955 if (devinfo->gen >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
4956 op = SHADER_OPCODE_TXL_LZ;
4957 break;
4958 }
4959 bld.MOV(sources[length], lod);
4960 length++;
4961 break;
4962 case SHADER_OPCODE_TXD:
4963 /* TXD should have been lowered in SIMD16 mode. */
4964 assert(bld.dispatch_width() == 8);
4965
4966 /* Load dPdx and the coordinate together:
4967 * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
4968 */
4969 for (unsigned i = 0; i < coord_components; i++) {
4970 bld.MOV(sources[length++], offset(coordinate, bld, i));
4971
4972 /* For cube map array, the coordinate is (u,v,r,ai) but there are
4973 * only derivatives for (u, v, r).
4974 */
4975 if (i < grad_components) {
4976 bld.MOV(sources[length++], offset(lod, bld, i));
4977 bld.MOV(sources[length++], offset(lod2, bld, i));
4978 }
4979 }
4980
4981 coordinate_done = true;
4982 break;
4983 case SHADER_OPCODE_TXS:
4984 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
4985 length++;
4986 break;
4987 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4988 /* We need an LOD; just use 0 */
4989 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), brw_imm_ud(0));
4990 length++;
4991 break;
4992 case SHADER_OPCODE_TXF:
4993 /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
4994 * On Gen9 they are u, v, lod, r
4995 */
4996 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
4997
4998 if (devinfo->gen >= 9) {
4999 if (coord_components >= 2) {
5000 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
5001 offset(coordinate, bld, 1));
5002 } else {
5003 sources[length] = brw_imm_d(0);
5004 }
5005 length++;
5006 }
5007
5008 if (devinfo->gen >= 9 && lod.is_zero()) {
5009 op = SHADER_OPCODE_TXF_LZ;
5010 } else {
5011 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
5012 length++;
5013 }
5014
5015 for (unsigned i = devinfo->gen >= 9 ? 2 : 1; i < coord_components; i++)
5016 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
5017 offset(coordinate, bld, i));
5018
5019 coordinate_done = true;
5020 break;
5021
5022 case SHADER_OPCODE_TXF_CMS:
5023 case SHADER_OPCODE_TXF_CMS_W:
5024 case SHADER_OPCODE_TXF_UMS:
5025 case SHADER_OPCODE_TXF_MCS:
5026 if (op == SHADER_OPCODE_TXF_UMS ||
5027 op == SHADER_OPCODE_TXF_CMS ||
5028 op == SHADER_OPCODE_TXF_CMS_W) {
5029 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
5030 length++;
5031 }
5032
5033 if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
5034 /* Data from the multisample control surface. */
5035 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
5036 length++;
5037
5038 /* On Gen9+ we'll use ld2dms_w instead which has two registers for
5039 * the MCS data.
5040 */
5041 if (op == SHADER_OPCODE_TXF_CMS_W) {
5042 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
5043 mcs.file == IMM ?
5044 mcs :
5045 offset(mcs, bld, 1));
5046 length++;
5047 }
5048 }
5049
5050 /* There is no offsetting for this message; just copy in the integer
5051 * texture coordinates.
5052 */
5053 for (unsigned i = 0; i < coord_components; i++)
5054 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
5055 offset(coordinate, bld, i));
5056
5057 coordinate_done = true;
5058 break;
5059 case SHADER_OPCODE_TG4_OFFSET:
5060 /* More crazy intermixing */
5061 for (unsigned i = 0; i < 2; i++) /* u, v */
5062 bld.MOV(sources[length++], offset(coordinate, bld, i));
5063
5064 for (unsigned i = 0; i < 2; i++) /* offu, offv */
5065 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
5066 offset(tg4_offset, bld, i));
5067
5068 if (coord_components == 3) /* r if present */
5069 bld.MOV(sources[length++], offset(coordinate, bld, 2));
5070
5071 coordinate_done = true;
5072 break;
5073 default:
5074 break;
5075 }
5076
5077 /* Set up the coordinate (except for cases where it was done above) */
5078 if (!coordinate_done) {
5079 for (unsigned i = 0; i < coord_components; i++)
5080 bld.MOV(sources[length++], offset(coordinate, bld, i));
5081 }
5082
5083 if (min_lod.file != BAD_FILE) {
5084 /* Account for all of the missing coordinate sources */
5085 length += 4 - coord_components;
5086 if (op == SHADER_OPCODE_TXD)
5087 length += (3 - grad_components) * 2;
5088
5089 bld.MOV(sources[length++], min_lod);
5090 }
5091
5092 unsigned mlen;
5093 if (reg_width == 2)
5094 mlen = length * reg_width - header_size;
5095 else
5096 mlen = length * reg_width;
5097
5098 const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
5099 BRW_REGISTER_TYPE_F);
5100 bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
5101
5102 /* Generate the SEND. */
5103 inst->opcode = SHADER_OPCODE_SEND;
5104 inst->mlen = mlen;
5105 inst->header_size = header_size;
5106
5107 const unsigned msg_type =
5108 sampler_msg_type(devinfo, op, inst->shadow_compare);
5109 const unsigned simd_mode =
5110 inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
5111 BRW_SAMPLER_SIMD_MODE_SIMD16;
5112
5113 uint32_t base_binding_table_index;
5114 switch (op) {
5115 case SHADER_OPCODE_TG4:
5116 case SHADER_OPCODE_TG4_OFFSET:
5117 base_binding_table_index = prog_data->binding_table.gather_texture_start;
5118 break;
5119 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5120 base_binding_table_index = prog_data->binding_table.image_start;
5121 break;
5122 default:
5123 base_binding_table_index = prog_data->binding_table.texture_start;
5124 break;
5125 }
5126
5127 inst->sfid = BRW_SFID_SAMPLER;
5128 if (surface.file == IMM &&
5129 (sampler.file == IMM || sampler_handle.file != BAD_FILE)) {
5130 inst->desc = brw_sampler_desc(devinfo,
5131 surface.ud + base_binding_table_index,
5132 sampler.file == IMM ? sampler.ud % 16 : 0,
5133 msg_type,
5134 simd_mode,
5135 0 /* return_format unused on gen7+ */);
5136 inst->src[0] = brw_imm_ud(0);
5137 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5138 } else if (surface_handle.file != BAD_FILE) {
5139 /* Bindless surface */
5140 assert(devinfo->gen >= 9);
5141 inst->desc = brw_sampler_desc(devinfo,
5142 GEN9_BTI_BINDLESS,
5143 sampler.file == IMM ? sampler.ud % 16 : 0,
5144 msg_type,
5145 simd_mode,
5146 0 /* return_format unused on gen7+ */);
5147
5148 /* For bindless samplers, the entire address is included in the message
5149 * header so we can leave the portion in the message descriptor 0.
5150 */
5151 if (sampler_handle.file != BAD_FILE || sampler.file == IMM) {
5152 inst->src[0] = brw_imm_ud(0);
5153 } else {
5154 const fs_builder ubld = bld.group(1, 0).exec_all();
5155 fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5156 ubld.SHL(desc, sampler, brw_imm_ud(8));
5157 inst->src[0] = desc;
5158 }
5159
5160 /* We assume that the driver provided the handle in the top 20 bits so
5161 * we can use the surface handle directly as the extended descriptor.
5162 */
5163 inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5164 } else {
5165 /* Immediate portion of the descriptor */
5166 inst->desc = brw_sampler_desc(devinfo,
5167 0, /* surface */
5168 0, /* sampler */
5169 msg_type,
5170 simd_mode,
5171 0 /* return_format unused on gen7+ */);
5172 const fs_builder ubld = bld.group(1, 0).exec_all();
5173 fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5174 if (surface.equals(sampler)) {
5175 /* This case is common in GL */
5176 ubld.MUL(desc, surface, brw_imm_ud(0x101));
5177 } else {
5178 if (sampler_handle.file != BAD_FILE) {
5179 ubld.MOV(desc, surface);
5180 } else if (sampler.file == IMM) {
5181 ubld.OR(desc, surface, brw_imm_ud(sampler.ud << 8));
5182 } else {
5183 ubld.SHL(desc, sampler, brw_imm_ud(8));
5184 ubld.OR(desc, desc, surface);
5185 }
5186 }
5187 if (base_binding_table_index)
5188 ubld.ADD(desc, desc, brw_imm_ud(base_binding_table_index));
5189 ubld.AND(desc, desc, brw_imm_ud(0xfff));
5190
5191 inst->src[0] = component(desc, 0);
5192 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5193 }
5194
5195 inst->src[2] = src_payload;
5196 inst->resize_sources(3);
5197
5198 if (inst->eot) {
5199 /* EOT sampler messages don't make sense to split because it would
5200 * involve ending half of the thread early.
5201 */
5202 assert(inst->group == 0);
5203 /* We need to use SENDC for EOT sampler messages */
5204 inst->check_tdr = true;
5205 inst->send_has_side_effects = true;
5206 }
5207
5208 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
5209 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
5210 }
5211
5212 static void
5213 lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
5214 {
5215 const gen_device_info *devinfo = bld.shader->devinfo;
5216 const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
5217 const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
5218 const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
5219 const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
5220 const fs_reg &min_lod = inst->src[TEX_LOGICAL_SRC_MIN_LOD];
5221 const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
5222 const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
5223 const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
5224 const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
5225 const fs_reg &surface_handle = inst->src[TEX_LOGICAL_SRC_SURFACE_HANDLE];
5226 const fs_reg &sampler_handle = inst->src[TEX_LOGICAL_SRC_SAMPLER_HANDLE];
5227 const fs_reg &tg4_offset = inst->src[TEX_LOGICAL_SRC_TG4_OFFSET];
5228 assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
5229 const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
5230 assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
5231 const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
5232
5233 if (devinfo->gen >= 7) {
5234 lower_sampler_logical_send_gen7(bld, inst, op, coordinate,
5235 shadow_c, lod, lod2, min_lod,
5236 sample_index,
5237 mcs, surface, sampler,
5238 surface_handle, sampler_handle,
5239 tg4_offset,
5240 coord_components, grad_components);
5241 } else if (devinfo->gen >= 5) {
5242 lower_sampler_logical_send_gen5(bld, inst, op, coordinate,
5243 shadow_c, lod, lod2, sample_index,
5244 surface, sampler,
5245 coord_components, grad_components);
5246 } else {
5247 lower_sampler_logical_send_gen4(bld, inst, op, coordinate,
5248 shadow_c, lod, lod2,
5249 surface, sampler,
5250 coord_components, grad_components);
5251 }
5252 }
5253
5254 /**
5255 * Initialize the header present in some typed and untyped surface
5256 * messages.
5257 */
5258 static fs_reg
5259 emit_surface_header(const fs_builder &bld, const fs_reg &sample_mask)
5260 {
5261 fs_builder ubld = bld.exec_all().group(8, 0);
5262 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5263 ubld.MOV(dst, brw_imm_d(0));
5264 ubld.group(1, 0).MOV(component(dst, 7), sample_mask);
5265 return dst;
5266 }
5267
5268 static void
5269 lower_surface_logical_send(const fs_builder &bld, fs_inst *inst)
5270 {
5271 const gen_device_info *devinfo = bld.shader->devinfo;
5272
5273 /* Get the logical send arguments. */
5274 const fs_reg &addr = inst->src[SURFACE_LOGICAL_SRC_ADDRESS];
5275 const fs_reg &src = inst->src[SURFACE_LOGICAL_SRC_DATA];
5276 const fs_reg &surface = inst->src[SURFACE_LOGICAL_SRC_SURFACE];
5277 const fs_reg &surface_handle = inst->src[SURFACE_LOGICAL_SRC_SURFACE_HANDLE];
5278 const UNUSED fs_reg &dims = inst->src[SURFACE_LOGICAL_SRC_IMM_DIMS];
5279 const fs_reg &arg = inst->src[SURFACE_LOGICAL_SRC_IMM_ARG];
5280 assert(arg.file == IMM);
5281
5282 /* We must have exactly one of surface and surface_handle */
5283 assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
5284
5285 /* Calculate the total number of components of the payload. */
5286 const unsigned addr_sz = inst->components_read(SURFACE_LOGICAL_SRC_ADDRESS);
5287 const unsigned src_sz = inst->components_read(SURFACE_LOGICAL_SRC_DATA);
5288
5289 const bool is_typed_access =
5290 inst->opcode == SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL ||
5291 inst->opcode == SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL ||
5292 inst->opcode == SHADER_OPCODE_TYPED_ATOMIC_LOGICAL;
5293
5294 /* From the BDW PRM Volume 7, page 147:
5295 *
5296 * "For the Data Cache Data Port*, the header must be present for the
5297 * following message types: [...] Typed read/write/atomics"
5298 *
5299 * Earlier generations have a similar wording. Because of this restriction
5300 * we don't attempt to implement sample masks via predication for such
5301 * messages prior to Gen9, since we have to provide a header anyway. On
5302 * Gen11+ the header has been removed so we can only use predication.
5303 */
5304 const unsigned header_sz = devinfo->gen < 9 && is_typed_access ? 1 : 0;
5305
5306 const bool has_side_effects = inst->has_side_effects();
5307 fs_reg sample_mask = has_side_effects ? bld.sample_mask_reg() :
5308 fs_reg(brw_imm_d(0xffff));
5309
5310 fs_reg payload, payload2;
5311 unsigned mlen, ex_mlen = 0;
5312 if (devinfo->gen >= 9) {
5313 /* We have split sends on gen9 and above */
5314 assert(header_sz == 0);
5315 payload = bld.move_to_vgrf(addr, addr_sz);
5316 payload2 = bld.move_to_vgrf(src, src_sz);
5317 mlen = addr_sz * (inst->exec_size / 8);
5318 ex_mlen = src_sz * (inst->exec_size / 8);
5319 } else {
5320 /* Allocate space for the payload. */
5321 const unsigned sz = header_sz + addr_sz + src_sz;
5322 payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
5323 fs_reg *const components = new fs_reg[sz];
5324 unsigned n = 0;
5325
5326 /* Construct the payload. */
5327 if (header_sz)
5328 components[n++] = emit_surface_header(bld, sample_mask);
5329
5330 for (unsigned i = 0; i < addr_sz; i++)
5331 components[n++] = offset(addr, bld, i);
5332
5333 for (unsigned i = 0; i < src_sz; i++)
5334 components[n++] = offset(src, bld, i);
5335
5336 bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
5337 mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
5338
5339 delete[] components;
5340 }
5341
5342 /* Predicate the instruction on the sample mask if no header is
5343 * provided.
5344 */
5345 if (!header_sz && sample_mask.file != BAD_FILE &&
5346 sample_mask.file != IMM) {
5347 const fs_builder ubld = bld.group(1, 0).exec_all();
5348 if (inst->predicate) {
5349 assert(inst->predicate == BRW_PREDICATE_NORMAL);
5350 assert(!inst->predicate_inverse);
5351 assert(inst->flag_subreg < 2);
5352 /* Combine the sample mask with the existing predicate by using a
5353 * vertical predication mode.
5354 */
5355 inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
5356 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg + 2),
5357 sample_mask.type),
5358 sample_mask);
5359 } else {
5360 inst->flag_subreg = 2;
5361 inst->predicate = BRW_PREDICATE_NORMAL;
5362 inst->predicate_inverse = false;
5363 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5364 sample_mask);
5365 }
5366 }
5367
5368 uint32_t sfid;
5369 switch (inst->opcode) {
5370 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5371 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5372 /* Byte scattered opcodes go through the normal data cache */
5373 sfid = GEN7_SFID_DATAPORT_DATA_CACHE;
5374 break;
5375
5376 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5377 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5378 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5379 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5380 /* Untyped Surface messages go through the data cache but the SFID value
5381 * changed on Haswell.
5382 */
5383 sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5384 HSW_SFID_DATAPORT_DATA_CACHE_1 :
5385 GEN7_SFID_DATAPORT_DATA_CACHE);
5386 break;
5387
5388 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5389 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5390 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5391 /* Typed surface messages go through the render cache on IVB and the
5392 * data cache on HSW+.
5393 */
5394 sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5395 HSW_SFID_DATAPORT_DATA_CACHE_1 :
5396 GEN6_SFID_DATAPORT_RENDER_CACHE);
5397 break;
5398
5399 default:
5400 unreachable("Unsupported surface opcode");
5401 }
5402
5403 uint32_t desc;
5404 switch (inst->opcode) {
5405 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5406 desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5407 arg.ud, /* num_channels */
5408 false /* write */);
5409 break;
5410
5411 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5412 desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5413 arg.ud, /* num_channels */
5414 true /* write */);
5415 break;
5416
5417 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5418 desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5419 arg.ud, /* bit_size */
5420 false /* write */);
5421 break;
5422
5423 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5424 desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5425 arg.ud, /* bit_size */
5426 true /* write */);
5427 break;
5428
5429 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5430 desc = brw_dp_untyped_atomic_desc(devinfo, inst->exec_size,
5431 arg.ud, /* atomic_op */
5432 !inst->dst.is_null());
5433 break;
5434
5435 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5436 desc = brw_dp_untyped_atomic_float_desc(devinfo, inst->exec_size,
5437 arg.ud, /* atomic_op */
5438 !inst->dst.is_null());
5439 break;
5440
5441 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5442 desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5443 arg.ud, /* num_channels */
5444 false /* write */);
5445 break;
5446
5447 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5448 desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5449 arg.ud, /* num_channels */
5450 true /* write */);
5451 break;
5452
5453 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5454 desc = brw_dp_typed_atomic_desc(devinfo, inst->exec_size, inst->group,
5455 arg.ud, /* atomic_op */
5456 !inst->dst.is_null());
5457 break;
5458
5459 default:
5460 unreachable("Unknown surface logical instruction");
5461 }
5462
5463 /* Update the original instruction. */
5464 inst->opcode = SHADER_OPCODE_SEND;
5465 inst->mlen = mlen;
5466 inst->ex_mlen = ex_mlen;
5467 inst->header_size = header_sz;
5468 inst->send_has_side_effects = has_side_effects;
5469 inst->send_is_volatile = !has_side_effects;
5470
5471 /* Set up SFID and descriptors */
5472 inst->sfid = sfid;
5473 inst->desc = desc;
5474 if (surface.file == IMM) {
5475 inst->desc |= surface.ud & 0xff;
5476 inst->src[0] = brw_imm_ud(0);
5477 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5478 } else if (surface_handle.file != BAD_FILE) {
5479 /* Bindless surface */
5480 assert(devinfo->gen >= 9);
5481 inst->desc |= GEN9_BTI_BINDLESS;
5482 inst->src[0] = brw_imm_ud(0);
5483
5484 /* We assume that the driver provided the handle in the top 20 bits so
5485 * we can use the surface handle directly as the extended descriptor.
5486 */
5487 inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5488 } else {
5489 const fs_builder ubld = bld.exec_all().group(1, 0);
5490 fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5491 ubld.AND(tmp, surface, brw_imm_ud(0xff));
5492 inst->src[0] = component(tmp, 0);
5493 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5494 }
5495
5496 /* Finally, the payload */
5497 inst->src[2] = payload;
5498 inst->src[3] = payload2;
5499
5500 inst->resize_sources(4);
5501 }
5502
5503 static void
5504 lower_a64_logical_send(const fs_builder &bld, fs_inst *inst)
5505 {
5506 const gen_device_info *devinfo = bld.shader->devinfo;
5507
5508 const fs_reg &addr = inst->src[0];
5509 const fs_reg &src = inst->src[1];
5510 const unsigned src_comps = inst->components_read(1);
5511 assert(inst->src[2].file == IMM);
5512 const unsigned arg = inst->src[2].ud;
5513 const bool has_side_effects = inst->has_side_effects();
5514
5515 /* If the surface message has side effects and we're a fragment shader, we
5516 * have to predicate with the sample mask to avoid helper invocations.
5517 */
5518 if (has_side_effects && bld.shader->stage == MESA_SHADER_FRAGMENT) {
5519 inst->flag_subreg = 2;
5520 inst->predicate = BRW_PREDICATE_NORMAL;
5521 inst->predicate_inverse = false;
5522
5523 fs_reg sample_mask = bld.sample_mask_reg();
5524 const fs_builder ubld = bld.group(1, 0).exec_all();
5525 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5526 sample_mask);
5527 }
5528
5529 fs_reg payload, payload2;
5530 unsigned mlen, ex_mlen = 0;
5531 if (devinfo->gen >= 9) {
5532 /* On Skylake and above, we have SENDS */
5533 mlen = 2 * (inst->exec_size / 8);
5534 ex_mlen = src_comps * type_sz(src.type) * inst->exec_size / REG_SIZE;
5535 payload = retype(bld.move_to_vgrf(addr, 1), BRW_REGISTER_TYPE_UD);
5536 payload2 = retype(bld.move_to_vgrf(src, src_comps),
5537 BRW_REGISTER_TYPE_UD);
5538 } else {
5539 /* Add two because the address is 64-bit */
5540 const unsigned dwords = 2 + src_comps;
5541 mlen = dwords * (inst->exec_size / 8);
5542
5543 fs_reg sources[5];
5544
5545 sources[0] = addr;
5546
5547 for (unsigned i = 0; i < src_comps; i++)
5548 sources[1 + i] = offset(src, bld, i);
5549
5550 payload = bld.vgrf(BRW_REGISTER_TYPE_UD, dwords);
5551 bld.LOAD_PAYLOAD(payload, sources, 1 + src_comps, 0);
5552 }
5553
5554 uint32_t desc;
5555 switch (inst->opcode) {
5556 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5557 desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5558 arg, /* num_channels */
5559 false /* write */);
5560 break;
5561
5562 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5563 desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5564 arg, /* num_channels */
5565 true /* write */);
5566 break;
5567
5568 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5569 desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5570 arg, /* bit_size */
5571 false /* write */);
5572 break;
5573
5574 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5575 desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5576 arg, /* bit_size */
5577 true /* write */);
5578 break;
5579
5580 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5581 desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 32,
5582 arg, /* atomic_op */
5583 !inst->dst.is_null());
5584 break;
5585
5586 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
5587 desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 64,
5588 arg, /* atomic_op */
5589 !inst->dst.is_null());
5590 break;
5591
5592
5593 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5594 desc = brw_dp_a64_untyped_atomic_float_desc(devinfo, inst->exec_size,
5595 arg, /* atomic_op */
5596 !inst->dst.is_null());
5597 break;
5598
5599 default:
5600 unreachable("Unknown A64 logical instruction");
5601 }
5602
5603 /* Update the original instruction. */
5604 inst->opcode = SHADER_OPCODE_SEND;
5605 inst->mlen = mlen;
5606 inst->ex_mlen = ex_mlen;
5607 inst->header_size = 0;
5608 inst->send_has_side_effects = has_side_effects;
5609 inst->send_is_volatile = !has_side_effects;
5610
5611 /* Set up SFID and descriptors */
5612 inst->sfid = HSW_SFID_DATAPORT_DATA_CACHE_1;
5613 inst->desc = desc;
5614 inst->resize_sources(4);
5615 inst->src[0] = brw_imm_ud(0); /* desc */
5616 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5617 inst->src[2] = payload;
5618 inst->src[3] = payload2;
5619 }
5620
5621 static void
5622 lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
5623 {
5624 const gen_device_info *devinfo = bld.shader->devinfo;
5625
5626 if (devinfo->gen >= 7) {
5627 fs_reg index = inst->src[0];
5628 /* We are switching the instruction from an ALU-like instruction to a
5629 * send-from-grf instruction. Since sends can't handle strides or
5630 * source modifiers, we have to make a copy of the offset source.
5631 */
5632 fs_reg offset = bld.vgrf(BRW_REGISTER_TYPE_UD);
5633 bld.MOV(offset, inst->src[1]);
5634
5635 const unsigned simd_mode =
5636 inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
5637 BRW_SAMPLER_SIMD_MODE_SIMD16;
5638
5639 inst->opcode = SHADER_OPCODE_SEND;
5640 inst->mlen = inst->exec_size / 8;
5641 inst->resize_sources(3);
5642
5643 inst->sfid = BRW_SFID_SAMPLER;
5644 inst->desc = brw_sampler_desc(devinfo, 0, 0,
5645 GEN5_SAMPLER_MESSAGE_SAMPLE_LD,
5646 simd_mode, 0);
5647 if (index.file == IMM) {
5648 inst->desc |= index.ud & 0xff;
5649 inst->src[0] = brw_imm_ud(0);
5650 } else {
5651 const fs_builder ubld = bld.exec_all().group(1, 0);
5652 fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5653 ubld.AND(tmp, index, brw_imm_ud(0xff));
5654 inst->src[0] = component(tmp, 0);
5655 }
5656 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5657 inst->src[2] = offset; /* payload */
5658 } else {
5659 const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->gen),
5660 BRW_REGISTER_TYPE_UD);
5661
5662 bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
5663
5664 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4;
5665 inst->resize_sources(1);
5666 inst->base_mrf = payload.nr;
5667 inst->header_size = 1;
5668 inst->mlen = 1 + inst->exec_size / 8;
5669 }
5670 }
5671
5672 static void
5673 lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
5674 {
5675 assert(bld.shader->devinfo->gen < 6);
5676
5677 inst->base_mrf = 2;
5678 inst->mlen = inst->sources * inst->exec_size / 8;
5679
5680 if (inst->sources > 1) {
5681 /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
5682 * "Message Payload":
5683 *
5684 * "Operand0[7]. For the INT DIV functions, this operand is the
5685 * denominator."
5686 * ...
5687 * "Operand1[7]. For the INT DIV functions, this operand is the
5688 * numerator."
5689 */
5690 const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
5691 const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
5692 const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
5693
5694 inst->resize_sources(1);
5695 inst->src[0] = src0;
5696
5697 assert(inst->exec_size == 8);
5698 bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
5699 }
5700 }
5701
5702 bool
5703 fs_visitor::lower_logical_sends()
5704 {
5705 bool progress = false;
5706
5707 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5708 const fs_builder ibld(this, block, inst);
5709
5710 switch (inst->opcode) {
5711 case FS_OPCODE_FB_WRITE_LOGICAL:
5712 assert(stage == MESA_SHADER_FRAGMENT);
5713 lower_fb_write_logical_send(ibld, inst,
5714 brw_wm_prog_data(prog_data),
5715 (const brw_wm_prog_key *)key,
5716 payload);
5717 break;
5718
5719 case FS_OPCODE_FB_READ_LOGICAL:
5720 lower_fb_read_logical_send(ibld, inst);
5721 break;
5722
5723 case SHADER_OPCODE_TEX_LOGICAL:
5724 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
5725 break;
5726
5727 case SHADER_OPCODE_TXD_LOGICAL:
5728 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
5729 break;
5730
5731 case SHADER_OPCODE_TXF_LOGICAL:
5732 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
5733 break;
5734
5735 case SHADER_OPCODE_TXL_LOGICAL:
5736 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
5737 break;
5738
5739 case SHADER_OPCODE_TXS_LOGICAL:
5740 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
5741 break;
5742
5743 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5744 lower_sampler_logical_send(ibld, inst,
5745 SHADER_OPCODE_IMAGE_SIZE_LOGICAL);
5746 break;
5747
5748 case FS_OPCODE_TXB_LOGICAL:
5749 lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
5750 break;
5751
5752 case SHADER_OPCODE_TXF_CMS_LOGICAL:
5753 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
5754 break;
5755
5756 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
5757 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
5758 break;
5759
5760 case SHADER_OPCODE_TXF_UMS_LOGICAL:
5761 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
5762 break;
5763
5764 case SHADER_OPCODE_TXF_MCS_LOGICAL:
5765 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
5766 break;
5767
5768 case SHADER_OPCODE_LOD_LOGICAL:
5769 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
5770 break;
5771
5772 case SHADER_OPCODE_TG4_LOGICAL:
5773 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
5774 break;
5775
5776 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
5777 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
5778 break;
5779
5780 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
5781 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
5782 break;
5783
5784 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5785 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5786 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5787 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5788 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5789 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5790 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5791 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5792 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5793 lower_surface_logical_send(ibld, inst);
5794 break;
5795
5796 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5797 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5798 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5799 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5800 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5801 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
5802 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5803 lower_a64_logical_send(ibld, inst);
5804 break;
5805
5806 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
5807 lower_varying_pull_constant_logical_send(ibld, inst);
5808 break;
5809
5810 case SHADER_OPCODE_RCP:
5811 case SHADER_OPCODE_RSQ:
5812 case SHADER_OPCODE_SQRT:
5813 case SHADER_OPCODE_EXP2:
5814 case SHADER_OPCODE_LOG2:
5815 case SHADER_OPCODE_SIN:
5816 case SHADER_OPCODE_COS:
5817 case SHADER_OPCODE_POW:
5818 case SHADER_OPCODE_INT_QUOTIENT:
5819 case SHADER_OPCODE_INT_REMAINDER:
5820 /* The math opcodes are overloaded for the send-like and
5821 * expression-like instructions which seems kind of icky. Gen6+ has
5822 * a native (but rather quirky) MATH instruction so we don't need to
5823 * do anything here. On Gen4-5 we'll have to lower the Gen6-like
5824 * logical instructions (which we can easily recognize because they
5825 * have mlen = 0) into send-like virtual instructions.
5826 */
5827 if (devinfo->gen < 6 && inst->mlen == 0) {
5828 lower_math_logical_send(ibld, inst);
5829 break;
5830
5831 } else {
5832 continue;
5833 }
5834
5835 default:
5836 continue;
5837 }
5838
5839 progress = true;
5840 }
5841
5842 if (progress)
5843 invalidate_live_intervals();
5844
5845 return progress;
5846 }
5847
5848 static bool
5849 is_mixed_float_with_fp32_dst(const fs_inst *inst)
5850 {
5851 /* This opcode sometimes uses :W type on the source even if the operand is
5852 * a :HF, because in gen7 there is no support for :HF, and thus it uses :W.
5853 */
5854 if (inst->opcode == BRW_OPCODE_F16TO32)
5855 return true;
5856
5857 if (inst->dst.type != BRW_REGISTER_TYPE_F)
5858 return false;
5859
5860 for (int i = 0; i < inst->sources; i++) {
5861 if (inst->src[i].type == BRW_REGISTER_TYPE_HF)
5862 return true;
5863 }
5864
5865 return false;
5866 }
5867
5868 static bool
5869 is_mixed_float_with_packed_fp16_dst(const fs_inst *inst)
5870 {
5871 /* This opcode sometimes uses :W type on the destination even if the
5872 * destination is a :HF, because in gen7 there is no support for :HF, and
5873 * thus it uses :W.
5874 */
5875 if (inst->opcode == BRW_OPCODE_F32TO16 &&
5876 inst->dst.stride == 1)
5877 return true;
5878
5879 if (inst->dst.type != BRW_REGISTER_TYPE_HF ||
5880 inst->dst.stride != 1)
5881 return false;
5882
5883 for (int i = 0; i < inst->sources; i++) {
5884 if (inst->src[i].type == BRW_REGISTER_TYPE_F)
5885 return true;
5886 }
5887
5888 return false;
5889 }
5890
5891 /**
5892 * Get the closest allowed SIMD width for instruction \p inst accounting for
5893 * some common regioning and execution control restrictions that apply to FPU
5894 * instructions. These restrictions don't necessarily have any relevance to
5895 * instructions not executed by the FPU pipeline like extended math, control
5896 * flow or send message instructions.
5897 *
5898 * For virtual opcodes it's really up to the instruction -- In some cases
5899 * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
5900 * instructions) it may simplify virtual instruction lowering if we can
5901 * enforce FPU-like regioning restrictions already on the virtual instruction,
5902 * in other cases (e.g. virtual send-like instructions) this may be
5903 * excessively restrictive.
5904 */
5905 static unsigned
5906 get_fpu_lowered_simd_width(const struct gen_device_info *devinfo,
5907 const fs_inst *inst)
5908 {
5909 /* Maximum execution size representable in the instruction controls. */
5910 unsigned max_width = MIN2(32, inst->exec_size);
5911
5912 /* According to the PRMs:
5913 * "A. In Direct Addressing mode, a source cannot span more than 2
5914 * adjacent GRF registers.
5915 * B. A destination cannot span more than 2 adjacent GRF registers."
5916 *
5917 * Look for the source or destination with the largest register region
5918 * which is the one that is going to limit the overall execution size of
5919 * the instruction due to this rule.
5920 */
5921 unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5922
5923 for (unsigned i = 0; i < inst->sources; i++)
5924 reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
5925
5926 /* Calculate the maximum execution size of the instruction based on the
5927 * factor by which it goes over the hardware limit of 2 GRFs.
5928 */
5929 if (reg_count > 2)
5930 max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
5931
5932 /* According to the IVB PRMs:
5933 * "When destination spans two registers, the source MUST span two
5934 * registers. The exception to the above rule:
5935 *
5936 * - When source is scalar, the source registers are not incremented.
5937 * - When source is packed integer Word and destination is packed
5938 * integer DWord, the source register is not incremented but the
5939 * source sub register is incremented."
5940 *
5941 * The hardware specs from Gen4 to Gen7.5 mention similar regioning
5942 * restrictions. The code below intentionally doesn't check whether the
5943 * destination type is integer because empirically the hardware doesn't
5944 * seem to care what the actual type is as long as it's dword-aligned.
5945 */
5946 if (devinfo->gen < 8) {
5947 for (unsigned i = 0; i < inst->sources; i++) {
5948 /* IVB implements DF scalars as <0;2,1> regions. */
5949 const bool is_scalar_exception = is_uniform(inst->src[i]) &&
5950 (devinfo->is_haswell || type_sz(inst->src[i].type) != 8);
5951 const bool is_packed_word_exception =
5952 type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
5953 type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
5954
5955 /* We check size_read(i) against size_written instead of REG_SIZE
5956 * because we want to properly handle SIMD32. In SIMD32, you can end
5957 * up with writes to 4 registers and a source that reads 2 registers
5958 * and we may still need to lower all the way to SIMD8 in that case.
5959 */
5960 if (inst->size_written > REG_SIZE &&
5961 inst->size_read(i) != 0 &&
5962 inst->size_read(i) < inst->size_written &&
5963 !is_scalar_exception && !is_packed_word_exception) {
5964 const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5965 max_width = MIN2(max_width, inst->exec_size / reg_count);
5966 }
5967 }
5968 }
5969
5970 if (devinfo->gen < 6) {
5971 /* From the G45 PRM, Volume 4 Page 361:
5972 *
5973 * "Operand Alignment Rule: With the exceptions listed below, a
5974 * source/destination operand in general should be aligned to even
5975 * 256-bit physical register with a region size equal to two 256-bit
5976 * physical registers."
5977 *
5978 * Normally we enforce this by allocating virtual registers to the
5979 * even-aligned class. But we need to handle payload registers.
5980 */
5981 for (unsigned i = 0; i < inst->sources; i++) {
5982 if (inst->src[i].file == FIXED_GRF && (inst->src[i].nr & 1) &&
5983 inst->size_read(i) > REG_SIZE) {
5984 max_width = MIN2(max_width, 8);
5985 }
5986 }
5987 }
5988
5989 /* From the IVB PRMs:
5990 * "When an instruction is SIMD32, the low 16 bits of the execution mask
5991 * are applied for both halves of the SIMD32 instruction. If different
5992 * execution mask channels are required, split the instruction into two
5993 * SIMD16 instructions."
5994 *
5995 * There is similar text in the HSW PRMs. Gen4-6 don't even implement
5996 * 32-wide control flow support in hardware and will behave similarly.
5997 */
5998 if (devinfo->gen < 8 && !inst->force_writemask_all)
5999 max_width = MIN2(max_width, 16);
6000
6001 /* From the IVB PRMs (applies to HSW too):
6002 * "Instructions with condition modifiers must not use SIMD32."
6003 *
6004 * From the BDW PRMs (applies to later hardware too):
6005 * "Ternary instruction with condition modifiers must not use SIMD32."
6006 */
6007 if (inst->conditional_mod && (devinfo->gen < 8 || inst->is_3src(devinfo)))
6008 max_width = MIN2(max_width, 16);
6009
6010 /* From the IVB PRMs (applies to other devices that don't have the
6011 * gen_device_info::supports_simd16_3src flag set):
6012 * "In Align16 access mode, SIMD16 is not allowed for DW operations and
6013 * SIMD8 is not allowed for DF operations."
6014 */
6015 if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
6016 max_width = MIN2(max_width, inst->exec_size / reg_count);
6017
6018 /* Pre-Gen8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
6019 * the 8-bit quarter of the execution mask signals specified in the
6020 * instruction control fields) for the second compressed half of any
6021 * single-precision instruction (for double-precision instructions
6022 * it's hardwired to use NibCtrl+1, at least on HSW), which means that
6023 * the EU will apply the wrong execution controls for the second
6024 * sequential GRF write if the number of channels per GRF is not exactly
6025 * eight in single-precision mode (or four in double-float mode).
6026 *
6027 * In this situation we calculate the maximum size of the split
6028 * instructions so they only ever write to a single register.
6029 */
6030 if (devinfo->gen < 8 && inst->size_written > REG_SIZE &&
6031 !inst->force_writemask_all) {
6032 const unsigned channels_per_grf = inst->exec_size /
6033 DIV_ROUND_UP(inst->size_written, REG_SIZE);
6034 const unsigned exec_type_size = get_exec_type_size(inst);
6035 assert(exec_type_size);
6036
6037 /* The hardware shifts exactly 8 channels per compressed half of the
6038 * instruction in single-precision mode and exactly 4 in double-precision.
6039 */
6040 if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
6041 max_width = MIN2(max_width, channels_per_grf);
6042
6043 /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
6044 * because HW applies the same channel enable signals to both halves of
6045 * the compressed instruction which will be just wrong under
6046 * non-uniform control flow.
6047 */
6048 if (devinfo->gen == 7 && !devinfo->is_haswell &&
6049 (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
6050 max_width = MIN2(max_width, 4);
6051 }
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 f32. Instruction
6057 * execution size must be no more than 8."
6058 *
6059 * FIXME: the simulator doesn't seem to complain if we don't do this and
6060 * empirical testing with existing CTS tests show that they pass just fine
6061 * without implementing this, however, since our interpretation of the PRM
6062 * is that conversion MOVs between HF and F are still mixed-float
6063 * instructions (and therefore subject to this restriction) we decided to
6064 * split them to be safe. Might be useful to do additional investigation to
6065 * lift the restriction if we can ensure that it is safe though, since these
6066 * conversions are common when half-float types are involved since many
6067 * instructions do not support HF types and conversions from/to F are
6068 * required.
6069 */
6070 if (is_mixed_float_with_fp32_dst(inst))
6071 max_width = MIN2(max_width, 8);
6072
6073 /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
6074 * Float Operations:
6075 *
6076 * "No SIMD16 in mixed mode when destination is packed f16 for both
6077 * Align1 and Align16."
6078 */
6079 if (is_mixed_float_with_packed_fp16_dst(inst))
6080 max_width = MIN2(max_width, 8);
6081
6082 /* Only power-of-two execution sizes are representable in the instruction
6083 * control fields.
6084 */
6085 return 1 << _mesa_logbase2(max_width);
6086 }
6087
6088 /**
6089 * Get the maximum allowed SIMD width for instruction \p inst accounting for
6090 * various payload size restrictions that apply to sampler message
6091 * instructions.
6092 *
6093 * This is only intended to provide a maximum theoretical bound for the
6094 * execution size of the message based on the number of argument components
6095 * alone, which in most cases will determine whether the SIMD8 or SIMD16
6096 * variant of the message can be used, though some messages may have
6097 * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
6098 * the message length to determine the exact SIMD width and argument count,
6099 * which makes a number of sampler message combinations impossible to
6100 * represent).
6101 */
6102 static unsigned
6103 get_sampler_lowered_simd_width(const struct gen_device_info *devinfo,
6104 const fs_inst *inst)
6105 {
6106 /* If we have a min_lod parameter on anything other than a simple sample
6107 * message, it will push it over 5 arguments and we have to fall back to
6108 * SIMD8.
6109 */
6110 if (inst->opcode != SHADER_OPCODE_TEX &&
6111 inst->components_read(TEX_LOGICAL_SRC_MIN_LOD))
6112 return 8;
6113
6114 /* Calculate the number of coordinate components that have to be present
6115 * assuming that additional arguments follow the texel coordinates in the
6116 * message payload. On IVB+ there is no need for padding, on ILK-SNB we
6117 * need to pad to four or three components depending on the message,
6118 * pre-ILK we need to pad to at most three components.
6119 */
6120 const unsigned req_coord_components =
6121 (devinfo->gen >= 7 ||
6122 !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
6123 (devinfo->gen >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
6124 inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
6125 3;
6126
6127 /* On Gen9+ the LOD argument is for free if we're able to use the LZ
6128 * variant of the TXL or TXF message.
6129 */
6130 const bool implicit_lod = devinfo->gen >= 9 &&
6131 (inst->opcode == SHADER_OPCODE_TXL ||
6132 inst->opcode == SHADER_OPCODE_TXF) &&
6133 inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
6134
6135 /* Calculate the total number of argument components that need to be passed
6136 * to the sampler unit.
6137 */
6138 const unsigned num_payload_components =
6139 MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
6140 req_coord_components) +
6141 inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
6142 (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
6143 inst->components_read(TEX_LOGICAL_SRC_LOD2) +
6144 inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
6145 (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
6146 inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
6147 inst->components_read(TEX_LOGICAL_SRC_MCS);
6148
6149 /* SIMD16 messages with more than five arguments exceed the maximum message
6150 * size supported by the sampler, regardless of whether a header is
6151 * provided or not.
6152 */
6153 return MIN2(inst->exec_size,
6154 num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
6155 }
6156
6157 /**
6158 * Get the closest native SIMD width supported by the hardware for instruction
6159 * \p inst. The instruction will be left untouched by
6160 * fs_visitor::lower_simd_width() if the returned value is equal to the
6161 * original execution size.
6162 */
6163 static unsigned
6164 get_lowered_simd_width(const struct gen_device_info *devinfo,
6165 const fs_inst *inst)
6166 {
6167 switch (inst->opcode) {
6168 case BRW_OPCODE_MOV:
6169 case BRW_OPCODE_SEL:
6170 case BRW_OPCODE_NOT:
6171 case BRW_OPCODE_AND:
6172 case BRW_OPCODE_OR:
6173 case BRW_OPCODE_XOR:
6174 case BRW_OPCODE_SHR:
6175 case BRW_OPCODE_SHL:
6176 case BRW_OPCODE_ASR:
6177 case BRW_OPCODE_CMPN:
6178 case BRW_OPCODE_CSEL:
6179 case BRW_OPCODE_F32TO16:
6180 case BRW_OPCODE_F16TO32:
6181 case BRW_OPCODE_BFREV:
6182 case BRW_OPCODE_BFE:
6183 case BRW_OPCODE_ADD:
6184 case BRW_OPCODE_MUL:
6185 case BRW_OPCODE_AVG:
6186 case BRW_OPCODE_FRC:
6187 case BRW_OPCODE_RNDU:
6188 case BRW_OPCODE_RNDD:
6189 case BRW_OPCODE_RNDE:
6190 case BRW_OPCODE_RNDZ:
6191 case BRW_OPCODE_LZD:
6192 case BRW_OPCODE_FBH:
6193 case BRW_OPCODE_FBL:
6194 case BRW_OPCODE_CBIT:
6195 case BRW_OPCODE_SAD2:
6196 case BRW_OPCODE_MAD:
6197 case BRW_OPCODE_LRP:
6198 case FS_OPCODE_PACK:
6199 case SHADER_OPCODE_SEL_EXEC:
6200 case SHADER_OPCODE_CLUSTER_BROADCAST:
6201 return get_fpu_lowered_simd_width(devinfo, inst);
6202
6203 case BRW_OPCODE_CMP: {
6204 /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
6205 * when the destination is a GRF the dependency-clear bit on the flag
6206 * register is cleared early.
6207 *
6208 * Suggested workarounds are to disable coissuing CMP instructions
6209 * or to split CMP(16) instructions into two CMP(8) instructions.
6210 *
6211 * We choose to split into CMP(8) instructions since disabling
6212 * coissuing would affect CMP instructions not otherwise affected by
6213 * the errata.
6214 */
6215 const unsigned max_width = (devinfo->gen == 7 && !devinfo->is_haswell &&
6216 !inst->dst.is_null() ? 8 : ~0);
6217 return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
6218 }
6219 case BRW_OPCODE_BFI1:
6220 case BRW_OPCODE_BFI2:
6221 /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
6222 * should
6223 * "Force BFI instructions to be executed always in SIMD8."
6224 */
6225 return MIN2(devinfo->is_haswell ? 8 : ~0u,
6226 get_fpu_lowered_simd_width(devinfo, inst));
6227
6228 case BRW_OPCODE_IF:
6229 assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
6230 return inst->exec_size;
6231
6232 case SHADER_OPCODE_RCP:
6233 case SHADER_OPCODE_RSQ:
6234 case SHADER_OPCODE_SQRT:
6235 case SHADER_OPCODE_EXP2:
6236 case SHADER_OPCODE_LOG2:
6237 case SHADER_OPCODE_SIN:
6238 case SHADER_OPCODE_COS: {
6239 /* Unary extended math instructions are limited to SIMD8 on Gen4 and
6240 * Gen6. Extended Math Function is limited to SIMD8 with half-float.
6241 */
6242 if (devinfo->gen == 6 || (devinfo->gen == 4 && !devinfo->is_g4x))
6243 return MIN2(8, inst->exec_size);
6244 if (inst->dst.type == BRW_REGISTER_TYPE_HF)
6245 return MIN2(8, inst->exec_size);
6246 return MIN2(16, inst->exec_size);
6247 }
6248
6249 case SHADER_OPCODE_POW: {
6250 /* SIMD16 is only allowed on Gen7+. Extended Math Function is limited
6251 * to SIMD8 with half-float
6252 */
6253 if (devinfo->gen < 7)
6254 return MIN2(8, inst->exec_size);
6255 if (inst->dst.type == BRW_REGISTER_TYPE_HF)
6256 return MIN2(8, inst->exec_size);
6257 return MIN2(16, inst->exec_size);
6258 }
6259
6260 case SHADER_OPCODE_INT_QUOTIENT:
6261 case SHADER_OPCODE_INT_REMAINDER:
6262 /* Integer division is limited to SIMD8 on all generations. */
6263 return MIN2(8, inst->exec_size);
6264
6265 case FS_OPCODE_LINTERP:
6266 case SHADER_OPCODE_GET_BUFFER_SIZE:
6267 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
6268 case FS_OPCODE_PACK_HALF_2x16_SPLIT:
6269 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
6270 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
6271 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
6272 return MIN2(16, inst->exec_size);
6273
6274 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
6275 /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
6276 * message used to implement varying pull constant loads, so expand it
6277 * to SIMD16. An alternative with longer message payload length but
6278 * shorter return payload would be to use the SIMD8 sampler message that
6279 * takes (header, u, v, r) as parameters instead of (header, u).
6280 */
6281 return (devinfo->gen == 4 ? 16 : MIN2(16, inst->exec_size));
6282
6283 case FS_OPCODE_DDX_COARSE:
6284 case FS_OPCODE_DDX_FINE:
6285 case FS_OPCODE_DDY_COARSE:
6286 case FS_OPCODE_DDY_FINE:
6287 /* The implementation of this virtual opcode may require emitting
6288 * compressed Align16 instructions, which are severely limited on some
6289 * generations.
6290 *
6291 * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
6292 * Region Restrictions):
6293 *
6294 * "In Align16 access mode, SIMD16 is not allowed for DW operations
6295 * and SIMD8 is not allowed for DF operations."
6296 *
6297 * In this context, "DW operations" means "operations acting on 32-bit
6298 * values", so it includes operations on floats.
6299 *
6300 * Gen4 has a similar restriction. From the i965 PRM, section 11.5.3
6301 * (Instruction Compression -> Rules and Restrictions):
6302 *
6303 * "A compressed instruction must be in Align1 access mode. Align16
6304 * mode instructions cannot be compressed."
6305 *
6306 * Similar text exists in the g45 PRM.
6307 *
6308 * Empirically, compressed align16 instructions using odd register
6309 * numbers don't appear to work on Sandybridge either.
6310 */
6311 return (devinfo->gen == 4 || devinfo->gen == 6 ||
6312 (devinfo->gen == 7 && !devinfo->is_haswell) ?
6313 MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
6314
6315 case SHADER_OPCODE_MULH:
6316 /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
6317 * is 8-wide on Gen7+.
6318 */
6319 return (devinfo->gen >= 7 ? 8 :
6320 get_fpu_lowered_simd_width(devinfo, inst));
6321
6322 case FS_OPCODE_FB_WRITE_LOGICAL:
6323 /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
6324 * here.
6325 */
6326 assert(devinfo->gen != 6 ||
6327 inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
6328 inst->exec_size == 8);
6329 /* Dual-source FB writes are unsupported in SIMD16 mode. */
6330 return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
6331 8 : MIN2(16, inst->exec_size));
6332
6333 case FS_OPCODE_FB_READ_LOGICAL:
6334 return MIN2(16, inst->exec_size);
6335
6336 case SHADER_OPCODE_TEX_LOGICAL:
6337 case SHADER_OPCODE_TXF_CMS_LOGICAL:
6338 case SHADER_OPCODE_TXF_UMS_LOGICAL:
6339 case SHADER_OPCODE_TXF_MCS_LOGICAL:
6340 case SHADER_OPCODE_LOD_LOGICAL:
6341 case SHADER_OPCODE_TG4_LOGICAL:
6342 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
6343 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
6344 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
6345 return get_sampler_lowered_simd_width(devinfo, inst);
6346
6347 case SHADER_OPCODE_TXD_LOGICAL:
6348 /* TXD is unsupported in SIMD16 mode. */
6349 return 8;
6350
6351 case SHADER_OPCODE_TXL_LOGICAL:
6352 case FS_OPCODE_TXB_LOGICAL:
6353 /* Only one execution size is representable pre-ILK depending on whether
6354 * the shadow reference argument is present.
6355 */
6356 if (devinfo->gen == 4)
6357 return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
6358 else
6359 return get_sampler_lowered_simd_width(devinfo, inst);
6360
6361 case SHADER_OPCODE_TXF_LOGICAL:
6362 case SHADER_OPCODE_TXS_LOGICAL:
6363 /* Gen4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
6364 * messages. Use SIMD16 instead.
6365 */
6366 if (devinfo->gen == 4)
6367 return 16;
6368 else
6369 return get_sampler_lowered_simd_width(devinfo, inst);
6370
6371 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
6372 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
6373 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
6374 return 8;
6375
6376 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
6377 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6378 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
6379 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
6380 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
6381 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
6382 return MIN2(16, inst->exec_size);
6383
6384 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
6385 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
6386 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
6387 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
6388 return devinfo->gen <= 8 ? 8 : MIN2(16, inst->exec_size);
6389
6390 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
6391 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
6392 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6393 return 8;
6394
6395 case SHADER_OPCODE_URB_READ_SIMD8:
6396 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
6397 case SHADER_OPCODE_URB_WRITE_SIMD8:
6398 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
6399 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
6400 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
6401 return MIN2(8, inst->exec_size);
6402
6403 case SHADER_OPCODE_QUAD_SWIZZLE: {
6404 const unsigned swiz = inst->src[1].ud;
6405 return (is_uniform(inst->src[0]) ?
6406 get_fpu_lowered_simd_width(devinfo, inst) :
6407 devinfo->gen < 11 && type_sz(inst->src[0].type) == 4 ? 8 :
6408 swiz == BRW_SWIZZLE_XYXY || swiz == BRW_SWIZZLE_ZWZW ? 4 :
6409 get_fpu_lowered_simd_width(devinfo, inst));
6410 }
6411 case SHADER_OPCODE_MOV_INDIRECT: {
6412 /* From IVB and HSW PRMs:
6413 *
6414 * "2.When the destination requires two registers and the sources are
6415 * indirect, the sources must use 1x1 regioning mode.
6416 *
6417 * In case of DF instructions in HSW/IVB, the exec_size is limited by
6418 * the EU decompression logic not handling VxH indirect addressing
6419 * correctly.
6420 */
6421 const unsigned max_size = (devinfo->gen >= 8 ? 2 : 1) * REG_SIZE;
6422 /* Prior to Broadwell, we only have 8 address subregisters. */
6423 return MIN3(devinfo->gen >= 8 ? 16 : 8,
6424 max_size / (inst->dst.stride * type_sz(inst->dst.type)),
6425 inst->exec_size);
6426 }
6427
6428 case SHADER_OPCODE_LOAD_PAYLOAD: {
6429 const unsigned reg_count =
6430 DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
6431
6432 if (reg_count > 2) {
6433 /* Only LOAD_PAYLOAD instructions with per-channel destination region
6434 * can be easily lowered (which excludes headers and heterogeneous
6435 * types).
6436 */
6437 assert(!inst->header_size);
6438 for (unsigned i = 0; i < inst->sources; i++)
6439 assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
6440 inst->src[i].file == BAD_FILE);
6441
6442 return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
6443 } else {
6444 return inst->exec_size;
6445 }
6446 }
6447 default:
6448 return inst->exec_size;
6449 }
6450 }
6451
6452 /**
6453 * Return true if splitting out the group of channels of instruction \p inst
6454 * given by lbld.group() requires allocating a temporary for the i-th source
6455 * of the lowered instruction.
6456 */
6457 static inline bool
6458 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
6459 {
6460 return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
6461 (inst->components_read(i) == 1 &&
6462 lbld.dispatch_width() <= inst->exec_size)) ||
6463 (inst->flags_written() &
6464 flag_mask(inst->src[i], type_sz(inst->src[i].type)));
6465 }
6466
6467 /**
6468 * Extract the data that would be consumed by the channel group given by
6469 * lbld.group() from the i-th source region of instruction \p inst and return
6470 * it as result in packed form.
6471 */
6472 static fs_reg
6473 emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
6474 {
6475 assert(lbld.group() >= inst->group);
6476
6477 /* Specified channel group from the source region. */
6478 const fs_reg src = horiz_offset(inst->src[i], lbld.group() - inst->group);
6479
6480 if (needs_src_copy(lbld, inst, i)) {
6481 /* Builder of the right width to perform the copy avoiding uninitialized
6482 * data if the lowered execution size is greater than the original
6483 * execution size of the instruction.
6484 */
6485 const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
6486 inst->exec_size), 0);
6487 const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
6488
6489 for (unsigned k = 0; k < inst->components_read(i); ++k)
6490 cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
6491
6492 return tmp;
6493
6494 } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
6495 /* The source is invariant for all dispatch_width-wide groups of the
6496 * original region.
6497 */
6498 return inst->src[i];
6499
6500 } else {
6501 /* We can just point the lowered instruction at the right channel group
6502 * from the original region.
6503 */
6504 return src;
6505 }
6506 }
6507
6508 /**
6509 * Return true if splitting out the group of channels of instruction \p inst
6510 * given by lbld.group() requires allocating a temporary for the destination
6511 * of the lowered instruction and copying the data back to the original
6512 * destination region.
6513 */
6514 static inline bool
6515 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
6516 {
6517 /* If the instruction writes more than one component we'll have to shuffle
6518 * the results of multiple lowered instructions in order to make sure that
6519 * they end up arranged correctly in the original destination region.
6520 */
6521 if (inst->size_written > inst->dst.component_size(inst->exec_size))
6522 return true;
6523
6524 /* If the lowered execution size is larger than the original the result of
6525 * the instruction won't fit in the original destination, so we'll have to
6526 * allocate a temporary in any case.
6527 */
6528 if (lbld.dispatch_width() > inst->exec_size)
6529 return true;
6530
6531 for (unsigned i = 0; i < inst->sources; i++) {
6532 /* If we already made a copy of the source for other reasons there won't
6533 * be any overlap with the destination.
6534 */
6535 if (needs_src_copy(lbld, inst, i))
6536 continue;
6537
6538 /* In order to keep the logic simple we emit a copy whenever the
6539 * destination region doesn't exactly match an overlapping source, which
6540 * may point at the source and destination not being aligned group by
6541 * group which could cause one of the lowered instructions to overwrite
6542 * the data read from the same source by other lowered instructions.
6543 */
6544 if (regions_overlap(inst->dst, inst->size_written,
6545 inst->src[i], inst->size_read(i)) &&
6546 !inst->dst.equals(inst->src[i]))
6547 return true;
6548 }
6549
6550 return false;
6551 }
6552
6553 /**
6554 * Insert data from a packed temporary into the channel group given by
6555 * lbld.group() of the destination region of instruction \p inst and return
6556 * the temporary as result. Any copy instructions that are required for
6557 * unzipping the previous value (in the case of partial writes) will be
6558 * inserted using \p lbld_before and any copy instructions required for
6559 * zipping up the destination of \p inst will be inserted using \p lbld_after.
6560 */
6561 static fs_reg
6562 emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
6563 fs_inst *inst)
6564 {
6565 assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
6566 assert(lbld_before.group() == lbld_after.group());
6567 assert(lbld_after.group() >= inst->group);
6568
6569 /* Specified channel group from the destination region. */
6570 const fs_reg dst = horiz_offset(inst->dst, lbld_after.group() - inst->group);
6571 const unsigned dst_size = inst->size_written /
6572 inst->dst.component_size(inst->exec_size);
6573
6574 if (needs_dst_copy(lbld_after, inst)) {
6575 const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
6576
6577 if (inst->predicate) {
6578 /* Handle predication by copying the original contents of
6579 * the destination into the temporary before emitting the
6580 * lowered instruction.
6581 */
6582 const fs_builder gbld_before =
6583 lbld_before.group(MIN2(lbld_before.dispatch_width(),
6584 inst->exec_size), 0);
6585 for (unsigned k = 0; k < dst_size; ++k) {
6586 gbld_before.MOV(offset(tmp, lbld_before, k),
6587 offset(dst, inst->exec_size, k));
6588 }
6589 }
6590
6591 const fs_builder gbld_after =
6592 lbld_after.group(MIN2(lbld_after.dispatch_width(),
6593 inst->exec_size), 0);
6594 for (unsigned k = 0; k < dst_size; ++k) {
6595 /* Use a builder of the right width to perform the copy avoiding
6596 * uninitialized data if the lowered execution size is greater than
6597 * the original execution size of the instruction.
6598 */
6599 gbld_after.MOV(offset(dst, inst->exec_size, k),
6600 offset(tmp, lbld_after, k));
6601 }
6602
6603 return tmp;
6604
6605 } else {
6606 /* No need to allocate a temporary for the lowered instruction, just
6607 * take the right group of channels from the original region.
6608 */
6609 return dst;
6610 }
6611 }
6612
6613 bool
6614 fs_visitor::lower_simd_width()
6615 {
6616 bool progress = false;
6617
6618 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
6619 const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
6620
6621 if (lower_width != inst->exec_size) {
6622 /* Builder matching the original instruction. We may also need to
6623 * emit an instruction of width larger than the original, set the
6624 * execution size of the builder to the highest of both for now so
6625 * we're sure that both cases can be handled.
6626 */
6627 const unsigned max_width = MAX2(inst->exec_size, lower_width);
6628 const fs_builder ibld = bld.at(block, inst)
6629 .exec_all(inst->force_writemask_all)
6630 .group(max_width, inst->group / max_width);
6631
6632 /* Split the copies in chunks of the execution width of either the
6633 * original or the lowered instruction, whichever is lower.
6634 */
6635 const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
6636 const unsigned dst_size = inst->size_written /
6637 inst->dst.component_size(inst->exec_size);
6638
6639 assert(!inst->writes_accumulator && !inst->mlen);
6640
6641 /* Inserting the zip, unzip, and duplicated instructions in all of
6642 * the right spots is somewhat tricky. All of the unzip and any
6643 * instructions from the zip which unzip the destination prior to
6644 * writing need to happen before all of the per-group instructions
6645 * and the zip instructions need to happen after. In order to sort
6646 * this all out, we insert the unzip instructions before \p inst,
6647 * insert the per-group instructions after \p inst (i.e. before
6648 * inst->next), and insert the zip instructions before the
6649 * instruction after \p inst. Since we are inserting instructions
6650 * after \p inst, inst->next is a moving target and we need to save
6651 * it off here so that we insert the zip instructions in the right
6652 * place.
6653 *
6654 * Since we're inserting split instructions after after_inst, the
6655 * instructions will end up in the reverse order that we insert them.
6656 * However, certain render target writes require that the low group
6657 * instructions come before the high group. From the Ivy Bridge PRM
6658 * Vol. 4, Pt. 1, Section 3.9.11:
6659 *
6660 * "If multiple SIMD8 Dual Source messages are delivered by the
6661 * pixel shader thread, each SIMD8_DUALSRC_LO message must be
6662 * issued before the SIMD8_DUALSRC_HI message with the same Slot
6663 * Group Select setting."
6664 *
6665 * And, from Section 3.9.11.1 of the same PRM:
6666 *
6667 * "When SIMD32 or SIMD16 PS threads send render target writes
6668 * with multiple SIMD8 and SIMD16 messages, the following must
6669 * hold:
6670 *
6671 * All the slots (as described above) must have a corresponding
6672 * render target write irrespective of the slot's validity. A slot
6673 * is considered valid when at least one sample is enabled. For
6674 * example, a SIMD16 PS thread must send two SIMD8 render target
6675 * writes to cover all the slots.
6676 *
6677 * PS thread must send SIMD render target write messages with
6678 * increasing slot numbers. For example, SIMD16 thread has
6679 * Slot[15:0] and if two SIMD8 render target writes are used, the
6680 * first SIMD8 render target write must send Slot[7:0] and the
6681 * next one must send Slot[15:8]."
6682 *
6683 * In order to make low group instructions come before high group
6684 * instructions (this is required for some render target writes), we
6685 * split from the highest group to lowest.
6686 */
6687 exec_node *const after_inst = inst->next;
6688 for (int i = n - 1; i >= 0; i--) {
6689 /* Emit a copy of the original instruction with the lowered width.
6690 * If the EOT flag was set throw it away except for the last
6691 * instruction to avoid killing the thread prematurely.
6692 */
6693 fs_inst split_inst = *inst;
6694 split_inst.exec_size = lower_width;
6695 split_inst.eot = inst->eot && i == int(n - 1);
6696
6697 /* Select the correct channel enables for the i-th group, then
6698 * transform the sources and destination and emit the lowered
6699 * instruction.
6700 */
6701 const fs_builder lbld = ibld.group(lower_width, i);
6702
6703 for (unsigned j = 0; j < inst->sources; j++)
6704 split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
6705
6706 split_inst.dst = emit_zip(lbld.at(block, inst),
6707 lbld.at(block, after_inst), inst);
6708 split_inst.size_written =
6709 split_inst.dst.component_size(lower_width) * dst_size;
6710
6711 lbld.at(block, inst->next).emit(split_inst);
6712 }
6713
6714 inst->remove(block);
6715 progress = true;
6716 }
6717 }
6718
6719 if (progress)
6720 invalidate_live_intervals();
6721
6722 return progress;
6723 }
6724
6725 void
6726 fs_visitor::dump_instructions()
6727 {
6728 dump_instructions(NULL);
6729 }
6730
6731 void
6732 fs_visitor::dump_instructions(const char *name)
6733 {
6734 FILE *file = stderr;
6735 if (name && geteuid() != 0) {
6736 file = fopen(name, "w");
6737 if (!file)
6738 file = stderr;
6739 }
6740
6741 if (cfg) {
6742 calculate_register_pressure();
6743 int ip = 0, max_pressure = 0;
6744 foreach_block_and_inst(block, backend_instruction, inst, cfg) {
6745 max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
6746 fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
6747 dump_instruction(inst, file);
6748 ip++;
6749 }
6750 fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
6751 } else {
6752 int ip = 0;
6753 foreach_in_list(backend_instruction, inst, &instructions) {
6754 fprintf(file, "%4d: ", ip++);
6755 dump_instruction(inst, file);
6756 }
6757 }
6758
6759 if (file != stderr) {
6760 fclose(file);
6761 }
6762 }
6763
6764 void
6765 fs_visitor::dump_instruction(backend_instruction *be_inst)
6766 {
6767 dump_instruction(be_inst, stderr);
6768 }
6769
6770 void
6771 fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
6772 {
6773 fs_inst *inst = (fs_inst *)be_inst;
6774
6775 if (inst->predicate) {
6776 fprintf(file, "(%cf%d.%d) ",
6777 inst->predicate_inverse ? '-' : '+',
6778 inst->flag_subreg / 2,
6779 inst->flag_subreg % 2);
6780 }
6781
6782 fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
6783 if (inst->saturate)
6784 fprintf(file, ".sat");
6785 if (inst->conditional_mod) {
6786 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
6787 if (!inst->predicate &&
6788 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
6789 inst->opcode != BRW_OPCODE_CSEL &&
6790 inst->opcode != BRW_OPCODE_IF &&
6791 inst->opcode != BRW_OPCODE_WHILE))) {
6792 fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
6793 inst->flag_subreg % 2);
6794 }
6795 }
6796 fprintf(file, "(%d) ", inst->exec_size);
6797
6798 if (inst->mlen) {
6799 fprintf(file, "(mlen: %d) ", inst->mlen);
6800 }
6801
6802 if (inst->ex_mlen) {
6803 fprintf(file, "(ex_mlen: %d) ", inst->ex_mlen);
6804 }
6805
6806 if (inst->eot) {
6807 fprintf(file, "(EOT) ");
6808 }
6809
6810 switch (inst->dst.file) {
6811 case VGRF:
6812 fprintf(file, "vgrf%d", inst->dst.nr);
6813 break;
6814 case FIXED_GRF:
6815 fprintf(file, "g%d", inst->dst.nr);
6816 break;
6817 case MRF:
6818 fprintf(file, "m%d", inst->dst.nr);
6819 break;
6820 case BAD_FILE:
6821 fprintf(file, "(null)");
6822 break;
6823 case UNIFORM:
6824 fprintf(file, "***u%d***", inst->dst.nr);
6825 break;
6826 case ATTR:
6827 fprintf(file, "***attr%d***", inst->dst.nr);
6828 break;
6829 case ARF:
6830 switch (inst->dst.nr) {
6831 case BRW_ARF_NULL:
6832 fprintf(file, "null");
6833 break;
6834 case BRW_ARF_ADDRESS:
6835 fprintf(file, "a0.%d", inst->dst.subnr);
6836 break;
6837 case BRW_ARF_ACCUMULATOR:
6838 fprintf(file, "acc%d", inst->dst.subnr);
6839 break;
6840 case BRW_ARF_FLAG:
6841 fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6842 break;
6843 default:
6844 fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6845 break;
6846 }
6847 break;
6848 case IMM:
6849 unreachable("not reached");
6850 }
6851
6852 if (inst->dst.offset ||
6853 (inst->dst.file == VGRF &&
6854 alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
6855 const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
6856 fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
6857 inst->dst.offset % reg_size);
6858 }
6859
6860 if (inst->dst.stride != 1)
6861 fprintf(file, "<%u>", inst->dst.stride);
6862 fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
6863
6864 for (int i = 0; i < inst->sources; i++) {
6865 if (inst->src[i].negate)
6866 fprintf(file, "-");
6867 if (inst->src[i].abs)
6868 fprintf(file, "|");
6869 switch (inst->src[i].file) {
6870 case VGRF:
6871 fprintf(file, "vgrf%d", inst->src[i].nr);
6872 break;
6873 case FIXED_GRF:
6874 fprintf(file, "g%d", inst->src[i].nr);
6875 break;
6876 case MRF:
6877 fprintf(file, "***m%d***", inst->src[i].nr);
6878 break;
6879 case ATTR:
6880 fprintf(file, "attr%d", inst->src[i].nr);
6881 break;
6882 case UNIFORM:
6883 fprintf(file, "u%d", inst->src[i].nr);
6884 break;
6885 case BAD_FILE:
6886 fprintf(file, "(null)");
6887 break;
6888 case IMM:
6889 switch (inst->src[i].type) {
6890 case BRW_REGISTER_TYPE_F:
6891 fprintf(file, "%-gf", inst->src[i].f);
6892 break;
6893 case BRW_REGISTER_TYPE_DF:
6894 fprintf(file, "%fdf", inst->src[i].df);
6895 break;
6896 case BRW_REGISTER_TYPE_W:
6897 case BRW_REGISTER_TYPE_D:
6898 fprintf(file, "%dd", inst->src[i].d);
6899 break;
6900 case BRW_REGISTER_TYPE_UW:
6901 case BRW_REGISTER_TYPE_UD:
6902 fprintf(file, "%uu", inst->src[i].ud);
6903 break;
6904 case BRW_REGISTER_TYPE_Q:
6905 fprintf(file, "%" PRId64 "q", inst->src[i].d64);
6906 break;
6907 case BRW_REGISTER_TYPE_UQ:
6908 fprintf(file, "%" PRIu64 "uq", inst->src[i].u64);
6909 break;
6910 case BRW_REGISTER_TYPE_VF:
6911 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
6912 brw_vf_to_float((inst->src[i].ud >> 0) & 0xff),
6913 brw_vf_to_float((inst->src[i].ud >> 8) & 0xff),
6914 brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
6915 brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
6916 break;
6917 case BRW_REGISTER_TYPE_V:
6918 case BRW_REGISTER_TYPE_UV:
6919 fprintf(file, "%08x%s", inst->src[i].ud,
6920 inst->src[i].type == BRW_REGISTER_TYPE_V ? "V" : "UV");
6921 break;
6922 default:
6923 fprintf(file, "???");
6924 break;
6925 }
6926 break;
6927 case ARF:
6928 switch (inst->src[i].nr) {
6929 case BRW_ARF_NULL:
6930 fprintf(file, "null");
6931 break;
6932 case BRW_ARF_ADDRESS:
6933 fprintf(file, "a0.%d", inst->src[i].subnr);
6934 break;
6935 case BRW_ARF_ACCUMULATOR:
6936 fprintf(file, "acc%d", inst->src[i].subnr);
6937 break;
6938 case BRW_ARF_FLAG:
6939 fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6940 break;
6941 default:
6942 fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6943 break;
6944 }
6945 break;
6946 }
6947
6948 if (inst->src[i].offset ||
6949 (inst->src[i].file == VGRF &&
6950 alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
6951 const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
6952 fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
6953 inst->src[i].offset % reg_size);
6954 }
6955
6956 if (inst->src[i].abs)
6957 fprintf(file, "|");
6958
6959 if (inst->src[i].file != IMM) {
6960 unsigned stride;
6961 if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
6962 unsigned hstride = inst->src[i].hstride;
6963 stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
6964 } else {
6965 stride = inst->src[i].stride;
6966 }
6967 if (stride != 1)
6968 fprintf(file, "<%u>", stride);
6969
6970 fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
6971 }
6972
6973 if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
6974 fprintf(file, ", ");
6975 }
6976
6977 fprintf(file, " ");
6978
6979 if (inst->force_writemask_all)
6980 fprintf(file, "NoMask ");
6981
6982 if (inst->exec_size != dispatch_width)
6983 fprintf(file, "group%d ", inst->group);
6984
6985 fprintf(file, "\n");
6986 }
6987
6988 void
6989 fs_visitor::setup_fs_payload_gen6()
6990 {
6991 assert(stage == MESA_SHADER_FRAGMENT);
6992 struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
6993 const unsigned payload_width = MIN2(16, dispatch_width);
6994 assert(dispatch_width % payload_width == 0);
6995 assert(devinfo->gen >= 6);
6996
6997 prog_data->uses_src_depth = prog_data->uses_src_w =
6998 (nir->info.system_values_read & (1ull << SYSTEM_VALUE_FRAG_COORD)) != 0;
6999
7000 prog_data->uses_sample_mask =
7001 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_MASK_IN) != 0;
7002
7003 /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
7004 *
7005 * "MSDISPMODE_PERSAMPLE is required in order to select
7006 * POSOFFSET_SAMPLE"
7007 *
7008 * So we can only really get sample positions if we are doing real
7009 * per-sample dispatch. If we need gl_SamplePosition and we don't have
7010 * persample dispatch, we hard-code it to 0.5.
7011 */
7012 prog_data->uses_pos_offset = prog_data->persample_dispatch &&
7013 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_POS);
7014
7015 /* R0: PS thread payload header. */
7016 payload.num_regs++;
7017
7018 for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
7019 /* R1: masks, pixel X/Y coordinates. */
7020 payload.subspan_coord_reg[j] = payload.num_regs++;
7021 }
7022
7023 for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
7024 /* R3-26: barycentric interpolation coordinates. These appear in the
7025 * same order that they appear in the brw_barycentric_mode enum. Each
7026 * set of coordinates occupies 2 registers if dispatch width == 8 and 4
7027 * registers if dispatch width == 16. Coordinates only appear if they
7028 * were enabled using the "Barycentric Interpolation Mode" bits in
7029 * WM_STATE.
7030 */
7031 for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
7032 if (prog_data->barycentric_interp_modes & (1 << i)) {
7033 payload.barycentric_coord_reg[i][j] = payload.num_regs;
7034 payload.num_regs += payload_width / 4;
7035 }
7036 }
7037
7038 /* R27-28: interpolated depth if uses source depth */
7039 if (prog_data->uses_src_depth) {
7040 payload.source_depth_reg[j] = payload.num_regs;
7041 payload.num_regs += payload_width / 8;
7042 }
7043
7044 /* R29-30: interpolated W set if GEN6_WM_USES_SOURCE_W. */
7045 if (prog_data->uses_src_w) {
7046 payload.source_w_reg[j] = payload.num_regs;
7047 payload.num_regs += payload_width / 8;
7048 }
7049
7050 /* R31: MSAA position offsets. */
7051 if (prog_data->uses_pos_offset) {
7052 payload.sample_pos_reg[j] = payload.num_regs;
7053 payload.num_regs++;
7054 }
7055
7056 /* R32-33: MSAA input coverage mask */
7057 if (prog_data->uses_sample_mask) {
7058 assert(devinfo->gen >= 7);
7059 payload.sample_mask_in_reg[j] = payload.num_regs;
7060 payload.num_regs += payload_width / 8;
7061 }
7062 }
7063
7064 if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
7065 source_depth_to_render_target = true;
7066 }
7067 }
7068
7069 void
7070 fs_visitor::setup_vs_payload()
7071 {
7072 /* R0: thread header, R1: urb handles */
7073 payload.num_regs = 2;
7074 }
7075
7076 void
7077 fs_visitor::setup_gs_payload()
7078 {
7079 assert(stage == MESA_SHADER_GEOMETRY);
7080
7081 struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
7082 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
7083
7084 /* R0: thread header, R1: output URB handles */
7085 payload.num_regs = 2;
7086
7087 if (gs_prog_data->include_primitive_id) {
7088 /* R2: Primitive ID 0..7 */
7089 payload.num_regs++;
7090 }
7091
7092 /* Always enable VUE handles so we can safely use pull model if needed.
7093 *
7094 * The push model for a GS uses a ton of register space even for trivial
7095 * scenarios with just a few inputs, so just make things easier and a bit
7096 * safer by always having pull model available.
7097 */
7098 gs_prog_data->base.include_vue_handles = true;
7099
7100 /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
7101 payload.num_regs += nir->info.gs.vertices_in;
7102
7103 /* Use a maximum of 24 registers for push-model inputs. */
7104 const unsigned max_push_components = 24;
7105
7106 /* If pushing our inputs would take too many registers, reduce the URB read
7107 * length (which is in HWords, or 8 registers), and resort to pulling.
7108 *
7109 * Note that the GS reads <URB Read Length> HWords for every vertex - so we
7110 * have to multiply by VerticesIn to obtain the total storage requirement.
7111 */
7112 if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
7113 max_push_components) {
7114 vue_prog_data->urb_read_length =
7115 ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
7116 }
7117 }
7118
7119 void
7120 fs_visitor::setup_cs_payload()
7121 {
7122 assert(devinfo->gen >= 7);
7123 payload.num_regs = 1;
7124 }
7125
7126 void
7127 fs_visitor::calculate_register_pressure()
7128 {
7129 invalidate_live_intervals();
7130 calculate_live_intervals();
7131
7132 unsigned num_instructions = 0;
7133 foreach_block(block, cfg)
7134 num_instructions += block->instructions.length();
7135
7136 regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
7137
7138 for (unsigned reg = 0; reg < alloc.count; reg++) {
7139 for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
7140 regs_live_at_ip[ip] += alloc.sizes[reg];
7141 }
7142 }
7143
7144 void
7145 fs_visitor::optimize()
7146 {
7147 /* Start by validating the shader we currently have. */
7148 validate();
7149
7150 /* bld is the common builder object pointing at the end of the program we
7151 * used to translate it into i965 IR. For the optimization and lowering
7152 * passes coming next, any code added after the end of the program without
7153 * having explicitly called fs_builder::at() clearly points at a mistake.
7154 * Ideally optimization passes wouldn't be part of the visitor so they
7155 * wouldn't have access to bld at all, but they do, so just in case some
7156 * pass forgets to ask for a location explicitly set it to NULL here to
7157 * make it trip. The dispatch width is initialized to a bogus value to
7158 * make sure that optimizations set the execution controls explicitly to
7159 * match the code they are manipulating instead of relying on the defaults.
7160 */
7161 bld = fs_builder(this, 64);
7162
7163 assign_constant_locations();
7164 lower_constant_loads();
7165
7166 validate();
7167
7168 split_virtual_grfs();
7169 validate();
7170
7171 #define OPT(pass, args...) ({ \
7172 pass_num++; \
7173 bool this_progress = pass(args); \
7174 \
7175 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
7176 char filename[64]; \
7177 snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass, \
7178 stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
7179 \
7180 backend_shader::dump_instructions(filename); \
7181 } \
7182 \
7183 validate(); \
7184 \
7185 progress = progress || this_progress; \
7186 this_progress; \
7187 })
7188
7189 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
7190 char filename[64];
7191 snprintf(filename, 64, "%s%d-%s-00-00-start",
7192 stage_abbrev, dispatch_width, nir->info.name);
7193
7194 backend_shader::dump_instructions(filename);
7195 }
7196
7197 bool progress = false;
7198 int iteration = 0;
7199 int pass_num = 0;
7200
7201 /* Before anything else, eliminate dead code. The results of some NIR
7202 * instructions may effectively be calculated twice. Once when the
7203 * instruction is encountered, and again when the user of that result is
7204 * encountered. Wipe those away before algebraic optimizations and
7205 * especially copy propagation can mix things up.
7206 */
7207 OPT(dead_code_eliminate);
7208
7209 OPT(remove_extra_rounding_modes);
7210
7211 do {
7212 progress = false;
7213 pass_num = 0;
7214 iteration++;
7215
7216 OPT(remove_duplicate_mrf_writes);
7217
7218 OPT(opt_algebraic);
7219 OPT(opt_cse);
7220 OPT(opt_copy_propagation);
7221 OPT(opt_predicated_break, this);
7222 OPT(opt_cmod_propagation);
7223 OPT(dead_code_eliminate);
7224 OPT(opt_peephole_sel);
7225 OPT(dead_control_flow_eliminate, this);
7226 OPT(opt_register_renaming);
7227 OPT(opt_saturate_propagation);
7228 OPT(register_coalesce);
7229 OPT(compute_to_mrf);
7230 OPT(eliminate_find_live_channel);
7231
7232 OPT(compact_virtual_grfs);
7233 } while (progress);
7234
7235 /* Do this after cmod propagation has had every possible opportunity to
7236 * propagate results into SEL instructions.
7237 */
7238 if (OPT(opt_peephole_csel))
7239 OPT(dead_code_eliminate);
7240
7241 progress = false;
7242 pass_num = 0;
7243
7244 if (OPT(lower_pack)) {
7245 OPT(register_coalesce);
7246 OPT(dead_code_eliminate);
7247 }
7248
7249 OPT(lower_simd_width);
7250
7251 /* After SIMD lowering just in case we had to unroll the EOT send. */
7252 OPT(opt_sampler_eot);
7253
7254 OPT(lower_logical_sends);
7255
7256 if (progress) {
7257 OPT(opt_copy_propagation);
7258 /* Only run after logical send lowering because it's easier to implement
7259 * in terms of physical sends.
7260 */
7261 if (OPT(opt_zero_samples))
7262 OPT(opt_copy_propagation);
7263 /* Run after logical send lowering to give it a chance to CSE the
7264 * LOAD_PAYLOAD instructions created to construct the payloads of
7265 * e.g. texturing messages in cases where it wasn't possible to CSE the
7266 * whole logical instruction.
7267 */
7268 OPT(opt_cse);
7269 OPT(register_coalesce);
7270 OPT(compute_to_mrf);
7271 OPT(dead_code_eliminate);
7272 OPT(remove_duplicate_mrf_writes);
7273 OPT(opt_peephole_sel);
7274 }
7275
7276 OPT(opt_redundant_discard_jumps);
7277
7278 if (OPT(lower_load_payload)) {
7279 split_virtual_grfs();
7280 OPT(register_coalesce);
7281 OPT(lower_simd_width);
7282 OPT(compute_to_mrf);
7283 OPT(dead_code_eliminate);
7284 }
7285
7286 OPT(opt_combine_constants);
7287 OPT(lower_integer_multiplication);
7288
7289 if (devinfo->gen <= 5 && OPT(lower_minmax)) {
7290 OPT(opt_cmod_propagation);
7291 OPT(opt_cse);
7292 OPT(opt_copy_propagation);
7293 OPT(dead_code_eliminate);
7294 }
7295
7296 if (OPT(lower_regioning)) {
7297 OPT(opt_copy_propagation);
7298 OPT(dead_code_eliminate);
7299 OPT(lower_simd_width);
7300 }
7301
7302 OPT(fixup_sends_duplicate_payload);
7303
7304 lower_uniform_pull_constant_loads();
7305
7306 validate();
7307 }
7308
7309 /**
7310 * From the Skylake PRM Vol. 2a docs for sends:
7311 *
7312 * "It is required that the second block of GRFs does not overlap with the
7313 * first block."
7314 *
7315 * There are plenty of cases where we may accidentally violate this due to
7316 * having, for instance, both sources be the constant 0. This little pass
7317 * just adds a new vgrf for the second payload and copies it over.
7318 */
7319 bool
7320 fs_visitor::fixup_sends_duplicate_payload()
7321 {
7322 bool progress = false;
7323
7324 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7325 if (inst->opcode == SHADER_OPCODE_SEND && inst->ex_mlen > 0 &&
7326 regions_overlap(inst->src[2], inst->mlen * REG_SIZE,
7327 inst->src[3], inst->ex_mlen * REG_SIZE)) {
7328 fs_reg tmp = fs_reg(VGRF, alloc.allocate(inst->ex_mlen),
7329 BRW_REGISTER_TYPE_UD);
7330 /* Sadly, we've lost all notion of channels and bit sizes at this
7331 * point. Just WE_all it.
7332 */
7333 const fs_builder ibld = bld.at(block, inst).exec_all().group(16, 0);
7334 fs_reg copy_src = retype(inst->src[3], BRW_REGISTER_TYPE_UD);
7335 fs_reg copy_dst = tmp;
7336 for (unsigned i = 0; i < inst->ex_mlen; i += 2) {
7337 if (inst->ex_mlen == i + 1) {
7338 /* Only one register left; do SIMD8 */
7339 ibld.group(8, 0).MOV(copy_dst, copy_src);
7340 } else {
7341 ibld.MOV(copy_dst, copy_src);
7342 }
7343 copy_src = offset(copy_src, ibld, 1);
7344 copy_dst = offset(copy_dst, ibld, 1);
7345 }
7346 inst->src[3] = tmp;
7347 progress = true;
7348 }
7349 }
7350
7351 if (progress)
7352 invalidate_live_intervals();
7353
7354 return progress;
7355 }
7356
7357 /**
7358 * Three source instruction must have a GRF/MRF destination register.
7359 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
7360 */
7361 void
7362 fs_visitor::fixup_3src_null_dest()
7363 {
7364 bool progress = false;
7365
7366 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7367 if (inst->is_3src(devinfo) && inst->dst.is_null()) {
7368 inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
7369 inst->dst.type);
7370 progress = true;
7371 }
7372 }
7373
7374 if (progress)
7375 invalidate_live_intervals();
7376 }
7377
7378 void
7379 fs_visitor::allocate_registers(unsigned min_dispatch_width, bool allow_spilling)
7380 {
7381 bool allocated;
7382
7383 static const enum instruction_scheduler_mode pre_modes[] = {
7384 SCHEDULE_PRE,
7385 SCHEDULE_PRE_NON_LIFO,
7386 SCHEDULE_PRE_LIFO,
7387 };
7388
7389 static const char *scheduler_mode_name[] = {
7390 "top-down",
7391 "non-lifo",
7392 "lifo"
7393 };
7394
7395 bool spill_all = allow_spilling && (INTEL_DEBUG & DEBUG_SPILL_FS);
7396
7397 /* Try each scheduling heuristic to see if it can successfully register
7398 * allocate without spilling. They should be ordered by decreasing
7399 * performance but increasing likelihood of allocating.
7400 */
7401 for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
7402 schedule_instructions(pre_modes[i]);
7403 this->shader_stats.scheduler_mode = scheduler_mode_name[i];
7404
7405 if (0) {
7406 assign_regs_trivial();
7407 allocated = true;
7408 break;
7409 }
7410
7411 /* We only allow spilling for the last schedule mode and only if the
7412 * allow_spilling parameter and dispatch width work out ok.
7413 */
7414 bool can_spill = allow_spilling &&
7415 (i == ARRAY_SIZE(pre_modes) - 1) &&
7416 dispatch_width == min_dispatch_width;
7417
7418 /* We should only spill registers on the last scheduling. */
7419 assert(!spilled_any_registers);
7420
7421 allocated = assign_regs(can_spill, spill_all);
7422 if (allocated)
7423 break;
7424 }
7425
7426 if (!allocated) {
7427 if (!allow_spilling)
7428 fail("Failure to register allocate and spilling is not allowed.");
7429
7430 /* We assume that any spilling is worse than just dropping back to
7431 * SIMD8. There's probably actually some intermediate point where
7432 * SIMD16 with a couple of spills is still better.
7433 */
7434 if (dispatch_width > min_dispatch_width) {
7435 fail("Failure to register allocate. Reduce number of "
7436 "live scalar values to avoid this.");
7437 }
7438
7439 /* If we failed to allocate, we must have a reason */
7440 assert(failed);
7441 } else if (spilled_any_registers) {
7442 compiler->shader_perf_log(log_data,
7443 "%s shader triggered register spilling. "
7444 "Try reducing the number of live scalar "
7445 "values to improve performance.\n",
7446 stage_name);
7447 }
7448
7449 /* This must come after all optimization and register allocation, since
7450 * it inserts dead code that happens to have side effects, and it does
7451 * so based on the actual physical registers in use.
7452 */
7453 insert_gen4_send_dependency_workarounds();
7454
7455 if (failed)
7456 return;
7457
7458 opt_bank_conflicts();
7459
7460 schedule_instructions(SCHEDULE_POST);
7461
7462 if (last_scratch > 0) {
7463 ASSERTED unsigned max_scratch_size = 2 * 1024 * 1024;
7464
7465 prog_data->total_scratch = brw_get_scratch_size(last_scratch);
7466
7467 if (stage == MESA_SHADER_COMPUTE) {
7468 if (devinfo->is_haswell) {
7469 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7470 * field documentation, Haswell supports a minimum of 2kB of
7471 * scratch space for compute shaders, unlike every other stage
7472 * and platform.
7473 */
7474 prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
7475 } else if (devinfo->gen <= 7) {
7476 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7477 * field documentation, platforms prior to Haswell measure scratch
7478 * size linearly with a range of [1kB, 12kB] and 1kB granularity.
7479 */
7480 prog_data->total_scratch = ALIGN(last_scratch, 1024);
7481 max_scratch_size = 12 * 1024;
7482 }
7483 }
7484
7485 /* We currently only support up to 2MB of scratch space. If we
7486 * need to support more eventually, the documentation suggests
7487 * that we could allocate a larger buffer, and partition it out
7488 * ourselves. We'd just have to undo the hardware's address
7489 * calculation by subtracting (FFTID * Per Thread Scratch Space)
7490 * and then add FFTID * (Larger Per Thread Scratch Space).
7491 *
7492 * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
7493 * Thread Group Tracking > Local Memory/Scratch Space.
7494 */
7495 assert(prog_data->total_scratch < max_scratch_size);
7496 }
7497 }
7498
7499 bool
7500 fs_visitor::run_vs()
7501 {
7502 assert(stage == MESA_SHADER_VERTEX);
7503
7504 setup_vs_payload();
7505
7506 if (shader_time_index >= 0)
7507 emit_shader_time_begin();
7508
7509 emit_nir_code();
7510
7511 if (failed)
7512 return false;
7513
7514 emit_urb_writes();
7515
7516 if (shader_time_index >= 0)
7517 emit_shader_time_end();
7518
7519 calculate_cfg();
7520
7521 optimize();
7522
7523 assign_curb_setup();
7524 assign_vs_urb_setup();
7525
7526 fixup_3src_null_dest();
7527 allocate_registers(8, true);
7528
7529 return !failed;
7530 }
7531
7532 void
7533 fs_visitor::set_tcs_invocation_id()
7534 {
7535 struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
7536 struct brw_vue_prog_data *vue_prog_data = &tcs_prog_data->base;
7537
7538 const unsigned instance_id_mask =
7539 devinfo->gen >= 11 ? INTEL_MASK(22, 16) : INTEL_MASK(23, 17);
7540 const unsigned instance_id_shift =
7541 devinfo->gen >= 11 ? 16 : 17;
7542
7543 /* Get instance number from g0.2 bits 22:16 or 23:17 */
7544 fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
7545 bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
7546 brw_imm_ud(instance_id_mask));
7547
7548 invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
7549
7550 if (vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH) {
7551 /* gl_InvocationID is just the thread number */
7552 bld.SHR(invocation_id, t, brw_imm_ud(instance_id_shift));
7553 return;
7554 }
7555
7556 assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH);
7557
7558 fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
7559 fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
7560 bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
7561 bld.MOV(channels_ud, channels_uw);
7562
7563 if (tcs_prog_data->instances == 1) {
7564 invocation_id = channels_ud;
7565 } else {
7566 fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
7567 bld.SHR(instance_times_8, t, brw_imm_ud(instance_id_shift - 3));
7568 bld.ADD(invocation_id, instance_times_8, channels_ud);
7569 }
7570 }
7571
7572 bool
7573 fs_visitor::run_tcs()
7574 {
7575 assert(stage == MESA_SHADER_TESS_CTRL);
7576
7577 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
7578 struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
7579 struct brw_tcs_prog_key *tcs_key = (struct brw_tcs_prog_key *) key;
7580
7581 assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH ||
7582 vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH);
7583
7584 if (vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH) {
7585 /* r1-r4 contain the ICP handles. */
7586 payload.num_regs = 5;
7587 } else {
7588 assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH);
7589 assert(tcs_key->input_vertices > 0);
7590 /* r1 contains output handles, r2 may contain primitive ID, then the
7591 * ICP handles occupy the next 1-32 registers.
7592 */
7593 payload.num_regs = 2 + tcs_prog_data->include_primitive_id +
7594 tcs_key->input_vertices;
7595 }
7596
7597 if (shader_time_index >= 0)
7598 emit_shader_time_begin();
7599
7600 /* Initialize gl_InvocationID */
7601 set_tcs_invocation_id();
7602
7603 const bool fix_dispatch_mask =
7604 vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH &&
7605 (nir->info.tess.tcs_vertices_out % 8) != 0;
7606
7607 /* Fix the disptach mask */
7608 if (fix_dispatch_mask) {
7609 bld.CMP(bld.null_reg_ud(), invocation_id,
7610 brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
7611 bld.IF(BRW_PREDICATE_NORMAL);
7612 }
7613
7614 emit_nir_code();
7615
7616 if (fix_dispatch_mask) {
7617 bld.emit(BRW_OPCODE_ENDIF);
7618 }
7619
7620 /* Emit EOT write; set TR DS Cache bit */
7621 fs_reg srcs[3] = {
7622 fs_reg(get_tcs_output_urb_handle()),
7623 fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
7624 fs_reg(brw_imm_ud(0)),
7625 };
7626 fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
7627 bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
7628
7629 fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
7630 bld.null_reg_ud(), payload);
7631 inst->mlen = 3;
7632 inst->eot = true;
7633
7634 if (shader_time_index >= 0)
7635 emit_shader_time_end();
7636
7637 if (failed)
7638 return false;
7639
7640 calculate_cfg();
7641
7642 optimize();
7643
7644 assign_curb_setup();
7645 assign_tcs_urb_setup();
7646
7647 fixup_3src_null_dest();
7648 allocate_registers(8, true);
7649
7650 return !failed;
7651 }
7652
7653 bool
7654 fs_visitor::run_tes()
7655 {
7656 assert(stage == MESA_SHADER_TESS_EVAL);
7657
7658 /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
7659 payload.num_regs = 5;
7660
7661 if (shader_time_index >= 0)
7662 emit_shader_time_begin();
7663
7664 emit_nir_code();
7665
7666 if (failed)
7667 return false;
7668
7669 emit_urb_writes();
7670
7671 if (shader_time_index >= 0)
7672 emit_shader_time_end();
7673
7674 calculate_cfg();
7675
7676 optimize();
7677
7678 assign_curb_setup();
7679 assign_tes_urb_setup();
7680
7681 fixup_3src_null_dest();
7682 allocate_registers(8, true);
7683
7684 return !failed;
7685 }
7686
7687 bool
7688 fs_visitor::run_gs()
7689 {
7690 assert(stage == MESA_SHADER_GEOMETRY);
7691
7692 setup_gs_payload();
7693
7694 this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
7695
7696 if (gs_compile->control_data_header_size_bits > 0) {
7697 /* Create a VGRF to store accumulated control data bits. */
7698 this->control_data_bits = vgrf(glsl_type::uint_type);
7699
7700 /* If we're outputting more than 32 control data bits, then EmitVertex()
7701 * will set control_data_bits to 0 after emitting the first vertex.
7702 * Otherwise, we need to initialize it to 0 here.
7703 */
7704 if (gs_compile->control_data_header_size_bits <= 32) {
7705 const fs_builder abld = bld.annotate("initialize control data bits");
7706 abld.MOV(this->control_data_bits, brw_imm_ud(0u));
7707 }
7708 }
7709
7710 if (shader_time_index >= 0)
7711 emit_shader_time_begin();
7712
7713 emit_nir_code();
7714
7715 emit_gs_thread_end();
7716
7717 if (shader_time_index >= 0)
7718 emit_shader_time_end();
7719
7720 if (failed)
7721 return false;
7722
7723 calculate_cfg();
7724
7725 optimize();
7726
7727 assign_curb_setup();
7728 assign_gs_urb_setup();
7729
7730 fixup_3src_null_dest();
7731 allocate_registers(8, true);
7732
7733 return !failed;
7734 }
7735
7736 /* From the SKL PRM, Volume 16, Workarounds:
7737 *
7738 * 0877 3D Pixel Shader Hang possible when pixel shader dispatched with
7739 * only header phases (R0-R2)
7740 *
7741 * WA: Enable a non-header phase (e.g. push constant) when dispatch would
7742 * have been header only.
7743 *
7744 * Instead of enabling push constants one can alternatively enable one of the
7745 * inputs. Here one simply chooses "layer" which shouldn't impose much
7746 * overhead.
7747 */
7748 static void
7749 gen9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
7750 {
7751 if (wm_prog_data->num_varying_inputs)
7752 return;
7753
7754 if (wm_prog_data->base.curb_read_length)
7755 return;
7756
7757 wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
7758 wm_prog_data->num_varying_inputs = 1;
7759 }
7760
7761 bool
7762 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
7763 {
7764 struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
7765 brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
7766
7767 assert(stage == MESA_SHADER_FRAGMENT);
7768
7769 if (devinfo->gen >= 6)
7770 setup_fs_payload_gen6();
7771 else
7772 setup_fs_payload_gen4();
7773
7774 if (0) {
7775 emit_dummy_fs();
7776 } else if (do_rep_send) {
7777 assert(dispatch_width == 16);
7778 emit_repclear_shader();
7779 } else {
7780 if (shader_time_index >= 0)
7781 emit_shader_time_begin();
7782
7783 if (nir->info.inputs_read > 0 ||
7784 (nir->info.system_values_read & (1ull << SYSTEM_VALUE_FRAG_COORD)) ||
7785 (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
7786 if (devinfo->gen < 6)
7787 emit_interpolation_setup_gen4();
7788 else
7789 emit_interpolation_setup_gen6();
7790 }
7791
7792 /* We handle discards by keeping track of the still-live pixels in f0.1.
7793 * Initialize it with the dispatched pixels.
7794 */
7795 if (wm_prog_data->uses_kill) {
7796 const fs_reg dispatch_mask =
7797 devinfo->gen >= 6 ? brw_vec1_grf(1, 7) : brw_vec1_grf(0, 0);
7798 bld.exec_all().group(1, 0)
7799 .MOV(retype(brw_flag_reg(0, 1), BRW_REGISTER_TYPE_UW),
7800 retype(dispatch_mask, BRW_REGISTER_TYPE_UW));
7801 }
7802
7803 emit_nir_code();
7804
7805 if (failed)
7806 return false;
7807
7808 if (wm_prog_data->uses_kill)
7809 bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
7810
7811 if (wm_key->alpha_test_func)
7812 emit_alpha_test();
7813
7814 emit_fb_writes();
7815
7816 if (shader_time_index >= 0)
7817 emit_shader_time_end();
7818
7819 calculate_cfg();
7820
7821 optimize();
7822
7823 assign_curb_setup();
7824
7825 if (devinfo->gen >= 9)
7826 gen9_ps_header_only_workaround(wm_prog_data);
7827
7828 assign_urb_setup();
7829
7830 fixup_3src_null_dest();
7831 allocate_registers(8, allow_spilling);
7832
7833 if (failed)
7834 return false;
7835 }
7836
7837 return !failed;
7838 }
7839
7840 bool
7841 fs_visitor::run_cs(unsigned min_dispatch_width)
7842 {
7843 assert(stage == MESA_SHADER_COMPUTE);
7844 assert(dispatch_width >= min_dispatch_width);
7845
7846 setup_cs_payload();
7847
7848 if (shader_time_index >= 0)
7849 emit_shader_time_begin();
7850
7851 if (devinfo->is_haswell && prog_data->total_shared > 0) {
7852 /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
7853 const fs_builder abld = bld.exec_all().group(1, 0);
7854 abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
7855 suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
7856 }
7857
7858 emit_nir_code();
7859
7860 if (failed)
7861 return false;
7862
7863 emit_cs_terminate();
7864
7865 if (shader_time_index >= 0)
7866 emit_shader_time_end();
7867
7868 calculate_cfg();
7869
7870 optimize();
7871
7872 assign_curb_setup();
7873
7874 fixup_3src_null_dest();
7875 allocate_registers(min_dispatch_width, true);
7876
7877 if (failed)
7878 return false;
7879
7880 return !failed;
7881 }
7882
7883 static bool
7884 is_used_in_not_interp_frag_coord(nir_ssa_def *def)
7885 {
7886 nir_foreach_use(src, def) {
7887 if (src->parent_instr->type != nir_instr_type_intrinsic)
7888 return true;
7889
7890 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(src->parent_instr);
7891 if (intrin->intrinsic != nir_intrinsic_load_frag_coord)
7892 return true;
7893 }
7894
7895 nir_foreach_if_use(src, def)
7896 return true;
7897
7898 return false;
7899 }
7900
7901 /**
7902 * Return a bitfield where bit n is set if barycentric interpolation mode n
7903 * (see enum brw_barycentric_mode) is needed by the fragment shader.
7904 *
7905 * We examine the load_barycentric intrinsics rather than looking at input
7906 * variables so that we catch interpolateAtCentroid() messages too, which
7907 * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
7908 */
7909 static unsigned
7910 brw_compute_barycentric_interp_modes(const struct gen_device_info *devinfo,
7911 const nir_shader *shader)
7912 {
7913 unsigned barycentric_interp_modes = 0;
7914
7915 nir_foreach_function(f, shader) {
7916 if (!f->impl)
7917 continue;
7918
7919 nir_foreach_block(block, f->impl) {
7920 nir_foreach_instr(instr, block) {
7921 if (instr->type != nir_instr_type_intrinsic)
7922 continue;
7923
7924 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7925 switch (intrin->intrinsic) {
7926 case nir_intrinsic_load_barycentric_pixel:
7927 case nir_intrinsic_load_barycentric_centroid:
7928 case nir_intrinsic_load_barycentric_sample:
7929 break;
7930 default:
7931 continue;
7932 }
7933
7934 /* Ignore WPOS; it doesn't require interpolation. */
7935 assert(intrin->dest.is_ssa);
7936 if (!is_used_in_not_interp_frag_coord(&intrin->dest.ssa))
7937 continue;
7938
7939 enum glsl_interp_mode interp = (enum glsl_interp_mode)
7940 nir_intrinsic_interp_mode(intrin);
7941 nir_intrinsic_op bary_op = intrin->intrinsic;
7942 enum brw_barycentric_mode bary =
7943 brw_barycentric_mode(interp, bary_op);
7944
7945 barycentric_interp_modes |= 1 << bary;
7946
7947 if (devinfo->needs_unlit_centroid_workaround &&
7948 bary_op == nir_intrinsic_load_barycentric_centroid)
7949 barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
7950 }
7951 }
7952 }
7953
7954 return barycentric_interp_modes;
7955 }
7956
7957 static void
7958 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
7959 const nir_shader *shader)
7960 {
7961 prog_data->flat_inputs = 0;
7962
7963 nir_foreach_variable(var, &shader->inputs) {
7964 unsigned slots = glsl_count_attribute_slots(var->type, false);
7965 for (unsigned s = 0; s < slots; s++) {
7966 int input_index = prog_data->urb_setup[var->data.location + s];
7967
7968 if (input_index < 0)
7969 continue;
7970
7971 /* flat shading */
7972 if (var->data.interpolation == INTERP_MODE_FLAT)
7973 prog_data->flat_inputs |= 1 << input_index;
7974 }
7975 }
7976 }
7977
7978 static uint8_t
7979 computed_depth_mode(const nir_shader *shader)
7980 {
7981 if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
7982 switch (shader->info.fs.depth_layout) {
7983 case FRAG_DEPTH_LAYOUT_NONE:
7984 case FRAG_DEPTH_LAYOUT_ANY:
7985 return BRW_PSCDEPTH_ON;
7986 case FRAG_DEPTH_LAYOUT_GREATER:
7987 return BRW_PSCDEPTH_ON_GE;
7988 case FRAG_DEPTH_LAYOUT_LESS:
7989 return BRW_PSCDEPTH_ON_LE;
7990 case FRAG_DEPTH_LAYOUT_UNCHANGED:
7991 return BRW_PSCDEPTH_OFF;
7992 }
7993 }
7994 return BRW_PSCDEPTH_OFF;
7995 }
7996
7997 /**
7998 * Move load_interpolated_input with simple (payload-based) barycentric modes
7999 * to the top of the program so we don't emit multiple PLNs for the same input.
8000 *
8001 * This works around CSE not being able to handle non-dominating cases
8002 * such as:
8003 *
8004 * if (...) {
8005 * interpolate input
8006 * } else {
8007 * interpolate the same exact input
8008 * }
8009 *
8010 * This should be replaced by global value numbering someday.
8011 */
8012 static bool
8013 move_interpolation_to_top(nir_shader *nir)
8014 {
8015 bool progress = false;
8016
8017 nir_foreach_function(f, nir) {
8018 if (!f->impl)
8019 continue;
8020
8021 nir_block *top = nir_start_block(f->impl);
8022 exec_node *cursor_node = NULL;
8023
8024 nir_foreach_block(block, f->impl) {
8025 if (block == top)
8026 continue;
8027
8028 nir_foreach_instr_safe(instr, block) {
8029 if (instr->type != nir_instr_type_intrinsic)
8030 continue;
8031
8032 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
8033 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
8034 continue;
8035 nir_intrinsic_instr *bary_intrinsic =
8036 nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
8037 nir_intrinsic_op op = bary_intrinsic->intrinsic;
8038
8039 /* Leave interpolateAtSample/Offset() where they are. */
8040 if (op == nir_intrinsic_load_barycentric_at_sample ||
8041 op == nir_intrinsic_load_barycentric_at_offset)
8042 continue;
8043
8044 nir_instr *move[3] = {
8045 &bary_intrinsic->instr,
8046 intrin->src[1].ssa->parent_instr,
8047 instr
8048 };
8049
8050 for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
8051 if (move[i]->block != top) {
8052 move[i]->block = top;
8053 exec_node_remove(&move[i]->node);
8054 if (cursor_node) {
8055 exec_node_insert_after(cursor_node, &move[i]->node);
8056 } else {
8057 exec_list_push_head(&top->instr_list, &move[i]->node);
8058 }
8059 cursor_node = &move[i]->node;
8060 progress = true;
8061 }
8062 }
8063 }
8064 }
8065 nir_metadata_preserve(f->impl, (nir_metadata)
8066 ((unsigned) nir_metadata_block_index |
8067 (unsigned) nir_metadata_dominance));
8068 }
8069
8070 return progress;
8071 }
8072
8073 /**
8074 * Demote per-sample barycentric intrinsics to centroid.
8075 *
8076 * Useful when rendering to a non-multisampled buffer.
8077 */
8078 static bool
8079 demote_sample_qualifiers(nir_shader *nir)
8080 {
8081 bool progress = true;
8082
8083 nir_foreach_function(f, nir) {
8084 if (!f->impl)
8085 continue;
8086
8087 nir_builder b;
8088 nir_builder_init(&b, f->impl);
8089
8090 nir_foreach_block(block, f->impl) {
8091 nir_foreach_instr_safe(instr, block) {
8092 if (instr->type != nir_instr_type_intrinsic)
8093 continue;
8094
8095 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
8096 if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
8097 intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
8098 continue;
8099
8100 b.cursor = nir_before_instr(instr);
8101 nir_ssa_def *centroid =
8102 nir_load_barycentric(&b, nir_intrinsic_load_barycentric_centroid,
8103 nir_intrinsic_interp_mode(intrin));
8104 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
8105 nir_src_for_ssa(centroid));
8106 nir_instr_remove(instr);
8107 progress = true;
8108 }
8109 }
8110
8111 nir_metadata_preserve(f->impl, (nir_metadata)
8112 ((unsigned) nir_metadata_block_index |
8113 (unsigned) nir_metadata_dominance));
8114 }
8115
8116 return progress;
8117 }
8118
8119 /**
8120 * Pre-gen6, the register file of the EUs was shared between threads,
8121 * and each thread used some subset allocated on a 16-register block
8122 * granularity. The unit states wanted these block counts.
8123 */
8124 static inline int
8125 brw_register_blocks(int reg_count)
8126 {
8127 return ALIGN(reg_count, 16) / 16 - 1;
8128 }
8129
8130 const unsigned *
8131 brw_compile_fs(const struct brw_compiler *compiler, void *log_data,
8132 void *mem_ctx,
8133 const struct brw_wm_prog_key *key,
8134 struct brw_wm_prog_data *prog_data,
8135 nir_shader *shader,
8136 int shader_time_index8, int shader_time_index16,
8137 int shader_time_index32, bool allow_spilling,
8138 bool use_rep_send, struct brw_vue_map *vue_map,
8139 struct brw_compile_stats *stats,
8140 char **error_str)
8141 {
8142 const struct gen_device_info *devinfo = compiler->devinfo;
8143
8144 unsigned max_subgroup_size = unlikely(INTEL_DEBUG & DEBUG_DO32) ? 32 : 16;
8145
8146 brw_nir_apply_key(shader, compiler, &key->base, max_subgroup_size, true);
8147 brw_nir_lower_fs_inputs(shader, devinfo, key);
8148 brw_nir_lower_fs_outputs(shader);
8149
8150 if (devinfo->gen < 6)
8151 brw_setup_vue_interpolation(vue_map, shader, prog_data);
8152
8153 if (!key->multisample_fbo)
8154 NIR_PASS_V(shader, demote_sample_qualifiers);
8155 NIR_PASS_V(shader, move_interpolation_to_top);
8156 brw_postprocess_nir(shader, compiler, true);
8157
8158 /* key->alpha_test_func means simulating alpha testing via discards,
8159 * so the shader definitely kills pixels.
8160 */
8161 prog_data->uses_kill = shader->info.fs.uses_discard ||
8162 key->alpha_test_func;
8163 prog_data->uses_omask = key->multisample_fbo &&
8164 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
8165 prog_data->computed_depth_mode = computed_depth_mode(shader);
8166 prog_data->computed_stencil =
8167 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
8168
8169 prog_data->persample_dispatch =
8170 key->multisample_fbo &&
8171 (key->persample_interp ||
8172 (shader->info.system_values_read & (SYSTEM_BIT_SAMPLE_ID |
8173 SYSTEM_BIT_SAMPLE_POS)) ||
8174 shader->info.fs.uses_sample_qualifier ||
8175 shader->info.outputs_read);
8176
8177 prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
8178
8179 prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
8180 prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
8181 prog_data->inner_coverage = shader->info.fs.inner_coverage;
8182
8183 prog_data->barycentric_interp_modes =
8184 brw_compute_barycentric_interp_modes(compiler->devinfo, shader);
8185
8186 calculate_urb_setup(devinfo, key, prog_data, shader);
8187 brw_compute_flat_inputs(prog_data, shader);
8188
8189 cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL, *simd32_cfg = NULL;
8190
8191 fs_visitor v8(compiler, log_data, mem_ctx, &key->base,
8192 &prog_data->base, shader, 8,
8193 shader_time_index8);
8194 if (!v8.run_fs(allow_spilling, false /* do_rep_send */)) {
8195 if (error_str)
8196 *error_str = ralloc_strdup(mem_ctx, v8.fail_msg);
8197
8198 return NULL;
8199 } else if (likely(!(INTEL_DEBUG & DEBUG_NO8))) {
8200 simd8_cfg = v8.cfg;
8201 prog_data->base.dispatch_grf_start_reg = v8.payload.num_regs;
8202 prog_data->reg_blocks_8 = brw_register_blocks(v8.grf_used);
8203 }
8204
8205 if (v8.max_dispatch_width >= 16 &&
8206 likely(!(INTEL_DEBUG & DEBUG_NO16) || use_rep_send)) {
8207 /* Try a SIMD16 compile */
8208 fs_visitor v16(compiler, log_data, mem_ctx, &key->base,
8209 &prog_data->base, shader, 16,
8210 shader_time_index16);
8211 v16.import_uniforms(&v8);
8212 if (!v16.run_fs(allow_spilling, use_rep_send)) {
8213 compiler->shader_perf_log(log_data,
8214 "SIMD16 shader failed to compile: %s",
8215 v16.fail_msg);
8216 } else {
8217 simd16_cfg = v16.cfg;
8218 prog_data->dispatch_grf_start_reg_16 = v16.payload.num_regs;
8219 prog_data->reg_blocks_16 = brw_register_blocks(v16.grf_used);
8220 }
8221 }
8222
8223 /* Currently, the compiler only supports SIMD32 on SNB+ */
8224 if (v8.max_dispatch_width >= 32 && !use_rep_send &&
8225 compiler->devinfo->gen >= 6 &&
8226 unlikely(INTEL_DEBUG & DEBUG_DO32)) {
8227 /* Try a SIMD32 compile */
8228 fs_visitor v32(compiler, log_data, mem_ctx, &key->base,
8229 &prog_data->base, shader, 32,
8230 shader_time_index32);
8231 v32.import_uniforms(&v8);
8232 if (!v32.run_fs(allow_spilling, false)) {
8233 compiler->shader_perf_log(log_data,
8234 "SIMD32 shader failed to compile: %s",
8235 v32.fail_msg);
8236 } else {
8237 simd32_cfg = v32.cfg;
8238 prog_data->dispatch_grf_start_reg_32 = v32.payload.num_regs;
8239 prog_data->reg_blocks_32 = brw_register_blocks(v32.grf_used);
8240 }
8241 }
8242
8243 /* When the caller requests a repclear shader, they want SIMD16-only */
8244 if (use_rep_send)
8245 simd8_cfg = NULL;
8246
8247 /* Prior to Iron Lake, the PS had a single shader offset with a jump table
8248 * at the top to select the shader. We've never implemented that.
8249 * Instead, we just give them exactly one shader and we pick the widest one
8250 * available.
8251 */
8252 if (compiler->devinfo->gen < 5) {
8253 if (simd32_cfg || simd16_cfg)
8254 simd8_cfg = NULL;
8255 if (simd32_cfg)
8256 simd16_cfg = NULL;
8257 }
8258
8259 /* If computed depth is enabled SNB only allows SIMD8. */
8260 if (compiler->devinfo->gen == 6 &&
8261 prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF)
8262 assert(simd16_cfg == NULL && simd32_cfg == NULL);
8263
8264 if (compiler->devinfo->gen <= 5 && !simd8_cfg) {
8265 /* Iron lake and earlier only have one Dispatch GRF start field. Make
8266 * the data available in the base prog data struct for convenience.
8267 */
8268 if (simd16_cfg) {
8269 prog_data->base.dispatch_grf_start_reg =
8270 prog_data->dispatch_grf_start_reg_16;
8271 } else if (simd32_cfg) {
8272 prog_data->base.dispatch_grf_start_reg =
8273 prog_data->dispatch_grf_start_reg_32;
8274 }
8275 }
8276
8277 if (prog_data->persample_dispatch) {
8278 /* Starting with SandyBridge (where we first get MSAA), the different
8279 * pixel dispatch combinations are grouped into classifications A
8280 * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1). On all hardware
8281 * generations, the only configurations supporting persample dispatch
8282 * are are this in which only one dispatch width is enabled.
8283 */
8284 if (simd32_cfg || simd16_cfg)
8285 simd8_cfg = NULL;
8286 if (simd32_cfg)
8287 simd16_cfg = NULL;
8288 }
8289
8290 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
8291 v8.shader_stats, v8.runtime_check_aads_emit,
8292 MESA_SHADER_FRAGMENT);
8293
8294 if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
8295 g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
8296 shader->info.label ?
8297 shader->info.label : "unnamed",
8298 shader->info.name));
8299 }
8300
8301 if (simd8_cfg) {
8302 prog_data->dispatch_8 = true;
8303 g.generate_code(simd8_cfg, 8, stats);
8304 stats = stats ? stats + 1 : NULL;
8305 }
8306
8307 if (simd16_cfg) {
8308 prog_data->dispatch_16 = true;
8309 prog_data->prog_offset_16 = g.generate_code(simd16_cfg, 16, stats);
8310 stats = stats ? stats + 1 : NULL;
8311 }
8312
8313 if (simd32_cfg) {
8314 prog_data->dispatch_32 = true;
8315 prog_data->prog_offset_32 = g.generate_code(simd32_cfg, 32, stats);
8316 stats = stats ? stats + 1 : NULL;
8317 }
8318
8319 return g.get_assembly();
8320 }
8321
8322 fs_reg *
8323 fs_visitor::emit_cs_work_group_id_setup()
8324 {
8325 assert(stage == MESA_SHADER_COMPUTE);
8326
8327 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
8328
8329 struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
8330 struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
8331 struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
8332
8333 bld.MOV(*reg, r0_1);
8334 bld.MOV(offset(*reg, bld, 1), r0_6);
8335 bld.MOV(offset(*reg, bld, 2), r0_7);
8336
8337 return reg;
8338 }
8339
8340 static void
8341 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
8342 {
8343 block->dwords = dwords;
8344 block->regs = DIV_ROUND_UP(dwords, 8);
8345 block->size = block->regs * 32;
8346 }
8347
8348 static void
8349 cs_fill_push_const_info(const struct gen_device_info *devinfo,
8350 struct brw_cs_prog_data *cs_prog_data)
8351 {
8352 const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
8353 int subgroup_id_index = get_subgroup_id_param_index(prog_data);
8354 bool cross_thread_supported = devinfo->gen > 7 || devinfo->is_haswell;
8355
8356 /* The thread ID should be stored in the last param dword */
8357 assert(subgroup_id_index == -1 ||
8358 subgroup_id_index == (int)prog_data->nr_params - 1);
8359
8360 unsigned cross_thread_dwords, per_thread_dwords;
8361 if (!cross_thread_supported) {
8362 cross_thread_dwords = 0u;
8363 per_thread_dwords = prog_data->nr_params;
8364 } else if (subgroup_id_index >= 0) {
8365 /* Fill all but the last register with cross-thread payload */
8366 cross_thread_dwords = 8 * (subgroup_id_index / 8);
8367 per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
8368 assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
8369 } else {
8370 /* Fill all data using cross-thread payload */
8371 cross_thread_dwords = prog_data->nr_params;
8372 per_thread_dwords = 0u;
8373 }
8374
8375 fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
8376 fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
8377
8378 unsigned total_dwords =
8379 (cs_prog_data->push.per_thread.size * cs_prog_data->threads +
8380 cs_prog_data->push.cross_thread.size) / 4;
8381 fill_push_const_block_info(&cs_prog_data->push.total, total_dwords);
8382
8383 assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
8384 cs_prog_data->push.per_thread.size == 0);
8385 assert(cs_prog_data->push.cross_thread.dwords +
8386 cs_prog_data->push.per_thread.dwords ==
8387 prog_data->nr_params);
8388 }
8389
8390 static void
8391 cs_set_simd_size(struct brw_cs_prog_data *cs_prog_data, unsigned size)
8392 {
8393 cs_prog_data->simd_size = size;
8394 unsigned group_size = cs_prog_data->local_size[0] *
8395 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
8396 cs_prog_data->threads = (group_size + size - 1) / size;
8397 }
8398
8399 static nir_shader *
8400 compile_cs_to_nir(const struct brw_compiler *compiler,
8401 void *mem_ctx,
8402 const struct brw_cs_prog_key *key,
8403 const nir_shader *src_shader,
8404 unsigned dispatch_width)
8405 {
8406 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
8407 brw_nir_apply_key(shader, compiler, &key->base, dispatch_width, true);
8408
8409 NIR_PASS_V(shader, brw_nir_lower_cs_intrinsics, dispatch_width);
8410
8411 /* Clean up after the local index and ID calculations. */
8412 NIR_PASS_V(shader, nir_opt_constant_folding);
8413 NIR_PASS_V(shader, nir_opt_dce);
8414
8415 brw_postprocess_nir(shader, compiler, true);
8416
8417 return shader;
8418 }
8419
8420 const unsigned *
8421 brw_compile_cs(const struct brw_compiler *compiler, void *log_data,
8422 void *mem_ctx,
8423 const struct brw_cs_prog_key *key,
8424 struct brw_cs_prog_data *prog_data,
8425 const nir_shader *src_shader,
8426 int shader_time_index,
8427 struct brw_compile_stats *stats,
8428 char **error_str)
8429 {
8430 prog_data->base.total_shared = src_shader->info.cs.shared_size;
8431 prog_data->local_size[0] = src_shader->info.cs.local_size[0];
8432 prog_data->local_size[1] = src_shader->info.cs.local_size[1];
8433 prog_data->local_size[2] = src_shader->info.cs.local_size[2];
8434 prog_data->slm_size = src_shader->num_shared;
8435 unsigned local_workgroup_size =
8436 src_shader->info.cs.local_size[0] * src_shader->info.cs.local_size[1] *
8437 src_shader->info.cs.local_size[2];
8438
8439 unsigned min_dispatch_width =
8440 DIV_ROUND_UP(local_workgroup_size, compiler->devinfo->max_cs_threads);
8441 min_dispatch_width = MAX2(8, min_dispatch_width);
8442 min_dispatch_width = util_next_power_of_two(min_dispatch_width);
8443 assert(min_dispatch_width <= 32);
8444 unsigned max_dispatch_width = 32;
8445
8446 fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
8447 fs_visitor *v = NULL;
8448 const char *fail_msg = NULL;
8449
8450 if ((int)key->base.subgroup_size_type >= (int)BRW_SUBGROUP_SIZE_REQUIRE_8) {
8451 /* These enum values are expressly chosen to be equal to the subgroup
8452 * size that they require.
8453 */
8454 const unsigned required_dispatch_width =
8455 (unsigned)key->base.subgroup_size_type;
8456 assert(required_dispatch_width == 8 ||
8457 required_dispatch_width == 16 ||
8458 required_dispatch_width == 32);
8459 if (required_dispatch_width < min_dispatch_width ||
8460 required_dispatch_width > max_dispatch_width) {
8461 fail_msg = "Cannot satisfy explicit subgroup size";
8462 } else {
8463 min_dispatch_width = max_dispatch_width = required_dispatch_width;
8464 }
8465 }
8466
8467 /* Now the main event: Visit the shader IR and generate our CS IR for it.
8468 */
8469 if (!fail_msg && min_dispatch_width <= 8 && max_dispatch_width >= 8) {
8470 nir_shader *nir8 = compile_cs_to_nir(compiler, mem_ctx, key,
8471 src_shader, 8);
8472 v8 = new fs_visitor(compiler, log_data, mem_ctx, &key->base,
8473 &prog_data->base,
8474 nir8, 8, shader_time_index);
8475 if (!v8->run_cs(min_dispatch_width)) {
8476 fail_msg = v8->fail_msg;
8477 } else {
8478 /* We should always be able to do SIMD32 for compute shaders */
8479 assert(v8->max_dispatch_width >= 32);
8480
8481 v = v8;
8482 cs_set_simd_size(prog_data, 8);
8483 cs_fill_push_const_info(compiler->devinfo, prog_data);
8484 }
8485 }
8486
8487 if (likely(!(INTEL_DEBUG & DEBUG_NO16)) &&
8488 !fail_msg && min_dispatch_width <= 16 && max_dispatch_width >= 16) {
8489 /* Try a SIMD16 compile */
8490 nir_shader *nir16 = compile_cs_to_nir(compiler, mem_ctx, key,
8491 src_shader, 16);
8492 v16 = new fs_visitor(compiler, log_data, mem_ctx, &key->base,
8493 &prog_data->base,
8494 nir16, 16, shader_time_index);
8495 if (v8)
8496 v16->import_uniforms(v8);
8497
8498 if (!v16->run_cs(min_dispatch_width)) {
8499 compiler->shader_perf_log(log_data,
8500 "SIMD16 shader failed to compile: %s",
8501 v16->fail_msg);
8502 if (!v) {
8503 fail_msg =
8504 "Couldn't generate SIMD16 program and not "
8505 "enough threads for SIMD8";
8506 }
8507 } else {
8508 /* We should always be able to do SIMD32 for compute shaders */
8509 assert(v16->max_dispatch_width >= 32);
8510
8511 v = v16;
8512 cs_set_simd_size(prog_data, 16);
8513 cs_fill_push_const_info(compiler->devinfo, prog_data);
8514 }
8515 }
8516
8517 /* We should always be able to do SIMD32 for compute shaders */
8518 assert(!v16 || v16->max_dispatch_width >= 32);
8519
8520 if (!fail_msg && (min_dispatch_width > 16 || (INTEL_DEBUG & DEBUG_DO32)) &&
8521 max_dispatch_width >= 32) {
8522 /* Try a SIMD32 compile */
8523 nir_shader *nir32 = compile_cs_to_nir(compiler, mem_ctx, key,
8524 src_shader, 32);
8525 v32 = new fs_visitor(compiler, log_data, mem_ctx, &key->base,
8526 &prog_data->base,
8527 nir32, 32, shader_time_index);
8528 if (v8)
8529 v32->import_uniforms(v8);
8530 else if (v16)
8531 v32->import_uniforms(v16);
8532
8533 if (!v32->run_cs(min_dispatch_width)) {
8534 compiler->shader_perf_log(log_data,
8535 "SIMD32 shader failed to compile: %s",
8536 v32->fail_msg);
8537 if (!v) {
8538 fail_msg =
8539 "Couldn't generate SIMD32 program and not "
8540 "enough threads for SIMD16";
8541 }
8542 } else {
8543 v = v32;
8544 cs_set_simd_size(prog_data, 32);
8545 cs_fill_push_const_info(compiler->devinfo, prog_data);
8546 }
8547 }
8548
8549 const unsigned *ret = NULL;
8550 if (unlikely(v == NULL)) {
8551 assert(fail_msg);
8552 if (error_str)
8553 *error_str = ralloc_strdup(mem_ctx, fail_msg);
8554 } else {
8555 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
8556 v->shader_stats, v->runtime_check_aads_emit,
8557 MESA_SHADER_COMPUTE);
8558 if (INTEL_DEBUG & DEBUG_CS) {
8559 char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
8560 src_shader->info.label ?
8561 src_shader->info.label : "unnamed",
8562 src_shader->info.name);
8563 g.enable_debug(name);
8564 }
8565
8566 g.generate_code(v->cfg, prog_data->simd_size, stats);
8567
8568 ret = g.get_assembly();
8569 }
8570
8571 delete v8;
8572 delete v16;
8573 delete v32;
8574
8575 return ret;
8576 }
8577
8578 /**
8579 * Test the dispatch mask packing assumptions of
8580 * brw_stage_has_packed_dispatch(). Call this from e.g. the top of
8581 * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
8582 * executed with an unexpected dispatch mask.
8583 */
8584 static UNUSED void
8585 brw_fs_test_dispatch_packing(const fs_builder &bld)
8586 {
8587 const gl_shader_stage stage = bld.shader->stage;
8588
8589 if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
8590 bld.shader->stage_prog_data)) {
8591 const fs_builder ubld = bld.exec_all().group(1, 0);
8592 const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
8593 const fs_reg mask = (stage == MESA_SHADER_FRAGMENT ? brw_vmask_reg() :
8594 brw_dmask_reg());
8595
8596 ubld.ADD(tmp, mask, brw_imm_ud(1));
8597 ubld.AND(tmp, mask, tmp);
8598
8599 /* This will loop forever if the dispatch mask doesn't have the expected
8600 * form '2^n-1', in which case tmp will be non-zero.
8601 */
8602 bld.emit(BRW_OPCODE_DO);
8603 bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
8604 set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));
8605 }
8606 }