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