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