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