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