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