- if (val->defs[block->index] == NULL) {
- if (block->imm_dom) {
- /* Grab it from our immediate dominator. We'll stash it here for
- * easy access later.
- */
- val->defs[block->index] =
- nir_phi_builder_value_get_block_def(val, block->imm_dom);
- return val->defs[block->index];
- } else {
- /* No immediate dominator means that this block is either the
- * start block or unreachable. In either case, the value is
- * undefined so we need an SSA undef.
- */
- nir_ssa_undef_instr *undef =
- nir_ssa_undef_instr_create(val->builder->shader,
- val->num_components);
- nir_instr_insert(nir_before_cf_list(&val->builder->impl->body),
- &undef->instr);
- val->defs[block->index] = &undef->def;
- return &undef->def;
- }
- } else if (val->defs[block->index] == NEEDS_PHI) {
- /* If we need a phi instruction, go ahead and create one but don't
- * add it to the program yet. Later, we'll go through and set up phi
- * sources and add the instructions will be added at that time.
+ /* Crawl up the dominance tree and find the closest dominator for which we
+ * have a valid ssa_def, if any.
+ */
+ nir_block *dom = block;
+ struct hash_entry *he = NULL;
+
+ while (dom != NULL) {
+ he = _mesa_hash_table_search(&val->ht, INDEX_TO_KEY(dom->index));
+ if (he != NULL)
+ break;
+
+ dom = dom->imm_dom;
+ }
+
+ /* Exactly one of (he != NULL) and (dom == NULL) must be true. */
+ assert((he != NULL) != (dom == NULL));
+
+ nir_ssa_def *def;
+ if (dom == NULL) {
+ /* No dominator means either that we crawled to the top without ever
+ * finding a definition or that this block is unreachable. In either
+ * case, the value is undefined so we need an SSA undef.
+ */
+ nir_ssa_undef_instr *undef =
+ nir_ssa_undef_instr_create(val->builder->shader,
+ val->num_components,
+ val->bit_size);
+ nir_instr_insert(nir_before_cf_list(&val->builder->impl->body),
+ &undef->instr);
+ def = &undef->def;
+ } else if (he->data == NEEDS_PHI) {
+ /* The magic value NEEDS_PHI indicates that the block needs a phi node
+ * but none has been created. We need to create one now so we can
+ * return it to the caller.
+ *
+ * Because a phi node may use SSA defs that it does not dominate (this
+ * happens in loops), we do not yet have enough information to fully
+ * fill out the phi node. Instead, the phi nodes we create here will be
+ * empty (have no sources) and won't actually be placed in the block's
+ * instruction list yet. Later, in nir_phi_builder_finish(), we walk
+ * over all of the phi instructions, fill out the sources lists, and
+ * place them at the top of their respective block's instruction list.
+ *
+ * Creating phi nodes on-demand allows us to avoid creating dead phi
+ * nodes that will just get deleted later. While this probably isn't a
+ * big win for a full into-SSA pass, other users may use the phi builder
+ * to make small SSA form repairs where most of the phi nodes will never
+ * be used.