[LLD][COFF] Don't thunk an in-range branch within one section #240564
@mstorsjo could you review this?
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-lld-coff
@llvm/pr-subscribers-lld
@llvm/pr-subscribers-platform-windows
Author: Hamed (hamed7ir)
<details>
<summary>Changes</summary>
createThunks gives a branch a range extension thunk when it is out of range
with a safety margin, and the margin grows when a pass fails. A branch to a
target in its own section chunk got one too, although its distance can't
change: thunks are only placed between chunks. The thunk clobbers r12 on ARM
(x16 on ARM64) in the middle of a function. MSVC's __rt_sdiv keeps a value
in r12 across such a branch, so its remainders came back with the wrong
sign. Check these branches without the margin.
Assisted-by: Claude Opus 5.5 (Anthropic)
---
Full diff: https://github.com/llvm/llvm-project/pull/240564.diff
3 Files Affected:
````````````diff --git a/lld/COFF/Writer.cpp b/lld/COFF/Writer.cpp
index 3cab426df55cf3..a692ee7e23c13a 100644
--- a/lld/COFF/Writer.cpp
+++ b/lld/COFF/Writer.cpp
@@ -530,6 +530,14 @@ bool Writer::createThunks(OutputSection *os, int margin) {
uint64_t s = sym->getRVA();
+ // A target in the relocation's own chunk needs no margin: thunks are
+ // only inserted between chunks, so this distance cannot change.
+ if (auto *dr = dyn_cast<DefinedRegular>(sym))
+ if (dr->getChunk() == sc &&
+ isInRange(rel.Type, s, sc->getRVA() + rel.VirtualAddress, 0,
+ machine))
+ continue;
+
if (isInRange(rel.Type, s, p, margin, machine))
continue;
diff --git a/lld/test/COFF/arm-thumb-thunks-same-chunk.s b/lld/test/COFF/arm-thumb-thunks-same-chunk.s
new file mode 100644
index 00000000000000..521e90931f667c
--- /dev/null
+++ b/lld/test/COFF/arm-thumb-thunks-same-chunk.s
@@ -0,0 +1,33 @@
+// REQUIRES: arm
+// RUN: llvm-mc -filetype=obj -triple=thumbv7-windows %s -o %t.obj
+// RUN: lld-link -entry:main -subsystem:console %t.obj -out:%t.exe -verbose 2>&1 | FileCheck -check-prefix=VERBOSE %s
+// RUN: llvm-objdump --no-print-imm-hex -d %t.exe --start-address=0x401000 --stop-address=0x401008 | FileCheck --check-prefix=MAIN %s
+
+// A branch to a target in its own section chunk gets no thunk while it is in
+// range, even within the margin, because its distance can't change. A thunk
+// would clobber r12. far_target is out of range and gets the one thunk.
+// local_target is a function so that the assembler keeps the relocation.
+
+// VERBOSE: Added 1 thunks with margin 102400 in 1 passes
+
+// MAIN: 401000: {{.*}}bne.w 0x4f1004 <.text+0xf0004>
+// MAIN-NEXT: 401004: {{.*}}bne.w 0x4f1006 <.text+0xf0006>
+
+ .syntax unified
+ .globl main
+ .text
+ .def main; .scl 2; .type 32; .endef
+main:
+ bne.w local_target
+ bne.w far_target
+ bx lr
+ .space 0xF0000 - 6
+ .def local_target; .scl 3; .type 32; .endef
+local_target:
+ bx lr
+ .section .text$z, "xr"
+ .space 0x100000
+ .def far_target; .scl 2; .type 32; .endef
+ .globl far_target
+far_target:
+ bx lr
diff --git a/lld/test/COFF/arm64-thunks-same-chunk.s b/lld/test/COFF/arm64-thunks-same-chunk.s
new file mode 100644
index 00000000000000..aeab431f7d084a
--- /dev/null
+++ b/lld/test/COFF/arm64-thunks-same-chunk.s
@@ -0,0 +1,31 @@
+// REQUIRES: aarch64
+// RUN: llvm-mc -filetype=obj -triple=aarch64-windows %s -o %t.obj
+// RUN: lld-link -entry:main -subsystem:console %t.obj -out:%t.exe -verbose 2>&1 | FileCheck -check-prefix=VERBOSE %s
+// RUN: llvm-objdump --no-print-imm-hex -d %t.exe --start-address=0x140001000 --stop-address=0x140001008 | FileCheck %s
+
+// The same on ARM64: every BRANCH14 is within the initial margin of its range,
+// but the TBZ to a target in its own chunk stays direct. The one to far, in
+// another chunk, gets the one thunk. near is a function so that the assembler
+// keeps the relocation.
+
+// VERBOSE: Added 1 thunks with margin 102400 in 1 passes
+
+// CHECK: 140001000: {{.*}}tbz w0, #0, 0x14000100c
+// CHECK-NEXT: 140001004: {{.*}}tbz w0, #0, 0x140001010
+
+ .globl main
+ .globl near
+ .text
+main:
+ tbz w0, #0, near
+ tbz w0, #0, far
+ ret
+ .def near; .scl 2; .type 32; .endef
+near:
+ ret
+ .section .text$a, "xr"
+ .space 0x8000
+ .section .text$b, "xr"
+ .globl far
+far:
+ ret
</details>
I think this condition may be fine - but, if the isInRange() check here fails, that also means that the added thunk will be out of range, as it will be at least as far away as the end of the chunk, right?
(So if we're hitting it, the thunk insertion won't converge in the end at all anyway - right?)
I don't immediately understand what you refer to with "near is a function so that the assembler keeps the relocation" here?
Thanks, this looks good in general! I've got two questions about it though.
Also CC @kfarnung who recently also was touching the thunk insertion algorithm. This change might reduce the number of thunks inserted.
Yes, for a forward branch. The thunk goes after the chunk, past the target, so it's out of range too. I tried a tbz to a function 36 KB ahead in the same section: lld stops with "adding thunks hasn't converged after 10 passes", the same as without this patch.
A backward branch can still work, though. A tbz at the end of a 36 KB function back to its start gets a thunk right after the chunk, which is in range, and it links. That's why I only skip the margin when the branch is in range without one, and otherwise keep the old path.
llvm-mc resolves a branch to a plain label in the same section by itself and emits no relocation, so lld never sees that branch and the test would check nothing. With near declared as a function (the .def line), it keeps the IMAGE_REL_ARM64_BRANCH14; the .globl doesn't matter. I reworded the comment in both tests to say that (89d686922fa3).
Ok, I see! Yeah, then tentatively trying to add a thunk may or may not work when out of range within the same chunk seems reasonable.
I was aware of the assembler avoiding the symbol reference and relocation when possible - but I wasn't aware that it doesn't do this if the symbol is declared as a function with .def - interesting! (Do you happen to have a reference to the code where/why it does that? Is it an explicit feature or an implicit consequence of something else?)
What's the difference between the .def here for local_target (which uses .scl 3) vs for main (which uses .scl 2)?
I looked it up - .scl 3 is IMAGE_SYM_CLASS_STATIC (i.e. static symbol) while .scl 2 is IMAGE_SYM_CLASS_EXTERNAL); the fact that it is a function is set by .type 32 (which is IMAGE_SYM_DTYPE_FUNCTION but left-shifted by 4 I think).
Actually - if llvm-mc would change in the future so that it would avoid the relocation and symbol reference for references within the section, even when declared as a function, then the test would lose coverage of this. Can we add a check in the test that we actually do have the expected relocations in the right places here?
It's explicit. WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl in llvm/lib/MC/WinCOFFObjectWriter.cpp never treats a reference to a symbol of function type as resolved, even within the same section. Its comment says MSVC linker features need those relocations: /INCREMENTAL points them at thunks, and /GUARD:CF (lld's too) uses them to find the address-taken functions.
Good idea, done in 0649d73886d4. Both tests now check with llvm-objdump -r that the two branches keep their relocations. I tried it: without the .def line, the RELOC check fails.
Yes, that's it. .scl 3 keeps local_target static, and .type 32 (IMAGE_SYM_DTYPE_FUNCTION shifted by SCT_COMPLEX_TYPE_SHIFT) makes it a function, which is what that check in WinCOFFObjectWriter looks at. I left it static so the test doesn't depend on the target being global.
LGTM
Thanks for digging up the reference, and for adding the check to the testcase!
mstorsjo
hamed7ir
createThunks gives a branch a range extension thunk when it is out of range
with a safety margin, and the margin grows when a pass fails. A branch to a
target in its own section chunk got one too, although its distance can't
change: thunks are only placed between chunks. The thunk clobbers r12 on ARM
(x16 on ARM64) in the middle of a function. MSVC's __rt_sdiv keeps a value
in r12 across such a branch, so its remainders came back with the wrong
sign. Check these branches without the margin.
Assisted-by: Claude Opus 5.5 (Anthropic)