================
@@ -1152,6 +1153,147 @@ void AArch64::applyBranchToBranchOpt() const {
redirectControlTransferRelocations);
}
+// Returns true if the AArch64 relocation type is a direct branch/call that
+// does not constitute an address-taken use of a function symbol. A function
+// reached only via such relocations never has its address stored anywhere and
+// therefore does not need a BTI landing pad.
+static bool isAArch64DirectBranchReloc(RelType type) {
+ switch (type) {
+ case R_AARCH64_CALL26:
+ case R_AARCH64_JUMP26:
+ case R_AARCH64_CONDBR19:
+ case R_AARCH64_TSTBR14:
+ case R_AARCH64_PLT32:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// BTI link-time relaxation: replace a redundant "bti c" instruction at the
+// entry of a function with a NOP when the linker can prove that the function
+// is never the target of an indirect branch.
+//
+// The compiler conservatively adds "bti c" to every function with external
+// linkage because it cannot know at compile time whether the function will be
+// called indirectly. The linker, however, has whole-program visibility and
+// can determine which functions are only ever reached via direct BL/B
+// branches. For those functions the "bti c" is redundant and can be replaced
+// with a NOP, reducing code size without compromising security.
+//
+// A function's "bti c" is KEPT when any of the following hold:
+// isGlobal(sym): preemptible (dynamic interposition), exported to
+// .dynsym, or in a shared library where all globally
+// visible symbols are potentially called indirectly.
+// isAddressTaken(sym): has a PLT entry (PLT uses an indirect branch),
+// has a GOT entry (address can be loaded and used as a
+// function pointer), is an ifunc (always uses IPLT),
+// or is referenced by a non-direct-branch relocation
+// (address stored in data or computed in code for use
+// as a function pointer).
+// hasDirectBranchReloc(sym): at least one direct branch relocation was seen
----------------
smithp35 wrote:
I don't follow the logic here. That there is a direct branch to a symbol, does not predict that there will also be an indirect branch to a symbol.
If I'm reading the code below correctly, the condition is at least one direct branch relocation is necessary to be a candidate to remove the BTI, however the comment says that at least one of the conditions is necessary to keep the BTI. I think the comment and the implementation are out of sync.
```
if (addrTaken.count(d))
return;
if (!hasDirectBranchReloc.count(d))
return;
```
https://github.com/llvm/llvm-project/pull/187871