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