cfbd66d297bbac554230ee1446915f5694a42b1b
[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 brw_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.reg_offset != 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.reg_offset += 1;
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 brw_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->reg_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 brw_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].reg_offset;
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].reg_offset;
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.reg_offset;
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].reg_offset;
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.reg_offset;
1830 inst->dst.nr = new_virtual_grf[reg];
1831 inst->dst.reg_offset = new_reg_offset[reg];
1832 assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1833 }
1834 for (int i = 0; i < inst->sources; i++) {
1835 if (inst->src[i].file == VGRF) {
1836 reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].reg_offset;
1837 inst->src[i].nr = new_virtual_grf[reg];
1838 inst->src[i].reg_offset = new_reg_offset[reg];
1839 assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1840 }
1841 }
1842 }
1843 invalidate_live_intervals();
1844 }
1845
1846 /**
1847 * Remove unused virtual GRFs and compact the virtual_grf_* arrays.
1848 *
1849 * During code generation, we create tons of temporary variables, many of
1850 * which get immediately killed and are never used again. Yet, in later
1851 * optimization and analysis passes, such as compute_live_intervals, we need
1852 * to loop over all the virtual GRFs. Compacting them can save a lot of
1853 * overhead.
1854 */
1855 bool
1856 fs_visitor::compact_virtual_grfs()
1857 {
1858 bool progress = false;
1859 int remap_table[this->alloc.count];
1860 memset(remap_table, -1, sizeof(remap_table));
1861
1862 /* Mark which virtual GRFs are used. */
1863 foreach_block_and_inst(block, const fs_inst, inst, cfg) {
1864 if (inst->dst.file == VGRF)
1865 remap_table[inst->dst.nr] = 0;
1866
1867 for (int i = 0; i < inst->sources; i++) {
1868 if (inst->src[i].file == VGRF)
1869 remap_table[inst->src[i].nr] = 0;
1870 }
1871 }
1872
1873 /* Compact the GRF arrays. */
1874 int new_index = 0;
1875 for (unsigned i = 0; i < this->alloc.count; i++) {
1876 if (remap_table[i] == -1) {
1877 /* We just found an unused register. This means that we are
1878 * actually going to compact something.
1879 */
1880 progress = true;
1881 } else {
1882 remap_table[i] = new_index;
1883 alloc.sizes[new_index] = alloc.sizes[i];
1884 invalidate_live_intervals();
1885 ++new_index;
1886 }
1887 }
1888
1889 this->alloc.count = new_index;
1890
1891 /* Patch all the instructions to use the newly renumbered registers */
1892 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1893 if (inst->dst.file == VGRF)
1894 inst->dst.nr = remap_table[inst->dst.nr];
1895
1896 for (int i = 0; i < inst->sources; i++) {
1897 if (inst->src[i].file == VGRF)
1898 inst->src[i].nr = remap_table[inst->src[i].nr];
1899 }
1900 }
1901
1902 /* Patch all the references to delta_xy, since they're used in register
1903 * allocation. If they're unused, switch them to BAD_FILE so we don't
1904 * think some random VGRF is delta_xy.
1905 */
1906 for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
1907 if (delta_xy[i].file == VGRF) {
1908 if (remap_table[delta_xy[i].nr] != -1) {
1909 delta_xy[i].nr = remap_table[delta_xy[i].nr];
1910 } else {
1911 delta_xy[i].file = BAD_FILE;
1912 }
1913 }
1914 }
1915
1916 return progress;
1917 }
1918
1919 static void
1920 set_push_pull_constant_loc(unsigned uniform, int *chunk_start, bool contiguous,
1921 int *push_constant_loc, int *pull_constant_loc,
1922 unsigned *num_push_constants,
1923 unsigned *num_pull_constants,
1924 const unsigned max_push_components,
1925 const unsigned max_chunk_size,
1926 struct brw_stage_prog_data *stage_prog_data)
1927 {
1928 /* This is the first live uniform in the chunk */
1929 if (*chunk_start < 0)
1930 *chunk_start = uniform;
1931
1932 /* If this element does not need to be contiguous with the next, we
1933 * split at this point and everything between chunk_start and u forms a
1934 * single chunk.
1935 */
1936 if (!contiguous) {
1937 unsigned chunk_size = uniform - *chunk_start + 1;
1938
1939 /* Decide whether we should push or pull this parameter. In the
1940 * Vulkan driver, push constants are explicitly exposed via the API
1941 * so we push everything. In GL, we only push small arrays.
1942 */
1943 if (stage_prog_data->pull_param == NULL ||
1944 (*num_push_constants + chunk_size <= max_push_components &&
1945 chunk_size <= max_chunk_size)) {
1946 assert(*num_push_constants + chunk_size <= max_push_components);
1947 for (unsigned j = *chunk_start; j <= uniform; j++)
1948 push_constant_loc[j] = (*num_push_constants)++;
1949 } else {
1950 for (unsigned j = *chunk_start; j <= uniform; j++)
1951 pull_constant_loc[j] = (*num_pull_constants)++;
1952 }
1953
1954 *chunk_start = -1;
1955 }
1956 }
1957
1958 /**
1959 * Assign UNIFORM file registers to either push constants or pull constants.
1960 *
1961 * We allow a fragment shader to have more than the specified minimum
1962 * maximum number of fragment shader uniform components (64). If
1963 * there are too many of these, they'd fill up all of register space.
1964 * So, this will push some of them out to the pull constant buffer and
1965 * update the program to load them.
1966 */
1967 void
1968 fs_visitor::assign_constant_locations()
1969 {
1970 /* Only the first compile gets to decide on locations. */
1971 if (dispatch_width != min_dispatch_width)
1972 return;
1973
1974 bool is_live[uniforms];
1975 memset(is_live, 0, sizeof(is_live));
1976 bool is_live_64bit[uniforms];
1977 memset(is_live_64bit, 0, sizeof(is_live_64bit));
1978
1979 /* For each uniform slot, a value of true indicates that the given slot and
1980 * the next slot must remain contiguous. This is used to keep us from
1981 * splitting arrays apart.
1982 */
1983 bool contiguous[uniforms];
1984 memset(contiguous, 0, sizeof(contiguous));
1985
1986 int thread_local_id_index =
1987 (stage == MESA_SHADER_COMPUTE) ?
1988 ((brw_cs_prog_data*)stage_prog_data)->thread_local_id_index : -1;
1989
1990 /* First, we walk through the instructions and do two things:
1991 *
1992 * 1) Figure out which uniforms are live.
1993 *
1994 * 2) Mark any indirectly used ranges of registers as contiguous.
1995 *
1996 * Note that we don't move constant-indexed accesses to arrays. No
1997 * testing has been done of the performance impact of this choice.
1998 */
1999 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2000 for (int i = 0 ; i < inst->sources; i++) {
2001 if (inst->src[i].file != UNIFORM)
2002 continue;
2003
2004 int constant_nr = inst->src[i].nr + inst->src[i].reg_offset;
2005
2006 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0) {
2007 assert(inst->src[2].ud % 4 == 0);
2008 unsigned last = constant_nr + (inst->src[2].ud / 4) - 1;
2009 assert(last < uniforms);
2010
2011 for (unsigned j = constant_nr; j < last; j++) {
2012 is_live[j] = true;
2013 contiguous[j] = true;
2014 if (type_sz(inst->src[i].type) == 8) {
2015 is_live_64bit[j] = true;
2016 }
2017 }
2018 is_live[last] = true;
2019 } else {
2020 if (constant_nr >= 0 && constant_nr < (int) uniforms) {
2021 int regs_read = inst->components_read(i) *
2022 type_sz(inst->src[i].type) / 4;
2023 for (int j = 0; j < regs_read; j++) {
2024 is_live[constant_nr + j] = true;
2025 if (type_sz(inst->src[i].type) == 8) {
2026 is_live_64bit[constant_nr + j] = true;
2027 }
2028 }
2029 }
2030 }
2031 }
2032 }
2033
2034 if (thread_local_id_index >= 0 && !is_live[thread_local_id_index])
2035 thread_local_id_index = -1;
2036
2037 /* Only allow 16 registers (128 uniform components) as push constants.
2038 *
2039 * Just demote the end of the list. We could probably do better
2040 * here, demoting things that are rarely used in the program first.
2041 *
2042 * If changing this value, note the limitation about total_regs in
2043 * brw_curbe.c.
2044 */
2045 unsigned int max_push_components = 16 * 8;
2046 if (thread_local_id_index >= 0)
2047 max_push_components--; /* Save a slot for the thread ID */
2048
2049 /* We push small arrays, but no bigger than 16 floats. This is big enough
2050 * for a vec4 but hopefully not large enough to push out other stuff. We
2051 * should probably use a better heuristic at some point.
2052 */
2053 const unsigned int max_chunk_size = 16;
2054
2055 unsigned int num_push_constants = 0;
2056 unsigned int num_pull_constants = 0;
2057
2058 push_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2059 pull_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2060
2061 /* Default to -1 meaning no location */
2062 memset(push_constant_loc, -1, uniforms * sizeof(*push_constant_loc));
2063 memset(pull_constant_loc, -1, uniforms * sizeof(*pull_constant_loc));
2064
2065 int chunk_start = -1;
2066
2067 /* First push 64-bit uniforms to ensure they are properly aligned */
2068 for (unsigned u = 0; u < uniforms; u++) {
2069 if (!is_live[u] || !is_live_64bit[u])
2070 continue;
2071
2072 set_push_pull_constant_loc(u, &chunk_start, contiguous[u],
2073 push_constant_loc, pull_constant_loc,
2074 &num_push_constants, &num_pull_constants,
2075 max_push_components, max_chunk_size,
2076 stage_prog_data);
2077
2078 }
2079
2080 /* Then push the rest of uniforms */
2081 for (unsigned u = 0; u < uniforms; u++) {
2082 if (!is_live[u] || is_live_64bit[u])
2083 continue;
2084
2085 /* Skip thread_local_id_index to put it in the last push register. */
2086 if (thread_local_id_index == (int)u)
2087 continue;
2088
2089 set_push_pull_constant_loc(u, &chunk_start, contiguous[u],
2090 push_constant_loc, pull_constant_loc,
2091 &num_push_constants, &num_pull_constants,
2092 max_push_components, max_chunk_size,
2093 stage_prog_data);
2094 }
2095
2096 /* Add the CS local thread ID uniform at the end of the push constants */
2097 if (thread_local_id_index >= 0)
2098 push_constant_loc[thread_local_id_index] = num_push_constants++;
2099
2100 /* As the uniforms are going to be reordered, take the data from a temporary
2101 * copy of the original param[].
2102 */
2103 gl_constant_value **param = ralloc_array(NULL, gl_constant_value*,
2104 stage_prog_data->nr_params);
2105 memcpy(param, stage_prog_data->param,
2106 sizeof(gl_constant_value*) * stage_prog_data->nr_params);
2107 stage_prog_data->nr_params = num_push_constants;
2108 stage_prog_data->nr_pull_params = num_pull_constants;
2109
2110 /* Up until now, the param[] array has been indexed by reg + reg_offset
2111 * of UNIFORM registers. Move pull constants into pull_param[] and
2112 * condense param[] to only contain the uniforms we chose to push.
2113 *
2114 * NOTE: Because we are condensing the params[] array, we know that
2115 * push_constant_loc[i] <= i and we can do it in one smooth loop without
2116 * having to make a copy.
2117 */
2118 int new_thread_local_id_index = -1;
2119 for (unsigned int i = 0; i < uniforms; i++) {
2120 const gl_constant_value *value = param[i];
2121
2122 if (pull_constant_loc[i] != -1) {
2123 stage_prog_data->pull_param[pull_constant_loc[i]] = value;
2124 } else if (push_constant_loc[i] != -1) {
2125 stage_prog_data->param[push_constant_loc[i]] = value;
2126 if (thread_local_id_index == (int)i)
2127 new_thread_local_id_index = push_constant_loc[i];
2128 }
2129 }
2130 ralloc_free(param);
2131
2132 if (stage == MESA_SHADER_COMPUTE)
2133 ((brw_cs_prog_data*)stage_prog_data)->thread_local_id_index =
2134 new_thread_local_id_index;
2135 }
2136
2137 /**
2138 * Replace UNIFORM register file access with either UNIFORM_PULL_CONSTANT_LOAD
2139 * or VARYING_PULL_CONSTANT_LOAD instructions which load values into VGRFs.
2140 */
2141 void
2142 fs_visitor::lower_constant_loads()
2143 {
2144 const unsigned index = stage_prog_data->binding_table.pull_constants_start;
2145
2146 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2147 /* Set up the annotation tracking for new generated instructions. */
2148 const fs_builder ibld(this, block, inst);
2149
2150 for (int i = 0; i < inst->sources; i++) {
2151 if (inst->src[i].file != UNIFORM)
2152 continue;
2153
2154 /* We'll handle this case later */
2155 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0)
2156 continue;
2157
2158 unsigned location = inst->src[i].nr + inst->src[i].reg_offset;
2159 if (location >= uniforms)
2160 continue; /* Out of bounds access */
2161
2162 int pull_index = pull_constant_loc[location];
2163
2164 if (pull_index == -1)
2165 continue;
2166
2167 const unsigned index = stage_prog_data->binding_table.pull_constants_start;
2168 fs_reg dst;
2169
2170 if (type_sz(inst->src[i].type) <= 4)
2171 dst = vgrf(glsl_type::float_type);
2172 else
2173 dst = vgrf(glsl_type::double_type);
2174
2175 assert(inst->src[i].stride == 0);
2176
2177 const fs_builder ubld = ibld.exec_all().group(8, 0);
2178 struct brw_reg offset = brw_imm_ud((unsigned)(pull_index * 4) & ~15);
2179 ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
2180 dst, brw_imm_ud(index), offset);
2181
2182 /* Rewrite the instruction to use the temporary VGRF. */
2183 inst->src[i].file = VGRF;
2184 inst->src[i].nr = dst.nr;
2185 inst->src[i].reg_offset = 0;
2186 inst->src[i].set_smear((pull_index & 3) * 4 /
2187 type_sz(inst->src[i].type));
2188
2189 brw_mark_surface_used(prog_data, index);
2190 }
2191
2192 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
2193 inst->src[0].file == UNIFORM) {
2194
2195 unsigned location = inst->src[0].nr + inst->src[0].reg_offset;
2196 if (location >= uniforms)
2197 continue; /* Out of bounds access */
2198
2199 int pull_index = pull_constant_loc[location];
2200
2201 if (pull_index == -1)
2202 continue;
2203
2204 VARYING_PULL_CONSTANT_LOAD(ibld, inst->dst,
2205 brw_imm_ud(index),
2206 inst->src[1],
2207 pull_index * 4);
2208 inst->remove(block);
2209
2210 brw_mark_surface_used(prog_data, index);
2211 }
2212 }
2213 invalidate_live_intervals();
2214 }
2215
2216 bool
2217 fs_visitor::opt_algebraic()
2218 {
2219 bool progress = false;
2220
2221 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2222 switch (inst->opcode) {
2223 case BRW_OPCODE_MOV:
2224 if (inst->src[0].file != IMM)
2225 break;
2226
2227 if (inst->saturate) {
2228 if (inst->dst.type != inst->src[0].type)
2229 assert(!"unimplemented: saturate mixed types");
2230
2231 if (brw_saturate_immediate(inst->dst.type,
2232 &inst->src[0].as_brw_reg())) {
2233 inst->saturate = false;
2234 progress = true;
2235 }
2236 }
2237 break;
2238
2239 case BRW_OPCODE_MUL:
2240 if (inst->src[1].file != IMM)
2241 continue;
2242
2243 /* a * 1.0 = a */
2244 if (inst->src[1].is_one()) {
2245 inst->opcode = BRW_OPCODE_MOV;
2246 inst->src[1] = reg_undef;
2247 progress = true;
2248 break;
2249 }
2250
2251 /* a * -1.0 = -a */
2252 if (inst->src[1].is_negative_one()) {
2253 inst->opcode = BRW_OPCODE_MOV;
2254 inst->src[0].negate = !inst->src[0].negate;
2255 inst->src[1] = reg_undef;
2256 progress = true;
2257 break;
2258 }
2259
2260 /* a * 0.0 = 0.0 */
2261 if (inst->src[1].is_zero()) {
2262 inst->opcode = BRW_OPCODE_MOV;
2263 inst->src[0] = inst->src[1];
2264 inst->src[1] = reg_undef;
2265 progress = true;
2266 break;
2267 }
2268
2269 if (inst->src[0].file == IMM) {
2270 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2271 inst->opcode = BRW_OPCODE_MOV;
2272 inst->src[0].f *= inst->src[1].f;
2273 inst->src[1] = reg_undef;
2274 progress = true;
2275 break;
2276 }
2277 break;
2278 case BRW_OPCODE_ADD:
2279 if (inst->src[1].file != IMM)
2280 continue;
2281
2282 /* a + 0.0 = a */
2283 if (inst->src[1].is_zero()) {
2284 inst->opcode = BRW_OPCODE_MOV;
2285 inst->src[1] = reg_undef;
2286 progress = true;
2287 break;
2288 }
2289
2290 if (inst->src[0].file == IMM) {
2291 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2292 inst->opcode = BRW_OPCODE_MOV;
2293 inst->src[0].f += inst->src[1].f;
2294 inst->src[1] = reg_undef;
2295 progress = true;
2296 break;
2297 }
2298 break;
2299 case BRW_OPCODE_OR:
2300 if (inst->src[0].equals(inst->src[1])) {
2301 inst->opcode = BRW_OPCODE_MOV;
2302 inst->src[1] = reg_undef;
2303 progress = true;
2304 break;
2305 }
2306 break;
2307 case BRW_OPCODE_LRP:
2308 if (inst->src[1].equals(inst->src[2])) {
2309 inst->opcode = BRW_OPCODE_MOV;
2310 inst->src[0] = inst->src[1];
2311 inst->src[1] = reg_undef;
2312 inst->src[2] = reg_undef;
2313 progress = true;
2314 break;
2315 }
2316 break;
2317 case BRW_OPCODE_CMP:
2318 if (inst->conditional_mod == BRW_CONDITIONAL_GE &&
2319 inst->src[0].abs &&
2320 inst->src[0].negate &&
2321 inst->src[1].is_zero()) {
2322 inst->src[0].abs = false;
2323 inst->src[0].negate = false;
2324 inst->conditional_mod = BRW_CONDITIONAL_Z;
2325 progress = true;
2326 break;
2327 }
2328 break;
2329 case BRW_OPCODE_SEL:
2330 if (inst->src[0].equals(inst->src[1])) {
2331 inst->opcode = BRW_OPCODE_MOV;
2332 inst->src[1] = reg_undef;
2333 inst->predicate = BRW_PREDICATE_NONE;
2334 inst->predicate_inverse = false;
2335 progress = true;
2336 } else if (inst->saturate && inst->src[1].file == IMM) {
2337 switch (inst->conditional_mod) {
2338 case BRW_CONDITIONAL_LE:
2339 case BRW_CONDITIONAL_L:
2340 switch (inst->src[1].type) {
2341 case BRW_REGISTER_TYPE_F:
2342 if (inst->src[1].f >= 1.0f) {
2343 inst->opcode = BRW_OPCODE_MOV;
2344 inst->src[1] = reg_undef;
2345 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2346 progress = true;
2347 }
2348 break;
2349 default:
2350 break;
2351 }
2352 break;
2353 case BRW_CONDITIONAL_GE:
2354 case BRW_CONDITIONAL_G:
2355 switch (inst->src[1].type) {
2356 case BRW_REGISTER_TYPE_F:
2357 if (inst->src[1].f <= 0.0f) {
2358 inst->opcode = BRW_OPCODE_MOV;
2359 inst->src[1] = reg_undef;
2360 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2361 progress = true;
2362 }
2363 break;
2364 default:
2365 break;
2366 }
2367 default:
2368 break;
2369 }
2370 }
2371 break;
2372 case BRW_OPCODE_MAD:
2373 if (inst->src[1].is_zero() || inst->src[2].is_zero()) {
2374 inst->opcode = BRW_OPCODE_MOV;
2375 inst->src[1] = reg_undef;
2376 inst->src[2] = reg_undef;
2377 progress = true;
2378 } else if (inst->src[0].is_zero()) {
2379 inst->opcode = BRW_OPCODE_MUL;
2380 inst->src[0] = inst->src[2];
2381 inst->src[2] = reg_undef;
2382 progress = true;
2383 } else if (inst->src[1].is_one()) {
2384 inst->opcode = BRW_OPCODE_ADD;
2385 inst->src[1] = inst->src[2];
2386 inst->src[2] = reg_undef;
2387 progress = true;
2388 } else if (inst->src[2].is_one()) {
2389 inst->opcode = BRW_OPCODE_ADD;
2390 inst->src[2] = reg_undef;
2391 progress = true;
2392 } else if (inst->src[1].file == IMM && inst->src[2].file == IMM) {
2393 inst->opcode = BRW_OPCODE_ADD;
2394 inst->src[1].f *= inst->src[2].f;
2395 inst->src[2] = reg_undef;
2396 progress = true;
2397 }
2398 break;
2399 case SHADER_OPCODE_BROADCAST:
2400 if (is_uniform(inst->src[0])) {
2401 inst->opcode = BRW_OPCODE_MOV;
2402 inst->sources = 1;
2403 inst->force_writemask_all = true;
2404 progress = true;
2405 } else if (inst->src[1].file == IMM) {
2406 inst->opcode = BRW_OPCODE_MOV;
2407 inst->src[0] = component(inst->src[0],
2408 inst->src[1].ud);
2409 inst->sources = 1;
2410 inst->force_writemask_all = true;
2411 progress = true;
2412 }
2413 break;
2414
2415 default:
2416 break;
2417 }
2418
2419 /* Swap if src[0] is immediate. */
2420 if (progress && inst->is_commutative()) {
2421 if (inst->src[0].file == IMM) {
2422 fs_reg tmp = inst->src[1];
2423 inst->src[1] = inst->src[0];
2424 inst->src[0] = tmp;
2425 }
2426 }
2427 }
2428 return progress;
2429 }
2430
2431 /**
2432 * Optimize sample messages that have constant zero values for the trailing
2433 * texture coordinates. We can just reduce the message length for these
2434 * instructions instead of reserving a register for it. Trailing parameters
2435 * that aren't sent default to zero anyway. This will cause the dead code
2436 * eliminator to remove the MOV instruction that would otherwise be emitted to
2437 * set up the zero value.
2438 */
2439 bool
2440 fs_visitor::opt_zero_samples()
2441 {
2442 /* Gen4 infers the texturing opcode based on the message length so we can't
2443 * change it.
2444 */
2445 if (devinfo->gen < 5)
2446 return false;
2447
2448 bool progress = false;
2449
2450 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2451 if (!inst->is_tex())
2452 continue;
2453
2454 fs_inst *load_payload = (fs_inst *) inst->prev;
2455
2456 if (load_payload->is_head_sentinel() ||
2457 load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2458 continue;
2459
2460 /* We don't want to remove the message header or the first parameter.
2461 * Removing the first parameter is not allowed, see the Haswell PRM
2462 * volume 7, page 149:
2463 *
2464 * "Parameter 0 is required except for the sampleinfo message, which
2465 * has no parameter 0"
2466 */
2467 while (inst->mlen > inst->header_size + inst->exec_size / 8 &&
2468 load_payload->src[(inst->mlen - inst->header_size) /
2469 (inst->exec_size / 8) +
2470 inst->header_size - 1].is_zero()) {
2471 inst->mlen -= inst->exec_size / 8;
2472 progress = true;
2473 }
2474 }
2475
2476 if (progress)
2477 invalidate_live_intervals();
2478
2479 return progress;
2480 }
2481
2482 /**
2483 * Optimize sample messages which are followed by the final RT write.
2484 *
2485 * CHV, and GEN9+ can mark a texturing SEND instruction with EOT to have its
2486 * results sent directly to the framebuffer, bypassing the EU. Recognize the
2487 * final texturing results copied to the framebuffer write payload and modify
2488 * them to write to the framebuffer directly.
2489 */
2490 bool
2491 fs_visitor::opt_sampler_eot()
2492 {
2493 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
2494
2495 if (stage != MESA_SHADER_FRAGMENT)
2496 return false;
2497
2498 if (devinfo->gen < 9 && !devinfo->is_cherryview)
2499 return false;
2500
2501 /* FINISHME: It should be possible to implement this optimization when there
2502 * are multiple drawbuffers.
2503 */
2504 if (key->nr_color_regions != 1)
2505 return false;
2506
2507 /* Requires emitting a bunch of saturating MOV instructions during logical
2508 * send lowering to clamp the color payload, which the sampler unit isn't
2509 * going to do for us.
2510 */
2511 if (key->clamp_fragment_color)
2512 return false;
2513
2514 /* Look for a texturing instruction immediately before the final FB_WRITE. */
2515 bblock_t *block = cfg->blocks[cfg->num_blocks - 1];
2516 fs_inst *fb_write = (fs_inst *)block->end();
2517 assert(fb_write->eot);
2518 assert(fb_write->opcode == FS_OPCODE_FB_WRITE_LOGICAL);
2519
2520 /* There wasn't one; nothing to do. */
2521 if (unlikely(fb_write->prev->is_head_sentinel()))
2522 return false;
2523
2524 fs_inst *tex_inst = (fs_inst *) fb_write->prev;
2525
2526 /* 3D Sampler » Messages » Message Format
2527 *
2528 * “Response Length of zero is allowed on all SIMD8* and SIMD16* sampler
2529 * messages except sample+killpix, resinfo, sampleinfo, LOD, and gather4*”
2530 */
2531 if (tex_inst->opcode != SHADER_OPCODE_TEX_LOGICAL &&
2532 tex_inst->opcode != SHADER_OPCODE_TXD_LOGICAL &&
2533 tex_inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
2534 tex_inst->opcode != SHADER_OPCODE_TXL_LOGICAL &&
2535 tex_inst->opcode != FS_OPCODE_TXB_LOGICAL &&
2536 tex_inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL &&
2537 tex_inst->opcode != SHADER_OPCODE_TXF_CMS_W_LOGICAL &&
2538 tex_inst->opcode != SHADER_OPCODE_TXF_UMS_LOGICAL)
2539 return false;
2540
2541 /* XXX - This shouldn't be necessary. */
2542 if (tex_inst->prev->is_head_sentinel())
2543 return false;
2544
2545 /* Check that the FB write sources are fully initialized by the single
2546 * texturing instruction.
2547 */
2548 for (unsigned i = 0; i < FB_WRITE_LOGICAL_NUM_SRCS; i++) {
2549 if (i == FB_WRITE_LOGICAL_SRC_COLOR0) {
2550 if (!fb_write->src[i].equals(tex_inst->dst) ||
2551 fb_write->regs_read(i) != tex_inst->regs_written)
2552 return false;
2553 } else if (i != FB_WRITE_LOGICAL_SRC_COMPONENTS) {
2554 if (fb_write->src[i].file != BAD_FILE)
2555 return false;
2556 }
2557 }
2558
2559 assert(!tex_inst->eot); /* We can't get here twice */
2560 assert((tex_inst->offset & (0xff << 24)) == 0);
2561
2562 const fs_builder ibld(this, block, tex_inst);
2563
2564 tex_inst->offset |= fb_write->target << 24;
2565 tex_inst->eot = true;
2566 tex_inst->dst = ibld.null_reg_ud();
2567 tex_inst->regs_written = 0;
2568 fb_write->remove(cfg->blocks[cfg->num_blocks - 1]);
2569
2570 /* Marking EOT is sufficient, lower_logical_sends() will notice the EOT
2571 * flag and submit a header together with the sampler message as required
2572 * by the hardware.
2573 */
2574 invalidate_live_intervals();
2575 return true;
2576 }
2577
2578 bool
2579 fs_visitor::opt_register_renaming()
2580 {
2581 bool progress = false;
2582 int depth = 0;
2583
2584 int remap[alloc.count];
2585 memset(remap, -1, sizeof(int) * alloc.count);
2586
2587 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2588 if (inst->opcode == BRW_OPCODE_IF || inst->opcode == BRW_OPCODE_DO) {
2589 depth++;
2590 } else if (inst->opcode == BRW_OPCODE_ENDIF ||
2591 inst->opcode == BRW_OPCODE_WHILE) {
2592 depth--;
2593 }
2594
2595 /* Rewrite instruction sources. */
2596 for (int i = 0; i < inst->sources; i++) {
2597 if (inst->src[i].file == VGRF &&
2598 remap[inst->src[i].nr] != -1 &&
2599 remap[inst->src[i].nr] != inst->src[i].nr) {
2600 inst->src[i].nr = remap[inst->src[i].nr];
2601 progress = true;
2602 }
2603 }
2604
2605 const int dst = inst->dst.nr;
2606
2607 if (depth == 0 &&
2608 inst->dst.file == VGRF &&
2609 alloc.sizes[inst->dst.nr] == inst->regs_written &&
2610 !inst->is_partial_write()) {
2611 if (remap[dst] == -1) {
2612 remap[dst] = dst;
2613 } else {
2614 remap[dst] = alloc.allocate(inst->regs_written);
2615 inst->dst.nr = remap[dst];
2616 progress = true;
2617 }
2618 } else if (inst->dst.file == VGRF &&
2619 remap[dst] != -1 &&
2620 remap[dst] != dst) {
2621 inst->dst.nr = remap[dst];
2622 progress = true;
2623 }
2624 }
2625
2626 if (progress) {
2627 invalidate_live_intervals();
2628
2629 for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2630 if (delta_xy[i].file == VGRF && remap[delta_xy[i].nr] != -1) {
2631 delta_xy[i].nr = remap[delta_xy[i].nr];
2632 }
2633 }
2634 }
2635
2636 return progress;
2637 }
2638
2639 /**
2640 * Remove redundant or useless discard jumps.
2641 *
2642 * For example, we can eliminate jumps in the following sequence:
2643 *
2644 * discard-jump (redundant with the next jump)
2645 * discard-jump (useless; jumps to the next instruction)
2646 * placeholder-halt
2647 */
2648 bool
2649 fs_visitor::opt_redundant_discard_jumps()
2650 {
2651 bool progress = false;
2652
2653 bblock_t *last_bblock = cfg->blocks[cfg->num_blocks - 1];
2654
2655 fs_inst *placeholder_halt = NULL;
2656 foreach_inst_in_block_reverse(fs_inst, inst, last_bblock) {
2657 if (inst->opcode == FS_OPCODE_PLACEHOLDER_HALT) {
2658 placeholder_halt = inst;
2659 break;
2660 }
2661 }
2662
2663 if (!placeholder_halt)
2664 return false;
2665
2666 /* Delete any HALTs immediately before the placeholder halt. */
2667 for (fs_inst *prev = (fs_inst *) placeholder_halt->prev;
2668 !prev->is_head_sentinel() && prev->opcode == FS_OPCODE_DISCARD_JUMP;
2669 prev = (fs_inst *) placeholder_halt->prev) {
2670 prev->remove(last_bblock);
2671 progress = true;
2672 }
2673
2674 if (progress)
2675 invalidate_live_intervals();
2676
2677 return progress;
2678 }
2679
2680 /**
2681 * Compute a bitmask with GRF granularity with a bit set for each GRF starting
2682 * from \p r which overlaps the region starting at \p r and spanning \p n GRF
2683 * units.
2684 */
2685 static inline unsigned
2686 mask_relative_to(const fs_reg &r, const fs_reg &s, unsigned n)
2687 {
2688 const int rel_offset = (reg_offset(s) - reg_offset(r)) / REG_SIZE;
2689 assert(reg_space(r) == reg_space(s) &&
2690 rel_offset >= 0 && rel_offset < int(8 * sizeof(unsigned)));
2691 return ((1 << n) - 1) << rel_offset;
2692 }
2693
2694 bool
2695 fs_visitor::compute_to_mrf()
2696 {
2697 bool progress = false;
2698 int next_ip = 0;
2699
2700 /* No MRFs on Gen >= 7. */
2701 if (devinfo->gen >= 7)
2702 return false;
2703
2704 calculate_live_intervals();
2705
2706 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2707 int ip = next_ip;
2708 next_ip++;
2709
2710 if (inst->opcode != BRW_OPCODE_MOV ||
2711 inst->is_partial_write() ||
2712 inst->dst.file != MRF || inst->src[0].file != VGRF ||
2713 inst->dst.type != inst->src[0].type ||
2714 inst->src[0].abs || inst->src[0].negate ||
2715 !inst->src[0].is_contiguous() ||
2716 inst->src[0].subreg_offset)
2717 continue;
2718
2719 /* Can't compute-to-MRF this GRF if someone else was going to
2720 * read it later.
2721 */
2722 if (this->virtual_grf_end[inst->src[0].nr] > ip)
2723 continue;
2724
2725 /* Found a move of a GRF to a MRF. Let's see if we can go rewrite the
2726 * things that computed the value of all GRFs of the source region. The
2727 * regs_left bitset keeps track of the registers we haven't yet found a
2728 * generating instruction for.
2729 */
2730 unsigned regs_left = (1 << inst->regs_read(0)) - 1;
2731
2732 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
2733 if (regions_overlap(scan_inst->dst, scan_inst->regs_written * REG_SIZE,
2734 inst->src[0], inst->regs_read(0) * REG_SIZE)) {
2735 /* Found the last thing to write our reg we want to turn
2736 * into a compute-to-MRF.
2737 */
2738
2739 /* If this one instruction didn't populate all the
2740 * channels, bail. We might be able to rewrite everything
2741 * that writes that reg, but it would require smarter
2742 * tracking.
2743 */
2744 if (scan_inst->is_partial_write())
2745 break;
2746
2747 /* Handling things not fully contained in the source of the copy
2748 * would need us to understand coalescing out more than one MOV at
2749 * a time.
2750 */
2751 if (scan_inst->dst.reg_offset < inst->src[0].reg_offset ||
2752 scan_inst->dst.reg_offset + scan_inst->regs_written >
2753 inst->src[0].reg_offset + inst->regs_read(0))
2754 break;
2755
2756 /* SEND instructions can't have MRF as a destination. */
2757 if (scan_inst->mlen)
2758 break;
2759
2760 if (devinfo->gen == 6) {
2761 /* gen6 math instructions must have the destination be
2762 * GRF, so no compute-to-MRF for them.
2763 */
2764 if (scan_inst->is_math()) {
2765 break;
2766 }
2767 }
2768
2769 /* Clear the bits for any registers this instruction overwrites. */
2770 regs_left &= ~mask_relative_to(
2771 inst->src[0], scan_inst->dst, scan_inst->regs_written);
2772 if (!regs_left)
2773 break;
2774 }
2775
2776 /* We don't handle control flow here. Most computation of
2777 * values that end up in MRFs are shortly before the MRF
2778 * write anyway.
2779 */
2780 if (block->start() == scan_inst)
2781 break;
2782
2783 /* You can't read from an MRF, so if someone else reads our
2784 * MRF's source GRF that we wanted to rewrite, that stops us.
2785 */
2786 bool interfered = false;
2787 for (int i = 0; i < scan_inst->sources; i++) {
2788 if (regions_overlap(scan_inst->src[i], scan_inst->regs_read(i) * REG_SIZE,
2789 inst->src[0], inst->regs_read(0) * REG_SIZE)) {
2790 interfered = true;
2791 }
2792 }
2793 if (interfered)
2794 break;
2795
2796 if (regions_overlap(scan_inst->dst, scan_inst->regs_written * REG_SIZE,
2797 inst->dst, inst->regs_written * REG_SIZE)) {
2798 /* If somebody else writes our MRF here, we can't
2799 * compute-to-MRF before that.
2800 */
2801 break;
2802 }
2803
2804 if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1 &&
2805 regions_overlap(fs_reg(MRF, scan_inst->base_mrf), scan_inst->mlen * REG_SIZE,
2806 inst->dst, inst->regs_written * REG_SIZE)) {
2807 /* Found a SEND instruction, which means that there are
2808 * live values in MRFs from base_mrf to base_mrf +
2809 * scan_inst->mlen - 1. Don't go pushing our MRF write up
2810 * above it.
2811 */
2812 break;
2813 }
2814 }
2815
2816 if (regs_left)
2817 continue;
2818
2819 /* Found all generating instructions of our MRF's source value, so it
2820 * should be safe to rewrite them to point to the MRF directly.
2821 */
2822 regs_left = (1 << inst->regs_read(0)) - 1;
2823
2824 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
2825 if (regions_overlap(scan_inst->dst, scan_inst->regs_written * REG_SIZE,
2826 inst->src[0], inst->regs_read(0) * REG_SIZE)) {
2827 /* Clear the bits for any registers this instruction overwrites. */
2828 regs_left &= ~mask_relative_to(
2829 inst->src[0], scan_inst->dst, scan_inst->regs_written);
2830
2831 const unsigned rel_offset = (reg_offset(scan_inst->dst) -
2832 reg_offset(inst->src[0])) / REG_SIZE;
2833
2834 if (inst->dst.nr & BRW_MRF_COMPR4) {
2835 /* Apply the same address transformation done by the hardware
2836 * for COMPR4 MRF writes.
2837 */
2838 assert(rel_offset < 2);
2839 scan_inst->dst.nr = inst->dst.nr + rel_offset * 4;
2840
2841 /* Clear the COMPR4 bit if the generating instruction is not
2842 * compressed.
2843 */
2844 if (scan_inst->regs_written < 2)
2845 scan_inst->dst.nr &= ~BRW_MRF_COMPR4;
2846
2847 } else {
2848 /* Calculate the MRF number the result of this instruction is
2849 * ultimately written to.
2850 */
2851 scan_inst->dst.nr = inst->dst.nr + rel_offset;
2852 }
2853
2854 scan_inst->dst.file = MRF;
2855 scan_inst->dst.reg_offset = 0;
2856 scan_inst->saturate |= inst->saturate;
2857 if (!regs_left)
2858 break;
2859 }
2860 }
2861
2862 assert(!regs_left);
2863 inst->remove(block);
2864 progress = true;
2865 }
2866
2867 if (progress)
2868 invalidate_live_intervals();
2869
2870 return progress;
2871 }
2872
2873 /**
2874 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
2875 * flow. We could probably do better here with some form of divergence
2876 * analysis.
2877 */
2878 bool
2879 fs_visitor::eliminate_find_live_channel()
2880 {
2881 bool progress = false;
2882 unsigned depth = 0;
2883
2884 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2885 switch (inst->opcode) {
2886 case BRW_OPCODE_IF:
2887 case BRW_OPCODE_DO:
2888 depth++;
2889 break;
2890
2891 case BRW_OPCODE_ENDIF:
2892 case BRW_OPCODE_WHILE:
2893 depth--;
2894 break;
2895
2896 case FS_OPCODE_DISCARD_JUMP:
2897 /* This can potentially make control flow non-uniform until the end
2898 * of the program.
2899 */
2900 return progress;
2901
2902 case SHADER_OPCODE_FIND_LIVE_CHANNEL:
2903 if (depth == 0) {
2904 inst->opcode = BRW_OPCODE_MOV;
2905 inst->src[0] = brw_imm_ud(0u);
2906 inst->sources = 1;
2907 inst->force_writemask_all = true;
2908 progress = true;
2909 }
2910 break;
2911
2912 default:
2913 break;
2914 }
2915 }
2916
2917 return progress;
2918 }
2919
2920 /**
2921 * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
2922 * instructions to FS_OPCODE_REP_FB_WRITE.
2923 */
2924 void
2925 fs_visitor::emit_repclear_shader()
2926 {
2927 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
2928 int base_mrf = 0;
2929 int color_mrf = base_mrf + 2;
2930 fs_inst *mov;
2931
2932 if (uniforms > 0) {
2933 mov = bld.exec_all().group(4, 0)
2934 .MOV(brw_message_reg(color_mrf),
2935 fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
2936 } else {
2937 struct brw_reg reg =
2938 brw_reg(BRW_GENERAL_REGISTER_FILE, 2, 3, 0, 0, BRW_REGISTER_TYPE_F,
2939 BRW_VERTICAL_STRIDE_8, BRW_WIDTH_2, BRW_HORIZONTAL_STRIDE_4,
2940 BRW_SWIZZLE_XYZW, WRITEMASK_XYZW);
2941
2942 mov = bld.exec_all().group(4, 0)
2943 .MOV(vec4(brw_message_reg(color_mrf)), fs_reg(reg));
2944 }
2945
2946 fs_inst *write;
2947 if (key->nr_color_regions == 1) {
2948 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
2949 write->saturate = key->clamp_fragment_color;
2950 write->base_mrf = color_mrf;
2951 write->target = 0;
2952 write->header_size = 0;
2953 write->mlen = 1;
2954 } else {
2955 assume(key->nr_color_regions > 0);
2956 for (int i = 0; i < key->nr_color_regions; ++i) {
2957 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
2958 write->saturate = key->clamp_fragment_color;
2959 write->base_mrf = base_mrf;
2960 write->target = i;
2961 write->header_size = 2;
2962 write->mlen = 3;
2963 }
2964 }
2965 write->eot = true;
2966
2967 calculate_cfg();
2968
2969 assign_constant_locations();
2970 assign_curb_setup();
2971
2972 /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
2973 if (uniforms > 0) {
2974 assert(mov->src[0].file == FIXED_GRF);
2975 mov->src[0] = brw_vec4_grf(mov->src[0].nr, 0);
2976 }
2977 }
2978
2979 /**
2980 * Walks through basic blocks, looking for repeated MRF writes and
2981 * removing the later ones.
2982 */
2983 bool
2984 fs_visitor::remove_duplicate_mrf_writes()
2985 {
2986 fs_inst *last_mrf_move[BRW_MAX_MRF(devinfo->gen)];
2987 bool progress = false;
2988
2989 /* Need to update the MRF tracking for compressed instructions. */
2990 if (dispatch_width >= 16)
2991 return false;
2992
2993 memset(last_mrf_move, 0, sizeof(last_mrf_move));
2994
2995 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2996 if (inst->is_control_flow()) {
2997 memset(last_mrf_move, 0, sizeof(last_mrf_move));
2998 }
2999
3000 if (inst->opcode == BRW_OPCODE_MOV &&
3001 inst->dst.file == MRF) {
3002 fs_inst *prev_inst = last_mrf_move[inst->dst.nr];
3003 if (prev_inst && inst->equals(prev_inst)) {
3004 inst->remove(block);
3005 progress = true;
3006 continue;
3007 }
3008 }
3009
3010 /* Clear out the last-write records for MRFs that were overwritten. */
3011 if (inst->dst.file == MRF) {
3012 last_mrf_move[inst->dst.nr] = NULL;
3013 }
3014
3015 if (inst->mlen > 0 && inst->base_mrf != -1) {
3016 /* Found a SEND instruction, which will include two or fewer
3017 * implied MRF writes. We could do better here.
3018 */
3019 for (int i = 0; i < implied_mrf_writes(inst); i++) {
3020 last_mrf_move[inst->base_mrf + i] = NULL;
3021 }
3022 }
3023
3024 /* Clear out any MRF move records whose sources got overwritten. */
3025 for (unsigned i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
3026 if (last_mrf_move[i] &&
3027 regions_overlap(inst->dst, inst->regs_written * REG_SIZE,
3028 last_mrf_move[i]->src[0],
3029 last_mrf_move[i]->regs_read(0) * REG_SIZE)) {
3030 last_mrf_move[i] = NULL;
3031 }
3032 }
3033
3034 if (inst->opcode == BRW_OPCODE_MOV &&
3035 inst->dst.file == MRF &&
3036 inst->src[0].file != ARF &&
3037 !inst->is_partial_write()) {
3038 last_mrf_move[inst->dst.nr] = inst;
3039 }
3040 }
3041
3042 if (progress)
3043 invalidate_live_intervals();
3044
3045 return progress;
3046 }
3047
3048 static void
3049 clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
3050 {
3051 /* Clear the flag for registers that actually got read (as expected). */
3052 for (int i = 0; i < inst->sources; i++) {
3053 int grf;
3054 if (inst->src[i].file == VGRF || inst->src[i].file == FIXED_GRF) {
3055 grf = inst->src[i].nr;
3056 } else {
3057 continue;
3058 }
3059
3060 if (grf >= first_grf &&
3061 grf < first_grf + grf_len) {
3062 deps[grf - first_grf] = false;
3063 if (inst->exec_size == 16)
3064 deps[grf - first_grf + 1] = false;
3065 }
3066 }
3067 }
3068
3069 /**
3070 * Implements this workaround for the original 965:
3071 *
3072 * "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
3073 * check for post destination dependencies on this instruction, software
3074 * must ensure that there is no destination hazard for the case of ‘write
3075 * followed by a posted write’ shown in the following example.
3076 *
3077 * 1. mov r3 0
3078 * 2. send r3.xy <rest of send instruction>
3079 * 3. mov r2 r3
3080 *
3081 * Due to no post-destination dependency check on the ‘send’, the above
3082 * code sequence could have two instructions (1 and 2) in flight at the
3083 * same time that both consider ‘r3’ as the target of their final writes.
3084 */
3085 void
3086 fs_visitor::insert_gen4_pre_send_dependency_workarounds(bblock_t *block,
3087 fs_inst *inst)
3088 {
3089 int write_len = inst->regs_written;
3090 int first_write_grf = inst->dst.nr;
3091 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3092 assert(write_len < (int)sizeof(needs_dep) - 1);
3093
3094 memset(needs_dep, false, sizeof(needs_dep));
3095 memset(needs_dep, true, write_len);
3096
3097 clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
3098
3099 /* Walk backwards looking for writes to registers we're writing which
3100 * aren't read since being written. If we hit the start of the program,
3101 * we assume that there are no outstanding dependencies on entry to the
3102 * program.
3103 */
3104 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3105 /* If we hit control flow, assume that there *are* outstanding
3106 * dependencies, and force their cleanup before our instruction.
3107 */
3108 if (block->start() == scan_inst && block->num != 0) {
3109 for (int i = 0; i < write_len; i++) {
3110 if (needs_dep[i])
3111 DEP_RESOLVE_MOV(fs_builder(this, block, inst),
3112 first_write_grf + i);
3113 }
3114 return;
3115 }
3116
3117 /* We insert our reads as late as possible on the assumption that any
3118 * instruction but a MOV that might have left us an outstanding
3119 * dependency has more latency than a MOV.
3120 */
3121 if (scan_inst->dst.file == VGRF) {
3122 for (int i = 0; i < scan_inst->regs_written; i++) {
3123 int reg = scan_inst->dst.nr + i;
3124
3125 if (reg >= first_write_grf &&
3126 reg < first_write_grf + write_len &&
3127 needs_dep[reg - first_write_grf]) {
3128 DEP_RESOLVE_MOV(fs_builder(this, block, inst), reg);
3129 needs_dep[reg - first_write_grf] = false;
3130 if (scan_inst->exec_size == 16)
3131 needs_dep[reg - first_write_grf + 1] = false;
3132 }
3133 }
3134 }
3135
3136 /* Clear the flag for registers that actually got read (as expected). */
3137 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3138
3139 /* Continue the loop only if we haven't resolved all the dependencies */
3140 int i;
3141 for (i = 0; i < write_len; i++) {
3142 if (needs_dep[i])
3143 break;
3144 }
3145 if (i == write_len)
3146 return;
3147 }
3148 }
3149
3150 /**
3151 * Implements this workaround for the original 965:
3152 *
3153 * "[DevBW, DevCL] Errata: A destination register from a send can not be
3154 * used as a destination register until after it has been sourced by an
3155 * instruction with a different destination register.
3156 */
3157 void
3158 fs_visitor::insert_gen4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
3159 {
3160 int write_len = inst->regs_written;
3161 int first_write_grf = inst->dst.nr;
3162 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3163 assert(write_len < (int)sizeof(needs_dep) - 1);
3164
3165 memset(needs_dep, false, sizeof(needs_dep));
3166 memset(needs_dep, true, write_len);
3167 /* Walk forwards looking for writes to registers we're writing which aren't
3168 * read before being written.
3169 */
3170 foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst) {
3171 /* If we hit control flow, force resolve all remaining dependencies. */
3172 if (block->end() == scan_inst && block->num != cfg->num_blocks - 1) {
3173 for (int i = 0; i < write_len; i++) {
3174 if (needs_dep[i])
3175 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3176 first_write_grf + i);
3177 }
3178 return;
3179 }
3180
3181 /* Clear the flag for registers that actually got read (as expected). */
3182 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3183
3184 /* We insert our reads as late as possible since they're reading the
3185 * result of a SEND, which has massive latency.
3186 */
3187 if (scan_inst->dst.file == VGRF &&
3188 scan_inst->dst.nr >= first_write_grf &&
3189 scan_inst->dst.nr < first_write_grf + write_len &&
3190 needs_dep[scan_inst->dst.nr - first_write_grf]) {
3191 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3192 scan_inst->dst.nr);
3193 needs_dep[scan_inst->dst.nr - first_write_grf] = false;
3194 }
3195
3196 /* Continue the loop only if we haven't resolved all the dependencies */
3197 int i;
3198 for (i = 0; i < write_len; i++) {
3199 if (needs_dep[i])
3200 break;
3201 }
3202 if (i == write_len)
3203 return;
3204 }
3205 }
3206
3207 void
3208 fs_visitor::insert_gen4_send_dependency_workarounds()
3209 {
3210 if (devinfo->gen != 4 || devinfo->is_g4x)
3211 return;
3212
3213 bool progress = false;
3214
3215 /* Note that we're done with register allocation, so GRF fs_regs always
3216 * have a .reg_offset of 0.
3217 */
3218
3219 foreach_block_and_inst(block, fs_inst, inst, cfg) {
3220 if (inst->mlen != 0 && inst->dst.file == VGRF) {
3221 insert_gen4_pre_send_dependency_workarounds(block, inst);
3222 insert_gen4_post_send_dependency_workarounds(block, inst);
3223 progress = true;
3224 }
3225 }
3226
3227 if (progress)
3228 invalidate_live_intervals();
3229 }
3230
3231 /**
3232 * Turns the generic expression-style uniform pull constant load instruction
3233 * into a hardware-specific series of instructions for loading a pull
3234 * constant.
3235 *
3236 * The expression style allows the CSE pass before this to optimize out
3237 * repeated loads from the same offset, and gives the pre-register-allocation
3238 * scheduling full flexibility, while the conversion to native instructions
3239 * allows the post-register-allocation scheduler the best information
3240 * possible.
3241 *
3242 * Note that execution masking for setting up pull constant loads is special:
3243 * the channels that need to be written are unrelated to the current execution
3244 * mask, since a later instruction will use one of the result channels as a
3245 * source operand for all 8 or 16 of its channels.
3246 */
3247 void
3248 fs_visitor::lower_uniform_pull_constant_loads()
3249 {
3250 foreach_block_and_inst (block, fs_inst, inst, cfg) {
3251 if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
3252 continue;
3253
3254 if (devinfo->gen >= 7) {
3255 /* The offset arg is a vec4-aligned immediate byte offset. */
3256 fs_reg const_offset_reg = inst->src[1];
3257 assert(const_offset_reg.file == IMM &&
3258 const_offset_reg.type == BRW_REGISTER_TYPE_UD);
3259 assert(const_offset_reg.ud % 16 == 0);
3260
3261 fs_reg payload, offset;
3262 if (devinfo->gen >= 9) {
3263 /* We have to use a message header on Skylake to get SIMD4x2
3264 * mode. Reserve space for the register.
3265 */
3266 offset = payload = fs_reg(VGRF, alloc.allocate(2));
3267 offset.reg_offset++;
3268 inst->mlen = 2;
3269 } else {
3270 offset = payload = fs_reg(VGRF, alloc.allocate(1));
3271 inst->mlen = 1;
3272 }
3273
3274 /* This is actually going to be a MOV, but since only the first dword
3275 * is accessed, we have a special opcode to do just that one. Note
3276 * that this needs to be an operation that will be considered a def
3277 * by live variable analysis, or register allocation will explode.
3278 */
3279 fs_inst *setup = new(mem_ctx) fs_inst(FS_OPCODE_SET_SIMD4X2_OFFSET,
3280 8, offset, const_offset_reg);
3281 setup->force_writemask_all = true;
3282
3283 setup->ir = inst->ir;
3284 setup->annotation = inst->annotation;
3285 inst->insert_before(block, setup);
3286
3287 /* Similarly, this will only populate the first 4 channels of the
3288 * result register (since we only use smear values from 0-3), but we
3289 * don't tell the optimizer.
3290 */
3291 inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7;
3292 inst->src[1] = payload;
3293
3294 invalidate_live_intervals();
3295 } else {
3296 /* Before register allocation, we didn't tell the scheduler about the
3297 * MRF we use. We know it's safe to use this MRF because nothing
3298 * else does except for register spill/unspill, which generates and
3299 * uses its MRF within a single IR instruction.
3300 */
3301 inst->base_mrf = FIRST_PULL_LOAD_MRF(devinfo->gen) + 1;
3302 inst->mlen = 1;
3303 }
3304 }
3305 }
3306
3307 bool
3308 fs_visitor::lower_load_payload()
3309 {
3310 bool progress = false;
3311
3312 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3313 if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3314 continue;
3315
3316 assert(inst->dst.file == MRF || inst->dst.file == VGRF);
3317 assert(inst->saturate == false);
3318 fs_reg dst = inst->dst;
3319
3320 /* Get rid of COMPR4. We'll add it back in if we need it */
3321 if (dst.file == MRF)
3322 dst.nr = dst.nr & ~BRW_MRF_COMPR4;
3323
3324 const fs_builder ibld(this, block, inst);
3325 const fs_builder hbld = ibld.exec_all().group(8, 0);
3326
3327 for (uint8_t i = 0; i < inst->header_size; i++) {
3328 if (inst->src[i].file != BAD_FILE) {
3329 fs_reg mov_dst = retype(dst, BRW_REGISTER_TYPE_UD);
3330 fs_reg mov_src = retype(inst->src[i], BRW_REGISTER_TYPE_UD);
3331 hbld.MOV(mov_dst, mov_src);
3332 }
3333 dst = offset(dst, hbld, 1);
3334 }
3335
3336 if (inst->dst.file == MRF && (inst->dst.nr & BRW_MRF_COMPR4) &&
3337 inst->exec_size > 8) {
3338 /* In this case, the payload portion of the LOAD_PAYLOAD isn't
3339 * a straightforward copy. Instead, the result of the
3340 * LOAD_PAYLOAD is treated as interleaved and the first four
3341 * non-header sources are unpacked as:
3342 *
3343 * m + 0: r0
3344 * m + 1: g0
3345 * m + 2: b0
3346 * m + 3: a0
3347 * m + 4: r1
3348 * m + 5: g1
3349 * m + 6: b1
3350 * m + 7: a1
3351 *
3352 * This is used for gen <= 5 fb writes.
3353 */
3354 assert(inst->exec_size == 16);
3355 assert(inst->header_size + 4 <= inst->sources);
3356 for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
3357 if (inst->src[i].file != BAD_FILE) {
3358 if (devinfo->has_compr4) {
3359 fs_reg compr4_dst = retype(dst, inst->src[i].type);
3360 compr4_dst.nr |= BRW_MRF_COMPR4;
3361 ibld.MOV(compr4_dst, inst->src[i]);
3362 } else {
3363 /* Platform doesn't have COMPR4. We have to fake it */
3364 fs_reg mov_dst = retype(dst, inst->src[i].type);
3365 ibld.half(0).MOV(mov_dst, half(inst->src[i], 0));
3366 mov_dst.nr += 4;
3367 ibld.half(1).MOV(mov_dst, half(inst->src[i], 1));
3368 }
3369 }
3370
3371 dst.nr++;
3372 }
3373
3374 /* The loop above only ever incremented us through the first set
3375 * of 4 registers. However, thanks to the magic of COMPR4, we
3376 * actually wrote to the first 8 registers, so we need to take
3377 * that into account now.
3378 */
3379 dst.nr += 4;
3380
3381 /* The COMPR4 code took care of the first 4 sources. We'll let
3382 * the regular path handle any remaining sources. Yes, we are
3383 * modifying the instruction but we're about to delete it so
3384 * this really doesn't hurt anything.
3385 */
3386 inst->header_size += 4;
3387 }
3388
3389 for (uint8_t i = inst->header_size; i < inst->sources; i++) {
3390 if (inst->src[i].file != BAD_FILE)
3391 ibld.MOV(retype(dst, inst->src[i].type), inst->src[i]);
3392 dst = offset(dst, ibld, 1);
3393 }
3394
3395 inst->remove(block);
3396 progress = true;
3397 }
3398
3399 if (progress)
3400 invalidate_live_intervals();
3401
3402 return progress;
3403 }
3404
3405 bool
3406 fs_visitor::lower_integer_multiplication()
3407 {
3408 bool progress = false;
3409
3410 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3411 const fs_builder ibld(this, block, inst);
3412
3413 if (inst->opcode == BRW_OPCODE_MUL) {
3414 if (inst->dst.is_accumulator() ||
3415 (inst->dst.type != BRW_REGISTER_TYPE_D &&
3416 inst->dst.type != BRW_REGISTER_TYPE_UD))
3417 continue;
3418
3419 /* Gen8's MUL instruction can do a 32-bit x 32-bit -> 32-bit
3420 * operation directly, but CHV/BXT cannot.
3421 */
3422 if (devinfo->gen >= 8 &&
3423 !devinfo->is_cherryview && !devinfo->is_broxton)
3424 continue;
3425
3426 if (inst->src[1].file == IMM &&
3427 inst->src[1].ud < (1 << 16)) {
3428 /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3429 * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3430 * src1 are used.
3431 *
3432 * If multiplying by an immediate value that fits in 16-bits, do a
3433 * single MUL instruction with that value in the proper location.
3434 */
3435 if (devinfo->gen < 7) {
3436 fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8),
3437 inst->dst.type);
3438 ibld.MOV(imm, inst->src[1]);
3439 ibld.MUL(inst->dst, imm, inst->src[0]);
3440 } else {
3441 const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
3442 ibld.MUL(inst->dst, inst->src[0],
3443 ud ? brw_imm_uw(inst->src[1].ud)
3444 : brw_imm_w(inst->src[1].d));
3445 }
3446 } else {
3447 /* Gen < 8 (and some Gen8+ low-power parts like Cherryview) cannot
3448 * do 32-bit integer multiplication in one instruction, but instead
3449 * must do a sequence (which actually calculates a 64-bit result):
3450 *
3451 * mul(8) acc0<1>D g3<8,8,1>D g4<8,8,1>D
3452 * mach(8) null g3<8,8,1>D g4<8,8,1>D
3453 * mov(8) g2<1>D acc0<8,8,1>D
3454 *
3455 * But on Gen > 6, the ability to use second accumulator register
3456 * (acc1) for non-float data types was removed, preventing a simple
3457 * implementation in SIMD16. A 16-channel result can be calculated by
3458 * executing the three instructions twice in SIMD8, once with quarter
3459 * control of 1Q for the first eight channels and again with 2Q for
3460 * the second eight channels.
3461 *
3462 * Which accumulator register is implicitly accessed (by AccWrEnable
3463 * for instance) is determined by the quarter control. Unfortunately
3464 * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3465 * implicit accumulator access by an instruction with 2Q will access
3466 * acc1 regardless of whether the data type is usable in acc1.
3467 *
3468 * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3469 * integer data types.
3470 *
3471 * Since we only want the low 32-bits of the result, we can do two
3472 * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3473 * adjust the high result and add them (like the mach is doing):
3474 *
3475 * mul(8) g7<1>D g3<8,8,1>D g4.0<8,8,1>UW
3476 * mul(8) g8<1>D g3<8,8,1>D g4.1<8,8,1>UW
3477 * shl(8) g9<1>D g8<8,8,1>D 16D
3478 * add(8) g2<1>D g7<8,8,1>D g8<8,8,1>D
3479 *
3480 * We avoid the shl instruction by realizing that we only want to add
3481 * the low 16-bits of the "high" result to the high 16-bits of the
3482 * "low" result and using proper regioning on the add:
3483 *
3484 * mul(8) g7<1>D g3<8,8,1>D g4.0<16,8,2>UW
3485 * mul(8) g8<1>D g3<8,8,1>D g4.1<16,8,2>UW
3486 * add(8) g7.1<2>UW g7.1<16,8,2>UW g8<16,8,2>UW
3487 *
3488 * Since it does not use the (single) accumulator register, we can
3489 * schedule multi-component multiplications much better.
3490 */
3491
3492 fs_reg orig_dst = inst->dst;
3493 if (orig_dst.is_null() || orig_dst.file == MRF) {
3494 inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
3495 inst->dst.type);
3496 }
3497 fs_reg low = inst->dst;
3498 fs_reg high(VGRF, alloc.allocate(dispatch_width / 8),
3499 inst->dst.type);
3500
3501 if (devinfo->gen >= 7) {
3502 fs_reg src1_0_w = inst->src[1];
3503 fs_reg src1_1_w = inst->src[1];
3504
3505 if (inst->src[1].file == IMM) {
3506 src1_0_w.ud &= 0xffff;
3507 src1_1_w.ud >>= 16;
3508 } else {
3509 src1_0_w.type = BRW_REGISTER_TYPE_UW;
3510 if (src1_0_w.stride != 0) {
3511 assert(src1_0_w.stride == 1);
3512 src1_0_w.stride = 2;
3513 }
3514
3515 src1_1_w.type = BRW_REGISTER_TYPE_UW;
3516 if (src1_1_w.stride != 0) {
3517 assert(src1_1_w.stride == 1);
3518 src1_1_w.stride = 2;
3519 }
3520 src1_1_w.subreg_offset += type_sz(BRW_REGISTER_TYPE_UW);
3521 }
3522 ibld.MUL(low, inst->src[0], src1_0_w);
3523 ibld.MUL(high, inst->src[0], src1_1_w);
3524 } else {
3525 fs_reg src0_0_w = inst->src[0];
3526 fs_reg src0_1_w = inst->src[0];
3527
3528 src0_0_w.type = BRW_REGISTER_TYPE_UW;
3529 if (src0_0_w.stride != 0) {
3530 assert(src0_0_w.stride == 1);
3531 src0_0_w.stride = 2;
3532 }
3533
3534 src0_1_w.type = BRW_REGISTER_TYPE_UW;
3535 if (src0_1_w.stride != 0) {
3536 assert(src0_1_w.stride == 1);
3537 src0_1_w.stride = 2;
3538 }
3539 src0_1_w.subreg_offset += type_sz(BRW_REGISTER_TYPE_UW);
3540
3541 ibld.MUL(low, src0_0_w, inst->src[1]);
3542 ibld.MUL(high, src0_1_w, inst->src[1]);
3543 }
3544
3545 fs_reg dst = inst->dst;
3546 dst.type = BRW_REGISTER_TYPE_UW;
3547 dst.subreg_offset = 2;
3548 dst.stride = 2;
3549
3550 high.type = BRW_REGISTER_TYPE_UW;
3551 high.stride = 2;
3552
3553 low.type = BRW_REGISTER_TYPE_UW;
3554 low.subreg_offset = 2;
3555 low.stride = 2;
3556
3557 ibld.ADD(dst, low, high);
3558
3559 if (inst->conditional_mod || orig_dst.file == MRF) {
3560 set_condmod(inst->conditional_mod,
3561 ibld.MOV(orig_dst, inst->dst));
3562 }
3563 }
3564
3565 } else if (inst->opcode == SHADER_OPCODE_MULH) {
3566 /* Should have been lowered to 8-wide. */
3567 assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
3568 const fs_reg acc = retype(brw_acc_reg(inst->exec_size),
3569 inst->dst.type);
3570 fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
3571 fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
3572
3573 if (devinfo->gen >= 8) {
3574 /* Until Gen8, integer multiplies read 32-bits from one source,
3575 * and 16-bits from the other, and relying on the MACH instruction
3576 * to generate the high bits of the result.
3577 *
3578 * On Gen8, the multiply instruction does a full 32x32-bit
3579 * multiply, but in order to do a 64-bit multiply we can simulate
3580 * the previous behavior and then use a MACH instruction.
3581 *
3582 * FINISHME: Don't use source modifiers on src1.
3583 */
3584 assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
3585 mul->src[1].type == BRW_REGISTER_TYPE_UD);
3586 mul->src[1].type = BRW_REGISTER_TYPE_UW;
3587 mul->src[1].stride *= 2;
3588
3589 } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
3590 inst->group > 0) {
3591 /* Among other things the quarter control bits influence which
3592 * accumulator register is used by the hardware for instructions
3593 * that access the accumulator implicitly (e.g. MACH). A
3594 * second-half instruction would normally map to acc1, which
3595 * doesn't exist on Gen7 and up (the hardware does emulate it for
3596 * floating-point instructions *only* by taking advantage of the
3597 * extra precision of acc0 not normally used for floating point
3598 * arithmetic).
3599 *
3600 * HSW and up are careful enough not to try to access an
3601 * accumulator register that doesn't exist, but on earlier Gen7
3602 * hardware we need to make sure that the quarter control bits are
3603 * zero to avoid non-deterministic behaviour and emit an extra MOV
3604 * to get the result masked correctly according to the current
3605 * channel enables.
3606 */
3607 mach->group = 0;
3608 mach->force_writemask_all = true;
3609 mach->dst = ibld.vgrf(inst->dst.type);
3610 ibld.MOV(inst->dst, mach->dst);
3611 }
3612 } else {
3613 continue;
3614 }
3615
3616 inst->remove(block);
3617 progress = true;
3618 }
3619
3620 if (progress)
3621 invalidate_live_intervals();
3622
3623 return progress;
3624 }
3625
3626 bool
3627 fs_visitor::lower_minmax()
3628 {
3629 assert(devinfo->gen < 6);
3630
3631 bool progress = false;
3632
3633 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3634 const fs_builder ibld(this, block, inst);
3635
3636 if (inst->opcode == BRW_OPCODE_SEL &&
3637 inst->predicate == BRW_PREDICATE_NONE) {
3638 /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
3639 * the original SEL.L/GE instruction
3640 */
3641 ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
3642 inst->conditional_mod);
3643 inst->predicate = BRW_PREDICATE_NORMAL;
3644 inst->conditional_mod = BRW_CONDITIONAL_NONE;
3645
3646 progress = true;
3647 }
3648 }
3649
3650 if (progress)
3651 invalidate_live_intervals();
3652
3653 return progress;
3654 }
3655
3656 static void
3657 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
3658 fs_reg *dst, fs_reg color, unsigned components)
3659 {
3660 if (key->clamp_fragment_color) {
3661 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
3662 assert(color.type == BRW_REGISTER_TYPE_F);
3663
3664 for (unsigned i = 0; i < components; i++)
3665 set_saturate(true,
3666 bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
3667
3668 color = tmp;
3669 }
3670
3671 for (unsigned i = 0; i < components; i++)
3672 dst[i] = offset(color, bld, i);
3673 }
3674
3675 static void
3676 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
3677 const brw_wm_prog_data *prog_data,
3678 const brw_wm_prog_key *key,
3679 const fs_visitor::thread_payload &payload)
3680 {
3681 assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
3682 const brw_device_info *devinfo = bld.shader->devinfo;
3683 const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
3684 const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
3685 const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
3686 const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
3687 const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
3688 const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
3689 fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
3690 const unsigned components =
3691 inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
3692
3693 /* We can potentially have a message length of up to 15, so we have to set
3694 * base_mrf to either 0 or 1 in order to fit in m0..m15.
3695 */
3696 fs_reg sources[15];
3697 int header_size = 2, payload_header_size;
3698 unsigned length = 0;
3699
3700 /* From the Sandy Bridge PRM, volume 4, page 198:
3701 *
3702 * "Dispatched Pixel Enables. One bit per pixel indicating
3703 * which pixels were originally enabled when the thread was
3704 * dispatched. This field is only required for the end-of-
3705 * thread message and on all dual-source messages."
3706 */
3707 if (devinfo->gen >= 6 &&
3708 (devinfo->is_haswell || devinfo->gen >= 8 || !prog_data->uses_kill) &&
3709 color1.file == BAD_FILE &&
3710 key->nr_color_regions == 1) {
3711 header_size = 0;
3712 }
3713
3714 if (header_size != 0) {
3715 assert(header_size == 2);
3716 /* Allocate 2 registers for a header */
3717 length += 2;
3718 }
3719
3720 if (payload.aa_dest_stencil_reg) {
3721 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
3722 bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
3723 .MOV(sources[length],
3724 fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg, 0)));
3725 length++;
3726 }
3727
3728 if (sample_mask.file != BAD_FILE) {
3729 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
3730 BRW_REGISTER_TYPE_UD);
3731
3732 /* Hand over gl_SampleMask. Only the lower 16 bits of each channel are
3733 * relevant. Since it's unsigned single words one vgrf is always
3734 * 16-wide, but only the lower or higher 8 channels will be used by the
3735 * hardware when doing a SIMD8 write depending on whether we have
3736 * selected the subspans for the first or second half respectively.
3737 */
3738 assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
3739 sample_mask.type = BRW_REGISTER_TYPE_UW;
3740 sample_mask.stride *= 2;
3741
3742 bld.exec_all().annotate("FB write oMask")
3743 .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
3744 inst->group),
3745 sample_mask);
3746 length++;
3747 }
3748
3749 payload_header_size = length;
3750
3751 if (src0_alpha.file != BAD_FILE) {
3752 /* FIXME: This is being passed at the wrong location in the payload and
3753 * doesn't work when gl_SampleMask and MRTs are used simultaneously.
3754 * It's supposed to be immediately before oMask but there seems to be no
3755 * reasonable way to pass them in the correct order because LOAD_PAYLOAD
3756 * requires header sources to form a contiguous segment at the beginning
3757 * of the message and src0_alpha has per-channel semantics.
3758 */
3759 setup_color_payload(bld, key, &sources[length], src0_alpha, 1);
3760 length++;
3761 }
3762
3763 setup_color_payload(bld, key, &sources[length], color0, components);
3764 length += 4;
3765
3766 if (color1.file != BAD_FILE) {
3767 setup_color_payload(bld, key, &sources[length], color1, components);
3768 length += 4;
3769 }
3770
3771 if (src_depth.file != BAD_FILE) {
3772 sources[length] = src_depth;
3773 length++;
3774 }
3775
3776 if (dst_depth.file != BAD_FILE) {
3777 sources[length] = dst_depth;
3778 length++;
3779 }
3780
3781 if (src_stencil.file != BAD_FILE) {
3782 assert(devinfo->gen >= 9);
3783 assert(bld.dispatch_width() != 16);
3784
3785 /* XXX: src_stencil is only available on gen9+. dst_depth is never
3786 * available on gen9+. As such it's impossible to have both enabled at the
3787 * same time and therefore length cannot overrun the array.
3788 */
3789 assert(length < 15);
3790
3791 sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
3792 bld.exec_all().annotate("FB write OS")
3793 .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
3794 subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
3795 length++;
3796 }
3797
3798 fs_inst *load;
3799 if (devinfo->gen >= 7) {
3800 /* Send from the GRF */
3801 fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
3802 load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
3803 payload.nr = bld.shader->alloc.allocate(load->regs_written);
3804 load->dst = payload;
3805
3806 inst->src[0] = payload;
3807 inst->resize_sources(1);
3808 } else {
3809 /* Send from the MRF */
3810 load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
3811 sources, length, payload_header_size);
3812
3813 /* On pre-SNB, we have to interlace the color values. LOAD_PAYLOAD
3814 * will do this for us if we just give it a COMPR4 destination.
3815 */
3816 if (devinfo->gen < 6 && bld.dispatch_width() == 16)
3817 load->dst.nr |= BRW_MRF_COMPR4;
3818
3819 inst->resize_sources(0);
3820 inst->base_mrf = 1;
3821 }
3822
3823 inst->opcode = FS_OPCODE_FB_WRITE;
3824 inst->mlen = load->regs_written;
3825 inst->header_size = header_size;
3826 }
3827
3828 static void
3829 lower_sampler_logical_send_gen4(const fs_builder &bld, fs_inst *inst, opcode op,
3830 const fs_reg &coordinate,
3831 const fs_reg &shadow_c,
3832 const fs_reg &lod, const fs_reg &lod2,
3833 const fs_reg &surface,
3834 const fs_reg &sampler,
3835 unsigned coord_components,
3836 unsigned grad_components)
3837 {
3838 const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
3839 op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
3840 fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
3841 fs_reg msg_end = msg_begin;
3842
3843 /* g0 header. */
3844 msg_end = offset(msg_end, bld.group(8, 0), 1);
3845
3846 for (unsigned i = 0; i < coord_components; i++)
3847 bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
3848 offset(coordinate, bld, i));
3849
3850 msg_end = offset(msg_end, bld, coord_components);
3851
3852 /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
3853 * require all three components to be present and zero if they are unused.
3854 */
3855 if (coord_components > 0 &&
3856 (has_lod || shadow_c.file != BAD_FILE ||
3857 (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
3858 for (unsigned i = coord_components; i < 3; i++)
3859 bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
3860
3861 msg_end = offset(msg_end, bld, 3 - coord_components);
3862 }
3863
3864 if (op == SHADER_OPCODE_TXD) {
3865 /* TXD unsupported in SIMD16 mode. */
3866 assert(bld.dispatch_width() == 8);
3867
3868 /* the slots for u and v are always present, but r is optional */
3869 if (coord_components < 2)
3870 msg_end = offset(msg_end, bld, 2 - coord_components);
3871
3872 /* P = u, v, r
3873 * dPdx = dudx, dvdx, drdx
3874 * dPdy = dudy, dvdy, drdy
3875 *
3876 * 1-arg: Does not exist.
3877 *
3878 * 2-arg: dudx dvdx dudy dvdy
3879 * dPdx.x dPdx.y dPdy.x dPdy.y
3880 * m4 m5 m6 m7
3881 *
3882 * 3-arg: dudx dvdx drdx dudy dvdy drdy
3883 * dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
3884 * m5 m6 m7 m8 m9 m10
3885 */
3886 for (unsigned i = 0; i < grad_components; i++)
3887 bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
3888
3889 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
3890
3891 for (unsigned i = 0; i < grad_components; i++)
3892 bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
3893
3894 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
3895 }
3896
3897 if (has_lod) {
3898 /* Bias/LOD with shadow comparitor is unsupported in SIMD16 -- *Without*
3899 * shadow comparitor (including RESINFO) it's unsupported in SIMD8 mode.
3900 */
3901 assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
3902 bld.dispatch_width() == 16);
3903
3904 const brw_reg_type type =
3905 (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
3906 BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
3907 bld.MOV(retype(msg_end, type), lod);
3908 msg_end = offset(msg_end, bld, 1);
3909 }
3910
3911 if (shadow_c.file != BAD_FILE) {
3912 if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
3913 /* There's no plain shadow compare message, so we use shadow
3914 * compare with a bias of 0.0.
3915 */
3916 bld.MOV(msg_end, brw_imm_f(0.0f));
3917 msg_end = offset(msg_end, bld, 1);
3918 }
3919
3920 bld.MOV(msg_end, shadow_c);
3921 msg_end = offset(msg_end, bld, 1);
3922 }
3923
3924 inst->opcode = op;
3925 inst->src[0] = reg_undef;
3926 inst->src[1] = surface;
3927 inst->src[2] = sampler;
3928 inst->resize_sources(3);
3929 inst->base_mrf = msg_begin.nr;
3930 inst->mlen = msg_end.nr - msg_begin.nr;
3931 inst->header_size = 1;
3932 }
3933
3934 static void
3935 lower_sampler_logical_send_gen5(const fs_builder &bld, fs_inst *inst, opcode op,
3936 const fs_reg &coordinate,
3937 const fs_reg &shadow_c,
3938 const fs_reg &lod, const fs_reg &lod2,
3939 const fs_reg &sample_index,
3940 const fs_reg &surface,
3941 const fs_reg &sampler,
3942 const fs_reg &offset_value,
3943 unsigned coord_components,
3944 unsigned grad_components)
3945 {
3946 fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
3947 fs_reg msg_coords = message;
3948 unsigned header_size = 0;
3949
3950 if (offset_value.file != BAD_FILE) {
3951 /* The offsets set up by the visitor are in the m1 header, so we can't
3952 * go headerless.
3953 */
3954 header_size = 1;
3955 message.nr--;
3956 }
3957
3958 for (unsigned i = 0; i < coord_components; i++)
3959 bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
3960 offset(coordinate, bld, i));
3961
3962 fs_reg msg_end = offset(msg_coords, bld, coord_components);
3963 fs_reg msg_lod = offset(msg_coords, bld, 4);
3964
3965 if (shadow_c.file != BAD_FILE) {
3966 fs_reg msg_shadow = msg_lod;
3967 bld.MOV(msg_shadow, shadow_c);
3968 msg_lod = offset(msg_shadow, bld, 1);
3969 msg_end = msg_lod;
3970 }
3971
3972 switch (op) {
3973 case SHADER_OPCODE_TXL:
3974 case FS_OPCODE_TXB:
3975 bld.MOV(msg_lod, lod);
3976 msg_end = offset(msg_lod, bld, 1);
3977 break;
3978 case SHADER_OPCODE_TXD:
3979 /**
3980 * P = u, v, r
3981 * dPdx = dudx, dvdx, drdx
3982 * dPdy = dudy, dvdy, drdy
3983 *
3984 * Load up these values:
3985 * - dudx dudy dvdx dvdy drdx drdy
3986 * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
3987 */
3988 msg_end = msg_lod;
3989 for (unsigned i = 0; i < grad_components; i++) {
3990 bld.MOV(msg_end, offset(lod, bld, i));
3991 msg_end = offset(msg_end, bld, 1);
3992
3993 bld.MOV(msg_end, offset(lod2, bld, i));
3994 msg_end = offset(msg_end, bld, 1);
3995 }
3996 break;
3997 case SHADER_OPCODE_TXS:
3998 msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
3999 bld.MOV(msg_lod, lod);
4000 msg_end = offset(msg_lod, bld, 1);
4001 break;
4002 case SHADER_OPCODE_TXF:
4003 msg_lod = offset(msg_coords, bld, 3);
4004 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
4005 msg_end = offset(msg_lod, bld, 1);
4006 break;
4007 case SHADER_OPCODE_TXF_CMS:
4008 msg_lod = offset(msg_coords, bld, 3);
4009 /* lod */
4010 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
4011 /* sample index */
4012 bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
4013 msg_end = offset(msg_lod, bld, 2);
4014 break;
4015 default:
4016 break;
4017 }
4018
4019 inst->opcode = op;
4020 inst->src[0] = reg_undef;
4021 inst->src[1] = surface;
4022 inst->src[2] = sampler;
4023 inst->resize_sources(3);
4024 inst->base_mrf = message.nr;
4025 inst->mlen = msg_end.nr - message.nr;
4026 inst->header_size = header_size;
4027
4028 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4029 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4030 }
4031
4032 static bool
4033 is_high_sampler(const struct brw_device_info *devinfo, const fs_reg &sampler)
4034 {
4035 if (devinfo->gen < 8 && !devinfo->is_haswell)
4036 return false;
4037
4038 return sampler.file != IMM || sampler.ud >= 16;
4039 }
4040
4041 static void
4042 lower_sampler_logical_send_gen7(const fs_builder &bld, fs_inst *inst, opcode op,
4043 const fs_reg &coordinate,
4044 const fs_reg &shadow_c,
4045 fs_reg lod, const fs_reg &lod2,
4046 const fs_reg &sample_index,
4047 const fs_reg &mcs,
4048 const fs_reg &surface,
4049 const fs_reg &sampler,
4050 const fs_reg &offset_value,
4051 unsigned coord_components,
4052 unsigned grad_components)
4053 {
4054 const brw_device_info *devinfo = bld.shader->devinfo;
4055 int reg_width = bld.dispatch_width() / 8;
4056 unsigned header_size = 0, length = 0;
4057 fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
4058 for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
4059 sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
4060
4061 if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
4062 offset_value.file != BAD_FILE || inst->eot ||
4063 op == SHADER_OPCODE_SAMPLEINFO ||
4064 is_high_sampler(devinfo, sampler)) {
4065 /* For general texture offsets (no txf workaround), we need a header to
4066 * put them in. Note that we're only reserving space for it in the
4067 * message payload as it will be initialized implicitly by the
4068 * generator.
4069 *
4070 * TG4 needs to place its channel select in the header, for interaction
4071 * with ARB_texture_swizzle. The sampler index is only 4-bits, so for
4072 * larger sampler numbers we need to offset the Sampler State Pointer in
4073 * the header.
4074 */
4075 header_size = 1;
4076 sources[0] = fs_reg();
4077 length++;
4078
4079 /* If we're requesting fewer than four channels worth of response,
4080 * and we have an explicit header, we need to set up the sampler
4081 * writemask. It's reversed from normal: 1 means "don't write".
4082 */
4083 if (!inst->eot && inst->regs_written != 4 * reg_width) {
4084 assert((inst->regs_written % reg_width) == 0);
4085 unsigned mask = ~((1 << (inst->regs_written / reg_width)) - 1) & 0xf;
4086 inst->offset |= mask << 12;
4087 }
4088 }
4089
4090 if (shadow_c.file != BAD_FILE) {
4091 bld.MOV(sources[length], shadow_c);
4092 length++;
4093 }
4094
4095 bool coordinate_done = false;
4096
4097 /* Set up the LOD info */
4098 switch (op) {
4099 case FS_OPCODE_TXB:
4100 case SHADER_OPCODE_TXL:
4101 if (devinfo->gen >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
4102 op = SHADER_OPCODE_TXL_LZ;
4103 break;
4104 }
4105 bld.MOV(sources[length], lod);
4106 length++;
4107 break;
4108 case SHADER_OPCODE_TXD:
4109 /* TXD should have been lowered in SIMD16 mode. */
4110 assert(bld.dispatch_width() == 8);
4111
4112 /* Load dPdx and the coordinate together:
4113 * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
4114 */
4115 for (unsigned i = 0; i < coord_components; i++) {
4116 bld.MOV(sources[length++], offset(coordinate, bld, i));
4117
4118 /* For cube map array, the coordinate is (u,v,r,ai) but there are
4119 * only derivatives for (u, v, r).
4120 */
4121 if (i < grad_components) {
4122 bld.MOV(sources[length++], offset(lod, bld, i));
4123 bld.MOV(sources[length++], offset(lod2, bld, i));
4124 }
4125 }
4126
4127 coordinate_done = true;
4128 break;
4129 case SHADER_OPCODE_TXS:
4130 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
4131 length++;
4132 break;
4133 case SHADER_OPCODE_TXF:
4134 /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
4135 * On Gen9 they are u, v, lod, r
4136 */
4137 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
4138
4139 if (devinfo->gen >= 9) {
4140 if (coord_components >= 2) {
4141 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
4142 offset(coordinate, bld, 1));
4143 } else {
4144 sources[length] = brw_imm_d(0);
4145 }
4146 length++;
4147 }
4148
4149 if (devinfo->gen >= 9 && lod.is_zero()) {
4150 op = SHADER_OPCODE_TXF_LZ;
4151 } else {
4152 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
4153 length++;
4154 }
4155
4156 for (unsigned i = devinfo->gen >= 9 ? 2 : 1; i < coord_components; i++)
4157 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4158 offset(coordinate, bld, i));
4159
4160 coordinate_done = true;
4161 break;
4162
4163 case SHADER_OPCODE_TXF_CMS:
4164 case SHADER_OPCODE_TXF_CMS_W:
4165 case SHADER_OPCODE_TXF_UMS:
4166 case SHADER_OPCODE_TXF_MCS:
4167 if (op == SHADER_OPCODE_TXF_UMS ||
4168 op == SHADER_OPCODE_TXF_CMS ||
4169 op == SHADER_OPCODE_TXF_CMS_W) {
4170 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
4171 length++;
4172 }
4173
4174 if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
4175 /* Data from the multisample control surface. */
4176 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
4177 length++;
4178
4179 /* On Gen9+ we'll use ld2dms_w instead which has two registers for
4180 * the MCS data.
4181 */
4182 if (op == SHADER_OPCODE_TXF_CMS_W) {
4183 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
4184 mcs.file == IMM ?
4185 mcs :
4186 offset(mcs, bld, 1));
4187 length++;
4188 }
4189 }
4190
4191 /* There is no offsetting for this message; just copy in the integer
4192 * texture coordinates.
4193 */
4194 for (unsigned i = 0; i < coord_components; i++)
4195 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4196 offset(coordinate, bld, i));
4197
4198 coordinate_done = true;
4199 break;
4200 case SHADER_OPCODE_TG4_OFFSET:
4201 /* More crazy intermixing */
4202 for (unsigned i = 0; i < 2; i++) /* u, v */
4203 bld.MOV(sources[length++], offset(coordinate, bld, i));
4204
4205 for (unsigned i = 0; i < 2; i++) /* offu, offv */
4206 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4207 offset(offset_value, bld, i));
4208
4209 if (coord_components == 3) /* r if present */
4210 bld.MOV(sources[length++], offset(coordinate, bld, 2));
4211
4212 coordinate_done = true;
4213 break;
4214 default:
4215 break;
4216 }
4217
4218 /* Set up the coordinate (except for cases where it was done above) */
4219 if (!coordinate_done) {
4220 for (unsigned i = 0; i < coord_components; i++)
4221 bld.MOV(sources[length++], offset(coordinate, bld, i));
4222 }
4223
4224 int mlen;
4225 if (reg_width == 2)
4226 mlen = length * reg_width - header_size;
4227 else
4228 mlen = length * reg_width;
4229
4230 const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
4231 BRW_REGISTER_TYPE_F);
4232 bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
4233
4234 /* Generate the SEND. */
4235 inst->opcode = op;
4236 inst->src[0] = src_payload;
4237 inst->src[1] = surface;
4238 inst->src[2] = sampler;
4239 inst->resize_sources(3);
4240 inst->mlen = mlen;
4241 inst->header_size = header_size;
4242
4243 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4244 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4245 }
4246
4247 static void
4248 lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
4249 {
4250 const brw_device_info *devinfo = bld.shader->devinfo;
4251 const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
4252 const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
4253 const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
4254 const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
4255 const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
4256 const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
4257 const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
4258 const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
4259 const fs_reg &offset_value = inst->src[TEX_LOGICAL_SRC_OFFSET_VALUE];
4260 assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
4261 const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
4262 assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
4263 const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
4264
4265 if (devinfo->gen >= 7) {
4266 lower_sampler_logical_send_gen7(bld, inst, op, coordinate,
4267 shadow_c, lod, lod2, sample_index,
4268 mcs, surface, sampler, offset_value,
4269 coord_components, grad_components);
4270 } else if (devinfo->gen >= 5) {
4271 lower_sampler_logical_send_gen5(bld, inst, op, coordinate,
4272 shadow_c, lod, lod2, sample_index,
4273 surface, sampler, offset_value,
4274 coord_components, grad_components);
4275 } else {
4276 lower_sampler_logical_send_gen4(bld, inst, op, coordinate,
4277 shadow_c, lod, lod2,
4278 surface, sampler,
4279 coord_components, grad_components);
4280 }
4281 }
4282
4283 /**
4284 * Initialize the header present in some typed and untyped surface
4285 * messages.
4286 */
4287 static fs_reg
4288 emit_surface_header(const fs_builder &bld, const fs_reg &sample_mask)
4289 {
4290 fs_builder ubld = bld.exec_all().group(8, 0);
4291 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4292 ubld.MOV(dst, brw_imm_d(0));
4293 ubld.MOV(component(dst, 7), sample_mask);
4294 return dst;
4295 }
4296
4297 static void
4298 lower_surface_logical_send(const fs_builder &bld, fs_inst *inst, opcode op,
4299 const fs_reg &sample_mask)
4300 {
4301 /* Get the logical send arguments. */
4302 const fs_reg &addr = inst->src[0];
4303 const fs_reg &src = inst->src[1];
4304 const fs_reg &surface = inst->src[2];
4305 const UNUSED fs_reg &dims = inst->src[3];
4306 const fs_reg &arg = inst->src[4];
4307
4308 /* Calculate the total number of components of the payload. */
4309 const unsigned addr_sz = inst->components_read(0);
4310 const unsigned src_sz = inst->components_read(1);
4311 const unsigned header_sz = (sample_mask.file == BAD_FILE ? 0 : 1);
4312 const unsigned sz = header_sz + addr_sz + src_sz;
4313
4314 /* Allocate space for the payload. */
4315 fs_reg *const components = new fs_reg[sz];
4316 const fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
4317 unsigned n = 0;
4318
4319 /* Construct the payload. */
4320 if (header_sz)
4321 components[n++] = emit_surface_header(bld, sample_mask);
4322
4323 for (unsigned i = 0; i < addr_sz; i++)
4324 components[n++] = offset(addr, bld, i);
4325
4326 for (unsigned i = 0; i < src_sz; i++)
4327 components[n++] = offset(src, bld, i);
4328
4329 bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
4330
4331 /* Update the original instruction. */
4332 inst->opcode = op;
4333 inst->mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
4334 inst->header_size = header_sz;
4335
4336 inst->src[0] = payload;
4337 inst->src[1] = surface;
4338 inst->src[2] = arg;
4339 inst->resize_sources(3);
4340
4341 delete[] components;
4342 }
4343
4344 static void
4345 lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
4346 {
4347 const brw_device_info *devinfo = bld.shader->devinfo;
4348
4349 if (devinfo->gen >= 7) {
4350 /* We are switching the instruction from an ALU-like instruction to a
4351 * send-from-grf instruction. Since sends can't handle strides or
4352 * source modifiers, we have to make a copy of the offset source.
4353 */
4354 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD);
4355 bld.MOV(tmp, inst->src[1]);
4356 inst->src[1] = tmp;
4357
4358 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7;
4359
4360 } else {
4361 const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->gen),
4362 BRW_REGISTER_TYPE_UD);
4363
4364 bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
4365
4366 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4;
4367 inst->resize_sources(1);
4368 inst->base_mrf = payload.nr;
4369 inst->header_size = 1;
4370 inst->mlen = 1 + inst->exec_size / 8;
4371 }
4372 }
4373
4374 static void
4375 lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
4376 {
4377 assert(bld.shader->devinfo->gen < 6);
4378
4379 inst->base_mrf = 2;
4380 inst->mlen = inst->sources * inst->exec_size / 8;
4381
4382 if (inst->sources > 1) {
4383 /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
4384 * "Message Payload":
4385 *
4386 * "Operand0[7]. For the INT DIV functions, this operand is the
4387 * denominator."
4388 * ...
4389 * "Operand1[7]. For the INT DIV functions, this operand is the
4390 * numerator."
4391 */
4392 const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
4393 const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
4394 const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
4395
4396 inst->resize_sources(1);
4397 inst->src[0] = src0;
4398
4399 assert(inst->exec_size == 8);
4400 bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
4401 }
4402 }
4403
4404 bool
4405 fs_visitor::lower_logical_sends()
4406 {
4407 bool progress = false;
4408
4409 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4410 const fs_builder ibld(this, block, inst);
4411
4412 switch (inst->opcode) {
4413 case FS_OPCODE_FB_WRITE_LOGICAL:
4414 assert(stage == MESA_SHADER_FRAGMENT);
4415 lower_fb_write_logical_send(ibld, inst,
4416 (const brw_wm_prog_data *)prog_data,
4417 (const brw_wm_prog_key *)key,
4418 payload);
4419 break;
4420
4421 case SHADER_OPCODE_TEX_LOGICAL:
4422 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
4423 break;
4424
4425 case SHADER_OPCODE_TXD_LOGICAL:
4426 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
4427 break;
4428
4429 case SHADER_OPCODE_TXF_LOGICAL:
4430 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
4431 break;
4432
4433 case SHADER_OPCODE_TXL_LOGICAL:
4434 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
4435 break;
4436
4437 case SHADER_OPCODE_TXS_LOGICAL:
4438 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
4439 break;
4440
4441 case FS_OPCODE_TXB_LOGICAL:
4442 lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
4443 break;
4444
4445 case SHADER_OPCODE_TXF_CMS_LOGICAL:
4446 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
4447 break;
4448
4449 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
4450 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
4451 break;
4452
4453 case SHADER_OPCODE_TXF_UMS_LOGICAL:
4454 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
4455 break;
4456
4457 case SHADER_OPCODE_TXF_MCS_LOGICAL:
4458 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
4459 break;
4460
4461 case SHADER_OPCODE_LOD_LOGICAL:
4462 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
4463 break;
4464
4465 case SHADER_OPCODE_TG4_LOGICAL:
4466 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
4467 break;
4468
4469 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
4470 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
4471 break;
4472
4473 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
4474 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
4475 break;
4476
4477 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
4478 lower_surface_logical_send(ibld, inst,
4479 SHADER_OPCODE_UNTYPED_SURFACE_READ,
4480 fs_reg());
4481 break;
4482
4483 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
4484 lower_surface_logical_send(ibld, inst,
4485 SHADER_OPCODE_UNTYPED_SURFACE_WRITE,
4486 ibld.sample_mask_reg());
4487 break;
4488
4489 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
4490 lower_surface_logical_send(ibld, inst,
4491 SHADER_OPCODE_UNTYPED_ATOMIC,
4492 ibld.sample_mask_reg());
4493 break;
4494
4495 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
4496 lower_surface_logical_send(ibld, inst,
4497 SHADER_OPCODE_TYPED_SURFACE_READ,
4498 brw_imm_d(0xffff));
4499 break;
4500
4501 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
4502 lower_surface_logical_send(ibld, inst,
4503 SHADER_OPCODE_TYPED_SURFACE_WRITE,
4504 ibld.sample_mask_reg());
4505 break;
4506
4507 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
4508 lower_surface_logical_send(ibld, inst,
4509 SHADER_OPCODE_TYPED_ATOMIC,
4510 ibld.sample_mask_reg());
4511 break;
4512
4513 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
4514 lower_varying_pull_constant_logical_send(ibld, inst);
4515 break;
4516
4517 case SHADER_OPCODE_RCP:
4518 case SHADER_OPCODE_RSQ:
4519 case SHADER_OPCODE_SQRT:
4520 case SHADER_OPCODE_EXP2:
4521 case SHADER_OPCODE_LOG2:
4522 case SHADER_OPCODE_SIN:
4523 case SHADER_OPCODE_COS:
4524 case SHADER_OPCODE_POW:
4525 case SHADER_OPCODE_INT_QUOTIENT:
4526 case SHADER_OPCODE_INT_REMAINDER:
4527 /* The math opcodes are overloaded for the send-like and
4528 * expression-like instructions which seems kind of icky. Gen6+ has
4529 * a native (but rather quirky) MATH instruction so we don't need to
4530 * do anything here. On Gen4-5 we'll have to lower the Gen6-like
4531 * logical instructions (which we can easily recognize because they
4532 * have mlen = 0) into send-like virtual instructions.
4533 */
4534 if (devinfo->gen < 6 && inst->mlen == 0) {
4535 lower_math_logical_send(ibld, inst);
4536 break;
4537
4538 } else {
4539 continue;
4540 }
4541
4542 default:
4543 continue;
4544 }
4545
4546 progress = true;
4547 }
4548
4549 if (progress)
4550 invalidate_live_intervals();
4551
4552 return progress;
4553 }
4554
4555 /**
4556 * Get the closest allowed SIMD width for instruction \p inst accounting for
4557 * some common regioning and execution control restrictions that apply to FPU
4558 * instructions. These restrictions don't necessarily have any relevance to
4559 * instructions not executed by the FPU pipeline like extended math, control
4560 * flow or send message instructions.
4561 *
4562 * For virtual opcodes it's really up to the instruction -- In some cases
4563 * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
4564 * instructions) it may simplify virtual instruction lowering if we can
4565 * enforce FPU-like regioning restrictions already on the virtual instruction,
4566 * in other cases (e.g. virtual send-like instructions) this may be
4567 * excessively restrictive.
4568 */
4569 static unsigned
4570 get_fpu_lowered_simd_width(const struct brw_device_info *devinfo,
4571 const fs_inst *inst)
4572 {
4573 /* Maximum execution size representable in the instruction controls. */
4574 unsigned max_width = MIN2(32, inst->exec_size);
4575
4576 /* According to the PRMs:
4577 * "A. In Direct Addressing mode, a source cannot span more than 2
4578 * adjacent GRF registers.
4579 * B. A destination cannot span more than 2 adjacent GRF registers."
4580 *
4581 * Look for the source or destination with the largest register region
4582 * which is the one that is going to limit the overall execution size of
4583 * the instruction due to this rule.
4584 */
4585 unsigned reg_count = inst->regs_written;
4586
4587 for (unsigned i = 0; i < inst->sources; i++)
4588 reg_count = MAX2(reg_count, (unsigned)inst->regs_read(i));
4589
4590 /* Calculate the maximum execution size of the instruction based on the
4591 * factor by which it goes over the hardware limit of 2 GRFs.
4592 */
4593 if (reg_count > 2)
4594 max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
4595
4596 /* According to the IVB PRMs:
4597 * "When destination spans two registers, the source MUST span two
4598 * registers. The exception to the above rule:
4599 *
4600 * - When source is scalar, the source registers are not incremented.
4601 * - When source is packed integer Word and destination is packed
4602 * integer DWord, the source register is not incremented but the
4603 * source sub register is incremented."
4604 *
4605 * The hardware specs from Gen4 to Gen7.5 mention similar regioning
4606 * restrictions. The code below intentionally doesn't check whether the
4607 * destination type is integer because empirically the hardware doesn't
4608 * seem to care what the actual type is as long as it's dword-aligned.
4609 */
4610 if (devinfo->gen < 8) {
4611 for (unsigned i = 0; i < inst->sources; i++) {
4612 if (inst->regs_written == 2 &&
4613 inst->regs_read(i) != 0 && inst->regs_read(i) != 2 &&
4614 !is_uniform(inst->src[i]) &&
4615 !(type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
4616 type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1))
4617 max_width = MIN2(max_width, inst->exec_size /
4618 inst->regs_written);
4619 }
4620 }
4621
4622 /* From the IVB PRMs:
4623 * "When an instruction is SIMD32, the low 16 bits of the execution mask
4624 * are applied for both halves of the SIMD32 instruction. If different
4625 * execution mask channels are required, split the instruction into two
4626 * SIMD16 instructions."
4627 *
4628 * There is similar text in the HSW PRMs. Gen4-6 don't even implement
4629 * 32-wide control flow support in hardware and will behave similarly.
4630 */
4631 if (devinfo->gen < 8 && !inst->force_writemask_all)
4632 max_width = MIN2(max_width, 16);
4633
4634 /* From the IVB PRMs (applies to HSW too):
4635 * "Instructions with condition modifiers must not use SIMD32."
4636 *
4637 * From the BDW PRMs (applies to later hardware too):
4638 * "Ternary instruction with condition modifiers must not use SIMD32."
4639 */
4640 if (inst->conditional_mod && (devinfo->gen < 8 || inst->is_3src(devinfo)))
4641 max_width = MIN2(max_width, 16);
4642
4643 /* From the IVB PRMs (applies to other devices that don't have the
4644 * brw_device_info::supports_simd16_3src flag set):
4645 * "In Align16 access mode, SIMD16 is not allowed for DW operations and
4646 * SIMD8 is not allowed for DF operations."
4647 */
4648 if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
4649 max_width = MIN2(max_width, inst->exec_size / reg_count);
4650
4651 /* Pre-Gen8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
4652 * the 8-bit quarter of the execution mask signals specified in the
4653 * instruction control fields) for the second compressed half of any
4654 * single-precision instruction (for double-precision instructions
4655 * it's hardwired to use NibCtrl+1, at least on HSW), which means that
4656 * the EU will apply the wrong execution controls for the second
4657 * sequential GRF write if the number of channels per GRF is not exactly
4658 * eight in single-precision mode (or four in double-float mode).
4659 *
4660 * In this situation we calculate the maximum size of the split
4661 * instructions so they only ever write to a single register.
4662 */
4663 if (devinfo->gen < 8 && inst->regs_written > 1 &&
4664 !inst->force_writemask_all) {
4665 const unsigned channels_per_grf = inst->exec_size / inst->regs_written;
4666 unsigned exec_type_size = 0;
4667 for (int i = 0; i < inst->sources; i++) {
4668 if (inst->src[i].file != BAD_FILE)
4669 exec_type_size = MAX2(exec_type_size, type_sz(inst->src[i].type));
4670 }
4671 assert(exec_type_size);
4672
4673 /* The hardware shifts exactly 8 channels per compressed half of the
4674 * instruction in single-precision mode and exactly 4 in double-precision.
4675 */
4676 if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
4677 max_width = MIN2(max_width, channels_per_grf);
4678 }
4679
4680 /* Only power-of-two execution sizes are representable in the instruction
4681 * control fields.
4682 */
4683 return 1 << _mesa_logbase2(max_width);
4684 }
4685
4686 /**
4687 * Get the maximum allowed SIMD width for instruction \p inst accounting for
4688 * various payload size restrictions that apply to sampler message
4689 * instructions.
4690 *
4691 * This is only intended to provide a maximum theoretical bound for the
4692 * execution size of the message based on the number of argument components
4693 * alone, which in most cases will determine whether the SIMD8 or SIMD16
4694 * variant of the message can be used, though some messages may have
4695 * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
4696 * the message length to determine the exact SIMD width and argument count,
4697 * which makes a number of sampler message combinations impossible to
4698 * represent).
4699 */
4700 static unsigned
4701 get_sampler_lowered_simd_width(const struct brw_device_info *devinfo,
4702 const fs_inst *inst)
4703 {
4704 /* Calculate the number of coordinate components that have to be present
4705 * assuming that additional arguments follow the texel coordinates in the
4706 * message payload. On IVB+ there is no need for padding, on ILK-SNB we
4707 * need to pad to four or three components depending on the message,
4708 * pre-ILK we need to pad to at most three components.
4709 */
4710 const unsigned req_coord_components =
4711 (devinfo->gen >= 7 ||
4712 !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
4713 (devinfo->gen >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
4714 inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
4715 3;
4716
4717 /* On Gen9+ the LOD argument is for free if we're able to use the LZ
4718 * variant of the TXL or TXF message.
4719 */
4720 const bool implicit_lod = devinfo->gen >= 9 &&
4721 (inst->opcode == SHADER_OPCODE_TXL ||
4722 inst->opcode == SHADER_OPCODE_TXF) &&
4723 inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
4724
4725 /* Calculate the total number of argument components that need to be passed
4726 * to the sampler unit.
4727 */
4728 const unsigned num_payload_components =
4729 MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
4730 req_coord_components) +
4731 inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
4732 (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
4733 inst->components_read(TEX_LOGICAL_SRC_LOD2) +
4734 inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
4735 (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
4736 inst->components_read(TEX_LOGICAL_SRC_OFFSET_VALUE) : 0) +
4737 inst->components_read(TEX_LOGICAL_SRC_MCS);
4738
4739 /* SIMD16 messages with more than five arguments exceed the maximum message
4740 * size supported by the sampler, regardless of whether a header is
4741 * provided or not.
4742 */
4743 return MIN2(inst->exec_size,
4744 num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
4745 }
4746
4747 /**
4748 * Get the closest native SIMD width supported by the hardware for instruction
4749 * \p inst. The instruction will be left untouched by
4750 * fs_visitor::lower_simd_width() if the returned value is equal to the
4751 * original execution size.
4752 */
4753 static unsigned
4754 get_lowered_simd_width(const struct brw_device_info *devinfo,
4755 const fs_inst *inst)
4756 {
4757 switch (inst->opcode) {
4758 case BRW_OPCODE_MOV:
4759 case BRW_OPCODE_SEL:
4760 case BRW_OPCODE_NOT:
4761 case BRW_OPCODE_AND:
4762 case BRW_OPCODE_OR:
4763 case BRW_OPCODE_XOR:
4764 case BRW_OPCODE_SHR:
4765 case BRW_OPCODE_SHL:
4766 case BRW_OPCODE_ASR:
4767 case BRW_OPCODE_CMPN:
4768 case BRW_OPCODE_CSEL:
4769 case BRW_OPCODE_F32TO16:
4770 case BRW_OPCODE_F16TO32:
4771 case BRW_OPCODE_BFREV:
4772 case BRW_OPCODE_BFE:
4773 case BRW_OPCODE_ADD:
4774 case BRW_OPCODE_MUL:
4775 case BRW_OPCODE_AVG:
4776 case BRW_OPCODE_FRC:
4777 case BRW_OPCODE_RNDU:
4778 case BRW_OPCODE_RNDD:
4779 case BRW_OPCODE_RNDE:
4780 case BRW_OPCODE_RNDZ:
4781 case BRW_OPCODE_LZD:
4782 case BRW_OPCODE_FBH:
4783 case BRW_OPCODE_FBL:
4784 case BRW_OPCODE_CBIT:
4785 case BRW_OPCODE_SAD2:
4786 case BRW_OPCODE_MAD:
4787 case BRW_OPCODE_LRP:
4788 case FS_OPCODE_PACK:
4789 return get_fpu_lowered_simd_width(devinfo, inst);
4790
4791 case BRW_OPCODE_CMP: {
4792 /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
4793 * when the destination is a GRF the dependency-clear bit on the flag
4794 * register is cleared early.
4795 *
4796 * Suggested workarounds are to disable coissuing CMP instructions
4797 * or to split CMP(16) instructions into two CMP(8) instructions.
4798 *
4799 * We choose to split into CMP(8) instructions since disabling
4800 * coissuing would affect CMP instructions not otherwise affected by
4801 * the errata.
4802 */
4803 const unsigned max_width = (devinfo->gen == 7 && !devinfo->is_haswell &&
4804 !inst->dst.is_null() ? 8 : ~0);
4805 return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
4806 }
4807 case BRW_OPCODE_BFI1:
4808 case BRW_OPCODE_BFI2:
4809 /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
4810 * should
4811 * "Force BFI instructions to be executed always in SIMD8."
4812 */
4813 return MIN2(devinfo->is_haswell ? 8 : ~0u,
4814 get_fpu_lowered_simd_width(devinfo, inst));
4815
4816 case BRW_OPCODE_IF:
4817 assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
4818 return inst->exec_size;
4819
4820 case SHADER_OPCODE_RCP:
4821 case SHADER_OPCODE_RSQ:
4822 case SHADER_OPCODE_SQRT:
4823 case SHADER_OPCODE_EXP2:
4824 case SHADER_OPCODE_LOG2:
4825 case SHADER_OPCODE_SIN:
4826 case SHADER_OPCODE_COS:
4827 /* Unary extended math instructions are limited to SIMD8 on Gen4 and
4828 * Gen6.
4829 */
4830 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
4831 devinfo->gen == 5 || devinfo->is_g4x ? MIN2(16, inst->exec_size) :
4832 MIN2(8, inst->exec_size));
4833
4834 case SHADER_OPCODE_POW:
4835 /* SIMD16 is only allowed on Gen7+. */
4836 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
4837 MIN2(8, inst->exec_size));
4838
4839 case SHADER_OPCODE_INT_QUOTIENT:
4840 case SHADER_OPCODE_INT_REMAINDER:
4841 /* Integer division is limited to SIMD8 on all generations. */
4842 return MIN2(8, inst->exec_size);
4843
4844 case FS_OPCODE_LINTERP:
4845 case FS_OPCODE_GET_BUFFER_SIZE:
4846 case FS_OPCODE_DDX_COARSE:
4847 case FS_OPCODE_DDX_FINE:
4848 case FS_OPCODE_DDY_COARSE:
4849 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
4850 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7:
4851 case FS_OPCODE_PACK_HALF_2x16_SPLIT:
4852 case FS_OPCODE_UNPACK_HALF_2x16_SPLIT_X:
4853 case FS_OPCODE_UNPACK_HALF_2x16_SPLIT_Y:
4854 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
4855 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
4856 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
4857 return MIN2(16, inst->exec_size);
4858
4859 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
4860 /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
4861 * message used to implement varying pull constant loads, so expand it
4862 * to SIMD16. An alternative with longer message payload length but
4863 * shorter return payload would be to use the SIMD8 sampler message that
4864 * takes (header, u, v, r) as parameters instead of (header, u).
4865 */
4866 return (devinfo->gen == 4 ? 16 : MIN2(16, inst->exec_size));
4867
4868 case FS_OPCODE_DDY_FINE:
4869 /* The implementation of this virtual opcode may require emitting
4870 * compressed Align16 instructions, which are severely limited on some
4871 * generations.
4872 *
4873 * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
4874 * Region Restrictions):
4875 *
4876 * "In Align16 access mode, SIMD16 is not allowed for DW operations
4877 * and SIMD8 is not allowed for DF operations."
4878 *
4879 * In this context, "DW operations" means "operations acting on 32-bit
4880 * values", so it includes operations on floats.
4881 *
4882 * Gen4 has a similar restriction. From the i965 PRM, section 11.5.3
4883 * (Instruction Compression -> Rules and Restrictions):
4884 *
4885 * "A compressed instruction must be in Align1 access mode. Align16
4886 * mode instructions cannot be compressed."
4887 *
4888 * Similar text exists in the g45 PRM.
4889 *
4890 * Empirically, compressed align16 instructions using odd register
4891 * numbers don't appear to work on Sandybridge either.
4892 */
4893 return (devinfo->gen == 4 || devinfo->gen == 6 ||
4894 (devinfo->gen == 7 && !devinfo->is_haswell) ?
4895 MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
4896
4897 case SHADER_OPCODE_MULH:
4898 /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
4899 * is 8-wide on Gen7+.
4900 */
4901 return (devinfo->gen >= 7 ? 8 :
4902 get_fpu_lowered_simd_width(devinfo, inst));
4903
4904 case FS_OPCODE_FB_WRITE_LOGICAL:
4905 /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
4906 * here.
4907 */
4908 assert(devinfo->gen != 6 ||
4909 inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
4910 inst->exec_size == 8);
4911 /* Dual-source FB writes are unsupported in SIMD16 mode. */
4912 return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
4913 8 : MIN2(16, inst->exec_size));
4914
4915 case SHADER_OPCODE_TEX_LOGICAL:
4916 case SHADER_OPCODE_TXF_CMS_LOGICAL:
4917 case SHADER_OPCODE_TXF_UMS_LOGICAL:
4918 case SHADER_OPCODE_TXF_MCS_LOGICAL:
4919 case SHADER_OPCODE_LOD_LOGICAL:
4920 case SHADER_OPCODE_TG4_LOGICAL:
4921 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
4922 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
4923 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
4924 return get_sampler_lowered_simd_width(devinfo, inst);
4925
4926 case SHADER_OPCODE_TXD_LOGICAL:
4927 /* TXD is unsupported in SIMD16 mode. */
4928 return 8;
4929
4930 case SHADER_OPCODE_TXL_LOGICAL:
4931 case FS_OPCODE_TXB_LOGICAL:
4932 /* Only one execution size is representable pre-ILK depending on whether
4933 * the shadow reference argument is present.
4934 */
4935 if (devinfo->gen == 4)
4936 return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
4937 else
4938 return get_sampler_lowered_simd_width(devinfo, inst);
4939
4940 case SHADER_OPCODE_TXF_LOGICAL:
4941 case SHADER_OPCODE_TXS_LOGICAL:
4942 /* Gen4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
4943 * messages. Use SIMD16 instead.
4944 */
4945 if (devinfo->gen == 4)
4946 return 16;
4947 else
4948 return get_sampler_lowered_simd_width(devinfo, inst);
4949
4950 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
4951 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
4952 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
4953 return 8;
4954
4955 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
4956 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
4957 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
4958 return MIN2(16, inst->exec_size);
4959
4960 case SHADER_OPCODE_URB_READ_SIMD8:
4961 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
4962 case SHADER_OPCODE_URB_WRITE_SIMD8:
4963 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
4964 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
4965 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
4966 return MIN2(8, inst->exec_size);
4967
4968 case SHADER_OPCODE_MOV_INDIRECT:
4969 /* Prior to Broadwell, we only have 8 address subregisters */
4970 return MIN3(devinfo->gen >= 8 ? 16 : 8,
4971 2 * REG_SIZE / (inst->dst.stride * type_sz(inst->dst.type)),
4972 inst->exec_size);
4973
4974 case SHADER_OPCODE_LOAD_PAYLOAD: {
4975 const unsigned reg_count =
4976 DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
4977
4978 if (reg_count > 2) {
4979 /* Only LOAD_PAYLOAD instructions with per-channel destination region
4980 * can be easily lowered (which excludes headers and heterogeneous
4981 * types).
4982 */
4983 assert(!inst->header_size);
4984 for (unsigned i = 0; i < inst->sources; i++)
4985 assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
4986 inst->src[i].file == BAD_FILE);
4987
4988 return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
4989 } else {
4990 return inst->exec_size;
4991 }
4992 }
4993 default:
4994 return inst->exec_size;
4995 }
4996 }
4997
4998 /**
4999 * Return true if splitting out the group of channels of instruction \p inst
5000 * given by lbld.group() requires allocating a temporary for the i-th source
5001 * of the lowered instruction.
5002 */
5003 static inline bool
5004 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
5005 {
5006 return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
5007 (inst->components_read(i) == 1 &&
5008 lbld.dispatch_width() <= inst->exec_size));
5009 }
5010
5011 /**
5012 * Extract the data that would be consumed by the channel group given by
5013 * lbld.group() from the i-th source region of instruction \p inst and return
5014 * it as result in packed form. If any copy instructions are required they
5015 * will be emitted before the given \p inst in \p block.
5016 */
5017 static fs_reg
5018 emit_unzip(const fs_builder &lbld, bblock_t *block, fs_inst *inst,
5019 unsigned i)
5020 {
5021 /* Specified channel group from the source region. */
5022 const fs_reg src = horiz_offset(inst->src[i], lbld.group());
5023
5024 if (needs_src_copy(lbld, inst, i)) {
5025 /* Builder of the right width to perform the copy avoiding uninitialized
5026 * data if the lowered execution size is greater than the original
5027 * execution size of the instruction.
5028 */
5029 const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
5030 inst->exec_size), 0);
5031 const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
5032
5033 for (unsigned k = 0; k < inst->components_read(i); ++k)
5034 cbld.at(block, inst)
5035 .MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
5036
5037 return tmp;
5038
5039 } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
5040 /* The source is invariant for all dispatch_width-wide groups of the
5041 * original region.
5042 */
5043 return inst->src[i];
5044
5045 } else {
5046 /* We can just point the lowered instruction at the right channel group
5047 * from the original region.
5048 */
5049 return src;
5050 }
5051 }
5052
5053 /**
5054 * Return true if splitting out the group of channels of instruction \p inst
5055 * given by lbld.group() requires allocating a temporary for the destination
5056 * of the lowered instruction and copying the data back to the original
5057 * destination region.
5058 */
5059 static inline bool
5060 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
5061 {
5062 /* If the instruction writes more than one component we'll have to shuffle
5063 * the results of multiple lowered instructions in order to make sure that
5064 * they end up arranged correctly in the original destination region.
5065 */
5066 if (inst->regs_written * REG_SIZE >
5067 inst->dst.component_size(inst->exec_size))
5068 return true;
5069
5070 /* If the lowered execution size is larger than the original the result of
5071 * the instruction won't fit in the original destination, so we'll have to
5072 * allocate a temporary in any case.
5073 */
5074 if (lbld.dispatch_width() > inst->exec_size)
5075 return true;
5076
5077 for (unsigned i = 0; i < inst->sources; i++) {
5078 /* If we already made a copy of the source for other reasons there won't
5079 * be any overlap with the destination.
5080 */
5081 if (needs_src_copy(lbld, inst, i))
5082 continue;
5083
5084 /* In order to keep the logic simple we emit a copy whenever the
5085 * destination region doesn't exactly match an overlapping source, which
5086 * may point at the source and destination not being aligned group by
5087 * group which could cause one of the lowered instructions to overwrite
5088 * the data read from the same source by other lowered instructions.
5089 */
5090 if (regions_overlap(inst->dst, inst->regs_written * REG_SIZE,
5091 inst->src[i], inst->regs_read(i) * REG_SIZE) &&
5092 !inst->dst.equals(inst->src[i]))
5093 return true;
5094 }
5095
5096 return false;
5097 }
5098
5099 /**
5100 * Insert data from a packed temporary into the channel group given by
5101 * lbld.group() of the destination region of instruction \p inst and return
5102 * the temporary as result. If any copy instructions are required they will
5103 * be emitted around the given \p inst in \p block.
5104 */
5105 static fs_reg
5106 emit_zip(const fs_builder &lbld, bblock_t *block, fs_inst *inst)
5107 {
5108 /* Builder of the right width to perform the copy avoiding uninitialized
5109 * data if the lowered execution size is greater than the original
5110 * execution size of the instruction.
5111 */
5112 const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
5113 inst->exec_size), 0);
5114
5115 /* Specified channel group from the destination region. */
5116 const fs_reg dst = horiz_offset(inst->dst, lbld.group());
5117 const unsigned dst_size = inst->regs_written * REG_SIZE /
5118 inst->dst.component_size(inst->exec_size);
5119
5120 if (needs_dst_copy(lbld, inst)) {
5121 const fs_reg tmp = lbld.vgrf(inst->dst.type, dst_size);
5122
5123 if (inst->predicate) {
5124 /* Handle predication by copying the original contents of
5125 * the destination into the temporary before emitting the
5126 * lowered instruction.
5127 */
5128 for (unsigned k = 0; k < dst_size; ++k)
5129 cbld.at(block, inst)
5130 .MOV(offset(tmp, lbld, k), offset(dst, inst->exec_size, k));
5131 }
5132
5133 for (unsigned k = 0; k < dst_size; ++k)
5134 cbld.at(block, inst->next)
5135 .MOV(offset(dst, inst->exec_size, k), offset(tmp, lbld, k));
5136
5137 return tmp;
5138
5139 } else {
5140 /* No need to allocate a temporary for the lowered instruction, just
5141 * take the right group of channels from the original region.
5142 */
5143 return dst;
5144 }
5145 }
5146
5147 bool
5148 fs_visitor::lower_simd_width()
5149 {
5150 bool progress = false;
5151
5152 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5153 const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
5154
5155 if (lower_width != inst->exec_size) {
5156 /* Builder matching the original instruction. We may also need to
5157 * emit an instruction of width larger than the original, set the
5158 * execution size of the builder to the highest of both for now so
5159 * we're sure that both cases can be handled.
5160 */
5161 const unsigned max_width = MAX2(inst->exec_size, lower_width);
5162 const fs_builder ibld = bld.at(block, inst)
5163 .exec_all(inst->force_writemask_all)
5164 .group(max_width, inst->group / max_width);
5165
5166 /* Split the copies in chunks of the execution width of either the
5167 * original or the lowered instruction, whichever is lower.
5168 */
5169 const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
5170 const unsigned dst_size = inst->regs_written * REG_SIZE /
5171 inst->dst.component_size(inst->exec_size);
5172
5173 assert(!inst->writes_accumulator && !inst->mlen);
5174
5175 for (unsigned i = 0; i < n; i++) {
5176 /* Emit a copy of the original instruction with the lowered width.
5177 * If the EOT flag was set throw it away except for the last
5178 * instruction to avoid killing the thread prematurely.
5179 */
5180 fs_inst split_inst = *inst;
5181 split_inst.exec_size = lower_width;
5182 split_inst.eot = inst->eot && i == n - 1;
5183
5184 /* Select the correct channel enables for the i-th group, then
5185 * transform the sources and destination and emit the lowered
5186 * instruction.
5187 */
5188 const fs_builder lbld = ibld.group(lower_width, i);
5189
5190 for (unsigned j = 0; j < inst->sources; j++)
5191 split_inst.src[j] = emit_unzip(lbld, block, inst, j);
5192
5193 split_inst.dst = emit_zip(lbld, block, inst);
5194 split_inst.regs_written = DIV_ROUND_UP(
5195 split_inst.dst.component_size(lower_width) * dst_size,
5196 REG_SIZE);
5197
5198 lbld.emit(split_inst);
5199 }
5200
5201 inst->remove(block);
5202 progress = true;
5203 }
5204 }
5205
5206 if (progress)
5207 invalidate_live_intervals();
5208
5209 return progress;
5210 }
5211
5212 void
5213 fs_visitor::dump_instructions()
5214 {
5215 dump_instructions(NULL);
5216 }
5217
5218 void
5219 fs_visitor::dump_instructions(const char *name)
5220 {
5221 FILE *file = stderr;
5222 if (name && geteuid() != 0) {
5223 file = fopen(name, "w");
5224 if (!file)
5225 file = stderr;
5226 }
5227
5228 if (cfg) {
5229 calculate_register_pressure();
5230 int ip = 0, max_pressure = 0;
5231 foreach_block_and_inst(block, backend_instruction, inst, cfg) {
5232 max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
5233 fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
5234 dump_instruction(inst, file);
5235 ip++;
5236 }
5237 fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
5238 } else {
5239 int ip = 0;
5240 foreach_in_list(backend_instruction, inst, &instructions) {
5241 fprintf(file, "%4d: ", ip++);
5242 dump_instruction(inst, file);
5243 }
5244 }
5245
5246 if (file != stderr) {
5247 fclose(file);
5248 }
5249 }
5250
5251 void
5252 fs_visitor::dump_instruction(backend_instruction *be_inst)
5253 {
5254 dump_instruction(be_inst, stderr);
5255 }
5256
5257 void
5258 fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
5259 {
5260 fs_inst *inst = (fs_inst *)be_inst;
5261
5262 if (inst->predicate) {
5263 fprintf(file, "(%cf0.%d) ",
5264 inst->predicate_inverse ? '-' : '+',
5265 inst->flag_subreg);
5266 }
5267
5268 fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
5269 if (inst->saturate)
5270 fprintf(file, ".sat");
5271 if (inst->conditional_mod) {
5272 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
5273 if (!inst->predicate &&
5274 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
5275 inst->opcode != BRW_OPCODE_IF &&
5276 inst->opcode != BRW_OPCODE_WHILE))) {
5277 fprintf(file, ".f0.%d", inst->flag_subreg);
5278 }
5279 }
5280 fprintf(file, "(%d) ", inst->exec_size);
5281
5282 if (inst->mlen) {
5283 fprintf(file, "(mlen: %d) ", inst->mlen);
5284 }
5285
5286 if (inst->eot) {
5287 fprintf(file, "(EOT) ");
5288 }
5289
5290 switch (inst->dst.file) {
5291 case VGRF:
5292 fprintf(file, "vgrf%d", inst->dst.nr);
5293 if (alloc.sizes[inst->dst.nr] != inst->regs_written ||
5294 inst->dst.subreg_offset)
5295 fprintf(file, "+%d.%d",
5296 inst->dst.reg_offset, inst->dst.subreg_offset);
5297 break;
5298 case FIXED_GRF:
5299 fprintf(file, "g%d", inst->dst.nr);
5300 break;
5301 case MRF:
5302 fprintf(file, "m%d", inst->dst.nr);
5303 break;
5304 case BAD_FILE:
5305 fprintf(file, "(null)");
5306 break;
5307 case UNIFORM:
5308 fprintf(file, "***u%d***", inst->dst.nr + inst->dst.reg_offset);
5309 break;
5310 case ATTR:
5311 fprintf(file, "***attr%d***", inst->dst.nr + inst->dst.reg_offset);
5312 break;
5313 case ARF:
5314 switch (inst->dst.nr) {
5315 case BRW_ARF_NULL:
5316 fprintf(file, "null");
5317 break;
5318 case BRW_ARF_ADDRESS:
5319 fprintf(file, "a0.%d", inst->dst.subnr);
5320 break;
5321 case BRW_ARF_ACCUMULATOR:
5322 fprintf(file, "acc%d", inst->dst.subnr);
5323 break;
5324 case BRW_ARF_FLAG:
5325 fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5326 break;
5327 default:
5328 fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5329 break;
5330 }
5331 if (inst->dst.subnr)
5332 fprintf(file, "+%d", inst->dst.subnr);
5333 break;
5334 case IMM:
5335 unreachable("not reached");
5336 }
5337 if (inst->dst.stride != 1)
5338 fprintf(file, "<%u>", inst->dst.stride);
5339 fprintf(file, ":%s, ", brw_reg_type_letters(inst->dst.type));
5340
5341 for (int i = 0; i < inst->sources; i++) {
5342 if (inst->src[i].negate)
5343 fprintf(file, "-");
5344 if (inst->src[i].abs)
5345 fprintf(file, "|");
5346 switch (inst->src[i].file) {
5347 case VGRF:
5348 fprintf(file, "vgrf%d", inst->src[i].nr);
5349 if (alloc.sizes[inst->src[i].nr] != (unsigned)inst->regs_read(i) ||
5350 inst->src[i].subreg_offset)
5351 fprintf(file, "+%d.%d", inst->src[i].reg_offset,
5352 inst->src[i].subreg_offset);
5353 break;
5354 case FIXED_GRF:
5355 fprintf(file, "g%d", inst->src[i].nr);
5356 break;
5357 case MRF:
5358 fprintf(file, "***m%d***", inst->src[i].nr);
5359 break;
5360 case ATTR:
5361 fprintf(file, "attr%d+%d", inst->src[i].nr, inst->src[i].reg_offset);
5362 break;
5363 case UNIFORM:
5364 fprintf(file, "u%d", inst->src[i].nr + inst->src[i].reg_offset);
5365 if (inst->src[i].subreg_offset) {
5366 fprintf(file, "+%d.%d", inst->src[i].reg_offset,
5367 inst->src[i].subreg_offset);
5368 }
5369 break;
5370 case BAD_FILE:
5371 fprintf(file, "(null)");
5372 break;
5373 case IMM:
5374 switch (inst->src[i].type) {
5375 case BRW_REGISTER_TYPE_F:
5376 fprintf(file, "%-gf", inst->src[i].f);
5377 break;
5378 case BRW_REGISTER_TYPE_DF:
5379 fprintf(file, "%fdf", inst->src[i].df);
5380 break;
5381 case BRW_REGISTER_TYPE_W:
5382 case BRW_REGISTER_TYPE_D:
5383 fprintf(file, "%dd", inst->src[i].d);
5384 break;
5385 case BRW_REGISTER_TYPE_UW:
5386 case BRW_REGISTER_TYPE_UD:
5387 fprintf(file, "%uu", inst->src[i].ud);
5388 break;
5389 case BRW_REGISTER_TYPE_VF:
5390 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
5391 brw_vf_to_float((inst->src[i].ud >> 0) & 0xff),
5392 brw_vf_to_float((inst->src[i].ud >> 8) & 0xff),
5393 brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
5394 brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
5395 break;
5396 default:
5397 fprintf(file, "???");
5398 break;
5399 }
5400 break;
5401 case ARF:
5402 switch (inst->src[i].nr) {
5403 case BRW_ARF_NULL:
5404 fprintf(file, "null");
5405 break;
5406 case BRW_ARF_ADDRESS:
5407 fprintf(file, "a0.%d", inst->src[i].subnr);
5408 break;
5409 case BRW_ARF_ACCUMULATOR:
5410 fprintf(file, "acc%d", inst->src[i].subnr);
5411 break;
5412 case BRW_ARF_FLAG:
5413 fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5414 break;
5415 default:
5416 fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5417 break;
5418 }
5419 if (inst->src[i].subnr)
5420 fprintf(file, "+%d", inst->src[i].subnr);
5421 break;
5422 }
5423 if (inst->src[i].abs)
5424 fprintf(file, "|");
5425
5426 if (inst->src[i].file != IMM) {
5427 unsigned stride;
5428 if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
5429 unsigned hstride = inst->src[i].hstride;
5430 stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
5431 } else {
5432 stride = inst->src[i].stride;
5433 }
5434 if (stride != 1)
5435 fprintf(file, "<%u>", stride);
5436
5437 fprintf(file, ":%s", brw_reg_type_letters(inst->src[i].type));
5438 }
5439
5440 if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
5441 fprintf(file, ", ");
5442 }
5443
5444 fprintf(file, " ");
5445
5446 if (inst->force_writemask_all)
5447 fprintf(file, "NoMask ");
5448
5449 if (inst->exec_size != dispatch_width)
5450 fprintf(file, "group%d ", inst->group);
5451
5452 fprintf(file, "\n");
5453 }
5454
5455 /**
5456 * Possibly returns an instruction that set up @param reg.
5457 *
5458 * Sometimes we want to take the result of some expression/variable
5459 * dereference tree and rewrite the instruction generating the result
5460 * of the tree. When processing the tree, we know that the
5461 * instructions generated are all writing temporaries that are dead
5462 * outside of this tree. So, if we have some instructions that write
5463 * a temporary, we're free to point that temp write somewhere else.
5464 *
5465 * Note that this doesn't guarantee that the instruction generated
5466 * only reg -- it might be the size=4 destination of a texture instruction.
5467 */
5468 fs_inst *
5469 fs_visitor::get_instruction_generating_reg(fs_inst *start,
5470 fs_inst *end,
5471 const fs_reg &reg)
5472 {
5473 if (end == start ||
5474 end->is_partial_write() ||
5475 !reg.equals(end->dst)) {
5476 return NULL;
5477 } else {
5478 return end;
5479 }
5480 }
5481
5482 void
5483 fs_visitor::setup_fs_payload_gen6()
5484 {
5485 assert(stage == MESA_SHADER_FRAGMENT);
5486 brw_wm_prog_data *prog_data = (brw_wm_prog_data*) this->prog_data;
5487
5488 unsigned barycentric_interp_modes =
5489 (stage == MESA_SHADER_FRAGMENT) ?
5490 ((brw_wm_prog_data*) this->prog_data)->barycentric_interp_modes : 0;
5491
5492 assert(devinfo->gen >= 6);
5493
5494 /* R0-1: masks, pixel X/Y coordinates. */
5495 payload.num_regs = 2;
5496 /* R2: only for 32-pixel dispatch.*/
5497
5498 /* R3-26: barycentric interpolation coordinates. These appear in the
5499 * same order that they appear in the brw_barycentric_mode
5500 * enum. Each set of coordinates occupies 2 registers if dispatch width
5501 * == 8 and 4 registers if dispatch width == 16. Coordinates only
5502 * appear if they were enabled using the "Barycentric Interpolation
5503 * Mode" bits in WM_STATE.
5504 */
5505 for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
5506 if (barycentric_interp_modes & (1 << i)) {
5507 payload.barycentric_coord_reg[i] = payload.num_regs;
5508 payload.num_regs += 2;
5509 if (dispatch_width == 16) {
5510 payload.num_regs += 2;
5511 }
5512 }
5513 }
5514
5515 /* R27: interpolated depth if uses source depth */
5516 prog_data->uses_src_depth =
5517 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
5518 if (prog_data->uses_src_depth) {
5519 payload.source_depth_reg = payload.num_regs;
5520 payload.num_regs++;
5521 if (dispatch_width == 16) {
5522 /* R28: interpolated depth if not SIMD8. */
5523 payload.num_regs++;
5524 }
5525 }
5526
5527 /* R29: interpolated W set if GEN6_WM_USES_SOURCE_W. */
5528 prog_data->uses_src_w =
5529 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
5530 if (prog_data->uses_src_w) {
5531 payload.source_w_reg = payload.num_regs;
5532 payload.num_regs++;
5533 if (dispatch_width == 16) {
5534 /* R30: interpolated W if not SIMD8. */
5535 payload.num_regs++;
5536 }
5537 }
5538
5539 /* R31: MSAA position offsets. */
5540 if (prog_data->persample_dispatch &&
5541 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_POS)) {
5542 /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
5543 *
5544 * "MSDISPMODE_PERSAMPLE is required in order to select
5545 * POSOFFSET_SAMPLE"
5546 *
5547 * So we can only really get sample positions if we are doing real
5548 * per-sample dispatch. If we need gl_SamplePosition and we don't have
5549 * persample dispatch, we hard-code it to 0.5.
5550 */
5551 prog_data->uses_pos_offset = true;
5552 payload.sample_pos_reg = payload.num_regs;
5553 payload.num_regs++;
5554 }
5555
5556 /* R32: MSAA input coverage mask */
5557 prog_data->uses_sample_mask =
5558 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_MASK_IN) != 0;
5559 if (prog_data->uses_sample_mask) {
5560 assert(devinfo->gen >= 7);
5561 payload.sample_mask_in_reg = payload.num_regs;
5562 payload.num_regs++;
5563 if (dispatch_width == 16) {
5564 /* R33: input coverage mask if not SIMD8. */
5565 payload.num_regs++;
5566 }
5567 }
5568
5569 /* R34-: bary for 32-pixel. */
5570 /* R58-59: interp W for 32-pixel. */
5571
5572 if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
5573 source_depth_to_render_target = true;
5574 }
5575 }
5576
5577 void
5578 fs_visitor::setup_vs_payload()
5579 {
5580 /* R0: thread header, R1: urb handles */
5581 payload.num_regs = 2;
5582 }
5583
5584 void
5585 fs_visitor::setup_gs_payload()
5586 {
5587 assert(stage == MESA_SHADER_GEOMETRY);
5588
5589 struct brw_gs_prog_data *gs_prog_data =
5590 (struct brw_gs_prog_data *) prog_data;
5591 struct brw_vue_prog_data *vue_prog_data =
5592 (struct brw_vue_prog_data *) prog_data;
5593
5594 /* R0: thread header, R1: output URB handles */
5595 payload.num_regs = 2;
5596
5597 if (gs_prog_data->include_primitive_id) {
5598 /* R2: Primitive ID 0..7 */
5599 payload.num_regs++;
5600 }
5601
5602 /* Use a maximum of 24 registers for push-model inputs. */
5603 const unsigned max_push_components = 24;
5604
5605 /* If pushing our inputs would take too many registers, reduce the URB read
5606 * length (which is in HWords, or 8 registers), and resort to pulling.
5607 *
5608 * Note that the GS reads <URB Read Length> HWords for every vertex - so we
5609 * have to multiply by VerticesIn to obtain the total storage requirement.
5610 */
5611 if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
5612 max_push_components || gs_prog_data->invocations > 1) {
5613 gs_prog_data->base.include_vue_handles = true;
5614
5615 /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
5616 payload.num_regs += nir->info.gs.vertices_in;
5617
5618 vue_prog_data->urb_read_length =
5619 ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
5620 }
5621 }
5622
5623 void
5624 fs_visitor::setup_cs_payload()
5625 {
5626 assert(devinfo->gen >= 7);
5627 payload.num_regs = 1;
5628 }
5629
5630 void
5631 fs_visitor::calculate_register_pressure()
5632 {
5633 invalidate_live_intervals();
5634 calculate_live_intervals();
5635
5636 unsigned num_instructions = 0;
5637 foreach_block(block, cfg)
5638 num_instructions += block->instructions.length();
5639
5640 regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
5641
5642 for (unsigned reg = 0; reg < alloc.count; reg++) {
5643 for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
5644 regs_live_at_ip[ip] += alloc.sizes[reg];
5645 }
5646 }
5647
5648 /**
5649 * Look for repeated FS_OPCODE_MOV_DISPATCH_TO_FLAGS and drop the later ones.
5650 *
5651 * The needs_unlit_centroid_workaround ends up producing one of these per
5652 * channel of centroid input, so it's good to clean them up.
5653 *
5654 * An assumption here is that nothing ever modifies the dispatched pixels
5655 * value that FS_OPCODE_MOV_DISPATCH_TO_FLAGS reads from, but the hardware
5656 * dictates that anyway.
5657 */
5658 bool
5659 fs_visitor::opt_drop_redundant_mov_to_flags()
5660 {
5661 bool flag_mov_found[2] = {false};
5662 bool progress = false;
5663
5664 /* Instructions removed by this pass can only be added if this were true */
5665 if (!devinfo->needs_unlit_centroid_workaround)
5666 return false;
5667
5668 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5669 if (inst->is_control_flow()) {
5670 memset(flag_mov_found, 0, sizeof(flag_mov_found));
5671 } else if (inst->opcode == FS_OPCODE_MOV_DISPATCH_TO_FLAGS) {
5672 if (!flag_mov_found[inst->flag_subreg]) {
5673 flag_mov_found[inst->flag_subreg] = true;
5674 } else {
5675 inst->remove(block);
5676 progress = true;
5677 }
5678 } else if (inst->flags_written()) {
5679 flag_mov_found[inst->flag_subreg] = false;
5680 }
5681 }
5682
5683 return progress;
5684 }
5685
5686 void
5687 fs_visitor::optimize()
5688 {
5689 /* Start by validating the shader we currently have. */
5690 validate();
5691
5692 /* bld is the common builder object pointing at the end of the program we
5693 * used to translate it into i965 IR. For the optimization and lowering
5694 * passes coming next, any code added after the end of the program without
5695 * having explicitly called fs_builder::at() clearly points at a mistake.
5696 * Ideally optimization passes wouldn't be part of the visitor so they
5697 * wouldn't have access to bld at all, but they do, so just in case some
5698 * pass forgets to ask for a location explicitly set it to NULL here to
5699 * make it trip. The dispatch width is initialized to a bogus value to
5700 * make sure that optimizations set the execution controls explicitly to
5701 * match the code they are manipulating instead of relying on the defaults.
5702 */
5703 bld = fs_builder(this, 64);
5704
5705 assign_constant_locations();
5706 lower_constant_loads();
5707
5708 validate();
5709
5710 split_virtual_grfs();
5711 validate();
5712
5713 #define OPT(pass, args...) ({ \
5714 pass_num++; \
5715 bool this_progress = pass(args); \
5716 \
5717 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
5718 char filename[64]; \
5719 snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass, \
5720 stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
5721 \
5722 backend_shader::dump_instructions(filename); \
5723 } \
5724 \
5725 validate(); \
5726 \
5727 progress = progress || this_progress; \
5728 this_progress; \
5729 })
5730
5731 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
5732 char filename[64];
5733 snprintf(filename, 64, "%s%d-%s-00-00-start",
5734 stage_abbrev, dispatch_width, nir->info.name);
5735
5736 backend_shader::dump_instructions(filename);
5737 }
5738
5739 bool progress = false;
5740 int iteration = 0;
5741 int pass_num = 0;
5742
5743 OPT(opt_drop_redundant_mov_to_flags);
5744
5745 do {
5746 progress = false;
5747 pass_num = 0;
5748 iteration++;
5749
5750 OPT(remove_duplicate_mrf_writes);
5751
5752 OPT(opt_algebraic);
5753 OPT(opt_cse);
5754 OPT(opt_copy_propagate);
5755 OPT(opt_predicated_break, this);
5756 OPT(opt_cmod_propagation);
5757 OPT(dead_code_eliminate);
5758 OPT(opt_peephole_sel);
5759 OPT(dead_control_flow_eliminate, this);
5760 OPT(opt_register_renaming);
5761 OPT(opt_saturate_propagation);
5762 OPT(register_coalesce);
5763 OPT(compute_to_mrf);
5764 OPT(eliminate_find_live_channel);
5765
5766 OPT(compact_virtual_grfs);
5767 } while (progress);
5768
5769 progress = false;
5770 pass_num = 0;
5771
5772 if (OPT(lower_pack)) {
5773 OPT(register_coalesce);
5774 OPT(dead_code_eliminate);
5775 }
5776
5777 if (OPT(lower_d2x)) {
5778 OPT(opt_copy_propagate);
5779 OPT(dead_code_eliminate);
5780 }
5781
5782 OPT(lower_simd_width);
5783
5784 /* After SIMD lowering just in case we had to unroll the EOT send. */
5785 OPT(opt_sampler_eot);
5786
5787 OPT(lower_logical_sends);
5788
5789 if (progress) {
5790 OPT(opt_copy_propagate);
5791 /* Only run after logical send lowering because it's easier to implement
5792 * in terms of physical sends.
5793 */
5794 if (OPT(opt_zero_samples))
5795 OPT(opt_copy_propagate);
5796 /* Run after logical send lowering to give it a chance to CSE the
5797 * LOAD_PAYLOAD instructions created to construct the payloads of
5798 * e.g. texturing messages in cases where it wasn't possible to CSE the
5799 * whole logical instruction.
5800 */
5801 OPT(opt_cse);
5802 OPT(register_coalesce);
5803 OPT(compute_to_mrf);
5804 OPT(dead_code_eliminate);
5805 OPT(remove_duplicate_mrf_writes);
5806 OPT(opt_peephole_sel);
5807 }
5808
5809 OPT(opt_redundant_discard_jumps);
5810
5811 if (OPT(lower_load_payload)) {
5812 split_virtual_grfs();
5813 OPT(register_coalesce);
5814 OPT(compute_to_mrf);
5815 OPT(dead_code_eliminate);
5816 }
5817
5818 OPT(opt_combine_constants);
5819 OPT(lower_integer_multiplication);
5820
5821 if (devinfo->gen <= 5 && OPT(lower_minmax)) {
5822 OPT(opt_cmod_propagation);
5823 OPT(opt_cse);
5824 OPT(opt_copy_propagate);
5825 OPT(dead_code_eliminate);
5826 }
5827
5828 lower_uniform_pull_constant_loads();
5829
5830 validate();
5831 }
5832
5833 /**
5834 * Three source instruction must have a GRF/MRF destination register.
5835 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
5836 */
5837 void
5838 fs_visitor::fixup_3src_null_dest()
5839 {
5840 bool progress = false;
5841
5842 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
5843 if (inst->is_3src(devinfo) && inst->dst.is_null()) {
5844 inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
5845 inst->dst.type);
5846 progress = true;
5847 }
5848 }
5849
5850 if (progress)
5851 invalidate_live_intervals();
5852 }
5853
5854 void
5855 fs_visitor::allocate_registers(bool allow_spilling)
5856 {
5857 bool allocated_without_spills;
5858
5859 static const enum instruction_scheduler_mode pre_modes[] = {
5860 SCHEDULE_PRE,
5861 SCHEDULE_PRE_NON_LIFO,
5862 SCHEDULE_PRE_LIFO,
5863 };
5864
5865 bool spill_all = allow_spilling && (INTEL_DEBUG & DEBUG_SPILL_FS);
5866
5867 /* Try each scheduling heuristic to see if it can successfully register
5868 * allocate without spilling. They should be ordered by decreasing
5869 * performance but increasing likelihood of allocating.
5870 */
5871 for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
5872 schedule_instructions(pre_modes[i]);
5873
5874 if (0) {
5875 assign_regs_trivial();
5876 allocated_without_spills = true;
5877 } else {
5878 allocated_without_spills = assign_regs(false, spill_all);
5879 }
5880 if (allocated_without_spills)
5881 break;
5882 }
5883
5884 if (!allocated_without_spills) {
5885 /* We assume that any spilling is worse than just dropping back to
5886 * SIMD8. There's probably actually some intermediate point where
5887 * SIMD16 with a couple of spills is still better.
5888 */
5889 if (dispatch_width > min_dispatch_width) {
5890 fail("Failure to register allocate. Reduce number of "
5891 "live scalar values to avoid this.");
5892 } else {
5893 compiler->shader_perf_log(log_data,
5894 "%s shader triggered register spilling. "
5895 "Try reducing the number of live scalar "
5896 "values to improve performance.\n",
5897 stage_name);
5898 }
5899
5900 /* Since we're out of heuristics, just go spill registers until we
5901 * get an allocation.
5902 */
5903 while (!assign_regs(true, spill_all)) {
5904 if (failed)
5905 break;
5906 }
5907 }
5908
5909 assert(last_scratch == 0 || allow_spilling);
5910
5911 /* This must come after all optimization and register allocation, since
5912 * it inserts dead code that happens to have side effects, and it does
5913 * so based on the actual physical registers in use.
5914 */
5915 insert_gen4_send_dependency_workarounds();
5916
5917 if (failed)
5918 return;
5919
5920 schedule_instructions(SCHEDULE_POST);
5921
5922 if (last_scratch > 0) {
5923 unsigned max_scratch_size = 2 * 1024 * 1024;
5924
5925 prog_data->total_scratch = brw_get_scratch_size(last_scratch);
5926
5927 if (stage == MESA_SHADER_COMPUTE) {
5928 if (devinfo->is_haswell) {
5929 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
5930 * field documentation, Haswell supports a minimum of 2kB of
5931 * scratch space for compute shaders, unlike every other stage
5932 * and platform.
5933 */
5934 prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
5935 } else if (devinfo->gen <= 7) {
5936 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
5937 * field documentation, platforms prior to Haswell measure scratch
5938 * size linearly with a range of [1kB, 12kB] and 1kB granularity.
5939 */
5940 prog_data->total_scratch = ALIGN(last_scratch, 1024);
5941 max_scratch_size = 12 * 1024;
5942 }
5943 }
5944
5945 /* We currently only support up to 2MB of scratch space. If we
5946 * need to support more eventually, the documentation suggests
5947 * that we could allocate a larger buffer, and partition it out
5948 * ourselves. We'd just have to undo the hardware's address
5949 * calculation by subtracting (FFTID * Per Thread Scratch Space)
5950 * and then add FFTID * (Larger Per Thread Scratch Space).
5951 *
5952 * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
5953 * Thread Group Tracking > Local Memory/Scratch Space.
5954 */
5955 assert(prog_data->total_scratch < max_scratch_size);
5956 }
5957 }
5958
5959 bool
5960 fs_visitor::run_vs(gl_clip_plane *clip_planes)
5961 {
5962 assert(stage == MESA_SHADER_VERTEX);
5963
5964 setup_vs_payload();
5965
5966 if (shader_time_index >= 0)
5967 emit_shader_time_begin();
5968
5969 emit_nir_code();
5970
5971 if (failed)
5972 return false;
5973
5974 compute_clip_distance(clip_planes);
5975
5976 emit_urb_writes();
5977
5978 if (shader_time_index >= 0)
5979 emit_shader_time_end();
5980
5981 calculate_cfg();
5982
5983 optimize();
5984
5985 assign_curb_setup();
5986 assign_vs_urb_setup();
5987
5988 fixup_3src_null_dest();
5989 allocate_registers(true);
5990
5991 return !failed;
5992 }
5993
5994 bool
5995 fs_visitor::run_tcs_single_patch()
5996 {
5997 assert(stage == MESA_SHADER_TESS_CTRL);
5998
5999 struct brw_tcs_prog_data *tcs_prog_data =
6000 (struct brw_tcs_prog_data *) prog_data;
6001
6002 /* r1-r4 contain the ICP handles. */
6003 payload.num_regs = 5;
6004
6005 if (shader_time_index >= 0)
6006 emit_shader_time_begin();
6007
6008 /* Initialize gl_InvocationID */
6009 fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
6010 fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
6011 bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
6012 bld.MOV(channels_ud, channels_uw);
6013
6014 if (tcs_prog_data->instances == 1) {
6015 invocation_id = channels_ud;
6016 } else {
6017 invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
6018
6019 /* Get instance number from g0.2 bits 23:17, and multiply it by 8. */
6020 fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
6021 fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
6022 bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
6023 brw_imm_ud(INTEL_MASK(23, 17)));
6024 bld.SHR(instance_times_8, t, brw_imm_ud(17 - 3));
6025
6026 bld.ADD(invocation_id, instance_times_8, channels_ud);
6027 }
6028
6029 /* Fix the disptach mask */
6030 if (nir->info.tcs.vertices_out % 8) {
6031 bld.CMP(bld.null_reg_ud(), invocation_id,
6032 brw_imm_ud(nir->info.tcs.vertices_out), BRW_CONDITIONAL_L);
6033 bld.IF(BRW_PREDICATE_NORMAL);
6034 }
6035
6036 emit_nir_code();
6037
6038 if (nir->info.tcs.vertices_out % 8) {
6039 bld.emit(BRW_OPCODE_ENDIF);
6040 }
6041
6042 /* Emit EOT write; set TR DS Cache bit */
6043 fs_reg srcs[3] = {
6044 fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
6045 fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
6046 fs_reg(brw_imm_ud(0)),
6047 };
6048 fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
6049 bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
6050
6051 fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
6052 bld.null_reg_ud(), payload);
6053 inst->mlen = 3;
6054 inst->eot = true;
6055
6056 if (shader_time_index >= 0)
6057 emit_shader_time_end();
6058
6059 if (failed)
6060 return false;
6061
6062 calculate_cfg();
6063
6064 optimize();
6065
6066 assign_curb_setup();
6067 assign_tcs_single_patch_urb_setup();
6068
6069 fixup_3src_null_dest();
6070 allocate_registers(true);
6071
6072 return !failed;
6073 }
6074
6075 bool
6076 fs_visitor::run_tes()
6077 {
6078 assert(stage == MESA_SHADER_TESS_EVAL);
6079
6080 /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
6081 payload.num_regs = 5;
6082
6083 if (shader_time_index >= 0)
6084 emit_shader_time_begin();
6085
6086 emit_nir_code();
6087
6088 if (failed)
6089 return false;
6090
6091 emit_urb_writes();
6092
6093 if (shader_time_index >= 0)
6094 emit_shader_time_end();
6095
6096 calculate_cfg();
6097
6098 optimize();
6099
6100 assign_curb_setup();
6101 assign_tes_urb_setup();
6102
6103 fixup_3src_null_dest();
6104 allocate_registers(true);
6105
6106 return !failed;
6107 }
6108
6109 bool
6110 fs_visitor::run_gs()
6111 {
6112 assert(stage == MESA_SHADER_GEOMETRY);
6113
6114 setup_gs_payload();
6115
6116 this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
6117
6118 if (gs_compile->control_data_header_size_bits > 0) {
6119 /* Create a VGRF to store accumulated control data bits. */
6120 this->control_data_bits = vgrf(glsl_type::uint_type);
6121
6122 /* If we're outputting more than 32 control data bits, then EmitVertex()
6123 * will set control_data_bits to 0 after emitting the first vertex.
6124 * Otherwise, we need to initialize it to 0 here.
6125 */
6126 if (gs_compile->control_data_header_size_bits <= 32) {
6127 const fs_builder abld = bld.annotate("initialize control data bits");
6128 abld.MOV(this->control_data_bits, brw_imm_ud(0u));
6129 }
6130 }
6131
6132 if (shader_time_index >= 0)
6133 emit_shader_time_begin();
6134
6135 emit_nir_code();
6136
6137 emit_gs_thread_end();
6138
6139 if (shader_time_index >= 0)
6140 emit_shader_time_end();
6141
6142 if (failed)
6143 return false;
6144
6145 calculate_cfg();
6146
6147 optimize();
6148
6149 assign_curb_setup();
6150 assign_gs_urb_setup();
6151
6152 fixup_3src_null_dest();
6153 allocate_registers(true);
6154
6155 return !failed;
6156 }
6157
6158 bool
6159 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
6160 {
6161 brw_wm_prog_data *wm_prog_data = (brw_wm_prog_data *) this->prog_data;
6162 brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
6163
6164 assert(stage == MESA_SHADER_FRAGMENT);
6165
6166 if (devinfo->gen >= 6)
6167 setup_fs_payload_gen6();
6168 else
6169 setup_fs_payload_gen4();
6170
6171 if (0) {
6172 emit_dummy_fs();
6173 } else if (do_rep_send) {
6174 assert(dispatch_width == 16);
6175 emit_repclear_shader();
6176 } else {
6177 if (shader_time_index >= 0)
6178 emit_shader_time_begin();
6179
6180 calculate_urb_setup();
6181 if (nir->info.inputs_read > 0 ||
6182 (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
6183 if (devinfo->gen < 6)
6184 emit_interpolation_setup_gen4();
6185 else
6186 emit_interpolation_setup_gen6();
6187 }
6188
6189 /* We handle discards by keeping track of the still-live pixels in f0.1.
6190 * Initialize it with the dispatched pixels.
6191 */
6192 if (wm_prog_data->uses_kill) {
6193 fs_inst *discard_init = bld.emit(FS_OPCODE_MOV_DISPATCH_TO_FLAGS);
6194 discard_init->flag_subreg = 1;
6195 }
6196
6197 /* Generate FS IR for main(). (the visitor only descends into
6198 * functions called "main").
6199 */
6200 emit_nir_code();
6201
6202 if (failed)
6203 return false;
6204
6205 if (wm_prog_data->uses_kill)
6206 bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
6207
6208 if (wm_key->alpha_test_func)
6209 emit_alpha_test();
6210
6211 emit_fb_writes();
6212
6213 if (shader_time_index >= 0)
6214 emit_shader_time_end();
6215
6216 calculate_cfg();
6217
6218 optimize();
6219
6220 assign_curb_setup();
6221 assign_urb_setup();
6222
6223 fixup_3src_null_dest();
6224 allocate_registers(allow_spilling);
6225
6226 if (failed)
6227 return false;
6228 }
6229
6230 return !failed;
6231 }
6232
6233 bool
6234 fs_visitor::run_cs()
6235 {
6236 assert(stage == MESA_SHADER_COMPUTE);
6237
6238 setup_cs_payload();
6239
6240 if (shader_time_index >= 0)
6241 emit_shader_time_begin();
6242
6243 if (devinfo->is_haswell && prog_data->total_shared > 0) {
6244 /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
6245 const fs_builder abld = bld.exec_all().group(1, 0);
6246 abld.MOV(retype(suboffset(brw_sr0_reg(), 1), BRW_REGISTER_TYPE_UW),
6247 suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
6248 }
6249
6250 emit_nir_code();
6251
6252 if (failed)
6253 return false;
6254
6255 emit_cs_terminate();
6256
6257 if (shader_time_index >= 0)
6258 emit_shader_time_end();
6259
6260 calculate_cfg();
6261
6262 optimize();
6263
6264 assign_curb_setup();
6265
6266 fixup_3src_null_dest();
6267 allocate_registers(true);
6268
6269 if (failed)
6270 return false;
6271
6272 return !failed;
6273 }
6274
6275 /**
6276 * Return a bitfield where bit n is set if barycentric interpolation mode n
6277 * (see enum brw_barycentric_mode) is needed by the fragment shader.
6278 *
6279 * We examine the load_barycentric intrinsics rather than looking at input
6280 * variables so that we catch interpolateAtCentroid() messages too, which
6281 * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
6282 */
6283 static unsigned
6284 brw_compute_barycentric_interp_modes(const struct brw_device_info *devinfo,
6285 const nir_shader *shader)
6286 {
6287 unsigned barycentric_interp_modes = 0;
6288
6289 nir_foreach_function(f, shader) {
6290 if (!f->impl)
6291 continue;
6292
6293 nir_foreach_block(block, f->impl) {
6294 nir_foreach_instr(instr, block) {
6295 if (instr->type != nir_instr_type_intrinsic)
6296 continue;
6297
6298 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6299 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
6300 continue;
6301
6302 /* Ignore WPOS; it doesn't require interpolation. */
6303 if (nir_intrinsic_base(intrin) == VARYING_SLOT_POS)
6304 continue;
6305
6306 intrin = nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
6307 enum glsl_interp_mode interp = (enum glsl_interp_mode)
6308 nir_intrinsic_interp_mode(intrin);
6309 nir_intrinsic_op bary_op = intrin->intrinsic;
6310 enum brw_barycentric_mode bary =
6311 brw_barycentric_mode(interp, bary_op);
6312
6313 barycentric_interp_modes |= 1 << bary;
6314
6315 if (devinfo->needs_unlit_centroid_workaround &&
6316 bary_op == nir_intrinsic_load_barycentric_centroid)
6317 barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
6318 }
6319 }
6320 }
6321
6322 return barycentric_interp_modes;
6323 }
6324
6325 static void
6326 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
6327 const nir_shader *shader)
6328 {
6329 prog_data->flat_inputs = 0;
6330
6331 nir_foreach_variable(var, &shader->inputs) {
6332 int input_index = prog_data->urb_setup[var->data.location];
6333
6334 if (input_index < 0)
6335 continue;
6336
6337 /* flat shading */
6338 if (var->data.interpolation == INTERP_MODE_FLAT)
6339 prog_data->flat_inputs |= (1 << input_index);
6340 }
6341 }
6342
6343 static uint8_t
6344 computed_depth_mode(const nir_shader *shader)
6345 {
6346 if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
6347 switch (shader->info.fs.depth_layout) {
6348 case FRAG_DEPTH_LAYOUT_NONE:
6349 case FRAG_DEPTH_LAYOUT_ANY:
6350 return BRW_PSCDEPTH_ON;
6351 case FRAG_DEPTH_LAYOUT_GREATER:
6352 return BRW_PSCDEPTH_ON_GE;
6353 case FRAG_DEPTH_LAYOUT_LESS:
6354 return BRW_PSCDEPTH_ON_LE;
6355 case FRAG_DEPTH_LAYOUT_UNCHANGED:
6356 return BRW_PSCDEPTH_OFF;
6357 }
6358 }
6359 return BRW_PSCDEPTH_OFF;
6360 }
6361
6362 /**
6363 * Move load_interpolated_input with simple (payload-based) barycentric modes
6364 * to the top of the program so we don't emit multiple PLNs for the same input.
6365 *
6366 * This works around CSE not being able to handle non-dominating cases
6367 * such as:
6368 *
6369 * if (...) {
6370 * interpolate input
6371 * } else {
6372 * interpolate the same exact input
6373 * }
6374 *
6375 * This should be replaced by global value numbering someday.
6376 */
6377 void
6378 move_interpolation_to_top(nir_shader *nir)
6379 {
6380 nir_foreach_function(f, nir) {
6381 if (!f->impl)
6382 continue;
6383
6384 nir_block *top = nir_start_block(f->impl);
6385 exec_node *cursor_node = NULL;
6386
6387 nir_foreach_block(block, f->impl) {
6388 if (block == top)
6389 continue;
6390
6391 nir_foreach_instr_safe(instr, block) {
6392 if (instr->type != nir_instr_type_intrinsic)
6393 continue;
6394
6395 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6396 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
6397 continue;
6398 nir_intrinsic_instr *bary_intrinsic =
6399 nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
6400 nir_intrinsic_op op = bary_intrinsic->intrinsic;
6401
6402 /* Leave interpolateAtSample/Offset() where they are. */
6403 if (op == nir_intrinsic_load_barycentric_at_sample ||
6404 op == nir_intrinsic_load_barycentric_at_offset)
6405 continue;
6406
6407 nir_instr *move[3] = {
6408 &bary_intrinsic->instr,
6409 intrin->src[1].ssa->parent_instr,
6410 instr
6411 };
6412
6413 for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
6414 if (move[i]->block != top) {
6415 move[i]->block = top;
6416 exec_node_remove(&move[i]->node);
6417 if (cursor_node) {
6418 exec_node_insert_after(cursor_node, &move[i]->node);
6419 } else {
6420 exec_list_push_head(&top->instr_list, &move[i]->node);
6421 }
6422 cursor_node = &move[i]->node;
6423 }
6424 }
6425 }
6426 }
6427 nir_metadata_preserve(f->impl, (nir_metadata)
6428 ((unsigned) nir_metadata_block_index |
6429 (unsigned) nir_metadata_dominance));
6430 }
6431 }
6432
6433 /**
6434 * Apply default interpolation settings to FS inputs which don't specify any.
6435 */
6436 static void
6437 brw_nir_set_default_interpolation(const struct brw_device_info *devinfo,
6438 struct nir_shader *nir,
6439 bool api_flat_shade,
6440 bool per_sample_interpolation)
6441 {
6442 assert(nir->stage == MESA_SHADER_FRAGMENT);
6443
6444 nir_foreach_variable(var, &nir->inputs) {
6445 /* Apply default interpolation mode.
6446 *
6447 * Everything defaults to smooth except for the legacy GL color
6448 * built-in variables, which might be flat depending on API state.
6449 */
6450 if (var->data.interpolation == INTERP_MODE_NONE) {
6451 const bool flat = api_flat_shade &&
6452 (var->data.location == VARYING_SLOT_COL0 ||
6453 var->data.location == VARYING_SLOT_COL1);
6454
6455 var->data.interpolation = flat ? INTERP_MODE_FLAT
6456 : INTERP_MODE_SMOOTH;
6457 }
6458
6459 /* Apply 'sample' if necessary for API state. */
6460 if (per_sample_interpolation &&
6461 var->data.interpolation != INTERP_MODE_FLAT) {
6462 var->data.centroid = false;
6463 var->data.sample = true;
6464 }
6465
6466 /* On Ironlake and below, there is only one interpolation mode.
6467 * Centroid interpolation doesn't mean anything on this hardware --
6468 * there is no multisampling.
6469 */
6470 if (devinfo->gen < 6) {
6471 var->data.centroid = false;
6472 var->data.sample = false;
6473 }
6474 }
6475 }
6476
6477 /**
6478 * Demote per-sample barycentric intrinsics to centroid.
6479 *
6480 * Useful when rendering to a non-multisampled buffer.
6481 */
6482 static void
6483 demote_sample_qualifiers(nir_shader *nir)
6484 {
6485 nir_foreach_function(f, nir) {
6486 if (!f->impl)
6487 continue;
6488
6489 nir_builder b;
6490 nir_builder_init(&b, f->impl);
6491
6492 nir_foreach_block(block, f->impl) {
6493 nir_foreach_instr_safe(instr, block) {
6494 if (instr->type != nir_instr_type_intrinsic)
6495 continue;
6496
6497 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6498 if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
6499 intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
6500 continue;
6501
6502 b.cursor = nir_before_instr(instr);
6503 nir_ssa_def *centroid =
6504 nir_load_barycentric(&b, nir_intrinsic_load_barycentric_centroid,
6505 nir_intrinsic_interp_mode(intrin));
6506 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
6507 nir_src_for_ssa(centroid));
6508 nir_instr_remove(instr);
6509 }
6510 }
6511
6512 nir_metadata_preserve(f->impl, (nir_metadata)
6513 ((unsigned) nir_metadata_block_index |
6514 (unsigned) nir_metadata_dominance));
6515 }
6516 }
6517
6518 const unsigned *
6519 brw_compile_fs(const struct brw_compiler *compiler, void *log_data,
6520 void *mem_ctx,
6521 const struct brw_wm_prog_key *key,
6522 struct brw_wm_prog_data *prog_data,
6523 const nir_shader *src_shader,
6524 struct gl_program *prog,
6525 int shader_time_index8, int shader_time_index16,
6526 bool allow_spilling,
6527 bool use_rep_send,
6528 unsigned *final_assembly_size,
6529 char **error_str)
6530 {
6531 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
6532 shader = brw_nir_apply_sampler_key(shader, compiler->devinfo, &key->tex,
6533 true);
6534 brw_nir_set_default_interpolation(compiler->devinfo, shader,
6535 key->flat_shade, key->persample_interp);
6536 brw_nir_lower_fs_inputs(shader);
6537 brw_nir_lower_fs_outputs(shader);
6538 if (!key->multisample_fbo)
6539 NIR_PASS_V(shader, demote_sample_qualifiers);
6540 NIR_PASS_V(shader, move_interpolation_to_top);
6541 shader = brw_postprocess_nir(shader, compiler->devinfo, true);
6542
6543 /* key->alpha_test_func means simulating alpha testing via discards,
6544 * so the shader definitely kills pixels.
6545 */
6546 prog_data->uses_kill = shader->info.fs.uses_discard || key->alpha_test_func;
6547 prog_data->uses_omask = key->multisample_fbo &&
6548 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
6549 prog_data->computed_depth_mode = computed_depth_mode(shader);
6550 prog_data->computed_stencil =
6551 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
6552
6553 prog_data->persample_dispatch =
6554 key->multisample_fbo &&
6555 (key->persample_interp ||
6556 (shader->info.system_values_read & (SYSTEM_BIT_SAMPLE_ID |
6557 SYSTEM_BIT_SAMPLE_POS)) ||
6558 shader->info.fs.uses_sample_qualifier ||
6559 shader->info.outputs_read);
6560
6561 prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
6562
6563 prog_data->barycentric_interp_modes =
6564 brw_compute_barycentric_interp_modes(compiler->devinfo, shader);
6565
6566 cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL;
6567 uint8_t simd8_grf_start = 0, simd16_grf_start = 0;
6568 unsigned simd8_grf_used = 0, simd16_grf_used = 0;
6569
6570 fs_visitor v8(compiler, log_data, mem_ctx, key,
6571 &prog_data->base, prog, shader, 8,
6572 shader_time_index8);
6573 if (!v8.run_fs(allow_spilling, false /* do_rep_send */)) {
6574 if (error_str)
6575 *error_str = ralloc_strdup(mem_ctx, v8.fail_msg);
6576
6577 return NULL;
6578 } else if (likely(!(INTEL_DEBUG & DEBUG_NO8))) {
6579 simd8_cfg = v8.cfg;
6580 simd8_grf_start = v8.payload.num_regs;
6581 simd8_grf_used = v8.grf_used;
6582 }
6583
6584 if (v8.max_dispatch_width >= 16 &&
6585 likely(!(INTEL_DEBUG & DEBUG_NO16) || use_rep_send)) {
6586 /* Try a SIMD16 compile */
6587 fs_visitor v16(compiler, log_data, mem_ctx, key,
6588 &prog_data->base, prog, shader, 16,
6589 shader_time_index16);
6590 v16.import_uniforms(&v8);
6591 if (!v16.run_fs(allow_spilling, use_rep_send)) {
6592 compiler->shader_perf_log(log_data,
6593 "SIMD16 shader failed to compile: %s",
6594 v16.fail_msg);
6595 } else {
6596 simd16_cfg = v16.cfg;
6597 simd16_grf_start = v16.payload.num_regs;
6598 simd16_grf_used = v16.grf_used;
6599 }
6600 }
6601
6602 /* When the caller requests a repclear shader, they want SIMD16-only */
6603 if (use_rep_send)
6604 simd8_cfg = NULL;
6605
6606 /* Prior to Iron Lake, the PS had a single shader offset with a jump table
6607 * at the top to select the shader. We've never implemented that.
6608 * Instead, we just give them exactly one shader and we pick the widest one
6609 * available.
6610 */
6611 if (compiler->devinfo->gen < 5 && simd16_cfg)
6612 simd8_cfg = NULL;
6613
6614 if (prog_data->persample_dispatch) {
6615 /* Starting with SandyBridge (where we first get MSAA), the different
6616 * pixel dispatch combinations are grouped into classifications A
6617 * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1). On all hardware
6618 * generations, the only configurations supporting persample dispatch
6619 * are are this in which only one dispatch width is enabled.
6620 *
6621 * If computed depth is enabled, SNB only allows SIMD8 while IVB+
6622 * allow SIMD8 or SIMD16 so we choose SIMD16 if available.
6623 */
6624 if (compiler->devinfo->gen == 6 &&
6625 prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF) {
6626 simd16_cfg = NULL;
6627 } else if (simd16_cfg) {
6628 simd8_cfg = NULL;
6629 }
6630 }
6631
6632 /* We have to compute the flat inputs after the visitor is finished running
6633 * because it relies on prog_data->urb_setup which is computed in
6634 * fs_visitor::calculate_urb_setup().
6635 */
6636 brw_compute_flat_inputs(prog_data, shader);
6637
6638 fs_generator g(compiler, log_data, mem_ctx, (void *) key, &prog_data->base,
6639 v8.promoted_constants, v8.runtime_check_aads_emit,
6640 MESA_SHADER_FRAGMENT);
6641
6642 if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
6643 g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
6644 shader->info.label ? shader->info.label :
6645 "unnamed",
6646 shader->info.name));
6647 }
6648
6649 if (simd8_cfg) {
6650 prog_data->dispatch_8 = true;
6651 g.generate_code(simd8_cfg, 8);
6652 prog_data->base.dispatch_grf_start_reg = simd8_grf_start;
6653 prog_data->reg_blocks_0 = brw_register_blocks(simd8_grf_used);
6654
6655 if (simd16_cfg) {
6656 prog_data->dispatch_16 = true;
6657 prog_data->prog_offset_2 = g.generate_code(simd16_cfg, 16);
6658 prog_data->dispatch_grf_start_reg_2 = simd16_grf_start;
6659 prog_data->reg_blocks_2 = brw_register_blocks(simd16_grf_used);
6660 }
6661 } else if (simd16_cfg) {
6662 prog_data->dispatch_16 = true;
6663 g.generate_code(simd16_cfg, 16);
6664 prog_data->base.dispatch_grf_start_reg = simd16_grf_start;
6665 prog_data->reg_blocks_0 = brw_register_blocks(simd16_grf_used);
6666 }
6667
6668 return g.get_assembly(final_assembly_size);
6669 }
6670
6671 fs_reg *
6672 fs_visitor::emit_cs_work_group_id_setup()
6673 {
6674 assert(stage == MESA_SHADER_COMPUTE);
6675
6676 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
6677
6678 struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
6679 struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
6680 struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
6681
6682 bld.MOV(*reg, r0_1);
6683 bld.MOV(offset(*reg, bld, 1), r0_6);
6684 bld.MOV(offset(*reg, bld, 2), r0_7);
6685
6686 return reg;
6687 }
6688
6689 static void
6690 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
6691 {
6692 block->dwords = dwords;
6693 block->regs = DIV_ROUND_UP(dwords, 8);
6694 block->size = block->regs * 32;
6695 }
6696
6697 static void
6698 cs_fill_push_const_info(const struct brw_device_info *devinfo,
6699 struct brw_cs_prog_data *cs_prog_data)
6700 {
6701 const struct brw_stage_prog_data *prog_data =
6702 (struct brw_stage_prog_data*) cs_prog_data;
6703 bool fill_thread_id =
6704 cs_prog_data->thread_local_id_index >= 0 &&
6705 cs_prog_data->thread_local_id_index < (int)prog_data->nr_params;
6706 bool cross_thread_supported = devinfo->gen > 7 || devinfo->is_haswell;
6707
6708 /* The thread ID should be stored in the last param dword */
6709 assert(prog_data->nr_params > 0 || !fill_thread_id);
6710 assert(!fill_thread_id ||
6711 cs_prog_data->thread_local_id_index ==
6712 (int)prog_data->nr_params - 1);
6713
6714 unsigned cross_thread_dwords, per_thread_dwords;
6715 if (!cross_thread_supported) {
6716 cross_thread_dwords = 0u;
6717 per_thread_dwords = prog_data->nr_params;
6718 } else if (fill_thread_id) {
6719 /* Fill all but the last register with cross-thread payload */
6720 cross_thread_dwords = 8 * (cs_prog_data->thread_local_id_index / 8);
6721 per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
6722 assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
6723 } else {
6724 /* Fill all data using cross-thread payload */
6725 cross_thread_dwords = prog_data->nr_params;
6726 per_thread_dwords = 0u;
6727 }
6728
6729 fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
6730 fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
6731
6732 unsigned total_dwords =
6733 (cs_prog_data->push.per_thread.size * cs_prog_data->threads +
6734 cs_prog_data->push.cross_thread.size) / 4;
6735 fill_push_const_block_info(&cs_prog_data->push.total, total_dwords);
6736
6737 assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
6738 cs_prog_data->push.per_thread.size == 0);
6739 assert(cs_prog_data->push.cross_thread.dwords +
6740 cs_prog_data->push.per_thread.dwords ==
6741 prog_data->nr_params);
6742 }
6743
6744 static void
6745 cs_set_simd_size(struct brw_cs_prog_data *cs_prog_data, unsigned size)
6746 {
6747 cs_prog_data->simd_size = size;
6748 unsigned group_size = cs_prog_data->local_size[0] *
6749 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
6750 cs_prog_data->threads = (group_size + size - 1) / size;
6751 }
6752
6753 const unsigned *
6754 brw_compile_cs(const struct brw_compiler *compiler, void *log_data,
6755 void *mem_ctx,
6756 const struct brw_cs_prog_key *key,
6757 struct brw_cs_prog_data *prog_data,
6758 const nir_shader *src_shader,
6759 int shader_time_index,
6760 unsigned *final_assembly_size,
6761 char **error_str)
6762 {
6763 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
6764 shader = brw_nir_apply_sampler_key(shader, compiler->devinfo, &key->tex,
6765 true);
6766 brw_nir_lower_cs_shared(shader);
6767 prog_data->base.total_shared += shader->num_shared;
6768
6769 /* Now that we cloned the nir_shader, we can update num_uniforms based on
6770 * the thread_local_id_index.
6771 */
6772 assert(prog_data->thread_local_id_index >= 0);
6773 shader->num_uniforms =
6774 MAX2(shader->num_uniforms,
6775 (unsigned)4 * (prog_data->thread_local_id_index + 1));
6776
6777 brw_nir_lower_intrinsics(shader, &prog_data->base);
6778 shader = brw_postprocess_nir(shader, compiler->devinfo, true);
6779
6780 prog_data->local_size[0] = shader->info.cs.local_size[0];
6781 prog_data->local_size[1] = shader->info.cs.local_size[1];
6782 prog_data->local_size[2] = shader->info.cs.local_size[2];
6783 unsigned local_workgroup_size =
6784 shader->info.cs.local_size[0] * shader->info.cs.local_size[1] *
6785 shader->info.cs.local_size[2];
6786
6787 unsigned max_cs_threads = compiler->devinfo->max_cs_threads;
6788 unsigned simd_required = DIV_ROUND_UP(local_workgroup_size, max_cs_threads);
6789
6790 cfg_t *cfg = NULL;
6791 const char *fail_msg = NULL;
6792
6793 /* Now the main event: Visit the shader IR and generate our CS IR for it.
6794 */
6795 fs_visitor v8(compiler, log_data, mem_ctx, key, &prog_data->base,
6796 NULL, /* Never used in core profile */
6797 shader, 8, shader_time_index);
6798 if (simd_required <= 8) {
6799 if (!v8.run_cs()) {
6800 fail_msg = v8.fail_msg;
6801 } else {
6802 cfg = v8.cfg;
6803 cs_set_simd_size(prog_data, 8);
6804 cs_fill_push_const_info(compiler->devinfo, prog_data);
6805 prog_data->base.dispatch_grf_start_reg = v8.payload.num_regs;
6806 }
6807 }
6808
6809 fs_visitor v16(compiler, log_data, mem_ctx, key, &prog_data->base,
6810 NULL, /* Never used in core profile */
6811 shader, 16, shader_time_index);
6812 if (likely(!(INTEL_DEBUG & DEBUG_NO16)) &&
6813 !fail_msg && v8.max_dispatch_width >= 16 &&
6814 simd_required <= 16) {
6815 /* Try a SIMD16 compile */
6816 if (simd_required <= 8)
6817 v16.import_uniforms(&v8);
6818 if (!v16.run_cs()) {
6819 compiler->shader_perf_log(log_data,
6820 "SIMD16 shader failed to compile: %s",
6821 v16.fail_msg);
6822 if (!cfg) {
6823 fail_msg =
6824 "Couldn't generate SIMD16 program and not "
6825 "enough threads for SIMD8";
6826 }
6827 } else {
6828 cfg = v16.cfg;
6829 cs_set_simd_size(prog_data, 16);
6830 cs_fill_push_const_info(compiler->devinfo, prog_data);
6831 prog_data->dispatch_grf_start_reg_16 = v16.payload.num_regs;
6832 }
6833 }
6834
6835 fs_visitor v32(compiler, log_data, mem_ctx, key, &prog_data->base,
6836 NULL, /* Never used in core profile */
6837 shader, 32, shader_time_index);
6838 if (!fail_msg && v8.max_dispatch_width >= 32 &&
6839 (simd_required > 16 || (INTEL_DEBUG & DEBUG_DO32))) {
6840 /* Try a SIMD32 compile */
6841 if (simd_required <= 8)
6842 v32.import_uniforms(&v8);
6843 else if (simd_required <= 16)
6844 v32.import_uniforms(&v16);
6845
6846 if (!v32.run_cs()) {
6847 compiler->shader_perf_log(log_data,
6848 "SIMD32 shader failed to compile: %s",
6849 v16.fail_msg);
6850 if (!cfg) {
6851 fail_msg =
6852 "Couldn't generate SIMD32 program and not "
6853 "enough threads for SIMD16";
6854 }
6855 } else {
6856 cfg = v32.cfg;
6857 cs_set_simd_size(prog_data, 32);
6858 cs_fill_push_const_info(compiler->devinfo, prog_data);
6859 }
6860 }
6861
6862 if (unlikely(cfg == NULL)) {
6863 assert(fail_msg);
6864 if (error_str)
6865 *error_str = ralloc_strdup(mem_ctx, fail_msg);
6866
6867 return NULL;
6868 }
6869
6870 fs_generator g(compiler, log_data, mem_ctx, (void*) key, &prog_data->base,
6871 v8.promoted_constants, v8.runtime_check_aads_emit,
6872 MESA_SHADER_COMPUTE);
6873 if (INTEL_DEBUG & DEBUG_CS) {
6874 char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
6875 shader->info.label ? shader->info.label :
6876 "unnamed",
6877 shader->info.name);
6878 g.enable_debug(name);
6879 }
6880
6881 g.generate_code(cfg, prog_data->simd_size);
6882
6883 return g.get_assembly(final_assembly_size);
6884 }