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