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