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