OSDN Git Service

gallium/llvm: implement geometry shaders in the llvm paths
[android-x86/external-mesa.git] / src / gallium / drivers / llvmpipe / lp_state_fs.c
1 /**************************************************************************
2  * 
3  * Copyright 2009 VMware, Inc.
4  * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
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 TUNGSTEN GRAPHICS 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/u_format.h"
66 #include "util/u_dump.h"
67 #include "util/u_string.h"
68 #include "util/u_simple_list.h"
69 #include "util/u_dual_blend.h"
70 #include "os/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_swizzle.h"
84 #include "gallivm/lp_bld_flow.h"
85 #include "gallivm/lp_bld_debug.h"
86 #include "gallivm/lp_bld_arit.h"
87 #include "gallivm/lp_bld_pack.h"
88 #include "gallivm/lp_bld_format.h"
89 #include "gallivm/lp_bld_quad.h"
90
91 #include "lp_bld_alpha.h"
92 #include "lp_bld_blend.h"
93 #include "lp_bld_depth.h"
94 #include "lp_bld_interp.h"
95 #include "lp_context.h"
96 #include "lp_debug.h"
97 #include "lp_perf.h"
98 #include "lp_setup.h"
99 #include "lp_state.h"
100 #include "lp_tex_sample.h"
101 #include "lp_flush.h"
102 #include "lp_state_fs.h"
103
104
105 /** Fragment shader number (for debugging) */
106 static unsigned fs_no = 0;
107
108
109 /**
110  * Expand the relevant bits of mask_input to a n*4-dword mask for the
111  * n*four pixels in n 2x2 quads.  This will set the n*four elements of the
112  * quad mask vector to 0 or ~0.
113  * Grouping is 01, 23 for 2 quad mode hence only 0 and 2 are valid
114  * quad arguments with fs length 8.
115  *
116  * \param first_quad  which quad(s) of the quad group to test, in [0,3]
117  * \param mask_input  bitwise mask for the whole 4x4 stamp
118  */
119 static LLVMValueRef
120 generate_quad_mask(struct gallivm_state *gallivm,
121                    struct lp_type fs_type,
122                    unsigned first_quad,
123                    LLVMValueRef mask_input) /* int32 */
124 {
125    LLVMBuilderRef builder = gallivm->builder;
126    struct lp_type mask_type;
127    LLVMTypeRef i32t = LLVMInt32TypeInContext(gallivm->context);
128    LLVMValueRef bits[16];
129    LLVMValueRef mask;
130    int shift, i;
131
132    /*
133     * XXX: We'll need a different path for 16 x u8
134     */
135    assert(fs_type.width == 32);
136    assert(fs_type.length <= Elements(bits));
137    mask_type = lp_int_type(fs_type);
138
139    /*
140     * mask_input >>= (quad * 4)
141     */
142    switch (first_quad) {
143    case 0:
144       shift = 0;
145       break;
146    case 1:
147       assert(fs_type.length == 4);
148       shift = 2;
149       break;
150    case 2:
151       shift = 8;
152       break;
153    case 3:
154       assert(fs_type.length == 4);
155       shift = 10;
156       break;
157    default:
158       assert(0);
159       shift = 0;
160    }
161
162    mask_input = LLVMBuildLShr(builder,
163                               mask_input,
164                               LLVMConstInt(i32t, shift, 0),
165                               "");
166
167    /*
168     * mask = { mask_input & (1 << i), for i in [0,3] }
169     */
170    mask = lp_build_broadcast(gallivm,
171                              lp_build_vec_type(gallivm, mask_type),
172                              mask_input);
173
174    for (i = 0; i < fs_type.length / 4; i++) {
175       unsigned j = 2 * (i % 2) + (i / 2) * 8;
176       bits[4*i + 0] = LLVMConstInt(i32t, 1 << (j + 0), 0);
177       bits[4*i + 1] = LLVMConstInt(i32t, 1 << (j + 1), 0);
178       bits[4*i + 2] = LLVMConstInt(i32t, 1 << (j + 4), 0);
179       bits[4*i + 3] = LLVMConstInt(i32t, 1 << (j + 5), 0);
180    }
181    mask = LLVMBuildAnd(builder, mask, LLVMConstVector(bits, fs_type.length), "");
182
183    /*
184     * mask = mask != 0 ? ~0 : 0
185     */
186    mask = lp_build_compare(gallivm,
187                            mask_type, PIPE_FUNC_NOTEQUAL,
188                            mask,
189                            lp_build_const_int_vec(gallivm, mask_type, 0));
190
191    return mask;
192 }
193
194
195 #define EARLY_DEPTH_TEST  0x1
196 #define LATE_DEPTH_TEST   0x2
197 #define EARLY_DEPTH_WRITE 0x4
198 #define LATE_DEPTH_WRITE  0x8
199
200 static int
201 find_output_by_semantic( const struct tgsi_shader_info *info,
202                          unsigned semantic,
203                          unsigned index )
204 {
205    int i;
206
207    for (i = 0; i < info->num_outputs; i++)
208       if (info->output_semantic_name[i] == semantic &&
209           info->output_semantic_index[i] == index)
210          return i;
211
212    return -1;
213 }
214
215
216 /**
217  * Generate the fragment shader, depth/stencil test, and alpha tests.
218  * \param i  which quad in the tile, in range [0,3]
219  * \param partial_mask  if 1, do mask_input testing
220  */
221 static void
222 generate_fs(struct gallivm_state *gallivm,
223             struct lp_fragment_shader *shader,
224             const struct lp_fragment_shader_variant_key *key,
225             LLVMBuilderRef builder,
226             struct lp_type type,
227             LLVMValueRef context_ptr,
228             unsigned i,
229             struct lp_build_interp_soa_context *interp,
230             struct lp_build_sampler_soa *sampler,
231             LLVMValueRef *pmask,
232             LLVMValueRef (*color)[4],
233             LLVMValueRef depth_ptr,
234             LLVMValueRef facing,
235             unsigned partial_mask,
236             LLVMValueRef mask_input,
237             LLVMValueRef thread_data_ptr)
238 {
239    const struct util_format_description *zs_format_desc = NULL;
240    const struct tgsi_token *tokens = shader->base.tokens;
241    LLVMTypeRef vec_type;
242    LLVMValueRef consts_ptr;
243    LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
244    LLVMValueRef z;
245    LLVMValueRef zs_value = NULL;
246    LLVMValueRef stencil_refs[2];
247    struct lp_build_mask_context mask;
248    boolean simple_shader = (shader->info.base.file_count[TGSI_FILE_SAMPLER] == 0 &&
249                             shader->info.base.num_inputs < 3 &&
250                             shader->info.base.num_instructions < 8);
251    const boolean dual_source_blend = key->blend.rt[0].blend_enable &&
252                                      util_blend_state_is_dual(&key->blend, 0);
253    unsigned attrib;
254    unsigned chan;
255    unsigned cbuf;
256    unsigned depth_mode;
257    struct lp_bld_tgsi_system_values system_values;
258
259    memset(&system_values, 0, sizeof(system_values));
260
261    if (key->depth.enabled ||
262        key->stencil[0].enabled ||
263        key->stencil[1].enabled) {
264
265       zs_format_desc = util_format_description(key->zsbuf_format);
266       assert(zs_format_desc);
267
268       if (!shader->info.base.writes_z) {
269          if (key->alpha.enabled || shader->info.base.uses_kill)
270             /* With alpha test and kill, can do the depth test early
271              * and hopefully eliminate some quads.  But need to do a
272              * special deferred depth write once the final mask value
273              * is known.
274              */
275             depth_mode = EARLY_DEPTH_TEST | LATE_DEPTH_WRITE;
276          else
277             depth_mode = EARLY_DEPTH_TEST | EARLY_DEPTH_WRITE;
278       }
279       else {
280          depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
281       }
282
283       if (!(key->depth.enabled && key->depth.writemask) &&
284           !(key->stencil[0].enabled && key->stencil[0].writemask))
285          depth_mode &= ~(LATE_DEPTH_WRITE | EARLY_DEPTH_WRITE);
286    }
287    else {
288       depth_mode = 0;
289    }
290
291    assert(i < 4);
292
293    stencil_refs[0] = lp_jit_context_stencil_ref_front_value(gallivm, context_ptr);
294    stencil_refs[1] = lp_jit_context_stencil_ref_back_value(gallivm, context_ptr);
295
296    vec_type = lp_build_vec_type(gallivm, type);
297
298    consts_ptr = lp_jit_context_constants(gallivm, context_ptr);
299
300    memset(outputs, 0, sizeof outputs);
301
302    /* Declare the color and z variables */
303    for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
304       for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
305          color[cbuf][chan] = lp_build_alloca(gallivm, vec_type, "color");
306       }
307    }
308    if (dual_source_blend) {
309       assert(key->nr_cbufs <= 1);
310       for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
311          color[1][chan] = lp_build_alloca(gallivm, vec_type, "color1");
312       }
313    }
314
315    /* do triangle edge testing */
316    if (partial_mask) {
317       *pmask = generate_quad_mask(gallivm, type,
318                                   i*type.length/4, mask_input);
319    }
320    else {
321       *pmask = lp_build_const_int_vec(gallivm, type, ~0);
322    }
323
324    /* 'mask' will control execution based on quad's pixel alive/killed state */
325    lp_build_mask_begin(&mask, gallivm, type, *pmask);
326
327    if (!(depth_mode & EARLY_DEPTH_TEST) && !simple_shader)
328       lp_build_mask_check(&mask);
329
330    lp_build_interp_soa_update_pos(interp, gallivm, i*type.length/4);
331    z = interp->pos[2];
332
333    if (depth_mode & EARLY_DEPTH_TEST) {
334       lp_build_depth_stencil_test(gallivm,
335                                   &key->depth,
336                                   key->stencil,
337                                   type,
338                                   zs_format_desc,
339                                   &mask,
340                                   stencil_refs,
341                                   z,
342                                   depth_ptr, facing,
343                                   &zs_value,
344                                   !simple_shader);
345
346       if (depth_mode & EARLY_DEPTH_WRITE) {
347          lp_build_depth_write(gallivm, type, zs_format_desc, depth_ptr, zs_value);
348       }
349    }
350
351    lp_build_interp_soa_update_inputs(interp, gallivm, i*type.length/4);
352
353    /* Build the actual shader */
354    lp_build_tgsi_soa(gallivm, tokens, type, &mask,
355                      consts_ptr, &system_values,
356                      interp->pos, interp->inputs,
357                      outputs, sampler, &shader->info.base, NULL);
358
359    /* Alpha test */
360    if (key->alpha.enabled) {
361       int color0 = find_output_by_semantic(&shader->info.base,
362                                            TGSI_SEMANTIC_COLOR,
363                                            0);
364
365       if (color0 != -1 && outputs[color0][3]) {
366          const struct util_format_description *cbuf_format_desc;
367          LLVMValueRef alpha = LLVMBuildLoad(builder, outputs[color0][3], "alpha");
368          LLVMValueRef alpha_ref_value;
369
370          alpha_ref_value = lp_jit_context_alpha_ref_value(gallivm, context_ptr);
371          alpha_ref_value = lp_build_broadcast(gallivm, vec_type, alpha_ref_value);
372
373          cbuf_format_desc = util_format_description(key->cbuf_format[0]);
374
375          lp_build_alpha_test(gallivm, key->alpha.func, type, cbuf_format_desc,
376                              &mask, alpha, alpha_ref_value,
377                              (depth_mode & LATE_DEPTH_TEST) != 0);
378       }
379    }
380
381    /* Late Z test */
382    if (depth_mode & LATE_DEPTH_TEST) { 
383       int pos0 = find_output_by_semantic(&shader->info.base,
384                                          TGSI_SEMANTIC_POSITION,
385                                          0);
386          
387       if (pos0 != -1 && outputs[pos0][2]) {
388          z = LLVMBuildLoad(builder, outputs[pos0][2], "output.z");
389       }
390
391       lp_build_depth_stencil_test(gallivm,
392                                   &key->depth,
393                                   key->stencil,
394                                   type,
395                                   zs_format_desc,
396                                   &mask,
397                                   stencil_refs,
398                                   z,
399                                   depth_ptr, facing,
400                                   &zs_value,
401                                   !simple_shader);
402       /* Late Z write */
403       if (depth_mode & LATE_DEPTH_WRITE) {
404          lp_build_depth_write(gallivm, type, zs_format_desc, depth_ptr, zs_value);
405       }
406    }
407    else if ((depth_mode & EARLY_DEPTH_TEST) &&
408             (depth_mode & LATE_DEPTH_WRITE))
409    {
410       /* Need to apply a reduced mask to the depth write.  Reload the
411        * depth value, update from zs_value with the new mask value and
412        * write that out.
413        */
414       lp_build_deferred_depth_write(gallivm,
415                                     type,
416                                     zs_format_desc,
417                                     &mask,
418                                     depth_ptr,
419                                     zs_value);
420    }
421
422
423    /* Color write  */
424    for (attrib = 0; attrib < shader->info.base.num_outputs; ++attrib)
425    {
426       unsigned cbuf = shader->info.base.output_semantic_index[attrib];
427       if ((shader->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_COLOR) &&
428            ((cbuf < key->nr_cbufs) || (cbuf == 1 && dual_source_blend)))
429       {
430          unsigned cbuf = shader->info.base.output_semantic_index[attrib];
431          for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
432             if(outputs[attrib][chan]) {
433                /* XXX: just initialize outputs to point at colors[] and
434                 * skip this.
435                 */
436                LLVMValueRef out = LLVMBuildLoad(builder, outputs[attrib][chan], "");
437                lp_build_name(out, "color%u.%u.%c", i, attrib, "rgba"[chan]);
438                LLVMBuildStore(builder, out, color[cbuf][chan]);
439             }
440          }
441       }
442    }
443
444    if (key->occlusion_count) {
445       LLVMValueRef counter = lp_jit_thread_data_counter(gallivm, thread_data_ptr);
446       lp_build_name(counter, "counter");
447       lp_build_occlusion_count(gallivm, type,
448                                lp_build_mask_value(&mask), counter);
449    }
450
451    *pmask = lp_build_mask_end(&mask);
452 }
453
454
455 /**
456  * Generate the fragment shader, depth/stencil test, and alpha tests.
457  */
458 static void
459 generate_fs_loop(struct gallivm_state *gallivm,
460                  struct lp_fragment_shader *shader,
461                  const struct lp_fragment_shader_variant_key *key,
462                  LLVMBuilderRef builder,
463                  struct lp_type type,
464                  LLVMValueRef context_ptr,
465                  LLVMValueRef num_loop,
466                  struct lp_build_interp_soa_context *interp,
467                  struct lp_build_sampler_soa *sampler,
468                  LLVMValueRef mask_store,
469                  LLVMValueRef (*out_color)[4],
470                  LLVMValueRef depth_ptr,
471                  unsigned depth_bits,
472                  LLVMValueRef facing,
473                  LLVMValueRef thread_data_ptr)
474 {
475    const struct util_format_description *zs_format_desc = NULL;
476    const struct tgsi_token *tokens = shader->base.tokens;
477    LLVMTypeRef vec_type;
478    LLVMValueRef mask_ptr, mask_val;
479    LLVMValueRef consts_ptr;
480    LLVMValueRef z;
481    LLVMValueRef zs_value = NULL;
482    LLVMValueRef stencil_refs[2];
483    LLVMValueRef depth_ptr_i;
484    LLVMValueRef depth_offset;
485    LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
486    struct lp_build_for_loop_state loop_state;
487    struct lp_build_mask_context mask;
488    boolean simple_shader = (shader->info.base.file_count[TGSI_FILE_SAMPLER] == 0 &&
489                             shader->info.base.num_inputs < 3 &&
490                             shader->info.base.num_instructions < 8);
491    const boolean dual_source_blend = key->blend.rt[0].blend_enable &&
492                                      util_blend_state_is_dual(&key->blend, 0);
493    unsigned attrib;
494    unsigned chan;
495    unsigned cbuf;
496    unsigned depth_mode;
497
498    struct lp_bld_tgsi_system_values system_values;
499
500    memset(&system_values, 0, sizeof(system_values));
501
502    if (key->depth.enabled ||
503        key->stencil[0].enabled ||
504        key->stencil[1].enabled) {
505
506       zs_format_desc = util_format_description(key->zsbuf_format);
507       assert(zs_format_desc);
508
509       if (!shader->info.base.writes_z) {
510          if (key->alpha.enabled || shader->info.base.uses_kill)
511             /* With alpha test and kill, can do the depth test early
512              * and hopefully eliminate some quads.  But need to do a
513              * special deferred depth write once the final mask value
514              * is known.
515              */
516             depth_mode = EARLY_DEPTH_TEST | LATE_DEPTH_WRITE;
517          else
518             depth_mode = EARLY_DEPTH_TEST | EARLY_DEPTH_WRITE;
519       }
520       else {
521          depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
522       }
523
524       if (!(key->depth.enabled && key->depth.writemask) &&
525           !(key->stencil[0].enabled && key->stencil[0].writemask))
526          depth_mode &= ~(LATE_DEPTH_WRITE | EARLY_DEPTH_WRITE);
527    }
528    else {
529       depth_mode = 0;
530    }
531
532
533    stencil_refs[0] = lp_jit_context_stencil_ref_front_value(gallivm, context_ptr);
534    stencil_refs[1] = lp_jit_context_stencil_ref_back_value(gallivm, context_ptr);
535
536    vec_type = lp_build_vec_type(gallivm, type);
537
538    consts_ptr = lp_jit_context_constants(gallivm, context_ptr);
539
540    lp_build_for_loop_begin(&loop_state, gallivm,
541                            lp_build_const_int32(gallivm, 0),
542                            LLVMIntULT,
543                            num_loop,
544                            lp_build_const_int32(gallivm, 1));
545
546    mask_ptr = LLVMBuildGEP(builder, mask_store,
547                            &loop_state.counter, 1, "mask_ptr");
548    mask_val = LLVMBuildLoad(builder, mask_ptr, "");
549
550    depth_offset = LLVMBuildMul(builder, loop_state.counter,
551                                lp_build_const_int32(gallivm, depth_bits * type.length),
552                                "");
553
554    depth_ptr_i = LLVMBuildGEP(builder, depth_ptr, &depth_offset, 1, "");
555
556    memset(outputs, 0, sizeof outputs);
557
558    for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
559       for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
560          out_color[cbuf][chan] = lp_build_array_alloca(gallivm,
561                                                        lp_build_vec_type(gallivm,
562                                                                          type),
563                                                        num_loop, "color");
564       }
565    }
566    if (dual_source_blend) {
567       assert(key->nr_cbufs <= 1);
568       for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
569          out_color[1][chan] = lp_build_array_alloca(gallivm,
570                                                     lp_build_vec_type(gallivm,
571                                                                       type),
572                                                     num_loop, "color1");
573       }
574    }
575
576
577    /* 'mask' will control execution based on quad's pixel alive/killed state */
578    lp_build_mask_begin(&mask, gallivm, type, mask_val);
579
580    if (!(depth_mode & EARLY_DEPTH_TEST) && !simple_shader)
581       lp_build_mask_check(&mask);
582
583    lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter);
584    z = interp->pos[2];
585
586    if (depth_mode & EARLY_DEPTH_TEST) {
587       lp_build_depth_stencil_test(gallivm,
588                                   &key->depth,
589                                   key->stencil,
590                                   type,
591                                   zs_format_desc,
592                                   &mask,
593                                   stencil_refs,
594                                   z,
595                                   depth_ptr_i, facing,
596                                   &zs_value,
597                                   !simple_shader);
598
599       if (depth_mode & EARLY_DEPTH_WRITE) {
600          lp_build_depth_write(gallivm, type, zs_format_desc, depth_ptr_i, zs_value);
601       }
602    }
603
604    lp_build_interp_soa_update_inputs_dyn(interp, gallivm, loop_state.counter);
605
606    /* Build the actual shader */
607    lp_build_tgsi_soa(gallivm, tokens, type, &mask,
608                      consts_ptr, &system_values,
609                      interp->pos, interp->inputs,
610                      outputs, sampler, &shader->info.base, NULL);
611
612    /* Alpha test */
613    if (key->alpha.enabled) {
614       int color0 = find_output_by_semantic(&shader->info.base,
615                                            TGSI_SEMANTIC_COLOR,
616                                            0);
617
618       if (color0 != -1 && outputs[color0][3]) {
619          const struct util_format_description *cbuf_format_desc;
620          LLVMValueRef alpha = LLVMBuildLoad(builder, outputs[color0][3], "alpha");
621          LLVMValueRef alpha_ref_value;
622
623          alpha_ref_value = lp_jit_context_alpha_ref_value(gallivm, context_ptr);
624          alpha_ref_value = lp_build_broadcast(gallivm, vec_type, alpha_ref_value);
625
626          cbuf_format_desc = util_format_description(key->cbuf_format[0]);
627
628          lp_build_alpha_test(gallivm, key->alpha.func, type, cbuf_format_desc,
629                              &mask, alpha, alpha_ref_value,
630                              (depth_mode & LATE_DEPTH_TEST) != 0);
631       }
632    }
633
634    /* Late Z test */
635    if (depth_mode & LATE_DEPTH_TEST) {
636       int pos0 = find_output_by_semantic(&shader->info.base,
637                                          TGSI_SEMANTIC_POSITION,
638                                          0);
639
640       if (pos0 != -1 && outputs[pos0][2]) {
641          z = LLVMBuildLoad(builder, outputs[pos0][2], "output.z");
642       }
643
644       lp_build_depth_stencil_test(gallivm,
645                                   &key->depth,
646                                   key->stencil,
647                                   type,
648                                   zs_format_desc,
649                                   &mask,
650                                   stencil_refs,
651                                   z,
652                                   depth_ptr_i, facing,
653                                   &zs_value,
654                                   !simple_shader);
655       /* Late Z write */
656       if (depth_mode & LATE_DEPTH_WRITE) {
657          lp_build_depth_write(gallivm, type, zs_format_desc, depth_ptr_i, zs_value);
658       }
659    }
660    else if ((depth_mode & EARLY_DEPTH_TEST) &&
661             (depth_mode & LATE_DEPTH_WRITE))
662    {
663       /* Need to apply a reduced mask to the depth write.  Reload the
664        * depth value, update from zs_value with the new mask value and
665        * write that out.
666        */
667       lp_build_deferred_depth_write(gallivm,
668                                     type,
669                                     zs_format_desc,
670                                     &mask,
671                                     depth_ptr_i,
672                                     zs_value);
673    }
674
675
676    /* Color write  */
677    for (attrib = 0; attrib < shader->info.base.num_outputs; ++attrib)
678    {
679       unsigned cbuf = shader->info.base.output_semantic_index[attrib];
680       if ((shader->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_COLOR) &&
681            ((cbuf < key->nr_cbufs) || (cbuf == 1 && dual_source_blend)))
682       {
683          for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
684             if(outputs[attrib][chan]) {
685                /* XXX: just initialize outputs to point at colors[] and
686                 * skip this.
687                 */
688                LLVMValueRef out = LLVMBuildLoad(builder, outputs[attrib][chan], "");
689                LLVMValueRef color_ptr;
690                color_ptr = LLVMBuildGEP(builder, out_color[cbuf][chan],
691                                         &loop_state.counter, 1, "");
692                lp_build_name(out, "color%u.%c", attrib, "rgba"[chan]);
693                LLVMBuildStore(builder, out, color_ptr);
694             }
695          }
696       }
697    }
698
699    if (key->occlusion_count) {
700       LLVMValueRef counter = lp_jit_thread_data_counter(gallivm, thread_data_ptr);
701       lp_build_name(counter, "counter");
702       lp_build_occlusion_count(gallivm, type,
703                                lp_build_mask_value(&mask), counter);
704    }
705
706    mask_val = lp_build_mask_end(&mask);
707    LLVMBuildStore(builder, mask_val, mask_ptr);
708    lp_build_for_loop_end(&loop_state);
709 }
710
711
712 /**
713  * This function will reorder pixels from the fragment shader SoA to memory layout AoS
714  *
715  * Fragment Shader outputs pixels in small 2x2 blocks
716  *  e.g. (0, 0), (1, 0), (0, 1), (1, 1) ; (2, 0) ...
717  *
718  * However in memory pixels are stored in rows
719  *  e.g. (0, 0), (1, 0), (2, 0), (3, 0) ; (0, 1) ...
720  *
721  * @param type            fragment shader type (4x or 8x float)
722  * @param num_fs          number of fs_src
723  * @param dst_channels    number of output channels
724  * @param fs_src          output from fragment shader
725  * @param dst             pointer to store result
726  * @param pad_inline      is channel padding inline or at end of row
727  * @return                the number of dsts
728  */
729 static int
730 generate_fs_twiddle(struct gallivm_state *gallivm,
731                     struct lp_type type,
732                     unsigned num_fs,
733                     unsigned dst_channels,
734                     LLVMValueRef fs_src[][4],
735                     LLVMValueRef* dst,
736                     bool pad_inline)
737 {
738    LLVMValueRef src[16];
739
740    bool swizzle_pad;
741    bool twiddle;
742    bool split;
743
744    unsigned pixels = num_fs == 4 ? 1 : 2;
745    unsigned reorder_group;
746    unsigned src_channels;
747    unsigned src_count;
748    unsigned i;
749
750    src_channels = dst_channels < 3 ? dst_channels : 4;
751    src_count = num_fs * src_channels;
752
753    assert(pixels == 2 || num_fs == 4);
754    assert(num_fs * src_channels <= Elements(src));
755
756    /*
757     * Transpose from SoA -> AoS
758     */
759    for (i = 0; i < num_fs; ++i) {
760       lp_build_transpose_aos_n(gallivm, type, &fs_src[i][0], src_channels, &src[i * src_channels]);
761    }
762
763    /*
764     * Pick transformation options
765     */
766    swizzle_pad = false;
767    twiddle = false;
768    split = false;
769    reorder_group = 0;
770
771    if (dst_channels == 1) {
772       twiddle = true;
773
774       if (pixels == 2) {
775          split = true;
776       }
777    } else if (dst_channels == 2) {
778       if (pixels == 1) {
779          reorder_group = 1;
780       }
781    } else if (dst_channels > 2) {
782       if (pixels == 1) {
783          reorder_group = 2;
784       } else {
785          twiddle = true;
786       }
787
788       if (!pad_inline && dst_channels == 3 && pixels > 1) {
789          swizzle_pad = true;
790       }
791    }
792
793    /*
794     * Split the src in half
795     */
796    if (split) {
797       for (i = num_fs; i > 0; --i) {
798          src[(i - 1)*2 + 1] = lp_build_extract_range(gallivm, src[i - 1], 4, 4);
799          src[(i - 1)*2 + 0] = lp_build_extract_range(gallivm, src[i - 1], 0, 4);
800       }
801
802       src_count *= 2;
803       type.length = 4;
804    }
805
806    /*
807     * Ensure pixels are in memory order
808     */
809    if (reorder_group) {
810       /* Twiddle pixels by reordering the array, e.g.:
811        *
812        * src_count =  8 -> 0 2 1 3 4 6 5 7
813        * src_count = 16 -> 0 1 4 5 2 3 6 7 8 9 12 13 10 11 14 15
814        */
815       const unsigned reorder_sw[] = { 0, 2, 1, 3 };
816
817       for (i = 0; i < src_count; ++i) {
818          unsigned group = i / reorder_group;
819          unsigned block = (group / 4) * 4 * reorder_group;
820          unsigned j = block + (reorder_sw[group % 4] * reorder_group) + (i % reorder_group);
821          dst[i] = src[j];
822       }
823    } else if (twiddle) {
824       /* Twiddle pixels across elements of array */
825       lp_bld_quad_twiddle(gallivm, type, src, src_count, dst);
826    } else {
827       /* Do nothing */
828       memcpy(dst, src, sizeof(LLVMValueRef) * src_count);
829    }
830
831    /*
832     * Moves any padding between pixels to the end
833     * e.g. RGBXRGBX -> RGBRGBXX
834     */
835    if (swizzle_pad) {
836       unsigned char swizzles[16];
837       unsigned elems = pixels * dst_channels;
838
839       for (i = 0; i < type.length; ++i) {
840          if (i < elems)
841             swizzles[i] = i % dst_channels + (i / dst_channels) * 4;
842          else
843             swizzles[i] = LP_BLD_SWIZZLE_DONTCARE;
844       }
845
846       for (i = 0; i < src_count; ++i) {
847          dst[i] = lp_build_swizzle_aos_n(gallivm, dst[i], swizzles, type.length, type.length);
848       }
849    }
850
851    return src_count;
852 }
853
854
855 /**
856  * Load an unswizzled block of pixels from memory
857  */
858 static void
859 load_unswizzled_block(struct gallivm_state *gallivm,
860                       LLVMValueRef base_ptr,
861                       LLVMValueRef stride,
862                       unsigned block_width,
863                       unsigned block_height,
864                       LLVMValueRef* dst,
865                       struct lp_type dst_type,
866                       unsigned dst_count,
867                       unsigned dst_alignment)
868 {
869    LLVMBuilderRef builder = gallivm->builder;
870    unsigned row_size = dst_count / block_height;
871    unsigned i;
872
873    /* Ensure block exactly fits into dst */
874    assert((block_width * block_height) % dst_count == 0);
875
876    for (i = 0; i < dst_count; ++i) {
877       unsigned x = i % row_size;
878       unsigned y = i / row_size;
879
880       LLVMValueRef bx = lp_build_const_int32(gallivm, x * (dst_type.width / 8) * dst_type.length);
881       LLVMValueRef by = LLVMBuildMul(builder, lp_build_const_int32(gallivm, y), stride, "");
882
883       LLVMValueRef gep[2];
884       LLVMValueRef dst_ptr;
885
886       gep[0] = lp_build_const_int32(gallivm, 0);
887       gep[1] = LLVMBuildAdd(builder, bx, by, "");
888
889       dst_ptr = LLVMBuildGEP(builder, base_ptr, gep, 2, "");
890       dst_ptr = LLVMBuildBitCast(builder, dst_ptr, LLVMPointerType(lp_build_vec_type(gallivm, dst_type), 0), "");
891
892       dst[i] = LLVMBuildLoad(builder, dst_ptr, "");
893
894       lp_set_load_alignment(dst[i], dst_alignment);
895    }
896 }
897
898
899 /**
900  * Store an unswizzled block of pixels to memory
901  */
902 static void
903 store_unswizzled_block(struct gallivm_state *gallivm,
904                        LLVMValueRef base_ptr,
905                        LLVMValueRef stride,
906                        unsigned block_width,
907                        unsigned block_height,
908                        LLVMValueRef* src,
909                        struct lp_type src_type,
910                        unsigned src_count,
911                        unsigned src_alignment)
912 {
913    LLVMBuilderRef builder = gallivm->builder;
914    unsigned row_size = src_count / block_height;
915    unsigned i;
916
917    /* Ensure src exactly fits into block */
918    assert((block_width * block_height) % src_count == 0);
919
920    for (i = 0; i < src_count; ++i) {
921       unsigned x = i % row_size;
922       unsigned y = i / row_size;
923
924       LLVMValueRef bx = lp_build_const_int32(gallivm, x * (src_type.width / 8) * src_type.length);
925       LLVMValueRef by = LLVMBuildMul(builder, lp_build_const_int32(gallivm, y), stride, "");
926
927       LLVMValueRef gep[2];
928       LLVMValueRef src_ptr;
929
930       gep[0] = lp_build_const_int32(gallivm, 0);
931       gep[1] = LLVMBuildAdd(builder, bx, by, "");
932
933       src_ptr = LLVMBuildGEP(builder, base_ptr, gep, 2, "");
934       src_ptr = LLVMBuildBitCast(builder, src_ptr, LLVMPointerType(lp_build_vec_type(gallivm, src_type), 0), "");
935
936       src_ptr = LLVMBuildStore(builder, src[i], src_ptr);
937
938       lp_set_store_alignment(src_ptr, src_alignment);
939    }
940 }
941
942
943 /**
944  * Checks if a format description is an arithmetic format
945  *
946  * A format which has irregular channel sizes such as R3_G3_B2 or R5_G6_B5.
947  */
948 static INLINE boolean
949 is_arithmetic_format(const struct util_format_description *format_desc)
950 {
951    boolean arith = false;
952    unsigned i;
953
954    for (i = 0; i < format_desc->nr_channels; ++i) {
955       arith |= format_desc->channel[i].size != format_desc->channel[0].size;
956       arith |= (format_desc->channel[i].size % 8) != 0;
957    }
958
959    return arith;
960 }
961
962
963 /**
964  * Retrieves the type representing the memory layout for a format
965  *
966  * e.g. RGBA16F = 4x half-float and R3G3B2 = 1x byte
967  */
968 static INLINE void
969 lp_mem_type_from_format_desc(const struct util_format_description *format_desc,
970                              struct lp_type* type)
971 {
972    unsigned i;
973    unsigned chan;
974
975    if (format_desc->format == PIPE_FORMAT_R11G11B10_FLOAT) {
976       /* just make this a 32bit uint */
977       type->floating = false;
978       type->fixed = false;
979       type->sign = false;
980       type->norm = false;
981       type->width = 32;
982       type->length = 1;
983       return;
984    }
985
986    for (i = 0; i < 4; i++)
987       if (format_desc->channel[i].type != UTIL_FORMAT_TYPE_VOID)
988          break;
989    chan = i;
990
991    memset(type, 0, sizeof(struct lp_type));
992    type->floating = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FLOAT;
993    type->fixed    = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FIXED;
994    type->sign     = format_desc->channel[chan].type != UTIL_FORMAT_TYPE_UNSIGNED;
995    type->norm     = format_desc->channel[chan].normalized;
996
997    if (is_arithmetic_format(format_desc)) {
998       type->width = 0;
999       type->length = 1;
1000
1001       for (i = 0; i < format_desc->nr_channels; ++i) {
1002          type->width += format_desc->channel[i].size;
1003       }
1004    } else {
1005       type->width = format_desc->channel[chan].size;
1006       type->length = format_desc->nr_channels;
1007    }
1008 }
1009
1010
1011 /**
1012  * Retrieves the type for a format which is usable in the blending code.
1013  *
1014  * e.g. RGBA16F = 4x float, R3G3B2 = 3x byte
1015  */
1016 static INLINE void
1017 lp_blend_type_from_format_desc(const struct util_format_description *format_desc,
1018                                struct lp_type* type)
1019 {
1020    unsigned i;
1021    unsigned chan;
1022
1023    if (format_desc->format == PIPE_FORMAT_R11G11B10_FLOAT) {
1024       /* always use ordinary floats for blending */
1025       type->floating = true;
1026       type->fixed = false;
1027       type->sign = true;
1028       type->norm = false;
1029       type->width = 32;
1030       type->length = 4;
1031       return;
1032    }
1033
1034    for (i = 0; i < 4; i++)
1035       if (format_desc->channel[i].type != UTIL_FORMAT_TYPE_VOID)
1036          break;
1037    chan = i;
1038
1039    memset(type, 0, sizeof(struct lp_type));
1040    type->floating = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FLOAT;
1041    type->fixed    = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FIXED;
1042    type->sign     = format_desc->channel[chan].type != UTIL_FORMAT_TYPE_UNSIGNED;
1043    type->norm     = format_desc->channel[chan].normalized;
1044    type->width    = format_desc->channel[chan].size;
1045    type->length   = format_desc->nr_channels;
1046
1047    for (i = 1; i < format_desc->nr_channels; ++i) {
1048       if (format_desc->channel[i].size > type->width)
1049          type->width = format_desc->channel[i].size;
1050    }
1051
1052    if (type->floating) {
1053       type->width = 32;
1054    } else {
1055       if (type->width <= 8) {
1056          type->width = 8;
1057       } else if (type->width <= 16) {
1058          type->width = 16;
1059       } else {
1060          type->width = 32;
1061       }
1062    }
1063
1064    if (is_arithmetic_format(format_desc) && type->length == 3) {
1065       type->length = 4;
1066    }
1067 }
1068
1069
1070 /**
1071  * Scale a normalized value from src_bits to dst_bits
1072  */
1073 static INLINE LLVMValueRef
1074 scale_bits(struct gallivm_state *gallivm,
1075            int src_bits,
1076            int dst_bits,
1077            LLVMValueRef src,
1078            struct lp_type src_type)
1079 {
1080    LLVMBuilderRef builder = gallivm->builder;
1081    LLVMValueRef result = src;
1082
1083    if (dst_bits < src_bits) {
1084       /* Scale down by LShr */
1085       result = LLVMBuildLShr(builder,
1086                              src,
1087                              lp_build_const_int_vec(gallivm, src_type, src_bits - dst_bits),
1088                              "");
1089    } else if (dst_bits > src_bits) {
1090       /* Scale up bits */
1091       int db = dst_bits - src_bits;
1092
1093       /* Shift left by difference in bits */
1094       result = LLVMBuildShl(builder,
1095                             src,
1096                             lp_build_const_int_vec(gallivm, src_type, db),
1097                             "");
1098
1099       if (db < src_bits) {
1100          /* Enough bits in src to fill the remainder */
1101          LLVMValueRef lower = LLVMBuildLShr(builder,
1102                                             src,
1103                                             lp_build_const_int_vec(gallivm, src_type, src_bits - db),
1104                                             "");
1105
1106          result = LLVMBuildOr(builder, result, lower, "");
1107       } else if (db > src_bits) {
1108          /* Need to repeatedly copy src bits to fill remainder in dst */
1109          unsigned n;
1110
1111          for (n = src_bits; n < dst_bits; n *= 2) {
1112             LLVMValueRef shuv = lp_build_const_int_vec(gallivm, src_type, n);
1113
1114             result = LLVMBuildOr(builder,
1115                                  result,
1116                                  LLVMBuildLShr(builder, result, shuv, ""),
1117                                  "");
1118          }
1119       }
1120    }
1121
1122    return result;
1123 }
1124
1125
1126 /**
1127  * Convert from memory format to blending format
1128  *
1129  * e.g. GL_R3G3B2 is 1 byte in memory but 3 bytes for blending
1130  */
1131 static void
1132 convert_to_blend_type(struct gallivm_state *gallivm,
1133                       const struct util_format_description *src_fmt,
1134                       struct lp_type src_type,
1135                       struct lp_type dst_type,
1136                       LLVMValueRef* src, // and dst
1137                       unsigned num_srcs)
1138 {
1139    LLVMValueRef *dst = src;
1140    LLVMBuilderRef builder = gallivm->builder;
1141    struct lp_type blend_type;
1142    struct lp_type mem_type;
1143    unsigned i, j, k;
1144    unsigned pixels = 16 / num_srcs;
1145    bool is_arith;
1146
1147    /*
1148     * full custom path for packed floats - none of the later functions would do
1149     * anything useful, and given the lp_type representation they can't be fixed.
1150     */
1151    if (src_fmt->format == PIPE_FORMAT_R11G11B10_FLOAT) {
1152       LLVMValueRef tmpsrc[4];
1153       /*
1154        * This is pretty suboptimal for this case blending in SoA would be much
1155        * better, since conversion gets us SoA values so need to convert back.
1156        */
1157       assert(src_type.width == 32);
1158       assert(dst_type.floating);
1159       assert(dst_type.width == 32);
1160       assert(dst_type.length % 4 == 0);
1161       for (i = 0; i < 4; i++) {
1162          tmpsrc[i] = src[i];
1163       }
1164       for (i = 0; i < num_srcs / 4; i++) {
1165          LLVMValueRef tmpsoa[4];
1166          LLVMValueRef tmps = tmpsrc[i];
1167          if (num_srcs == 8) {
1168             LLVMValueRef shuffles[8];
1169             unsigned j;
1170             /* fetch was 4 values but need 8-wide output values */
1171             tmps = lp_build_concat(gallivm, &tmpsrc[i * 2], src_type, 2);
1172             /*
1173              * for 8-wide aos transpose would give us wrong order not matching
1174              * incoming converted fs values and mask. ARGH.
1175              */
1176             for (j = 0; j < 4; j++) {
1177                shuffles[j] = lp_build_const_int32(gallivm, j * 2);
1178                shuffles[j + 4] = lp_build_const_int32(gallivm, j * 2 + 1);
1179             }
1180             tmps = LLVMBuildShuffleVector(builder, tmps, tmps,
1181                                           LLVMConstVector(shuffles, 8), "");
1182          }
1183          lp_build_r11g11b10_to_float(gallivm, tmps, tmpsoa);
1184          lp_build_transpose_aos(gallivm, dst_type, tmpsoa, &src[i * 4]);
1185       }
1186       return;
1187    }
1188
1189    lp_mem_type_from_format_desc(src_fmt, &mem_type);
1190    lp_blend_type_from_format_desc(src_fmt, &blend_type);
1191
1192    /* Is the format arithmetic */
1193    is_arith = blend_type.length * blend_type.width != mem_type.width * mem_type.length;
1194    is_arith &= !(mem_type.width == 16 && mem_type.floating);
1195
1196    /* Pad if necessary */
1197    if (!is_arith && src_type.length < dst_type.length) {
1198       for (i = 0; i < num_srcs; ++i) {
1199          dst[i] = lp_build_pad_vector(gallivm, src[i], dst_type.length);
1200       }
1201
1202       src_type.length = dst_type.length;
1203    }
1204
1205    /* Special case for half-floats */
1206    if (mem_type.width == 16 && mem_type.floating) {
1207       assert(blend_type.width == 32 && blend_type.floating);
1208       lp_build_conv_auto(gallivm, src_type, &dst_type, dst, num_srcs, dst);
1209       is_arith = false;
1210    }
1211
1212    if (!is_arith) {
1213       return;
1214    }
1215
1216    src_type.width = blend_type.width * blend_type.length;
1217    blend_type.length *= pixels;
1218    src_type.length *= pixels / (src_type.length / mem_type.length);
1219
1220    for (i = 0; i < num_srcs; ++i) {
1221       LLVMValueRef chans[4];
1222       LLVMValueRef res = NULL;
1223       unsigned sa = 0;
1224
1225       dst[i] = LLVMBuildZExt(builder, src[i], lp_build_vec_type(gallivm, src_type), "");
1226
1227       for (j = 0; j < src_fmt->nr_channels; ++j) {
1228          unsigned mask = 0;
1229
1230          for (k = 0; k < src_fmt->channel[j].size; ++k) {
1231             mask |= 1 << k;
1232          }
1233
1234          /* Extract bits from source */
1235          chans[j] = LLVMBuildLShr(builder,
1236                                   dst[i],
1237                                   lp_build_const_int_vec(gallivm, src_type, sa),
1238                                   "");
1239
1240          chans[j] = LLVMBuildAnd(builder,
1241                                  chans[j],
1242                                  lp_build_const_int_vec(gallivm, src_type, mask),
1243                                  "");
1244
1245          /* Scale bits */
1246          if (src_type.norm) {
1247             chans[j] = scale_bits(gallivm, src_fmt->channel[j].size,
1248                                   blend_type.width, chans[j], src_type);
1249          }
1250
1251          /* Insert bits into correct position */
1252          chans[j] = LLVMBuildShl(builder,
1253                                  chans[j],
1254                                  lp_build_const_int_vec(gallivm, src_type, j * blend_type.width),
1255                                  "");
1256
1257          sa += src_fmt->channel[j].size;
1258
1259          if (j == 0) {
1260             res = chans[j];
1261          } else {
1262             res = LLVMBuildOr(builder, res, chans[j], "");
1263          }
1264       }
1265
1266       dst[i] = LLVMBuildBitCast(builder, res, lp_build_vec_type(gallivm, blend_type), "");
1267    }
1268 }
1269
1270
1271 /**
1272  * Convert from blending format to memory format
1273  *
1274  * e.g. GL_R3G3B2 is 3 bytes for blending but 1 byte in memory
1275  */
1276 static void
1277 convert_from_blend_type(struct gallivm_state *gallivm,
1278                         const struct util_format_description *src_fmt,
1279                         struct lp_type src_type,
1280                         struct lp_type dst_type,
1281                         LLVMValueRef* src, // and dst
1282                         unsigned num_srcs)
1283 {
1284    LLVMValueRef* dst = src;
1285    unsigned i, j, k;
1286    struct lp_type mem_type;
1287    struct lp_type blend_type;
1288    LLVMBuilderRef builder = gallivm->builder;
1289    unsigned pixels = 16 / num_srcs;
1290    bool is_arith;
1291
1292    /*
1293     * full custom path for packed floats - none of the later functions would do
1294     * anything useful, and given the lp_type representation they can't be fixed.
1295     */
1296    if (src_fmt->format == PIPE_FORMAT_R11G11B10_FLOAT) {
1297       /*
1298        * This is pretty suboptimal for this case blending in SoA would be much
1299        * better - we need to transpose the AoS values back to SoA values for
1300        * conversion/packing.
1301        */
1302       assert(src_type.floating);
1303       assert(src_type.width == 32);
1304       assert(src_type.length % 4 == 0);
1305       assert(dst_type.width == 32);
1306       for (i = 0; i < num_srcs / 4; i++) {
1307          LLVMValueRef tmpsoa[4], tmpdst;
1308          lp_build_transpose_aos(gallivm, src_type, &src[i * 4], tmpsoa);
1309          tmpdst = lp_build_float_to_r11g11b10(gallivm, tmpsoa);
1310          if (num_srcs == 8) {
1311             LLVMValueRef tmpaos, shuffles[8];
1312             unsigned j;
1313             /*
1314              * for 8-wide aos transpose has given us wrong order not matching
1315              * output order. HMPF. Also need to split the output values manually.
1316              */
1317             for (j = 0; j < 4; j++) {
1318                shuffles[j * 2] = lp_build_const_int32(gallivm, j);
1319                shuffles[j * 2 + 1] = lp_build_const_int32(gallivm, j + 4);
1320             }
1321             tmpaos = LLVMBuildShuffleVector(builder, tmpdst, tmpdst,
1322                                             LLVMConstVector(shuffles, 8), "");
1323             src[i * 2] = lp_build_extract_range(gallivm, tmpaos, 0, 4);
1324             src[i * 2 + 1] = lp_build_extract_range(gallivm, tmpaos, 4, 4);
1325          }
1326          else {
1327             src[i] = tmpdst;
1328          }
1329       }
1330       return;
1331    }
1332
1333    lp_mem_type_from_format_desc(src_fmt, &mem_type);
1334    lp_blend_type_from_format_desc(src_fmt, &blend_type);
1335
1336    is_arith = (blend_type.length * blend_type.width != mem_type.width * mem_type.length);
1337
1338    /* Special case for half-floats */
1339    if (mem_type.width == 16 && mem_type.floating) {
1340       int length = dst_type.length;
1341       assert(blend_type.width == 32 && blend_type.floating);
1342
1343       dst_type.length = src_type.length;
1344
1345       lp_build_conv_auto(gallivm, src_type, &dst_type, dst, num_srcs, dst);
1346
1347       dst_type.length = length;
1348       is_arith = false;
1349    }
1350
1351    /* Remove any padding */
1352    if (!is_arith && (src_type.length % mem_type.length)) {
1353       src_type.length -= (src_type.length % mem_type.length);
1354
1355       for (i = 0; i < num_srcs; ++i) {
1356          dst[i] = lp_build_extract_range(gallivm, dst[i], 0, src_type.length);
1357       }
1358    }
1359
1360    /* No bit arithmetic to do */
1361    if (!is_arith) {
1362       return;
1363    }
1364
1365    src_type.length = pixels;
1366    src_type.width = blend_type.length * blend_type.width;
1367    dst_type.length = pixels;
1368
1369    for (i = 0; i < num_srcs; ++i) {
1370       LLVMValueRef chans[4];
1371       LLVMValueRef res = NULL;
1372       unsigned sa = 0;
1373
1374       dst[i] = LLVMBuildBitCast(builder, src[i], lp_build_vec_type(gallivm, src_type), "");
1375
1376       for (j = 0; j < src_fmt->nr_channels; ++j) {
1377          unsigned mask = 0;
1378
1379          assert(blend_type.width > src_fmt->channel[j].size);
1380
1381          for (k = 0; k < blend_type.width; ++k) {
1382             mask |= 1 << k;
1383          }
1384
1385          /* Extract bits */
1386          chans[j] = LLVMBuildLShr(builder,
1387                                   dst[i],
1388                                   lp_build_const_int_vec(gallivm, src_type, j * blend_type.width),
1389                                   "");
1390
1391          chans[j] = LLVMBuildAnd(builder,
1392                                  chans[j],
1393                                  lp_build_const_int_vec(gallivm, src_type, mask),
1394                                  "");
1395
1396          /* Scale down bits */
1397          if (src_type.norm) {
1398             chans[j] = scale_bits(gallivm, blend_type.width,
1399                                   src_fmt->channel[j].size, chans[j], src_type);
1400          }
1401
1402          /* Insert bits */
1403          chans[j] = LLVMBuildShl(builder,
1404                                  chans[j],
1405                                  lp_build_const_int_vec(gallivm, src_type, sa),
1406                                  "");
1407
1408          sa += src_fmt->channel[j].size;
1409
1410          if (j == 0) {
1411             res = chans[j];
1412          } else {
1413             res = LLVMBuildOr(builder, res, chans[j], "");
1414          }
1415       }
1416
1417       assert (dst_type.width != 24);
1418
1419       dst[i] = LLVMBuildTrunc(builder, res, lp_build_vec_type(gallivm, dst_type), "");
1420    }
1421 }
1422
1423
1424 /**
1425  * Convert alpha to same blend type as src
1426  */
1427 static void
1428 convert_alpha(struct gallivm_state *gallivm,
1429               struct lp_type row_type,
1430               struct lp_type alpha_type,
1431               const unsigned block_size,
1432               const unsigned block_height,
1433               const unsigned src_count,
1434               const unsigned dst_channels,
1435               const bool pad_inline,
1436               LLVMValueRef* src_alpha)
1437 {
1438    LLVMBuilderRef builder = gallivm->builder;
1439    unsigned i, j;
1440    unsigned length = row_type.length;
1441    row_type.length = alpha_type.length;
1442
1443    /* Twiddle the alpha to match pixels */
1444    lp_bld_quad_twiddle(gallivm, alpha_type, src_alpha, 4, src_alpha);
1445
1446    for (i = 0; i < 4; ++i) {
1447       lp_build_conv(gallivm, alpha_type, row_type, &src_alpha[i], 1, &src_alpha[i], 1);
1448    }
1449
1450    alpha_type = row_type;
1451    row_type.length = length;
1452
1453    /* If only one channel we can only need the single alpha value per pixel */
1454    if (src_count == 1) {
1455       assert(dst_channels == 1);
1456
1457       lp_build_concat_n(gallivm, alpha_type, src_alpha, 4, src_alpha, src_count);
1458    } else {
1459       /* If there are more srcs than rows then we need to split alpha up */
1460       if (src_count > block_height) {
1461          for (i = src_count; i > 0; --i) {
1462             unsigned pixels = block_size / src_count;
1463             unsigned idx = i - 1;
1464
1465             src_alpha[idx] = lp_build_extract_range(gallivm, src_alpha[(idx * pixels) / 4], (idx * pixels) % 4, pixels);
1466          }
1467       }
1468
1469       /* If there is a src for each pixel broadcast the alpha across whole row */
1470       if (src_count == block_size) {
1471          for (i = 0; i < src_count; ++i) {
1472             src_alpha[i] = lp_build_broadcast(gallivm, lp_build_vec_type(gallivm, row_type), src_alpha[i]);
1473          }
1474       } else {
1475          unsigned pixels = block_size / src_count;
1476          unsigned channels = pad_inline ? TGSI_NUM_CHANNELS : dst_channels;
1477          unsigned alpha_span = 1;
1478          LLVMValueRef shuffles[LP_MAX_VECTOR_LENGTH];
1479
1480          /* Check if we need 2 src_alphas for our shuffles */
1481          if (pixels > alpha_type.length) {
1482             alpha_span = 2;
1483          }
1484
1485          /* Broadcast alpha across all channels, e.g. a1a2 to a1a1a1a1a2a2a2a2 */
1486          for (j = 0; j < row_type.length; ++j) {
1487             if (j < pixels * channels) {
1488                shuffles[j] = lp_build_const_int32(gallivm, j / channels);
1489             } else {
1490                shuffles[j] = LLVMGetUndef(LLVMInt32TypeInContext(gallivm->context));
1491             }
1492          }
1493
1494          for (i = 0; i < src_count; ++i) {
1495             unsigned idx1 = i, idx2 = i;
1496
1497             if (alpha_span > 1){
1498                idx1 *= alpha_span;
1499                idx2 = idx1 + 1;
1500             }
1501
1502             src_alpha[i] = LLVMBuildShuffleVector(builder,
1503                                                   src_alpha[idx1],
1504                                                   src_alpha[idx2],
1505                                                   LLVMConstVector(shuffles, row_type.length),
1506                                                   "");
1507          }
1508       }
1509    }
1510 }
1511
1512
1513 /**
1514  * Generates the blend function for unswizzled colour buffers
1515  * Also generates the read & write from colour buffer
1516  */
1517 static void
1518 generate_unswizzled_blend(struct gallivm_state *gallivm,
1519                           unsigned rt,
1520                           struct lp_fragment_shader_variant *variant,
1521                           enum pipe_format out_format,
1522                           unsigned int num_fs,
1523                           struct lp_type fs_type,
1524                           LLVMValueRef* fs_mask,
1525                           LLVMValueRef fs_out_color[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS][4],
1526                           LLVMValueRef context_ptr,
1527                           LLVMValueRef color_ptr,
1528                           LLVMValueRef stride,
1529                           unsigned partial_mask,
1530                           boolean do_branch)
1531 {
1532    const unsigned alpha_channel = 3;
1533    const unsigned block_width = 4;
1534    const unsigned block_height = 4;
1535    const unsigned block_size = block_width * block_height;
1536    const unsigned lp_integer_vector_width = 128;
1537
1538    LLVMBuilderRef builder = gallivm->builder;
1539    LLVMValueRef fs_src[4][TGSI_NUM_CHANNELS];
1540    LLVMValueRef fs_src1[4][TGSI_NUM_CHANNELS];
1541    LLVMValueRef src_alpha[4 * 4];
1542    LLVMValueRef src1_alpha[4 * 4];
1543    LLVMValueRef src_mask[4 * 4];
1544    LLVMValueRef src[4 * 4];
1545    LLVMValueRef src1[4 * 4];
1546    LLVMValueRef dst[4 * 4];
1547    LLVMValueRef blend_color;
1548    LLVMValueRef blend_alpha;
1549    LLVMValueRef i32_zero;
1550    LLVMValueRef check_mask;
1551
1552    struct lp_build_mask_context mask_ctx;
1553    struct lp_type mask_type;
1554    struct lp_type blend_type;
1555    struct lp_type row_type;
1556    struct lp_type dst_type;
1557
1558    unsigned char swizzle[TGSI_NUM_CHANNELS];
1559    unsigned vector_width;
1560    unsigned src_channels = TGSI_NUM_CHANNELS;
1561    unsigned dst_channels;
1562    unsigned dst_count;
1563    unsigned src_count;
1564    unsigned i, j;
1565
1566    const struct util_format_description* out_format_desc = util_format_description(out_format);
1567
1568    unsigned dst_alignment;
1569
1570    bool pad_inline = is_arithmetic_format(out_format_desc);
1571    bool has_alpha = false;
1572    const boolean dual_source_blend = variant->key.blend.rt[0].blend_enable &&
1573                                      util_blend_state_is_dual(&variant->key.blend, 0);
1574
1575    mask_type = lp_int32_vec4_type();
1576    mask_type.length = fs_type.length;
1577
1578    /* Compute the alignment of the destination pointer in bytes */
1579 #if 0
1580    dst_alignment = (block_width * out_format_desc->block.bits + 7)/(out_format_desc->block.width * 8);
1581 #else
1582    /* FIXME -- currently we're fetching pixels one by one, instead of row by row */
1583    dst_alignment = (1 * out_format_desc->block.bits + 7)/(out_format_desc->block.width * 8);
1584 #endif
1585    /* Force power-of-two alignment by extracting only the least-significant-bit */
1586    dst_alignment = 1 << (ffs(dst_alignment) - 1);
1587    /* Resource base and stride pointers are aligned to 16 bytes, so that's the maximum alignment we can guarantee */
1588    dst_alignment = MIN2(dst_alignment, 16);
1589
1590    /* Do not bother executing code when mask is empty.. */
1591    if (do_branch) {
1592       check_mask = LLVMConstNull(lp_build_int_vec_type(gallivm, mask_type));
1593
1594       for (i = 0; i < num_fs; ++i) {
1595          check_mask = LLVMBuildOr(builder, check_mask, fs_mask[i], "");
1596       }
1597
1598       lp_build_mask_begin(&mask_ctx, gallivm, mask_type, check_mask);
1599       lp_build_mask_check(&mask_ctx);
1600    }
1601
1602    partial_mask |= !variant->opaque;
1603    i32_zero = lp_build_const_int32(gallivm, 0);
1604
1605    /* Get type from output format */
1606    lp_blend_type_from_format_desc(out_format_desc, &row_type);
1607    lp_mem_type_from_format_desc(out_format_desc, &dst_type);
1608
1609    row_type.length = fs_type.length;
1610    vector_width    = dst_type.floating ? lp_native_vector_width : lp_integer_vector_width;
1611
1612    /* Compute correct swizzle and count channels */
1613    memset(swizzle, LP_BLD_SWIZZLE_DONTCARE, TGSI_NUM_CHANNELS);
1614    dst_channels = 0;
1615
1616    for (i = 0; i < TGSI_NUM_CHANNELS; ++i) {
1617       /* Ensure channel is used */
1618       if (out_format_desc->swizzle[i] >= TGSI_NUM_CHANNELS) {
1619          continue;
1620       }
1621
1622       /* Ensure not already written to (happens in case with GL_ALPHA) */
1623       if (swizzle[out_format_desc->swizzle[i]] < TGSI_NUM_CHANNELS) {
1624          continue;
1625       }
1626
1627       /* Ensure we havn't already found all channels */
1628       if (dst_channels >= out_format_desc->nr_channels) {
1629          continue;
1630       }
1631
1632       swizzle[out_format_desc->swizzle[i]] = i;
1633       ++dst_channels;
1634
1635       if (i == alpha_channel) {
1636          has_alpha = true;
1637       }
1638    }
1639
1640    if (out_format == PIPE_FORMAT_R11G11B10_FLOAT) {
1641       /* the code above can't work for layout_other */
1642       dst_channels = 4; /* HACK: this is fake 4 really but need it due to transpose stuff later */
1643       has_alpha = true;
1644       swizzle[0] = 0;
1645       swizzle[1] = 1;
1646       swizzle[2] = 2;
1647       swizzle[3] = 3;
1648       pad_inline = true; /* HACK: prevent rgbxrgbx->rgbrgbxx conversion later */
1649    }
1650
1651    /* If 3 channels then pad to include alpha for 4 element transpose */
1652    if (dst_channels == 3 && !has_alpha) {
1653       for (i = 0; i < TGSI_NUM_CHANNELS; i++) {
1654          if (swizzle[i] > TGSI_NUM_CHANNELS)
1655             swizzle[i] = 3;
1656       }
1657       if (out_format_desc->nr_channels == 4) {
1658          dst_channels = 4;
1659       }
1660    }
1661
1662    /*
1663     * Load shader output
1664     */
1665    for (i = 0; i < num_fs; ++i) {
1666       /* Always load alpha for use in blending */
1667       LLVMValueRef alpha = LLVMBuildLoad(builder, fs_out_color[rt][alpha_channel][i], "");
1668
1669       /* Load each channel */
1670       for (j = 0; j < dst_channels; ++j) {
1671          assert(swizzle[j] < 4);
1672          fs_src[i][j] = LLVMBuildLoad(builder, fs_out_color[rt][swizzle[j]][i], "");
1673       }
1674
1675       /* If 3 channels then pad to include alpha for 4 element transpose */
1676       /*
1677        * XXX If we include that here maybe could actually use it instead of
1678        * separate alpha for blending?
1679        */
1680       if (dst_channels == 3 && !has_alpha) {
1681          fs_src[i][3] = alpha;
1682       }
1683
1684       /* We split the row_mask and row_alpha as we want 128bit interleave */
1685       if (fs_type.length == 8) {
1686          src_mask[i*2 + 0]  = lp_build_extract_range(gallivm, fs_mask[i], 0, src_channels);
1687          src_mask[i*2 + 1]  = lp_build_extract_range(gallivm, fs_mask[i], src_channels, src_channels);
1688
1689          src_alpha[i*2 + 0] = lp_build_extract_range(gallivm, alpha, 0, src_channels);
1690          src_alpha[i*2 + 1] = lp_build_extract_range(gallivm, alpha, src_channels, src_channels);
1691       } else {
1692          src_mask[i] = fs_mask[i];
1693          src_alpha[i] = alpha;
1694       }
1695    }
1696    if (dual_source_blend) {
1697       /* same as above except different src/dst, skip masks and comments... */
1698       for (i = 0; i < num_fs; ++i) {
1699          LLVMValueRef alpha = LLVMBuildLoad(builder, fs_out_color[1][alpha_channel][i], "");
1700
1701          for (j = 0; j < dst_channels; ++j) {
1702             assert(swizzle[j] < 4);
1703             fs_src1[i][j] = LLVMBuildLoad(builder, fs_out_color[1][swizzle[j]][i], "");
1704          }
1705          if (dst_channels == 3 && !has_alpha) {
1706             fs_src1[i][3] = alpha;
1707          }
1708          if (fs_type.length == 8) {
1709             src1_alpha[i*2 + 0] = lp_build_extract_range(gallivm, alpha, 0, src_channels);
1710             src1_alpha[i*2 + 1] = lp_build_extract_range(gallivm, alpha, src_channels, src_channels);
1711          } else {
1712             src1_alpha[i] = alpha;
1713          }
1714       }
1715    }
1716
1717    if (util_format_is_pure_integer(out_format)) {
1718       /*
1719        * In this case fs_type was really ints or uints disguised as floats,
1720        * fix that up now.
1721        */
1722       fs_type.floating = 0;
1723       fs_type.sign = dst_type.sign;
1724       for (i = 0; i < num_fs; ++i) {
1725          for (j = 0; j < dst_channels; ++j) {
1726             fs_src[i][j] = LLVMBuildBitCast(builder, fs_src[i][j],
1727                                             lp_build_vec_type(gallivm, fs_type), "");
1728          }
1729          if (dst_channels == 3 && !has_alpha) {
1730             fs_src[i][3] = LLVMBuildBitCast(builder, fs_src[i][3],
1731                                             lp_build_vec_type(gallivm, fs_type), "");
1732          }
1733       }
1734    }
1735
1736    /*
1737     * Pixel twiddle from fragment shader order to memory order
1738     */
1739    src_count = generate_fs_twiddle(gallivm, fs_type, num_fs, dst_channels, fs_src, src, pad_inline);
1740    if (dual_source_blend) {
1741       generate_fs_twiddle(gallivm, fs_type, num_fs, dst_channels, fs_src1, src1, pad_inline);
1742    }
1743
1744    src_channels = dst_channels < 3 ? dst_channels : 4;
1745    if (src_count != num_fs * src_channels) {
1746       unsigned ds = src_count / (num_fs * src_channels);
1747       row_type.length /= ds;
1748       fs_type.length = row_type.length;
1749    }
1750
1751    blend_type = row_type;
1752    mask_type.length = 4;
1753
1754    /* Convert src to row_type */
1755    if (dual_source_blend) {
1756       struct lp_type old_row_type = row_type;
1757       lp_build_conv_auto(gallivm, fs_type, &row_type, src, src_count, src);
1758       src_count = lp_build_conv_auto(gallivm, fs_type, &old_row_type, src1, src_count, src1);
1759    }
1760    else {
1761       src_count = lp_build_conv_auto(gallivm, fs_type, &row_type, src, src_count, src);
1762    }
1763
1764    /* If the rows are not an SSE vector, combine them to become SSE size! */
1765    if ((row_type.width * row_type.length) % 128) {
1766       unsigned bits = row_type.width * row_type.length;
1767       unsigned combined;
1768
1769       dst_count = src_count / (vector_width / bits);
1770       combined = lp_build_concat_n(gallivm, row_type, src, src_count, src, dst_count);
1771       if (dual_source_blend) {
1772          lp_build_concat_n(gallivm, row_type, src1, src_count, src1, dst_count);
1773       }
1774
1775       row_type.length *= combined;
1776       src_count /= combined;
1777
1778       bits = row_type.width * row_type.length;
1779       assert(bits == 128 || bits == 256);
1780    }
1781
1782
1783    /*
1784     * Blend Colour conversion
1785     */
1786    blend_color = lp_jit_context_f_blend_color(gallivm, context_ptr);
1787    blend_color = LLVMBuildPointerCast(builder, blend_color, LLVMPointerType(lp_build_vec_type(gallivm, fs_type), 0), "");
1788    blend_color = LLVMBuildLoad(builder, LLVMBuildGEP(builder, blend_color, &i32_zero, 1, ""), "");
1789
1790    /* Convert */
1791    lp_build_conv(gallivm, fs_type, blend_type, &blend_color, 1, &blend_color, 1);
1792
1793    /* Extract alpha */
1794    blend_alpha = lp_build_extract_broadcast(gallivm, blend_type, row_type, blend_color, lp_build_const_int32(gallivm, 3));
1795
1796    /* Swizzle to appropriate channels, e.g. from RGBA to BGRA BGRA */
1797    pad_inline &= (dst_channels * (block_size / src_count) * row_type.width) != vector_width;
1798    if (pad_inline) {
1799       /* Use all 4 channels e.g. from RGBA RGBA to RGxx RGxx */
1800       blend_color = lp_build_swizzle_aos_n(gallivm, blend_color, swizzle, TGSI_NUM_CHANNELS, row_type.length);
1801    } else {
1802       /* Only use dst_channels e.g. RGBA RGBA to RG RG xxxx */
1803       blend_color = lp_build_swizzle_aos_n(gallivm, blend_color, swizzle, dst_channels, row_type.length);
1804    }
1805
1806    /*
1807     * Mask conversion
1808     */
1809    lp_bld_quad_twiddle(gallivm, mask_type, &src_mask[0], 4, &src_mask[0]);
1810
1811    if (src_count < block_height) {
1812       lp_build_concat_n(gallivm, mask_type, src_mask, 4, src_mask, src_count);
1813    } else if (src_count > block_height) {
1814       for (i = src_count; i > 0; --i) {
1815          unsigned pixels = block_size / src_count;
1816          unsigned idx = i - 1;
1817
1818          src_mask[idx] = lp_build_extract_range(gallivm, src_mask[(idx * pixels) / 4], (idx * pixels) % 4, pixels);
1819       }
1820    }
1821
1822    assert(mask_type.width == 32);
1823
1824    for (i = 0; i < src_count; ++i) {
1825       unsigned pixels = block_size / src_count;
1826       unsigned pixel_width = row_type.width * dst_channels;
1827
1828       if (pixel_width == 24) {
1829          mask_type.width = 8;
1830          mask_type.length = vector_width / mask_type.width;
1831       } else {
1832          mask_type.length = pixels;
1833          mask_type.width = row_type.width * dst_channels;
1834
1835          src_mask[i] = LLVMBuildIntCast(builder, src_mask[i], lp_build_int_vec_type(gallivm, mask_type), "");
1836
1837          mask_type.length *= dst_channels;
1838          mask_type.width /= dst_channels;
1839       }
1840
1841       src_mask[i] = LLVMBuildBitCast(builder, src_mask[i], lp_build_int_vec_type(gallivm, mask_type), "");
1842       src_mask[i] = lp_build_pad_vector(gallivm, src_mask[i], row_type.length);
1843    }
1844
1845    /*
1846     * Alpha conversion
1847     */
1848    if (!has_alpha) {
1849       struct lp_type alpha_type = fs_type;
1850       alpha_type.length = 4;
1851       convert_alpha(gallivm, row_type, alpha_type,
1852                     block_size, block_height,
1853                     src_count, dst_channels,
1854                     pad_inline, src_alpha);
1855       if (dual_source_blend) {
1856          convert_alpha(gallivm, row_type, alpha_type,
1857                        block_size, block_height,
1858                        src_count, dst_channels,
1859                        pad_inline, src1_alpha);
1860       }
1861    }
1862
1863
1864    /*
1865     * Load dst from memory
1866     */
1867    if (src_count < block_height) {
1868       dst_count = block_height;
1869    } else {
1870       dst_count = src_count;
1871    }
1872
1873    dst_type.length *= 16 / dst_count;
1874
1875    if (out_format == PIPE_FORMAT_R11G11B10_FLOAT) {
1876       /*
1877        * we need multiple values at once for the conversion, so can as well
1878        * load them vectorized here too instead of concatenating later.
1879        * (Still need concatenation later for 8-wide vectors).
1880        */
1881       dst_count = block_height;
1882       dst_type.length = block_width;
1883    }
1884
1885    load_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height,
1886                          dst, dst_type, dst_count, dst_alignment);
1887
1888
1889    /*
1890     * Convert from dst/output format to src/blending format.
1891     *
1892     * This is necessary as we can only read 1 row from memory at a time,
1893     * so the minimum dst_count will ever be at this point is 4.
1894     *
1895     * With, for example, R8 format you can have all 16 pixels in a 128 bit vector,
1896     * this will take the 4 dsts and combine them into 1 src so we can perform blending
1897     * on all 16 pixels in that single vector at once.
1898     */
1899    if (dst_count > src_count) {
1900       lp_build_concat_n(gallivm, dst_type, dst, 4, dst, src_count);
1901    }
1902
1903    /*
1904     * Blending
1905     */
1906    /* XXX this is broken for RGB8 formats -
1907     * they get expanded from 12 to 16 elements (to include alpha)
1908     * by convert_to_blend_type then reduced to 15 instead of 12
1909     * by convert_from_blend_type (a simple fix though breaks A8...).
1910     * R16G16B16 also crashes differently however something going wrong
1911     * inside llvm handling npot vector sizes seemingly.
1912     * It seems some cleanup could be done here (like skipping conversion/blend
1913     * when not needed).
1914     */
1915    convert_to_blend_type(gallivm, out_format_desc, dst_type, row_type, dst, src_count);
1916
1917    for (i = 0; i < src_count; ++i) {
1918       dst[i] = lp_build_blend_aos(gallivm,
1919                                   &variant->key.blend,
1920                                   out_format,
1921                                   row_type,
1922                                   rt,
1923                                   src[i],
1924                                   has_alpha ? NULL : src_alpha[i],
1925                                   src1[i],
1926                                   has_alpha ? NULL : src1_alpha[i],
1927                                   dst[i],
1928                                   partial_mask ? src_mask[i] : NULL,
1929                                   blend_color,
1930                                   has_alpha ? NULL : blend_alpha,
1931                                   swizzle,
1932                                   pad_inline ? 4 : dst_channels);
1933    }
1934
1935    convert_from_blend_type(gallivm, out_format_desc, row_type, dst_type, dst, src_count);
1936
1937    /* Split the blend rows back to memory rows */
1938    if (dst_count > src_count) {
1939       row_type.length = dst_type.length * (dst_count / src_count);
1940
1941       if (src_count == 1) {
1942          dst[1] = lp_build_extract_range(gallivm, dst[0], row_type.length / 2, row_type.length / 2);
1943          dst[0] = lp_build_extract_range(gallivm, dst[0], 0, row_type.length / 2);
1944
1945          row_type.length /= 2;
1946          src_count *= 2;
1947       }
1948
1949       dst[3] = lp_build_extract_range(gallivm, dst[1], row_type.length / 2, row_type.length / 2);
1950       dst[2] = lp_build_extract_range(gallivm, dst[1], 0, row_type.length / 2);
1951       dst[1] = lp_build_extract_range(gallivm, dst[0], row_type.length / 2, row_type.length / 2);
1952       dst[0] = lp_build_extract_range(gallivm, dst[0], 0, row_type.length / 2);
1953
1954       row_type.length /= 2;
1955       src_count *= 2;
1956    }
1957
1958
1959    /*
1960     * Store blend result to memory
1961     */
1962    store_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height,
1963                           dst, dst_type, dst_count, dst_alignment);
1964
1965    if (do_branch) {
1966       lp_build_mask_end(&mask_ctx);
1967    }
1968 }
1969
1970
1971 /**
1972  * Generate the runtime callable function for the whole fragment pipeline.
1973  * Note that the function which we generate operates on a block of 16
1974  * pixels at at time.  The block contains 2x2 quads.  Each quad contains
1975  * 2x2 pixels.
1976  */
1977 static void
1978 generate_fragment(struct llvmpipe_context *lp,
1979                   struct lp_fragment_shader *shader,
1980                   struct lp_fragment_shader_variant *variant,
1981                   unsigned partial_mask)
1982 {
1983    struct gallivm_state *gallivm = variant->gallivm;
1984    const struct lp_fragment_shader_variant_key *key = &variant->key;
1985    struct lp_shader_input inputs[PIPE_MAX_SHADER_INPUTS];
1986    char func_name[256];
1987    struct lp_type fs_type;
1988    struct lp_type blend_type;
1989    LLVMTypeRef fs_elem_type;
1990    LLVMTypeRef blend_vec_type;
1991    LLVMTypeRef arg_types[12];
1992    LLVMTypeRef func_type;
1993    LLVMTypeRef int32_type = LLVMInt32TypeInContext(gallivm->context);
1994    LLVMTypeRef int8_type = LLVMInt8TypeInContext(gallivm->context);
1995    LLVMValueRef context_ptr;
1996    LLVMValueRef x;
1997    LLVMValueRef y;
1998    LLVMValueRef a0_ptr;
1999    LLVMValueRef dadx_ptr;
2000    LLVMValueRef dady_ptr;
2001    LLVMValueRef color_ptr_ptr;
2002    LLVMValueRef stride_ptr;
2003    LLVMValueRef depth_ptr;
2004    LLVMValueRef mask_input;
2005    LLVMValueRef thread_data_ptr;
2006    LLVMBasicBlockRef block;
2007    LLVMBuilderRef builder;
2008    struct lp_build_sampler_soa *sampler;
2009    struct lp_build_interp_soa_context interp;
2010    LLVMValueRef fs_mask[16 / 4];
2011    LLVMValueRef fs_out_color[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS][16 / 4];
2012    LLVMValueRef function;
2013    LLVMValueRef facing;
2014    const struct util_format_description *zs_format_desc;
2015    unsigned num_fs;
2016    unsigned i;
2017    unsigned chan;
2018    unsigned cbuf;
2019    boolean cbuf0_write_all;
2020    boolean try_loop = TRUE;
2021    const boolean dual_source_blend = key->blend.rt[0].blend_enable &&
2022                                      util_blend_state_is_dual(&key->blend, 0);
2023
2024    assert(lp_native_vector_width / 32 >= 4);
2025
2026    /* Adjust color input interpolation according to flatshade state:
2027     */
2028    memcpy(inputs, shader->inputs, shader->info.base.num_inputs * sizeof inputs[0]);
2029    for (i = 0; i < shader->info.base.num_inputs; i++) {
2030       if (inputs[i].interp == LP_INTERP_COLOR) {
2031          if (key->flatshade)
2032             inputs[i].interp = LP_INTERP_CONSTANT;
2033          else
2034             inputs[i].interp = LP_INTERP_PERSPECTIVE;
2035       }
2036    }
2037
2038    /* check if writes to cbuf[0] are to be copied to all cbufs */
2039    cbuf0_write_all = FALSE;
2040    for (i = 0;i < shader->info.base.num_properties; i++) {
2041       if (shader->info.base.properties[i].name ==
2042           TGSI_PROPERTY_FS_COLOR0_WRITES_ALL_CBUFS) {
2043          cbuf0_write_all = TRUE;
2044          break;
2045       }
2046    }
2047
2048    /* TODO: actually pick these based on the fs and color buffer
2049     * characteristics. */
2050
2051    memset(&fs_type, 0, sizeof fs_type);
2052    fs_type.floating = TRUE;      /* floating point values */
2053    fs_type.sign = TRUE;          /* values are signed */
2054    fs_type.norm = FALSE;         /* values are not limited to [0,1] or [-1,1] */
2055    fs_type.width = 32;           /* 32-bit float */
2056    fs_type.length = MIN2(lp_native_vector_width / 32, 16); /* n*4 elements per vector */
2057    num_fs = 16 / fs_type.length; /* number of loops per 4x4 stamp */
2058
2059    memset(&blend_type, 0, sizeof blend_type);
2060    blend_type.floating = FALSE; /* values are integers */
2061    blend_type.sign = FALSE;     /* values are unsigned */
2062    blend_type.norm = TRUE;      /* values are in [0,1] or [-1,1] */
2063    blend_type.width = 8;        /* 8-bit ubyte values */
2064    blend_type.length = 16;      /* 16 elements per vector */
2065
2066    /* 
2067     * Generate the function prototype. Any change here must be reflected in
2068     * lp_jit.h's lp_jit_frag_func function pointer type, and vice-versa.
2069     */
2070
2071    fs_elem_type = lp_build_elem_type(gallivm, fs_type);
2072
2073    blend_vec_type = lp_build_vec_type(gallivm, blend_type);
2074
2075    util_snprintf(func_name, sizeof(func_name), "fs%u_variant%u_%s", 
2076                  shader->no, variant->no, partial_mask ? "partial" : "whole");
2077
2078    arg_types[0] = variant->jit_context_ptr_type;       /* context */
2079    arg_types[1] = int32_type;                          /* x */
2080    arg_types[2] = int32_type;                          /* y */
2081    arg_types[3] = int32_type;                          /* facing */
2082    arg_types[4] = LLVMPointerType(fs_elem_type, 0);    /* a0 */
2083    arg_types[5] = LLVMPointerType(fs_elem_type, 0);    /* dadx */
2084    arg_types[6] = LLVMPointerType(fs_elem_type, 0);    /* dady */
2085    arg_types[7] = LLVMPointerType(LLVMPointerType(blend_vec_type, 0), 0);  /* color */
2086    arg_types[8] = LLVMPointerType(int8_type, 0);       /* depth */
2087    arg_types[9] = int32_type;                          /* mask_input */
2088    arg_types[10] = variant->jit_thread_data_ptr_type;  /* per thread data */
2089    arg_types[11] = LLVMPointerType(int32_type, 0);     /* stride */
2090
2091    func_type = LLVMFunctionType(LLVMVoidTypeInContext(gallivm->context),
2092                                 arg_types, Elements(arg_types), 0);
2093
2094    function = LLVMAddFunction(gallivm->module, func_name, func_type);
2095    LLVMSetFunctionCallConv(function, LLVMCCallConv);
2096
2097    variant->function[partial_mask] = function;
2098
2099    /* XXX: need to propagate noalias down into color param now we are
2100     * passing a pointer-to-pointer?
2101     */
2102    for(i = 0; i < Elements(arg_types); ++i)
2103       if(LLVMGetTypeKind(arg_types[i]) == LLVMPointerTypeKind)
2104          LLVMAddAttribute(LLVMGetParam(function, i), LLVMNoAliasAttribute);
2105
2106    context_ptr  = LLVMGetParam(function, 0);
2107    x            = LLVMGetParam(function, 1);
2108    y            = LLVMGetParam(function, 2);
2109    facing       = LLVMGetParam(function, 3);
2110    a0_ptr       = LLVMGetParam(function, 4);
2111    dadx_ptr     = LLVMGetParam(function, 5);
2112    dady_ptr     = LLVMGetParam(function, 6);
2113    color_ptr_ptr = LLVMGetParam(function, 7);
2114    depth_ptr    = LLVMGetParam(function, 8);
2115    mask_input   = LLVMGetParam(function, 9);
2116    thread_data_ptr  = LLVMGetParam(function, 10);
2117    stride_ptr   = LLVMGetParam(function, 11);
2118
2119    lp_build_name(context_ptr, "context");
2120    lp_build_name(x, "x");
2121    lp_build_name(y, "y");
2122    lp_build_name(a0_ptr, "a0");
2123    lp_build_name(dadx_ptr, "dadx");
2124    lp_build_name(dady_ptr, "dady");
2125    lp_build_name(color_ptr_ptr, "color_ptr_ptr");
2126    lp_build_name(depth_ptr, "depth");
2127    lp_build_name(thread_data_ptr, "thread_data");
2128    lp_build_name(mask_input, "mask_input");
2129    lp_build_name(stride_ptr, "stride_ptr");
2130
2131    /*
2132     * Function body
2133     */
2134
2135    block = LLVMAppendBasicBlockInContext(gallivm->context, function, "entry");
2136    builder = gallivm->builder;
2137    assert(builder);
2138    LLVMPositionBuilderAtEnd(builder, block);
2139
2140    /* code generated texture sampling */
2141    sampler = lp_llvm_sampler_soa_create(key->state, context_ptr);
2142
2143    zs_format_desc = util_format_description(key->zsbuf_format);
2144
2145    if (!try_loop) {
2146       /*
2147        * The shader input interpolation info is not explicitely baked in the
2148        * shader key, but everything it derives from (TGSI, and flatshade) is
2149        * already included in the shader key.
2150        */
2151       lp_build_interp_soa_init(&interp,
2152                                gallivm,
2153                                shader->info.base.num_inputs,
2154                                inputs,
2155                                builder, fs_type,
2156                                FALSE,
2157                                a0_ptr, dadx_ptr, dady_ptr,
2158                                x, y);
2159
2160       /* loop over quads in the block */
2161       for(i = 0; i < num_fs; ++i) {
2162          LLVMValueRef depth_offset = LLVMConstInt(int32_type,
2163                                                   i*fs_type.length*zs_format_desc->block.bits/8,
2164                                                   0);
2165          LLVMValueRef out_color[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS];
2166          LLVMValueRef depth_ptr_i;
2167
2168          depth_ptr_i = LLVMBuildGEP(builder, depth_ptr, &depth_offset, 1, "");
2169
2170          generate_fs(gallivm,
2171                      shader, key,
2172                      builder,
2173                      fs_type,
2174                      context_ptr,
2175                      i,
2176                      &interp,
2177                      sampler,
2178                      &fs_mask[i], /* output */
2179                      out_color,
2180                      depth_ptr_i,
2181                      facing,
2182                      partial_mask,
2183                      mask_input,
2184                      thread_data_ptr);
2185
2186          for (cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
2187             for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan)
2188                fs_out_color[cbuf][chan][i] =
2189                   out_color[cbuf * !cbuf0_write_all][chan];
2190          }
2191          if (dual_source_blend) {
2192             /* only support one dual source blend target hence always use output 1 */
2193             for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan)
2194                fs_out_color[1][chan][i] =
2195                   out_color[1][chan];
2196          }
2197       }
2198    }
2199    else {
2200       unsigned depth_bits = zs_format_desc->block.bits/8;
2201       LLVMValueRef num_loop = lp_build_const_int32(gallivm, num_fs);
2202       LLVMTypeRef mask_type = lp_build_int_vec_type(gallivm, fs_type);
2203       LLVMValueRef mask_store = lp_build_array_alloca(gallivm, mask_type,
2204                                                       num_loop, "mask_store");
2205       LLVMValueRef color_store[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS];
2206
2207       /*
2208        * The shader input interpolation info is not explicitely baked in the
2209        * shader key, but everything it derives from (TGSI, and flatshade) is
2210        * already included in the shader key.
2211        */
2212       lp_build_interp_soa_init(&interp,
2213                                gallivm,
2214                                shader->info.base.num_inputs,
2215                                inputs,
2216                                builder, fs_type,
2217                                TRUE,
2218                                a0_ptr, dadx_ptr, dady_ptr,
2219                                x, y);
2220
2221       for (i = 0; i < num_fs; i++) {
2222          LLVMValueRef mask;
2223          LLVMValueRef indexi = lp_build_const_int32(gallivm, i);
2224          LLVMValueRef mask_ptr = LLVMBuildGEP(builder, mask_store,
2225                                               &indexi, 1, "mask_ptr");
2226
2227          if (partial_mask) {
2228             mask = generate_quad_mask(gallivm, fs_type,
2229                                       i*fs_type.length/4, mask_input);
2230          }
2231          else {
2232             mask = lp_build_const_int_vec(gallivm, fs_type, ~0);
2233          }
2234          LLVMBuildStore(builder, mask, mask_ptr);
2235       }
2236
2237       generate_fs_loop(gallivm,
2238                        shader, key,
2239                        builder,
2240                        fs_type,
2241                        context_ptr,
2242                        num_loop,
2243                        &interp,
2244                        sampler,
2245                        mask_store, /* output */
2246                        color_store,
2247                        depth_ptr,
2248                        depth_bits,
2249                        facing,
2250                        thread_data_ptr);
2251
2252       for (i = 0; i < num_fs; i++) {
2253          LLVMValueRef indexi = lp_build_const_int32(gallivm, i);
2254          LLVMValueRef ptr = LLVMBuildGEP(builder, mask_store,
2255                                          &indexi, 1, "");
2256          fs_mask[i] = LLVMBuildLoad(builder, ptr, "mask");
2257          /* This is fucked up need to reorganize things */
2258          for (cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
2259             for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
2260                ptr = LLVMBuildGEP(builder,
2261                                   color_store[cbuf * !cbuf0_write_all][chan],
2262                                   &indexi, 1, "");
2263                fs_out_color[cbuf][chan][i] = ptr;
2264             }
2265          }
2266          if (dual_source_blend) {
2267             /* only support one dual source blend target hence always use output 1 */
2268             for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
2269                ptr = LLVMBuildGEP(builder,
2270                                   color_store[1][chan],
2271                                   &indexi, 1, "");
2272                fs_out_color[1][chan][i] = ptr;
2273             }
2274          }
2275       }
2276    }
2277
2278    sampler->destroy(sampler);
2279
2280    /* Loop over color outputs / color buffers to do blending.
2281     */
2282    for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
2283       LLVMValueRef color_ptr;
2284       LLVMValueRef stride;
2285       LLVMValueRef index = lp_build_const_int32(gallivm, cbuf);
2286
2287       boolean do_branch = ((key->depth.enabled
2288                             || key->stencil[0].enabled
2289                             || key->alpha.enabled)
2290                            && !shader->info.base.uses_kill);
2291
2292       color_ptr = LLVMBuildLoad(builder,
2293                                 LLVMBuildGEP(builder, color_ptr_ptr, &index, 1, ""),
2294                                 "");
2295
2296       lp_build_name(color_ptr, "color_ptr%d", cbuf);
2297
2298       stride = LLVMBuildLoad(builder,
2299                              LLVMBuildGEP(builder, stride_ptr, &index, 1, ""),
2300                              "");
2301
2302       generate_unswizzled_blend(gallivm, cbuf, variant, key->cbuf_format[cbuf],
2303                                 num_fs, fs_type, fs_mask, fs_out_color,
2304                                 context_ptr, color_ptr, stride, partial_mask, do_branch);
2305    }
2306
2307    LLVMBuildRetVoid(builder);
2308
2309    gallivm_verify_function(gallivm, function);
2310
2311    variant->nr_instrs += lp_build_count_instructions(function);
2312 }
2313
2314
2315 static void
2316 dump_fs_variant_key(const struct lp_fragment_shader_variant_key *key)
2317 {
2318    unsigned i;
2319
2320    debug_printf("fs variant %p:\n", (void *) key);
2321
2322    if (key->flatshade) {
2323       debug_printf("flatshade = 1\n");
2324    }
2325    for (i = 0; i < key->nr_cbufs; ++i) {
2326       debug_printf("cbuf_format[%u] = %s\n", i, util_format_name(key->cbuf_format[i]));
2327    }
2328    if (key->depth.enabled) {
2329       debug_printf("depth.format = %s\n", util_format_name(key->zsbuf_format));
2330       debug_printf("depth.func = %s\n", util_dump_func(key->depth.func, TRUE));
2331       debug_printf("depth.writemask = %u\n", key->depth.writemask);
2332    }
2333
2334    for (i = 0; i < 2; ++i) {
2335       if (key->stencil[i].enabled) {
2336          debug_printf("stencil[%u].func = %s\n", i, util_dump_func(key->stencil[i].func, TRUE));
2337          debug_printf("stencil[%u].fail_op = %s\n", i, util_dump_stencil_op(key->stencil[i].fail_op, TRUE));
2338          debug_printf("stencil[%u].zpass_op = %s\n", i, util_dump_stencil_op(key->stencil[i].zpass_op, TRUE));
2339          debug_printf("stencil[%u].zfail_op = %s\n", i, util_dump_stencil_op(key->stencil[i].zfail_op, TRUE));
2340          debug_printf("stencil[%u].valuemask = 0x%x\n", i, key->stencil[i].valuemask);
2341          debug_printf("stencil[%u].writemask = 0x%x\n", i, key->stencil[i].writemask);
2342       }
2343    }
2344
2345    if (key->alpha.enabled) {
2346       debug_printf("alpha.func = %s\n", util_dump_func(key->alpha.func, TRUE));
2347    }
2348
2349    if (key->occlusion_count) {
2350       debug_printf("occlusion_count = 1\n");
2351    }
2352
2353    if (key->blend.logicop_enable) {
2354       debug_printf("blend.logicop_func = %s\n", util_dump_logicop(key->blend.logicop_func, TRUE));
2355    }
2356    else if (key->blend.rt[0].blend_enable) {
2357       debug_printf("blend.rgb_func = %s\n",   util_dump_blend_func  (key->blend.rt[0].rgb_func, TRUE));
2358       debug_printf("blend.rgb_src_factor = %s\n",   util_dump_blend_factor(key->blend.rt[0].rgb_src_factor, TRUE));
2359       debug_printf("blend.rgb_dst_factor = %s\n",   util_dump_blend_factor(key->blend.rt[0].rgb_dst_factor, TRUE));
2360       debug_printf("blend.alpha_func = %s\n",       util_dump_blend_func  (key->blend.rt[0].alpha_func, TRUE));
2361       debug_printf("blend.alpha_src_factor = %s\n", util_dump_blend_factor(key->blend.rt[0].alpha_src_factor, TRUE));
2362       debug_printf("blend.alpha_dst_factor = %s\n", util_dump_blend_factor(key->blend.rt[0].alpha_dst_factor, TRUE));
2363    }
2364    debug_printf("blend.colormask = 0x%x\n", key->blend.rt[0].colormask);
2365    for (i = 0; i < key->nr_samplers; ++i) {
2366       const struct lp_static_sampler_state *sampler = &key->state[i].sampler_state;
2367       debug_printf("sampler[%u] = \n", i);
2368       debug_printf("  .wrap = %s %s %s\n",
2369                    util_dump_tex_wrap(sampler->wrap_s, TRUE),
2370                    util_dump_tex_wrap(sampler->wrap_t, TRUE),
2371                    util_dump_tex_wrap(sampler->wrap_r, TRUE));
2372       debug_printf("  .min_img_filter = %s\n",
2373                    util_dump_tex_filter(sampler->min_img_filter, TRUE));
2374       debug_printf("  .min_mip_filter = %s\n",
2375                    util_dump_tex_mipfilter(sampler->min_mip_filter, TRUE));
2376       debug_printf("  .mag_img_filter = %s\n",
2377                    util_dump_tex_filter(sampler->mag_img_filter, TRUE));
2378       if (sampler->compare_mode != PIPE_TEX_COMPARE_NONE)
2379          debug_printf("  .compare_func = %s\n", util_dump_func(sampler->compare_func, TRUE));
2380       debug_printf("  .normalized_coords = %u\n", sampler->normalized_coords);
2381       debug_printf("  .min_max_lod_equal = %u\n", sampler->min_max_lod_equal);
2382       debug_printf("  .lod_bias_non_zero = %u\n", sampler->lod_bias_non_zero);
2383       debug_printf("  .apply_min_lod = %u\n", sampler->apply_min_lod);
2384       debug_printf("  .apply_max_lod = %u\n", sampler->apply_max_lod);
2385    }
2386    for (i = 0; i < key->nr_sampler_views; ++i) {
2387       const struct lp_static_texture_state *texture = &key->state[i].texture_state;
2388       debug_printf("texture[%u] = \n", i);
2389       debug_printf("  .format = %s\n",
2390                    util_format_name(texture->format));
2391       debug_printf("  .target = %s\n",
2392                    util_dump_tex_target(texture->target, TRUE));
2393       debug_printf("  .level_zero_only = %u\n",
2394                    texture->level_zero_only);
2395       debug_printf("  .pot = %u %u %u\n",
2396                    texture->pot_width,
2397                    texture->pot_height,
2398                    texture->pot_depth);
2399    }
2400 }
2401
2402
2403 void
2404 lp_debug_fs_variant(const struct lp_fragment_shader_variant *variant)
2405 {
2406    debug_printf("llvmpipe: Fragment shader #%u variant #%u:\n", 
2407                 variant->shader->no, variant->no);
2408    tgsi_dump(variant->shader->base.tokens, 0);
2409    dump_fs_variant_key(&variant->key);
2410    debug_printf("variant->opaque = %u\n", variant->opaque);
2411    debug_printf("\n");
2412 }
2413
2414
2415 /**
2416  * Generate a new fragment shader variant from the shader code and
2417  * other state indicated by the key.
2418  */
2419 static struct lp_fragment_shader_variant *
2420 generate_variant(struct llvmpipe_context *lp,
2421                  struct lp_fragment_shader *shader,
2422                  const struct lp_fragment_shader_variant_key *key)
2423 {
2424    struct lp_fragment_shader_variant *variant;
2425    const struct util_format_description *cbuf0_format_desc;
2426    boolean fullcolormask;
2427
2428    variant = CALLOC_STRUCT(lp_fragment_shader_variant);
2429    if(!variant)
2430       return NULL;
2431
2432    variant->gallivm = gallivm_create();
2433    if (!variant->gallivm) {
2434       FREE(variant);
2435       return NULL;
2436    }
2437
2438    variant->shader = shader;
2439    variant->list_item_global.base = variant;
2440    variant->list_item_local.base = variant;
2441    variant->no = shader->variants_created++;
2442
2443    memcpy(&variant->key, key, shader->variant_key_size);
2444
2445    /*
2446     * Determine whether we are touching all channels in the color buffer.
2447     */
2448    fullcolormask = FALSE;
2449    if (key->nr_cbufs == 1) {
2450       cbuf0_format_desc = util_format_description(key->cbuf_format[0]);
2451       fullcolormask = util_format_colormask_full(cbuf0_format_desc, key->blend.rt[0].colormask);
2452    }
2453
2454    variant->opaque =
2455          !key->blend.logicop_enable &&
2456          !key->blend.rt[0].blend_enable &&
2457          fullcolormask &&
2458          !key->stencil[0].enabled &&
2459          !key->alpha.enabled &&
2460          !key->depth.enabled &&
2461          !shader->info.base.uses_kill
2462          ? TRUE : FALSE;
2463
2464    if ((LP_DEBUG & DEBUG_FS) || (gallivm_debug & GALLIVM_DEBUG_IR)) {
2465       lp_debug_fs_variant(variant);
2466    }
2467
2468    lp_jit_init_types(variant);
2469    
2470    if (variant->jit_function[RAST_EDGE_TEST] == NULL)
2471       generate_fragment(lp, shader, variant, RAST_EDGE_TEST);
2472
2473    if (variant->jit_function[RAST_WHOLE] == NULL) {
2474       if (variant->opaque) {
2475          /* Specialized shader, which doesn't need to read the color buffer. */
2476          generate_fragment(lp, shader, variant, RAST_WHOLE);
2477       }
2478    }
2479
2480    /*
2481     * Compile everything
2482     */
2483
2484    gallivm_compile_module(variant->gallivm);
2485
2486    if (variant->function[RAST_EDGE_TEST]) {
2487       variant->jit_function[RAST_EDGE_TEST] = (lp_jit_frag_func)
2488             gallivm_jit_function(variant->gallivm,
2489                                  variant->function[RAST_EDGE_TEST]);
2490    }
2491
2492    if (variant->function[RAST_WHOLE]) {
2493          variant->jit_function[RAST_WHOLE] = (lp_jit_frag_func)
2494                gallivm_jit_function(variant->gallivm,
2495                                     variant->function[RAST_WHOLE]);
2496    } else if (!variant->jit_function[RAST_WHOLE]) {
2497       variant->jit_function[RAST_WHOLE] = variant->jit_function[RAST_EDGE_TEST];
2498    }
2499
2500    return variant;
2501 }
2502
2503
2504 static void *
2505 llvmpipe_create_fs_state(struct pipe_context *pipe,
2506                          const struct pipe_shader_state *templ)
2507 {
2508    struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
2509    struct lp_fragment_shader *shader;
2510    int nr_samplers;
2511    int nr_sampler_views;
2512    int i;
2513
2514    shader = CALLOC_STRUCT(lp_fragment_shader);
2515    if (!shader)
2516       return NULL;
2517
2518    shader->no = fs_no++;
2519    make_empty_list(&shader->variants);
2520
2521    /* get/save the summary info for this shader */
2522    lp_build_tgsi_info(templ->tokens, &shader->info);
2523
2524    /* we need to keep a local copy of the tokens */
2525    shader->base.tokens = tgsi_dup_tokens(templ->tokens);
2526
2527    shader->draw_data = draw_create_fragment_shader(llvmpipe->draw, templ);
2528    if (shader->draw_data == NULL) {
2529       FREE((void *) shader->base.tokens);
2530       FREE(shader);
2531       return NULL;
2532    }
2533
2534    nr_samplers = shader->info.base.file_max[TGSI_FILE_SAMPLER] + 1;
2535    nr_sampler_views = shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] + 1;
2536
2537    shader->variant_key_size = Offset(struct lp_fragment_shader_variant_key,
2538                                      state[MAX2(nr_samplers, nr_sampler_views)]);
2539
2540    for (i = 0; i < shader->info.base.num_inputs; i++) {
2541       shader->inputs[i].usage_mask = shader->info.base.input_usage_mask[i];
2542       shader->inputs[i].cyl_wrap = shader->info.base.input_cylindrical_wrap[i];
2543
2544       switch (shader->info.base.input_interpolate[i]) {
2545       case TGSI_INTERPOLATE_CONSTANT:
2546          shader->inputs[i].interp = LP_INTERP_CONSTANT;
2547          break;
2548       case TGSI_INTERPOLATE_LINEAR:
2549          shader->inputs[i].interp = LP_INTERP_LINEAR;
2550          break;
2551       case TGSI_INTERPOLATE_PERSPECTIVE:
2552          shader->inputs[i].interp = LP_INTERP_PERSPECTIVE;
2553          break;
2554       case TGSI_INTERPOLATE_COLOR:
2555          shader->inputs[i].interp = LP_INTERP_COLOR;
2556          break;
2557       default:
2558          assert(0);
2559          break;
2560       }
2561
2562       switch (shader->info.base.input_semantic_name[i]) {
2563       case TGSI_SEMANTIC_FACE:
2564          shader->inputs[i].interp = LP_INTERP_FACING;
2565          break;
2566       case TGSI_SEMANTIC_POSITION:
2567          /* Position was already emitted above
2568           */
2569          shader->inputs[i].interp = LP_INTERP_POSITION;
2570          shader->inputs[i].src_index = 0;
2571          continue;
2572       }
2573
2574       shader->inputs[i].src_index = i+1;
2575    }
2576
2577    if (LP_DEBUG & DEBUG_TGSI) {
2578       unsigned attrib;
2579       debug_printf("llvmpipe: Create fragment shader #%u %p:\n",
2580                    shader->no, (void *) shader);
2581       tgsi_dump(templ->tokens, 0);
2582       debug_printf("usage masks:\n");
2583       for (attrib = 0; attrib < shader->info.base.num_inputs; ++attrib) {
2584          unsigned usage_mask = shader->info.base.input_usage_mask[attrib];
2585          debug_printf("  IN[%u].%s%s%s%s\n",
2586                       attrib,
2587                       usage_mask & TGSI_WRITEMASK_X ? "x" : "",
2588                       usage_mask & TGSI_WRITEMASK_Y ? "y" : "",
2589                       usage_mask & TGSI_WRITEMASK_Z ? "z" : "",
2590                       usage_mask & TGSI_WRITEMASK_W ? "w" : "");
2591       }
2592       debug_printf("\n");
2593    }
2594
2595    return shader;
2596 }
2597
2598
2599 static void
2600 llvmpipe_bind_fs_state(struct pipe_context *pipe, void *fs)
2601 {
2602    struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
2603
2604    if (llvmpipe->fs == fs)
2605       return;
2606
2607    llvmpipe->fs = (struct lp_fragment_shader *) fs;
2608
2609    draw_bind_fragment_shader(llvmpipe->draw,
2610                              (llvmpipe->fs ? llvmpipe->fs->draw_data : NULL));
2611
2612    llvmpipe->dirty |= LP_NEW_FS;
2613 }
2614
2615
2616 /**
2617  * Remove shader variant from two lists: the shader's variant list
2618  * and the context's variant list.
2619  */
2620 void
2621 llvmpipe_remove_shader_variant(struct llvmpipe_context *lp,
2622                                struct lp_fragment_shader_variant *variant)
2623 {
2624    unsigned i;
2625
2626    if (gallivm_debug & GALLIVM_DEBUG_IR) {
2627       debug_printf("llvmpipe: del fs #%u var #%u v created #%u v cached"
2628                    " #%u v total cached #%u\n",
2629                    variant->shader->no,
2630                    variant->no,
2631                    variant->shader->variants_created,
2632                    variant->shader->variants_cached,
2633                    lp->nr_fs_variants);
2634    }
2635
2636    /* free all the variant's JIT'd functions */
2637    for (i = 0; i < Elements(variant->function); i++) {
2638       if (variant->function[i]) {
2639          gallivm_free_function(variant->gallivm,
2640                                variant->function[i],
2641                                variant->jit_function[i]);
2642       }
2643    }
2644
2645    gallivm_destroy(variant->gallivm);
2646
2647    /* remove from shader's list */
2648    remove_from_list(&variant->list_item_local);
2649    variant->shader->variants_cached--;
2650
2651    /* remove from context's list */
2652    remove_from_list(&variant->list_item_global);
2653    lp->nr_fs_variants--;
2654    lp->nr_fs_instrs -= variant->nr_instrs;
2655
2656    FREE(variant);
2657 }
2658
2659
2660 static void
2661 llvmpipe_delete_fs_state(struct pipe_context *pipe, void *fs)
2662 {
2663    struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
2664    struct lp_fragment_shader *shader = fs;
2665    struct lp_fs_variant_list_item *li;
2666
2667    assert(fs != llvmpipe->fs);
2668
2669    /*
2670     * XXX: we need to flush the context until we have some sort of reference
2671     * counting in fragment shaders as they may still be binned
2672     * Flushing alone might not sufficient we need to wait on it too.
2673     */
2674    llvmpipe_finish(pipe, __FUNCTION__);
2675
2676    /* Delete all the variants */
2677    li = first_elem(&shader->variants);
2678    while(!at_end(&shader->variants, li)) {
2679       struct lp_fs_variant_list_item *next = next_elem(li);
2680       llvmpipe_remove_shader_variant(llvmpipe, li->base);
2681       li = next;
2682    }
2683
2684    /* Delete draw module's data */
2685    draw_delete_fragment_shader(llvmpipe->draw, shader->draw_data);
2686
2687    assert(shader->variants_cached == 0);
2688    FREE((void *) shader->base.tokens);
2689    FREE(shader);
2690 }
2691
2692
2693
2694 static void
2695 llvmpipe_set_constant_buffer(struct pipe_context *pipe,
2696                              uint shader, uint index,
2697                              struct pipe_constant_buffer *cb)
2698 {
2699    struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
2700    struct pipe_resource *constants = cb ? cb->buffer : NULL;
2701
2702    assert(shader < PIPE_SHADER_TYPES);
2703    assert(index < Elements(llvmpipe->constants[shader]));
2704
2705    /* note: reference counting */
2706    util_copy_constant_buffer(&llvmpipe->constants[shader][index], cb);
2707
2708    if (shader == PIPE_SHADER_VERTEX ||
2709        shader == PIPE_SHADER_GEOMETRY) {
2710       /* Pass the constants to the 'draw' module */
2711       const unsigned size = cb ? cb->buffer_size : 0;
2712       const ubyte *data;
2713
2714       if (constants) {
2715          data = (ubyte *) llvmpipe_resource_data(constants);
2716       }
2717       else if (cb && cb->user_buffer) {
2718          data = (ubyte *) cb->user_buffer;
2719       }
2720       else {
2721          data = NULL;
2722       }
2723
2724       if (data)
2725          data += cb->buffer_offset;
2726
2727       draw_set_mapped_constant_buffer(llvmpipe->draw, shader,
2728                                       index, data, size);
2729    }
2730
2731    llvmpipe->dirty |= LP_NEW_CONSTANTS;
2732
2733    if (cb && cb->user_buffer) {
2734       pipe_resource_reference(&constants, NULL);
2735    }
2736 }
2737
2738
2739 /**
2740  * Return the blend factor equivalent to a destination alpha of one.
2741  */
2742 static INLINE unsigned
2743 force_dst_alpha_one(unsigned factor)
2744 {
2745    switch(factor) {
2746    case PIPE_BLENDFACTOR_DST_ALPHA:
2747       return PIPE_BLENDFACTOR_ONE;
2748    case PIPE_BLENDFACTOR_INV_DST_ALPHA:
2749       return PIPE_BLENDFACTOR_ZERO;
2750    case PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE:
2751       return PIPE_BLENDFACTOR_ZERO;
2752    }
2753
2754    return factor;
2755 }
2756
2757
2758 /**
2759  * We need to generate several variants of the fragment pipeline to match
2760  * all the combinations of the contributing state atoms.
2761  *
2762  * TODO: there is actually no reason to tie this to context state -- the
2763  * generated code could be cached globally in the screen.
2764  */
2765 static void
2766 make_variant_key(struct llvmpipe_context *lp,
2767                  struct lp_fragment_shader *shader,
2768                  struct lp_fragment_shader_variant_key *key)
2769 {
2770    unsigned i;
2771
2772    memset(key, 0, shader->variant_key_size);
2773
2774    if (lp->framebuffer.zsbuf) {
2775       if (lp->depth_stencil->depth.enabled) {
2776          key->zsbuf_format = lp->framebuffer.zsbuf->format;
2777          memcpy(&key->depth, &lp->depth_stencil->depth, sizeof key->depth);
2778       }
2779       if (lp->depth_stencil->stencil[0].enabled) {
2780          key->zsbuf_format = lp->framebuffer.zsbuf->format;
2781          memcpy(&key->stencil, &lp->depth_stencil->stencil, sizeof key->stencil);
2782       }
2783    }
2784
2785    /* alpha test only applies if render buffer 0 is non-integer (or does not exist) */
2786    if (!lp->framebuffer.nr_cbufs ||
2787        !util_format_is_pure_integer(lp->framebuffer.cbufs[0]->format)) {
2788       key->alpha.enabled = lp->depth_stencil->alpha.enabled;
2789    }
2790    if(key->alpha.enabled)
2791       key->alpha.func = lp->depth_stencil->alpha.func;
2792    /* alpha.ref_value is passed in jit_context */
2793
2794    key->flatshade = lp->rasterizer->flatshade;
2795    if (lp->active_occlusion_query) {
2796       key->occlusion_count = TRUE;
2797    }
2798
2799    if (lp->framebuffer.nr_cbufs) {
2800       memcpy(&key->blend, lp->blend, sizeof key->blend);
2801    }
2802
2803    key->nr_cbufs = lp->framebuffer.nr_cbufs;
2804
2805    if (!key->blend.independent_blend_enable) {
2806       /* we always need independent blend otherwise the fixups below won't work */
2807       for (i = 1; i < key->nr_cbufs; i++) {
2808          memcpy(&key->blend.rt[i], &key->blend.rt[0], sizeof(key->blend.rt[0]));
2809       }
2810       key->blend.independent_blend_enable = 1;
2811    }
2812
2813    for (i = 0; i < lp->framebuffer.nr_cbufs; i++) {
2814       enum pipe_format format = lp->framebuffer.cbufs[i]->format;
2815       struct pipe_rt_blend_state *blend_rt = &key->blend.rt[i];
2816       const struct util_format_description *format_desc;
2817
2818       key->cbuf_format[i] = format;
2819
2820       format_desc = util_format_description(format);
2821       assert(format_desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB ||
2822              format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB);
2823
2824       /*
2825        * Mask out color channels not present in the color buffer.
2826        */
2827       blend_rt->colormask &= util_format_colormask(format_desc);
2828
2829       /*
2830        * Disable blend for integer formats.
2831        */
2832       if (util_format_is_pure_integer(format)) {
2833          blend_rt->blend_enable = 0;
2834       }
2835
2836       /*
2837        * Our swizzled render tiles always have an alpha channel, but the linear
2838        * render target format often does not, so force here the dst alpha to be
2839        * one.
2840        *
2841        * This is not a mere optimization. Wrong results will be produced if the
2842        * dst alpha is used, the dst format does not have alpha, and the previous
2843        * rendering was not flushed from the swizzled to linear buffer. For
2844        * example, NonPowTwo DCT.
2845        *
2846        * TODO: This should be generalized to all channels for better
2847        * performance, but only alpha causes correctness issues.
2848        *
2849        * Also, force rgb/alpha func/factors match, to make AoS blending easier.
2850        */
2851       if (format_desc->swizzle[3] > UTIL_FORMAT_SWIZZLE_W ||
2852           format_desc->swizzle[3] == format_desc->swizzle[0]) {
2853          blend_rt->rgb_src_factor   = force_dst_alpha_one(blend_rt->rgb_src_factor);
2854          blend_rt->rgb_dst_factor   = force_dst_alpha_one(blend_rt->rgb_dst_factor);
2855          blend_rt->alpha_func       = blend_rt->rgb_func;
2856          blend_rt->alpha_src_factor = blend_rt->rgb_src_factor;
2857          blend_rt->alpha_dst_factor = blend_rt->rgb_dst_factor;
2858       }
2859    }
2860
2861    /* This value will be the same for all the variants of a given shader:
2862     */
2863    key->nr_samplers = shader->info.base.file_max[TGSI_FILE_SAMPLER] + 1;
2864
2865    for(i = 0; i < key->nr_samplers; ++i) {
2866       if(shader->info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
2867          lp_sampler_static_sampler_state(&key->state[i].sampler_state,
2868                                          lp->samplers[PIPE_SHADER_FRAGMENT][i]);
2869       }
2870    }
2871
2872    /*
2873     * XXX If TGSI_FILE_SAMPLER_VIEW exists assume all texture opcodes
2874     * are dx10-style? Can't really have mixed opcodes, at least not
2875     * if we want to skip the holes here (without rescanning tgsi).
2876     */
2877    if (shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] != -1) {
2878       key->nr_sampler_views = shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] + 1;
2879       for(i = 0; i < key->nr_sampler_views; ++i) {
2880          if(shader->info.base.file_mask[TGSI_FILE_SAMPLER_VIEW] & (1 << i)) {
2881             lp_sampler_static_texture_state(&key->state[i].texture_state,
2882                                             lp->sampler_views[PIPE_SHADER_FRAGMENT][i]);
2883          }
2884       }
2885    }
2886    else {
2887       key->nr_sampler_views = key->nr_samplers;
2888       for(i = 0; i < key->nr_sampler_views; ++i) {
2889          if(shader->info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
2890             lp_sampler_static_texture_state(&key->state[i].texture_state,
2891                                             lp->sampler_views[PIPE_SHADER_FRAGMENT][i]);
2892          }
2893       }
2894    }
2895 }
2896
2897
2898
2899 /**
2900  * Update fragment shader state.  This is called just prior to drawing
2901  * something when some fragment-related state has changed.
2902  */
2903 void 
2904 llvmpipe_update_fs(struct llvmpipe_context *lp)
2905 {
2906    struct lp_fragment_shader *shader = lp->fs;
2907    struct lp_fragment_shader_variant_key key;
2908    struct lp_fragment_shader_variant *variant = NULL;
2909    struct lp_fs_variant_list_item *li;
2910
2911    make_variant_key(lp, shader, &key);
2912
2913    /* Search the variants for one which matches the key */
2914    li = first_elem(&shader->variants);
2915    while(!at_end(&shader->variants, li)) {
2916       if(memcmp(&li->base->key, &key, shader->variant_key_size) == 0) {
2917          variant = li->base;
2918          break;
2919       }
2920       li = next_elem(li);
2921    }
2922
2923    if (variant) {
2924       /* Move this variant to the head of the list to implement LRU
2925        * deletion of shader's when we have too many.
2926        */
2927       move_to_head(&lp->fs_variants_list, &variant->list_item_global);
2928    }
2929    else {
2930       /* variant not found, create it now */
2931       int64_t t0, t1, dt;
2932       unsigned i;
2933       unsigned variants_to_cull;
2934
2935       if (0) {
2936          debug_printf("%u variants,\t%u instrs,\t%u instrs/variant\n",
2937                       lp->nr_fs_variants,
2938                       lp->nr_fs_instrs,
2939                       lp->nr_fs_variants ? lp->nr_fs_instrs / lp->nr_fs_variants : 0);
2940       }
2941
2942       /* First, check if we've exceeded the max number of shader variants.
2943        * If so, free 25% of them (the least recently used ones).
2944        */
2945       variants_to_cull = lp->nr_fs_variants >= LP_MAX_SHADER_VARIANTS ? LP_MAX_SHADER_VARIANTS / 4 : 0;
2946
2947       if (variants_to_cull ||
2948           lp->nr_fs_instrs >= LP_MAX_SHADER_INSTRUCTIONS) {
2949          struct pipe_context *pipe = &lp->pipe;
2950
2951          /*
2952           * XXX: we need to flush the context until we have some sort of
2953           * reference counting in fragment shaders as they may still be binned
2954           * Flushing alone might not be sufficient we need to wait on it too.
2955           */
2956          llvmpipe_finish(pipe, __FUNCTION__);
2957
2958          /*
2959           * We need to re-check lp->nr_fs_variants because an arbitrarliy large
2960           * number of shader variants (potentially all of them) could be
2961           * pending for destruction on flush.
2962           */
2963
2964          for (i = 0; i < variants_to_cull || lp->nr_fs_instrs >= LP_MAX_SHADER_INSTRUCTIONS; i++) {
2965             struct lp_fs_variant_list_item *item;
2966             if (is_empty_list(&lp->fs_variants_list)) {
2967                break;
2968             }
2969             item = last_elem(&lp->fs_variants_list);
2970             assert(item);
2971             assert(item->base);
2972             llvmpipe_remove_shader_variant(lp, item->base);
2973          }
2974       }
2975
2976       /*
2977        * Generate the new variant.
2978        */
2979       t0 = os_time_get();
2980       variant = generate_variant(lp, shader, &key);
2981       t1 = os_time_get();
2982       dt = t1 - t0;
2983       LP_COUNT_ADD(llvm_compile_time, dt);
2984       LP_COUNT_ADD(nr_llvm_compiles, 2);  /* emit vs. omit in/out test */
2985
2986       llvmpipe_variant_count++;
2987
2988       /* Put the new variant into the list */
2989       if (variant) {
2990          insert_at_head(&shader->variants, &variant->list_item_local);
2991          insert_at_head(&lp->fs_variants_list, &variant->list_item_global);
2992          lp->nr_fs_variants++;
2993          lp->nr_fs_instrs += variant->nr_instrs;
2994          shader->variants_cached++;
2995       }
2996    }
2997
2998    /* Bind this variant */
2999    lp_setup_set_fs_variant(lp->setup, variant);
3000 }
3001
3002
3003
3004
3005
3006 void
3007 llvmpipe_init_fs_funcs(struct llvmpipe_context *llvmpipe)
3008 {
3009    llvmpipe->pipe.create_fs_state = llvmpipe_create_fs_state;
3010    llvmpipe->pipe.bind_fs_state   = llvmpipe_bind_fs_state;
3011    llvmpipe->pipe.delete_fs_state = llvmpipe_delete_fs_state;
3012
3013    llvmpipe->pipe.set_constant_buffer = llvmpipe_set_constant_buffer;
3014 }