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