1 //===- ARM64.cpp ----------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "Arch/ARM64Common.h" 10 #include "InputFiles.h" 11 #include "Symbols.h" 12 #include "SyntheticSections.h" 13 #include "Target.h" 14 15 #include "lld/Common/ErrorHandler.h" 16 #include "mach-o/compact_unwind_encoding.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/BinaryFormat/MachO.h" 20 #include "llvm/Support/Endian.h" 21 #include "llvm/Support/MathExtras.h" 22 23 using namespace llvm; 24 using namespace llvm::MachO; 25 using namespace llvm::support::endian; 26 using namespace lld; 27 using namespace lld::macho; 28 29 namespace { 30 31 struct ARM64 : ARM64Common { 32 ARM64(); 33 void writeStub(uint8_t *buf, const Symbol &) const override; 34 void writeStubHelperHeader(uint8_t *buf) const override; 35 void writeStubHelperEntry(uint8_t *buf, const Symbol &, 36 uint64_t entryAddr) const override; 37 const RelocAttrs &getRelocAttrs(uint8_t type) const override; 38 void populateThunk(InputSection *thunk, Symbol *funcSym) override; 39 void applyOptimizationHints(uint8_t *, const ConcatInputSection *, 40 ArrayRef<uint64_t>) const override; 41 }; 42 43 } // namespace 44 45 // Random notes on reloc types: 46 // ADDEND always pairs with BRANCH26, PAGE21, or PAGEOFF12 47 // POINTER_TO_GOT: ld64 supports a 4-byte pc-relative form as well as an 8-byte 48 // absolute version of this relocation. The semantics of the absolute relocation 49 // are weird -- it results in the value of the GOT slot being written, instead 50 // of the address. Let's not support it unless we find a real-world use case. 51 52 const RelocAttrs &ARM64::getRelocAttrs(uint8_t type) const { 53 static const std::array<RelocAttrs, 11> relocAttrsArray{{ 54 #define B(x) RelocAttrBits::x 55 {"UNSIGNED", 56 B(UNSIGNED) | B(ABSOLUTE) | B(EXTERN) | B(LOCAL) | B(BYTE4) | B(BYTE8)}, 57 {"SUBTRACTOR", B(SUBTRAHEND) | B(EXTERN) | B(BYTE4) | B(BYTE8)}, 58 {"BRANCH26", B(PCREL) | B(EXTERN) | B(BRANCH) | B(BYTE4)}, 59 {"PAGE21", B(PCREL) | B(EXTERN) | B(BYTE4)}, 60 {"PAGEOFF12", B(ABSOLUTE) | B(EXTERN) | B(BYTE4)}, 61 {"GOT_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(GOT) | B(BYTE4)}, 62 {"GOT_LOAD_PAGEOFF12", 63 B(ABSOLUTE) | B(EXTERN) | B(GOT) | B(LOAD) | B(BYTE4)}, 64 {"POINTER_TO_GOT", B(PCREL) | B(EXTERN) | B(GOT) | B(POINTER) | B(BYTE4)}, 65 {"TLVP_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(TLV) | B(BYTE4)}, 66 {"TLVP_LOAD_PAGEOFF12", 67 B(ABSOLUTE) | B(EXTERN) | B(TLV) | B(LOAD) | B(BYTE4)}, 68 {"ADDEND", B(ADDEND)}, 69 #undef B 70 }}; 71 assert(type < relocAttrsArray.size() && "invalid relocation type"); 72 if (type >= relocAttrsArray.size()) 73 return invalidRelocAttrs; 74 return relocAttrsArray[type]; 75 } 76 77 static constexpr uint32_t stubCode[] = { 78 0x90000010, // 00: adrp x16, __la_symbol_ptr@page 79 0xf9400210, // 04: ldr x16, [x16, __la_symbol_ptr@pageoff] 80 0xd61f0200, // 08: br x16 81 }; 82 83 void ARM64::writeStub(uint8_t *buf8, const Symbol &sym) const { 84 ::writeStub<LP64>(buf8, stubCode, sym); 85 } 86 87 static constexpr uint32_t stubHelperHeaderCode[] = { 88 0x90000011, // 00: adrp x17, _dyld_private@page 89 0x91000231, // 04: add x17, x17, _dyld_private@pageoff 90 0xa9bf47f0, // 08: stp x16/x17, [sp, #-16]! 91 0x90000010, // 0c: adrp x16, dyld_stub_binder@page 92 0xf9400210, // 10: ldr x16, [x16, dyld_stub_binder@pageoff] 93 0xd61f0200, // 14: br x16 94 }; 95 96 void ARM64::writeStubHelperHeader(uint8_t *buf8) const { 97 ::writeStubHelperHeader<LP64>(buf8, stubHelperHeaderCode); 98 } 99 100 static constexpr uint32_t stubHelperEntryCode[] = { 101 0x18000050, // 00: ldr w16, l0 102 0x14000000, // 04: b stubHelperHeader 103 0x00000000, // 08: l0: .long 0 104 }; 105 106 void ARM64::writeStubHelperEntry(uint8_t *buf8, const Symbol &sym, 107 uint64_t entryVA) const { 108 ::writeStubHelperEntry(buf8, stubHelperEntryCode, sym, entryVA); 109 } 110 111 // A thunk is the relaxed variation of stubCode. We don't need the 112 // extra indirection through a lazy pointer because the target address 113 // is known at link time. 114 static constexpr uint32_t thunkCode[] = { 115 0x90000010, // 00: adrp x16, <thunk.ptr>@page 116 0x91000210, // 04: add x16, [x16,<thunk.ptr>@pageoff] 117 0xd61f0200, // 08: br x16 118 }; 119 120 void ARM64::populateThunk(InputSection *thunk, Symbol *funcSym) { 121 thunk->align = 4; 122 thunk->data = {reinterpret_cast<const uint8_t *>(thunkCode), 123 sizeof(thunkCode)}; 124 thunk->relocs.push_back({/*type=*/ARM64_RELOC_PAGEOFF12, 125 /*pcrel=*/false, /*length=*/2, 126 /*offset=*/4, /*addend=*/0, 127 /*referent=*/funcSym}); 128 thunk->relocs.push_back({/*type=*/ARM64_RELOC_PAGE21, 129 /*pcrel=*/true, /*length=*/2, 130 /*offset=*/0, /*addend=*/0, 131 /*referent=*/funcSym}); 132 } 133 134 ARM64::ARM64() : ARM64Common(LP64()) { 135 cpuType = CPU_TYPE_ARM64; 136 cpuSubtype = CPU_SUBTYPE_ARM64_ALL; 137 138 stubSize = sizeof(stubCode); 139 thunkSize = sizeof(thunkCode); 140 141 // Branch immediate is two's complement 26 bits, which is implicitly 142 // multiplied by 4 (since all functions are 4-aligned: The branch range 143 // is -4*(2**(26-1))..4*(2**(26-1) - 1). 144 backwardBranchRange = 128 * 1024 * 1024; 145 forwardBranchRange = backwardBranchRange - 4; 146 147 modeDwarfEncoding = UNWIND_ARM64_MODE_DWARF; 148 subtractorRelocType = ARM64_RELOC_SUBTRACTOR; 149 unsignedRelocType = ARM64_RELOC_UNSIGNED; 150 151 stubHelperHeaderSize = sizeof(stubHelperHeaderCode); 152 stubHelperEntrySize = sizeof(stubHelperEntryCode); 153 } 154 155 namespace { 156 struct Adrp { 157 uint32_t destRegister; 158 }; 159 160 struct Add { 161 uint8_t destRegister; 162 uint8_t srcRegister; 163 uint32_t addend; 164 }; 165 166 enum ExtendType { ZeroExtend = 1, Sign64 = 2, Sign32 = 3 }; 167 168 struct Ldr { 169 uint8_t destRegister; 170 uint8_t baseRegister; 171 uint8_t size; 172 bool isFloat; 173 ExtendType extendType; 174 uint64_t offset; 175 }; 176 177 struct PerformedReloc { 178 const Reloc &rel; 179 uint64_t referentVA; 180 }; 181 182 class OptimizationHintContext { 183 public: 184 OptimizationHintContext(uint8_t *buf, const ConcatInputSection *isec, 185 ArrayRef<uint64_t> relocTargets) 186 : buf(buf), isec(isec), relocTargets(relocTargets), 187 relocIt(isec->relocs.rbegin()) {} 188 189 void applyAdrpAdd(const OptimizationHint &); 190 void applyAdrpAdrp(const OptimizationHint &); 191 void applyAdrpLdr(const OptimizationHint &); 192 193 private: 194 uint8_t *buf; 195 const ConcatInputSection *isec; 196 ArrayRef<uint64_t> relocTargets; 197 std::vector<Reloc>::const_reverse_iterator relocIt; 198 199 uint64_t getRelocTarget(const Reloc &); 200 201 Optional<PerformedReloc> findPrimaryReloc(uint64_t offset); 202 Optional<PerformedReloc> findReloc(uint64_t offset); 203 }; 204 } // namespace 205 206 static bool parseAdrp(uint32_t insn, Adrp &adrp) { 207 if ((insn & 0x9f000000) != 0x90000000) 208 return false; 209 adrp.destRegister = insn & 0x1f; 210 return true; 211 } 212 213 static bool parseAdd(uint32_t insn, Add &add) { 214 if ((insn & 0xffc00000) != 0x91000000) 215 return false; 216 add.destRegister = insn & 0x1f; 217 add.srcRegister = (insn >> 5) & 0x1f; 218 add.addend = (insn >> 10) & 0xfff; 219 return true; 220 } 221 222 static bool parseLdr(uint32_t insn, Ldr &ldr) { 223 ldr.destRegister = insn & 0x1f; 224 ldr.baseRegister = (insn >> 5) & 0x1f; 225 uint8_t size = insn >> 30; 226 uint8_t opc = (insn >> 22) & 3; 227 228 if ((insn & 0x3fc00000) == 0x39400000) { 229 // LDR (immediate), LDRB (immediate), LDRH (immediate) 230 ldr.size = 1 << size; 231 ldr.extendType = ZeroExtend; 232 ldr.isFloat = false; 233 } else if ((insn & 0x3f800000) == 0x39800000) { 234 // LDRSB (immediate), LDRSH (immediate), LDRSW (immediate) 235 ldr.size = 1 << size; 236 ldr.extendType = static_cast<ExtendType>(opc); 237 ldr.isFloat = false; 238 } else if ((insn & 0x3f400000) == 0x3d400000) { 239 // LDR (immediate, SIMD&FP) 240 ldr.extendType = ZeroExtend; 241 ldr.isFloat = true; 242 if (size == 2 && opc == 1) 243 ldr.size = 4; 244 else if (size == 3 && opc == 1) 245 ldr.size = 8; 246 else if (size == 0 && opc == 3) 247 ldr.size = 16; 248 else 249 return false; 250 } else { 251 return false; 252 } 253 ldr.offset = ((insn >> 10) & 0xfff) * ldr.size; 254 return true; 255 } 256 257 static void writeAdr(void *loc, uint32_t dest, int32_t delta) { 258 uint32_t opcode = 0x10000000; 259 uint32_t immHi = (delta & 0x001ffffc) << 3; 260 uint32_t immLo = (delta & 0x00000003) << 29; 261 write32le(loc, opcode | immHi | immLo | dest); 262 } 263 264 static void writeNop(void *loc) { write32le(loc, 0xd503201f); } 265 266 static void writeLiteralLdr(void *loc, Ldr original, int32_t delta) { 267 uint32_t imm19 = (delta & 0x001ffffc) << 3; 268 uint32_t opcode = 0; 269 switch (original.size) { 270 case 4: 271 if (original.isFloat) 272 opcode = 0x1c000000; 273 else 274 opcode = original.extendType == Sign64 ? 0x98000000 : 0x18000000; 275 break; 276 case 8: 277 opcode = original.isFloat ? 0x5c000000 : 0x58000000; 278 break; 279 case 16: 280 opcode = 0x9c000000; 281 break; 282 default: 283 assert(false && "Invalid size for literal ldr"); 284 } 285 write32le(loc, opcode | imm19 | original.destRegister); 286 } 287 288 uint64_t OptimizationHintContext::getRelocTarget(const Reloc &reloc) { 289 size_t relocIdx = &reloc - isec->relocs.data(); 290 return relocTargets[relocIdx]; 291 } 292 293 // Optimization hints are sorted in a monotonically increasing order by their 294 // first address as are relocations (albeit in decreasing order), so if we keep 295 // a pointer around to the last found relocation, we don't have to do a full 296 // binary search every time. 297 Optional<PerformedReloc> 298 OptimizationHintContext::findPrimaryReloc(uint64_t offset) { 299 const auto end = isec->relocs.rend(); 300 while (relocIt != end && relocIt->offset < offset) 301 ++relocIt; 302 if (relocIt == end || relocIt->offset != offset) 303 return None; 304 return PerformedReloc{*relocIt, getRelocTarget(*relocIt)}; 305 } 306 307 // The second and third addresses of optimization hints have no such 308 // monotonicity as the first, so we search the entire range of relocations. 309 Optional<PerformedReloc> OptimizationHintContext::findReloc(uint64_t offset) { 310 // Optimization hints often apply to successive relocations, so we check for 311 // that first before doing a full binary search. 312 auto end = isec->relocs.rend(); 313 if (relocIt < end - 1 && (relocIt + 1)->offset == offset) 314 return PerformedReloc{*(relocIt + 1), getRelocTarget(*(relocIt + 1))}; 315 316 auto reloc = lower_bound(isec->relocs, offset, 317 [](const Reloc &reloc, uint64_t offset) { 318 return offset < reloc.offset; 319 }); 320 321 if (reloc == isec->relocs.end() || reloc->offset != offset) 322 return None; 323 return PerformedReloc{*reloc, getRelocTarget(*reloc)}; 324 } 325 326 // Transforms a pair of adrp+add instructions into an adr instruction if the 327 // target is within the +/- 1 MiB range allowed by the adr's 21 bit signed 328 // immediate offset. 329 // 330 // adrp xN, _foo@PAGE 331 // add xM, xN, _foo@PAGEOFF 332 // -> 333 // adr xM, _foo 334 // nop 335 void OptimizationHintContext::applyAdrpAdd(const OptimizationHint &hint) { 336 uint32_t ins1 = read32le(buf + hint.offset0); 337 uint32_t ins2 = read32le(buf + hint.offset0 + hint.delta[0]); 338 Adrp adrp; 339 if (!parseAdrp(ins1, adrp)) 340 return; 341 Add add; 342 if (!parseAdd(ins2, add)) 343 return; 344 if (adrp.destRegister != add.srcRegister) 345 return; 346 347 Optional<PerformedReloc> rel1 = findPrimaryReloc(hint.offset0); 348 Optional<PerformedReloc> rel2 = findReloc(hint.offset0 + hint.delta[0]); 349 if (!rel1 || !rel2) 350 return; 351 if (rel1->referentVA != rel2->referentVA) 352 return; 353 int64_t delta = rel1->referentVA - rel1->rel.offset - isec->getVA(); 354 if (delta >= (1 << 20) || delta < -(1 << 20)) 355 return; 356 357 writeAdr(buf + hint.offset0, add.destRegister, delta); 358 writeNop(buf + hint.offset0 + hint.delta[0]); 359 } 360 361 // Transforms two adrp instructions into a single adrp if their referent 362 // addresses are located on the same 4096 byte page. 363 // 364 // adrp xN, _foo@PAGE 365 // adrp xN, _bar@PAGE 366 // -> 367 // adrp xN, _foo@PAGE 368 // nop 369 void OptimizationHintContext::applyAdrpAdrp(const OptimizationHint &hint) { 370 uint32_t ins1 = read32le(buf + hint.offset0); 371 uint32_t ins2 = read32le(buf + hint.offset0 + hint.delta[0]); 372 Adrp adrp1, adrp2; 373 if (!parseAdrp(ins1, adrp1) || !parseAdrp(ins2, adrp2)) 374 return; 375 if (adrp1.destRegister != adrp2.destRegister) 376 return; 377 378 Optional<PerformedReloc> rel1 = findPrimaryReloc(hint.offset0); 379 Optional<PerformedReloc> rel2 = findReloc(hint.offset0 + hint.delta[0]); 380 if (!rel1 || !rel2) 381 return; 382 if ((rel1->referentVA & ~0xfffULL) != (rel2->referentVA & ~0xfffULL)) 383 return; 384 385 writeNop(buf + hint.offset0 + hint.delta[0]); 386 } 387 388 // Transforms a pair of adrp+ldr (immediate) instructions into an ldr (literal) 389 // load from a PC-relative address if it is 4-byte aligned and within +/- 1 MiB, 390 // as ldr can encode a signed 19-bit offset that gets multiplied by 4. 391 // 392 // adrp xN, _foo@PAGE 393 // ldr xM, [xN, _foo@PAGEOFF] 394 // -> 395 // nop 396 // ldr xM, _foo 397 void OptimizationHintContext::applyAdrpLdr(const OptimizationHint &hint) { 398 uint32_t ins1 = read32le(buf + hint.offset0); 399 uint32_t ins2 = read32le(buf + hint.offset0 + hint.delta[0]); 400 Adrp adrp; 401 if (!parseAdrp(ins1, adrp)) 402 return; 403 Ldr ldr; 404 if (!parseLdr(ins2, ldr)) 405 return; 406 if (adrp.destRegister != ldr.baseRegister) 407 return; 408 409 Optional<PerformedReloc> rel1 = findPrimaryReloc(hint.offset0); 410 Optional<PerformedReloc> rel2 = findReloc(hint.offset0 + hint.delta[0]); 411 if (!rel1 || !rel2) 412 return; 413 if (ldr.offset != (rel1->referentVA & 0xfff)) 414 return; 415 if ((rel1->referentVA & 3) != 0) 416 return; 417 if (ldr.size == 1 || ldr.size == 2) 418 return; 419 int64_t delta = rel1->referentVA - rel2->rel.offset - isec->getVA(); 420 if (delta >= (1 << 20) || delta < -(1 << 20)) 421 return; 422 423 writeNop(buf + hint.offset0); 424 writeLiteralLdr(buf + hint.offset0 + hint.delta[0], ldr, delta); 425 } 426 427 void ARM64::applyOptimizationHints(uint8_t *buf, const ConcatInputSection *isec, 428 ArrayRef<uint64_t> relocTargets) const { 429 assert(isec); 430 assert(relocTargets.size() == isec->relocs.size()); 431 432 // Note: Some of these optimizations might not be valid when shared regions 433 // are in use. Will need to revisit this if splitSegInfo is added. 434 435 OptimizationHintContext ctx1(buf, isec, relocTargets); 436 for (const OptimizationHint &hint : isec->optimizationHints) { 437 switch (hint.type) { 438 case LOH_ARM64_ADRP_ADRP: 439 // This is done in another pass because the other optimization hints 440 // might cause its targets to be turned into NOPs. 441 break; 442 case LOH_ARM64_ADRP_LDR: 443 ctx1.applyAdrpLdr(hint); 444 break; 445 case LOH_ARM64_ADRP_ADD_LDR: 446 case LOH_ARM64_ADRP_LDR_GOT_LDR: 447 case LOH_ARM64_ADRP_ADD_STR: 448 case LOH_ARM64_ADRP_LDR_GOT_STR: 449 // TODO: Implement these 450 break; 451 case LOH_ARM64_ADRP_ADD: 452 ctx1.applyAdrpAdd(hint); 453 break; 454 case LOH_ARM64_ADRP_LDR_GOT: 455 // TODO: Implement this as well 456 break; 457 } 458 } 459 460 OptimizationHintContext ctx2(buf, isec, relocTargets); 461 for (const OptimizationHint &hint : isec->optimizationHints) 462 if (hint.type == LOH_ARM64_ADRP_ADRP) 463 ctx2.applyAdrpAdrp(hint); 464 } 465 466 TargetInfo *macho::createARM64TargetInfo() { 467 static ARM64 t; 468 return &t; 469 } 470