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