[llvm] [SimpleLoopUnswitch] Allow trivial unswitch when exit LCSSA is a header PHI (PR #222962)

Ehsan Amiri via llvm-commits llvm-commits at lists.llvm.org
Thu Sep 17 06:46:58 PDT 2026


amehsan wrote:

IIUC, you can define a helper function like this

```
static Value *getLoopEntryValue(const Loop &L, Value *V) {
  if (!isLoopHeaderPHI(L, V))
    return V;
  return cast<PHINode>(V)->getIncomingValueForBlock(L.getLoopPreheader());
}
```

and it will help you simplify your code in a couple of places:

1- for codegen changes, you don't need the code that you have written currently. You can simply add the following line to `rewritePHINodesForUnswitchedExitBlock`:
```
PN.setIncomingValue(i, getLoopEntryValue(L, PN.getIncomingValue(i)));
```

2- This picks up correct incoming value for both loop invariant values and header phi nodes, so you won't need to pass a `bool *` to `areLoopExitPHIsTrivial`. a `bool` will be enough. 

3- Also a slightly simpler change in the body of `areLoopExitPHIsTrivial` will suffice.

```
-    if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
+    const Value *Incoming = PN->getIncomingValueForBlock(&ExitingBB);
+    if (!L.isLoopInvariant(Incoming) &&
+        !(AllowHeaderPHIs && isLoopHeaderPHI(L, Incoming)))
       return false;

```


https://github.com/llvm/llvm-project/pull/222962


More information about the llvm-commits mailing list