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