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