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