llvmpipe/fs: multisample depth/stencil bad ir generated
[mesa.git] / src / gallium / drivers / llvmpipe / lp_state_fs.c
1 /**************************************************************************
2 *
3 * Copyright 2009 VMware, Inc.
4 * Copyright 2007 VMware, Inc.
5 * All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the
9 * "Software"), to deal in the Software without restriction, including
10 * without limitation the rights to use, copy, modify, merge, publish,
11 * distribute, sub license, and/or sell copies of the Software, and to
12 * permit persons to whom the Software is furnished to do so, subject to
13 * the following conditions:
14 *
15 * The above copyright notice and this permission notice (including the
16 * next paragraph) shall be included in all copies or substantial portions
17 * of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
22 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
23 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 *
27 **************************************************************************/
28
29 /**
30 * @file
31 * Code generate the whole fragment pipeline.
32 *
33 * The fragment pipeline consists of the following stages:
34 * - early depth test
35 * - fragment shader
36 * - alpha test
37 * - depth/stencil test
38 * - blending
39 *
40 * This file has only the glue to assemble the fragment pipeline. The actual
41 * plumbing of converting Gallium state into LLVM IR is done elsewhere, in the
42 * lp_bld_*.[ch] files, and in a complete generic and reusable way. Here we
43 * muster the LLVM JIT execution engine to create a function that follows an
44 * established binary interface and that can be called from C directly.
45 *
46 * A big source of complexity here is that we often want to run different
47 * stages with different precisions and data types and precisions. For example,
48 * the fragment shader needs typically to be done in floats, but the
49 * depth/stencil test and blending is better done in the type that most closely
50 * matches the depth/stencil and color buffer respectively.
51 *
52 * Since the width of a SIMD vector register stays the same regardless of the
53 * element type, different types imply different number of elements, so we must
54 * code generate more instances of the stages with larger types to be able to
55 * feed/consume the stages with smaller types.
56 *
57 * @author Jose Fonseca <jfonseca@vmware.com>
58 */
59
60 #include <limits.h>
61 #include "pipe/p_defines.h"
62 #include "util/u_inlines.h"
63 #include "util/u_memory.h"
64 #include "util/u_pointer.h"
65 #include "util/format/u_format.h"
66 #include "util/u_dump.h"
67 #include "util/u_string.h"
68 #include "util/simple_list.h"
69 #include "util/u_dual_blend.h"
70 #include "util/os_time.h"
71 #include "pipe/p_shader_tokens.h"
72 #include "draw/draw_context.h"
73 #include "tgsi/tgsi_dump.h"
74 #include "tgsi/tgsi_scan.h"
75 #include "tgsi/tgsi_parse.h"
76 #include "gallivm/lp_bld_type.h"
77 #include "gallivm/lp_bld_const.h"
78 #include "gallivm/lp_bld_conv.h"
79 #include "gallivm/lp_bld_init.h"
80 #include "gallivm/lp_bld_intr.h"
81 #include "gallivm/lp_bld_logic.h"
82 #include "gallivm/lp_bld_tgsi.h"
83 #include "gallivm/lp_bld_nir.h"
84 #include "gallivm/lp_bld_swizzle.h"
85 #include "gallivm/lp_bld_flow.h"
86 #include "gallivm/lp_bld_debug.h"
87 #include "gallivm/lp_bld_arit.h"
88 #include "gallivm/lp_bld_bitarit.h"
89 #include "gallivm/lp_bld_pack.h"
90 #include "gallivm/lp_bld_format.h"
91 #include "gallivm/lp_bld_quad.h"
92 #include "gallivm/lp_bld_gather.h"
93
94 #include "lp_bld_alpha.h"
95 #include "lp_bld_blend.h"
96 #include "lp_bld_depth.h"
97 #include "lp_bld_interp.h"
98 #include "lp_context.h"
99 #include "lp_debug.h"
100 #include "lp_perf.h"
101 #include "lp_setup.h"
102 #include "lp_state.h"
103 #include "lp_tex_sample.h"
104 #include "lp_flush.h"
105 #include "lp_state_fs.h"
106 #include "lp_rast.h"
107 #include "nir/nir_to_tgsi_info.h"
108
109 #include "lp_screen.h"
110 #include "compiler/nir/nir_serialize.h"
111 #include "util/mesa-sha1.h"
112 /** Fragment shader number (for debugging) */
113 static unsigned fs_no = 0;
114
115 static void
116 load_unswizzled_block(struct gallivm_state *gallivm,
117 LLVMValueRef base_ptr,
118 LLVMValueRef stride,
119 unsigned block_width,
120 unsigned block_height,
121 LLVMValueRef* dst,
122 struct lp_type dst_type,
123 unsigned dst_count,
124 unsigned dst_alignment,
125 LLVMValueRef x_offset,
126 LLVMValueRef y_offset,
127 bool fb_fetch_twiddle);
128 /**
129 * Checks if a format description is an arithmetic format
130 *
131 * A format which has irregular channel sizes such as R3_G3_B2 or R5_G6_B5.
132 */
133 static inline boolean
134 is_arithmetic_format(const struct util_format_description *format_desc)
135 {
136 boolean arith = false;
137 unsigned i;
138
139 for (i = 0; i < format_desc->nr_channels; ++i) {
140 arith |= format_desc->channel[i].size != format_desc->channel[0].size;
141 arith |= (format_desc->channel[i].size % 8) != 0;
142 }
143
144 return arith;
145 }
146
147 /**
148 * Checks if this format requires special handling due to required expansion
149 * to floats for blending, and furthermore has "natural" packed AoS -> unpacked
150 * SoA conversion.
151 */
152 static inline boolean
153 format_expands_to_float_soa(const struct util_format_description *format_desc)
154 {
155 if (format_desc->format == PIPE_FORMAT_R11G11B10_FLOAT ||
156 format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB) {
157 return true;
158 }
159 return false;
160 }
161
162
163 /**
164 * Retrieves the type representing the memory layout for a format
165 *
166 * e.g. RGBA16F = 4x half-float and R3G3B2 = 1x byte
167 */
168 static inline void
169 lp_mem_type_from_format_desc(const struct util_format_description *format_desc,
170 struct lp_type* type)
171 {
172 unsigned i;
173 unsigned chan;
174
175 if (format_expands_to_float_soa(format_desc)) {
176 /* just make this a uint with width of block */
177 type->floating = false;
178 type->fixed = false;
179 type->sign = false;
180 type->norm = false;
181 type->width = format_desc->block.bits;
182 type->length = 1;
183 return;
184 }
185
186 for (i = 0; i < 4; i++)
187 if (format_desc->channel[i].type != UTIL_FORMAT_TYPE_VOID)
188 break;
189 chan = i;
190
191 memset(type, 0, sizeof(struct lp_type));
192 type->floating = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FLOAT;
193 type->fixed = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FIXED;
194 type->sign = format_desc->channel[chan].type != UTIL_FORMAT_TYPE_UNSIGNED;
195 type->norm = format_desc->channel[chan].normalized;
196
197 if (is_arithmetic_format(format_desc)) {
198 type->width = 0;
199 type->length = 1;
200
201 for (i = 0; i < format_desc->nr_channels; ++i) {
202 type->width += format_desc->channel[i].size;
203 }
204 } else {
205 type->width = format_desc->channel[chan].size;
206 type->length = format_desc->nr_channels;
207 }
208 }
209
210 /**
211 * Expand the relevant bits of mask_input to a n*4-dword mask for the
212 * n*four pixels in n 2x2 quads. This will set the n*four elements of the
213 * quad mask vector to 0 or ~0.
214 * Grouping is 01, 23 for 2 quad mode hence only 0 and 2 are valid
215 * quad arguments with fs length 8.
216 *
217 * \param first_quad which quad(s) of the quad group to test, in [0,3]
218 * \param mask_input bitwise mask for the whole 4x4 stamp
219 */
220 static LLVMValueRef
221 generate_quad_mask(struct gallivm_state *gallivm,
222 struct lp_type fs_type,
223 unsigned first_quad,
224 unsigned sample,
225 LLVMValueRef mask_input) /* int64 */
226 {
227 LLVMBuilderRef builder = gallivm->builder;
228 struct lp_type mask_type;
229 LLVMTypeRef i32t = LLVMInt32TypeInContext(gallivm->context);
230 LLVMValueRef bits[16];
231 LLVMValueRef mask, bits_vec;
232 int shift, i;
233
234 /*
235 * XXX: We'll need a different path for 16 x u8
236 */
237 assert(fs_type.width == 32);
238 assert(fs_type.length <= ARRAY_SIZE(bits));
239 mask_type = lp_int_type(fs_type);
240
241 /*
242 * mask_input >>= (quad * 4)
243 */
244 switch (first_quad) {
245 case 0:
246 shift = 0;
247 break;
248 case 1:
249 assert(fs_type.length == 4);
250 shift = 2;
251 break;
252 case 2:
253 shift = 8;
254 break;
255 case 3:
256 assert(fs_type.length == 4);
257 shift = 10;
258 break;
259 default:
260 assert(0);
261 shift = 0;
262 }
263
264 mask_input = LLVMBuildLShr(builder, mask_input, lp_build_const_int64(gallivm, 16 * sample), "");
265 mask_input = LLVMBuildTrunc(builder, mask_input,
266 i32t, "");
267 mask_input = LLVMBuildAnd(builder, mask_input, lp_build_const_int32(gallivm, 0xffff), "");
268
269 mask_input = LLVMBuildLShr(builder,
270 mask_input,
271 LLVMConstInt(i32t, shift, 0),
272 "");
273
274 /*
275 * mask = { mask_input & (1 << i), for i in [0,3] }
276 */
277 mask = lp_build_broadcast(gallivm,
278 lp_build_vec_type(gallivm, mask_type),
279 mask_input);
280
281 for (i = 0; i < fs_type.length / 4; i++) {
282 unsigned j = 2 * (i % 2) + (i / 2) * 8;
283 bits[4*i + 0] = LLVMConstInt(i32t, 1ULL << (j + 0), 0);
284 bits[4*i + 1] = LLVMConstInt(i32t, 1ULL << (j + 1), 0);
285 bits[4*i + 2] = LLVMConstInt(i32t, 1ULL << (j + 4), 0);
286 bits[4*i + 3] = LLVMConstInt(i32t, 1ULL << (j + 5), 0);
287 }
288 bits_vec = LLVMConstVector(bits, fs_type.length);
289 mask = LLVMBuildAnd(builder, mask, bits_vec, "");
290
291 /*
292 * mask = mask == bits ? ~0 : 0
293 */
294 mask = lp_build_compare(gallivm,
295 mask_type, PIPE_FUNC_EQUAL,
296 mask, bits_vec);
297
298 return mask;
299 }
300
301
302 #define EARLY_DEPTH_TEST 0x1
303 #define LATE_DEPTH_TEST 0x2
304 #define EARLY_DEPTH_WRITE 0x4
305 #define LATE_DEPTH_WRITE 0x8
306
307 static int
308 find_output_by_semantic( const struct tgsi_shader_info *info,
309 unsigned semantic,
310 unsigned index )
311 {
312 int i;
313
314 for (i = 0; i < info->num_outputs; i++)
315 if (info->output_semantic_name[i] == semantic &&
316 info->output_semantic_index[i] == index)
317 return i;
318
319 return -1;
320 }
321
322
323 /**
324 * Fetch the specified lp_jit_viewport structure for a given viewport_index.
325 */
326 static LLVMValueRef
327 lp_llvm_viewport(LLVMValueRef context_ptr,
328 struct gallivm_state *gallivm,
329 LLVMValueRef viewport_index)
330 {
331 LLVMBuilderRef builder = gallivm->builder;
332 LLVMValueRef ptr;
333 LLVMValueRef res;
334 struct lp_type viewport_type =
335 lp_type_float_vec(32, 32 * LP_JIT_VIEWPORT_NUM_FIELDS);
336
337 ptr = lp_jit_context_viewports(gallivm, context_ptr);
338 ptr = LLVMBuildPointerCast(builder, ptr,
339 LLVMPointerType(lp_build_vec_type(gallivm, viewport_type), 0), "");
340
341 res = lp_build_pointer_get(builder, ptr, viewport_index);
342
343 return res;
344 }
345
346
347 static LLVMValueRef
348 lp_build_depth_clamp(struct gallivm_state *gallivm,
349 LLVMBuilderRef builder,
350 struct lp_type type,
351 LLVMValueRef context_ptr,
352 LLVMValueRef thread_data_ptr,
353 LLVMValueRef z)
354 {
355 LLVMValueRef viewport, min_depth, max_depth;
356 LLVMValueRef viewport_index;
357 struct lp_build_context f32_bld;
358
359 assert(type.floating);
360 lp_build_context_init(&f32_bld, gallivm, type);
361
362 /*
363 * Assumes clamping of the viewport index will occur in setup/gs. Value
364 * is passed through the rasterization stage via lp_rast_shader_inputs.
365 *
366 * See: draw_clamp_viewport_idx and lp_clamp_viewport_idx for clamping
367 * semantics.
368 */
369 viewport_index = lp_jit_thread_data_raster_state_viewport_index(gallivm,
370 thread_data_ptr);
371
372 /*
373 * Load the min and max depth from the lp_jit_context.viewports
374 * array of lp_jit_viewport structures.
375 */
376 viewport = lp_llvm_viewport(context_ptr, gallivm, viewport_index);
377
378 /* viewports[viewport_index].min_depth */
379 min_depth = LLVMBuildExtractElement(builder, viewport,
380 lp_build_const_int32(gallivm, LP_JIT_VIEWPORT_MIN_DEPTH), "");
381 min_depth = lp_build_broadcast_scalar(&f32_bld, min_depth);
382
383 /* viewports[viewport_index].max_depth */
384 max_depth = LLVMBuildExtractElement(builder, viewport,
385 lp_build_const_int32(gallivm, LP_JIT_VIEWPORT_MAX_DEPTH), "");
386 max_depth = lp_build_broadcast_scalar(&f32_bld, max_depth);
387
388 /*
389 * Clamp to the min and max depth values for the given viewport.
390 */
391 return lp_build_clamp(&f32_bld, z, min_depth, max_depth);
392 }
393
394 static void
395 lp_build_sample_alpha_to_coverage(struct gallivm_state *gallivm,
396 struct lp_type type,
397 unsigned coverage_samples,
398 LLVMValueRef num_loop,
399 LLVMValueRef loop_counter,
400 LLVMValueRef coverage_mask_store,
401 LLVMValueRef alpha)
402 {
403 struct lp_build_context bld;
404 LLVMBuilderRef builder = gallivm->builder;
405 float step = 1.0 / coverage_samples;
406
407 lp_build_context_init(&bld, gallivm, type);
408 for (unsigned s = 0; s < coverage_samples; s++) {
409 LLVMValueRef alpha_ref_value = lp_build_const_vec(gallivm, type, step * s);
410 LLVMValueRef test = lp_build_cmp(&bld, PIPE_FUNC_GREATER, alpha, alpha_ref_value);
411
412 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, lp_build_const_int32(gallivm, s), num_loop, "");
413 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_counter, "");
414 LLVMValueRef s_mask_ptr = LLVMBuildGEP(builder, coverage_mask_store, &s_mask_idx, 1, "");
415 LLVMValueRef s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
416 s_mask = LLVMBuildAnd(builder, s_mask, test, "");
417 LLVMBuildStore(builder, s_mask, s_mask_ptr);
418 }
419 };
420
421 struct lp_build_fs_llvm_iface {
422 struct lp_build_fs_iface base;
423 struct lp_build_interp_soa_context *interp;
424 struct lp_build_for_loop_state *loop_state;
425 LLVMValueRef mask_store;
426 LLVMValueRef sample_id;
427 LLVMValueRef color_ptr_ptr;
428 LLVMValueRef color_stride_ptr;
429 LLVMValueRef color_sample_stride_ptr;
430 const struct lp_fragment_shader_variant_key *key;
431 };
432
433 static LLVMValueRef fs_interp(const struct lp_build_fs_iface *iface,
434 struct lp_build_context *bld,
435 unsigned attrib, unsigned chan,
436 bool centroid, bool sample,
437 LLVMValueRef attrib_indir,
438 LLVMValueRef offsets[2])
439 {
440 struct lp_build_fs_llvm_iface *fs_iface = (struct lp_build_fs_llvm_iface *)iface;
441 struct lp_build_interp_soa_context *interp = fs_iface->interp;
442 unsigned loc = TGSI_INTERPOLATE_LOC_CENTER;
443 if (centroid)
444 loc = TGSI_INTERPOLATE_LOC_CENTROID;
445 if (sample)
446 loc = TGSI_INTERPOLATE_LOC_SAMPLE;
447
448 return lp_build_interp_soa(interp, bld->gallivm, fs_iface->loop_state->counter,
449 fs_iface->mask_store,
450 attrib, chan, loc, attrib_indir, offsets);
451 }
452
453 static void fs_fb_fetch(const struct lp_build_fs_iface *iface,
454 struct lp_build_context *bld,
455 unsigned cbuf,
456 LLVMValueRef result[4])
457 {
458 struct lp_build_fs_llvm_iface *fs_iface = (struct lp_build_fs_llvm_iface *)iface;
459 struct gallivm_state *gallivm = bld->gallivm;
460 LLVMBuilderRef builder = gallivm->builder;
461 const struct lp_fragment_shader_variant_key *key = fs_iface->key;
462 LLVMValueRef index = lp_build_const_int32(gallivm, cbuf);
463 LLVMValueRef color_ptr = LLVMBuildLoad(builder, LLVMBuildGEP(builder, fs_iface->color_ptr_ptr, &index, 1, ""), "");
464 LLVMValueRef stride = LLVMBuildLoad(builder, LLVMBuildGEP(builder, fs_iface->color_stride_ptr, &index, 1, ""), "");
465
466 LLVMValueRef dst[4 * 4];
467 enum pipe_format cbuf_format = key->cbuf_format[cbuf];
468 const struct util_format_description* out_format_desc = util_format_description(cbuf_format);
469 struct lp_type dst_type;
470 unsigned block_size = bld->type.length;
471 unsigned block_height = key->resource_1d ? 1 : 2;
472 unsigned block_width = block_size / block_height;
473
474 lp_mem_type_from_format_desc(out_format_desc, &dst_type);
475
476 struct lp_type blend_type;
477 memset(&blend_type, 0, sizeof blend_type);
478 blend_type.floating = FALSE; /* values are integers */
479 blend_type.sign = FALSE; /* values are unsigned */
480 blend_type.norm = TRUE; /* values are in [0,1] or [-1,1] */
481 blend_type.width = 8; /* 8-bit ubyte values */
482 blend_type.length = 16; /* 16 elements per vector */
483
484 uint32_t dst_alignment;
485 /*
486 * Compute the alignment of the destination pointer in bytes
487 * We fetch 1-4 pixels, if the format has pot alignment then those fetches
488 * are always aligned by MIN2(16, fetch_width) except for buffers (not
489 * 1d tex but can't distinguish here) so need to stick with per-pixel
490 * alignment in this case.
491 */
492 if (key->resource_1d) {
493 dst_alignment = (out_format_desc->block.bits + 7)/(out_format_desc->block.width * 8);
494 }
495 else {
496 dst_alignment = dst_type.length * dst_type.width / 8;
497 }
498 /* Force power-of-two alignment by extracting only the least-significant-bit */
499 dst_alignment = 1 << (ffs(dst_alignment) - 1);
500 /*
501 * Resource base and stride pointers are aligned to 16 bytes, so that's
502 * the maximum alignment we can guarantee
503 */
504 dst_alignment = MIN2(16, dst_alignment);
505
506 LLVMTypeRef blend_vec_type = lp_build_vec_type(gallivm, blend_type);
507 color_ptr = LLVMBuildBitCast(builder, color_ptr, LLVMPointerType(blend_vec_type, 0), "");
508
509 if (key->multisample) {
510 LLVMValueRef sample_stride = LLVMBuildLoad(builder,
511 LLVMBuildGEP(builder, fs_iface->color_sample_stride_ptr,
512 &index, 1, ""), "");
513 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_stride, fs_iface->sample_id, "");
514 color_ptr = LLVMBuildGEP(builder, color_ptr, &sample_offset, 1, "");
515 }
516 /* fragment shader executes on 4x4 blocks. depending on vector width it can execute 2 or 4 iterations.
517 * only move to the next row once the top row has completed 8 wide 1 iteration, 4 wide 2 iterations */
518 LLVMValueRef x_offset = NULL, y_offset = NULL;
519 if (!key->resource_1d) {
520 LLVMValueRef counter = fs_iface->loop_state->counter;
521
522 if (block_size == 4) {
523 x_offset = LLVMBuildShl(builder,
524 LLVMBuildAnd(builder, fs_iface->loop_state->counter, lp_build_const_int32(gallivm, 1), ""),
525 lp_build_const_int32(gallivm, 1), "");
526 counter = LLVMBuildLShr(builder, fs_iface->loop_state->counter, lp_build_const_int32(gallivm, 1), "");
527 }
528 y_offset = LLVMBuildMul(builder, counter, lp_build_const_int32(gallivm, 2), "");
529 }
530 load_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height, dst, dst_type, block_size, dst_alignment, x_offset, y_offset, true);
531
532 for (unsigned i = 0; i < block_size; i++) {
533 dst[i] = LLVMBuildBitCast(builder, dst[i], LLVMInt32TypeInContext(gallivm->context), "");
534 }
535 LLVMValueRef packed = lp_build_gather_values(gallivm, dst, block_size);
536
537 struct lp_type texel_type = bld->type;
538 if (out_format_desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB &&
539 out_format_desc->channel[0].pure_integer) {
540 if (out_format_desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED) {
541 texel_type = lp_type_int_vec(bld->type.width, bld->type.width * bld->type.length);
542 }
543 else if (out_format_desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED) {
544 texel_type = lp_type_uint_vec(bld->type.width, bld->type.width * bld->type.length);
545 }
546 }
547 lp_build_unpack_rgba_soa(gallivm, out_format_desc,
548 texel_type,
549 packed, result);
550 }
551
552 /**
553 * Generate the fragment shader, depth/stencil test, and alpha tests.
554 */
555 static void
556 generate_fs_loop(struct gallivm_state *gallivm,
557 struct lp_fragment_shader *shader,
558 const struct lp_fragment_shader_variant_key *key,
559 LLVMBuilderRef builder,
560 struct lp_type type,
561 LLVMValueRef context_ptr,
562 LLVMValueRef sample_pos_array,
563 LLVMValueRef num_loop,
564 struct lp_build_interp_soa_context *interp,
565 const struct lp_build_sampler_soa *sampler,
566 const struct lp_build_image_soa *image,
567 LLVMValueRef mask_store,
568 LLVMValueRef (*out_color)[4],
569 LLVMValueRef depth_base_ptr,
570 LLVMValueRef depth_stride,
571 LLVMValueRef depth_sample_stride,
572 LLVMValueRef color_ptr_ptr,
573 LLVMValueRef color_stride_ptr,
574 LLVMValueRef color_sample_stride_ptr,
575 LLVMValueRef facing,
576 LLVMValueRef thread_data_ptr)
577 {
578 const struct util_format_description *zs_format_desc = NULL;
579 const struct tgsi_token *tokens = shader->base.tokens;
580 struct lp_type int_type = lp_int_type(type);
581 LLVMTypeRef vec_type, int_vec_type;
582 LLVMValueRef mask_ptr = NULL, mask_val = NULL;
583 LLVMValueRef consts_ptr, num_consts_ptr;
584 LLVMValueRef ssbo_ptr, num_ssbo_ptr;
585 LLVMValueRef z;
586 LLVMValueRef z_value, s_value;
587 LLVMValueRef z_fb, s_fb;
588 LLVMValueRef depth_ptr;
589 LLVMValueRef stencil_refs[2];
590 LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
591 LLVMValueRef zs_samples = lp_build_const_int32(gallivm, key->zsbuf_nr_samples);
592 struct lp_build_for_loop_state loop_state, sample_loop_state;
593 struct lp_build_mask_context mask;
594 /*
595 * TODO: figure out if simple_shader optimization is really worthwile to
596 * keep. Disabled because it may hide some real bugs in the (depth/stencil)
597 * code since tests tend to take another codepath than real shaders.
598 */
599 boolean simple_shader = (shader->info.base.file_count[TGSI_FILE_SAMPLER] == 0 &&
600 shader->info.base.num_inputs < 3 &&
601 shader->info.base.num_instructions < 8) && 0;
602 const boolean dual_source_blend = key->blend.rt[0].blend_enable &&
603 util_blend_state_is_dual(&key->blend, 0);
604 const bool post_depth_coverage = shader->info.base.properties[TGSI_PROPERTY_FS_POST_DEPTH_COVERAGE];
605 unsigned attrib;
606 unsigned chan;
607 unsigned cbuf;
608 unsigned depth_mode;
609
610 struct lp_bld_tgsi_system_values system_values;
611
612 memset(&system_values, 0, sizeof(system_values));
613
614 /* truncate then sign extend. */
615 system_values.front_facing = LLVMBuildTrunc(gallivm->builder, facing, LLVMInt1TypeInContext(gallivm->context), "");
616 system_values.front_facing = LLVMBuildSExt(gallivm->builder, system_values.front_facing, LLVMInt32TypeInContext(gallivm->context), "");
617
618 if (key->depth.enabled ||
619 key->stencil[0].enabled) {
620
621 zs_format_desc = util_format_description(key->zsbuf_format);
622 assert(zs_format_desc);
623
624 if (shader->info.base.properties[TGSI_PROPERTY_FS_EARLY_DEPTH_STENCIL])
625 depth_mode = EARLY_DEPTH_TEST | EARLY_DEPTH_WRITE;
626 else if (!shader->info.base.writes_z && !shader->info.base.writes_stencil) {
627 if (shader->info.base.writes_memory)
628 depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
629 else if (key->alpha.enabled ||
630 key->blend.alpha_to_coverage ||
631 shader->info.base.uses_kill ||
632 shader->info.base.writes_samplemask) {
633 /* With alpha test and kill, can do the depth test early
634 * and hopefully eliminate some quads. But need to do a
635 * special deferred depth write once the final mask value
636 * is known. This only works though if there's either no
637 * stencil test or the stencil value isn't written.
638 */
639 if (key->stencil[0].enabled && (key->stencil[0].writemask ||
640 (key->stencil[1].enabled &&
641 key->stencil[1].writemask)))
642 depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
643 else
644 depth_mode = EARLY_DEPTH_TEST | LATE_DEPTH_WRITE;
645 }
646 else
647 depth_mode = EARLY_DEPTH_TEST | EARLY_DEPTH_WRITE;
648 }
649 else {
650 depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
651 }
652
653 if (!(key->depth.enabled && key->depth.writemask) &&
654 !(key->stencil[0].enabled && (key->stencil[0].writemask ||
655 (key->stencil[1].enabled &&
656 key->stencil[1].writemask))))
657 depth_mode &= ~(LATE_DEPTH_WRITE | EARLY_DEPTH_WRITE);
658 }
659 else {
660 depth_mode = 0;
661 }
662
663 vec_type = lp_build_vec_type(gallivm, type);
664 int_vec_type = lp_build_vec_type(gallivm, int_type);
665
666 stencil_refs[0] = lp_jit_context_stencil_ref_front_value(gallivm, context_ptr);
667 stencil_refs[1] = lp_jit_context_stencil_ref_back_value(gallivm, context_ptr);
668 /* convert scalar stencil refs into vectors */
669 stencil_refs[0] = lp_build_broadcast(gallivm, int_vec_type, stencil_refs[0]);
670 stencil_refs[1] = lp_build_broadcast(gallivm, int_vec_type, stencil_refs[1]);
671
672 consts_ptr = lp_jit_context_constants(gallivm, context_ptr);
673 num_consts_ptr = lp_jit_context_num_constants(gallivm, context_ptr);
674
675 ssbo_ptr = lp_jit_context_ssbos(gallivm, context_ptr);
676 num_ssbo_ptr = lp_jit_context_num_ssbos(gallivm, context_ptr);
677
678 memset(outputs, 0, sizeof outputs);
679
680 /* Allocate color storage for each fragment sample */
681 LLVMValueRef color_store_size = num_loop;
682 if (key->min_samples > 1)
683 color_store_size = LLVMBuildMul(builder, num_loop, lp_build_const_int32(gallivm, key->min_samples), "");
684
685 for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
686 for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
687 out_color[cbuf][chan] = lp_build_array_alloca(gallivm,
688 lp_build_vec_type(gallivm,
689 type),
690 color_store_size, "color");
691 }
692 }
693 if (dual_source_blend) {
694 assert(key->nr_cbufs <= 1);
695 for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
696 out_color[1][chan] = lp_build_array_alloca(gallivm,
697 lp_build_vec_type(gallivm,
698 type),
699 color_store_size, "color1");
700 }
701 }
702
703 lp_build_for_loop_begin(&loop_state, gallivm,
704 lp_build_const_int32(gallivm, 0),
705 LLVMIntULT,
706 num_loop,
707 lp_build_const_int32(gallivm, 1));
708
709 LLVMValueRef sample_mask_in;
710 if (key->multisample) {
711 sample_mask_in = lp_build_const_int_vec(gallivm, type, 0);
712 /* create shader execution mask by combining all sample masks. */
713 for (unsigned s = 0; s < key->coverage_samples; s++) {
714 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, num_loop, lp_build_const_int32(gallivm, s), "");
715 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
716 LLVMValueRef s_mask = lp_build_pointer_get(builder, mask_store, s_mask_idx);
717 if (s == 0)
718 mask_val = s_mask;
719 else
720 mask_val = LLVMBuildOr(builder, s_mask, mask_val, "");
721
722 LLVMValueRef mask_in = LLVMBuildAnd(builder, s_mask, lp_build_const_int_vec(gallivm, type, (1 << s)), "");
723 sample_mask_in = LLVMBuildOr(builder, sample_mask_in, mask_in, "");
724 }
725 } else {
726 sample_mask_in = lp_build_const_int_vec(gallivm, type, 1);
727 mask_ptr = LLVMBuildGEP(builder, mask_store,
728 &loop_state.counter, 1, "mask_ptr");
729 mask_val = LLVMBuildLoad(builder, mask_ptr, "");
730
731 LLVMValueRef mask_in = LLVMBuildAnd(builder, mask_val, lp_build_const_int_vec(gallivm, type, 1), "");
732 sample_mask_in = LLVMBuildOr(builder, sample_mask_in, mask_in, "");
733 }
734
735 /* 'mask' will control execution based on quad's pixel alive/killed state */
736 lp_build_mask_begin(&mask, gallivm, type, mask_val);
737
738 if (!(depth_mode & EARLY_DEPTH_TEST) && !simple_shader)
739 lp_build_mask_check(&mask);
740
741 /* Create storage for recombining sample masks after early Z pass. */
742 LLVMValueRef s_mask_or = lp_build_alloca(gallivm, lp_build_int_vec_type(gallivm, type), "cov_mask_early_depth");
743 LLVMBuildStore(builder, LLVMConstNull(lp_build_int_vec_type(gallivm, type)), s_mask_or);
744
745 /* Create storage for post depth sample mask */
746 LLVMValueRef post_depth_sample_mask_in = NULL;
747 if (post_depth_coverage)
748 post_depth_sample_mask_in = lp_build_alloca(gallivm, int_vec_type, "post_depth_sample_mask_in");
749
750 LLVMValueRef s_mask = NULL, s_mask_ptr = NULL;
751 LLVMValueRef z_sample_value_store = NULL, s_sample_value_store = NULL;
752 LLVMValueRef z_fb_store = NULL, s_fb_store = NULL;
753 LLVMTypeRef z_type = NULL, z_fb_type = NULL;
754
755 /* Run early depth once per sample */
756 if (key->multisample) {
757
758 if (zs_format_desc) {
759 struct lp_type zs_type = lp_depth_type(zs_format_desc, type.length);
760 struct lp_type z_type = zs_type;
761 struct lp_type s_type = zs_type;
762 if (zs_format_desc->block.bits < type.width)
763 z_type.width = type.width;
764 if (zs_format_desc->block.bits == 8)
765 s_type.width = type.width;
766
767 else if (zs_format_desc->block.bits > 32) {
768 z_type.width = z_type.width / 2;
769 s_type.width = s_type.width / 2;
770 s_type.floating = 0;
771 }
772 z_sample_value_store = lp_build_array_alloca(gallivm, lp_build_int_vec_type(gallivm, type),
773 zs_samples, "z_sample_store");
774 s_sample_value_store = lp_build_array_alloca(gallivm, lp_build_int_vec_type(gallivm, type),
775 zs_samples, "s_sample_store");
776 z_fb_store = lp_build_array_alloca(gallivm, lp_build_vec_type(gallivm, z_type),
777 zs_samples, "z_fb_store");
778 s_fb_store = lp_build_array_alloca(gallivm, lp_build_vec_type(gallivm, s_type),
779 zs_samples, "s_fb_store");
780 }
781 lp_build_for_loop_begin(&sample_loop_state, gallivm,
782 lp_build_const_int32(gallivm, 0),
783 LLVMIntULT, lp_build_const_int32(gallivm, key->coverage_samples),
784 lp_build_const_int32(gallivm, 1));
785
786 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, sample_loop_state.counter, num_loop, "");
787 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
788 s_mask_ptr = LLVMBuildGEP(builder, mask_store, &s_mask_idx, 1, "");
789
790 s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
791 s_mask = LLVMBuildAnd(builder, s_mask, mask_val, "");
792 }
793
794
795 /* for multisample Z needs to be interpolated at sample points for testing. */
796 lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter, key->multisample ? sample_loop_state.counter : NULL);
797 z = interp->pos[2];
798
799 depth_ptr = depth_base_ptr;
800 if (key->multisample) {
801 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_loop_state.counter, depth_sample_stride, "");
802 depth_ptr = LLVMBuildGEP(builder, depth_ptr, &sample_offset, 1, "");
803 }
804
805 if (depth_mode & EARLY_DEPTH_TEST) {
806 /*
807 * Clamp according to ARB_depth_clamp semantics.
808 */
809 if (key->depth_clamp) {
810 z = lp_build_depth_clamp(gallivm, builder, type, context_ptr,
811 thread_data_ptr, z);
812 }
813 lp_build_depth_stencil_load_swizzled(gallivm, type,
814 zs_format_desc, key->resource_1d,
815 depth_ptr, depth_stride,
816 &z_fb, &s_fb, loop_state.counter);
817 lp_build_depth_stencil_test(gallivm,
818 &key->depth,
819 key->stencil,
820 type,
821 zs_format_desc,
822 key->multisample ? NULL : &mask,
823 &s_mask,
824 stencil_refs,
825 z, z_fb, s_fb,
826 facing,
827 &z_value, &s_value,
828 !simple_shader && !key->multisample);
829
830 if (depth_mode & EARLY_DEPTH_WRITE) {
831 lp_build_depth_stencil_write_swizzled(gallivm, type,
832 zs_format_desc, key->resource_1d,
833 NULL, NULL, NULL, loop_state.counter,
834 depth_ptr, depth_stride,
835 z_value, s_value);
836 }
837 /*
838 * Note mask check if stencil is enabled must be after ds write not after
839 * stencil test otherwise new stencil values may not get written if all
840 * fragments got killed by depth/stencil test.
841 */
842 if (!simple_shader && key->stencil[0].enabled && !key->multisample)
843 lp_build_mask_check(&mask);
844
845 if (key->multisample) {
846 z_fb_type = LLVMTypeOf(z_fb);
847 z_type = LLVMTypeOf(z_value);
848 lp_build_pointer_set(builder, z_sample_value_store, sample_loop_state.counter, LLVMBuildBitCast(builder, z_value, lp_build_int_vec_type(gallivm, type), ""));
849 lp_build_pointer_set(builder, s_sample_value_store, sample_loop_state.counter, LLVMBuildBitCast(builder, s_value, lp_build_int_vec_type(gallivm, type), ""));
850 lp_build_pointer_set(builder, z_fb_store, sample_loop_state.counter, z_fb);
851 lp_build_pointer_set(builder, s_fb_store, sample_loop_state.counter, s_fb);
852 }
853 }
854
855 if (key->multisample) {
856 /*
857 * Store the post-early Z coverage mask.
858 * Recombine the resulting coverage masks post early Z into the fragment
859 * shader execution mask.
860 */
861 LLVMValueRef tmp_s_mask_or = LLVMBuildLoad(builder, s_mask_or, "");
862 tmp_s_mask_or = LLVMBuildOr(builder, tmp_s_mask_or, s_mask, "");
863 LLVMBuildStore(builder, tmp_s_mask_or, s_mask_or);
864
865 if (post_depth_coverage) {
866 LLVMValueRef mask_bit_idx = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "");
867 LLVMValueRef post_depth_mask_in = LLVMBuildLoad(builder, post_depth_sample_mask_in, "");
868 mask_bit_idx = LLVMBuildAnd(builder, s_mask, lp_build_broadcast(gallivm, int_vec_type, mask_bit_idx), "");
869 post_depth_mask_in = LLVMBuildOr(builder, post_depth_mask_in, mask_bit_idx, "");
870 LLVMBuildStore(builder, post_depth_mask_in, post_depth_sample_mask_in);
871 }
872
873 LLVMBuildStore(builder, s_mask, s_mask_ptr);
874
875 lp_build_for_loop_end(&sample_loop_state);
876
877 /* recombined all the coverage masks in the shader exec mask. */
878 tmp_s_mask_or = LLVMBuildLoad(builder, s_mask_or, "");
879 lp_build_mask_update(&mask, tmp_s_mask_or);
880
881 if (key->min_samples == 1) {
882 /* for multisample Z needs to be re interpolated at pixel center */
883 lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter, NULL);
884 z = interp->pos[2];
885 lp_build_mask_update(&mask, tmp_s_mask_or);
886 }
887 } else {
888 if (post_depth_coverage) {
889 LLVMValueRef post_depth_mask_in = LLVMBuildAnd(builder, lp_build_mask_value(&mask), lp_build_const_int_vec(gallivm, type, 1), "");
890 LLVMBuildStore(builder, post_depth_mask_in, post_depth_sample_mask_in);
891 }
892 }
893
894 LLVMValueRef out_sample_mask_storage = NULL;
895 if (shader->info.base.writes_samplemask) {
896 out_sample_mask_storage = lp_build_alloca(gallivm, int_vec_type, "write_mask");
897 if (key->min_samples > 1)
898 LLVMBuildStore(builder, LLVMConstNull(int_vec_type), out_sample_mask_storage);
899 }
900
901 if (post_depth_coverage) {
902 system_values.sample_mask_in = LLVMBuildLoad(builder, post_depth_sample_mask_in, "");
903 }
904 else
905 system_values.sample_mask_in = sample_mask_in;
906 if (key->multisample && key->min_samples > 1) {
907 lp_build_for_loop_begin(&sample_loop_state, gallivm,
908 lp_build_const_int32(gallivm, 0),
909 LLVMIntULT,
910 lp_build_const_int32(gallivm, key->min_samples),
911 lp_build_const_int32(gallivm, 1));
912
913 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, sample_loop_state.counter, num_loop, "");
914 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
915 s_mask_ptr = LLVMBuildGEP(builder, mask_store, &s_mask_idx, 1, "");
916 s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
917 lp_build_mask_force(&mask, s_mask);
918 lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter, sample_loop_state.counter);
919 system_values.sample_id = sample_loop_state.counter;
920 system_values.sample_mask_in = LLVMBuildAnd(builder, system_values.sample_mask_in,
921 lp_build_broadcast(gallivm, int_vec_type,
922 LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "")), "");
923 } else {
924 system_values.sample_id = lp_build_const_int32(gallivm, 0);
925
926 }
927 system_values.sample_pos = sample_pos_array;
928
929 lp_build_interp_soa_update_inputs_dyn(interp, gallivm, loop_state.counter, mask_store, sample_loop_state.counter);
930
931 struct lp_build_fs_llvm_iface fs_iface = {
932 .base.interp_fn = fs_interp,
933 .base.fb_fetch = fs_fb_fetch,
934 .interp = interp,
935 .loop_state = &loop_state,
936 .sample_id = system_values.sample_id,
937 .mask_store = mask_store,
938 .color_ptr_ptr = color_ptr_ptr,
939 .color_stride_ptr = color_stride_ptr,
940 .color_sample_stride_ptr = color_sample_stride_ptr,
941 .key = key,
942 };
943
944 struct lp_build_tgsi_params params;
945 memset(&params, 0, sizeof(params));
946
947 params.type = type;
948 params.mask = &mask;
949 params.fs_iface = &fs_iface.base;
950 params.consts_ptr = consts_ptr;
951 params.const_sizes_ptr = num_consts_ptr;
952 params.system_values = &system_values;
953 params.inputs = interp->inputs;
954 params.context_ptr = context_ptr;
955 params.thread_data_ptr = thread_data_ptr;
956 params.sampler = sampler;
957 params.info = &shader->info.base;
958 params.ssbo_ptr = ssbo_ptr;
959 params.ssbo_sizes_ptr = num_ssbo_ptr;
960 params.image = image;
961
962 /* Build the actual shader */
963 if (shader->base.type == PIPE_SHADER_IR_TGSI)
964 lp_build_tgsi_soa(gallivm, tokens, &params,
965 outputs);
966 else
967 lp_build_nir_soa(gallivm, shader->base.ir.nir, &params,
968 outputs);
969
970 /* Alpha test */
971 if (key->alpha.enabled) {
972 int color0 = find_output_by_semantic(&shader->info.base,
973 TGSI_SEMANTIC_COLOR,
974 0);
975
976 if (color0 != -1 && outputs[color0][3]) {
977 const struct util_format_description *cbuf_format_desc;
978 LLVMValueRef alpha = LLVMBuildLoad(builder, outputs[color0][3], "alpha");
979 LLVMValueRef alpha_ref_value;
980
981 alpha_ref_value = lp_jit_context_alpha_ref_value(gallivm, context_ptr);
982 alpha_ref_value = lp_build_broadcast(gallivm, vec_type, alpha_ref_value);
983
984 cbuf_format_desc = util_format_description(key->cbuf_format[0]);
985
986 lp_build_alpha_test(gallivm, key->alpha.func, type, cbuf_format_desc,
987 &mask, alpha, alpha_ref_value,
988 (depth_mode & LATE_DEPTH_TEST) != 0);
989 }
990 }
991
992 /* Emulate Alpha to Coverage with Alpha test */
993 if (key->blend.alpha_to_coverage) {
994 int color0 = find_output_by_semantic(&shader->info.base,
995 TGSI_SEMANTIC_COLOR,
996 0);
997
998 if (color0 != -1 && outputs[color0][3]) {
999 LLVMValueRef alpha = LLVMBuildLoad(builder, outputs[color0][3], "alpha");
1000
1001 if (!key->multisample) {
1002 lp_build_alpha_to_coverage(gallivm, type,
1003 &mask, alpha,
1004 (depth_mode & LATE_DEPTH_TEST) != 0);
1005 } else {
1006 lp_build_sample_alpha_to_coverage(gallivm, type, key->coverage_samples, num_loop,
1007 loop_state.counter,
1008 mask_store, alpha);
1009 }
1010 }
1011 }
1012 if (key->blend.alpha_to_one && key->multisample) {
1013 for (attrib = 0; attrib < shader->info.base.num_outputs; ++attrib) {
1014 unsigned cbuf = shader->info.base.output_semantic_index[attrib];
1015 if ((shader->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_COLOR) &&
1016 ((cbuf < key->nr_cbufs) || (cbuf == 1 && dual_source_blend)))
1017 if (outputs[cbuf][3]) {
1018 LLVMBuildStore(builder, lp_build_const_vec(gallivm, type, 1.0), outputs[cbuf][3]);
1019 }
1020 }
1021 }
1022 if (shader->info.base.writes_samplemask) {
1023 LLVMValueRef output_smask = NULL;
1024 int smaski = find_output_by_semantic(&shader->info.base,
1025 TGSI_SEMANTIC_SAMPLEMASK,
1026 0);
1027 struct lp_build_context smask_bld;
1028 lp_build_context_init(&smask_bld, gallivm, int_type);
1029
1030 assert(smaski >= 0);
1031 output_smask = LLVMBuildLoad(builder, outputs[smaski][0], "smask");
1032 output_smask = LLVMBuildBitCast(builder, output_smask, smask_bld.vec_type, "");
1033
1034 if (key->min_samples > 1) {
1035 /* only the bit corresponding to this sample is to be used. */
1036 LLVMValueRef tmp_mask = LLVMBuildLoad(builder, out_sample_mask_storage, "tmp_mask");
1037 LLVMValueRef out_smask_idx = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "");
1038 LLVMValueRef smask_bit = LLVMBuildAnd(builder, output_smask, lp_build_broadcast(gallivm, int_vec_type, out_smask_idx), "");
1039 output_smask = LLVMBuildOr(builder, tmp_mask, smask_bit, "");
1040 }
1041
1042 LLVMBuildStore(builder, output_smask, out_sample_mask_storage);
1043 }
1044
1045 /* Color write - per fragment sample */
1046 for (attrib = 0; attrib < shader->info.base.num_outputs; ++attrib)
1047 {
1048 unsigned cbuf = shader->info.base.output_semantic_index[attrib];
1049 if ((shader->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_COLOR) &&
1050 ((cbuf < key->nr_cbufs) || (cbuf == 1 && dual_source_blend)))
1051 {
1052 for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
1053 if(outputs[attrib][chan]) {
1054 /* XXX: just initialize outputs to point at colors[] and
1055 * skip this.
1056 */
1057 LLVMValueRef out = LLVMBuildLoad(builder, outputs[attrib][chan], "");
1058 LLVMValueRef color_ptr;
1059 LLVMValueRef color_idx = loop_state.counter;
1060 if (key->min_samples > 1)
1061 color_idx = LLVMBuildAdd(builder, color_idx,
1062 LLVMBuildMul(builder, sample_loop_state.counter, num_loop, ""), "");
1063 color_ptr = LLVMBuildGEP(builder, out_color[cbuf][chan],
1064 &color_idx, 1, "");
1065 lp_build_name(out, "color%u.%c", attrib, "rgba"[chan]);
1066 LLVMBuildStore(builder, out, color_ptr);
1067 }
1068 }
1069 }
1070 }
1071
1072 if (key->multisample && key->min_samples > 1) {
1073 LLVMBuildStore(builder, lp_build_mask_value(&mask), s_mask_ptr);
1074 lp_build_for_loop_end(&sample_loop_state);
1075 }
1076
1077 if (key->multisample) {
1078 /* execute depth test for each sample */
1079 lp_build_for_loop_begin(&sample_loop_state, gallivm,
1080 lp_build_const_int32(gallivm, 0),
1081 LLVMIntULT, lp_build_const_int32(gallivm, key->coverage_samples),
1082 lp_build_const_int32(gallivm, 1));
1083
1084 /* load the per-sample coverage mask */
1085 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, sample_loop_state.counter, num_loop, "");
1086 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
1087 s_mask_ptr = LLVMBuildGEP(builder, mask_store, &s_mask_idx, 1, "");
1088
1089 /* combine the execution mask post fragment shader with the coverage mask. */
1090 s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
1091 if (key->min_samples == 1)
1092 s_mask = LLVMBuildAnd(builder, s_mask, lp_build_mask_value(&mask), "");
1093
1094 /* if the shader writes sample mask use that */
1095 if (shader->info.base.writes_samplemask) {
1096 LLVMValueRef out_smask_idx = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "");
1097 out_smask_idx = lp_build_broadcast(gallivm, int_vec_type, out_smask_idx);
1098 LLVMValueRef output_smask = LLVMBuildLoad(builder, out_sample_mask_storage, "");
1099 LLVMValueRef smask_bit = LLVMBuildAnd(builder, output_smask, out_smask_idx, "");
1100 LLVMValueRef cmp = LLVMBuildICmp(builder, LLVMIntNE, smask_bit, lp_build_const_int_vec(gallivm, int_type, 0), "");
1101 smask_bit = LLVMBuildSExt(builder, cmp, int_vec_type, "");
1102
1103 s_mask = LLVMBuildAnd(builder, s_mask, smask_bit, "");
1104 }
1105 }
1106
1107 depth_ptr = depth_base_ptr;
1108 if (key->multisample) {
1109 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_loop_state.counter, depth_sample_stride, "");
1110 depth_ptr = LLVMBuildGEP(builder, depth_ptr, &sample_offset, 1, "");
1111 }
1112
1113 /* Late Z test */
1114 if (depth_mode & LATE_DEPTH_TEST) {
1115 int pos0 = find_output_by_semantic(&shader->info.base,
1116 TGSI_SEMANTIC_POSITION,
1117 0);
1118 int s_out = find_output_by_semantic(&shader->info.base,
1119 TGSI_SEMANTIC_STENCIL,
1120 0);
1121 if (pos0 != -1 && outputs[pos0][2]) {
1122 z = LLVMBuildLoad(builder, outputs[pos0][2], "output.z");
1123 } else {
1124 if (key->multisample) {
1125 lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter, key->multisample ? sample_loop_state.counter : NULL);
1126 z = interp->pos[2];
1127 }
1128 }
1129 /*
1130 * Clamp according to ARB_depth_clamp semantics.
1131 */
1132 if (key->depth_clamp) {
1133 z = lp_build_depth_clamp(gallivm, builder, type, context_ptr,
1134 thread_data_ptr, z);
1135 }
1136
1137 if (s_out != -1 && outputs[s_out][1]) {
1138 /* there's only one value, and spec says to discard additional bits */
1139 LLVMValueRef s_max_mask = lp_build_const_int_vec(gallivm, int_type, 255);
1140 stencil_refs[0] = LLVMBuildLoad(builder, outputs[s_out][1], "output.s");
1141 stencil_refs[0] = LLVMBuildBitCast(builder, stencil_refs[0], int_vec_type, "");
1142 stencil_refs[0] = LLVMBuildAnd(builder, stencil_refs[0], s_max_mask, "");
1143 stencil_refs[1] = stencil_refs[0];
1144 }
1145
1146 lp_build_depth_stencil_load_swizzled(gallivm, type,
1147 zs_format_desc, key->resource_1d,
1148 depth_ptr, depth_stride,
1149 &z_fb, &s_fb, loop_state.counter);
1150
1151 lp_build_depth_stencil_test(gallivm,
1152 &key->depth,
1153 key->stencil,
1154 type,
1155 zs_format_desc,
1156 key->multisample ? NULL : &mask,
1157 &s_mask,
1158 stencil_refs,
1159 z, z_fb, s_fb,
1160 facing,
1161 &z_value, &s_value,
1162 !simple_shader);
1163 /* Late Z write */
1164 if (depth_mode & LATE_DEPTH_WRITE) {
1165 lp_build_depth_stencil_write_swizzled(gallivm, type,
1166 zs_format_desc, key->resource_1d,
1167 NULL, NULL, NULL, loop_state.counter,
1168 depth_ptr, depth_stride,
1169 z_value, s_value);
1170 }
1171 }
1172 else if ((depth_mode & EARLY_DEPTH_TEST) &&
1173 (depth_mode & LATE_DEPTH_WRITE))
1174 {
1175 /* Need to apply a reduced mask to the depth write. Reload the
1176 * depth value, update from zs_value with the new mask value and
1177 * write that out.
1178 */
1179 if (key->multisample) {
1180 z_value = LLVMBuildBitCast(builder, lp_build_pointer_get(builder, z_sample_value_store, sample_loop_state.counter), z_type, "");;
1181 s_value = lp_build_pointer_get(builder, s_sample_value_store, sample_loop_state.counter);
1182 z_fb = LLVMBuildBitCast(builder, lp_build_pointer_get(builder, z_fb_store, sample_loop_state.counter), z_fb_type, "");
1183 s_fb = lp_build_pointer_get(builder, s_fb_store, sample_loop_state.counter);
1184 }
1185 lp_build_depth_stencil_write_swizzled(gallivm, type,
1186 zs_format_desc, key->resource_1d,
1187 key->multisample ? s_mask : lp_build_mask_value(&mask), z_fb, s_fb, loop_state.counter,
1188 depth_ptr, depth_stride,
1189 z_value, s_value);
1190 }
1191
1192 if (key->occlusion_count) {
1193 LLVMValueRef counter = lp_jit_thread_data_counter(gallivm, thread_data_ptr);
1194 lp_build_name(counter, "counter");
1195
1196 lp_build_occlusion_count(gallivm, type,
1197 key->multisample ? s_mask : lp_build_mask_value(&mask), counter);
1198 }
1199
1200 if (key->multisample) {
1201 /* store the sample mask for this loop */
1202 LLVMBuildStore(builder, s_mask, s_mask_ptr);
1203 lp_build_for_loop_end(&sample_loop_state);
1204 }
1205
1206 mask_val = lp_build_mask_end(&mask);
1207 if (!key->multisample)
1208 LLVMBuildStore(builder, mask_val, mask_ptr);
1209 lp_build_for_loop_end(&loop_state);
1210 }
1211
1212
1213 /**
1214 * This function will reorder pixels from the fragment shader SoA to memory layout AoS
1215 *
1216 * Fragment Shader outputs pixels in small 2x2 blocks
1217 * e.g. (0, 0), (1, 0), (0, 1), (1, 1) ; (2, 0) ...
1218 *
1219 * However in memory pixels are stored in rows
1220 * e.g. (0, 0), (1, 0), (2, 0), (3, 0) ; (0, 1) ...
1221 *
1222 * @param type fragment shader type (4x or 8x float)
1223 * @param num_fs number of fs_src
1224 * @param is_1d whether we're outputting to a 1d resource
1225 * @param dst_channels number of output channels
1226 * @param fs_src output from fragment shader
1227 * @param dst pointer to store result
1228 * @param pad_inline is channel padding inline or at end of row
1229 * @return the number of dsts
1230 */
1231 static int
1232 generate_fs_twiddle(struct gallivm_state *gallivm,
1233 struct lp_type type,
1234 unsigned num_fs,
1235 unsigned dst_channels,
1236 LLVMValueRef fs_src[][4],
1237 LLVMValueRef* dst,
1238 bool pad_inline)
1239 {
1240 LLVMValueRef src[16];
1241
1242 bool swizzle_pad;
1243 bool twiddle;
1244 bool split;
1245
1246 unsigned pixels = type.length / 4;
1247 unsigned reorder_group;
1248 unsigned src_channels;
1249 unsigned src_count;
1250 unsigned i;
1251
1252 src_channels = dst_channels < 3 ? dst_channels : 4;
1253 src_count = num_fs * src_channels;
1254
1255 assert(pixels == 2 || pixels == 1);
1256 assert(num_fs * src_channels <= ARRAY_SIZE(src));
1257
1258 /*
1259 * Transpose from SoA -> AoS
1260 */
1261 for (i = 0; i < num_fs; ++i) {
1262 lp_build_transpose_aos_n(gallivm, type, &fs_src[i][0], src_channels, &src[i * src_channels]);
1263 }
1264
1265 /*
1266 * Pick transformation options
1267 */
1268 swizzle_pad = false;
1269 twiddle = false;
1270 split = false;
1271 reorder_group = 0;
1272
1273 if (dst_channels == 1) {
1274 twiddle = true;
1275
1276 if (pixels == 2) {
1277 split = true;
1278 }
1279 } else if (dst_channels == 2) {
1280 if (pixels == 1) {
1281 reorder_group = 1;
1282 }
1283 } else if (dst_channels > 2) {
1284 if (pixels == 1) {
1285 reorder_group = 2;
1286 } else {
1287 twiddle = true;
1288 }
1289
1290 if (!pad_inline && dst_channels == 3 && pixels > 1) {
1291 swizzle_pad = true;
1292 }
1293 }
1294
1295 /*
1296 * Split the src in half
1297 */
1298 if (split) {
1299 for (i = num_fs; i > 0; --i) {
1300 src[(i - 1)*2 + 1] = lp_build_extract_range(gallivm, src[i - 1], 4, 4);
1301 src[(i - 1)*2 + 0] = lp_build_extract_range(gallivm, src[i - 1], 0, 4);
1302 }
1303
1304 src_count *= 2;
1305 type.length = 4;
1306 }
1307
1308 /*
1309 * Ensure pixels are in memory order
1310 */
1311 if (reorder_group) {
1312 /* Twiddle pixels by reordering the array, e.g.:
1313 *
1314 * src_count = 8 -> 0 2 1 3 4 6 5 7
1315 * src_count = 16 -> 0 1 4 5 2 3 6 7 8 9 12 13 10 11 14 15
1316 */
1317 const unsigned reorder_sw[] = { 0, 2, 1, 3 };
1318
1319 for (i = 0; i < src_count; ++i) {
1320 unsigned group = i / reorder_group;
1321 unsigned block = (group / 4) * 4 * reorder_group;
1322 unsigned j = block + (reorder_sw[group % 4] * reorder_group) + (i % reorder_group);
1323 dst[i] = src[j];
1324 }
1325 } else if (twiddle) {
1326 /* Twiddle pixels across elements of array */
1327 /*
1328 * XXX: we should avoid this in some cases, but would need to tell
1329 * lp_build_conv to reorder (or deal with it ourselves).
1330 */
1331 lp_bld_quad_twiddle(gallivm, type, src, src_count, dst);
1332 } else {
1333 /* Do nothing */
1334 memcpy(dst, src, sizeof(LLVMValueRef) * src_count);
1335 }
1336
1337 /*
1338 * Moves any padding between pixels to the end
1339 * e.g. RGBXRGBX -> RGBRGBXX
1340 */
1341 if (swizzle_pad) {
1342 unsigned char swizzles[16];
1343 unsigned elems = pixels * dst_channels;
1344
1345 for (i = 0; i < type.length; ++i) {
1346 if (i < elems)
1347 swizzles[i] = i % dst_channels + (i / dst_channels) * 4;
1348 else
1349 swizzles[i] = LP_BLD_SWIZZLE_DONTCARE;
1350 }
1351
1352 for (i = 0; i < src_count; ++i) {
1353 dst[i] = lp_build_swizzle_aos_n(gallivm, dst[i], swizzles, type.length, type.length);
1354 }
1355 }
1356
1357 return src_count;
1358 }
1359
1360
1361 /*
1362 * Untwiddle and transpose, much like the above.
1363 * However, this is after conversion, so we get packed vectors.
1364 * At this time only handle 4x16i8 rgba / 2x16i8 rg / 1x16i8 r data,
1365 * the vectors will look like:
1366 * r0r1r4r5r2r3r6r7r8r9r12... (albeit color channels may
1367 * be swizzled here). Extending to 16bit should be trivial.
1368 * Should also be extended to handle twice wide vectors with AVX2...
1369 */
1370 static void
1371 fs_twiddle_transpose(struct gallivm_state *gallivm,
1372 struct lp_type type,
1373 LLVMValueRef *src,
1374 unsigned src_count,
1375 LLVMValueRef *dst)
1376 {
1377 unsigned i, j;
1378 struct lp_type type64, type16, type32;
1379 LLVMTypeRef type64_t, type8_t, type16_t, type32_t;
1380 LLVMBuilderRef builder = gallivm->builder;
1381 LLVMValueRef tmp[4], shuf[8];
1382 for (j = 0; j < 2; j++) {
1383 shuf[j*4 + 0] = lp_build_const_int32(gallivm, j*4 + 0);
1384 shuf[j*4 + 1] = lp_build_const_int32(gallivm, j*4 + 2);
1385 shuf[j*4 + 2] = lp_build_const_int32(gallivm, j*4 + 1);
1386 shuf[j*4 + 3] = lp_build_const_int32(gallivm, j*4 + 3);
1387 }
1388
1389 assert(src_count == 4 || src_count == 2 || src_count == 1);
1390 assert(type.width == 8);
1391 assert(type.length == 16);
1392
1393 type8_t = lp_build_vec_type(gallivm, type);
1394
1395 type64 = type;
1396 type64.length /= 8;
1397 type64.width *= 8;
1398 type64_t = lp_build_vec_type(gallivm, type64);
1399
1400 type16 = type;
1401 type16.length /= 2;
1402 type16.width *= 2;
1403 type16_t = lp_build_vec_type(gallivm, type16);
1404
1405 type32 = type;
1406 type32.length /= 4;
1407 type32.width *= 4;
1408 type32_t = lp_build_vec_type(gallivm, type32);
1409
1410 lp_build_transpose_aos_n(gallivm, type, src, src_count, tmp);
1411
1412 if (src_count == 1) {
1413 /* transpose was no-op, just untwiddle */
1414 LLVMValueRef shuf_vec;
1415 shuf_vec = LLVMConstVector(shuf, 8);
1416 tmp[0] = LLVMBuildBitCast(builder, src[0], type16_t, "");
1417 tmp[0] = LLVMBuildShuffleVector(builder, tmp[0], tmp[0], shuf_vec, "");
1418 dst[0] = LLVMBuildBitCast(builder, tmp[0], type8_t, "");
1419 } else if (src_count == 2) {
1420 LLVMValueRef shuf_vec;
1421 shuf_vec = LLVMConstVector(shuf, 4);
1422
1423 for (i = 0; i < 2; i++) {
1424 tmp[i] = LLVMBuildBitCast(builder, tmp[i], type32_t, "");
1425 tmp[i] = LLVMBuildShuffleVector(builder, tmp[i], tmp[i], shuf_vec, "");
1426 dst[i] = LLVMBuildBitCast(builder, tmp[i], type8_t, "");
1427 }
1428 } else {
1429 for (j = 0; j < 2; j++) {
1430 LLVMValueRef lo, hi, lo2, hi2;
1431 /*
1432 * Note that if we only really have 3 valid channels (rgb)
1433 * and we don't need alpha we could substitute a undef here
1434 * for the respective channel (causing llvm to drop conversion
1435 * for alpha).
1436 */
1437 /* we now have rgba0rgba1rgba4rgba5 etc, untwiddle */
1438 lo2 = LLVMBuildBitCast(builder, tmp[j*2], type64_t, "");
1439 hi2 = LLVMBuildBitCast(builder, tmp[j*2 + 1], type64_t, "");
1440 lo = lp_build_interleave2(gallivm, type64, lo2, hi2, 0);
1441 hi = lp_build_interleave2(gallivm, type64, lo2, hi2, 1);
1442 dst[j*2] = LLVMBuildBitCast(builder, lo, type8_t, "");
1443 dst[j*2 + 1] = LLVMBuildBitCast(builder, hi, type8_t, "");
1444 }
1445 }
1446 }
1447
1448
1449 /**
1450 * Load an unswizzled block of pixels from memory
1451 */
1452 static void
1453 load_unswizzled_block(struct gallivm_state *gallivm,
1454 LLVMValueRef base_ptr,
1455 LLVMValueRef stride,
1456 unsigned block_width,
1457 unsigned block_height,
1458 LLVMValueRef* dst,
1459 struct lp_type dst_type,
1460 unsigned dst_count,
1461 unsigned dst_alignment,
1462 LLVMValueRef x_offset,
1463 LLVMValueRef y_offset,
1464 bool fb_fetch_twiddle)
1465 {
1466 LLVMBuilderRef builder = gallivm->builder;
1467 unsigned row_size = dst_count / block_height;
1468 unsigned i;
1469
1470 /* Ensure block exactly fits into dst */
1471 assert((block_width * block_height) % dst_count == 0);
1472
1473 for (i = 0; i < dst_count; ++i) {
1474 unsigned x = i % row_size;
1475 unsigned y = i / row_size;
1476
1477 if (block_height == 2 && dst_count == 8 && fb_fetch_twiddle) {
1478 /* remap the raw slots into the fragment shader execution mode. */
1479 /* this math took me way too long to work out, I'm sure it's overkill. */
1480 x = (i & 1) + ((i >> 2) << 1);
1481 y = (i & 2) >> 1;
1482 }
1483
1484 LLVMValueRef x_val;
1485 if (x_offset) {
1486 x_val = lp_build_const_int32(gallivm, x);
1487 if (x_offset)
1488 x_val = LLVMBuildAdd(builder, x_val, x_offset, "");
1489 x_val = LLVMBuildMul(builder, x_val, lp_build_const_int32(gallivm, (dst_type.width / 8) * dst_type.length), "");
1490 } else
1491 x_val = lp_build_const_int32(gallivm, x * (dst_type.width / 8) * dst_type.length);
1492
1493 LLVMValueRef bx = x_val;
1494
1495 LLVMValueRef y_val = lp_build_const_int32(gallivm, y);
1496 if (y_offset)
1497 y_val = LLVMBuildAdd(builder, y_val, y_offset, "");
1498 LLVMValueRef by = LLVMBuildMul(builder, y_val, stride, "");
1499
1500 LLVMValueRef gep[2];
1501 LLVMValueRef dst_ptr;
1502
1503 gep[0] = lp_build_const_int32(gallivm, 0);
1504 gep[1] = LLVMBuildAdd(builder, bx, by, "");
1505
1506 dst_ptr = LLVMBuildGEP(builder, base_ptr, gep, 2, "");
1507 dst_ptr = LLVMBuildBitCast(builder, dst_ptr,
1508 LLVMPointerType(lp_build_vec_type(gallivm, dst_type), 0), "");
1509
1510 dst[i] = LLVMBuildLoad(builder, dst_ptr, "");
1511
1512 LLVMSetAlignment(dst[i], dst_alignment);
1513 }
1514 }
1515
1516
1517 /**
1518 * Store an unswizzled block of pixels to memory
1519 */
1520 static void
1521 store_unswizzled_block(struct gallivm_state *gallivm,
1522 LLVMValueRef base_ptr,
1523 LLVMValueRef stride,
1524 unsigned block_width,
1525 unsigned block_height,
1526 LLVMValueRef* src,
1527 struct lp_type src_type,
1528 unsigned src_count,
1529 unsigned src_alignment)
1530 {
1531 LLVMBuilderRef builder = gallivm->builder;
1532 unsigned row_size = src_count / block_height;
1533 unsigned i;
1534
1535 /* Ensure src exactly fits into block */
1536 assert((block_width * block_height) % src_count == 0);
1537
1538 for (i = 0; i < src_count; ++i) {
1539 unsigned x = i % row_size;
1540 unsigned y = i / row_size;
1541
1542 LLVMValueRef bx = lp_build_const_int32(gallivm, x * (src_type.width / 8) * src_type.length);
1543 LLVMValueRef by = LLVMBuildMul(builder, lp_build_const_int32(gallivm, y), stride, "");
1544
1545 LLVMValueRef gep[2];
1546 LLVMValueRef src_ptr;
1547
1548 gep[0] = lp_build_const_int32(gallivm, 0);
1549 gep[1] = LLVMBuildAdd(builder, bx, by, "");
1550
1551 src_ptr = LLVMBuildGEP(builder, base_ptr, gep, 2, "");
1552 src_ptr = LLVMBuildBitCast(builder, src_ptr,
1553 LLVMPointerType(lp_build_vec_type(gallivm, src_type), 0), "");
1554
1555 src_ptr = LLVMBuildStore(builder, src[i], src_ptr);
1556
1557 LLVMSetAlignment(src_ptr, src_alignment);
1558 }
1559 }
1560
1561
1562
1563 /**
1564 * Retrieves the type for a format which is usable in the blending code.
1565 *
1566 * e.g. RGBA16F = 4x float, R3G3B2 = 3x byte
1567 */
1568 static inline void
1569 lp_blend_type_from_format_desc(const struct util_format_description *format_desc,
1570 struct lp_type* type)
1571 {
1572 unsigned i;
1573 unsigned chan;
1574
1575 if (format_expands_to_float_soa(format_desc)) {
1576 /* always use ordinary floats for blending */
1577 type->floating = true;
1578 type->fixed = false;
1579 type->sign = true;
1580 type->norm = false;
1581 type->width = 32;
1582 type->length = 4;
1583 return;
1584 }
1585
1586 for (i = 0; i < 4; i++)
1587 if (format_desc->channel[i].type != UTIL_FORMAT_TYPE_VOID)
1588 break;
1589 chan = i;
1590
1591 memset(type, 0, sizeof(struct lp_type));
1592 type->floating = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FLOAT;
1593 type->fixed = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FIXED;
1594 type->sign = format_desc->channel[chan].type != UTIL_FORMAT_TYPE_UNSIGNED;
1595 type->norm = format_desc->channel[chan].normalized;
1596 type->width = format_desc->channel[chan].size;
1597 type->length = format_desc->nr_channels;
1598
1599 for (i = 1; i < format_desc->nr_channels; ++i) {
1600 if (format_desc->channel[i].size > type->width)
1601 type->width = format_desc->channel[i].size;
1602 }
1603
1604 if (type->floating) {
1605 type->width = 32;
1606 } else {
1607 if (type->width <= 8) {
1608 type->width = 8;
1609 } else if (type->width <= 16) {
1610 type->width = 16;
1611 } else {
1612 type->width = 32;
1613 }
1614 }
1615
1616 if (is_arithmetic_format(format_desc) && type->length == 3) {
1617 type->length = 4;
1618 }
1619 }
1620
1621
1622 /**
1623 * Scale a normalized value from src_bits to dst_bits.
1624 *
1625 * The exact calculation is
1626 *
1627 * dst = iround(src * dst_mask / src_mask)
1628 *
1629 * or with integer rounding
1630 *
1631 * dst = src * (2*dst_mask + sign(src)*src_mask) / (2*src_mask)
1632 *
1633 * where
1634 *
1635 * src_mask = (1 << src_bits) - 1
1636 * dst_mask = (1 << dst_bits) - 1
1637 *
1638 * but we try to avoid division and multiplication through shifts.
1639 */
1640 static inline LLVMValueRef
1641 scale_bits(struct gallivm_state *gallivm,
1642 int src_bits,
1643 int dst_bits,
1644 LLVMValueRef src,
1645 struct lp_type src_type)
1646 {
1647 LLVMBuilderRef builder = gallivm->builder;
1648 LLVMValueRef result = src;
1649
1650 if (dst_bits < src_bits) {
1651 int delta_bits = src_bits - dst_bits;
1652
1653 if (delta_bits <= dst_bits) {
1654 /*
1655 * Approximate the rescaling with a single shift.
1656 *
1657 * This gives the wrong rounding.
1658 */
1659
1660 result = LLVMBuildLShr(builder,
1661 src,
1662 lp_build_const_int_vec(gallivm, src_type, delta_bits),
1663 "");
1664
1665 } else {
1666 /*
1667 * Try more accurate rescaling.
1668 */
1669
1670 /*
1671 * Drop the least significant bits to make space for the multiplication.
1672 *
1673 * XXX: A better approach would be to use a wider integer type as intermediate. But
1674 * this is enough to convert alpha from 16bits -> 2 when rendering to
1675 * PIPE_FORMAT_R10G10B10A2_UNORM.
1676 */
1677 result = LLVMBuildLShr(builder,
1678 src,
1679 lp_build_const_int_vec(gallivm, src_type, dst_bits),
1680 "");
1681
1682
1683 result = LLVMBuildMul(builder,
1684 result,
1685 lp_build_const_int_vec(gallivm, src_type, (1LL << dst_bits) - 1),
1686 "");
1687
1688 /*
1689 * Add a rounding term before the division.
1690 *
1691 * TODO: Handle signed integers too.
1692 */
1693 if (!src_type.sign) {
1694 result = LLVMBuildAdd(builder,
1695 result,
1696 lp_build_const_int_vec(gallivm, src_type, (1LL << (delta_bits - 1))),
1697 "");
1698 }
1699
1700 /*
1701 * Approximate the division by src_mask with a src_bits shift.
1702 *
1703 * Given the src has already been shifted by dst_bits, all we need
1704 * to do is to shift by the difference.
1705 */
1706
1707 result = LLVMBuildLShr(builder,
1708 result,
1709 lp_build_const_int_vec(gallivm, src_type, delta_bits),
1710 "");
1711 }
1712
1713 } else if (dst_bits > src_bits) {
1714 /* Scale up bits */
1715 int db = dst_bits - src_bits;
1716
1717 /* Shift left by difference in bits */
1718 result = LLVMBuildShl(builder,
1719 src,
1720 lp_build_const_int_vec(gallivm, src_type, db),
1721 "");
1722
1723 if (db <= src_bits) {
1724 /* Enough bits in src to fill the remainder */
1725 LLVMValueRef lower = LLVMBuildLShr(builder,
1726 src,
1727 lp_build_const_int_vec(gallivm, src_type, src_bits - db),
1728 "");
1729
1730 result = LLVMBuildOr(builder, result, lower, "");
1731 } else if (db > src_bits) {
1732 /* Need to repeatedly copy src bits to fill remainder in dst */
1733 unsigned n;
1734
1735 for (n = src_bits; n < dst_bits; n *= 2) {
1736 LLVMValueRef shuv = lp_build_const_int_vec(gallivm, src_type, n);
1737
1738 result = LLVMBuildOr(builder,
1739 result,
1740 LLVMBuildLShr(builder, result, shuv, ""),
1741 "");
1742 }
1743 }
1744 }
1745
1746 return result;
1747 }
1748
1749 /**
1750 * If RT is a smallfloat (needing denorms) format
1751 */
1752 static inline int
1753 have_smallfloat_format(struct lp_type dst_type,
1754 enum pipe_format format)
1755 {
1756 return ((dst_type.floating && dst_type.width != 32) ||
1757 /* due to format handling hacks this format doesn't have floating set
1758 * here (and actually has width set to 32 too) so special case this. */
1759 (format == PIPE_FORMAT_R11G11B10_FLOAT));
1760 }
1761
1762
1763 /**
1764 * Convert from memory format to blending format
1765 *
1766 * e.g. GL_R3G3B2 is 1 byte in memory but 3 bytes for blending
1767 */
1768 static void
1769 convert_to_blend_type(struct gallivm_state *gallivm,
1770 unsigned block_size,
1771 const struct util_format_description *src_fmt,
1772 struct lp_type src_type,
1773 struct lp_type dst_type,
1774 LLVMValueRef* src, // and dst
1775 unsigned num_srcs)
1776 {
1777 LLVMValueRef *dst = src;
1778 LLVMBuilderRef builder = gallivm->builder;
1779 struct lp_type blend_type;
1780 struct lp_type mem_type;
1781 unsigned i, j;
1782 unsigned pixels = block_size / num_srcs;
1783 bool is_arith;
1784
1785 /*
1786 * full custom path for packed floats and srgb formats - none of the later
1787 * functions would do anything useful, and given the lp_type representation they
1788 * can't be fixed. Should really have some SoA blend path for these kind of
1789 * formats rather than hacking them in here.
1790 */
1791 if (format_expands_to_float_soa(src_fmt)) {
1792 LLVMValueRef tmpsrc[4];
1793 /*
1794 * This is pretty suboptimal for this case blending in SoA would be much
1795 * better, since conversion gets us SoA values so need to convert back.
1796 */
1797 assert(src_type.width == 32 || src_type.width == 16);
1798 assert(dst_type.floating);
1799 assert(dst_type.width == 32);
1800 assert(dst_type.length % 4 == 0);
1801 assert(num_srcs % 4 == 0);
1802
1803 if (src_type.width == 16) {
1804 /* expand 4x16bit values to 4x32bit */
1805 struct lp_type type32x4 = src_type;
1806 LLVMTypeRef ltype32x4;
1807 unsigned num_fetch = dst_type.length == 8 ? num_srcs / 2 : num_srcs / 4;
1808 type32x4.width = 32;
1809 ltype32x4 = lp_build_vec_type(gallivm, type32x4);
1810 for (i = 0; i < num_fetch; i++) {
1811 src[i] = LLVMBuildZExt(builder, src[i], ltype32x4, "");
1812 }
1813 src_type.width = 32;
1814 }
1815 for (i = 0; i < 4; i++) {
1816 tmpsrc[i] = src[i];
1817 }
1818 for (i = 0; i < num_srcs / 4; i++) {
1819 LLVMValueRef tmpsoa[4];
1820 LLVMValueRef tmps = tmpsrc[i];
1821 if (dst_type.length == 8) {
1822 LLVMValueRef shuffles[8];
1823 unsigned j;
1824 /* fetch was 4 values but need 8-wide output values */
1825 tmps = lp_build_concat(gallivm, &tmpsrc[i * 2], src_type, 2);
1826 /*
1827 * for 8-wide aos transpose would give us wrong order not matching
1828 * incoming converted fs values and mask. ARGH.
1829 */
1830 for (j = 0; j < 4; j++) {
1831 shuffles[j] = lp_build_const_int32(gallivm, j * 2);
1832 shuffles[j + 4] = lp_build_const_int32(gallivm, j * 2 + 1);
1833 }
1834 tmps = LLVMBuildShuffleVector(builder, tmps, tmps,
1835 LLVMConstVector(shuffles, 8), "");
1836 }
1837 if (src_fmt->format == PIPE_FORMAT_R11G11B10_FLOAT) {
1838 lp_build_r11g11b10_to_float(gallivm, tmps, tmpsoa);
1839 }
1840 else {
1841 lp_build_unpack_rgba_soa(gallivm, src_fmt, dst_type, tmps, tmpsoa);
1842 }
1843 lp_build_transpose_aos(gallivm, dst_type, tmpsoa, &src[i * 4]);
1844 }
1845 return;
1846 }
1847
1848 lp_mem_type_from_format_desc(src_fmt, &mem_type);
1849 lp_blend_type_from_format_desc(src_fmt, &blend_type);
1850
1851 /* Is the format arithmetic */
1852 is_arith = blend_type.length * blend_type.width != mem_type.width * mem_type.length;
1853 is_arith &= !(mem_type.width == 16 && mem_type.floating);
1854
1855 /* Pad if necessary */
1856 if (!is_arith && src_type.length < dst_type.length) {
1857 for (i = 0; i < num_srcs; ++i) {
1858 dst[i] = lp_build_pad_vector(gallivm, src[i], dst_type.length);
1859 }
1860
1861 src_type.length = dst_type.length;
1862 }
1863
1864 /* Special case for half-floats */
1865 if (mem_type.width == 16 && mem_type.floating) {
1866 assert(blend_type.width == 32 && blend_type.floating);
1867 lp_build_conv_auto(gallivm, src_type, &dst_type, dst, num_srcs, dst);
1868 is_arith = false;
1869 }
1870
1871 if (!is_arith) {
1872 return;
1873 }
1874
1875 src_type.width = blend_type.width * blend_type.length;
1876 blend_type.length *= pixels;
1877 src_type.length *= pixels / (src_type.length / mem_type.length);
1878
1879 for (i = 0; i < num_srcs; ++i) {
1880 LLVMValueRef chans[4];
1881 LLVMValueRef res = NULL;
1882
1883 dst[i] = LLVMBuildZExt(builder, src[i], lp_build_vec_type(gallivm, src_type), "");
1884
1885 for (j = 0; j < src_fmt->nr_channels; ++j) {
1886 unsigned mask = 0;
1887 unsigned sa = src_fmt->channel[j].shift;
1888 #if UTIL_ARCH_LITTLE_ENDIAN
1889 unsigned from_lsb = j;
1890 #else
1891 unsigned from_lsb = src_fmt->nr_channels - j - 1;
1892 #endif
1893
1894 mask = (1 << src_fmt->channel[j].size) - 1;
1895
1896 /* Extract bits from source */
1897 chans[j] = LLVMBuildLShr(builder,
1898 dst[i],
1899 lp_build_const_int_vec(gallivm, src_type, sa),
1900 "");
1901
1902 chans[j] = LLVMBuildAnd(builder,
1903 chans[j],
1904 lp_build_const_int_vec(gallivm, src_type, mask),
1905 "");
1906
1907 /* Scale bits */
1908 if (src_type.norm) {
1909 chans[j] = scale_bits(gallivm, src_fmt->channel[j].size,
1910 blend_type.width, chans[j], src_type);
1911 }
1912
1913 /* Insert bits into correct position */
1914 chans[j] = LLVMBuildShl(builder,
1915 chans[j],
1916 lp_build_const_int_vec(gallivm, src_type, from_lsb * blend_type.width),
1917 "");
1918
1919 if (j == 0) {
1920 res = chans[j];
1921 } else {
1922 res = LLVMBuildOr(builder, res, chans[j], "");
1923 }
1924 }
1925
1926 dst[i] = LLVMBuildBitCast(builder, res, lp_build_vec_type(gallivm, blend_type), "");
1927 }
1928 }
1929
1930
1931 /**
1932 * Convert from blending format to memory format
1933 *
1934 * e.g. GL_R3G3B2 is 3 bytes for blending but 1 byte in memory
1935 */
1936 static void
1937 convert_from_blend_type(struct gallivm_state *gallivm,
1938 unsigned block_size,
1939 const struct util_format_description *src_fmt,
1940 struct lp_type src_type,
1941 struct lp_type dst_type,
1942 LLVMValueRef* src, // and dst
1943 unsigned num_srcs)
1944 {
1945 LLVMValueRef* dst = src;
1946 unsigned i, j, k;
1947 struct lp_type mem_type;
1948 struct lp_type blend_type;
1949 LLVMBuilderRef builder = gallivm->builder;
1950 unsigned pixels = block_size / num_srcs;
1951 bool is_arith;
1952
1953 /*
1954 * full custom path for packed floats and srgb formats - none of the later
1955 * functions would do anything useful, and given the lp_type representation they
1956 * can't be fixed. Should really have some SoA blend path for these kind of
1957 * formats rather than hacking them in here.
1958 */
1959 if (format_expands_to_float_soa(src_fmt)) {
1960 /*
1961 * This is pretty suboptimal for this case blending in SoA would be much
1962 * better - we need to transpose the AoS values back to SoA values for
1963 * conversion/packing.
1964 */
1965 assert(src_type.floating);
1966 assert(src_type.width == 32);
1967 assert(src_type.length % 4 == 0);
1968 assert(dst_type.width == 32 || dst_type.width == 16);
1969
1970 for (i = 0; i < num_srcs / 4; i++) {
1971 LLVMValueRef tmpsoa[4], tmpdst;
1972 lp_build_transpose_aos(gallivm, src_type, &src[i * 4], tmpsoa);
1973 /* really really need SoA here */
1974
1975 if (src_fmt->format == PIPE_FORMAT_R11G11B10_FLOAT) {
1976 tmpdst = lp_build_float_to_r11g11b10(gallivm, tmpsoa);
1977 }
1978 else {
1979 tmpdst = lp_build_float_to_srgb_packed(gallivm, src_fmt,
1980 src_type, tmpsoa);
1981 }
1982
1983 if (src_type.length == 8) {
1984 LLVMValueRef tmpaos, shuffles[8];
1985 unsigned j;
1986 /*
1987 * for 8-wide aos transpose has given us wrong order not matching
1988 * output order. HMPF. Also need to split the output values manually.
1989 */
1990 for (j = 0; j < 4; j++) {
1991 shuffles[j * 2] = lp_build_const_int32(gallivm, j);
1992 shuffles[j * 2 + 1] = lp_build_const_int32(gallivm, j + 4);
1993 }
1994 tmpaos = LLVMBuildShuffleVector(builder, tmpdst, tmpdst,
1995 LLVMConstVector(shuffles, 8), "");
1996 src[i * 2] = lp_build_extract_range(gallivm, tmpaos, 0, 4);
1997 src[i * 2 + 1] = lp_build_extract_range(gallivm, tmpaos, 4, 4);
1998 }
1999 else {
2000 src[i] = tmpdst;
2001 }
2002 }
2003 if (dst_type.width == 16) {
2004 struct lp_type type16x8 = dst_type;
2005 struct lp_type type32x4 = dst_type;
2006 LLVMTypeRef ltype16x4, ltypei64, ltypei128;
2007 unsigned num_fetch = src_type.length == 8 ? num_srcs / 2 : num_srcs / 4;
2008 type16x8.length = 8;
2009 type32x4.width = 32;
2010 ltypei128 = LLVMIntTypeInContext(gallivm->context, 128);
2011 ltypei64 = LLVMIntTypeInContext(gallivm->context, 64);
2012 ltype16x4 = lp_build_vec_type(gallivm, dst_type);
2013 /* We could do vector truncation but it doesn't generate very good code */
2014 for (i = 0; i < num_fetch; i++) {
2015 src[i] = lp_build_pack2(gallivm, type32x4, type16x8,
2016 src[i], lp_build_zero(gallivm, type32x4));
2017 src[i] = LLVMBuildBitCast(builder, src[i], ltypei128, "");
2018 src[i] = LLVMBuildTrunc(builder, src[i], ltypei64, "");
2019 src[i] = LLVMBuildBitCast(builder, src[i], ltype16x4, "");
2020 }
2021 }
2022 return;
2023 }
2024
2025 lp_mem_type_from_format_desc(src_fmt, &mem_type);
2026 lp_blend_type_from_format_desc(src_fmt, &blend_type);
2027
2028 is_arith = (blend_type.length * blend_type.width != mem_type.width * mem_type.length);
2029
2030 /* Special case for half-floats */
2031 if (mem_type.width == 16 && mem_type.floating) {
2032 int length = dst_type.length;
2033 assert(blend_type.width == 32 && blend_type.floating);
2034
2035 dst_type.length = src_type.length;
2036
2037 lp_build_conv_auto(gallivm, src_type, &dst_type, dst, num_srcs, dst);
2038
2039 dst_type.length = length;
2040 is_arith = false;
2041 }
2042
2043 /* Remove any padding */
2044 if (!is_arith && (src_type.length % mem_type.length)) {
2045 src_type.length -= (src_type.length % mem_type.length);
2046
2047 for (i = 0; i < num_srcs; ++i) {
2048 dst[i] = lp_build_extract_range(gallivm, dst[i], 0, src_type.length);
2049 }
2050 }
2051
2052 /* No bit arithmetic to do */
2053 if (!is_arith) {
2054 return;
2055 }
2056
2057 src_type.length = pixels;
2058 src_type.width = blend_type.length * blend_type.width;
2059 dst_type.length = pixels;
2060
2061 for (i = 0; i < num_srcs; ++i) {
2062 LLVMValueRef chans[4];
2063 LLVMValueRef res = NULL;
2064
2065 dst[i] = LLVMBuildBitCast(builder, src[i], lp_build_vec_type(gallivm, src_type), "");
2066
2067 for (j = 0; j < src_fmt->nr_channels; ++j) {
2068 unsigned mask = 0;
2069 unsigned sa = src_fmt->channel[j].shift;
2070 unsigned sz_a = src_fmt->channel[j].size;
2071 #if UTIL_ARCH_LITTLE_ENDIAN
2072 unsigned from_lsb = j;
2073 #else
2074 unsigned from_lsb = src_fmt->nr_channels - j - 1;
2075 #endif
2076
2077 assert(blend_type.width > src_fmt->channel[j].size);
2078
2079 for (k = 0; k < blend_type.width; ++k) {
2080 mask |= 1 << k;
2081 }
2082
2083 /* Extract bits */
2084 chans[j] = LLVMBuildLShr(builder,
2085 dst[i],
2086 lp_build_const_int_vec(gallivm, src_type,
2087 from_lsb * blend_type.width),
2088 "");
2089
2090 chans[j] = LLVMBuildAnd(builder,
2091 chans[j],
2092 lp_build_const_int_vec(gallivm, src_type, mask),
2093 "");
2094
2095 /* Scale down bits */
2096 if (src_type.norm) {
2097 chans[j] = scale_bits(gallivm, blend_type.width,
2098 src_fmt->channel[j].size, chans[j], src_type);
2099 } else if (!src_type.floating && sz_a < blend_type.width) {
2100 LLVMValueRef mask_val = lp_build_const_int_vec(gallivm, src_type, (1UL << sz_a) - 1);
2101 LLVMValueRef mask = LLVMBuildICmp(builder, LLVMIntUGT, chans[j], mask_val, "");
2102 chans[j] = LLVMBuildSelect(builder, mask, mask_val, chans[j], "");
2103 }
2104
2105 /* Insert bits */
2106 chans[j] = LLVMBuildShl(builder,
2107 chans[j],
2108 lp_build_const_int_vec(gallivm, src_type, sa),
2109 "");
2110
2111 sa += src_fmt->channel[j].size;
2112
2113 if (j == 0) {
2114 res = chans[j];
2115 } else {
2116 res = LLVMBuildOr(builder, res, chans[j], "");
2117 }
2118 }
2119
2120 assert (dst_type.width != 24);
2121
2122 dst[i] = LLVMBuildTrunc(builder, res, lp_build_vec_type(gallivm, dst_type), "");
2123 }
2124 }
2125
2126
2127 /**
2128 * Convert alpha to same blend type as src
2129 */
2130 static void
2131 convert_alpha(struct gallivm_state *gallivm,
2132 struct lp_type row_type,
2133 struct lp_type alpha_type,
2134 const unsigned block_size,
2135 const unsigned block_height,
2136 const unsigned src_count,
2137 const unsigned dst_channels,
2138 const bool pad_inline,
2139 LLVMValueRef* src_alpha)
2140 {
2141 LLVMBuilderRef builder = gallivm->builder;
2142 unsigned i, j;
2143 unsigned length = row_type.length;
2144 row_type.length = alpha_type.length;
2145
2146 /* Twiddle the alpha to match pixels */
2147 lp_bld_quad_twiddle(gallivm, alpha_type, src_alpha, block_height, src_alpha);
2148
2149 /*
2150 * TODO this should use single lp_build_conv call for
2151 * src_count == 1 && dst_channels == 1 case (dropping the concat below)
2152 */
2153 for (i = 0; i < block_height; ++i) {
2154 lp_build_conv(gallivm, alpha_type, row_type, &src_alpha[i], 1, &src_alpha[i], 1);
2155 }
2156
2157 alpha_type = row_type;
2158 row_type.length = length;
2159
2160 /* If only one channel we can only need the single alpha value per pixel */
2161 if (src_count == 1 && dst_channels == 1) {
2162
2163 lp_build_concat_n(gallivm, alpha_type, src_alpha, block_height, src_alpha, src_count);
2164 } else {
2165 /* If there are more srcs than rows then we need to split alpha up */
2166 if (src_count > block_height) {
2167 for (i = src_count; i > 0; --i) {
2168 unsigned pixels = block_size / src_count;
2169 unsigned idx = i - 1;
2170
2171 src_alpha[idx] = lp_build_extract_range(gallivm, src_alpha[(idx * pixels) / 4],
2172 (idx * pixels) % 4, pixels);
2173 }
2174 }
2175
2176 /* If there is a src for each pixel broadcast the alpha across whole row */
2177 if (src_count == block_size) {
2178 for (i = 0; i < src_count; ++i) {
2179 src_alpha[i] = lp_build_broadcast(gallivm,
2180 lp_build_vec_type(gallivm, row_type), src_alpha[i]);
2181 }
2182 } else {
2183 unsigned pixels = block_size / src_count;
2184 unsigned channels = pad_inline ? TGSI_NUM_CHANNELS : dst_channels;
2185 unsigned alpha_span = 1;
2186 LLVMValueRef shuffles[LP_MAX_VECTOR_LENGTH];
2187
2188 /* Check if we need 2 src_alphas for our shuffles */
2189 if (pixels > alpha_type.length) {
2190 alpha_span = 2;
2191 }
2192
2193 /* Broadcast alpha across all channels, e.g. a1a2 to a1a1a1a1a2a2a2a2 */
2194 for (j = 0; j < row_type.length; ++j) {
2195 if (j < pixels * channels) {
2196 shuffles[j] = lp_build_const_int32(gallivm, j / channels);
2197 } else {
2198 shuffles[j] = LLVMGetUndef(LLVMInt32TypeInContext(gallivm->context));
2199 }
2200 }
2201
2202 for (i = 0; i < src_count; ++i) {
2203 unsigned idx1 = i, idx2 = i;
2204
2205 if (alpha_span > 1){
2206 idx1 *= alpha_span;
2207 idx2 = idx1 + 1;
2208 }
2209
2210 src_alpha[i] = LLVMBuildShuffleVector(builder,
2211 src_alpha[idx1],
2212 src_alpha[idx2],
2213 LLVMConstVector(shuffles, row_type.length),
2214 "");
2215 }
2216 }
2217 }
2218 }
2219
2220
2221 /**
2222 * Generates the blend function for unswizzled colour buffers
2223 * Also generates the read & write from colour buffer
2224 */
2225 static void
2226 generate_unswizzled_blend(struct gallivm_state *gallivm,
2227 unsigned rt,
2228 struct lp_fragment_shader_variant *variant,
2229 enum pipe_format out_format,
2230 unsigned int num_fs,
2231 struct lp_type fs_type,
2232 LLVMValueRef* fs_mask,
2233 LLVMValueRef fs_out_color[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS][4],
2234 LLVMValueRef context_ptr,
2235 LLVMValueRef color_ptr,
2236 LLVMValueRef stride,
2237 unsigned partial_mask,
2238 boolean do_branch)
2239 {
2240 const unsigned alpha_channel = 3;
2241 const unsigned block_width = LP_RASTER_BLOCK_SIZE;
2242 const unsigned block_height = LP_RASTER_BLOCK_SIZE;
2243 const unsigned block_size = block_width * block_height;
2244 const unsigned lp_integer_vector_width = 128;
2245
2246 LLVMBuilderRef builder = gallivm->builder;
2247 LLVMValueRef fs_src[4][TGSI_NUM_CHANNELS];
2248 LLVMValueRef fs_src1[4][TGSI_NUM_CHANNELS];
2249 LLVMValueRef src_alpha[4 * 4];
2250 LLVMValueRef src1_alpha[4 * 4] = { NULL };
2251 LLVMValueRef src_mask[4 * 4];
2252 LLVMValueRef src[4 * 4];
2253 LLVMValueRef src1[4 * 4];
2254 LLVMValueRef dst[4 * 4];
2255 LLVMValueRef blend_color;
2256 LLVMValueRef blend_alpha;
2257 LLVMValueRef i32_zero;
2258 LLVMValueRef check_mask;
2259 LLVMValueRef undef_src_val;
2260
2261 struct lp_build_mask_context mask_ctx;
2262 struct lp_type mask_type;
2263 struct lp_type blend_type;
2264 struct lp_type row_type;
2265 struct lp_type dst_type;
2266 struct lp_type ls_type;
2267
2268 unsigned char swizzle[TGSI_NUM_CHANNELS];
2269 unsigned vector_width;
2270 unsigned src_channels = TGSI_NUM_CHANNELS;
2271 unsigned dst_channels;
2272 unsigned dst_count;
2273 unsigned src_count;
2274 unsigned i, j;
2275
2276 const struct util_format_description* out_format_desc = util_format_description(out_format);
2277
2278 unsigned dst_alignment;
2279
2280 bool pad_inline = is_arithmetic_format(out_format_desc);
2281 bool has_alpha = false;
2282 const boolean dual_source_blend = variant->key.blend.rt[0].blend_enable &&
2283 util_blend_state_is_dual(&variant->key.blend, 0);
2284
2285 const boolean is_1d = variant->key.resource_1d;
2286 boolean twiddle_after_convert = FALSE;
2287 unsigned num_fullblock_fs = is_1d ? 2 * num_fs : num_fs;
2288 LLVMValueRef fpstate = 0;
2289
2290 /* Get type from output format */
2291 lp_blend_type_from_format_desc(out_format_desc, &row_type);
2292 lp_mem_type_from_format_desc(out_format_desc, &dst_type);
2293
2294 /*
2295 * Technically this code should go into lp_build_smallfloat_to_float
2296 * and lp_build_float_to_smallfloat but due to the
2297 * http://llvm.org/bugs/show_bug.cgi?id=6393
2298 * llvm reorders the mxcsr intrinsics in a way that breaks the code.
2299 * So the ordering is important here and there shouldn't be any
2300 * llvm ir instrunctions in this function before
2301 * this, otherwise half-float format conversions won't work
2302 * (again due to llvm bug #6393).
2303 */
2304 if (have_smallfloat_format(dst_type, out_format)) {
2305 /* We need to make sure that denorms are ok for half float
2306 conversions */
2307 fpstate = lp_build_fpstate_get(gallivm);
2308 lp_build_fpstate_set_denorms_zero(gallivm, FALSE);
2309 }
2310
2311 mask_type = lp_int32_vec4_type();
2312 mask_type.length = fs_type.length;
2313
2314 for (i = num_fs; i < num_fullblock_fs; i++) {
2315 fs_mask[i] = lp_build_zero(gallivm, mask_type);
2316 }
2317
2318 /* Do not bother executing code when mask is empty.. */
2319 if (do_branch) {
2320 check_mask = LLVMConstNull(lp_build_int_vec_type(gallivm, mask_type));
2321
2322 for (i = 0; i < num_fullblock_fs; ++i) {
2323 check_mask = LLVMBuildOr(builder, check_mask, fs_mask[i], "");
2324 }
2325
2326 lp_build_mask_begin(&mask_ctx, gallivm, mask_type, check_mask);
2327 lp_build_mask_check(&mask_ctx);
2328 }
2329
2330 partial_mask |= !variant->opaque;
2331 i32_zero = lp_build_const_int32(gallivm, 0);
2332
2333 undef_src_val = lp_build_undef(gallivm, fs_type);
2334
2335 row_type.length = fs_type.length;
2336 vector_width = dst_type.floating ? lp_native_vector_width : lp_integer_vector_width;
2337
2338 /* Compute correct swizzle and count channels */
2339 memset(swizzle, LP_BLD_SWIZZLE_DONTCARE, TGSI_NUM_CHANNELS);
2340 dst_channels = 0;
2341
2342 for (i = 0; i < TGSI_NUM_CHANNELS; ++i) {
2343 /* Ensure channel is used */
2344 if (out_format_desc->swizzle[i] >= TGSI_NUM_CHANNELS) {
2345 continue;
2346 }
2347
2348 /* Ensure not already written to (happens in case with GL_ALPHA) */
2349 if (swizzle[out_format_desc->swizzle[i]] < TGSI_NUM_CHANNELS) {
2350 continue;
2351 }
2352
2353 /* Ensure we havn't already found all channels */
2354 if (dst_channels >= out_format_desc->nr_channels) {
2355 continue;
2356 }
2357
2358 swizzle[out_format_desc->swizzle[i]] = i;
2359 ++dst_channels;
2360
2361 if (i == alpha_channel) {
2362 has_alpha = true;
2363 }
2364 }
2365
2366 if (format_expands_to_float_soa(out_format_desc)) {
2367 /*
2368 * the code above can't work for layout_other
2369 * for srgb it would sort of work but we short-circuit swizzles, etc.
2370 * as that is done as part of unpack / pack.
2371 */
2372 dst_channels = 4; /* HACK: this is fake 4 really but need it due to transpose stuff later */
2373 has_alpha = true;
2374 swizzle[0] = 0;
2375 swizzle[1] = 1;
2376 swizzle[2] = 2;
2377 swizzle[3] = 3;
2378 pad_inline = true; /* HACK: prevent rgbxrgbx->rgbrgbxx conversion later */
2379 }
2380
2381 /* If 3 channels then pad to include alpha for 4 element transpose */
2382 if (dst_channels == 3) {
2383 assert (!has_alpha);
2384 for (i = 0; i < TGSI_NUM_CHANNELS; i++) {
2385 if (swizzle[i] > TGSI_NUM_CHANNELS)
2386 swizzle[i] = 3;
2387 }
2388 if (out_format_desc->nr_channels == 4) {
2389 dst_channels = 4;
2390 /*
2391 * We use alpha from the color conversion, not separate one.
2392 * We had to include it for transpose, hence it will get converted
2393 * too (albeit when doing transpose after conversion, that would
2394 * no longer be the case necessarily).
2395 * (It works only with 4 channel dsts, e.g. rgbx formats, because
2396 * otherwise we really have padding, not alpha, included.)
2397 */
2398 has_alpha = true;
2399 }
2400 }
2401
2402 /*
2403 * Load shader output
2404 */
2405 for (i = 0; i < num_fullblock_fs; ++i) {
2406 /* Always load alpha for use in blending */
2407 LLVMValueRef alpha;
2408 if (i < num_fs) {
2409 alpha = LLVMBuildLoad(builder, fs_out_color[rt][alpha_channel][i], "");
2410 }
2411 else {
2412 alpha = undef_src_val;
2413 }
2414
2415 /* Load each channel */
2416 for (j = 0; j < dst_channels; ++j) {
2417 assert(swizzle[j] < 4);
2418 if (i < num_fs) {
2419 fs_src[i][j] = LLVMBuildLoad(builder, fs_out_color[rt][swizzle[j]][i], "");
2420 }
2421 else {
2422 fs_src[i][j] = undef_src_val;
2423 }
2424 }
2425
2426 /* If 3 channels then pad to include alpha for 4 element transpose */
2427 /*
2428 * XXX If we include that here maybe could actually use it instead of
2429 * separate alpha for blending?
2430 * (Difficult though we actually convert pad channels, not alpha.)
2431 */
2432 if (dst_channels == 3 && !has_alpha) {
2433 fs_src[i][3] = alpha;
2434 }
2435
2436 /* We split the row_mask and row_alpha as we want 128bit interleave */
2437 if (fs_type.length == 8) {
2438 src_mask[i*2 + 0] = lp_build_extract_range(gallivm, fs_mask[i],
2439 0, src_channels);
2440 src_mask[i*2 + 1] = lp_build_extract_range(gallivm, fs_mask[i],
2441 src_channels, src_channels);
2442
2443 src_alpha[i*2 + 0] = lp_build_extract_range(gallivm, alpha, 0, src_channels);
2444 src_alpha[i*2 + 1] = lp_build_extract_range(gallivm, alpha,
2445 src_channels, src_channels);
2446 } else {
2447 src_mask[i] = fs_mask[i];
2448 src_alpha[i] = alpha;
2449 }
2450 }
2451 if (dual_source_blend) {
2452 /* same as above except different src/dst, skip masks and comments... */
2453 for (i = 0; i < num_fullblock_fs; ++i) {
2454 LLVMValueRef alpha;
2455 if (i < num_fs) {
2456 alpha = LLVMBuildLoad(builder, fs_out_color[1][alpha_channel][i], "");
2457 }
2458 else {
2459 alpha = undef_src_val;
2460 }
2461
2462 for (j = 0; j < dst_channels; ++j) {
2463 assert(swizzle[j] < 4);
2464 if (i < num_fs) {
2465 fs_src1[i][j] = LLVMBuildLoad(builder, fs_out_color[1][swizzle[j]][i], "");
2466 }
2467 else {
2468 fs_src1[i][j] = undef_src_val;
2469 }
2470 }
2471 if (dst_channels == 3 && !has_alpha) {
2472 fs_src1[i][3] = alpha;
2473 }
2474 if (fs_type.length == 8) {
2475 src1_alpha[i*2 + 0] = lp_build_extract_range(gallivm, alpha, 0, src_channels);
2476 src1_alpha[i*2 + 1] = lp_build_extract_range(gallivm, alpha,
2477 src_channels, src_channels);
2478 } else {
2479 src1_alpha[i] = alpha;
2480 }
2481 }
2482 }
2483
2484 if (util_format_is_pure_integer(out_format)) {
2485 /*
2486 * In this case fs_type was really ints or uints disguised as floats,
2487 * fix that up now.
2488 */
2489 fs_type.floating = 0;
2490 fs_type.sign = dst_type.sign;
2491 for (i = 0; i < num_fullblock_fs; ++i) {
2492 for (j = 0; j < dst_channels; ++j) {
2493 fs_src[i][j] = LLVMBuildBitCast(builder, fs_src[i][j],
2494 lp_build_vec_type(gallivm, fs_type), "");
2495 }
2496 if (dst_channels == 3 && !has_alpha) {
2497 fs_src[i][3] = LLVMBuildBitCast(builder, fs_src[i][3],
2498 lp_build_vec_type(gallivm, fs_type), "");
2499 }
2500 }
2501 }
2502
2503 /*
2504 * We actually should generally do conversion first (for non-1d cases)
2505 * when the blend format is 8 or 16 bits. The reason is obvious,
2506 * there's 2 or 4 times less vectors to deal with for the interleave...
2507 * Albeit for the AVX (not AVX2) case there's no benefit with 16 bit
2508 * vectors (as it can do 32bit unpack with 256bit vectors, but 8/16bit
2509 * unpack only with 128bit vectors).
2510 * Note: for 16bit sizes really need matching pack conversion code
2511 */
2512 if (!is_1d && dst_channels != 3 && dst_type.width == 8) {
2513 twiddle_after_convert = TRUE;
2514 }
2515
2516 /*
2517 * Pixel twiddle from fragment shader order to memory order
2518 */
2519 if (!twiddle_after_convert) {
2520 src_count = generate_fs_twiddle(gallivm, fs_type, num_fullblock_fs,
2521 dst_channels, fs_src, src, pad_inline);
2522 if (dual_source_blend) {
2523 generate_fs_twiddle(gallivm, fs_type, num_fullblock_fs, dst_channels,
2524 fs_src1, src1, pad_inline);
2525 }
2526 } else {
2527 src_count = num_fullblock_fs * dst_channels;
2528 /*
2529 * We reorder things a bit here, so the cases for 4-wide and 8-wide
2530 * (AVX) turn out the same later when untwiddling/transpose (albeit
2531 * for true AVX2 path untwiddle needs to be different).
2532 * For now just order by colors first (so we can use unpack later).
2533 */
2534 for (j = 0; j < num_fullblock_fs; j++) {
2535 for (i = 0; i < dst_channels; i++) {
2536 src[i*num_fullblock_fs + j] = fs_src[j][i];
2537 if (dual_source_blend) {
2538 src1[i*num_fullblock_fs + j] = fs_src1[j][i];
2539 }
2540 }
2541 }
2542 }
2543
2544 src_channels = dst_channels < 3 ? dst_channels : 4;
2545 if (src_count != num_fullblock_fs * src_channels) {
2546 unsigned ds = src_count / (num_fullblock_fs * src_channels);
2547 row_type.length /= ds;
2548 fs_type.length = row_type.length;
2549 }
2550
2551 blend_type = row_type;
2552 mask_type.length = 4;
2553
2554 /* Convert src to row_type */
2555 if (dual_source_blend) {
2556 struct lp_type old_row_type = row_type;
2557 lp_build_conv_auto(gallivm, fs_type, &row_type, src, src_count, src);
2558 src_count = lp_build_conv_auto(gallivm, fs_type, &old_row_type, src1, src_count, src1);
2559 }
2560 else {
2561 src_count = lp_build_conv_auto(gallivm, fs_type, &row_type, src, src_count, src);
2562 }
2563
2564 /* If the rows are not an SSE vector, combine them to become SSE size! */
2565 if ((row_type.width * row_type.length) % 128) {
2566 unsigned bits = row_type.width * row_type.length;
2567 unsigned combined;
2568
2569 assert(src_count >= (vector_width / bits));
2570
2571 dst_count = src_count / (vector_width / bits);
2572
2573 combined = lp_build_concat_n(gallivm, row_type, src, src_count, src, dst_count);
2574 if (dual_source_blend) {
2575 lp_build_concat_n(gallivm, row_type, src1, src_count, src1, dst_count);
2576 }
2577
2578 row_type.length *= combined;
2579 src_count /= combined;
2580
2581 bits = row_type.width * row_type.length;
2582 assert(bits == 128 || bits == 256);
2583 }
2584
2585 if (twiddle_after_convert) {
2586 fs_twiddle_transpose(gallivm, row_type, src, src_count, src);
2587 if (dual_source_blend) {
2588 fs_twiddle_transpose(gallivm, row_type, src1, src_count, src1);
2589 }
2590 }
2591
2592 /*
2593 * Blend Colour conversion
2594 */
2595 blend_color = lp_jit_context_f_blend_color(gallivm, context_ptr);
2596 blend_color = LLVMBuildPointerCast(builder, blend_color,
2597 LLVMPointerType(lp_build_vec_type(gallivm, fs_type), 0), "");
2598 blend_color = LLVMBuildLoad(builder, LLVMBuildGEP(builder, blend_color,
2599 &i32_zero, 1, ""), "");
2600
2601 /* Convert */
2602 lp_build_conv(gallivm, fs_type, blend_type, &blend_color, 1, &blend_color, 1);
2603
2604 if (out_format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB) {
2605 /*
2606 * since blending is done with floats, there was no conversion.
2607 * However, the rules according to fixed point renderbuffers still
2608 * apply, that is we must clamp inputs to 0.0/1.0.
2609 * (This would apply to separate alpha conversion too but we currently
2610 * force has_alpha to be true.)
2611 * TODO: should skip this with "fake" blend, since post-blend conversion
2612 * will clamp anyway.
2613 * TODO: could also skip this if fragment color clamping is enabled. We
2614 * don't support it natively so it gets baked into the shader however, so
2615 * can't really tell here.
2616 */
2617 struct lp_build_context f32_bld;
2618 assert(row_type.floating);
2619 lp_build_context_init(&f32_bld, gallivm, row_type);
2620 for (i = 0; i < src_count; i++) {
2621 src[i] = lp_build_clamp_zero_one_nanzero(&f32_bld, src[i]);
2622 }
2623 if (dual_source_blend) {
2624 for (i = 0; i < src_count; i++) {
2625 src1[i] = lp_build_clamp_zero_one_nanzero(&f32_bld, src1[i]);
2626 }
2627 }
2628 /* probably can't be different than row_type but better safe than sorry... */
2629 lp_build_context_init(&f32_bld, gallivm, blend_type);
2630 blend_color = lp_build_clamp(&f32_bld, blend_color, f32_bld.zero, f32_bld.one);
2631 }
2632
2633 /* Extract alpha */
2634 blend_alpha = lp_build_extract_broadcast(gallivm, blend_type, row_type, blend_color, lp_build_const_int32(gallivm, 3));
2635
2636 /* Swizzle to appropriate channels, e.g. from RGBA to BGRA BGRA */
2637 pad_inline &= (dst_channels * (block_size / src_count) * row_type.width) != vector_width;
2638 if (pad_inline) {
2639 /* Use all 4 channels e.g. from RGBA RGBA to RGxx RGxx */
2640 blend_color = lp_build_swizzle_aos_n(gallivm, blend_color, swizzle, TGSI_NUM_CHANNELS, row_type.length);
2641 } else {
2642 /* Only use dst_channels e.g. RGBA RGBA to RG RG xxxx */
2643 blend_color = lp_build_swizzle_aos_n(gallivm, blend_color, swizzle, dst_channels, row_type.length);
2644 }
2645
2646 /*
2647 * Mask conversion
2648 */
2649 lp_bld_quad_twiddle(gallivm, mask_type, &src_mask[0], block_height, &src_mask[0]);
2650
2651 if (src_count < block_height) {
2652 lp_build_concat_n(gallivm, mask_type, src_mask, 4, src_mask, src_count);
2653 } else if (src_count > block_height) {
2654 for (i = src_count; i > 0; --i) {
2655 unsigned pixels = block_size / src_count;
2656 unsigned idx = i - 1;
2657
2658 src_mask[idx] = lp_build_extract_range(gallivm, src_mask[(idx * pixels) / 4],
2659 (idx * pixels) % 4, pixels);
2660 }
2661 }
2662
2663 assert(mask_type.width == 32);
2664
2665 for (i = 0; i < src_count; ++i) {
2666 unsigned pixels = block_size / src_count;
2667 unsigned pixel_width = row_type.width * dst_channels;
2668
2669 if (pixel_width == 24) {
2670 mask_type.width = 8;
2671 mask_type.length = vector_width / mask_type.width;
2672 } else {
2673 mask_type.length = pixels;
2674 mask_type.width = row_type.width * dst_channels;
2675
2676 /*
2677 * If mask_type width is smaller than 32bit, this doesn't quite
2678 * generate the most efficient code (could use some pack).
2679 */
2680 src_mask[i] = LLVMBuildIntCast(builder, src_mask[i],
2681 lp_build_int_vec_type(gallivm, mask_type), "");
2682
2683 mask_type.length *= dst_channels;
2684 mask_type.width /= dst_channels;
2685 }
2686
2687 src_mask[i] = LLVMBuildBitCast(builder, src_mask[i],
2688 lp_build_int_vec_type(gallivm, mask_type), "");
2689 src_mask[i] = lp_build_pad_vector(gallivm, src_mask[i], row_type.length);
2690 }
2691
2692 /*
2693 * Alpha conversion
2694 */
2695 if (!has_alpha) {
2696 struct lp_type alpha_type = fs_type;
2697 alpha_type.length = 4;
2698 convert_alpha(gallivm, row_type, alpha_type,
2699 block_size, block_height,
2700 src_count, dst_channels,
2701 pad_inline, src_alpha);
2702 if (dual_source_blend) {
2703 convert_alpha(gallivm, row_type, alpha_type,
2704 block_size, block_height,
2705 src_count, dst_channels,
2706 pad_inline, src1_alpha);
2707 }
2708 }
2709
2710
2711 /*
2712 * Load dst from memory
2713 */
2714 if (src_count < block_height) {
2715 dst_count = block_height;
2716 } else {
2717 dst_count = src_count;
2718 }
2719
2720 dst_type.length *= block_size / dst_count;
2721
2722 if (format_expands_to_float_soa(out_format_desc)) {
2723 /*
2724 * we need multiple values at once for the conversion, so can as well
2725 * load them vectorized here too instead of concatenating later.
2726 * (Still need concatenation later for 8-wide vectors).
2727 */
2728 dst_count = block_height;
2729 dst_type.length = block_width;
2730 }
2731
2732 /*
2733 * Compute the alignment of the destination pointer in bytes
2734 * We fetch 1-4 pixels, if the format has pot alignment then those fetches
2735 * are always aligned by MIN2(16, fetch_width) except for buffers (not
2736 * 1d tex but can't distinguish here) so need to stick with per-pixel
2737 * alignment in this case.
2738 */
2739 if (is_1d) {
2740 dst_alignment = (out_format_desc->block.bits + 7)/(out_format_desc->block.width * 8);
2741 }
2742 else {
2743 dst_alignment = dst_type.length * dst_type.width / 8;
2744 }
2745 /* Force power-of-two alignment by extracting only the least-significant-bit */
2746 dst_alignment = 1 << (ffs(dst_alignment) - 1);
2747 /*
2748 * Resource base and stride pointers are aligned to 16 bytes, so that's
2749 * the maximum alignment we can guarantee
2750 */
2751 dst_alignment = MIN2(16, dst_alignment);
2752
2753 ls_type = dst_type;
2754
2755 if (dst_count > src_count) {
2756 if ((dst_type.width == 8 || dst_type.width == 16) &&
2757 util_is_power_of_two_or_zero(dst_type.length) &&
2758 dst_type.length * dst_type.width < 128) {
2759 /*
2760 * Never try to load values as 4xi8 which we will then
2761 * concatenate to larger vectors. This gives llvm a real
2762 * headache (the problem is the type legalizer (?) will
2763 * try to load that as 4xi8 zext to 4xi32 to fill the vector,
2764 * then the shuffles to concatenate are more or less impossible
2765 * - llvm is easily capable of generating a sequence of 32
2766 * pextrb/pinsrb instructions for that. Albeit it appears to
2767 * be fixed in llvm 4.0. So, load and concatenate with 32bit
2768 * width to avoid the trouble (16bit seems not as bad, llvm
2769 * probably recognizes the load+shuffle as only one shuffle
2770 * is necessary, but we can do just the same anyway).
2771 */
2772 ls_type.length = dst_type.length * dst_type.width / 32;
2773 ls_type.width = 32;
2774 }
2775 }
2776
2777 if (is_1d) {
2778 load_unswizzled_block(gallivm, color_ptr, stride, block_width, 1,
2779 dst, ls_type, dst_count / 4, dst_alignment, NULL, NULL, false);
2780 for (i = dst_count / 4; i < dst_count; i++) {
2781 dst[i] = lp_build_undef(gallivm, ls_type);
2782 }
2783
2784 }
2785 else {
2786 load_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height,
2787 dst, ls_type, dst_count, dst_alignment, NULL, NULL, false);
2788 }
2789
2790
2791 /*
2792 * Convert from dst/output format to src/blending format.
2793 *
2794 * This is necessary as we can only read 1 row from memory at a time,
2795 * so the minimum dst_count will ever be at this point is 4.
2796 *
2797 * With, for example, R8 format you can have all 16 pixels in a 128 bit vector,
2798 * this will take the 4 dsts and combine them into 1 src so we can perform blending
2799 * on all 16 pixels in that single vector at once.
2800 */
2801 if (dst_count > src_count) {
2802 if (ls_type.length != dst_type.length && ls_type.length == 1) {
2803 LLVMTypeRef elem_type = lp_build_elem_type(gallivm, ls_type);
2804 LLVMTypeRef ls_vec_type = LLVMVectorType(elem_type, 1);
2805 for (i = 0; i < dst_count; i++) {
2806 dst[i] = LLVMBuildBitCast(builder, dst[i], ls_vec_type, "");
2807 }
2808 }
2809
2810 lp_build_concat_n(gallivm, ls_type, dst, 4, dst, src_count);
2811
2812 if (ls_type.length != dst_type.length) {
2813 struct lp_type tmp_type = dst_type;
2814 tmp_type.length = dst_type.length * 4 / src_count;
2815 for (i = 0; i < src_count; i++) {
2816 dst[i] = LLVMBuildBitCast(builder, dst[i],
2817 lp_build_vec_type(gallivm, tmp_type), "");
2818 }
2819 }
2820 }
2821
2822 /*
2823 * Blending
2824 */
2825 /* XXX this is broken for RGB8 formats -
2826 * they get expanded from 12 to 16 elements (to include alpha)
2827 * by convert_to_blend_type then reduced to 15 instead of 12
2828 * by convert_from_blend_type (a simple fix though breaks A8...).
2829 * R16G16B16 also crashes differently however something going wrong
2830 * inside llvm handling npot vector sizes seemingly.
2831 * It seems some cleanup could be done here (like skipping conversion/blend
2832 * when not needed).
2833 */
2834 convert_to_blend_type(gallivm, block_size, out_format_desc, dst_type,
2835 row_type, dst, src_count);
2836
2837 /*
2838 * FIXME: Really should get logic ops / masks out of generic blend / row
2839 * format. Logic ops will definitely not work on the blend float format
2840 * used for SRGB here and I think OpenGL expects this to work as expected
2841 * (that is incoming values converted to srgb then logic op applied).
2842 */
2843 for (i = 0; i < src_count; ++i) {
2844 dst[i] = lp_build_blend_aos(gallivm,
2845 &variant->key.blend,
2846 out_format,
2847 row_type,
2848 rt,
2849 src[i],
2850 has_alpha ? NULL : src_alpha[i],
2851 src1[i],
2852 has_alpha ? NULL : src1_alpha[i],
2853 dst[i],
2854 partial_mask ? src_mask[i] : NULL,
2855 blend_color,
2856 has_alpha ? NULL : blend_alpha,
2857 swizzle,
2858 pad_inline ? 4 : dst_channels);
2859 }
2860
2861 convert_from_blend_type(gallivm, block_size, out_format_desc,
2862 row_type, dst_type, dst, src_count);
2863
2864 /* Split the blend rows back to memory rows */
2865 if (dst_count > src_count) {
2866 row_type.length = dst_type.length * (dst_count / src_count);
2867
2868 if (src_count == 1) {
2869 dst[1] = lp_build_extract_range(gallivm, dst[0], row_type.length / 2, row_type.length / 2);
2870 dst[0] = lp_build_extract_range(gallivm, dst[0], 0, row_type.length / 2);
2871
2872 row_type.length /= 2;
2873 src_count *= 2;
2874 }
2875
2876 dst[3] = lp_build_extract_range(gallivm, dst[1], row_type.length / 2, row_type.length / 2);
2877 dst[2] = lp_build_extract_range(gallivm, dst[1], 0, row_type.length / 2);
2878 dst[1] = lp_build_extract_range(gallivm, dst[0], row_type.length / 2, row_type.length / 2);
2879 dst[0] = lp_build_extract_range(gallivm, dst[0], 0, row_type.length / 2);
2880
2881 row_type.length /= 2;
2882 src_count *= 2;
2883 }
2884
2885 /*
2886 * Store blend result to memory
2887 */
2888 if (is_1d) {
2889 store_unswizzled_block(gallivm, color_ptr, stride, block_width, 1,
2890 dst, dst_type, dst_count / 4, dst_alignment);
2891 }
2892 else {
2893 store_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height,
2894 dst, dst_type, dst_count, dst_alignment);
2895 }
2896
2897 if (have_smallfloat_format(dst_type, out_format)) {
2898 lp_build_fpstate_set(gallivm, fpstate);
2899 }
2900
2901 if (do_branch) {
2902 lp_build_mask_end(&mask_ctx);
2903 }
2904 }
2905
2906
2907 /**
2908 * Generate the runtime callable function for the whole fragment pipeline.
2909 * Note that the function which we generate operates on a block of 16
2910 * pixels at at time. The block contains 2x2 quads. Each quad contains
2911 * 2x2 pixels.
2912 */
2913 static void
2914 generate_fragment(struct llvmpipe_context *lp,
2915 struct lp_fragment_shader *shader,
2916 struct lp_fragment_shader_variant *variant,
2917 unsigned partial_mask)
2918 {
2919 struct gallivm_state *gallivm = variant->gallivm;
2920 struct lp_fragment_shader_variant_key *key = &variant->key;
2921 struct lp_shader_input inputs[PIPE_MAX_SHADER_INPUTS];
2922 char func_name[64];
2923 struct lp_type fs_type;
2924 struct lp_type blend_type;
2925 LLVMTypeRef fs_elem_type;
2926 LLVMTypeRef blend_vec_type;
2927 LLVMTypeRef arg_types[15];
2928 LLVMTypeRef func_type;
2929 LLVMTypeRef int32_type = LLVMInt32TypeInContext(gallivm->context);
2930 LLVMTypeRef int8_type = LLVMInt8TypeInContext(gallivm->context);
2931 LLVMValueRef context_ptr;
2932 LLVMValueRef x;
2933 LLVMValueRef y;
2934 LLVMValueRef a0_ptr;
2935 LLVMValueRef dadx_ptr;
2936 LLVMValueRef dady_ptr;
2937 LLVMValueRef color_ptr_ptr;
2938 LLVMValueRef stride_ptr;
2939 LLVMValueRef color_sample_stride_ptr;
2940 LLVMValueRef depth_ptr;
2941 LLVMValueRef depth_stride;
2942 LLVMValueRef depth_sample_stride;
2943 LLVMValueRef mask_input;
2944 LLVMValueRef thread_data_ptr;
2945 LLVMBasicBlockRef block;
2946 LLVMBuilderRef builder;
2947 struct lp_build_sampler_soa *sampler;
2948 struct lp_build_image_soa *image;
2949 struct lp_build_interp_soa_context interp;
2950 LLVMValueRef fs_mask[(16 / 4) * LP_MAX_SAMPLES];
2951 LLVMValueRef fs_out_color[LP_MAX_SAMPLES][PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS][16 / 4];
2952 LLVMValueRef function;
2953 LLVMValueRef facing;
2954 unsigned num_fs;
2955 unsigned i;
2956 unsigned chan;
2957 unsigned cbuf;
2958 boolean cbuf0_write_all;
2959 const boolean dual_source_blend = key->blend.rt[0].blend_enable &&
2960 util_blend_state_is_dual(&key->blend, 0);
2961
2962 assert(lp_native_vector_width / 32 >= 4);
2963
2964 /* Adjust color input interpolation according to flatshade state:
2965 */
2966 memcpy(inputs, shader->inputs, shader->info.base.num_inputs * sizeof inputs[0]);
2967 for (i = 0; i < shader->info.base.num_inputs; i++) {
2968 if (inputs[i].interp == LP_INTERP_COLOR) {
2969 if (key->flatshade)
2970 inputs[i].interp = LP_INTERP_CONSTANT;
2971 else
2972 inputs[i].interp = LP_INTERP_PERSPECTIVE;
2973 }
2974 }
2975
2976 /* check if writes to cbuf[0] are to be copied to all cbufs */
2977 cbuf0_write_all =
2978 shader->info.base.properties[TGSI_PROPERTY_FS_COLOR0_WRITES_ALL_CBUFS];
2979
2980 /* TODO: actually pick these based on the fs and color buffer
2981 * characteristics. */
2982
2983 memset(&fs_type, 0, sizeof fs_type);
2984 fs_type.floating = TRUE; /* floating point values */
2985 fs_type.sign = TRUE; /* values are signed */
2986 fs_type.norm = FALSE; /* values are not limited to [0,1] or [-1,1] */
2987 fs_type.width = 32; /* 32-bit float */
2988 fs_type.length = MIN2(lp_native_vector_width / 32, 16); /* n*4 elements per vector */
2989
2990 memset(&blend_type, 0, sizeof blend_type);
2991 blend_type.floating = FALSE; /* values are integers */
2992 blend_type.sign = FALSE; /* values are unsigned */
2993 blend_type.norm = TRUE; /* values are in [0,1] or [-1,1] */
2994 blend_type.width = 8; /* 8-bit ubyte values */
2995 blend_type.length = 16; /* 16 elements per vector */
2996
2997 /*
2998 * Generate the function prototype. Any change here must be reflected in
2999 * lp_jit.h's lp_jit_frag_func function pointer type, and vice-versa.
3000 */
3001
3002 fs_elem_type = lp_build_elem_type(gallivm, fs_type);
3003
3004 blend_vec_type = lp_build_vec_type(gallivm, blend_type);
3005
3006 snprintf(func_name, sizeof(func_name), "fs_variant_%s",
3007 partial_mask ? "partial" : "whole");
3008
3009 arg_types[0] = variant->jit_context_ptr_type; /* context */
3010 arg_types[1] = int32_type; /* x */
3011 arg_types[2] = int32_type; /* y */
3012 arg_types[3] = int32_type; /* facing */
3013 arg_types[4] = LLVMPointerType(fs_elem_type, 0); /* a0 */
3014 arg_types[5] = LLVMPointerType(fs_elem_type, 0); /* dadx */
3015 arg_types[6] = LLVMPointerType(fs_elem_type, 0); /* dady */
3016 arg_types[7] = LLVMPointerType(LLVMPointerType(int8_type, 0), 0); /* color */
3017 arg_types[8] = LLVMPointerType(int8_type, 0); /* depth */
3018 arg_types[9] = LLVMInt64TypeInContext(gallivm->context); /* mask_input */
3019 arg_types[10] = variant->jit_thread_data_ptr_type; /* per thread data */
3020 arg_types[11] = LLVMPointerType(int32_type, 0); /* stride */
3021 arg_types[12] = int32_type; /* depth_stride */
3022 arg_types[13] = LLVMPointerType(int32_type, 0); /* color sample strides */
3023 arg_types[14] = int32_type; /* depth sample stride */
3024
3025 func_type = LLVMFunctionType(LLVMVoidTypeInContext(gallivm->context),
3026 arg_types, ARRAY_SIZE(arg_types), 0);
3027
3028 function = LLVMAddFunction(gallivm->module, func_name, func_type);
3029 LLVMSetFunctionCallConv(function, LLVMCCallConv);
3030
3031 variant->function[partial_mask] = function;
3032
3033 /* XXX: need to propagate noalias down into color param now we are
3034 * passing a pointer-to-pointer?
3035 */
3036 for(i = 0; i < ARRAY_SIZE(arg_types); ++i)
3037 if(LLVMGetTypeKind(arg_types[i]) == LLVMPointerTypeKind)
3038 lp_add_function_attr(function, i + 1, LP_FUNC_ATTR_NOALIAS);
3039
3040 if (variant->gallivm->cache->data_size)
3041 return;
3042
3043 context_ptr = LLVMGetParam(function, 0);
3044 x = LLVMGetParam(function, 1);
3045 y = LLVMGetParam(function, 2);
3046 facing = LLVMGetParam(function, 3);
3047 a0_ptr = LLVMGetParam(function, 4);
3048 dadx_ptr = LLVMGetParam(function, 5);
3049 dady_ptr = LLVMGetParam(function, 6);
3050 color_ptr_ptr = LLVMGetParam(function, 7);
3051 depth_ptr = LLVMGetParam(function, 8);
3052 mask_input = LLVMGetParam(function, 9);
3053 thread_data_ptr = LLVMGetParam(function, 10);
3054 stride_ptr = LLVMGetParam(function, 11);
3055 depth_stride = LLVMGetParam(function, 12);
3056 color_sample_stride_ptr = LLVMGetParam(function, 13);
3057 depth_sample_stride = LLVMGetParam(function, 14);
3058
3059 lp_build_name(context_ptr, "context");
3060 lp_build_name(x, "x");
3061 lp_build_name(y, "y");
3062 lp_build_name(a0_ptr, "a0");
3063 lp_build_name(dadx_ptr, "dadx");
3064 lp_build_name(dady_ptr, "dady");
3065 lp_build_name(color_ptr_ptr, "color_ptr_ptr");
3066 lp_build_name(depth_ptr, "depth");
3067 lp_build_name(mask_input, "mask_input");
3068 lp_build_name(thread_data_ptr, "thread_data");
3069 lp_build_name(stride_ptr, "stride_ptr");
3070 lp_build_name(depth_stride, "depth_stride");
3071 lp_build_name(color_sample_stride_ptr, "color_sample_stride_ptr");
3072 lp_build_name(depth_sample_stride, "depth_sample_stride");
3073
3074 /*
3075 * Function body
3076 */
3077
3078 block = LLVMAppendBasicBlockInContext(gallivm->context, function, "entry");
3079 builder = gallivm->builder;
3080 assert(builder);
3081 LLVMPositionBuilderAtEnd(builder, block);
3082
3083 /*
3084 * Must not count ps invocations if there's a null shader.
3085 * (It would be ok to count with null shader if there's d/s tests,
3086 * but only if there's d/s buffers too, which is different
3087 * to implicit rasterization disable which must not depend
3088 * on the d/s buffers.)
3089 * Could use popcount on mask, but pixel accuracy is not required.
3090 * Could disable if there's no stats query, but maybe not worth it.
3091 */
3092 if (shader->info.base.num_instructions > 1) {
3093 LLVMValueRef invocs, val;
3094 invocs = lp_jit_thread_data_invocations(gallivm, thread_data_ptr);
3095 val = LLVMBuildLoad(builder, invocs, "");
3096 val = LLVMBuildAdd(builder, val,
3097 LLVMConstInt(LLVMInt64TypeInContext(gallivm->context), 1, 0),
3098 "invoc_count");
3099 LLVMBuildStore(builder, val, invocs);
3100 }
3101
3102 /* code generated texture sampling */
3103 sampler = lp_llvm_sampler_soa_create(key->samplers, key->nr_samplers);
3104 image = lp_llvm_image_soa_create(lp_fs_variant_key_images(key), key->nr_images);
3105
3106 num_fs = 16 / fs_type.length; /* number of loops per 4x4 stamp */
3107 /* for 1d resources only run "upper half" of stamp */
3108 if (key->resource_1d)
3109 num_fs /= 2;
3110
3111 {
3112 LLVMValueRef num_loop = lp_build_const_int32(gallivm, num_fs);
3113 LLVMTypeRef mask_type = lp_build_int_vec_type(gallivm, fs_type);
3114 LLVMValueRef num_loop_samp = lp_build_const_int32(gallivm, num_fs * key->coverage_samples);
3115 LLVMValueRef mask_store = lp_build_array_alloca(gallivm, mask_type,
3116 num_loop_samp, "mask_store");
3117
3118 LLVMTypeRef flt_type = LLVMFloatTypeInContext(gallivm->context);
3119 LLVMValueRef glob_sample_pos = LLVMAddGlobal(gallivm->module, LLVMArrayType(flt_type, key->coverage_samples * 2), "");
3120 LLVMValueRef sample_pos_array;
3121
3122 if (key->multisample && key->coverage_samples == 4) {
3123 LLVMValueRef sample_pos_arr[8];
3124 for (unsigned i = 0; i < 4; i++) {
3125 sample_pos_arr[i * 2] = LLVMConstReal(flt_type, lp_sample_pos_4x[i][0]);
3126 sample_pos_arr[i * 2 + 1] = LLVMConstReal(flt_type, lp_sample_pos_4x[i][1]);
3127 }
3128 sample_pos_array = LLVMConstArray(LLVMFloatTypeInContext(gallivm->context), sample_pos_arr, 8);
3129 } else {
3130 LLVMValueRef sample_pos_arr[2];
3131 sample_pos_arr[0] = LLVMConstReal(flt_type, 0.5);
3132 sample_pos_arr[1] = LLVMConstReal(flt_type, 0.5);
3133 sample_pos_array = LLVMConstArray(LLVMFloatTypeInContext(gallivm->context), sample_pos_arr, 2);
3134 }
3135 LLVMSetInitializer(glob_sample_pos, sample_pos_array);
3136
3137 LLVMValueRef color_store[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS];
3138 boolean pixel_center_integer =
3139 shader->info.base.properties[TGSI_PROPERTY_FS_COORD_PIXEL_CENTER];
3140
3141 /*
3142 * The shader input interpolation info is not explicitely baked in the
3143 * shader key, but everything it derives from (TGSI, and flatshade) is
3144 * already included in the shader key.
3145 */
3146 lp_build_interp_soa_init(&interp,
3147 gallivm,
3148 shader->info.base.num_inputs,
3149 inputs,
3150 pixel_center_integer,
3151 key->coverage_samples, glob_sample_pos,
3152 num_loop,
3153 key->depth_clamp,
3154 builder, fs_type,
3155 a0_ptr, dadx_ptr, dady_ptr,
3156 x, y);
3157
3158 for (i = 0; i < num_fs; i++) {
3159 if (key->multisample) {
3160 LLVMValueRef smask_val = LLVMBuildLoad(builder, lp_jit_context_sample_mask(gallivm, context_ptr), "");
3161
3162 /*
3163 * For multisampling, extract the per-sample mask from the incoming 64-bit mask,
3164 * store to the per sample mask storage. Or all of them together to generate
3165 * the fragment shader mask. (sample shading TODO).
3166 * Take the incoming state coverage mask into account.
3167 */
3168 for (unsigned s = 0; s < key->coverage_samples; s++) {
3169 LLVMValueRef sindexi = lp_build_const_int32(gallivm, i + (s * num_fs));
3170 LLVMValueRef sample_mask_ptr = LLVMBuildGEP(builder, mask_store,
3171 &sindexi, 1, "sample_mask_ptr");
3172 LLVMValueRef s_mask = generate_quad_mask(gallivm, fs_type,
3173 i*fs_type.length/4, s, mask_input);
3174
3175 LLVMValueRef smask_bit = LLVMBuildAnd(builder, smask_val, lp_build_const_int32(gallivm, (1 << s)), "");
3176 LLVMValueRef cmp = LLVMBuildICmp(builder, LLVMIntNE, smask_bit, lp_build_const_int32(gallivm, 0), "");
3177 smask_bit = LLVMBuildSExt(builder, cmp, int32_type, "");
3178 smask_bit = lp_build_broadcast(gallivm, mask_type, smask_bit);
3179
3180 s_mask = LLVMBuildAnd(builder, s_mask, smask_bit, "");
3181 LLVMBuildStore(builder, s_mask, sample_mask_ptr);
3182 }
3183 } else {
3184 LLVMValueRef mask;
3185 LLVMValueRef indexi = lp_build_const_int32(gallivm, i);
3186 LLVMValueRef mask_ptr = LLVMBuildGEP(builder, mask_store,
3187 &indexi, 1, "mask_ptr");
3188
3189 if (partial_mask) {
3190 mask = generate_quad_mask(gallivm, fs_type,
3191 i*fs_type.length/4, 0, mask_input);
3192 }
3193 else {
3194 mask = lp_build_const_int_vec(gallivm, fs_type, ~0);
3195 }
3196 LLVMBuildStore(builder, mask, mask_ptr);
3197 }
3198 }
3199
3200 generate_fs_loop(gallivm,
3201 shader, key,
3202 builder,
3203 fs_type,
3204 context_ptr,
3205 glob_sample_pos,
3206 num_loop,
3207 &interp,
3208 sampler,
3209 image,
3210 mask_store, /* output */
3211 color_store,
3212 depth_ptr,
3213 depth_stride,
3214 depth_sample_stride,
3215 color_ptr_ptr,
3216 stride_ptr,
3217 color_sample_stride_ptr,
3218 facing,
3219 thread_data_ptr);
3220
3221 for (i = 0; i < num_fs; i++) {
3222 LLVMValueRef ptr;
3223 for (unsigned s = 0; s < key->coverage_samples; s++) {
3224 int idx = (i + (s * num_fs));
3225 LLVMValueRef sindexi = lp_build_const_int32(gallivm, idx);
3226 ptr = LLVMBuildGEP(builder, mask_store, &sindexi, 1, "");
3227
3228 fs_mask[idx] = LLVMBuildLoad(builder, ptr, "smask");
3229 }
3230
3231 for (unsigned s = 0; s < key->min_samples; s++) {
3232 /* This is fucked up need to reorganize things */
3233 int idx = s * num_fs + i;
3234 LLVMValueRef sindexi = lp_build_const_int32(gallivm, idx);
3235 for (cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
3236 for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
3237 ptr = LLVMBuildGEP(builder,
3238 color_store[cbuf * !cbuf0_write_all][chan],
3239 &sindexi, 1, "");
3240 fs_out_color[s][cbuf][chan][i] = ptr;
3241 }
3242 }
3243 if (dual_source_blend) {
3244 /* only support one dual source blend target hence always use output 1 */
3245 for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
3246 ptr = LLVMBuildGEP(builder,
3247 color_store[1][chan],
3248 &sindexi, 1, "");
3249 fs_out_color[s][1][chan][i] = ptr;
3250 }
3251 }
3252 }
3253 }
3254 }
3255
3256 sampler->destroy(sampler);
3257 image->destroy(image);
3258 /* Loop over color outputs / color buffers to do blending.
3259 */
3260 for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
3261 if (key->cbuf_format[cbuf] != PIPE_FORMAT_NONE) {
3262 LLVMValueRef color_ptr;
3263 LLVMValueRef stride;
3264 LLVMValueRef sample_stride = NULL;
3265 LLVMValueRef index = lp_build_const_int32(gallivm, cbuf);
3266
3267 boolean do_branch = ((key->depth.enabled
3268 || key->stencil[0].enabled
3269 || key->alpha.enabled)
3270 && !shader->info.base.uses_kill);
3271
3272 color_ptr = LLVMBuildLoad(builder,
3273 LLVMBuildGEP(builder, color_ptr_ptr,
3274 &index, 1, ""),
3275 "");
3276
3277 stride = LLVMBuildLoad(builder,
3278 LLVMBuildGEP(builder, stride_ptr, &index, 1, ""),
3279 "");
3280
3281 if (key->multisample)
3282 sample_stride = LLVMBuildLoad(builder,
3283 LLVMBuildGEP(builder, color_sample_stride_ptr,
3284 &index, 1, ""), "");
3285
3286 for (unsigned s = 0; s < key->cbuf_nr_samples[cbuf]; s++) {
3287 unsigned mask_idx = num_fs * (key->multisample ? s : 0);
3288 unsigned out_idx = key->min_samples == 1 ? 0 : s;
3289 LLVMValueRef out_ptr = color_ptr;;
3290
3291 if (key->multisample) {
3292 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_stride, lp_build_const_int32(gallivm, s), "");
3293 out_ptr = LLVMBuildGEP(builder, out_ptr, &sample_offset, 1, "");
3294 }
3295 out_ptr = LLVMBuildBitCast(builder, out_ptr, LLVMPointerType(blend_vec_type, 0), "");
3296
3297 lp_build_name(out_ptr, "color_ptr%d", cbuf);
3298
3299 generate_unswizzled_blend(gallivm, cbuf, variant,
3300 key->cbuf_format[cbuf],
3301 num_fs, fs_type, &fs_mask[mask_idx], fs_out_color[out_idx],
3302 context_ptr, out_ptr, stride,
3303 partial_mask, do_branch);
3304 }
3305 }
3306 }
3307
3308 LLVMBuildRetVoid(builder);
3309
3310 gallivm_verify_function(gallivm, function);
3311 }
3312
3313
3314 static void
3315 dump_fs_variant_key(struct lp_fragment_shader_variant_key *key)
3316 {
3317 unsigned i;
3318
3319 debug_printf("fs variant %p:\n", (void *) key);
3320
3321 if (key->flatshade) {
3322 debug_printf("flatshade = 1\n");
3323 }
3324 if (key->multisample) {
3325 debug_printf("multisample = 1\n");
3326 debug_printf("coverage samples = %d\n", key->coverage_samples);
3327 debug_printf("min samples = %d\n", key->min_samples);
3328 }
3329 for (i = 0; i < key->nr_cbufs; ++i) {
3330 debug_printf("cbuf_format[%u] = %s\n", i, util_format_name(key->cbuf_format[i]));
3331 debug_printf("cbuf nr_samples[%u] = %d\n", i, key->cbuf_nr_samples[i]);
3332 }
3333 if (key->depth.enabled || key->stencil[0].enabled) {
3334 debug_printf("depth.format = %s\n", util_format_name(key->zsbuf_format));
3335 debug_printf("depth nr_samples = %d\n", key->zsbuf_nr_samples);
3336 }
3337 if (key->depth.enabled) {
3338 debug_printf("depth.func = %s\n", util_str_func(key->depth.func, TRUE));
3339 debug_printf("depth.writemask = %u\n", key->depth.writemask);
3340 }
3341
3342 for (i = 0; i < 2; ++i) {
3343 if (key->stencil[i].enabled) {
3344 debug_printf("stencil[%u].func = %s\n", i, util_str_func(key->stencil[i].func, TRUE));
3345 debug_printf("stencil[%u].fail_op = %s\n", i, util_str_stencil_op(key->stencil[i].fail_op, TRUE));
3346 debug_printf("stencil[%u].zpass_op = %s\n", i, util_str_stencil_op(key->stencil[i].zpass_op, TRUE));
3347 debug_printf("stencil[%u].zfail_op = %s\n", i, util_str_stencil_op(key->stencil[i].zfail_op, TRUE));
3348 debug_printf("stencil[%u].valuemask = 0x%x\n", i, key->stencil[i].valuemask);
3349 debug_printf("stencil[%u].writemask = 0x%x\n", i, key->stencil[i].writemask);
3350 }
3351 }
3352
3353 if (key->alpha.enabled) {
3354 debug_printf("alpha.func = %s\n", util_str_func(key->alpha.func, TRUE));
3355 }
3356
3357 if (key->occlusion_count) {
3358 debug_printf("occlusion_count = 1\n");
3359 }
3360
3361 if (key->blend.logicop_enable) {
3362 debug_printf("blend.logicop_func = %s\n", util_str_logicop(key->blend.logicop_func, TRUE));
3363 }
3364 else if (key->blend.rt[0].blend_enable) {
3365 debug_printf("blend.rgb_func = %s\n", util_str_blend_func (key->blend.rt[0].rgb_func, TRUE));
3366 debug_printf("blend.rgb_src_factor = %s\n", util_str_blend_factor(key->blend.rt[0].rgb_src_factor, TRUE));
3367 debug_printf("blend.rgb_dst_factor = %s\n", util_str_blend_factor(key->blend.rt[0].rgb_dst_factor, TRUE));
3368 debug_printf("blend.alpha_func = %s\n", util_str_blend_func (key->blend.rt[0].alpha_func, TRUE));
3369 debug_printf("blend.alpha_src_factor = %s\n", util_str_blend_factor(key->blend.rt[0].alpha_src_factor, TRUE));
3370 debug_printf("blend.alpha_dst_factor = %s\n", util_str_blend_factor(key->blend.rt[0].alpha_dst_factor, TRUE));
3371 }
3372 debug_printf("blend.colormask = 0x%x\n", key->blend.rt[0].colormask);
3373 if (key->blend.alpha_to_coverage) {
3374 debug_printf("blend.alpha_to_coverage is enabled\n");
3375 }
3376 for (i = 0; i < key->nr_samplers; ++i) {
3377 const struct lp_static_sampler_state *sampler = &key->samplers[i].sampler_state;
3378 debug_printf("sampler[%u] = \n", i);
3379 debug_printf(" .wrap = %s %s %s\n",
3380 util_str_tex_wrap(sampler->wrap_s, TRUE),
3381 util_str_tex_wrap(sampler->wrap_t, TRUE),
3382 util_str_tex_wrap(sampler->wrap_r, TRUE));
3383 debug_printf(" .min_img_filter = %s\n",
3384 util_str_tex_filter(sampler->min_img_filter, TRUE));
3385 debug_printf(" .min_mip_filter = %s\n",
3386 util_str_tex_mipfilter(sampler->min_mip_filter, TRUE));
3387 debug_printf(" .mag_img_filter = %s\n",
3388 util_str_tex_filter(sampler->mag_img_filter, TRUE));
3389 if (sampler->compare_mode != PIPE_TEX_COMPARE_NONE)
3390 debug_printf(" .compare_func = %s\n", util_str_func(sampler->compare_func, TRUE));
3391 debug_printf(" .normalized_coords = %u\n", sampler->normalized_coords);
3392 debug_printf(" .min_max_lod_equal = %u\n", sampler->min_max_lod_equal);
3393 debug_printf(" .lod_bias_non_zero = %u\n", sampler->lod_bias_non_zero);
3394 debug_printf(" .apply_min_lod = %u\n", sampler->apply_min_lod);
3395 debug_printf(" .apply_max_lod = %u\n", sampler->apply_max_lod);
3396 }
3397 for (i = 0; i < key->nr_sampler_views; ++i) {
3398 const struct lp_static_texture_state *texture = &key->samplers[i].texture_state;
3399 debug_printf("texture[%u] = \n", i);
3400 debug_printf(" .format = %s\n",
3401 util_format_name(texture->format));
3402 debug_printf(" .target = %s\n",
3403 util_str_tex_target(texture->target, TRUE));
3404 debug_printf(" .level_zero_only = %u\n",
3405 texture->level_zero_only);
3406 debug_printf(" .pot = %u %u %u\n",
3407 texture->pot_width,
3408 texture->pot_height,
3409 texture->pot_depth);
3410 }
3411 struct lp_image_static_state *images = lp_fs_variant_key_images(key);
3412 for (i = 0; i < key->nr_images; ++i) {
3413 const struct lp_static_texture_state *image = &images[i].image_state;
3414 debug_printf("image[%u] = \n", i);
3415 debug_printf(" .format = %s\n",
3416 util_format_name(image->format));
3417 debug_printf(" .target = %s\n",
3418 util_str_tex_target(image->target, TRUE));
3419 debug_printf(" .level_zero_only = %u\n",
3420 image->level_zero_only);
3421 debug_printf(" .pot = %u %u %u\n",
3422 image->pot_width,
3423 image->pot_height,
3424 image->pot_depth);
3425 }
3426 }
3427
3428
3429 void
3430 lp_debug_fs_variant(struct lp_fragment_shader_variant *variant)
3431 {
3432 debug_printf("llvmpipe: Fragment shader #%u variant #%u:\n",
3433 variant->shader->no, variant->no);
3434 if (variant->shader->base.type == PIPE_SHADER_IR_TGSI)
3435 tgsi_dump(variant->shader->base.tokens, 0);
3436 else
3437 nir_print_shader(variant->shader->base.ir.nir, stderr);
3438 dump_fs_variant_key(&variant->key);
3439 debug_printf("variant->opaque = %u\n", variant->opaque);
3440 debug_printf("\n");
3441 }
3442
3443 static void
3444 lp_fs_get_ir_cache_key(struct lp_fragment_shader_variant *variant,
3445 unsigned char ir_sha1_cache_key[20])
3446 {
3447 struct blob blob = { 0 };
3448 unsigned ir_size;
3449 void *ir_binary;
3450
3451 blob_init(&blob);
3452 nir_serialize(&blob, variant->shader->base.ir.nir, true);
3453 ir_binary = blob.data;
3454 ir_size = blob.size;
3455
3456 struct mesa_sha1 ctx;
3457 _mesa_sha1_init(&ctx);
3458 _mesa_sha1_update(&ctx, &variant->key, variant->shader->variant_key_size);
3459 _mesa_sha1_update(&ctx, ir_binary, ir_size);
3460 _mesa_sha1_final(&ctx, ir_sha1_cache_key);
3461
3462 blob_finish(&blob);
3463 }
3464
3465 /**
3466 * Generate a new fragment shader variant from the shader code and
3467 * other state indicated by the key.
3468 */
3469 static struct lp_fragment_shader_variant *
3470 generate_variant(struct llvmpipe_context *lp,
3471 struct lp_fragment_shader *shader,
3472 const struct lp_fragment_shader_variant_key *key)
3473 {
3474 struct llvmpipe_screen *screen = llvmpipe_screen(lp->pipe.screen);
3475 struct lp_fragment_shader_variant *variant;
3476 const struct util_format_description *cbuf0_format_desc = NULL;
3477 boolean fullcolormask;
3478 char module_name[64];
3479 unsigned char ir_sha1_cache_key[20];
3480 struct lp_cached_code cached = { 0 };
3481 bool needs_caching = false;
3482 variant = MALLOC(sizeof *variant + shader->variant_key_size - sizeof variant->key);
3483 if (!variant)
3484 return NULL;
3485
3486 memset(variant, 0, sizeof(*variant));
3487 snprintf(module_name, sizeof(module_name), "fs%u_variant%u",
3488 shader->no, shader->variants_created);
3489
3490 pipe_reference_init(&variant->reference, 1);
3491 lp_fs_reference(lp, &variant->shader, shader);
3492
3493 memcpy(&variant->key, key, shader->variant_key_size);
3494
3495 if (shader->base.ir.nir) {
3496 lp_fs_get_ir_cache_key(variant, ir_sha1_cache_key);
3497
3498 lp_disk_cache_find_shader(screen, &cached, ir_sha1_cache_key);
3499 if (!cached.data_size)
3500 needs_caching = true;
3501 }
3502 variant->gallivm = gallivm_create(module_name, lp->context, &cached);
3503 if (!variant->gallivm) {
3504 FREE(variant);
3505 return NULL;
3506 }
3507
3508 variant->list_item_global.base = variant;
3509 variant->list_item_local.base = variant;
3510 variant->no = shader->variants_created++;
3511
3512
3513
3514 /*
3515 * Determine whether we are touching all channels in the color buffer.
3516 */
3517 fullcolormask = FALSE;
3518 if (key->nr_cbufs == 1) {
3519 cbuf0_format_desc = util_format_description(key->cbuf_format[0]);
3520 fullcolormask = util_format_colormask_full(cbuf0_format_desc, key->blend.rt[0].colormask);
3521 }
3522
3523 variant->opaque =
3524 !key->blend.logicop_enable &&
3525 !key->blend.rt[0].blend_enable &&
3526 fullcolormask &&
3527 !key->stencil[0].enabled &&
3528 !key->alpha.enabled &&
3529 !key->multisample &&
3530 !key->blend.alpha_to_coverage &&
3531 !key->depth.enabled &&
3532 !shader->info.base.uses_kill &&
3533 !shader->info.base.writes_samplemask
3534 ? TRUE : FALSE;
3535
3536 if ((LP_DEBUG & DEBUG_FS) || (gallivm_debug & GALLIVM_DEBUG_IR)) {
3537 lp_debug_fs_variant(variant);
3538 }
3539
3540 lp_jit_init_types(variant);
3541
3542 if (variant->jit_function[RAST_EDGE_TEST] == NULL)
3543 generate_fragment(lp, shader, variant, RAST_EDGE_TEST);
3544
3545 if (variant->jit_function[RAST_WHOLE] == NULL) {
3546 if (variant->opaque) {
3547 /* Specialized shader, which doesn't need to read the color buffer. */
3548 generate_fragment(lp, shader, variant, RAST_WHOLE);
3549 }
3550 }
3551
3552 /*
3553 * Compile everything
3554 */
3555
3556 gallivm_compile_module(variant->gallivm);
3557
3558 variant->nr_instrs += lp_build_count_ir_module(variant->gallivm->module);
3559
3560 if (variant->function[RAST_EDGE_TEST]) {
3561 variant->jit_function[RAST_EDGE_TEST] = (lp_jit_frag_func)
3562 gallivm_jit_function(variant->gallivm,
3563 variant->function[RAST_EDGE_TEST]);
3564 }
3565
3566 if (variant->function[RAST_WHOLE]) {
3567 variant->jit_function[RAST_WHOLE] = (lp_jit_frag_func)
3568 gallivm_jit_function(variant->gallivm,
3569 variant->function[RAST_WHOLE]);
3570 } else if (!variant->jit_function[RAST_WHOLE]) {
3571 variant->jit_function[RAST_WHOLE] = variant->jit_function[RAST_EDGE_TEST];
3572 }
3573
3574 if (needs_caching) {
3575 lp_disk_cache_insert_shader(screen, &cached, ir_sha1_cache_key);
3576 }
3577
3578 gallivm_free_ir(variant->gallivm);
3579
3580 return variant;
3581 }
3582
3583
3584 static void *
3585 llvmpipe_create_fs_state(struct pipe_context *pipe,
3586 const struct pipe_shader_state *templ)
3587 {
3588 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3589 struct lp_fragment_shader *shader;
3590 int nr_samplers;
3591 int nr_sampler_views;
3592 int nr_images;
3593 int i;
3594
3595 shader = CALLOC_STRUCT(lp_fragment_shader);
3596 if (!shader)
3597 return NULL;
3598
3599 pipe_reference_init(&shader->reference, 1);
3600 shader->no = fs_no++;
3601 make_empty_list(&shader->variants);
3602
3603 shader->base.type = templ->type;
3604 if (templ->type == PIPE_SHADER_IR_TGSI) {
3605 /* get/save the summary info for this shader */
3606 lp_build_tgsi_info(templ->tokens, &shader->info);
3607
3608 /* we need to keep a local copy of the tokens */
3609 shader->base.tokens = tgsi_dup_tokens(templ->tokens);
3610 } else {
3611 shader->base.ir.nir = templ->ir.nir;
3612 nir_tgsi_scan_shader(templ->ir.nir, &shader->info.base, true);
3613 }
3614
3615 shader->draw_data = draw_create_fragment_shader(llvmpipe->draw, templ);
3616 if (shader->draw_data == NULL) {
3617 FREE((void *) shader->base.tokens);
3618 FREE(shader);
3619 return NULL;
3620 }
3621
3622 nr_samplers = shader->info.base.file_max[TGSI_FILE_SAMPLER] + 1;
3623 nr_sampler_views = shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] + 1;
3624 nr_images = shader->info.base.file_max[TGSI_FILE_IMAGE] + 1;
3625 shader->variant_key_size = lp_fs_variant_key_size(MAX2(nr_samplers, nr_sampler_views), nr_images);
3626
3627 for (i = 0; i < shader->info.base.num_inputs; i++) {
3628 shader->inputs[i].usage_mask = shader->info.base.input_usage_mask[i];
3629 shader->inputs[i].cyl_wrap = shader->info.base.input_cylindrical_wrap[i];
3630 shader->inputs[i].location = shader->info.base.input_interpolate_loc[i];
3631
3632 switch (shader->info.base.input_interpolate[i]) {
3633 case TGSI_INTERPOLATE_CONSTANT:
3634 shader->inputs[i].interp = LP_INTERP_CONSTANT;
3635 break;
3636 case TGSI_INTERPOLATE_LINEAR:
3637 shader->inputs[i].interp = LP_INTERP_LINEAR;
3638 break;
3639 case TGSI_INTERPOLATE_PERSPECTIVE:
3640 shader->inputs[i].interp = LP_INTERP_PERSPECTIVE;
3641 break;
3642 case TGSI_INTERPOLATE_COLOR:
3643 shader->inputs[i].interp = LP_INTERP_COLOR;
3644 break;
3645 default:
3646 assert(0);
3647 break;
3648 }
3649
3650 switch (shader->info.base.input_semantic_name[i]) {
3651 case TGSI_SEMANTIC_FACE:
3652 shader->inputs[i].interp = LP_INTERP_FACING;
3653 break;
3654 case TGSI_SEMANTIC_POSITION:
3655 /* Position was already emitted above
3656 */
3657 shader->inputs[i].interp = LP_INTERP_POSITION;
3658 shader->inputs[i].src_index = 0;
3659 continue;
3660 }
3661
3662 /* XXX this is a completely pointless index map... */
3663 shader->inputs[i].src_index = i+1;
3664 }
3665
3666 if (LP_DEBUG & DEBUG_TGSI) {
3667 unsigned attrib;
3668 debug_printf("llvmpipe: Create fragment shader #%u %p:\n",
3669 shader->no, (void *) shader);
3670 tgsi_dump(templ->tokens, 0);
3671 debug_printf("usage masks:\n");
3672 for (attrib = 0; attrib < shader->info.base.num_inputs; ++attrib) {
3673 unsigned usage_mask = shader->info.base.input_usage_mask[attrib];
3674 debug_printf(" IN[%u].%s%s%s%s\n",
3675 attrib,
3676 usage_mask & TGSI_WRITEMASK_X ? "x" : "",
3677 usage_mask & TGSI_WRITEMASK_Y ? "y" : "",
3678 usage_mask & TGSI_WRITEMASK_Z ? "z" : "",
3679 usage_mask & TGSI_WRITEMASK_W ? "w" : "");
3680 }
3681 debug_printf("\n");
3682 }
3683
3684 return shader;
3685 }
3686
3687
3688 static void
3689 llvmpipe_bind_fs_state(struct pipe_context *pipe, void *fs)
3690 {
3691 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3692 struct lp_fragment_shader *lp_fs = (struct lp_fragment_shader *)fs;
3693 if (llvmpipe->fs == lp_fs)
3694 return;
3695
3696 draw_bind_fragment_shader(llvmpipe->draw,
3697 (lp_fs ? lp_fs->draw_data : NULL));
3698
3699 lp_fs_reference(llvmpipe, &llvmpipe->fs, lp_fs);
3700
3701 /* invalidate the setup link, NEW_FS will make it update */
3702 lp_setup_set_fs_variant(llvmpipe->setup, NULL);
3703 llvmpipe->dirty |= LP_NEW_FS;
3704 }
3705
3706
3707 /**
3708 * Remove shader variant from two lists: the shader's variant list
3709 * and the context's variant list.
3710 */
3711
3712 static
3713 void llvmpipe_remove_shader_variant(struct llvmpipe_context *lp,
3714 struct lp_fragment_shader_variant *variant)
3715 {
3716 if ((LP_DEBUG & DEBUG_FS) || (gallivm_debug & GALLIVM_DEBUG_IR)) {
3717 debug_printf("llvmpipe: del fs #%u var %u v created %u v cached %u "
3718 "v total cached %u inst %u total inst %u\n",
3719 variant->shader->no, variant->no,
3720 variant->shader->variants_created,
3721 variant->shader->variants_cached,
3722 lp->nr_fs_variants, variant->nr_instrs, lp->nr_fs_instrs);
3723 }
3724
3725 /* remove from shader's list */
3726 remove_from_list(&variant->list_item_local);
3727 variant->shader->variants_cached--;
3728
3729 /* remove from context's list */
3730 remove_from_list(&variant->list_item_global);
3731 lp->nr_fs_variants--;
3732 lp->nr_fs_instrs -= variant->nr_instrs;
3733 }
3734
3735 void
3736 llvmpipe_destroy_shader_variant(struct llvmpipe_context *lp,
3737 struct lp_fragment_shader_variant *variant)
3738 {
3739 gallivm_destroy(variant->gallivm);
3740
3741 lp_fs_reference(lp, &variant->shader, NULL);
3742
3743 FREE(variant);
3744 }
3745
3746 void
3747 llvmpipe_destroy_fs(struct llvmpipe_context *llvmpipe,
3748 struct lp_fragment_shader *shader)
3749 {
3750 /* Delete draw module's data */
3751 draw_delete_fragment_shader(llvmpipe->draw, shader->draw_data);
3752
3753 if (shader->base.ir.nir)
3754 ralloc_free(shader->base.ir.nir);
3755 assert(shader->variants_cached == 0);
3756 FREE((void *) shader->base.tokens);
3757 FREE(shader);
3758 }
3759
3760 static void
3761 llvmpipe_delete_fs_state(struct pipe_context *pipe, void *fs)
3762 {
3763 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3764 struct lp_fragment_shader *shader = fs;
3765 struct lp_fs_variant_list_item *li;
3766
3767 /* Delete all the variants */
3768 li = first_elem(&shader->variants);
3769 while(!at_end(&shader->variants, li)) {
3770 struct lp_fs_variant_list_item *next = next_elem(li);
3771 struct lp_fragment_shader_variant *variant;
3772 variant = li->base;
3773 llvmpipe_remove_shader_variant(llvmpipe, li->base);
3774 lp_fs_variant_reference(llvmpipe, &variant, NULL);
3775 li = next;
3776 }
3777
3778 lp_fs_reference(llvmpipe, &shader, NULL);
3779 }
3780
3781 static void
3782 llvmpipe_set_constant_buffer(struct pipe_context *pipe,
3783 enum pipe_shader_type shader, uint index,
3784 const struct pipe_constant_buffer *cb)
3785 {
3786 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3787 struct pipe_resource *constants = cb ? cb->buffer : NULL;
3788
3789 assert(shader < PIPE_SHADER_TYPES);
3790 assert(index < ARRAY_SIZE(llvmpipe->constants[shader]));
3791
3792 /* note: reference counting */
3793 util_copy_constant_buffer(&llvmpipe->constants[shader][index], cb);
3794
3795 if (constants) {
3796 if (!(constants->bind & PIPE_BIND_CONSTANT_BUFFER)) {
3797 debug_printf("Illegal set constant without bind flag\n");
3798 constants->bind |= PIPE_BIND_CONSTANT_BUFFER;
3799 }
3800 }
3801
3802 if (shader == PIPE_SHADER_VERTEX ||
3803 shader == PIPE_SHADER_GEOMETRY ||
3804 shader == PIPE_SHADER_TESS_CTRL ||
3805 shader == PIPE_SHADER_TESS_EVAL) {
3806 /* Pass the constants to the 'draw' module */
3807 const unsigned size = cb ? cb->buffer_size : 0;
3808 const ubyte *data;
3809
3810 if (constants) {
3811 data = (ubyte *) llvmpipe_resource_data(constants);
3812 }
3813 else if (cb && cb->user_buffer) {
3814 data = (ubyte *) cb->user_buffer;
3815 }
3816 else {
3817 data = NULL;
3818 }
3819
3820 if (data)
3821 data += cb->buffer_offset;
3822
3823 draw_set_mapped_constant_buffer(llvmpipe->draw, shader,
3824 index, data, size);
3825 }
3826 else if (shader == PIPE_SHADER_COMPUTE)
3827 llvmpipe->cs_dirty |= LP_CSNEW_CONSTANTS;
3828 else
3829 llvmpipe->dirty |= LP_NEW_FS_CONSTANTS;
3830
3831 if (cb && cb->user_buffer) {
3832 pipe_resource_reference(&constants, NULL);
3833 }
3834 }
3835
3836 static void
3837 llvmpipe_set_shader_buffers(struct pipe_context *pipe,
3838 enum pipe_shader_type shader, unsigned start_slot,
3839 unsigned count, const struct pipe_shader_buffer *buffers,
3840 unsigned writable_bitmask)
3841 {
3842 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3843 unsigned i, idx;
3844 for (i = start_slot, idx = 0; i < start_slot + count; i++, idx++) {
3845 const struct pipe_shader_buffer *buffer = buffers ? &buffers[idx] : NULL;
3846
3847 util_copy_shader_buffer(&llvmpipe->ssbos[shader][i], buffer);
3848
3849 if (shader == PIPE_SHADER_VERTEX ||
3850 shader == PIPE_SHADER_GEOMETRY ||
3851 shader == PIPE_SHADER_TESS_CTRL ||
3852 shader == PIPE_SHADER_TESS_EVAL) {
3853 const unsigned size = buffer ? buffer->buffer_size : 0;
3854 const ubyte *data = NULL;
3855 if (buffer && buffer->buffer)
3856 data = (ubyte *) llvmpipe_resource_data(buffer->buffer);
3857 if (data)
3858 data += buffer->buffer_offset;
3859 draw_set_mapped_shader_buffer(llvmpipe->draw, shader,
3860 i, data, size);
3861 } else if (shader == PIPE_SHADER_COMPUTE) {
3862 llvmpipe->cs_dirty |= LP_CSNEW_SSBOS;
3863 } else if (shader == PIPE_SHADER_FRAGMENT) {
3864 llvmpipe->dirty |= LP_NEW_FS_SSBOS;
3865 }
3866 }
3867 }
3868
3869 static void
3870 llvmpipe_set_shader_images(struct pipe_context *pipe,
3871 enum pipe_shader_type shader, unsigned start_slot,
3872 unsigned count, const struct pipe_image_view *images)
3873 {
3874 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3875 unsigned i, idx;
3876
3877 draw_flush(llvmpipe->draw);
3878 for (i = start_slot, idx = 0; i < start_slot + count; i++, idx++) {
3879 const struct pipe_image_view *image = images ? &images[idx] : NULL;
3880
3881 util_copy_image_view(&llvmpipe->images[shader][i], image);
3882 }
3883
3884 llvmpipe->num_images[shader] = start_slot + count;
3885 if (shader == PIPE_SHADER_VERTEX ||
3886 shader == PIPE_SHADER_GEOMETRY ||
3887 shader == PIPE_SHADER_TESS_CTRL ||
3888 shader == PIPE_SHADER_TESS_EVAL) {
3889 draw_set_images(llvmpipe->draw,
3890 shader,
3891 llvmpipe->images[shader],
3892 start_slot + count);
3893 } else if (shader == PIPE_SHADER_COMPUTE)
3894 llvmpipe->cs_dirty |= LP_CSNEW_IMAGES;
3895 else
3896 llvmpipe->dirty |= LP_NEW_FS_IMAGES;
3897 }
3898
3899 /**
3900 * Return the blend factor equivalent to a destination alpha of one.
3901 */
3902 static inline unsigned
3903 force_dst_alpha_one(unsigned factor, boolean clamped_zero)
3904 {
3905 switch(factor) {
3906 case PIPE_BLENDFACTOR_DST_ALPHA:
3907 return PIPE_BLENDFACTOR_ONE;
3908 case PIPE_BLENDFACTOR_INV_DST_ALPHA:
3909 return PIPE_BLENDFACTOR_ZERO;
3910 case PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE:
3911 if (clamped_zero)
3912 return PIPE_BLENDFACTOR_ZERO;
3913 else
3914 return PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE;
3915 }
3916
3917 return factor;
3918 }
3919
3920
3921 /**
3922 * We need to generate several variants of the fragment pipeline to match
3923 * all the combinations of the contributing state atoms.
3924 *
3925 * TODO: there is actually no reason to tie this to context state -- the
3926 * generated code could be cached globally in the screen.
3927 */
3928 static struct lp_fragment_shader_variant_key *
3929 make_variant_key(struct llvmpipe_context *lp,
3930 struct lp_fragment_shader *shader,
3931 char *store)
3932 {
3933 unsigned i;
3934 struct lp_fragment_shader_variant_key *key;
3935
3936 key = (struct lp_fragment_shader_variant_key *)store;
3937
3938 memset(key, 0, offsetof(struct lp_fragment_shader_variant_key, samplers[1]));
3939
3940 if (lp->framebuffer.zsbuf) {
3941 enum pipe_format zsbuf_format = lp->framebuffer.zsbuf->format;
3942 const struct util_format_description *zsbuf_desc =
3943 util_format_description(zsbuf_format);
3944
3945 if (lp->depth_stencil->depth.enabled &&
3946 util_format_has_depth(zsbuf_desc)) {
3947 key->zsbuf_format = zsbuf_format;
3948 memcpy(&key->depth, &lp->depth_stencil->depth, sizeof key->depth);
3949 }
3950 if (lp->depth_stencil->stencil[0].enabled &&
3951 util_format_has_stencil(zsbuf_desc)) {
3952 key->zsbuf_format = zsbuf_format;
3953 memcpy(&key->stencil, &lp->depth_stencil->stencil, sizeof key->stencil);
3954 }
3955 if (llvmpipe_resource_is_1d(lp->framebuffer.zsbuf->texture)) {
3956 key->resource_1d = TRUE;
3957 }
3958 key->zsbuf_nr_samples = util_res_sample_count(lp->framebuffer.zsbuf->texture);
3959 }
3960
3961 /*
3962 * Propagate the depth clamp setting from the rasterizer state.
3963 * depth_clip == 0 implies depth clamping is enabled.
3964 *
3965 * When clip_halfz is enabled, then always clamp the depth values.
3966 *
3967 * XXX: This is incorrect for GL, but correct for d3d10 (depth
3968 * clamp is always active in d3d10, regardless if depth clip is
3969 * enabled or not).
3970 * (GL has an always-on [0,1] clamp on fs depth output instead
3971 * to ensure the depth values stay in range. Doesn't look like
3972 * we do that, though...)
3973 */
3974 if (lp->rasterizer->clip_halfz) {
3975 key->depth_clamp = 1;
3976 } else {
3977 key->depth_clamp = (lp->rasterizer->depth_clip_near == 0) ? 1 : 0;
3978 }
3979
3980 /* alpha test only applies if render buffer 0 is non-integer (or does not exist) */
3981 if (!lp->framebuffer.nr_cbufs ||
3982 !lp->framebuffer.cbufs[0] ||
3983 !util_format_is_pure_integer(lp->framebuffer.cbufs[0]->format)) {
3984 key->alpha.enabled = lp->depth_stencil->alpha.enabled;
3985 }
3986 if(key->alpha.enabled)
3987 key->alpha.func = lp->depth_stencil->alpha.func;
3988 /* alpha.ref_value is passed in jit_context */
3989
3990 key->flatshade = lp->rasterizer->flatshade;
3991 key->multisample = lp->rasterizer->multisample;
3992 if (lp->active_occlusion_queries && !lp->queries_disabled) {
3993 key->occlusion_count = TRUE;
3994 }
3995
3996 memcpy(&key->blend, lp->blend, sizeof key->blend);
3997
3998 key->coverage_samples = 1;
3999 key->min_samples = 1;
4000 if (key->multisample) {
4001 key->coverage_samples = util_framebuffer_get_num_samples(&lp->framebuffer);
4002 key->min_samples = lp->min_samples == 1 ? 1 : key->coverage_samples;
4003 }
4004 key->nr_cbufs = lp->framebuffer.nr_cbufs;
4005
4006 if (!key->blend.independent_blend_enable) {
4007 /* we always need independent blend otherwise the fixups below won't work */
4008 for (i = 1; i < key->nr_cbufs; i++) {
4009 memcpy(&key->blend.rt[i], &key->blend.rt[0], sizeof(key->blend.rt[0]));
4010 }
4011 key->blend.independent_blend_enable = 1;
4012 }
4013
4014 for (i = 0; i < lp->framebuffer.nr_cbufs; i++) {
4015 struct pipe_rt_blend_state *blend_rt = &key->blend.rt[i];
4016
4017 if (lp->framebuffer.cbufs[i]) {
4018 enum pipe_format format = lp->framebuffer.cbufs[i]->format;
4019 const struct util_format_description *format_desc;
4020
4021 key->cbuf_format[i] = format;
4022 key->cbuf_nr_samples[i] = util_res_sample_count(lp->framebuffer.cbufs[i]->texture);
4023
4024 /*
4025 * Figure out if this is a 1d resource. Note that OpenGL allows crazy
4026 * mixing of 2d textures with height 1 and 1d textures, so make sure
4027 * we pick 1d if any cbuf or zsbuf is 1d.
4028 */
4029 if (llvmpipe_resource_is_1d(lp->framebuffer.cbufs[i]->texture)) {
4030 key->resource_1d = TRUE;
4031 }
4032
4033 format_desc = util_format_description(format);
4034 assert(format_desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB ||
4035 format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB);
4036
4037 /*
4038 * Mask out color channels not present in the color buffer.
4039 */
4040 blend_rt->colormask &= util_format_colormask(format_desc);
4041
4042 /*
4043 * Disable blend for integer formats.
4044 */
4045 if (util_format_is_pure_integer(format)) {
4046 blend_rt->blend_enable = 0;
4047 }
4048
4049 /*
4050 * Our swizzled render tiles always have an alpha channel, but the
4051 * linear render target format often does not, so force here the dst
4052 * alpha to be one.
4053 *
4054 * This is not a mere optimization. Wrong results will be produced if
4055 * the dst alpha is used, the dst format does not have alpha, and the
4056 * previous rendering was not flushed from the swizzled to linear
4057 * buffer. For example, NonPowTwo DCT.
4058 *
4059 * TODO: This should be generalized to all channels for better
4060 * performance, but only alpha causes correctness issues.
4061 *
4062 * Also, force rgb/alpha func/factors match, to make AoS blending
4063 * easier.
4064 */
4065 if (format_desc->swizzle[3] > PIPE_SWIZZLE_W ||
4066 format_desc->swizzle[3] == format_desc->swizzle[0]) {
4067 /* Doesn't cover mixed snorm/unorm but can't render to them anyway */
4068 boolean clamped_zero = !util_format_is_float(format) &&
4069 !util_format_is_snorm(format);
4070 blend_rt->rgb_src_factor =
4071 force_dst_alpha_one(blend_rt->rgb_src_factor, clamped_zero);
4072 blend_rt->rgb_dst_factor =
4073 force_dst_alpha_one(blend_rt->rgb_dst_factor, clamped_zero);
4074 blend_rt->alpha_func = blend_rt->rgb_func;
4075 blend_rt->alpha_src_factor = blend_rt->rgb_src_factor;
4076 blend_rt->alpha_dst_factor = blend_rt->rgb_dst_factor;
4077 }
4078 }
4079 else {
4080 /* no color buffer for this fragment output */
4081 key->cbuf_format[i] = PIPE_FORMAT_NONE;
4082 key->cbuf_nr_samples[i] = 0;
4083 blend_rt->colormask = 0x0;
4084 blend_rt->blend_enable = 0;
4085 }
4086 }
4087
4088 /* This value will be the same for all the variants of a given shader:
4089 */
4090 key->nr_samplers = shader->info.base.file_max[TGSI_FILE_SAMPLER] + 1;
4091
4092 struct lp_sampler_static_state *fs_sampler;
4093
4094 fs_sampler = key->samplers;
4095
4096 memset(fs_sampler, 0, MAX2(key->nr_samplers, key->nr_sampler_views) * sizeof *fs_sampler);
4097
4098 for(i = 0; i < key->nr_samplers; ++i) {
4099 if(shader->info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
4100 lp_sampler_static_sampler_state(&fs_sampler[i].sampler_state,
4101 lp->samplers[PIPE_SHADER_FRAGMENT][i]);
4102 }
4103 }
4104
4105 /*
4106 * XXX If TGSI_FILE_SAMPLER_VIEW exists assume all texture opcodes
4107 * are dx10-style? Can't really have mixed opcodes, at least not
4108 * if we want to skip the holes here (without rescanning tgsi).
4109 */
4110 if (shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] != -1) {
4111 key->nr_sampler_views = shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] + 1;
4112 for(i = 0; i < key->nr_sampler_views; ++i) {
4113 /*
4114 * Note sview may exceed what's representable by file_mask.
4115 * This will still work, the only downside is that not actually
4116 * used views may be included in the shader key.
4117 */
4118 if(shader->info.base.file_mask[TGSI_FILE_SAMPLER_VIEW] & (1u << (i & 31))) {
4119 lp_sampler_static_texture_state(&fs_sampler[i].texture_state,
4120 lp->sampler_views[PIPE_SHADER_FRAGMENT][i]);
4121 }
4122 }
4123 }
4124 else {
4125 key->nr_sampler_views = key->nr_samplers;
4126 for(i = 0; i < key->nr_sampler_views; ++i) {
4127 if(shader->info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
4128 lp_sampler_static_texture_state(&fs_sampler[i].texture_state,
4129 lp->sampler_views[PIPE_SHADER_FRAGMENT][i]);
4130 }
4131 }
4132 }
4133
4134 struct lp_image_static_state *lp_image;
4135 lp_image = lp_fs_variant_key_images(key);
4136 key->nr_images = shader->info.base.file_max[TGSI_FILE_IMAGE] + 1;
4137 for (i = 0; i < key->nr_images; ++i) {
4138 if (shader->info.base.file_mask[TGSI_FILE_IMAGE] & (1 << i)) {
4139 lp_sampler_static_texture_state_image(&lp_image[i].image_state,
4140 &lp->images[PIPE_SHADER_FRAGMENT][i]);
4141 }
4142 }
4143 return key;
4144 }
4145
4146
4147
4148 /**
4149 * Update fragment shader state. This is called just prior to drawing
4150 * something when some fragment-related state has changed.
4151 */
4152 void
4153 llvmpipe_update_fs(struct llvmpipe_context *lp)
4154 {
4155 struct lp_fragment_shader *shader = lp->fs;
4156 struct lp_fragment_shader_variant_key *key;
4157 struct lp_fragment_shader_variant *variant = NULL;
4158 struct lp_fs_variant_list_item *li;
4159 char store[LP_FS_MAX_VARIANT_KEY_SIZE];
4160
4161 key = make_variant_key(lp, shader, store);
4162
4163 /* Search the variants for one which matches the key */
4164 li = first_elem(&shader->variants);
4165 while(!at_end(&shader->variants, li)) {
4166 if(memcmp(&li->base->key, key, shader->variant_key_size) == 0) {
4167 variant = li->base;
4168 break;
4169 }
4170 li = next_elem(li);
4171 }
4172
4173 if (variant) {
4174 /* Move this variant to the head of the list to implement LRU
4175 * deletion of shader's when we have too many.
4176 */
4177 move_to_head(&lp->fs_variants_list, &variant->list_item_global);
4178 }
4179 else {
4180 /* variant not found, create it now */
4181 int64_t t0, t1, dt;
4182 unsigned i;
4183 unsigned variants_to_cull;
4184
4185 if (LP_DEBUG & DEBUG_FS) {
4186 debug_printf("%u variants,\t%u instrs,\t%u instrs/variant\n",
4187 lp->nr_fs_variants,
4188 lp->nr_fs_instrs,
4189 lp->nr_fs_variants ? lp->nr_fs_instrs / lp->nr_fs_variants : 0);
4190 }
4191
4192 /* First, check if we've exceeded the max number of shader variants.
4193 * If so, free 6.25% of them (the least recently used ones).
4194 */
4195 variants_to_cull = lp->nr_fs_variants >= LP_MAX_SHADER_VARIANTS ? LP_MAX_SHADER_VARIANTS / 16 : 0;
4196
4197 if (variants_to_cull ||
4198 lp->nr_fs_instrs >= LP_MAX_SHADER_INSTRUCTIONS) {
4199 if (gallivm_debug & GALLIVM_DEBUG_PERF) {
4200 debug_printf("Evicting FS: %u fs variants,\t%u total variants,"
4201 "\t%u instrs,\t%u instrs/variant\n",
4202 shader->variants_cached,
4203 lp->nr_fs_variants, lp->nr_fs_instrs,
4204 lp->nr_fs_instrs / lp->nr_fs_variants);
4205 }
4206
4207 /*
4208 * We need to re-check lp->nr_fs_variants because an arbitrarliy large
4209 * number of shader variants (potentially all of them) could be
4210 * pending for destruction on flush.
4211 */
4212
4213 for (i = 0; i < variants_to_cull || lp->nr_fs_instrs >= LP_MAX_SHADER_INSTRUCTIONS; i++) {
4214 struct lp_fs_variant_list_item *item;
4215 if (is_empty_list(&lp->fs_variants_list)) {
4216 break;
4217 }
4218 item = last_elem(&lp->fs_variants_list);
4219 assert(item);
4220 assert(item->base);
4221 llvmpipe_remove_shader_variant(lp, item->base);
4222 lp_fs_variant_reference(lp, &item->base, NULL);
4223 }
4224 }
4225
4226 /*
4227 * Generate the new variant.
4228 */
4229 t0 = os_time_get();
4230 variant = generate_variant(lp, shader, key);
4231 t1 = os_time_get();
4232 dt = t1 - t0;
4233 LP_COUNT_ADD(llvm_compile_time, dt);
4234 LP_COUNT_ADD(nr_llvm_compiles, 2); /* emit vs. omit in/out test */
4235
4236 /* Put the new variant into the list */
4237 if (variant) {
4238 insert_at_head(&shader->variants, &variant->list_item_local);
4239 insert_at_head(&lp->fs_variants_list, &variant->list_item_global);
4240 lp->nr_fs_variants++;
4241 lp->nr_fs_instrs += variant->nr_instrs;
4242 shader->variants_cached++;
4243 }
4244 }
4245
4246 /* Bind this variant */
4247 lp_setup_set_fs_variant(lp->setup, variant);
4248 }
4249
4250
4251
4252
4253
4254 void
4255 llvmpipe_init_fs_funcs(struct llvmpipe_context *llvmpipe)
4256 {
4257 llvmpipe->pipe.create_fs_state = llvmpipe_create_fs_state;
4258 llvmpipe->pipe.bind_fs_state = llvmpipe_bind_fs_state;
4259 llvmpipe->pipe.delete_fs_state = llvmpipe_delete_fs_state;
4260
4261 llvmpipe->pipe.set_constant_buffer = llvmpipe_set_constant_buffer;
4262
4263 llvmpipe->pipe.set_shader_buffers = llvmpipe_set_shader_buffers;
4264 llvmpipe->pipe.set_shader_images = llvmpipe_set_shader_images;
4265 }
4266
4267