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