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