Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * Copyright © 2014 Intel Corporation
  3.  *
  4.  * Permission is hereby granted, free of charge, to any person obtaining a
  5.  * copy of this software and associated documentation files (the "Software"),
  6.  * to deal in the Software without restriction, including without limitation
  7.  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8.  * and/or sell copies of the Software, and to permit persons to whom the
  9.  * Software is furnished to do so, subject to the following conditions:
  10.  *
  11.  * The above copyright notice and this permission notice (including the next
  12.  * paragraph) shall be included in all copies or substantial portions of the
  13.  * Software.
  14.  *
  15.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  18.  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20.  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21.  * IN THE SOFTWARE.
  22.  *
  23.  * Authors:
  24.  *    Jason Ekstrand (jason@jlekstrand.net)
  25.  *
  26.  */
  27.  
  28. #include "nir.h"
  29. #include "nir_vla.h"
  30.  
  31.  
  32. struct deref_node {
  33.    struct deref_node *parent;
  34.    const struct glsl_type *type;
  35.  
  36.    bool lower_to_ssa;
  37.  
  38.    /* Only valid for things that end up in the direct list.
  39.     * Note that multiple nir_deref_vars may correspond to this node, but they
  40.     * will all be equivalent, so any is as good as the other.
  41.     */
  42.    nir_deref_var *deref;
  43.    struct exec_node direct_derefs_link;
  44.  
  45.    struct set *loads;
  46.    struct set *stores;
  47.    struct set *copies;
  48.  
  49.    nir_ssa_def **def_stack;
  50.    nir_ssa_def **def_stack_tail;
  51.  
  52.    struct deref_node *wildcard;
  53.    struct deref_node *indirect;
  54.    struct deref_node *children[0];
  55. };
  56.  
  57. struct lower_variables_state {
  58.    nir_shader *shader;
  59.    void *dead_ctx;
  60.    nir_function_impl *impl;
  61.  
  62.    /* A hash table mapping variables to deref_node data */
  63.    struct hash_table *deref_var_nodes;
  64.  
  65.    /* A hash table mapping fully-qualified direct dereferences, i.e.
  66.     * dereferences with no indirect or wildcard array dereferences, to
  67.     * deref_node data.
  68.     *
  69.     * At the moment, we only lower loads, stores, and copies that can be
  70.     * trivially lowered to loads and stores, i.e. copies with no indirects
  71.     * and no wildcards.  If a part of a variable that is being loaded from
  72.     * and/or stored into is also involved in a copy operation with
  73.     * wildcards, then we lower that copy operation to loads and stores, but
  74.     * otherwise we leave copies with wildcards alone. Since the only derefs
  75.     * used in these loads, stores, and trivial copies are ones with no
  76.     * wildcards and no indirects, these are precisely the derefs that we
  77.     * can actually consider lowering.
  78.     */
  79.    struct exec_list direct_deref_nodes;
  80.  
  81.    /* Controls whether get_deref_node will add variables to the
  82.     * direct_deref_nodes table.  This is turned on when we are initially
  83.     * scanning for load/store instructions.  It is then turned off so we
  84.     * don't accidentally change the direct_deref_nodes table while we're
  85.     * iterating throug it.
  86.     */
  87.    bool add_to_direct_deref_nodes;
  88.  
  89.    /* A hash table mapping phi nodes to deref_state data */
  90.    struct hash_table *phi_table;
  91. };
  92.  
  93. static struct deref_node *
  94. deref_node_create(struct deref_node *parent,
  95.                   const struct glsl_type *type, nir_shader *shader)
  96. {
  97.    size_t size = sizeof(struct deref_node) +
  98.                  glsl_get_length(type) * sizeof(struct deref_node *);
  99.  
  100.    struct deref_node *node = rzalloc_size(shader, size);
  101.    node->type = type;
  102.    node->parent = parent;
  103.    node->deref = NULL;
  104.    exec_node_init(&node->direct_derefs_link);
  105.  
  106.    return node;
  107. }
  108.  
  109. /* Returns the deref node associated with the given variable.  This will be
  110.  * the root of the tree representing all of the derefs of the given variable.
  111.  */
  112. static struct deref_node *
  113. get_deref_node_for_var(nir_variable *var, struct lower_variables_state *state)
  114. {
  115.    struct deref_node *node;
  116.  
  117.    struct hash_entry *var_entry =
  118.       _mesa_hash_table_search(state->deref_var_nodes, var);
  119.  
  120.    if (var_entry) {
  121.       return var_entry->data;
  122.    } else {
  123.       node = deref_node_create(NULL, var->type, state->dead_ctx);
  124.       _mesa_hash_table_insert(state->deref_var_nodes, var, node);
  125.       return node;
  126.    }
  127. }
  128.  
  129. /* Gets the deref_node for the given deref chain and creates it if it
  130.  * doesn't yet exist.  If the deref is fully-qualified and direct and
  131.  * state->add_to_direct_deref_nodes is true, it will be added to the hash
  132.  * table of of fully-qualified direct derefs.
  133.  */
  134. static struct deref_node *
  135. get_deref_node(nir_deref_var *deref, struct lower_variables_state *state)
  136. {
  137.    bool is_direct = true;
  138.  
  139.    /* Start at the base of the chain. */
  140.    struct deref_node *node = get_deref_node_for_var(deref->var, state);
  141.    assert(deref->deref.type == node->type);
  142.  
  143.    for (nir_deref *tail = deref->deref.child; tail; tail = tail->child) {
  144.       switch (tail->deref_type) {
  145.       case nir_deref_type_struct: {
  146.          nir_deref_struct *deref_struct = nir_deref_as_struct(tail);
  147.  
  148.          assert(deref_struct->index < glsl_get_length(node->type));
  149.  
  150.          if (node->children[deref_struct->index] == NULL)
  151.             node->children[deref_struct->index] =
  152.                deref_node_create(node, tail->type, state->dead_ctx);
  153.  
  154.          node = node->children[deref_struct->index];
  155.          break;
  156.       }
  157.  
  158.       case nir_deref_type_array: {
  159.          nir_deref_array *arr = nir_deref_as_array(tail);
  160.  
  161.          switch (arr->deref_array_type) {
  162.          case nir_deref_array_type_direct:
  163.             /* This is possible if a loop unrolls and generates an
  164.              * out-of-bounds offset.  We need to handle this at least
  165.              * somewhat gracefully.
  166.              */
  167.             if (arr->base_offset >= glsl_get_length(node->type))
  168.                return NULL;
  169.  
  170.             if (node->children[arr->base_offset] == NULL)
  171.                node->children[arr->base_offset] =
  172.                   deref_node_create(node, tail->type, state->dead_ctx);
  173.  
  174.             node = node->children[arr->base_offset];
  175.             break;
  176.  
  177.          case nir_deref_array_type_indirect:
  178.             if (node->indirect == NULL)
  179.                node->indirect = deref_node_create(node, tail->type,
  180.                                                   state->dead_ctx);
  181.  
  182.             node = node->indirect;
  183.             is_direct = false;
  184.             break;
  185.  
  186.          case nir_deref_array_type_wildcard:
  187.             if (node->wildcard == NULL)
  188.                node->wildcard = deref_node_create(node, tail->type,
  189.                                                   state->dead_ctx);
  190.  
  191.             node = node->wildcard;
  192.             is_direct = false;
  193.             break;
  194.  
  195.          default:
  196.             unreachable("Invalid array deref type");
  197.          }
  198.          break;
  199.       }
  200.       default:
  201.          unreachable("Invalid deref type");
  202.       }
  203.    }
  204.  
  205.    assert(node);
  206.  
  207.    /* Only insert if it isn't already in the list. */
  208.    if (is_direct && state->add_to_direct_deref_nodes &&
  209.        node->direct_derefs_link.next == NULL) {
  210.       node->deref = deref;
  211.       assert(deref->var != NULL);
  212.       exec_list_push_tail(&state->direct_deref_nodes,
  213.                           &node->direct_derefs_link);
  214.    }
  215.  
  216.    return node;
  217. }
  218.  
  219. /* \sa foreach_deref_node_match */
  220. static bool
  221. foreach_deref_node_worker(struct deref_node *node, nir_deref *deref,
  222.                           bool (* cb)(struct deref_node *node,
  223.                                       struct lower_variables_state *state),
  224.                           struct lower_variables_state *state)
  225. {
  226.    if (deref->child == NULL) {
  227.       return cb(node, state);
  228.    } else {
  229.       switch (deref->child->deref_type) {
  230.       case nir_deref_type_array: {
  231.          nir_deref_array *arr = nir_deref_as_array(deref->child);
  232.          assert(arr->deref_array_type == nir_deref_array_type_direct);
  233.          if (node->children[arr->base_offset] &&
  234.              !foreach_deref_node_worker(node->children[arr->base_offset],
  235.                                         deref->child, cb, state))
  236.             return false;
  237.  
  238.          if (node->wildcard &&
  239.              !foreach_deref_node_worker(node->wildcard,
  240.                                         deref->child, cb, state))
  241.             return false;
  242.  
  243.          return true;
  244.       }
  245.  
  246.       case nir_deref_type_struct: {
  247.          nir_deref_struct *str = nir_deref_as_struct(deref->child);
  248.          return foreach_deref_node_worker(node->children[str->index],
  249.                                           deref->child, cb, state);
  250.       }
  251.  
  252.       default:
  253.          unreachable("Invalid deref child type");
  254.       }
  255.    }
  256. }
  257.  
  258. /* Walks over every "matching" deref_node and calls the callback.  A node
  259.  * is considered to "match" if either refers to that deref or matches up t
  260.  * a wildcard.  In other words, the following would match a[6].foo[3].bar:
  261.  *
  262.  * a[6].foo[3].bar
  263.  * a[*].foo[3].bar
  264.  * a[6].foo[*].bar
  265.  * a[*].foo[*].bar
  266.  *
  267.  * The given deref must be a full-length and fully qualified (no wildcards
  268.  * or indirects) deref chain.
  269.  */
  270. static bool
  271. foreach_deref_node_match(nir_deref_var *deref,
  272.                          bool (* cb)(struct deref_node *node,
  273.                                      struct lower_variables_state *state),
  274.                          struct lower_variables_state *state)
  275. {
  276.    nir_deref_var var_deref = *deref;
  277.    var_deref.deref.child = NULL;
  278.    struct deref_node *node = get_deref_node(&var_deref, state);
  279.  
  280.    if (node == NULL)
  281.       return false;
  282.  
  283.    return foreach_deref_node_worker(node, &deref->deref, cb, state);
  284. }
  285.  
  286. /* \sa deref_may_be_aliased */
  287. static bool
  288. deref_may_be_aliased_node(struct deref_node *node, nir_deref *deref,
  289.                           struct lower_variables_state *state)
  290. {
  291.    if (deref->child == NULL) {
  292.       return false;
  293.    } else {
  294.       switch (deref->child->deref_type) {
  295.       case nir_deref_type_array: {
  296.          nir_deref_array *arr = nir_deref_as_array(deref->child);
  297.          if (arr->deref_array_type == nir_deref_array_type_indirect)
  298.             return true;
  299.  
  300.          /* If there is an indirect at this level, we're aliased. */
  301.          if (node->indirect)
  302.             return true;
  303.  
  304.          assert(arr->deref_array_type == nir_deref_array_type_direct);
  305.  
  306.          if (node->children[arr->base_offset] &&
  307.              deref_may_be_aliased_node(node->children[arr->base_offset],
  308.                                        deref->child, state))
  309.             return true;
  310.  
  311.          if (node->wildcard &&
  312.              deref_may_be_aliased_node(node->wildcard, deref->child, state))
  313.             return true;
  314.  
  315.          return false;
  316.       }
  317.  
  318.       case nir_deref_type_struct: {
  319.          nir_deref_struct *str = nir_deref_as_struct(deref->child);
  320.          if (node->children[str->index]) {
  321.              return deref_may_be_aliased_node(node->children[str->index],
  322.                                               deref->child, state);
  323.          } else {
  324.             return false;
  325.          }
  326.       }
  327.  
  328.       default:
  329.          unreachable("Invalid nir_deref child type");
  330.       }
  331.    }
  332. }
  333.  
  334. /* Returns true if there are no indirects that can ever touch this deref.
  335.  *
  336.  * For example, if the given deref is a[6].foo, then any uses of a[i].foo
  337.  * would cause this to return false, but a[i].bar would not affect it
  338.  * because it's a different structure member.  A var_copy involving of
  339.  * a[*].bar also doesn't affect it because that can be lowered to entirely
  340.  * direct load/stores.
  341.  *
  342.  * We only support asking this question about fully-qualified derefs.
  343.  * Obviously, it's pointless to ask this about indirects, but we also
  344.  * rule-out wildcards.  Handling Wildcard dereferences would involve
  345.  * checking each array index to make sure that there aren't any indirect
  346.  * references.
  347.  */
  348. static bool
  349. deref_may_be_aliased(nir_deref_var *deref,
  350.                      struct lower_variables_state *state)
  351. {
  352.    return deref_may_be_aliased_node(get_deref_node_for_var(deref->var, state),
  353.                                     &deref->deref, state);
  354. }
  355.  
  356. static void
  357. register_load_instr(nir_intrinsic_instr *load_instr,
  358.                     struct lower_variables_state *state)
  359. {
  360.    struct deref_node *node = get_deref_node(load_instr->variables[0], state);
  361.    if (node == NULL)
  362.       return;
  363.  
  364.    if (node->loads == NULL)
  365.       node->loads = _mesa_set_create(state->dead_ctx, _mesa_hash_pointer,
  366.                                      _mesa_key_pointer_equal);
  367.  
  368.    _mesa_set_add(node->loads, load_instr);
  369. }
  370.  
  371. static void
  372. register_store_instr(nir_intrinsic_instr *store_instr,
  373.                      struct lower_variables_state *state)
  374. {
  375.    struct deref_node *node = get_deref_node(store_instr->variables[0], state);
  376.    if (node == NULL)
  377.       return;
  378.  
  379.    if (node->stores == NULL)
  380.       node->stores = _mesa_set_create(state->dead_ctx, _mesa_hash_pointer,
  381.                                      _mesa_key_pointer_equal);
  382.  
  383.    _mesa_set_add(node->stores, store_instr);
  384. }
  385.  
  386. static void
  387. register_copy_instr(nir_intrinsic_instr *copy_instr,
  388.                     struct lower_variables_state *state)
  389. {
  390.    for (unsigned idx = 0; idx < 2; idx++) {
  391.       struct deref_node *node =
  392.          get_deref_node(copy_instr->variables[idx], state);
  393.  
  394.       if (node == NULL)
  395.          continue;
  396.  
  397.       if (node->copies == NULL)
  398.          node->copies = _mesa_set_create(state->dead_ctx, _mesa_hash_pointer,
  399.                                          _mesa_key_pointer_equal);
  400.  
  401.       _mesa_set_add(node->copies, copy_instr);
  402.    }
  403. }
  404.  
  405. /* Registers all variable uses in the given block. */
  406. static bool
  407. register_variable_uses_block(nir_block *block, void *void_state)
  408. {
  409.    struct lower_variables_state *state = void_state;
  410.  
  411.    nir_foreach_instr_safe(block, instr) {
  412.       if (instr->type != nir_instr_type_intrinsic)
  413.          continue;
  414.  
  415.       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
  416.  
  417.       switch (intrin->intrinsic) {
  418.       case nir_intrinsic_load_var:
  419.          register_load_instr(intrin, state);
  420.          break;
  421.  
  422.       case nir_intrinsic_store_var:
  423.          register_store_instr(intrin, state);
  424.          break;
  425.  
  426.       case nir_intrinsic_copy_var:
  427.          register_copy_instr(intrin, state);
  428.          break;
  429.  
  430.       default:
  431.          continue;
  432.       }
  433.    }
  434.  
  435.    return true;
  436. }
  437.  
  438. /* Walks over all of the copy instructions to or from the given deref_node
  439.  * and lowers them to load/store intrinsics.
  440.  */
  441. static bool
  442. lower_copies_to_load_store(struct deref_node *node,
  443.                            struct lower_variables_state *state)
  444. {
  445.    if (!node->copies)
  446.       return true;
  447.  
  448.    struct set_entry *copy_entry;
  449.    set_foreach(node->copies, copy_entry) {
  450.       nir_intrinsic_instr *copy = (void *)copy_entry->key;
  451.  
  452.       nir_lower_var_copy_instr(copy, state->shader);
  453.  
  454.       for (unsigned i = 0; i < 2; ++i) {
  455.          struct deref_node *arg_node =
  456.             get_deref_node(copy->variables[i], state);
  457.  
  458.          if (arg_node == NULL)
  459.             continue;
  460.  
  461.          struct set_entry *arg_entry = _mesa_set_search(arg_node->copies, copy);
  462.          assert(arg_entry);
  463.          _mesa_set_remove(node->copies, arg_entry);
  464.       }
  465.  
  466.       nir_instr_remove(&copy->instr);
  467.    }
  468.  
  469.    return true;
  470. }
  471.  
  472. /** Pushes an SSA def onto the def stack for the given node
  473.  *
  474.  * Each node is potentially associated with a stack of SSA definitions.
  475.  * This stack is used for determining what SSA definition reaches a given
  476.  * point in the program for variable renaming.  The stack is always kept in
  477.  * dominance-order with at most one SSA def per block.  If the SSA
  478.  * definition on the top of the stack is in the same block as the one being
  479.  * pushed, the top element is replaced.
  480.  */
  481. static void
  482. def_stack_push(struct deref_node *node, nir_ssa_def *def,
  483.                struct lower_variables_state *state)
  484. {
  485.    if (node->def_stack == NULL) {
  486.       node->def_stack = ralloc_array(state->dead_ctx, nir_ssa_def *,
  487.                                      state->impl->num_blocks);
  488.       node->def_stack_tail = node->def_stack - 1;
  489.    }
  490.  
  491.    if (node->def_stack_tail >= node->def_stack) {
  492.       nir_ssa_def *top_def = *node->def_stack_tail;
  493.  
  494.       if (def->parent_instr->block == top_def->parent_instr->block) {
  495.          /* They're in the same block, just replace the top */
  496.          *node->def_stack_tail = def;
  497.          return;
  498.       }
  499.    }
  500.  
  501.    *(++node->def_stack_tail) = def;
  502. }
  503.  
  504. /* Pop the top of the def stack if it's in the given block */
  505. static void
  506. def_stack_pop_if_in_block(struct deref_node *node, nir_block *block)
  507. {
  508.    /* If we're popping, then we have presumably pushed at some time in the
  509.     * past so this should exist.
  510.     */
  511.    assert(node->def_stack != NULL);
  512.  
  513.    /* The stack is already empty.  Do nothing. */
  514.    if (node->def_stack_tail < node->def_stack)
  515.       return;
  516.  
  517.    nir_ssa_def *def = *node->def_stack_tail;
  518.    if (def->parent_instr->block == block)
  519.       node->def_stack_tail--;
  520. }
  521.  
  522. /** Retrieves the SSA definition on the top of the stack for the given
  523.  * node, if one exists.  If the stack is empty, then we return the constant
  524.  * initializer (if it exists) or an SSA undef.
  525.  */
  526. static nir_ssa_def *
  527. get_ssa_def_for_block(struct deref_node *node, nir_block *block,
  528.                       struct lower_variables_state *state)
  529. {
  530.    /* If we have something on the stack, go ahead and return it.  We're
  531.     * assuming that the top of the stack dominates the given block.
  532.     */
  533.    if (node->def_stack && node->def_stack_tail >= node->def_stack)
  534.       return *node->def_stack_tail;
  535.  
  536.    /* If we got here then we don't have a definition that dominates the
  537.     * given block.  This means that we need to add an undef and use that.
  538.     */
  539.    nir_ssa_undef_instr *undef =
  540.       nir_ssa_undef_instr_create(state->shader,
  541.                                  glsl_get_vector_elements(node->type));
  542.    nir_instr_insert_before_cf_list(&state->impl->body, &undef->instr);
  543.    def_stack_push(node, &undef->def, state);
  544.    return &undef->def;
  545. }
  546.  
  547. /* Given a block and one of its predecessors, this function fills in the
  548.  * souces of the phi nodes to take SSA defs from the given predecessor.
  549.  * This function must be called exactly once per block/predecessor pair.
  550.  */
  551. static void
  552. add_phi_sources(nir_block *block, nir_block *pred,
  553.                 struct lower_variables_state *state)
  554. {
  555.    nir_foreach_instr(block, instr) {
  556.       if (instr->type != nir_instr_type_phi)
  557.          break;
  558.  
  559.       nir_phi_instr *phi = nir_instr_as_phi(instr);
  560.  
  561.       struct hash_entry *entry =
  562.             _mesa_hash_table_search(state->phi_table, phi);
  563.       if (!entry)
  564.          continue;
  565.  
  566.       struct deref_node *node = entry->data;
  567.  
  568.       nir_phi_src *src = ralloc(phi, nir_phi_src);
  569.       src->pred = pred;
  570.       src->src.parent_instr = &phi->instr;
  571.       src->src.is_ssa = true;
  572.       src->src.ssa = get_ssa_def_for_block(node, pred, state);
  573.  
  574.       list_addtail(&src->src.use_link, &src->src.ssa->uses);
  575.  
  576.       exec_list_push_tail(&phi->srcs, &src->node);
  577.    }
  578. }
  579.  
  580. /* Performs variable renaming by doing a DFS of the dominance tree
  581.  *
  582.  * This algorithm is very similar to the one outlined in "Efficiently
  583.  * Computing Static Single Assignment Form and the Control Dependence
  584.  * Graph" by Cytron et. al.  The primary difference is that we only put one
  585.  * SSA def on the stack per block.
  586.  */
  587. static bool
  588. rename_variables_block(nir_block *block, struct lower_variables_state *state)
  589. {
  590.    nir_foreach_instr_safe(block, instr) {
  591.       if (instr->type == nir_instr_type_phi) {
  592.          nir_phi_instr *phi = nir_instr_as_phi(instr);
  593.  
  594.          struct hash_entry *entry =
  595.             _mesa_hash_table_search(state->phi_table, phi);
  596.  
  597.          /* This can happen if we already have phi nodes in the program
  598.           * that were not created in this pass.
  599.           */
  600.          if (!entry)
  601.             continue;
  602.  
  603.          struct deref_node *node = entry->data;
  604.  
  605.          def_stack_push(node, &phi->dest.ssa, state);
  606.       } else if (instr->type == nir_instr_type_intrinsic) {
  607.          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
  608.  
  609.          switch (intrin->intrinsic) {
  610.          case nir_intrinsic_load_var: {
  611.             struct deref_node *node =
  612.                get_deref_node(intrin->variables[0], state);
  613.  
  614.             if (node == NULL) {
  615.                /* If we hit this path then we are referencing an invalid
  616.                 * value.  Most likely, we unrolled something and are
  617.                 * reading past the end of some array.  In any case, this
  618.                 * should result in an undefined value.
  619.                 */
  620.                nir_ssa_undef_instr *undef =
  621.                   nir_ssa_undef_instr_create(state->shader,
  622.                                              intrin->num_components);
  623.  
  624.                nir_instr_insert_before(&intrin->instr, &undef->instr);
  625.                nir_instr_remove(&intrin->instr);
  626.  
  627.                nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
  628.                                         nir_src_for_ssa(&undef->def),
  629.                                         state->shader);
  630.                continue;
  631.             }
  632.  
  633.             if (!node->lower_to_ssa)
  634.                continue;
  635.  
  636.             nir_alu_instr *mov = nir_alu_instr_create(state->shader,
  637.                                                       nir_op_imov);
  638.             mov->src[0].src.is_ssa = true;
  639.             mov->src[0].src.ssa = get_ssa_def_for_block(node, block, state);
  640.             for (unsigned i = intrin->num_components; i < 4; i++)
  641.                mov->src[0].swizzle[i] = 0;
  642.  
  643.             assert(intrin->dest.is_ssa);
  644.  
  645.             mov->dest.write_mask = (1 << intrin->num_components) - 1;
  646.             nir_ssa_dest_init(&mov->instr, &mov->dest.dest,
  647.                               intrin->num_components, NULL);
  648.  
  649.             nir_instr_insert_before(&intrin->instr, &mov->instr);
  650.             nir_instr_remove(&intrin->instr);
  651.  
  652.             nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
  653.                                      nir_src_for_ssa(&mov->dest.dest.ssa),
  654.                                      state->shader);
  655.             break;
  656.          }
  657.  
  658.          case nir_intrinsic_store_var: {
  659.             struct deref_node *node =
  660.                get_deref_node(intrin->variables[0], state);
  661.  
  662.             if (node == NULL) {
  663.                /* Probably an out-of-bounds array store.  That should be a
  664.                 * no-op. */
  665.                nir_instr_remove(&intrin->instr);
  666.                continue;
  667.             }
  668.  
  669.             if (!node->lower_to_ssa)
  670.                continue;
  671.  
  672.             assert(intrin->num_components ==
  673.                    glsl_get_vector_elements(node->type));
  674.  
  675.             assert(intrin->src[0].is_ssa);
  676.  
  677.             nir_alu_instr *mov = nir_alu_instr_create(state->shader,
  678.                                                       nir_op_imov);
  679.             mov->src[0].src.is_ssa = true;
  680.             mov->src[0].src.ssa = intrin->src[0].ssa;
  681.             for (unsigned i = intrin->num_components; i < 4; i++)
  682.                mov->src[0].swizzle[i] = 0;
  683.  
  684.             mov->dest.write_mask = (1 << intrin->num_components) - 1;
  685.             nir_ssa_dest_init(&mov->instr, &mov->dest.dest,
  686.                               intrin->num_components, NULL);
  687.  
  688.             nir_instr_insert_before(&intrin->instr, &mov->instr);
  689.  
  690.             def_stack_push(node, &mov->dest.dest.ssa, state);
  691.  
  692.             /* We'll wait to remove the instruction until the next pass
  693.              * where we pop the node we just pushed back off the stack.
  694.              */
  695.             break;
  696.          }
  697.  
  698.          default:
  699.             break;
  700.          }
  701.       }
  702.    }
  703.  
  704.    if (block->successors[0])
  705.       add_phi_sources(block->successors[0], block, state);
  706.    if (block->successors[1])
  707.       add_phi_sources(block->successors[1], block, state);
  708.  
  709.    for (unsigned i = 0; i < block->num_dom_children; ++i)
  710.       rename_variables_block(block->dom_children[i], state);
  711.  
  712.    /* Now we iterate over the instructions and pop off any SSA defs that we
  713.     * pushed in the first loop.
  714.     */
  715.    nir_foreach_instr_safe(block, instr) {
  716.       if (instr->type == nir_instr_type_phi) {
  717.          nir_phi_instr *phi = nir_instr_as_phi(instr);
  718.  
  719.          struct hash_entry *entry =
  720.             _mesa_hash_table_search(state->phi_table, phi);
  721.  
  722.          /* This can happen if we already have phi nodes in the program
  723.           * that were not created in this pass.
  724.           */
  725.          if (!entry)
  726.             continue;
  727.  
  728.          struct deref_node *node = entry->data;
  729.  
  730.          def_stack_pop_if_in_block(node, block);
  731.       } else if (instr->type == nir_instr_type_intrinsic) {
  732.          nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
  733.  
  734.          if (intrin->intrinsic != nir_intrinsic_store_var)
  735.             continue;
  736.  
  737.          struct deref_node *node = get_deref_node(intrin->variables[0], state);
  738.          if (!node)
  739.             continue;
  740.  
  741.          if (!node->lower_to_ssa)
  742.             continue;
  743.  
  744.          def_stack_pop_if_in_block(node, block);
  745.          nir_instr_remove(&intrin->instr);
  746.       }
  747.    }
  748.  
  749.    return true;
  750. }
  751.  
  752. /* Inserts phi nodes for all variables marked lower_to_ssa
  753.  *
  754.  * This is the same algorithm as presented in "Efficiently Computing Static
  755.  * Single Assignment Form and the Control Dependence Graph" by Cytron et.
  756.  * al.
  757.  */
  758. static void
  759. insert_phi_nodes(struct lower_variables_state *state)
  760. {
  761.    NIR_VLA_ZERO(unsigned, work, state->impl->num_blocks);
  762.    NIR_VLA_ZERO(unsigned, has_already, state->impl->num_blocks);
  763.  
  764.    /*
  765.     * Since the work flags already prevent us from inserting a node that has
  766.     * ever been inserted into W, we don't need to use a set to represent W.
  767.     * Also, since no block can ever be inserted into W more than once, we know
  768.     * that the maximum size of W is the number of basic blocks in the
  769.     * function. So all we need to handle W is an array and a pointer to the
  770.     * next element to be inserted and the next element to be removed.
  771.     */
  772.    NIR_VLA(nir_block *, W, state->impl->num_blocks);
  773.  
  774.    unsigned w_start, w_end;
  775.    unsigned iter_count = 0;
  776.  
  777.    foreach_list_typed(struct deref_node, node, direct_derefs_link,
  778.                       &state->direct_deref_nodes) {
  779.       if (node->stores == NULL)
  780.          continue;
  781.  
  782.       if (!node->lower_to_ssa)
  783.          continue;
  784.  
  785.       w_start = w_end = 0;
  786.       iter_count++;
  787.  
  788.       struct set_entry *store_entry;
  789.       set_foreach(node->stores, store_entry) {
  790.          nir_intrinsic_instr *store = (nir_intrinsic_instr *)store_entry->key;
  791.          if (work[store->instr.block->index] < iter_count)
  792.             W[w_end++] = store->instr.block;
  793.          work[store->instr.block->index] = iter_count;
  794.       }
  795.  
  796.       while (w_start != w_end) {
  797.          nir_block *cur = W[w_start++];
  798.          struct set_entry *dom_entry;
  799.          set_foreach(cur->dom_frontier, dom_entry) {
  800.             nir_block *next = (nir_block *) dom_entry->key;
  801.  
  802.             /*
  803.              * If there's more than one return statement, then the end block
  804.              * can be a join point for some definitions. However, there are
  805.              * no instructions in the end block, so nothing would use those
  806.              * phi nodes. Of course, we couldn't place those phi nodes
  807.              * anyways due to the restriction of having no instructions in the
  808.              * end block...
  809.              */
  810.             if (next == state->impl->end_block)
  811.                continue;
  812.  
  813.             if (has_already[next->index] < iter_count) {
  814.                nir_phi_instr *phi = nir_phi_instr_create(state->shader);
  815.                nir_ssa_dest_init(&phi->instr, &phi->dest,
  816.                                  glsl_get_vector_elements(node->type), NULL);
  817.                nir_instr_insert_before_block(next, &phi->instr);
  818.  
  819.                _mesa_hash_table_insert(state->phi_table, phi, node);
  820.  
  821.                has_already[next->index] = iter_count;
  822.                if (work[next->index] < iter_count) {
  823.                   work[next->index] = iter_count;
  824.                   W[w_end++] = next;
  825.                }
  826.             }
  827.          }
  828.       }
  829.    }
  830. }
  831.  
  832.  
  833. /** Implements a pass to lower variable uses to SSA values
  834.  *
  835.  * This path walks the list of instructions and tries to lower as many
  836.  * local variable load/store operations to SSA defs and uses as it can.
  837.  * The process involves four passes:
  838.  *
  839.  *  1) Iterate over all of the instructions and mark where each local
  840.  *     variable deref is used in a load, store, or copy.  While we're at
  841.  *     it, we keep track of all of the fully-qualified (no wildcards) and
  842.  *     fully-direct references we see and store them in the
  843.  *     direct_deref_nodes hash table.
  844.  *
  845.  *  2) Walk over the the list of fully-qualified direct derefs generated in
  846.  *     the previous pass.  For each deref, we determine if it can ever be
  847.  *     aliased, i.e. if there is an indirect reference anywhere that may
  848.  *     refer to it.  If it cannot be aliased, we mark it for lowering to an
  849.  *     SSA value.  At this point, we lower any var_copy instructions that
  850.  *     use the given deref to load/store operations and, if the deref has a
  851.  *     constant initializer, we go ahead and add a load_const value at the
  852.  *     beginning of the function with the initialized value.
  853.  *
  854.  *  3) Walk over the list of derefs we plan to lower to SSA values and
  855.  *     insert phi nodes as needed.
  856.  *
  857.  *  4) Perform "variable renaming" by replacing the load/store instructions
  858.  *     with SSA definitions and SSA uses.
  859.  */
  860. static bool
  861. nir_lower_vars_to_ssa_impl(nir_function_impl *impl)
  862. {
  863.    struct lower_variables_state state;
  864.  
  865.    state.shader = impl->overload->function->shader;
  866.    state.dead_ctx = ralloc_context(state.shader);
  867.    state.impl = impl;
  868.  
  869.    state.deref_var_nodes = _mesa_hash_table_create(state.dead_ctx,
  870.                                                    _mesa_hash_pointer,
  871.                                                    _mesa_key_pointer_equal);
  872.    exec_list_make_empty(&state.direct_deref_nodes);
  873.    state.phi_table = _mesa_hash_table_create(state.dead_ctx,
  874.                                              _mesa_hash_pointer,
  875.                                              _mesa_key_pointer_equal);
  876.  
  877.    /* Build the initial deref structures and direct_deref_nodes table */
  878.    state.add_to_direct_deref_nodes = true;
  879.    nir_foreach_block(impl, register_variable_uses_block, &state);
  880.  
  881.    struct set *outputs = _mesa_set_create(state.dead_ctx,
  882.                                           _mesa_hash_pointer,
  883.                                           _mesa_key_pointer_equal);
  884.  
  885.    bool progress = false;
  886.  
  887.    nir_metadata_require(impl, nir_metadata_block_index);
  888.  
  889.    /* We're about to iterate through direct_deref_nodes.  Don't modify it. */
  890.    state.add_to_direct_deref_nodes = false;
  891.  
  892.    foreach_list_typed_safe(struct deref_node, node, direct_derefs_link,
  893.                            &state.direct_deref_nodes) {
  894.       nir_deref_var *deref = node->deref;
  895.  
  896.       if (deref->var->data.mode != nir_var_local) {
  897.          exec_node_remove(&node->direct_derefs_link);
  898.          continue;
  899.       }
  900.  
  901.       if (deref_may_be_aliased(deref, &state)) {
  902.          exec_node_remove(&node->direct_derefs_link);
  903.          continue;
  904.       }
  905.  
  906.       node->lower_to_ssa = true;
  907.       progress = true;
  908.  
  909.       if (deref->var->constant_initializer) {
  910.          nir_load_const_instr *load =
  911.             nir_deref_get_const_initializer_load(state.shader, deref);
  912.          nir_ssa_def_init(&load->instr, &load->def,
  913.                           glsl_get_vector_elements(node->type), NULL);
  914.          nir_instr_insert_before_cf_list(&impl->body, &load->instr);
  915.          def_stack_push(node, &load->def, &state);
  916.       }
  917.  
  918.       if (deref->var->data.mode == nir_var_shader_out)
  919.          _mesa_set_add(outputs, node);
  920.  
  921.       foreach_deref_node_match(deref, lower_copies_to_load_store, &state);
  922.    }
  923.  
  924.    if (!progress)
  925.       return false;
  926.  
  927.    nir_metadata_require(impl, nir_metadata_dominance);
  928.  
  929.    /* We may have lowered some copy instructions to load/store
  930.     * instructions.  The uses from the copy instructions hav already been
  931.     * removed but we need to rescan to ensure that the uses from the newly
  932.     * added load/store instructions are registered.  We need this
  933.     * information for phi node insertion below.
  934.     */
  935.    nir_foreach_block(impl, register_variable_uses_block, &state);
  936.  
  937.    insert_phi_nodes(&state);
  938.    rename_variables_block(impl->start_block, &state);
  939.  
  940.    nir_metadata_preserve(impl, nir_metadata_block_index |
  941.                                nir_metadata_dominance);
  942.  
  943.    ralloc_free(state.dead_ctx);
  944.  
  945.    return progress;
  946. }
  947.  
  948. void
  949. nir_lower_vars_to_ssa(nir_shader *shader)
  950. {
  951.    nir_foreach_overload(shader, overload) {
  952.       if (overload->impl)
  953.          nir_lower_vars_to_ssa_impl(overload->impl);
  954.    }
  955. }
  956.