nir/spirv: Move CF emit code into vtn_cfg.c
[mesa.git] / src / glsl / lower_ubo_reference.cpp
index 31885cd3dec4610aac2515c9d7ef10894484c8bb..a172054bac8279f399e2b00867e8b12642d29f86 100644 (file)
  * their own.
  */
 
-#include "ir.h"
+#include "lower_buffer_access.h"
 #include "ir_builder.h"
-#include "ir_rvalue_visitor.h"
 #include "main/macros.h"
 #include "glsl_parser_extras.h"
 
 using namespace ir_builder;
 
-/**
- * Determine if a thing being dereferenced is row-major
- *
- * There is some trickery here.
- *
- * If the thing being dereferenced is a member of uniform block \b without an
- * instance name, then the name of the \c ir_variable is the field name of an
- * interface type.  If this field is row-major, then the thing referenced is
- * row-major.
- *
- * If the thing being dereferenced is a member of uniform block \b with an
- * instance name, then the last dereference in the tree will be an
- * \c ir_dereference_record.  If that record field is row-major, then the
- * thing referenced is row-major.
- */
-static bool
-is_dereferenced_thing_row_major(const ir_rvalue *deref)
-{
-   bool matrix = false;
-   const ir_rvalue *ir = deref;
-
-   while (true) {
-      matrix = matrix || ir->type->without_array()->is_matrix();
-
-      switch (ir->ir_type) {
-      case ir_type_dereference_array: {
-         const ir_dereference_array *const array_deref =
-            (const ir_dereference_array *) ir;
-
-         ir = array_deref->array;
-         break;
-      }
-
-      case ir_type_dereference_record: {
-         const ir_dereference_record *const record_deref =
-            (const ir_dereference_record *) ir;
-
-         ir = record_deref->record;
-
-         const int idx = ir->type->field_index(record_deref->field);
-         assert(idx >= 0);
-
-         const enum glsl_matrix_layout matrix_layout =
-            glsl_matrix_layout(ir->type->fields.structure[idx].matrix_layout);
-
-         switch (matrix_layout) {
-         case GLSL_MATRIX_LAYOUT_INHERITED:
-            break;
-         case GLSL_MATRIX_LAYOUT_COLUMN_MAJOR:
-            return false;
-         case GLSL_MATRIX_LAYOUT_ROW_MAJOR:
-            return matrix || deref->type->without_array()->is_record();
-         }
-
-         break;
-      }
-
-      case ir_type_dereference_variable: {
-         const ir_dereference_variable *const var_deref =
-            (const ir_dereference_variable *) ir;
-
-         const enum glsl_matrix_layout matrix_layout =
-            glsl_matrix_layout(var_deref->var->data.matrix_layout);
-
-         switch (matrix_layout) {
-         case GLSL_MATRIX_LAYOUT_INHERITED:
-            assert(!matrix);
-            return false;
-         case GLSL_MATRIX_LAYOUT_COLUMN_MAJOR:
-            return false;
-         case GLSL_MATRIX_LAYOUT_ROW_MAJOR:
-            return matrix || deref->type->without_array()->is_record();
-         }
-
-         unreachable("invalid matrix layout");
-         break;
-      }
-
-      default:
-         return false;
-      }
-   }
-
-   /* The tree must have ended with a dereference that wasn't an
-    * ir_dereference_variable.  That is invalid, and it should be impossible.
-    */
-   unreachable("invalid dereference tree");
-   return false;
-}
-
 namespace {
-class lower_ubo_reference_visitor : public ir_rvalue_enter_visitor {
+class lower_ubo_reference_visitor :
+      public lower_buffer_access::lower_buffer_access {
 public:
    lower_ubo_reference_visitor(struct gl_shader *shader)
    : shader(shader)
@@ -142,30 +52,38 @@ public:
    void handle_rvalue(ir_rvalue **rvalue);
    ir_visitor_status visit_enter(ir_assignment *ir);
 
-   void setup_for_load_or_store(ir_variable *var,
+   void setup_for_load_or_store(void *mem_ctx,
+                                ir_variable *var,
                                 ir_rvalue *deref,
                                 ir_rvalue **offset,
                                 unsigned *const_offset,
                                 bool *row_major,
                                 int *matrix_columns,
                                 unsigned packing);
-   ir_expression *ubo_load(const struct glsl_type *type,
+   ir_expression *ubo_load(void *mem_ctx, const struct glsl_type *type,
                           ir_rvalue *offset);
-   ir_call *ssbo_load(const struct glsl_type *type,
+   ir_call *ssbo_load(void *mem_ctx, const struct glsl_type *type,
                       ir_rvalue *offset);
 
+   bool check_for_buffer_array_copy(ir_assignment *ir);
+   bool check_for_buffer_struct_copy(ir_assignment *ir);
    void check_for_ssbo_store(ir_assignment *ir);
-   void write_to_memory(ir_dereference *deref,
-                        ir_variable *var,
-                        ir_variable *write_var,
-                        unsigned write_mask);
-   ir_call *ssbo_store(ir_rvalue *deref, ir_rvalue *offset,
+   void write_to_memory(void *mem_ctx, ir_dereference *deref, ir_variable *var,
+                        ir_variable *write_var, unsigned write_mask);
+   ir_call *ssbo_store(void *mem_ctx, ir_rvalue *deref, ir_rvalue *offset,
                        unsigned write_mask);
 
-   void emit_access(bool is_write, ir_dereference *deref,
-                    ir_variable *base_offset, unsigned int deref_offset,
-                    bool row_major, int matrix_columns,
-                    unsigned packing, unsigned write_mask);
+   enum {
+      ubo_load_access,
+      ssbo_load_access,
+      ssbo_store_access,
+      ssbo_unsized_array_length_access,
+      ssbo_atomic_access,
+   } buffer_access_type;
+
+   void insert_buffer_access(void *mem_ctx, ir_dereference *deref,
+                             const glsl_type *type, ir_rvalue *offset,
+                             unsigned mask, int channel);
 
    ir_visitor_status visit_enter(class ir_expression *);
    ir_expression *calculate_ssbo_unsized_array_length(ir_expression *expr);
@@ -175,7 +93,7 @@ public:
    ir_expression *process_ssbo_unsized_array_length(ir_rvalue **,
                                                     ir_dereference *,
                                                     ir_variable *);
-   ir_expression *emit_ssbo_get_buffer_size();
+   ir_expression *emit_ssbo_get_buffer_size(void *mem_ctx);
 
    unsigned calculate_unsized_array_stride(ir_dereference *deref,
                                            unsigned packing);
@@ -184,12 +102,10 @@ public:
    ir_call *check_for_ssbo_atomic_intrinsic(ir_call *ir);
    ir_visitor_status visit_enter(ir_call *ir);
 
-   void *mem_ctx;
    struct gl_shader *shader;
    struct gl_uniform_buffer_variable *ubo_var;
    ir_rvalue *uniform_block;
    bool progress;
-   bool is_shader_storage;
 };
 
 /**
@@ -203,55 +119,116 @@ static const char *
 interface_field_name(void *mem_ctx, char *base_name, ir_rvalue *d,
                      ir_rvalue **nonconst_block_index)
 {
-   ir_rvalue *previous_index = NULL;
    *nonconst_block_index = NULL;
+   char *name_copy = NULL;
+   size_t base_length = 0;
+
+   /* Loop back through the IR until we find the uniform block */
+   ir_rvalue *ir = d;
+   while (ir != NULL) {
+      switch (ir->ir_type) {
+      case ir_type_dereference_variable: {
+         /* Exit loop */
+         ir = NULL;
+         break;
+      }
+
+      case ir_type_dereference_record: {
+         ir_dereference_record *r = (ir_dereference_record *) ir;
+         ir = r->record->as_dereference();
+
+         /* If we got here it means any previous array subscripts belong to
+          * block members and not the block itself so skip over them in the
+          * next pass.
+          */
+         d = ir;
+         break;
+      }
+
+      case ir_type_dereference_array: {
+         ir_dereference_array *a = (ir_dereference_array *) ir;
+         ir = a->array->as_dereference();
+         break;
+      }
+
+      case ir_type_swizzle: {
+         ir_swizzle *s = (ir_swizzle *) ir;
+         ir = s->val->as_dereference();
+         /* Skip swizzle in the next pass */
+         d = ir;
+         break;
+      }
+
+      default:
+         assert(!"Should not get here.");
+         break;
+      }
+   }
 
    while (d != NULL) {
       switch (d->ir_type) {
       case ir_type_dereference_variable: {
          ir_dereference_variable *v = (ir_dereference_variable *) d;
-         if (previous_index
-             && v->var->is_interface_instance()
-             && v->var->type->is_array()) {
-
-            ir_constant *const_index = previous_index->as_constant();
-            if (!const_index) {
-               *nonconst_block_index = previous_index;
-               return ralloc_asprintf(mem_ctx, "%s[0]", base_name);
-            } else {
-               return ralloc_asprintf(mem_ctx,
-                                      "%s[%d]",
-                                      base_name,
-                                      const_index->get_uint_component(0));
-            }
+         if (name_copy != NULL &&
+             v->var->is_interface_instance() &&
+             v->var->type->is_array()) {
+            return name_copy;
          } else {
+            *nonconst_block_index = NULL;
             return base_name;
          }
 
          break;
       }
 
-      case ir_type_dereference_record: {
-         ir_dereference_record *r = (ir_dereference_record *) d;
-
-         d = r->record->as_dereference();
-         break;
-      }
-
       case ir_type_dereference_array: {
          ir_dereference_array *a = (ir_dereference_array *) d;
+         size_t new_length;
+
+         if (name_copy == NULL) {
+            name_copy = ralloc_strdup(mem_ctx, base_name);
+            base_length = strlen(name_copy);
+         }
+
+         /* For arrays of arrays we start at the innermost array and work our
+          * way out so we need to insert the subscript at the base of the
+          * name string rather than just attaching it to the end.
+          */
+         new_length = base_length;
+         ir_constant *const_index = a->array_index->as_constant();
+         char *end = ralloc_strdup(NULL, &name_copy[new_length]);
+         if (!const_index) {
+            ir_rvalue *array_index = a->array_index;
+            if (array_index->type != glsl_type::uint_type)
+               array_index = i2u(array_index);
+
+            if (a->array->type->is_array() &&
+                a->array->type->fields.array->is_array()) {
+               ir_constant *base_size = new(mem_ctx)
+                  ir_constant(a->array->type->fields.array->arrays_of_arrays_size());
+               array_index = mul(array_index, base_size);
+            }
+
+            if (*nonconst_block_index) {
+               *nonconst_block_index = add(*nonconst_block_index, array_index);
+            } else {
+               *nonconst_block_index = array_index;
+            }
+
+            ralloc_asprintf_rewrite_tail(&name_copy, &new_length, "[0]%s",
+                                         end);
+         } else {
+            ralloc_asprintf_rewrite_tail(&name_copy, &new_length, "[%d]%s",
+                                         const_index->get_uint_component(0),
+                                         end);
+         }
+         ralloc_free(end);
 
          d = a->array->as_dereference();
-         previous_index = a->array_index;
 
          break;
       }
-      case ir_type_swizzle: {
-         ir_swizzle *s = (ir_swizzle *) d;
 
-         d = s->val->as_dereference();
-         break;
-      }
       default:
          assert(!"Should not get here.");
          break;
@@ -263,7 +240,8 @@ interface_field_name(void *mem_ctx, char *base_name, ir_rvalue *d,
 }
 
 void
-lower_ubo_reference_visitor::setup_for_load_or_store(ir_variable *var,
+lower_ubo_reference_visitor::setup_for_load_or_store(void *mem_ctx,
+                                                     ir_variable *var,
                                                      ir_rvalue *deref,
                                                      ir_rvalue **offset,
                                                      unsigned *const_offset,
@@ -277,27 +255,30 @@ lower_ubo_reference_visitor::setup_for_load_or_store(ir_variable *var,
       interface_field_name(mem_ctx, (char *) var->get_interface_type()->name,
                            deref, &nonconst_block_index);
 
-   /* Locate the ubo block by interface name */
+   /* Locate the block by interface name */
+   unsigned num_blocks;
+   struct gl_uniform_block **blocks;
+   if (this->buffer_access_type != ubo_load_access) {
+      num_blocks = shader->NumShaderStorageBlocks;
+      blocks = shader->ShaderStorageBlocks;
+   } else {
+      num_blocks = shader->NumUniformBlocks;
+      blocks = shader->UniformBlocks;
+   }
    this->uniform_block = NULL;
-   for (unsigned i = 0; i < shader->NumUniformBlocks; i++) {
-      if (strcmp(field_name, shader->UniformBlocks[i].Name) == 0) {
+   for (unsigned i = 0; i < num_blocks; i++) {
+      if (strcmp(field_name, blocks[i]->Name) == 0) {
 
          ir_constant *index = new(mem_ctx) ir_constant(i);
 
          if (nonconst_block_index) {
-            if (nonconst_block_index->type != glsl_type::uint_type)
-               nonconst_block_index = i2u(nonconst_block_index);
             this->uniform_block = add(nonconst_block_index, index);
          } else {
             this->uniform_block = index;
          }
 
-         this->is_shader_storage = shader->UniformBlocks[i].IsShaderStorage;
-
-         struct gl_uniform_block *block = &shader->UniformBlocks[i];
-
          this->ubo_var = var->is_interface_instance()
-            ? &block->Uniforms[0] : &block->Uniforms[var->data.location];
+            ? &blocks[i]->Uniforms[0] : &blocks[i]->Uniforms[var->data.location];
 
          break;
       }
@@ -305,153 +286,10 @@ lower_ubo_reference_visitor::setup_for_load_or_store(ir_variable *var,
 
    assert(this->uniform_block);
 
-   *offset = new(mem_ctx) ir_constant(0u);
-   *const_offset = 0;
-   *row_major = is_dereferenced_thing_row_major(deref);
-   *matrix_columns = 1;
-
-   /* Calculate the offset to the start of the region of the UBO
-    * dereferenced by *rvalue.  This may be a variable offset if an
-    * array dereference has a variable index.
-    */
-   while (deref) {
-      switch (deref->ir_type) {
-      case ir_type_dereference_variable: {
-         *const_offset += ubo_var->Offset;
-         deref = NULL;
-         break;
-      }
-
-      case ir_type_dereference_array: {
-         ir_dereference_array *deref_array = (ir_dereference_array *) deref;
-         unsigned array_stride;
-         if (deref_array->array->type->is_matrix() && *row_major) {
-            /* When loading a vector out of a row major matrix, the
-             * step between the columns (vectors) is the size of a
-             * float, while the step between the rows (elements of a
-             * vector) is handled below in emit_ubo_loads.
-             */
-            array_stride = 4;
-            if (deref_array->array->type->is_double())
-               array_stride *= 2;
-            *matrix_columns = deref_array->array->type->matrix_columns;
-         } else if (deref_array->type->is_interface()) {
-            /* We're processing an array dereference of an interface instance
-             * array. The thing being dereferenced *must* be a variable
-             * dereference because interfaces cannot be embedded in other
-             * types. In terms of calculating the offsets for the lowering
-             * pass, we don't care about the array index. All elements of an
-             * interface instance array will have the same offsets relative to
-             * the base of the block that backs them.
-             */
-            assert(deref_array->array->as_dereference_variable());
-            deref = deref_array->array->as_dereference();
-            break;
-         } else {
-            /* Whether or not the field is row-major (because it might be a
-             * bvec2 or something) does not affect the array itself. We need
-             * to know whether an array element in its entirety is row-major.
-             */
-            const bool array_row_major =
-               is_dereferenced_thing_row_major(deref_array);
-
-            /* The array type will give the correct interface packing
-             * information
-             */
-            if (packing == GLSL_INTERFACE_PACKING_STD430) {
-               array_stride = deref_array->type->std430_array_stride(array_row_major);
-            } else {
-               array_stride = deref_array->type->std140_size(array_row_major);
-               array_stride = glsl_align(array_stride, 16);
-            }
-         }
-
-         ir_rvalue *array_index = deref_array->array_index;
-         if (array_index->type->base_type == GLSL_TYPE_INT)
-            array_index = i2u(array_index);
-
-         ir_constant *const_index =
-            array_index->constant_expression_value(NULL);
-         if (const_index) {
-            *const_offset += array_stride * const_index->value.u[0];
-         } else {
-            *offset = add(*offset,
-                          mul(array_index,
-                              new(mem_ctx) ir_constant(array_stride)));
-         }
-         deref = deref_array->array->as_dereference();
-         break;
-      }
-
-      case ir_type_dereference_record: {
-         ir_dereference_record *deref_record = (ir_dereference_record *) deref;
-         const glsl_type *struct_type = deref_record->record->type;
-         unsigned intra_struct_offset = 0;
-
-         for (unsigned int i = 0; i < struct_type->length; i++) {
-            const glsl_type *type = struct_type->fields.structure[i].type;
-
-            ir_dereference_record *field_deref = new(mem_ctx)
-               ir_dereference_record(deref_record->record,
-                                     struct_type->fields.structure[i].name);
-            const bool field_row_major =
-               is_dereferenced_thing_row_major(field_deref);
-
-            ralloc_free(field_deref);
-
-            unsigned field_align = 0;
-
-            if (packing == GLSL_INTERFACE_PACKING_STD430)
-               field_align = type->std430_base_alignment(field_row_major);
-            else
-               field_align = type->std140_base_alignment(field_row_major);
-
-            intra_struct_offset = glsl_align(intra_struct_offset, field_align);
-
-            if (strcmp(struct_type->fields.structure[i].name,
-                       deref_record->field) == 0)
-               break;
-
-            if (packing == GLSL_INTERFACE_PACKING_STD430)
-               intra_struct_offset += type->std430_size(field_row_major);
-            else
-               intra_struct_offset += type->std140_size(field_row_major);
-
-            /* If the field just examined was itself a structure, apply rule
-             * #9:
-             *
-             *     "The structure may have padding at the end; the base offset
-             *     of the member following the sub-structure is rounded up to
-             *     the next multiple of the base alignment of the structure."
-             */
-            if (type->without_array()->is_record()) {
-               intra_struct_offset = glsl_align(intra_struct_offset,
-                                                field_align);
-
-            }
-         }
-
-         *const_offset += intra_struct_offset;
-         deref = deref_record->record->as_dereference();
-         break;
-      }
-
-      case ir_type_swizzle: {
-         ir_swizzle *deref_swizzle = (ir_swizzle *) deref;
-
-         assert(deref_swizzle->mask.num_components == 1);
+   *const_offset = ubo_var->Offset;
 
-         *const_offset += deref_swizzle->mask.x * sizeof(int);
-         deref = deref_swizzle->val->as_dereference();
-         break;
-      }
-
-      default:
-         assert(!"not reached");
-         deref = NULL;
-         break;
-      }
-   }
+   setup_buffer_access(mem_ctx, var, deref, offset, const_offset, row_major,
+                       matrix_columns, packing);
 }
 
 void
@@ -468,7 +306,7 @@ lower_ubo_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
    if (!var || !var->is_in_buffer_block())
       return;
 
-   mem_ctx = ralloc_parent(shader->ir);
+   void *mem_ctx = ralloc_parent(shader->ir);
 
    ir_rvalue *offset = NULL;
    unsigned const_offset;
@@ -476,10 +314,14 @@ lower_ubo_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
    int matrix_columns;
    unsigned packing = var->get_interface_type()->interface_packing;
 
+   this->buffer_access_type =
+      var->is_in_shader_storage_block() ?
+      ssbo_load_access : ubo_load_access;
+
    /* Compute the offset to the start if the dereference as well as other
     * information we need to configure the write
     */
-   setup_for_load_or_store(var, deref,
+   setup_for_load_or_store(mem_ctx, var, deref,
                            &offset, &const_offset,
                            &row_major, &matrix_columns,
                            packing);
@@ -501,7 +343,7 @@ lower_ubo_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
    base_ir->insert_before(assign(load_offset, offset));
 
    deref = new(mem_ctx) ir_dereference_variable(load_var);
-   emit_access(false, deref, load_offset, const_offset,
+   emit_access(mem_ctx, false, deref, load_offset, const_offset,
                row_major, matrix_columns, packing, 0);
    *rvalue = deref;
 
@@ -509,7 +351,8 @@ lower_ubo_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
 }
 
 ir_expression *
-lower_ubo_reference_visitor::ubo_load(const glsl_type *type,
+lower_ubo_reference_visitor::ubo_load(void *mem_ctx,
+                                      const glsl_type *type,
                                      ir_rvalue *offset)
 {
    ir_rvalue *block_ref = this->uniform_block->clone(mem_ctx, NULL);
@@ -528,7 +371,8 @@ shader_storage_buffer_object(const _mesa_glsl_parse_state *state)
 }
 
 ir_call *
-lower_ubo_reference_visitor::ssbo_store(ir_rvalue *deref,
+lower_ubo_reference_visitor::ssbo_store(void *mem_ctx,
+                                        ir_rvalue *deref,
                                         ir_rvalue *offset,
                                         unsigned write_mask)
 {
@@ -568,7 +412,8 @@ lower_ubo_reference_visitor::ssbo_store(ir_rvalue *deref,
 }
 
 ir_call *
-lower_ubo_reference_visitor::ssbo_load(const struct glsl_type *type,
+lower_ubo_reference_visitor::ssbo_load(void *mem_ctx,
+                                       const struct glsl_type *type,
                                        ir_rvalue *offset)
 {
    exec_list sig_params;
@@ -603,178 +448,46 @@ lower_ubo_reference_visitor::ssbo_load(const struct glsl_type *type,
    return new(mem_ctx) ir_call(sig, deref_result, &call_params);
 }
 
-static inline int
-writemask_for_size(unsigned n)
-{
-   return ((1 << n) - 1);
-}
-
-/**
- * Takes a deref and recursively calls itself to break the deref down to the
- * point that the reads or writes generated are contiguous scalars or vectors.
- */
 void
-lower_ubo_reference_visitor::emit_access(bool is_write,
-                                         ir_dereference *deref,
-                                         ir_variable *base_offset,
-                                         unsigned int deref_offset,
-                                         bool row_major,
-                                         int matrix_columns,
-                                         unsigned packing,
-                                         unsigned write_mask)
+lower_ubo_reference_visitor::insert_buffer_access(void *mem_ctx,
+                                                  ir_dereference *deref,
+                                                  const glsl_type *type,
+                                                  ir_rvalue *offset,
+                                                  unsigned mask,
+                                                  int channel)
 {
-   if (deref->type->is_record()) {
-      unsigned int field_offset = 0;
-
-      for (unsigned i = 0; i < deref->type->length; i++) {
-         const struct glsl_struct_field *field =
-            &deref->type->fields.structure[i];
-         ir_dereference *field_deref =
-            new(mem_ctx) ir_dereference_record(deref->clone(mem_ctx, NULL),
-                                               field->name);
-
-         field_offset =
-            glsl_align(field_offset,
-                       field->type->std140_base_alignment(row_major));
-
-         emit_access(is_write, field_deref, base_offset,
-                     deref_offset + field_offset,
-                     row_major, 1, packing,
-                     writemask_for_size(field_deref->type->vector_elements));
-
-         field_offset += field->type->std140_size(row_major);
-      }
-      return;
-   }
-
-   if (deref->type->is_array()) {
-      unsigned array_stride = packing == GLSL_INTERFACE_PACKING_STD430 ?
-         deref->type->fields.array->std430_array_stride(row_major) :
-         glsl_align(deref->type->fields.array->std140_size(row_major), 16);
-
-      for (unsigned i = 0; i < deref->type->length; i++) {
-         ir_constant *element = new(mem_ctx) ir_constant(i);
-         ir_dereference *element_deref =
-            new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL),
-                                              element);
-         emit_access(is_write, element_deref, base_offset,
-                     deref_offset + i * array_stride,
-                     row_major, 1, packing,
-                     writemask_for_size(element_deref->type->vector_elements));
-      }
-      return;
-   }
-
-   if (deref->type->is_matrix()) {
-      for (unsigned i = 0; i < deref->type->matrix_columns; i++) {
-         ir_constant *col = new(mem_ctx) ir_constant(i);
-         ir_dereference *col_deref =
-            new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL), col);
-
-         if (row_major) {
-            /* For a row-major matrix, the next column starts at the next
-             * element.
-             */
-            int size_mul = deref->type->is_double() ? 8 : 4;
-            emit_access(is_write, col_deref, base_offset,
-                        deref_offset + i * size_mul,
-                        row_major, deref->type->matrix_columns, packing,
-                        writemask_for_size(col_deref->type->vector_elements));
-         } else {
-            int size_mul;
-
-            /* std430 doesn't round up vec2 size to a vec4 size */
-            if (packing == GLSL_INTERFACE_PACKING_STD430 &&
-                deref->type->vector_elements == 2 &&
-                !deref->type->is_double()) {
-               size_mul = 8;
-            } else {
-               /* std140 always rounds the stride of arrays (and matrices) to a
-                * vec4, so matrices are always 16 between columns/rows. With
-                * doubles, they will be 32 apart when there are more than 2 rows.
-                *
-                * For both std140 and std430, if the member is a
-                * three-'component vector with components consuming N basic
-                * machine units, the base alignment is 4N. For vec4, base
-                * alignment is 4N.
-                */
-               size_mul = (deref->type->is_double() &&
-                           deref->type->vector_elements > 2) ? 32 : 16;
-            }
-
-            emit_access(is_write, col_deref, base_offset,
-                        deref_offset + i * size_mul,
-                        row_major, deref->type->matrix_columns, packing,
-                        writemask_for_size(col_deref->type->vector_elements));
-         }
-      }
-      return;
+   switch (this->buffer_access_type) {
+   case ubo_load_access:
+      base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
+                                    ubo_load(mem_ctx, type, offset),
+                                    mask));
+      break;
+   case ssbo_load_access: {
+      ir_call *load_ssbo = ssbo_load(mem_ctx, type, offset);
+      base_ir->insert_before(load_ssbo);
+      ir_rvalue *value = load_ssbo->return_deref->as_rvalue()->clone(mem_ctx, NULL);
+      ir_assignment *assignment =
+         assign(deref->clone(mem_ctx, NULL), value, mask);
+      base_ir->insert_before(assignment);
+      break;
    }
-
-   assert(deref->type->is_scalar() || deref->type->is_vector());
-
-   if (!row_major) {
-      ir_rvalue *offset =
-         add(base_offset, new(mem_ctx) ir_constant(deref_offset));
-      if (is_write)
-         base_ir->insert_after(ssbo_store(deref, offset, write_mask));
-      else {
-         if (!this->is_shader_storage) {
-             base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
-                                           ubo_load(deref->type, offset)));
-         } else {
-            ir_call *load_ssbo = ssbo_load(deref->type, offset);
-            base_ir->insert_before(load_ssbo);
-            ir_rvalue *value = load_ssbo->return_deref->as_rvalue()->clone(mem_ctx, NULL);
-            base_ir->insert_before(assign(deref->clone(mem_ctx, NULL), value));
-         }
-      }
-   } else {
-      unsigned N = deref->type->is_double() ? 8 : 4;
-
-      /* We're dereffing a column out of a row-major matrix, so we
-       * gather the vector from each stored row.
-      */
-      assert(deref->type->base_type == GLSL_TYPE_FLOAT ||
-             deref->type->base_type == GLSL_TYPE_DOUBLE);
-      /* Matrices, row_major or not, are stored as if they were
-       * arrays of vectors of the appropriate size in std140.
-       * Arrays have their strides rounded up to a vec4, so the
-       * matrix stride is always 16. However a double matrix may either be 16
-       * or 32 depending on the number of columns.
-       */
-      assert(matrix_columns <= 4);
-      unsigned matrix_stride = glsl_align(matrix_columns * N, 16);
-
-      const glsl_type *deref_type = deref->type->base_type == GLSL_TYPE_FLOAT ?
-         glsl_type::float_type : glsl_type::double_type;
-
-      for (unsigned i = 0; i < deref->type->vector_elements; i++) {
-         ir_rvalue *chan_offset =
-            add(base_offset,
-                new(mem_ctx) ir_constant(deref_offset + i * matrix_stride));
-         if (is_write) {
-            base_ir->insert_after(ssbo_store(swizzle(deref, i, 1), chan_offset, 1));
-         } else {
-            if (!this->is_shader_storage) {
-               base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
-                                             ubo_load(deref_type, chan_offset),
-                                             (1U << i)));
-            } else {
-               ir_call *load_ssbo = ssbo_load(deref_type, chan_offset);
-               base_ir->insert_before(load_ssbo);
-               ir_rvalue *value = load_ssbo->return_deref->as_rvalue()->clone(mem_ctx, NULL);
-               base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
-                                             value,
-                                             (1U << i)));
-            }
-         }
+   case ssbo_store_access:
+      if (channel >= 0) {
+         base_ir->insert_after(ssbo_store(mem_ctx,
+                                          swizzle(deref, channel, 1),
+                                          offset, 1));
+      } else {
+         base_ir->insert_after(ssbo_store(mem_ctx, deref, offset, mask));
       }
+      break;
+   default:
+      unreachable("invalid buffer_access_type in insert_buffer_access");
    }
 }
 
 void
-lower_ubo_reference_visitor::write_to_memory(ir_dereference *deref,
+lower_ubo_reference_visitor::write_to_memory(void *mem_ctx,
+                                             ir_dereference *deref,
                                              ir_variable *var,
                                              ir_variable *write_var,
                                              unsigned write_mask)
@@ -785,10 +498,12 @@ lower_ubo_reference_visitor::write_to_memory(ir_dereference *deref,
    int matrix_columns;
    unsigned packing = var->get_interface_type()->interface_packing;
 
+   this->buffer_access_type = ssbo_store_access;
+
    /* Compute the offset to the start if the dereference as well as other
     * information we need to configure the write
     */
-   setup_for_load_or_store(var, deref,
+   setup_for_load_or_store(mem_ctx, var, deref,
                            &offset, &const_offset,
                            &row_major, &matrix_columns,
                            packing);
@@ -804,7 +519,7 @@ lower_ubo_reference_visitor::write_to_memory(ir_dereference *deref,
    base_ir->insert_before(assign(write_offset, offset));
 
    deref = new(mem_ctx) ir_dereference_variable(write_var);
-   emit_access(true, deref, write_offset, const_offset,
+   emit_access(mem_ctx, true, deref, write_offset, const_offset,
                row_major, matrix_columns, packing, write_mask);
 }
 
@@ -879,7 +594,7 @@ lower_ubo_reference_visitor::check_ssbo_unsized_array_length_assignment(ir_assig
 }
 
 ir_expression *
-lower_ubo_reference_visitor::emit_ssbo_get_buffer_size()
+lower_ubo_reference_visitor::emit_ssbo_get_buffer_size(void *mem_ctx)
 {
    ir_rvalue *block_ref = this->uniform_block->clone(mem_ctx, NULL);
    return new(mem_ctx) ir_expression(ir_unop_get_buffer_size,
@@ -922,12 +637,14 @@ lower_ubo_reference_visitor::calculate_unsized_array_stride(ir_dereference *dere
    case ir_type_dereference_record:
    {
       ir_dereference_record *deref_record = (ir_dereference_record *) deref;
-      const struct glsl_type *deref_record_type =
-         deref_record->record->as_dereference()->type;
-      unsigned record_length = deref_record_type->length;
+      ir_dereference *interface_deref =
+         deref_record->record->as_dereference();
+      assert(interface_deref != NULL);
+      const struct glsl_type *interface_type = interface_deref->type;
+      unsigned record_length = interface_type->length;
       /* Unsized array is always the last element of the interface */
       const struct glsl_type *unsized_array_type =
-         deref_record_type->fields.structure[record_length - 1].type->fields.array;
+         interface_type->fields.structure[record_length - 1].type->fields.array;
 
       const bool array_row_major =
          is_dereferenced_thing_row_major(deref_record);
@@ -951,7 +668,7 @@ lower_ubo_reference_visitor::process_ssbo_unsized_array_length(ir_rvalue **rvalu
                                                                ir_dereference *deref,
                                                                ir_variable *var)
 {
-   mem_ctx = ralloc_parent(*rvalue);
+   void *mem_ctx = ralloc_parent(*rvalue);
 
    ir_rvalue *base_offset = NULL;
    unsigned const_offset;
@@ -960,17 +677,19 @@ lower_ubo_reference_visitor::process_ssbo_unsized_array_length(ir_rvalue **rvalu
    unsigned packing = var->get_interface_type()->interface_packing;
    int unsized_array_stride = calculate_unsized_array_stride(deref, packing);
 
+   this->buffer_access_type = ssbo_unsized_array_length_access;
+
    /* Compute the offset to the start if the dereference as well as other
     * information we need to calculate the length.
     */
-   setup_for_load_or_store(var, deref,
+   setup_for_load_or_store(mem_ctx, var, deref,
                            &base_offset, &const_offset,
                            &row_major, &matrix_columns,
                            packing);
    /* array.length() =
     *  max((buffer_object_size - offset_of_array) / stride_of_array, 0)
     */
-   ir_expression *buffer_size = emit_ssbo_get_buffer_size();
+   ir_expression *buffer_size = emit_ssbo_get_buffer_size(mem_ctx);
 
    ir_expression *offset_of_array = new(mem_ctx)
       ir_expression(ir_binop_add, base_offset,
@@ -1004,13 +723,13 @@ lower_ubo_reference_visitor::check_for_ssbo_store(ir_assignment *ir)
       return;
 
    ir_variable *var = ir->lhs->variable_referenced();
-   if (!var || !var->is_in_buffer_block())
+   if (!var || !var->is_in_shader_storage_block())
       return;
 
    /* We have a write to a buffer variable, so declare a temporary and rewrite
     * the assignment so that the temporary is the LHS.
     */
-   mem_ctx = ralloc_parent(shader->ir);
+   void *mem_ctx = ralloc_parent(shader->ir);
 
    const glsl_type *type = rvalue->type;
    ir_variable *write_var = new(mem_ctx) ir_variable(type,
@@ -1020,14 +739,131 @@ lower_ubo_reference_visitor::check_for_ssbo_store(ir_assignment *ir)
    ir->lhs = new(mem_ctx) ir_dereference_variable(write_var);
 
    /* Now we have to write the value assigned to the temporary back to memory */
-   write_to_memory(deref, var, write_var, ir->write_mask);
+   write_to_memory(mem_ctx, deref, var, write_var, ir->write_mask);
    progress = true;
 }
 
+static bool
+is_buffer_backed_variable(ir_variable *var)
+{
+   return var->is_in_buffer_block() ||
+          var->data.mode == ir_var_shader_shared;
+}
+
+bool
+lower_ubo_reference_visitor::check_for_buffer_array_copy(ir_assignment *ir)
+{
+   if (!ir || !ir->lhs || !ir->rhs)
+      return false;
+
+   /* LHS and RHS must be arrays
+    * FIXME: arrays of arrays?
+    */
+   if (!ir->lhs->type->is_array() || !ir->rhs->type->is_array())
+      return false;
+
+   /* RHS must be a buffer-backed variable. This is what can cause the problem
+    * since it would lead to a series of loads that need to live until we
+    * see the writes to the LHS.
+    */
+   ir_variable *rhs_var = ir->rhs->variable_referenced();
+   if (!rhs_var || !is_buffer_backed_variable(rhs_var))
+      return false;
+
+   /* Split the array copy into individual element copies to reduce
+    * register pressure
+    */
+   ir_dereference *rhs_deref = ir->rhs->as_dereference();
+   if (!rhs_deref)
+      return false;
+
+   ir_dereference *lhs_deref = ir->lhs->as_dereference();
+   if (!lhs_deref)
+      return false;
+
+   assert(lhs_deref->type->length == rhs_deref->type->length);
+   void *mem_ctx = ralloc_parent(shader->ir);
+
+   for (unsigned i = 0; i < lhs_deref->type->length; i++) {
+      ir_dereference *lhs_i =
+         new(mem_ctx) ir_dereference_array(lhs_deref->clone(mem_ctx, NULL),
+                                           new(mem_ctx) ir_constant(i));
+
+      ir_dereference *rhs_i =
+         new(mem_ctx) ir_dereference_array(rhs_deref->clone(mem_ctx, NULL),
+                                           new(mem_ctx) ir_constant(i));
+      ir->insert_after(assign(lhs_i, rhs_i));
+   }
+
+   ir->remove();
+   progress = true;
+   return true;
+}
+
+bool
+lower_ubo_reference_visitor::check_for_buffer_struct_copy(ir_assignment *ir)
+{
+   if (!ir || !ir->lhs || !ir->rhs)
+      return false;
+
+   /* LHS and RHS must be records */
+   if (!ir->lhs->type->is_record() || !ir->rhs->type->is_record())
+      return false;
+
+   /* RHS must be a buffer-backed variable. This is what can cause the problem
+    * since it would lead to a series of loads that need to live until we
+    * see the writes to the LHS.
+    */
+   ir_variable *rhs_var = ir->rhs->variable_referenced();
+   if (!rhs_var || !is_buffer_backed_variable(rhs_var))
+      return false;
+
+   /* Split the struct copy into individual element copies to reduce
+    * register pressure
+    */
+   ir_dereference *rhs_deref = ir->rhs->as_dereference();
+   if (!rhs_deref)
+      return false;
+
+   ir_dereference *lhs_deref = ir->lhs->as_dereference();
+   if (!lhs_deref)
+      return false;
+
+   assert(lhs_deref->type->record_compare(rhs_deref->type));
+   void *mem_ctx = ralloc_parent(shader->ir);
+
+   for (unsigned i = 0; i < lhs_deref->type->length; i++) {
+      const char *field_name = lhs_deref->type->fields.structure[i].name;
+      ir_dereference *lhs_field =
+         new(mem_ctx) ir_dereference_record(lhs_deref->clone(mem_ctx, NULL),
+                                            field_name);
+      ir_dereference *rhs_field =
+         new(mem_ctx) ir_dereference_record(rhs_deref->clone(mem_ctx, NULL),
+                                            field_name);
+      ir->insert_after(assign(lhs_field, rhs_field));
+   }
+
+   ir->remove();
+   progress = true;
+   return true;
+}
 
 ir_visitor_status
 lower_ubo_reference_visitor::visit_enter(ir_assignment *ir)
 {
+   /* Array and struct copies could involve large amounts of load/store
+    * operations. To improve register pressure we want to special-case
+    * these and split them into individual element copies.
+    * This way we avoid emitting all the loads for the RHS first and
+    * all the writes for the LHS second and register usage is more
+    * efficient.
+    */
+   if (check_for_buffer_array_copy(ir))
+      return visit_continue_with_parent;
+
+   if (check_for_buffer_struct_copy(ir))
+      return visit_continue_with_parent;
+
    check_ssbo_unsized_array_length_assignment(ir);
    check_for_ssbo_store(ir);
    return rvalue_visit(ir);
@@ -1065,7 +901,7 @@ lower_ubo_reference_visitor::lower_ssbo_atomic_intrinsic(ir_call *ir)
    /* Compute the offset to the start if the dereference and the
     * block index
     */
-   mem_ctx = ralloc_parent(shader->ir);
+   void *mem_ctx = ralloc_parent(shader->ir);
 
    ir_rvalue *offset = NULL;
    unsigned const_offset;
@@ -1073,7 +909,9 @@ lower_ubo_reference_visitor::lower_ssbo_atomic_intrinsic(ir_call *ir)
    int matrix_columns;
    unsigned packing = var->get_interface_type()->interface_packing;
 
-   setup_for_load_or_store(var, deref,
+   this->buffer_access_type = ssbo_atomic_access;
+
+   setup_for_load_or_store(mem_ctx, var, deref,
                            &offset, &const_offset,
                            &row_major, &matrix_columns,
                            packing);
@@ -1099,13 +937,11 @@ lower_ubo_reference_visitor::lower_ssbo_atomic_intrinsic(ir_call *ir)
 
    const glsl_type *type = deref->type->base_type == GLSL_TYPE_INT ?
       glsl_type::int_type : glsl_type::uint_type;
-   param = param->get_next();
    sig_param = new(mem_ctx)
          ir_variable(type, "data1", ir_var_function_in);
    sig_params.push_tail(sig_param);
 
    if (param_count == 3) {
-      param = param->get_next();
       sig_param = new(mem_ctx)
             ir_variable(type, "data2", ir_var_function_in);
       sig_params.push_tail(sig_param);
@@ -1119,7 +955,7 @@ lower_ubo_reference_visitor::lower_ssbo_atomic_intrinsic(ir_call *ir)
    sig->is_intrinsic = true;
 
    char func_name[64];
-   sprintf(func_name, "%s_internal", ir->callee_name());
+   sprintf(func_name, "%s_ssbo", ir->callee_name());
    ir_function *f = new(mem_ctx) ir_function(func_name);
    f->add_signature(sig);
 
@@ -1143,15 +979,29 @@ lower_ubo_reference_visitor::lower_ssbo_atomic_intrinsic(ir_call *ir)
 ir_call *
 lower_ubo_reference_visitor::check_for_ssbo_atomic_intrinsic(ir_call *ir)
 {
+   exec_list& params = ir->actual_parameters;
+
+   if (params.length() < 2 || params.length() > 3)
+      return ir;
+
+   ir_rvalue *rvalue =
+      ((ir_instruction *) params.get_head())->as_rvalue();
+   if (!rvalue)
+      return ir;
+
+   ir_variable *var = rvalue->variable_referenced();
+   if (!var || !var->is_in_shader_storage_block())
+      return ir;
+
    const char *callee = ir->callee_name();
-   if (!strcmp("__intrinsic_ssbo_atomic_add", callee) ||
-       !strcmp("__intrinsic_ssbo_atomic_min", callee) ||
-       !strcmp("__intrinsic_ssbo_atomic_max", callee) ||
-       !strcmp("__intrinsic_ssbo_atomic_and", callee) ||
-       !strcmp("__intrinsic_ssbo_atomic_or", callee) ||
-       !strcmp("__intrinsic_ssbo_atomic_xor", callee) ||
-       !strcmp("__intrinsic_ssbo_atomic_exchange", callee) ||
-       !strcmp("__intrinsic_ssbo_atomic_comp_swap", callee)) {
+   if (!strcmp("__intrinsic_atomic_add", callee) ||
+       !strcmp("__intrinsic_atomic_min", callee) ||
+       !strcmp("__intrinsic_atomic_max", callee) ||
+       !strcmp("__intrinsic_atomic_and", callee) ||
+       !strcmp("__intrinsic_atomic_or", callee) ||
+       !strcmp("__intrinsic_atomic_xor", callee) ||
+       !strcmp("__intrinsic_atomic_exchange", callee) ||
+       !strcmp("__intrinsic_atomic_comp_swap", callee)) {
       return lower_ssbo_atomic_intrinsic(ir);
    }
 
@@ -1176,7 +1026,7 @@ lower_ubo_reference_visitor::visit_enter(ir_call *ir)
 } /* unnamed namespace */
 
 void
-lower_ubo_reference(struct gl_shader *shader, exec_list *instructions)
+lower_ubo_reference(struct gl_shader *shader)
 {
    lower_ubo_reference_visitor v(shader);
 
@@ -1187,6 +1037,6 @@ lower_ubo_reference(struct gl_shader *shader, exec_list *instructions)
     */
    do {
       v.progress = false;
-      visit_list_elements(&v, instructions);
+      visit_list_elements(&v, shader->ir);
    } while (v.progress);
 }