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