[llvm] [BPF] Remove 'may_goto 0' instructions (PR #123482)

via llvm-commits llvm-commits at lists.llvm.org
Fri Jan 24 13:52:46 PST 2025


================
@@ -682,6 +685,56 @@ bool BPFMIPreEmitPeephole::insertMissingCallerSavedSpills() {
   return Changed;
 }
 
+bool BPFMIPreEmitPeephole::removeMayGotoZero() {
+  bool Changed = false;
+  MachineBasicBlock *Prev_MBB, *Curr_MBB = nullptr;
+
+  for (MachineBasicBlock &MBB : make_early_inc_range(reverse(*MF))) {
+    Prev_MBB = Curr_MBB;
+    Curr_MBB = &MBB;
+    if (Prev_MBB == nullptr)
+      continue;
+
+    MachineInstr &MI = MBB.back();
+    if (MI.getOpcode() != TargetOpcode::INLINEASM_BR)
+      continue;
+
+    const char *AsmStr = MI.getOperand(0).getSymbolName();
+    SmallVector<StringRef, 4> AsmPieces;
+    SplitString(AsmStr, AsmPieces, ";\n");
+
+    // Do not support multiple insns in one inline asm.
+    if (AsmPieces.size() != 1)
+      continue;
+
+    // The asm insn must be a may_goto insn.
+    SmallVector<StringRef, 4> AsmOpPieces;
+    SplitString(AsmPieces[0], AsmOpPieces, " ");
+    if (AsmOpPieces[0] != "may_goto")
----------------
eddyz87 wrote:

I think that `AsmOpPieces[1]` should be checked as well (and total number of pieces).
Otherwise the algorithm would produce strange results for the following (incorrect) inputs:

```c
void bar() {
  asm volatile goto ("may_goto +1;"::::lbl); // should not be removed
 lbl:
  asm volatile("r0 = 42;");
  return;
}
```

```c
void bar() {
  asm volatile goto ("may_goto foobar;"::::lbl); // should not be removed, asm parser should report error later
 lbl:
  asm volatile("r0 = 42;");
  return;
}
```

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


More information about the llvm-commits mailing list