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