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