7bbf348e0b84bc4fbffe2af68a4263d67e134286
[profile/ivi/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  * - triangle edge in/out testing
35  * - scissor test
36  * - stipple (TBI)
37  * - early depth test
38  * - fragment shader
39  * - alpha test
40  * - depth/stencil test (stencil TBI)
41  * - blending
42  *
43  * This file has only the glue to assemble the fragment pipeline.  The actual
44  * plumbing of converting Gallium state into LLVM IR is done elsewhere, in the
45  * lp_bld_*.[ch] files, and in a complete generic and reusable way. Here we
46  * muster the LLVM JIT execution engine to create a function that follows an
47  * established binary interface and that can be called from C directly.
48  *
49  * A big source of complexity here is that we often want to run different
50  * stages with different precisions and data types and precisions. For example,
51  * the fragment shader needs typically to be done in floats, but the
52  * depth/stencil test and blending is better done in the type that most closely
53  * matches the depth/stencil and color buffer respectively.
54  *
55  * Since the width of a SIMD vector register stays the same regardless of the
56  * element type, different types imply different number of elements, so we must
57  * code generate more instances of the stages with larger types to be able to
58  * feed/consume the stages with smaller types.
59  *
60  * @author Jose Fonseca <jfonseca@vmware.com>
61  */
62
63 #include <limits.h>
64 #include "pipe/p_defines.h"
65 #include "util/u_inlines.h"
66 #include "util/u_memory.h"
67 #include "util/u_format.h"
68 #include "util/u_dump.h"
69 #include "os/os_time.h"
70 #include "pipe/p_shader_tokens.h"
71 #include "draw/draw_context.h"
72 #include "tgsi/tgsi_dump.h"
73 #include "tgsi/tgsi_scan.h"
74 #include "tgsi/tgsi_parse.h"
75 #include "gallivm/lp_bld_type.h"
76 #include "gallivm/lp_bld_const.h"
77 #include "gallivm/lp_bld_conv.h"
78 #include "gallivm/lp_bld_intr.h"
79 #include "gallivm/lp_bld_logic.h"
80 #include "gallivm/lp_bld_depth.h"
81 #include "gallivm/lp_bld_interp.h"
82 #include "gallivm/lp_bld_tgsi.h"
83 #include "gallivm/lp_bld_alpha.h"
84 #include "gallivm/lp_bld_blend.h"
85 #include "gallivm/lp_bld_swizzle.h"
86 #include "gallivm/lp_bld_flow.h"
87 #include "gallivm/lp_bld_debug.h"
88 #include "lp_buffer.h"
89 #include "lp_context.h"
90 #include "lp_debug.h"
91 #include "lp_perf.h"
92 #include "lp_screen.h"
93 #include "lp_setup.h"
94 #include "lp_state.h"
95 #include "lp_tex_sample.h"
96
97
98 #include <llvm-c/Analysis.h>
99
100
101 static const unsigned char quad_offset_x[4] = {0, 1, 0, 1};
102 static const unsigned char quad_offset_y[4] = {0, 0, 1, 1};
103
104
105 /*
106  * Derive from the quad's upper left scalar coordinates the coordinates for
107  * all other quad pixels
108  */
109 static void
110 generate_pos0(LLVMBuilderRef builder,
111               LLVMValueRef x,
112               LLVMValueRef y,
113               LLVMValueRef *x0,
114               LLVMValueRef *y0)
115 {
116    LLVMTypeRef int_elem_type = LLVMInt32Type();
117    LLVMTypeRef int_vec_type = LLVMVectorType(int_elem_type, QUAD_SIZE);
118    LLVMTypeRef elem_type = LLVMFloatType();
119    LLVMTypeRef vec_type = LLVMVectorType(elem_type, QUAD_SIZE);
120    LLVMValueRef x_offsets[QUAD_SIZE];
121    LLVMValueRef y_offsets[QUAD_SIZE];
122    unsigned i;
123
124    x = lp_build_broadcast(builder, int_vec_type, x);
125    y = lp_build_broadcast(builder, int_vec_type, y);
126
127    for(i = 0; i < QUAD_SIZE; ++i) {
128       x_offsets[i] = LLVMConstInt(int_elem_type, quad_offset_x[i], 0);
129       y_offsets[i] = LLVMConstInt(int_elem_type, quad_offset_y[i], 0);
130    }
131
132    x = LLVMBuildAdd(builder, x, LLVMConstVector(x_offsets, QUAD_SIZE), "");
133    y = LLVMBuildAdd(builder, y, LLVMConstVector(y_offsets, QUAD_SIZE), "");
134
135    *x0 = LLVMBuildSIToFP(builder, x, vec_type, "");
136    *y0 = LLVMBuildSIToFP(builder, y, vec_type, "");
137 }
138
139
140 /**
141  * Generate the depth /stencil test code.
142  */
143 static void
144 generate_depth_stencil(LLVMBuilderRef builder,
145                        const struct lp_fragment_shader_variant_key *key,
146                        struct lp_type src_type,
147                        struct lp_build_mask_context *mask,
148                        LLVMValueRef stencil_refs[2],
149                        LLVMValueRef src,
150                        LLVMValueRef dst_ptr,
151                        LLVMValueRef facing)
152 {
153    const struct util_format_description *format_desc;
154    struct lp_type dst_type;
155
156    if (!key->depth.enabled && !key->stencil[0].enabled && !key->stencil[1].enabled)
157       return;
158
159    format_desc = util_format_description(key->zsbuf_format);
160    assert(format_desc);
161
162    /*
163     * Depths are expected to be between 0 and 1, even if they are stored in
164     * floats. Setting these bits here will ensure that the lp_build_conv() call
165     * below won't try to unnecessarily clamp the incoming values.
166     */
167    if(src_type.floating) {
168       src_type.sign = FALSE;
169       src_type.norm = TRUE;
170    }
171    else {
172       assert(!src_type.sign);
173       assert(src_type.norm);
174    }
175
176    /* Pick the depth type. */
177    dst_type = lp_depth_type(format_desc, src_type.width*src_type.length);
178
179    /* FIXME: Cope with a depth test type with a different bit width. */
180    assert(dst_type.width == src_type.width);
181    assert(dst_type.length == src_type.length);
182
183    /* Convert fragment Z from float to integer */
184    lp_build_conv(builder, src_type, dst_type, &src, 1, &src, 1);
185
186    dst_ptr = LLVMBuildBitCast(builder,
187                               dst_ptr,
188                               LLVMPointerType(lp_build_vec_type(dst_type), 0), "");
189    lp_build_depth_stencil_test(builder,
190                                &key->depth,
191                                key->stencil,
192                                dst_type,
193                                format_desc,
194                                mask,
195                                stencil_refs,
196                                src,
197                                dst_ptr,
198                                facing);
199 }
200
201
202 /**
203  * Generate the code to do inside/outside triangle testing for the
204  * four pixels in a 2x2 quad.  This will set the four elements of the
205  * quad mask vector to 0 or ~0.
206  * \param i  which quad of the quad group to test, in [0,3]
207  */
208 static void
209 generate_tri_edge_mask(LLVMBuilderRef builder,
210                        unsigned i,
211                        LLVMValueRef *mask,      /* ivec4, out */
212                        LLVMValueRef c0,         /* int32 */
213                        LLVMValueRef c1,         /* int32 */
214                        LLVMValueRef c2,         /* int32 */
215                        LLVMValueRef step0_ptr,  /* ivec4 */
216                        LLVMValueRef step1_ptr,  /* ivec4 */
217                        LLVMValueRef step2_ptr)  /* ivec4 */
218 {
219 #define OPTIMIZE_IN_OUT_TEST 0
220 #if OPTIMIZE_IN_OUT_TEST
221    struct lp_build_if_state ifctx;
222    LLVMValueRef not_draw_all;
223 #endif
224    struct lp_build_flow_context *flow;
225    struct lp_type i32_type;
226    LLVMTypeRef i32vec4_type, mask_type;
227    LLVMValueRef c0_vec, c1_vec, c2_vec;
228    LLVMValueRef in_out_mask;
229
230    assert(i < 4);
231    
232    /* int32 vector type */
233    memset(&i32_type, 0, sizeof i32_type);
234    i32_type.floating = FALSE; /* values are integers */
235    i32_type.sign = TRUE;      /* values are signed */
236    i32_type.norm = FALSE;     /* values are not normalized */
237    i32_type.width = 32;       /* 32-bit int values */
238    i32_type.length = 4;       /* 4 elements per vector */
239
240    i32vec4_type = lp_build_int32_vec4_type();
241
242    mask_type = LLVMIntType(32 * 4);
243
244    /*
245     * Use a conditional here to do detailed pixel in/out testing.
246     * We only have to do this if c0 != INT_MIN.
247     */
248    flow = lp_build_flow_create(builder);
249    lp_build_flow_scope_begin(flow);
250
251    {
252 #if OPTIMIZE_IN_OUT_TEST
253       /* not_draw_all = (c0 != INT_MIN) */
254       not_draw_all = LLVMBuildICmp(builder,
255                                    LLVMIntNE,
256                                    c0,
257                                    LLVMConstInt(LLVMInt32Type(), INT_MIN, 0),
258                                    "");
259
260       in_out_mask = lp_build_const_int_vec(i32_type, ~0);
261
262
263       lp_build_flow_scope_declare(flow, &in_out_mask);
264
265       /* if (not_draw_all) {... */
266       lp_build_if(&ifctx, flow, builder, not_draw_all);
267 #endif
268       {
269          LLVMValueRef step0_vec, step1_vec, step2_vec;
270          LLVMValueRef m0_vec, m1_vec, m2_vec;
271          LLVMValueRef index, m;
272
273          /* c0_vec = {c0, c0, c0, c0}
274           * Note that we emit this code four times but LLVM optimizes away
275           * three instances of it.
276           */
277          c0_vec = lp_build_broadcast(builder, i32vec4_type, c0);
278          c1_vec = lp_build_broadcast(builder, i32vec4_type, c1);
279          c2_vec = lp_build_broadcast(builder, i32vec4_type, c2);
280          lp_build_name(c0_vec, "edgeconst0vec");
281          lp_build_name(c1_vec, "edgeconst1vec");
282          lp_build_name(c2_vec, "edgeconst2vec");
283
284          /* load step0vec, step1, step2 vec from memory */
285          index = LLVMConstInt(LLVMInt32Type(), i, 0);
286          step0_vec = LLVMBuildLoad(builder, LLVMBuildGEP(builder, step0_ptr, &index, 1, ""), "");
287          step1_vec = LLVMBuildLoad(builder, LLVMBuildGEP(builder, step1_ptr, &index, 1, ""), "");
288          step2_vec = LLVMBuildLoad(builder, LLVMBuildGEP(builder, step2_ptr, &index, 1, ""), "");
289          lp_build_name(step0_vec, "step0vec");
290          lp_build_name(step1_vec, "step1vec");
291          lp_build_name(step2_vec, "step2vec");
292
293          /* m0_vec = step0_ptr[i] > c0_vec */
294          m0_vec = lp_build_compare(builder, i32_type, PIPE_FUNC_GREATER, step0_vec, c0_vec);
295          m1_vec = lp_build_compare(builder, i32_type, PIPE_FUNC_GREATER, step1_vec, c1_vec);
296          m2_vec = lp_build_compare(builder, i32_type, PIPE_FUNC_GREATER, step2_vec, c2_vec);
297
298          /* in_out_mask = m0_vec & m1_vec & m2_vec */
299          m = LLVMBuildAnd(builder, m0_vec, m1_vec, "");
300          in_out_mask = LLVMBuildAnd(builder, m, m2_vec, "");
301          lp_build_name(in_out_mask, "inoutmaskvec");
302       }
303 #if OPTIMIZE_IN_OUT_TEST
304       lp_build_endif(&ifctx);
305 #endif
306
307    }
308    lp_build_flow_scope_end(flow);
309    lp_build_flow_destroy(flow);
310
311    /* This is the initial alive/dead pixel mask for a quad of four pixels.
312     * It's an int[4] vector with each word set to 0 or ~0.
313     * Words will get cleared when pixels faile the Z test, etc.
314     */
315    *mask = in_out_mask;
316 }
317
318
319 static LLVMValueRef
320 generate_scissor_test(LLVMBuilderRef builder,
321                       LLVMValueRef context_ptr,
322                       const struct lp_build_interp_soa_context *interp,
323                       struct lp_type type)
324 {
325    LLVMTypeRef vec_type = lp_build_vec_type(type);
326    LLVMValueRef xpos = interp->pos[0], ypos = interp->pos[1];
327    LLVMValueRef xmin, ymin, xmax, ymax;
328    LLVMValueRef m0, m1, m2, m3, m;
329
330    /* xpos, ypos contain the window coords for the four pixels in the quad */
331    assert(xpos);
332    assert(ypos);
333
334    /* get the current scissor bounds, convert to vectors */
335    xmin = lp_jit_context_scissor_xmin_value(builder, context_ptr);
336    xmin = lp_build_broadcast(builder, vec_type, xmin);
337
338    ymin = lp_jit_context_scissor_ymin_value(builder, context_ptr);
339    ymin = lp_build_broadcast(builder, vec_type, ymin);
340
341    xmax = lp_jit_context_scissor_xmax_value(builder, context_ptr);
342    xmax = lp_build_broadcast(builder, vec_type, xmax);
343
344    ymax = lp_jit_context_scissor_ymax_value(builder, context_ptr);
345    ymax = lp_build_broadcast(builder, vec_type, ymax);
346
347    /* compare the fragment's position coordinates against the scissor bounds */
348    m0 = lp_build_compare(builder, type, PIPE_FUNC_GEQUAL, xpos, xmin);
349    m1 = lp_build_compare(builder, type, PIPE_FUNC_GEQUAL, ypos, ymin);
350    m2 = lp_build_compare(builder, type, PIPE_FUNC_LESS, xpos, xmax);
351    m3 = lp_build_compare(builder, type, PIPE_FUNC_LESS, ypos, ymax);
352
353    /* AND all the masks together */
354    m = LLVMBuildAnd(builder, m0, m1, "");
355    m = LLVMBuildAnd(builder, m, m2, "");
356    m = LLVMBuildAnd(builder, m, m3, "");
357
358    lp_build_name(m, "scissormask");
359
360    return m;
361 }
362
363
364 static LLVMValueRef
365 build_int32_vec_const(int value)
366 {
367    struct lp_type i32_type;
368
369    memset(&i32_type, 0, sizeof i32_type);
370    i32_type.floating = FALSE; /* values are integers */
371    i32_type.sign = TRUE;      /* values are signed */
372    i32_type.norm = FALSE;     /* values are not normalized */
373    i32_type.width = 32;       /* 32-bit int values */
374    i32_type.length = 4;       /* 4 elements per vector */
375    return lp_build_const_int_vec(i32_type, value);
376 }
377
378
379
380 /**
381  * Generate the fragment shader, depth/stencil test, and alpha tests.
382  * \param i  which quad in the tile, in range [0,3]
383  * \param do_tri_test  if 1, do triangle edge in/out testing
384  */
385 static void
386 generate_fs(struct llvmpipe_context *lp,
387             struct lp_fragment_shader *shader,
388             const struct lp_fragment_shader_variant_key *key,
389             LLVMBuilderRef builder,
390             struct lp_type type,
391             LLVMValueRef context_ptr,
392             unsigned i,
393             const struct lp_build_interp_soa_context *interp,
394             struct lp_build_sampler_soa *sampler,
395             LLVMValueRef *pmask,
396             LLVMValueRef (*color)[4],
397             LLVMValueRef depth_ptr,
398             LLVMValueRef facing,
399             unsigned do_tri_test,
400             LLVMValueRef c0,
401             LLVMValueRef c1,
402             LLVMValueRef c2,
403             LLVMValueRef step0_ptr,
404             LLVMValueRef step1_ptr,
405             LLVMValueRef step2_ptr)
406 {
407    const struct tgsi_token *tokens = shader->base.tokens;
408    LLVMTypeRef elem_type;
409    LLVMTypeRef vec_type;
410    LLVMTypeRef int_vec_type;
411    LLVMValueRef consts_ptr;
412    LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][NUM_CHANNELS];
413    LLVMValueRef z = interp->pos[2];
414    LLVMValueRef stencil_refs[2];
415    struct lp_build_flow_context *flow;
416    struct lp_build_mask_context mask;
417    boolean early_depth_stencil_test;
418    unsigned attrib;
419    unsigned chan;
420    unsigned cbuf;
421
422    assert(i < 4);
423
424    stencil_refs[0] = lp_jit_context_stencil_ref_front_value(builder, context_ptr);
425    stencil_refs[1] = lp_jit_context_stencil_ref_back_value(builder, context_ptr);
426
427    elem_type = lp_build_elem_type(type);
428    vec_type = lp_build_vec_type(type);
429    int_vec_type = lp_build_int_vec_type(type);
430
431    consts_ptr = lp_jit_context_constants(builder, context_ptr);
432
433    flow = lp_build_flow_create(builder);
434
435    memset(outputs, 0, sizeof outputs);
436
437    lp_build_flow_scope_begin(flow);
438
439    /* Declare the color and z variables */
440    for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
441       for(chan = 0; chan < NUM_CHANNELS; ++chan) {
442          color[cbuf][chan] = LLVMGetUndef(vec_type);
443          lp_build_flow_scope_declare(flow, &color[cbuf][chan]);
444       }
445    }
446    lp_build_flow_scope_declare(flow, &z);
447
448    /* do triangle edge testing */
449    if (do_tri_test) {
450       generate_tri_edge_mask(builder, i, pmask,
451                              c0, c1, c2, step0_ptr, step1_ptr, step2_ptr);
452    }
453    else {
454       *pmask = build_int32_vec_const(~0);
455    }
456
457    /* 'mask' will control execution based on quad's pixel alive/killed state */
458    lp_build_mask_begin(&mask, flow, type, *pmask);
459
460    if (key->scissor) {
461       LLVMValueRef smask =
462          generate_scissor_test(builder, context_ptr, interp, type);
463       lp_build_mask_update(&mask, smask);
464    }
465
466    early_depth_stencil_test =
467       (key->depth.enabled || key->stencil[0].enabled) &&
468       !key->alpha.enabled &&
469       !shader->info.uses_kill &&
470       !shader->info.writes_z;
471
472    if (early_depth_stencil_test)
473       generate_depth_stencil(builder, key,
474                              type, &mask,
475                              stencil_refs, z, depth_ptr, facing);
476
477    lp_build_tgsi_soa(builder, tokens, type, &mask,
478                      consts_ptr, interp->pos, interp->inputs,
479                      outputs, sampler);
480
481    for (attrib = 0; attrib < shader->info.num_outputs; ++attrib) {
482       for(chan = 0; chan < NUM_CHANNELS; ++chan) {
483          if(outputs[attrib][chan]) {
484             LLVMValueRef out = LLVMBuildLoad(builder, outputs[attrib][chan], "");
485             lp_build_name(out, "output%u.%u.%c", i, attrib, "xyzw"[chan]);
486
487             switch (shader->info.output_semantic_name[attrib]) {
488             case TGSI_SEMANTIC_COLOR:
489                {
490                   unsigned cbuf = shader->info.output_semantic_index[attrib];
491
492                   lp_build_name(out, "color%u.%u.%c", i, attrib, "rgba"[chan]);
493
494                   /* Alpha test */
495                   /* XXX: should the alpha reference value be passed separately? */
496                   /* XXX: should only test the final assignment to alpha */
497                   if(cbuf == 0 && chan == 3) {
498                      LLVMValueRef alpha = out;
499                      LLVMValueRef alpha_ref_value;
500                      alpha_ref_value = lp_jit_context_alpha_ref_value(builder, context_ptr);
501                      alpha_ref_value = lp_build_broadcast(builder, vec_type, alpha_ref_value);
502                      lp_build_alpha_test(builder, &key->alpha, type,
503                                          &mask, alpha, alpha_ref_value);
504                   }
505
506                   color[cbuf][chan] = out;
507                   break;
508                }
509
510             case TGSI_SEMANTIC_POSITION:
511                if(chan == 2)
512                   z = out;
513                break;
514             }
515          }
516       }
517    }
518
519    if (!early_depth_stencil_test)
520       generate_depth_stencil(builder, key,
521                              type, &mask,
522                              stencil_refs, z, depth_ptr, facing);
523
524    lp_build_mask_end(&mask);
525
526    lp_build_flow_scope_end(flow);
527
528    lp_build_flow_destroy(flow);
529
530    *pmask = mask.value;
531
532 }
533
534
535 /**
536  * Generate color blending and color output.
537  */
538 static void
539 generate_blend(const struct pipe_blend_state *blend,
540                LLVMBuilderRef builder,
541                struct lp_type type,
542                LLVMValueRef context_ptr,
543                LLVMValueRef mask,
544                LLVMValueRef *src,
545                LLVMValueRef dst_ptr)
546 {
547    struct lp_build_context bld;
548    struct lp_build_flow_context *flow;
549    struct lp_build_mask_context mask_ctx;
550    LLVMTypeRef vec_type;
551    LLVMTypeRef int_vec_type;
552    LLVMValueRef const_ptr;
553    LLVMValueRef con[4];
554    LLVMValueRef dst[4];
555    LLVMValueRef res[4];
556    unsigned chan;
557
558    lp_build_context_init(&bld, builder, type);
559
560    flow = lp_build_flow_create(builder);
561
562    /* we'll use this mask context to skip blending if all pixels are dead */
563    lp_build_mask_begin(&mask_ctx, flow, type, mask);
564
565    vec_type = lp_build_vec_type(type);
566    int_vec_type = lp_build_int_vec_type(type);
567
568    const_ptr = lp_jit_context_blend_color(builder, context_ptr);
569    const_ptr = LLVMBuildBitCast(builder, const_ptr,
570                                 LLVMPointerType(vec_type, 0), "");
571
572    for(chan = 0; chan < 4; ++chan) {
573       LLVMValueRef index = LLVMConstInt(LLVMInt32Type(), chan, 0);
574       con[chan] = LLVMBuildLoad(builder, LLVMBuildGEP(builder, const_ptr, &index, 1, ""), "");
575
576       dst[chan] = LLVMBuildLoad(builder, LLVMBuildGEP(builder, dst_ptr, &index, 1, ""), "");
577
578       lp_build_name(con[chan], "con.%c", "rgba"[chan]);
579       lp_build_name(dst[chan], "dst.%c", "rgba"[chan]);
580    }
581
582    lp_build_blend_soa(builder, blend, type, src, dst, con, res);
583
584    for(chan = 0; chan < 4; ++chan) {
585       if(blend->rt[0].colormask & (1 << chan)) {
586          LLVMValueRef index = LLVMConstInt(LLVMInt32Type(), chan, 0);
587          lp_build_name(res[chan], "res.%c", "rgba"[chan]);
588          res[chan] = lp_build_select(&bld, mask, res[chan], dst[chan]);
589          LLVMBuildStore(builder, res[chan], LLVMBuildGEP(builder, dst_ptr, &index, 1, ""));
590       }
591    }
592
593    lp_build_mask_end(&mask_ctx);
594    lp_build_flow_destroy(flow);
595 }
596
597
598 /** casting function to avoid compiler warnings */
599 static lp_jit_frag_func
600 cast_voidptr_to_lp_jit_frag_func(void *p)
601 {
602    union {
603       void *v;
604       lp_jit_frag_func f;
605    } tmp;
606    assert(sizeof(tmp.v) == sizeof(tmp.f));
607    tmp.v = p;
608    return tmp.f;
609 }
610
611
612 /**
613  * Generate the runtime callable function for the whole fragment pipeline.
614  * Note that the function which we generate operates on a block of 16
615  * pixels at at time.  The block contains 2x2 quads.  Each quad contains
616  * 2x2 pixels.
617  */
618 static void
619 generate_fragment(struct llvmpipe_context *lp,
620                   struct lp_fragment_shader *shader,
621                   struct lp_fragment_shader_variant *variant,
622                   unsigned do_tri_test)
623 {
624    struct llvmpipe_screen *screen = llvmpipe_screen(lp->pipe.screen);
625    const struct lp_fragment_shader_variant_key *key = &variant->key;
626    struct lp_type fs_type;
627    struct lp_type blend_type;
628    LLVMTypeRef fs_elem_type;
629    LLVMTypeRef fs_vec_type;
630    LLVMTypeRef fs_int_vec_type;
631    LLVMTypeRef blend_vec_type;
632    LLVMTypeRef blend_int_vec_type;
633    LLVMTypeRef arg_types[15];
634    LLVMTypeRef func_type;
635    LLVMTypeRef int32_vec4_type = lp_build_int32_vec4_type();
636    LLVMValueRef context_ptr;
637    LLVMValueRef x;
638    LLVMValueRef y;
639    LLVMValueRef a0_ptr;
640    LLVMValueRef dadx_ptr;
641    LLVMValueRef dady_ptr;
642    LLVMValueRef color_ptr_ptr;
643    LLVMValueRef depth_ptr;
644    LLVMValueRef c0, c1, c2, step0_ptr, step1_ptr, step2_ptr;
645    LLVMBasicBlockRef block;
646    LLVMBuilderRef builder;
647    LLVMValueRef x0;
648    LLVMValueRef y0;
649    struct lp_build_sampler_soa *sampler;
650    struct lp_build_interp_soa_context interp;
651    LLVMValueRef fs_mask[LP_MAX_VECTOR_LENGTH];
652    LLVMValueRef fs_out_color[PIPE_MAX_COLOR_BUFS][NUM_CHANNELS][LP_MAX_VECTOR_LENGTH];
653    LLVMValueRef blend_mask;
654    LLVMValueRef blend_in_color[NUM_CHANNELS];
655    LLVMValueRef function;
656    LLVMValueRef facing;
657    unsigned num_fs;
658    unsigned i;
659    unsigned chan;
660    unsigned cbuf;
661
662
663    /* TODO: actually pick these based on the fs and color buffer
664     * characteristics. */
665
666    memset(&fs_type, 0, sizeof fs_type);
667    fs_type.floating = TRUE; /* floating point values */
668    fs_type.sign = TRUE;     /* values are signed */
669    fs_type.norm = FALSE;    /* values are not limited to [0,1] or [-1,1] */
670    fs_type.width = 32;      /* 32-bit float */
671    fs_type.length = 4;      /* 4 elements per vector */
672    num_fs = 4;              /* number of quads per block */
673
674    memset(&blend_type, 0, sizeof blend_type);
675    blend_type.floating = FALSE; /* values are integers */
676    blend_type.sign = FALSE;     /* values are unsigned */
677    blend_type.norm = TRUE;      /* values are in [0,1] or [-1,1] */
678    blend_type.width = 8;        /* 8-bit ubyte values */
679    blend_type.length = 16;      /* 16 elements per vector */
680
681    /* 
682     * Generate the function prototype. Any change here must be reflected in
683     * lp_jit.h's lp_jit_frag_func function pointer type, and vice-versa.
684     */
685
686    fs_elem_type = lp_build_elem_type(fs_type);
687    fs_vec_type = lp_build_vec_type(fs_type);
688    fs_int_vec_type = lp_build_int_vec_type(fs_type);
689
690    blend_vec_type = lp_build_vec_type(blend_type);
691    blend_int_vec_type = lp_build_int_vec_type(blend_type);
692
693    arg_types[0] = screen->context_ptr_type;            /* context */
694    arg_types[1] = LLVMInt32Type();                     /* x */
695    arg_types[2] = LLVMInt32Type();                     /* y */
696    arg_types[3] = LLVMFloatType();                     /* facing */
697    arg_types[4] = LLVMPointerType(fs_elem_type, 0);    /* a0 */
698    arg_types[5] = LLVMPointerType(fs_elem_type, 0);    /* dadx */
699    arg_types[6] = LLVMPointerType(fs_elem_type, 0);    /* dady */
700    arg_types[7] = LLVMPointerType(LLVMPointerType(blend_vec_type, 0), 0);  /* color */
701    arg_types[8] = LLVMPointerType(fs_int_vec_type, 0); /* depth */
702    arg_types[9] = LLVMInt32Type();                     /* c0 */
703    arg_types[10] = LLVMInt32Type();                    /* c1 */
704    arg_types[11] = LLVMInt32Type();                    /* c2 */
705    /* Note: the step arrays are built as int32[16] but we interpret
706     * them here as int32_vec4[4].
707     */
708    arg_types[12] = LLVMPointerType(int32_vec4_type, 0);/* step0 */
709    arg_types[13] = LLVMPointerType(int32_vec4_type, 0);/* step1 */
710    arg_types[14] = LLVMPointerType(int32_vec4_type, 0);/* step2 */
711
712    func_type = LLVMFunctionType(LLVMVoidType(), arg_types, Elements(arg_types), 0);
713
714    function = LLVMAddFunction(screen->module, "shader", func_type);
715    LLVMSetFunctionCallConv(function, LLVMCCallConv);
716
717    variant->function[do_tri_test] = function;
718
719
720    /* XXX: need to propagate noalias down into color param now we are
721     * passing a pointer-to-pointer?
722     */
723    for(i = 0; i < Elements(arg_types); ++i)
724       if(LLVMGetTypeKind(arg_types[i]) == LLVMPointerTypeKind)
725          LLVMAddAttribute(LLVMGetParam(function, i), LLVMNoAliasAttribute);
726
727    context_ptr  = LLVMGetParam(function, 0);
728    x            = LLVMGetParam(function, 1);
729    y            = LLVMGetParam(function, 2);
730    facing       = LLVMGetParam(function, 3);
731    a0_ptr       = LLVMGetParam(function, 4);
732    dadx_ptr     = LLVMGetParam(function, 5);
733    dady_ptr     = LLVMGetParam(function, 6);
734    color_ptr_ptr = LLVMGetParam(function, 7);
735    depth_ptr    = LLVMGetParam(function, 8);
736    c0           = LLVMGetParam(function, 9);
737    c1           = LLVMGetParam(function, 10);
738    c2           = LLVMGetParam(function, 11);
739    step0_ptr    = LLVMGetParam(function, 12);
740    step1_ptr    = LLVMGetParam(function, 13);
741    step2_ptr    = LLVMGetParam(function, 14);
742
743    lp_build_name(context_ptr, "context");
744    lp_build_name(x, "x");
745    lp_build_name(y, "y");
746    lp_build_name(a0_ptr, "a0");
747    lp_build_name(dadx_ptr, "dadx");
748    lp_build_name(dady_ptr, "dady");
749    lp_build_name(color_ptr_ptr, "color_ptr");
750    lp_build_name(depth_ptr, "depth");
751    lp_build_name(c0, "c0");
752    lp_build_name(c1, "c1");
753    lp_build_name(c2, "c2");
754    lp_build_name(step0_ptr, "step0");
755    lp_build_name(step1_ptr, "step1");
756    lp_build_name(step2_ptr, "step2");
757
758    /*
759     * Function body
760     */
761
762    block = LLVMAppendBasicBlock(function, "entry");
763    builder = LLVMCreateBuilder();
764    LLVMPositionBuilderAtEnd(builder, block);
765
766    generate_pos0(builder, x, y, &x0, &y0);
767
768    lp_build_interp_soa_init(&interp, 
769                             shader->base.tokens,
770                             key->flatshade,
771                             builder, fs_type,
772                             a0_ptr, dadx_ptr, dady_ptr,
773                             x0, y0);
774
775    /* code generated texture sampling */
776    sampler = lp_llvm_sampler_soa_create(key->sampler, context_ptr);
777
778    /* loop over quads in the block */
779    for(i = 0; i < num_fs; ++i) {
780       LLVMValueRef index = LLVMConstInt(LLVMInt32Type(), i, 0);
781       LLVMValueRef out_color[PIPE_MAX_COLOR_BUFS][NUM_CHANNELS];
782       LLVMValueRef depth_ptr_i;
783       int cbuf;
784
785       if(i != 0)
786          lp_build_interp_soa_update(&interp, i);
787
788       depth_ptr_i = LLVMBuildGEP(builder, depth_ptr, &index, 1, "");
789
790       generate_fs(lp, shader, key,
791                   builder,
792                   fs_type,
793                   context_ptr,
794                   i,
795                   &interp,
796                   sampler,
797                   &fs_mask[i], /* output */
798                   out_color,
799                   depth_ptr_i,
800                   facing,
801                   do_tri_test,
802                   c0, c1, c2,
803                   step0_ptr, step1_ptr, step2_ptr);
804
805       for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++)
806          for(chan = 0; chan < NUM_CHANNELS; ++chan)
807             fs_out_color[cbuf][chan][i] = out_color[cbuf][chan];
808    }
809
810    sampler->destroy(sampler);
811
812    /* Loop over color outputs / color buffers to do blending.
813     */
814    for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
815       LLVMValueRef color_ptr;
816       LLVMValueRef index = LLVMConstInt(LLVMInt32Type(), cbuf, 0);
817
818       /* 
819        * Convert the fs's output color and mask to fit to the blending type. 
820        */
821       for(chan = 0; chan < NUM_CHANNELS; ++chan) {
822          lp_build_conv(builder, fs_type, blend_type,
823                        fs_out_color[cbuf][chan], num_fs,
824                        &blend_in_color[chan], 1);
825          lp_build_name(blend_in_color[chan], "color%d.%c", cbuf, "rgba"[chan]);
826       }
827
828       lp_build_conv_mask(builder, fs_type, blend_type,
829                          fs_mask, num_fs,
830                          &blend_mask, 1);
831
832       color_ptr = LLVMBuildLoad(builder, 
833                                 LLVMBuildGEP(builder, color_ptr_ptr, &index, 1, ""),
834                                 "");
835       lp_build_name(color_ptr, "color_ptr%d", cbuf);
836
837       /*
838        * Blending.
839        */
840       generate_blend(&key->blend,
841                      builder,
842                      blend_type,
843                      context_ptr,
844                      blend_mask,
845                      blend_in_color,
846                      color_ptr);
847    }
848
849    LLVMBuildRetVoid(builder);
850
851    LLVMDisposeBuilder(builder);
852
853
854    /* Verify the LLVM IR.  If invalid, dump and abort */
855 #ifdef DEBUG
856    if(LLVMVerifyFunction(function, LLVMPrintMessageAction)) {
857       if (1)
858          LLVMDumpValue(function);
859       abort();
860    }
861 #endif
862
863    /* Apply optimizations to LLVM IR */
864    if (1)
865       LLVMRunFunctionPassManager(screen->pass, function);
866
867    if (LP_DEBUG & DEBUG_JIT) {
868       /* Print the LLVM IR to stderr */
869       LLVMDumpValue(function);
870       debug_printf("\n");
871    }
872
873    /*
874     * Translate the LLVM IR into machine code.
875     */
876    {
877       void *f = LLVMGetPointerToGlobal(screen->engine, function);
878
879       variant->jit_function[do_tri_test] = cast_voidptr_to_lp_jit_frag_func(f);
880
881       if (LP_DEBUG & DEBUG_ASM)
882          lp_disassemble(f);
883    }
884 }
885
886
887 static struct lp_fragment_shader_variant *
888 generate_variant(struct llvmpipe_context *lp,
889                  struct lp_fragment_shader *shader,
890                  const struct lp_fragment_shader_variant_key *key)
891 {
892    struct lp_fragment_shader_variant *variant;
893
894    if (LP_DEBUG & DEBUG_JIT) {
895       unsigned i;
896
897       tgsi_dump(shader->base.tokens, 0);
898       if(key->depth.enabled) {
899          debug_printf("depth.format = %s\n", util_format_name(key->zsbuf_format));
900          debug_printf("depth.func = %s\n", util_dump_func(key->depth.func, TRUE));
901          debug_printf("depth.writemask = %u\n", key->depth.writemask);
902       }
903       if(key->alpha.enabled) {
904          debug_printf("alpha.func = %s\n", util_dump_func(key->alpha.func, TRUE));
905          debug_printf("alpha.ref_value = %f\n", key->alpha.ref_value);
906       }
907       if(key->blend.logicop_enable) {
908          debug_printf("blend.logicop_func = %u\n", key->blend.logicop_func);
909       }
910       else if(key->blend.rt[0].blend_enable) {
911          debug_printf("blend.rgb_func = %s\n",   util_dump_blend_func  (key->blend.rt[0].rgb_func, TRUE));
912          debug_printf("rgb_src_factor = %s\n",   util_dump_blend_factor(key->blend.rt[0].rgb_src_factor, TRUE));
913          debug_printf("rgb_dst_factor = %s\n",   util_dump_blend_factor(key->blend.rt[0].rgb_dst_factor, TRUE));
914          debug_printf("alpha_func = %s\n",       util_dump_blend_func  (key->blend.rt[0].alpha_func, TRUE));
915          debug_printf("alpha_src_factor = %s\n", util_dump_blend_factor(key->blend.rt[0].alpha_src_factor, TRUE));
916          debug_printf("alpha_dst_factor = %s\n", util_dump_blend_factor(key->blend.rt[0].alpha_dst_factor, TRUE));
917       }
918       debug_printf("blend.colormask = 0x%x\n", key->blend.rt[0].colormask);
919       for(i = 0; i < PIPE_MAX_SAMPLERS; ++i) {
920          if(key->sampler[i].format) {
921             debug_printf("sampler[%u] = \n", i);
922             debug_printf("  .format = %s\n",
923                          util_format_name(key->sampler[i].format));
924             debug_printf("  .target = %s\n",
925                          util_dump_tex_target(key->sampler[i].target, TRUE));
926             debug_printf("  .pot = %u %u %u\n",
927                          key->sampler[i].pot_width,
928                          key->sampler[i].pot_height,
929                          key->sampler[i].pot_depth);
930             debug_printf("  .wrap = %s %s %s\n",
931                          util_dump_tex_wrap(key->sampler[i].wrap_s, TRUE),
932                          util_dump_tex_wrap(key->sampler[i].wrap_t, TRUE),
933                          util_dump_tex_wrap(key->sampler[i].wrap_r, TRUE));
934             debug_printf("  .min_img_filter = %s\n",
935                          util_dump_tex_filter(key->sampler[i].min_img_filter, TRUE));
936             debug_printf("  .min_mip_filter = %s\n",
937                          util_dump_tex_mipfilter(key->sampler[i].min_mip_filter, TRUE));
938             debug_printf("  .mag_img_filter = %s\n",
939                          util_dump_tex_filter(key->sampler[i].mag_img_filter, TRUE));
940             if(key->sampler[i].compare_mode != PIPE_TEX_COMPARE_NONE)
941                debug_printf("  .compare_func = %s\n", util_dump_func(key->sampler[i].compare_func, TRUE));
942             debug_printf("  .normalized_coords = %u\n", key->sampler[i].normalized_coords);
943          }
944       }
945    }
946
947    variant = CALLOC_STRUCT(lp_fragment_shader_variant);
948    if(!variant)
949       return NULL;
950
951    variant->shader = shader;
952    memcpy(&variant->key, key, sizeof *key);
953
954    generate_fragment(lp, shader, variant, 0);
955    generate_fragment(lp, shader, variant, 1);
956
957    /* insert new variant into linked list */
958    variant->next = shader->variants;
959    shader->variants = variant;
960
961    return variant;
962 }
963
964
965 void *
966 llvmpipe_create_fs_state(struct pipe_context *pipe,
967                          const struct pipe_shader_state *templ)
968 {
969    struct lp_fragment_shader *shader;
970
971    shader = CALLOC_STRUCT(lp_fragment_shader);
972    if (!shader)
973       return NULL;
974
975    /* get/save the summary info for this shader */
976    tgsi_scan_shader(templ->tokens, &shader->info);
977
978    /* we need to keep a local copy of the tokens */
979    shader->base.tokens = tgsi_dup_tokens(templ->tokens);
980
981    return shader;
982 }
983
984
985 void
986 llvmpipe_bind_fs_state(struct pipe_context *pipe, void *fs)
987 {
988    struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
989
990    if (llvmpipe->fs == fs)
991       return;
992
993    draw_flush(llvmpipe->draw);
994
995    llvmpipe->fs = fs;
996
997    llvmpipe->dirty |= LP_NEW_FS;
998 }
999
1000
1001 void
1002 llvmpipe_delete_fs_state(struct pipe_context *pipe, void *fs)
1003 {
1004    struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
1005    struct llvmpipe_screen *screen = llvmpipe_screen(pipe->screen);
1006    struct lp_fragment_shader *shader = fs;
1007    struct lp_fragment_shader_variant *variant;
1008
1009    assert(fs != llvmpipe->fs);
1010    (void) llvmpipe;
1011
1012    /*
1013     * XXX: we need to flush the context until we have some sort of reference
1014     * counting in fragment shaders as they may still be binned
1015     */
1016    draw_flush(llvmpipe->draw);
1017    lp_setup_flush(llvmpipe->setup, 0);
1018
1019    variant = shader->variants;
1020    while(variant) {
1021       struct lp_fragment_shader_variant *next = variant->next;
1022       unsigned i;
1023
1024       for (i = 0; i < Elements(variant->function); i++) {
1025          if (variant->function[i]) {
1026             if (variant->jit_function[i])
1027                LLVMFreeMachineCodeForFunction(screen->engine,
1028                                               variant->function[i]);
1029             LLVMDeleteFunction(variant->function[i]);
1030          }
1031       }
1032
1033       FREE(variant);
1034
1035       variant = next;
1036    }
1037
1038    FREE((void *) shader->base.tokens);
1039    FREE(shader);
1040 }
1041
1042
1043
1044 void
1045 llvmpipe_set_constant_buffer(struct pipe_context *pipe,
1046                              uint shader, uint index,
1047                              struct pipe_buffer *constants)
1048 {
1049    struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
1050    unsigned size = constants ? constants->size : 0;
1051    const void *data = constants ? llvmpipe_buffer(constants)->data : NULL;
1052
1053    assert(shader < PIPE_SHADER_TYPES);
1054    assert(index == 0);
1055
1056    if(llvmpipe->constants[shader] == constants)
1057       return;
1058
1059    draw_flush(llvmpipe->draw);
1060
1061    /* note: reference counting */
1062    pipe_buffer_reference(&llvmpipe->constants[shader], constants);
1063
1064    if(shader == PIPE_SHADER_VERTEX) {
1065       draw_set_mapped_constant_buffer(llvmpipe->draw, PIPE_SHADER_VERTEX, 0,
1066                                       data, size);
1067    }
1068
1069    llvmpipe->dirty |= LP_NEW_CONSTANTS;
1070 }
1071
1072
1073 /**
1074  * We need to generate several variants of the fragment pipeline to match
1075  * all the combinations of the contributing state atoms.
1076  *
1077  * TODO: there is actually no reason to tie this to context state -- the
1078  * generated code could be cached globally in the screen.
1079  */
1080 static void
1081 make_variant_key(struct llvmpipe_context *lp,
1082                  struct lp_fragment_shader *shader,
1083                  struct lp_fragment_shader_variant_key *key)
1084 {
1085    unsigned i;
1086
1087    memset(key, 0, sizeof *key);
1088
1089    if (lp->framebuffer.zsbuf) {
1090       if (lp->depth_stencil->depth.enabled) {
1091          key->zsbuf_format = lp->framebuffer.zsbuf->format;
1092          memcpy(&key->depth, &lp->depth_stencil->depth, sizeof key->depth);
1093       }
1094       if (lp->depth_stencil->stencil[0].enabled) {
1095          key->zsbuf_format = lp->framebuffer.zsbuf->format;
1096          memcpy(&key->stencil, &lp->depth_stencil->stencil, sizeof key->stencil);
1097       }
1098    }
1099
1100    key->alpha.enabled = lp->depth_stencil->alpha.enabled;
1101    if(key->alpha.enabled)
1102       key->alpha.func = lp->depth_stencil->alpha.func;
1103    /* alpha.ref_value is passed in jit_context */
1104
1105    key->flatshade = lp->rasterizer->flatshade;
1106    key->scissor = lp->rasterizer->scissor;
1107
1108    if (lp->framebuffer.nr_cbufs) {
1109       memcpy(&key->blend, lp->blend, sizeof key->blend);
1110    }
1111
1112    key->nr_cbufs = lp->framebuffer.nr_cbufs;
1113    for (i = 0; i < lp->framebuffer.nr_cbufs; i++) {
1114       const struct util_format_description *format_desc;
1115       unsigned chan;
1116
1117       format_desc = util_format_description(lp->framebuffer.cbufs[i]->format);
1118       assert(format_desc->layout == UTIL_FORMAT_COLORSPACE_RGB ||
1119              format_desc->layout == UTIL_FORMAT_COLORSPACE_SRGB);
1120
1121       /* mask out color channels not present in the color buffer.
1122        * Should be simple to incorporate per-cbuf writemasks:
1123        */
1124       for(chan = 0; chan < 4; ++chan) {
1125          enum util_format_swizzle swizzle = format_desc->swizzle[chan];
1126
1127          if(swizzle <= UTIL_FORMAT_SWIZZLE_W)
1128             key->blend.rt[0].colormask |= (1 << chan);
1129       }
1130    }
1131
1132    for(i = 0; i < PIPE_MAX_SAMPLERS; ++i)
1133       if(shader->info.file_mask[TGSI_FILE_SAMPLER] & (1 << i))
1134          lp_sampler_static_state(&key->sampler[i], lp->fragment_sampler_views[i]->texture, lp->sampler[i]);
1135 }
1136
1137
1138 /**
1139  * Update fragment state.  This is called just prior to drawing
1140  * something when some fragment-related state has changed.
1141  */
1142 void 
1143 llvmpipe_update_fs(struct llvmpipe_context *lp)
1144 {
1145    struct lp_fragment_shader *shader = lp->fs;
1146    struct lp_fragment_shader_variant_key key;
1147    struct lp_fragment_shader_variant *variant;
1148    boolean opaque;
1149
1150    make_variant_key(lp, shader, &key);
1151
1152    variant = shader->variants;
1153    while(variant) {
1154       if(memcmp(&variant->key, &key, sizeof key) == 0)
1155          break;
1156
1157       variant = variant->next;
1158    }
1159
1160    if (!variant) {
1161       int64_t t0, t1;
1162       int64_t dt;
1163       t0 = os_time_get();
1164
1165       variant = generate_variant(lp, shader, &key);
1166
1167       t1 = os_time_get();
1168       dt = t1 - t0;
1169       LP_COUNT_ADD(llvm_compile_time, dt);
1170       LP_COUNT_ADD(nr_llvm_compiles, 2);  /* emit vs. omit in/out test */
1171    }
1172
1173    shader->current = variant;
1174
1175    /* TODO: put this in the variant */
1176    /* TODO: most of these can be relaxed, in particular the colormask */
1177    opaque = !key.blend.logicop_enable &&
1178             !key.blend.rt[0].blend_enable &&
1179             key.blend.rt[0].colormask == 0xf &&
1180             !key.stencil[0].enabled &&
1181             !key.alpha.enabled &&
1182             !key.depth.enabled &&
1183             !key.scissor &&
1184             !shader->info.uses_kill
1185             ? TRUE : FALSE;
1186
1187    lp_setup_set_fs_functions(lp->setup, 
1188                              shader->current->jit_function[RAST_WHOLE],
1189                              shader->current->jit_function[RAST_EDGE_TEST],
1190                              opaque);
1191 }