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