i965/fs: Implement lowering of logical framebuffer writes.
[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_cfg.h"
46 #include "brw_dead_control_flow.h"
47 #include "main/uniforms.h"
48 #include "brw_fs_live_variables.h"
49 #include "glsl/glsl_types.h"
50 #include "program/sampler.h"
51
52 using namespace brw;
53
54 void
55 fs_inst::init(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
56 const fs_reg *src, unsigned sources)
57 {
58 memset(this, 0, sizeof(*this));
59
60 this->src = new fs_reg[MAX2(sources, 3)];
61 for (unsigned i = 0; i < sources; i++)
62 this->src[i] = src[i];
63
64 this->opcode = opcode;
65 this->dst = dst;
66 this->sources = sources;
67 this->exec_size = exec_size;
68
69 assert(dst.file != IMM && dst.file != UNIFORM);
70
71 assert(this->exec_size != 0);
72
73 this->conditional_mod = BRW_CONDITIONAL_NONE;
74
75 /* This will be the case for almost all instructions. */
76 switch (dst.file) {
77 case GRF:
78 case HW_REG:
79 case MRF:
80 case ATTR:
81 this->regs_written = DIV_ROUND_UP(dst.component_size(exec_size),
82 REG_SIZE);
83 break;
84 case BAD_FILE:
85 this->regs_written = 0;
86 break;
87 case IMM:
88 case UNIFORM:
89 unreachable("Invalid destination register file");
90 default:
91 unreachable("Invalid register file");
92 }
93
94 this->writes_accumulator = false;
95 }
96
97 fs_inst::fs_inst()
98 {
99 init(BRW_OPCODE_NOP, 8, dst, NULL, 0);
100 }
101
102 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size)
103 {
104 init(opcode, exec_size, reg_undef, NULL, 0);
105 }
106
107 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst)
108 {
109 init(opcode, exec_size, dst, NULL, 0);
110 }
111
112 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
113 const fs_reg &src0)
114 {
115 const fs_reg src[1] = { src0 };
116 init(opcode, exec_size, dst, src, 1);
117 }
118
119 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
120 const fs_reg &src0, const fs_reg &src1)
121 {
122 const fs_reg src[2] = { src0, src1 };
123 init(opcode, exec_size, dst, src, 2);
124 }
125
126 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
127 const fs_reg &src0, const fs_reg &src1, const fs_reg &src2)
128 {
129 const fs_reg src[3] = { src0, src1, src2 };
130 init(opcode, exec_size, dst, src, 3);
131 }
132
133 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_width, const fs_reg &dst,
134 const fs_reg src[], unsigned sources)
135 {
136 init(opcode, exec_width, dst, src, sources);
137 }
138
139 fs_inst::fs_inst(const fs_inst &that)
140 {
141 memcpy(this, &that, sizeof(that));
142
143 this->src = new fs_reg[MAX2(that.sources, 3)];
144
145 for (unsigned i = 0; i < that.sources; i++)
146 this->src[i] = that.src[i];
147 }
148
149 fs_inst::~fs_inst()
150 {
151 delete[] this->src;
152 }
153
154 void
155 fs_inst::resize_sources(uint8_t num_sources)
156 {
157 if (this->sources != num_sources) {
158 fs_reg *src = new fs_reg[MAX2(num_sources, 3)];
159
160 for (unsigned i = 0; i < MIN2(this->sources, num_sources); ++i)
161 src[i] = this->src[i];
162
163 delete[] this->src;
164 this->src = src;
165 this->sources = num_sources;
166 }
167 }
168
169 void
170 fs_visitor::VARYING_PULL_CONSTANT_LOAD(const fs_builder &bld,
171 const fs_reg &dst,
172 const fs_reg &surf_index,
173 const fs_reg &varying_offset,
174 uint32_t const_offset)
175 {
176 /* We have our constant surface use a pitch of 4 bytes, so our index can
177 * be any component of a vector, and then we load 4 contiguous
178 * components starting from that.
179 *
180 * We break down the const_offset to a portion added to the variable
181 * offset and a portion done using reg_offset, which means that if you
182 * have GLSL using something like "uniform vec4 a[20]; gl_FragColor =
183 * a[i]", we'll temporarily generate 4 vec4 loads from offset i * 4, and
184 * CSE can later notice that those loads are all the same and eliminate
185 * the redundant ones.
186 */
187 fs_reg vec4_offset = vgrf(glsl_type::int_type);
188 bld.ADD(vec4_offset, varying_offset, fs_reg(const_offset & ~3));
189
190 int scale = 1;
191 if (devinfo->gen == 4 && bld.dispatch_width() == 8) {
192 /* Pre-gen5, we can either use a SIMD8 message that requires (header,
193 * u, v, r) as parameters, or we can just use the SIMD16 message
194 * consisting of (header, u). We choose the second, at the cost of a
195 * longer return length.
196 */
197 scale = 2;
198 }
199
200 enum opcode op;
201 if (devinfo->gen >= 7)
202 op = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7;
203 else
204 op = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD;
205
206 int regs_written = 4 * (bld.dispatch_width() / 8) * scale;
207 fs_reg vec4_result = fs_reg(GRF, alloc.allocate(regs_written), dst.type);
208 fs_inst *inst = bld.emit(op, vec4_result, surf_index, vec4_offset);
209 inst->regs_written = regs_written;
210
211 if (devinfo->gen < 7) {
212 inst->base_mrf = 13;
213 inst->header_size = 1;
214 if (devinfo->gen == 4)
215 inst->mlen = 3;
216 else
217 inst->mlen = 1 + bld.dispatch_width() / 8;
218 }
219
220 bld.MOV(dst, offset(vec4_result, bld, (const_offset & 3) * scale));
221 }
222
223 /**
224 * A helper for MOV generation for fixing up broken hardware SEND dependency
225 * handling.
226 */
227 void
228 fs_visitor::DEP_RESOLVE_MOV(const fs_builder &bld, int grf)
229 {
230 /* The caller always wants uncompressed to emit the minimal extra
231 * dependencies, and to avoid having to deal with aligning its regs to 2.
232 */
233 const fs_builder ubld = bld.annotate("send dependency resolve")
234 .half(0);
235
236 ubld.MOV(ubld.null_reg_f(), fs_reg(GRF, grf, BRW_REGISTER_TYPE_F));
237 }
238
239 bool
240 fs_inst::equals(fs_inst *inst) const
241 {
242 return (opcode == inst->opcode &&
243 dst.equals(inst->dst) &&
244 src[0].equals(inst->src[0]) &&
245 src[1].equals(inst->src[1]) &&
246 src[2].equals(inst->src[2]) &&
247 saturate == inst->saturate &&
248 predicate == inst->predicate &&
249 conditional_mod == inst->conditional_mod &&
250 mlen == inst->mlen &&
251 base_mrf == inst->base_mrf &&
252 target == inst->target &&
253 eot == inst->eot &&
254 header_size == inst->header_size &&
255 shadow_compare == inst->shadow_compare &&
256 exec_size == inst->exec_size &&
257 offset == inst->offset);
258 }
259
260 bool
261 fs_inst::overwrites_reg(const fs_reg &reg) const
262 {
263 return reg.in_range(dst, regs_written);
264 }
265
266 bool
267 fs_inst::is_send_from_grf() const
268 {
269 switch (opcode) {
270 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7:
271 case SHADER_OPCODE_SHADER_TIME_ADD:
272 case FS_OPCODE_INTERPOLATE_AT_CENTROID:
273 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
274 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
275 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
276 case SHADER_OPCODE_UNTYPED_ATOMIC:
277 case SHADER_OPCODE_UNTYPED_SURFACE_READ:
278 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
279 case SHADER_OPCODE_TYPED_ATOMIC:
280 case SHADER_OPCODE_TYPED_SURFACE_READ:
281 case SHADER_OPCODE_TYPED_SURFACE_WRITE:
282 case SHADER_OPCODE_URB_WRITE_SIMD8:
283 return true;
284 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
285 return src[1].file == GRF;
286 case FS_OPCODE_FB_WRITE:
287 return src[0].file == GRF;
288 default:
289 if (is_tex())
290 return src[0].file == GRF;
291
292 return false;
293 }
294 }
295
296 bool
297 fs_inst::is_copy_payload(const brw::simple_allocator &grf_alloc) const
298 {
299 if (this->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
300 return false;
301
302 fs_reg reg = this->src[0];
303 if (reg.file != GRF || reg.reg_offset != 0 || reg.stride == 0)
304 return false;
305
306 if (grf_alloc.sizes[reg.reg] != this->regs_written)
307 return false;
308
309 for (int i = 0; i < this->sources; i++) {
310 reg.type = this->src[i].type;
311 if (!this->src[i].equals(reg))
312 return false;
313
314 if (i < this->header_size) {
315 reg.reg_offset += 1;
316 } else {
317 reg.reg_offset += this->exec_size / 8;
318 }
319 }
320
321 return true;
322 }
323
324 bool
325 fs_inst::can_do_source_mods(const struct brw_device_info *devinfo)
326 {
327 if (devinfo->gen == 6 && is_math())
328 return false;
329
330 if (is_send_from_grf())
331 return false;
332
333 if (!backend_instruction::can_do_source_mods())
334 return false;
335
336 return true;
337 }
338
339 bool
340 fs_inst::has_side_effects() const
341 {
342 return this->eot || backend_instruction::has_side_effects();
343 }
344
345 void
346 fs_reg::init()
347 {
348 memset(this, 0, sizeof(*this));
349 stride = 1;
350 }
351
352 /** Generic unset register constructor. */
353 fs_reg::fs_reg()
354 {
355 init();
356 this->file = BAD_FILE;
357 }
358
359 /** Immediate value constructor. */
360 fs_reg::fs_reg(float f)
361 {
362 init();
363 this->file = IMM;
364 this->type = BRW_REGISTER_TYPE_F;
365 this->stride = 0;
366 this->fixed_hw_reg.dw1.f = f;
367 }
368
369 /** Immediate value constructor. */
370 fs_reg::fs_reg(int32_t i)
371 {
372 init();
373 this->file = IMM;
374 this->type = BRW_REGISTER_TYPE_D;
375 this->stride = 0;
376 this->fixed_hw_reg.dw1.d = i;
377 }
378
379 /** Immediate value constructor. */
380 fs_reg::fs_reg(uint32_t u)
381 {
382 init();
383 this->file = IMM;
384 this->type = BRW_REGISTER_TYPE_UD;
385 this->stride = 0;
386 this->fixed_hw_reg.dw1.ud = u;
387 }
388
389 /** Vector float immediate value constructor. */
390 fs_reg::fs_reg(uint8_t vf[4])
391 {
392 init();
393 this->file = IMM;
394 this->type = BRW_REGISTER_TYPE_VF;
395 memcpy(&this->fixed_hw_reg.dw1.ud, vf, sizeof(unsigned));
396 }
397
398 /** Vector float immediate value constructor. */
399 fs_reg::fs_reg(uint8_t vf0, uint8_t vf1, uint8_t vf2, uint8_t vf3)
400 {
401 init();
402 this->file = IMM;
403 this->type = BRW_REGISTER_TYPE_VF;
404 this->fixed_hw_reg.dw1.ud = (vf0 << 0) |
405 (vf1 << 8) |
406 (vf2 << 16) |
407 (vf3 << 24);
408 }
409
410 /** Fixed brw_reg. */
411 fs_reg::fs_reg(struct brw_reg fixed_hw_reg)
412 {
413 init();
414 this->file = HW_REG;
415 this->fixed_hw_reg = fixed_hw_reg;
416 this->type = fixed_hw_reg.type;
417 }
418
419 bool
420 fs_reg::equals(const fs_reg &r) const
421 {
422 return (file == r.file &&
423 reg == r.reg &&
424 reg_offset == r.reg_offset &&
425 subreg_offset == r.subreg_offset &&
426 type == r.type &&
427 negate == r.negate &&
428 abs == r.abs &&
429 !reladdr && !r.reladdr &&
430 memcmp(&fixed_hw_reg, &r.fixed_hw_reg, sizeof(fixed_hw_reg)) == 0 &&
431 stride == r.stride);
432 }
433
434 fs_reg &
435 fs_reg::set_smear(unsigned subreg)
436 {
437 assert(file != HW_REG && file != IMM);
438 subreg_offset = subreg * type_sz(type);
439 stride = 0;
440 return *this;
441 }
442
443 bool
444 fs_reg::is_contiguous() const
445 {
446 return stride == 1;
447 }
448
449 unsigned
450 fs_reg::component_size(unsigned width) const
451 {
452 const unsigned stride = (file != HW_REG ? this->stride :
453 fixed_hw_reg.hstride == 0 ? 0 :
454 1 << (fixed_hw_reg.hstride - 1));
455 return MAX2(width * stride, 1) * type_sz(type);
456 }
457
458 int
459 fs_visitor::type_size(const struct glsl_type *type)
460 {
461 unsigned int size, i;
462
463 switch (type->base_type) {
464 case GLSL_TYPE_UINT:
465 case GLSL_TYPE_INT:
466 case GLSL_TYPE_FLOAT:
467 case GLSL_TYPE_BOOL:
468 return type->components();
469 case GLSL_TYPE_ARRAY:
470 return type_size(type->fields.array) * type->length;
471 case GLSL_TYPE_STRUCT:
472 size = 0;
473 for (i = 0; i < type->length; i++) {
474 size += type_size(type->fields.structure[i].type);
475 }
476 return size;
477 case GLSL_TYPE_SAMPLER:
478 /* Samplers take up no register space, since they're baked in at
479 * link time.
480 */
481 return 0;
482 case GLSL_TYPE_ATOMIC_UINT:
483 return 0;
484 case GLSL_TYPE_SUBROUTINE:
485 return 1;
486 case GLSL_TYPE_IMAGE:
487 case GLSL_TYPE_VOID:
488 case GLSL_TYPE_ERROR:
489 case GLSL_TYPE_INTERFACE:
490 case GLSL_TYPE_DOUBLE:
491 unreachable("not reached");
492 }
493
494 return 0;
495 }
496
497 /**
498 * Create a MOV to read the timestamp register.
499 *
500 * The caller is responsible for emitting the MOV. The return value is
501 * the destination of the MOV, with extra parameters set.
502 */
503 fs_reg
504 fs_visitor::get_timestamp(const fs_builder &bld)
505 {
506 assert(devinfo->gen >= 7);
507
508 fs_reg ts = fs_reg(retype(brw_vec4_reg(BRW_ARCHITECTURE_REGISTER_FILE,
509 BRW_ARF_TIMESTAMP,
510 0),
511 BRW_REGISTER_TYPE_UD));
512
513 fs_reg dst = fs_reg(GRF, alloc.allocate(1), BRW_REGISTER_TYPE_UD);
514
515 /* We want to read the 3 fields we care about even if it's not enabled in
516 * the dispatch.
517 */
518 bld.group(4, 0).exec_all().MOV(dst, ts);
519
520 /* The caller wants the low 32 bits of the timestamp. Since it's running
521 * at the GPU clock rate of ~1.2ghz, it will roll over every ~3 seconds,
522 * which is plenty of time for our purposes. It is identical across the
523 * EUs, but since it's tracking GPU core speed it will increment at a
524 * varying rate as render P-states change.
525 *
526 * The caller could also check if render P-states have changed (or anything
527 * else that might disrupt timing) by setting smear to 2 and checking if
528 * that field is != 0.
529 */
530 dst.set_smear(0);
531
532 return dst;
533 }
534
535 void
536 fs_visitor::emit_shader_time_begin()
537 {
538 shader_start_time = get_timestamp(bld.annotate("shader time start"));
539 }
540
541 void
542 fs_visitor::emit_shader_time_end()
543 {
544 /* Insert our code just before the final SEND with EOT. */
545 exec_node *end = this->instructions.get_tail();
546 assert(end && ((fs_inst *) end)->eot);
547 const fs_builder ibld = bld.annotate("shader time end")
548 .exec_all().at(NULL, end);
549
550 fs_reg shader_end_time = get_timestamp(ibld);
551
552 /* Check that there weren't any timestamp reset events (assuming these
553 * were the only two timestamp reads that happened).
554 */
555 fs_reg reset = shader_end_time;
556 reset.set_smear(2);
557 set_condmod(BRW_CONDITIONAL_Z,
558 ibld.AND(ibld.null_reg_ud(), reset, fs_reg(1u)));
559 ibld.IF(BRW_PREDICATE_NORMAL);
560
561 fs_reg start = shader_start_time;
562 start.negate = true;
563 fs_reg diff = fs_reg(GRF, alloc.allocate(1), BRW_REGISTER_TYPE_UD);
564 diff.set_smear(0);
565
566 const fs_builder cbld = ibld.group(1, 0);
567 cbld.group(1, 0).ADD(diff, start, shader_end_time);
568
569 /* If there were no instructions between the two timestamp gets, the diff
570 * is 2 cycles. Remove that overhead, so I can forget about that when
571 * trying to determine the time taken for single instructions.
572 */
573 cbld.ADD(diff, diff, fs_reg(-2u));
574 SHADER_TIME_ADD(cbld, 0, diff);
575 SHADER_TIME_ADD(cbld, 1, fs_reg(1u));
576 ibld.emit(BRW_OPCODE_ELSE);
577 SHADER_TIME_ADD(cbld, 2, fs_reg(1u));
578 ibld.emit(BRW_OPCODE_ENDIF);
579 }
580
581 void
582 fs_visitor::SHADER_TIME_ADD(const fs_builder &bld,
583 int shader_time_subindex,
584 fs_reg value)
585 {
586 int index = shader_time_index * 3 + shader_time_subindex;
587 fs_reg offset = fs_reg(index * SHADER_TIME_STRIDE);
588
589 fs_reg payload;
590 if (dispatch_width == 8)
591 payload = vgrf(glsl_type::uvec2_type);
592 else
593 payload = vgrf(glsl_type::uint_type);
594
595 bld.emit(SHADER_OPCODE_SHADER_TIME_ADD, fs_reg(), payload, offset, value);
596 }
597
598 void
599 fs_visitor::vfail(const char *format, va_list va)
600 {
601 char *msg;
602
603 if (failed)
604 return;
605
606 failed = true;
607
608 msg = ralloc_vasprintf(mem_ctx, format, va);
609 msg = ralloc_asprintf(mem_ctx, "%s compile failed: %s\n", stage_abbrev, msg);
610
611 this->fail_msg = msg;
612
613 if (debug_enabled) {
614 fprintf(stderr, "%s", msg);
615 }
616 }
617
618 void
619 fs_visitor::fail(const char *format, ...)
620 {
621 va_list va;
622
623 va_start(va, format);
624 vfail(format, va);
625 va_end(va);
626 }
627
628 /**
629 * Mark this program as impossible to compile in SIMD16 mode.
630 *
631 * During the SIMD8 compile (which happens first), we can detect and flag
632 * things that are unsupported in SIMD16 mode, so the compiler can skip
633 * the SIMD16 compile altogether.
634 *
635 * During a SIMD16 compile (if one happens anyway), this just calls fail().
636 */
637 void
638 fs_visitor::no16(const char *msg)
639 {
640 if (dispatch_width == 16) {
641 fail("%s", msg);
642 } else {
643 simd16_unsupported = true;
644
645 compiler->shader_perf_log(log_data,
646 "SIMD16 shader failed to compile: %s", msg);
647 }
648 }
649
650 /**
651 * Returns true if the instruction has a flag that means it won't
652 * update an entire destination register.
653 *
654 * For example, dead code elimination and live variable analysis want to know
655 * when a write to a variable screens off any preceding values that were in
656 * it.
657 */
658 bool
659 fs_inst::is_partial_write() const
660 {
661 return ((this->predicate && this->opcode != BRW_OPCODE_SEL) ||
662 (this->exec_size * type_sz(this->dst.type)) < 32 ||
663 !this->dst.is_contiguous());
664 }
665
666 unsigned
667 fs_inst::components_read(unsigned i) const
668 {
669 switch (opcode) {
670 case FS_OPCODE_LINTERP:
671 if (i == 0)
672 return 2;
673 else
674 return 1;
675
676 case FS_OPCODE_PIXEL_X:
677 case FS_OPCODE_PIXEL_Y:
678 assert(i == 0);
679 return 2;
680
681 case FS_OPCODE_FB_WRITE_LOGICAL:
682 assert(src[6].file == IMM);
683 /* First/second FB write color. */
684 if (i < 2)
685 return src[6].fixed_hw_reg.dw1.ud;
686 else
687 return 1;
688
689 default:
690 return 1;
691 }
692 }
693
694 int
695 fs_inst::regs_read(int arg) const
696 {
697 switch (opcode) {
698 case FS_OPCODE_FB_WRITE:
699 case SHADER_OPCODE_URB_WRITE_SIMD8:
700 case SHADER_OPCODE_UNTYPED_ATOMIC:
701 case SHADER_OPCODE_UNTYPED_SURFACE_READ:
702 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
703 case SHADER_OPCODE_TYPED_ATOMIC:
704 case SHADER_OPCODE_TYPED_SURFACE_READ:
705 case SHADER_OPCODE_TYPED_SURFACE_WRITE:
706 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
707 if (arg == 0)
708 return mlen;
709 break;
710
711 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7:
712 /* The payload is actually stored in src1 */
713 if (arg == 1)
714 return mlen;
715 break;
716
717 case FS_OPCODE_LINTERP:
718 if (arg == 1)
719 return 1;
720 break;
721
722 case SHADER_OPCODE_LOAD_PAYLOAD:
723 if (arg < this->header_size)
724 return 1;
725 break;
726
727 case CS_OPCODE_CS_TERMINATE:
728 return 1;
729
730 default:
731 if (is_tex() && arg == 0 && src[0].file == GRF)
732 return mlen;
733 break;
734 }
735
736 switch (src[arg].file) {
737 case BAD_FILE:
738 return 0;
739 case UNIFORM:
740 case IMM:
741 return 1;
742 case GRF:
743 case HW_REG:
744 return DIV_ROUND_UP(components_read(arg) *
745 src[arg].component_size(exec_size),
746 REG_SIZE);
747 case MRF:
748 unreachable("MRF registers are not allowed as sources");
749 default:
750 unreachable("Invalid register file");
751 }
752 }
753
754 bool
755 fs_inst::reads_flag() const
756 {
757 return predicate;
758 }
759
760 bool
761 fs_inst::writes_flag() const
762 {
763 return (conditional_mod && (opcode != BRW_OPCODE_SEL &&
764 opcode != BRW_OPCODE_IF &&
765 opcode != BRW_OPCODE_WHILE)) ||
766 opcode == FS_OPCODE_MOV_DISPATCH_TO_FLAGS;
767 }
768
769 /**
770 * Returns how many MRFs an FS opcode will write over.
771 *
772 * Note that this is not the 0 or 1 implied writes in an actual gen
773 * instruction -- the FS opcodes often generate MOVs in addition.
774 */
775 int
776 fs_visitor::implied_mrf_writes(fs_inst *inst)
777 {
778 if (inst->mlen == 0)
779 return 0;
780
781 if (inst->base_mrf == -1)
782 return 0;
783
784 switch (inst->opcode) {
785 case SHADER_OPCODE_RCP:
786 case SHADER_OPCODE_RSQ:
787 case SHADER_OPCODE_SQRT:
788 case SHADER_OPCODE_EXP2:
789 case SHADER_OPCODE_LOG2:
790 case SHADER_OPCODE_SIN:
791 case SHADER_OPCODE_COS:
792 return 1 * dispatch_width / 8;
793 case SHADER_OPCODE_POW:
794 case SHADER_OPCODE_INT_QUOTIENT:
795 case SHADER_OPCODE_INT_REMAINDER:
796 return 2 * dispatch_width / 8;
797 case SHADER_OPCODE_TEX:
798 case FS_OPCODE_TXB:
799 case SHADER_OPCODE_TXD:
800 case SHADER_OPCODE_TXF:
801 case SHADER_OPCODE_TXF_CMS:
802 case SHADER_OPCODE_TXF_MCS:
803 case SHADER_OPCODE_TG4:
804 case SHADER_OPCODE_TG4_OFFSET:
805 case SHADER_OPCODE_TXL:
806 case SHADER_OPCODE_TXS:
807 case SHADER_OPCODE_LOD:
808 return 1;
809 case FS_OPCODE_FB_WRITE:
810 return 2;
811 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
812 case SHADER_OPCODE_GEN4_SCRATCH_READ:
813 return 1;
814 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD:
815 return inst->mlen;
816 case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
817 return inst->mlen;
818 case SHADER_OPCODE_UNTYPED_ATOMIC:
819 case SHADER_OPCODE_UNTYPED_SURFACE_READ:
820 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
821 case SHADER_OPCODE_TYPED_ATOMIC:
822 case SHADER_OPCODE_TYPED_SURFACE_READ:
823 case SHADER_OPCODE_TYPED_SURFACE_WRITE:
824 case SHADER_OPCODE_URB_WRITE_SIMD8:
825 case FS_OPCODE_INTERPOLATE_AT_CENTROID:
826 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
827 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
828 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
829 return 0;
830 default:
831 unreachable("not reached");
832 }
833 }
834
835 fs_reg
836 fs_visitor::vgrf(const glsl_type *const type)
837 {
838 int reg_width = dispatch_width / 8;
839 return fs_reg(GRF, alloc.allocate(type_size(type) * reg_width),
840 brw_type_for_base_type(type));
841 }
842
843 /** Fixed HW reg constructor. */
844 fs_reg::fs_reg(enum register_file file, int reg)
845 {
846 init();
847 this->file = file;
848 this->reg = reg;
849 this->type = BRW_REGISTER_TYPE_F;
850 this->stride = (file == UNIFORM ? 0 : 1);
851 }
852
853 /** Fixed HW reg constructor. */
854 fs_reg::fs_reg(enum register_file file, int reg, enum brw_reg_type type)
855 {
856 init();
857 this->file = file;
858 this->reg = reg;
859 this->type = type;
860 this->stride = (file == UNIFORM ? 0 : 1);
861 }
862
863 /* For SIMD16, we need to follow from the uniform setup of SIMD8 dispatch.
864 * This brings in those uniform definitions
865 */
866 void
867 fs_visitor::import_uniforms(fs_visitor *v)
868 {
869 this->push_constant_loc = v->push_constant_loc;
870 this->pull_constant_loc = v->pull_constant_loc;
871 this->uniforms = v->uniforms;
872 this->param_size = v->param_size;
873 }
874
875 fs_reg *
876 fs_visitor::emit_fragcoord_interpolation(bool pixel_center_integer,
877 bool origin_upper_left)
878 {
879 assert(stage == MESA_SHADER_FRAGMENT);
880 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
881 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::vec4_type));
882 fs_reg wpos = *reg;
883 bool flip = !origin_upper_left ^ key->render_to_fbo;
884
885 /* gl_FragCoord.x */
886 if (pixel_center_integer) {
887 bld.MOV(wpos, this->pixel_x);
888 } else {
889 bld.ADD(wpos, this->pixel_x, fs_reg(0.5f));
890 }
891 wpos = offset(wpos, bld, 1);
892
893 /* gl_FragCoord.y */
894 if (!flip && pixel_center_integer) {
895 bld.MOV(wpos, this->pixel_y);
896 } else {
897 fs_reg pixel_y = this->pixel_y;
898 float offset = (pixel_center_integer ? 0.0 : 0.5);
899
900 if (flip) {
901 pixel_y.negate = true;
902 offset += key->drawable_height - 1.0;
903 }
904
905 bld.ADD(wpos, pixel_y, fs_reg(offset));
906 }
907 wpos = offset(wpos, bld, 1);
908
909 /* gl_FragCoord.z */
910 if (devinfo->gen >= 6) {
911 bld.MOV(wpos, fs_reg(brw_vec8_grf(payload.source_depth_reg, 0)));
912 } else {
913 bld.emit(FS_OPCODE_LINTERP, wpos,
914 this->delta_xy[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
915 interp_reg(VARYING_SLOT_POS, 2));
916 }
917 wpos = offset(wpos, bld, 1);
918
919 /* gl_FragCoord.w: Already set up in emit_interpolation */
920 bld.MOV(wpos, this->wpos_w);
921
922 return reg;
923 }
924
925 fs_inst *
926 fs_visitor::emit_linterp(const fs_reg &attr, const fs_reg &interp,
927 glsl_interp_qualifier interpolation_mode,
928 bool is_centroid, bool is_sample)
929 {
930 brw_wm_barycentric_interp_mode barycoord_mode;
931 if (devinfo->gen >= 6) {
932 if (is_centroid) {
933 if (interpolation_mode == INTERP_QUALIFIER_SMOOTH)
934 barycoord_mode = BRW_WM_PERSPECTIVE_CENTROID_BARYCENTRIC;
935 else
936 barycoord_mode = BRW_WM_NONPERSPECTIVE_CENTROID_BARYCENTRIC;
937 } else if (is_sample) {
938 if (interpolation_mode == INTERP_QUALIFIER_SMOOTH)
939 barycoord_mode = BRW_WM_PERSPECTIVE_SAMPLE_BARYCENTRIC;
940 else
941 barycoord_mode = BRW_WM_NONPERSPECTIVE_SAMPLE_BARYCENTRIC;
942 } else {
943 if (interpolation_mode == INTERP_QUALIFIER_SMOOTH)
944 barycoord_mode = BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC;
945 else
946 barycoord_mode = BRW_WM_NONPERSPECTIVE_PIXEL_BARYCENTRIC;
947 }
948 } else {
949 /* On Ironlake and below, there is only one interpolation mode.
950 * Centroid interpolation doesn't mean anything on this hardware --
951 * there is no multisampling.
952 */
953 barycoord_mode = BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC;
954 }
955 return bld.emit(FS_OPCODE_LINTERP, attr,
956 this->delta_xy[barycoord_mode], interp);
957 }
958
959 void
960 fs_visitor::emit_general_interpolation(fs_reg attr, const char *name,
961 const glsl_type *type,
962 glsl_interp_qualifier interpolation_mode,
963 int location, bool mod_centroid,
964 bool mod_sample)
965 {
966 attr.type = brw_type_for_base_type(type->get_scalar_type());
967
968 assert(stage == MESA_SHADER_FRAGMENT);
969 brw_wm_prog_data *prog_data = (brw_wm_prog_data*) this->prog_data;
970 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
971
972 unsigned int array_elements;
973
974 if (type->is_array()) {
975 array_elements = type->length;
976 if (array_elements == 0) {
977 fail("dereferenced array '%s' has length 0\n", name);
978 }
979 type = type->fields.array;
980 } else {
981 array_elements = 1;
982 }
983
984 if (interpolation_mode == INTERP_QUALIFIER_NONE) {
985 bool is_gl_Color =
986 location == VARYING_SLOT_COL0 || location == VARYING_SLOT_COL1;
987 if (key->flat_shade && is_gl_Color) {
988 interpolation_mode = INTERP_QUALIFIER_FLAT;
989 } else {
990 interpolation_mode = INTERP_QUALIFIER_SMOOTH;
991 }
992 }
993
994 for (unsigned int i = 0; i < array_elements; i++) {
995 for (unsigned int j = 0; j < type->matrix_columns; j++) {
996 if (prog_data->urb_setup[location] == -1) {
997 /* If there's no incoming setup data for this slot, don't
998 * emit interpolation for it.
999 */
1000 attr = offset(attr, bld, type->vector_elements);
1001 location++;
1002 continue;
1003 }
1004
1005 if (interpolation_mode == INTERP_QUALIFIER_FLAT) {
1006 /* Constant interpolation (flat shading) case. The SF has
1007 * handed us defined values in only the constant offset
1008 * field of the setup reg.
1009 */
1010 for (unsigned int k = 0; k < type->vector_elements; k++) {
1011 struct brw_reg interp = interp_reg(location, k);
1012 interp = suboffset(interp, 3);
1013 interp.type = attr.type;
1014 bld.emit(FS_OPCODE_CINTERP, attr, fs_reg(interp));
1015 attr = offset(attr, bld, 1);
1016 }
1017 } else {
1018 /* Smooth/noperspective interpolation case. */
1019 for (unsigned int k = 0; k < type->vector_elements; k++) {
1020 struct brw_reg interp = interp_reg(location, k);
1021 if (devinfo->needs_unlit_centroid_workaround && mod_centroid) {
1022 /* Get the pixel/sample mask into f0 so that we know
1023 * which pixels are lit. Then, for each channel that is
1024 * unlit, replace the centroid data with non-centroid
1025 * data.
1026 */
1027 bld.emit(FS_OPCODE_MOV_DISPATCH_TO_FLAGS);
1028
1029 fs_inst *inst;
1030 inst = emit_linterp(attr, fs_reg(interp), interpolation_mode,
1031 false, false);
1032 inst->predicate = BRW_PREDICATE_NORMAL;
1033 inst->predicate_inverse = true;
1034 if (devinfo->has_pln)
1035 inst->no_dd_clear = true;
1036
1037 inst = emit_linterp(attr, fs_reg(interp), interpolation_mode,
1038 mod_centroid && !key->persample_shading,
1039 mod_sample || key->persample_shading);
1040 inst->predicate = BRW_PREDICATE_NORMAL;
1041 inst->predicate_inverse = false;
1042 if (devinfo->has_pln)
1043 inst->no_dd_check = true;
1044
1045 } else {
1046 emit_linterp(attr, fs_reg(interp), interpolation_mode,
1047 mod_centroid && !key->persample_shading,
1048 mod_sample || key->persample_shading);
1049 }
1050 if (devinfo->gen < 6 && interpolation_mode == INTERP_QUALIFIER_SMOOTH) {
1051 bld.MUL(attr, attr, this->pixel_w);
1052 }
1053 attr = offset(attr, bld, 1);
1054 }
1055
1056 }
1057 location++;
1058 }
1059 }
1060 }
1061
1062 fs_reg *
1063 fs_visitor::emit_frontfacing_interpolation()
1064 {
1065 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::bool_type));
1066
1067 if (devinfo->gen >= 6) {
1068 /* Bit 15 of g0.0 is 0 if the polygon is front facing. We want to create
1069 * a boolean result from this (~0/true or 0/false).
1070 *
1071 * We can use the fact that bit 15 is the MSB of g0.0:W to accomplish
1072 * this task in only one instruction:
1073 * - a negation source modifier will flip the bit; and
1074 * - a W -> D type conversion will sign extend the bit into the high
1075 * word of the destination.
1076 *
1077 * An ASR 15 fills the low word of the destination.
1078 */
1079 fs_reg g0 = fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_W));
1080 g0.negate = true;
1081
1082 bld.ASR(*reg, g0, fs_reg(15));
1083 } else {
1084 /* Bit 31 of g1.6 is 0 if the polygon is front facing. We want to create
1085 * a boolean result from this (1/true or 0/false).
1086 *
1087 * Like in the above case, since the bit is the MSB of g1.6:UD we can use
1088 * the negation source modifier to flip it. Unfortunately the SHR
1089 * instruction only operates on UD (or D with an abs source modifier)
1090 * sources without negation.
1091 *
1092 * Instead, use ASR (which will give ~0/true or 0/false).
1093 */
1094 fs_reg g1_6 = fs_reg(retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_D));
1095 g1_6.negate = true;
1096
1097 bld.ASR(*reg, g1_6, fs_reg(31));
1098 }
1099
1100 return reg;
1101 }
1102
1103 void
1104 fs_visitor::compute_sample_position(fs_reg dst, fs_reg int_sample_pos)
1105 {
1106 assert(stage == MESA_SHADER_FRAGMENT);
1107 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1108 assert(dst.type == BRW_REGISTER_TYPE_F);
1109
1110 if (key->compute_pos_offset) {
1111 /* Convert int_sample_pos to floating point */
1112 bld.MOV(dst, int_sample_pos);
1113 /* Scale to the range [0, 1] */
1114 bld.MUL(dst, dst, fs_reg(1 / 16.0f));
1115 }
1116 else {
1117 /* From ARB_sample_shading specification:
1118 * "When rendering to a non-multisample buffer, or if multisample
1119 * rasterization is disabled, gl_SamplePosition will always be
1120 * (0.5, 0.5).
1121 */
1122 bld.MOV(dst, fs_reg(0.5f));
1123 }
1124 }
1125
1126 fs_reg *
1127 fs_visitor::emit_samplepos_setup()
1128 {
1129 assert(devinfo->gen >= 6);
1130
1131 const fs_builder abld = bld.annotate("compute sample position");
1132 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::vec2_type));
1133 fs_reg pos = *reg;
1134 fs_reg int_sample_x = vgrf(glsl_type::int_type);
1135 fs_reg int_sample_y = vgrf(glsl_type::int_type);
1136
1137 /* WM will be run in MSDISPMODE_PERSAMPLE. So, only one of SIMD8 or SIMD16
1138 * mode will be enabled.
1139 *
1140 * From the Ivy Bridge PRM, volume 2 part 1, page 344:
1141 * R31.1:0 Position Offset X/Y for Slot[3:0]
1142 * R31.3:2 Position Offset X/Y for Slot[7:4]
1143 * .....
1144 *
1145 * The X, Y sample positions come in as bytes in thread payload. So, read
1146 * the positions using vstride=16, width=8, hstride=2.
1147 */
1148 struct brw_reg sample_pos_reg =
1149 stride(retype(brw_vec1_grf(payload.sample_pos_reg, 0),
1150 BRW_REGISTER_TYPE_B), 16, 8, 2);
1151
1152 if (dispatch_width == 8) {
1153 abld.MOV(int_sample_x, fs_reg(sample_pos_reg));
1154 } else {
1155 abld.half(0).MOV(half(int_sample_x, 0), fs_reg(sample_pos_reg));
1156 abld.half(1).MOV(half(int_sample_x, 1),
1157 fs_reg(suboffset(sample_pos_reg, 16)));
1158 }
1159 /* Compute gl_SamplePosition.x */
1160 compute_sample_position(pos, int_sample_x);
1161 pos = offset(pos, abld, 1);
1162 if (dispatch_width == 8) {
1163 abld.MOV(int_sample_y, fs_reg(suboffset(sample_pos_reg, 1)));
1164 } else {
1165 abld.half(0).MOV(half(int_sample_y, 0),
1166 fs_reg(suboffset(sample_pos_reg, 1)));
1167 abld.half(1).MOV(half(int_sample_y, 1),
1168 fs_reg(suboffset(sample_pos_reg, 17)));
1169 }
1170 /* Compute gl_SamplePosition.y */
1171 compute_sample_position(pos, int_sample_y);
1172 return reg;
1173 }
1174
1175 fs_reg *
1176 fs_visitor::emit_sampleid_setup()
1177 {
1178 assert(stage == MESA_SHADER_FRAGMENT);
1179 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1180 assert(devinfo->gen >= 6);
1181
1182 const fs_builder abld = bld.annotate("compute sample id");
1183 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::int_type));
1184
1185 if (key->compute_sample_id) {
1186 fs_reg t1 = vgrf(glsl_type::int_type);
1187 fs_reg t2 = vgrf(glsl_type::int_type);
1188 t2.type = BRW_REGISTER_TYPE_UW;
1189
1190 /* The PS will be run in MSDISPMODE_PERSAMPLE. For example with
1191 * 8x multisampling, subspan 0 will represent sample N (where N
1192 * is 0, 2, 4 or 6), subspan 1 will represent sample 1, 3, 5 or
1193 * 7. We can find the value of N by looking at R0.0 bits 7:6
1194 * ("Starting Sample Pair Index (SSPI)") and multiplying by two
1195 * (since samples are always delivered in pairs). That is, we
1196 * compute 2*((R0.0 & 0xc0) >> 6) == (R0.0 & 0xc0) >> 5. Then
1197 * we need to add N to the sequence (0, 0, 0, 0, 1, 1, 1, 1) in
1198 * case of SIMD8 and sequence (0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2,
1199 * 2, 3, 3, 3, 3) in case of SIMD16. We compute this sequence by
1200 * populating a temporary variable with the sequence (0, 1, 2, 3),
1201 * and then reading from it using vstride=1, width=4, hstride=0.
1202 * These computations hold good for 4x multisampling as well.
1203 *
1204 * For 2x MSAA and SIMD16, we want to use the sequence (0, 1, 0, 1):
1205 * the first four slots are sample 0 of subspan 0; the next four
1206 * are sample 1 of subspan 0; the third group is sample 0 of
1207 * subspan 1, and finally sample 1 of subspan 1.
1208 */
1209 abld.exec_all()
1210 .AND(t1, fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
1211 fs_reg(0xc0));
1212 abld.exec_all().SHR(t1, t1, fs_reg(5));
1213
1214 /* This works for both SIMD8 and SIMD16 */
1215 abld.exec_all()
1216 .MOV(t2, brw_imm_v(key->persample_2x ? 0x1010 : 0x3210));
1217
1218 /* This special instruction takes care of setting vstride=1,
1219 * width=4, hstride=0 of t2 during an ADD instruction.
1220 */
1221 abld.emit(FS_OPCODE_SET_SAMPLE_ID, *reg, t1, t2);
1222 } else {
1223 /* As per GL_ARB_sample_shading specification:
1224 * "When rendering to a non-multisample buffer, or if multisample
1225 * rasterization is disabled, gl_SampleID will always be zero."
1226 */
1227 abld.MOV(*reg, fs_reg(0));
1228 }
1229
1230 return reg;
1231 }
1232
1233 void
1234 fs_visitor::resolve_source_modifiers(fs_reg *src)
1235 {
1236 if (!src->abs && !src->negate)
1237 return;
1238
1239 fs_reg temp = bld.vgrf(src->type);
1240 bld.MOV(temp, *src);
1241 *src = temp;
1242 }
1243
1244 void
1245 fs_visitor::emit_discard_jump()
1246 {
1247 assert(((brw_wm_prog_data*) this->prog_data)->uses_kill);
1248
1249 /* For performance, after a discard, jump to the end of the
1250 * shader if all relevant channels have been discarded.
1251 */
1252 fs_inst *discard_jump = bld.emit(FS_OPCODE_DISCARD_JUMP);
1253 discard_jump->flag_subreg = 1;
1254
1255 discard_jump->predicate = (dispatch_width == 8)
1256 ? BRW_PREDICATE_ALIGN1_ANY8H
1257 : BRW_PREDICATE_ALIGN1_ANY16H;
1258 discard_jump->predicate_inverse = true;
1259 }
1260
1261 void
1262 fs_visitor::assign_curb_setup()
1263 {
1264 if (dispatch_width == 8) {
1265 prog_data->dispatch_grf_start_reg = payload.num_regs;
1266 } else {
1267 if (stage == MESA_SHADER_FRAGMENT) {
1268 brw_wm_prog_data *prog_data = (brw_wm_prog_data*) this->prog_data;
1269 prog_data->dispatch_grf_start_reg_16 = payload.num_regs;
1270 } else if (stage == MESA_SHADER_COMPUTE) {
1271 brw_cs_prog_data *prog_data = (brw_cs_prog_data*) this->prog_data;
1272 prog_data->dispatch_grf_start_reg_16 = payload.num_regs;
1273 } else {
1274 unreachable("Unsupported shader type!");
1275 }
1276 }
1277
1278 prog_data->curb_read_length = ALIGN(stage_prog_data->nr_params, 8) / 8;
1279
1280 /* Map the offsets in the UNIFORM file to fixed HW regs. */
1281 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1282 for (unsigned int i = 0; i < inst->sources; i++) {
1283 if (inst->src[i].file == UNIFORM) {
1284 int uniform_nr = inst->src[i].reg + inst->src[i].reg_offset;
1285 int constant_nr;
1286 if (uniform_nr >= 0 && uniform_nr < (int) uniforms) {
1287 constant_nr = push_constant_loc[uniform_nr];
1288 } else {
1289 /* Section 5.11 of the OpenGL 4.1 spec says:
1290 * "Out-of-bounds reads return undefined values, which include
1291 * values from other variables of the active program or zero."
1292 * Just return the first push constant.
1293 */
1294 constant_nr = 0;
1295 }
1296
1297 struct brw_reg brw_reg = brw_vec1_grf(payload.num_regs +
1298 constant_nr / 8,
1299 constant_nr % 8);
1300
1301 assert(inst->src[i].stride == 0);
1302 inst->src[i].file = HW_REG;
1303 inst->src[i].fixed_hw_reg = byte_offset(
1304 retype(brw_reg, inst->src[i].type),
1305 inst->src[i].subreg_offset);
1306 }
1307 }
1308 }
1309 }
1310
1311 void
1312 fs_visitor::calculate_urb_setup()
1313 {
1314 assert(stage == MESA_SHADER_FRAGMENT);
1315 brw_wm_prog_data *prog_data = (brw_wm_prog_data*) this->prog_data;
1316 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1317
1318 memset(prog_data->urb_setup, -1,
1319 sizeof(prog_data->urb_setup[0]) * VARYING_SLOT_MAX);
1320
1321 int urb_next = 0;
1322 /* Figure out where each of the incoming setup attributes lands. */
1323 if (devinfo->gen >= 6) {
1324 if (_mesa_bitcount_64(prog->InputsRead &
1325 BRW_FS_VARYING_INPUT_MASK) <= 16) {
1326 /* The SF/SBE pipeline stage can do arbitrary rearrangement of the
1327 * first 16 varying inputs, so we can put them wherever we want.
1328 * Just put them in order.
1329 *
1330 * This is useful because it means that (a) inputs not used by the
1331 * fragment shader won't take up valuable register space, and (b) we
1332 * won't have to recompile the fragment shader if it gets paired with
1333 * a different vertex (or geometry) shader.
1334 */
1335 for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1336 if (prog->InputsRead & BRW_FS_VARYING_INPUT_MASK &
1337 BITFIELD64_BIT(i)) {
1338 prog_data->urb_setup[i] = urb_next++;
1339 }
1340 }
1341 } else {
1342 /* We have enough input varyings that the SF/SBE pipeline stage can't
1343 * arbitrarily rearrange them to suit our whim; we have to put them
1344 * in an order that matches the output of the previous pipeline stage
1345 * (geometry or vertex shader).
1346 */
1347 struct brw_vue_map prev_stage_vue_map;
1348 brw_compute_vue_map(devinfo, &prev_stage_vue_map,
1349 key->input_slots_valid);
1350 int first_slot = 2 * BRW_SF_URB_ENTRY_READ_OFFSET;
1351 assert(prev_stage_vue_map.num_slots <= first_slot + 32);
1352 for (int slot = first_slot; slot < prev_stage_vue_map.num_slots;
1353 slot++) {
1354 int varying = prev_stage_vue_map.slot_to_varying[slot];
1355 /* Note that varying == BRW_VARYING_SLOT_COUNT when a slot is
1356 * unused.
1357 */
1358 if (varying != BRW_VARYING_SLOT_COUNT &&
1359 (prog->InputsRead & BRW_FS_VARYING_INPUT_MASK &
1360 BITFIELD64_BIT(varying))) {
1361 prog_data->urb_setup[varying] = slot - first_slot;
1362 }
1363 }
1364 urb_next = prev_stage_vue_map.num_slots - first_slot;
1365 }
1366 } else {
1367 /* FINISHME: The sf doesn't map VS->FS inputs for us very well. */
1368 for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1369 /* Point size is packed into the header, not as a general attribute */
1370 if (i == VARYING_SLOT_PSIZ)
1371 continue;
1372
1373 if (key->input_slots_valid & BITFIELD64_BIT(i)) {
1374 /* The back color slot is skipped when the front color is
1375 * also written to. In addition, some slots can be
1376 * written in the vertex shader and not read in the
1377 * fragment shader. So the register number must always be
1378 * incremented, mapped or not.
1379 */
1380 if (_mesa_varying_slot_in_fs((gl_varying_slot) i))
1381 prog_data->urb_setup[i] = urb_next;
1382 urb_next++;
1383 }
1384 }
1385
1386 /*
1387 * It's a FS only attribute, and we did interpolation for this attribute
1388 * in SF thread. So, count it here, too.
1389 *
1390 * See compile_sf_prog() for more info.
1391 */
1392 if (prog->InputsRead & BITFIELD64_BIT(VARYING_SLOT_PNTC))
1393 prog_data->urb_setup[VARYING_SLOT_PNTC] = urb_next++;
1394 }
1395
1396 prog_data->num_varying_inputs = urb_next;
1397 }
1398
1399 void
1400 fs_visitor::assign_urb_setup()
1401 {
1402 assert(stage == MESA_SHADER_FRAGMENT);
1403 brw_wm_prog_data *prog_data = (brw_wm_prog_data*) this->prog_data;
1404
1405 int urb_start = payload.num_regs + prog_data->base.curb_read_length;
1406
1407 /* Offset all the urb_setup[] index by the actual position of the
1408 * setup regs, now that the location of the constants has been chosen.
1409 */
1410 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1411 if (inst->opcode == FS_OPCODE_LINTERP) {
1412 assert(inst->src[1].file == HW_REG);
1413 inst->src[1].fixed_hw_reg.nr += urb_start;
1414 }
1415
1416 if (inst->opcode == FS_OPCODE_CINTERP) {
1417 assert(inst->src[0].file == HW_REG);
1418 inst->src[0].fixed_hw_reg.nr += urb_start;
1419 }
1420 }
1421
1422 /* Each attribute is 4 setup channels, each of which is half a reg. */
1423 this->first_non_payload_grf =
1424 urb_start + prog_data->num_varying_inputs * 2;
1425 }
1426
1427 void
1428 fs_visitor::assign_vs_urb_setup()
1429 {
1430 brw_vs_prog_data *vs_prog_data = (brw_vs_prog_data *) prog_data;
1431 int grf, count, slot, channel, attr;
1432
1433 assert(stage == MESA_SHADER_VERTEX);
1434 count = _mesa_bitcount_64(vs_prog_data->inputs_read);
1435 if (vs_prog_data->uses_vertexid || vs_prog_data->uses_instanceid)
1436 count++;
1437
1438 /* Each attribute is 4 regs. */
1439 this->first_non_payload_grf =
1440 payload.num_regs + prog_data->curb_read_length + count * 4;
1441
1442 unsigned vue_entries =
1443 MAX2(count, vs_prog_data->base.vue_map.num_slots);
1444
1445 vs_prog_data->base.urb_entry_size = ALIGN(vue_entries, 4) / 4;
1446 vs_prog_data->base.urb_read_length = (count + 1) / 2;
1447
1448 assert(vs_prog_data->base.urb_read_length <= 15);
1449
1450 /* Rewrite all ATTR file references to the hw grf that they land in. */
1451 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1452 for (int i = 0; i < inst->sources; i++) {
1453 if (inst->src[i].file == ATTR) {
1454
1455 if (inst->src[i].reg == VERT_ATTRIB_MAX) {
1456 slot = count - 1;
1457 } else {
1458 /* Attributes come in in a contiguous block, ordered by their
1459 * gl_vert_attrib value. That means we can compute the slot
1460 * number for an attribute by masking out the enabled
1461 * attributes before it and counting the bits.
1462 */
1463 attr = inst->src[i].reg + inst->src[i].reg_offset / 4;
1464 slot = _mesa_bitcount_64(vs_prog_data->inputs_read &
1465 BITFIELD64_MASK(attr));
1466 }
1467
1468 channel = inst->src[i].reg_offset & 3;
1469
1470 grf = payload.num_regs +
1471 prog_data->curb_read_length +
1472 slot * 4 + channel;
1473
1474 inst->src[i].file = HW_REG;
1475 inst->src[i].fixed_hw_reg =
1476 retype(brw_vec8_grf(grf, 0), inst->src[i].type);
1477 }
1478 }
1479 }
1480 }
1481
1482 /**
1483 * Split large virtual GRFs into separate components if we can.
1484 *
1485 * This is mostly duplicated with what brw_fs_vector_splitting does,
1486 * but that's really conservative because it's afraid of doing
1487 * splitting that doesn't result in real progress after the rest of
1488 * the optimization phases, which would cause infinite looping in
1489 * optimization. We can do it once here, safely. This also has the
1490 * opportunity to split interpolated values, or maybe even uniforms,
1491 * which we don't have at the IR level.
1492 *
1493 * We want to split, because virtual GRFs are what we register
1494 * allocate and spill (due to contiguousness requirements for some
1495 * instructions), and they're what we naturally generate in the
1496 * codegen process, but most virtual GRFs don't actually need to be
1497 * contiguous sets of GRFs. If we split, we'll end up with reduced
1498 * live intervals and better dead code elimination and coalescing.
1499 */
1500 void
1501 fs_visitor::split_virtual_grfs()
1502 {
1503 int num_vars = this->alloc.count;
1504
1505 /* Count the total number of registers */
1506 int reg_count = 0;
1507 int vgrf_to_reg[num_vars];
1508 for (int i = 0; i < num_vars; i++) {
1509 vgrf_to_reg[i] = reg_count;
1510 reg_count += alloc.sizes[i];
1511 }
1512
1513 /* An array of "split points". For each register slot, this indicates
1514 * if this slot can be separated from the previous slot. Every time an
1515 * instruction uses multiple elements of a register (as a source or
1516 * destination), we mark the used slots as inseparable. Then we go
1517 * through and split the registers into the smallest pieces we can.
1518 */
1519 bool split_points[reg_count];
1520 memset(split_points, 0, sizeof(split_points));
1521
1522 /* Mark all used registers as fully splittable */
1523 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1524 if (inst->dst.file == GRF) {
1525 int reg = vgrf_to_reg[inst->dst.reg];
1526 for (unsigned j = 1; j < this->alloc.sizes[inst->dst.reg]; j++)
1527 split_points[reg + j] = true;
1528 }
1529
1530 for (int i = 0; i < inst->sources; i++) {
1531 if (inst->src[i].file == GRF) {
1532 int reg = vgrf_to_reg[inst->src[i].reg];
1533 for (unsigned j = 1; j < this->alloc.sizes[inst->src[i].reg]; j++)
1534 split_points[reg + j] = true;
1535 }
1536 }
1537 }
1538
1539 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1540 if (inst->dst.file == GRF) {
1541 int reg = vgrf_to_reg[inst->dst.reg] + inst->dst.reg_offset;
1542 for (int j = 1; j < inst->regs_written; j++)
1543 split_points[reg + j] = false;
1544 }
1545 for (int i = 0; i < inst->sources; i++) {
1546 if (inst->src[i].file == GRF) {
1547 int reg = vgrf_to_reg[inst->src[i].reg] + inst->src[i].reg_offset;
1548 for (int j = 1; j < inst->regs_read(i); j++)
1549 split_points[reg + j] = false;
1550 }
1551 }
1552 }
1553
1554 int new_virtual_grf[reg_count];
1555 int new_reg_offset[reg_count];
1556
1557 int reg = 0;
1558 for (int i = 0; i < num_vars; i++) {
1559 /* The first one should always be 0 as a quick sanity check. */
1560 assert(split_points[reg] == false);
1561
1562 /* j = 0 case */
1563 new_reg_offset[reg] = 0;
1564 reg++;
1565 int offset = 1;
1566
1567 /* j > 0 case */
1568 for (unsigned j = 1; j < alloc.sizes[i]; j++) {
1569 /* If this is a split point, reset the offset to 0 and allocate a
1570 * new virtual GRF for the previous offset many registers
1571 */
1572 if (split_points[reg]) {
1573 assert(offset <= MAX_VGRF_SIZE);
1574 int grf = alloc.allocate(offset);
1575 for (int k = reg - offset; k < reg; k++)
1576 new_virtual_grf[k] = grf;
1577 offset = 0;
1578 }
1579 new_reg_offset[reg] = offset;
1580 offset++;
1581 reg++;
1582 }
1583
1584 /* The last one gets the original register number */
1585 assert(offset <= MAX_VGRF_SIZE);
1586 alloc.sizes[i] = offset;
1587 for (int k = reg - offset; k < reg; k++)
1588 new_virtual_grf[k] = i;
1589 }
1590 assert(reg == reg_count);
1591
1592 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1593 if (inst->dst.file == GRF) {
1594 reg = vgrf_to_reg[inst->dst.reg] + inst->dst.reg_offset;
1595 inst->dst.reg = new_virtual_grf[reg];
1596 inst->dst.reg_offset = new_reg_offset[reg];
1597 assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1598 }
1599 for (int i = 0; i < inst->sources; i++) {
1600 if (inst->src[i].file == GRF) {
1601 reg = vgrf_to_reg[inst->src[i].reg] + inst->src[i].reg_offset;
1602 inst->src[i].reg = new_virtual_grf[reg];
1603 inst->src[i].reg_offset = new_reg_offset[reg];
1604 assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1605 }
1606 }
1607 }
1608 invalidate_live_intervals();
1609 }
1610
1611 /**
1612 * Remove unused virtual GRFs and compact the virtual_grf_* arrays.
1613 *
1614 * During code generation, we create tons of temporary variables, many of
1615 * which get immediately killed and are never used again. Yet, in later
1616 * optimization and analysis passes, such as compute_live_intervals, we need
1617 * to loop over all the virtual GRFs. Compacting them can save a lot of
1618 * overhead.
1619 */
1620 bool
1621 fs_visitor::compact_virtual_grfs()
1622 {
1623 bool progress = false;
1624 int remap_table[this->alloc.count];
1625 memset(remap_table, -1, sizeof(remap_table));
1626
1627 /* Mark which virtual GRFs are used. */
1628 foreach_block_and_inst(block, const fs_inst, inst, cfg) {
1629 if (inst->dst.file == GRF)
1630 remap_table[inst->dst.reg] = 0;
1631
1632 for (int i = 0; i < inst->sources; i++) {
1633 if (inst->src[i].file == GRF)
1634 remap_table[inst->src[i].reg] = 0;
1635 }
1636 }
1637
1638 /* Compact the GRF arrays. */
1639 int new_index = 0;
1640 for (unsigned i = 0; i < this->alloc.count; i++) {
1641 if (remap_table[i] == -1) {
1642 /* We just found an unused register. This means that we are
1643 * actually going to compact something.
1644 */
1645 progress = true;
1646 } else {
1647 remap_table[i] = new_index;
1648 alloc.sizes[new_index] = alloc.sizes[i];
1649 invalidate_live_intervals();
1650 ++new_index;
1651 }
1652 }
1653
1654 this->alloc.count = new_index;
1655
1656 /* Patch all the instructions to use the newly renumbered registers */
1657 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1658 if (inst->dst.file == GRF)
1659 inst->dst.reg = remap_table[inst->dst.reg];
1660
1661 for (int i = 0; i < inst->sources; i++) {
1662 if (inst->src[i].file == GRF)
1663 inst->src[i].reg = remap_table[inst->src[i].reg];
1664 }
1665 }
1666
1667 /* Patch all the references to delta_xy, since they're used in register
1668 * allocation. If they're unused, switch them to BAD_FILE so we don't
1669 * think some random VGRF is delta_xy.
1670 */
1671 for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
1672 if (delta_xy[i].file == GRF) {
1673 if (remap_table[delta_xy[i].reg] != -1) {
1674 delta_xy[i].reg = remap_table[delta_xy[i].reg];
1675 } else {
1676 delta_xy[i].file = BAD_FILE;
1677 }
1678 }
1679 }
1680
1681 return progress;
1682 }
1683
1684 /*
1685 * Implements array access of uniforms by inserting a
1686 * PULL_CONSTANT_LOAD instruction.
1687 *
1688 * Unlike temporary GRF array access (where we don't support it due to
1689 * the difficulty of doing relative addressing on instruction
1690 * destinations), we could potentially do array access of uniforms
1691 * that were loaded in GRF space as push constants. In real-world
1692 * usage we've seen, though, the arrays being used are always larger
1693 * than we could load as push constants, so just always move all
1694 * uniform array access out to a pull constant buffer.
1695 */
1696 void
1697 fs_visitor::move_uniform_array_access_to_pull_constants()
1698 {
1699 if (dispatch_width != 8)
1700 return;
1701
1702 pull_constant_loc = ralloc_array(mem_ctx, int, uniforms);
1703 memset(pull_constant_loc, -1, sizeof(pull_constant_loc[0]) * uniforms);
1704
1705 /* Walk through and find array access of uniforms. Put a copy of that
1706 * uniform in the pull constant buffer.
1707 *
1708 * Note that we don't move constant-indexed accesses to arrays. No
1709 * testing has been done of the performance impact of this choice.
1710 */
1711 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
1712 for (int i = 0 ; i < inst->sources; i++) {
1713 if (inst->src[i].file != UNIFORM || !inst->src[i].reladdr)
1714 continue;
1715
1716 int uniform = inst->src[i].reg;
1717
1718 /* If this array isn't already present in the pull constant buffer,
1719 * add it.
1720 */
1721 if (pull_constant_loc[uniform] == -1) {
1722 const gl_constant_value **values = &stage_prog_data->param[uniform];
1723
1724 assert(param_size[uniform]);
1725
1726 for (int j = 0; j < param_size[uniform]; j++) {
1727 pull_constant_loc[uniform + j] = stage_prog_data->nr_pull_params;
1728
1729 stage_prog_data->pull_param[stage_prog_data->nr_pull_params++] =
1730 values[j];
1731 }
1732 }
1733 }
1734 }
1735 }
1736
1737 /**
1738 * Assign UNIFORM file registers to either push constants or pull constants.
1739 *
1740 * We allow a fragment shader to have more than the specified minimum
1741 * maximum number of fragment shader uniform components (64). If
1742 * there are too many of these, they'd fill up all of register space.
1743 * So, this will push some of them out to the pull constant buffer and
1744 * update the program to load them.
1745 */
1746 void
1747 fs_visitor::assign_constant_locations()
1748 {
1749 /* Only the first compile (SIMD8 mode) gets to decide on locations. */
1750 if (dispatch_width != 8)
1751 return;
1752
1753 /* Find which UNIFORM registers are still in use. */
1754 bool is_live[uniforms];
1755 for (unsigned int i = 0; i < uniforms; i++) {
1756 is_live[i] = false;
1757 }
1758
1759 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1760 for (int i = 0; i < inst->sources; i++) {
1761 if (inst->src[i].file != UNIFORM)
1762 continue;
1763
1764 int constant_nr = inst->src[i].reg + inst->src[i].reg_offset;
1765 if (constant_nr >= 0 && constant_nr < (int) uniforms)
1766 is_live[constant_nr] = true;
1767 }
1768 }
1769
1770 /* Only allow 16 registers (128 uniform components) as push constants.
1771 *
1772 * Just demote the end of the list. We could probably do better
1773 * here, demoting things that are rarely used in the program first.
1774 *
1775 * If changing this value, note the limitation about total_regs in
1776 * brw_curbe.c.
1777 */
1778 unsigned int max_push_components = 16 * 8;
1779 unsigned int num_push_constants = 0;
1780
1781 push_constant_loc = ralloc_array(mem_ctx, int, uniforms);
1782
1783 for (unsigned int i = 0; i < uniforms; i++) {
1784 if (!is_live[i] || pull_constant_loc[i] != -1) {
1785 /* This UNIFORM register is either dead, or has already been demoted
1786 * to a pull const. Mark it as no longer living in the param[] array.
1787 */
1788 push_constant_loc[i] = -1;
1789 continue;
1790 }
1791
1792 if (num_push_constants < max_push_components) {
1793 /* Retain as a push constant. Record the location in the params[]
1794 * array.
1795 */
1796 push_constant_loc[i] = num_push_constants++;
1797 } else {
1798 /* Demote to a pull constant. */
1799 push_constant_loc[i] = -1;
1800
1801 int pull_index = stage_prog_data->nr_pull_params++;
1802 stage_prog_data->pull_param[pull_index] = stage_prog_data->param[i];
1803 pull_constant_loc[i] = pull_index;
1804 }
1805 }
1806
1807 stage_prog_data->nr_params = num_push_constants;
1808
1809 /* Up until now, the param[] array has been indexed by reg + reg_offset
1810 * of UNIFORM registers. Condense it to only contain the uniforms we
1811 * chose to upload as push constants.
1812 */
1813 for (unsigned int i = 0; i < uniforms; i++) {
1814 int remapped = push_constant_loc[i];
1815
1816 if (remapped == -1)
1817 continue;
1818
1819 assert(remapped <= (int)i);
1820 stage_prog_data->param[remapped] = stage_prog_data->param[i];
1821 }
1822 }
1823
1824 /**
1825 * Replace UNIFORM register file access with either UNIFORM_PULL_CONSTANT_LOAD
1826 * or VARYING_PULL_CONSTANT_LOAD instructions which load values into VGRFs.
1827 */
1828 void
1829 fs_visitor::demote_pull_constants()
1830 {
1831 foreach_block_and_inst (block, fs_inst, inst, cfg) {
1832 for (int i = 0; i < inst->sources; i++) {
1833 if (inst->src[i].file != UNIFORM)
1834 continue;
1835
1836 int pull_index;
1837 unsigned location = inst->src[i].reg + inst->src[i].reg_offset;
1838 if (location >= uniforms) /* Out of bounds access */
1839 pull_index = -1;
1840 else
1841 pull_index = pull_constant_loc[location];
1842
1843 if (pull_index == -1)
1844 continue;
1845
1846 /* Set up the annotation tracking for new generated instructions. */
1847 const fs_builder ibld = bld.annotate(inst->annotation, inst->ir)
1848 .at(block, inst);
1849 fs_reg surf_index(stage_prog_data->binding_table.pull_constants_start);
1850 fs_reg dst = vgrf(glsl_type::float_type);
1851
1852 assert(inst->src[i].stride == 0);
1853
1854 /* Generate a pull load into dst. */
1855 if (inst->src[i].reladdr) {
1856 VARYING_PULL_CONSTANT_LOAD(ibld, dst,
1857 surf_index,
1858 *inst->src[i].reladdr,
1859 pull_index);
1860 inst->src[i].reladdr = NULL;
1861 inst->src[i].stride = 1;
1862 } else {
1863 fs_reg offset = fs_reg((unsigned)(pull_index * 4) & ~15);
1864 ibld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
1865 dst, surf_index, offset);
1866 inst->src[i].set_smear(pull_index & 3);
1867 }
1868
1869 /* Rewrite the instruction to use the temporary VGRF. */
1870 inst->src[i].file = GRF;
1871 inst->src[i].reg = dst.reg;
1872 inst->src[i].reg_offset = 0;
1873 }
1874 }
1875 invalidate_live_intervals();
1876 }
1877
1878 bool
1879 fs_visitor::opt_algebraic()
1880 {
1881 bool progress = false;
1882
1883 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1884 switch (inst->opcode) {
1885 case BRW_OPCODE_MOV:
1886 if (inst->src[0].file != IMM)
1887 break;
1888
1889 if (inst->saturate) {
1890 if (inst->dst.type != inst->src[0].type)
1891 assert(!"unimplemented: saturate mixed types");
1892
1893 if (brw_saturate_immediate(inst->dst.type,
1894 &inst->src[0].fixed_hw_reg)) {
1895 inst->saturate = false;
1896 progress = true;
1897 }
1898 }
1899 break;
1900
1901 case BRW_OPCODE_MUL:
1902 if (inst->src[1].file != IMM)
1903 continue;
1904
1905 /* a * 1.0 = a */
1906 if (inst->src[1].is_one()) {
1907 inst->opcode = BRW_OPCODE_MOV;
1908 inst->src[1] = reg_undef;
1909 progress = true;
1910 break;
1911 }
1912
1913 /* a * -1.0 = -a */
1914 if (inst->src[1].is_negative_one()) {
1915 inst->opcode = BRW_OPCODE_MOV;
1916 inst->src[0].negate = !inst->src[0].negate;
1917 inst->src[1] = reg_undef;
1918 progress = true;
1919 break;
1920 }
1921
1922 /* a * 0.0 = 0.0 */
1923 if (inst->src[1].is_zero()) {
1924 inst->opcode = BRW_OPCODE_MOV;
1925 inst->src[0] = inst->src[1];
1926 inst->src[1] = reg_undef;
1927 progress = true;
1928 break;
1929 }
1930
1931 if (inst->src[0].file == IMM) {
1932 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
1933 inst->opcode = BRW_OPCODE_MOV;
1934 inst->src[0].fixed_hw_reg.dw1.f *= inst->src[1].fixed_hw_reg.dw1.f;
1935 inst->src[1] = reg_undef;
1936 progress = true;
1937 break;
1938 }
1939 break;
1940 case BRW_OPCODE_ADD:
1941 if (inst->src[1].file != IMM)
1942 continue;
1943
1944 /* a + 0.0 = a */
1945 if (inst->src[1].is_zero()) {
1946 inst->opcode = BRW_OPCODE_MOV;
1947 inst->src[1] = reg_undef;
1948 progress = true;
1949 break;
1950 }
1951
1952 if (inst->src[0].file == IMM) {
1953 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
1954 inst->opcode = BRW_OPCODE_MOV;
1955 inst->src[0].fixed_hw_reg.dw1.f += inst->src[1].fixed_hw_reg.dw1.f;
1956 inst->src[1] = reg_undef;
1957 progress = true;
1958 break;
1959 }
1960 break;
1961 case BRW_OPCODE_OR:
1962 if (inst->src[0].equals(inst->src[1])) {
1963 inst->opcode = BRW_OPCODE_MOV;
1964 inst->src[1] = reg_undef;
1965 progress = true;
1966 break;
1967 }
1968 break;
1969 case BRW_OPCODE_LRP:
1970 if (inst->src[1].equals(inst->src[2])) {
1971 inst->opcode = BRW_OPCODE_MOV;
1972 inst->src[0] = inst->src[1];
1973 inst->src[1] = reg_undef;
1974 inst->src[2] = reg_undef;
1975 progress = true;
1976 break;
1977 }
1978 break;
1979 case BRW_OPCODE_CMP:
1980 if (inst->conditional_mod == BRW_CONDITIONAL_GE &&
1981 inst->src[0].abs &&
1982 inst->src[0].negate &&
1983 inst->src[1].is_zero()) {
1984 inst->src[0].abs = false;
1985 inst->src[0].negate = false;
1986 inst->conditional_mod = BRW_CONDITIONAL_Z;
1987 progress = true;
1988 break;
1989 }
1990 break;
1991 case BRW_OPCODE_SEL:
1992 if (inst->src[0].equals(inst->src[1])) {
1993 inst->opcode = BRW_OPCODE_MOV;
1994 inst->src[1] = reg_undef;
1995 inst->predicate = BRW_PREDICATE_NONE;
1996 inst->predicate_inverse = false;
1997 progress = true;
1998 } else if (inst->saturate && inst->src[1].file == IMM) {
1999 switch (inst->conditional_mod) {
2000 case BRW_CONDITIONAL_LE:
2001 case BRW_CONDITIONAL_L:
2002 switch (inst->src[1].type) {
2003 case BRW_REGISTER_TYPE_F:
2004 if (inst->src[1].fixed_hw_reg.dw1.f >= 1.0f) {
2005 inst->opcode = BRW_OPCODE_MOV;
2006 inst->src[1] = reg_undef;
2007 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2008 progress = true;
2009 }
2010 break;
2011 default:
2012 break;
2013 }
2014 break;
2015 case BRW_CONDITIONAL_GE:
2016 case BRW_CONDITIONAL_G:
2017 switch (inst->src[1].type) {
2018 case BRW_REGISTER_TYPE_F:
2019 if (inst->src[1].fixed_hw_reg.dw1.f <= 0.0f) {
2020 inst->opcode = BRW_OPCODE_MOV;
2021 inst->src[1] = reg_undef;
2022 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2023 progress = true;
2024 }
2025 break;
2026 default:
2027 break;
2028 }
2029 default:
2030 break;
2031 }
2032 }
2033 break;
2034 case BRW_OPCODE_MAD:
2035 if (inst->src[1].is_zero() || inst->src[2].is_zero()) {
2036 inst->opcode = BRW_OPCODE_MOV;
2037 inst->src[1] = reg_undef;
2038 inst->src[2] = reg_undef;
2039 progress = true;
2040 } else if (inst->src[0].is_zero()) {
2041 inst->opcode = BRW_OPCODE_MUL;
2042 inst->src[0] = inst->src[2];
2043 inst->src[2] = reg_undef;
2044 progress = true;
2045 } else if (inst->src[1].is_one()) {
2046 inst->opcode = BRW_OPCODE_ADD;
2047 inst->src[1] = inst->src[2];
2048 inst->src[2] = reg_undef;
2049 progress = true;
2050 } else if (inst->src[2].is_one()) {
2051 inst->opcode = BRW_OPCODE_ADD;
2052 inst->src[2] = reg_undef;
2053 progress = true;
2054 } else if (inst->src[1].file == IMM && inst->src[2].file == IMM) {
2055 inst->opcode = BRW_OPCODE_ADD;
2056 inst->src[1].fixed_hw_reg.dw1.f *= inst->src[2].fixed_hw_reg.dw1.f;
2057 inst->src[2] = reg_undef;
2058 progress = true;
2059 }
2060 break;
2061 case SHADER_OPCODE_RCP: {
2062 fs_inst *prev = (fs_inst *)inst->prev;
2063 if (prev->opcode == SHADER_OPCODE_SQRT) {
2064 if (inst->src[0].equals(prev->dst)) {
2065 inst->opcode = SHADER_OPCODE_RSQ;
2066 inst->src[0] = prev->src[0];
2067 progress = true;
2068 }
2069 }
2070 break;
2071 }
2072 case SHADER_OPCODE_BROADCAST:
2073 if (is_uniform(inst->src[0])) {
2074 inst->opcode = BRW_OPCODE_MOV;
2075 inst->sources = 1;
2076 inst->force_writemask_all = true;
2077 progress = true;
2078 } else if (inst->src[1].file == IMM) {
2079 inst->opcode = BRW_OPCODE_MOV;
2080 inst->src[0] = component(inst->src[0],
2081 inst->src[1].fixed_hw_reg.dw1.ud);
2082 inst->sources = 1;
2083 inst->force_writemask_all = true;
2084 progress = true;
2085 }
2086 break;
2087
2088 default:
2089 break;
2090 }
2091
2092 /* Swap if src[0] is immediate. */
2093 if (progress && inst->is_commutative()) {
2094 if (inst->src[0].file == IMM) {
2095 fs_reg tmp = inst->src[1];
2096 inst->src[1] = inst->src[0];
2097 inst->src[0] = tmp;
2098 }
2099 }
2100 }
2101 return progress;
2102 }
2103
2104 /**
2105 * Optimize sample messages that have constant zero values for the trailing
2106 * texture coordinates. We can just reduce the message length for these
2107 * instructions instead of reserving a register for it. Trailing parameters
2108 * that aren't sent default to zero anyway. This will cause the dead code
2109 * eliminator to remove the MOV instruction that would otherwise be emitted to
2110 * set up the zero value.
2111 */
2112 bool
2113 fs_visitor::opt_zero_samples()
2114 {
2115 /* Gen4 infers the texturing opcode based on the message length so we can't
2116 * change it.
2117 */
2118 if (devinfo->gen < 5)
2119 return false;
2120
2121 bool progress = false;
2122
2123 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2124 if (!inst->is_tex())
2125 continue;
2126
2127 fs_inst *load_payload = (fs_inst *) inst->prev;
2128
2129 if (load_payload->is_head_sentinel() ||
2130 load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2131 continue;
2132
2133 /* We don't want to remove the message header or the first parameter.
2134 * Removing the first parameter is not allowed, see the Haswell PRM
2135 * volume 7, page 149:
2136 *
2137 * "Parameter 0 is required except for the sampleinfo message, which
2138 * has no parameter 0"
2139 */
2140 while (inst->mlen > inst->header_size + dispatch_width / 8 &&
2141 load_payload->src[(inst->mlen - inst->header_size) /
2142 (dispatch_width / 8) +
2143 inst->header_size - 1].is_zero()) {
2144 inst->mlen -= dispatch_width / 8;
2145 progress = true;
2146 }
2147 }
2148
2149 if (progress)
2150 invalidate_live_intervals();
2151
2152 return progress;
2153 }
2154
2155 /**
2156 * Optimize sample messages which are followed by the final RT write.
2157 *
2158 * CHV, and GEN9+ can mark a texturing SEND instruction with EOT to have its
2159 * results sent directly to the framebuffer, bypassing the EU. Recognize the
2160 * final texturing results copied to the framebuffer write payload and modify
2161 * them to write to the framebuffer directly.
2162 */
2163 bool
2164 fs_visitor::opt_sampler_eot()
2165 {
2166 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
2167
2168 if (stage != MESA_SHADER_FRAGMENT)
2169 return false;
2170
2171 if (devinfo->gen < 9 && !devinfo->is_cherryview)
2172 return false;
2173
2174 /* FINISHME: It should be possible to implement this optimization when there
2175 * are multiple drawbuffers.
2176 */
2177 if (key->nr_color_regions != 1)
2178 return false;
2179
2180 /* Look for a texturing instruction immediately before the final FB_WRITE. */
2181 fs_inst *fb_write = (fs_inst *) cfg->blocks[cfg->num_blocks - 1]->end();
2182 assert(fb_write->eot);
2183 assert(fb_write->opcode == FS_OPCODE_FB_WRITE);
2184
2185 fs_inst *tex_inst = (fs_inst *) fb_write->prev;
2186
2187 /* There wasn't one; nothing to do. */
2188 if (unlikely(tex_inst->is_head_sentinel()) || !tex_inst->is_tex())
2189 return false;
2190
2191 /* This optimisation doesn't seem to work for textureGather for some
2192 * reason. I can't find any documentation or known workarounds to indicate
2193 * that this is expected, but considering that it is probably pretty
2194 * unlikely that a shader would directly write out the results from
2195 * textureGather we might as well just disable it.
2196 */
2197 if (tex_inst->opcode == SHADER_OPCODE_TG4 ||
2198 tex_inst->opcode == SHADER_OPCODE_TG4_OFFSET)
2199 return false;
2200
2201 /* If there's no header present, we need to munge the LOAD_PAYLOAD as well.
2202 * It's very likely to be the previous instruction.
2203 */
2204 fs_inst *load_payload = (fs_inst *) tex_inst->prev;
2205 if (load_payload->is_head_sentinel() ||
2206 load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2207 return false;
2208
2209 assert(!tex_inst->eot); /* We can't get here twice */
2210 assert((tex_inst->offset & (0xff << 24)) == 0);
2211
2212 tex_inst->offset |= fb_write->target << 24;
2213 tex_inst->eot = true;
2214 tex_inst->dst = bld.null_reg_ud();
2215 fb_write->remove(cfg->blocks[cfg->num_blocks - 1]);
2216
2217 /* If a header is present, marking the eot is sufficient. Otherwise, we need
2218 * to create a new LOAD_PAYLOAD command with the same sources and a space
2219 * saved for the header. Using a new destination register not only makes sure
2220 * we have enough space, but it will make sure the dead code eliminator kills
2221 * the instruction that this will replace.
2222 */
2223 if (tex_inst->header_size != 0)
2224 return true;
2225
2226 fs_reg send_header = bld.vgrf(BRW_REGISTER_TYPE_F,
2227 load_payload->sources + 1);
2228 fs_reg *new_sources =
2229 ralloc_array(mem_ctx, fs_reg, load_payload->sources + 1);
2230
2231 new_sources[0] = fs_reg();
2232 for (int i = 0; i < load_payload->sources; i++)
2233 new_sources[i+1] = load_payload->src[i];
2234
2235 /* The LOAD_PAYLOAD helper seems like the obvious choice here. However, it
2236 * requires a lot of information about the sources to appropriately figure
2237 * out the number of registers needed to be used. Given this stage in our
2238 * optimization, we may not have the appropriate GRFs required by
2239 * LOAD_PAYLOAD at this point (copy propagation). Therefore, we need to
2240 * manually emit the instruction.
2241 */
2242 fs_inst *new_load_payload = new(mem_ctx) fs_inst(SHADER_OPCODE_LOAD_PAYLOAD,
2243 load_payload->exec_size,
2244 send_header,
2245 new_sources,
2246 load_payload->sources + 1);
2247
2248 new_load_payload->regs_written = load_payload->regs_written + 1;
2249 new_load_payload->header_size = 1;
2250 tex_inst->mlen++;
2251 tex_inst->header_size = 1;
2252 tex_inst->insert_before(cfg->blocks[cfg->num_blocks - 1], new_load_payload);
2253 tex_inst->src[0] = send_header;
2254
2255 return true;
2256 }
2257
2258 bool
2259 fs_visitor::opt_register_renaming()
2260 {
2261 bool progress = false;
2262 int depth = 0;
2263
2264 int remap[alloc.count];
2265 memset(remap, -1, sizeof(int) * alloc.count);
2266
2267 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2268 if (inst->opcode == BRW_OPCODE_IF || inst->opcode == BRW_OPCODE_DO) {
2269 depth++;
2270 } else if (inst->opcode == BRW_OPCODE_ENDIF ||
2271 inst->opcode == BRW_OPCODE_WHILE) {
2272 depth--;
2273 }
2274
2275 /* Rewrite instruction sources. */
2276 for (int i = 0; i < inst->sources; i++) {
2277 if (inst->src[i].file == GRF &&
2278 remap[inst->src[i].reg] != -1 &&
2279 remap[inst->src[i].reg] != inst->src[i].reg) {
2280 inst->src[i].reg = remap[inst->src[i].reg];
2281 progress = true;
2282 }
2283 }
2284
2285 const int dst = inst->dst.reg;
2286
2287 if (depth == 0 &&
2288 inst->dst.file == GRF &&
2289 alloc.sizes[inst->dst.reg] == inst->exec_size / 8 &&
2290 !inst->is_partial_write()) {
2291 if (remap[dst] == -1) {
2292 remap[dst] = dst;
2293 } else {
2294 remap[dst] = alloc.allocate(inst->exec_size / 8);
2295 inst->dst.reg = remap[dst];
2296 progress = true;
2297 }
2298 } else if (inst->dst.file == GRF &&
2299 remap[dst] != -1 &&
2300 remap[dst] != dst) {
2301 inst->dst.reg = remap[dst];
2302 progress = true;
2303 }
2304 }
2305
2306 if (progress) {
2307 invalidate_live_intervals();
2308
2309 for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2310 if (delta_xy[i].file == GRF && remap[delta_xy[i].reg] != -1) {
2311 delta_xy[i].reg = remap[delta_xy[i].reg];
2312 }
2313 }
2314 }
2315
2316 return progress;
2317 }
2318
2319 /**
2320 * Remove redundant or useless discard jumps.
2321 *
2322 * For example, we can eliminate jumps in the following sequence:
2323 *
2324 * discard-jump (redundant with the next jump)
2325 * discard-jump (useless; jumps to the next instruction)
2326 * placeholder-halt
2327 */
2328 bool
2329 fs_visitor::opt_redundant_discard_jumps()
2330 {
2331 bool progress = false;
2332
2333 bblock_t *last_bblock = cfg->blocks[cfg->num_blocks - 1];
2334
2335 fs_inst *placeholder_halt = NULL;
2336 foreach_inst_in_block_reverse(fs_inst, inst, last_bblock) {
2337 if (inst->opcode == FS_OPCODE_PLACEHOLDER_HALT) {
2338 placeholder_halt = inst;
2339 break;
2340 }
2341 }
2342
2343 if (!placeholder_halt)
2344 return false;
2345
2346 /* Delete any HALTs immediately before the placeholder halt. */
2347 for (fs_inst *prev = (fs_inst *) placeholder_halt->prev;
2348 !prev->is_head_sentinel() && prev->opcode == FS_OPCODE_DISCARD_JUMP;
2349 prev = (fs_inst *) placeholder_halt->prev) {
2350 prev->remove(last_bblock);
2351 progress = true;
2352 }
2353
2354 if (progress)
2355 invalidate_live_intervals();
2356
2357 return progress;
2358 }
2359
2360 bool
2361 fs_visitor::compute_to_mrf()
2362 {
2363 bool progress = false;
2364 int next_ip = 0;
2365
2366 /* No MRFs on Gen >= 7. */
2367 if (devinfo->gen >= 7)
2368 return false;
2369
2370 calculate_live_intervals();
2371
2372 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2373 int ip = next_ip;
2374 next_ip++;
2375
2376 if (inst->opcode != BRW_OPCODE_MOV ||
2377 inst->is_partial_write() ||
2378 inst->dst.file != MRF || inst->src[0].file != GRF ||
2379 inst->dst.type != inst->src[0].type ||
2380 inst->src[0].abs || inst->src[0].negate ||
2381 !inst->src[0].is_contiguous() ||
2382 inst->src[0].subreg_offset)
2383 continue;
2384
2385 /* Work out which hardware MRF registers are written by this
2386 * instruction.
2387 */
2388 int mrf_low = inst->dst.reg & ~BRW_MRF_COMPR4;
2389 int mrf_high;
2390 if (inst->dst.reg & BRW_MRF_COMPR4) {
2391 mrf_high = mrf_low + 4;
2392 } else if (inst->exec_size == 16) {
2393 mrf_high = mrf_low + 1;
2394 } else {
2395 mrf_high = mrf_low;
2396 }
2397
2398 /* Can't compute-to-MRF this GRF if someone else was going to
2399 * read it later.
2400 */
2401 if (this->virtual_grf_end[inst->src[0].reg] > ip)
2402 continue;
2403
2404 /* Found a move of a GRF to a MRF. Let's see if we can go
2405 * rewrite the thing that made this GRF to write into the MRF.
2406 */
2407 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst, block) {
2408 if (scan_inst->dst.file == GRF &&
2409 scan_inst->dst.reg == inst->src[0].reg) {
2410 /* Found the last thing to write our reg we want to turn
2411 * into a compute-to-MRF.
2412 */
2413
2414 /* If this one instruction didn't populate all the
2415 * channels, bail. We might be able to rewrite everything
2416 * that writes that reg, but it would require smarter
2417 * tracking to delay the rewriting until complete success.
2418 */
2419 if (scan_inst->is_partial_write())
2420 break;
2421
2422 /* Things returning more than one register would need us to
2423 * understand coalescing out more than one MOV at a time.
2424 */
2425 if (scan_inst->regs_written > scan_inst->exec_size / 8)
2426 break;
2427
2428 /* SEND instructions can't have MRF as a destination. */
2429 if (scan_inst->mlen)
2430 break;
2431
2432 if (devinfo->gen == 6) {
2433 /* gen6 math instructions must have the destination be
2434 * GRF, so no compute-to-MRF for them.
2435 */
2436 if (scan_inst->is_math()) {
2437 break;
2438 }
2439 }
2440
2441 if (scan_inst->dst.reg_offset == inst->src[0].reg_offset) {
2442 /* Found the creator of our MRF's source value. */
2443 scan_inst->dst.file = MRF;
2444 scan_inst->dst.reg = inst->dst.reg;
2445 scan_inst->saturate |= inst->saturate;
2446 inst->remove(block);
2447 progress = true;
2448 }
2449 break;
2450 }
2451
2452 /* We don't handle control flow here. Most computation of
2453 * values that end up in MRFs are shortly before the MRF
2454 * write anyway.
2455 */
2456 if (block->start() == scan_inst)
2457 break;
2458
2459 /* You can't read from an MRF, so if someone else reads our
2460 * MRF's source GRF that we wanted to rewrite, that stops us.
2461 */
2462 bool interfered = false;
2463 for (int i = 0; i < scan_inst->sources; i++) {
2464 if (scan_inst->src[i].file == GRF &&
2465 scan_inst->src[i].reg == inst->src[0].reg &&
2466 scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
2467 interfered = true;
2468 }
2469 }
2470 if (interfered)
2471 break;
2472
2473 if (scan_inst->dst.file == MRF) {
2474 /* If somebody else writes our MRF here, we can't
2475 * compute-to-MRF before that.
2476 */
2477 int scan_mrf_low = scan_inst->dst.reg & ~BRW_MRF_COMPR4;
2478 int scan_mrf_high;
2479
2480 if (scan_inst->dst.reg & BRW_MRF_COMPR4) {
2481 scan_mrf_high = scan_mrf_low + 4;
2482 } else if (scan_inst->exec_size == 16) {
2483 scan_mrf_high = scan_mrf_low + 1;
2484 } else {
2485 scan_mrf_high = scan_mrf_low;
2486 }
2487
2488 if (mrf_low == scan_mrf_low ||
2489 mrf_low == scan_mrf_high ||
2490 mrf_high == scan_mrf_low ||
2491 mrf_high == scan_mrf_high) {
2492 break;
2493 }
2494 }
2495
2496 if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1) {
2497 /* Found a SEND instruction, which means that there are
2498 * live values in MRFs from base_mrf to base_mrf +
2499 * scan_inst->mlen - 1. Don't go pushing our MRF write up
2500 * above it.
2501 */
2502 if (mrf_low >= scan_inst->base_mrf &&
2503 mrf_low < scan_inst->base_mrf + scan_inst->mlen) {
2504 break;
2505 }
2506 if (mrf_high >= scan_inst->base_mrf &&
2507 mrf_high < scan_inst->base_mrf + scan_inst->mlen) {
2508 break;
2509 }
2510 }
2511 }
2512 }
2513
2514 if (progress)
2515 invalidate_live_intervals();
2516
2517 return progress;
2518 }
2519
2520 /**
2521 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
2522 * flow. We could probably do better here with some form of divergence
2523 * analysis.
2524 */
2525 bool
2526 fs_visitor::eliminate_find_live_channel()
2527 {
2528 bool progress = false;
2529 unsigned depth = 0;
2530
2531 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2532 switch (inst->opcode) {
2533 case BRW_OPCODE_IF:
2534 case BRW_OPCODE_DO:
2535 depth++;
2536 break;
2537
2538 case BRW_OPCODE_ENDIF:
2539 case BRW_OPCODE_WHILE:
2540 depth--;
2541 break;
2542
2543 case FS_OPCODE_DISCARD_JUMP:
2544 /* This can potentially make control flow non-uniform until the end
2545 * of the program.
2546 */
2547 return progress;
2548
2549 case SHADER_OPCODE_FIND_LIVE_CHANNEL:
2550 if (depth == 0) {
2551 inst->opcode = BRW_OPCODE_MOV;
2552 inst->src[0] = fs_reg(0);
2553 inst->sources = 1;
2554 inst->force_writemask_all = true;
2555 progress = true;
2556 }
2557 break;
2558
2559 default:
2560 break;
2561 }
2562 }
2563
2564 return progress;
2565 }
2566
2567 /**
2568 * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
2569 * instructions to FS_OPCODE_REP_FB_WRITE.
2570 */
2571 void
2572 fs_visitor::emit_repclear_shader()
2573 {
2574 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
2575 int base_mrf = 1;
2576 int color_mrf = base_mrf + 2;
2577
2578 fs_inst *mov = bld.exec_all().MOV(vec4(brw_message_reg(color_mrf)),
2579 fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
2580
2581 fs_inst *write;
2582 if (key->nr_color_regions == 1) {
2583 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
2584 write->saturate = key->clamp_fragment_color;
2585 write->base_mrf = color_mrf;
2586 write->target = 0;
2587 write->header_size = 0;
2588 write->mlen = 1;
2589 } else {
2590 assume(key->nr_color_regions > 0);
2591 for (int i = 0; i < key->nr_color_regions; ++i) {
2592 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
2593 write->saturate = key->clamp_fragment_color;
2594 write->base_mrf = base_mrf;
2595 write->target = i;
2596 write->header_size = 2;
2597 write->mlen = 3;
2598 }
2599 }
2600 write->eot = true;
2601
2602 calculate_cfg();
2603
2604 assign_constant_locations();
2605 assign_curb_setup();
2606
2607 /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
2608 assert(mov->src[0].file == HW_REG);
2609 mov->src[0] = brw_vec4_grf(mov->src[0].fixed_hw_reg.nr, 0);
2610 }
2611
2612 /**
2613 * Walks through basic blocks, looking for repeated MRF writes and
2614 * removing the later ones.
2615 */
2616 bool
2617 fs_visitor::remove_duplicate_mrf_writes()
2618 {
2619 fs_inst *last_mrf_move[16];
2620 bool progress = false;
2621
2622 /* Need to update the MRF tracking for compressed instructions. */
2623 if (dispatch_width == 16)
2624 return false;
2625
2626 memset(last_mrf_move, 0, sizeof(last_mrf_move));
2627
2628 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2629 if (inst->is_control_flow()) {
2630 memset(last_mrf_move, 0, sizeof(last_mrf_move));
2631 }
2632
2633 if (inst->opcode == BRW_OPCODE_MOV &&
2634 inst->dst.file == MRF) {
2635 fs_inst *prev_inst = last_mrf_move[inst->dst.reg];
2636 if (prev_inst && inst->equals(prev_inst)) {
2637 inst->remove(block);
2638 progress = true;
2639 continue;
2640 }
2641 }
2642
2643 /* Clear out the last-write records for MRFs that were overwritten. */
2644 if (inst->dst.file == MRF) {
2645 last_mrf_move[inst->dst.reg] = NULL;
2646 }
2647
2648 if (inst->mlen > 0 && inst->base_mrf != -1) {
2649 /* Found a SEND instruction, which will include two or fewer
2650 * implied MRF writes. We could do better here.
2651 */
2652 for (int i = 0; i < implied_mrf_writes(inst); i++) {
2653 last_mrf_move[inst->base_mrf + i] = NULL;
2654 }
2655 }
2656
2657 /* Clear out any MRF move records whose sources got overwritten. */
2658 if (inst->dst.file == GRF) {
2659 for (unsigned int i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
2660 if (last_mrf_move[i] &&
2661 last_mrf_move[i]->src[0].reg == inst->dst.reg) {
2662 last_mrf_move[i] = NULL;
2663 }
2664 }
2665 }
2666
2667 if (inst->opcode == BRW_OPCODE_MOV &&
2668 inst->dst.file == MRF &&
2669 inst->src[0].file == GRF &&
2670 !inst->is_partial_write()) {
2671 last_mrf_move[inst->dst.reg] = inst;
2672 }
2673 }
2674
2675 if (progress)
2676 invalidate_live_intervals();
2677
2678 return progress;
2679 }
2680
2681 static void
2682 clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
2683 {
2684 /* Clear the flag for registers that actually got read (as expected). */
2685 for (int i = 0; i < inst->sources; i++) {
2686 int grf;
2687 if (inst->src[i].file == GRF) {
2688 grf = inst->src[i].reg;
2689 } else if (inst->src[i].file == HW_REG &&
2690 inst->src[i].fixed_hw_reg.file == BRW_GENERAL_REGISTER_FILE) {
2691 grf = inst->src[i].fixed_hw_reg.nr;
2692 } else {
2693 continue;
2694 }
2695
2696 if (grf >= first_grf &&
2697 grf < first_grf + grf_len) {
2698 deps[grf - first_grf] = false;
2699 if (inst->exec_size == 16)
2700 deps[grf - first_grf + 1] = false;
2701 }
2702 }
2703 }
2704
2705 /**
2706 * Implements this workaround for the original 965:
2707 *
2708 * "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
2709 * check for post destination dependencies on this instruction, software
2710 * must ensure that there is no destination hazard for the case of ‘write
2711 * followed by a posted write’ shown in the following example.
2712 *
2713 * 1. mov r3 0
2714 * 2. send r3.xy <rest of send instruction>
2715 * 3. mov r2 r3
2716 *
2717 * Due to no post-destination dependency check on the ‘send’, the above
2718 * code sequence could have two instructions (1 and 2) in flight at the
2719 * same time that both consider ‘r3’ as the target of their final writes.
2720 */
2721 void
2722 fs_visitor::insert_gen4_pre_send_dependency_workarounds(bblock_t *block,
2723 fs_inst *inst)
2724 {
2725 int write_len = inst->regs_written;
2726 int first_write_grf = inst->dst.reg;
2727 bool needs_dep[BRW_MAX_MRF];
2728 assert(write_len < (int)sizeof(needs_dep) - 1);
2729
2730 memset(needs_dep, false, sizeof(needs_dep));
2731 memset(needs_dep, true, write_len);
2732
2733 clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
2734
2735 /* Walk backwards looking for writes to registers we're writing which
2736 * aren't read since being written. If we hit the start of the program,
2737 * we assume that there are no outstanding dependencies on entry to the
2738 * program.
2739 */
2740 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst, block) {
2741 /* If we hit control flow, assume that there *are* outstanding
2742 * dependencies, and force their cleanup before our instruction.
2743 */
2744 if (block->start() == scan_inst) {
2745 for (int i = 0; i < write_len; i++) {
2746 if (needs_dep[i])
2747 DEP_RESOLVE_MOV(bld.at(block, inst), first_write_grf + i);
2748 }
2749 return;
2750 }
2751
2752 /* We insert our reads as late as possible on the assumption that any
2753 * instruction but a MOV that might have left us an outstanding
2754 * dependency has more latency than a MOV.
2755 */
2756 if (scan_inst->dst.file == GRF) {
2757 for (int i = 0; i < scan_inst->regs_written; i++) {
2758 int reg = scan_inst->dst.reg + i;
2759
2760 if (reg >= first_write_grf &&
2761 reg < first_write_grf + write_len &&
2762 needs_dep[reg - first_write_grf]) {
2763 DEP_RESOLVE_MOV(bld.at(block, inst), reg);
2764 needs_dep[reg - first_write_grf] = false;
2765 if (scan_inst->exec_size == 16)
2766 needs_dep[reg - first_write_grf + 1] = false;
2767 }
2768 }
2769 }
2770
2771 /* Clear the flag for registers that actually got read (as expected). */
2772 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
2773
2774 /* Continue the loop only if we haven't resolved all the dependencies */
2775 int i;
2776 for (i = 0; i < write_len; i++) {
2777 if (needs_dep[i])
2778 break;
2779 }
2780 if (i == write_len)
2781 return;
2782 }
2783 }
2784
2785 /**
2786 * Implements this workaround for the original 965:
2787 *
2788 * "[DevBW, DevCL] Errata: A destination register from a send can not be
2789 * used as a destination register until after it has been sourced by an
2790 * instruction with a different destination register.
2791 */
2792 void
2793 fs_visitor::insert_gen4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
2794 {
2795 int write_len = inst->regs_written;
2796 int first_write_grf = inst->dst.reg;
2797 bool needs_dep[BRW_MAX_MRF];
2798 assert(write_len < (int)sizeof(needs_dep) - 1);
2799
2800 memset(needs_dep, false, sizeof(needs_dep));
2801 memset(needs_dep, true, write_len);
2802 /* Walk forwards looking for writes to registers we're writing which aren't
2803 * read before being written.
2804 */
2805 foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst, block) {
2806 /* If we hit control flow, force resolve all remaining dependencies. */
2807 if (block->end() == scan_inst) {
2808 for (int i = 0; i < write_len; i++) {
2809 if (needs_dep[i])
2810 DEP_RESOLVE_MOV(bld.at(block, scan_inst), first_write_grf + i);
2811 }
2812 return;
2813 }
2814
2815 /* Clear the flag for registers that actually got read (as expected). */
2816 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
2817
2818 /* We insert our reads as late as possible since they're reading the
2819 * result of a SEND, which has massive latency.
2820 */
2821 if (scan_inst->dst.file == GRF &&
2822 scan_inst->dst.reg >= first_write_grf &&
2823 scan_inst->dst.reg < first_write_grf + write_len &&
2824 needs_dep[scan_inst->dst.reg - first_write_grf]) {
2825 DEP_RESOLVE_MOV(bld.at(block, scan_inst), scan_inst->dst.reg);
2826 needs_dep[scan_inst->dst.reg - first_write_grf] = false;
2827 }
2828
2829 /* Continue the loop only if we haven't resolved all the dependencies */
2830 int i;
2831 for (i = 0; i < write_len; i++) {
2832 if (needs_dep[i])
2833 break;
2834 }
2835 if (i == write_len)
2836 return;
2837 }
2838 }
2839
2840 void
2841 fs_visitor::insert_gen4_send_dependency_workarounds()
2842 {
2843 if (devinfo->gen != 4 || devinfo->is_g4x)
2844 return;
2845
2846 bool progress = false;
2847
2848 /* Note that we're done with register allocation, so GRF fs_regs always
2849 * have a .reg_offset of 0.
2850 */
2851
2852 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2853 if (inst->mlen != 0 && inst->dst.file == GRF) {
2854 insert_gen4_pre_send_dependency_workarounds(block, inst);
2855 insert_gen4_post_send_dependency_workarounds(block, inst);
2856 progress = true;
2857 }
2858 }
2859
2860 if (progress)
2861 invalidate_live_intervals();
2862 }
2863
2864 /**
2865 * Turns the generic expression-style uniform pull constant load instruction
2866 * into a hardware-specific series of instructions for loading a pull
2867 * constant.
2868 *
2869 * The expression style allows the CSE pass before this to optimize out
2870 * repeated loads from the same offset, and gives the pre-register-allocation
2871 * scheduling full flexibility, while the conversion to native instructions
2872 * allows the post-register-allocation scheduler the best information
2873 * possible.
2874 *
2875 * Note that execution masking for setting up pull constant loads is special:
2876 * the channels that need to be written are unrelated to the current execution
2877 * mask, since a later instruction will use one of the result channels as a
2878 * source operand for all 8 or 16 of its channels.
2879 */
2880 void
2881 fs_visitor::lower_uniform_pull_constant_loads()
2882 {
2883 foreach_block_and_inst (block, fs_inst, inst, cfg) {
2884 if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
2885 continue;
2886
2887 if (devinfo->gen >= 7) {
2888 /* The offset arg before was a vec4-aligned byte offset. We need to
2889 * turn it into a dword offset.
2890 */
2891 fs_reg const_offset_reg = inst->src[1];
2892 assert(const_offset_reg.file == IMM &&
2893 const_offset_reg.type == BRW_REGISTER_TYPE_UD);
2894 const_offset_reg.fixed_hw_reg.dw1.ud /= 4;
2895
2896 fs_reg payload, offset;
2897 if (devinfo->gen >= 9) {
2898 /* We have to use a message header on Skylake to get SIMD4x2
2899 * mode. Reserve space for the register.
2900 */
2901 offset = payload = fs_reg(GRF, alloc.allocate(2));
2902 offset.reg_offset++;
2903 inst->mlen = 2;
2904 } else {
2905 offset = payload = fs_reg(GRF, alloc.allocate(1));
2906 inst->mlen = 1;
2907 }
2908
2909 /* This is actually going to be a MOV, but since only the first dword
2910 * is accessed, we have a special opcode to do just that one. Note
2911 * that this needs to be an operation that will be considered a def
2912 * by live variable analysis, or register allocation will explode.
2913 */
2914 fs_inst *setup = new(mem_ctx) fs_inst(FS_OPCODE_SET_SIMD4X2_OFFSET,
2915 8, offset, const_offset_reg);
2916 setup->force_writemask_all = true;
2917
2918 setup->ir = inst->ir;
2919 setup->annotation = inst->annotation;
2920 inst->insert_before(block, setup);
2921
2922 /* Similarly, this will only populate the first 4 channels of the
2923 * result register (since we only use smear values from 0-3), but we
2924 * don't tell the optimizer.
2925 */
2926 inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7;
2927 inst->src[1] = payload;
2928 inst->base_mrf = -1;
2929
2930 invalidate_live_intervals();
2931 } else {
2932 /* Before register allocation, we didn't tell the scheduler about the
2933 * MRF we use. We know it's safe to use this MRF because nothing
2934 * else does except for register spill/unspill, which generates and
2935 * uses its MRF within a single IR instruction.
2936 */
2937 inst->base_mrf = 14;
2938 inst->mlen = 1;
2939 }
2940 }
2941 }
2942
2943 bool
2944 fs_visitor::lower_load_payload()
2945 {
2946 bool progress = false;
2947
2948 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2949 if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2950 continue;
2951
2952 assert(inst->dst.file == MRF || inst->dst.file == GRF);
2953 assert(inst->saturate == false);
2954 fs_reg dst = inst->dst;
2955
2956 /* Get rid of COMPR4. We'll add it back in if we need it */
2957 if (dst.file == MRF)
2958 dst.reg = dst.reg & ~BRW_MRF_COMPR4;
2959
2960 const fs_builder hbld = bld.exec_all().group(8, 0).at(block, inst);
2961
2962 for (uint8_t i = 0; i < inst->header_size; i++) {
2963 if (inst->src[i].file != BAD_FILE) {
2964 fs_reg mov_dst = retype(dst, BRW_REGISTER_TYPE_UD);
2965 fs_reg mov_src = retype(inst->src[i], BRW_REGISTER_TYPE_UD);
2966 hbld.MOV(mov_dst, mov_src);
2967 }
2968 dst = offset(dst, hbld, 1);
2969 }
2970
2971 const fs_builder ibld = bld.exec_all(inst->force_writemask_all)
2972 .group(inst->exec_size, inst->force_sechalf)
2973 .at(block, inst);
2974
2975 if (inst->dst.file == MRF && (inst->dst.reg & BRW_MRF_COMPR4) &&
2976 inst->exec_size > 8) {
2977 /* In this case, the payload portion of the LOAD_PAYLOAD isn't
2978 * a straightforward copy. Instead, the result of the
2979 * LOAD_PAYLOAD is treated as interleaved and the first four
2980 * non-header sources are unpacked as:
2981 *
2982 * m + 0: r0
2983 * m + 1: g0
2984 * m + 2: b0
2985 * m + 3: a0
2986 * m + 4: r1
2987 * m + 5: g1
2988 * m + 6: b1
2989 * m + 7: a1
2990 *
2991 * This is used for gen <= 5 fb writes.
2992 */
2993 assert(inst->exec_size == 16);
2994 assert(inst->header_size + 4 <= inst->sources);
2995 for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
2996 if (inst->src[i].file != BAD_FILE) {
2997 if (devinfo->has_compr4) {
2998 fs_reg compr4_dst = retype(dst, inst->src[i].type);
2999 compr4_dst.reg |= BRW_MRF_COMPR4;
3000 ibld.MOV(compr4_dst, inst->src[i]);
3001 } else {
3002 /* Platform doesn't have COMPR4. We have to fake it */
3003 fs_reg mov_dst = retype(dst, inst->src[i].type);
3004 ibld.half(0).MOV(mov_dst, half(inst->src[i], 0));
3005 mov_dst.reg += 4;
3006 ibld.half(1).MOV(mov_dst, half(inst->src[i], 1));
3007 }
3008 }
3009
3010 dst.reg++;
3011 }
3012
3013 /* The loop above only ever incremented us through the first set
3014 * of 4 registers. However, thanks to the magic of COMPR4, we
3015 * actually wrote to the first 8 registers, so we need to take
3016 * that into account now.
3017 */
3018 dst.reg += 4;
3019
3020 /* The COMPR4 code took care of the first 4 sources. We'll let
3021 * the regular path handle any remaining sources. Yes, we are
3022 * modifying the instruction but we're about to delete it so
3023 * this really doesn't hurt anything.
3024 */
3025 inst->header_size += 4;
3026 }
3027
3028 for (uint8_t i = inst->header_size; i < inst->sources; i++) {
3029 if (inst->src[i].file != BAD_FILE)
3030 ibld.MOV(retype(dst, inst->src[i].type), inst->src[i]);
3031 dst = offset(dst, ibld, 1);
3032 }
3033
3034 inst->remove(block);
3035 progress = true;
3036 }
3037
3038 if (progress)
3039 invalidate_live_intervals();
3040
3041 return progress;
3042 }
3043
3044 bool
3045 fs_visitor::lower_integer_multiplication()
3046 {
3047 bool progress = false;
3048
3049 /* Gen8's MUL instruction can do a 32-bit x 32-bit -> 32-bit operation
3050 * directly, but Cherryview cannot.
3051 */
3052 if (devinfo->gen >= 8 && !devinfo->is_cherryview)
3053 return false;
3054
3055 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3056 if (inst->opcode != BRW_OPCODE_MUL ||
3057 inst->dst.is_accumulator() ||
3058 (inst->dst.type != BRW_REGISTER_TYPE_D &&
3059 inst->dst.type != BRW_REGISTER_TYPE_UD))
3060 continue;
3061
3062 const fs_builder ibld = bld.at(block, inst);
3063
3064 /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3065 * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3066 * src1 are used.
3067 *
3068 * If multiplying by an immediate value that fits in 16-bits, do a
3069 * single MUL instruction with that value in the proper location.
3070 */
3071 if (inst->src[1].file == IMM &&
3072 inst->src[1].fixed_hw_reg.dw1.ud < (1 << 16)) {
3073 if (devinfo->gen < 7) {
3074 fs_reg imm(GRF, alloc.allocate(dispatch_width / 8),
3075 inst->dst.type);
3076 ibld.MOV(imm, inst->src[1]);
3077 ibld.MUL(inst->dst, imm, inst->src[0]);
3078 } else {
3079 ibld.MUL(inst->dst, inst->src[0], inst->src[1]);
3080 }
3081 } else {
3082 /* Gen < 8 (and some Gen8+ low-power parts like Cherryview) cannot
3083 * do 32-bit integer multiplication in one instruction, but instead
3084 * must do a sequence (which actually calculates a 64-bit result):
3085 *
3086 * mul(8) acc0<1>D g3<8,8,1>D g4<8,8,1>D
3087 * mach(8) null g3<8,8,1>D g4<8,8,1>D
3088 * mov(8) g2<1>D acc0<8,8,1>D
3089 *
3090 * But on Gen > 6, the ability to use second accumulator register
3091 * (acc1) for non-float data types was removed, preventing a simple
3092 * implementation in SIMD16. A 16-channel result can be calculated by
3093 * executing the three instructions twice in SIMD8, once with quarter
3094 * control of 1Q for the first eight channels and again with 2Q for
3095 * the second eight channels.
3096 *
3097 * Which accumulator register is implicitly accessed (by AccWrEnable
3098 * for instance) is determined by the quarter control. Unfortunately
3099 * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3100 * implicit accumulator access by an instruction with 2Q will access
3101 * acc1 regardless of whether the data type is usable in acc1.
3102 *
3103 * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3104 * integer data types.
3105 *
3106 * Since we only want the low 32-bits of the result, we can do two
3107 * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3108 * adjust the high result and add them (like the mach is doing):
3109 *
3110 * mul(8) g7<1>D g3<8,8,1>D g4.0<8,8,1>UW
3111 * mul(8) g8<1>D g3<8,8,1>D g4.1<8,8,1>UW
3112 * shl(8) g9<1>D g8<8,8,1>D 16D
3113 * add(8) g2<1>D g7<8,8,1>D g8<8,8,1>D
3114 *
3115 * We avoid the shl instruction by realizing that we only want to add
3116 * the low 16-bits of the "high" result to the high 16-bits of the
3117 * "low" result and using proper regioning on the add:
3118 *
3119 * mul(8) g7<1>D g3<8,8,1>D g4.0<16,8,2>UW
3120 * mul(8) g8<1>D g3<8,8,1>D g4.1<16,8,2>UW
3121 * add(8) g7.1<2>UW g7.1<16,8,2>UW g8<16,8,2>UW
3122 *
3123 * Since it does not use the (single) accumulator register, we can
3124 * schedule multi-component multiplications much better.
3125 */
3126
3127 if (inst->conditional_mod && inst->dst.is_null()) {
3128 inst->dst = fs_reg(GRF, alloc.allocate(dispatch_width / 8),
3129 inst->dst.type);
3130 }
3131 fs_reg low = inst->dst;
3132 fs_reg high(GRF, alloc.allocate(dispatch_width / 8),
3133 inst->dst.type);
3134
3135 if (devinfo->gen >= 7) {
3136 fs_reg src1_0_w = inst->src[1];
3137 fs_reg src1_1_w = inst->src[1];
3138
3139 if (inst->src[1].file == IMM) {
3140 src1_0_w.fixed_hw_reg.dw1.ud &= 0xffff;
3141 src1_1_w.fixed_hw_reg.dw1.ud >>= 16;
3142 } else {
3143 src1_0_w.type = BRW_REGISTER_TYPE_UW;
3144 if (src1_0_w.stride != 0) {
3145 assert(src1_0_w.stride == 1);
3146 src1_0_w.stride = 2;
3147 }
3148
3149 src1_1_w.type = BRW_REGISTER_TYPE_UW;
3150 if (src1_1_w.stride != 0) {
3151 assert(src1_1_w.stride == 1);
3152 src1_1_w.stride = 2;
3153 }
3154 src1_1_w.subreg_offset += type_sz(BRW_REGISTER_TYPE_UW);
3155 }
3156 ibld.MUL(low, inst->src[0], src1_0_w);
3157 ibld.MUL(high, inst->src[0], src1_1_w);
3158 } else {
3159 fs_reg src0_0_w = inst->src[0];
3160 fs_reg src0_1_w = inst->src[0];
3161
3162 src0_0_w.type = BRW_REGISTER_TYPE_UW;
3163 if (src0_0_w.stride != 0) {
3164 assert(src0_0_w.stride == 1);
3165 src0_0_w.stride = 2;
3166 }
3167
3168 src0_1_w.type = BRW_REGISTER_TYPE_UW;
3169 if (src0_1_w.stride != 0) {
3170 assert(src0_1_w.stride == 1);
3171 src0_1_w.stride = 2;
3172 }
3173 src0_1_w.subreg_offset += type_sz(BRW_REGISTER_TYPE_UW);
3174
3175 ibld.MUL(low, src0_0_w, inst->src[1]);
3176 ibld.MUL(high, src0_1_w, inst->src[1]);
3177 }
3178
3179 fs_reg dst = inst->dst;
3180 dst.type = BRW_REGISTER_TYPE_UW;
3181 dst.subreg_offset = 2;
3182 dst.stride = 2;
3183
3184 high.type = BRW_REGISTER_TYPE_UW;
3185 high.stride = 2;
3186
3187 low.type = BRW_REGISTER_TYPE_UW;
3188 low.subreg_offset = 2;
3189 low.stride = 2;
3190
3191 ibld.ADD(dst, low, high);
3192
3193 if (inst->conditional_mod) {
3194 fs_reg null(retype(ibld.null_reg_f(), inst->dst.type));
3195 set_condmod(inst->conditional_mod,
3196 ibld.MOV(null, inst->dst));
3197 }
3198 }
3199
3200 inst->remove(block);
3201 progress = true;
3202 }
3203
3204 if (progress)
3205 invalidate_live_intervals();
3206
3207 return progress;
3208 }
3209
3210 static void
3211 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
3212 fs_reg *dst, fs_reg color, unsigned components)
3213 {
3214 if (key->clamp_fragment_color) {
3215 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
3216 assert(color.type == BRW_REGISTER_TYPE_F);
3217
3218 for (unsigned i = 0; i < components; i++)
3219 set_saturate(true,
3220 bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
3221
3222 color = tmp;
3223 }
3224
3225 for (unsigned i = 0; i < components; i++)
3226 dst[i] = offset(color, bld, i);
3227 }
3228
3229 static void
3230 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
3231 const brw_wm_prog_data *prog_data,
3232 const brw_wm_prog_key *key,
3233 const fs_visitor::thread_payload &payload)
3234 {
3235 assert(inst->src[6].file == IMM);
3236 const brw_device_info *devinfo = bld.shader->devinfo;
3237 const fs_reg &color0 = inst->src[0];
3238 const fs_reg &color1 = inst->src[1];
3239 const fs_reg &src0_alpha = inst->src[2];
3240 const fs_reg &src_depth = inst->src[3];
3241 const fs_reg &dst_depth = inst->src[4];
3242 fs_reg sample_mask = inst->src[5];
3243 const unsigned components = inst->src[6].fixed_hw_reg.dw1.ud;
3244
3245 /* We can potentially have a message length of up to 15, so we have to set
3246 * base_mrf to either 0 or 1 in order to fit in m0..m15.
3247 */
3248 fs_reg sources[15];
3249 int header_size = 2, payload_header_size;
3250 unsigned length = 0;
3251
3252 /* From the Sandy Bridge PRM, volume 4, page 198:
3253 *
3254 * "Dispatched Pixel Enables. One bit per pixel indicating
3255 * which pixels were originally enabled when the thread was
3256 * dispatched. This field is only required for the end-of-
3257 * thread message and on all dual-source messages."
3258 */
3259 if (devinfo->gen >= 6 &&
3260 (devinfo->is_haswell || devinfo->gen >= 8 || !prog_data->uses_kill) &&
3261 color1.file == BAD_FILE &&
3262 key->nr_color_regions == 1) {
3263 header_size = 0;
3264 }
3265
3266 if (header_size != 0) {
3267 assert(header_size == 2);
3268 /* Allocate 2 registers for a header */
3269 length += 2;
3270 }
3271
3272 if (payload.aa_dest_stencil_reg) {
3273 sources[length] = fs_reg(GRF, bld.shader->alloc.allocate(1));
3274 bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
3275 .MOV(sources[length],
3276 fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg, 0)));
3277 length++;
3278 }
3279
3280 if (prog_data->uses_omask) {
3281 sources[length] = fs_reg(GRF, bld.shader->alloc.allocate(1),
3282 BRW_REGISTER_TYPE_UD);
3283
3284 /* Hand over gl_SampleMask. Only the lower 16 bits of each channel are
3285 * relevant. Since it's unsigned single words one vgrf is always
3286 * 16-wide, but only the lower or higher 8 channels will be used by the
3287 * hardware when doing a SIMD8 write depending on whether we have
3288 * selected the subspans for the first or second half respectively.
3289 */
3290 assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
3291 sample_mask.type = BRW_REGISTER_TYPE_UW;
3292 sample_mask.stride *= 2;
3293
3294 bld.exec_all().annotate("FB write oMask")
3295 .MOV(half(retype(sources[length], BRW_REGISTER_TYPE_UW),
3296 inst->force_sechalf),
3297 sample_mask);
3298 length++;
3299 }
3300
3301 payload_header_size = length;
3302
3303 if (src0_alpha.file != BAD_FILE) {
3304 /* FIXME: This is being passed at the wrong location in the payload and
3305 * doesn't work when gl_SampleMask and MRTs are used simultaneously.
3306 * It's supposed to be immediately before oMask but there seems to be no
3307 * reasonable way to pass them in the correct order because LOAD_PAYLOAD
3308 * requires header sources to form a contiguous segment at the beginning
3309 * of the message and src0_alpha has per-channel semantics.
3310 */
3311 setup_color_payload(bld, key, &sources[length], src0_alpha, 1);
3312 length++;
3313 }
3314
3315 setup_color_payload(bld, key, &sources[length], color0, components);
3316 length += 4;
3317
3318 if (color1.file != BAD_FILE) {
3319 setup_color_payload(bld, key, &sources[length], color1, components);
3320 length += 4;
3321 }
3322
3323 if (src_depth.file != BAD_FILE) {
3324 sources[length] = src_depth;
3325 length++;
3326 }
3327
3328 if (dst_depth.file != BAD_FILE) {
3329 sources[length] = dst_depth;
3330 length++;
3331 }
3332
3333 fs_inst *load;
3334 if (devinfo->gen >= 7) {
3335 /* Send from the GRF */
3336 fs_reg payload = fs_reg(GRF, -1, BRW_REGISTER_TYPE_F);
3337 load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
3338 payload.reg = bld.shader->alloc.allocate(load->regs_written);
3339 load->dst = payload;
3340
3341 inst->src[0] = payload;
3342 inst->resize_sources(1);
3343 inst->base_mrf = -1;
3344 } else {
3345 /* Send from the MRF */
3346 load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
3347 sources, length, payload_header_size);
3348
3349 /* On pre-SNB, we have to interlace the color values. LOAD_PAYLOAD
3350 * will do this for us if we just give it a COMPR4 destination.
3351 */
3352 if (devinfo->gen < 6 && bld.dispatch_width() == 16)
3353 load->dst.reg |= BRW_MRF_COMPR4;
3354
3355 inst->resize_sources(0);
3356 inst->base_mrf = 1;
3357 }
3358
3359 inst->opcode = FS_OPCODE_FB_WRITE;
3360 inst->mlen = load->regs_written;
3361 inst->header_size = header_size;
3362 }
3363
3364 bool
3365 fs_visitor::lower_logical_sends()
3366 {
3367 bool progress = false;
3368
3369 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3370 const fs_builder ibld = bld.exec_all(inst->force_writemask_all)
3371 .group(inst->exec_size, inst->force_sechalf)
3372 .at(block, inst);
3373
3374 switch (inst->opcode) {
3375 case FS_OPCODE_FB_WRITE_LOGICAL:
3376 assert(stage == MESA_SHADER_FRAGMENT);
3377 lower_fb_write_logical_send(ibld, inst,
3378 (const brw_wm_prog_data *)prog_data,
3379 (const brw_wm_prog_key *)key,
3380 payload);
3381 break;
3382
3383 default:
3384 continue;
3385 }
3386
3387 progress = true;
3388 }
3389
3390 if (progress)
3391 invalidate_live_intervals();
3392
3393 return progress;
3394 }
3395
3396 /**
3397 * Get the closest native SIMD width supported by the hardware for instruction
3398 * \p inst. The instruction will be left untouched by
3399 * fs_visitor::lower_simd_width() if the returned value is equal to the
3400 * original execution size.
3401 */
3402 static unsigned
3403 get_lowered_simd_width(const struct brw_device_info *devinfo,
3404 const fs_inst *inst)
3405 {
3406 switch (inst->opcode) {
3407 case FS_OPCODE_FB_WRITE_LOGICAL:
3408 /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
3409 * here.
3410 */
3411 assert(devinfo->gen != 6 || inst->src[3].file == BAD_FILE ||
3412 inst->exec_size == 8);
3413 /* Dual-source FB writes are unsupported in SIMD16 mode. */
3414 return (inst->src[1].file != BAD_FILE ? 8 : inst->exec_size);
3415
3416 default:
3417 return inst->exec_size;
3418 }
3419 }
3420
3421 /**
3422 * The \p rows array of registers represents a \p num_rows by \p num_columns
3423 * matrix in row-major order, write it in column-major order into the register
3424 * passed as destination. \p stride gives the separation between matrix
3425 * elements in the input in fs_builder::dispatch_width() units.
3426 */
3427 static void
3428 emit_transpose(const fs_builder &bld,
3429 const fs_reg &dst, const fs_reg *rows,
3430 unsigned num_rows, unsigned num_columns, unsigned stride)
3431 {
3432 fs_reg *const components = new fs_reg[num_rows * num_columns];
3433
3434 for (unsigned i = 0; i < num_columns; ++i) {
3435 for (unsigned j = 0; j < num_rows; ++j)
3436 components[num_rows * i + j] = offset(rows[j], bld, stride * i);
3437 }
3438
3439 bld.LOAD_PAYLOAD(dst, components, num_rows * num_columns, 0);
3440
3441 delete[] components;
3442 }
3443
3444 bool
3445 fs_visitor::lower_simd_width()
3446 {
3447 bool progress = false;
3448
3449 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3450 const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
3451
3452 if (lower_width != inst->exec_size) {
3453 /* Builder matching the original instruction. */
3454 const fs_builder ibld = bld.at(block, inst)
3455 .exec_all(inst->force_writemask_all)
3456 .group(inst->exec_size, inst->force_sechalf);
3457
3458 /* Split the copies in chunks of the execution width of either the
3459 * original or the lowered instruction, whichever is lower.
3460 */
3461 const unsigned copy_width = MIN2(lower_width, inst->exec_size);
3462 const unsigned n = inst->exec_size / copy_width;
3463 const unsigned dst_size = inst->regs_written * REG_SIZE /
3464 inst->dst.component_size(inst->exec_size);
3465 fs_reg dsts[4];
3466
3467 assert(n > 0 && n <= ARRAY_SIZE(dsts) &&
3468 !inst->writes_accumulator && !inst->mlen);
3469
3470 for (unsigned i = 0; i < n; i++) {
3471 /* Emit a copy of the original instruction with the lowered width.
3472 * If the EOT flag was set throw it away except for the last
3473 * instruction to avoid killing the thread prematurely.
3474 */
3475 fs_inst split_inst = *inst;
3476 split_inst.exec_size = lower_width;
3477 split_inst.eot = inst->eot && i == n - 1;
3478
3479 /* Set exec_all if the lowered width is higher than the original
3480 * to avoid breaking the compiler invariant that no control
3481 * flow-masked instruction is wider than the shader's
3482 * dispatch_width. Then transform the sources and destination and
3483 * emit the lowered instruction.
3484 */
3485 const fs_builder lbld = ibld.exec_all(lower_width > inst->exec_size)
3486 .group(lower_width, i);
3487
3488 for (unsigned j = 0; j < inst->sources; j++) {
3489 if (inst->src[j].file != BAD_FILE &&
3490 !is_uniform(inst->src[j])) {
3491 /* Get the i-th copy_width-wide chunk of the source. */
3492 const fs_reg src = horiz_offset(inst->src[j], copy_width * i);
3493 const unsigned src_size = inst->components_read(j);
3494
3495 /* Use a trivial transposition to copy one every n
3496 * copy_width-wide components of the register into a
3497 * temporary passed as source to the lowered instruction.
3498 */
3499 split_inst.src[j] = lbld.vgrf(inst->src[j].type, src_size);
3500 emit_transpose(lbld.group(copy_width, 0),
3501 split_inst.src[j], &src, 1, src_size, n);
3502 }
3503 }
3504
3505 if (inst->regs_written) {
3506 /* Allocate enough space to hold the result of the lowered
3507 * instruction and fix up the number of registers written.
3508 */
3509 split_inst.dst = dsts[i] =
3510 lbld.vgrf(inst->dst.type, dst_size);
3511 split_inst.regs_written =
3512 DIV_ROUND_UP(inst->regs_written * lower_width,
3513 inst->exec_size);
3514 }
3515
3516 lbld.emit(split_inst);
3517 }
3518
3519 if (inst->regs_written) {
3520 /* Distance between useful channels in the temporaries, skipping
3521 * garbage if the lowered instruction is wider than the original.
3522 */
3523 const unsigned m = lower_width / copy_width;
3524
3525 /* Interleave the components of the result from the lowered
3526 * instructions. We need to set exec_all() when copying more than
3527 * one half per component, because LOAD_PAYLOAD (in terms of which
3528 * emit_transpose is implemented) can only use the same channel
3529 * enable signals for all of its non-header sources.
3530 */
3531 emit_transpose(ibld.exec_all(inst->exec_size > copy_width)
3532 .group(copy_width, 0),
3533 inst->dst, dsts, n, dst_size, m);
3534 }
3535
3536 inst->remove(block);
3537 progress = true;
3538 }
3539 }
3540
3541 if (progress)
3542 invalidate_live_intervals();
3543
3544 return progress;
3545 }
3546
3547 void
3548 fs_visitor::dump_instructions()
3549 {
3550 dump_instructions(NULL);
3551 }
3552
3553 void
3554 fs_visitor::dump_instructions(const char *name)
3555 {
3556 FILE *file = stderr;
3557 if (name && geteuid() != 0) {
3558 file = fopen(name, "w");
3559 if (!file)
3560 file = stderr;
3561 }
3562
3563 if (cfg) {
3564 calculate_register_pressure();
3565 int ip = 0, max_pressure = 0;
3566 foreach_block_and_inst(block, backend_instruction, inst, cfg) {
3567 max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
3568 fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
3569 dump_instruction(inst, file);
3570 ip++;
3571 }
3572 fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
3573 } else {
3574 int ip = 0;
3575 foreach_in_list(backend_instruction, inst, &instructions) {
3576 fprintf(file, "%4d: ", ip++);
3577 dump_instruction(inst, file);
3578 }
3579 }
3580
3581 if (file != stderr) {
3582 fclose(file);
3583 }
3584 }
3585
3586 void
3587 fs_visitor::dump_instruction(backend_instruction *be_inst)
3588 {
3589 dump_instruction(be_inst, stderr);
3590 }
3591
3592 void
3593 fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
3594 {
3595 fs_inst *inst = (fs_inst *)be_inst;
3596
3597 if (inst->predicate) {
3598 fprintf(file, "(%cf0.%d) ",
3599 inst->predicate_inverse ? '-' : '+',
3600 inst->flag_subreg);
3601 }
3602
3603 fprintf(file, "%s", brw_instruction_name(inst->opcode));
3604 if (inst->saturate)
3605 fprintf(file, ".sat");
3606 if (inst->conditional_mod) {
3607 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
3608 if (!inst->predicate &&
3609 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
3610 inst->opcode != BRW_OPCODE_IF &&
3611 inst->opcode != BRW_OPCODE_WHILE))) {
3612 fprintf(file, ".f0.%d", inst->flag_subreg);
3613 }
3614 }
3615 fprintf(file, "(%d) ", inst->exec_size);
3616
3617 if (inst->mlen) {
3618 fprintf(file, "(mlen: %d) ", inst->mlen);
3619 }
3620
3621 switch (inst->dst.file) {
3622 case GRF:
3623 fprintf(file, "vgrf%d", inst->dst.reg);
3624 if (alloc.sizes[inst->dst.reg] != inst->regs_written ||
3625 inst->dst.subreg_offset)
3626 fprintf(file, "+%d.%d",
3627 inst->dst.reg_offset, inst->dst.subreg_offset);
3628 break;
3629 case MRF:
3630 fprintf(file, "m%d", inst->dst.reg);
3631 break;
3632 case BAD_FILE:
3633 fprintf(file, "(null)");
3634 break;
3635 case UNIFORM:
3636 fprintf(file, "***u%d***", inst->dst.reg + inst->dst.reg_offset);
3637 break;
3638 case ATTR:
3639 fprintf(file, "***attr%d***", inst->dst.reg + inst->dst.reg_offset);
3640 break;
3641 case HW_REG:
3642 if (inst->dst.fixed_hw_reg.file == BRW_ARCHITECTURE_REGISTER_FILE) {
3643 switch (inst->dst.fixed_hw_reg.nr) {
3644 case BRW_ARF_NULL:
3645 fprintf(file, "null");
3646 break;
3647 case BRW_ARF_ADDRESS:
3648 fprintf(file, "a0.%d", inst->dst.fixed_hw_reg.subnr);
3649 break;
3650 case BRW_ARF_ACCUMULATOR:
3651 fprintf(file, "acc%d", inst->dst.fixed_hw_reg.subnr);
3652 break;
3653 case BRW_ARF_FLAG:
3654 fprintf(file, "f%d.%d", inst->dst.fixed_hw_reg.nr & 0xf,
3655 inst->dst.fixed_hw_reg.subnr);
3656 break;
3657 default:
3658 fprintf(file, "arf%d.%d", inst->dst.fixed_hw_reg.nr & 0xf,
3659 inst->dst.fixed_hw_reg.subnr);
3660 break;
3661 }
3662 } else {
3663 fprintf(file, "hw_reg%d", inst->dst.fixed_hw_reg.nr);
3664 }
3665 if (inst->dst.fixed_hw_reg.subnr)
3666 fprintf(file, "+%d", inst->dst.fixed_hw_reg.subnr);
3667 break;
3668 default:
3669 fprintf(file, "???");
3670 break;
3671 }
3672 fprintf(file, ":%s, ", brw_reg_type_letters(inst->dst.type));
3673
3674 for (int i = 0; i < inst->sources; i++) {
3675 if (inst->src[i].negate)
3676 fprintf(file, "-");
3677 if (inst->src[i].abs)
3678 fprintf(file, "|");
3679 switch (inst->src[i].file) {
3680 case GRF:
3681 fprintf(file, "vgrf%d", inst->src[i].reg);
3682 if (alloc.sizes[inst->src[i].reg] != (unsigned)inst->regs_read(i) ||
3683 inst->src[i].subreg_offset)
3684 fprintf(file, "+%d.%d", inst->src[i].reg_offset,
3685 inst->src[i].subreg_offset);
3686 break;
3687 case MRF:
3688 fprintf(file, "***m%d***", inst->src[i].reg);
3689 break;
3690 case ATTR:
3691 fprintf(file, "attr%d", inst->src[i].reg + inst->src[i].reg_offset);
3692 break;
3693 case UNIFORM:
3694 fprintf(file, "u%d", inst->src[i].reg + inst->src[i].reg_offset);
3695 if (inst->src[i].reladdr) {
3696 fprintf(file, "+reladdr");
3697 } else if (inst->src[i].subreg_offset) {
3698 fprintf(file, "+%d.%d", inst->src[i].reg_offset,
3699 inst->src[i].subreg_offset);
3700 }
3701 break;
3702 case BAD_FILE:
3703 fprintf(file, "(null)");
3704 break;
3705 case IMM:
3706 switch (inst->src[i].type) {
3707 case BRW_REGISTER_TYPE_F:
3708 fprintf(file, "%ff", inst->src[i].fixed_hw_reg.dw1.f);
3709 break;
3710 case BRW_REGISTER_TYPE_W:
3711 case BRW_REGISTER_TYPE_D:
3712 fprintf(file, "%dd", inst->src[i].fixed_hw_reg.dw1.d);
3713 break;
3714 case BRW_REGISTER_TYPE_UW:
3715 case BRW_REGISTER_TYPE_UD:
3716 fprintf(file, "%uu", inst->src[i].fixed_hw_reg.dw1.ud);
3717 break;
3718 case BRW_REGISTER_TYPE_VF:
3719 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
3720 brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 0) & 0xff),
3721 brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 8) & 0xff),
3722 brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 16) & 0xff),
3723 brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 24) & 0xff));
3724 break;
3725 default:
3726 fprintf(file, "???");
3727 break;
3728 }
3729 break;
3730 case HW_REG:
3731 if (inst->src[i].fixed_hw_reg.negate)
3732 fprintf(file, "-");
3733 if (inst->src[i].fixed_hw_reg.abs)
3734 fprintf(file, "|");
3735 if (inst->src[i].fixed_hw_reg.file == BRW_ARCHITECTURE_REGISTER_FILE) {
3736 switch (inst->src[i].fixed_hw_reg.nr) {
3737 case BRW_ARF_NULL:
3738 fprintf(file, "null");
3739 break;
3740 case BRW_ARF_ADDRESS:
3741 fprintf(file, "a0.%d", inst->src[i].fixed_hw_reg.subnr);
3742 break;
3743 case BRW_ARF_ACCUMULATOR:
3744 fprintf(file, "acc%d", inst->src[i].fixed_hw_reg.subnr);
3745 break;
3746 case BRW_ARF_FLAG:
3747 fprintf(file, "f%d.%d", inst->src[i].fixed_hw_reg.nr & 0xf,
3748 inst->src[i].fixed_hw_reg.subnr);
3749 break;
3750 default:
3751 fprintf(file, "arf%d.%d", inst->src[i].fixed_hw_reg.nr & 0xf,
3752 inst->src[i].fixed_hw_reg.subnr);
3753 break;
3754 }
3755 } else {
3756 fprintf(file, "hw_reg%d", inst->src[i].fixed_hw_reg.nr);
3757 }
3758 if (inst->src[i].fixed_hw_reg.subnr)
3759 fprintf(file, "+%d", inst->src[i].fixed_hw_reg.subnr);
3760 if (inst->src[i].fixed_hw_reg.abs)
3761 fprintf(file, "|");
3762 break;
3763 default:
3764 fprintf(file, "???");
3765 break;
3766 }
3767 if (inst->src[i].abs)
3768 fprintf(file, "|");
3769
3770 if (inst->src[i].file != IMM) {
3771 fprintf(file, ":%s", brw_reg_type_letters(inst->src[i].type));
3772 }
3773
3774 if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
3775 fprintf(file, ", ");
3776 }
3777
3778 fprintf(file, " ");
3779
3780 if (dispatch_width == 16 && inst->exec_size == 8) {
3781 if (inst->force_sechalf)
3782 fprintf(file, "2ndhalf ");
3783 else
3784 fprintf(file, "1sthalf ");
3785 }
3786
3787 fprintf(file, "\n");
3788 }
3789
3790 /**
3791 * Possibly returns an instruction that set up @param reg.
3792 *
3793 * Sometimes we want to take the result of some expression/variable
3794 * dereference tree and rewrite the instruction generating the result
3795 * of the tree. When processing the tree, we know that the
3796 * instructions generated are all writing temporaries that are dead
3797 * outside of this tree. So, if we have some instructions that write
3798 * a temporary, we're free to point that temp write somewhere else.
3799 *
3800 * Note that this doesn't guarantee that the instruction generated
3801 * only reg -- it might be the size=4 destination of a texture instruction.
3802 */
3803 fs_inst *
3804 fs_visitor::get_instruction_generating_reg(fs_inst *start,
3805 fs_inst *end,
3806 const fs_reg &reg)
3807 {
3808 if (end == start ||
3809 end->is_partial_write() ||
3810 reg.reladdr ||
3811 !reg.equals(end->dst)) {
3812 return NULL;
3813 } else {
3814 return end;
3815 }
3816 }
3817
3818 void
3819 fs_visitor::setup_payload_gen6()
3820 {
3821 bool uses_depth =
3822 (prog->InputsRead & (1 << VARYING_SLOT_POS)) != 0;
3823 unsigned barycentric_interp_modes =
3824 (stage == MESA_SHADER_FRAGMENT) ?
3825 ((brw_wm_prog_data*) this->prog_data)->barycentric_interp_modes : 0;
3826
3827 assert(devinfo->gen >= 6);
3828
3829 /* R0-1: masks, pixel X/Y coordinates. */
3830 payload.num_regs = 2;
3831 /* R2: only for 32-pixel dispatch.*/
3832
3833 /* R3-26: barycentric interpolation coordinates. These appear in the
3834 * same order that they appear in the brw_wm_barycentric_interp_mode
3835 * enum. Each set of coordinates occupies 2 registers if dispatch width
3836 * == 8 and 4 registers if dispatch width == 16. Coordinates only
3837 * appear if they were enabled using the "Barycentric Interpolation
3838 * Mode" bits in WM_STATE.
3839 */
3840 for (int i = 0; i < BRW_WM_BARYCENTRIC_INTERP_MODE_COUNT; ++i) {
3841 if (barycentric_interp_modes & (1 << i)) {
3842 payload.barycentric_coord_reg[i] = payload.num_regs;
3843 payload.num_regs += 2;
3844 if (dispatch_width == 16) {
3845 payload.num_regs += 2;
3846 }
3847 }
3848 }
3849
3850 /* R27: interpolated depth if uses source depth */
3851 if (uses_depth) {
3852 payload.source_depth_reg = payload.num_regs;
3853 payload.num_regs++;
3854 if (dispatch_width == 16) {
3855 /* R28: interpolated depth if not SIMD8. */
3856 payload.num_regs++;
3857 }
3858 }
3859 /* R29: interpolated W set if GEN6_WM_USES_SOURCE_W. */
3860 if (uses_depth) {
3861 payload.source_w_reg = payload.num_regs;
3862 payload.num_regs++;
3863 if (dispatch_width == 16) {
3864 /* R30: interpolated W if not SIMD8. */
3865 payload.num_regs++;
3866 }
3867 }
3868
3869 if (stage == MESA_SHADER_FRAGMENT) {
3870 brw_wm_prog_data *prog_data = (brw_wm_prog_data*) this->prog_data;
3871 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3872 prog_data->uses_pos_offset = key->compute_pos_offset;
3873 /* R31: MSAA position offsets. */
3874 if (prog_data->uses_pos_offset) {
3875 payload.sample_pos_reg = payload.num_regs;
3876 payload.num_regs++;
3877 }
3878 }
3879
3880 /* R32: MSAA input coverage mask */
3881 if (prog->SystemValuesRead & SYSTEM_BIT_SAMPLE_MASK_IN) {
3882 assert(devinfo->gen >= 7);
3883 payload.sample_mask_in_reg = payload.num_regs;
3884 payload.num_regs++;
3885 if (dispatch_width == 16) {
3886 /* R33: input coverage mask if not SIMD8. */
3887 payload.num_regs++;
3888 }
3889 }
3890
3891 /* R34-: bary for 32-pixel. */
3892 /* R58-59: interp W for 32-pixel. */
3893
3894 if (prog->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
3895 source_depth_to_render_target = true;
3896 }
3897 }
3898
3899 void
3900 fs_visitor::setup_vs_payload()
3901 {
3902 /* R0: thread header, R1: urb handles */
3903 payload.num_regs = 2;
3904 }
3905
3906 void
3907 fs_visitor::setup_cs_payload()
3908 {
3909 assert(devinfo->gen >= 7);
3910
3911 payload.num_regs = 1;
3912 }
3913
3914 void
3915 fs_visitor::assign_binding_table_offsets()
3916 {
3917 assert(stage == MESA_SHADER_FRAGMENT);
3918 brw_wm_prog_data *prog_data = (brw_wm_prog_data*) this->prog_data;
3919 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3920 uint32_t next_binding_table_offset = 0;
3921
3922 /* If there are no color regions, we still perform an FB write to a null
3923 * renderbuffer, which we place at surface index 0.
3924 */
3925 prog_data->binding_table.render_target_start = next_binding_table_offset;
3926 next_binding_table_offset += MAX2(key->nr_color_regions, 1);
3927
3928 assign_common_binding_table_offsets(next_binding_table_offset);
3929 }
3930
3931 void
3932 fs_visitor::calculate_register_pressure()
3933 {
3934 invalidate_live_intervals();
3935 calculate_live_intervals();
3936
3937 unsigned num_instructions = 0;
3938 foreach_block(block, cfg)
3939 num_instructions += block->instructions.length();
3940
3941 regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
3942
3943 for (unsigned reg = 0; reg < alloc.count; reg++) {
3944 for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
3945 regs_live_at_ip[ip] += alloc.sizes[reg];
3946 }
3947 }
3948
3949 void
3950 fs_visitor::optimize()
3951 {
3952 /* bld is the common builder object pointing at the end of the program we
3953 * used to translate it into i965 IR. For the optimization and lowering
3954 * passes coming next, any code added after the end of the program without
3955 * having explicitly called fs_builder::at() clearly points at a mistake.
3956 * Ideally optimization passes wouldn't be part of the visitor so they
3957 * wouldn't have access to bld at all, but they do, so just in case some
3958 * pass forgets to ask for a location explicitly set it to NULL here to
3959 * make it trip.
3960 */
3961 bld = bld.at(NULL, NULL);
3962
3963 split_virtual_grfs();
3964
3965 move_uniform_array_access_to_pull_constants();
3966 assign_constant_locations();
3967 demote_pull_constants();
3968
3969 #define OPT(pass, args...) ({ \
3970 pass_num++; \
3971 bool this_progress = pass(args); \
3972 \
3973 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
3974 char filename[64]; \
3975 snprintf(filename, 64, "%s%d-%04d-%02d-%02d-" #pass, \
3976 stage_abbrev, dispatch_width, shader_prog ? shader_prog->Name : 0, iteration, pass_num); \
3977 \
3978 backend_shader::dump_instructions(filename); \
3979 } \
3980 \
3981 progress = progress || this_progress; \
3982 this_progress; \
3983 })
3984
3985 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
3986 char filename[64];
3987 snprintf(filename, 64, "%s%d-%04d-00-start",
3988 stage_abbrev, dispatch_width,
3989 shader_prog ? shader_prog->Name : 0);
3990
3991 backend_shader::dump_instructions(filename);
3992 }
3993
3994 bool progress = false;
3995 int iteration = 0;
3996 int pass_num = 0;
3997
3998 OPT(lower_simd_width);
3999 OPT(lower_logical_sends);
4000
4001 do {
4002 progress = false;
4003 pass_num = 0;
4004 iteration++;
4005
4006 OPT(remove_duplicate_mrf_writes);
4007
4008 OPT(opt_algebraic);
4009 OPT(opt_cse);
4010 OPT(opt_copy_propagate);
4011 OPT(opt_peephole_predicated_break);
4012 OPT(opt_cmod_propagation);
4013 OPT(dead_code_eliminate);
4014 OPT(opt_peephole_sel);
4015 OPT(dead_control_flow_eliminate, this);
4016 OPT(opt_register_renaming);
4017 OPT(opt_redundant_discard_jumps);
4018 OPT(opt_saturate_propagation);
4019 OPT(opt_zero_samples);
4020 OPT(register_coalesce);
4021 OPT(compute_to_mrf);
4022 OPT(eliminate_find_live_channel);
4023
4024 OPT(compact_virtual_grfs);
4025 } while (progress);
4026
4027 pass_num = 0;
4028
4029 OPT(opt_sampler_eot);
4030
4031 if (OPT(lower_load_payload)) {
4032 split_virtual_grfs();
4033 OPT(register_coalesce);
4034 OPT(compute_to_mrf);
4035 OPT(dead_code_eliminate);
4036 }
4037
4038 OPT(opt_combine_constants);
4039 OPT(lower_integer_multiplication);
4040
4041 lower_uniform_pull_constant_loads();
4042 }
4043
4044 /**
4045 * Three source instruction must have a GRF/MRF destination register.
4046 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
4047 */
4048 void
4049 fs_visitor::fixup_3src_null_dest()
4050 {
4051 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
4052 if (inst->is_3src() && inst->dst.is_null()) {
4053 inst->dst = fs_reg(GRF, alloc.allocate(dispatch_width / 8),
4054 inst->dst.type);
4055 }
4056 }
4057 }
4058
4059 void
4060 fs_visitor::allocate_registers()
4061 {
4062 bool allocated_without_spills;
4063
4064 static const enum instruction_scheduler_mode pre_modes[] = {
4065 SCHEDULE_PRE,
4066 SCHEDULE_PRE_NON_LIFO,
4067 SCHEDULE_PRE_LIFO,
4068 };
4069
4070 /* Try each scheduling heuristic to see if it can successfully register
4071 * allocate without spilling. They should be ordered by decreasing
4072 * performance but increasing likelihood of allocating.
4073 */
4074 for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
4075 schedule_instructions(pre_modes[i]);
4076
4077 if (0) {
4078 assign_regs_trivial();
4079 allocated_without_spills = true;
4080 } else {
4081 allocated_without_spills = assign_regs(false);
4082 }
4083 if (allocated_without_spills)
4084 break;
4085 }
4086
4087 if (!allocated_without_spills) {
4088 /* We assume that any spilling is worse than just dropping back to
4089 * SIMD8. There's probably actually some intermediate point where
4090 * SIMD16 with a couple of spills is still better.
4091 */
4092 if (dispatch_width == 16) {
4093 fail("Failure to register allocate. Reduce number of "
4094 "live scalar values to avoid this.");
4095 } else {
4096 compiler->shader_perf_log(log_data,
4097 "%s shader triggered register spilling. "
4098 "Try reducing the number of live scalar "
4099 "values to improve performance.\n",
4100 stage_name);
4101 }
4102
4103 /* Since we're out of heuristics, just go spill registers until we
4104 * get an allocation.
4105 */
4106 while (!assign_regs(true)) {
4107 if (failed)
4108 break;
4109 }
4110 }
4111
4112 /* This must come after all optimization and register allocation, since
4113 * it inserts dead code that happens to have side effects, and it does
4114 * so based on the actual physical registers in use.
4115 */
4116 insert_gen4_send_dependency_workarounds();
4117
4118 if (failed)
4119 return;
4120
4121 if (!allocated_without_spills)
4122 schedule_instructions(SCHEDULE_POST);
4123
4124 if (last_scratch > 0)
4125 prog_data->total_scratch = brw_get_scratch_size(last_scratch);
4126 }
4127
4128 bool
4129 fs_visitor::run_vs(gl_clip_plane *clip_planes)
4130 {
4131 assert(stage == MESA_SHADER_VERTEX);
4132
4133 assign_common_binding_table_offsets(0);
4134 setup_vs_payload();
4135
4136 if (shader_time_index >= 0)
4137 emit_shader_time_begin();
4138
4139 emit_nir_code();
4140
4141 if (failed)
4142 return false;
4143
4144 compute_clip_distance(clip_planes);
4145
4146 emit_urb_writes();
4147
4148 if (shader_time_index >= 0)
4149 emit_shader_time_end();
4150
4151 calculate_cfg();
4152
4153 optimize();
4154
4155 assign_curb_setup();
4156 assign_vs_urb_setup();
4157
4158 fixup_3src_null_dest();
4159 allocate_registers();
4160
4161 return !failed;
4162 }
4163
4164 bool
4165 fs_visitor::run_fs(bool do_rep_send)
4166 {
4167 brw_wm_prog_data *wm_prog_data = (brw_wm_prog_data *) this->prog_data;
4168 brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
4169
4170 assert(stage == MESA_SHADER_FRAGMENT);
4171
4172 sanity_param_count = prog->Parameters->NumParameters;
4173
4174 assign_binding_table_offsets();
4175
4176 if (devinfo->gen >= 6)
4177 setup_payload_gen6();
4178 else
4179 setup_payload_gen4();
4180
4181 if (0) {
4182 emit_dummy_fs();
4183 } else if (do_rep_send) {
4184 assert(dispatch_width == 16);
4185 emit_repclear_shader();
4186 } else {
4187 if (shader_time_index >= 0)
4188 emit_shader_time_begin();
4189
4190 calculate_urb_setup();
4191 if (prog->InputsRead > 0) {
4192 if (devinfo->gen < 6)
4193 emit_interpolation_setup_gen4();
4194 else
4195 emit_interpolation_setup_gen6();
4196 }
4197
4198 /* We handle discards by keeping track of the still-live pixels in f0.1.
4199 * Initialize it with the dispatched pixels.
4200 */
4201 if (wm_prog_data->uses_kill) {
4202 fs_inst *discard_init = bld.emit(FS_OPCODE_MOV_DISPATCH_TO_FLAGS);
4203 discard_init->flag_subreg = 1;
4204 }
4205
4206 /* Generate FS IR for main(). (the visitor only descends into
4207 * functions called "main").
4208 */
4209 emit_nir_code();
4210
4211 if (failed)
4212 return false;
4213
4214 if (wm_prog_data->uses_kill)
4215 bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
4216
4217 if (wm_key->alpha_test_func)
4218 emit_alpha_test();
4219
4220 emit_fb_writes();
4221
4222 if (shader_time_index >= 0)
4223 emit_shader_time_end();
4224
4225 calculate_cfg();
4226
4227 optimize();
4228
4229 assign_curb_setup();
4230 assign_urb_setup();
4231
4232 fixup_3src_null_dest();
4233 allocate_registers();
4234
4235 if (failed)
4236 return false;
4237 }
4238
4239 if (dispatch_width == 8)
4240 wm_prog_data->reg_blocks = brw_register_blocks(grf_used);
4241 else
4242 wm_prog_data->reg_blocks_16 = brw_register_blocks(grf_used);
4243
4244 /* If any state parameters were appended, then ParameterValues could have
4245 * been realloced, in which case the driver uniform storage set up by
4246 * _mesa_associate_uniform_storage() would point to freed memory. Make
4247 * sure that didn't happen.
4248 */
4249 assert(sanity_param_count == prog->Parameters->NumParameters);
4250
4251 return !failed;
4252 }
4253
4254 bool
4255 fs_visitor::run_cs()
4256 {
4257 assert(stage == MESA_SHADER_COMPUTE);
4258 assert(shader);
4259
4260 sanity_param_count = prog->Parameters->NumParameters;
4261
4262 assign_common_binding_table_offsets(0);
4263
4264 setup_cs_payload();
4265
4266 if (shader_time_index >= 0)
4267 emit_shader_time_begin();
4268
4269 emit_nir_code();
4270
4271 if (failed)
4272 return false;
4273
4274 emit_cs_terminate();
4275
4276 if (shader_time_index >= 0)
4277 emit_shader_time_end();
4278
4279 calculate_cfg();
4280
4281 optimize();
4282
4283 assign_curb_setup();
4284
4285 fixup_3src_null_dest();
4286 allocate_registers();
4287
4288 if (failed)
4289 return false;
4290
4291 /* If any state parameters were appended, then ParameterValues could have
4292 * been realloced, in which case the driver uniform storage set up by
4293 * _mesa_associate_uniform_storage() would point to freed memory. Make
4294 * sure that didn't happen.
4295 */
4296 assert(sanity_param_count == prog->Parameters->NumParameters);
4297
4298 return !failed;
4299 }
4300
4301 const unsigned *
4302 brw_wm_fs_emit(struct brw_context *brw,
4303 void *mem_ctx,
4304 const struct brw_wm_prog_key *key,
4305 struct brw_wm_prog_data *prog_data,
4306 struct gl_fragment_program *fp,
4307 struct gl_shader_program *prog,
4308 unsigned *final_assembly_size)
4309 {
4310 bool start_busy = false;
4311 double start_time = 0;
4312
4313 if (unlikely(brw->perf_debug)) {
4314 start_busy = (brw->batch.last_bo &&
4315 drm_intel_bo_busy(brw->batch.last_bo));
4316 start_time = get_time();
4317 }
4318
4319 struct brw_shader *shader = NULL;
4320 if (prog)
4321 shader = (brw_shader *) prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
4322
4323 if (unlikely(INTEL_DEBUG & DEBUG_WM))
4324 brw_dump_ir("fragment", prog, &shader->base, &fp->Base);
4325
4326 int st_index8 = -1, st_index16 = -1;
4327 if (INTEL_DEBUG & DEBUG_SHADER_TIME) {
4328 st_index8 = brw_get_shader_time_index(brw, prog, &fp->Base, ST_FS8);
4329 st_index16 = brw_get_shader_time_index(brw, prog, &fp->Base, ST_FS16);
4330 }
4331
4332 /* Now the main event: Visit the shader IR and generate our FS IR for it.
4333 */
4334 fs_visitor v(brw->intelScreen->compiler, brw,
4335 mem_ctx, MESA_SHADER_FRAGMENT, key, &prog_data->base,
4336 prog, &fp->Base, 8, st_index8);
4337 if (!v.run_fs(false /* do_rep_send */)) {
4338 if (prog) {
4339 prog->LinkStatus = false;
4340 ralloc_strcat(&prog->InfoLog, v.fail_msg);
4341 }
4342
4343 _mesa_problem(NULL, "Failed to compile fragment shader: %s\n",
4344 v.fail_msg);
4345
4346 return NULL;
4347 }
4348
4349 cfg_t *simd16_cfg = NULL;
4350 fs_visitor v2(brw->intelScreen->compiler, brw,
4351 mem_ctx, MESA_SHADER_FRAGMENT, key, &prog_data->base,
4352 prog, &fp->Base, 16, st_index16);
4353 if (likely(!(INTEL_DEBUG & DEBUG_NO16) || brw->use_rep_send)) {
4354 if (!v.simd16_unsupported) {
4355 /* Try a SIMD16 compile */
4356 v2.import_uniforms(&v);
4357 if (!v2.run_fs(brw->use_rep_send)) {
4358 perf_debug("SIMD16 shader failed to compile: %s", v2.fail_msg);
4359 } else {
4360 simd16_cfg = v2.cfg;
4361 }
4362 }
4363 }
4364
4365 cfg_t *simd8_cfg;
4366 int no_simd8 = (INTEL_DEBUG & DEBUG_NO8) || brw->no_simd8;
4367 if ((no_simd8 || brw->gen < 5) && simd16_cfg) {
4368 simd8_cfg = NULL;
4369 prog_data->no_8 = true;
4370 } else {
4371 simd8_cfg = v.cfg;
4372 prog_data->no_8 = false;
4373 }
4374
4375 fs_generator g(brw->intelScreen->compiler, brw,
4376 mem_ctx, (void *) key, &prog_data->base,
4377 &fp->Base, v.promoted_constants, v.runtime_check_aads_emit, "FS");
4378
4379 if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
4380 char *name;
4381 if (prog)
4382 name = ralloc_asprintf(mem_ctx, "%s fragment shader %d",
4383 prog->Label ? prog->Label : "unnamed",
4384 prog->Name);
4385 else
4386 name = ralloc_asprintf(mem_ctx, "fragment program %d", fp->Base.Id);
4387
4388 g.enable_debug(name);
4389 }
4390
4391 if (simd8_cfg)
4392 g.generate_code(simd8_cfg, 8);
4393 if (simd16_cfg)
4394 prog_data->prog_offset_16 = g.generate_code(simd16_cfg, 16);
4395
4396 if (unlikely(brw->perf_debug) && shader) {
4397 if (shader->compiled_once)
4398 brw_wm_debug_recompile(brw, prog, key);
4399 shader->compiled_once = true;
4400
4401 if (start_busy && !drm_intel_bo_busy(brw->batch.last_bo)) {
4402 perf_debug("FS compile took %.03f ms and stalled the GPU\n",
4403 (get_time() - start_time) * 1000);
4404 }
4405 }
4406
4407 return g.get_assembly(final_assembly_size);
4408 }
4409
4410 extern "C" bool
4411 brw_fs_precompile(struct gl_context *ctx,
4412 struct gl_shader_program *shader_prog,
4413 struct gl_program *prog)
4414 {
4415 struct brw_context *brw = brw_context(ctx);
4416 struct brw_wm_prog_key key;
4417
4418 struct gl_fragment_program *fp = (struct gl_fragment_program *) prog;
4419 struct brw_fragment_program *bfp = brw_fragment_program(fp);
4420 bool program_uses_dfdy = fp->UsesDFdy;
4421
4422 memset(&key, 0, sizeof(key));
4423
4424 if (brw->gen < 6) {
4425 if (fp->UsesKill)
4426 key.iz_lookup |= IZ_PS_KILL_ALPHATEST_BIT;
4427
4428 if (fp->Base.OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH))
4429 key.iz_lookup |= IZ_PS_COMPUTES_DEPTH_BIT;
4430
4431 /* Just assume depth testing. */
4432 key.iz_lookup |= IZ_DEPTH_TEST_ENABLE_BIT;
4433 key.iz_lookup |= IZ_DEPTH_WRITE_ENABLE_BIT;
4434 }
4435
4436 if (brw->gen < 6 || _mesa_bitcount_64(fp->Base.InputsRead &
4437 BRW_FS_VARYING_INPUT_MASK) > 16)
4438 key.input_slots_valid = fp->Base.InputsRead | VARYING_BIT_POS;
4439
4440 brw_setup_tex_for_precompile(brw, &key.tex, &fp->Base);
4441
4442 if (fp->Base.InputsRead & VARYING_BIT_POS) {
4443 key.drawable_height = ctx->DrawBuffer->Height;
4444 }
4445
4446 key.nr_color_regions = _mesa_bitcount_64(fp->Base.OutputsWritten &
4447 ~(BITFIELD64_BIT(FRAG_RESULT_DEPTH) |
4448 BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK)));
4449
4450 if ((fp->Base.InputsRead & VARYING_BIT_POS) || program_uses_dfdy) {
4451 key.render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer) ||
4452 key.nr_color_regions > 1;
4453 }
4454
4455 key.program_string_id = bfp->id;
4456
4457 uint32_t old_prog_offset = brw->wm.base.prog_offset;
4458 struct brw_wm_prog_data *old_prog_data = brw->wm.prog_data;
4459
4460 bool success = brw_codegen_wm_prog(brw, shader_prog, bfp, &key);
4461
4462 brw->wm.base.prog_offset = old_prog_offset;
4463 brw->wm.prog_data = old_prog_data;
4464
4465 return success;
4466 }
4467
4468 void
4469 brw_setup_tex_for_precompile(struct brw_context *brw,
4470 struct brw_sampler_prog_key_data *tex,
4471 struct gl_program *prog)
4472 {
4473 const bool has_shader_channel_select = brw->is_haswell || brw->gen >= 8;
4474 unsigned sampler_count = _mesa_fls(prog->SamplersUsed);
4475 for (unsigned i = 0; i < sampler_count; i++) {
4476 if (!has_shader_channel_select && (prog->ShadowSamplers & (1 << i))) {
4477 /* Assume DEPTH_TEXTURE_MODE is the default: X, X, X, 1 */
4478 tex->swizzles[i] =
4479 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_ONE);
4480 } else {
4481 /* Color sampler: assume no swizzling. */
4482 tex->swizzles[i] = SWIZZLE_XYZW;
4483 }
4484 }
4485 }