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