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

    <tr>
        <th>Summary</th>
        <td>
            Missing optimization: loop invariant memset should be hoisted if it's the only memory access in loop
        </td>
    </tr>

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

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

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

<pre>
    Currently memset is unrolled and optimized within the body of the loop instead of being hoisted, which is suboptimal when the unrolling is less than the iteration number: https://godbolt.org/z/dK3a7xjPW.

This also means -fno-unroll-loops causes the memsets to not be optimized at all.

Previously discussed in https://github.com/llvm/llvm-project/issues/143015:

> The optimization happens as a result of unrolling, so it is affected by target-dependent heuristics. It would be legal to do it independently of unrolling by hoisting the memset out of the loop, it's just not implemented. It does work for a plain store, implemented here I believe: https://github.com/llvm/llvm-project/blob/470f456567fb6c6ee8b6e51c06a64536ca076d74/llvm/lib/Transforms/Scalar/LICM.cpp#L1269 It could be extended to the memset case. 

 _Originally posted by @nikic in [#143015](https://github.com/llvm/llvm-project/issues/143015#issuecomment-2948480418)_
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJykVE2P2zYQ_TX0ZWBDoj590GGb1MCiCRqgC-QY8GNkzYYiBQ61jvPrC8r71aJADzlZID3vzbz3OIqZzh5xEM1vovm4U2uaQhy-Km8xkj_frVHtdLDX4cMaI_rkrjDjzJiAGFYfg3NoQXkLYUk000-0cKE0kYc0IeRSCOP27UJYgDwnVDafaSR_hikQJ7RCfoDLRGbKuLzqDU05uEx4Q7px5QpicMgMaVK3K0oYVaLgwa-zxiiqO5hSWlhUd0KehDydg9XBpUOIZyFPP4U82T8q1f14_PL1IIo7Udw9TMSgHAeYUXmG_ejD_sa5z40zGLUy8kZ4U4AhBfAhgcZ3w6sEyrln1C8Rnyis7K5gic3KjBb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