swr_shader.cpp revision b8e80941
1/****************************************************************************
2 * Copyright (C) 2015 Intel Corporation.   All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 ***************************************************************************/
23
24// llvm redefines DEBUG
25#pragma push_macro("DEBUG")
26#undef DEBUG
27#include "JitManager.h"
28#include "llvm-c/Core.h"
29#include "llvm/Support/CBindingWrapping.h"
30#include "llvm/IR/LegacyPassManager.h"
31#pragma pop_macro("DEBUG")
32
33#include "state.h"
34#include "gen_state_llvm.h"
35#include "builder.h"
36#include "functionpasses/passes.h"
37
38#include "tgsi/tgsi_strings.h"
39#include "util/u_format.h"
40#include "util/u_prim.h"
41#include "gallivm/lp_bld_init.h"
42#include "gallivm/lp_bld_flow.h"
43#include "gallivm/lp_bld_struct.h"
44#include "gallivm/lp_bld_tgsi.h"
45
46#include "swr_context.h"
47#include "gen_swr_context_llvm.h"
48#include "swr_resource.h"
49#include "swr_state.h"
50#include "swr_screen.h"
51
52using namespace SwrJit;
53using namespace llvm;
54
55static unsigned
56locate_linkage(ubyte name, ubyte index, struct tgsi_shader_info *info);
57
58bool operator==(const swr_jit_fs_key &lhs, const swr_jit_fs_key &rhs)
59{
60   return !memcmp(&lhs, &rhs, sizeof(lhs));
61}
62
63bool operator==(const swr_jit_vs_key &lhs, const swr_jit_vs_key &rhs)
64{
65   return !memcmp(&lhs, &rhs, sizeof(lhs));
66}
67
68bool operator==(const swr_jit_fetch_key &lhs, const swr_jit_fetch_key &rhs)
69{
70   return !memcmp(&lhs, &rhs, sizeof(lhs));
71}
72
73bool operator==(const swr_jit_gs_key &lhs, const swr_jit_gs_key &rhs)
74{
75   return !memcmp(&lhs, &rhs, sizeof(lhs));
76}
77
78static void
79swr_generate_sampler_key(const struct lp_tgsi_info &info,
80                         struct swr_context *ctx,
81                         enum pipe_shader_type shader_type,
82                         struct swr_jit_sampler_key &key)
83{
84   key.nr_samplers = info.base.file_max[TGSI_FILE_SAMPLER] + 1;
85
86   for (unsigned i = 0; i < key.nr_samplers; i++) {
87      if (info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
88         lp_sampler_static_sampler_state(
89            &key.sampler[i].sampler_state,
90            ctx->samplers[shader_type][i]);
91      }
92   }
93
94   /*
95    * XXX If TGSI_FILE_SAMPLER_VIEW exists assume all texture opcodes
96    * are dx10-style? Can't really have mixed opcodes, at least not
97    * if we want to skip the holes here (without rescanning tgsi).
98    */
99   if (info.base.file_max[TGSI_FILE_SAMPLER_VIEW] != -1) {
100      key.nr_sampler_views =
101         info.base.file_max[TGSI_FILE_SAMPLER_VIEW] + 1;
102      for (unsigned i = 0; i < key.nr_sampler_views; i++) {
103         if (info.base.file_mask[TGSI_FILE_SAMPLER_VIEW] & (1u << (i & 31))) {
104            const struct pipe_sampler_view *view =
105               ctx->sampler_views[shader_type][i];
106            lp_sampler_static_texture_state(
107               &key.sampler[i].texture_state, view);
108            if (view) {
109               struct swr_resource *swr_res = swr_resource(view->texture);
110               const struct util_format_description *desc =
111                  util_format_description(view->format);
112               if (swr_res->has_depth && swr_res->has_stencil &&
113                   !util_format_has_depth(desc))
114                  key.sampler[i].texture_state.format = PIPE_FORMAT_S8_UINT;
115            }
116         }
117      }
118   } else {
119      key.nr_sampler_views = key.nr_samplers;
120      for (unsigned i = 0; i < key.nr_sampler_views; i++) {
121         if (info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
122            const struct pipe_sampler_view *view =
123               ctx->sampler_views[shader_type][i];
124            lp_sampler_static_texture_state(
125               &key.sampler[i].texture_state, view);
126            if (view) {
127               struct swr_resource *swr_res = swr_resource(view->texture);
128               const struct util_format_description *desc =
129                  util_format_description(view->format);
130               if (swr_res->has_depth && swr_res->has_stencil &&
131                   !util_format_has_depth(desc))
132                  key.sampler[i].texture_state.format = PIPE_FORMAT_S8_UINT;
133            }
134         }
135      }
136   }
137}
138
139void
140swr_generate_fs_key(struct swr_jit_fs_key &key,
141                    struct swr_context *ctx,
142                    swr_fragment_shader *swr_fs)
143{
144   memset(&key, 0, sizeof(key));
145
146   key.nr_cbufs = ctx->framebuffer.nr_cbufs;
147   key.light_twoside = ctx->rasterizer->light_twoside;
148   key.sprite_coord_enable = ctx->rasterizer->sprite_coord_enable;
149
150   struct tgsi_shader_info *pPrevShader;
151   if (ctx->gs)
152      pPrevShader = &ctx->gs->info.base;
153   else
154      pPrevShader = &ctx->vs->info.base;
155
156   memcpy(&key.vs_output_semantic_name,
157          &pPrevShader->output_semantic_name,
158          sizeof(key.vs_output_semantic_name));
159   memcpy(&key.vs_output_semantic_idx,
160          &pPrevShader->output_semantic_index,
161          sizeof(key.vs_output_semantic_idx));
162
163   swr_generate_sampler_key(swr_fs->info, ctx, PIPE_SHADER_FRAGMENT, key);
164
165   key.poly_stipple_enable = ctx->rasterizer->poly_stipple_enable &&
166      ctx->poly_stipple.prim_is_poly;
167}
168
169void
170swr_generate_vs_key(struct swr_jit_vs_key &key,
171                    struct swr_context *ctx,
172                    swr_vertex_shader *swr_vs)
173{
174   memset(&key, 0, sizeof(key));
175
176   key.clip_plane_mask =
177      swr_vs->info.base.clipdist_writemask ?
178      swr_vs->info.base.clipdist_writemask & ctx->rasterizer->clip_plane_enable :
179      ctx->rasterizer->clip_plane_enable;
180
181   swr_generate_sampler_key(swr_vs->info, ctx, PIPE_SHADER_VERTEX, key);
182}
183
184void
185swr_generate_fetch_key(struct swr_jit_fetch_key &key,
186                       struct swr_vertex_element_state *velems)
187{
188   memset(&key, 0, sizeof(key));
189
190   key.fsState = velems->fsState;
191}
192
193void
194swr_generate_gs_key(struct swr_jit_gs_key &key,
195                    struct swr_context *ctx,
196                    swr_geometry_shader *swr_gs)
197{
198   memset(&key, 0, sizeof(key));
199
200   struct tgsi_shader_info *pPrevShader = &ctx->vs->info.base;
201
202   memcpy(&key.vs_output_semantic_name,
203          &pPrevShader->output_semantic_name,
204          sizeof(key.vs_output_semantic_name));
205   memcpy(&key.vs_output_semantic_idx,
206          &pPrevShader->output_semantic_index,
207          sizeof(key.vs_output_semantic_idx));
208
209   swr_generate_sampler_key(swr_gs->info, ctx, PIPE_SHADER_GEOMETRY, key);
210}
211
212struct BuilderSWR : public Builder {
213   BuilderSWR(JitManager *pJitMgr, const char *pName)
214      : Builder(pJitMgr)
215   {
216      pJitMgr->SetupNewModule();
217      gallivm = gallivm_create(pName, wrap(&JM()->mContext));
218      pJitMgr->mpCurrentModule = unwrap(gallivm->module);
219   }
220
221   ~BuilderSWR() {
222      gallivm_free_ir(gallivm);
223   }
224
225   void WriteVS(Value *pVal, Value *pVsContext, Value *pVtxOutput,
226                unsigned slot, unsigned channel);
227
228   struct gallivm_state *gallivm;
229   PFN_VERTEX_FUNC CompileVS(struct swr_context *ctx, swr_jit_vs_key &key);
230   PFN_PIXEL_KERNEL CompileFS(struct swr_context *ctx, swr_jit_fs_key &key);
231   PFN_GS_FUNC CompileGS(struct swr_context *ctx, swr_jit_gs_key &key);
232
233   LLVMValueRef
234   swr_gs_llvm_fetch_input(const struct lp_build_tgsi_gs_iface *gs_iface,
235                           struct lp_build_tgsi_context * bld_base,
236                           boolean is_vindex_indirect,
237                           LLVMValueRef vertex_index,
238                           boolean is_aindex_indirect,
239                           LLVMValueRef attrib_index,
240                           LLVMValueRef swizzle_index);
241   void
242   swr_gs_llvm_emit_vertex(const struct lp_build_tgsi_gs_iface *gs_base,
243                           struct lp_build_tgsi_context * bld_base,
244                           LLVMValueRef (*outputs)[4],
245                           LLVMValueRef emitted_vertices_vec);
246
247   void
248   swr_gs_llvm_end_primitive(const struct lp_build_tgsi_gs_iface *gs_base,
249                             struct lp_build_tgsi_context * bld_base,
250                             LLVMValueRef verts_per_prim_vec,
251                             LLVMValueRef emitted_prims_vec);
252
253   void
254   swr_gs_llvm_epilogue(const struct lp_build_tgsi_gs_iface *gs_base,
255                        struct lp_build_tgsi_context * bld_base,
256                        LLVMValueRef total_emitted_vertices_vec,
257                        LLVMValueRef emitted_prims_vec);
258
259};
260
261struct swr_gs_llvm_iface {
262   struct lp_build_tgsi_gs_iface base;
263   struct tgsi_shader_info *info;
264
265   BuilderSWR *pBuilder;
266
267   Value *pGsCtx;
268   SWR_GS_STATE *pGsState;
269   uint32_t num_outputs;
270   uint32_t num_verts_per_prim;
271
272   Value *pVtxAttribMap;
273};
274
275// trampoline functions so we can use the builder llvm construction methods
276static LLVMValueRef
277swr_gs_llvm_fetch_input(const struct lp_build_tgsi_gs_iface *gs_iface,
278                           struct lp_build_tgsi_context * bld_base,
279                           boolean is_vindex_indirect,
280                           LLVMValueRef vertex_index,
281                           boolean is_aindex_indirect,
282                           LLVMValueRef attrib_index,
283                           LLVMValueRef swizzle_index)
284{
285    swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_iface;
286
287    return iface->pBuilder->swr_gs_llvm_fetch_input(gs_iface, bld_base,
288                                                   is_vindex_indirect,
289                                                   vertex_index,
290                                                   is_aindex_indirect,
291                                                   attrib_index,
292                                                   swizzle_index);
293}
294
295static void
296swr_gs_llvm_emit_vertex(const struct lp_build_tgsi_gs_iface *gs_base,
297                           struct lp_build_tgsi_context * bld_base,
298                           LLVMValueRef (*outputs)[4],
299                           LLVMValueRef emitted_vertices_vec)
300{
301    swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_base;
302
303    iface->pBuilder->swr_gs_llvm_emit_vertex(gs_base, bld_base,
304                                            outputs,
305                                            emitted_vertices_vec);
306}
307
308static void
309swr_gs_llvm_end_primitive(const struct lp_build_tgsi_gs_iface *gs_base,
310                             struct lp_build_tgsi_context * bld_base,
311                             LLVMValueRef verts_per_prim_vec,
312                             LLVMValueRef emitted_prims_vec)
313{
314    swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_base;
315
316    iface->pBuilder->swr_gs_llvm_end_primitive(gs_base, bld_base,
317                                              verts_per_prim_vec,
318                                              emitted_prims_vec);
319}
320
321static void
322swr_gs_llvm_epilogue(const struct lp_build_tgsi_gs_iface *gs_base,
323                        struct lp_build_tgsi_context * bld_base,
324                        LLVMValueRef total_emitted_vertices_vec,
325                        LLVMValueRef emitted_prims_vec)
326{
327    swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_base;
328
329    iface->pBuilder->swr_gs_llvm_epilogue(gs_base, bld_base,
330                                         total_emitted_vertices_vec,
331                                         emitted_prims_vec);
332}
333
334LLVMValueRef
335BuilderSWR::swr_gs_llvm_fetch_input(const struct lp_build_tgsi_gs_iface *gs_iface,
336                           struct lp_build_tgsi_context * bld_base,
337                           boolean is_vindex_indirect,
338                           LLVMValueRef vertex_index,
339                           boolean is_aindex_indirect,
340                           LLVMValueRef attrib_index,
341                           LLVMValueRef swizzle_index)
342{
343    swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_iface;
344    Value *vert_index = unwrap(vertex_index);
345    Value *attr_index = unwrap(attrib_index);
346
347    IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
348
349    if (is_vindex_indirect || is_aindex_indirect) {
350       int i;
351       Value *res = unwrap(bld_base->base.zero);
352       struct lp_type type = bld_base->base.type;
353
354       for (i = 0; i < type.length; i++) {
355          Value *vert_chan_index = vert_index;
356          Value *attr_chan_index = attr_index;
357
358          if (is_vindex_indirect) {
359             vert_chan_index = VEXTRACT(vert_index, C(i));
360          }
361          if (is_aindex_indirect) {
362             attr_chan_index = VEXTRACT(attr_index, C(i));
363          }
364
365          Value *attrib =
366             LOAD(GEP(iface->pVtxAttribMap, {C(0), attr_chan_index}));
367
368          Value *pVertex = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_pVerts});
369          Value *pInputVertStride = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_inputVertStride});
370
371          Value *pVector = ADD(MUL(vert_chan_index, pInputVertStride), attrib);
372          Value *pInput = LOAD(GEP(pVertex, {pVector, unwrap(swizzle_index)}));
373
374          Value *value = VEXTRACT(pInput, C(i));
375          res = VINSERT(res, value, C(i));
376       }
377
378       return wrap(res);
379    } else {
380       Value *attrib = LOAD(GEP(iface->pVtxAttribMap, {C(0), attr_index}));
381
382       Value *pVertex = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_pVerts});
383       Value *pInputVertStride = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_inputVertStride});
384
385       Value *pVector = ADD(MUL(vert_index, pInputVertStride), attrib);
386
387       Value *pInput = LOAD(GEP(pVertex, {pVector, unwrap(swizzle_index)}));
388
389       return wrap(pInput);
390    }
391}
392
393// GS output stream layout
394#define VERTEX_COUNT_SIZE 32
395#define CONTROL_HEADER_SIZE (8*32)
396
397void
398BuilderSWR::swr_gs_llvm_emit_vertex(const struct lp_build_tgsi_gs_iface *gs_base,
399                           struct lp_build_tgsi_context * bld_base,
400                           LLVMValueRef (*outputs)[4],
401                           LLVMValueRef emitted_vertices_vec)
402{
403    swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_base;
404
405    IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
406
407    const uint32_t headerSize = VERTEX_COUNT_SIZE + CONTROL_HEADER_SIZE;
408    const uint32_t attribSize = 4 * sizeof(float);
409    const uint32_t vertSize = attribSize * SWR_VTX_NUM_SLOTS;
410    Value *pVertexOffset = MUL(unwrap(emitted_vertices_vec), VIMMED1(vertSize));
411
412    Value *vMask = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_mask});
413    Value *vMask1 = TRUNC(vMask, VectorType::get(mInt1Ty, mVWidth));
414
415    Value *pStack = STACKSAVE();
416    Value *pTmpPtr = ALLOCA(mFP32Ty, C(4)); // used for dummy write for lane masking
417
418    for (uint32_t attrib = 0; attrib < iface->num_outputs; ++attrib) {
419       uint32_t attribSlot = attrib;
420       uint32_t sgvChannel = 0;
421       if (iface->info->output_semantic_name[attrib] == TGSI_SEMANTIC_PSIZE) {
422          attribSlot = VERTEX_SGV_SLOT;
423          sgvChannel = VERTEX_SGV_POINT_SIZE_COMP;
424       } else if (iface->info->output_semantic_name[attrib] == TGSI_SEMANTIC_LAYER) {
425          attribSlot = VERTEX_SGV_SLOT;
426          sgvChannel = VERTEX_SGV_RTAI_COMP;
427       } else if (iface->info->output_semantic_name[attrib] == TGSI_SEMANTIC_POSITION) {
428          attribSlot = VERTEX_POSITION_SLOT;
429       } else {
430          attribSlot = VERTEX_ATTRIB_START_SLOT + attrib;
431          if (iface->info->writes_position) {
432             attribSlot--;
433          }
434       }
435
436       Value *pOutputOffset = ADD(pVertexOffset, VIMMED1(headerSize + attribSize * attribSlot)); // + sgvChannel ?
437
438       for (uint32_t lane = 0; lane < mVWidth; ++lane) {
439          Value *pLaneOffset = VEXTRACT(pOutputOffset, C(lane));
440          Value *pStream = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_pStreams, lane});
441          Value *pStreamOffset = GEP(pStream, pLaneOffset);
442          pStreamOffset = BITCAST(pStreamOffset, mFP32PtrTy);
443
444          Value *pLaneMask = VEXTRACT(vMask1, C(lane));
445          pStreamOffset = SELECT(pLaneMask, pStreamOffset, pTmpPtr);
446
447          for (uint32_t channel = 0; channel < 4; ++channel) {
448             Value *vData;
449
450             if (attribSlot == VERTEX_SGV_SLOT)
451                vData = LOAD(unwrap(outputs[attrib][0]));
452             else
453                vData = LOAD(unwrap(outputs[attrib][channel]));
454
455             if (attribSlot != VERTEX_SGV_SLOT ||
456                 sgvChannel == channel) {
457                vData = VEXTRACT(vData, C(lane));
458                STORE(vData, pStreamOffset);
459             }
460             pStreamOffset = GEP(pStreamOffset, C(1));
461          }
462       }
463    }
464
465    STACKRESTORE(pStack);
466}
467
468void
469BuilderSWR::swr_gs_llvm_end_primitive(const struct lp_build_tgsi_gs_iface *gs_base,
470                             struct lp_build_tgsi_context * bld_base,
471                             LLVMValueRef verts_per_prim_vec,
472                             LLVMValueRef emitted_prims_vec)
473{
474    swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_base;
475
476    IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
477
478    Value *vMask = LOAD(iface->pGsCtx, { 0, SWR_GS_CONTEXT_mask });
479    Value *vMask1 = TRUNC(vMask, VectorType::get(mInt1Ty, 8));
480
481    uint32_t vertsPerPrim = iface->num_verts_per_prim;
482
483    Value *vCount =
484       ADD(MUL(unwrap(emitted_prims_vec), VIMMED1(vertsPerPrim)),
485           unwrap(verts_per_prim_vec));
486
487    struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
488    vCount = LOAD(unwrap(bld->total_emitted_vertices_vec_ptr));
489
490    struct lp_exec_mask *exec_mask = &bld->exec_mask;
491    Value *mask = unwrap(lp_build_mask_value(bld->mask));
492    if (exec_mask->has_mask)
493       mask = AND(mask, unwrap(exec_mask->exec_mask));
494
495    Value *cmpMask = VMASK(ICMP_NE(unwrap(verts_per_prim_vec), VIMMED1(0)));
496    mask = AND(mask, cmpMask);
497    vMask1 = TRUNC(mask, VectorType::get(mInt1Ty, 8));
498
499    vCount = SUB(vCount, VIMMED1(1));
500    Value *vOffset = ADD(UDIV(vCount, VIMMED1(8)), VIMMED1(VERTEX_COUNT_SIZE));
501    Value *vValue = SHL(VIMMED1(1), UREM(vCount, VIMMED1(8)));
502
503    vValue = TRUNC(vValue, VectorType::get(mInt8Ty, 8));
504
505    Value *pStack = STACKSAVE();
506    Value *pTmpPtr = ALLOCA(mInt8Ty, C(4)); // used for dummy read/write for lane masking
507
508    for (uint32_t lane = 0; lane < mVWidth; ++lane) {
509       Value *vLaneOffset = VEXTRACT(vOffset, C(lane));
510       Value *pStream = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_pStreams, lane});
511       Value *pStreamOffset = GEP(pStream, vLaneOffset);
512
513       Value *pLaneMask = VEXTRACT(vMask1, C(lane));
514       pStreamOffset = SELECT(pLaneMask, pStreamOffset, pTmpPtr);
515
516       Value *vVal = LOAD(pStreamOffset);
517       vVal = OR(vVal, VEXTRACT(vValue, C(lane)));
518       STORE(vVal, pStreamOffset);
519    }
520
521    STACKRESTORE(pStack);
522}
523
524void
525BuilderSWR::swr_gs_llvm_epilogue(const struct lp_build_tgsi_gs_iface *gs_base,
526                        struct lp_build_tgsi_context * bld_base,
527                        LLVMValueRef total_emitted_vertices_vec,
528                        LLVMValueRef emitted_prims_vec)
529{
530   swr_gs_llvm_iface *iface = (swr_gs_llvm_iface*)gs_base;
531
532   IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
533
534   // Store emit count to each output stream in the first DWORD
535   for (uint32_t lane = 0; lane < mVWidth; ++lane)
536   {
537      Value* pStream = LOAD(iface->pGsCtx, {0, SWR_GS_CONTEXT_pStreams, lane});
538      pStream = BITCAST(pStream, mInt32PtrTy);
539      Value* pLaneCount = VEXTRACT(unwrap(total_emitted_vertices_vec), C(lane));
540      STORE(pLaneCount, pStream);
541   }
542}
543
544PFN_GS_FUNC
545BuilderSWR::CompileGS(struct swr_context *ctx, swr_jit_gs_key &key)
546{
547   SWR_GS_STATE *pGS = &ctx->gs->gsState;
548   struct tgsi_shader_info *info = &ctx->gs->info.base;
549
550   memset(pGS, 0, sizeof(*pGS));
551
552   pGS->gsEnable = true;
553
554   pGS->numInputAttribs = info->num_inputs;
555   pGS->outputTopology =
556      swr_convert_prim_topology(info->properties[TGSI_PROPERTY_GS_OUTPUT_PRIM]);
557   pGS->maxNumVerts = info->properties[TGSI_PROPERTY_GS_MAX_OUTPUT_VERTICES];
558   pGS->instanceCount = info->properties[TGSI_PROPERTY_GS_INVOCATIONS];
559
560   // XXX: single stream for now...
561   pGS->isSingleStream = true;
562   pGS->singleStreamID = 0;
563
564   pGS->vertexAttribOffset = VERTEX_ATTRIB_START_SLOT; // TODO: optimize
565   pGS->srcVertexAttribOffset = VERTEX_ATTRIB_START_SLOT; // TODO: optimize
566   pGS->inputVertStride = pGS->numInputAttribs + pGS->vertexAttribOffset;
567   pGS->outputVertexSize = SWR_VTX_NUM_SLOTS;
568   pGS->controlDataSize = 8; // GS ouputs max of 8 32B units
569   pGS->controlDataOffset = VERTEX_COUNT_SIZE;
570   pGS->outputVertexOffset = pGS->controlDataOffset + CONTROL_HEADER_SIZE;
571
572   pGS->allocationSize =
573      VERTEX_COUNT_SIZE + // vertex count
574      CONTROL_HEADER_SIZE + // control header
575      (SWR_VTX_NUM_SLOTS * 16) * // sizeof vertex
576      pGS->maxNumVerts; // num verts
577
578   struct swr_geometry_shader *gs = ctx->gs;
579
580   LLVMValueRef inputs[PIPE_MAX_SHADER_INPUTS][TGSI_NUM_CHANNELS];
581   LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
582
583   memset(outputs, 0, sizeof(outputs));
584
585   AttrBuilder attrBuilder;
586   attrBuilder.addStackAlignmentAttr(JM()->mVWidth * sizeof(float));
587
588   std::vector<Type *> gsArgs{PointerType::get(Gen_swr_draw_context(JM()), 0),
589                              PointerType::get(mInt8Ty, 0),
590                              PointerType::get(Gen_SWR_GS_CONTEXT(JM()), 0)};
591   FunctionType *vsFuncType =
592      FunctionType::get(Type::getVoidTy(JM()->mContext), gsArgs, false);
593
594   // create new vertex shader function
595   auto pFunction = Function::Create(vsFuncType,
596                                     GlobalValue::ExternalLinkage,
597                                     "GS",
598                                     JM()->mpCurrentModule);
599#if HAVE_LLVM < 0x0500
600   AttributeSet attrSet = AttributeSet::get(
601      JM()->mContext, AttributeSet::FunctionIndex, attrBuilder);
602   pFunction->addAttributes(AttributeSet::FunctionIndex, attrSet);
603#else
604   pFunction->addAttributes(AttributeList::FunctionIndex, attrBuilder);
605#endif
606
607   BasicBlock *block = BasicBlock::Create(JM()->mContext, "entry", pFunction);
608   IRB()->SetInsertPoint(block);
609   LLVMPositionBuilderAtEnd(gallivm->builder, wrap(block));
610
611   auto argitr = pFunction->arg_begin();
612   Value *hPrivateData = &*argitr++;
613   hPrivateData->setName("hPrivateData");
614   Value *pWorkerData = &*argitr++;
615   pWorkerData->setName("pWorkerData");
616   Value *pGsCtx = &*argitr++;
617   pGsCtx->setName("gsCtx");
618
619   Value *consts_ptr =
620      GEP(hPrivateData, {C(0), C(swr_draw_context_constantGS)});
621   consts_ptr->setName("gs_constants");
622   Value *const_sizes_ptr =
623      GEP(hPrivateData, {0, swr_draw_context_num_constantsGS});
624   const_sizes_ptr->setName("num_gs_constants");
625
626   struct lp_build_sampler_soa *sampler =
627      swr_sampler_soa_create(key.sampler, PIPE_SHADER_GEOMETRY);
628
629   struct lp_bld_tgsi_system_values system_values;
630   memset(&system_values, 0, sizeof(system_values));
631   system_values.prim_id = wrap(LOAD(pGsCtx, {0, SWR_GS_CONTEXT_PrimitiveID}));
632   system_values.instance_id = wrap(LOAD(pGsCtx, {0, SWR_GS_CONTEXT_InstanceID}));
633
634   std::vector<Constant*> mapConstants;
635   Value *vtxAttribMap = ALLOCA(ArrayType::get(mInt32Ty, PIPE_MAX_SHADER_INPUTS));
636   for (unsigned slot = 0; slot < info->num_inputs; slot++) {
637      ubyte semantic_name = info->input_semantic_name[slot];
638      ubyte semantic_idx = info->input_semantic_index[slot];
639
640      unsigned vs_slot = locate_linkage(semantic_name, semantic_idx, &ctx->vs->info.base);
641
642      vs_slot += VERTEX_ATTRIB_START_SLOT;
643
644      if (ctx->vs->info.base.output_semantic_name[0] == TGSI_SEMANTIC_POSITION)
645         vs_slot--;
646
647      if (semantic_name == TGSI_SEMANTIC_POSITION)
648         vs_slot = VERTEX_POSITION_SLOT;
649
650      STORE(C(vs_slot), vtxAttribMap, {0, slot});
651      mapConstants.push_back(C(vs_slot));
652   }
653
654   struct lp_build_mask_context mask;
655   Value *mask_val = LOAD(pGsCtx, {0, SWR_GS_CONTEXT_mask}, "gsMask");
656   lp_build_mask_begin(&mask, gallivm,
657                       lp_type_float_vec(32, 32 * 8), wrap(mask_val));
658
659   // zero out cut buffer so we can load/modify/store bits
660   for (uint32_t lane = 0; lane < mVWidth; ++lane)
661   {
662      Value* pStream = LOAD(pGsCtx, {0, SWR_GS_CONTEXT_pStreams, lane});
663      MEMSET(pStream, C((char)0), VERTEX_COUNT_SIZE + CONTROL_HEADER_SIZE, sizeof(float) * KNOB_SIMD_WIDTH);
664   }
665
666   struct swr_gs_llvm_iface gs_iface;
667   gs_iface.base.fetch_input = ::swr_gs_llvm_fetch_input;
668   gs_iface.base.emit_vertex = ::swr_gs_llvm_emit_vertex;
669   gs_iface.base.end_primitive = ::swr_gs_llvm_end_primitive;
670   gs_iface.base.gs_epilogue = ::swr_gs_llvm_epilogue;
671   gs_iface.pBuilder = this;
672   gs_iface.pGsCtx = pGsCtx;
673   gs_iface.pGsState = pGS;
674   gs_iface.num_outputs = gs->info.base.num_outputs;
675   gs_iface.num_verts_per_prim =
676      u_vertices_per_prim((pipe_prim_type)info->properties[TGSI_PROPERTY_GS_OUTPUT_PRIM]);
677   gs_iface.info = info;
678   gs_iface.pVtxAttribMap = vtxAttribMap;
679
680   lp_build_tgsi_soa(gallivm,
681                     gs->pipe.tokens,
682                     lp_type_float_vec(32, 32 * 8),
683                     &mask,
684                     wrap(consts_ptr),
685                     wrap(const_sizes_ptr),
686                     &system_values,
687                     inputs,
688                     outputs,
689                     wrap(hPrivateData), // (sampler context)
690                     NULL, // thread data
691                     sampler,
692                     &gs->info.base,
693                     &gs_iface.base);
694
695   lp_build_mask_end(&mask);
696
697   sampler->destroy(sampler);
698
699   IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
700
701   RET_VOID();
702
703   gallivm_verify_function(gallivm, wrap(pFunction));
704   gallivm_compile_module(gallivm);
705
706   PFN_GS_FUNC pFunc =
707      (PFN_GS_FUNC)gallivm_jit_function(gallivm, wrap(pFunction));
708
709   debug_printf("geom shader  %p\n", pFunc);
710   assert(pFunc && "Error: GeomShader = NULL");
711
712   JM()->mIsModuleFinalized = true;
713
714   return pFunc;
715}
716
717PFN_GS_FUNC
718swr_compile_gs(struct swr_context *ctx, swr_jit_gs_key &key)
719{
720   BuilderSWR builder(
721      reinterpret_cast<JitManager *>(swr_screen(ctx->pipe.screen)->hJitMgr),
722      "GS");
723   PFN_GS_FUNC func = builder.CompileGS(ctx, key);
724
725   ctx->gs->map.insert(std::make_pair(key, make_unique<VariantGS>(builder.gallivm, func)));
726   return func;
727}
728
729void
730BuilderSWR::WriteVS(Value *pVal, Value *pVsContext, Value *pVtxOutput, unsigned slot, unsigned channel)
731{
732#if USE_SIMD16_FRONTEND && !USE_SIMD16_VS
733   // interleave the simdvertex components into the dest simd16vertex
734   //   slot16offset = slot8offset * 2
735   //   comp16offset = comp8offset * 2 + alternateOffset
736
737   Value *offset = LOAD(pVsContext, { 0, SWR_VS_CONTEXT_AlternateOffset });
738   Value *pOut = GEP(pVtxOutput, { C(0), C(0), C(slot * 2), offset } );
739   STORE(pVal, pOut, {channel * 2});
740#else
741   Value *pOut = GEP(pVtxOutput, {0, 0, slot});
742   STORE(pVal, pOut, {0, channel});
743#endif
744}
745
746PFN_VERTEX_FUNC
747BuilderSWR::CompileVS(struct swr_context *ctx, swr_jit_vs_key &key)
748{
749   struct swr_vertex_shader *swr_vs = ctx->vs;
750
751   LLVMValueRef inputs[PIPE_MAX_SHADER_INPUTS][TGSI_NUM_CHANNELS];
752   LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
753
754   memset(outputs, 0, sizeof(outputs));
755
756   AttrBuilder attrBuilder;
757   attrBuilder.addStackAlignmentAttr(JM()->mVWidth * sizeof(float));
758
759   std::vector<Type *> vsArgs{PointerType::get(Gen_swr_draw_context(JM()), 0),
760                              PointerType::get(mInt8Ty, 0),
761                              PointerType::get(Gen_SWR_VS_CONTEXT(JM()), 0)};
762   FunctionType *vsFuncType =
763      FunctionType::get(Type::getVoidTy(JM()->mContext), vsArgs, false);
764
765   // create new vertex shader function
766   auto pFunction = Function::Create(vsFuncType,
767                                     GlobalValue::ExternalLinkage,
768                                     "VS",
769                                     JM()->mpCurrentModule);
770#if HAVE_LLVM < 0x0500
771   AttributeSet attrSet = AttributeSet::get(
772      JM()->mContext, AttributeSet::FunctionIndex, attrBuilder);
773   pFunction->addAttributes(AttributeSet::FunctionIndex, attrSet);
774#else
775   pFunction->addAttributes(AttributeList::FunctionIndex, attrBuilder);
776#endif
777
778   BasicBlock *block = BasicBlock::Create(JM()->mContext, "entry", pFunction);
779   IRB()->SetInsertPoint(block);
780   LLVMPositionBuilderAtEnd(gallivm->builder, wrap(block));
781
782   auto argitr = pFunction->arg_begin();
783   Value *hPrivateData = &*argitr++;
784   hPrivateData->setName("hPrivateData");
785   Value *pWorkerData = &*argitr++;
786   pWorkerData->setName("pWorkerData");
787   Value *pVsCtx = &*argitr++;
788   pVsCtx->setName("vsCtx");
789
790   Value *consts_ptr = GEP(hPrivateData, {C(0), C(swr_draw_context_constantVS)});
791
792   consts_ptr->setName("vs_constants");
793   Value *const_sizes_ptr =
794      GEP(hPrivateData, {0, swr_draw_context_num_constantsVS});
795   const_sizes_ptr->setName("num_vs_constants");
796
797   Value *vtxInput = LOAD(pVsCtx, {0, SWR_VS_CONTEXT_pVin});
798#if USE_SIMD16_VS
799   vtxInput = BITCAST(vtxInput, PointerType::get(Gen_simd16vertex(JM()), 0));
800#endif
801
802   for (uint32_t attrib = 0; attrib < PIPE_MAX_SHADER_INPUTS; attrib++) {
803      const unsigned mask = swr_vs->info.base.input_usage_mask[attrib];
804      for (uint32_t channel = 0; channel < TGSI_NUM_CHANNELS; channel++) {
805         if (mask & (1 << channel)) {
806            inputs[attrib][channel] =
807               wrap(LOAD(vtxInput, {0, 0, attrib, channel}));
808         }
809      }
810   }
811
812   struct lp_build_sampler_soa *sampler =
813      swr_sampler_soa_create(key.sampler, PIPE_SHADER_VERTEX);
814
815   struct lp_bld_tgsi_system_values system_values;
816   memset(&system_values, 0, sizeof(system_values));
817   system_values.instance_id = wrap(LOAD(pVsCtx, {0, SWR_VS_CONTEXT_InstanceID}));
818
819#if USE_SIMD16_VS
820   system_values.vertex_id = wrap(LOAD(pVsCtx, {0, SWR_VS_CONTEXT_VertexID16}));
821#else
822   system_values.vertex_id = wrap(LOAD(pVsCtx, {0, SWR_VS_CONTEXT_VertexID}));
823#endif
824
825#if USE_SIMD16_VS
826   uint32_t vectorWidth = mVWidth16;
827#else
828   uint32_t vectorWidth = mVWidth;
829#endif
830
831   lp_build_tgsi_soa(gallivm,
832                     swr_vs->pipe.tokens,
833                     lp_type_float_vec(32, 32 * vectorWidth),
834                     NULL, // mask
835                     wrap(consts_ptr),
836                     wrap(const_sizes_ptr),
837                     &system_values,
838                     inputs,
839                     outputs,
840                     wrap(hPrivateData), // (sampler context)
841                     NULL, // thread data
842                     sampler, // sampler
843                     &swr_vs->info.base,
844                     NULL); // geometry shader face
845
846   sampler->destroy(sampler);
847
848   IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
849
850   Value *vtxOutput = LOAD(pVsCtx, {0, SWR_VS_CONTEXT_pVout});
851#if USE_SIMD16_VS
852   vtxOutput = BITCAST(vtxOutput, PointerType::get(Gen_simd16vertex(JM()), 0));
853#endif
854
855   for (uint32_t channel = 0; channel < TGSI_NUM_CHANNELS; channel++) {
856      for (uint32_t attrib = 0; attrib < PIPE_MAX_SHADER_OUTPUTS; attrib++) {
857         if (!outputs[attrib][channel])
858            continue;
859
860         Value *val;
861         uint32_t outSlot;
862
863         if (swr_vs->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_PSIZE) {
864            if (channel != VERTEX_SGV_POINT_SIZE_COMP)
865               continue;
866            val = LOAD(unwrap(outputs[attrib][0]));
867            outSlot = VERTEX_SGV_SLOT;
868         } else if (swr_vs->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_POSITION) {
869            val = LOAD(unwrap(outputs[attrib][channel]));
870            outSlot = VERTEX_POSITION_SLOT;
871         } else {
872            val = LOAD(unwrap(outputs[attrib][channel]));
873            outSlot = VERTEX_ATTRIB_START_SLOT + attrib;
874            if (swr_vs->info.base.output_semantic_name[0] == TGSI_SEMANTIC_POSITION)
875               outSlot--;
876         }
877
878         WriteVS(val, pVsCtx, vtxOutput, outSlot, channel);
879      }
880   }
881
882   if (ctx->rasterizer->clip_plane_enable ||
883       swr_vs->info.base.culldist_writemask) {
884      unsigned clip_mask = ctx->rasterizer->clip_plane_enable;
885
886      unsigned cv = 0;
887      if (swr_vs->info.base.writes_clipvertex) {
888         cv = locate_linkage(TGSI_SEMANTIC_CLIPVERTEX, 0,
889                             &swr_vs->info.base);
890      } else {
891         for (int i = 0; i < PIPE_MAX_SHADER_OUTPUTS; i++) {
892            if (swr_vs->info.base.output_semantic_name[i] == TGSI_SEMANTIC_POSITION &&
893                swr_vs->info.base.output_semantic_index[i] == 0) {
894               cv = i;
895               break;
896            }
897         }
898      }
899      LLVMValueRef cx = LLVMBuildLoad(gallivm->builder, outputs[cv][0], "");
900      LLVMValueRef cy = LLVMBuildLoad(gallivm->builder, outputs[cv][1], "");
901      LLVMValueRef cz = LLVMBuildLoad(gallivm->builder, outputs[cv][2], "");
902      LLVMValueRef cw = LLVMBuildLoad(gallivm->builder, outputs[cv][3], "");
903
904      for (unsigned val = 0; val < PIPE_MAX_CLIP_PLANES; val++) {
905         // clip distance overrides user clip planes
906         if ((swr_vs->info.base.clipdist_writemask & clip_mask & (1 << val)) ||
907             ((swr_vs->info.base.culldist_writemask << swr_vs->info.base.num_written_clipdistance) & (1 << val))) {
908            unsigned cv = locate_linkage(TGSI_SEMANTIC_CLIPDIST, val < 4 ? 0 : 1,
909                                         &swr_vs->info.base);
910            if (val < 4) {
911               LLVMValueRef dist = LLVMBuildLoad(gallivm->builder, outputs[cv][val], "");
912               WriteVS(unwrap(dist), pVsCtx, vtxOutput, VERTEX_CLIPCULL_DIST_LO_SLOT, val);
913            } else {
914               LLVMValueRef dist = LLVMBuildLoad(gallivm->builder, outputs[cv][val - 4], "");
915               WriteVS(unwrap(dist), pVsCtx, vtxOutput, VERTEX_CLIPCULL_DIST_HI_SLOT, val - 4);
916            }
917            continue;
918         }
919
920         if (!(clip_mask & (1 << val)))
921            continue;
922
923         Value *px = LOAD(GEP(hPrivateData, {0, swr_draw_context_userClipPlanes, val, 0}));
924         Value *py = LOAD(GEP(hPrivateData, {0, swr_draw_context_userClipPlanes, val, 1}));
925         Value *pz = LOAD(GEP(hPrivateData, {0, swr_draw_context_userClipPlanes, val, 2}));
926         Value *pw = LOAD(GEP(hPrivateData, {0, swr_draw_context_userClipPlanes, val, 3}));
927#if USE_SIMD16_VS
928         Value *bpx = VBROADCAST_16(px);
929         Value *bpy = VBROADCAST_16(py);
930         Value *bpz = VBROADCAST_16(pz);
931         Value *bpw = VBROADCAST_16(pw);
932#else
933         Value *bpx = VBROADCAST(px);
934         Value *bpy = VBROADCAST(py);
935         Value *bpz = VBROADCAST(pz);
936         Value *bpw = VBROADCAST(pw);
937#endif
938         Value *dist = FADD(FMUL(unwrap(cx), bpx),
939                            FADD(FMUL(unwrap(cy), bpy),
940                                 FADD(FMUL(unwrap(cz), bpz),
941                                      FMUL(unwrap(cw), bpw))));
942
943         if (val < 4)
944            WriteVS(dist, pVsCtx, vtxOutput, VERTEX_CLIPCULL_DIST_LO_SLOT, val);
945         else
946            WriteVS(dist, pVsCtx, vtxOutput, VERTEX_CLIPCULL_DIST_HI_SLOT, val - 4);
947      }
948   }
949
950   RET_VOID();
951
952   gallivm_verify_function(gallivm, wrap(pFunction));
953   gallivm_compile_module(gallivm);
954
955   //   lp_debug_dump_value(func);
956
957   PFN_VERTEX_FUNC pFunc =
958      (PFN_VERTEX_FUNC)gallivm_jit_function(gallivm, wrap(pFunction));
959
960   debug_printf("vert shader  %p\n", pFunc);
961   assert(pFunc && "Error: VertShader = NULL");
962
963   JM()->mIsModuleFinalized = true;
964
965   return pFunc;
966}
967
968PFN_VERTEX_FUNC
969swr_compile_vs(struct swr_context *ctx, swr_jit_vs_key &key)
970{
971   if (!ctx->vs->pipe.tokens)
972      return NULL;
973
974   BuilderSWR builder(
975      reinterpret_cast<JitManager *>(swr_screen(ctx->pipe.screen)->hJitMgr),
976      "VS");
977   PFN_VERTEX_FUNC func = builder.CompileVS(ctx, key);
978
979   ctx->vs->map.insert(std::make_pair(key, make_unique<VariantVS>(builder.gallivm, func)));
980   return func;
981}
982
983unsigned
984swr_so_adjust_attrib(unsigned in_attrib,
985                     swr_vertex_shader *swr_vs)
986{
987   ubyte semantic_name;
988   unsigned attrib;
989
990   attrib = in_attrib + VERTEX_ATTRIB_START_SLOT;
991
992   if (swr_vs) {
993      semantic_name = swr_vs->info.base.output_semantic_name[in_attrib];
994      if (semantic_name == TGSI_SEMANTIC_POSITION) {
995         attrib = VERTEX_POSITION_SLOT;
996      } else if (semantic_name == TGSI_SEMANTIC_PSIZE) {
997         attrib = VERTEX_SGV_SLOT;
998      } else if (semantic_name == TGSI_SEMANTIC_LAYER) {
999         attrib = VERTEX_SGV_SLOT;
1000      } else {
1001         if (swr_vs->info.base.writes_position) {
1002               attrib--;
1003         }
1004      }
1005   }
1006
1007   return attrib;
1008}
1009
1010static unsigned
1011locate_linkage(ubyte name, ubyte index, struct tgsi_shader_info *info)
1012{
1013   for (int i = 0; i < PIPE_MAX_SHADER_OUTPUTS; i++) {
1014      if ((info->output_semantic_name[i] == name)
1015          && (info->output_semantic_index[i] == index)) {
1016         return i;
1017      }
1018   }
1019
1020   return 0xFFFFFFFF;
1021}
1022
1023PFN_PIXEL_KERNEL
1024BuilderSWR::CompileFS(struct swr_context *ctx, swr_jit_fs_key &key)
1025{
1026   struct swr_fragment_shader *swr_fs = ctx->fs;
1027
1028   struct tgsi_shader_info *pPrevShader;
1029   if (ctx->gs)
1030      pPrevShader = &ctx->gs->info.base;
1031   else
1032      pPrevShader = &ctx->vs->info.base;
1033
1034   LLVMValueRef inputs[PIPE_MAX_SHADER_INPUTS][TGSI_NUM_CHANNELS];
1035   LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
1036
1037   memset(inputs, 0, sizeof(inputs));
1038   memset(outputs, 0, sizeof(outputs));
1039
1040   struct lp_build_sampler_soa *sampler = NULL;
1041
1042   AttrBuilder attrBuilder;
1043   attrBuilder.addStackAlignmentAttr(JM()->mVWidth * sizeof(float));
1044
1045   std::vector<Type *> fsArgs{PointerType::get(Gen_swr_draw_context(JM()), 0),
1046                              PointerType::get(mInt8Ty, 0),
1047                              PointerType::get(Gen_SWR_PS_CONTEXT(JM()), 0)};
1048   FunctionType *funcType =
1049      FunctionType::get(Type::getVoidTy(JM()->mContext), fsArgs, false);
1050
1051   auto pFunction = Function::Create(funcType,
1052                                     GlobalValue::ExternalLinkage,
1053                                     "FS",
1054                                     JM()->mpCurrentModule);
1055#if HAVE_LLVM < 0x0500
1056   AttributeSet attrSet = AttributeSet::get(
1057      JM()->mContext, AttributeSet::FunctionIndex, attrBuilder);
1058   pFunction->addAttributes(AttributeSet::FunctionIndex, attrSet);
1059#else
1060   pFunction->addAttributes(AttributeList::FunctionIndex, attrBuilder);
1061#endif
1062
1063   BasicBlock *block = BasicBlock::Create(JM()->mContext, "entry", pFunction);
1064   IRB()->SetInsertPoint(block);
1065   LLVMPositionBuilderAtEnd(gallivm->builder, wrap(block));
1066
1067   auto args = pFunction->arg_begin();
1068   Value *hPrivateData = &*args++;
1069   hPrivateData->setName("hPrivateData");
1070   Value *pWorkerData = &*args++;
1071   pWorkerData->setName("pWorkerData");
1072   Value *pPS = &*args++;
1073   pPS->setName("psCtx");
1074
1075   Value *consts_ptr = GEP(hPrivateData, {0, swr_draw_context_constantFS});
1076   consts_ptr->setName("fs_constants");
1077   Value *const_sizes_ptr =
1078      GEP(hPrivateData, {0, swr_draw_context_num_constantsFS});
1079   const_sizes_ptr->setName("num_fs_constants");
1080
1081   // load *pAttribs, *pPerspAttribs
1082   Value *pRawAttribs = LOAD(pPS, {0, SWR_PS_CONTEXT_pAttribs}, "pRawAttribs");
1083   Value *pPerspAttribs =
1084      LOAD(pPS, {0, SWR_PS_CONTEXT_pPerspAttribs}, "pPerspAttribs");
1085
1086   swr_fs->constantMask = 0;
1087   swr_fs->flatConstantMask = 0;
1088   swr_fs->pointSpriteMask = 0;
1089
1090   for (int attrib = 0; attrib < PIPE_MAX_SHADER_INPUTS; attrib++) {
1091      const unsigned mask = swr_fs->info.base.input_usage_mask[attrib];
1092      const unsigned interpMode = swr_fs->info.base.input_interpolate[attrib];
1093      const unsigned interpLoc = swr_fs->info.base.input_interpolate_loc[attrib];
1094
1095      if (!mask)
1096         continue;
1097
1098      // load i,j
1099      Value *vi = nullptr, *vj = nullptr;
1100      switch (interpLoc) {
1101      case TGSI_INTERPOLATE_LOC_CENTER:
1102         vi = LOAD(pPS, {0, SWR_PS_CONTEXT_vI, PixelPositions_center}, "i");
1103         vj = LOAD(pPS, {0, SWR_PS_CONTEXT_vJ, PixelPositions_center}, "j");
1104         break;
1105      case TGSI_INTERPOLATE_LOC_CENTROID:
1106         vi = LOAD(pPS, {0, SWR_PS_CONTEXT_vI, PixelPositions_centroid}, "i");
1107         vj = LOAD(pPS, {0, SWR_PS_CONTEXT_vJ, PixelPositions_centroid}, "j");
1108         break;
1109      case TGSI_INTERPOLATE_LOC_SAMPLE:
1110         vi = LOAD(pPS, {0, SWR_PS_CONTEXT_vI, PixelPositions_sample}, "i");
1111         vj = LOAD(pPS, {0, SWR_PS_CONTEXT_vJ, PixelPositions_sample}, "j");
1112         break;
1113      }
1114
1115      // load/compute w
1116      Value *vw = nullptr, *pAttribs;
1117      if (interpMode == TGSI_INTERPOLATE_PERSPECTIVE ||
1118          interpMode == TGSI_INTERPOLATE_COLOR) {
1119         pAttribs = pPerspAttribs;
1120         switch (interpLoc) {
1121         case TGSI_INTERPOLATE_LOC_CENTER:
1122            vw = VRCP(LOAD(pPS, {0, SWR_PS_CONTEXT_vOneOverW, PixelPositions_center}));
1123            break;
1124         case TGSI_INTERPOLATE_LOC_CENTROID:
1125            vw = VRCP(LOAD(pPS, {0, SWR_PS_CONTEXT_vOneOverW, PixelPositions_centroid}));
1126            break;
1127         case TGSI_INTERPOLATE_LOC_SAMPLE:
1128            vw = VRCP(LOAD(pPS, {0, SWR_PS_CONTEXT_vOneOverW, PixelPositions_sample}));
1129            break;
1130         }
1131      } else {
1132         pAttribs = pRawAttribs;
1133         vw = VIMMED1(1.f);
1134      }
1135
1136      vw->setName("w");
1137
1138      ubyte semantic_name = swr_fs->info.base.input_semantic_name[attrib];
1139      ubyte semantic_idx = swr_fs->info.base.input_semantic_index[attrib];
1140
1141      if (semantic_name == TGSI_SEMANTIC_FACE) {
1142         Value *ff =
1143            UI_TO_FP(LOAD(pPS, {0, SWR_PS_CONTEXT_frontFace}), mFP32Ty);
1144         ff = FSUB(FMUL(ff, C(2.0f)), C(1.0f));
1145         ff = VECTOR_SPLAT(JM()->mVWidth, ff, "vFrontFace");
1146
1147         inputs[attrib][0] = wrap(ff);
1148         inputs[attrib][1] = wrap(VIMMED1(0.0f));
1149         inputs[attrib][2] = wrap(VIMMED1(0.0f));
1150         inputs[attrib][3] = wrap(VIMMED1(1.0f));
1151         continue;
1152      } else if (semantic_name == TGSI_SEMANTIC_POSITION) { // gl_FragCoord
1153         if (swr_fs->info.base.properties[TGSI_PROPERTY_FS_COORD_PIXEL_CENTER] ==
1154             TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER) {
1155            inputs[attrib][0] = wrap(LOAD(pPS, {0, SWR_PS_CONTEXT_vX, PixelPositions_center}, "vX"));
1156            inputs[attrib][1] = wrap(LOAD(pPS, {0, SWR_PS_CONTEXT_vY, PixelPositions_center}, "vY"));
1157         } else {
1158            inputs[attrib][0] = wrap(LOAD(pPS, {0, SWR_PS_CONTEXT_vX, PixelPositions_UL}, "vX"));
1159            inputs[attrib][1] = wrap(LOAD(pPS, {0, SWR_PS_CONTEXT_vY, PixelPositions_UL}, "vY"));
1160         }
1161         inputs[attrib][2] = wrap(LOAD(pPS, {0, SWR_PS_CONTEXT_vZ}, "vZ"));
1162         inputs[attrib][3] =
1163            wrap(LOAD(pPS, {0, SWR_PS_CONTEXT_vOneOverW, PixelPositions_center}, "vOneOverW"));
1164         continue;
1165      }
1166
1167      unsigned linkedAttrib =
1168         locate_linkage(semantic_name, semantic_idx, pPrevShader) - 1;
1169
1170      uint32_t extraAttribs = 0;
1171      if (semantic_name == TGSI_SEMANTIC_PRIMID && !ctx->gs) {
1172         /* non-gs generated primID - need to grab from swizzleMap override */
1173         linkedAttrib = pPrevShader->num_outputs - 1;
1174         swr_fs->constantMask |= 1 << linkedAttrib;
1175         extraAttribs++;
1176      } else if (semantic_name == TGSI_SEMANTIC_GENERIC &&
1177          key.sprite_coord_enable & (1 << semantic_idx)) {
1178         /* we add an extra attrib to the backendState in swr_update_derived. */
1179         linkedAttrib = pPrevShader->num_outputs + extraAttribs - 1;
1180         swr_fs->pointSpriteMask |= (1 << linkedAttrib);
1181         extraAttribs++;
1182      } else if (linkedAttrib == 0xFFFFFFFF) {
1183         inputs[attrib][0] = wrap(VIMMED1(0.0f));
1184         inputs[attrib][1] = wrap(VIMMED1(0.0f));
1185         inputs[attrib][2] = wrap(VIMMED1(0.0f));
1186         inputs[attrib][3] = wrap(VIMMED1(1.0f));
1187         /* If we're reading in color and 2-sided lighting is enabled, we have
1188          * to keep going.
1189          */
1190         if (semantic_name != TGSI_SEMANTIC_COLOR || !key.light_twoside)
1191            continue;
1192      } else {
1193         if (interpMode == TGSI_INTERPOLATE_CONSTANT) {
1194            swr_fs->constantMask |= 1 << linkedAttrib;
1195         } else if (interpMode == TGSI_INTERPOLATE_COLOR) {
1196            swr_fs->flatConstantMask |= 1 << linkedAttrib;
1197         }
1198      }
1199
1200      unsigned bcolorAttrib = 0xFFFFFFFF;
1201      Value *offset = NULL;
1202      if (semantic_name == TGSI_SEMANTIC_COLOR && key.light_twoside) {
1203         bcolorAttrib = locate_linkage(
1204               TGSI_SEMANTIC_BCOLOR, semantic_idx, pPrevShader) - 1;
1205         /* Neither front nor back colors were available. Nothing to load. */
1206         if (bcolorAttrib == 0xFFFFFFFF && linkedAttrib == 0xFFFFFFFF)
1207            continue;
1208         /* If there is no front color, just always use the back color. */
1209         if (linkedAttrib == 0xFFFFFFFF)
1210            linkedAttrib = bcolorAttrib;
1211
1212         if (bcolorAttrib != 0xFFFFFFFF) {
1213            if (interpMode == TGSI_INTERPOLATE_CONSTANT) {
1214               swr_fs->constantMask |= 1 << bcolorAttrib;
1215            } else if (interpMode == TGSI_INTERPOLATE_COLOR) {
1216               swr_fs->flatConstantMask |= 1 << bcolorAttrib;
1217            }
1218
1219            unsigned diff = 12 * (bcolorAttrib - linkedAttrib);
1220
1221            if (diff) {
1222               Value *back =
1223                  XOR(C(1), LOAD(pPS, {0, SWR_PS_CONTEXT_frontFace}), "backFace");
1224
1225               offset = MUL(back, C(diff));
1226               offset->setName("offset");
1227            }
1228         }
1229      }
1230
1231      for (int channel = 0; channel < TGSI_NUM_CHANNELS; channel++) {
1232         if (mask & (1 << channel)) {
1233            Value *indexA = C(linkedAttrib * 12 + channel);
1234            Value *indexB = C(linkedAttrib * 12 + channel + 4);
1235            Value *indexC = C(linkedAttrib * 12 + channel + 8);
1236
1237            if (offset) {
1238               indexA = ADD(indexA, offset);
1239               indexB = ADD(indexB, offset);
1240               indexC = ADD(indexC, offset);
1241            }
1242
1243            Value *va = VBROADCAST(LOAD(GEP(pAttribs, indexA)));
1244            Value *vb = VBROADCAST(LOAD(GEP(pAttribs, indexB)));
1245            Value *vc = VBROADCAST(LOAD(GEP(pAttribs, indexC)));
1246
1247            if (interpMode == TGSI_INTERPOLATE_CONSTANT) {
1248               inputs[attrib][channel] = wrap(va);
1249            } else {
1250               Value *vk = FSUB(FSUB(VIMMED1(1.0f), vi), vj);
1251
1252               vc = FMUL(vk, vc);
1253
1254               Value *interp = FMUL(va, vi);
1255               Value *interp1 = FMUL(vb, vj);
1256               interp = FADD(interp, interp1);
1257               interp = FADD(interp, vc);
1258               if (interpMode == TGSI_INTERPOLATE_PERSPECTIVE ||
1259                   interpMode == TGSI_INTERPOLATE_COLOR)
1260                  interp = FMUL(interp, vw);
1261               inputs[attrib][channel] = wrap(interp);
1262            }
1263         }
1264      }
1265   }
1266
1267   sampler = swr_sampler_soa_create(key.sampler, PIPE_SHADER_FRAGMENT);
1268
1269   struct lp_bld_tgsi_system_values system_values;
1270   memset(&system_values, 0, sizeof(system_values));
1271
1272   struct lp_build_mask_context mask;
1273   bool uses_mask = false;
1274
1275   if (swr_fs->info.base.uses_kill ||
1276       key.poly_stipple_enable) {
1277      Value *vActiveMask = NULL;
1278      if (swr_fs->info.base.uses_kill) {
1279         vActiveMask = LOAD(pPS, {0, SWR_PS_CONTEXT_activeMask}, "activeMask");
1280      }
1281      if (key.poly_stipple_enable) {
1282         // first get fragment xy coords and clip to stipple bounds
1283         Value *vXf = LOAD(pPS, {0, SWR_PS_CONTEXT_vX, PixelPositions_UL});
1284         Value *vYf = LOAD(pPS, {0, SWR_PS_CONTEXT_vY, PixelPositions_UL});
1285         Value *vXu = FP_TO_UI(vXf, mSimdInt32Ty);
1286         Value *vYu = FP_TO_UI(vYf, mSimdInt32Ty);
1287
1288         // stipple pattern is 32x32, which means that one line of stipple
1289         // is stored in one word:
1290         // vXstipple is bit offset inside 32-bit stipple word
1291         // vYstipple is word index is stipple array
1292         Value *vXstipple = AND(vXu, VIMMED1(0x1f)); // & (32-1)
1293         Value *vYstipple = AND(vYu, VIMMED1(0x1f)); // & (32-1)
1294
1295         // grab stipple pattern base address
1296         Value *stipplePtr = GEP(hPrivateData, {0, swr_draw_context_polyStipple, 0});
1297         stipplePtr = BITCAST(stipplePtr, mInt8PtrTy);
1298
1299         // peform a gather to grab stipple words for each lane
1300         Value *vStipple = GATHERDD(VUNDEF_I(), stipplePtr, vYstipple,
1301                                    VIMMED1(0xffffffff), 4);
1302
1303         // create a mask with one bit corresponding to the x stipple
1304         // and AND it with the pattern, to see if we have a bit
1305         Value *vBitMask = LSHR(VIMMED1(0x80000000), vXstipple);
1306         Value *vStippleMask = AND(vStipple, vBitMask);
1307         vStippleMask = ICMP_NE(vStippleMask, VIMMED1(0));
1308         vStippleMask = VMASK(vStippleMask);
1309
1310         if (swr_fs->info.base.uses_kill) {
1311            vActiveMask = AND(vActiveMask, vStippleMask);
1312         } else {
1313            vActiveMask = vStippleMask;
1314         }
1315      }
1316      lp_build_mask_begin(
1317         &mask, gallivm, lp_type_float_vec(32, 32 * 8), wrap(vActiveMask));
1318      uses_mask = true;
1319   }
1320
1321   lp_build_tgsi_soa(gallivm,
1322                     swr_fs->pipe.tokens,
1323                     lp_type_float_vec(32, 32 * 8),
1324                     uses_mask ? &mask : NULL, // mask
1325                     wrap(consts_ptr),
1326                     wrap(const_sizes_ptr),
1327                     &system_values,
1328                     inputs,
1329                     outputs,
1330                     wrap(hPrivateData),
1331                     NULL, // thread data
1332                     sampler, // sampler
1333                     &swr_fs->info.base,
1334                     NULL); // geometry shader face
1335
1336   sampler->destroy(sampler);
1337
1338   IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
1339
1340   for (uint32_t attrib = 0; attrib < swr_fs->info.base.num_outputs;
1341        attrib++) {
1342      switch (swr_fs->info.base.output_semantic_name[attrib]) {
1343      case TGSI_SEMANTIC_POSITION: {
1344         // write z
1345         LLVMValueRef outZ =
1346            LLVMBuildLoad(gallivm->builder, outputs[attrib][2], "");
1347         STORE(unwrap(outZ), pPS, {0, SWR_PS_CONTEXT_vZ});
1348         break;
1349      }
1350      case TGSI_SEMANTIC_COLOR: {
1351         for (uint32_t channel = 0; channel < TGSI_NUM_CHANNELS; channel++) {
1352            if (!outputs[attrib][channel])
1353               continue;
1354
1355            LLVMValueRef out =
1356               LLVMBuildLoad(gallivm->builder, outputs[attrib][channel], "");
1357            if (swr_fs->info.base.properties[TGSI_PROPERTY_FS_COLOR0_WRITES_ALL_CBUFS] &&
1358                swr_fs->info.base.output_semantic_index[attrib] == 0) {
1359               for (uint32_t rt = 0; rt < key.nr_cbufs; rt++) {
1360                  STORE(unwrap(out),
1361                        pPS,
1362                        {0, SWR_PS_CONTEXT_shaded, rt, channel});
1363               }
1364            } else {
1365               STORE(unwrap(out),
1366                     pPS,
1367                     {0,
1368                           SWR_PS_CONTEXT_shaded,
1369                           swr_fs->info.base.output_semantic_index[attrib],
1370                           channel});
1371            }
1372         }
1373         break;
1374      }
1375      default: {
1376         fprintf(stderr,
1377                 "unknown output from FS %s[%d]\n",
1378                 tgsi_semantic_names[swr_fs->info.base
1379                                        .output_semantic_name[attrib]],
1380                 swr_fs->info.base.output_semantic_index[attrib]);
1381         break;
1382      }
1383      }
1384   }
1385
1386   LLVMValueRef mask_result = 0;
1387   if (uses_mask) {
1388      mask_result = lp_build_mask_end(&mask);
1389   }
1390
1391   IRB()->SetInsertPoint(unwrap(LLVMGetInsertBlock(gallivm->builder)));
1392
1393   if (uses_mask) {
1394      STORE(unwrap(mask_result), pPS, {0, SWR_PS_CONTEXT_activeMask});
1395   }
1396
1397   RET_VOID();
1398
1399   gallivm_verify_function(gallivm, wrap(pFunction));
1400
1401   gallivm_compile_module(gallivm);
1402
1403   // after the gallivm passes, we have to lower the core's intrinsics
1404   llvm::legacy::FunctionPassManager lowerPass(JM()->mpCurrentModule);
1405   lowerPass.add(createLowerX86Pass(this));
1406   lowerPass.run(*pFunction);
1407
1408   PFN_PIXEL_KERNEL kernel =
1409      (PFN_PIXEL_KERNEL)gallivm_jit_function(gallivm, wrap(pFunction));
1410   debug_printf("frag shader  %p\n", kernel);
1411   assert(kernel && "Error: FragShader = NULL");
1412
1413   JM()->mIsModuleFinalized = true;
1414
1415   return kernel;
1416}
1417
1418PFN_PIXEL_KERNEL
1419swr_compile_fs(struct swr_context *ctx, swr_jit_fs_key &key)
1420{
1421   if (!ctx->fs->pipe.tokens)
1422      return NULL;
1423
1424   BuilderSWR builder(
1425      reinterpret_cast<JitManager *>(swr_screen(ctx->pipe.screen)->hJitMgr),
1426      "FS");
1427   PFN_PIXEL_KERNEL func = builder.CompileFS(ctx, key);
1428
1429   ctx->fs->map.insert(std::make_pair(key, make_unique<VariantFS>(builder.gallivm, func)));
1430   return func;
1431}
1432