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