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