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