intel/fs: Exclude control sources from execution type and region alignment calculations.
[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 fs_reg low = inst->dst;
4000 if (orig_dst.is_null() || orig_dst.file == MRF ||
4001 regions_overlap(inst->dst, inst->size_written,
4002 inst->src[0], inst->size_read(0)) ||
4003 regions_overlap(inst->dst, inst->size_written,
4004 inst->src[1], inst->size_read(1))) {
4005 needs_mov = true;
4006 /* Get a new VGRF but keep the same stride as inst->dst */
4007 low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
4008 inst->dst.type);
4009 low.stride = inst->dst.stride;
4010 low.offset = inst->dst.offset % REG_SIZE;
4011 }
4012
4013 /* Get a new VGRF but keep the same stride as inst->dst */
4014 fs_reg high(VGRF, alloc.allocate(regs_written(inst)),
4015 inst->dst.type);
4016 high.stride = inst->dst.stride;
4017 high.offset = inst->dst.offset % REG_SIZE;
4018
4019 if (devinfo->gen >= 7) {
4020 if (inst->src[1].abs)
4021 lower_src_modifiers(this, block, inst, 1);
4022
4023 if (inst->src[1].file == IMM) {
4024 ibld.MUL(low, inst->src[0],
4025 brw_imm_uw(inst->src[1].ud & 0xffff));
4026 ibld.MUL(high, inst->src[0],
4027 brw_imm_uw(inst->src[1].ud >> 16));
4028 } else {
4029 ibld.MUL(low, inst->src[0],
4030 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4031 ibld.MUL(high, inst->src[0],
4032 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
4033 }
4034 } else {
4035 if (inst->src[0].abs)
4036 lower_src_modifiers(this, block, inst, 0);
4037
4038 ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
4039 inst->src[1]);
4040 ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
4041 inst->src[1]);
4042 }
4043
4044 ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
4045 subscript(low, BRW_REGISTER_TYPE_UW, 1),
4046 subscript(high, BRW_REGISTER_TYPE_UW, 0));
4047
4048 if (needs_mov || inst->conditional_mod) {
4049 set_condmod(inst->conditional_mod,
4050 ibld.MOV(orig_dst, low));
4051 }
4052 }
4053
4054 } else if (inst->opcode == SHADER_OPCODE_MULH) {
4055 /* According to the BDW+ BSpec page for the "Multiply Accumulate
4056 * High" instruction:
4057 *
4058 * "An added preliminary mov is required for source modification on
4059 * src1:
4060 * mov (8) r3.0<1>:d -r3<8;8,1>:d
4061 * mul (8) acc0:d r2.0<8;8,1>:d r3.0<16;8,2>:uw
4062 * mach (8) r5.0<1>:d r2.0<8;8,1>:d r3.0<8;8,1>:d"
4063 */
4064 if (devinfo->gen >= 8 && (inst->src[1].negate || inst->src[1].abs))
4065 lower_src_modifiers(this, block, inst, 1);
4066
4067 /* Should have been lowered to 8-wide. */
4068 assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
4069 const fs_reg acc = retype(brw_acc_reg(inst->exec_size),
4070 inst->dst.type);
4071 fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
4072 fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
4073
4074 if (devinfo->gen >= 8) {
4075 /* Until Gen8, integer multiplies read 32-bits from one source,
4076 * and 16-bits from the other, and relying on the MACH instruction
4077 * to generate the high bits of the result.
4078 *
4079 * On Gen8, the multiply instruction does a full 32x32-bit
4080 * multiply, but in order to do a 64-bit multiply we can simulate
4081 * the previous behavior and then use a MACH instruction.
4082 */
4083 assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
4084 mul->src[1].type == BRW_REGISTER_TYPE_UD);
4085 mul->src[1].type = BRW_REGISTER_TYPE_UW;
4086 mul->src[1].stride *= 2;
4087
4088 } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
4089 inst->group > 0) {
4090 /* Among other things the quarter control bits influence which
4091 * accumulator register is used by the hardware for instructions
4092 * that access the accumulator implicitly (e.g. MACH). A
4093 * second-half instruction would normally map to acc1, which
4094 * doesn't exist on Gen7 and up (the hardware does emulate it for
4095 * floating-point instructions *only* by taking advantage of the
4096 * extra precision of acc0 not normally used for floating point
4097 * arithmetic).
4098 *
4099 * HSW and up are careful enough not to try to access an
4100 * accumulator register that doesn't exist, but on earlier Gen7
4101 * hardware we need to make sure that the quarter control bits are
4102 * zero to avoid non-deterministic behaviour and emit an extra MOV
4103 * to get the result masked correctly according to the current
4104 * channel enables.
4105 */
4106 mach->group = 0;
4107 mach->force_writemask_all = true;
4108 mach->dst = ibld.vgrf(inst->dst.type);
4109 ibld.MOV(inst->dst, mach->dst);
4110 }
4111 } else {
4112 continue;
4113 }
4114
4115 inst->remove(block);
4116 progress = true;
4117 }
4118
4119 if (progress)
4120 invalidate_live_intervals();
4121
4122 return progress;
4123 }
4124
4125 bool
4126 fs_visitor::lower_minmax()
4127 {
4128 assert(devinfo->gen < 6);
4129
4130 bool progress = false;
4131
4132 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4133 const fs_builder ibld(this, block, inst);
4134
4135 if (inst->opcode == BRW_OPCODE_SEL &&
4136 inst->predicate == BRW_PREDICATE_NONE) {
4137 /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
4138 * the original SEL.L/GE instruction
4139 */
4140 ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4141 inst->conditional_mod);
4142 inst->predicate = BRW_PREDICATE_NORMAL;
4143 inst->conditional_mod = BRW_CONDITIONAL_NONE;
4144
4145 progress = true;
4146 }
4147 }
4148
4149 if (progress)
4150 invalidate_live_intervals();
4151
4152 return progress;
4153 }
4154
4155 static void
4156 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
4157 fs_reg *dst, fs_reg color, unsigned components)
4158 {
4159 if (key->clamp_fragment_color) {
4160 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
4161 assert(color.type == BRW_REGISTER_TYPE_F);
4162
4163 for (unsigned i = 0; i < components; i++)
4164 set_saturate(true,
4165 bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
4166
4167 color = tmp;
4168 }
4169
4170 for (unsigned i = 0; i < components; i++)
4171 dst[i] = offset(color, bld, i);
4172 }
4173
4174 static void
4175 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
4176 const struct brw_wm_prog_data *prog_data,
4177 const brw_wm_prog_key *key,
4178 const fs_visitor::thread_payload &payload)
4179 {
4180 assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
4181 const gen_device_info *devinfo = bld.shader->devinfo;
4182 const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
4183 const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
4184 const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
4185 const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
4186 const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
4187 const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
4188 fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
4189 const unsigned components =
4190 inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
4191
4192 /* We can potentially have a message length of up to 15, so we have to set
4193 * base_mrf to either 0 or 1 in order to fit in m0..m15.
4194 */
4195 fs_reg sources[15];
4196 int header_size = 2, payload_header_size;
4197 unsigned length = 0;
4198
4199 if (devinfo->gen < 6) {
4200 /* TODO: Support SIMD32 on gen4-5 */
4201 assert(bld.group() < 16);
4202
4203 /* For gen4-5, we always have a header consisting of g0 and g1. We have
4204 * an implied MOV from g0,g1 to the start of the message. The MOV from
4205 * g0 is handled by the hardware and the MOV from g1 is provided by the
4206 * generator. This is required because, on gen4-5, the generator may
4207 * generate two write messages with different message lengths in order
4208 * to handle AA data properly.
4209 *
4210 * Also, since the pixel mask goes in the g0 portion of the message and
4211 * since render target writes are the last thing in the shader, we write
4212 * the pixel mask directly into g0 and it will get copied as part of the
4213 * implied write.
4214 */
4215 if (prog_data->uses_kill) {
4216 bld.exec_all().group(1, 0)
4217 .MOV(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW),
4218 brw_flag_reg(0, 1));
4219 }
4220
4221 assert(length == 0);
4222 length = 2;
4223 } else if ((devinfo->gen <= 7 && !devinfo->is_haswell &&
4224 prog_data->uses_kill) ||
4225 color1.file != BAD_FILE ||
4226 key->nr_color_regions > 1) {
4227 /* From the Sandy Bridge PRM, volume 4, page 198:
4228 *
4229 * "Dispatched Pixel Enables. One bit per pixel indicating
4230 * which pixels were originally enabled when the thread was
4231 * dispatched. This field is only required for the end-of-
4232 * thread message and on all dual-source messages."
4233 */
4234 const fs_builder ubld = bld.exec_all().group(8, 0);
4235
4236 fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
4237 if (bld.group() < 16) {
4238 /* The header starts off as g0 and g1 for the first half */
4239 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4240 BRW_REGISTER_TYPE_UD));
4241 } else {
4242 /* The header starts off as g0 and g2 for the second half */
4243 assert(bld.group() < 32);
4244 const fs_reg header_sources[2] = {
4245 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4246 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD),
4247 };
4248 ubld.LOAD_PAYLOAD(header, header_sources, 2, 0);
4249 }
4250
4251 uint32_t g00_bits = 0;
4252
4253 /* Set "Source0 Alpha Present to RenderTarget" bit in message
4254 * header.
4255 */
4256 if (inst->target > 0 && key->replicate_alpha)
4257 g00_bits |= 1 << 11;
4258
4259 /* Set computes stencil to render target */
4260 if (prog_data->computed_stencil)
4261 g00_bits |= 1 << 14;
4262
4263 if (g00_bits) {
4264 /* OR extra bits into g0.0 */
4265 ubld.group(1, 0).OR(component(header, 0),
4266 retype(brw_vec1_grf(0, 0),
4267 BRW_REGISTER_TYPE_UD),
4268 brw_imm_ud(g00_bits));
4269 }
4270
4271 /* Set the render target index for choosing BLEND_STATE. */
4272 if (inst->target > 0) {
4273 ubld.group(1, 0).MOV(component(header, 2), brw_imm_ud(inst->target));
4274 }
4275
4276 if (prog_data->uses_kill) {
4277 assert(bld.group() < 16);
4278 ubld.group(1, 0).MOV(retype(component(header, 15),
4279 BRW_REGISTER_TYPE_UW),
4280 brw_flag_reg(0, 1));
4281 }
4282
4283 assert(length == 0);
4284 sources[0] = header;
4285 sources[1] = horiz_offset(header, 8);
4286 length = 2;
4287 }
4288 assert(length == 0 || length == 2);
4289 header_size = length;
4290
4291 if (payload.aa_dest_stencil_reg[0]) {
4292 assert(inst->group < 16);
4293 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
4294 bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
4295 .MOV(sources[length],
4296 fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg[0], 0)));
4297 length++;
4298 }
4299
4300 if (sample_mask.file != BAD_FILE) {
4301 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
4302 BRW_REGISTER_TYPE_UD);
4303
4304 /* Hand over gl_SampleMask. Only the lower 16 bits of each channel are
4305 * relevant. Since it's unsigned single words one vgrf is always
4306 * 16-wide, but only the lower or higher 8 channels will be used by the
4307 * hardware when doing a SIMD8 write depending on whether we have
4308 * selected the subspans for the first or second half respectively.
4309 */
4310 assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
4311 sample_mask.type = BRW_REGISTER_TYPE_UW;
4312 sample_mask.stride *= 2;
4313
4314 bld.exec_all().annotate("FB write oMask")
4315 .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
4316 inst->group % 16),
4317 sample_mask);
4318 length++;
4319 }
4320
4321 payload_header_size = length;
4322
4323 if (src0_alpha.file != BAD_FILE) {
4324 /* FIXME: This is being passed at the wrong location in the payload and
4325 * doesn't work when gl_SampleMask and MRTs are used simultaneously.
4326 * It's supposed to be immediately before oMask but there seems to be no
4327 * reasonable way to pass them in the correct order because LOAD_PAYLOAD
4328 * requires header sources to form a contiguous segment at the beginning
4329 * of the message and src0_alpha has per-channel semantics.
4330 */
4331 setup_color_payload(bld, key, &sources[length], src0_alpha, 1);
4332 length++;
4333 } else if (key->replicate_alpha && inst->target != 0) {
4334 /* Handle the case when fragment shader doesn't write to draw buffer
4335 * zero. No need to call setup_color_payload() for src0_alpha because
4336 * alpha value will be undefined.
4337 */
4338 length++;
4339 }
4340
4341 setup_color_payload(bld, key, &sources[length], color0, components);
4342 length += 4;
4343
4344 if (color1.file != BAD_FILE) {
4345 setup_color_payload(bld, key, &sources[length], color1, components);
4346 length += 4;
4347 }
4348
4349 if (src_depth.file != BAD_FILE) {
4350 sources[length] = src_depth;
4351 length++;
4352 }
4353
4354 if (dst_depth.file != BAD_FILE) {
4355 sources[length] = dst_depth;
4356 length++;
4357 }
4358
4359 if (src_stencil.file != BAD_FILE) {
4360 assert(devinfo->gen >= 9);
4361 assert(bld.dispatch_width() == 8);
4362
4363 /* XXX: src_stencil is only available on gen9+. dst_depth is never
4364 * available on gen9+. As such it's impossible to have both enabled at the
4365 * same time and therefore length cannot overrun the array.
4366 */
4367 assert(length < 15);
4368
4369 sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
4370 bld.exec_all().annotate("FB write OS")
4371 .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
4372 subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
4373 length++;
4374 }
4375
4376 fs_inst *load;
4377 if (devinfo->gen >= 7) {
4378 /* Send from the GRF */
4379 fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
4380 load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
4381 payload.nr = bld.shader->alloc.allocate(regs_written(load));
4382 load->dst = payload;
4383
4384 inst->src[0] = payload;
4385 inst->resize_sources(1);
4386 } else {
4387 /* Send from the MRF */
4388 load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
4389 sources, length, payload_header_size);
4390
4391 /* On pre-SNB, we have to interlace the color values. LOAD_PAYLOAD
4392 * will do this for us if we just give it a COMPR4 destination.
4393 */
4394 if (devinfo->gen < 6 && bld.dispatch_width() == 16)
4395 load->dst.nr |= BRW_MRF_COMPR4;
4396
4397 if (devinfo->gen < 6) {
4398 /* Set up src[0] for the implied MOV from grf0-1 */
4399 inst->resize_sources(1);
4400 inst->src[0] = brw_vec8_grf(0, 0);
4401 } else {
4402 inst->resize_sources(0);
4403 }
4404 inst->base_mrf = 1;
4405 }
4406
4407 inst->opcode = FS_OPCODE_FB_WRITE;
4408 inst->mlen = regs_written(load);
4409 inst->header_size = header_size;
4410 }
4411
4412 static void
4413 lower_fb_read_logical_send(const fs_builder &bld, fs_inst *inst)
4414 {
4415 const fs_builder &ubld = bld.exec_all().group(8, 0);
4416 const unsigned length = 2;
4417 const fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, length);
4418
4419 if (bld.group() < 16) {
4420 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4421 BRW_REGISTER_TYPE_UD));
4422 } else {
4423 assert(bld.group() < 32);
4424 const fs_reg header_sources[] = {
4425 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4426 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD)
4427 };
4428 ubld.LOAD_PAYLOAD(header, header_sources, ARRAY_SIZE(header_sources), 0);
4429 }
4430
4431 inst->resize_sources(1);
4432 inst->src[0] = header;
4433 inst->opcode = FS_OPCODE_FB_READ;
4434 inst->mlen = length;
4435 inst->header_size = length;
4436 }
4437
4438 static void
4439 lower_sampler_logical_send_gen4(const fs_builder &bld, fs_inst *inst, opcode op,
4440 const fs_reg &coordinate,
4441 const fs_reg &shadow_c,
4442 const fs_reg &lod, const fs_reg &lod2,
4443 const fs_reg &surface,
4444 const fs_reg &sampler,
4445 unsigned coord_components,
4446 unsigned grad_components)
4447 {
4448 const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
4449 op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
4450 fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
4451 fs_reg msg_end = msg_begin;
4452
4453 /* g0 header. */
4454 msg_end = offset(msg_end, bld.group(8, 0), 1);
4455
4456 for (unsigned i = 0; i < coord_components; i++)
4457 bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
4458 offset(coordinate, bld, i));
4459
4460 msg_end = offset(msg_end, bld, coord_components);
4461
4462 /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
4463 * require all three components to be present and zero if they are unused.
4464 */
4465 if (coord_components > 0 &&
4466 (has_lod || shadow_c.file != BAD_FILE ||
4467 (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
4468 for (unsigned i = coord_components; i < 3; i++)
4469 bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
4470
4471 msg_end = offset(msg_end, bld, 3 - coord_components);
4472 }
4473
4474 if (op == SHADER_OPCODE_TXD) {
4475 /* TXD unsupported in SIMD16 mode. */
4476 assert(bld.dispatch_width() == 8);
4477
4478 /* the slots for u and v are always present, but r is optional */
4479 if (coord_components < 2)
4480 msg_end = offset(msg_end, bld, 2 - coord_components);
4481
4482 /* P = u, v, r
4483 * dPdx = dudx, dvdx, drdx
4484 * dPdy = dudy, dvdy, drdy
4485 *
4486 * 1-arg: Does not exist.
4487 *
4488 * 2-arg: dudx dvdx dudy dvdy
4489 * dPdx.x dPdx.y dPdy.x dPdy.y
4490 * m4 m5 m6 m7
4491 *
4492 * 3-arg: dudx dvdx drdx dudy dvdy drdy
4493 * dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
4494 * m5 m6 m7 m8 m9 m10
4495 */
4496 for (unsigned i = 0; i < grad_components; i++)
4497 bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
4498
4499 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4500
4501 for (unsigned i = 0; i < grad_components; i++)
4502 bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
4503
4504 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4505 }
4506
4507 if (has_lod) {
4508 /* Bias/LOD with shadow comparator is unsupported in SIMD16 -- *Without*
4509 * shadow comparator (including RESINFO) it's unsupported in SIMD8 mode.
4510 */
4511 assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
4512 bld.dispatch_width() == 16);
4513
4514 const brw_reg_type type =
4515 (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
4516 BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
4517 bld.MOV(retype(msg_end, type), lod);
4518 msg_end = offset(msg_end, bld, 1);
4519 }
4520
4521 if (shadow_c.file != BAD_FILE) {
4522 if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
4523 /* There's no plain shadow compare message, so we use shadow
4524 * compare with a bias of 0.0.
4525 */
4526 bld.MOV(msg_end, brw_imm_f(0.0f));
4527 msg_end = offset(msg_end, bld, 1);
4528 }
4529
4530 bld.MOV(msg_end, shadow_c);
4531 msg_end = offset(msg_end, bld, 1);
4532 }
4533
4534 inst->opcode = op;
4535 inst->src[0] = reg_undef;
4536 inst->src[1] = surface;
4537 inst->src[2] = sampler;
4538 inst->resize_sources(3);
4539 inst->base_mrf = msg_begin.nr;
4540 inst->mlen = msg_end.nr - msg_begin.nr;
4541 inst->header_size = 1;
4542 }
4543
4544 static void
4545 lower_sampler_logical_send_gen5(const fs_builder &bld, fs_inst *inst, opcode op,
4546 const fs_reg &coordinate,
4547 const fs_reg &shadow_c,
4548 const fs_reg &lod, const fs_reg &lod2,
4549 const fs_reg &sample_index,
4550 const fs_reg &surface,
4551 const fs_reg &sampler,
4552 unsigned coord_components,
4553 unsigned grad_components)
4554 {
4555 fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
4556 fs_reg msg_coords = message;
4557 unsigned header_size = 0;
4558
4559 if (inst->offset != 0) {
4560 /* The offsets set up by the visitor are in the m1 header, so we can't
4561 * go headerless.
4562 */
4563 header_size = 1;
4564 message.nr--;
4565 }
4566
4567 for (unsigned i = 0; i < coord_components; i++)
4568 bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
4569 offset(coordinate, bld, i));
4570
4571 fs_reg msg_end = offset(msg_coords, bld, coord_components);
4572 fs_reg msg_lod = offset(msg_coords, bld, 4);
4573
4574 if (shadow_c.file != BAD_FILE) {
4575 fs_reg msg_shadow = msg_lod;
4576 bld.MOV(msg_shadow, shadow_c);
4577 msg_lod = offset(msg_shadow, bld, 1);
4578 msg_end = msg_lod;
4579 }
4580
4581 switch (op) {
4582 case SHADER_OPCODE_TXL:
4583 case FS_OPCODE_TXB:
4584 bld.MOV(msg_lod, lod);
4585 msg_end = offset(msg_lod, bld, 1);
4586 break;
4587 case SHADER_OPCODE_TXD:
4588 /**
4589 * P = u, v, r
4590 * dPdx = dudx, dvdx, drdx
4591 * dPdy = dudy, dvdy, drdy
4592 *
4593 * Load up these values:
4594 * - dudx dudy dvdx dvdy drdx drdy
4595 * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
4596 */
4597 msg_end = msg_lod;
4598 for (unsigned i = 0; i < grad_components; i++) {
4599 bld.MOV(msg_end, offset(lod, bld, i));
4600 msg_end = offset(msg_end, bld, 1);
4601
4602 bld.MOV(msg_end, offset(lod2, bld, i));
4603 msg_end = offset(msg_end, bld, 1);
4604 }
4605 break;
4606 case SHADER_OPCODE_TXS:
4607 msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
4608 bld.MOV(msg_lod, lod);
4609 msg_end = offset(msg_lod, bld, 1);
4610 break;
4611 case SHADER_OPCODE_TXF:
4612 msg_lod = offset(msg_coords, bld, 3);
4613 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
4614 msg_end = offset(msg_lod, bld, 1);
4615 break;
4616 case SHADER_OPCODE_TXF_CMS:
4617 msg_lod = offset(msg_coords, bld, 3);
4618 /* lod */
4619 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
4620 /* sample index */
4621 bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
4622 msg_end = offset(msg_lod, bld, 2);
4623 break;
4624 default:
4625 break;
4626 }
4627
4628 inst->opcode = op;
4629 inst->src[0] = reg_undef;
4630 inst->src[1] = surface;
4631 inst->src[2] = sampler;
4632 inst->resize_sources(3);
4633 inst->base_mrf = message.nr;
4634 inst->mlen = msg_end.nr - message.nr;
4635 inst->header_size = header_size;
4636
4637 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4638 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4639 }
4640
4641 static bool
4642 is_high_sampler(const struct gen_device_info *devinfo, const fs_reg &sampler)
4643 {
4644 if (devinfo->gen < 8 && !devinfo->is_haswell)
4645 return false;
4646
4647 return sampler.file != IMM || sampler.ud >= 16;
4648 }
4649
4650 static unsigned
4651 sampler_msg_type(const gen_device_info *devinfo,
4652 opcode opcode, bool shadow_compare)
4653 {
4654 assert(devinfo->gen >= 5);
4655 switch (opcode) {
4656 case SHADER_OPCODE_TEX:
4657 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_COMPARE :
4658 GEN5_SAMPLER_MESSAGE_SAMPLE;
4659 case FS_OPCODE_TXB:
4660 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS_COMPARE :
4661 GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS;
4662 case SHADER_OPCODE_TXL:
4663 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_LOD_COMPARE :
4664 GEN5_SAMPLER_MESSAGE_SAMPLE_LOD;
4665 case SHADER_OPCODE_TXL_LZ:
4666 return shadow_compare ? GEN9_SAMPLER_MESSAGE_SAMPLE_C_LZ :
4667 GEN9_SAMPLER_MESSAGE_SAMPLE_LZ;
4668 case SHADER_OPCODE_TXS:
4669 case SHADER_OPCODE_IMAGE_SIZE:
4670 return GEN5_SAMPLER_MESSAGE_SAMPLE_RESINFO;
4671 case SHADER_OPCODE_TXD:
4672 assert(!shadow_compare || devinfo->gen >= 8 || devinfo->is_haswell);
4673 return shadow_compare ? HSW_SAMPLER_MESSAGE_SAMPLE_DERIV_COMPARE :
4674 GEN5_SAMPLER_MESSAGE_SAMPLE_DERIVS;
4675 case SHADER_OPCODE_TXF:
4676 return GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4677 case SHADER_OPCODE_TXF_LZ:
4678 assert(devinfo->gen >= 9);
4679 return GEN9_SAMPLER_MESSAGE_SAMPLE_LD_LZ;
4680 case SHADER_OPCODE_TXF_CMS_W:
4681 assert(devinfo->gen >= 9);
4682 return GEN9_SAMPLER_MESSAGE_SAMPLE_LD2DMS_W;
4683 case SHADER_OPCODE_TXF_CMS:
4684 return devinfo->gen >= 7 ? GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DMS :
4685 GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4686 case SHADER_OPCODE_TXF_UMS:
4687 assert(devinfo->gen >= 7);
4688 return GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DSS;
4689 case SHADER_OPCODE_TXF_MCS:
4690 assert(devinfo->gen >= 7);
4691 return GEN7_SAMPLER_MESSAGE_SAMPLE_LD_MCS;
4692 case SHADER_OPCODE_LOD:
4693 return GEN5_SAMPLER_MESSAGE_LOD;
4694 case SHADER_OPCODE_TG4:
4695 assert(devinfo->gen >= 7);
4696 return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_C :
4697 GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4;
4698 break;
4699 case SHADER_OPCODE_TG4_OFFSET:
4700 assert(devinfo->gen >= 7);
4701 return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO_C :
4702 GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO;
4703 case SHADER_OPCODE_SAMPLEINFO:
4704 return GEN6_SAMPLER_MESSAGE_SAMPLE_SAMPLEINFO;
4705 default:
4706 unreachable("not reached");
4707 }
4708 }
4709
4710 static void
4711 lower_sampler_logical_send_gen7(const fs_builder &bld, fs_inst *inst, opcode op,
4712 const fs_reg &coordinate,
4713 const fs_reg &shadow_c,
4714 fs_reg lod, const fs_reg &lod2,
4715 const fs_reg &min_lod,
4716 const fs_reg &sample_index,
4717 const fs_reg &mcs,
4718 const fs_reg &surface,
4719 const fs_reg &sampler,
4720 const fs_reg &tg4_offset,
4721 unsigned coord_components,
4722 unsigned grad_components)
4723 {
4724 const gen_device_info *devinfo = bld.shader->devinfo;
4725 const brw_stage_prog_data *prog_data = bld.shader->stage_prog_data;
4726 unsigned reg_width = bld.dispatch_width() / 8;
4727 unsigned header_size = 0, length = 0;
4728 fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
4729 for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
4730 sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
4731
4732 if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
4733 inst->offset != 0 || inst->eot ||
4734 op == SHADER_OPCODE_SAMPLEINFO ||
4735 is_high_sampler(devinfo, sampler)) {
4736 /* For general texture offsets (no txf workaround), we need a header to
4737 * put them in.
4738 *
4739 * TG4 needs to place its channel select in the header, for interaction
4740 * with ARB_texture_swizzle. The sampler index is only 4-bits, so for
4741 * larger sampler numbers we need to offset the Sampler State Pointer in
4742 * the header.
4743 */
4744 fs_reg header = retype(sources[0], BRW_REGISTER_TYPE_UD);
4745 header_size = 1;
4746 length++;
4747
4748 /* If we're requesting fewer than four channels worth of response,
4749 * and we have an explicit header, we need to set up the sampler
4750 * writemask. It's reversed from normal: 1 means "don't write".
4751 */
4752 if (!inst->eot && regs_written(inst) != 4 * reg_width) {
4753 assert(regs_written(inst) % reg_width == 0);
4754 unsigned mask = ~((1 << (regs_written(inst) / reg_width)) - 1) & 0xf;
4755 inst->offset |= mask << 12;
4756 }
4757
4758 /* Build the actual header */
4759 const fs_builder ubld = bld.exec_all().group(8, 0);
4760 const fs_builder ubld1 = ubld.group(1, 0);
4761 ubld.MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
4762 if (inst->offset) {
4763 ubld1.MOV(component(header, 2), brw_imm_ud(inst->offset));
4764 } else if (bld.shader->stage != MESA_SHADER_VERTEX &&
4765 bld.shader->stage != MESA_SHADER_FRAGMENT) {
4766 /* The vertex and fragment stages have g0.2 set to 0, so
4767 * header0.2 is 0 when g0 is copied. Other stages may not, so we
4768 * must set it to 0 to avoid setting undesirable bits in the
4769 * message.
4770 */
4771 ubld1.MOV(component(header, 2), brw_imm_ud(0));
4772 }
4773
4774 if (is_high_sampler(devinfo, sampler)) {
4775 if (sampler.file == BRW_IMMEDIATE_VALUE) {
4776 assert(sampler.ud >= 16);
4777 const int sampler_state_size = 16; /* 16 bytes */
4778
4779 ubld1.ADD(component(header, 3),
4780 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4781 brw_imm_ud(16 * (sampler.ud / 16) * sampler_state_size));
4782 } else {
4783 fs_reg tmp = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
4784 ubld1.AND(tmp, sampler, brw_imm_ud(0x0f0));
4785 ubld1.SHL(tmp, tmp, brw_imm_ud(4));
4786 ubld1.ADD(component(header, 3),
4787 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4788 tmp);
4789 }
4790 }
4791 }
4792
4793 if (shadow_c.file != BAD_FILE) {
4794 bld.MOV(sources[length], shadow_c);
4795 length++;
4796 }
4797
4798 bool coordinate_done = false;
4799
4800 /* Set up the LOD info */
4801 switch (op) {
4802 case FS_OPCODE_TXB:
4803 case SHADER_OPCODE_TXL:
4804 if (devinfo->gen >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
4805 op = SHADER_OPCODE_TXL_LZ;
4806 break;
4807 }
4808 bld.MOV(sources[length], lod);
4809 length++;
4810 break;
4811 case SHADER_OPCODE_TXD:
4812 /* TXD should have been lowered in SIMD16 mode. */
4813 assert(bld.dispatch_width() == 8);
4814
4815 /* Load dPdx and the coordinate together:
4816 * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
4817 */
4818 for (unsigned i = 0; i < coord_components; i++) {
4819 bld.MOV(sources[length++], offset(coordinate, bld, i));
4820
4821 /* For cube map array, the coordinate is (u,v,r,ai) but there are
4822 * only derivatives for (u, v, r).
4823 */
4824 if (i < grad_components) {
4825 bld.MOV(sources[length++], offset(lod, bld, i));
4826 bld.MOV(sources[length++], offset(lod2, bld, i));
4827 }
4828 }
4829
4830 coordinate_done = true;
4831 break;
4832 case SHADER_OPCODE_TXS:
4833 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
4834 length++;
4835 break;
4836 case SHADER_OPCODE_IMAGE_SIZE:
4837 /* We need an LOD; just use 0 */
4838 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), brw_imm_ud(0));
4839 length++;
4840 break;
4841 case SHADER_OPCODE_TXF:
4842 /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
4843 * On Gen9 they are u, v, lod, r
4844 */
4845 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
4846
4847 if (devinfo->gen >= 9) {
4848 if (coord_components >= 2) {
4849 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
4850 offset(coordinate, bld, 1));
4851 } else {
4852 sources[length] = brw_imm_d(0);
4853 }
4854 length++;
4855 }
4856
4857 if (devinfo->gen >= 9 && lod.is_zero()) {
4858 op = SHADER_OPCODE_TXF_LZ;
4859 } else {
4860 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
4861 length++;
4862 }
4863
4864 for (unsigned i = devinfo->gen >= 9 ? 2 : 1; i < coord_components; i++)
4865 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4866 offset(coordinate, bld, i));
4867
4868 coordinate_done = true;
4869 break;
4870
4871 case SHADER_OPCODE_TXF_CMS:
4872 case SHADER_OPCODE_TXF_CMS_W:
4873 case SHADER_OPCODE_TXF_UMS:
4874 case SHADER_OPCODE_TXF_MCS:
4875 if (op == SHADER_OPCODE_TXF_UMS ||
4876 op == SHADER_OPCODE_TXF_CMS ||
4877 op == SHADER_OPCODE_TXF_CMS_W) {
4878 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
4879 length++;
4880 }
4881
4882 if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
4883 /* Data from the multisample control surface. */
4884 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
4885 length++;
4886
4887 /* On Gen9+ we'll use ld2dms_w instead which has two registers for
4888 * the MCS data.
4889 */
4890 if (op == SHADER_OPCODE_TXF_CMS_W) {
4891 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
4892 mcs.file == IMM ?
4893 mcs :
4894 offset(mcs, bld, 1));
4895 length++;
4896 }
4897 }
4898
4899 /* There is no offsetting for this message; just copy in the integer
4900 * texture coordinates.
4901 */
4902 for (unsigned i = 0; i < coord_components; i++)
4903 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4904 offset(coordinate, bld, i));
4905
4906 coordinate_done = true;
4907 break;
4908 case SHADER_OPCODE_TG4_OFFSET:
4909 /* More crazy intermixing */
4910 for (unsigned i = 0; i < 2; i++) /* u, v */
4911 bld.MOV(sources[length++], offset(coordinate, bld, i));
4912
4913 for (unsigned i = 0; i < 2; i++) /* offu, offv */
4914 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4915 offset(tg4_offset, bld, i));
4916
4917 if (coord_components == 3) /* r if present */
4918 bld.MOV(sources[length++], offset(coordinate, bld, 2));
4919
4920 coordinate_done = true;
4921 break;
4922 default:
4923 break;
4924 }
4925
4926 /* Set up the coordinate (except for cases where it was done above) */
4927 if (!coordinate_done) {
4928 for (unsigned i = 0; i < coord_components; i++)
4929 bld.MOV(sources[length++], offset(coordinate, bld, i));
4930 }
4931
4932 if (min_lod.file != BAD_FILE) {
4933 /* Account for all of the missing coordinate sources */
4934 length += 4 - coord_components;
4935 if (op == SHADER_OPCODE_TXD)
4936 length += (3 - grad_components) * 2;
4937
4938 bld.MOV(sources[length++], min_lod);
4939 }
4940
4941 unsigned mlen;
4942 if (reg_width == 2)
4943 mlen = length * reg_width - header_size;
4944 else
4945 mlen = length * reg_width;
4946
4947 const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
4948 BRW_REGISTER_TYPE_F);
4949 bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
4950
4951 /* Generate the SEND. */
4952 inst->opcode = SHADER_OPCODE_SEND;
4953 inst->mlen = mlen;
4954 inst->header_size = header_size;
4955
4956 const unsigned msg_type =
4957 sampler_msg_type(devinfo, op, inst->shadow_compare);
4958 const unsigned simd_mode =
4959 inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
4960 BRW_SAMPLER_SIMD_MODE_SIMD16;
4961
4962 uint32_t base_binding_table_index;
4963 switch (op) {
4964 case SHADER_OPCODE_TG4:
4965 case SHADER_OPCODE_TG4_OFFSET:
4966 base_binding_table_index = prog_data->binding_table.gather_texture_start;
4967 break;
4968 case SHADER_OPCODE_IMAGE_SIZE:
4969 base_binding_table_index = prog_data->binding_table.image_start;
4970 break;
4971 default:
4972 base_binding_table_index = prog_data->binding_table.texture_start;
4973 break;
4974 }
4975
4976 inst->sfid = BRW_SFID_SAMPLER;
4977 if (surface.file == IMM && sampler.file == IMM) {
4978 inst->desc = brw_sampler_desc(devinfo,
4979 surface.ud + base_binding_table_index,
4980 sampler.ud % 16,
4981 msg_type,
4982 simd_mode,
4983 0 /* return_format unused on gen7+ */);
4984 inst->src[0] = brw_imm_ud(0);
4985 } else {
4986 /* Immediate portion of the descriptor */
4987 inst->desc = brw_sampler_desc(devinfo,
4988 0, /* surface */
4989 0, /* sampler */
4990 msg_type,
4991 simd_mode,
4992 0 /* return_format unused on gen7+ */);
4993 const fs_builder ubld = bld.group(1, 0).exec_all();
4994 fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4995 if (surface.equals(sampler)) {
4996 /* This case is common in GL */
4997 ubld.MUL(desc, surface, brw_imm_ud(0x101));
4998 } else {
4999 if (sampler.file == IMM) {
5000 ubld.OR(desc, surface, brw_imm_ud(sampler.ud << 8));
5001 } else {
5002 ubld.SHL(desc, sampler, brw_imm_ud(8));
5003 ubld.OR(desc, desc, surface);
5004 }
5005 }
5006 if (base_binding_table_index)
5007 ubld.ADD(desc, desc, brw_imm_ud(base_binding_table_index));
5008 ubld.AND(desc, desc, brw_imm_ud(0xfff));
5009
5010 inst->src[0] = component(desc, 0);
5011 }
5012 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5013
5014 inst->src[2] = src_payload;
5015 inst->resize_sources(3);
5016
5017 if (inst->eot) {
5018 /* EOT sampler messages don't make sense to split because it would
5019 * involve ending half of the thread early.
5020 */
5021 assert(inst->group == 0);
5022 /* We need to use SENDC for EOT sampler messages */
5023 inst->check_tdr = true;
5024 inst->send_has_side_effects = true;
5025 }
5026
5027 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
5028 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
5029 }
5030
5031 static void
5032 lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
5033 {
5034 const gen_device_info *devinfo = bld.shader->devinfo;
5035 const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
5036 const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
5037 const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
5038 const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
5039 const fs_reg &min_lod = inst->src[TEX_LOGICAL_SRC_MIN_LOD];
5040 const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
5041 const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
5042 const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
5043 const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
5044 const fs_reg &tg4_offset = inst->src[TEX_LOGICAL_SRC_TG4_OFFSET];
5045 assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
5046 const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
5047 assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
5048 const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
5049
5050 if (devinfo->gen >= 7) {
5051 lower_sampler_logical_send_gen7(bld, inst, op, coordinate,
5052 shadow_c, lod, lod2, min_lod,
5053 sample_index,
5054 mcs, surface, sampler, tg4_offset,
5055 coord_components, grad_components);
5056 } else if (devinfo->gen >= 5) {
5057 lower_sampler_logical_send_gen5(bld, inst, op, coordinate,
5058 shadow_c, lod, lod2, sample_index,
5059 surface, sampler,
5060 coord_components, grad_components);
5061 } else {
5062 lower_sampler_logical_send_gen4(bld, inst, op, coordinate,
5063 shadow_c, lod, lod2,
5064 surface, sampler,
5065 coord_components, grad_components);
5066 }
5067 }
5068
5069 /**
5070 * Initialize the header present in some typed and untyped surface
5071 * messages.
5072 */
5073 static fs_reg
5074 emit_surface_header(const fs_builder &bld, const fs_reg &sample_mask)
5075 {
5076 fs_builder ubld = bld.exec_all().group(8, 0);
5077 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5078 ubld.MOV(dst, brw_imm_d(0));
5079 ubld.group(1, 0).MOV(component(dst, 7), sample_mask);
5080 return dst;
5081 }
5082
5083 static void
5084 lower_surface_logical_send(const fs_builder &bld, fs_inst *inst)
5085 {
5086 const gen_device_info *devinfo = bld.shader->devinfo;
5087
5088 /* Get the logical send arguments. */
5089 const fs_reg &addr = inst->src[0];
5090 const fs_reg &src = inst->src[1];
5091 const fs_reg &surface = inst->src[2];
5092 const UNUSED fs_reg &dims = inst->src[3];
5093 const fs_reg &arg = inst->src[4];
5094 assert(arg.file == IMM);
5095
5096 /* Calculate the total number of components of the payload. */
5097 const unsigned addr_sz = inst->components_read(0);
5098 const unsigned src_sz = inst->components_read(1);
5099
5100 const bool is_typed_access =
5101 inst->opcode == SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL ||
5102 inst->opcode == SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL ||
5103 inst->opcode == SHADER_OPCODE_TYPED_ATOMIC_LOGICAL;
5104
5105 /* From the BDW PRM Volume 7, page 147:
5106 *
5107 * "For the Data Cache Data Port*, the header must be present for the
5108 * following message types: [...] Typed read/write/atomics"
5109 *
5110 * Earlier generations have a similar wording. Because of this restriction
5111 * we don't attempt to implement sample masks via predication for such
5112 * messages prior to Gen9, since we have to provide a header anyway. On
5113 * Gen11+ the header has been removed so we can only use predication.
5114 */
5115 const unsigned header_sz = devinfo->gen < 9 && is_typed_access ? 1 : 0;
5116
5117 const bool has_side_effects = inst->has_side_effects();
5118 fs_reg sample_mask = has_side_effects ? bld.sample_mask_reg() :
5119 fs_reg(brw_imm_d(0xffff));
5120
5121 fs_reg payload, payload2;
5122 unsigned mlen, ex_mlen = 0;
5123 if (devinfo->gen >= 9) {
5124 /* We have split sends on gen9 and above */
5125 assert(header_sz == 0);
5126 payload = bld.move_to_vgrf(addr, addr_sz);
5127 payload2 = bld.move_to_vgrf(src, src_sz);
5128 mlen = addr_sz * (inst->exec_size / 8);
5129 ex_mlen = src_sz * (inst->exec_size / 8);
5130 } else {
5131 /* Allocate space for the payload. */
5132 const unsigned sz = header_sz + addr_sz + src_sz;
5133 payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
5134 fs_reg *const components = new fs_reg[sz];
5135 unsigned n = 0;
5136
5137 /* Construct the payload. */
5138 if (header_sz)
5139 components[n++] = emit_surface_header(bld, sample_mask);
5140
5141 for (unsigned i = 0; i < addr_sz; i++)
5142 components[n++] = offset(addr, bld, i);
5143
5144 for (unsigned i = 0; i < src_sz; i++)
5145 components[n++] = offset(src, bld, i);
5146
5147 bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
5148 mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
5149
5150 delete[] components;
5151 }
5152
5153 /* Predicate the instruction on the sample mask if no header is
5154 * provided.
5155 */
5156 if (!header_sz && sample_mask.file != BAD_FILE &&
5157 sample_mask.file != IMM) {
5158 const fs_builder ubld = bld.group(1, 0).exec_all();
5159 if (inst->predicate) {
5160 assert(inst->predicate == BRW_PREDICATE_NORMAL);
5161 assert(!inst->predicate_inverse);
5162 assert(inst->flag_subreg < 2);
5163 /* Combine the sample mask with the existing predicate by using a
5164 * vertical predication mode.
5165 */
5166 inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
5167 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg + 2),
5168 sample_mask.type),
5169 sample_mask);
5170 } else {
5171 inst->flag_subreg = 2;
5172 inst->predicate = BRW_PREDICATE_NORMAL;
5173 inst->predicate_inverse = false;
5174 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5175 sample_mask);
5176 }
5177 }
5178
5179 uint32_t sfid;
5180 switch (inst->opcode) {
5181 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5182 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5183 /* Byte scattered opcodes go through the normal data cache */
5184 sfid = GEN7_SFID_DATAPORT_DATA_CACHE;
5185 break;
5186
5187 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5188 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5189 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5190 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5191 /* Untyped Surface messages go through the data cache but the SFID value
5192 * changed on Haswell.
5193 */
5194 sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5195 HSW_SFID_DATAPORT_DATA_CACHE_1 :
5196 GEN7_SFID_DATAPORT_DATA_CACHE);
5197 break;
5198
5199 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5200 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5201 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5202 /* Typed surface messages go through the render cache on IVB and the
5203 * data cache on HSW+.
5204 */
5205 sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5206 HSW_SFID_DATAPORT_DATA_CACHE_1 :
5207 GEN6_SFID_DATAPORT_RENDER_CACHE);
5208 break;
5209
5210 default:
5211 unreachable("Unsupported surface opcode");
5212 }
5213
5214 uint32_t desc;
5215 switch (inst->opcode) {
5216 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5217 desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5218 arg.ud, /* num_channels */
5219 false /* write */);
5220 break;
5221
5222 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5223 desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5224 arg.ud, /* num_channels */
5225 true /* write */);
5226 break;
5227
5228 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5229 desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5230 arg.ud, /* bit_size */
5231 false /* write */);
5232 break;
5233
5234 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5235 desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5236 arg.ud, /* bit_size */
5237 true /* write */);
5238 break;
5239
5240 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5241 desc = brw_dp_untyped_atomic_desc(devinfo, inst->exec_size,
5242 arg.ud, /* atomic_op */
5243 !inst->dst.is_null());
5244 break;
5245
5246 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5247 desc = brw_dp_untyped_atomic_float_desc(devinfo, inst->exec_size,
5248 arg.ud, /* atomic_op */
5249 !inst->dst.is_null());
5250 break;
5251
5252 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5253 desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5254 arg.ud, /* num_channels */
5255 false /* write */);
5256 break;
5257
5258 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5259 desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5260 arg.ud, /* num_channels */
5261 true /* write */);
5262 break;
5263
5264 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5265 desc = brw_dp_typed_atomic_desc(devinfo, inst->exec_size, inst->group,
5266 arg.ud, /* atomic_op */
5267 !inst->dst.is_null());
5268 break;
5269
5270 default:
5271 unreachable("Unknown surface logical instruction");
5272 }
5273
5274 /* Update the original instruction. */
5275 inst->opcode = SHADER_OPCODE_SEND;
5276 inst->mlen = mlen;
5277 inst->ex_mlen = ex_mlen;
5278 inst->header_size = header_sz;
5279 inst->send_has_side_effects = has_side_effects;
5280 inst->send_is_volatile = !has_side_effects;
5281
5282 /* Set up SFID and descriptors */
5283 inst->sfid = sfid;
5284 inst->desc = desc;
5285 if (surface.file == IMM) {
5286 inst->desc |= surface.ud & 0xff;
5287 inst->src[0] = brw_imm_ud(0);
5288 } else {
5289 const fs_builder ubld = bld.exec_all().group(1, 0);
5290 fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5291 ubld.AND(tmp, surface, brw_imm_ud(0xff));
5292 inst->src[0] = component(tmp, 0);
5293 }
5294 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5295
5296 /* Finally, the payload */
5297 inst->src[2] = payload;
5298 inst->src[3] = payload2;
5299
5300 inst->resize_sources(4);
5301 }
5302
5303 static void
5304 lower_a64_logical_send(const fs_builder &bld, fs_inst *inst)
5305 {
5306 const gen_device_info *devinfo = bld.shader->devinfo;
5307
5308 const fs_reg &addr = inst->src[0];
5309 const fs_reg &src = inst->src[1];
5310 const unsigned src_comps = inst->components_read(1);
5311 assert(inst->src[2].file == IMM);
5312 const unsigned arg = inst->src[2].ud;
5313 const bool has_side_effects = inst->has_side_effects();
5314
5315 /* If the surface message has side effects and we're a fragment shader, we
5316 * have to predicate with the sample mask to avoid helper invocations.
5317 */
5318 if (has_side_effects && bld.shader->stage == MESA_SHADER_FRAGMENT) {
5319 inst->flag_subreg = 2;
5320 inst->predicate = BRW_PREDICATE_NORMAL;
5321 inst->predicate_inverse = false;
5322
5323 fs_reg sample_mask = bld.sample_mask_reg();
5324 const fs_builder ubld = bld.group(1, 0).exec_all();
5325 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5326 sample_mask);
5327 }
5328
5329 fs_reg payload, payload2;
5330 unsigned mlen, ex_mlen = 0;
5331 if (devinfo->gen >= 9) {
5332 /* On Skylake and above, we have SENDS */
5333 mlen = 2 * (inst->exec_size / 8);
5334 ex_mlen = src_comps * (inst->exec_size / 8);
5335 payload = retype(bld.move_to_vgrf(addr, 1), BRW_REGISTER_TYPE_UD);
5336 payload2 = retype(bld.move_to_vgrf(src, src_comps),
5337 BRW_REGISTER_TYPE_UD);
5338 } else {
5339 /* Add two because the address is 64-bit */
5340 const unsigned dwords = 2 + src_comps;
5341 mlen = dwords * (inst->exec_size / 8);
5342
5343 fs_reg sources[5];
5344
5345 sources[0] = addr;
5346
5347 for (unsigned i = 0; i < src_comps; i++)
5348 sources[1 + i] = offset(src, bld, i);
5349
5350 payload = bld.vgrf(BRW_REGISTER_TYPE_UD, dwords);
5351 bld.LOAD_PAYLOAD(payload, sources, 1 + src_comps, 0);
5352 }
5353
5354 uint32_t desc;
5355 switch (inst->opcode) {
5356 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5357 desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5358 arg, /* num_channels */
5359 false /* write */);
5360 break;
5361
5362 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5363 desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5364 arg, /* num_channels */
5365 true /* write */);
5366 break;
5367
5368 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5369 desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5370 arg, /* bit_size */
5371 false /* write */);
5372 break;
5373
5374 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5375 desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5376 arg, /* bit_size */
5377 true /* write */);
5378 break;
5379
5380 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5381 desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 32,
5382 arg, /* atomic_op */
5383 !inst->dst.is_null());
5384 break;
5385
5386 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5387 desc = brw_dp_a64_untyped_atomic_float_desc(devinfo, inst->exec_size,
5388 arg, /* atomic_op */
5389 !inst->dst.is_null());
5390 break;
5391
5392 default:
5393 unreachable("Unknown A64 logical instruction");
5394 }
5395
5396 /* Update the original instruction. */
5397 inst->opcode = SHADER_OPCODE_SEND;
5398 inst->mlen = mlen;
5399 inst->ex_mlen = ex_mlen;
5400 inst->header_size = 0;
5401 inst->send_has_side_effects = has_side_effects;
5402 inst->send_is_volatile = !has_side_effects;
5403
5404 /* Set up SFID and descriptors */
5405 inst->sfid = HSW_SFID_DATAPORT_DATA_CACHE_1;
5406 inst->desc = desc;
5407 inst->resize_sources(4);
5408 inst->src[0] = brw_imm_ud(0); /* desc */
5409 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5410 inst->src[2] = payload;
5411 inst->src[3] = payload2;
5412 }
5413
5414 static void
5415 lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
5416 {
5417 const gen_device_info *devinfo = bld.shader->devinfo;
5418
5419 if (devinfo->gen >= 7) {
5420 fs_reg index = inst->src[0];
5421 /* We are switching the instruction from an ALU-like instruction to a
5422 * send-from-grf instruction. Since sends can't handle strides or
5423 * source modifiers, we have to make a copy of the offset source.
5424 */
5425 fs_reg offset = bld.vgrf(BRW_REGISTER_TYPE_UD);
5426 bld.MOV(offset, inst->src[1]);
5427
5428 const unsigned simd_mode =
5429 inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
5430 BRW_SAMPLER_SIMD_MODE_SIMD16;
5431
5432 inst->opcode = SHADER_OPCODE_SEND;
5433 inst->mlen = inst->exec_size / 8;
5434 inst->resize_sources(3);
5435
5436 inst->sfid = BRW_SFID_SAMPLER;
5437 inst->desc = brw_sampler_desc(devinfo, 0, 0,
5438 GEN5_SAMPLER_MESSAGE_SAMPLE_LD,
5439 simd_mode, 0);
5440 if (index.file == IMM) {
5441 inst->desc |= index.ud & 0xff;
5442 inst->src[0] = brw_imm_ud(0);
5443 } else {
5444 const fs_builder ubld = bld.exec_all().group(1, 0);
5445 fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5446 ubld.AND(tmp, index, brw_imm_ud(0xff));
5447 inst->src[0] = component(tmp, 0);
5448 }
5449 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5450 inst->src[2] = offset; /* payload */
5451 } else {
5452 const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->gen),
5453 BRW_REGISTER_TYPE_UD);
5454
5455 bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
5456
5457 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4;
5458 inst->resize_sources(1);
5459 inst->base_mrf = payload.nr;
5460 inst->header_size = 1;
5461 inst->mlen = 1 + inst->exec_size / 8;
5462 }
5463 }
5464
5465 static void
5466 lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
5467 {
5468 assert(bld.shader->devinfo->gen < 6);
5469
5470 inst->base_mrf = 2;
5471 inst->mlen = inst->sources * inst->exec_size / 8;
5472
5473 if (inst->sources > 1) {
5474 /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
5475 * "Message Payload":
5476 *
5477 * "Operand0[7]. For the INT DIV functions, this operand is the
5478 * denominator."
5479 * ...
5480 * "Operand1[7]. For the INT DIV functions, this operand is the
5481 * numerator."
5482 */
5483 const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
5484 const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
5485 const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
5486
5487 inst->resize_sources(1);
5488 inst->src[0] = src0;
5489
5490 assert(inst->exec_size == 8);
5491 bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
5492 }
5493 }
5494
5495 bool
5496 fs_visitor::lower_logical_sends()
5497 {
5498 bool progress = false;
5499
5500 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5501 const fs_builder ibld(this, block, inst);
5502
5503 switch (inst->opcode) {
5504 case FS_OPCODE_FB_WRITE_LOGICAL:
5505 assert(stage == MESA_SHADER_FRAGMENT);
5506 lower_fb_write_logical_send(ibld, inst,
5507 brw_wm_prog_data(prog_data),
5508 (const brw_wm_prog_key *)key,
5509 payload);
5510 break;
5511
5512 case FS_OPCODE_FB_READ_LOGICAL:
5513 lower_fb_read_logical_send(ibld, inst);
5514 break;
5515
5516 case SHADER_OPCODE_TEX_LOGICAL:
5517 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
5518 break;
5519
5520 case SHADER_OPCODE_TXD_LOGICAL:
5521 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
5522 break;
5523
5524 case SHADER_OPCODE_TXF_LOGICAL:
5525 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
5526 break;
5527
5528 case SHADER_OPCODE_TXL_LOGICAL:
5529 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
5530 break;
5531
5532 case SHADER_OPCODE_TXS_LOGICAL:
5533 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
5534 break;
5535
5536 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5537 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_IMAGE_SIZE);
5538 break;
5539
5540 case FS_OPCODE_TXB_LOGICAL:
5541 lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
5542 break;
5543
5544 case SHADER_OPCODE_TXF_CMS_LOGICAL:
5545 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
5546 break;
5547
5548 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
5549 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
5550 break;
5551
5552 case SHADER_OPCODE_TXF_UMS_LOGICAL:
5553 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
5554 break;
5555
5556 case SHADER_OPCODE_TXF_MCS_LOGICAL:
5557 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
5558 break;
5559
5560 case SHADER_OPCODE_LOD_LOGICAL:
5561 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
5562 break;
5563
5564 case SHADER_OPCODE_TG4_LOGICAL:
5565 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
5566 break;
5567
5568 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
5569 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
5570 break;
5571
5572 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
5573 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
5574 break;
5575
5576 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5577 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5578 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5579 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5580 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5581 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5582 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5583 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5584 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5585 lower_surface_logical_send(ibld, inst);
5586 break;
5587
5588 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5589 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5590 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5591 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5592 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5593 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5594 lower_a64_logical_send(ibld, inst);
5595 break;
5596
5597 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
5598 lower_varying_pull_constant_logical_send(ibld, inst);
5599 break;
5600
5601 case SHADER_OPCODE_RCP:
5602 case SHADER_OPCODE_RSQ:
5603 case SHADER_OPCODE_SQRT:
5604 case SHADER_OPCODE_EXP2:
5605 case SHADER_OPCODE_LOG2:
5606 case SHADER_OPCODE_SIN:
5607 case SHADER_OPCODE_COS:
5608 case SHADER_OPCODE_POW:
5609 case SHADER_OPCODE_INT_QUOTIENT:
5610 case SHADER_OPCODE_INT_REMAINDER:
5611 /* The math opcodes are overloaded for the send-like and
5612 * expression-like instructions which seems kind of icky. Gen6+ has
5613 * a native (but rather quirky) MATH instruction so we don't need to
5614 * do anything here. On Gen4-5 we'll have to lower the Gen6-like
5615 * logical instructions (which we can easily recognize because they
5616 * have mlen = 0) into send-like virtual instructions.
5617 */
5618 if (devinfo->gen < 6 && inst->mlen == 0) {
5619 lower_math_logical_send(ibld, inst);
5620 break;
5621
5622 } else {
5623 continue;
5624 }
5625
5626 default:
5627 continue;
5628 }
5629
5630 progress = true;
5631 }
5632
5633 if (progress)
5634 invalidate_live_intervals();
5635
5636 return progress;
5637 }
5638
5639 /**
5640 * Get the closest allowed SIMD width for instruction \p inst accounting for
5641 * some common regioning and execution control restrictions that apply to FPU
5642 * instructions. These restrictions don't necessarily have any relevance to
5643 * instructions not executed by the FPU pipeline like extended math, control
5644 * flow or send message instructions.
5645 *
5646 * For virtual opcodes it's really up to the instruction -- In some cases
5647 * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
5648 * instructions) it may simplify virtual instruction lowering if we can
5649 * enforce FPU-like regioning restrictions already on the virtual instruction,
5650 * in other cases (e.g. virtual send-like instructions) this may be
5651 * excessively restrictive.
5652 */
5653 static unsigned
5654 get_fpu_lowered_simd_width(const struct gen_device_info *devinfo,
5655 const fs_inst *inst)
5656 {
5657 /* Maximum execution size representable in the instruction controls. */
5658 unsigned max_width = MIN2(32, inst->exec_size);
5659
5660 /* According to the PRMs:
5661 * "A. In Direct Addressing mode, a source cannot span more than 2
5662 * adjacent GRF registers.
5663 * B. A destination cannot span more than 2 adjacent GRF registers."
5664 *
5665 * Look for the source or destination with the largest register region
5666 * which is the one that is going to limit the overall execution size of
5667 * the instruction due to this rule.
5668 */
5669 unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5670
5671 for (unsigned i = 0; i < inst->sources; i++)
5672 reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
5673
5674 /* Calculate the maximum execution size of the instruction based on the
5675 * factor by which it goes over the hardware limit of 2 GRFs.
5676 */
5677 if (reg_count > 2)
5678 max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
5679
5680 /* According to the IVB PRMs:
5681 * "When destination spans two registers, the source MUST span two
5682 * registers. The exception to the above rule:
5683 *
5684 * - When source is scalar, the source registers are not incremented.
5685 * - When source is packed integer Word and destination is packed
5686 * integer DWord, the source register is not incremented but the
5687 * source sub register is incremented."
5688 *
5689 * The hardware specs from Gen4 to Gen7.5 mention similar regioning
5690 * restrictions. The code below intentionally doesn't check whether the
5691 * destination type is integer because empirically the hardware doesn't
5692 * seem to care what the actual type is as long as it's dword-aligned.
5693 */
5694 if (devinfo->gen < 8) {
5695 for (unsigned i = 0; i < inst->sources; i++) {
5696 /* IVB implements DF scalars as <0;2,1> regions. */
5697 const bool is_scalar_exception = is_uniform(inst->src[i]) &&
5698 (devinfo->is_haswell || type_sz(inst->src[i].type) != 8);
5699 const bool is_packed_word_exception =
5700 type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
5701 type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
5702
5703 /* We check size_read(i) against size_written instead of REG_SIZE
5704 * because we want to properly handle SIMD32. In SIMD32, you can end
5705 * up with writes to 4 registers and a source that reads 2 registers
5706 * and we may still need to lower all the way to SIMD8 in that case.
5707 */
5708 if (inst->size_written > REG_SIZE &&
5709 inst->size_read(i) != 0 &&
5710 inst->size_read(i) < inst->size_written &&
5711 !is_scalar_exception && !is_packed_word_exception) {
5712 const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5713 max_width = MIN2(max_width, inst->exec_size / reg_count);
5714 }
5715 }
5716 }
5717
5718 if (devinfo->gen < 6) {
5719 /* From the G45 PRM, Volume 4 Page 361:
5720 *
5721 * "Operand Alignment Rule: With the exceptions listed below, a
5722 * source/destination operand in general should be aligned to even
5723 * 256-bit physical register with a region size equal to two 256-bit
5724 * physical registers."
5725 *
5726 * Normally we enforce this by allocating virtual registers to the
5727 * even-aligned class. But we need to handle payload registers.
5728 */
5729 for (unsigned i = 0; i < inst->sources; i++) {
5730 if (inst->src[i].file == FIXED_GRF && (inst->src[i].nr & 1) &&
5731 inst->size_read(i) > REG_SIZE) {
5732 max_width = MIN2(max_width, 8);
5733 }
5734 }
5735 }
5736
5737 /* From the IVB PRMs:
5738 * "When an instruction is SIMD32, the low 16 bits of the execution mask
5739 * are applied for both halves of the SIMD32 instruction. If different
5740 * execution mask channels are required, split the instruction into two
5741 * SIMD16 instructions."
5742 *
5743 * There is similar text in the HSW PRMs. Gen4-6 don't even implement
5744 * 32-wide control flow support in hardware and will behave similarly.
5745 */
5746 if (devinfo->gen < 8 && !inst->force_writemask_all)
5747 max_width = MIN2(max_width, 16);
5748
5749 /* From the IVB PRMs (applies to HSW too):
5750 * "Instructions with condition modifiers must not use SIMD32."
5751 *
5752 * From the BDW PRMs (applies to later hardware too):
5753 * "Ternary instruction with condition modifiers must not use SIMD32."
5754 */
5755 if (inst->conditional_mod && (devinfo->gen < 8 || inst->is_3src(devinfo)))
5756 max_width = MIN2(max_width, 16);
5757
5758 /* From the IVB PRMs (applies to other devices that don't have the
5759 * gen_device_info::supports_simd16_3src flag set):
5760 * "In Align16 access mode, SIMD16 is not allowed for DW operations and
5761 * SIMD8 is not allowed for DF operations."
5762 */
5763 if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
5764 max_width = MIN2(max_width, inst->exec_size / reg_count);
5765
5766 /* Pre-Gen8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
5767 * the 8-bit quarter of the execution mask signals specified in the
5768 * instruction control fields) for the second compressed half of any
5769 * single-precision instruction (for double-precision instructions
5770 * it's hardwired to use NibCtrl+1, at least on HSW), which means that
5771 * the EU will apply the wrong execution controls for the second
5772 * sequential GRF write if the number of channels per GRF is not exactly
5773 * eight in single-precision mode (or four in double-float mode).
5774 *
5775 * In this situation we calculate the maximum size of the split
5776 * instructions so they only ever write to a single register.
5777 */
5778 if (devinfo->gen < 8 && inst->size_written > REG_SIZE &&
5779 !inst->force_writemask_all) {
5780 const unsigned channels_per_grf = inst->exec_size /
5781 DIV_ROUND_UP(inst->size_written, REG_SIZE);
5782 const unsigned exec_type_size = get_exec_type_size(inst);
5783 assert(exec_type_size);
5784
5785 /* The hardware shifts exactly 8 channels per compressed half of the
5786 * instruction in single-precision mode and exactly 4 in double-precision.
5787 */
5788 if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
5789 max_width = MIN2(max_width, channels_per_grf);
5790
5791 /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
5792 * because HW applies the same channel enable signals to both halves of
5793 * the compressed instruction which will be just wrong under
5794 * non-uniform control flow.
5795 */
5796 if (devinfo->gen == 7 && !devinfo->is_haswell &&
5797 (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
5798 max_width = MIN2(max_width, 4);
5799 }
5800
5801 /* Only power-of-two execution sizes are representable in the instruction
5802 * control fields.
5803 */
5804 return 1 << _mesa_logbase2(max_width);
5805 }
5806
5807 /**
5808 * Get the maximum allowed SIMD width for instruction \p inst accounting for
5809 * various payload size restrictions that apply to sampler message
5810 * instructions.
5811 *
5812 * This is only intended to provide a maximum theoretical bound for the
5813 * execution size of the message based on the number of argument components
5814 * alone, which in most cases will determine whether the SIMD8 or SIMD16
5815 * variant of the message can be used, though some messages may have
5816 * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
5817 * the message length to determine the exact SIMD width and argument count,
5818 * which makes a number of sampler message combinations impossible to
5819 * represent).
5820 */
5821 static unsigned
5822 get_sampler_lowered_simd_width(const struct gen_device_info *devinfo,
5823 const fs_inst *inst)
5824 {
5825 /* If we have a min_lod parameter on anything other than a simple sample
5826 * message, it will push it over 5 arguments and we have to fall back to
5827 * SIMD8.
5828 */
5829 if (inst->opcode != SHADER_OPCODE_TEX &&
5830 inst->components_read(TEX_LOGICAL_SRC_MIN_LOD))
5831 return 8;
5832
5833 /* Calculate the number of coordinate components that have to be present
5834 * assuming that additional arguments follow the texel coordinates in the
5835 * message payload. On IVB+ there is no need for padding, on ILK-SNB we
5836 * need to pad to four or three components depending on the message,
5837 * pre-ILK we need to pad to at most three components.
5838 */
5839 const unsigned req_coord_components =
5840 (devinfo->gen >= 7 ||
5841 !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
5842 (devinfo->gen >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
5843 inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
5844 3;
5845
5846 /* On Gen9+ the LOD argument is for free if we're able to use the LZ
5847 * variant of the TXL or TXF message.
5848 */
5849 const bool implicit_lod = devinfo->gen >= 9 &&
5850 (inst->opcode == SHADER_OPCODE_TXL ||
5851 inst->opcode == SHADER_OPCODE_TXF) &&
5852 inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
5853
5854 /* Calculate the total number of argument components that need to be passed
5855 * to the sampler unit.
5856 */
5857 const unsigned num_payload_components =
5858 MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
5859 req_coord_components) +
5860 inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
5861 (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
5862 inst->components_read(TEX_LOGICAL_SRC_LOD2) +
5863 inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
5864 (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
5865 inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
5866 inst->components_read(TEX_LOGICAL_SRC_MCS);
5867
5868 /* SIMD16 messages with more than five arguments exceed the maximum message
5869 * size supported by the sampler, regardless of whether a header is
5870 * provided or not.
5871 */
5872 return MIN2(inst->exec_size,
5873 num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
5874 }
5875
5876 /**
5877 * Get the closest native SIMD width supported by the hardware for instruction
5878 * \p inst. The instruction will be left untouched by
5879 * fs_visitor::lower_simd_width() if the returned value is equal to the
5880 * original execution size.
5881 */
5882 static unsigned
5883 get_lowered_simd_width(const struct gen_device_info *devinfo,
5884 const fs_inst *inst)
5885 {
5886 switch (inst->opcode) {
5887 case BRW_OPCODE_MOV:
5888 case BRW_OPCODE_SEL:
5889 case BRW_OPCODE_NOT:
5890 case BRW_OPCODE_AND:
5891 case BRW_OPCODE_OR:
5892 case BRW_OPCODE_XOR:
5893 case BRW_OPCODE_SHR:
5894 case BRW_OPCODE_SHL:
5895 case BRW_OPCODE_ASR:
5896 case BRW_OPCODE_CMPN:
5897 case BRW_OPCODE_CSEL:
5898 case BRW_OPCODE_F32TO16:
5899 case BRW_OPCODE_F16TO32:
5900 case BRW_OPCODE_BFREV:
5901 case BRW_OPCODE_BFE:
5902 case BRW_OPCODE_ADD:
5903 case BRW_OPCODE_MUL:
5904 case BRW_OPCODE_AVG:
5905 case BRW_OPCODE_FRC:
5906 case BRW_OPCODE_RNDU:
5907 case BRW_OPCODE_RNDD:
5908 case BRW_OPCODE_RNDE:
5909 case BRW_OPCODE_RNDZ:
5910 case BRW_OPCODE_LZD:
5911 case BRW_OPCODE_FBH:
5912 case BRW_OPCODE_FBL:
5913 case BRW_OPCODE_CBIT:
5914 case BRW_OPCODE_SAD2:
5915 case BRW_OPCODE_MAD:
5916 case BRW_OPCODE_LRP:
5917 case FS_OPCODE_PACK:
5918 case SHADER_OPCODE_SEL_EXEC:
5919 case SHADER_OPCODE_CLUSTER_BROADCAST:
5920 return get_fpu_lowered_simd_width(devinfo, inst);
5921
5922 case BRW_OPCODE_CMP: {
5923 /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
5924 * when the destination is a GRF the dependency-clear bit on the flag
5925 * register is cleared early.
5926 *
5927 * Suggested workarounds are to disable coissuing CMP instructions
5928 * or to split CMP(16) instructions into two CMP(8) instructions.
5929 *
5930 * We choose to split into CMP(8) instructions since disabling
5931 * coissuing would affect CMP instructions not otherwise affected by
5932 * the errata.
5933 */
5934 const unsigned max_width = (devinfo->gen == 7 && !devinfo->is_haswell &&
5935 !inst->dst.is_null() ? 8 : ~0);
5936 return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
5937 }
5938 case BRW_OPCODE_BFI1:
5939 case BRW_OPCODE_BFI2:
5940 /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
5941 * should
5942 * "Force BFI instructions to be executed always in SIMD8."
5943 */
5944 return MIN2(devinfo->is_haswell ? 8 : ~0u,
5945 get_fpu_lowered_simd_width(devinfo, inst));
5946
5947 case BRW_OPCODE_IF:
5948 assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
5949 return inst->exec_size;
5950
5951 case SHADER_OPCODE_RCP:
5952 case SHADER_OPCODE_RSQ:
5953 case SHADER_OPCODE_SQRT:
5954 case SHADER_OPCODE_EXP2:
5955 case SHADER_OPCODE_LOG2:
5956 case SHADER_OPCODE_SIN:
5957 case SHADER_OPCODE_COS:
5958 /* Unary extended math instructions are limited to SIMD8 on Gen4 and
5959 * Gen6.
5960 */
5961 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
5962 devinfo->gen == 5 || devinfo->is_g4x ? MIN2(16, inst->exec_size) :
5963 MIN2(8, inst->exec_size));
5964
5965 case SHADER_OPCODE_POW:
5966 /* SIMD16 is only allowed on Gen7+. */
5967 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
5968 MIN2(8, inst->exec_size));
5969
5970 case SHADER_OPCODE_INT_QUOTIENT:
5971 case SHADER_OPCODE_INT_REMAINDER:
5972 /* Integer division is limited to SIMD8 on all generations. */
5973 return MIN2(8, inst->exec_size);
5974
5975 case FS_OPCODE_LINTERP:
5976 case SHADER_OPCODE_GET_BUFFER_SIZE:
5977 case FS_OPCODE_DDX_COARSE:
5978 case FS_OPCODE_DDX_FINE:
5979 case FS_OPCODE_DDY_COARSE:
5980 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
5981 case FS_OPCODE_PACK_HALF_2x16_SPLIT:
5982 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
5983 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
5984 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
5985 return MIN2(16, inst->exec_size);
5986
5987 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
5988 /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
5989 * message used to implement varying pull constant loads, so expand it
5990 * to SIMD16. An alternative with longer message payload length but
5991 * shorter return payload would be to use the SIMD8 sampler message that
5992 * takes (header, u, v, r) as parameters instead of (header, u).
5993 */
5994 return (devinfo->gen == 4 ? 16 : MIN2(16, inst->exec_size));
5995
5996 case FS_OPCODE_DDY_FINE:
5997 /* The implementation of this virtual opcode may require emitting
5998 * compressed Align16 instructions, which are severely limited on some
5999 * generations.
6000 *
6001 * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
6002 * Region Restrictions):
6003 *
6004 * "In Align16 access mode, SIMD16 is not allowed for DW operations
6005 * and SIMD8 is not allowed for DF operations."
6006 *
6007 * In this context, "DW operations" means "operations acting on 32-bit
6008 * values", so it includes operations on floats.
6009 *
6010 * Gen4 has a similar restriction. From the i965 PRM, section 11.5.3
6011 * (Instruction Compression -> Rules and Restrictions):
6012 *
6013 * "A compressed instruction must be in Align1 access mode. Align16
6014 * mode instructions cannot be compressed."
6015 *
6016 * Similar text exists in the g45 PRM.
6017 *
6018 * Empirically, compressed align16 instructions using odd register
6019 * numbers don't appear to work on Sandybridge either.
6020 */
6021 return (devinfo->gen == 4 || devinfo->gen == 6 ||
6022 (devinfo->gen == 7 && !devinfo->is_haswell) ?
6023 MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
6024
6025 case SHADER_OPCODE_MULH:
6026 /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
6027 * is 8-wide on Gen7+.
6028 */
6029 return (devinfo->gen >= 7 ? 8 :
6030 get_fpu_lowered_simd_width(devinfo, inst));
6031
6032 case FS_OPCODE_FB_WRITE_LOGICAL:
6033 /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
6034 * here.
6035 */
6036 assert(devinfo->gen != 6 ||
6037 inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
6038 inst->exec_size == 8);
6039 /* Dual-source FB writes are unsupported in SIMD16 mode. */
6040 return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
6041 8 : MIN2(16, inst->exec_size));
6042
6043 case FS_OPCODE_FB_READ_LOGICAL:
6044 return MIN2(16, inst->exec_size);
6045
6046 case SHADER_OPCODE_TEX_LOGICAL:
6047 case SHADER_OPCODE_TXF_CMS_LOGICAL:
6048 case SHADER_OPCODE_TXF_UMS_LOGICAL:
6049 case SHADER_OPCODE_TXF_MCS_LOGICAL:
6050 case SHADER_OPCODE_LOD_LOGICAL:
6051 case SHADER_OPCODE_TG4_LOGICAL:
6052 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
6053 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
6054 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
6055 return get_sampler_lowered_simd_width(devinfo, inst);
6056
6057 case SHADER_OPCODE_TXD_LOGICAL:
6058 /* TXD is unsupported in SIMD16 mode. */
6059 return 8;
6060
6061 case SHADER_OPCODE_TXL_LOGICAL:
6062 case FS_OPCODE_TXB_LOGICAL:
6063 /* Only one execution size is representable pre-ILK depending on whether
6064 * the shadow reference argument is present.
6065 */
6066 if (devinfo->gen == 4)
6067 return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
6068 else
6069 return get_sampler_lowered_simd_width(devinfo, inst);
6070
6071 case SHADER_OPCODE_TXF_LOGICAL:
6072 case SHADER_OPCODE_TXS_LOGICAL:
6073 /* Gen4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
6074 * messages. Use SIMD16 instead.
6075 */
6076 if (devinfo->gen == 4)
6077 return 16;
6078 else
6079 return get_sampler_lowered_simd_width(devinfo, inst);
6080
6081 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
6082 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
6083 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
6084 return 8;
6085
6086 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
6087 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6088 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
6089 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
6090 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
6091 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
6092 return MIN2(16, inst->exec_size);
6093
6094 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
6095 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
6096 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
6097 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
6098 return devinfo->gen <= 8 ? 8 : MIN2(16, inst->exec_size);
6099
6100 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
6101 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6102 return 8;
6103
6104 case SHADER_OPCODE_URB_READ_SIMD8:
6105 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
6106 case SHADER_OPCODE_URB_WRITE_SIMD8:
6107 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
6108 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
6109 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
6110 return MIN2(8, inst->exec_size);
6111
6112 case SHADER_OPCODE_QUAD_SWIZZLE: {
6113 const unsigned swiz = inst->src[1].ud;
6114 return (is_uniform(inst->src[0]) ?
6115 get_fpu_lowered_simd_width(devinfo, inst) :
6116 devinfo->gen < 11 && type_sz(inst->src[0].type) == 4 ? 8 :
6117 swiz == BRW_SWIZZLE_XYXY || swiz == BRW_SWIZZLE_ZWZW ? 4 :
6118 get_fpu_lowered_simd_width(devinfo, inst));
6119 }
6120 case SHADER_OPCODE_MOV_INDIRECT: {
6121 /* From IVB and HSW PRMs:
6122 *
6123 * "2.When the destination requires two registers and the sources are
6124 * indirect, the sources must use 1x1 regioning mode.
6125 *
6126 * In case of DF instructions in HSW/IVB, the exec_size is limited by
6127 * the EU decompression logic not handling VxH indirect addressing
6128 * correctly.
6129 */
6130 const unsigned max_size = (devinfo->gen >= 8 ? 2 : 1) * REG_SIZE;
6131 /* Prior to Broadwell, we only have 8 address subregisters. */
6132 return MIN3(devinfo->gen >= 8 ? 16 : 8,
6133 max_size / (inst->dst.stride * type_sz(inst->dst.type)),
6134 inst->exec_size);
6135 }
6136
6137 case SHADER_OPCODE_LOAD_PAYLOAD: {
6138 const unsigned reg_count =
6139 DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
6140
6141 if (reg_count > 2) {
6142 /* Only LOAD_PAYLOAD instructions with per-channel destination region
6143 * can be easily lowered (which excludes headers and heterogeneous
6144 * types).
6145 */
6146 assert(!inst->header_size);
6147 for (unsigned i = 0; i < inst->sources; i++)
6148 assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
6149 inst->src[i].file == BAD_FILE);
6150
6151 return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
6152 } else {
6153 return inst->exec_size;
6154 }
6155 }
6156 default:
6157 return inst->exec_size;
6158 }
6159 }
6160
6161 /**
6162 * Return true if splitting out the group of channels of instruction \p inst
6163 * given by lbld.group() requires allocating a temporary for the i-th source
6164 * of the lowered instruction.
6165 */
6166 static inline bool
6167 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
6168 {
6169 return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
6170 (inst->components_read(i) == 1 &&
6171 lbld.dispatch_width() <= inst->exec_size)) ||
6172 (inst->flags_written() &
6173 flag_mask(inst->src[i], type_sz(inst->src[i].type)));
6174 }
6175
6176 /**
6177 * Extract the data that would be consumed by the channel group given by
6178 * lbld.group() from the i-th source region of instruction \p inst and return
6179 * it as result in packed form.
6180 */
6181 static fs_reg
6182 emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
6183 {
6184 assert(lbld.group() >= inst->group);
6185
6186 /* Specified channel group from the source region. */
6187 const fs_reg src = horiz_offset(inst->src[i], lbld.group() - inst->group);
6188
6189 if (needs_src_copy(lbld, inst, i)) {
6190 /* Builder of the right width to perform the copy avoiding uninitialized
6191 * data if the lowered execution size is greater than the original
6192 * execution size of the instruction.
6193 */
6194 const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
6195 inst->exec_size), 0);
6196 const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
6197
6198 for (unsigned k = 0; k < inst->components_read(i); ++k)
6199 cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
6200
6201 return tmp;
6202
6203 } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
6204 /* The source is invariant for all dispatch_width-wide groups of the
6205 * original region.
6206 */
6207 return inst->src[i];
6208
6209 } else {
6210 /* We can just point the lowered instruction at the right channel group
6211 * from the original region.
6212 */
6213 return src;
6214 }
6215 }
6216
6217 /**
6218 * Return true if splitting out the group of channels of instruction \p inst
6219 * given by lbld.group() requires allocating a temporary for the destination
6220 * of the lowered instruction and copying the data back to the original
6221 * destination region.
6222 */
6223 static inline bool
6224 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
6225 {
6226 /* If the instruction writes more than one component we'll have to shuffle
6227 * the results of multiple lowered instructions in order to make sure that
6228 * they end up arranged correctly in the original destination region.
6229 */
6230 if (inst->size_written > inst->dst.component_size(inst->exec_size))
6231 return true;
6232
6233 /* If the lowered execution size is larger than the original the result of
6234 * the instruction won't fit in the original destination, so we'll have to
6235 * allocate a temporary in any case.
6236 */
6237 if (lbld.dispatch_width() > inst->exec_size)
6238 return true;
6239
6240 for (unsigned i = 0; i < inst->sources; i++) {
6241 /* If we already made a copy of the source for other reasons there won't
6242 * be any overlap with the destination.
6243 */
6244 if (needs_src_copy(lbld, inst, i))
6245 continue;
6246
6247 /* In order to keep the logic simple we emit a copy whenever the
6248 * destination region doesn't exactly match an overlapping source, which
6249 * may point at the source and destination not being aligned group by
6250 * group which could cause one of the lowered instructions to overwrite
6251 * the data read from the same source by other lowered instructions.
6252 */
6253 if (regions_overlap(inst->dst, inst->size_written,
6254 inst->src[i], inst->size_read(i)) &&
6255 !inst->dst.equals(inst->src[i]))
6256 return true;
6257 }
6258
6259 return false;
6260 }
6261
6262 /**
6263 * Insert data from a packed temporary into the channel group given by
6264 * lbld.group() of the destination region of instruction \p inst and return
6265 * the temporary as result. Any copy instructions that are required for
6266 * unzipping the previous value (in the case of partial writes) will be
6267 * inserted using \p lbld_before and any copy instructions required for
6268 * zipping up the destination of \p inst will be inserted using \p lbld_after.
6269 */
6270 static fs_reg
6271 emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
6272 fs_inst *inst)
6273 {
6274 assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
6275 assert(lbld_before.group() == lbld_after.group());
6276 assert(lbld_after.group() >= inst->group);
6277
6278 /* Specified channel group from the destination region. */
6279 const fs_reg dst = horiz_offset(inst->dst, lbld_after.group() - inst->group);
6280 const unsigned dst_size = inst->size_written /
6281 inst->dst.component_size(inst->exec_size);
6282
6283 if (needs_dst_copy(lbld_after, inst)) {
6284 const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
6285
6286 if (inst->predicate) {
6287 /* Handle predication by copying the original contents of
6288 * the destination into the temporary before emitting the
6289 * lowered instruction.
6290 */
6291 const fs_builder gbld_before =
6292 lbld_before.group(MIN2(lbld_before.dispatch_width(),
6293 inst->exec_size), 0);
6294 for (unsigned k = 0; k < dst_size; ++k) {
6295 gbld_before.MOV(offset(tmp, lbld_before, k),
6296 offset(dst, inst->exec_size, k));
6297 }
6298 }
6299
6300 const fs_builder gbld_after =
6301 lbld_after.group(MIN2(lbld_after.dispatch_width(),
6302 inst->exec_size), 0);
6303 for (unsigned k = 0; k < dst_size; ++k) {
6304 /* Use a builder of the right width to perform the copy avoiding
6305 * uninitialized data if the lowered execution size is greater than
6306 * the original execution size of the instruction.
6307 */
6308 gbld_after.MOV(offset(dst, inst->exec_size, k),
6309 offset(tmp, lbld_after, k));
6310 }
6311
6312 return tmp;
6313
6314 } else {
6315 /* No need to allocate a temporary for the lowered instruction, just
6316 * take the right group of channels from the original region.
6317 */
6318 return dst;
6319 }
6320 }
6321
6322 bool
6323 fs_visitor::lower_simd_width()
6324 {
6325 bool progress = false;
6326
6327 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
6328 const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
6329
6330 if (lower_width != inst->exec_size) {
6331 /* Builder matching the original instruction. We may also need to
6332 * emit an instruction of width larger than the original, set the
6333 * execution size of the builder to the highest of both for now so
6334 * we're sure that both cases can be handled.
6335 */
6336 const unsigned max_width = MAX2(inst->exec_size, lower_width);
6337 const fs_builder ibld = bld.at(block, inst)
6338 .exec_all(inst->force_writemask_all)
6339 .group(max_width, inst->group / max_width);
6340
6341 /* Split the copies in chunks of the execution width of either the
6342 * original or the lowered instruction, whichever is lower.
6343 */
6344 const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
6345 const unsigned dst_size = inst->size_written /
6346 inst->dst.component_size(inst->exec_size);
6347
6348 assert(!inst->writes_accumulator && !inst->mlen);
6349
6350 /* Inserting the zip, unzip, and duplicated instructions in all of
6351 * the right spots is somewhat tricky. All of the unzip and any
6352 * instructions from the zip which unzip the destination prior to
6353 * writing need to happen before all of the per-group instructions
6354 * and the zip instructions need to happen after. In order to sort
6355 * this all out, we insert the unzip instructions before \p inst,
6356 * insert the per-group instructions after \p inst (i.e. before
6357 * inst->next), and insert the zip instructions before the
6358 * instruction after \p inst. Since we are inserting instructions
6359 * after \p inst, inst->next is a moving target and we need to save
6360 * it off here so that we insert the zip instructions in the right
6361 * place.
6362 *
6363 * Since we're inserting split instructions after after_inst, the
6364 * instructions will end up in the reverse order that we insert them.
6365 * However, certain render target writes require that the low group
6366 * instructions come before the high group. From the Ivy Bridge PRM
6367 * Vol. 4, Pt. 1, Section 3.9.11:
6368 *
6369 * "If multiple SIMD8 Dual Source messages are delivered by the
6370 * pixel shader thread, each SIMD8_DUALSRC_LO message must be
6371 * issued before the SIMD8_DUALSRC_HI message with the same Slot
6372 * Group Select setting."
6373 *
6374 * And, from Section 3.9.11.1 of the same PRM:
6375 *
6376 * "When SIMD32 or SIMD16 PS threads send render target writes
6377 * with multiple SIMD8 and SIMD16 messages, the following must
6378 * hold:
6379 *
6380 * All the slots (as described above) must have a corresponding
6381 * render target write irrespective of the slot's validity. A slot
6382 * is considered valid when at least one sample is enabled. For
6383 * example, a SIMD16 PS thread must send two SIMD8 render target
6384 * writes to cover all the slots.
6385 *
6386 * PS thread must send SIMD render target write messages with
6387 * increasing slot numbers. For example, SIMD16 thread has
6388 * Slot[15:0] and if two SIMD8 render target writes are used, the
6389 * first SIMD8 render target write must send Slot[7:0] and the
6390 * next one must send Slot[15:8]."
6391 *
6392 * In order to make low group instructions come before high group
6393 * instructions (this is required for some render target writes), we
6394 * split from the highest group to lowest.
6395 */
6396 exec_node *const after_inst = inst->next;
6397 for (int i = n - 1; i >= 0; i--) {
6398 /* Emit a copy of the original instruction with the lowered width.
6399 * If the EOT flag was set throw it away except for the last
6400 * instruction to avoid killing the thread prematurely.
6401 */
6402 fs_inst split_inst = *inst;
6403 split_inst.exec_size = lower_width;
6404 split_inst.eot = inst->eot && i == int(n - 1);
6405
6406 /* Select the correct channel enables for the i-th group, then
6407 * transform the sources and destination and emit the lowered
6408 * instruction.
6409 */
6410 const fs_builder lbld = ibld.group(lower_width, i);
6411
6412 for (unsigned j = 0; j < inst->sources; j++)
6413 split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
6414
6415 split_inst.dst = emit_zip(lbld.at(block, inst),
6416 lbld.at(block, after_inst), inst);
6417 split_inst.size_written =
6418 split_inst.dst.component_size(lower_width) * dst_size;
6419
6420 lbld.at(block, inst->next).emit(split_inst);
6421 }
6422
6423 inst->remove(block);
6424 progress = true;
6425 }
6426 }
6427
6428 if (progress)
6429 invalidate_live_intervals();
6430
6431 return progress;
6432 }
6433
6434 void
6435 fs_visitor::dump_instructions()
6436 {
6437 dump_instructions(NULL);
6438 }
6439
6440 void
6441 fs_visitor::dump_instructions(const char *name)
6442 {
6443 FILE *file = stderr;
6444 if (name && geteuid() != 0) {
6445 file = fopen(name, "w");
6446 if (!file)
6447 file = stderr;
6448 }
6449
6450 if (cfg) {
6451 calculate_register_pressure();
6452 int ip = 0, max_pressure = 0;
6453 foreach_block_and_inst(block, backend_instruction, inst, cfg) {
6454 max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
6455 fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
6456 dump_instruction(inst, file);
6457 ip++;
6458 }
6459 fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
6460 } else {
6461 int ip = 0;
6462 foreach_in_list(backend_instruction, inst, &instructions) {
6463 fprintf(file, "%4d: ", ip++);
6464 dump_instruction(inst, file);
6465 }
6466 }
6467
6468 if (file != stderr) {
6469 fclose(file);
6470 }
6471 }
6472
6473 void
6474 fs_visitor::dump_instruction(backend_instruction *be_inst)
6475 {
6476 dump_instruction(be_inst, stderr);
6477 }
6478
6479 void
6480 fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
6481 {
6482 fs_inst *inst = (fs_inst *)be_inst;
6483
6484 if (inst->predicate) {
6485 fprintf(file, "(%cf%d.%d) ",
6486 inst->predicate_inverse ? '-' : '+',
6487 inst->flag_subreg / 2,
6488 inst->flag_subreg % 2);
6489 }
6490
6491 fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
6492 if (inst->saturate)
6493 fprintf(file, ".sat");
6494 if (inst->conditional_mod) {
6495 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
6496 if (!inst->predicate &&
6497 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
6498 inst->opcode != BRW_OPCODE_CSEL &&
6499 inst->opcode != BRW_OPCODE_IF &&
6500 inst->opcode != BRW_OPCODE_WHILE))) {
6501 fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
6502 inst->flag_subreg % 2);
6503 }
6504 }
6505 fprintf(file, "(%d) ", inst->exec_size);
6506
6507 if (inst->mlen) {
6508 fprintf(file, "(mlen: %d) ", inst->mlen);
6509 }
6510
6511 if (inst->ex_mlen) {
6512 fprintf(file, "(ex_mlen: %d) ", inst->ex_mlen);
6513 }
6514
6515 if (inst->eot) {
6516 fprintf(file, "(EOT) ");
6517 }
6518
6519 switch (inst->dst.file) {
6520 case VGRF:
6521 fprintf(file, "vgrf%d", inst->dst.nr);
6522 break;
6523 case FIXED_GRF:
6524 fprintf(file, "g%d", inst->dst.nr);
6525 break;
6526 case MRF:
6527 fprintf(file, "m%d", inst->dst.nr);
6528 break;
6529 case BAD_FILE:
6530 fprintf(file, "(null)");
6531 break;
6532 case UNIFORM:
6533 fprintf(file, "***u%d***", inst->dst.nr);
6534 break;
6535 case ATTR:
6536 fprintf(file, "***attr%d***", inst->dst.nr);
6537 break;
6538 case ARF:
6539 switch (inst->dst.nr) {
6540 case BRW_ARF_NULL:
6541 fprintf(file, "null");
6542 break;
6543 case BRW_ARF_ADDRESS:
6544 fprintf(file, "a0.%d", inst->dst.subnr);
6545 break;
6546 case BRW_ARF_ACCUMULATOR:
6547 fprintf(file, "acc%d", inst->dst.subnr);
6548 break;
6549 case BRW_ARF_FLAG:
6550 fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6551 break;
6552 default:
6553 fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6554 break;
6555 }
6556 break;
6557 case IMM:
6558 unreachable("not reached");
6559 }
6560
6561 if (inst->dst.offset ||
6562 (inst->dst.file == VGRF &&
6563 alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
6564 const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
6565 fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
6566 inst->dst.offset % reg_size);
6567 }
6568
6569 if (inst->dst.stride != 1)
6570 fprintf(file, "<%u>", inst->dst.stride);
6571 fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
6572
6573 for (int i = 0; i < inst->sources; i++) {
6574 if (inst->src[i].negate)
6575 fprintf(file, "-");
6576 if (inst->src[i].abs)
6577 fprintf(file, "|");
6578 switch (inst->src[i].file) {
6579 case VGRF:
6580 fprintf(file, "vgrf%d", inst->src[i].nr);
6581 break;
6582 case FIXED_GRF:
6583 fprintf(file, "g%d", inst->src[i].nr);
6584 break;
6585 case MRF:
6586 fprintf(file, "***m%d***", inst->src[i].nr);
6587 break;
6588 case ATTR:
6589 fprintf(file, "attr%d", inst->src[i].nr);
6590 break;
6591 case UNIFORM:
6592 fprintf(file, "u%d", inst->src[i].nr);
6593 break;
6594 case BAD_FILE:
6595 fprintf(file, "(null)");
6596 break;
6597 case IMM:
6598 switch (inst->src[i].type) {
6599 case BRW_REGISTER_TYPE_F:
6600 fprintf(file, "%-gf", inst->src[i].f);
6601 break;
6602 case BRW_REGISTER_TYPE_DF:
6603 fprintf(file, "%fdf", inst->src[i].df);
6604 break;
6605 case BRW_REGISTER_TYPE_W:
6606 case BRW_REGISTER_TYPE_D:
6607 fprintf(file, "%dd", inst->src[i].d);
6608 break;
6609 case BRW_REGISTER_TYPE_UW:
6610 case BRW_REGISTER_TYPE_UD:
6611 fprintf(file, "%uu", inst->src[i].ud);
6612 break;
6613 case BRW_REGISTER_TYPE_Q:
6614 fprintf(file, "%" PRId64 "q", inst->src[i].d64);
6615 break;
6616 case BRW_REGISTER_TYPE_UQ:
6617 fprintf(file, "%" PRIu64 "uq", inst->src[i].u64);
6618 break;
6619 case BRW_REGISTER_TYPE_VF:
6620 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
6621 brw_vf_to_float((inst->src[i].ud >> 0) & 0xff),
6622 brw_vf_to_float((inst->src[i].ud >> 8) & 0xff),
6623 brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
6624 brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
6625 break;
6626 case BRW_REGISTER_TYPE_V:
6627 case BRW_REGISTER_TYPE_UV:
6628 fprintf(file, "%08x%s", inst->src[i].ud,
6629 inst->src[i].type == BRW_REGISTER_TYPE_V ? "V" : "UV");
6630 break;
6631 default:
6632 fprintf(file, "???");
6633 break;
6634 }
6635 break;
6636 case ARF:
6637 switch (inst->src[i].nr) {
6638 case BRW_ARF_NULL:
6639 fprintf(file, "null");
6640 break;
6641 case BRW_ARF_ADDRESS:
6642 fprintf(file, "a0.%d", inst->src[i].subnr);
6643 break;
6644 case BRW_ARF_ACCUMULATOR:
6645 fprintf(file, "acc%d", inst->src[i].subnr);
6646 break;
6647 case BRW_ARF_FLAG:
6648 fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6649 break;
6650 default:
6651 fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6652 break;
6653 }
6654 break;
6655 }
6656
6657 if (inst->src[i].offset ||
6658 (inst->src[i].file == VGRF &&
6659 alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
6660 const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
6661 fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
6662 inst->src[i].offset % reg_size);
6663 }
6664
6665 if (inst->src[i].abs)
6666 fprintf(file, "|");
6667
6668 if (inst->src[i].file != IMM) {
6669 unsigned stride;
6670 if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
6671 unsigned hstride = inst->src[i].hstride;
6672 stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
6673 } else {
6674 stride = inst->src[i].stride;
6675 }
6676 if (stride != 1)
6677 fprintf(file, "<%u>", stride);
6678
6679 fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
6680 }
6681
6682 if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
6683 fprintf(file, ", ");
6684 }
6685
6686 fprintf(file, " ");
6687
6688 if (inst->force_writemask_all)
6689 fprintf(file, "NoMask ");
6690
6691 if (inst->exec_size != dispatch_width)
6692 fprintf(file, "group%d ", inst->group);
6693
6694 fprintf(file, "\n");
6695 }
6696
6697 void
6698 fs_visitor::setup_fs_payload_gen6()
6699 {
6700 assert(stage == MESA_SHADER_FRAGMENT);
6701 struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
6702 const unsigned payload_width = MIN2(16, dispatch_width);
6703 assert(dispatch_width % payload_width == 0);
6704 assert(devinfo->gen >= 6);
6705
6706 prog_data->uses_src_depth = prog_data->uses_src_w =
6707 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
6708
6709 prog_data->uses_sample_mask =
6710 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_MASK_IN) != 0;
6711
6712 /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
6713 *
6714 * "MSDISPMODE_PERSAMPLE is required in order to select
6715 * POSOFFSET_SAMPLE"
6716 *
6717 * So we can only really get sample positions if we are doing real
6718 * per-sample dispatch. If we need gl_SamplePosition and we don't have
6719 * persample dispatch, we hard-code it to 0.5.
6720 */
6721 prog_data->uses_pos_offset = prog_data->persample_dispatch &&
6722 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_POS);
6723
6724 /* R0: PS thread payload header. */
6725 payload.num_regs++;
6726
6727 for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
6728 /* R1: masks, pixel X/Y coordinates. */
6729 payload.subspan_coord_reg[j] = payload.num_regs++;
6730 }
6731
6732 for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
6733 /* R3-26: barycentric interpolation coordinates. These appear in the
6734 * same order that they appear in the brw_barycentric_mode enum. Each
6735 * set of coordinates occupies 2 registers if dispatch width == 8 and 4
6736 * registers if dispatch width == 16. Coordinates only appear if they
6737 * were enabled using the "Barycentric Interpolation Mode" bits in
6738 * WM_STATE.
6739 */
6740 for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
6741 if (prog_data->barycentric_interp_modes & (1 << i)) {
6742 payload.barycentric_coord_reg[i][j] = payload.num_regs;
6743 payload.num_regs += payload_width / 4;
6744 }
6745 }
6746
6747 /* R27-28: interpolated depth if uses source depth */
6748 if (prog_data->uses_src_depth) {
6749 payload.source_depth_reg[j] = payload.num_regs;
6750 payload.num_regs += payload_width / 8;
6751 }
6752
6753 /* R29-30: interpolated W set if GEN6_WM_USES_SOURCE_W. */
6754 if (prog_data->uses_src_w) {
6755 payload.source_w_reg[j] = payload.num_regs;
6756 payload.num_regs += payload_width / 8;
6757 }
6758
6759 /* R31: MSAA position offsets. */
6760 if (prog_data->uses_pos_offset) {
6761 payload.sample_pos_reg[j] = payload.num_regs;
6762 payload.num_regs++;
6763 }
6764
6765 /* R32-33: MSAA input coverage mask */
6766 if (prog_data->uses_sample_mask) {
6767 assert(devinfo->gen >= 7);
6768 payload.sample_mask_in_reg[j] = payload.num_regs;
6769 payload.num_regs += payload_width / 8;
6770 }
6771 }
6772
6773 if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
6774 source_depth_to_render_target = true;
6775 }
6776 }
6777
6778 void
6779 fs_visitor::setup_vs_payload()
6780 {
6781 /* R0: thread header, R1: urb handles */
6782 payload.num_regs = 2;
6783 }
6784
6785 void
6786 fs_visitor::setup_gs_payload()
6787 {
6788 assert(stage == MESA_SHADER_GEOMETRY);
6789
6790 struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
6791 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
6792
6793 /* R0: thread header, R1: output URB handles */
6794 payload.num_regs = 2;
6795
6796 if (gs_prog_data->include_primitive_id) {
6797 /* R2: Primitive ID 0..7 */
6798 payload.num_regs++;
6799 }
6800
6801 /* Always enable VUE handles so we can safely use pull model if needed.
6802 *
6803 * The push model for a GS uses a ton of register space even for trivial
6804 * scenarios with just a few inputs, so just make things easier and a bit
6805 * safer by always having pull model available.
6806 */
6807 gs_prog_data->base.include_vue_handles = true;
6808
6809 /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
6810 payload.num_regs += nir->info.gs.vertices_in;
6811
6812 /* Use a maximum of 24 registers for push-model inputs. */
6813 const unsigned max_push_components = 24;
6814
6815 /* If pushing our inputs would take too many registers, reduce the URB read
6816 * length (which is in HWords, or 8 registers), and resort to pulling.
6817 *
6818 * Note that the GS reads <URB Read Length> HWords for every vertex - so we
6819 * have to multiply by VerticesIn to obtain the total storage requirement.
6820 */
6821 if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
6822 max_push_components) {
6823 vue_prog_data->urb_read_length =
6824 ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
6825 }
6826 }
6827
6828 void
6829 fs_visitor::setup_cs_payload()
6830 {
6831 assert(devinfo->gen >= 7);
6832 payload.num_regs = 1;
6833 }
6834
6835 void
6836 fs_visitor::calculate_register_pressure()
6837 {
6838 invalidate_live_intervals();
6839 calculate_live_intervals();
6840
6841 unsigned num_instructions = 0;
6842 foreach_block(block, cfg)
6843 num_instructions += block->instructions.length();
6844
6845 regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
6846
6847 for (unsigned reg = 0; reg < alloc.count; reg++) {
6848 for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
6849 regs_live_at_ip[ip] += alloc.sizes[reg];
6850 }
6851 }
6852
6853 void
6854 fs_visitor::optimize()
6855 {
6856 /* Start by validating the shader we currently have. */
6857 validate();
6858
6859 /* bld is the common builder object pointing at the end of the program we
6860 * used to translate it into i965 IR. For the optimization and lowering
6861 * passes coming next, any code added after the end of the program without
6862 * having explicitly called fs_builder::at() clearly points at a mistake.
6863 * Ideally optimization passes wouldn't be part of the visitor so they
6864 * wouldn't have access to bld at all, but they do, so just in case some
6865 * pass forgets to ask for a location explicitly set it to NULL here to
6866 * make it trip. The dispatch width is initialized to a bogus value to
6867 * make sure that optimizations set the execution controls explicitly to
6868 * match the code they are manipulating instead of relying on the defaults.
6869 */
6870 bld = fs_builder(this, 64);
6871
6872 assign_constant_locations();
6873 lower_constant_loads();
6874
6875 validate();
6876
6877 split_virtual_grfs();
6878 validate();
6879
6880 #define OPT(pass, args...) ({ \
6881 pass_num++; \
6882 bool this_progress = pass(args); \
6883 \
6884 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
6885 char filename[64]; \
6886 snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass, \
6887 stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
6888 \
6889 backend_shader::dump_instructions(filename); \
6890 } \
6891 \
6892 validate(); \
6893 \
6894 progress = progress || this_progress; \
6895 this_progress; \
6896 })
6897
6898 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
6899 char filename[64];
6900 snprintf(filename, 64, "%s%d-%s-00-00-start",
6901 stage_abbrev, dispatch_width, nir->info.name);
6902
6903 backend_shader::dump_instructions(filename);
6904 }
6905
6906 bool progress = false;
6907 int iteration = 0;
6908 int pass_num = 0;
6909
6910 OPT(remove_extra_rounding_modes);
6911
6912 do {
6913 progress = false;
6914 pass_num = 0;
6915 iteration++;
6916
6917 OPT(remove_duplicate_mrf_writes);
6918
6919 OPT(opt_algebraic);
6920 OPT(opt_cse);
6921 OPT(opt_copy_propagation);
6922 OPT(opt_predicated_break, this);
6923 OPT(opt_cmod_propagation);
6924 OPT(dead_code_eliminate);
6925 OPT(opt_peephole_sel);
6926 OPT(dead_control_flow_eliminate, this);
6927 OPT(opt_register_renaming);
6928 OPT(opt_saturate_propagation);
6929 OPT(register_coalesce);
6930 OPT(compute_to_mrf);
6931 OPT(eliminate_find_live_channel);
6932
6933 OPT(compact_virtual_grfs);
6934 } while (progress);
6935
6936 /* Do this after cmod propagation has had every possible opportunity to
6937 * propagate results into SEL instructions.
6938 */
6939 if (OPT(opt_peephole_csel))
6940 OPT(dead_code_eliminate);
6941
6942 progress = false;
6943 pass_num = 0;
6944
6945 if (OPT(lower_pack)) {
6946 OPT(register_coalesce);
6947 OPT(dead_code_eliminate);
6948 }
6949
6950 OPT(lower_simd_width);
6951
6952 /* After SIMD lowering just in case we had to unroll the EOT send. */
6953 OPT(opt_sampler_eot);
6954
6955 OPT(lower_logical_sends);
6956
6957 if (progress) {
6958 OPT(opt_copy_propagation);
6959 /* Only run after logical send lowering because it's easier to implement
6960 * in terms of physical sends.
6961 */
6962 if (OPT(opt_zero_samples))
6963 OPT(opt_copy_propagation);
6964 /* Run after logical send lowering to give it a chance to CSE the
6965 * LOAD_PAYLOAD instructions created to construct the payloads of
6966 * e.g. texturing messages in cases where it wasn't possible to CSE the
6967 * whole logical instruction.
6968 */
6969 OPT(opt_cse);
6970 OPT(register_coalesce);
6971 OPT(compute_to_mrf);
6972 OPT(dead_code_eliminate);
6973 OPT(remove_duplicate_mrf_writes);
6974 OPT(opt_peephole_sel);
6975 }
6976
6977 OPT(opt_redundant_discard_jumps);
6978
6979 if (OPT(lower_load_payload)) {
6980 split_virtual_grfs();
6981 OPT(register_coalesce);
6982 OPT(lower_simd_width);
6983 OPT(compute_to_mrf);
6984 OPT(dead_code_eliminate);
6985 }
6986
6987 OPT(opt_combine_constants);
6988 OPT(lower_integer_multiplication);
6989
6990 if (devinfo->gen <= 5 && OPT(lower_minmax)) {
6991 OPT(opt_cmod_propagation);
6992 OPT(opt_cse);
6993 OPT(opt_copy_propagation);
6994 OPT(dead_code_eliminate);
6995 }
6996
6997 if (OPT(lower_regioning)) {
6998 OPT(opt_copy_propagation);
6999 OPT(dead_code_eliminate);
7000 OPT(lower_simd_width);
7001 }
7002
7003 OPT(fixup_sends_duplicate_payload);
7004
7005 lower_uniform_pull_constant_loads();
7006
7007 validate();
7008 }
7009
7010 /**
7011 * From the Skylake PRM Vol. 2a docs for sends:
7012 *
7013 * "It is required that the second block of GRFs does not overlap with the
7014 * first block."
7015 *
7016 * There are plenty of cases where we may accidentally violate this due to
7017 * having, for instance, both sources be the constant 0. This little pass
7018 * just adds a new vgrf for the second payload and copies it over.
7019 */
7020 bool
7021 fs_visitor::fixup_sends_duplicate_payload()
7022 {
7023 bool progress = false;
7024
7025 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7026 if (inst->opcode == SHADER_OPCODE_SEND && inst->ex_mlen > 0 &&
7027 regions_overlap(inst->src[2], inst->mlen * REG_SIZE,
7028 inst->src[3], inst->ex_mlen * REG_SIZE)) {
7029 fs_reg tmp = fs_reg(VGRF, alloc.allocate(inst->ex_mlen),
7030 BRW_REGISTER_TYPE_UD);
7031 /* Sadly, we've lost all notion of channels and bit sizes at this
7032 * point. Just WE_all it.
7033 */
7034 const fs_builder ibld = bld.at(block, inst).exec_all().group(16, 0);
7035 fs_reg copy_src = retype(inst->src[3], BRW_REGISTER_TYPE_UD);
7036 fs_reg copy_dst = tmp;
7037 for (unsigned i = 0; i < inst->ex_mlen; i += 2) {
7038 if (inst->ex_mlen == i + 1) {
7039 /* Only one register left; do SIMD8 */
7040 ibld.group(8, 0).MOV(copy_dst, copy_src);
7041 } else {
7042 ibld.MOV(copy_dst, copy_src);
7043 }
7044 copy_src = offset(copy_src, ibld, 1);
7045 copy_dst = offset(copy_dst, ibld, 1);
7046 }
7047 inst->src[3] = tmp;
7048 progress = true;
7049 }
7050 }
7051
7052 if (progress)
7053 invalidate_live_intervals();
7054
7055 return progress;
7056 }
7057
7058 /**
7059 * Three source instruction must have a GRF/MRF destination register.
7060 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
7061 */
7062 void
7063 fs_visitor::fixup_3src_null_dest()
7064 {
7065 bool progress = false;
7066
7067 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7068 if (inst->is_3src(devinfo) && inst->dst.is_null()) {
7069 inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
7070 inst->dst.type);
7071 progress = true;
7072 }
7073 }
7074
7075 if (progress)
7076 invalidate_live_intervals();
7077 }
7078
7079 void
7080 fs_visitor::allocate_registers(unsigned min_dispatch_width, bool allow_spilling)
7081 {
7082 bool allocated_without_spills;
7083
7084 static const enum instruction_scheduler_mode pre_modes[] = {
7085 SCHEDULE_PRE,
7086 SCHEDULE_PRE_NON_LIFO,
7087 SCHEDULE_PRE_LIFO,
7088 };
7089
7090 bool spill_all = allow_spilling && (INTEL_DEBUG & DEBUG_SPILL_FS);
7091
7092 /* Try each scheduling heuristic to see if it can successfully register
7093 * allocate without spilling. They should be ordered by decreasing
7094 * performance but increasing likelihood of allocating.
7095 */
7096 for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
7097 schedule_instructions(pre_modes[i]);
7098
7099 if (0) {
7100 assign_regs_trivial();
7101 allocated_without_spills = true;
7102 } else {
7103 allocated_without_spills = assign_regs(false, spill_all);
7104 }
7105 if (allocated_without_spills)
7106 break;
7107 }
7108
7109 if (!allocated_without_spills) {
7110 if (!allow_spilling)
7111 fail("Failure to register allocate and spilling is not allowed.");
7112
7113 /* We assume that any spilling is worse than just dropping back to
7114 * SIMD8. There's probably actually some intermediate point where
7115 * SIMD16 with a couple of spills is still better.
7116 */
7117 if (dispatch_width > min_dispatch_width) {
7118 fail("Failure to register allocate. Reduce number of "
7119 "live scalar values to avoid this.");
7120 } else {
7121 compiler->shader_perf_log(log_data,
7122 "%s shader triggered register spilling. "
7123 "Try reducing the number of live scalar "
7124 "values to improve performance.\n",
7125 stage_name);
7126 }
7127
7128 /* Since we're out of heuristics, just go spill registers until we
7129 * get an allocation.
7130 */
7131 while (!assign_regs(true, spill_all)) {
7132 if (failed)
7133 break;
7134 }
7135 }
7136
7137 /* This must come after all optimization and register allocation, since
7138 * it inserts dead code that happens to have side effects, and it does
7139 * so based on the actual physical registers in use.
7140 */
7141 insert_gen4_send_dependency_workarounds();
7142
7143 if (failed)
7144 return;
7145
7146 opt_bank_conflicts();
7147
7148 schedule_instructions(SCHEDULE_POST);
7149
7150 if (last_scratch > 0) {
7151 MAYBE_UNUSED unsigned max_scratch_size = 2 * 1024 * 1024;
7152
7153 prog_data->total_scratch = brw_get_scratch_size(last_scratch);
7154
7155 if (stage == MESA_SHADER_COMPUTE) {
7156 if (devinfo->is_haswell) {
7157 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7158 * field documentation, Haswell supports a minimum of 2kB of
7159 * scratch space for compute shaders, unlike every other stage
7160 * and platform.
7161 */
7162 prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
7163 } else if (devinfo->gen <= 7) {
7164 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7165 * field documentation, platforms prior to Haswell measure scratch
7166 * size linearly with a range of [1kB, 12kB] and 1kB granularity.
7167 */
7168 prog_data->total_scratch = ALIGN(last_scratch, 1024);
7169 max_scratch_size = 12 * 1024;
7170 }
7171 }
7172
7173 /* We currently only support up to 2MB of scratch space. If we
7174 * need to support more eventually, the documentation suggests
7175 * that we could allocate a larger buffer, and partition it out
7176 * ourselves. We'd just have to undo the hardware's address
7177 * calculation by subtracting (FFTID * Per Thread Scratch Space)
7178 * and then add FFTID * (Larger Per Thread Scratch Space).
7179 *
7180 * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
7181 * Thread Group Tracking > Local Memory/Scratch Space.
7182 */
7183 assert(prog_data->total_scratch < max_scratch_size);
7184 }
7185 }
7186
7187 bool
7188 fs_visitor::run_vs()
7189 {
7190 assert(stage == MESA_SHADER_VERTEX);
7191
7192 setup_vs_payload();
7193
7194 if (shader_time_index >= 0)
7195 emit_shader_time_begin();
7196
7197 emit_nir_code();
7198
7199 if (failed)
7200 return false;
7201
7202 compute_clip_distance();
7203
7204 emit_urb_writes();
7205
7206 if (shader_time_index >= 0)
7207 emit_shader_time_end();
7208
7209 calculate_cfg();
7210
7211 optimize();
7212
7213 assign_curb_setup();
7214 assign_vs_urb_setup();
7215
7216 fixup_3src_null_dest();
7217 allocate_registers(8, true);
7218
7219 return !failed;
7220 }
7221
7222 bool
7223 fs_visitor::run_tcs_single_patch()
7224 {
7225 assert(stage == MESA_SHADER_TESS_CTRL);
7226
7227 struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
7228
7229 /* r1-r4 contain the ICP handles. */
7230 payload.num_regs = 5;
7231
7232 if (shader_time_index >= 0)
7233 emit_shader_time_begin();
7234
7235 /* Initialize gl_InvocationID */
7236 fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
7237 fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
7238 bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
7239 bld.MOV(channels_ud, channels_uw);
7240
7241 if (tcs_prog_data->instances == 1) {
7242 invocation_id = channels_ud;
7243 } else {
7244 const unsigned invocation_id_mask = devinfo->gen >= 11 ?
7245 INTEL_MASK(22, 16) : INTEL_MASK(23, 17);
7246 const unsigned invocation_id_shift = devinfo->gen >= 11 ? 16 : 17;
7247
7248 invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
7249
7250 /* Get instance number from g0.2 bits 23:17, and multiply it by 8. */
7251 fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
7252 fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
7253 bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
7254 brw_imm_ud(invocation_id_mask));
7255 bld.SHR(instance_times_8, t, brw_imm_ud(invocation_id_shift - 3));
7256
7257 bld.ADD(invocation_id, instance_times_8, channels_ud);
7258 }
7259
7260 /* Fix the disptach mask */
7261 if (nir->info.tess.tcs_vertices_out % 8) {
7262 bld.CMP(bld.null_reg_ud(), invocation_id,
7263 brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
7264 bld.IF(BRW_PREDICATE_NORMAL);
7265 }
7266
7267 emit_nir_code();
7268
7269 if (nir->info.tess.tcs_vertices_out % 8) {
7270 bld.emit(BRW_OPCODE_ENDIF);
7271 }
7272
7273 /* Emit EOT write; set TR DS Cache bit */
7274 fs_reg srcs[3] = {
7275 fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
7276 fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
7277 fs_reg(brw_imm_ud(0)),
7278 };
7279 fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
7280 bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
7281
7282 fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
7283 bld.null_reg_ud(), payload);
7284 inst->mlen = 3;
7285 inst->eot = true;
7286
7287 if (shader_time_index >= 0)
7288 emit_shader_time_end();
7289
7290 if (failed)
7291 return false;
7292
7293 calculate_cfg();
7294
7295 optimize();
7296
7297 assign_curb_setup();
7298 assign_tcs_single_patch_urb_setup();
7299
7300 fixup_3src_null_dest();
7301 allocate_registers(8, true);
7302
7303 return !failed;
7304 }
7305
7306 bool
7307 fs_visitor::run_tes()
7308 {
7309 assert(stage == MESA_SHADER_TESS_EVAL);
7310
7311 /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
7312 payload.num_regs = 5;
7313
7314 if (shader_time_index >= 0)
7315 emit_shader_time_begin();
7316
7317 emit_nir_code();
7318
7319 if (failed)
7320 return false;
7321
7322 emit_urb_writes();
7323
7324 if (shader_time_index >= 0)
7325 emit_shader_time_end();
7326
7327 calculate_cfg();
7328
7329 optimize();
7330
7331 assign_curb_setup();
7332 assign_tes_urb_setup();
7333
7334 fixup_3src_null_dest();
7335 allocate_registers(8, true);
7336
7337 return !failed;
7338 }
7339
7340 bool
7341 fs_visitor::run_gs()
7342 {
7343 assert(stage == MESA_SHADER_GEOMETRY);
7344
7345 setup_gs_payload();
7346
7347 this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
7348
7349 if (gs_compile->control_data_header_size_bits > 0) {
7350 /* Create a VGRF to store accumulated control data bits. */
7351 this->control_data_bits = vgrf(glsl_type::uint_type);
7352
7353 /* If we're outputting more than 32 control data bits, then EmitVertex()
7354 * will set control_data_bits to 0 after emitting the first vertex.
7355 * Otherwise, we need to initialize it to 0 here.
7356 */
7357 if (gs_compile->control_data_header_size_bits <= 32) {
7358 const fs_builder abld = bld.annotate("initialize control data bits");
7359 abld.MOV(this->control_data_bits, brw_imm_ud(0u));
7360 }
7361 }
7362
7363 if (shader_time_index >= 0)
7364 emit_shader_time_begin();
7365
7366 emit_nir_code();
7367
7368 emit_gs_thread_end();
7369
7370 if (shader_time_index >= 0)
7371 emit_shader_time_end();
7372
7373 if (failed)
7374 return false;
7375
7376 calculate_cfg();
7377
7378 optimize();
7379
7380 assign_curb_setup();
7381 assign_gs_urb_setup();
7382
7383 fixup_3src_null_dest();
7384 allocate_registers(8, true);
7385
7386 return !failed;
7387 }
7388
7389 /* From the SKL PRM, Volume 16, Workarounds:
7390 *
7391 * 0877 3D Pixel Shader Hang possible when pixel shader dispatched with
7392 * only header phases (R0-R2)
7393 *
7394 * WA: Enable a non-header phase (e.g. push constant) when dispatch would
7395 * have been header only.
7396 *
7397 * Instead of enabling push constants one can alternatively enable one of the
7398 * inputs. Here one simply chooses "layer" which shouldn't impose much
7399 * overhead.
7400 */
7401 static void
7402 gen9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
7403 {
7404 if (wm_prog_data->num_varying_inputs)
7405 return;
7406
7407 if (wm_prog_data->base.curb_read_length)
7408 return;
7409
7410 wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
7411 wm_prog_data->num_varying_inputs = 1;
7412 }
7413
7414 bool
7415 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
7416 {
7417 struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
7418 brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
7419
7420 assert(stage == MESA_SHADER_FRAGMENT);
7421
7422 if (devinfo->gen >= 6)
7423 setup_fs_payload_gen6();
7424 else
7425 setup_fs_payload_gen4();
7426
7427 if (0) {
7428 emit_dummy_fs();
7429 } else if (do_rep_send) {
7430 assert(dispatch_width == 16);
7431 emit_repclear_shader();
7432 } else {
7433 if (shader_time_index >= 0)
7434 emit_shader_time_begin();
7435
7436 calculate_urb_setup();
7437 if (nir->info.inputs_read > 0 ||
7438 (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
7439 if (devinfo->gen < 6)
7440 emit_interpolation_setup_gen4();
7441 else
7442 emit_interpolation_setup_gen6();
7443 }
7444
7445 /* We handle discards by keeping track of the still-live pixels in f0.1.
7446 * Initialize it with the dispatched pixels.
7447 */
7448 if (wm_prog_data->uses_kill) {
7449 const fs_reg dispatch_mask =
7450 devinfo->gen >= 6 ? brw_vec1_grf(1, 7) : brw_vec1_grf(0, 0);
7451 bld.exec_all().group(1, 0)
7452 .MOV(retype(brw_flag_reg(0, 1), BRW_REGISTER_TYPE_UW),
7453 retype(dispatch_mask, BRW_REGISTER_TYPE_UW));
7454 }
7455
7456 emit_nir_code();
7457
7458 if (failed)
7459 return false;
7460
7461 if (wm_prog_data->uses_kill)
7462 bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
7463
7464 if (wm_key->alpha_test_func)
7465 emit_alpha_test();
7466
7467 emit_fb_writes();
7468
7469 if (shader_time_index >= 0)
7470 emit_shader_time_end();
7471
7472 calculate_cfg();
7473
7474 optimize();
7475
7476 assign_curb_setup();
7477
7478 if (devinfo->gen >= 9)
7479 gen9_ps_header_only_workaround(wm_prog_data);
7480
7481 assign_urb_setup();
7482
7483 fixup_3src_null_dest();
7484 allocate_registers(8, allow_spilling);
7485
7486 if (failed)
7487 return false;
7488 }
7489
7490 return !failed;
7491 }
7492
7493 bool
7494 fs_visitor::run_cs(unsigned min_dispatch_width)
7495 {
7496 assert(stage == MESA_SHADER_COMPUTE);
7497 assert(dispatch_width >= min_dispatch_width);
7498
7499 setup_cs_payload();
7500
7501 if (shader_time_index >= 0)
7502 emit_shader_time_begin();
7503
7504 if (devinfo->is_haswell && prog_data->total_shared > 0) {
7505 /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
7506 const fs_builder abld = bld.exec_all().group(1, 0);
7507 abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
7508 suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
7509 }
7510
7511 emit_nir_code();
7512
7513 if (failed)
7514 return false;
7515
7516 emit_cs_terminate();
7517
7518 if (shader_time_index >= 0)
7519 emit_shader_time_end();
7520
7521 calculate_cfg();
7522
7523 optimize();
7524
7525 assign_curb_setup();
7526
7527 fixup_3src_null_dest();
7528 allocate_registers(min_dispatch_width, true);
7529
7530 if (failed)
7531 return false;
7532
7533 return !failed;
7534 }
7535
7536 /**
7537 * Return a bitfield where bit n is set if barycentric interpolation mode n
7538 * (see enum brw_barycentric_mode) is needed by the fragment shader.
7539 *
7540 * We examine the load_barycentric intrinsics rather than looking at input
7541 * variables so that we catch interpolateAtCentroid() messages too, which
7542 * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
7543 */
7544 static unsigned
7545 brw_compute_barycentric_interp_modes(const struct gen_device_info *devinfo,
7546 const nir_shader *shader)
7547 {
7548 unsigned barycentric_interp_modes = 0;
7549
7550 nir_foreach_function(f, shader) {
7551 if (!f->impl)
7552 continue;
7553
7554 nir_foreach_block(block, f->impl) {
7555 nir_foreach_instr(instr, block) {
7556 if (instr->type != nir_instr_type_intrinsic)
7557 continue;
7558
7559 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7560 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
7561 continue;
7562
7563 /* Ignore WPOS; it doesn't require interpolation. */
7564 if (nir_intrinsic_base(intrin) == VARYING_SLOT_POS)
7565 continue;
7566
7567 intrin = nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
7568 enum glsl_interp_mode interp = (enum glsl_interp_mode)
7569 nir_intrinsic_interp_mode(intrin);
7570 nir_intrinsic_op bary_op = intrin->intrinsic;
7571 enum brw_barycentric_mode bary =
7572 brw_barycentric_mode(interp, bary_op);
7573
7574 barycentric_interp_modes |= 1 << bary;
7575
7576 if (devinfo->needs_unlit_centroid_workaround &&
7577 bary_op == nir_intrinsic_load_barycentric_centroid)
7578 barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
7579 }
7580 }
7581 }
7582
7583 return barycentric_interp_modes;
7584 }
7585
7586 static void
7587 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
7588 const nir_shader *shader)
7589 {
7590 prog_data->flat_inputs = 0;
7591
7592 nir_foreach_variable(var, &shader->inputs) {
7593 unsigned slots = glsl_count_attribute_slots(var->type, false);
7594 for (unsigned s = 0; s < slots; s++) {
7595 int input_index = prog_data->urb_setup[var->data.location + s];
7596
7597 if (input_index < 0)
7598 continue;
7599
7600 /* flat shading */
7601 if (var->data.interpolation == INTERP_MODE_FLAT)
7602 prog_data->flat_inputs |= 1 << input_index;
7603 }
7604 }
7605 }
7606
7607 static uint8_t
7608 computed_depth_mode(const nir_shader *shader)
7609 {
7610 if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
7611 switch (shader->info.fs.depth_layout) {
7612 case FRAG_DEPTH_LAYOUT_NONE:
7613 case FRAG_DEPTH_LAYOUT_ANY:
7614 return BRW_PSCDEPTH_ON;
7615 case FRAG_DEPTH_LAYOUT_GREATER:
7616 return BRW_PSCDEPTH_ON_GE;
7617 case FRAG_DEPTH_LAYOUT_LESS:
7618 return BRW_PSCDEPTH_ON_LE;
7619 case FRAG_DEPTH_LAYOUT_UNCHANGED:
7620 return BRW_PSCDEPTH_OFF;
7621 }
7622 }
7623 return BRW_PSCDEPTH_OFF;
7624 }
7625
7626 /**
7627 * Move load_interpolated_input with simple (payload-based) barycentric modes
7628 * to the top of the program so we don't emit multiple PLNs for the same input.
7629 *
7630 * This works around CSE not being able to handle non-dominating cases
7631 * such as:
7632 *
7633 * if (...) {
7634 * interpolate input
7635 * } else {
7636 * interpolate the same exact input
7637 * }
7638 *
7639 * This should be replaced by global value numbering someday.
7640 */
7641 static bool
7642 move_interpolation_to_top(nir_shader *nir)
7643 {
7644 bool progress = false;
7645
7646 nir_foreach_function(f, nir) {
7647 if (!f->impl)
7648 continue;
7649
7650 nir_block *top = nir_start_block(f->impl);
7651 exec_node *cursor_node = NULL;
7652
7653 nir_foreach_block(block, f->impl) {
7654 if (block == top)
7655 continue;
7656
7657 nir_foreach_instr_safe(instr, block) {
7658 if (instr->type != nir_instr_type_intrinsic)
7659 continue;
7660
7661 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7662 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
7663 continue;
7664 nir_intrinsic_instr *bary_intrinsic =
7665 nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
7666 nir_intrinsic_op op = bary_intrinsic->intrinsic;
7667
7668 /* Leave interpolateAtSample/Offset() where they are. */
7669 if (op == nir_intrinsic_load_barycentric_at_sample ||
7670 op == nir_intrinsic_load_barycentric_at_offset)
7671 continue;
7672
7673 nir_instr *move[3] = {
7674 &bary_intrinsic->instr,
7675 intrin->src[1].ssa->parent_instr,
7676 instr
7677 };
7678
7679 for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
7680 if (move[i]->block != top) {
7681 move[i]->block = top;
7682 exec_node_remove(&move[i]->node);
7683 if (cursor_node) {
7684 exec_node_insert_after(cursor_node, &move[i]->node);
7685 } else {
7686 exec_list_push_head(&top->instr_list, &move[i]->node);
7687 }
7688 cursor_node = &move[i]->node;
7689 progress = true;
7690 }
7691 }
7692 }
7693 }
7694 nir_metadata_preserve(f->impl, (nir_metadata)
7695 ((unsigned) nir_metadata_block_index |
7696 (unsigned) nir_metadata_dominance));
7697 }
7698
7699 return progress;
7700 }
7701
7702 /**
7703 * Demote per-sample barycentric intrinsics to centroid.
7704 *
7705 * Useful when rendering to a non-multisampled buffer.
7706 */
7707 static bool
7708 demote_sample_qualifiers(nir_shader *nir)
7709 {
7710 bool progress = true;
7711
7712 nir_foreach_function(f, nir) {
7713 if (!f->impl)
7714 continue;
7715
7716 nir_builder b;
7717 nir_builder_init(&b, f->impl);
7718
7719 nir_foreach_block(block, f->impl) {
7720 nir_foreach_instr_safe(instr, block) {
7721 if (instr->type != nir_instr_type_intrinsic)
7722 continue;
7723
7724 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7725 if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
7726 intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
7727 continue;
7728
7729 b.cursor = nir_before_instr(instr);
7730 nir_ssa_def *centroid =
7731 nir_load_barycentric(&b, nir_intrinsic_load_barycentric_centroid,
7732 nir_intrinsic_interp_mode(intrin));
7733 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
7734 nir_src_for_ssa(centroid));
7735 nir_instr_remove(instr);
7736 progress = true;
7737 }
7738 }
7739
7740 nir_metadata_preserve(f->impl, (nir_metadata)
7741 ((unsigned) nir_metadata_block_index |
7742 (unsigned) nir_metadata_dominance));
7743 }
7744
7745 return progress;
7746 }
7747
7748 /**
7749 * Pre-gen6, the register file of the EUs was shared between threads,
7750 * and each thread used some subset allocated on a 16-register block
7751 * granularity. The unit states wanted these block counts.
7752 */
7753 static inline int
7754 brw_register_blocks(int reg_count)
7755 {
7756 return ALIGN(reg_count, 16) / 16 - 1;
7757 }
7758
7759 const unsigned *
7760 brw_compile_fs(const struct brw_compiler *compiler, void *log_data,
7761 void *mem_ctx,
7762 const struct brw_wm_prog_key *key,
7763 struct brw_wm_prog_data *prog_data,
7764 nir_shader *shader,
7765 struct gl_program *prog,
7766 int shader_time_index8, int shader_time_index16,
7767 int shader_time_index32, bool allow_spilling,
7768 bool use_rep_send, struct brw_vue_map *vue_map,
7769 char **error_str)
7770 {
7771 const struct gen_device_info *devinfo = compiler->devinfo;
7772
7773 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
7774 brw_nir_lower_fs_inputs(shader, devinfo, key);
7775 brw_nir_lower_fs_outputs(shader);
7776
7777 if (devinfo->gen < 6) {
7778 brw_setup_vue_interpolation(vue_map, shader, prog_data, devinfo);
7779 }
7780
7781 if (!key->multisample_fbo)
7782 NIR_PASS_V(shader, demote_sample_qualifiers);
7783 NIR_PASS_V(shader, move_interpolation_to_top);
7784 shader = brw_postprocess_nir(shader, compiler, true);
7785
7786 /* key->alpha_test_func means simulating alpha testing via discards,
7787 * so the shader definitely kills pixels.
7788 */
7789 prog_data->uses_kill = shader->info.fs.uses_discard ||
7790 key->alpha_test_func;
7791 prog_data->uses_omask = key->multisample_fbo &&
7792 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
7793 prog_data->computed_depth_mode = computed_depth_mode(shader);
7794 prog_data->computed_stencil =
7795 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
7796
7797 prog_data->persample_dispatch =
7798 key->multisample_fbo &&
7799 (key->persample_interp ||
7800 (shader->info.system_values_read & (SYSTEM_BIT_SAMPLE_ID |
7801 SYSTEM_BIT_SAMPLE_POS)) ||
7802 shader->info.fs.uses_sample_qualifier ||
7803 shader->info.outputs_read);
7804
7805 prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
7806
7807 prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
7808 prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
7809 prog_data->inner_coverage = shader->info.fs.inner_coverage;
7810
7811 prog_data->barycentric_interp_modes =
7812 brw_compute_barycentric_interp_modes(compiler->devinfo, shader);
7813
7814 cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL, *simd32_cfg = NULL;
7815
7816 fs_visitor v8(compiler, log_data, mem_ctx, key,
7817 &prog_data->base, prog, shader, 8,
7818 shader_time_index8);
7819 if (!v8.run_fs(allow_spilling, false /* do_rep_send */)) {
7820 if (error_str)
7821 *error_str = ralloc_strdup(mem_ctx, v8.fail_msg);
7822
7823 return NULL;
7824 } else if (likely(!(INTEL_DEBUG & DEBUG_NO8))) {
7825 simd8_cfg = v8.cfg;
7826 prog_data->base.dispatch_grf_start_reg = v8.payload.num_regs;
7827 prog_data->reg_blocks_8 = brw_register_blocks(v8.grf_used);
7828 }
7829
7830 if (v8.max_dispatch_width >= 16 &&
7831 likely(!(INTEL_DEBUG & DEBUG_NO16) || use_rep_send)) {
7832 /* Try a SIMD16 compile */
7833 fs_visitor v16(compiler, log_data, mem_ctx, key,
7834 &prog_data->base, prog, shader, 16,
7835 shader_time_index16);
7836 v16.import_uniforms(&v8);
7837 if (!v16.run_fs(allow_spilling, use_rep_send)) {
7838 compiler->shader_perf_log(log_data,
7839 "SIMD16 shader failed to compile: %s",
7840 v16.fail_msg);
7841 } else {
7842 simd16_cfg = v16.cfg;
7843 prog_data->dispatch_grf_start_reg_16 = v16.payload.num_regs;
7844 prog_data->reg_blocks_16 = brw_register_blocks(v16.grf_used);
7845 }
7846 }
7847
7848 /* Currently, the compiler only supports SIMD32 on SNB+ */
7849 if (v8.max_dispatch_width >= 32 && !use_rep_send &&
7850 compiler->devinfo->gen >= 6 &&
7851 unlikely(INTEL_DEBUG & DEBUG_DO32)) {
7852 /* Try a SIMD32 compile */
7853 fs_visitor v32(compiler, log_data, mem_ctx, key,
7854 &prog_data->base, prog, shader, 32,
7855 shader_time_index32);
7856 v32.import_uniforms(&v8);
7857 if (!v32.run_fs(allow_spilling, false)) {
7858 compiler->shader_perf_log(log_data,
7859 "SIMD32 shader failed to compile: %s",
7860 v32.fail_msg);
7861 } else {
7862 simd32_cfg = v32.cfg;
7863 prog_data->dispatch_grf_start_reg_32 = v32.payload.num_regs;
7864 prog_data->reg_blocks_32 = brw_register_blocks(v32.grf_used);
7865 }
7866 }
7867
7868 /* When the caller requests a repclear shader, they want SIMD16-only */
7869 if (use_rep_send)
7870 simd8_cfg = NULL;
7871
7872 /* Prior to Iron Lake, the PS had a single shader offset with a jump table
7873 * at the top to select the shader. We've never implemented that.
7874 * Instead, we just give them exactly one shader and we pick the widest one
7875 * available.
7876 */
7877 if (compiler->devinfo->gen < 5) {
7878 if (simd32_cfg || simd16_cfg)
7879 simd8_cfg = NULL;
7880 if (simd32_cfg)
7881 simd16_cfg = NULL;
7882 }
7883
7884 /* If computed depth is enabled SNB only allows SIMD8. */
7885 if (compiler->devinfo->gen == 6 &&
7886 prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF)
7887 assert(simd16_cfg == NULL && simd32_cfg == NULL);
7888
7889 if (compiler->devinfo->gen <= 5 && !simd8_cfg) {
7890 /* Iron lake and earlier only have one Dispatch GRF start field. Make
7891 * the data available in the base prog data struct for convenience.
7892 */
7893 if (simd16_cfg) {
7894 prog_data->base.dispatch_grf_start_reg =
7895 prog_data->dispatch_grf_start_reg_16;
7896 } else if (simd32_cfg) {
7897 prog_data->base.dispatch_grf_start_reg =
7898 prog_data->dispatch_grf_start_reg_32;
7899 }
7900 }
7901
7902 if (prog_data->persample_dispatch) {
7903 /* Starting with SandyBridge (where we first get MSAA), the different
7904 * pixel dispatch combinations are grouped into classifications A
7905 * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1). On all hardware
7906 * generations, the only configurations supporting persample dispatch
7907 * are are this in which only one dispatch width is enabled.
7908 */
7909 if (simd32_cfg || simd16_cfg)
7910 simd8_cfg = NULL;
7911 if (simd32_cfg)
7912 simd16_cfg = NULL;
7913 }
7914
7915 /* We have to compute the flat inputs after the visitor is finished running
7916 * because it relies on prog_data->urb_setup which is computed in
7917 * fs_visitor::calculate_urb_setup().
7918 */
7919 brw_compute_flat_inputs(prog_data, shader);
7920
7921 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
7922 v8.promoted_constants, v8.runtime_check_aads_emit,
7923 MESA_SHADER_FRAGMENT);
7924
7925 if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
7926 g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
7927 shader->info.label ?
7928 shader->info.label : "unnamed",
7929 shader->info.name));
7930 }
7931
7932 if (simd8_cfg) {
7933 prog_data->dispatch_8 = true;
7934 g.generate_code(simd8_cfg, 8);
7935 }
7936
7937 if (simd16_cfg) {
7938 prog_data->dispatch_16 = true;
7939 prog_data->prog_offset_16 = g.generate_code(simd16_cfg, 16);
7940 }
7941
7942 if (simd32_cfg) {
7943 prog_data->dispatch_32 = true;
7944 prog_data->prog_offset_32 = g.generate_code(simd32_cfg, 32);
7945 }
7946
7947 return g.get_assembly();
7948 }
7949
7950 fs_reg *
7951 fs_visitor::emit_cs_work_group_id_setup()
7952 {
7953 assert(stage == MESA_SHADER_COMPUTE);
7954
7955 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
7956
7957 struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
7958 struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
7959 struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
7960
7961 bld.MOV(*reg, r0_1);
7962 bld.MOV(offset(*reg, bld, 1), r0_6);
7963 bld.MOV(offset(*reg, bld, 2), r0_7);
7964
7965 return reg;
7966 }
7967
7968 static void
7969 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
7970 {
7971 block->dwords = dwords;
7972 block->regs = DIV_ROUND_UP(dwords, 8);
7973 block->size = block->regs * 32;
7974 }
7975
7976 static void
7977 cs_fill_push_const_info(const struct gen_device_info *devinfo,
7978 struct brw_cs_prog_data *cs_prog_data)
7979 {
7980 const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
7981 int subgroup_id_index = get_subgroup_id_param_index(prog_data);
7982 bool cross_thread_supported = devinfo->gen > 7 || devinfo->is_haswell;
7983
7984 /* The thread ID should be stored in the last param dword */
7985 assert(subgroup_id_index == -1 ||
7986 subgroup_id_index == (int)prog_data->nr_params - 1);
7987
7988 unsigned cross_thread_dwords, per_thread_dwords;
7989 if (!cross_thread_supported) {
7990 cross_thread_dwords = 0u;
7991 per_thread_dwords = prog_data->nr_params;
7992 } else if (subgroup_id_index >= 0) {
7993 /* Fill all but the last register with cross-thread payload */
7994 cross_thread_dwords = 8 * (subgroup_id_index / 8);
7995 per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
7996 assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
7997 } else {
7998 /* Fill all data using cross-thread payload */
7999 cross_thread_dwords = prog_data->nr_params;
8000 per_thread_dwords = 0u;
8001 }
8002
8003 fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
8004 fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
8005
8006 unsigned total_dwords =
8007 (cs_prog_data->push.per_thread.size * cs_prog_data->threads +
8008 cs_prog_data->push.cross_thread.size) / 4;
8009 fill_push_const_block_info(&cs_prog_data->push.total, total_dwords);
8010
8011 assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
8012 cs_prog_data->push.per_thread.size == 0);
8013 assert(cs_prog_data->push.cross_thread.dwords +
8014 cs_prog_data->push.per_thread.dwords ==
8015 prog_data->nr_params);
8016 }
8017
8018 static void
8019 cs_set_simd_size(struct brw_cs_prog_data *cs_prog_data, unsigned size)
8020 {
8021 cs_prog_data->simd_size = size;
8022 unsigned group_size = cs_prog_data->local_size[0] *
8023 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
8024 cs_prog_data->threads = (group_size + size - 1) / size;
8025 }
8026
8027 static nir_shader *
8028 compile_cs_to_nir(const struct brw_compiler *compiler,
8029 void *mem_ctx,
8030 const struct brw_cs_prog_key *key,
8031 const nir_shader *src_shader,
8032 unsigned dispatch_width)
8033 {
8034 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
8035 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
8036 brw_nir_lower_cs_intrinsics(shader, dispatch_width);
8037 return brw_postprocess_nir(shader, compiler, true);
8038 }
8039
8040 const unsigned *
8041 brw_compile_cs(const struct brw_compiler *compiler, void *log_data,
8042 void *mem_ctx,
8043 const struct brw_cs_prog_key *key,
8044 struct brw_cs_prog_data *prog_data,
8045 const nir_shader *src_shader,
8046 int shader_time_index,
8047 char **error_str)
8048 {
8049 prog_data->local_size[0] = src_shader->info.cs.local_size[0];
8050 prog_data->local_size[1] = src_shader->info.cs.local_size[1];
8051 prog_data->local_size[2] = src_shader->info.cs.local_size[2];
8052 unsigned local_workgroup_size =
8053 src_shader->info.cs.local_size[0] * src_shader->info.cs.local_size[1] *
8054 src_shader->info.cs.local_size[2];
8055
8056 unsigned min_dispatch_width =
8057 DIV_ROUND_UP(local_workgroup_size, compiler->devinfo->max_cs_threads);
8058 min_dispatch_width = MAX2(8, min_dispatch_width);
8059 min_dispatch_width = util_next_power_of_two(min_dispatch_width);
8060 assert(min_dispatch_width <= 32);
8061
8062 fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
8063 cfg_t *cfg = NULL;
8064 const char *fail_msg = NULL;
8065 unsigned promoted_constants = 0;
8066
8067 /* Now the main event: Visit the shader IR and generate our CS IR for it.
8068 */
8069 if (min_dispatch_width <= 8) {
8070 nir_shader *nir8 = compile_cs_to_nir(compiler, mem_ctx, key,
8071 src_shader, 8);
8072 v8 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8073 NULL, /* Never used in core profile */
8074 nir8, 8, shader_time_index);
8075 if (!v8->run_cs(min_dispatch_width)) {
8076 fail_msg = v8->fail_msg;
8077 } else {
8078 /* We should always be able to do SIMD32 for compute shaders */
8079 assert(v8->max_dispatch_width >= 32);
8080
8081 cfg = v8->cfg;
8082 cs_set_simd_size(prog_data, 8);
8083 cs_fill_push_const_info(compiler->devinfo, prog_data);
8084 promoted_constants = v8->promoted_constants;
8085 }
8086 }
8087
8088 if (likely(!(INTEL_DEBUG & DEBUG_NO16)) &&
8089 !fail_msg && min_dispatch_width <= 16) {
8090 /* Try a SIMD16 compile */
8091 nir_shader *nir16 = compile_cs_to_nir(compiler, mem_ctx, key,
8092 src_shader, 16);
8093 v16 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8094 NULL, /* Never used in core profile */
8095 nir16, 16, shader_time_index);
8096 if (v8)
8097 v16->import_uniforms(v8);
8098
8099 if (!v16->run_cs(min_dispatch_width)) {
8100 compiler->shader_perf_log(log_data,
8101 "SIMD16 shader failed to compile: %s",
8102 v16->fail_msg);
8103 if (!cfg) {
8104 fail_msg =
8105 "Couldn't generate SIMD16 program and not "
8106 "enough threads for SIMD8";
8107 }
8108 } else {
8109 /* We should always be able to do SIMD32 for compute shaders */
8110 assert(v16->max_dispatch_width >= 32);
8111
8112 cfg = v16->cfg;
8113 cs_set_simd_size(prog_data, 16);
8114 cs_fill_push_const_info(compiler->devinfo, prog_data);
8115 promoted_constants = v16->promoted_constants;
8116 }
8117 }
8118
8119 /* We should always be able to do SIMD32 for compute shaders */
8120 assert(!v16 || v16->max_dispatch_width >= 32);
8121
8122 if (!fail_msg && (min_dispatch_width > 16 || (INTEL_DEBUG & DEBUG_DO32))) {
8123 /* Try a SIMD32 compile */
8124 nir_shader *nir32 = compile_cs_to_nir(compiler, mem_ctx, key,
8125 src_shader, 32);
8126 v32 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8127 NULL, /* Never used in core profile */
8128 nir32, 32, shader_time_index);
8129 if (v8)
8130 v32->import_uniforms(v8);
8131 else if (v16)
8132 v32->import_uniforms(v16);
8133
8134 if (!v32->run_cs(min_dispatch_width)) {
8135 compiler->shader_perf_log(log_data,
8136 "SIMD32 shader failed to compile: %s",
8137 v16->fail_msg);
8138 if (!cfg) {
8139 fail_msg =
8140 "Couldn't generate SIMD32 program and not "
8141 "enough threads for SIMD16";
8142 }
8143 } else {
8144 cfg = v32->cfg;
8145 cs_set_simd_size(prog_data, 32);
8146 cs_fill_push_const_info(compiler->devinfo, prog_data);
8147 promoted_constants = v32->promoted_constants;
8148 }
8149 }
8150
8151 const unsigned *ret = NULL;
8152 if (unlikely(cfg == NULL)) {
8153 assert(fail_msg);
8154 if (error_str)
8155 *error_str = ralloc_strdup(mem_ctx, fail_msg);
8156 } else {
8157 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
8158 promoted_constants, false, MESA_SHADER_COMPUTE);
8159 if (INTEL_DEBUG & DEBUG_CS) {
8160 char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
8161 src_shader->info.label ?
8162 src_shader->info.label : "unnamed",
8163 src_shader->info.name);
8164 g.enable_debug(name);
8165 }
8166
8167 g.generate_code(cfg, prog_data->simd_size);
8168
8169 ret = g.get_assembly();
8170 }
8171
8172 delete v8;
8173 delete v16;
8174 delete v32;
8175
8176 return ret;
8177 }
8178
8179 /**
8180 * Test the dispatch mask packing assumptions of
8181 * brw_stage_has_packed_dispatch(). Call this from e.g. the top of
8182 * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
8183 * executed with an unexpected dispatch mask.
8184 */
8185 static UNUSED void
8186 brw_fs_test_dispatch_packing(const fs_builder &bld)
8187 {
8188 const gl_shader_stage stage = bld.shader->stage;
8189
8190 if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
8191 bld.shader->stage_prog_data)) {
8192 const fs_builder ubld = bld.exec_all().group(1, 0);
8193 const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
8194 const fs_reg mask = (stage == MESA_SHADER_FRAGMENT ? brw_vmask_reg() :
8195 brw_dmask_reg());
8196
8197 ubld.ADD(tmp, mask, brw_imm_ud(1));
8198 ubld.AND(tmp, mask, tmp);
8199
8200 /* This will loop forever if the dispatch mask doesn't have the expected
8201 * form '2^n-1', in which case tmp will be non-zero.
8202 */
8203 bld.emit(BRW_OPCODE_DO);
8204 bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
8205 set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));
8206 }
8207 }