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