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