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