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