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