radeonsi: inline si_llvm_shader_type into si_llvm_create_func
[mesa.git] / src / gallium / drivers / radeonsi / si_shader_tgsi_setup.c
index e1534c717a076d0e7e5342e4b61d2fdc23a02efe..de671ef80d6ed6f38f95d0c024d4beea28f7d1ae 100644 (file)
@@ -22,7 +22,7 @@
  */
 
 #include "si_shader_internal.h"
-#include "radeon/radeon_elf_util.h"
+#include "si_pipe.h"
 
 #include "gallivm/lp_bld_const.h"
 #include "gallivm/lp_bld_gather.h"
 #include "util/u_debug.h"
 
 #include <stdio.h>
+#include <llvm-c/Transforms/IPO.h>
 #include <llvm-c/Transforms/Scalar.h>
+#include <llvm-c/Support.h>
 
 /* Data for if/else/endif and bgnloop/endloop control flow structures.
  */
-struct radeon_llvm_flow {
+struct si_llvm_flow {
        /* Loop exit or next part of if/else/endif. */
        LLVMBasicBlockRef next_block;
        LLVMBasicBlockRef loop_entry_block;
 };
 
-#define CPU_STRING_LEN 30
-#define FS_STRING_LEN 30
-#define TRIPLE_STRING_LEN 7
-
-/**
- * Shader types for the LLVM backend.
- */
-enum radeon_llvm_shader_type {
-       RADEON_LLVM_SHADER_PS = 0,
-       RADEON_LLVM_SHADER_VS = 1,
-       RADEON_LLVM_SHADER_GS = 2,
-       RADEON_LLVM_SHADER_CS = 3,
-};
-
-enum radeon_llvm_calling_convention {
+enum si_llvm_calling_convention {
        RADEON_LLVM_AMDGPU_VS = 87,
        RADEON_LLVM_AMDGPU_GS = 88,
        RADEON_LLVM_AMDGPU_PS = 89,
        RADEON_LLVM_AMDGPU_CS = 90,
 };
 
-void radeon_llvm_add_attribute(LLVMValueRef F, const char *name, int value)
+void si_llvm_add_attribute(LLVMValueRef F, const char *name, int value)
 {
        char str[16];
 
@@ -77,70 +65,36 @@ void radeon_llvm_add_attribute(LLVMValueRef F, const char *name, int value)
        LLVMAddTargetDependentFunctionAttr(F, name, str);
 }
 
-/**
- * Set the shader type we want to compile
- *
- * @param type shader type to set
- */
-void radeon_llvm_shader_type(LLVMValueRef F, unsigned type)
-{
-       enum radeon_llvm_shader_type llvm_type;
-       enum radeon_llvm_calling_convention calling_conv;
-
-       switch (type) {
-       case PIPE_SHADER_VERTEX:
-       case PIPE_SHADER_TESS_CTRL:
-       case PIPE_SHADER_TESS_EVAL:
-               llvm_type = RADEON_LLVM_SHADER_VS;
-               calling_conv = RADEON_LLVM_AMDGPU_VS;
-               break;
-       case PIPE_SHADER_GEOMETRY:
-               llvm_type = RADEON_LLVM_SHADER_GS;
-               calling_conv = RADEON_LLVM_AMDGPU_GS;
-               break;
-       case PIPE_SHADER_FRAGMENT:
-               llvm_type = RADEON_LLVM_SHADER_PS;
-               calling_conv = RADEON_LLVM_AMDGPU_PS;
-               break;
-       case PIPE_SHADER_COMPUTE:
-               llvm_type = RADEON_LLVM_SHADER_CS;
-               calling_conv = RADEON_LLVM_AMDGPU_CS;
-               break;
-       default:
-               unreachable("Unhandle shader type");
-       }
-
-       if (HAVE_LLVM >= 0x309)
-               LLVMSetFunctionCallConv(F, calling_conv);
-       else
-               radeon_llvm_add_attribute(F, "ShaderType", llvm_type);
-}
-
-static void init_r600_target()
+static void init_amdgpu_target()
 {
        gallivm_init_llvm_targets();
-#if HAVE_LLVM < 0x0307
-       LLVMInitializeR600TargetInfo();
-       LLVMInitializeR600Target();
-       LLVMInitializeR600TargetMC();
-       LLVMInitializeR600AsmPrinter();
-#else
        LLVMInitializeAMDGPUTargetInfo();
        LLVMInitializeAMDGPUTarget();
        LLVMInitializeAMDGPUTargetMC();
        LLVMInitializeAMDGPUAsmPrinter();
 
-#endif
+       /* For inline assembly. */
+       LLVMInitializeAMDGPUAsmParser();
+
+       if (HAVE_LLVM >= 0x0400) {
+               /*
+                * Workaround for bug in llvm 4.0 that causes image intrinsics
+                * to disappear.
+                * https://reviews.llvm.org/D26348
+                */
+               const char *argv[2] = {"mesa", "-simplifycfg-sink-common=false"};
+               LLVMParseCommandLineOptions(2, argv, NULL);
+       }
 }
 
-static once_flag init_r600_target_once_flag = ONCE_FLAG_INIT;
+static once_flag init_amdgpu_target_once_flag = ONCE_FLAG_INIT;
 
-LLVMTargetRef radeon_llvm_get_r600_target(const char *triple)
+LLVMTargetRef si_llvm_get_amdgpu_target(const char *triple)
 {
        LLVMTargetRef target = NULL;
        char *err_message = NULL;
 
-       call_once(&init_r600_target_once_flag, init_r600_target);
+       call_once(&init_amdgpu_target_once_flag, init_amdgpu_target);
 
        if (LLVMGetTargetFromTriple(triple, &target, &err_message)) {
                fprintf(stderr, "Cannot find target for triple %s ", triple);
@@ -153,14 +107,14 @@ LLVMTargetRef radeon_llvm_get_r600_target(const char *triple)
        return target;
 }
 
-struct radeon_llvm_diagnostics {
+struct si_llvm_diagnostics {
        struct pipe_debug_callback *debug;
        unsigned retval;
 };
 
-static void radeonDiagnosticHandler(LLVMDiagnosticInfoRef di, void *context)
+static void si_diagnostic_handler(LLVMDiagnosticInfoRef di, void *context)
 {
-       struct radeon_llvm_diagnostics *diag = (struct radeon_llvm_diagnostics *)context;
+       struct si_llvm_diagnostics *diag = (struct si_llvm_diagnostics *)context;
        LLVMDiagnosticSeverity severity = LLVMGetDiagInfoSeverity(di);
        char *description = LLVMGetDiagInfoDescription(di);
        const char *severity_str = NULL;
@@ -198,11 +152,11 @@ static void radeonDiagnosticHandler(LLVMDiagnosticInfoRef di, void *context)
  *
  * @returns 0 for success, 1 for failure
  */
-unsigned radeon_llvm_compile(LLVMModuleRef M, struct radeon_shader_binary *binary,
-                            LLVMTargetMachineRef tm,
-                            struct pipe_debug_callback *debug)
+unsigned si_llvm_compile(LLVMModuleRef M, struct ac_shader_binary *binary,
+                        LLVMTargetMachineRef tm,
+                        struct pipe_debug_callback *debug)
 {
-       struct radeon_llvm_diagnostics diag;
+       struct si_llvm_diagnostics diag;
        char *err;
        LLVMContextRef llvm_ctx;
        LLVMMemoryBufferRef out_buffer;
@@ -216,7 +170,7 @@ unsigned radeon_llvm_compile(LLVMModuleRef M, struct radeon_shader_binary *binar
        /* Setup Diagnostic Handler*/
        llvm_ctx = LLVMGetModuleContext(M);
 
-       LLVMContextSetDiagnosticHandler(llvm_ctx, radeonDiagnosticHandler, &diag);
+       LLVMContextSetDiagnosticHandler(llvm_ctx, si_diagnostic_handler, &diag);
 
        /* Compile IR*/
        mem_err = LLVMTargetMachineEmitToMemoryBuffer(tm, M, LLVMObjectFile, &err,
@@ -236,7 +190,7 @@ unsigned radeon_llvm_compile(LLVMModuleRef M, struct radeon_shader_binary *binar
        buffer_size = LLVMGetBufferSize(out_buffer);
        buffer_data = LLVMGetBufferStart(out_buffer);
 
-       radeon_elf_read(buffer_data, buffer_size, binary);
+       ac_elf_read(buffer_data, buffer_size, binary);
 
        /* Clean up */
        LLVMDisposeMemoryBuffer(out_buffer);
@@ -285,13 +239,13 @@ LLVMValueRef bitcast(struct lp_build_tgsi_context *bld_base,
  * Return a value that is equal to the given i32 \p index if it lies in [0,num)
  * or an undefined value in the same interval otherwise.
  */
-LLVMValueRef radeon_llvm_bound_index(struct radeon_llvm_context *ctx,
-                                    LLVMValueRef index,
-                                    unsigned num)
+LLVMValueRef si_llvm_bound_index(struct si_shader_context *ctx,
+                                LLVMValueRef index,
+                                unsigned num)
 {
        struct gallivm_state *gallivm = &ctx->gallivm;
        LLVMBuilderRef builder = gallivm->builder;
-       LLVMValueRef c_max = lp_build_const_int32(gallivm, num - 1);
+       LLVMValueRef c_max = LLVMConstInt(ctx->i32, num - 1, 0);
        LLVMValueRef cc;
 
        if (util_is_power_of_two(num)) {
@@ -310,16 +264,16 @@ LLVMValueRef radeon_llvm_bound_index(struct radeon_llvm_context *ctx,
        return index;
 }
 
-static struct radeon_llvm_flow *
-get_current_flow(struct radeon_llvm_context *ctx)
+static struct si_llvm_flow *
+get_current_flow(struct si_shader_context *ctx)
 {
        if (ctx->flow_depth > 0)
                return &ctx->flow[ctx->flow_depth - 1];
        return NULL;
 }
 
-static struct radeon_llvm_flow *
-get_innermost_loop(struct radeon_llvm_context *ctx)
+static struct si_llvm_flow *
+get_innermost_loop(struct si_shader_context *ctx)
 {
        for (unsigned i = ctx->flow_depth; i > 0; --i) {
                if (ctx->flow[i - 1].loop_entry_block)
@@ -328,10 +282,10 @@ get_innermost_loop(struct radeon_llvm_context *ctx)
        return NULL;
 }
 
-static struct radeon_llvm_flow *
-push_flow(struct radeon_llvm_context *ctx)
+static struct si_llvm_flow *
+push_flow(struct si_shader_context *ctx)
 {
-       struct radeon_llvm_flow *flow;
+       struct si_llvm_flow *flow;
 
        if (ctx->flow_depth >= ctx->flow_depth_max) {
                unsigned new_max = MAX2(ctx->flow_depth << 1, RADEON_LLVM_INITIAL_CF_DEPTH);
@@ -380,8 +334,8 @@ get_temp_array_id(struct lp_build_tgsi_context *bld_base,
                  unsigned reg_index,
                  const struct tgsi_ind_register *reg)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       unsigned num_arrays = ctx->soa.bld_base.info->array_max[TGSI_FILE_TEMPORARY];
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       unsigned num_arrays = ctx->bld_base.info->array_max[TGSI_FILE_TEMPORARY];
        unsigned i;
 
        if (reg && reg->ArrayID > 0 && reg->ArrayID <= num_arrays)
@@ -402,7 +356,7 @@ get_array_range(struct lp_build_tgsi_context *bld_base,
                unsigned File, unsigned reg_index,
                const struct tgsi_ind_register *reg)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
        struct tgsi_declaration_range range;
 
        if (File == TGSI_FILE_TEMPORARY) {
@@ -417,17 +371,17 @@ get_array_range(struct lp_build_tgsi_context *bld_base,
 }
 
 static LLVMValueRef
-emit_array_index(struct lp_build_tgsi_soa_context *bld,
+emit_array_index(struct si_shader_context *ctx,
                 const struct tgsi_ind_register *reg,
                 unsigned offset)
 {
-       struct gallivm_state *gallivm = bld->bld_base.base.gallivm;
+       struct gallivm_state *gallivm = &ctx->gallivm;
 
        if (!reg) {
-               return lp_build_const_int32(gallivm, offset);
+               return LLVMConstInt(ctx->i32, offset, 0);
        }
-       LLVMValueRef addr = LLVMBuildLoad(gallivm->builder, bld->addr[reg->Index][reg->Swizzle], "");
-       return LLVMBuildAdd(gallivm->builder, addr, lp_build_const_int32(gallivm, offset), "");
+       LLVMValueRef addr = LLVMBuildLoad(gallivm->builder, ctx->addrs[reg->Index][reg->Swizzle], "");
+       return LLVMBuildAdd(gallivm->builder, addr, LLVMConstInt(ctx->i32, offset, 0), "");
 }
 
 /**
@@ -438,7 +392,7 @@ emit_array_index(struct lp_build_tgsi_soa_context *bld,
  * must be used.
  */
 static LLVMValueRef
-get_pointer_into_array(struct radeon_llvm_context *ctx,
+get_pointer_into_array(struct si_shader_context *ctx,
                       unsigned file,
                       unsigned swizzle,
                       unsigned reg_index,
@@ -446,7 +400,7 @@ get_pointer_into_array(struct radeon_llvm_context *ctx,
 {
        unsigned array_id;
        struct tgsi_array_info *array;
-       struct gallivm_state *gallivm = ctx->soa.bld_base.base.gallivm;
+       struct gallivm_state *gallivm = &ctx->gallivm;
        LLVMBuilderRef builder = gallivm->builder;
        LLVMValueRef idxs[2];
        LLVMValueRef index;
@@ -455,7 +409,7 @@ get_pointer_into_array(struct radeon_llvm_context *ctx,
        if (file != TGSI_FILE_TEMPORARY)
                return NULL;
 
-       array_id = get_temp_array_id(&ctx->soa.bld_base, reg_index, reg_indirect);
+       array_id = get_temp_array_id(&ctx->bld_base, reg_index, reg_indirect);
        if (!array_id)
                return NULL;
 
@@ -468,7 +422,7 @@ get_pointer_into_array(struct radeon_llvm_context *ctx,
        if (!(array->writemask & (1 << swizzle)))
                return ctx->undef_alloca;
 
-       index = emit_array_index(&ctx->soa, reg_indirect,
+       index = emit_array_index(ctx, reg_indirect,
                                 reg_index - ctx->temp_arrays[array_id - 1].range.First);
 
        /* Ensure that the index is within a valid range, to guard against
@@ -483,28 +437,27 @@ get_pointer_into_array(struct radeon_llvm_context *ctx,
         * 2. the memory for allocas must be allocated at the _end_ of the
         *    scratch space (after spilled registers)
         */
-       index = radeon_llvm_bound_index(ctx, index, array->range.Last - array->range.First + 1);
+       index = si_llvm_bound_index(ctx, index, array->range.Last - array->range.First + 1);
 
        index = LLVMBuildMul(
                builder, index,
-               lp_build_const_int32(gallivm, util_bitcount(array->writemask)),
+               LLVMConstInt(ctx->i32, util_bitcount(array->writemask), 0),
                "");
        index = LLVMBuildAdd(
                builder, index,
-               lp_build_const_int32(
-                       gallivm,
-                       util_bitcount(array->writemask & ((1 << swizzle) - 1))),
+               LLVMConstInt(ctx->i32,
+                            util_bitcount(array->writemask & ((1 << swizzle) - 1)), 0),
                "");
-       idxs[0] = ctx->soa.bld_base.uint_bld.zero;
+       idxs[0] = ctx->i32_0;
        idxs[1] = index;
        return LLVMBuildGEP(builder, alloca, idxs, 2, "");
 }
 
 LLVMValueRef
-radeon_llvm_emit_fetch_64bit(struct lp_build_tgsi_context *bld_base,
-                            enum tgsi_opcode_type type,
-                            LLVMValueRef ptr,
-                            LLVMValueRef ptr2)
+si_llvm_emit_fetch_64bit(struct lp_build_tgsi_context *bld_base,
+                        enum tgsi_opcode_type type,
+                        LLVMValueRef ptr,
+                        LLVMValueRef ptr2)
 {
        LLVMBuilderRef builder = bld_base->base.gallivm->builder;
        LLVMValueRef result;
@@ -528,9 +481,9 @@ emit_array_fetch(struct lp_build_tgsi_context *bld_base,
                 struct tgsi_declaration_range range,
                 unsigned swizzle)
 {
-       struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
-       struct gallivm_state *gallivm = bld->bld_base.base.gallivm;
-       LLVMBuilderRef builder = bld_base->base.gallivm->builder;
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+
+       LLVMBuilderRef builder = ctx->gallivm.builder;
 
        unsigned i, size = range.Last - range.First + 1;
        LLVMTypeRef vec = LLVMVectorType(tgsi2llvmtype(bld_base, type), size);
@@ -541,9 +494,9 @@ emit_array_fetch(struct lp_build_tgsi_context *bld_base,
 
        for (i = 0; i < size; ++i) {
                tmp_reg.Register.Index = i + range.First;
-               LLVMValueRef temp = radeon_llvm_emit_fetch(bld_base, &tmp_reg, type, swizzle);
+               LLVMValueRef temp = si_llvm_emit_fetch(bld_base, &tmp_reg, type, swizzle);
                result = LLVMBuildInsertElement(builder, result, temp,
-                       lp_build_const_int32(gallivm, i), "array_vector");
+                       LLVMConstInt(ctx->i32, i, 0), "array_vector");
        }
        return result;
 }
@@ -556,9 +509,8 @@ load_value_from_array(struct lp_build_tgsi_context *bld_base,
                      unsigned reg_index,
                      const struct tgsi_ind_register *reg_indirect)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
        LLVMBuilderRef builder = gallivm->builder;
        LLVMValueRef ptr;
 
@@ -567,9 +519,9 @@ load_value_from_array(struct lp_build_tgsi_context *bld_base,
                LLVMValueRef val = LLVMBuildLoad(builder, ptr, "");
                if (tgsi_type_is_64bit(type)) {
                        LLVMValueRef ptr_hi, val_hi;
-                       ptr_hi = LLVMBuildGEP(builder, ptr, &bld_base->uint_bld.one, 1, "");
+                       ptr_hi = LLVMBuildGEP(builder, ptr, &ctx->i32_1, 1, "");
                        val_hi = LLVMBuildLoad(builder, ptr_hi, "");
-                       val = radeon_llvm_emit_fetch_64bit(bld_base, type, val, val_hi);
+                       val = si_llvm_emit_fetch_64bit(bld_base, type, val, val_hi);
                }
 
                return val;
@@ -577,7 +529,7 @@ load_value_from_array(struct lp_build_tgsi_context *bld_base,
                struct tgsi_declaration_range range =
                        get_array_range(bld_base, file, reg_index, reg_indirect);
                LLVMValueRef index =
-                       emit_array_index(bld, reg_indirect, reg_index - range.First);
+                       emit_array_index(ctx, reg_indirect, reg_index - range.First);
                LLVMValueRef array =
                        emit_array_fetch(bld_base, file, type, range, swizzle);
                return LLVMBuildExtractElement(builder, array, index, "");
@@ -592,9 +544,8 @@ store_value_to_array(struct lp_build_tgsi_context *bld_base,
                     unsigned reg_index,
                     const struct tgsi_ind_register *reg_indirect)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
        LLVMBuilderRef builder = gallivm->builder;
        LLVMValueRef ptr;
 
@@ -604,7 +555,7 @@ store_value_to_array(struct lp_build_tgsi_context *bld_base,
        } else {
                unsigned i, size;
                struct tgsi_declaration_range range = get_array_range(bld_base, file, reg_index, reg_indirect);
-               LLVMValueRef index = emit_array_index(bld, reg_indirect, reg_index - range.First);
+               LLVMValueRef index = emit_array_index(ctx, reg_indirect, reg_index - range.First);
                LLVMValueRef array =
                        emit_array_fetch(bld_base, file, TGSI_TYPE_FLOAT, range, chan_index);
                LLVMValueRef temp_ptr;
@@ -615,7 +566,7 @@ store_value_to_array(struct lp_build_tgsi_context *bld_base,
                for (i = 0; i < size; ++i) {
                        switch(file) {
                        case TGSI_FILE_OUTPUT:
-                               temp_ptr = bld->outputs[i + range.First][chan_index];
+                               temp_ptr = ctx->outputs[i + range.First][chan_index];
                                break;
 
                        case TGSI_FILE_TEMPORARY:
@@ -628,29 +579,51 @@ store_value_to_array(struct lp_build_tgsi_context *bld_base,
                                continue;
                        }
                        value = LLVMBuildExtractElement(builder, array,
-                               lp_build_const_int32(gallivm, i), "");
+                               LLVMConstInt(ctx->i32, i, 0), "");
                        LLVMBuildStore(builder, value, temp_ptr);
                }
        }
 }
 
-LLVMValueRef radeon_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
-                                   const struct tgsi_full_src_register *reg,
-                                   enum tgsi_opcode_type type,
-                                   unsigned swizzle)
+/* If this is true, preload FS inputs at the beginning of shaders. Otherwise,
+ * reload them at each use. This must be true if the shader is using
+ * derivatives and KILL, because KILL can leave the WQM and then a lazy
+ * input load isn't in the WQM anymore.
+ */
+static bool si_preload_fs_inputs(struct si_shader_context *ctx)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
-       LLVMBuilderRef builder = bld_base->base.gallivm->builder;
+       struct si_shader_selector *sel = ctx->shader->selector;
+
+       return sel->info.uses_derivatives &&
+              sel->info.uses_kill;
+}
+
+static LLVMValueRef
+get_output_ptr(struct lp_build_tgsi_context *bld_base, unsigned index,
+              unsigned chan)
+{
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+
+       assert(index <= ctx->bld_base.info->file_max[TGSI_FILE_OUTPUT]);
+       return ctx->outputs[index][chan];
+}
+
+LLVMValueRef si_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
+                               const struct tgsi_full_src_register *reg,
+                               enum tgsi_opcode_type type,
+                               unsigned swizzle)
+{
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       LLVMBuilderRef builder = ctx->gallivm.builder;
        LLVMValueRef result = NULL, ptr, ptr2;
 
        if (swizzle == ~0) {
                LLVMValueRef values[TGSI_NUM_CHANNELS];
                unsigned chan;
                for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
-                       values[chan] = radeon_llvm_emit_fetch(bld_base, reg, type, chan);
+                       values[chan] = si_llvm_emit_fetch(bld_base, reg, type, chan);
                }
-               return lp_build_gather_values(bld_base->base.gallivm, values,
+               return lp_build_gather_values(&ctx->gallivm, values,
                                              TGSI_NUM_CHANNELS);
        }
 
@@ -664,16 +637,16 @@ LLVMValueRef radeon_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
        case TGSI_FILE_IMMEDIATE: {
                LLVMTypeRef ctype = tgsi2llvmtype(bld_base, type);
                if (tgsi_type_is_64bit(type)) {
-                       result = LLVMGetUndef(LLVMVectorType(LLVMIntTypeInContext(bld_base->base.gallivm->context, 32), bld_base->base.type.length * 2));
+                       result = LLVMGetUndef(LLVMVectorType(ctx->i32, bld_base->base.type.length * 2));
                        result = LLVMConstInsertElement(result,
-                                                       bld->immediates[reg->Register.Index][swizzle],
-                                                       bld_base->int_bld.zero);
+                                                       ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle],
+                                                       ctx->i32_0);
                        result = LLVMConstInsertElement(result,
-                                                       bld->immediates[reg->Register.Index][swizzle + 1],
-                                                       bld_base->int_bld.one);
+                                                       ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle + 1],
+                                                       ctx->i32_1);
                        return LLVMConstBitCast(result, ctype);
                } else {
-                       return LLVMConstBitCast(bld->immediates[reg->Register.Index][swizzle], ctype);
+                       return LLVMConstBitCast(ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle], ctype);
                }
        }
 
@@ -686,7 +659,8 @@ LLVMValueRef radeon_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
                 * only once. Fragment shaders don't care much, because
                 * v_interp instructions are much cheaper than VMEM loads.
                 */
-               if (ctx->soa.bld_base.info->processor == PIPE_SHADER_FRAGMENT)
+               if (!si_preload_fs_inputs(ctx) &&
+                   ctx->bld_base.info->processor == PIPE_SHADER_FRAGMENT)
                        ctx->load_input(ctx, index, &ctx->input_decls[index], input);
                else
                        memcpy(input, &ctx->inputs[index * 4], sizeof(input));
@@ -696,7 +670,7 @@ LLVMValueRef radeon_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
                if (tgsi_type_is_64bit(type)) {
                        ptr = result;
                        ptr2 = input[swizzle + 1];
-                       return radeon_llvm_emit_fetch_64bit(bld_base, type, ptr, ptr2);
+                       return si_llvm_emit_fetch_64bit(bld_base, type, ptr, ptr2);
                }
                break;
        }
@@ -707,20 +681,20 @@ LLVMValueRef radeon_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
                ptr = ctx->temps[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle];
                if (tgsi_type_is_64bit(type)) {
                        ptr2 = ctx->temps[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle + 1];
-                       return radeon_llvm_emit_fetch_64bit(bld_base, type,
-                                                LLVMBuildLoad(builder, ptr, ""),
-                                                LLVMBuildLoad(builder, ptr2, ""));
+                       return si_llvm_emit_fetch_64bit(bld_base, type,
+                                                       LLVMBuildLoad(builder, ptr, ""),
+                                                       LLVMBuildLoad(builder, ptr2, ""));
                }
                result = LLVMBuildLoad(builder, ptr, "");
                break;
 
        case TGSI_FILE_OUTPUT:
-               ptr = lp_get_output_ptr(bld, reg->Register.Index, swizzle);
+               ptr = get_output_ptr(bld_base, reg->Register.Index, swizzle);
                if (tgsi_type_is_64bit(type)) {
-                       ptr2 = lp_get_output_ptr(bld, reg->Register.Index, swizzle + 1);
-                       return radeon_llvm_emit_fetch_64bit(bld_base, type,
-                                                LLVMBuildLoad(builder, ptr, ""),
-                                                LLVMBuildLoad(builder, ptr2, ""));
+                       ptr2 = get_output_ptr(bld_base, reg->Register.Index, swizzle + 1);
+                       return si_llvm_emit_fetch_64bit(bld_base, type,
+                                                       LLVMBuildLoad(builder, ptr, ""),
+                                                       LLVMBuildLoad(builder, ptr2, ""));
                }
                result = LLVMBuildLoad(builder, ptr, "");
                break;
@@ -737,22 +711,38 @@ static LLVMValueRef fetch_system_value(struct lp_build_tgsi_context *bld_base,
                                       enum tgsi_opcode_type type,
                                       unsigned swizzle)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       LLVMBuilderRef builder = ctx->gallivm.builder;
        LLVMValueRef cval = ctx->system_values[reg->Register.Index];
+
+       if (tgsi_type_is_64bit(type)) {
+               LLVMValueRef lo, hi;
+
+               assert(swizzle == 0 || swizzle == 2);
+
+               lo = LLVMBuildExtractElement(
+                       builder, cval, LLVMConstInt(ctx->i32, swizzle, 0), "");
+               hi = LLVMBuildExtractElement(
+                       builder, cval, LLVMConstInt(ctx->i32, swizzle + 1, 0), "");
+
+               return si_llvm_emit_fetch_64bit(bld_base, type, lo, hi);
+       }
+
        if (LLVMGetTypeKind(LLVMTypeOf(cval)) == LLVMVectorTypeKind) {
-               cval = LLVMBuildExtractElement(gallivm->builder, cval,
-                                              lp_build_const_int32(gallivm, swizzle), "");
+               cval = LLVMBuildExtractElement(
+                       builder, cval, LLVMConstInt(ctx->i32, swizzle, 0), "");
+       } else {
+               assert(swizzle == 0);
        }
+
        return bitcast(bld_base, type, cval);
 }
 
 static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                             const struct tgsi_full_declaration *decl)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       LLVMBuilderRef builder = bld_base->base.gallivm->builder;
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       LLVMBuilderRef builder = ctx->gallivm.builder;
        unsigned first, last, i;
        switch(decl->Declaration.File) {
        case TGSI_FILE_ADDRESS:
@@ -761,9 +751,9 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
                        unsigned chan;
                        for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
-                                ctx->soa.addr[idx][chan] = lp_build_alloca_undef(
+                                ctx->addrs[idx][chan] = lp_build_alloca_undef(
                                        &ctx->gallivm,
-                                       ctx->soa.bld_base.uint_bld.elem_type, "");
+                                       ctx->i32, "");
                        }
                }
                break;
@@ -805,12 +795,12 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                         * FIXME: We shouldn't need to have the non-alloca
                         * code path for arrays. LLVM should be smart enough to
                         * promote allocas into registers when profitable.
-                        *
-                        * LLVM 3.8 crashes with this.
                         */
-                       if (HAVE_LLVM >= 0x0309 && array_size > 16) {
+                       if (array_size > 16 ||
+                           /* TODO: VGPR indexing is buggy on GFX9. */
+                           ctx->screen->b.chip_class == GFX9) {
                                array_alloca = LLVMBuildAlloca(builder,
-                                       LLVMArrayType(bld_base->base.vec_type,
+                                       LLVMArrayType(ctx->f32,
                                                      array_size), "array");
                                ctx->temp_array_allocas[id] = array_alloca;
                        }
@@ -827,13 +817,13 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                                         first + i / 4, "xyzw"[i % 4]);
 #endif
                                ctx->temps[first * TGSI_NUM_CHANNELS + i] =
-                                       lp_build_alloca_undef(bld_base->base.gallivm,
-                                                             bld_base->base.vec_type,
+                                       lp_build_alloca_undef(&ctx->gallivm,
+                                                             ctx->f32,
                                                              name);
                        }
                } else {
                        LLVMValueRef idxs[2] = {
-                               bld_base->uint_bld.zero,
+                               ctx->i32_0,
                                NULL
                        };
                        unsigned j = 0;
@@ -846,8 +836,8 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                                 * it never writes to.
                                 */
                                ctx->undef_alloca = lp_build_alloca_undef(
-                                       bld_base->base.gallivm,
-                                       bld_base->base.vec_type, "undef");
+                                       &ctx->gallivm,
+                                       ctx->f32, "undef");
                        }
 
                        for (i = 0; i < decl_size; ++i) {
@@ -857,7 +847,7 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                                        snprintf(name, sizeof(name), "TEMP%d.%c",
                                                 first + i / 4, "xyzw"[i % 4]);
 #endif
-                                       idxs[1] = lp_build_const_int32(bld_base->base.gallivm, j);
+                                       idxs[1] = LLVMConstInt(ctx->i32, j, 0);
                                        ptr = LLVMBuildGEP(builder, array_alloca, idxs, 2, name);
                                        j++;
                                } else {
@@ -875,9 +865,13 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                        if (ctx->load_input &&
                            ctx->input_decls[idx].Declaration.File != TGSI_FILE_INPUT) {
                                ctx->input_decls[idx] = *decl;
+                               ctx->input_decls[idx].Range.First = idx;
+                               ctx->input_decls[idx].Range.Last = idx;
+                               ctx->input_decls[idx].Semantic.Index += idx - decl->Range.First;
 
-                               if (bld_base->info->processor != PIPE_SHADER_FRAGMENT)
-                                       ctx->load_input(ctx, idx, decl,
+                               if (si_preload_fs_inputs(ctx) ||
+                                   bld_base->info->processor != PIPE_SHADER_FRAGMENT)
+                                       ctx->load_input(ctx, idx, &ctx->input_decls[idx],
                                                        &ctx->inputs[idx * 4]);
                        }
                }
@@ -900,16 +894,16 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
                for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
                        unsigned chan;
                        assert(idx < RADEON_LLVM_MAX_OUTPUTS);
-                       if (ctx->soa.outputs[idx][0])
+                       if (ctx->outputs[idx][0])
                                continue;
                        for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
 #ifdef DEBUG
                                snprintf(name, sizeof(name), "OUT%d.%c",
                                         idx, "xyzw"[chan % 4]);
 #endif
-                               ctx->soa.outputs[idx][chan] = lp_build_alloca_undef(
+                               ctx->outputs[idx][chan] = lp_build_alloca_undef(
                                        &ctx->gallivm,
-                                       ctx->soa.bld_base.base.elem_type, name);
+                                       ctx->f32, name);
                        }
                }
                break;
@@ -924,31 +918,15 @@ static void emit_declaration(struct lp_build_tgsi_context *bld_base,
        }
 }
 
-LLVMValueRef radeon_llvm_saturate(struct lp_build_tgsi_context *bld_base,
-                                  LLVMValueRef value)
-{
-       struct lp_build_emit_data clamp_emit_data;
-
-       memset(&clamp_emit_data, 0, sizeof(clamp_emit_data));
-       clamp_emit_data.arg_count = 3;
-       clamp_emit_data.args[0] = value;
-       clamp_emit_data.args[2] = bld_base->base.one;
-       clamp_emit_data.args[1] = bld_base->base.zero;
-
-       return lp_build_emit_llvm(bld_base, TGSI_OPCODE_CLAMP,
-                                 &clamp_emit_data);
-}
-
-void radeon_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
-                           const struct tgsi_full_instruction *inst,
-                           const struct tgsi_opcode_info *info,
-                           LLVMValueRef dst[4])
+void si_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
+                       const struct tgsi_full_instruction *inst,
+                       const struct tgsi_opcode_info *info,
+                       LLVMValueRef dst[4])
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
-       struct gallivm_state *gallivm = bld->bld_base.base.gallivm;
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
        const struct tgsi_full_dst_register *reg = &inst->Dst[0];
-       LLVMBuilderRef builder = bld->bld_base.base.gallivm->builder;
+       LLVMBuilderRef builder = ctx->gallivm.builder;
        LLVMValueRef temp_ptr, temp_ptr2 = NULL;
        unsigned chan, chan_index;
        bool is_vec_store = false;
@@ -962,7 +940,7 @@ void radeon_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
        if (is_vec_store) {
                LLVMValueRef values[4] = {};
                TGSI_FOR_EACH_DST0_ENABLED_CHANNEL(inst, chan) {
-                       LLVMValueRef index = lp_build_const_int32(gallivm, chan);
+                       LLVMValueRef index = LLVMConstInt(ctx->i32, chan, 0);
                        values[chan]  = LLVMBuildExtractElement(gallivm->builder,
                                                        dst[0], index, "");
                }
@@ -976,10 +954,10 @@ void radeon_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
                if (tgsi_type_is_64bit(dtype) && (chan_index == 1 || chan_index == 3))
                        continue;
                if (inst->Instruction.Saturate)
-                       value = radeon_llvm_saturate(bld_base, value);
+                       value = ac_build_clamp(&ctx->ac, value);
 
                if (reg->Register.File == TGSI_FILE_ADDRESS) {
-                       temp_ptr = bld->addr[reg->Register.Index][chan_index];
+                       temp_ptr = ctx->addrs[reg->Register.Index][chan_index];
                        LLVMBuildStore(builder, value, temp_ptr);
                        continue;
                }
@@ -995,9 +973,9 @@ void radeon_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
                } else {
                        switch(reg->Register.File) {
                        case TGSI_FILE_OUTPUT:
-                               temp_ptr = bld->outputs[reg->Register.Index][chan_index];
+                               temp_ptr = ctx->outputs[reg->Register.Index][chan_index];
                                if (tgsi_type_is_64bit(dtype))
-                                       temp_ptr2 = bld->outputs[reg->Register.Index][chan_index + 1];
+                                       temp_ptr2 = ctx->outputs[reg->Register.Index][chan_index + 1];
                                break;
 
                        case TGSI_FILE_TEMPORARY:
@@ -1018,12 +996,12 @@ void radeon_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
                                LLVMBuildStore(builder, value, temp_ptr);
                        else {
                                LLVMValueRef ptr = LLVMBuildBitCast(builder, value,
-                                                                   LLVMVectorType(LLVMIntTypeInContext(bld_base->base.gallivm->context, 32), 2), "");
+                                                                   LLVMVectorType(ctx->i32, 2), "");
                                LLVMValueRef val2;
                                value = LLVMBuildExtractElement(builder, ptr,
-                                                               bld_base->uint_bld.zero, "");
+                                                               ctx->i32_0, "");
                                val2 = LLVMBuildExtractElement(builder, ptr,
-                                                               bld_base->uint_bld.one, "");
+                                                              ctx->i32_1, "");
 
                                LLVMBuildStore(builder, bitcast(bld_base, TGSI_TYPE_FLOAT, value), temp_ptr);
                                LLVMBuildStore(builder, bitcast(bld_base, TGSI_TYPE_FLOAT, val2), temp_ptr2);
@@ -1045,7 +1023,7 @@ static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base, int pc)
 
 /* Append a basic block at the level of the parent flow.
  */
-static LLVMBasicBlockRef append_basic_block(struct radeon_llvm_context *ctx,
+static LLVMBasicBlockRef append_basic_block(struct si_shader_context *ctx,
                                            const char *name)
 {
        struct gallivm_state *gallivm = &ctx->gallivm;
@@ -1053,7 +1031,7 @@ static LLVMBasicBlockRef append_basic_block(struct radeon_llvm_context *ctx,
        assert(ctx->flow_depth >= 1);
 
        if (ctx->flow_depth >= 2) {
-               struct radeon_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
+               struct si_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
 
                return LLVMInsertBasicBlockInContext(gallivm->context,
                                                     flow->next_block, name);
@@ -1076,9 +1054,9 @@ static void bgnloop_emit(const struct lp_build_tgsi_action *action,
                         struct lp_build_tgsi_context *bld_base,
                         struct lp_build_emit_data *emit_data)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-       struct radeon_llvm_flow *flow = push_flow(ctx);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
+       struct si_llvm_flow *flow = push_flow(ctx);
        flow->loop_entry_block = append_basic_block(ctx, "LOOP");
        flow->next_block = append_basic_block(ctx, "ENDLOOP");
        set_basicblock_name(flow->loop_entry_block, "loop", bld_base->pc);
@@ -1090,9 +1068,9 @@ static void brk_emit(const struct lp_build_tgsi_action *action,
                     struct lp_build_tgsi_context *bld_base,
                     struct lp_build_emit_data *emit_data)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-       struct radeon_llvm_flow *flow = get_innermost_loop(ctx);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
+       struct si_llvm_flow *flow = get_innermost_loop(ctx);
 
        LLVMBuildBr(gallivm->builder, flow->next_block);
 }
@@ -1101,9 +1079,9 @@ static void cont_emit(const struct lp_build_tgsi_action *action,
                      struct lp_build_tgsi_context *bld_base,
                      struct lp_build_emit_data *emit_data)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-       struct radeon_llvm_flow *flow = get_innermost_loop(ctx);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
+       struct si_llvm_flow *flow = get_innermost_loop(ctx);
 
        LLVMBuildBr(gallivm->builder, flow->loop_entry_block);
 }
@@ -1112,9 +1090,9 @@ static void else_emit(const struct lp_build_tgsi_action *action,
                      struct lp_build_tgsi_context *bld_base,
                      struct lp_build_emit_data *emit_data)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-       struct radeon_llvm_flow *current_branch = get_current_flow(ctx);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
+       struct si_llvm_flow *current_branch = get_current_flow(ctx);
        LLVMBasicBlockRef endif_block;
 
        assert(!current_branch->loop_entry_block);
@@ -1132,9 +1110,9 @@ static void endif_emit(const struct lp_build_tgsi_action *action,
                       struct lp_build_tgsi_context *bld_base,
                       struct lp_build_emit_data *emit_data)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-       struct radeon_llvm_flow *current_branch = get_current_flow(ctx);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
+       struct si_llvm_flow *current_branch = get_current_flow(ctx);
 
        assert(!current_branch->loop_entry_block);
 
@@ -1149,9 +1127,9 @@ static void endloop_emit(const struct lp_build_tgsi_action *action,
                         struct lp_build_tgsi_context *bld_base,
                         struct lp_build_emit_data *emit_data)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-       struct radeon_llvm_flow *current_loop = get_current_flow(ctx);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
+       struct si_llvm_flow *current_loop = get_current_flow(ctx);
 
        assert(current_loop->loop_entry_block);
 
@@ -1167,9 +1145,9 @@ static void if_cond_emit(const struct lp_build_tgsi_action *action,
                         struct lp_build_emit_data *emit_data,
                         LLVMValueRef cond)
 {
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
-       struct gallivm_state *gallivm = bld_base->base.gallivm;
-       struct radeon_llvm_flow *flow = push_flow(ctx);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct gallivm_state *gallivm = &ctx->gallivm;
+       struct si_llvm_flow *flow = push_flow(ctx);
        LLVMBasicBlockRef if_block;
 
        if_block = append_basic_block(ctx, "IF");
@@ -1211,19 +1189,19 @@ static void emit_immediate(struct lp_build_tgsi_context *bld_base,
                           const struct tgsi_full_immediate *imm)
 {
        unsigned i;
-       struct radeon_llvm_context *ctx = radeon_llvm_context(bld_base);
+       struct si_shader_context *ctx = si_shader_context(bld_base);
 
        for (i = 0; i < 4; ++i) {
-               ctx->soa.immediates[ctx->soa.num_immediates][i] =
-                               LLVMConstInt(bld_base->uint_bld.elem_type, imm->u[i].Uint, false   );
+               ctx->imms[ctx->imms_num * TGSI_NUM_CHANNELS + i] =
+                               LLVMConstInt(ctx->i32, imm->u[i].Uint, false   );
        }
 
-       ctx->soa.num_immediates++;
+       ctx->imms_num++;
 }
 
-void radeon_llvm_context_init(struct radeon_llvm_context *ctx, const char *triple,
-                             const struct tgsi_shader_info *info,
-                             const struct tgsi_token *tokens)
+void si_llvm_context_init(struct si_shader_context *ctx,
+                         struct si_screen *sscreen,
+                         LLVMTargetMachineRef tm)
 {
        struct lp_type type;
 
@@ -1232,28 +1210,34 @@ void radeon_llvm_context_init(struct radeon_llvm_context *ctx, const char *tripl
         * This should be enough for us to be able to pass our gallivm struct to the
         * helper functions in the gallivm module.
         */
-       memset(&ctx->gallivm, 0, sizeof (ctx->gallivm));
-       memset(&ctx->soa, 0, sizeof(ctx->soa));
+       memset(ctx, 0, sizeof(*ctx));
+       ctx->screen = sscreen;
+       ctx->tm = tm;
+
        ctx->gallivm.context = LLVMContextCreate();
        ctx->gallivm.module = LLVMModuleCreateWithNameInContext("tgsi",
                                                ctx->gallivm.context);
-       LLVMSetTarget(ctx->gallivm.module, triple);
-       ctx->gallivm.builder = LLVMCreateBuilderInContext(ctx->gallivm.context);
+       LLVMSetTarget(ctx->gallivm.module, "amdgcn--");
 
-       struct lp_build_tgsi_context *bld_base = &ctx->soa.bld_base;
+       LLVMTargetDataRef data_layout = LLVMCreateTargetDataLayout(tm);
+       char *data_layout_str = LLVMCopyStringRepOfTargetData(data_layout);
+       LLVMSetDataLayout(ctx->gallivm.module, data_layout_str);
+       LLVMDisposeTargetData(data_layout);
+       LLVMDisposeMessage(data_layout_str);
 
-       bld_base->info = info;
+       bool unsafe_fpmath = (sscreen->b.debug_flags & DBG_UNSAFE_MATH) != 0;
+       enum lp_float_mode float_mode =
+               unsafe_fpmath ? LP_FLOAT_MODE_UNSAFE_FP_MATH :
+                               LP_FLOAT_MODE_NO_SIGNED_ZEROS_FP_MATH;
 
-       if (info && info->array_max[TGSI_FILE_TEMPORARY] > 0) {
-               int size = info->array_max[TGSI_FILE_TEMPORARY];
+       ctx->gallivm.builder = lp_create_builder(ctx->gallivm.context,
+                                                float_mode);
 
-               ctx->temp_arrays = CALLOC(size, sizeof(ctx->temp_arrays[0]));
-               ctx->temp_array_allocas = CALLOC(size, sizeof(ctx->temp_array_allocas[0]));
+       ac_llvm_context_init(&ctx->ac, ctx->gallivm.context);
+       ctx->ac.module = ctx->gallivm.module;
+       ctx->ac.builder = ctx->gallivm.builder;
 
-               if (tokens)
-                       tgsi_scan_arrays(tokens, TGSI_FILE_TEMPORARY, size,
-                                        ctx->temp_arrays);
-       }
+       struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
 
        type.floating = true;
        type.fixed = false;
@@ -1263,25 +1247,18 @@ void radeon_llvm_context_init(struct radeon_llvm_context *ctx, const char *tripl
        type.length = 1;
 
        lp_build_context_init(&bld_base->base, &ctx->gallivm, type);
-       lp_build_context_init(&ctx->soa.bld_base.uint_bld, &ctx->gallivm, lp_uint_type(type));
-       lp_build_context_init(&ctx->soa.bld_base.int_bld, &ctx->gallivm, lp_int_type(type));
+       lp_build_context_init(&ctx->bld_base.uint_bld, &ctx->gallivm, lp_uint_type(type));
+       lp_build_context_init(&ctx->bld_base.int_bld, &ctx->gallivm, lp_int_type(type));
        type.width *= 2;
-       lp_build_context_init(&ctx->soa.bld_base.dbl_bld, &ctx->gallivm, type);
-       lp_build_context_init(&ctx->soa.bld_base.uint64_bld, &ctx->gallivm, lp_uint_type(type));
-       lp_build_context_init(&ctx->soa.bld_base.int64_bld, &ctx->gallivm, lp_int_type(type));
+       lp_build_context_init(&ctx->bld_base.dbl_bld, &ctx->gallivm, type);
+       lp_build_context_init(&ctx->bld_base.uint64_bld, &ctx->gallivm, lp_uint_type(type));
+       lp_build_context_init(&ctx->bld_base.int64_bld, &ctx->gallivm, lp_int_type(type));
 
        bld_base->soa = 1;
-       bld_base->emit_store = radeon_llvm_emit_store;
        bld_base->emit_swizzle = emit_swizzle;
        bld_base->emit_declaration = emit_declaration;
        bld_base->emit_immediate = emit_immediate;
 
-       bld_base->emit_fetch_funcs[TGSI_FILE_IMMEDIATE] = radeon_llvm_emit_fetch;
-       bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = radeon_llvm_emit_fetch;
-       bld_base->emit_fetch_funcs[TGSI_FILE_TEMPORARY] = radeon_llvm_emit_fetch;
-       bld_base->emit_fetch_funcs[TGSI_FILE_OUTPUT] = radeon_llvm_emit_fetch;
-       bld_base->emit_fetch_funcs[TGSI_FILE_SYSTEM_VALUE] = fetch_system_value;
-
        /* metadata allowing 2.5 ULP */
        ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->gallivm.context,
                                                       "fpmath", 6);
@@ -1289,9 +1266,6 @@ void radeon_llvm_context_init(struct radeon_llvm_context *ctx, const char *tripl
        ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->gallivm.context,
                                                     &arg, 1);
 
-       /* Allocate outputs */
-       ctx->soa.outputs = ctx->outputs;
-
        bld_base->op_actions[TGSI_OPCODE_BGNLOOP].emit = bgnloop_emit;
        bld_base->op_actions[TGSI_OPCODE_BRK].emit = brk_emit;
        bld_base->op_actions[TGSI_OPCODE_CONT].emit = cont_emit;
@@ -1300,14 +1274,94 @@ void radeon_llvm_context_init(struct radeon_llvm_context *ctx, const char *tripl
        bld_base->op_actions[TGSI_OPCODE_ELSE].emit = else_emit;
        bld_base->op_actions[TGSI_OPCODE_ENDIF].emit = endif_emit;
        bld_base->op_actions[TGSI_OPCODE_ENDLOOP].emit = endloop_emit;
+
+       si_shader_context_init_alu(&ctx->bld_base);
+
+       ctx->voidt = LLVMVoidTypeInContext(ctx->gallivm.context);
+       ctx->i1 = LLVMInt1TypeInContext(ctx->gallivm.context);
+       ctx->i8 = LLVMInt8TypeInContext(ctx->gallivm.context);
+       ctx->i32 = LLVMInt32TypeInContext(ctx->gallivm.context);
+       ctx->i64 = LLVMInt64TypeInContext(ctx->gallivm.context);
+       ctx->i128 = LLVMIntTypeInContext(ctx->gallivm.context, 128);
+       ctx->f32 = LLVMFloatTypeInContext(ctx->gallivm.context);
+       ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
+       ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
+       ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
+       ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
+
+       ctx->i32_0 = LLVMConstInt(ctx->i32, 0, 0);
+       ctx->i32_1 = LLVMConstInt(ctx->i32, 1, 0);
+}
+
+/* Set the context to a certain TGSI shader. Can be called repeatedly
+ * to change the shader. */
+void si_llvm_context_set_tgsi(struct si_shader_context *ctx,
+                             struct si_shader *shader)
+{
+       const struct tgsi_shader_info *info = NULL;
+       const struct tgsi_token *tokens = NULL;
+
+       if (shader && shader->selector) {
+               info = &shader->selector->info;
+               tokens = shader->selector->tokens;
+       }
+
+       ctx->shader = shader;
+       ctx->type = info ? info->processor : -1;
+       ctx->bld_base.info = info;
+
+       /* Clean up the old contents. */
+       FREE(ctx->temp_arrays);
+       ctx->temp_arrays = NULL;
+       FREE(ctx->temp_array_allocas);
+       ctx->temp_array_allocas = NULL;
+
+       FREE(ctx->imms);
+       ctx->imms = NULL;
+       ctx->imms_num = 0;
+
+       FREE(ctx->temps);
+       ctx->temps = NULL;
+       ctx->temps_count = 0;
+
+       if (!info || !tokens)
+               return;
+
+       if (info->array_max[TGSI_FILE_TEMPORARY] > 0) {
+               int size = info->array_max[TGSI_FILE_TEMPORARY];
+
+               ctx->temp_arrays = CALLOC(size, sizeof(ctx->temp_arrays[0]));
+               ctx->temp_array_allocas = CALLOC(size, sizeof(ctx->temp_array_allocas[0]));
+
+               tgsi_scan_arrays(tokens, TGSI_FILE_TEMPORARY, size,
+                                ctx->temp_arrays);
+       }
+       if (info->file_max[TGSI_FILE_IMMEDIATE] >= 0) {
+               int size = info->file_max[TGSI_FILE_IMMEDIATE] + 1;
+               ctx->imms = MALLOC(size * TGSI_NUM_CHANNELS * sizeof(LLVMValueRef));
+       }
+
+       /* Re-set these to start with a clean slate. */
+       ctx->bld_base.num_instructions = 0;
+       ctx->bld_base.pc = 0;
+       memset(ctx->outputs, 0, sizeof(ctx->outputs));
+
+       ctx->bld_base.emit_store = si_llvm_emit_store;
+       ctx->bld_base.emit_fetch_funcs[TGSI_FILE_IMMEDIATE] = si_llvm_emit_fetch;
+       ctx->bld_base.emit_fetch_funcs[TGSI_FILE_INPUT] = si_llvm_emit_fetch;
+       ctx->bld_base.emit_fetch_funcs[TGSI_FILE_TEMPORARY] = si_llvm_emit_fetch;
+       ctx->bld_base.emit_fetch_funcs[TGSI_FILE_OUTPUT] = si_llvm_emit_fetch;
+       ctx->bld_base.emit_fetch_funcs[TGSI_FILE_SYSTEM_VALUE] = fetch_system_value;
 }
 
-void radeon_llvm_create_func(struct radeon_llvm_context *ctx,
-                            LLVMTypeRef *return_types, unsigned num_return_elems,
-                            LLVMTypeRef *ParamTypes, unsigned ParamCount)
+void si_llvm_create_func(struct si_shader_context *ctx,
+                        const char *name,
+                        LLVMTypeRef *return_types, unsigned num_return_elems,
+                        LLVMTypeRef *ParamTypes, unsigned ParamCount)
 {
        LLVMTypeRef main_fn_type, ret_type;
        LLVMBasicBlockRef main_fn_body;
+       enum si_llvm_calling_convention call_conv;
 
        if (num_return_elems)
                ret_type = LLVMStructTypeInContext(ctx->gallivm.context,
@@ -1319,29 +1373,55 @@ void radeon_llvm_create_func(struct radeon_llvm_context *ctx,
        /* Setup the function */
        ctx->return_type = ret_type;
        main_fn_type = LLVMFunctionType(ret_type, ParamTypes, ParamCount, 0);
-       ctx->main_fn = LLVMAddFunction(ctx->gallivm.module, "main", main_fn_type);
+       ctx->main_fn = LLVMAddFunction(ctx->gallivm.module, name, main_fn_type);
        main_fn_body = LLVMAppendBasicBlockInContext(ctx->gallivm.context,
                        ctx->main_fn, "main_body");
        LLVMPositionBuilderAtEnd(ctx->gallivm.builder, main_fn_body);
+
+       switch (ctx->type) {
+       case PIPE_SHADER_VERTEX:
+       case PIPE_SHADER_TESS_CTRL:
+       case PIPE_SHADER_TESS_EVAL:
+               call_conv = RADEON_LLVM_AMDGPU_VS;
+               break;
+       case PIPE_SHADER_GEOMETRY:
+               call_conv = RADEON_LLVM_AMDGPU_GS;
+               break;
+       case PIPE_SHADER_FRAGMENT:
+               call_conv = RADEON_LLVM_AMDGPU_PS;
+               break;
+       case PIPE_SHADER_COMPUTE:
+               call_conv = RADEON_LLVM_AMDGPU_CS;
+               break;
+       default:
+               unreachable("Unhandle shader type");
+       }
+
+       LLVMSetFunctionCallConv(ctx->main_fn, call_conv);
 }
 
-void radeon_llvm_finalize_module(struct radeon_llvm_context *ctx,
-                                bool run_verifier)
+void si_llvm_optimize_module(struct si_shader_context *ctx)
 {
-       struct gallivm_state *gallivm = ctx->soa.bld_base.base.gallivm;
+       struct gallivm_state *gallivm = &ctx->gallivm;
        const char *triple = LLVMGetTarget(gallivm->module);
        LLVMTargetLibraryInfoRef target_library_info;
 
+       /* Dump LLVM IR before any optimization passes */
+       if (ctx->screen->b.debug_flags & DBG_PREOPT_IR &&
+           r600_can_dump_shader(&ctx->screen->b, ctx->type))
+               LLVMDumpModule(ctx->gallivm.module);
+
        /* Create the pass manager */
-       gallivm->passmgr = LLVMCreateFunctionPassManagerForModule(
-                                                       gallivm->module);
+       gallivm->passmgr = LLVMCreatePassManager();
 
        target_library_info = gallivm_create_target_library_info(triple);
        LLVMAddTargetLibraryInfo(target_library_info, gallivm->passmgr);
 
-       if (run_verifier)
+       if (r600_extra_shader_checks(&ctx->screen->b, ctx->type))
                LLVMAddVerifierPass(gallivm->passmgr);
 
+       LLVMAddAlwaysInlinerPass(gallivm->passmgr);
+
        /* This pass should eliminate all the load and store instructions */
        LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
 
@@ -1353,19 +1433,17 @@ void radeon_llvm_finalize_module(struct radeon_llvm_context *ctx,
        LLVMAddInstructionCombiningPass(gallivm->passmgr);
 
        /* Run the pass */
-       LLVMInitializeFunctionPassManager(gallivm->passmgr);
-       LLVMRunFunctionPassManager(gallivm->passmgr, ctx->main_fn);
-       LLVMFinalizeFunctionPassManager(gallivm->passmgr);
+       LLVMRunPassManager(gallivm->passmgr, ctx->gallivm.module);
 
        LLVMDisposeBuilder(gallivm->builder);
        LLVMDisposePassManager(gallivm->passmgr);
        gallivm_dispose_target_library_info(target_library_info);
 }
 
-void radeon_llvm_dispose(struct radeon_llvm_context *ctx)
+void si_llvm_dispose(struct si_shader_context *ctx)
 {
-       LLVMDisposeModule(ctx->soa.bld_base.base.gallivm->module);
-       LLVMContextDispose(ctx->soa.bld_base.base.gallivm->context);
+       LLVMDisposeModule(ctx->gallivm.module);
+       LLVMContextDispose(ctx->gallivm.context);
        FREE(ctx->temp_arrays);
        ctx->temp_arrays = NULL;
        FREE(ctx->temp_array_allocas);
@@ -1373,6 +1451,9 @@ void radeon_llvm_dispose(struct radeon_llvm_context *ctx)
        FREE(ctx->temps);
        ctx->temps = NULL;
        ctx->temps_count = 0;
+       FREE(ctx->imms);
+       ctx->imms = NULL;
+       ctx->imms_num = 0;
        FREE(ctx->flow);
        ctx->flow = NULL;
        ctx->flow_depth_max = 0;