| Issue |
234428
|
| Summary |
[BOLT] A block-ending branch that BOLT re-creates loses its line and runs under the next block's CFI
|
| Labels |
BOLT
|
| Assignees |
|
| Reporter |
not4juu
|
## Description
With `--update-debug-sections`, an unconditional branch or tail call that ends a basic block and that BOLT re-creates has two problems:
1. **Line table:** the new branch has no row of its own and reports the line of the instruction before it.
2. **CFI:** when the input's next block starts with another CFI state, the output switches to that state at the branch instead of after it. Unwinding from a PC on the branch recovers the wrong caller.
**Environment:**
- **BOLT:** `llvm-bolt` built from `bd6adfedc776c07caf158e59367d9c246c933510`
- **Tools:** `clang`, `llvm-symbolizer` and `llvm-dwarfdump` `23.0.0git` (same build), GNU Binutils 2.46 (`ld`, `objdump`), `gdb 16.3`
## Reproducer
Clang shrink-wraps `f`: the frameless early return (`return a * 3`) is laid out right after the `jmp` that closes the inlined `times` loop, which runs with the 144-byte frame set up.
```cpp
// lib.cpp
static unsigned long times(const unsigned long *m, unsigned long v) {
unsigned long s = 0;
while (v) { if (v & 1) s ^= *m; v >>= 1; m++; }
return s;
}
unsigned long f(unsigned long a, unsigned long b, long len) {
if (len <= 0) return a * 3;
unsigned long m[32];
for (int i = 0; i < 32; i++) m[i] = 1UL << i;
do {
if (len & 1) a = times(m, a);
len >>= 1;
if (len == 0) break;
if (len & 1) a = times(m, a + 1);
len >>= 1;
} while (len != 0);
return a ^ b;
}
```
```cpp
// main.cpp
unsigned long f(unsigned long a, unsigned long b, long len);
int main(int argc, char **) { return (int)f(argc, 0, argc); }
```
```bash
clang++ -O2 -gdwarf-5 -gz=none -fPIC -shared lib.cpp -o libt.so -Wl,--emit-relocs
clang++ -O2 -gdwarf-5 -gz=none main.cpp -o main -L. -lt
mkdir -p bolt && llvm-bolt libt.so -o bolt/libt.so --update-debug-sections
```
## Analysis
The code is laid out the same on both sides, with the branch at `f+0x1b3` (`0x12b3 - 0x1100`) and `f+0x19a` (`0x40025a - 0x4000c0`):
```bash
objdump -d --no-show-raw-insn --disassemble=_Z1fmml libt.so
objdump -d --no-show-raw-insn --disassemble=_Z1fmml bolt/libt.so
# libt.so # bolt/libt.so
0000000000001100 <_Z1fmml>: 00000000004000c0 <_Z1fmml>:
... ...
12b0: xor (%r8),%rdi 400257: xor (%r8),%rdi
12b3: jmp 12a0 <_Z1fmml+0x1a0> 40025a: jmp 400247 <_Z1fmml+0x187>
12b5: lea (%rax,%rax,2),%rax 40025c: lea (%rax,%rax,2),%rax
12b9: ret 400260: ret
```
```bash
llvm-symbolizer -e libt.so 0x12b3
llvm-symbolizer -e bolt/libt.so 0x40025a
llvm-dwarfdump --eh-frame libt.so
llvm-dwarfdump --eh-frame bolt/libt.so
```
| | `libt.so` | `bolt/libt.so` | expected result |
| ----------------- | ------------------------------------------ | ---------------------------------- | ---------------------------- |
| line of the `jmp` | `lib.cpp:0` | `lib.cpp:4` (as the `xor`) | `lib.cpp:0` |
| CFA at the `jmp` | `rsp+144` (row `rsp+8` starts at `0x12b5`) | `rsp+8` (row starts at `0x40025a`) | `rsp+144`, row at `0x40025c` |
`llvm-dwarfdump --verify` does not detect it: it reports the same three `.debug_str_offsets` errors for both files, which are already in the input.
```bash
LD_LIBRARY_PATH=. gdb -q -batch ./main -ex 'break main' -ex run -ex 'break *(f+0x1b3)' -ex continue -ex bt
LD_LIBRARY_PATH=bolt gdb -q -batch ./main -ex 'break main' -ex run -ex 'break *(f+0x19a)' -ex continue -ex bt
```
```text
# libt.so
#0 0x00007ffff7fba2b3 in times (m=0x7fffffffc880, v=1) at lib.cpp:4
#1 f (a=<optimized out>, b=0, len=1) at lib.cpp:12
#2 0x00007ffff7aaa58e in __libc_start_call_main () from /lib64/libc.so.6
#3 0x00007ffff7aaa649 in __libc_start_main_impl () from /lib64/libc.so.6
#4 0x0000555555555075 in _start ()
# bolt/libt.so
#0 0x00007ffff7e0025a in times (m=0x7fffffffc880, v=1) at lib.cpp:4
#1 f (a=<optimized out>, b=0, len=1) at lib.cpp:12
#2 0x0000000000010000 in ?? ()
#3 0x0000000000020000 in ?? ()
...
#17 0x0000000080000000 in ?? ()
#18 0x0000000000000000 in ?? ()
```
On the BOLTed branch the unwinder takes the return address from inside the frame: the "callers" are the elements of `m`. A signal, a sampling profiler, or a debugger stopping on such a branch gets the same broken stack.
### Cause
- `buildCFG()` attaches the CFI at the offset of the next instruction to the current block: in a block ending in a `jmp`, the next block's CFI sits **after** the `jmp`.
- `fixBranches()` (`addBranchInstruction()`) and `fixDoubleJumps()` (`addTailCallInstruction()`) re-create that branch at the end of the block, after the CFI, so it runs under the next block's state.
- These branches, and the `jmp callee` that `removeConditionalTailCalls()` builds, have no `SMLoc`. `emitLineInfo()` emits no row for them, so they get the line of the instruction before.
## Proposed fix
`fixBranches()` records the debug location of the old branch and how many pseudo-instructions follow it, and `addBranchInstruction()` inserts the new branch at that position with that location. The location (`SMLoc`) refers to the branch's rows in the input line table, so `emitLineInfo()` emits a row for it again. The exact position matters: the branch has to stay after the CFI that describes it and before the CFI of the next block. In an AArch64 epilogue (`ldp x29, x30, [sp], #0x20` + CFI + `b`), putting it before all trailing CFI would give the `b` the CFA rule from before the `ldp`, although the frame is already popped. A block without an old branch falls through, and its trailing CFI describes its last instruction (e.g. a `pop`), so the new branch goes at the end.
`fixDoubleJumps()` turns the old jump into the tail call in place (`createTailCall()` replaces only the opcode and the operands), and `removeConditionalTailCalls()` gives the new tail call the debug location of the conditional one.
```diff
diff --git a/bolt/include/bolt/Core/BinaryBasicBlock.h b/bolt/include/bolt/Core/BinaryBasicBlock.h
--- a/bolt/include/bolt/Core/BinaryBasicBlock.h
+++ b/bolt/include/bolt/Core/BinaryBasicBlock.h
@@ -440,8 +440,10 @@ public:
bool swapConditionalSuccessors();
/// Add an instruction with unconditional control transfer to \p Successor
- /// basic block to the end of this basic block.
- void addBranchInstruction(const BinaryBasicBlock *Successor);
+ /// basic block to the end of this basic block, before the last
+ /// \p NumPseudosAfter instructions, with debug location \p Loc.
+ void addBranchInstruction(const BinaryBasicBlock *Successor,
+ SMLoc Loc = SMLoc(), unsigned NumPseudosAfter = 0);
/// Add an instruction with tail call control transfer to \p Target
/// to the end of this basic block.
diff --git a/bolt/lib/Core/BinaryBasicBlock.cpp b/bolt/lib/Core/BinaryBasicBlock.cpp
--- a/bolt/lib/Core/BinaryBasicBlock.cpp
+++ b/bolt/lib/Core/BinaryBasicBlock.cpp
@@ -455,13 +455,17 @@ bool BinaryBasicBlock::swapConditionalSuccessors() {
return true;
}
-void BinaryBasicBlock::addBranchInstruction(const BinaryBasicBlock *Successor) {
+void BinaryBasicBlock::addBranchInstruction(const BinaryBasicBlock *Successor,
+ SMLoc Loc,
+ unsigned NumPseudosAfter) {
assert(isSuccessor(Successor));
BinaryContext &BC = Function->getBinaryContext();
MCInst NewInst;
std::unique_lock<llvm::sys::RWMutex> Lock(BC.CtxMutex);
BC.MIB->createUncondBranch(NewInst, Successor->getLabel(), BC.Ctx.get());
- Instructions.emplace_back(std::move(NewInst));
+ NewInst.setLoc(Loc);
+ Instructions.emplace(Instructions.end() - NumPseudosAfter,
+ std::move(NewInst));
}
void BinaryBasicBlock::addTailCallInstruction(const MCSymbol *Target) {
diff --git a/bolt/lib/Core/BinaryFunction.cpp b/bolt/lib/Core/BinaryFunction.cpp
--- a/bolt/lib/Core/BinaryFunction.cpp
+++ b/bolt/lib/Core/BinaryFunction.cpp
@@ -2654,6 +2654,7 @@ void BinaryFunction::removeConditionalTailCalls() {
assert(CTCTargetLabel && "symbol expected for conditional tail call");
MCInst TailCallInstr;
BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
+ TailCallInstr.setLoc(CTCInstr->getLoc());
// Move offset from CTCInstr to TailCallInstr.
if (const std::optional<uint32_t> Offset = BC.MIB->getOffset(*CTCInstr)) {
@@ -3667,8 +3668,15 @@ void BinaryFunction::fixBranches() {
continue;
// We will create unconditional branch with correct destination if needed.
- if (UncondBranch)
+ // Put the new branch where the old one was (before the next block's CFI),
+ // with its debug location. Without one, trailing CFI applies to the branch.
+ unsigned NumPseudosAfter = 0;
+ SMLoc BranchLoc;
+ if (UncondBranch) {
+ NumPseudosAfter = std::distance(BB->rbegin(), BB->getLastNonPseudo());
+ BranchLoc = UncondBranch->getLoc();
BB->eraseInstruction(BB->findInstruction(UncondBranch));
+ }
// Basic block that follows the current one in the final layout.
const BinaryBasicBlock *const NextBB =
@@ -3683,7 +3691,7 @@ void BinaryFunction::fixBranches() {
BB->eraseInstruction(BB->findInstruction(CondBranch));
if (BB->getSuccessor() == NextBB)
continue;
- BB->addBranchInstruction(BB->getSuccessor());
+ BB->addBranchInstruction(BB->getSuccessor(), BranchLoc, NumPseudosAfter);
} else if (BB->succ_size() == 2) {
assert(CondBranch && "conditional branch expected");
const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
@@ -3703,7 +3711,7 @@ void BinaryFunction::fixBranches() {
BB->removeDuplicateConditionalSuccessor(CondBranch);
if (TSuccessor != NextBB)
- BB->addBranchInstruction(TSuccessor);
+ BB->addBranchInstruction(TSuccessor, BranchLoc, NumPseudosAfter);
continue;
}
@@ -3750,7 +3758,7 @@ void BinaryFunction::fixBranches() {
swapSuccessors();
}
- BB->addBranchInstruction(FSuccessor);
+ BB->addBranchInstruction(FSuccessor, BranchLoc, NumPseudosAfter);
}
// Cases where the number of successors is 0 (block ends with a
// terminator) or more than 2 (switch table) don't require branch
diff --git a/bolt/lib/Passes/BinaryPasses.cpp b/bolt/lib/Passes/BinaryPasses.cpp
--- a/bolt/lib/Passes/BinaryPasses.cpp
+++ b/bolt/lib/Passes/BinaryPasses.cpp
@@ -780,13 +780,10 @@ static uint64_t fixDoubleJumps(BinaryFunction &Function, bool MarkInvalid) {
if (Branch && MIB->isUnconditionalBranch(*Branch)) {
assert(MIB->getTargetSymbol(*Branch) == BB.getLabel());
Pred->removeSuccessor(&BB);
- Pred->eraseInstruction(Pred->findInstruction(Branch));
- Pred->addTailCallInstruction(SuccSym);
- if (Offset) {
- MCInst *TailCall = Pred->getLastNonPseudoInstr();
- assert(TailCall);
- MIB->setOffset(*TailCall, *Offset);
- }
+ // In place, to keep the jump's position and debug location.
+ MIB->createTailCall(*Branch, SuccSym, Ctx);
+ if (Offset)
+ MIB->setOffset(*Branch, *Offset);
} else {
return false;
}
```
> [!NOTE]
> A `DW_AT_call_return_pc` or a location list end at a re-created branch still lands past it, as the branch has no input offset (case 1 in the comment on [#230108](https://github.com/llvm/llvm-project/issues/230108)). With #230108 and the diff from its comment, that call site gets the right return PC.
Tested on the reproducer above: every instruction of `f` that comes from the input has the line and the CFA rule of its input instruction, and `gdb` unwinds from the branch to `_start`. The fix also covers:
- the AArch64 epilogue (`ldp` + CFI + `b`): line and CFA rule of the input branch;
- a jump to a shared tail call (`pop`/`ldp` + CFI + jump): line and CFA rule of the input jump;
- a block that ends in `pop %rbx` and falls through in the input, when its successor is moved away: the new `jmp` keeps `rsp+8`, the rule after the `pop`, as without the fix;
- the `jmp` of a conditional tail call kept split by `--sctc-mode=preserve`: line of the input `je`;
- with [#232806](https://github.com/llvm/llvm-project/issues/232806), the branch of a frontier stub (case 4 there): line of the branch it serves.
`check-bolt`, `check-large-bolt` and `check-large-bolt-arm` show no new failures.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs