<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/78154>78154</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [DSE] Wrong code introduced by DeadStoreElimination when moving a store through another store to the same memory location
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          adamszilagyi
      </td>
    </tr>
</table>

<pre>
    The wrong code was discovered in the following example:

https://godbolt.org/z/c65nxKhjY

With O1 the result is the correct `39058` value, but for O2, O3, Ofast, Oz DSE kicks in and the result becomes `0`

The changes made by DSE can be seen here: https://godbolt.org/z/3jGxM5PEn
DSE moves up the `store i16 -26478, ptr @g_127, align 2` store and merge it with `store i32 20, ptr @g_127, align 4` since these two stores refer to the same memory location and one overwrites the other value, but the problem is that when iterating through the in-between instruction to check if any of them potentially modifies the same memory location, the alias analysis somehow can not deduce that the `%0 = load volatile ptr, ptr @g_543, align 4` instruction refers to the same memory location so the store removing is not safe in this example, but DSE does it anyway and `@g_543` will be set to `0` by `store i32 0, ptr %0, align 4` hence the wrong `0` result at the end. The two global variables declaration in question is

```.C
union U1 {
   uint16_t  f0;
   int32_t f1;
   uint32_t  f2;
   signed f3 : 29;
};

static union U1 g_127 = {0x2045};
static int32_t * volatile g_543 = &g_127.f1;
```
Im not sure if this is an UB, but i think the store merging should not be possible in this situation.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyEVd-P4yYQ_mvIy2gjjH8kecjD7WVTVVV1la6nU59O2IztucWQAo4399dXYGeTXfVaKXJggOGbb74ZpPfUGcQ9Kx9ZeVjJMfTW7aWSg_9BWnYXWtVWXfZ_9giTs6aDxiqESXpQ5Bt7RocKyEDoEVqrtZ3IdIAvcjhpZPkHxg-ML98-hJOPNnFk4thZVVsd1tZ1TBx_MHFsqtK8_NZ__-v-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