[llvm] [ControlFlowHub] Add support for switch-based guards (PR #213549)
Robert Imschweiler via llvm-commits
llvm-commits at lists.llvm.org
Mon Sep 7 09:00:15 PDT 2026
================
@@ -350,5 +363,68 @@ std::pair<BasicBlock *, bool> ControlFlowHub::finalize(
Inst->eraseFromParent();
}
- return {FirstGuardBlock, true};
+ return FirstGuardBlock;
+}
+
+BasicBlock *ControlFlowHub::finalizeAsSwitch(
+ DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
+ const StringRef Prefix, SetVector<BasicBlock *> &Outgoing) {
+
+ SmallVector<DominatorTree::UpdateType, 16> Updates;
+ if (DTU) {
+ for (auto [BB, Succ0, Succ1] : Branches) {
+ if (Succ0)
+ Updates.push_back({DominatorTree::Delete, BB, Succ0});
+ // Only add Succ1 if it's different from Succ0 to avoid duplicate updates
+ if (Succ1 && Succ1 != Succ0)
+ Updates.push_back({DominatorTree::Delete, BB, Succ1});
+ }
+ }
+
+ Function *F = Outgoing.front()->getParent();
+ BasicBlock *Guard = BasicBlock::Create(F->getContext(), Prefix + ".guard", F);
+ GuardBlocks.push_back(Guard);
+ Type *Int32Ty = Type::getInt32Ty(F->getContext());
+ IRBuilder<> Builder(Guard);
+ auto *Phi = Builder.CreatePHI(Int32Ty, Branches.size(), "merged.bb.idx");
+ for (auto [BB, Succ0, Succ1] : Branches) {
+ Value *Condition = redirectToHub(BB, Succ0, Succ1, Guard);
+ Value *IncomingId = nullptr;
+
+ if (Succ0 && Succ1 && Succ0 != Succ1) {
+ Value *Id0 = ConstantInt::get(
+ Int32Ty, std::distance(Outgoing.begin(), find(Outgoing, Succ0)));
+ Value *Id1 = ConstantInt::get(
+ Int32Ty, std::distance(Outgoing.begin(), find(Outgoing, Succ1)));
+ IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
+ BB->getTerminator()->getIterator());
+ } else {
+ BasicBlock *Succ = Succ0 ? Succ0 : Succ1;
+ uint64_t Idx = std::distance(Outgoing.begin(), find(Outgoing, Succ));
+ IncomingId = ConstantInt::get(Int32Ty, Idx);
+ }
+
+ Phi->addIncoming(IncomingId, BB);
+ }
+
+ BasicBlock *DefaultDest =
+ BasicBlock::Create(F->getContext(), Prefix + ".guard.default", F);
+ IRBuilder<>(DefaultDest).CreateUnreachable();
----------------
ro-i wrote:
this might be an issue? For example, doesn't this generate another loop exit that would need to be handled by UnifyLoopExits? If only the real targets would be used for the switch, I think this would save us from unnecessary (?) complexity.
https://github.com/llvm/llvm-project/pull/213549
More information about the llvm-commits
mailing list