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

    <tr>
        <th>Summary</th>
        <td>
            Miss optimize for loop vsetvli
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            backend:RISC-V,
            missed-optimization
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
            preames,
            topperc
      </td>
    </tr>

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

<pre>
    Hi,

For the bellow C code, there is a redundant `vsetvli` instruction in the loop body of the output assembly code. I think this can be removed and also need to pay attention to situations that cannot be removed, such as `vl` and `vtype` at the end of the loop being different. Thanks.

C code:

```c
#include <riscv_vector.h>

void foo9 (int8_t *base, int8_t* out, size_t vl, size_t m)
{
    vint8mf8_t v0;
    size_t avl = vsetvl_e8mf8 (vl);

    for (size_t i = 0; i < m; i++)
    {
        v0 = vle8_v_i8mf8 (base + i, avl);
        vse8_v_i8mf8 (out + i, v0, avl);
    }
}
```

asm:

```asm
foo9:                                   # @foo9
        vsetvli a2, a2, e8, mf8, ta, mu
        beqz    a3, .LBB0_2
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
        vsetvli zero, a2, e8, mf8, ta, mu
        vle8.v  v8, (a0)
        vse8.v  v8, (a1)
        addi    a3, a3, -1
        addi    a1, a1, 1
        addi    a0, a0, 1
        bnez    a3, .LBB0_1
.LBB0_2:
        ret
```

compiler explorer: https://godbolt.org/z/P6b7dPWPP
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyVVVtvozgU_jXwYhWBCYE88NAmO5pKs1K1O9p5jAw-Cd4am7UNM-2v32NDmqTTzgWB7XN8Lt-52DSaP9UfRUS3UbqL0tt5_KANcR2QBqTUX8mWtJoDynimASIsYcQAHxVnypFonU4W3CQFrohQ1pmxdUIrXAczUuuBNOiJ6ENg6NENoyPMWugb-RTMJ-Qe94R69KMlLVP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